xref: /openbsd-src/usr.bin/ssh/ssh.c (revision daf88648c0e349d5c02e1504293082072c981640)
1 /* $OpenBSD: ssh.c,v 1.295 2007/01/03 03:01:40 stevesk 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 <sys/types.h>
44 #include <sys/time.h>
45 #include <sys/resource.h>
46 #include <sys/ioctl.h>
47 #include <sys/types.h>
48 #include <sys/socket.h>
49 #include <sys/un.h>
50 #include <sys/stat.h>
51 
52 #include <ctype.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <netdb.h>
56 #include <paths.h>
57 #include <pwd.h>
58 #include <signal.h>
59 #include <stddef.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 
65 #include <openssl/evp.h>
66 #include <openssl/err.h>
67 
68 #include "xmalloc.h"
69 #include "ssh.h"
70 #include "ssh1.h"
71 #include "ssh2.h"
72 #include "compat.h"
73 #include "cipher.h"
74 #include "packet.h"
75 #include "buffer.h"
76 #include "channels.h"
77 #include "key.h"
78 #include "authfd.h"
79 #include "authfile.h"
80 #include "pathnames.h"
81 #include "dispatch.h"
82 #include "clientloop.h"
83 #include "log.h"
84 #include "readconf.h"
85 #include "sshconnect.h"
86 #include "misc.h"
87 #include "kex.h"
88 #include "mac.h"
89 #include "sshpty.h"
90 #include "match.h"
91 #include "msg.h"
92 #include "monitor_fdpass.h"
93 #include "uidswap.h"
94 #include "version.h"
95 
96 #ifdef SMARTCARD
97 #include "scard.h"
98 #endif
99 
100 extern char *__progname;
101 
102 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
103 int debug_flag = 0;
104 
105 /* Flag indicating whether a tty should be allocated */
106 int tty_flag = 0;
107 int no_tty_flag = 0;
108 int force_tty_flag = 0;
109 
110 /* don't exec a shell */
111 int no_shell_flag = 0;
112 
113 /*
114  * Flag indicating that nothing should be read from stdin.  This can be set
115  * on the command line.
116  */
117 int stdin_null_flag = 0;
118 
119 /*
120  * Flag indicating that ssh should fork after authentication.  This is useful
121  * so that the passphrase can be entered manually, and then ssh goes to the
122  * background.
123  */
124 int fork_after_authentication_flag = 0;
125 
126 /*
127  * General data structure for command line options and options configurable
128  * in configuration files.  See readconf.h.
129  */
130 Options options;
131 
132 /* optional user configfile */
133 char *config = NULL;
134 
135 /*
136  * Name of the host we are connecting to.  This is the name given on the
137  * command line, or the HostName specified for the user-supplied name in a
138  * configuration file.
139  */
140 char *host;
141 
142 /* socket address the host resolves to */
143 struct sockaddr_storage hostaddr;
144 
145 /* Private host keys. */
146 Sensitive sensitive_data;
147 
148 /* Original real UID. */
149 uid_t original_real_uid;
150 uid_t original_effective_uid;
151 
152 /* command to be executed */
153 Buffer command;
154 
155 /* Should we execute a command or invoke a subsystem? */
156 int subsystem_flag = 0;
157 
158 /* # of replies received for global requests */
159 static int client_global_request_id = 0;
160 
161 /* pid of proxycommand child process */
162 pid_t proxy_command_pid = 0;
163 
164 /* fd to control socket */
165 int control_fd = -1;
166 
167 /* Multiplexing control command */
168 static u_int mux_command = 0;
169 
170 /* Only used in control client mode */
171 volatile sig_atomic_t control_client_terminate = 0;
172 u_int control_server_pid = 0;
173 
174 /* Prints a help message to the user.  This function never returns. */
175 
176 static void
177 usage(void)
178 {
179 	fprintf(stderr,
180 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
181 "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
182 "           [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
183 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
184 "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
185 "           [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
186 	);
187 	exit(255);
188 }
189 
190 static int ssh_session(void);
191 static int ssh_session2(void);
192 static void load_public_identity_files(void);
193 static void control_client(const char *path);
194 
195 /*
196  * Main program for the ssh client.
197  */
198 int
199 main(int ac, char **av)
200 {
201 	int i, opt, exit_status;
202 	char *p, *cp, *line, buf[256];
203 	struct stat st;
204 	struct passwd *pw;
205 	int dummy;
206 	extern int optind, optreset;
207 	extern char *optarg;
208 	struct servent *sp;
209 	Forward fwd;
210 
211 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
212 	sanitise_stdfd();
213 
214 	/*
215 	 * Save the original real uid.  It will be needed later (uid-swapping
216 	 * may clobber the real uid).
217 	 */
218 	original_real_uid = getuid();
219 	original_effective_uid = geteuid();
220 
221 	/*
222 	 * Use uid-swapping to give up root privileges for the duration of
223 	 * option processing.  We will re-instantiate the rights when we are
224 	 * ready to create the privileged port, and will permanently drop
225 	 * them when the port has been created (actually, when the connection
226 	 * has been made, as we may need to create the port several times).
227 	 */
228 	PRIV_END;
229 
230 	/* If we are installed setuid root be careful to not drop core. */
231 	if (original_real_uid != original_effective_uid) {
232 		struct rlimit rlim;
233 		rlim.rlim_cur = rlim.rlim_max = 0;
234 		if (setrlimit(RLIMIT_CORE, &rlim) < 0)
235 			fatal("setrlimit failed: %.100s", strerror(errno));
236 	}
237 	/* Get user data. */
238 	pw = getpwuid(original_real_uid);
239 	if (!pw) {
240 		logit("You don't exist, go away!");
241 		exit(255);
242 	}
243 	/* Take a copy of the returned structure. */
244 	pw = pwcopy(pw);
245 
246 	/*
247 	 * Set our umask to something reasonable, as some files are created
248 	 * with the default umask.  This will make them world-readable but
249 	 * writable only by the owner, which is ok for all files for which we
250 	 * don't set the modes explicitly.
251 	 */
252 	umask(022);
253 
254 	/* Initialize option structure to indicate that no values have been set. */
255 	initialize_options(&options);
256 
257 	/* Parse command-line arguments. */
258 	host = NULL;
259 
260  again:
261 	while ((opt = getopt(ac, av,
262 	    "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
263 		switch (opt) {
264 		case '1':
265 			options.protocol = SSH_PROTO_1;
266 			break;
267 		case '2':
268 			options.protocol = SSH_PROTO_2;
269 			break;
270 		case '4':
271 			options.address_family = AF_INET;
272 			break;
273 		case '6':
274 			options.address_family = AF_INET6;
275 			break;
276 		case 'n':
277 			stdin_null_flag = 1;
278 			break;
279 		case 'f':
280 			fork_after_authentication_flag = 1;
281 			stdin_null_flag = 1;
282 			break;
283 		case 'x':
284 			options.forward_x11 = 0;
285 			break;
286 		case 'X':
287 			options.forward_x11 = 1;
288 			break;
289 		case 'Y':
290 			options.forward_x11 = 1;
291 			options.forward_x11_trusted = 1;
292 			break;
293 		case 'g':
294 			options.gateway_ports = 1;
295 			break;
296 		case 'O':
297 			if (strcmp(optarg, "check") == 0)
298 				mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
299 			else if (strcmp(optarg, "exit") == 0)
300 				mux_command = SSHMUX_COMMAND_TERMINATE;
301 			else
302 				fatal("Invalid multiplex command.");
303 			break;
304 		case 'P':	/* deprecated */
305 			options.use_privileged_port = 0;
306 			break;
307 		case 'a':
308 			options.forward_agent = 0;
309 			break;
310 		case 'A':
311 			options.forward_agent = 1;
312 			break;
313 		case 'k':
314 			options.gss_deleg_creds = 0;
315 			break;
316 		case 'i':
317 			if (stat(optarg, &st) < 0) {
318 				fprintf(stderr, "Warning: Identity file %s "
319 				    "not accessible: %s.\n", optarg,
320 				    strerror(errno));
321 				break;
322 			}
323 			if (options.num_identity_files >=
324 			    SSH_MAX_IDENTITY_FILES)
325 				fatal("Too many identity files specified "
326 				    "(max %d)", SSH_MAX_IDENTITY_FILES);
327 			options.identity_files[options.num_identity_files++] =
328 			    xstrdup(optarg);
329 			break;
330 		case 'I':
331 #ifdef SMARTCARD
332 			options.smartcard_device = xstrdup(optarg);
333 #else
334 			fprintf(stderr, "no support for smartcards.\n");
335 #endif
336 			break;
337 		case 't':
338 			if (tty_flag)
339 				force_tty_flag = 1;
340 			tty_flag = 1;
341 			break;
342 		case 'v':
343 			if (debug_flag == 0) {
344 				debug_flag = 1;
345 				options.log_level = SYSLOG_LEVEL_DEBUG1;
346 			} else {
347 				if (options.log_level < SYSLOG_LEVEL_DEBUG3)
348 					options.log_level++;
349 				break;
350 			}
351 			/* FALLTHROUGH */
352 		case 'V':
353 			fprintf(stderr, "%s, %s\n",
354 			    SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
355 			if (opt == 'V')
356 				exit(0);
357 			break;
358 		case 'w':
359 			if (options.tun_open == -1)
360 				options.tun_open = SSH_TUNMODE_DEFAULT;
361 			options.tun_local = a2tun(optarg, &options.tun_remote);
362 			if (options.tun_local == SSH_TUNID_ERR) {
363 				fprintf(stderr, "Bad tun device '%s'\n", optarg);
364 				exit(255);
365 			}
366 			break;
367 		case 'q':
368 			options.log_level = SYSLOG_LEVEL_QUIET;
369 			break;
370 		case 'e':
371 			if (optarg[0] == '^' && optarg[2] == 0 &&
372 			    (u_char) optarg[1] >= 64 &&
373 			    (u_char) optarg[1] < 128)
374 				options.escape_char = (u_char) optarg[1] & 31;
375 			else if (strlen(optarg) == 1)
376 				options.escape_char = (u_char) optarg[0];
377 			else if (strcmp(optarg, "none") == 0)
378 				options.escape_char = SSH_ESCAPECHAR_NONE;
379 			else {
380 				fprintf(stderr, "Bad escape character '%s'.\n",
381 				    optarg);
382 				exit(255);
383 			}
384 			break;
385 		case 'c':
386 			if (ciphers_valid(optarg)) {
387 				/* SSH2 only */
388 				options.ciphers = xstrdup(optarg);
389 				options.cipher = SSH_CIPHER_INVALID;
390 			} else {
391 				/* SSH1 only */
392 				options.cipher = cipher_number(optarg);
393 				if (options.cipher == -1) {
394 					fprintf(stderr,
395 					    "Unknown cipher type '%s'\n",
396 					    optarg);
397 					exit(255);
398 				}
399 				if (options.cipher == SSH_CIPHER_3DES)
400 					options.ciphers = "3des-cbc";
401 				else if (options.cipher == SSH_CIPHER_BLOWFISH)
402 					options.ciphers = "blowfish-cbc";
403 				else
404 					options.ciphers = (char *)-1;
405 			}
406 			break;
407 		case 'm':
408 			if (mac_valid(optarg))
409 				options.macs = xstrdup(optarg);
410 			else {
411 				fprintf(stderr, "Unknown mac type '%s'\n",
412 				    optarg);
413 				exit(255);
414 			}
415 			break;
416 		case 'M':
417 			if (options.control_master == SSHCTL_MASTER_YES)
418 				options.control_master = SSHCTL_MASTER_ASK;
419 			else
420 				options.control_master = SSHCTL_MASTER_YES;
421 			break;
422 		case 'p':
423 			options.port = a2port(optarg);
424 			if (options.port == 0) {
425 				fprintf(stderr, "Bad port '%s'\n", optarg);
426 				exit(255);
427 			}
428 			break;
429 		case 'l':
430 			options.user = optarg;
431 			break;
432 
433 		case 'L':
434 			if (parse_forward(&fwd, optarg))
435 				add_local_forward(&options, &fwd);
436 			else {
437 				fprintf(stderr,
438 				    "Bad local forwarding specification '%s'\n",
439 				    optarg);
440 				exit(255);
441 			}
442 			break;
443 
444 		case 'R':
445 			if (parse_forward(&fwd, optarg)) {
446 				add_remote_forward(&options, &fwd);
447 			} else {
448 				fprintf(stderr,
449 				    "Bad remote forwarding specification "
450 				    "'%s'\n", optarg);
451 				exit(255);
452 			}
453 			break;
454 
455 		case 'D':
456 			cp = p = xstrdup(optarg);
457 			memset(&fwd, '\0', sizeof(fwd));
458 			fwd.connect_host = "socks";
459 			if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
460 				fprintf(stderr, "Bad dynamic forwarding "
461 				    "specification '%.100s'\n", optarg);
462 				exit(255);
463 			}
464 			if (cp != NULL) {
465 				fwd.listen_port = a2port(cp);
466 				fwd.listen_host = cleanhostname(fwd.listen_host);
467 			} else {
468 				fwd.listen_port = a2port(fwd.listen_host);
469 				fwd.listen_host = NULL;
470 			}
471 
472 			if (fwd.listen_port == 0) {
473 				fprintf(stderr, "Bad dynamic port '%s'\n",
474 				    optarg);
475 				exit(255);
476 			}
477 			add_local_forward(&options, &fwd);
478 			xfree(p);
479 			break;
480 
481 		case 'C':
482 			options.compression = 1;
483 			break;
484 		case 'N':
485 			no_shell_flag = 1;
486 			no_tty_flag = 1;
487 			break;
488 		case 'T':
489 			no_tty_flag = 1;
490 			break;
491 		case 'o':
492 			dummy = 1;
493 			line = xstrdup(optarg);
494 			if (process_config_line(&options, host ? host : "",
495 			    line, "command-line", 0, &dummy) != 0)
496 				exit(255);
497 			xfree(line);
498 			break;
499 		case 's':
500 			subsystem_flag = 1;
501 			break;
502 		case 'S':
503 			if (options.control_path != NULL)
504 				free(options.control_path);
505 			options.control_path = xstrdup(optarg);
506 			break;
507 		case 'b':
508 			options.bind_address = optarg;
509 			break;
510 		case 'F':
511 			config = optarg;
512 			break;
513 		default:
514 			usage();
515 		}
516 	}
517 
518 	ac -= optind;
519 	av += optind;
520 
521 	if (ac > 0 && !host && **av != '-') {
522 		if (strrchr(*av, '@')) {
523 			p = xstrdup(*av);
524 			cp = strrchr(p, '@');
525 			if (cp == NULL || cp == p)
526 				usage();
527 			options.user = p;
528 			*cp = '\0';
529 			host = ++cp;
530 		} else
531 			host = *av;
532 		if (ac > 1) {
533 			optind = optreset = 1;
534 			goto again;
535 		}
536 		ac--, av++;
537 	}
538 
539 	/* Check that we got a host name. */
540 	if (!host)
541 		usage();
542 
543 	SSLeay_add_all_algorithms();
544 	ERR_load_crypto_strings();
545 
546 	/* Initialize the command to execute on remote host. */
547 	buffer_init(&command);
548 
549 	/*
550 	 * Save the command to execute on the remote host in a buffer. There
551 	 * is no limit on the length of the command, except by the maximum
552 	 * packet size.  Also sets the tty flag if there is no command.
553 	 */
554 	if (!ac) {
555 		/* No command specified - execute shell on a tty. */
556 		tty_flag = 1;
557 		if (subsystem_flag) {
558 			fprintf(stderr,
559 			    "You must specify a subsystem to invoke.\n");
560 			usage();
561 		}
562 	} else {
563 		/* A command has been specified.  Store it into the buffer. */
564 		for (i = 0; i < ac; i++) {
565 			if (i)
566 				buffer_append(&command, " ", 1);
567 			buffer_append(&command, av[i], strlen(av[i]));
568 		}
569 	}
570 
571 	/* Cannot fork to background if no command. */
572 	if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
573 		fatal("Cannot fork into background without a command to execute.");
574 
575 	/* Allocate a tty by default if no command specified. */
576 	if (buffer_len(&command) == 0)
577 		tty_flag = 1;
578 
579 	/* Force no tty */
580 	if (no_tty_flag)
581 		tty_flag = 0;
582 	/* Do not allocate a tty if stdin is not a tty. */
583 	if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
584 		if (tty_flag)
585 			logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
586 		tty_flag = 0;
587 	}
588 
589 	/*
590 	 * Initialize "log" output.  Since we are the client all output
591 	 * actually goes to stderr.
592 	 */
593 	log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
594 	    SYSLOG_FACILITY_USER, 1);
595 
596 	/*
597 	 * Read per-user configuration file.  Ignore the system wide config
598 	 * file if the user specifies a config file on the command line.
599 	 */
600 	if (config != NULL) {
601 		if (!read_config_file(config, host, &options, 0))
602 			fatal("Can't open user config file %.100s: "
603 			    "%.100s", config, strerror(errno));
604 	} else {
605 		snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
606 		    _PATH_SSH_USER_CONFFILE);
607 		(void)read_config_file(buf, host, &options, 1);
608 
609 		/* Read systemwide configuration file after use config. */
610 		(void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
611 		    &options, 0);
612 	}
613 
614 	/* Fill configuration defaults. */
615 	fill_default_options(&options);
616 
617 	channel_set_af(options.address_family);
618 
619 	/* reinit */
620 	log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
621 
622 	if (options.user == NULL)
623 		options.user = xstrdup(pw->pw_name);
624 
625 	if (options.hostname != NULL)
626 		host = options.hostname;
627 
628 	/* force lowercase for hostkey matching */
629 	if (options.host_key_alias != NULL) {
630 		for (p = options.host_key_alias; *p; p++)
631 			if (isupper(*p))
632 				*p = (char)tolower(*p);
633 	}
634 
635 	/* Get default port if port has not been set. */
636 	if (options.port == 0) {
637 		sp = getservbyname(SSH_SERVICE_NAME, "tcp");
638 		options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
639 	}
640 
641 	if (options.proxy_command != NULL &&
642 	    strcmp(options.proxy_command, "none") == 0)
643 		options.proxy_command = NULL;
644 	if (options.control_path != NULL &&
645 	    strcmp(options.control_path, "none") == 0)
646 		options.control_path = NULL;
647 
648 	if (options.control_path != NULL) {
649 		char thishost[NI_MAXHOST];
650 
651 		if (gethostname(thishost, sizeof(thishost)) == -1)
652 			fatal("gethostname: %s", strerror(errno));
653 		snprintf(buf, sizeof(buf), "%d", options.port);
654 		cp = tilde_expand_filename(options.control_path,
655 		    original_real_uid);
656 		options.control_path = percent_expand(cp, "p", buf, "h", host,
657 		    "r", options.user, "l", thishost, (char *)NULL);
658 		xfree(cp);
659 	}
660 	if (mux_command != 0 && options.control_path == NULL)
661 		fatal("No ControlPath specified for \"-O\" command");
662 	if (options.control_path != NULL)
663 		control_client(options.control_path);
664 
665 	/* Open a connection to the remote host. */
666 	if (ssh_connect(host, &hostaddr, options.port,
667 	    options.address_family, options.connection_attempts,
668 	    original_effective_uid == 0 && options.use_privileged_port,
669 	    options.proxy_command) != 0)
670 		exit(255);
671 
672 	/*
673 	 * If we successfully made the connection, load the host private key
674 	 * in case we will need it later for combined rsa-rhosts
675 	 * authentication. This must be done before releasing extra
676 	 * privileges, because the file is only readable by root.
677 	 * If we cannot access the private keys, load the public keys
678 	 * instead and try to execute the ssh-keysign helper instead.
679 	 */
680 	sensitive_data.nkeys = 0;
681 	sensitive_data.keys = NULL;
682 	sensitive_data.external_keysign = 0;
683 	if (options.rhosts_rsa_authentication ||
684 	    options.hostbased_authentication) {
685 		sensitive_data.nkeys = 3;
686 		sensitive_data.keys = xcalloc(sensitive_data.nkeys,
687 		    sizeof(Key));
688 
689 		PRIV_START;
690 		sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
691 		    _PATH_HOST_KEY_FILE, "", NULL, NULL);
692 		sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
693 		    _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
694 		sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
695 		    _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
696 		PRIV_END;
697 
698 		if (options.hostbased_authentication == 1 &&
699 		    sensitive_data.keys[0] == NULL &&
700 		    sensitive_data.keys[1] == NULL &&
701 		    sensitive_data.keys[2] == NULL) {
702 			sensitive_data.keys[1] = key_load_public(
703 			    _PATH_HOST_DSA_KEY_FILE, NULL);
704 			sensitive_data.keys[2] = key_load_public(
705 			    _PATH_HOST_RSA_KEY_FILE, NULL);
706 			sensitive_data.external_keysign = 1;
707 		}
708 	}
709 	/*
710 	 * Get rid of any extra privileges that we may have.  We will no
711 	 * longer need them.  Also, extra privileges could make it very hard
712 	 * to read identity files and other non-world-readable files from the
713 	 * user's home directory if it happens to be on a NFS volume where
714 	 * root is mapped to nobody.
715 	 */
716 	if (original_effective_uid == 0) {
717 		PRIV_START;
718 		permanently_set_uid(pw);
719 	}
720 
721 	/*
722 	 * Now that we are back to our own permissions, create ~/.ssh
723 	 * directory if it doesn't already exist.
724 	 */
725 	snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
726 	if (stat(buf, &st) < 0)
727 		if (mkdir(buf, 0700) < 0)
728 			error("Could not create directory '%.200s'.", buf);
729 
730 	/* load options.identity_files */
731 	load_public_identity_files();
732 
733 	/* Expand ~ in known host file names. */
734 	/* XXX mem-leaks: */
735 	options.system_hostfile =
736 	    tilde_expand_filename(options.system_hostfile, original_real_uid);
737 	options.user_hostfile =
738 	    tilde_expand_filename(options.user_hostfile, original_real_uid);
739 	options.system_hostfile2 =
740 	    tilde_expand_filename(options.system_hostfile2, original_real_uid);
741 	options.user_hostfile2 =
742 	    tilde_expand_filename(options.user_hostfile2, original_real_uid);
743 
744 	signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
745 
746 	/* Log into the remote system.  This never returns if the login fails. */
747 	ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
748 
749 	/* We no longer need the private host keys.  Clear them now. */
750 	if (sensitive_data.nkeys != 0) {
751 		for (i = 0; i < sensitive_data.nkeys; i++) {
752 			if (sensitive_data.keys[i] != NULL) {
753 				/* Destroys contents safely */
754 				debug3("clear hostkey %d", i);
755 				key_free(sensitive_data.keys[i]);
756 				sensitive_data.keys[i] = NULL;
757 			}
758 		}
759 		xfree(sensitive_data.keys);
760 	}
761 	for (i = 0; i < options.num_identity_files; i++) {
762 		if (options.identity_files[i]) {
763 			xfree(options.identity_files[i]);
764 			options.identity_files[i] = NULL;
765 		}
766 		if (options.identity_keys[i]) {
767 			key_free(options.identity_keys[i]);
768 			options.identity_keys[i] = NULL;
769 		}
770 	}
771 
772 	exit_status = compat20 ? ssh_session2() : ssh_session();
773 	packet_close();
774 
775 	if (options.control_path != NULL && control_fd != -1)
776 		unlink(options.control_path);
777 
778 	/*
779 	 * Send SIGHUP to proxy command if used. We don't wait() in
780 	 * case it hangs and instead rely on init to reap the child
781 	 */
782 	if (proxy_command_pid > 1)
783 		kill(proxy_command_pid, SIGHUP);
784 
785 	return exit_status;
786 }
787 
788 static void
789 ssh_init_forwarding(void)
790 {
791 	int success = 0;
792 	int i;
793 
794 	/* Initiate local TCP/IP port forwardings. */
795 	for (i = 0; i < options.num_local_forwards; i++) {
796 		debug("Local connections to %.200s:%d forwarded to remote "
797 		    "address %.200s:%d",
798 		    (options.local_forwards[i].listen_host == NULL) ?
799 		    (options.gateway_ports ? "*" : "LOCALHOST") :
800 		    options.local_forwards[i].listen_host,
801 		    options.local_forwards[i].listen_port,
802 		    options.local_forwards[i].connect_host,
803 		    options.local_forwards[i].connect_port);
804 		success += channel_setup_local_fwd_listener(
805 		    options.local_forwards[i].listen_host,
806 		    options.local_forwards[i].listen_port,
807 		    options.local_forwards[i].connect_host,
808 		    options.local_forwards[i].connect_port,
809 		    options.gateway_ports);
810 	}
811 	if (i > 0 && success != i && options.exit_on_forward_failure)
812 		fatal("Could not request local forwarding.");
813 	if (i > 0 && success == 0)
814 		error("Could not request local forwarding.");
815 
816 	/* Initiate remote TCP/IP port forwardings. */
817 	for (i = 0; i < options.num_remote_forwards; i++) {
818 		debug("Remote connections from %.200s:%d forwarded to "
819 		    "local address %.200s:%d",
820 		    (options.remote_forwards[i].listen_host == NULL) ?
821 		    "LOCALHOST" : options.remote_forwards[i].listen_host,
822 		    options.remote_forwards[i].listen_port,
823 		    options.remote_forwards[i].connect_host,
824 		    options.remote_forwards[i].connect_port);
825 		if (channel_request_remote_forwarding(
826 		    options.remote_forwards[i].listen_host,
827 		    options.remote_forwards[i].listen_port,
828 		    options.remote_forwards[i].connect_host,
829 		    options.remote_forwards[i].connect_port) < 0) {
830 			if (options.exit_on_forward_failure)
831 				fatal("Could not request remote forwarding.");
832 			else
833 				logit("Warning: Could not request remote "
834 				    "forwarding.");
835 		}
836 	}
837 }
838 
839 static void
840 check_agent_present(void)
841 {
842 	if (options.forward_agent) {
843 		/* Clear agent forwarding if we don't have an agent. */
844 		if (!ssh_agent_present())
845 			options.forward_agent = 0;
846 	}
847 }
848 
849 static int
850 ssh_session(void)
851 {
852 	int type;
853 	int interactive = 0;
854 	int have_tty = 0;
855 	struct winsize ws;
856 	char *cp;
857 	const char *display;
858 
859 	/* Enable compression if requested. */
860 	if (options.compression) {
861 		debug("Requesting compression at level %d.", options.compression_level);
862 
863 		if (options.compression_level < 1 || options.compression_level > 9)
864 			fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
865 
866 		/* Send the request. */
867 		packet_start(SSH_CMSG_REQUEST_COMPRESSION);
868 		packet_put_int(options.compression_level);
869 		packet_send();
870 		packet_write_wait();
871 		type = packet_read();
872 		if (type == SSH_SMSG_SUCCESS)
873 			packet_start_compression(options.compression_level);
874 		else if (type == SSH_SMSG_FAILURE)
875 			logit("Warning: Remote host refused compression.");
876 		else
877 			packet_disconnect("Protocol error waiting for compression response.");
878 	}
879 	/* Allocate a pseudo tty if appropriate. */
880 	if (tty_flag) {
881 		debug("Requesting pty.");
882 
883 		/* Start the packet. */
884 		packet_start(SSH_CMSG_REQUEST_PTY);
885 
886 		/* Store TERM in the packet.  There is no limit on the
887 		   length of the string. */
888 		cp = getenv("TERM");
889 		if (!cp)
890 			cp = "";
891 		packet_put_cstring(cp);
892 
893 		/* Store window size in the packet. */
894 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
895 			memset(&ws, 0, sizeof(ws));
896 		packet_put_int((u_int)ws.ws_row);
897 		packet_put_int((u_int)ws.ws_col);
898 		packet_put_int((u_int)ws.ws_xpixel);
899 		packet_put_int((u_int)ws.ws_ypixel);
900 
901 		/* Store tty modes in the packet. */
902 		tty_make_modes(fileno(stdin), NULL);
903 
904 		/* Send the packet, and wait for it to leave. */
905 		packet_send();
906 		packet_write_wait();
907 
908 		/* Read response from the server. */
909 		type = packet_read();
910 		if (type == SSH_SMSG_SUCCESS) {
911 			interactive = 1;
912 			have_tty = 1;
913 		} else if (type == SSH_SMSG_FAILURE)
914 			logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
915 		else
916 			packet_disconnect("Protocol error waiting for pty request response.");
917 	}
918 	/* Request X11 forwarding if enabled and DISPLAY is set. */
919 	display = getenv("DISPLAY");
920 	if (options.forward_x11 && display != NULL) {
921 		char *proto, *data;
922 		/* Get reasonable local authentication information. */
923 		client_x11_get_proto(display, options.xauth_location,
924 		    options.forward_x11_trusted, &proto, &data);
925 		/* Request forwarding with authentication spoofing. */
926 		debug("Requesting X11 forwarding with authentication spoofing.");
927 		x11_request_forwarding_with_spoofing(0, display, proto, data);
928 
929 		/* Read response from the server. */
930 		type = packet_read();
931 		if (type == SSH_SMSG_SUCCESS) {
932 			interactive = 1;
933 		} else if (type == SSH_SMSG_FAILURE) {
934 			logit("Warning: Remote host denied X11 forwarding.");
935 		} else {
936 			packet_disconnect("Protocol error waiting for X11 forwarding");
937 		}
938 	}
939 	/* Tell the packet module whether this is an interactive session. */
940 	packet_set_interactive(interactive);
941 
942 	/* Request authentication agent forwarding if appropriate. */
943 	check_agent_present();
944 
945 	if (options.forward_agent) {
946 		debug("Requesting authentication agent forwarding.");
947 		auth_request_forwarding();
948 
949 		/* Read response from the server. */
950 		type = packet_read();
951 		packet_check_eom();
952 		if (type != SSH_SMSG_SUCCESS)
953 			logit("Warning: Remote host denied authentication agent forwarding.");
954 	}
955 
956 	/* Initiate port forwardings. */
957 	ssh_init_forwarding();
958 
959 	/* If requested, let ssh continue in the background. */
960 	if (fork_after_authentication_flag)
961 		if (daemon(1, 1) < 0)
962 			fatal("daemon() failed: %.200s", strerror(errno));
963 
964 	/*
965 	 * If a command was specified on the command line, execute the
966 	 * command now. Otherwise request the server to start a shell.
967 	 */
968 	if (buffer_len(&command) > 0) {
969 		int len = buffer_len(&command);
970 		if (len > 900)
971 			len = 900;
972 		debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
973 		packet_start(SSH_CMSG_EXEC_CMD);
974 		packet_put_string(buffer_ptr(&command), buffer_len(&command));
975 		packet_send();
976 		packet_write_wait();
977 	} else {
978 		debug("Requesting shell.");
979 		packet_start(SSH_CMSG_EXEC_SHELL);
980 		packet_send();
981 		packet_write_wait();
982 	}
983 
984 	/* Enter the interactive session. */
985 	return client_loop(have_tty, tty_flag ?
986 	    options.escape_char : SSH_ESCAPECHAR_NONE, 0);
987 }
988 
989 static void
990 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
991 {
992 	int id, len;
993 
994 	id = packet_get_int();
995 	len = buffer_len(&command);
996 	if (len > 900)
997 		len = 900;
998 	packet_check_eom();
999 	if (type == SSH2_MSG_CHANNEL_FAILURE)
1000 		fatal("Request for subsystem '%.*s' failed on channel %d",
1001 		    len, (u_char *)buffer_ptr(&command), id);
1002 }
1003 
1004 void
1005 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1006 {
1007 	int i;
1008 
1009 	i = client_global_request_id++;
1010 	if (i >= options.num_remote_forwards)
1011 		return;
1012 	debug("remote forward %s for: listen %d, connect %s:%d",
1013 	    type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1014 	    options.remote_forwards[i].listen_port,
1015 	    options.remote_forwards[i].connect_host,
1016 	    options.remote_forwards[i].connect_port);
1017 	if (type == SSH2_MSG_REQUEST_FAILURE) {
1018 		if (options.exit_on_forward_failure)
1019 			fatal("Error: remote port forwarding failed for "
1020 			    "listen port %d",
1021 			    options.remote_forwards[i].listen_port);
1022 		else
1023 			logit("Warning: remote port forwarding failed for "
1024 			    "listen port %d",
1025 			    options.remote_forwards[i].listen_port);
1026 	}
1027 }
1028 
1029 static void
1030 ssh_control_listener(void)
1031 {
1032 	struct sockaddr_un addr;
1033 	mode_t old_umask;
1034 
1035 	if (options.control_path == NULL ||
1036 	    options.control_master == SSHCTL_MASTER_NO)
1037 		return;
1038 
1039 	debug("setting up multiplex master socket");
1040 
1041 	memset(&addr, '\0', sizeof(addr));
1042 	addr.sun_family = AF_UNIX;
1043 	addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
1044 	    strlen(options.control_path) + 1;
1045 
1046 	if (strlcpy(addr.sun_path, options.control_path,
1047 	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1048 		fatal("ControlPath too long");
1049 
1050 	if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1051 		fatal("%s socket(): %s", __func__, strerror(errno));
1052 
1053 	old_umask = umask(0177);
1054 	if (bind(control_fd, (struct sockaddr *)&addr, addr.sun_len) == -1) {
1055 		control_fd = -1;
1056 		if (errno == EINVAL || errno == EADDRINUSE)
1057 			fatal("ControlSocket %s already exists",
1058 			    options.control_path);
1059 		else
1060 			fatal("%s bind(): %s", __func__, strerror(errno));
1061 	}
1062 	umask(old_umask);
1063 
1064 	if (listen(control_fd, 64) == -1)
1065 		fatal("%s listen(): %s", __func__, strerror(errno));
1066 
1067 	set_nonblock(control_fd);
1068 }
1069 
1070 /* request pty/x11/agent/tcpfwd/shell for channel */
1071 static void
1072 ssh_session2_setup(int id, void *arg)
1073 {
1074 	extern char **environ;
1075 	const char *display;
1076 	int interactive = tty_flag;
1077 
1078 	display = getenv("DISPLAY");
1079 	if (options.forward_x11 && display != NULL) {
1080 		char *proto, *data;
1081 		/* Get reasonable local authentication information. */
1082 		client_x11_get_proto(display, options.xauth_location,
1083 		    options.forward_x11_trusted, &proto, &data);
1084 		/* Request forwarding with authentication spoofing. */
1085 		debug("Requesting X11 forwarding with authentication spoofing.");
1086 		x11_request_forwarding_with_spoofing(id, display, proto, data);
1087 		interactive = 1;
1088 		/* XXX wait for reply */
1089 	}
1090 
1091 	check_agent_present();
1092 	if (options.forward_agent) {
1093 		debug("Requesting authentication agent forwarding.");
1094 		channel_request_start(id, "auth-agent-req@openssh.com", 0);
1095 		packet_send();
1096 	}
1097 
1098 	if (options.tun_open != SSH_TUNMODE_NO) {
1099 		Channel *c;
1100 		int fd;
1101 
1102 		debug("Requesting tun.");
1103 		if ((fd = tun_open(options.tun_local,
1104 		    options.tun_open)) >= 0) {
1105 			c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1106 			    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1107 			    0, "tun", 1);
1108 			c->datagram = 1;
1109 			packet_start(SSH2_MSG_CHANNEL_OPEN);
1110 			packet_put_cstring("tun@openssh.com");
1111 			packet_put_int(c->self);
1112 			packet_put_int(c->local_window_max);
1113 			packet_put_int(c->local_maxpacket);
1114 			packet_put_int(options.tun_open);
1115 			packet_put_int(options.tun_remote);
1116 			packet_send();
1117 		}
1118 	}
1119 
1120 	client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1121 	    NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1122 
1123 	packet_set_interactive(interactive);
1124 }
1125 
1126 /* open new channel for a session */
1127 static int
1128 ssh_session2_open(void)
1129 {
1130 	Channel *c;
1131 	int window, packetmax, in, out, err;
1132 
1133 	if (stdin_null_flag) {
1134 		in = open(_PATH_DEVNULL, O_RDONLY);
1135 	} else {
1136 		in = dup(STDIN_FILENO);
1137 	}
1138 	out = dup(STDOUT_FILENO);
1139 	err = dup(STDERR_FILENO);
1140 
1141 	if (in < 0 || out < 0 || err < 0)
1142 		fatal("dup() in/out/err failed");
1143 
1144 	/* enable nonblocking unless tty */
1145 	if (!isatty(in))
1146 		set_nonblock(in);
1147 	if (!isatty(out))
1148 		set_nonblock(out);
1149 	if (!isatty(err))
1150 		set_nonblock(err);
1151 
1152 	window = CHAN_SES_WINDOW_DEFAULT;
1153 	packetmax = CHAN_SES_PACKET_DEFAULT;
1154 	if (tty_flag) {
1155 		window >>= 1;
1156 		packetmax >>= 1;
1157 	}
1158 	c = channel_new(
1159 	    "session", SSH_CHANNEL_OPENING, in, out, err,
1160 	    window, packetmax, CHAN_EXTENDED_WRITE,
1161 	    "client-session", /*nonblock*/0);
1162 
1163 	debug3("ssh_session2_open: channel_new: %d", c->self);
1164 
1165 	channel_send_open(c->self);
1166 	if (!no_shell_flag)
1167 		channel_register_confirm(c->self, ssh_session2_setup, NULL);
1168 
1169 	return c->self;
1170 }
1171 
1172 static int
1173 ssh_session2(void)
1174 {
1175 	int id = -1;
1176 
1177 	/* XXX should be pre-session */
1178 	ssh_init_forwarding();
1179 	ssh_control_listener();
1180 
1181 	if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1182 		id = ssh_session2_open();
1183 
1184 	/* Execute a local command */
1185 	if (options.local_command != NULL &&
1186 	    options.permit_local_command)
1187 		ssh_local_cmd(options.local_command);
1188 
1189 	/* If requested, let ssh continue in the background. */
1190 	if (fork_after_authentication_flag)
1191 		if (daemon(1, 1) < 0)
1192 			fatal("daemon() failed: %.200s", strerror(errno));
1193 
1194 	return client_loop(tty_flag, tty_flag ?
1195 	    options.escape_char : SSH_ESCAPECHAR_NONE, id);
1196 }
1197 
1198 static void
1199 load_public_identity_files(void)
1200 {
1201 	char *filename, *cp, thishost[NI_MAXHOST];
1202 	int i = 0;
1203 	Key *public;
1204 	struct passwd *pw;
1205 #ifdef SMARTCARD
1206 	Key **keys;
1207 
1208 	if (options.smartcard_device != NULL &&
1209 	    options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1210 	    (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1211 		int count = 0;
1212 		for (i = 0; keys[i] != NULL; i++) {
1213 			count++;
1214 			memmove(&options.identity_files[1], &options.identity_files[0],
1215 			    sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1216 			memmove(&options.identity_keys[1], &options.identity_keys[0],
1217 			    sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1218 			options.num_identity_files++;
1219 			options.identity_keys[0] = keys[i];
1220 			options.identity_files[0] = sc_get_key_label(keys[i]);
1221 		}
1222 		if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1223 			options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1224 		i = count;
1225 		xfree(keys);
1226 	}
1227 #endif /* SMARTCARD */
1228 	if ((pw = getpwuid(original_real_uid)) == NULL)
1229 		fatal("load_public_identity_files: getpwuid failed");
1230 	if (gethostname(thishost, sizeof(thishost)) == -1)
1231 		fatal("load_public_identity_files: gethostname: %s",
1232 		    strerror(errno));
1233 	for (; i < options.num_identity_files; i++) {
1234 		cp = tilde_expand_filename(options.identity_files[i],
1235 		    original_real_uid);
1236 		filename = percent_expand(cp, "d", pw->pw_dir,
1237 		    "u", pw->pw_name, "l", thishost, "h", host,
1238 		    "r", options.user, (char *)NULL);
1239 		xfree(cp);
1240 		public = key_load_public(filename, NULL);
1241 		debug("identity file %s type %d", filename,
1242 		    public ? public->type : -1);
1243 		xfree(options.identity_files[i]);
1244 		options.identity_files[i] = filename;
1245 		options.identity_keys[i] = public;
1246 	}
1247 }
1248 
1249 static void
1250 control_client_sighandler(int signo)
1251 {
1252 	control_client_terminate = signo;
1253 }
1254 
1255 static void
1256 control_client_sigrelay(int signo)
1257 {
1258 	if (control_server_pid > 1)
1259 		kill(control_server_pid, signo);
1260 }
1261 
1262 static int
1263 env_permitted(char *env)
1264 {
1265 	int i, ret;
1266 	char name[1024], *cp;
1267 
1268 	if ((cp = strchr(env, '=')) == NULL || cp == env)
1269 		return (0);
1270 	ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1271 	if (ret <= 0 || (size_t)ret >= sizeof(name))
1272 		fatal("env_permitted: name '%.100s...' too long", env);
1273 
1274 	for (i = 0; i < options.num_send_env; i++)
1275 		if (match_pattern(name, options.send_env[i]))
1276 			return (1);
1277 
1278 	return (0);
1279 }
1280 
1281 static void
1282 control_client(const char *path)
1283 {
1284 	struct sockaddr_un addr;
1285 	int i, r, fd, sock, exitval, num_env;
1286 	Buffer m;
1287 	char *term;
1288 	extern char **environ;
1289 	u_int  flags;
1290 
1291 	if (mux_command == 0)
1292 		mux_command = SSHMUX_COMMAND_OPEN;
1293 
1294 	switch (options.control_master) {
1295 	case SSHCTL_MASTER_AUTO:
1296 	case SSHCTL_MASTER_AUTO_ASK:
1297 		debug("auto-mux: Trying existing master");
1298 		/* FALLTHROUGH */
1299 	case SSHCTL_MASTER_NO:
1300 		break;
1301 	default:
1302 		return;
1303 	}
1304 
1305 	memset(&addr, '\0', sizeof(addr));
1306 	addr.sun_family = AF_UNIX;
1307 	addr.sun_len = offsetof(struct sockaddr_un, sun_path) +
1308 	    strlen(path) + 1;
1309 
1310 	if (strlcpy(addr.sun_path, path,
1311 	    sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1312 		fatal("ControlPath too long");
1313 
1314 	if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1315 		fatal("%s socket(): %s", __func__, strerror(errno));
1316 
1317 	if (connect(sock, (struct sockaddr *)&addr, addr.sun_len) == -1) {
1318 		if (mux_command != SSHMUX_COMMAND_OPEN) {
1319 			fatal("Control socket connect(%.100s): %s", path,
1320 			    strerror(errno));
1321 		}
1322 		if (errno == ENOENT)
1323 			debug("Control socket \"%.100s\" does not exist", path);
1324 		else {
1325 			error("Control socket connect(%.100s): %s", path,
1326 			    strerror(errno));
1327 		}
1328 		close(sock);
1329 		return;
1330 	}
1331 
1332 	if (stdin_null_flag) {
1333 		if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1334 			fatal("open(/dev/null): %s", strerror(errno));
1335 		if (dup2(fd, STDIN_FILENO) == -1)
1336 			fatal("dup2: %s", strerror(errno));
1337 		if (fd > STDERR_FILENO)
1338 			close(fd);
1339 	}
1340 
1341 	term = getenv("TERM");
1342 
1343 	flags = 0;
1344 	if (tty_flag)
1345 		flags |= SSHMUX_FLAG_TTY;
1346 	if (subsystem_flag)
1347 		flags |= SSHMUX_FLAG_SUBSYS;
1348 	if (options.forward_x11)
1349 		flags |= SSHMUX_FLAG_X11_FWD;
1350 	if (options.forward_agent)
1351 		flags |= SSHMUX_FLAG_AGENT_FWD;
1352 
1353 	buffer_init(&m);
1354 
1355 	/* Send our command to server */
1356 	buffer_put_int(&m, mux_command);
1357 	buffer_put_int(&m, flags);
1358 	if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1359 		fatal("%s: msg_send", __func__);
1360 	buffer_clear(&m);
1361 
1362 	/* Get authorisation status and PID of controlee */
1363 	if (ssh_msg_recv(sock, &m) == -1)
1364 		fatal("%s: msg_recv", __func__);
1365 	if (buffer_get_char(&m) != SSHMUX_VER)
1366 		fatal("%s: wrong version", __func__);
1367 	if (buffer_get_int(&m) != 1)
1368 		fatal("Connection to master denied");
1369 	control_server_pid = buffer_get_int(&m);
1370 
1371 	buffer_clear(&m);
1372 
1373 	switch (mux_command) {
1374 	case SSHMUX_COMMAND_ALIVE_CHECK:
1375 		fprintf(stderr, "Master running (pid=%d)\r\n",
1376 		    control_server_pid);
1377 		exit(0);
1378 	case SSHMUX_COMMAND_TERMINATE:
1379 		fprintf(stderr, "Exit request sent.\r\n");
1380 		exit(0);
1381 	case SSHMUX_COMMAND_OPEN:
1382 		/* continue below */
1383 		break;
1384 	default:
1385 		fatal("silly mux_command %d", mux_command);
1386 	}
1387 
1388 	/* SSHMUX_COMMAND_OPEN */
1389 	buffer_put_cstring(&m, term ? term : "");
1390 	buffer_append(&command, "\0", 1);
1391 	buffer_put_cstring(&m, buffer_ptr(&command));
1392 
1393 	if (options.num_send_env == 0 || environ == NULL) {
1394 		buffer_put_int(&m, 0);
1395 	} else {
1396 		/* Pass environment */
1397 		num_env = 0;
1398 		for (i = 0; environ[i] != NULL; i++)
1399 			if (env_permitted(environ[i]))
1400 				num_env++; /* Count */
1401 
1402 		buffer_put_int(&m, num_env);
1403 
1404 		for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1405 			if (env_permitted(environ[i])) {
1406 				num_env--;
1407 				buffer_put_cstring(&m, environ[i]);
1408 			}
1409 	}
1410 
1411 	if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1412 		fatal("%s: msg_send", __func__);
1413 
1414 	mm_send_fd(sock, STDIN_FILENO);
1415 	mm_send_fd(sock, STDOUT_FILENO);
1416 	mm_send_fd(sock, STDERR_FILENO);
1417 
1418 	/* Wait for reply, so master has a chance to gather ttymodes */
1419 	buffer_clear(&m);
1420 	if (ssh_msg_recv(sock, &m) == -1)
1421 		fatal("%s: msg_recv", __func__);
1422 	if (buffer_get_char(&m) != SSHMUX_VER)
1423 		fatal("%s: wrong version", __func__);
1424 	buffer_free(&m);
1425 
1426 	signal(SIGHUP, control_client_sighandler);
1427 	signal(SIGINT, control_client_sighandler);
1428 	signal(SIGTERM, control_client_sighandler);
1429 	signal(SIGWINCH, control_client_sigrelay);
1430 
1431 	if (tty_flag)
1432 		enter_raw_mode();
1433 
1434 	/* Stick around until the controlee closes the client_fd */
1435 	exitval = 0;
1436 	for (;!control_client_terminate;) {
1437 		r = read(sock, &exitval, sizeof(exitval));
1438 		if (r == 0) {
1439 			debug2("Received EOF from master");
1440 			break;
1441 		}
1442 		if (r > 0)
1443 			debug2("Received exit status from master %d", exitval);
1444 		if (r == -1 && errno != EINTR)
1445 			fatal("%s: read %s", __func__, strerror(errno));
1446 	}
1447 
1448 	if (control_client_terminate)
1449 		debug2("Exiting on signal %d", control_client_terminate);
1450 
1451 	close(sock);
1452 
1453 	leave_raw_mode();
1454 
1455 	if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1456 		fprintf(stderr, "Connection to master closed.\r\n");
1457 
1458 	exit(exitval);
1459 }
1460