ssh.c revision 264377
1/* $OpenBSD: ssh.c,v 1.401 2014/02/26 20:18:37 djm Exp $ */
2/* $FreeBSD: stable/10/crypto/openssh/ssh.c 264377 2014-04-12 20:22:59Z des $ */
3/*
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 *                    All rights reserved
7 * Ssh client program.  This program can be used to log into a remote machine.
8 * The software supports strong authentication, encryption, and forwarding
9 * of X11, TCP/IP, and authentication connections.
10 *
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose.  Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
16 *
17 * Copyright (c) 1999 Niels Provos.  All rights reserved.
18 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
19 *
20 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
21 * in Canada (German citizen).
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 *
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 */
43
44#include "includes.h"
45__RCSID("$FreeBSD: stable/10/crypto/openssh/ssh.c 264377 2014-04-12 20:22:59Z des $");
46
47#include <sys/types.h>
48#ifdef HAVE_SYS_STAT_H
49# include <sys/stat.h>
50#endif
51#include <sys/resource.h>
52#include <sys/ioctl.h>
53#include <sys/param.h>
54#include <sys/socket.h>
55#include <sys/wait.h>
56
57#include <ctype.h>
58#include <errno.h>
59#include <fcntl.h>
60#include <netdb.h>
61#ifdef HAVE_PATHS_H
62#include <paths.h>
63#endif
64#include <pwd.h>
65#include <signal.h>
66#include <stdarg.h>
67#include <stddef.h>
68#include <stdio.h>
69#include <stdlib.h>
70#include <string.h>
71#include <unistd.h>
72
73#include <netinet/in.h>
74#include <arpa/inet.h>
75
76#include <openssl/evp.h>
77#include <openssl/err.h>
78#include "openbsd-compat/openssl-compat.h"
79#include "openbsd-compat/sys-queue.h"
80
81#include "xmalloc.h"
82#include "ssh.h"
83#include "ssh1.h"
84#include "ssh2.h"
85#include "canohost.h"
86#include "compat.h"
87#include "cipher.h"
88#include "packet.h"
89#include "buffer.h"
90#include "channels.h"
91#include "key.h"
92#include "authfd.h"
93#include "authfile.h"
94#include "pathnames.h"
95#include "dispatch.h"
96#include "clientloop.h"
97#include "log.h"
98#include "readconf.h"
99#include "sshconnect.h"
100#include "misc.h"
101#include "kex.h"
102#include "mac.h"
103#include "sshpty.h"
104#include "match.h"
105#include "msg.h"
106#include "uidswap.h"
107#include "roaming.h"
108#include "version.h"
109
110#ifdef ENABLE_PKCS11
111#include "ssh-pkcs11.h"
112#endif
113
114extern char *__progname;
115
116/* Saves a copy of argv for setproctitle emulation */
117#ifndef HAVE_SETPROCTITLE
118static char **saved_av;
119#endif
120
121/* Flag indicating whether debug mode is on.  May be set on the command line. */
122int debug_flag = 0;
123
124/* Flag indicating whether a tty should be requested */
125int tty_flag = 0;
126
127/* don't exec a shell */
128int no_shell_flag = 0;
129
130/*
131 * Flag indicating that nothing should be read from stdin.  This can be set
132 * on the command line.
133 */
134int stdin_null_flag = 0;
135
136/*
137 * Flag indicating that the current process should be backgrounded and
138 * a new slave launched in the foreground for ControlPersist.
139 */
140int need_controlpersist_detach = 0;
141
142/* Copies of flags for ControlPersist foreground slave */
143int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
144
145/*
146 * Flag indicating that ssh should fork after authentication.  This is useful
147 * so that the passphrase can be entered manually, and then ssh goes to the
148 * background.
149 */
150int fork_after_authentication_flag = 0;
151
152/* forward stdio to remote host and port */
153char *stdio_forward_host = NULL;
154int stdio_forward_port = 0;
155
156/*
157 * General data structure for command line options and options configurable
158 * in configuration files.  See readconf.h.
159 */
160Options options;
161
162/* optional user configfile */
163char *config = NULL;
164
165/*
166 * Name of the host we are connecting to.  This is the name given on the
167 * command line, or the HostName specified for the user-supplied name in a
168 * configuration file.
169 */
170char *host;
171
172/* socket address the host resolves to */
173struct sockaddr_storage hostaddr;
174
175/* Private host keys. */
176Sensitive sensitive_data;
177
178/* Original real UID. */
179uid_t original_real_uid;
180uid_t original_effective_uid;
181
182/* command to be executed */
183Buffer command;
184
185/* Should we execute a command or invoke a subsystem? */
186int subsystem_flag = 0;
187
188/* # of replies received for global requests */
189static int remote_forward_confirms_received = 0;
190
191/* mux.c */
192extern int muxserver_sock;
193extern u_int muxclient_command;
194
195/* Prints a help message to the user.  This function never returns. */
196
197static void
198usage(void)
199{
200	fprintf(stderr,
201"usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
202"           [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
203"           [-F configfile] [-I pkcs11] [-i identity_file]\n"
204"           [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]\n"
205"           [-O ctl_cmd] [-o option] [-p port]\n"
206"           [-Q cipher | cipher-auth | mac | kex | key]\n"
207"           [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]\n"
208"           [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
209	);
210	exit(255);
211}
212
213static int ssh_session(void);
214static int ssh_session2(void);
215static void load_public_identity_files(void);
216static void main_sigchld_handler(int);
217
218/* from muxclient.c */
219void muxclient(const char *);
220void muxserver_listen(void);
221
222/* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
223static void
224tilde_expand_paths(char **paths, u_int num_paths)
225{
226	u_int i;
227	char *cp;
228
229	for (i = 0; i < num_paths; i++) {
230		cp = tilde_expand_filename(paths[i], original_real_uid);
231		free(paths[i]);
232		paths[i] = cp;
233	}
234}
235
236/*
237 * Attempt to resolve a host name / port to a set of addresses and
238 * optionally return any CNAMEs encountered along the way.
239 * Returns NULL on failure.
240 * NB. this function must operate with a options having undefined members.
241 */
242static struct addrinfo *
243resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
244{
245	char strport[NI_MAXSERV];
246	struct addrinfo hints, *res;
247	int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
248
249	if (port <= 0)
250		port = default_ssh_port();
251
252	snprintf(strport, sizeof strport, "%u", port);
253	memset(&hints, 0, sizeof(hints));
254	hints.ai_family = options.address_family == -1 ?
255	    AF_UNSPEC : options.address_family;
256	hints.ai_socktype = SOCK_STREAM;
257	if (cname != NULL)
258		hints.ai_flags = AI_CANONNAME;
259	if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
260		if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
261			loglevel = SYSLOG_LEVEL_ERROR;
262		do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
263		    __progname, name, ssh_gai_strerror(gaierr));
264		return NULL;
265	}
266	if (cname != NULL && res->ai_canonname != NULL) {
267		if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
268			error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
269			    __func__, name,  res->ai_canonname, (u_long)clen);
270			if (clen > 0)
271				*cname = '\0';
272		}
273	}
274	return res;
275}
276
277/*
278 * Check whether the cname is a permitted replacement for the hostname
279 * and perform the replacement if it is.
280 * NB. this function must operate with a options having undefined members.
281 */
282static int
283check_follow_cname(char **namep, const char *cname)
284{
285	int i;
286	struct allowed_cname *rule;
287
288	if (*cname == '\0' || options.num_permitted_cnames == 0 ||
289	    strcmp(*namep, cname) == 0)
290		return 0;
291	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
292		return 0;
293	/*
294	 * Don't attempt to canonicalize names that will be interpreted by
295	 * a proxy unless the user specifically requests so.
296	 */
297	if (!option_clear_or_none(options.proxy_command) &&
298	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
299		return 0;
300	debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
301	for (i = 0; i < options.num_permitted_cnames; i++) {
302		rule = options.permitted_cnames + i;
303		if (match_pattern_list(*namep, rule->source_list,
304		    strlen(rule->source_list), 1) != 1 ||
305		    match_pattern_list(cname, rule->target_list,
306		    strlen(rule->target_list), 1) != 1)
307			continue;
308		verbose("Canonicalized DNS aliased hostname "
309		    "\"%s\" => \"%s\"", *namep, cname);
310		free(*namep);
311		*namep = xstrdup(cname);
312		return 1;
313	}
314	return 0;
315}
316
317/*
318 * Attempt to resolve the supplied hostname after applying the user's
319 * canonicalization rules. Returns the address list for the host or NULL
320 * if no name was found after canonicalization.
321 * NB. this function must operate with a options having undefined members.
322 */
323static struct addrinfo *
324resolve_canonicalize(char **hostp, int port)
325{
326	int i, ndots;
327	char *cp, *fullhost, cname_target[NI_MAXHOST];
328	struct addrinfo *addrs;
329
330	if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
331		return NULL;
332
333	/*
334	 * Don't attempt to canonicalize names that will be interpreted by
335	 * a proxy unless the user specifically requests so.
336	 */
337	if (!option_clear_or_none(options.proxy_command) &&
338	    options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
339		return NULL;
340
341	/* Don't apply canonicalization to sufficiently-qualified hostnames */
342	ndots = 0;
343	for (cp = *hostp; *cp != '\0'; cp++) {
344		if (*cp == '.')
345			ndots++;
346	}
347	if (ndots > options.canonicalize_max_dots) {
348		debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
349		    __func__, *hostp, options.canonicalize_max_dots);
350		return NULL;
351	}
352	/* Attempt each supplied suffix */
353	for (i = 0; i < options.num_canonical_domains; i++) {
354		*cname_target = '\0';
355		xasprintf(&fullhost, "%s.%s.", *hostp,
356		    options.canonical_domains[i]);
357		debug3("%s: attempting \"%s\" => \"%s\"", __func__,
358		    *hostp, fullhost);
359		if ((addrs = resolve_host(fullhost, port, 0,
360		    cname_target, sizeof(cname_target))) == NULL) {
361			free(fullhost);
362			continue;
363		}
364		/* Remove trailing '.' */
365		fullhost[strlen(fullhost) - 1] = '\0';
366		/* Follow CNAME if requested */
367		if (!check_follow_cname(&fullhost, cname_target)) {
368			debug("Canonicalized hostname \"%s\" => \"%s\"",
369			    *hostp, fullhost);
370		}
371		free(*hostp);
372		*hostp = fullhost;
373		return addrs;
374	}
375	if (!options.canonicalize_fallback_local)
376		fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
377	debug2("%s: host %s not found in any suffix", __func__, *hostp);
378	return NULL;
379}
380
381/*
382 * Read per-user configuration file.  Ignore the system wide config
383 * file if the user specifies a config file on the command line.
384 */
385static void
386process_config_files(struct passwd *pw)
387{
388	char buf[MAXPATHLEN];
389	int r;
390
391	if (config != NULL) {
392		if (strcasecmp(config, "none") != 0 &&
393		    !read_config_file(config, pw, host, &options,
394		    SSHCONF_USERCONF))
395			fatal("Can't open user config file %.100s: "
396			    "%.100s", config, strerror(errno));
397	} else {
398		r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
399		    _PATH_SSH_USER_CONFFILE);
400		if (r > 0 && (size_t)r < sizeof(buf))
401			(void)read_config_file(buf, pw, host, &options,
402			     SSHCONF_CHECKPERM|SSHCONF_USERCONF);
403
404		/* Read systemwide configuration file after user config. */
405		(void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host,
406		    &options, 0);
407	}
408}
409
410/*
411 * Main program for the ssh client.
412 */
413int
414main(int ac, char **av)
415{
416	int i, r, opt, exit_status, use_syslog;
417	char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile;
418	char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
419	char cname[NI_MAXHOST];
420	struct stat st;
421	struct passwd *pw;
422	int timeout_ms;
423	extern int optind, optreset;
424	extern char *optarg;
425	Forward fwd;
426	struct addrinfo *addrs = NULL;
427
428	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
429	sanitise_stdfd();
430
431	__progname = ssh_get_progname(av[0]);
432
433#ifndef HAVE_SETPROCTITLE
434	/* Prepare for later setproctitle emulation */
435	/* Save argv so it isn't clobbered by setproctitle() emulation */
436	saved_av = xcalloc(ac + 1, sizeof(*saved_av));
437	for (i = 0; i < ac; i++)
438		saved_av[i] = xstrdup(av[i]);
439	saved_av[i] = NULL;
440	compat_init_setproctitle(ac, av);
441	av = saved_av;
442#endif
443
444	/*
445	 * Discard other fds that are hanging around. These can cause problem
446	 * with backgrounded ssh processes started by ControlPersist.
447	 */
448	closefrom(STDERR_FILENO + 1);
449
450	/*
451	 * Save the original real uid.  It will be needed later (uid-swapping
452	 * may clobber the real uid).
453	 */
454	original_real_uid = getuid();
455	original_effective_uid = geteuid();
456
457	/*
458	 * Use uid-swapping to give up root privileges for the duration of
459	 * option processing.  We will re-instantiate the rights when we are
460	 * ready to create the privileged port, and will permanently drop
461	 * them when the port has been created (actually, when the connection
462	 * has been made, as we may need to create the port several times).
463	 */
464	PRIV_END;
465
466#ifdef HAVE_SETRLIMIT
467	/* If we are installed setuid root be careful to not drop core. */
468	if (original_real_uid != original_effective_uid) {
469		struct rlimit rlim;
470		rlim.rlim_cur = rlim.rlim_max = 0;
471		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
472			fatal("setrlimit failed: %.100s", strerror(errno));
473	}
474#endif
475	/* Get user data. */
476	pw = getpwuid(original_real_uid);
477	if (!pw) {
478		logit("No user exists for uid %lu", (u_long)original_real_uid);
479		exit(255);
480	}
481	/* Take a copy of the returned structure. */
482	pw = pwcopy(pw);
483
484	/*
485	 * Set our umask to something reasonable, as some files are created
486	 * with the default umask.  This will make them world-readable but
487	 * writable only by the owner, which is ok for all files for which we
488	 * don't set the modes explicitly.
489	 */
490	umask(022);
491
492	/*
493	 * Initialize option structure to indicate that no values have been
494	 * set.
495	 */
496	initialize_options(&options);
497
498	/* Parse command-line arguments. */
499	host = NULL;
500	use_syslog = 0;
501	logfile = NULL;
502	argv0 = av[0];
503
504 again:
505	while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
506	    "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
507		switch (opt) {
508		case '1':
509			options.protocol = SSH_PROTO_1;
510			break;
511		case '2':
512			options.protocol = SSH_PROTO_2;
513			break;
514		case '4':
515			options.address_family = AF_INET;
516			break;
517		case '6':
518			options.address_family = AF_INET6;
519			break;
520		case 'n':
521			stdin_null_flag = 1;
522			break;
523		case 'f':
524			fork_after_authentication_flag = 1;
525			stdin_null_flag = 1;
526			break;
527		case 'x':
528			options.forward_x11 = 0;
529			break;
530		case 'X':
531			options.forward_x11 = 1;
532			break;
533		case 'y':
534			use_syslog = 1;
535			break;
536		case 'E':
537			logfile = xstrdup(optarg);
538			break;
539		case 'Y':
540			options.forward_x11 = 1;
541			options.forward_x11_trusted = 1;
542			break;
543		case 'g':
544			options.gateway_ports = 1;
545			break;
546		case 'O':
547			if (stdio_forward_host != NULL)
548				fatal("Cannot specify multiplexing "
549				    "command with -W");
550			else if (muxclient_command != 0)
551				fatal("Multiplexing command already specified");
552			if (strcmp(optarg, "check") == 0)
553				muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
554			else if (strcmp(optarg, "forward") == 0)
555				muxclient_command = SSHMUX_COMMAND_FORWARD;
556			else if (strcmp(optarg, "exit") == 0)
557				muxclient_command = SSHMUX_COMMAND_TERMINATE;
558			else if (strcmp(optarg, "stop") == 0)
559				muxclient_command = SSHMUX_COMMAND_STOP;
560			else if (strcmp(optarg, "cancel") == 0)
561				muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
562			else
563				fatal("Invalid multiplex command.");
564			break;
565		case 'P':	/* deprecated */
566			options.use_privileged_port = 0;
567			break;
568		case 'Q':
569			cp = NULL;
570			if (strcmp(optarg, "cipher") == 0)
571				cp = cipher_alg_list('\n', 0);
572			else if (strcmp(optarg, "cipher-auth") == 0)
573				cp = cipher_alg_list('\n', 1);
574			else if (strcmp(optarg, "mac") == 0)
575				cp = mac_alg_list('\n');
576			else if (strcmp(optarg, "kex") == 0)
577				cp = kex_alg_list('\n');
578			else if (strcmp(optarg, "key") == 0)
579				cp = key_alg_list(0, 0);
580			else if (strcmp(optarg, "key-cert") == 0)
581				cp = key_alg_list(1, 0);
582			else if (strcmp(optarg, "key-plain") == 0)
583				cp = key_alg_list(0, 1);
584			if (cp == NULL)
585				fatal("Unsupported query \"%s\"", optarg);
586			printf("%s\n", cp);
587			free(cp);
588			exit(0);
589			break;
590		case 'a':
591			options.forward_agent = 0;
592			break;
593		case 'A':
594			options.forward_agent = 1;
595			break;
596		case 'k':
597			options.gss_deleg_creds = 0;
598			break;
599		case 'K':
600			options.gss_authentication = 1;
601			options.gss_deleg_creds = 1;
602			break;
603		case 'i':
604			if (stat(optarg, &st) < 0) {
605				fprintf(stderr, "Warning: Identity file %s "
606				    "not accessible: %s.\n", optarg,
607				    strerror(errno));
608				break;
609			}
610			add_identity_file(&options, NULL, optarg, 1);
611			break;
612		case 'I':
613#ifdef ENABLE_PKCS11
614			options.pkcs11_provider = xstrdup(optarg);
615#else
616			fprintf(stderr, "no support for PKCS#11.\n");
617#endif
618			break;
619		case 't':
620			if (options.request_tty == REQUEST_TTY_YES)
621				options.request_tty = REQUEST_TTY_FORCE;
622			else
623				options.request_tty = REQUEST_TTY_YES;
624			break;
625		case 'v':
626			if (debug_flag == 0) {
627				debug_flag = 1;
628				options.log_level = SYSLOG_LEVEL_DEBUG1;
629			} else {
630				if (options.log_level < SYSLOG_LEVEL_DEBUG3)
631					options.log_level++;
632			}
633			break;
634		case 'V':
635			if (options.version_addendum &&
636			    *options.version_addendum != '\0')
637				fprintf(stderr, "%s%s %s, %s\n", SSH_RELEASE,
638				    options.hpn_disabled ? "" : SSH_VERSION_HPN,
639				    options.version_addendum,
640				    SSLeay_version(SSLEAY_VERSION));
641			else
642				fprintf(stderr, "%s%s, %s\n", SSH_RELEASE,
643				    options.hpn_disabled ? "" : SSH_VERSION_HPN,
644				    SSLeay_version(SSLEAY_VERSION));
645			if (opt == 'V')
646				exit(0);
647			break;
648		case 'w':
649			if (options.tun_open == -1)
650				options.tun_open = SSH_TUNMODE_DEFAULT;
651			options.tun_local = a2tun(optarg, &options.tun_remote);
652			if (options.tun_local == SSH_TUNID_ERR) {
653				fprintf(stderr,
654				    "Bad tun device '%s'\n", optarg);
655				exit(255);
656			}
657			break;
658		case 'W':
659			if (stdio_forward_host != NULL)
660				fatal("stdio forward already specified");
661			if (muxclient_command != 0)
662				fatal("Cannot specify stdio forward with -O");
663			if (parse_forward(&fwd, optarg, 1, 0)) {
664				stdio_forward_host = fwd.listen_host;
665				stdio_forward_port = fwd.listen_port;
666				free(fwd.connect_host);
667			} else {
668				fprintf(stderr,
669				    "Bad stdio forwarding specification '%s'\n",
670				    optarg);
671				exit(255);
672			}
673			options.request_tty = REQUEST_TTY_NO;
674			no_shell_flag = 1;
675			options.clear_forwardings = 1;
676			options.exit_on_forward_failure = 1;
677			break;
678		case 'q':
679			options.log_level = SYSLOG_LEVEL_QUIET;
680			break;
681		case 'e':
682			if (optarg[0] == '^' && optarg[2] == 0 &&
683			    (u_char) optarg[1] >= 64 &&
684			    (u_char) optarg[1] < 128)
685				options.escape_char = (u_char) optarg[1] & 31;
686			else if (strlen(optarg) == 1)
687				options.escape_char = (u_char) optarg[0];
688			else if (strcmp(optarg, "none") == 0)
689				options.escape_char = SSH_ESCAPECHAR_NONE;
690			else {
691				fprintf(stderr, "Bad escape character '%s'.\n",
692				    optarg);
693				exit(255);
694			}
695			break;
696		case 'c':
697			if (ciphers_valid(optarg)) {
698				/* SSH2 only */
699				options.ciphers = xstrdup(optarg);
700				options.cipher = SSH_CIPHER_INVALID;
701			} else {
702				/* SSH1 only */
703				options.cipher = cipher_number(optarg);
704				if (options.cipher == -1) {
705					fprintf(stderr,
706					    "Unknown cipher type '%s'\n",
707					    optarg);
708					exit(255);
709				}
710				if (options.cipher == SSH_CIPHER_3DES)
711					options.ciphers = "3des-cbc";
712				else if (options.cipher == SSH_CIPHER_BLOWFISH)
713					options.ciphers = "blowfish-cbc";
714				else
715					options.ciphers = (char *)-1;
716			}
717			break;
718		case 'm':
719			if (mac_valid(optarg))
720				options.macs = xstrdup(optarg);
721			else {
722				fprintf(stderr, "Unknown mac type '%s'\n",
723				    optarg);
724				exit(255);
725			}
726			break;
727		case 'M':
728			if (options.control_master == SSHCTL_MASTER_YES)
729				options.control_master = SSHCTL_MASTER_ASK;
730			else
731				options.control_master = SSHCTL_MASTER_YES;
732			break;
733		case 'p':
734			options.port = a2port(optarg);
735			if (options.port <= 0) {
736				fprintf(stderr, "Bad port '%s'\n", optarg);
737				exit(255);
738			}
739			break;
740		case 'l':
741			options.user = optarg;
742			break;
743
744		case 'L':
745			if (parse_forward(&fwd, optarg, 0, 0))
746				add_local_forward(&options, &fwd);
747			else {
748				fprintf(stderr,
749				    "Bad local forwarding specification '%s'\n",
750				    optarg);
751				exit(255);
752			}
753			break;
754
755		case 'R':
756			if (parse_forward(&fwd, optarg, 0, 1)) {
757				add_remote_forward(&options, &fwd);
758			} else {
759				fprintf(stderr,
760				    "Bad remote forwarding specification "
761				    "'%s'\n", optarg);
762				exit(255);
763			}
764			break;
765
766		case 'D':
767			if (parse_forward(&fwd, optarg, 1, 0)) {
768				add_local_forward(&options, &fwd);
769			} else {
770				fprintf(stderr,
771				    "Bad dynamic forwarding specification "
772				    "'%s'\n", optarg);
773				exit(255);
774			}
775			break;
776
777		case 'C':
778			options.compression = 1;
779			break;
780		case 'N':
781			no_shell_flag = 1;
782			options.request_tty = REQUEST_TTY_NO;
783			break;
784		case 'T':
785			options.request_tty = REQUEST_TTY_NO;
786#ifdef	NONE_CIPHER_ENABLED
787			/*
788			 * Ensure that the user does not try to backdoor a
789			 * NONE cipher switch on an interactive session by
790			 * explicitly disabling it if the user asks for a
791			 * session without a tty.
792			 */
793			options.none_switch = 0;
794#endif
795			break;
796		case 'o':
797			line = xstrdup(optarg);
798			if (process_config_line(&options, pw, host ? host : "",
799			    line, "command-line", 0, NULL, SSHCONF_USERCONF)
800			    != 0)
801				exit(255);
802			free(line);
803			break;
804		case 's':
805			subsystem_flag = 1;
806			break;
807		case 'S':
808			if (options.control_path != NULL)
809				free(options.control_path);
810			options.control_path = xstrdup(optarg);
811			break;
812		case 'b':
813			options.bind_address = optarg;
814			break;
815		case 'F':
816			config = optarg;
817			break;
818		default:
819			usage();
820		}
821	}
822
823	ac -= optind;
824	av += optind;
825
826	if (ac > 0 && !host) {
827		if (strrchr(*av, '@')) {
828			p = xstrdup(*av);
829			cp = strrchr(p, '@');
830			if (cp == NULL || cp == p)
831				usage();
832			options.user = p;
833			*cp = '\0';
834			host = xstrdup(++cp);
835		} else
836			host = xstrdup(*av);
837		if (ac > 1) {
838			optind = optreset = 1;
839			goto again;
840		}
841		ac--, av++;
842	}
843
844	/* Check that we got a host name. */
845	if (!host)
846		usage();
847
848	host_arg = xstrdup(host);
849
850	OpenSSL_add_all_algorithms();
851	ERR_load_crypto_strings();
852
853	/* Initialize the command to execute on remote host. */
854	buffer_init(&command);
855
856	/*
857	 * Save the command to execute on the remote host in a buffer. There
858	 * is no limit on the length of the command, except by the maximum
859	 * packet size.  Also sets the tty flag if there is no command.
860	 */
861	if (!ac) {
862		/* No command specified - execute shell on a tty. */
863		if (subsystem_flag) {
864			fprintf(stderr,
865			    "You must specify a subsystem to invoke.\n");
866			usage();
867		}
868	} else {
869		/* A command has been specified.  Store it into the buffer. */
870		for (i = 0; i < ac; i++) {
871			if (i)
872				buffer_append(&command, " ", 1);
873			buffer_append(&command, av[i], strlen(av[i]));
874		}
875	}
876
877	/* Cannot fork to background if no command. */
878	if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
879	    !no_shell_flag)
880		fatal("Cannot fork into background without a command "
881		    "to execute.");
882
883	/*
884	 * Initialize "log" output.  Since we are the client all output
885	 * goes to stderr unless otherwise specified by -y or -E.
886	 */
887	if (use_syslog && logfile != NULL)
888		fatal("Can't specify both -y and -E");
889	if (logfile != NULL) {
890		log_redirect_stderr_to(logfile);
891		free(logfile);
892	}
893	log_init(argv0,
894	    options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
895	    SYSLOG_FACILITY_USER, !use_syslog);
896
897	if (debug_flag)
898		logit("%s, %s", SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
899
900	/* Parse the configuration files */
901	process_config_files(pw);
902
903	/* Hostname canonicalisation needs a few options filled. */
904	fill_default_options_for_canonicalization(&options);
905
906	/* If the user has replaced the hostname then take it into use now */
907	if (options.hostname != NULL) {
908		/* NB. Please keep in sync with readconf.c:match_cfg_line() */
909		cp = percent_expand(options.hostname,
910		    "h", host, (char *)NULL);
911		free(host);
912		host = cp;
913	}
914
915	/* If canonicalization requested then try to apply it */
916	lowercase(host);
917	if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
918		addrs = resolve_canonicalize(&host, options.port);
919
920	/*
921	 * If CanonicalizePermittedCNAMEs have been specified but
922	 * other canonicalization did not happen (by not being requested
923	 * or by failing with fallback) then the hostname may still be changed
924	 * as a result of CNAME following.
925	 *
926	 * Try to resolve the bare hostname name using the system resolver's
927	 * usual search rules and then apply the CNAME follow rules.
928	 *
929	 * Skip the lookup if a ProxyCommand is being used unless the user
930	 * has specifically requested canonicalisation for this case via
931	 * CanonicalizeHostname=always
932	 */
933	if (addrs == NULL && options.num_permitted_cnames != 0 &&
934	    (option_clear_or_none(options.proxy_command) ||
935            options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
936		if ((addrs = resolve_host(host, options.port, 1,
937		    cname, sizeof(cname))) == NULL)
938			cleanup_exit(255); /* resolve_host logs the error */
939		check_follow_cname(&host, cname);
940	}
941
942	/*
943	 * If the target hostname has changed as a result of canonicalisation
944	 * then re-parse the configuration files as new stanzas may match.
945	 */
946	if (strcasecmp(host_arg, host) != 0) {
947		debug("Hostname has changed; re-reading configuration");
948		process_config_files(pw);
949	}
950
951	/* Fill configuration defaults. */
952	fill_default_options(&options);
953
954	if (options.port == 0)
955		options.port = default_ssh_port();
956	channel_set_af(options.address_family);
957
958	/* Tidy and check options */
959	if (options.host_key_alias != NULL)
960		lowercase(options.host_key_alias);
961	if (options.proxy_command != NULL &&
962	    strcmp(options.proxy_command, "-") == 0 &&
963	    options.proxy_use_fdpass)
964		fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
965#ifndef HAVE_CYGWIN
966	if (original_effective_uid != 0)
967		options.use_privileged_port = 0;
968#endif
969
970	/* reinit */
971	log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
972
973	if (options.request_tty == REQUEST_TTY_YES ||
974	    options.request_tty == REQUEST_TTY_FORCE)
975		tty_flag = 1;
976
977	/* Allocate a tty by default if no command specified. */
978	if (buffer_len(&command) == 0)
979		tty_flag = options.request_tty != REQUEST_TTY_NO;
980
981	/* Force no tty */
982	if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
983		tty_flag = 0;
984	/* Do not allocate a tty if stdin is not a tty. */
985	if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
986	    options.request_tty != REQUEST_TTY_FORCE) {
987		if (tty_flag)
988			logit("Pseudo-terminal will not be allocated because "
989			    "stdin is not a terminal.");
990		tty_flag = 0;
991	}
992
993	seed_rng();
994
995	if (options.user == NULL)
996		options.user = xstrdup(pw->pw_name);
997
998	if (gethostname(thishost, sizeof(thishost)) == -1)
999		fatal("gethostname: %s", strerror(errno));
1000	strlcpy(shorthost, thishost, sizeof(shorthost));
1001	shorthost[strcspn(thishost, ".")] = '\0';
1002	snprintf(portstr, sizeof(portstr), "%d", options.port);
1003
1004	if (options.local_command != NULL) {
1005		debug3("expanding LocalCommand: %s", options.local_command);
1006		cp = options.local_command;
1007		options.local_command = percent_expand(cp, "d", pw->pw_dir,
1008		    "h", host, "l", thishost, "n", host_arg, "r", options.user,
1009		    "p", portstr, "u", pw->pw_name, "L", shorthost,
1010		    (char *)NULL);
1011		debug3("expanded LocalCommand: %s", options.local_command);
1012		free(cp);
1013	}
1014
1015	if (options.control_path != NULL) {
1016		cp = tilde_expand_filename(options.control_path,
1017		    original_real_uid);
1018		free(options.control_path);
1019		options.control_path = percent_expand(cp, "h", host,
1020		    "l", thishost, "n", host_arg, "r", options.user,
1021		    "p", portstr, "u", pw->pw_name, "L", shorthost,
1022		    (char *)NULL);
1023		free(cp);
1024	}
1025	if (muxclient_command != 0 && options.control_path == NULL)
1026		fatal("No ControlPath specified for \"-O\" command");
1027	if (options.control_path != NULL)
1028		muxclient(options.control_path);
1029
1030	/*
1031	 * If hostname canonicalisation was not enabled, then we may not
1032	 * have yet resolved the hostname. Do so now.
1033	 */
1034	if (addrs == NULL && options.proxy_command == NULL) {
1035		if ((addrs = resolve_host(host, options.port, 1,
1036		    cname, sizeof(cname))) == NULL)
1037			cleanup_exit(255); /* resolve_host logs the error */
1038	}
1039
1040	timeout_ms = options.connection_timeout * 1000;
1041
1042	/* Open a connection to the remote host. */
1043	if (ssh_connect(host, addrs, &hostaddr, options.port,
1044	    options.address_family, options.connection_attempts,
1045	    &timeout_ms, options.tcp_keep_alive,
1046	    options.use_privileged_port) != 0)
1047 		exit(255);
1048
1049	if (addrs != NULL)
1050		freeaddrinfo(addrs);
1051
1052	packet_set_timeout(options.server_alive_interval,
1053	    options.server_alive_count_max);
1054
1055	if (timeout_ms > 0)
1056		debug3("timeout: %d ms remain after connect", timeout_ms);
1057
1058	/*
1059	 * If we successfully made the connection, load the host private key
1060	 * in case we will need it later for combined rsa-rhosts
1061	 * authentication. This must be done before releasing extra
1062	 * privileges, because the file is only readable by root.
1063	 * If we cannot access the private keys, load the public keys
1064	 * instead and try to execute the ssh-keysign helper instead.
1065	 */
1066	sensitive_data.nkeys = 0;
1067	sensitive_data.keys = NULL;
1068	sensitive_data.external_keysign = 0;
1069	if (options.rhosts_rsa_authentication ||
1070	    options.hostbased_authentication) {
1071		sensitive_data.nkeys = 9;
1072		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1073		    sizeof(Key));
1074		for (i = 0; i < sensitive_data.nkeys; i++)
1075			sensitive_data.keys[i] = NULL;
1076
1077		PRIV_START;
1078		sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1079		    _PATH_HOST_KEY_FILE, "", NULL, NULL);
1080		sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
1081		    _PATH_HOST_DSA_KEY_FILE, "", NULL);
1082#ifdef OPENSSL_HAS_ECC
1083		sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
1084		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1085#endif
1086		sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1087		    _PATH_HOST_RSA_KEY_FILE, "", NULL);
1088		sensitive_data.keys[4] = key_load_private_cert(KEY_ED25519,
1089		    _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1090		sensitive_data.keys[5] = key_load_private_type(KEY_DSA,
1091		    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1092#ifdef OPENSSL_HAS_ECC
1093		sensitive_data.keys[6] = key_load_private_type(KEY_ECDSA,
1094		    _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1095#endif
1096		sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1097		    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1098		sensitive_data.keys[8] = key_load_private_type(KEY_ED25519,
1099		    _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1100		PRIV_END;
1101
1102		if (options.hostbased_authentication == 1 &&
1103		    sensitive_data.keys[0] == NULL &&
1104		    sensitive_data.keys[5] == NULL &&
1105		    sensitive_data.keys[6] == NULL &&
1106		    sensitive_data.keys[7] == NULL &&
1107		    sensitive_data.keys[8] == NULL) {
1108			sensitive_data.keys[1] = key_load_cert(
1109			    _PATH_HOST_DSA_KEY_FILE);
1110#ifdef OPENSSL_HAS_ECC
1111			sensitive_data.keys[2] = key_load_cert(
1112			    _PATH_HOST_ECDSA_KEY_FILE);
1113#endif
1114			sensitive_data.keys[3] = key_load_cert(
1115			    _PATH_HOST_RSA_KEY_FILE);
1116			sensitive_data.keys[4] = key_load_cert(
1117			    _PATH_HOST_ED25519_KEY_FILE);
1118			sensitive_data.keys[5] = key_load_public(
1119			    _PATH_HOST_DSA_KEY_FILE, NULL);
1120#ifdef OPENSSL_HAS_ECC
1121			sensitive_data.keys[6] = key_load_public(
1122			    _PATH_HOST_ECDSA_KEY_FILE, NULL);
1123#endif
1124			sensitive_data.keys[7] = key_load_public(
1125			    _PATH_HOST_RSA_KEY_FILE, NULL);
1126			sensitive_data.keys[8] = key_load_public(
1127			    _PATH_HOST_ED25519_KEY_FILE, NULL);
1128			sensitive_data.external_keysign = 1;
1129		}
1130	}
1131	/*
1132	 * Get rid of any extra privileges that we may have.  We will no
1133	 * longer need them.  Also, extra privileges could make it very hard
1134	 * to read identity files and other non-world-readable files from the
1135	 * user's home directory if it happens to be on a NFS volume where
1136	 * root is mapped to nobody.
1137	 */
1138	if (original_effective_uid == 0) {
1139		PRIV_START;
1140		permanently_set_uid(pw);
1141	}
1142
1143	/*
1144	 * Now that we are back to our own permissions, create ~/.ssh
1145	 * directory if it doesn't already exist.
1146	 */
1147	if (config == NULL) {
1148		r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1149		    strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1150		if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1151#ifdef WITH_SELINUX
1152			ssh_selinux_setfscreatecon(buf);
1153#endif
1154			if (mkdir(buf, 0700) < 0)
1155				error("Could not create directory '%.200s'.",
1156				    buf);
1157#ifdef WITH_SELINUX
1158			ssh_selinux_setfscreatecon(NULL);
1159#endif
1160		}
1161	}
1162	/* load options.identity_files */
1163	load_public_identity_files();
1164
1165	/* Expand ~ in known host file names. */
1166	tilde_expand_paths(options.system_hostfiles,
1167	    options.num_system_hostfiles);
1168	tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1169
1170	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1171	signal(SIGCHLD, main_sigchld_handler);
1172
1173	/* Log into the remote system.  Never returns if the login fails. */
1174	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1175	    options.port, pw, timeout_ms);
1176
1177	if (packet_connection_is_on_socket()) {
1178		verbose("Authenticated to %s ([%s]:%d).", host,
1179		    get_remote_ipaddr(), get_remote_port());
1180	} else {
1181		verbose("Authenticated to %s (via proxy).", host);
1182	}
1183
1184	/* We no longer need the private host keys.  Clear them now. */
1185	if (sensitive_data.nkeys != 0) {
1186		for (i = 0; i < sensitive_data.nkeys; i++) {
1187			if (sensitive_data.keys[i] != NULL) {
1188				/* Destroys contents safely */
1189				debug3("clear hostkey %d", i);
1190				key_free(sensitive_data.keys[i]);
1191				sensitive_data.keys[i] = NULL;
1192			}
1193		}
1194		free(sensitive_data.keys);
1195	}
1196	for (i = 0; i < options.num_identity_files; i++) {
1197		free(options.identity_files[i]);
1198		options.identity_files[i] = NULL;
1199		if (options.identity_keys[i]) {
1200			key_free(options.identity_keys[i]);
1201			options.identity_keys[i] = NULL;
1202		}
1203	}
1204
1205	exit_status = compat20 ? ssh_session2() : ssh_session();
1206	packet_close();
1207
1208	if (options.control_path != NULL && muxserver_sock != -1)
1209		unlink(options.control_path);
1210
1211	/* Kill ProxyCommand if it is running. */
1212	ssh_kill_proxy_command();
1213
1214	return exit_status;
1215}
1216
1217static void
1218control_persist_detach(void)
1219{
1220	pid_t pid;
1221	int devnull;
1222
1223	debug("%s: backgrounding master process", __func__);
1224
1225 	/*
1226 	 * master (current process) into the background, and make the
1227 	 * foreground process a client of the backgrounded master.
1228 	 */
1229	switch ((pid = fork())) {
1230	case -1:
1231		fatal("%s: fork: %s", __func__, strerror(errno));
1232	case 0:
1233		/* Child: master process continues mainloop */
1234 		break;
1235 	default:
1236		/* Parent: set up mux slave to connect to backgrounded master */
1237		debug2("%s: background process is %ld", __func__, (long)pid);
1238		stdin_null_flag = ostdin_null_flag;
1239		options.request_tty = orequest_tty;
1240		tty_flag = otty_flag;
1241 		close(muxserver_sock);
1242 		muxserver_sock = -1;
1243		options.control_master = SSHCTL_MASTER_NO;
1244 		muxclient(options.control_path);
1245		/* muxclient() doesn't return on success. */
1246 		fatal("Failed to connect to new control master");
1247 	}
1248	if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1249		error("%s: open(\"/dev/null\"): %s", __func__,
1250		    strerror(errno));
1251	} else {
1252		if (dup2(devnull, STDIN_FILENO) == -1 ||
1253		    dup2(devnull, STDOUT_FILENO) == -1)
1254			error("%s: dup2: %s", __func__, strerror(errno));
1255		if (devnull > STDERR_FILENO)
1256			close(devnull);
1257	}
1258	daemon(1, 1);
1259	setproctitle("%s [mux]", options.control_path);
1260}
1261
1262/* Do fork() after authentication. Used by "ssh -f" */
1263static void
1264fork_postauth(void)
1265{
1266	if (need_controlpersist_detach)
1267		control_persist_detach();
1268	debug("forking to background");
1269	fork_after_authentication_flag = 0;
1270	if (daemon(1, 1) < 0)
1271		fatal("daemon() failed: %.200s", strerror(errno));
1272}
1273
1274/* Callback for remote forward global requests */
1275static void
1276ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1277{
1278	Forward *rfwd = (Forward *)ctxt;
1279
1280	/* XXX verbose() on failure? */
1281	debug("remote forward %s for: listen %d, connect %s:%d",
1282	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1283	    rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1284	if (rfwd->listen_port == 0) {
1285		if (type == SSH2_MSG_REQUEST_SUCCESS) {
1286			rfwd->allocated_port = packet_get_int();
1287			logit("Allocated port %u for remote forward to %s:%d",
1288			    rfwd->allocated_port,
1289			    rfwd->connect_host, rfwd->connect_port);
1290			channel_update_permitted_opens(rfwd->handle,
1291			    rfwd->allocated_port);
1292		} else {
1293			channel_update_permitted_opens(rfwd->handle, -1);
1294		}
1295	}
1296
1297	if (type == SSH2_MSG_REQUEST_FAILURE) {
1298		if (options.exit_on_forward_failure)
1299			fatal("Error: remote port forwarding failed for "
1300			    "listen port %d", rfwd->listen_port);
1301		else
1302			logit("Warning: remote port forwarding failed for "
1303			    "listen port %d", rfwd->listen_port);
1304	}
1305	if (++remote_forward_confirms_received == options.num_remote_forwards) {
1306		debug("All remote forwarding requests processed");
1307		if (fork_after_authentication_flag)
1308			fork_postauth();
1309	}
1310}
1311
1312static void
1313client_cleanup_stdio_fwd(int id, void *arg)
1314{
1315	debug("stdio forwarding: done");
1316	cleanup_exit(0);
1317}
1318
1319static void
1320ssh_init_stdio_forwarding(void)
1321{
1322	Channel *c;
1323	int in, out;
1324
1325	if (stdio_forward_host == NULL)
1326		return;
1327	if (!compat20)
1328		fatal("stdio forwarding require Protocol 2");
1329
1330	debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1331
1332	if ((in = dup(STDIN_FILENO)) < 0 ||
1333	    (out = dup(STDOUT_FILENO)) < 0)
1334		fatal("channel_connect_stdio_fwd: dup() in/out failed");
1335	if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1336	    stdio_forward_port, in, out)) == NULL)
1337		fatal("%s: channel_connect_stdio_fwd failed", __func__);
1338	channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1339}
1340
1341static void
1342ssh_init_forwarding(void)
1343{
1344	int success = 0;
1345	int i;
1346
1347	/* Initiate local TCP/IP port forwardings. */
1348	for (i = 0; i < options.num_local_forwards; i++) {
1349		debug("Local connections to %.200s:%d forwarded to remote "
1350		    "address %.200s:%d",
1351		    (options.local_forwards[i].listen_host == NULL) ?
1352		    (options.gateway_ports ? "*" : "LOCALHOST") :
1353		    options.local_forwards[i].listen_host,
1354		    options.local_forwards[i].listen_port,
1355		    options.local_forwards[i].connect_host,
1356		    options.local_forwards[i].connect_port);
1357		success += channel_setup_local_fwd_listener(
1358		    options.local_forwards[i].listen_host,
1359		    options.local_forwards[i].listen_port,
1360		    options.local_forwards[i].connect_host,
1361		    options.local_forwards[i].connect_port,
1362		    options.gateway_ports);
1363	}
1364	if (i > 0 && success != i && options.exit_on_forward_failure)
1365		fatal("Could not request local forwarding.");
1366	if (i > 0 && success == 0)
1367		error("Could not request local forwarding.");
1368
1369	/* Initiate remote TCP/IP port forwardings. */
1370	for (i = 0; i < options.num_remote_forwards; i++) {
1371		debug("Remote connections from %.200s:%d forwarded to "
1372		    "local address %.200s:%d",
1373		    (options.remote_forwards[i].listen_host == NULL) ?
1374		    "LOCALHOST" : options.remote_forwards[i].listen_host,
1375		    options.remote_forwards[i].listen_port,
1376		    options.remote_forwards[i].connect_host,
1377		    options.remote_forwards[i].connect_port);
1378		options.remote_forwards[i].handle =
1379		    channel_request_remote_forwarding(
1380		    options.remote_forwards[i].listen_host,
1381		    options.remote_forwards[i].listen_port,
1382		    options.remote_forwards[i].connect_host,
1383		    options.remote_forwards[i].connect_port);
1384		if (options.remote_forwards[i].handle < 0) {
1385			if (options.exit_on_forward_failure)
1386				fatal("Could not request remote forwarding.");
1387			else
1388				logit("Warning: Could not request remote "
1389				    "forwarding.");
1390		} else {
1391			client_register_global_confirm(ssh_confirm_remote_forward,
1392			    &options.remote_forwards[i]);
1393		}
1394	}
1395
1396	/* Initiate tunnel forwarding. */
1397	if (options.tun_open != SSH_TUNMODE_NO) {
1398		if (client_request_tun_fwd(options.tun_open,
1399		    options.tun_local, options.tun_remote) == -1) {
1400			if (options.exit_on_forward_failure)
1401				fatal("Could not request tunnel forwarding.");
1402			else
1403				error("Could not request tunnel forwarding.");
1404		}
1405	}
1406}
1407
1408static void
1409check_agent_present(void)
1410{
1411	if (options.forward_agent) {
1412		/* Clear agent forwarding if we don't have an agent. */
1413		if (!ssh_agent_present())
1414			options.forward_agent = 0;
1415	}
1416}
1417
1418static int
1419ssh_session(void)
1420{
1421	int type;
1422	int interactive = 0;
1423	int have_tty = 0;
1424	struct winsize ws;
1425	char *cp;
1426	const char *display;
1427
1428	/* Enable compression if requested. */
1429	if (options.compression) {
1430		debug("Requesting compression at level %d.",
1431		    options.compression_level);
1432
1433		if (options.compression_level < 1 ||
1434		    options.compression_level > 9)
1435			fatal("Compression level must be from 1 (fast) to "
1436			    "9 (slow, best).");
1437
1438		/* Send the request. */
1439		packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1440		packet_put_int(options.compression_level);
1441		packet_send();
1442		packet_write_wait();
1443		type = packet_read();
1444		if (type == SSH_SMSG_SUCCESS)
1445			packet_start_compression(options.compression_level);
1446		else if (type == SSH_SMSG_FAILURE)
1447			logit("Warning: Remote host refused compression.");
1448		else
1449			packet_disconnect("Protocol error waiting for "
1450			    "compression response.");
1451	}
1452	/* Allocate a pseudo tty if appropriate. */
1453	if (tty_flag) {
1454		debug("Requesting pty.");
1455
1456		/* Start the packet. */
1457		packet_start(SSH_CMSG_REQUEST_PTY);
1458
1459		/* Store TERM in the packet.  There is no limit on the
1460		   length of the string. */
1461		cp = getenv("TERM");
1462		if (!cp)
1463			cp = "";
1464		packet_put_cstring(cp);
1465
1466		/* Store window size in the packet. */
1467		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1468			memset(&ws, 0, sizeof(ws));
1469		packet_put_int((u_int)ws.ws_row);
1470		packet_put_int((u_int)ws.ws_col);
1471		packet_put_int((u_int)ws.ws_xpixel);
1472		packet_put_int((u_int)ws.ws_ypixel);
1473
1474		/* Store tty modes in the packet. */
1475		tty_make_modes(fileno(stdin), NULL);
1476
1477		/* Send the packet, and wait for it to leave. */
1478		packet_send();
1479		packet_write_wait();
1480
1481		/* Read response from the server. */
1482		type = packet_read();
1483		if (type == SSH_SMSG_SUCCESS) {
1484			interactive = 1;
1485			have_tty = 1;
1486		} else if (type == SSH_SMSG_FAILURE)
1487			logit("Warning: Remote host failed or refused to "
1488			    "allocate a pseudo tty.");
1489		else
1490			packet_disconnect("Protocol error waiting for pty "
1491			    "request response.");
1492	}
1493	/* Request X11 forwarding if enabled and DISPLAY is set. */
1494	display = getenv("DISPLAY");
1495	if (options.forward_x11 && display != NULL) {
1496		char *proto, *data;
1497		/* Get reasonable local authentication information. */
1498		client_x11_get_proto(display, options.xauth_location,
1499		    options.forward_x11_trusted,
1500		    options.forward_x11_timeout,
1501		    &proto, &data);
1502		/* Request forwarding with authentication spoofing. */
1503		debug("Requesting X11 forwarding with authentication "
1504		    "spoofing.");
1505		x11_request_forwarding_with_spoofing(0, display, proto,
1506		    data, 0);
1507		/* Read response from the server. */
1508		type = packet_read();
1509		if (type == SSH_SMSG_SUCCESS) {
1510			interactive = 1;
1511		} else if (type == SSH_SMSG_FAILURE) {
1512			logit("Warning: Remote host denied X11 forwarding.");
1513		} else {
1514			packet_disconnect("Protocol error waiting for X11 "
1515			    "forwarding");
1516		}
1517	}
1518	/* Tell the packet module whether this is an interactive session. */
1519	packet_set_interactive(interactive,
1520	    options.ip_qos_interactive, options.ip_qos_bulk);
1521
1522	/* Request authentication agent forwarding if appropriate. */
1523	check_agent_present();
1524
1525	if (options.forward_agent) {
1526		debug("Requesting authentication agent forwarding.");
1527		auth_request_forwarding();
1528
1529		/* Read response from the server. */
1530		type = packet_read();
1531		packet_check_eom();
1532		if (type != SSH_SMSG_SUCCESS)
1533			logit("Warning: Remote host denied authentication agent forwarding.");
1534	}
1535
1536	/* Initiate port forwardings. */
1537	ssh_init_stdio_forwarding();
1538	ssh_init_forwarding();
1539
1540	/* Execute a local command */
1541	if (options.local_command != NULL &&
1542	    options.permit_local_command)
1543		ssh_local_cmd(options.local_command);
1544
1545	/*
1546	 * If requested and we are not interested in replies to remote
1547	 * forwarding requests, then let ssh continue in the background.
1548	 */
1549	if (fork_after_authentication_flag) {
1550		if (options.exit_on_forward_failure &&
1551		    options.num_remote_forwards > 0) {
1552			debug("deferring postauth fork until remote forward "
1553			    "confirmation received");
1554		} else
1555			fork_postauth();
1556	}
1557
1558	/*
1559	 * If a command was specified on the command line, execute the
1560	 * command now. Otherwise request the server to start a shell.
1561	 */
1562	if (buffer_len(&command) > 0) {
1563		int len = buffer_len(&command);
1564		if (len > 900)
1565			len = 900;
1566		debug("Sending command: %.*s", len,
1567		    (u_char *)buffer_ptr(&command));
1568		packet_start(SSH_CMSG_EXEC_CMD);
1569		packet_put_string(buffer_ptr(&command), buffer_len(&command));
1570		packet_send();
1571		packet_write_wait();
1572	} else {
1573		debug("Requesting shell.");
1574		packet_start(SSH_CMSG_EXEC_SHELL);
1575		packet_send();
1576		packet_write_wait();
1577	}
1578
1579	/* Enter the interactive session. */
1580	return client_loop(have_tty, tty_flag ?
1581	    options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1582}
1583
1584/* request pty/x11/agent/tcpfwd/shell for channel */
1585static void
1586ssh_session2_setup(int id, int success, void *arg)
1587{
1588	extern char **environ;
1589	const char *display;
1590	int interactive = tty_flag;
1591
1592	if (!success)
1593		return; /* No need for error message, channels code sens one */
1594
1595	display = getenv("DISPLAY");
1596	if (options.forward_x11 && display != NULL) {
1597		char *proto, *data;
1598		/* Get reasonable local authentication information. */
1599		client_x11_get_proto(display, options.xauth_location,
1600		    options.forward_x11_trusted,
1601		    options.forward_x11_timeout, &proto, &data);
1602		/* Request forwarding with authentication spoofing. */
1603		debug("Requesting X11 forwarding with authentication "
1604		    "spoofing.");
1605		x11_request_forwarding_with_spoofing(id, display, proto,
1606		    data, 1);
1607		client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1608		/* XXX exit_on_forward_failure */
1609		interactive = 1;
1610	}
1611
1612	check_agent_present();
1613	if (options.forward_agent) {
1614		debug("Requesting authentication agent forwarding.");
1615		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1616		packet_send();
1617	}
1618
1619	/* Tell the packet module whether this is an interactive session. */
1620	packet_set_interactive(interactive,
1621	    options.ip_qos_interactive, options.ip_qos_bulk);
1622
1623	client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1624	    NULL, fileno(stdin), &command, environ);
1625}
1626
1627/* open new channel for a session */
1628static int
1629ssh_session2_open(void)
1630{
1631	Channel *c;
1632	int window, packetmax, in, out, err;
1633
1634	if (stdin_null_flag) {
1635		in = open(_PATH_DEVNULL, O_RDONLY);
1636	} else {
1637		in = dup(STDIN_FILENO);
1638	}
1639	out = dup(STDOUT_FILENO);
1640	err = dup(STDERR_FILENO);
1641
1642	if (in < 0 || out < 0 || err < 0)
1643		fatal("dup() in/out/err failed");
1644
1645	/* enable nonblocking unless tty */
1646	if (!isatty(in))
1647		set_nonblock(in);
1648	if (!isatty(out))
1649		set_nonblock(out);
1650	if (!isatty(err))
1651		set_nonblock(err);
1652
1653	/*
1654	 * We need to check to see what to do about buffer sizes here.
1655	 * - In an HPN to non-HPN connection we want to limit the window size to
1656	 *   something reasonable in case the far side has the large window bug.
1657	 * - In an HPN to HPN connection we want to use the max window size but
1658	 *   allow the user to override it.
1659	 * - Lastly if HPN is disabled then use the ssh standard window size.
1660	 *
1661	 * We cannot just do a getsockopt() here and set the ssh window to that
1662	 * as in case of autotuning of socket buffers the window would get stuck
1663	 * at the initial buffer size, generally less than 96k.  Therefore we
1664	 * need to set the maximum ssh window size to the maximum HPN buffer
1665	 * size unless the user has set TcpRcvBufPoll to no.  In that case we
1666	 * can just set the window to the minimum of HPN buffer size and TCP
1667	 * receive buffer size.
1668	 */
1669	if (tty_flag)
1670		options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1671	else
1672		options.hpn_buffer_size = CHAN_HPN_MIN_WINDOW_DEFAULT;
1673
1674	if (datafellows & SSH_BUG_LARGEWINDOW) {
1675		debug("HPN to Non-HPN Connection");
1676	} else if (options.tcp_rcv_buf_poll <= 0) {
1677		sock_get_rcvbuf(&options.hpn_buffer_size, 0);
1678		debug("HPNBufferSize set to TCP RWIN: %d",
1679		    options.hpn_buffer_size);
1680	} else if (options.tcp_rcv_buf > 0) {
1681		sock_get_rcvbuf(&options.hpn_buffer_size,
1682		    options.tcp_rcv_buf);
1683		debug("HPNBufferSize set to user TCPRcvBuf: %d",
1684		    options.hpn_buffer_size);
1685	}
1686	debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1687	channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1688	window = options.hpn_buffer_size;
1689
1690	packetmax = CHAN_SES_PACKET_DEFAULT;
1691	if (tty_flag) {
1692		window = CHAN_SES_WINDOW_DEFAULT;
1693		window >>= 1;
1694		packetmax >>= 1;
1695	}
1696	c = channel_new(
1697	    "session", SSH_CHANNEL_OPENING, in, out, err,
1698	    window, packetmax, CHAN_EXTENDED_WRITE,
1699	    "client-session", /*nonblock*/0);
1700	if (!options.hpn_disabled && options.tcp_rcv_buf_poll > 0) {
1701		c->dynamic_window = 1;
1702		debug("Enabled Dynamic Window Scaling\n");
1703	}
1704
1705	debug3("ssh_session2_open: channel_new: %d", c->self);
1706
1707	channel_send_open(c->self);
1708	if (!no_shell_flag)
1709		channel_register_open_confirm(c->self,
1710		    ssh_session2_setup, NULL);
1711
1712	return c->self;
1713}
1714
1715static int
1716ssh_session2(void)
1717{
1718	int id = -1;
1719
1720	/* XXX should be pre-session */
1721	if (!options.control_persist)
1722		ssh_init_stdio_forwarding();
1723	ssh_init_forwarding();
1724
1725	/* Start listening for multiplex clients */
1726	muxserver_listen();
1727
1728 	/*
1729	 * If we are in control persist mode and have a working mux listen
1730	 * socket, then prepare to background ourselves and have a foreground
1731	 * client attach as a control slave.
1732	 * NB. we must save copies of the flags that we override for
1733	 * the backgrounding, since we defer attachment of the slave until
1734	 * after the connection is fully established (in particular,
1735	 * async rfwd replies have been received for ExitOnForwardFailure).
1736	 */
1737 	if (options.control_persist && muxserver_sock != -1) {
1738		ostdin_null_flag = stdin_null_flag;
1739		ono_shell_flag = no_shell_flag;
1740		orequest_tty = options.request_tty;
1741		otty_flag = tty_flag;
1742 		stdin_null_flag = 1;
1743 		no_shell_flag = 1;
1744 		tty_flag = 0;
1745		if (!fork_after_authentication_flag)
1746			need_controlpersist_detach = 1;
1747		fork_after_authentication_flag = 1;
1748 	}
1749	/*
1750	 * ControlPersist mux listen socket setup failed, attempt the
1751	 * stdio forward setup that we skipped earlier.
1752	 */
1753	if (options.control_persist && muxserver_sock == -1)
1754		ssh_init_stdio_forwarding();
1755
1756	if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1757		id = ssh_session2_open();
1758	else {
1759		packet_set_interactive(
1760		    options.control_master == SSHCTL_MASTER_NO,
1761		    options.ip_qos_interactive, options.ip_qos_bulk);
1762	}
1763
1764	/* If we don't expect to open a new session, then disallow it */
1765	if (options.control_master == SSHCTL_MASTER_NO &&
1766	    (datafellows & SSH_NEW_OPENSSH)) {
1767		debug("Requesting no-more-sessions@openssh.com");
1768		packet_start(SSH2_MSG_GLOBAL_REQUEST);
1769		packet_put_cstring("no-more-sessions@openssh.com");
1770		packet_put_char(0);
1771		packet_send();
1772	}
1773
1774	/* Execute a local command */
1775	if (options.local_command != NULL &&
1776	    options.permit_local_command)
1777		ssh_local_cmd(options.local_command);
1778
1779	/*
1780	 * If requested and we are not interested in replies to remote
1781	 * forwarding requests, then let ssh continue in the background.
1782	 */
1783	if (fork_after_authentication_flag) {
1784		if (options.exit_on_forward_failure &&
1785		    options.num_remote_forwards > 0) {
1786			debug("deferring postauth fork until remote forward "
1787			    "confirmation received");
1788		} else
1789			fork_postauth();
1790	}
1791
1792	if (options.use_roaming)
1793		request_roaming();
1794
1795	return client_loop(tty_flag, tty_flag ?
1796	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
1797}
1798
1799static void
1800load_public_identity_files(void)
1801{
1802	char *filename, *cp, thishost[NI_MAXHOST];
1803	char *pwdir = NULL, *pwname = NULL;
1804	int i = 0;
1805	Key *public;
1806	struct passwd *pw;
1807	u_int n_ids;
1808	char *identity_files[SSH_MAX_IDENTITY_FILES];
1809	Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1810#ifdef ENABLE_PKCS11
1811	Key **keys;
1812	int nkeys;
1813#endif /* PKCS11 */
1814
1815	n_ids = 0;
1816	memset(identity_files, 0, sizeof(identity_files));
1817	memset(identity_keys, 0, sizeof(identity_keys));
1818
1819#ifdef ENABLE_PKCS11
1820	if (options.pkcs11_provider != NULL &&
1821	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1822	    (pkcs11_init(!options.batch_mode) == 0) &&
1823	    (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1824	    &keys)) > 0) {
1825		for (i = 0; i < nkeys; i++) {
1826			if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1827				key_free(keys[i]);
1828				continue;
1829			}
1830			identity_keys[n_ids] = keys[i];
1831			identity_files[n_ids] =
1832			    xstrdup(options.pkcs11_provider); /* XXX */
1833			n_ids++;
1834		}
1835		free(keys);
1836	}
1837#endif /* ENABLE_PKCS11 */
1838	if ((pw = getpwuid(original_real_uid)) == NULL)
1839		fatal("load_public_identity_files: getpwuid failed");
1840	pwname = xstrdup(pw->pw_name);
1841	pwdir = xstrdup(pw->pw_dir);
1842	if (gethostname(thishost, sizeof(thishost)) == -1)
1843		fatal("load_public_identity_files: gethostname: %s",
1844		    strerror(errno));
1845	for (i = 0; i < options.num_identity_files; i++) {
1846		if (n_ids >= SSH_MAX_IDENTITY_FILES ||
1847		    strcasecmp(options.identity_files[i], "none") == 0) {
1848			free(options.identity_files[i]);
1849			continue;
1850		}
1851		cp = tilde_expand_filename(options.identity_files[i],
1852		    original_real_uid);
1853		filename = percent_expand(cp, "d", pwdir,
1854		    "u", pwname, "l", thishost, "h", host,
1855		    "r", options.user, (char *)NULL);
1856		free(cp);
1857		public = key_load_public(filename, NULL);
1858		debug("identity file %s type %d", filename,
1859		    public ? public->type : -1);
1860		free(options.identity_files[i]);
1861		identity_files[n_ids] = filename;
1862		identity_keys[n_ids] = public;
1863
1864		if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1865			continue;
1866
1867		/* Try to add the certificate variant too */
1868		xasprintf(&cp, "%s-cert", filename);
1869		public = key_load_public(cp, NULL);
1870		debug("identity file %s type %d", cp,
1871		    public ? public->type : -1);
1872		if (public == NULL) {
1873			free(cp);
1874			continue;
1875		}
1876		if (!key_is_cert(public)) {
1877			debug("%s: key %s type %s is not a certificate",
1878			    __func__, cp, key_type(public));
1879			key_free(public);
1880			free(cp);
1881			continue;
1882		}
1883		identity_keys[n_ids] = public;
1884		/* point to the original path, most likely the private key */
1885		identity_files[n_ids] = xstrdup(filename);
1886		n_ids++;
1887	}
1888	options.num_identity_files = n_ids;
1889	memcpy(options.identity_files, identity_files, sizeof(identity_files));
1890	memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1891
1892	explicit_bzero(pwname, strlen(pwname));
1893	free(pwname);
1894	explicit_bzero(pwdir, strlen(pwdir));
1895	free(pwdir);
1896}
1897
1898static void
1899main_sigchld_handler(int sig)
1900{
1901	int save_errno = errno;
1902	pid_t pid;
1903	int status;
1904
1905	while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1906	    (pid < 0 && errno == EINTR))
1907		;
1908
1909	signal(sig, main_sigchld_handler);
1910	errno = save_errno;
1911}
1912