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