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