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