xref: /openssh-portable/ssh.c (revision 7be4ac81)
1 /* $OpenBSD: ssh.c,v 1.557 2021/05/19 01:24:05 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
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.
9  *
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".
15  *
16  * Copyright (c) 1999 Niels Provos.  All rights reserved.
17  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
18  *
19  * Modified to work with SSLeay by Niels Provos <provos@citi.umich.edu>
20  * in Canada (German citizen).
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
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.
30  *
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.
41  */
42 
43 #include "includes.h"
44 
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #include <sys/wait.h>
53 
54 #include <ctype.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <netdb.h>
58 #ifdef HAVE_PATHS_H
59 #include <paths.h>
60 #endif
61 #include <pwd.h>
62 #include <signal.h>
63 #include <stdarg.h>
64 #include <stddef.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <stdarg.h>
69 #include <unistd.h>
70 #include <limits.h>
71 #include <locale.h>
72 
73 #include <netinet/in.h>
74 #include <arpa/inet.h>
75 
76 #ifdef WITH_OPENSSL
77 #include <openssl/evp.h>
78 #include <openssl/err.h>
79 #endif
80 #include "openbsd-compat/openssl-compat.h"
81 #include "openbsd-compat/sys-queue.h"
82 
83 #include "xmalloc.h"
84 #include "ssh.h"
85 #include "ssh2.h"
86 #include "canohost.h"
87 #include "compat.h"
88 #include "cipher.h"
89 #include "packet.h"
90 #include "sshbuf.h"
91 #include "channels.h"
92 #include "sshkey.h"
93 #include "authfd.h"
94 #include "authfile.h"
95 #include "pathnames.h"
96 #include "dispatch.h"
97 #include "clientloop.h"
98 #include "log.h"
99 #include "misc.h"
100 #include "readconf.h"
101 #include "sshconnect.h"
102 #include "kex.h"
103 #include "mac.h"
104 #include "sshpty.h"
105 #include "match.h"
106 #include "msg.h"
107 #include "version.h"
108 #include "ssherr.h"
109 #include "myproposal.h"
110 #include "utf8.h"
111 
112 #ifdef ENABLE_PKCS11
113 #include "ssh-pkcs11.h"
114 #endif
115 
116 extern char *__progname;
117 
118 /* Saves a copy of argv for setproctitle emulation */
119 #ifndef HAVE_SETPROCTITLE
120 static char **saved_av;
121 #endif
122 
123 /* Flag indicating whether debug mode is on.  May be set on the command line. */
124 int debug_flag = 0;
125 
126 /* Flag indicating whether a tty should be requested */
127 int tty_flag = 0;
128 
129 /* don't exec a shell */
130 int no_shell_flag = 0;
131 
132 /*
133  * Flag indicating that nothing should be read from stdin.  This can be set
134  * on the command line.
135  */
136 int stdin_null_flag = 0;
137 
138 /*
139  * Flag indicating that the current process should be backgrounded and
140  * a new mux-client launched in the foreground for ControlPersist.
141  */
142 int need_controlpersist_detach = 0;
143 
144 /* Copies of flags for ControlPersist foreground mux-client */
145 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
146 
147 /*
148  * Flag indicating that ssh should fork after authentication.  This is useful
149  * so that the passphrase can be entered manually, and then ssh goes to the
150  * background.
151  */
152 int fork_after_authentication_flag = 0;
153 
154 /*
155  * General data structure for command line options and options configurable
156  * in configuration files.  See readconf.h.
157  */
158 Options options;
159 
160 /* optional user configfile */
161 char *config = NULL;
162 
163 /*
164  * Name of the host we are connecting to.  This is the name given on the
165  * command line, or the Hostname specified for the user-supplied name in a
166  * configuration file.
167  */
168 char *host;
169 
170 /*
171  * A config can specify a path to forward, overriding SSH_AUTH_SOCK. If this is
172  * not NULL, forward the socket at this path instead.
173  */
174 char *forward_agent_sock_path = NULL;
175 
176 /* socket address the host resolves to */
177 struct sockaddr_storage hostaddr;
178 
179 /* Private host keys. */
180 Sensitive sensitive_data;
181 
182 /* command to be executed */
183 struct sshbuf *command;
184 
185 /* Should we execute a command or invoke a subsystem? */
186 int subsystem_flag = 0;
187 
188 /* # of replies received for global requests */
189 static int forward_confirms_pending = -1;
190 
191 /* mux.c */
192 extern int muxserver_sock;
193 extern u_int muxclient_command;
194 
195 /* Prints a help message to the user.  This function never returns. */
196 
197 static void
usage(void)198 usage(void)
199 {
200 	fprintf(stderr,
201 "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]\n"
202 "           [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]\n"
203 "           [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]\n"
204 "           [-i identity_file] [-J [user@]host[:port]] [-L address]\n"
205 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
206 "           [-Q query_option] [-R address] [-S ctl_path] [-W host:port]\n"
207 "           [-w local_tun[:remote_tun]] destination [command]\n"
208 	);
209 	exit(255);
210 }
211 
212 static int ssh_session2(struct ssh *, const struct ssh_conn_info *);
213 static void load_public_identity_files(const struct ssh_conn_info *);
214 static void main_sigchld_handler(int);
215 
216 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
217 static void
tilde_expand_paths(char ** paths,u_int num_paths)218 tilde_expand_paths(char **paths, u_int num_paths)
219 {
220 	u_int i;
221 	char *cp;
222 
223 	for (i = 0; i < num_paths; i++) {
224 		cp = tilde_expand_filename(paths[i], getuid());
225 		free(paths[i]);
226 		paths[i] = cp;
227 	}
228 }
229 
230 /*
231  * Expands the set of percent_expand options used by the majority of keywords
232  * in the client that support percent expansion.
233  * Caller must free returned string.
234  */
235 static char *
default_client_percent_expand(const char * str,const struct ssh_conn_info * cinfo)236 default_client_percent_expand(const char *str,
237     const struct ssh_conn_info *cinfo)
238 {
239 	return percent_expand(str,
240 	    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
241 	    (char *)NULL);
242 }
243 
244 /*
245  * Expands the set of percent_expand options used by the majority of keywords
246  * AND perform environment variable substitution.
247  * Caller must free returned string.
248  */
249 static char *
default_client_percent_dollar_expand(const char * str,const struct ssh_conn_info * cinfo)250 default_client_percent_dollar_expand(const char *str,
251     const struct ssh_conn_info *cinfo)
252 {
253 	char *ret;
254 
255 	ret = percent_dollar_expand(str,
256 	    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
257 	    (char *)NULL);
258 	if (ret == NULL)
259 		fatal("invalid environment variable expansion");
260 	return ret;
261 }
262 
263 /*
264  * Attempt to resolve a host name / port to a set of addresses and
265  * optionally return any CNAMEs encountered along the way.
266  * Returns NULL on failure.
267  * NB. this function must operate with a options having undefined members.
268  */
269 static struct addrinfo *
resolve_host(const char * name,int port,int logerr,char * cname,size_t clen)270 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
271 {
272 	char strport[NI_MAXSERV];
273 	struct addrinfo hints, *res;
274 	int gaierr;
275 	LogLevel loglevel = SYSLOG_LEVEL_DEBUG1;
276 
277 	if (port <= 0)
278 		port = default_ssh_port();
279 	if (cname != NULL)
280 		*cname = '\0';
281 
282 	snprintf(strport, sizeof strport, "%d", port);
283 	memset(&hints, 0, sizeof(hints));
284 	hints.ai_family = options.address_family == -1 ?
285 	    AF_UNSPEC : options.address_family;
286 	hints.ai_socktype = SOCK_STREAM;
287 	if (cname != NULL)
288 		hints.ai_flags = AI_CANONNAME;
289 	if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
290 		if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
291 			loglevel = SYSLOG_LEVEL_ERROR;
292 		do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
293 		    __progname, name, ssh_gai_strerror(gaierr));
294 		return NULL;
295 	}
296 	if (cname != NULL && res->ai_canonname != NULL) {
297 		if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
298 			error_f("host \"%s\" cname \"%s\" too long (max %lu)",
299 			    name,  res->ai_canonname, (u_long)clen);
300 			if (clen > 0)
301 				*cname = '\0';
302 		}
303 	}
304 	return res;
305 }
306 
307 /* Returns non-zero if name can only be an address and not a hostname */
308 static int
is_addr_fast(const char * name)309 is_addr_fast(const char *name)
310 {
311 	return (strchr(name, '%') != NULL || strchr(name, ':') != NULL ||
312 	    strspn(name, "0123456789.") == strlen(name));
313 }
314 
315 /* Returns non-zero if name represents a valid, single address */
316 static int
is_addr(const char * name)317 is_addr(const char *name)
318 {
319 	char strport[NI_MAXSERV];
320 	struct addrinfo hints, *res;
321 
322 	if (is_addr_fast(name))
323 		return 1;
324 
325 	snprintf(strport, sizeof strport, "%u", default_ssh_port());
326 	memset(&hints, 0, sizeof(hints));
327 	hints.ai_family = options.address_family == -1 ?
328 	    AF_UNSPEC : options.address_family;
329 	hints.ai_socktype = SOCK_STREAM;
330 	hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
331 	if (getaddrinfo(name, strport, &hints, &res) != 0)
332 		return 0;
333 	if (res == NULL || res->ai_next != NULL) {
334 		freeaddrinfo(res);
335 		return 0;
336 	}
337 	freeaddrinfo(res);
338 	return 1;
339 }
340 
341 /*
342  * Attempt to resolve a numeric host address / port to a single address.
343  * Returns a canonical address string.
344  * Returns NULL on failure.
345  * NB. this function must operate with a options having undefined members.
346  */
347 static struct addrinfo *
resolve_addr(const char * name,int port,char * caddr,size_t clen)348 resolve_addr(const char *name, int port, char *caddr, size_t clen)
349 {
350 	char addr[NI_MAXHOST], strport[NI_MAXSERV];
351 	struct addrinfo hints, *res;
352 	int gaierr;
353 
354 	if (port <= 0)
355 		port = default_ssh_port();
356 	snprintf(strport, sizeof strport, "%u", port);
357 	memset(&hints, 0, sizeof(hints));
358 	hints.ai_family = options.address_family == -1 ?
359 	    AF_UNSPEC : options.address_family;
360 	hints.ai_socktype = SOCK_STREAM;
361 	hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
362 	if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
363 		debug2_f("could not resolve name %.100s as address: %s",
364 		    name, ssh_gai_strerror(gaierr));
365 		return NULL;
366 	}
367 	if (res == NULL) {
368 		debug_f("getaddrinfo %.100s returned no addresses", name);
369 		return NULL;
370 	}
371 	if (res->ai_next != NULL) {
372 		debug_f("getaddrinfo %.100s returned multiple addresses", name);
373 		goto fail;
374 	}
375 	if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
376 	    addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
377 		debug_f("Could not format address for name %.100s: %s",
378 		    name, ssh_gai_strerror(gaierr));
379 		goto fail;
380 	}
381 	if (strlcpy(caddr, addr, clen) >= clen) {
382 		error_f("host \"%s\" addr \"%s\" too long (max %lu)",
383 		    name,  addr, (u_long)clen);
384 		if (clen > 0)
385 			*caddr = '\0';
386  fail:
387 		freeaddrinfo(res);
388 		return NULL;
389 	}
390 	return res;
391 }
392 
393 /*
394  * Check whether the cname is a permitted replacement for the hostname
395  * and perform the replacement if it is.
396  * NB. this function must operate with a options having undefined members.
397  */
398 static int
check_follow_cname(int direct,char ** namep,const char * cname)399 check_follow_cname(int direct, char **namep, const char *cname)
400 {
401 	int i;
402 	struct allowed_cname *rule;
403 
404 	if (*cname == '\0' || options.num_permitted_cnames == 0 ||
405 	    strcmp(*namep, cname) == 0)
406 		return 0;
407 	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
408 		return 0;
409 	/*
410 	 * Don't attempt to canonicalize names that will be interpreted by
411 	 * a proxy or jump host unless the user specifically requests so.
412 	 */
413 	if (!direct &&
414 	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
415 		return 0;
416 	debug3_f("check \"%s\" CNAME \"%s\"", *namep, cname);
417 	for (i = 0; i < options.num_permitted_cnames; i++) {
418 		rule = options.permitted_cnames + i;
419 		if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
420 		    match_pattern_list(cname, rule->target_list, 1) != 1)
421 			continue;
422 		verbose("Canonicalized DNS aliased hostname "
423 		    "\"%s\" => \"%s\"", *namep, cname);
424 		free(*namep);
425 		*namep = xstrdup(cname);
426 		return 1;
427 	}
428 	return 0;
429 }
430 
431 /*
432  * Attempt to resolve the supplied hostname after applying the user's
433  * canonicalization rules. Returns the address list for the host or NULL
434  * if no name was found after canonicalization.
435  * NB. this function must operate with a options having undefined members.
436  */
437 static struct addrinfo *
resolve_canonicalize(char ** hostp,int port)438 resolve_canonicalize(char **hostp, int port)
439 {
440 	int i, direct, ndots;
441 	char *cp, *fullhost, newname[NI_MAXHOST];
442 	struct addrinfo *addrs;
443 
444 	/*
445 	 * Attempt to canonicalise addresses, regardless of
446 	 * whether hostname canonicalisation was requested
447 	 */
448 	if ((addrs = resolve_addr(*hostp, port,
449 	    newname, sizeof(newname))) != NULL) {
450 		debug2_f("hostname %.100s is address", *hostp);
451 		if (strcasecmp(*hostp, newname) != 0) {
452 			debug2_f("canonicalised address \"%s\" => \"%s\"",
453 			    *hostp, newname);
454 			free(*hostp);
455 			*hostp = xstrdup(newname);
456 		}
457 		return addrs;
458 	}
459 
460 	/*
461 	 * If this looks like an address but didn't parse as one, it might
462 	 * be an address with an invalid interface scope. Skip further
463 	 * attempts at canonicalisation.
464 	 */
465 	if (is_addr_fast(*hostp)) {
466 		debug_f("hostname %.100s is an unrecognised address", *hostp);
467 		return NULL;
468 	}
469 
470 	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
471 		return NULL;
472 
473 	/*
474 	 * Don't attempt to canonicalize names that will be interpreted by
475 	 * a proxy unless the user specifically requests so.
476 	 */
477 	direct = option_clear_or_none(options.proxy_command) &&
478 	    options.jump_host == NULL;
479 	if (!direct &&
480 	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
481 		return NULL;
482 
483 	/* If domain name is anchored, then resolve it now */
484 	if ((*hostp)[strlen(*hostp) - 1] == '.') {
485 		debug3_f("name is fully qualified");
486 		fullhost = xstrdup(*hostp);
487 		if ((addrs = resolve_host(fullhost, port, 0,
488 		    newname, sizeof(newname))) != NULL)
489 			goto found;
490 		free(fullhost);
491 		goto notfound;
492 	}
493 
494 	/* Don't apply canonicalization to sufficiently-qualified hostnames */
495 	ndots = 0;
496 	for (cp = *hostp; *cp != '\0'; cp++) {
497 		if (*cp == '.')
498 			ndots++;
499 	}
500 	if (ndots > options.canonicalize_max_dots) {
501 		debug3_f("not canonicalizing hostname \"%s\" (max dots %d)",
502 		    *hostp, options.canonicalize_max_dots);
503 		return NULL;
504 	}
505 	/* Attempt each supplied suffix */
506 	for (i = 0; i < options.num_canonical_domains; i++) {
507 		xasprintf(&fullhost, "%s.%s.", *hostp,
508 		    options.canonical_domains[i]);
509 		debug3_f("attempting \"%s\" => \"%s\"", *hostp, fullhost);
510 		if ((addrs = resolve_host(fullhost, port, 0,
511 		    newname, sizeof(newname))) == NULL) {
512 			free(fullhost);
513 			continue;
514 		}
515  found:
516 		/* Remove trailing '.' */
517 		fullhost[strlen(fullhost) - 1] = '\0';
518 		/* Follow CNAME if requested */
519 		if (!check_follow_cname(direct, &fullhost, newname)) {
520 			debug("Canonicalized hostname \"%s\" => \"%s\"",
521 			    *hostp, fullhost);
522 		}
523 		free(*hostp);
524 		*hostp = fullhost;
525 		return addrs;
526 	}
527  notfound:
528 	if (!options.canonicalize_fallback_local)
529 		fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
530 	debug2_f("host %s not found in any suffix", *hostp);
531 	return NULL;
532 }
533 
534 /*
535  * Check the result of hostkey loading, ignoring some errors and
536  * fatal()ing for others.
537  */
538 static void
check_load(int r,const char * path,const char * message)539 check_load(int r, const char *path, const char *message)
540 {
541 	switch (r) {
542 	case 0:
543 		break;
544 	case SSH_ERR_INTERNAL_ERROR:
545 	case SSH_ERR_ALLOC_FAIL:
546 		fatal_r(r, "load %s \"%s\"", message, path);
547 	case SSH_ERR_SYSTEM_ERROR:
548 		/* Ignore missing files */
549 		if (errno == ENOENT)
550 			break;
551 		/* FALLTHROUGH */
552 	default:
553 		error_r(r, "load %s \"%s\"", message, path);
554 		break;
555 	}
556 }
557 
558 /*
559  * Read per-user configuration file.  Ignore the system wide config
560  * file if the user specifies a config file on the command line.
561  */
562 static void
process_config_files(const char * host_name,struct passwd * pw,int final_pass,int * want_final_pass)563 process_config_files(const char *host_name, struct passwd *pw, int final_pass,
564     int *want_final_pass)
565 {
566 	char buf[PATH_MAX];
567 	int r;
568 
569 	if (config != NULL) {
570 		if (strcasecmp(config, "none") != 0 &&
571 		    !read_config_file(config, pw, host, host_name, &options,
572 		    SSHCONF_USERCONF | (final_pass ? SSHCONF_FINAL : 0),
573 		    want_final_pass))
574 			fatal("Can't open user config file %.100s: "
575 			    "%.100s", config, strerror(errno));
576 	} else {
577 		r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
578 		    _PATH_SSH_USER_CONFFILE);
579 		if (r > 0 && (size_t)r < sizeof(buf))
580 			(void)read_config_file(buf, pw, host, host_name,
581 			    &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
582 			    (final_pass ? SSHCONF_FINAL : 0), want_final_pass);
583 
584 		/* Read systemwide configuration file after user config. */
585 		(void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
586 		    host, host_name, &options,
587 		    final_pass ? SSHCONF_FINAL : 0, want_final_pass);
588 	}
589 }
590 
591 /* Rewrite the port number in an addrinfo list of addresses */
592 static void
set_addrinfo_port(struct addrinfo * addrs,int port)593 set_addrinfo_port(struct addrinfo *addrs, int port)
594 {
595 	struct addrinfo *addr;
596 
597 	for (addr = addrs; addr != NULL; addr = addr->ai_next) {
598 		switch (addr->ai_family) {
599 		case AF_INET:
600 			((struct sockaddr_in *)addr->ai_addr)->
601 			    sin_port = htons(port);
602 			break;
603 		case AF_INET6:
604 			((struct sockaddr_in6 *)addr->ai_addr)->
605 			    sin6_port = htons(port);
606 			break;
607 		}
608 	}
609 }
610 
611 static void
ssh_conn_info_free(struct ssh_conn_info * cinfo)612 ssh_conn_info_free(struct ssh_conn_info *cinfo)
613 {
614 	if (cinfo == NULL)
615 		return;
616 	free(cinfo->conn_hash_hex);
617 	free(cinfo->shorthost);
618 	free(cinfo->uidstr);
619 	free(cinfo->keyalias);
620 	free(cinfo->thishost);
621 	free(cinfo->host_arg);
622 	free(cinfo->portstr);
623 	free(cinfo->remhost);
624 	free(cinfo->remuser);
625 	free(cinfo->homedir);
626 	free(cinfo->locuser);
627 	free(cinfo);
628 }
629 
630 /*
631  * Main program for the ssh client.
632  */
633 int
main(int ac,char ** av)634 main(int ac, char **av)
635 {
636 	struct ssh *ssh = NULL;
637 	int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
638 	int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0;
639 	char *p, *cp, *line, *argv0, *logfile, *host_arg;
640 	char cname[NI_MAXHOST], thishost[NI_MAXHOST];
641 	struct stat st;
642 	struct passwd *pw;
643 	extern int optind, optreset;
644 	extern char *optarg;
645 	struct Forward fwd;
646 	struct addrinfo *addrs = NULL;
647 	size_t n, len;
648 	u_int j;
649 	struct ssh_conn_info *cinfo = NULL;
650 
651 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
652 	sanitise_stdfd();
653 
654 	__progname = ssh_get_progname(av[0]);
655 
656 #ifndef HAVE_SETPROCTITLE
657 	/* Prepare for later setproctitle emulation */
658 	/* Save argv so it isn't clobbered by setproctitle() emulation */
659 	saved_av = xcalloc(ac + 1, sizeof(*saved_av));
660 	for (i = 0; i < ac; i++)
661 		saved_av[i] = xstrdup(av[i]);
662 	saved_av[i] = NULL;
663 	compat_init_setproctitle(ac, av);
664 	av = saved_av;
665 #endif
666 
667 	seed_rng();
668 
669 	/*
670 	 * Discard other fds that are hanging around. These can cause problem
671 	 * with backgrounded ssh processes started by ControlPersist.
672 	 */
673 	closefrom(STDERR_FILENO + 1);
674 
675 	/* Get user data. */
676 	pw = getpwuid(getuid());
677 	if (!pw) {
678 		logit("No user exists for uid %lu", (u_long)getuid());
679 		exit(255);
680 	}
681 	/* Take a copy of the returned structure. */
682 	pw = pwcopy(pw);
683 
684 	/*
685 	 * Set our umask to something reasonable, as some files are created
686 	 * with the default umask.  This will make them world-readable but
687 	 * writable only by the owner, which is ok for all files for which we
688 	 * don't set the modes explicitly.
689 	 */
690 	umask(022);
691 
692 	msetlocale();
693 
694 	/*
695 	 * Initialize option structure to indicate that no values have been
696 	 * set.
697 	 */
698 	initialize_options(&options);
699 
700 	/*
701 	 * Prepare main ssh transport/connection structures
702 	 */
703 	if ((ssh = ssh_alloc_session_state()) == NULL)
704 		fatal("Couldn't allocate session state");
705 	channel_init_channels(ssh);
706 
707 	/* Parse command-line arguments. */
708 	host = NULL;
709 	use_syslog = 0;
710 	logfile = NULL;
711 	argv0 = av[0];
712 
713  again:
714 	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
715 	    "AB:CD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
716 		switch (opt) {
717 		case '1':
718 			fatal("SSH protocol v.1 is no longer supported");
719 			break;
720 		case '2':
721 			/* Ignored */
722 			break;
723 		case '4':
724 			options.address_family = AF_INET;
725 			break;
726 		case '6':
727 			options.address_family = AF_INET6;
728 			break;
729 		case 'n':
730 			stdin_null_flag = 1;
731 			break;
732 		case 'f':
733 			fork_after_authentication_flag = 1;
734 			stdin_null_flag = 1;
735 			break;
736 		case 'x':
737 			options.forward_x11 = 0;
738 			break;
739 		case 'X':
740 			options.forward_x11 = 1;
741 			break;
742 		case 'y':
743 			use_syslog = 1;
744 			break;
745 		case 'E':
746 			logfile = optarg;
747 			break;
748 		case 'G':
749 			config_test = 1;
750 			break;
751 		case 'Y':
752 			options.forward_x11 = 1;
753 			options.forward_x11_trusted = 1;
754 			break;
755 		case 'g':
756 			options.fwd_opts.gateway_ports = 1;
757 			break;
758 		case 'O':
759 			if (options.stdio_forward_host != NULL)
760 				fatal("Cannot specify multiplexing "
761 				    "command with -W");
762 			else if (muxclient_command != 0)
763 				fatal("Multiplexing command already specified");
764 			if (strcmp(optarg, "check") == 0)
765 				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
766 			else if (strcmp(optarg, "forward") == 0)
767 				muxclient_command = SSHMUX_COMMAND_FORWARD;
768 			else if (strcmp(optarg, "exit") == 0)
769 				muxclient_command = SSHMUX_COMMAND_TERMINATE;
770 			else if (strcmp(optarg, "stop") == 0)
771 				muxclient_command = SSHMUX_COMMAND_STOP;
772 			else if (strcmp(optarg, "cancel") == 0)
773 				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
774 			else if (strcmp(optarg, "proxy") == 0)
775 				muxclient_command = SSHMUX_COMMAND_PROXY;
776 			else
777 				fatal("Invalid multiplex command.");
778 			break;
779 		case 'P':	/* deprecated */
780 			break;
781 		case 'Q':
782 			cp = NULL;
783 			if (strcmp(optarg, "cipher") == 0 ||
784 			    strcasecmp(optarg, "Ciphers") == 0)
785 				cp = cipher_alg_list('\n', 0);
786 			else if (strcmp(optarg, "cipher-auth") == 0)
787 				cp = cipher_alg_list('\n', 1);
788 			else if (strcmp(optarg, "mac") == 0 ||
789 			    strcasecmp(optarg, "MACs") == 0)
790 				cp = mac_alg_list('\n');
791 			else if (strcmp(optarg, "kex") == 0 ||
792 			    strcasecmp(optarg, "KexAlgorithms") == 0)
793 				cp = kex_alg_list('\n');
794 			else if (strcmp(optarg, "key") == 0)
795 				cp = sshkey_alg_list(0, 0, 0, '\n');
796 			else if (strcmp(optarg, "key-cert") == 0)
797 				cp = sshkey_alg_list(1, 0, 0, '\n');
798 			else if (strcmp(optarg, "key-plain") == 0)
799 				cp = sshkey_alg_list(0, 1, 0, '\n');
800 			else if (strcmp(optarg, "key-sig") == 0 ||
801 			    strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
802 			    strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
803 			    strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
804 			    strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
805 			    strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
806 			    strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
807 				cp = sshkey_alg_list(0, 0, 1, '\n');
808 			else if (strcmp(optarg, "sig") == 0)
809 				cp = sshkey_alg_list(0, 1, 1, '\n');
810 			else if (strcmp(optarg, "protocol-version") == 0)
811 				cp = xstrdup("2");
812 			else if (strcmp(optarg, "compression") == 0) {
813 				cp = xstrdup(compression_alg_list(0));
814 				len = strlen(cp);
815 				for (n = 0; n < len; n++)
816 					if (cp[n] == ',')
817 						cp[n] = '\n';
818 			} else if (strcmp(optarg, "help") == 0) {
819 				cp = xstrdup(
820 				    "cipher\ncipher-auth\ncompression\nkex\n"
821 				    "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
822 				    "protocol-version\nsig");
823 			}
824 			if (cp == NULL)
825 				fatal("Unsupported query \"%s\"", optarg);
826 			printf("%s\n", cp);
827 			free(cp);
828 			exit(0);
829 			break;
830 		case 'a':
831 			options.forward_agent = 0;
832 			break;
833 		case 'A':
834 			options.forward_agent = 1;
835 			break;
836 		case 'k':
837 			options.gss_deleg_creds = 0;
838 			break;
839 		case 'K':
840 			options.gss_authentication = 1;
841 			options.gss_deleg_creds = 1;
842 			break;
843 		case 'i':
844 			p = tilde_expand_filename(optarg, getuid());
845 			if (stat(p, &st) == -1)
846 				fprintf(stderr, "Warning: Identity file %s "
847 				    "not accessible: %s.\n", p,
848 				    strerror(errno));
849 			else
850 				add_identity_file(&options, NULL, p, 1);
851 			free(p);
852 			break;
853 		case 'I':
854 #ifdef ENABLE_PKCS11
855 			free(options.pkcs11_provider);
856 			options.pkcs11_provider = xstrdup(optarg);
857 #else
858 			fprintf(stderr, "no support for PKCS#11.\n");
859 #endif
860 			break;
861 		case 'J':
862 			if (options.jump_host != NULL) {
863 				fatal("Only a single -J option is permitted "
864 				    "(use commas to separate multiple "
865 				    "jump hops)");
866 			}
867 			if (options.proxy_command != NULL)
868 				fatal("Cannot specify -J with ProxyCommand");
869 			if (parse_jump(optarg, &options, 1) == -1)
870 				fatal("Invalid -J argument");
871 			options.proxy_command = xstrdup("none");
872 			break;
873 		case 't':
874 			if (options.request_tty == REQUEST_TTY_YES)
875 				options.request_tty = REQUEST_TTY_FORCE;
876 			else
877 				options.request_tty = REQUEST_TTY_YES;
878 			break;
879 		case 'v':
880 			if (debug_flag == 0) {
881 				debug_flag = 1;
882 				options.log_level = SYSLOG_LEVEL_DEBUG1;
883 			} else {
884 				if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
885 					debug_flag++;
886 					options.log_level++;
887 				}
888 			}
889 			break;
890 		case 'V':
891 			fprintf(stderr, "%s, %s\n",
892 			    SSH_RELEASE, SSH_OPENSSL_VERSION);
893 			if (opt == 'V')
894 				exit(0);
895 			break;
896 		case 'w':
897 			if (options.tun_open == -1)
898 				options.tun_open = SSH_TUNMODE_DEFAULT;
899 			options.tun_local = a2tun(optarg, &options.tun_remote);
900 			if (options.tun_local == SSH_TUNID_ERR) {
901 				fprintf(stderr,
902 				    "Bad tun device '%s'\n", optarg);
903 				exit(255);
904 			}
905 			break;
906 		case 'W':
907 			if (options.stdio_forward_host != NULL)
908 				fatal("stdio forward already specified");
909 			if (muxclient_command != 0)
910 				fatal("Cannot specify stdio forward with -O");
911 			if (parse_forward(&fwd, optarg, 1, 0)) {
912 				options.stdio_forward_host = fwd.listen_host;
913 				options.stdio_forward_port = fwd.listen_port;
914 				free(fwd.connect_host);
915 			} else {
916 				fprintf(stderr,
917 				    "Bad stdio forwarding specification '%s'\n",
918 				    optarg);
919 				exit(255);
920 			}
921 			options.request_tty = REQUEST_TTY_NO;
922 			no_shell_flag = 1;
923 			break;
924 		case 'q':
925 			options.log_level = SYSLOG_LEVEL_QUIET;
926 			break;
927 		case 'e':
928 			if (optarg[0] == '^' && optarg[2] == 0 &&
929 			    (u_char) optarg[1] >= 64 &&
930 			    (u_char) optarg[1] < 128)
931 				options.escape_char = (u_char) optarg[1] & 31;
932 			else if (strlen(optarg) == 1)
933 				options.escape_char = (u_char) optarg[0];
934 			else if (strcmp(optarg, "none") == 0)
935 				options.escape_char = SSH_ESCAPECHAR_NONE;
936 			else {
937 				fprintf(stderr, "Bad escape character '%s'.\n",
938 				    optarg);
939 				exit(255);
940 			}
941 			break;
942 		case 'c':
943 			if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
944 			    optarg + 1 : optarg)) {
945 				fprintf(stderr, "Unknown cipher type '%s'\n",
946 				    optarg);
947 				exit(255);
948 			}
949 			free(options.ciphers);
950 			options.ciphers = xstrdup(optarg);
951 			break;
952 		case 'm':
953 			if (mac_valid(optarg)) {
954 				free(options.macs);
955 				options.macs = xstrdup(optarg);
956 			} else {
957 				fprintf(stderr, "Unknown mac type '%s'\n",
958 				    optarg);
959 				exit(255);
960 			}
961 			break;
962 		case 'M':
963 			if (options.control_master == SSHCTL_MASTER_YES)
964 				options.control_master = SSHCTL_MASTER_ASK;
965 			else
966 				options.control_master = SSHCTL_MASTER_YES;
967 			break;
968 		case 'p':
969 			if (options.port == -1) {
970 				options.port = a2port(optarg);
971 				if (options.port <= 0) {
972 					fprintf(stderr, "Bad port '%s'\n",
973 					    optarg);
974 					exit(255);
975 				}
976 			}
977 			break;
978 		case 'l':
979 			if (options.user == NULL)
980 				options.user = optarg;
981 			break;
982 
983 		case 'L':
984 			if (parse_forward(&fwd, optarg, 0, 0))
985 				add_local_forward(&options, &fwd);
986 			else {
987 				fprintf(stderr,
988 				    "Bad local forwarding specification '%s'\n",
989 				    optarg);
990 				exit(255);
991 			}
992 			break;
993 
994 		case 'R':
995 			if (parse_forward(&fwd, optarg, 0, 1) ||
996 			    parse_forward(&fwd, optarg, 1, 1)) {
997 				add_remote_forward(&options, &fwd);
998 			} else {
999 				fprintf(stderr,
1000 				    "Bad remote forwarding specification "
1001 				    "'%s'\n", optarg);
1002 				exit(255);
1003 			}
1004 			break;
1005 
1006 		case 'D':
1007 			if (parse_forward(&fwd, optarg, 1, 0)) {
1008 				add_local_forward(&options, &fwd);
1009 			} else {
1010 				fprintf(stderr,
1011 				    "Bad dynamic forwarding specification "
1012 				    "'%s'\n", optarg);
1013 				exit(255);
1014 			}
1015 			break;
1016 
1017 		case 'C':
1018 #ifdef WITH_ZLIB
1019 			options.compression = 1;
1020 #else
1021 			error("Compression not supported, disabling.");
1022 #endif
1023 			break;
1024 		case 'N':
1025 			no_shell_flag = 1;
1026 			options.request_tty = REQUEST_TTY_NO;
1027 			break;
1028 		case 'T':
1029 			options.request_tty = REQUEST_TTY_NO;
1030 			break;
1031 		case 'o':
1032 			line = xstrdup(optarg);
1033 			if (process_config_line(&options, pw,
1034 			    host ? host : "", host ? host : "", line,
1035 			    "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1036 				exit(255);
1037 			free(line);
1038 			break;
1039 		case 's':
1040 			subsystem_flag = 1;
1041 			break;
1042 		case 'S':
1043 			free(options.control_path);
1044 			options.control_path = xstrdup(optarg);
1045 			break;
1046 		case 'b':
1047 			options.bind_address = optarg;
1048 			break;
1049 		case 'B':
1050 			options.bind_interface = optarg;
1051 			break;
1052 		case 'F':
1053 			config = optarg;
1054 			break;
1055 		default:
1056 			usage();
1057 		}
1058 	}
1059 
1060 	if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1061 		opt_terminated = 1;
1062 
1063 	ac -= optind;
1064 	av += optind;
1065 
1066 	if (ac > 0 && !host) {
1067 		int tport;
1068 		char *tuser;
1069 		switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1070 		case -1:
1071 			usage();
1072 			break;
1073 		case 0:
1074 			if (options.user == NULL) {
1075 				options.user = tuser;
1076 				tuser = NULL;
1077 			}
1078 			free(tuser);
1079 			if (options.port == -1 && tport != -1)
1080 				options.port = tport;
1081 			break;
1082 		default:
1083 			p = xstrdup(*av);
1084 			cp = strrchr(p, '@');
1085 			if (cp != NULL) {
1086 				if (cp == p)
1087 					usage();
1088 				if (options.user == NULL) {
1089 					options.user = p;
1090 					p = NULL;
1091 				}
1092 				*cp++ = '\0';
1093 				host = xstrdup(cp);
1094 				free(p);
1095 			} else
1096 				host = p;
1097 			break;
1098 		}
1099 		if (ac > 1 && !opt_terminated) {
1100 			optind = optreset = 1;
1101 			goto again;
1102 		}
1103 		ac--, av++;
1104 	}
1105 
1106 	/* Check that we got a host name. */
1107 	if (!host)
1108 		usage();
1109 
1110 	host_arg = xstrdup(host);
1111 
1112 	/* Initialize the command to execute on remote host. */
1113 	if ((command = sshbuf_new()) == NULL)
1114 		fatal("sshbuf_new failed");
1115 
1116 	/*
1117 	 * Save the command to execute on the remote host in a buffer. There
1118 	 * is no limit on the length of the command, except by the maximum
1119 	 * packet size.  Also sets the tty flag if there is no command.
1120 	 */
1121 	if (!ac) {
1122 		/* No command specified - execute shell on a tty. */
1123 		if (subsystem_flag) {
1124 			fprintf(stderr,
1125 			    "You must specify a subsystem to invoke.\n");
1126 			usage();
1127 		}
1128 	} else {
1129 		/* A command has been specified.  Store it into the buffer. */
1130 		for (i = 0; i < ac; i++) {
1131 			if ((r = sshbuf_putf(command, "%s%s",
1132 			    i ? " " : "", av[i])) != 0)
1133 				fatal_fr(r, "buffer error");
1134 		}
1135 	}
1136 
1137 	/*
1138 	 * Initialize "log" output.  Since we are the client all output
1139 	 * goes to stderr unless otherwise specified by -y or -E.
1140 	 */
1141 	if (use_syslog && logfile != NULL)
1142 		fatal("Can't specify both -y and -E");
1143 	if (logfile != NULL)
1144 		log_redirect_stderr_to(logfile);
1145 	log_init(argv0,
1146 	    options.log_level == SYSLOG_LEVEL_NOT_SET ?
1147 	    SYSLOG_LEVEL_INFO : options.log_level,
1148 	    options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1149 	    SYSLOG_FACILITY_USER : options.log_facility,
1150 	    !use_syslog);
1151 
1152 	if (debug_flag)
1153 		logit("%s, %s", SSH_RELEASE, SSH_OPENSSL_VERSION);
1154 
1155 	/* Parse the configuration files */
1156 	process_config_files(host_arg, pw, 0, &want_final_pass);
1157 	if (want_final_pass)
1158 		debug("configuration requests final Match pass");
1159 
1160 	/* Hostname canonicalisation needs a few options filled. */
1161 	fill_default_options_for_canonicalization(&options);
1162 
1163 	/* If the user has replaced the hostname then take it into use now */
1164 	if (options.hostname != NULL) {
1165 		/* NB. Please keep in sync with readconf.c:match_cfg_line() */
1166 		cp = percent_expand(options.hostname,
1167 		    "h", host, (char *)NULL);
1168 		free(host);
1169 		host = cp;
1170 		free(options.hostname);
1171 		options.hostname = xstrdup(host);
1172 	}
1173 
1174 	/* Don't lowercase addresses, they will be explicitly canonicalised */
1175 	if ((was_addr = is_addr(host)) == 0)
1176 		lowercase(host);
1177 
1178 	/*
1179 	 * Try to canonicalize if requested by configuration or the
1180 	 * hostname is an address.
1181 	 */
1182 	if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1183 		addrs = resolve_canonicalize(&host, options.port);
1184 
1185 	/*
1186 	 * If CanonicalizePermittedCNAMEs have been specified but
1187 	 * other canonicalization did not happen (by not being requested
1188 	 * or by failing with fallback) then the hostname may still be changed
1189 	 * as a result of CNAME following.
1190 	 *
1191 	 * Try to resolve the bare hostname name using the system resolver's
1192 	 * usual search rules and then apply the CNAME follow rules.
1193 	 *
1194 	 * Skip the lookup if a ProxyCommand is being used unless the user
1195 	 * has specifically requested canonicalisation for this case via
1196 	 * CanonicalizeHostname=always
1197 	 */
1198 	direct = option_clear_or_none(options.proxy_command) &&
1199 	    options.jump_host == NULL;
1200 	if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1201 	    options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1202 		if ((addrs = resolve_host(host, options.port,
1203 		    direct, cname, sizeof(cname))) == NULL) {
1204 			/* Don't fatal proxied host names not in the DNS */
1205 			if (direct)
1206 				cleanup_exit(255); /* logged in resolve_host */
1207 		} else
1208 			check_follow_cname(direct, &host, cname);
1209 	}
1210 
1211 	/*
1212 	 * If canonicalisation is enabled then re-parse the configuration
1213 	 * files as new stanzas may match.
1214 	 */
1215 	if (options.canonicalize_hostname != 0 && !want_final_pass) {
1216 		debug("hostname canonicalisation enabled, "
1217 		    "will re-parse configuration");
1218 		want_final_pass = 1;
1219 	}
1220 
1221 	if (want_final_pass) {
1222 		debug("re-parsing configuration");
1223 		free(options.hostname);
1224 		options.hostname = xstrdup(host);
1225 		process_config_files(host_arg, pw, 1, NULL);
1226 		/*
1227 		 * Address resolution happens early with canonicalisation
1228 		 * enabled and the port number may have changed since, so
1229 		 * reset it in address list
1230 		 */
1231 		if (addrs != NULL && options.port > 0)
1232 			set_addrinfo_port(addrs, options.port);
1233 	}
1234 
1235 	/* Fill configuration defaults. */
1236 	if (fill_default_options(&options) != 0)
1237 		cleanup_exit(255);
1238 
1239 	if (options.user == NULL)
1240 		options.user = xstrdup(pw->pw_name);
1241 
1242 	/*
1243 	 * If ProxyJump option specified, then construct a ProxyCommand now.
1244 	 */
1245 	if (options.jump_host != NULL) {
1246 		char port_s[8];
1247 		const char *jumpuser = options.jump_user, *sshbin = argv0;
1248 		int port = options.port, jumpport = options.jump_port;
1249 
1250 		if (port <= 0)
1251 			port = default_ssh_port();
1252 		if (jumpport <= 0)
1253 			jumpport = default_ssh_port();
1254 		if (jumpuser == NULL)
1255 			jumpuser = options.user;
1256 		if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1257 		    strcmp(options.user, jumpuser) == 0)
1258 			fatal("jumphost loop via %s", options.jump_host);
1259 
1260 		/*
1261 		 * Try to use SSH indicated by argv[0], but fall back to
1262 		 * "ssh" if it appears unavailable.
1263 		 */
1264 		if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1265 			sshbin = "ssh";
1266 
1267 		/* Consistency check */
1268 		if (options.proxy_command != NULL)
1269 			fatal("inconsistent options: ProxyCommand+ProxyJump");
1270 		/* Never use FD passing for ProxyJump */
1271 		options.proxy_use_fdpass = 0;
1272 		snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1273 		xasprintf(&options.proxy_command,
1274 		    "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1275 		    sshbin,
1276 		    /* Optional "-l user" argument if jump_user set */
1277 		    options.jump_user == NULL ? "" : " -l ",
1278 		    options.jump_user == NULL ? "" : options.jump_user,
1279 		    /* Optional "-p port" argument if jump_port set */
1280 		    options.jump_port <= 0 ? "" : " -p ",
1281 		    options.jump_port <= 0 ? "" : port_s,
1282 		    /* Optional additional jump hosts ",..." */
1283 		    options.jump_extra == NULL ? "" : " -J ",
1284 		    options.jump_extra == NULL ? "" : options.jump_extra,
1285 		    /* Optional "-F" argumment if -F specified */
1286 		    config == NULL ? "" : " -F ",
1287 		    config == NULL ? "" : config,
1288 		    /* Optional "-v" arguments if -v set */
1289 		    debug_flag ? " -" : "",
1290 		    debug_flag, "vvv",
1291 		    /* Mandatory hostname */
1292 		    options.jump_host);
1293 		debug("Setting implicit ProxyCommand from ProxyJump: %s",
1294 		    options.proxy_command);
1295 	}
1296 
1297 	if (options.port == 0)
1298 		options.port = default_ssh_port();
1299 	channel_set_af(ssh, options.address_family);
1300 
1301 	/* Tidy and check options */
1302 	if (options.host_key_alias != NULL)
1303 		lowercase(options.host_key_alias);
1304 	if (options.proxy_command != NULL &&
1305 	    strcmp(options.proxy_command, "-") == 0 &&
1306 	    options.proxy_use_fdpass)
1307 		fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1308 	if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1309 		if (options.control_persist && options.control_path != NULL) {
1310 			debug("UpdateHostKeys=ask is incompatible with "
1311 			    "ControlPersist; disabling");
1312 			options.update_hostkeys = 0;
1313 		} else if (sshbuf_len(command) != 0 ||
1314 		    options.remote_command != NULL ||
1315 		    options.request_tty == REQUEST_TTY_NO) {
1316 			debug("UpdateHostKeys=ask is incompatible with "
1317 			    "remote command execution; disabling");
1318 			options.update_hostkeys = 0;
1319 		} else if (options.log_level < SYSLOG_LEVEL_INFO) {
1320 			/* no point logging anything; user won't see it */
1321 			options.update_hostkeys = 0;
1322 		}
1323 	}
1324 	if (options.connection_attempts <= 0)
1325 		fatal("Invalid number of ConnectionAttempts");
1326 
1327 	if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1328 		fatal("Cannot execute command-line and remote command.");
1329 
1330 	/* Cannot fork to background if no command. */
1331 	if (fork_after_authentication_flag && sshbuf_len(command) == 0 &&
1332 	    options.remote_command == NULL && !no_shell_flag)
1333 		fatal("Cannot fork into background without a command "
1334 		    "to execute.");
1335 
1336 	/* reinit */
1337 	log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1338 	for (j = 0; j < options.num_log_verbose; j++)
1339 		log_verbose_add(options.log_verbose[j]);
1340 
1341 	if (options.request_tty == REQUEST_TTY_YES ||
1342 	    options.request_tty == REQUEST_TTY_FORCE)
1343 		tty_flag = 1;
1344 
1345 	/* Allocate a tty by default if no command specified. */
1346 	if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1347 		tty_flag = options.request_tty != REQUEST_TTY_NO;
1348 
1349 	/* Force no tty */
1350 	if (options.request_tty == REQUEST_TTY_NO ||
1351 	    (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1352 		tty_flag = 0;
1353 	/* Do not allocate a tty if stdin is not a tty. */
1354 	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1355 	    options.request_tty != REQUEST_TTY_FORCE) {
1356 		if (tty_flag)
1357 			logit("Pseudo-terminal will not be allocated because "
1358 			    "stdin is not a terminal.");
1359 		tty_flag = 0;
1360 	}
1361 
1362 	/* Set up strings used to percent_expand() arguments */
1363 	cinfo = xcalloc(1, sizeof(*cinfo));
1364 	if (gethostname(thishost, sizeof(thishost)) == -1)
1365 		fatal("gethostname: %s", strerror(errno));
1366 	cinfo->thishost = xstrdup(thishost);
1367 	thishost[strcspn(thishost, ".")] = '\0';
1368 	cinfo->shorthost = xstrdup(thishost);
1369 	xasprintf(&cinfo->portstr, "%d", options.port);
1370 	xasprintf(&cinfo->uidstr, "%llu",
1371 	    (unsigned long long)pw->pw_uid);
1372 	cinfo->keyalias = xstrdup(options.host_key_alias ?
1373 	    options.host_key_alias : host_arg);
1374 	cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
1375 	    cinfo->portstr, options.user);
1376 	cinfo->host_arg = xstrdup(host_arg);
1377 	cinfo->remhost = xstrdup(host);
1378 	cinfo->remuser = xstrdup(options.user);
1379 	cinfo->homedir = xstrdup(pw->pw_dir);
1380 	cinfo->locuser = xstrdup(pw->pw_name);
1381 
1382 	/*
1383 	 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1384 	 * after port-forwarding is set up, so it may pick up any local
1385 	 * tunnel interface name allocated.
1386 	 */
1387 	if (options.remote_command != NULL) {
1388 		debug3("expanding RemoteCommand: %s", options.remote_command);
1389 		cp = options.remote_command;
1390 		options.remote_command = default_client_percent_expand(cp,
1391 		    cinfo);
1392 		debug3("expanded RemoteCommand: %s", options.remote_command);
1393 		free(cp);
1394 		if ((r = sshbuf_put(command, options.remote_command,
1395 		    strlen(options.remote_command))) != 0)
1396 			fatal_fr(r, "buffer error");
1397 	}
1398 
1399 	if (options.control_path != NULL) {
1400 		cp = tilde_expand_filename(options.control_path, getuid());
1401 		free(options.control_path);
1402 		options.control_path = default_client_percent_dollar_expand(cp,
1403 		    cinfo);
1404 		free(cp);
1405 	}
1406 
1407 	if (options.identity_agent != NULL) {
1408 		p = tilde_expand_filename(options.identity_agent, getuid());
1409 		cp = default_client_percent_dollar_expand(p, cinfo);
1410 		free(p);
1411 		free(options.identity_agent);
1412 		options.identity_agent = cp;
1413 	}
1414 
1415 	if (options.forward_agent_sock_path != NULL) {
1416 		p = tilde_expand_filename(options.forward_agent_sock_path,
1417 		    getuid());
1418 		cp = default_client_percent_dollar_expand(p, cinfo);
1419 		free(p);
1420 		free(options.forward_agent_sock_path);
1421 		options.forward_agent_sock_path = cp;
1422 		if (stat(options.forward_agent_sock_path, &st) != 0) {
1423 			error("Cannot forward agent socket path \"%s\": %s",
1424 			    options.forward_agent_sock_path, strerror(errno));
1425 			if (options.exit_on_forward_failure)
1426 				cleanup_exit(255);
1427 		}
1428 	}
1429 
1430 	if (options.num_system_hostfiles > 0 &&
1431 	    strcasecmp(options.system_hostfiles[0], "none") == 0) {
1432 		if (options.num_system_hostfiles > 1)
1433 			fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1434 			    "appears with other entries");
1435 		free(options.system_hostfiles[0]);
1436 		options.system_hostfiles[0] = NULL;
1437 		options.num_system_hostfiles = 0;
1438 	}
1439 
1440 	if (options.num_user_hostfiles > 0 &&
1441 	    strcasecmp(options.user_hostfiles[0], "none") == 0) {
1442 		if (options.num_user_hostfiles > 1)
1443 			fatal("Invalid UserKnownHostsFiles: \"none\" "
1444 			    "appears with other entries");
1445 		free(options.user_hostfiles[0]);
1446 		options.user_hostfiles[0] = NULL;
1447 		options.num_user_hostfiles = 0;
1448 	}
1449 	for (j = 0; j < options.num_user_hostfiles; j++) {
1450 		if (options.user_hostfiles[j] == NULL)
1451 			continue;
1452 		cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1453 		p = default_client_percent_dollar_expand(cp, cinfo);
1454 		if (strcmp(options.user_hostfiles[j], p) != 0)
1455 			debug3("expanded UserKnownHostsFile '%s' -> "
1456 			    "'%s'", options.user_hostfiles[j], p);
1457 		free(options.user_hostfiles[j]);
1458 		free(cp);
1459 		options.user_hostfiles[j] = p;
1460 	}
1461 
1462 	for (i = 0; i < options.num_local_forwards; i++) {
1463 		if (options.local_forwards[i].listen_path != NULL) {
1464 			cp = options.local_forwards[i].listen_path;
1465 			p = options.local_forwards[i].listen_path =
1466 			    default_client_percent_expand(cp, cinfo);
1467 			if (strcmp(cp, p) != 0)
1468 				debug3("expanded LocalForward listen path "
1469 				    "'%s' -> '%s'", cp, p);
1470 			free(cp);
1471 		}
1472 		if (options.local_forwards[i].connect_path != NULL) {
1473 			cp = options.local_forwards[i].connect_path;
1474 			p = options.local_forwards[i].connect_path =
1475 			    default_client_percent_expand(cp, cinfo);
1476 			if (strcmp(cp, p) != 0)
1477 				debug3("expanded LocalForward connect path "
1478 				    "'%s' -> '%s'", cp, p);
1479 			free(cp);
1480 		}
1481 	}
1482 
1483 	for (i = 0; i < options.num_remote_forwards; i++) {
1484 		if (options.remote_forwards[i].listen_path != NULL) {
1485 			cp = options.remote_forwards[i].listen_path;
1486 			p = options.remote_forwards[i].listen_path =
1487 			    default_client_percent_expand(cp, cinfo);
1488 			if (strcmp(cp, p) != 0)
1489 				debug3("expanded RemoteForward listen path "
1490 				    "'%s' -> '%s'", cp, p);
1491 			free(cp);
1492 		}
1493 		if (options.remote_forwards[i].connect_path != NULL) {
1494 			cp = options.remote_forwards[i].connect_path;
1495 			p = options.remote_forwards[i].connect_path =
1496 			    default_client_percent_expand(cp, cinfo);
1497 			if (strcmp(cp, p) != 0)
1498 				debug3("expanded RemoteForward connect path "
1499 				    "'%s' -> '%s'", cp, p);
1500 			free(cp);
1501 		}
1502 	}
1503 
1504 	if (config_test) {
1505 		dump_client_config(&options, host);
1506 		exit(0);
1507 	}
1508 
1509 	/* Expand SecurityKeyProvider if it refers to an environment variable */
1510 	if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1511 	    strlen(options.sk_provider) > 1) {
1512 		if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1513 			debug("Authenticator provider %s did not resolve; "
1514 			    "disabling", options.sk_provider);
1515 			free(options.sk_provider);
1516 			options.sk_provider = NULL;
1517 		} else {
1518 			debug2("resolved SecurityKeyProvider %s => %s",
1519 			    options.sk_provider, cp);
1520 			free(options.sk_provider);
1521 			options.sk_provider = xstrdup(cp);
1522 		}
1523 	}
1524 
1525 	if (muxclient_command != 0 && options.control_path == NULL)
1526 		fatal("No ControlPath specified for \"-O\" command");
1527 	if (options.control_path != NULL) {
1528 		int sock;
1529 		if ((sock = muxclient(options.control_path)) >= 0) {
1530 			ssh_packet_set_connection(ssh, sock, sock);
1531 			ssh_packet_set_mux(ssh);
1532 			goto skip_connect;
1533 		}
1534 	}
1535 
1536 	/*
1537 	 * If hostname canonicalisation was not enabled, then we may not
1538 	 * have yet resolved the hostname. Do so now.
1539 	 */
1540 	if (addrs == NULL && options.proxy_command == NULL) {
1541 		debug2("resolving \"%s\" port %d", host, options.port);
1542 		if ((addrs = resolve_host(host, options.port, 1,
1543 		    cname, sizeof(cname))) == NULL)
1544 			cleanup_exit(255); /* resolve_host logs the error */
1545 	}
1546 
1547 	if (options.connection_timeout >= INT_MAX/1000)
1548 		timeout_ms = INT_MAX;
1549 	else
1550 		timeout_ms = options.connection_timeout * 1000;
1551 
1552 	/* Open a connection to the remote host. */
1553 	if (ssh_connect(ssh, host, host_arg, addrs, &hostaddr, options.port,
1554 	    options.connection_attempts,
1555 	    &timeout_ms, options.tcp_keep_alive) != 0)
1556 		exit(255);
1557 
1558 	if (addrs != NULL)
1559 		freeaddrinfo(addrs);
1560 
1561 	ssh_packet_set_timeout(ssh, options.server_alive_interval,
1562 	    options.server_alive_count_max);
1563 
1564 	if (timeout_ms > 0)
1565 		debug3("timeout: %d ms remain after connect", timeout_ms);
1566 
1567 	/*
1568 	 * If we successfully made the connection and we have hostbased auth
1569 	 * enabled, load the public keys so we can later use the ssh-keysign
1570 	 * helper to sign challenges.
1571 	 */
1572 	sensitive_data.nkeys = 0;
1573 	sensitive_data.keys = NULL;
1574 	if (options.hostbased_authentication) {
1575 		sensitive_data.nkeys = 10;
1576 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1577 		    sizeof(struct sshkey));
1578 
1579 		/* XXX check errors? */
1580 #define L_PUBKEY(p,o) do { \
1581 	if ((o) >= sensitive_data.nkeys) \
1582 		fatal_f("pubkey out of array bounds"); \
1583 	check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1584 	    p, "pubkey"); \
1585 } while (0)
1586 #define L_CERT(p,o) do { \
1587 	if ((o) >= sensitive_data.nkeys) \
1588 		fatal_f("cert out of array bounds"); \
1589 	check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \
1590 } while (0)
1591 
1592 		if (options.hostbased_authentication == 1) {
1593 			L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1594 			L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1595 			L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1596 			L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1597 			L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1598 			L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1599 			L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1600 			L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1601 			L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1602 			L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1603 		}
1604 	}
1605 
1606 	/* load options.identity_files */
1607 	load_public_identity_files(cinfo);
1608 
1609 	/* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1610 	if (options.identity_agent &&
1611 	    strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1612 		if (strcmp(options.identity_agent, "none") == 0) {
1613 			unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1614 		} else {
1615 			cp = options.identity_agent;
1616 			/* legacy (limited) format */
1617 			if (cp[0] == '$' && cp[1] != '{') {
1618 				if (!valid_env_name(cp + 1)) {
1619 					fatal("Invalid IdentityAgent "
1620 					    "environment variable name %s", cp);
1621 				}
1622 				if ((p = getenv(cp + 1)) == NULL)
1623 					unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1624 				else
1625 					setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1626 			} else {
1627 				/* identity_agent specifies a path directly */
1628 				setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1629 			}
1630 		}
1631 	}
1632 
1633 	if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1634 		cp = options.forward_agent_sock_path;
1635 		if (cp[0] == '$') {
1636 			if (!valid_env_name(cp + 1)) {
1637 				fatal("Invalid ForwardAgent environment variable name %s", cp);
1638 			}
1639 			if ((p = getenv(cp + 1)) != NULL)
1640 				forward_agent_sock_path = p;
1641 			else
1642 				options.forward_agent = 0;
1643 			free(cp);
1644 		} else {
1645 			forward_agent_sock_path = cp;
1646 		}
1647 	}
1648 
1649 	/* Expand ~ in known host file names. */
1650 	tilde_expand_paths(options.system_hostfiles,
1651 	    options.num_system_hostfiles);
1652 	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1653 
1654 	ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1655 	ssh_signal(SIGCHLD, main_sigchld_handler);
1656 
1657 	/* Log into the remote system.  Never returns if the login fails. */
1658 	ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1659 	    options.port, pw, timeout_ms, cinfo);
1660 
1661 	if (ssh_packet_connection_is_on_socket(ssh)) {
1662 		verbose("Authenticated to %s ([%s]:%d).", host,
1663 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1664 	} else {
1665 		verbose("Authenticated to %s (via proxy).", host);
1666 	}
1667 
1668 	/* We no longer need the private host keys.  Clear them now. */
1669 	if (sensitive_data.nkeys != 0) {
1670 		for (i = 0; i < sensitive_data.nkeys; i++) {
1671 			if (sensitive_data.keys[i] != NULL) {
1672 				/* Destroys contents safely */
1673 				debug3("clear hostkey %d", i);
1674 				sshkey_free(sensitive_data.keys[i]);
1675 				sensitive_data.keys[i] = NULL;
1676 			}
1677 		}
1678 		free(sensitive_data.keys);
1679 	}
1680 	for (i = 0; i < options.num_identity_files; i++) {
1681 		free(options.identity_files[i]);
1682 		options.identity_files[i] = NULL;
1683 		if (options.identity_keys[i]) {
1684 			sshkey_free(options.identity_keys[i]);
1685 			options.identity_keys[i] = NULL;
1686 		}
1687 	}
1688 	for (i = 0; i < options.num_certificate_files; i++) {
1689 		free(options.certificate_files[i]);
1690 		options.certificate_files[i] = NULL;
1691 	}
1692 
1693 #ifdef ENABLE_PKCS11
1694 	(void)pkcs11_del_provider(options.pkcs11_provider);
1695 #endif
1696 
1697  skip_connect:
1698 	exit_status = ssh_session2(ssh, cinfo);
1699 	ssh_conn_info_free(cinfo);
1700 	ssh_packet_close(ssh);
1701 
1702 	if (options.control_path != NULL && muxserver_sock != -1)
1703 		unlink(options.control_path);
1704 
1705 	/* Kill ProxyCommand if it is running. */
1706 	ssh_kill_proxy_command();
1707 
1708 	return exit_status;
1709 }
1710 
1711 static void
control_persist_detach(void)1712 control_persist_detach(void)
1713 {
1714 	pid_t pid;
1715 
1716 	debug_f("backgrounding master process");
1717 
1718 	/*
1719 	 * master (current process) into the background, and make the
1720 	 * foreground process a client of the backgrounded master.
1721 	 */
1722 	switch ((pid = fork())) {
1723 	case -1:
1724 		fatal_f("fork: %s", strerror(errno));
1725 	case 0:
1726 		/* Child: master process continues mainloop */
1727 		break;
1728 	default:
1729 		/* Parent: set up mux client to connect to backgrounded master */
1730 		debug2_f("background process is %ld", (long)pid);
1731 		stdin_null_flag = ostdin_null_flag;
1732 		options.request_tty = orequest_tty;
1733 		tty_flag = otty_flag;
1734 		close(muxserver_sock);
1735 		muxserver_sock = -1;
1736 		options.control_master = SSHCTL_MASTER_NO;
1737 		muxclient(options.control_path);
1738 		/* muxclient() doesn't return on success. */
1739 		fatal("Failed to connect to new control master");
1740 	}
1741 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1742 		error_f("stdfd_devnull failed");
1743 	daemon(1, 1);
1744 	setproctitle("%s [mux]", options.control_path);
1745 }
1746 
1747 /* Do fork() after authentication. Used by "ssh -f" */
1748 static void
fork_postauth(void)1749 fork_postauth(void)
1750 {
1751 	if (need_controlpersist_detach)
1752 		control_persist_detach();
1753 	debug("forking to background");
1754 	fork_after_authentication_flag = 0;
1755 	if (daemon(1, 1) == -1)
1756 		fatal("daemon() failed: %.200s", strerror(errno));
1757 	if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1758 		error_f("stdfd_devnull failed");
1759 }
1760 
1761 static void
forwarding_success(void)1762 forwarding_success(void)
1763 {
1764 	if (forward_confirms_pending == -1)
1765 		return;
1766 	if (--forward_confirms_pending == 0) {
1767 		debug_f("all expected forwarding replies received");
1768 		if (fork_after_authentication_flag)
1769 			fork_postauth();
1770 	} else {
1771 		debug2_f("%d expected forwarding replies remaining",
1772 		    forward_confirms_pending);
1773 	}
1774 }
1775 
1776 /* Callback for remote forward global requests */
1777 static void
ssh_confirm_remote_forward(struct ssh * ssh,int type,u_int32_t seq,void * ctxt)1778 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1779 {
1780 	struct Forward *rfwd = (struct Forward *)ctxt;
1781 	u_int port;
1782 	int r;
1783 
1784 	/* XXX verbose() on failure? */
1785 	debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1786 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1787 	    rfwd->listen_path ? rfwd->listen_path :
1788 	    rfwd->listen_host ? rfwd->listen_host : "",
1789 	    (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1790 	    rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1791 	    rfwd->connect_host, rfwd->connect_port);
1792 	if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1793 		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1794 			if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1795 				fatal_fr(r, "parse packet");
1796 			if (port > 65535) {
1797 				error("Invalid allocated port %u for remote "
1798 				    "forward to %s:%d", port,
1799 				    rfwd->connect_host, rfwd->connect_port);
1800 				/* Ensure failure processing runs below */
1801 				type = SSH2_MSG_REQUEST_FAILURE;
1802 				channel_update_permission(ssh,
1803 				    rfwd->handle, -1);
1804 			} else {
1805 				rfwd->allocated_port = (int)port;
1806 				logit("Allocated port %u for remote "
1807 				    "forward to %s:%d",
1808 				    rfwd->allocated_port, rfwd->connect_host,
1809 				    rfwd->connect_port);
1810 				channel_update_permission(ssh,
1811 				    rfwd->handle, rfwd->allocated_port);
1812 			}
1813 		} else {
1814 			channel_update_permission(ssh, rfwd->handle, -1);
1815 		}
1816 	}
1817 
1818 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1819 		if (options.exit_on_forward_failure) {
1820 			if (rfwd->listen_path != NULL)
1821 				fatal("Error: remote port forwarding failed "
1822 				    "for listen path %s", rfwd->listen_path);
1823 			else
1824 				fatal("Error: remote port forwarding failed "
1825 				    "for listen port %d", rfwd->listen_port);
1826 		} else {
1827 			if (rfwd->listen_path != NULL)
1828 				logit("Warning: remote port forwarding failed "
1829 				    "for listen path %s", rfwd->listen_path);
1830 			else
1831 				logit("Warning: remote port forwarding failed "
1832 				    "for listen port %d", rfwd->listen_port);
1833 		}
1834 	}
1835 	forwarding_success();
1836 }
1837 
1838 static void
client_cleanup_stdio_fwd(struct ssh * ssh,int id,void * arg)1839 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1840 {
1841 	debug("stdio forwarding: done");
1842 	cleanup_exit(0);
1843 }
1844 
1845 static void
ssh_stdio_confirm(struct ssh * ssh,int id,int success,void * arg)1846 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1847 {
1848 	if (!success)
1849 		fatal("stdio forwarding failed");
1850 }
1851 
1852 static void
ssh_tun_confirm(struct ssh * ssh,int id,int success,void * arg)1853 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1854 {
1855 	if (!success) {
1856 		error("Tunnel forwarding failed");
1857 		if (options.exit_on_forward_failure)
1858 			cleanup_exit(255);
1859 	}
1860 
1861 	debug_f("tunnel forward established, id=%d", id);
1862 	forwarding_success();
1863 }
1864 
1865 static void
ssh_init_stdio_forwarding(struct ssh * ssh)1866 ssh_init_stdio_forwarding(struct ssh *ssh)
1867 {
1868 	Channel *c;
1869 	int in, out;
1870 
1871 	if (options.stdio_forward_host == NULL)
1872 		return;
1873 
1874 	debug3_f("%s:%d", options.stdio_forward_host,
1875 	    options.stdio_forward_port);
1876 
1877 	if ((in = dup(STDIN_FILENO)) == -1 ||
1878 	    (out = dup(STDOUT_FILENO)) == -1)
1879 		fatal_f("dup() in/out failed");
1880 	if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1881 	    options.stdio_forward_port, in, out,
1882 	    CHANNEL_NONBLOCK_STDIO)) == NULL)
1883 		fatal_f("channel_connect_stdio_fwd failed");
1884 	channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1885 	channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1886 }
1887 
1888 static void
ssh_init_forward_permissions(struct ssh * ssh,const char * what,char ** opens,u_int num_opens)1889 ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
1890     u_int num_opens)
1891 {
1892 	u_int i;
1893 	int port;
1894 	char *addr, *arg, *oarg, ch;
1895 	int where = FORWARD_LOCAL;
1896 
1897 	channel_clear_permission(ssh, FORWARD_ADM, where);
1898 	if (num_opens == 0)
1899 		return; /* permit any */
1900 
1901 	/* handle keywords: "any" / "none" */
1902 	if (num_opens == 1 && strcmp(opens[0], "any") == 0)
1903 		return;
1904 	if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
1905 		channel_disable_admin(ssh, where);
1906 		return;
1907 	}
1908 	/* Otherwise treat it as a list of permitted host:port */
1909 	for (i = 0; i < num_opens; i++) {
1910 		oarg = arg = xstrdup(opens[i]);
1911 		ch = '\0';
1912 		addr = hpdelim2(&arg, &ch);
1913 		if (addr == NULL || ch == '/')
1914 			fatal_f("missing host in %s", what);
1915 		addr = cleanhostname(addr);
1916 		if (arg == NULL || ((port = permitopen_port(arg)) < 0))
1917 			fatal_f("bad port number in %s", what);
1918 		/* Send it to channels layer */
1919 		channel_add_permission(ssh, FORWARD_ADM,
1920 		    where, addr, port);
1921 		free(oarg);
1922 	}
1923 }
1924 
1925 static void
ssh_init_forwarding(struct ssh * ssh,char ** ifname)1926 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1927 {
1928 	int success = 0;
1929 	int i;
1930 
1931 	ssh_init_forward_permissions(ssh, "permitremoteopen",
1932 	    options.permitted_remote_opens,
1933 	    options.num_permitted_remote_opens);
1934 
1935 	if (options.exit_on_forward_failure)
1936 		forward_confirms_pending = 0; /* track pending requests */
1937 	/* Initiate local TCP/IP port forwardings. */
1938 	for (i = 0; i < options.num_local_forwards; i++) {
1939 		debug("Local connections to %.200s:%d forwarded to remote "
1940 		    "address %.200s:%d",
1941 		    (options.local_forwards[i].listen_path != NULL) ?
1942 		    options.local_forwards[i].listen_path :
1943 		    (options.local_forwards[i].listen_host == NULL) ?
1944 		    (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1945 		    options.local_forwards[i].listen_host,
1946 		    options.local_forwards[i].listen_port,
1947 		    (options.local_forwards[i].connect_path != NULL) ?
1948 		    options.local_forwards[i].connect_path :
1949 		    options.local_forwards[i].connect_host,
1950 		    options.local_forwards[i].connect_port);
1951 		success += channel_setup_local_fwd_listener(ssh,
1952 		    &options.local_forwards[i], &options.fwd_opts);
1953 	}
1954 	if (i > 0 && success != i && options.exit_on_forward_failure)
1955 		fatal("Could not request local forwarding.");
1956 	if (i > 0 && success == 0)
1957 		error("Could not request local forwarding.");
1958 
1959 	/* Initiate remote TCP/IP port forwardings. */
1960 	for (i = 0; i < options.num_remote_forwards; i++) {
1961 		debug("Remote connections from %.200s:%d forwarded to "
1962 		    "local address %.200s:%d",
1963 		    (options.remote_forwards[i].listen_path != NULL) ?
1964 		    options.remote_forwards[i].listen_path :
1965 		    (options.remote_forwards[i].listen_host == NULL) ?
1966 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1967 		    options.remote_forwards[i].listen_port,
1968 		    (options.remote_forwards[i].connect_path != NULL) ?
1969 		    options.remote_forwards[i].connect_path :
1970 		    options.remote_forwards[i].connect_host,
1971 		    options.remote_forwards[i].connect_port);
1972 		if ((options.remote_forwards[i].handle =
1973 		    channel_request_remote_forwarding(ssh,
1974 		    &options.remote_forwards[i])) >= 0) {
1975 			client_register_global_confirm(
1976 			    ssh_confirm_remote_forward,
1977 			    &options.remote_forwards[i]);
1978 			forward_confirms_pending++;
1979 		} else if (options.exit_on_forward_failure)
1980 			fatal("Could not request remote forwarding.");
1981 		else
1982 			logit("Warning: Could not request remote forwarding.");
1983 	}
1984 
1985 	/* Initiate tunnel forwarding. */
1986 	if (options.tun_open != SSH_TUNMODE_NO) {
1987 		if ((*ifname = client_request_tun_fwd(ssh,
1988 		    options.tun_open, options.tun_local,
1989 		    options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
1990 			forward_confirms_pending++;
1991 		else if (options.exit_on_forward_failure)
1992 			fatal("Could not request tunnel forwarding.");
1993 		else
1994 			error("Could not request tunnel forwarding.");
1995 	}
1996 	if (forward_confirms_pending > 0) {
1997 		debug_f("expecting replies for %d forwards",
1998 		    forward_confirms_pending);
1999 	}
2000 }
2001 
2002 static void
check_agent_present(void)2003 check_agent_present(void)
2004 {
2005 	int r;
2006 
2007 	if (options.forward_agent) {
2008 		/* Clear agent forwarding if we don't have an agent. */
2009 		if ((r = ssh_get_authentication_socket(NULL)) != 0) {
2010 			options.forward_agent = 0;
2011 			if (r != SSH_ERR_AGENT_NOT_PRESENT)
2012 				debug_r(r, "ssh_get_authentication_socket");
2013 		}
2014 	}
2015 }
2016 
2017 static void
ssh_session2_setup(struct ssh * ssh,int id,int success,void * arg)2018 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
2019 {
2020 	extern char **environ;
2021 	const char *display;
2022 	int r, interactive = tty_flag;
2023 	char *proto = NULL, *data = NULL;
2024 
2025 	if (!success)
2026 		return; /* No need for error message, channels code sens one */
2027 
2028 	display = getenv("DISPLAY");
2029 	if (display == NULL && options.forward_x11)
2030 		debug("X11 forwarding requested but DISPLAY not set");
2031 	if (options.forward_x11 && client_x11_get_proto(ssh, display,
2032 	    options.xauth_location, options.forward_x11_trusted,
2033 	    options.forward_x11_timeout, &proto, &data) == 0) {
2034 		/* Request forwarding with authentication spoofing. */
2035 		debug("Requesting X11 forwarding with authentication "
2036 		    "spoofing.");
2037 		x11_request_forwarding_with_spoofing(ssh, id, display, proto,
2038 		    data, 1);
2039 		client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
2040 		/* XXX exit_on_forward_failure */
2041 		interactive = 1;
2042 	}
2043 
2044 	check_agent_present();
2045 	if (options.forward_agent) {
2046 		debug("Requesting authentication agent forwarding.");
2047 		channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
2048 		if ((r = sshpkt_send(ssh)) != 0)
2049 			fatal_fr(r, "send packet");
2050 	}
2051 
2052 	/* Tell the packet module whether this is an interactive session. */
2053 	ssh_packet_set_interactive(ssh, interactive,
2054 	    options.ip_qos_interactive, options.ip_qos_bulk);
2055 
2056 	client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
2057 	    NULL, fileno(stdin), command, environ);
2058 }
2059 
2060 /* open new channel for a session */
2061 static int
ssh_session2_open(struct ssh * ssh)2062 ssh_session2_open(struct ssh *ssh)
2063 {
2064 	Channel *c;
2065 	int window, packetmax, in, out, err;
2066 
2067 	if (stdin_null_flag) {
2068 		in = open(_PATH_DEVNULL, O_RDONLY);
2069 	} else {
2070 		in = dup(STDIN_FILENO);
2071 	}
2072 	out = dup(STDOUT_FILENO);
2073 	err = dup(STDERR_FILENO);
2074 
2075 	if (in == -1 || out == -1 || err == -1)
2076 		fatal("dup() in/out/err failed");
2077 
2078 	window = CHAN_SES_WINDOW_DEFAULT;
2079 	packetmax = CHAN_SES_PACKET_DEFAULT;
2080 	if (tty_flag) {
2081 		window >>= 1;
2082 		packetmax >>= 1;
2083 	}
2084 	c = channel_new(ssh,
2085 	    "session", SSH_CHANNEL_OPENING, in, out, err,
2086 	    window, packetmax, CHAN_EXTENDED_WRITE,
2087 	    "client-session", CHANNEL_NONBLOCK_STDIO);
2088 
2089 	debug3_f("channel_new: %d", c->self);
2090 
2091 	channel_send_open(ssh, c->self);
2092 	if (!no_shell_flag)
2093 		channel_register_open_confirm(ssh, c->self,
2094 		    ssh_session2_setup, NULL);
2095 
2096 	return c->self;
2097 }
2098 
2099 static int
ssh_session2(struct ssh * ssh,const struct ssh_conn_info * cinfo)2100 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2101 {
2102 	int r, id = -1;
2103 	char *cp, *tun_fwd_ifname = NULL;
2104 
2105 	/* XXX should be pre-session */
2106 	if (!options.control_persist)
2107 		ssh_init_stdio_forwarding(ssh);
2108 
2109 	ssh_init_forwarding(ssh, &tun_fwd_ifname);
2110 
2111 	if (options.local_command != NULL) {
2112 		debug3("expanding LocalCommand: %s", options.local_command);
2113 		cp = options.local_command;
2114 		options.local_command = percent_expand(cp,
2115 		    DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2116 		    "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2117 		    (char *)NULL);
2118 		debug3("expanded LocalCommand: %s", options.local_command);
2119 		free(cp);
2120 	}
2121 
2122 	/* Start listening for multiplex clients */
2123 	if (!ssh_packet_get_mux(ssh))
2124 		muxserver_listen(ssh);
2125 
2126 	/*
2127 	 * If we are in control persist mode and have a working mux listen
2128 	 * socket, then prepare to background ourselves and have a foreground
2129 	 * client attach as a control client.
2130 	 * NB. we must save copies of the flags that we override for
2131 	 * the backgrounding, since we defer attachment of the client until
2132 	 * after the connection is fully established (in particular,
2133 	 * async rfwd replies have been received for ExitOnForwardFailure).
2134 	 */
2135 	if (options.control_persist && muxserver_sock != -1) {
2136 		ostdin_null_flag = stdin_null_flag;
2137 		ono_shell_flag = no_shell_flag;
2138 		orequest_tty = options.request_tty;
2139 		otty_flag = tty_flag;
2140 		stdin_null_flag = 1;
2141 		no_shell_flag = 1;
2142 		tty_flag = 0;
2143 		if (!fork_after_authentication_flag &&
2144 		    (!ono_shell_flag || options.stdio_forward_host != NULL))
2145 			need_controlpersist_detach = 1;
2146 		fork_after_authentication_flag = 1;
2147 	}
2148 	/*
2149 	 * ControlPersist mux listen socket setup failed, attempt the
2150 	 * stdio forward setup that we skipped earlier.
2151 	 */
2152 	if (options.control_persist && muxserver_sock == -1)
2153 		ssh_init_stdio_forwarding(ssh);
2154 
2155 	if (!no_shell_flag)
2156 		id = ssh_session2_open(ssh);
2157 	else {
2158 		ssh_packet_set_interactive(ssh,
2159 		    options.control_master == SSHCTL_MASTER_NO,
2160 		    options.ip_qos_interactive, options.ip_qos_bulk);
2161 	}
2162 
2163 	/* If we don't expect to open a new session, then disallow it */
2164 	if (options.control_master == SSHCTL_MASTER_NO &&
2165 	    (ssh->compat & SSH_NEW_OPENSSH)) {
2166 		debug("Requesting no-more-sessions@openssh.com");
2167 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2168 		    (r = sshpkt_put_cstring(ssh,
2169 		    "no-more-sessions@openssh.com")) != 0 ||
2170 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2171 		    (r = sshpkt_send(ssh)) != 0)
2172 			fatal_fr(r, "send packet");
2173 	}
2174 
2175 	/* Execute a local command */
2176 	if (options.local_command != NULL &&
2177 	    options.permit_local_command)
2178 		ssh_local_cmd(options.local_command);
2179 
2180 	/*
2181 	 * stdout is now owned by the session channel; clobber it here
2182 	 * so future channel closes are propagated to the local fd.
2183 	 * NB. this can only happen after LocalCommand has completed,
2184 	 * as it may want to write to stdout.
2185 	 */
2186 	if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2187 		error_f("stdfd_devnull failed");
2188 
2189 	/*
2190 	 * If requested and we are not interested in replies to remote
2191 	 * forwarding requests, then let ssh continue in the background.
2192 	 */
2193 	if (fork_after_authentication_flag) {
2194 		if (options.exit_on_forward_failure &&
2195 		    options.num_remote_forwards > 0) {
2196 			debug("deferring postauth fork until remote forward "
2197 			    "confirmation received");
2198 		} else
2199 			fork_postauth();
2200 	}
2201 
2202 	return client_loop(ssh, tty_flag, tty_flag ?
2203 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
2204 }
2205 
2206 /* Loads all IdentityFile and CertificateFile keys */
2207 static void
load_public_identity_files(const struct ssh_conn_info * cinfo)2208 load_public_identity_files(const struct ssh_conn_info *cinfo)
2209 {
2210 	char *filename, *cp;
2211 	struct sshkey *public;
2212 	int i;
2213 	u_int n_ids, n_certs;
2214 	char *identity_files[SSH_MAX_IDENTITY_FILES];
2215 	struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2216 	int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2217 	char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2218 	struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2219 	int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2220 #ifdef ENABLE_PKCS11
2221 	struct sshkey **keys = NULL;
2222 	char **comments = NULL;
2223 	int nkeys;
2224 #endif /* PKCS11 */
2225 
2226 	n_ids = n_certs = 0;
2227 	memset(identity_files, 0, sizeof(identity_files));
2228 	memset(identity_keys, 0, sizeof(identity_keys));
2229 	memset(identity_file_userprovided, 0,
2230 	    sizeof(identity_file_userprovided));
2231 	memset(certificate_files, 0, sizeof(certificate_files));
2232 	memset(certificates, 0, sizeof(certificates));
2233 	memset(certificate_file_userprovided, 0,
2234 	    sizeof(certificate_file_userprovided));
2235 
2236 #ifdef ENABLE_PKCS11
2237 	if (options.pkcs11_provider != NULL &&
2238 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2239 	    (pkcs11_init(!options.batch_mode) == 0) &&
2240 	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2241 	    &keys, &comments)) > 0) {
2242 		for (i = 0; i < nkeys; i++) {
2243 			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2244 				sshkey_free(keys[i]);
2245 				free(comments[i]);
2246 				continue;
2247 			}
2248 			identity_keys[n_ids] = keys[i];
2249 			identity_files[n_ids] = comments[i]; /* transferred */
2250 			n_ids++;
2251 		}
2252 		free(keys);
2253 		free(comments);
2254 	}
2255 #endif /* ENABLE_PKCS11 */
2256 	for (i = 0; i < options.num_identity_files; i++) {
2257 		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2258 		    strcasecmp(options.identity_files[i], "none") == 0) {
2259 			free(options.identity_files[i]);
2260 			options.identity_files[i] = NULL;
2261 			continue;
2262 		}
2263 		cp = tilde_expand_filename(options.identity_files[i], getuid());
2264 		filename = default_client_percent_dollar_expand(cp, cinfo);
2265 		free(cp);
2266 		check_load(sshkey_load_public(filename, &public, NULL),
2267 		    filename, "pubkey");
2268 		debug("identity file %s type %d", filename,
2269 		    public ? public->type : -1);
2270 		free(options.identity_files[i]);
2271 		identity_files[n_ids] = filename;
2272 		identity_keys[n_ids] = public;
2273 		identity_file_userprovided[n_ids] =
2274 		    options.identity_file_userprovided[i];
2275 		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2276 			continue;
2277 
2278 		/*
2279 		 * If no certificates have been explicitly listed then try
2280 		 * to add the default certificate variant too.
2281 		 */
2282 		if (options.num_certificate_files != 0)
2283 			continue;
2284 		xasprintf(&cp, "%s-cert", filename);
2285 		check_load(sshkey_load_public(cp, &public, NULL),
2286 		    filename, "pubkey");
2287 		debug("identity file %s type %d", cp,
2288 		    public ? public->type : -1);
2289 		if (public == NULL) {
2290 			free(cp);
2291 			continue;
2292 		}
2293 		if (!sshkey_is_cert(public)) {
2294 			debug_f("key %s type %s is not a certificate",
2295 			    cp, sshkey_type(public));
2296 			sshkey_free(public);
2297 			free(cp);
2298 			continue;
2299 		}
2300 		/* NB. leave filename pointing to private key */
2301 		identity_files[n_ids] = xstrdup(filename);
2302 		identity_keys[n_ids] = public;
2303 		identity_file_userprovided[n_ids] =
2304 		    options.identity_file_userprovided[i];
2305 		n_ids++;
2306 	}
2307 
2308 	if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2309 		fatal_f("too many certificates");
2310 	for (i = 0; i < options.num_certificate_files; i++) {
2311 		cp = tilde_expand_filename(options.certificate_files[i],
2312 		    getuid());
2313 		filename = default_client_percent_dollar_expand(cp, cinfo);
2314 		free(cp);
2315 
2316 		check_load(sshkey_load_public(filename, &public, NULL),
2317 		    filename, "certificate");
2318 		debug("certificate file %s type %d", filename,
2319 		    public ? public->type : -1);
2320 		free(options.certificate_files[i]);
2321 		options.certificate_files[i] = NULL;
2322 		if (public == NULL) {
2323 			free(filename);
2324 			continue;
2325 		}
2326 		if (!sshkey_is_cert(public)) {
2327 			debug_f("key %s type %s is not a certificate",
2328 			    filename, sshkey_type(public));
2329 			sshkey_free(public);
2330 			free(filename);
2331 			continue;
2332 		}
2333 		certificate_files[n_certs] = filename;
2334 		certificates[n_certs] = public;
2335 		certificate_file_userprovided[n_certs] =
2336 		    options.certificate_file_userprovided[i];
2337 		++n_certs;
2338 	}
2339 
2340 	options.num_identity_files = n_ids;
2341 	memcpy(options.identity_files, identity_files, sizeof(identity_files));
2342 	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2343 	memcpy(options.identity_file_userprovided,
2344 	    identity_file_userprovided, sizeof(identity_file_userprovided));
2345 
2346 	options.num_certificate_files = n_certs;
2347 	memcpy(options.certificate_files,
2348 	    certificate_files, sizeof(certificate_files));
2349 	memcpy(options.certificates, certificates, sizeof(certificates));
2350 	memcpy(options.certificate_file_userprovided,
2351 	    certificate_file_userprovided,
2352 	    sizeof(certificate_file_userprovided));
2353 }
2354 
2355 static void
main_sigchld_handler(int sig)2356 main_sigchld_handler(int sig)
2357 {
2358 	int save_errno = errno;
2359 	pid_t pid;
2360 	int status;
2361 
2362 	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2363 	    (pid == -1 && errno == EINTR))
2364 		;
2365 	errno = save_errno;
2366 }
2367