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