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