2e28eb87054c65a7791a88b6183a62505ac4a2ea
[dragonfly.git] / crypto / openssh-5 / ssh.c
1 /* $OpenBSD: ssh.c,v 1.309 2008/01/19 20:51:26 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Ssh client program.  This program can be used to log into a remote machine.
7  * The software supports strong authentication, encryption, and forwarding
8  * of X11, TCP/IP, and authentication connections.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * Copyright (c) 1999 Niels Provos.  All rights reserved.
17  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
18  *
19  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20  * in Canada (German citizen).
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the above copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41  */
42
43 #include "includes.h"
44
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #include <sys/un.h>
53
54 #include <ctype.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <netdb.h>
58 #ifdef HAVE_PATHS_H
59 #include <paths.h>
60 #endif
61 #include <pwd.h>
62 #include <signal.h>
63 #include <stdarg.h>
64 #include <stddef.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69
70 #include <netinet/in.h>
71 #include <arpa/inet.h>
72
73 #include <openssl/evp.h>
74 #include <openssl/err.h>
75 #include "openbsd-compat/openssl-compat.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 [-1246AaCfgKkMNnqsTtVvXxY] [-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, timeout_ms;
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:KL: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 'K':
331                         options.gss_authentication = 1;
332                         options.gss_deleg_creds = 1;
333                         break;
334                 case 'i':
335                         if (stat(optarg, &st) < 0) {
336                                 fprintf(stderr, "Warning: Identity file %s "
337                                     "not accessible: %s.\n", optarg,
338                                     strerror(errno));
339                                 break;
340                         }
341                         if (options.num_identity_files >=
342                             SSH_MAX_IDENTITY_FILES)
343                                 fatal("Too many identity files specified "
344                                     "(max %d)", SSH_MAX_IDENTITY_FILES);
345                         options.identity_files[options.num_identity_files++] =
346                             xstrdup(optarg);
347                         break;
348                 case 'I':
349 #ifdef SMARTCARD
350                         options.smartcard_device = xstrdup(optarg);
351 #else
352                         fprintf(stderr, "no support for smartcards.\n");
353 #endif
354                         break;
355                 case 't':
356                         if (tty_flag)
357                                 force_tty_flag = 1;
358                         tty_flag = 1;
359                         break;
360                 case 'v':
361                         if (debug_flag == 0) {
362                                 debug_flag = 1;
363                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
364                         } else {
365                                 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
366                                         options.log_level++;
367                                 break;
368                         }
369                         /* FALLTHROUGH */
370                 case 'V':
371                         fprintf(stderr, "%s, %s\n",
372                             SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
373                         if (opt == 'V')
374                                 exit(0);
375                         break;
376                 case 'w':
377                         if (options.tun_open == -1)
378                                 options.tun_open = SSH_TUNMODE_DEFAULT;
379                         options.tun_local = a2tun(optarg, &options.tun_remote);
380                         if (options.tun_local == SSH_TUNID_ERR) {
381                                 fprintf(stderr, "Bad tun device '%s'\n", optarg);
382                                 exit(255);
383                         }
384                         break;
385                 case 'q':
386                         options.log_level = SYSLOG_LEVEL_QUIET;
387                         break;
388                 case 'e':
389                         if (optarg[0] == '^' && optarg[2] == 0 &&
390                             (u_char) optarg[1] >= 64 &&
391                             (u_char) optarg[1] < 128)
392                                 options.escape_char = (u_char) optarg[1] & 31;
393                         else if (strlen(optarg) == 1)
394                                 options.escape_char = (u_char) optarg[0];
395                         else if (strcmp(optarg, "none") == 0)
396                                 options.escape_char = SSH_ESCAPECHAR_NONE;
397                         else {
398                                 fprintf(stderr, "Bad escape character '%s'.\n",
399                                     optarg);
400                                 exit(255);
401                         }
402                         break;
403                 case 'c':
404                         if (ciphers_valid(optarg)) {
405                                 /* SSH2 only */
406                                 options.ciphers = xstrdup(optarg);
407                                 options.cipher = SSH_CIPHER_INVALID;
408                         } else {
409                                 /* SSH1 only */
410                                 options.cipher = cipher_number(optarg);
411                                 if (options.cipher == -1) {
412                                         fprintf(stderr,
413                                             "Unknown cipher type '%s'\n",
414                                             optarg);
415                                         exit(255);
416                                 }
417                                 if (options.cipher == SSH_CIPHER_3DES)
418                                         options.ciphers = "3des-cbc";
419                                 else if (options.cipher == SSH_CIPHER_BLOWFISH)
420                                         options.ciphers = "blowfish-cbc";
421                                 else
422                                         options.ciphers = (char *)-1;
423                         }
424                         break;
425                 case 'm':
426                         if (mac_valid(optarg))
427                                 options.macs = xstrdup(optarg);
428                         else {
429                                 fprintf(stderr, "Unknown mac type '%s'\n",
430                                     optarg);
431                                 exit(255);
432                         }
433                         break;
434                 case 'M':
435                         if (options.control_master == SSHCTL_MASTER_YES)
436                                 options.control_master = SSHCTL_MASTER_ASK;
437                         else
438                                 options.control_master = SSHCTL_MASTER_YES;
439                         break;
440                 case 'p':
441                         options.port = a2port(optarg);
442                         if (options.port == 0) {
443                                 fprintf(stderr, "Bad port '%s'\n", optarg);
444                                 exit(255);
445                         }
446                         break;
447                 case 'l':
448                         options.user = optarg;
449                         break;
450
451                 case 'L':
452                         if (parse_forward(&fwd, optarg))
453                                 add_local_forward(&options, &fwd);
454                         else {
455                                 fprintf(stderr,
456                                     "Bad local forwarding specification '%s'\n",
457                                     optarg);
458                                 exit(255);
459                         }
460                         break;
461
462                 case 'R':
463                         if (parse_forward(&fwd, optarg)) {
464                                 add_remote_forward(&options, &fwd);
465                         } else {
466                                 fprintf(stderr,
467                                     "Bad remote forwarding specification "
468                                     "'%s'\n", optarg);
469                                 exit(255);
470                         }
471                         break;
472
473                 case 'D':
474                         cp = p = xstrdup(optarg);
475                         memset(&fwd, '\0', sizeof(fwd));
476                         fwd.connect_host = "socks";
477                         if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
478                                 fprintf(stderr, "Bad dynamic forwarding "
479                                     "specification '%.100s'\n", optarg);
480                                 exit(255);
481                         }
482                         if (cp != NULL) {
483                                 fwd.listen_port = a2port(cp);
484                                 fwd.listen_host = cleanhostname(fwd.listen_host);
485                         } else {
486                                 fwd.listen_port = a2port(fwd.listen_host);
487                                 fwd.listen_host = NULL;
488                         }
489
490                         if (fwd.listen_port == 0) {
491                                 fprintf(stderr, "Bad dynamic port '%s'\n",
492                                     optarg);
493                                 exit(255);
494                         }
495                         add_local_forward(&options, &fwd);
496                         xfree(p);
497                         break;
498
499                 case 'C':
500                         options.compression = 1;
501                         break;
502                 case 'N':
503                         no_shell_flag = 1;
504                         no_tty_flag = 1;
505                         break;
506                 case 'T':
507                         no_tty_flag = 1;
508                         break;
509                 case 'o':
510                         dummy = 1;
511                         line = xstrdup(optarg);
512                         if (process_config_line(&options, host ? host : "",
513                             line, "command-line", 0, &dummy) != 0)
514                                 exit(255);
515                         xfree(line);
516                         break;
517                 case 's':
518                         subsystem_flag = 1;
519                         break;
520                 case 'S':
521                         if (options.control_path != NULL)
522                                 free(options.control_path);
523                         options.control_path = xstrdup(optarg);
524                         break;
525                 case 'b':
526                         options.bind_address = optarg;
527                         break;
528                 case 'F':
529                         config = optarg;
530                         break;
531                 default:
532                         usage();
533                 }
534         }
535
536         ac -= optind;
537         av += optind;
538
539         if (ac > 0 && !host && **av != '-') {
540                 if (strrchr(*av, '@')) {
541                         p = xstrdup(*av);
542                         cp = strrchr(p, '@');
543                         if (cp == NULL || cp == p)
544                                 usage();
545                         options.user = p;
546                         *cp = '\0';
547                         host = ++cp;
548                 } else
549                         host = *av;
550                 if (ac > 1) {
551                         optind = optreset = 1;
552                         goto again;
553                 }
554                 ac--, av++;
555         }
556
557         /* Check that we got a host name. */
558         if (!host)
559                 usage();
560
561         SSLeay_add_all_algorithms();
562         ERR_load_crypto_strings();
563
564         /* Initialize the command to execute on remote host. */
565         buffer_init(&command);
566
567         /*
568          * Save the command to execute on the remote host in a buffer. There
569          * is no limit on the length of the command, except by the maximum
570          * packet size.  Also sets the tty flag if there is no command.
571          */
572         if (!ac) {
573                 /* No command specified - execute shell on a tty. */
574                 tty_flag = 1;
575                 if (subsystem_flag) {
576                         fprintf(stderr,
577                             "You must specify a subsystem to invoke.\n");
578                         usage();
579                 }
580         } else {
581                 /* A command has been specified.  Store it into the buffer. */
582                 for (i = 0; i < ac; i++) {
583                         if (i)
584                                 buffer_append(&command, " ", 1);
585                         buffer_append(&command, av[i], strlen(av[i]));
586                 }
587         }
588
589         /* Cannot fork to background if no command. */
590         if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
591                 fatal("Cannot fork into background without a command to execute.");
592
593         /* Allocate a tty by default if no command specified. */
594         if (buffer_len(&command) == 0)
595                 tty_flag = 1;
596
597         /* Force no tty */
598         if (no_tty_flag)
599                 tty_flag = 0;
600         /* Do not allocate a tty if stdin is not a tty. */
601         if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
602                 if (tty_flag)
603                         logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
604                 tty_flag = 0;
605         }
606
607         /*
608          * Initialize "log" output.  Since we are the client all output
609          * actually goes to stderr.
610          */
611         log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
612             SYSLOG_FACILITY_USER, 1);
613
614         /*
615          * Read per-user configuration file.  Ignore the system wide config
616          * file if the user specifies a config file on the command line.
617          */
618         if (config != NULL) {
619                 if (!read_config_file(config, host, &options, 0))
620                         fatal("Can't open user config file %.100s: "
621                             "%.100s", config, strerror(errno));
622         } else {
623                 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
624                     _PATH_SSH_USER_CONFFILE);
625                 (void)read_config_file(buf, host, &options, 1);
626
627                 /* Read systemwide configuration file after use config. */
628                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
629                     &options, 0);
630         }
631
632         /* Fill configuration defaults. */
633         fill_default_options(&options);
634
635         channel_set_af(options.address_family);
636
637         /* reinit */
638         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
639
640         seed_rng();
641
642         if (options.user == NULL)
643                 options.user = xstrdup(pw->pw_name);
644
645         if (options.hostname != NULL)
646                 host = options.hostname;
647
648         /* Find canonic host name. */
649         if (strchr(host, '.') == 0) {
650                 struct addrinfo hints;
651                 struct addrinfo *ai = NULL;
652                 int errgai;
653                 memset(&hints, 0, sizeof(hints));
654                 hints.ai_family = options.address_family;
655                 hints.ai_flags = AI_CANONNAME;
656                 hints.ai_socktype = SOCK_STREAM;
657                 errgai = getaddrinfo(host, NULL, &hints, &ai);
658                 if (errgai == 0) {
659                         if (ai->ai_canonname != NULL)
660                                 host = xstrdup(ai->ai_canonname);
661                         freeaddrinfo(ai);
662                 }
663         }
664
665         /* force lowercase for hostkey matching */
666         if (options.host_key_alias != NULL) {
667                 for (p = options.host_key_alias; *p; p++)
668                         if (isupper(*p))
669                                 *p = (char)tolower(*p);
670         }
671
672         /* Get default port if port has not been set. */
673         if (options.port == 0) {
674                 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
675                 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
676         }
677
678         if (options.proxy_command != NULL &&
679             strcmp(options.proxy_command, "none") == 0) {
680                 xfree(options.proxy_command);
681                 options.proxy_command = NULL;
682         }
683         if (options.control_path != NULL &&
684             strcmp(options.control_path, "none") == 0) {
685                 xfree(options.control_path);
686                 options.control_path = NULL;
687         }
688
689         if (options.control_path != NULL) {
690                 char thishost[NI_MAXHOST];
691
692                 if (gethostname(thishost, sizeof(thishost)) == -1)
693                         fatal("gethostname: %s", strerror(errno));
694                 snprintf(buf, sizeof(buf), "%d", options.port);
695                 cp = tilde_expand_filename(options.control_path,
696                     original_real_uid);
697                 xfree(options.control_path);
698                 options.control_path = percent_expand(cp, "p", buf, "h", host,
699                     "r", options.user, "l", thishost, (char *)NULL);
700                 xfree(cp);
701         }
702         if (mux_command != 0 && options.control_path == NULL)
703                 fatal("No ControlPath specified for \"-O\" command");
704         if (options.control_path != NULL)
705                 control_client(options.control_path);
706
707         timeout_ms = options.connection_timeout * 1000;
708
709         /* Open a connection to the remote host. */
710         if (ssh_connect(host, &hostaddr, options.port,
711             options.address_family, options.connection_attempts, &timeout_ms,
712             options.tcp_keep_alive, 
713 #ifdef HAVE_CYGWIN
714             options.use_privileged_port,
715 #else
716             original_effective_uid == 0 && options.use_privileged_port,
717 #endif
718             options.proxy_command) != 0)
719                 exit(255);
720
721         if (timeout_ms > 0)
722                 debug3("timeout: %d ms remain after connect", timeout_ms);
723
724         /*
725          * If we successfully made the connection, load the host private key
726          * in case we will need it later for combined rsa-rhosts
727          * authentication. This must be done before releasing extra
728          * privileges, because the file is only readable by root.
729          * If we cannot access the private keys, load the public keys
730          * instead and try to execute the ssh-keysign helper instead.
731          */
732         sensitive_data.nkeys = 0;
733         sensitive_data.keys = NULL;
734         sensitive_data.external_keysign = 0;
735         if (options.rhosts_rsa_authentication ||
736             options.hostbased_authentication) {
737                 sensitive_data.nkeys = 3;
738                 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
739                     sizeof(Key));
740
741                 PRIV_START;
742                 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
743                     _PATH_HOST_KEY_FILE, "", NULL, NULL);
744                 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
745                     _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
746                 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
747                     _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
748                 PRIV_END;
749
750                 if (options.hostbased_authentication == 1 &&
751                     sensitive_data.keys[0] == NULL &&
752                     sensitive_data.keys[1] == NULL &&
753                     sensitive_data.keys[2] == NULL) {
754                         sensitive_data.keys[1] = key_load_public(
755                             _PATH_HOST_DSA_KEY_FILE, NULL);
756                         sensitive_data.keys[2] = key_load_public(
757                             _PATH_HOST_RSA_KEY_FILE, NULL);
758                         sensitive_data.external_keysign = 1;
759                 }
760         }
761         /*
762          * Get rid of any extra privileges that we may have.  We will no
763          * longer need them.  Also, extra privileges could make it very hard
764          * to read identity files and other non-world-readable files from the
765          * user's home directory if it happens to be on a NFS volume where
766          * root is mapped to nobody.
767          */
768         if (original_effective_uid == 0) {
769                 PRIV_START;
770                 permanently_set_uid(pw);
771         }
772
773         /*
774          * Now that we are back to our own permissions, create ~/.ssh
775          * directory if it doesn't already exist.
776          */
777         snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
778         if (stat(buf, &st) < 0)
779                 if (mkdir(buf, 0700) < 0)
780                         error("Could not create directory '%.200s'.", buf);
781
782         /* load options.identity_files */
783         load_public_identity_files();
784
785         /* Expand ~ in known host file names. */
786         /* XXX mem-leaks: */
787         options.system_hostfile =
788             tilde_expand_filename(options.system_hostfile, original_real_uid);
789         options.user_hostfile =
790             tilde_expand_filename(options.user_hostfile, original_real_uid);
791         options.system_hostfile2 =
792             tilde_expand_filename(options.system_hostfile2, original_real_uid);
793         options.user_hostfile2 =
794             tilde_expand_filename(options.user_hostfile2, original_real_uid);
795
796         signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
797
798         /* Log into the remote system.  This never returns if the login fails. */
799         ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
800             pw, timeout_ms);
801
802         /* We no longer need the private host keys.  Clear them now. */
803         if (sensitive_data.nkeys != 0) {
804                 for (i = 0; i < sensitive_data.nkeys; i++) {
805                         if (sensitive_data.keys[i] != NULL) {
806                                 /* Destroys contents safely */
807                                 debug3("clear hostkey %d", i);
808                                 key_free(sensitive_data.keys[i]);
809                                 sensitive_data.keys[i] = NULL;
810                         }
811                 }
812                 xfree(sensitive_data.keys);
813         }
814         for (i = 0; i < options.num_identity_files; i++) {
815                 if (options.identity_files[i]) {
816                         xfree(options.identity_files[i]);
817                         options.identity_files[i] = NULL;
818                 }
819                 if (options.identity_keys[i]) {
820                         key_free(options.identity_keys[i]);
821                         options.identity_keys[i] = NULL;
822                 }
823         }
824
825         exit_status = compat20 ? ssh_session2() : ssh_session();
826         packet_close();
827
828         if (options.control_path != NULL && control_fd != -1)
829                 unlink(options.control_path);
830
831         /*
832          * Send SIGHUP to proxy command if used. We don't wait() in
833          * case it hangs and instead rely on init to reap the child
834          */
835         if (proxy_command_pid > 1)
836                 kill(proxy_command_pid, SIGHUP);
837
838         return exit_status;
839 }
840
841 static void
842 ssh_init_forwarding(void)
843 {
844         int success = 0;
845         int i;
846
847         /* Initiate local TCP/IP port forwardings. */
848         for (i = 0; i < options.num_local_forwards; i++) {
849                 debug("Local connections to %.200s:%d forwarded to remote "
850                     "address %.200s:%d",
851                     (options.local_forwards[i].listen_host == NULL) ?
852                     (options.gateway_ports ? "*" : "LOCALHOST") :
853                     options.local_forwards[i].listen_host,
854                     options.local_forwards[i].listen_port,
855                     options.local_forwards[i].connect_host,
856                     options.local_forwards[i].connect_port);
857                 success += channel_setup_local_fwd_listener(
858                     options.local_forwards[i].listen_host,
859                     options.local_forwards[i].listen_port,
860                     options.local_forwards[i].connect_host,
861                     options.local_forwards[i].connect_port,
862                     options.gateway_ports);
863         }
864         if (i > 0 && success != i && options.exit_on_forward_failure)
865                 fatal("Could not request local forwarding.");
866         if (i > 0 && success == 0)
867                 error("Could not request local forwarding.");
868
869         /* Initiate remote TCP/IP port forwardings. */
870         for (i = 0; i < options.num_remote_forwards; i++) {
871                 debug("Remote connections from %.200s:%d forwarded to "
872                     "local address %.200s:%d",
873                     (options.remote_forwards[i].listen_host == NULL) ?
874                     "LOCALHOST" : options.remote_forwards[i].listen_host,
875                     options.remote_forwards[i].listen_port,
876                     options.remote_forwards[i].connect_host,
877                     options.remote_forwards[i].connect_port);
878                 if (channel_request_remote_forwarding(
879                     options.remote_forwards[i].listen_host,
880                     options.remote_forwards[i].listen_port,
881                     options.remote_forwards[i].connect_host,
882                     options.remote_forwards[i].connect_port) < 0) {
883                         if (options.exit_on_forward_failure)
884                                 fatal("Could not request remote forwarding.");
885                         else
886                                 logit("Warning: Could not request remote "
887                                     "forwarding.");
888                 }
889         }
890
891         /* Initiate tunnel forwarding. */
892         if (options.tun_open != SSH_TUNMODE_NO) {
893                 if (client_request_tun_fwd(options.tun_open,
894                     options.tun_local, options.tun_remote) == -1) {
895                         if (options.exit_on_forward_failure)
896                                 fatal("Could not request tunnel forwarding.");
897                         else
898                                 error("Could not request tunnel forwarding.");
899                 }
900         }                       
901 }
902
903 static void
904 check_agent_present(void)
905 {
906         if (options.forward_agent) {
907                 /* Clear agent forwarding if we don't have an agent. */
908                 if (!ssh_agent_present())
909                         options.forward_agent = 0;
910         }
911 }
912
913 static int
914 ssh_session(void)
915 {
916         int type;
917         int interactive = 0;
918         int have_tty = 0;
919         struct winsize ws;
920         char *cp;
921         const char *display;
922
923         /* Enable compression if requested. */
924         if (options.compression) {
925                 debug("Requesting compression at level %d.", options.compression_level);
926
927                 if (options.compression_level < 1 || options.compression_level > 9)
928                         fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
929
930                 /* Send the request. */
931                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
932                 packet_put_int(options.compression_level);
933                 packet_send();
934                 packet_write_wait();
935                 type = packet_read();
936                 if (type == SSH_SMSG_SUCCESS)
937                         packet_start_compression(options.compression_level);
938                 else if (type == SSH_SMSG_FAILURE)
939                         logit("Warning: Remote host refused compression.");
940                 else
941                         packet_disconnect("Protocol error waiting for compression response.");
942         }
943         /* Allocate a pseudo tty if appropriate. */
944         if (tty_flag) {
945                 debug("Requesting pty.");
946
947                 /* Start the packet. */
948                 packet_start(SSH_CMSG_REQUEST_PTY);
949
950                 /* Store TERM in the packet.  There is no limit on the
951                    length of the string. */
952                 cp = getenv("TERM");
953                 if (!cp)
954                         cp = "";
955                 packet_put_cstring(cp);
956
957                 /* Store window size in the packet. */
958                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
959                         memset(&ws, 0, sizeof(ws));
960                 packet_put_int((u_int)ws.ws_row);
961                 packet_put_int((u_int)ws.ws_col);
962                 packet_put_int((u_int)ws.ws_xpixel);
963                 packet_put_int((u_int)ws.ws_ypixel);
964
965                 /* Store tty modes in the packet. */
966                 tty_make_modes(fileno(stdin), NULL);
967
968                 /* Send the packet, and wait for it to leave. */
969                 packet_send();
970                 packet_write_wait();
971
972                 /* Read response from the server. */
973                 type = packet_read();
974                 if (type == SSH_SMSG_SUCCESS) {
975                         interactive = 1;
976                         have_tty = 1;
977                 } else if (type == SSH_SMSG_FAILURE)
978                         logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
979                 else
980                         packet_disconnect("Protocol error waiting for pty request response.");
981         }
982         /* Request X11 forwarding if enabled and DISPLAY is set. */
983         display = getenv("DISPLAY");
984         if (options.forward_x11 && display != NULL) {
985                 char *proto, *data;
986                 /* Get reasonable local authentication information. */
987                 client_x11_get_proto(display, options.xauth_location,
988                     options.forward_x11_trusted, &proto, &data);
989                 /* Request forwarding with authentication spoofing. */
990                 debug("Requesting X11 forwarding with authentication spoofing.");
991                 x11_request_forwarding_with_spoofing(0, display, proto, data);
992
993                 /* Read response from the server. */
994                 type = packet_read();
995                 if (type == SSH_SMSG_SUCCESS) {
996                         interactive = 1;
997                 } else if (type == SSH_SMSG_FAILURE) {
998                         logit("Warning: Remote host denied X11 forwarding.");
999                 } else {
1000                         packet_disconnect("Protocol error waiting for X11 forwarding");
1001                 }
1002         }
1003         /* Tell the packet module whether this is an interactive session. */
1004         packet_set_interactive(interactive);
1005
1006         /* Request authentication agent forwarding if appropriate. */
1007         check_agent_present();
1008
1009         if (options.forward_agent) {
1010                 debug("Requesting authentication agent forwarding.");
1011                 auth_request_forwarding();
1012
1013                 /* Read response from the server. */
1014                 type = packet_read();
1015                 packet_check_eom();
1016                 if (type != SSH_SMSG_SUCCESS)
1017                         logit("Warning: Remote host denied authentication agent forwarding.");
1018         }
1019
1020         /* Initiate port forwardings. */
1021         ssh_init_forwarding();
1022
1023         /* Execute a local command */
1024         if (options.local_command != NULL &&
1025             options.permit_local_command)
1026                 ssh_local_cmd(options.local_command);
1027
1028         /* If requested, let ssh continue in the background. */
1029         if (fork_after_authentication_flag)
1030                 if (daemon(1, 1) < 0)
1031                         fatal("daemon() failed: %.200s", strerror(errno));
1032
1033         /*
1034          * If a command was specified on the command line, execute the
1035          * command now. Otherwise request the server to start a shell.
1036          */
1037         if (buffer_len(&command) > 0) {
1038                 int len = buffer_len(&command);
1039                 if (len > 900)
1040                         len = 900;
1041                 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1042                 packet_start(SSH_CMSG_EXEC_CMD);
1043                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1044                 packet_send();
1045                 packet_write_wait();
1046         } else {
1047                 debug("Requesting shell.");
1048                 packet_start(SSH_CMSG_EXEC_SHELL);
1049                 packet_send();
1050                 packet_write_wait();
1051         }
1052
1053         /* Enter the interactive session. */
1054         return client_loop(have_tty, tty_flag ?
1055             options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1056 }
1057
1058 static void
1059 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1060 {
1061         int id, len;
1062
1063         id = packet_get_int();
1064         len = buffer_len(&command);
1065         if (len > 900)
1066                 len = 900;
1067         packet_check_eom();
1068         if (type == SSH2_MSG_CHANNEL_FAILURE)
1069                 fatal("Request for subsystem '%.*s' failed on channel %d",
1070                     len, (u_char *)buffer_ptr(&command), id);
1071 }
1072
1073 void
1074 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1075 {
1076         int i;
1077
1078         i = client_global_request_id++;
1079         if (i >= options.num_remote_forwards)
1080                 return;
1081         debug("remote forward %s for: listen %d, connect %s:%d",
1082             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1083             options.remote_forwards[i].listen_port,
1084             options.remote_forwards[i].connect_host,
1085             options.remote_forwards[i].connect_port);
1086         if (type == SSH2_MSG_REQUEST_FAILURE) {
1087                 if (options.exit_on_forward_failure)
1088                         fatal("Error: remote port forwarding failed for "
1089                             "listen port %d",
1090                             options.remote_forwards[i].listen_port);
1091                 else
1092                         logit("Warning: remote port forwarding failed for "
1093                             "listen port %d",
1094                             options.remote_forwards[i].listen_port);
1095         }
1096 }
1097
1098 static void
1099 ssh_control_listener(void)
1100 {
1101         struct sockaddr_un addr;
1102         mode_t old_umask;
1103         int addr_len;
1104
1105         if (options.control_path == NULL ||
1106             options.control_master == SSHCTL_MASTER_NO)
1107                 return;
1108
1109         debug("setting up multiplex master socket");
1110
1111         memset(&addr, '\0', sizeof(addr));
1112         addr.sun_family = AF_UNIX;
1113         addr_len = offsetof(struct sockaddr_un, sun_path) +
1114             strlen(options.control_path) + 1;
1115
1116         if (strlcpy(addr.sun_path, options.control_path,
1117             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1118                 fatal("ControlPath too long");
1119
1120         if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1121                 fatal("%s socket(): %s", __func__, strerror(errno));
1122
1123         old_umask = umask(0177);
1124         if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1125                 control_fd = -1;
1126                 if (errno == EINVAL || errno == EADDRINUSE)
1127                         fatal("ControlSocket %s already exists",
1128                             options.control_path);
1129                 else
1130                         fatal("%s bind(): %s", __func__, strerror(errno));
1131         }
1132         umask(old_umask);
1133
1134         if (listen(control_fd, 64) == -1)
1135                 fatal("%s listen(): %s", __func__, strerror(errno));
1136
1137         set_nonblock(control_fd);
1138 }
1139
1140 /* request pty/x11/agent/tcpfwd/shell for channel */
1141 static void
1142 ssh_session2_setup(int id, void *arg)
1143 {
1144         extern char **environ;
1145         const char *display;
1146         int interactive = tty_flag;
1147
1148         display = getenv("DISPLAY");
1149         if (options.forward_x11 && display != NULL) {
1150                 char *proto, *data;
1151                 /* Get reasonable local authentication information. */
1152                 client_x11_get_proto(display, options.xauth_location,
1153                     options.forward_x11_trusted, &proto, &data);
1154                 /* Request forwarding with authentication spoofing. */
1155                 debug("Requesting X11 forwarding with authentication spoofing.");
1156                 x11_request_forwarding_with_spoofing(id, display, proto, data);
1157                 interactive = 1;
1158                 /* XXX wait for reply */
1159         }
1160
1161         check_agent_present();
1162         if (options.forward_agent) {
1163                 debug("Requesting authentication agent forwarding.");
1164                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1165                 packet_send();
1166         }
1167
1168         client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1169             NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1170
1171         packet_set_interactive(interactive);
1172 }
1173
1174 /* open new channel for a session */
1175 static int
1176 ssh_session2_open(void)
1177 {
1178         Channel *c;
1179         int window, packetmax, in, out, err;
1180
1181         if (stdin_null_flag) {
1182                 in = open(_PATH_DEVNULL, O_RDONLY);
1183         } else {
1184                 in = dup(STDIN_FILENO);
1185         }
1186         out = dup(STDOUT_FILENO);
1187         err = dup(STDERR_FILENO);
1188
1189         if (in < 0 || out < 0 || err < 0)
1190                 fatal("dup() in/out/err failed");
1191
1192         /* enable nonblocking unless tty */
1193         if (!isatty(in))
1194                 set_nonblock(in);
1195         if (!isatty(out))
1196                 set_nonblock(out);
1197         if (!isatty(err))
1198                 set_nonblock(err);
1199
1200         window = CHAN_SES_WINDOW_DEFAULT;
1201         packetmax = CHAN_SES_PACKET_DEFAULT;
1202         if (tty_flag) {
1203                 window >>= 1;
1204                 packetmax >>= 1;
1205         }
1206         c = channel_new(
1207             "session", SSH_CHANNEL_OPENING, in, out, err,
1208             window, packetmax, CHAN_EXTENDED_WRITE,
1209             "client-session", /*nonblock*/0);
1210
1211         debug3("ssh_session2_open: channel_new: %d", c->self);
1212
1213         channel_send_open(c->self);
1214         if (!no_shell_flag)
1215                 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1216
1217         return c->self;
1218 }
1219
1220 static int
1221 ssh_session2(void)
1222 {
1223         int id = -1;
1224
1225         /* XXX should be pre-session */
1226         ssh_init_forwarding();
1227
1228         if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1229                 id = ssh_session2_open();
1230
1231         /* Execute a local command */
1232         if (options.local_command != NULL &&
1233             options.permit_local_command)
1234                 ssh_local_cmd(options.local_command);
1235
1236         /* Start listening for multiplex clients */
1237         ssh_control_listener();
1238
1239         /* If requested, let ssh continue in the background. */
1240         if (fork_after_authentication_flag)
1241                 if (daemon(1, 1) < 0)
1242                         fatal("daemon() failed: %.200s", strerror(errno));
1243
1244         return client_loop(tty_flag, tty_flag ?
1245             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1246 }
1247
1248 static void
1249 load_public_identity_files(void)
1250 {
1251         char *filename, *cp, thishost[NI_MAXHOST];
1252         char *pwdir = NULL, *pwname = NULL;
1253         int i = 0;
1254         Key *public;
1255         struct passwd *pw;
1256 #ifdef SMARTCARD
1257         Key **keys;
1258
1259         if (options.smartcard_device != NULL &&
1260             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1261             (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1262                 int count = 0;
1263                 for (i = 0; keys[i] != NULL; i++) {
1264                         count++;
1265                         memmove(&options.identity_files[1], &options.identity_files[0],
1266                             sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1267                         memmove(&options.identity_keys[1], &options.identity_keys[0],
1268                             sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1269                         options.num_identity_files++;
1270                         options.identity_keys[0] = keys[i];
1271                         options.identity_files[0] = sc_get_key_label(keys[i]);
1272                 }
1273                 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1274                         options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1275                 i = count;
1276                 xfree(keys);
1277         }
1278 #endif /* SMARTCARD */
1279         if ((pw = getpwuid(original_real_uid)) == NULL)
1280                 fatal("load_public_identity_files: getpwuid failed");
1281         pwname = xstrdup(pw->pw_name);
1282         pwdir = xstrdup(pw->pw_dir);
1283         if (gethostname(thishost, sizeof(thishost)) == -1)
1284                 fatal("load_public_identity_files: gethostname: %s",
1285                     strerror(errno));
1286         for (; i < options.num_identity_files; i++) {
1287                 cp = tilde_expand_filename(options.identity_files[i],
1288                     original_real_uid);
1289                 filename = percent_expand(cp, "d", pwdir,
1290                     "u", pwname, "l", thishost, "h", host,
1291                     "r", options.user, (char *)NULL);
1292                 xfree(cp);
1293                 public = key_load_public(filename, NULL);
1294                 debug("identity file %s type %d", filename,
1295                     public ? public->type : -1);
1296                 xfree(options.identity_files[i]);
1297                 options.identity_files[i] = filename;
1298                 options.identity_keys[i] = public;
1299         }
1300         bzero(pwname, strlen(pwname));
1301         xfree(pwname);
1302         bzero(pwdir, strlen(pwdir));
1303         xfree(pwdir);
1304 }
1305
1306 static void
1307 control_client_sighandler(int signo)
1308 {
1309         control_client_terminate = signo;
1310 }
1311
1312 static void
1313 control_client_sigrelay(int signo)
1314 {
1315         int save_errno = errno;
1316
1317         if (control_server_pid > 1)
1318                 kill(control_server_pid, signo);
1319
1320         errno = save_errno;
1321 }
1322
1323 static int
1324 env_permitted(char *env)
1325 {
1326         int i, ret;
1327         char name[1024], *cp;
1328
1329         if ((cp = strchr(env, '=')) == NULL || cp == env)
1330                 return (0);
1331         ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1332         if (ret <= 0 || (size_t)ret >= sizeof(name))
1333                 fatal("env_permitted: name '%.100s...' too long", env);
1334
1335         for (i = 0; i < options.num_send_env; i++)
1336                 if (match_pattern(name, options.send_env[i]))
1337                         return (1);
1338
1339         return (0);
1340 }
1341
1342 static void
1343 control_client(const char *path)
1344 {
1345         struct sockaddr_un addr;
1346         int i, r, fd, sock, exitval[2], num_env, addr_len;
1347         Buffer m;
1348         char *term;
1349         extern char **environ;
1350         u_int  flags;
1351
1352         if (mux_command == 0)
1353                 mux_command = SSHMUX_COMMAND_OPEN;
1354
1355         switch (options.control_master) {
1356         case SSHCTL_MASTER_AUTO:
1357         case SSHCTL_MASTER_AUTO_ASK:
1358                 debug("auto-mux: Trying existing master");
1359                 /* FALLTHROUGH */
1360         case SSHCTL_MASTER_NO:
1361                 break;
1362         default:
1363                 return;
1364         }
1365
1366         memset(&addr, '\0', sizeof(addr));
1367         addr.sun_family = AF_UNIX;
1368         addr_len = offsetof(struct sockaddr_un, sun_path) +
1369             strlen(path) + 1;
1370
1371         if (strlcpy(addr.sun_path, path,
1372             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1373                 fatal("ControlPath too long");
1374
1375         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1376                 fatal("%s socket(): %s", __func__, strerror(errno));
1377
1378         if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1379                 if (mux_command != SSHMUX_COMMAND_OPEN) {
1380                         fatal("Control socket connect(%.100s): %s", path,
1381                             strerror(errno));
1382                 }
1383                 if (errno == ENOENT)
1384                         debug("Control socket \"%.100s\" does not exist", path);
1385                 else {
1386                         error("Control socket connect(%.100s): %s", path,
1387                             strerror(errno));
1388                 }
1389                 close(sock);
1390                 return;
1391         }
1392
1393         if (stdin_null_flag) {
1394                 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1395                         fatal("open(/dev/null): %s", strerror(errno));
1396                 if (dup2(fd, STDIN_FILENO) == -1)
1397                         fatal("dup2: %s", strerror(errno));
1398                 if (fd > STDERR_FILENO)
1399                         close(fd);
1400         }
1401
1402         term = getenv("TERM");
1403
1404         flags = 0;
1405         if (tty_flag)
1406                 flags |= SSHMUX_FLAG_TTY;
1407         if (subsystem_flag)
1408                 flags |= SSHMUX_FLAG_SUBSYS;
1409         if (options.forward_x11)
1410                 flags |= SSHMUX_FLAG_X11_FWD;
1411         if (options.forward_agent)
1412                 flags |= SSHMUX_FLAG_AGENT_FWD;
1413
1414         signal(SIGPIPE, SIG_IGN);
1415
1416         buffer_init(&m);
1417
1418         /* Send our command to server */
1419         buffer_put_int(&m, mux_command);
1420         buffer_put_int(&m, flags);
1421         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1422                 fatal("%s: msg_send", __func__);
1423         buffer_clear(&m);
1424
1425         /* Get authorisation status and PID of controlee */
1426         if (ssh_msg_recv(sock, &m) == -1)
1427                 fatal("%s: msg_recv", __func__);
1428         if (buffer_get_char(&m) != SSHMUX_VER)
1429                 fatal("%s: wrong version", __func__);
1430         if (buffer_get_int(&m) != 1)
1431                 fatal("Connection to master denied");
1432         control_server_pid = buffer_get_int(&m);
1433
1434         buffer_clear(&m);
1435
1436         switch (mux_command) {
1437         case SSHMUX_COMMAND_ALIVE_CHECK:
1438                 fprintf(stderr, "Master running (pid=%d)\r\n",
1439                     control_server_pid);
1440                 exit(0);
1441         case SSHMUX_COMMAND_TERMINATE:
1442                 fprintf(stderr, "Exit request sent.\r\n");
1443                 exit(0);
1444         case SSHMUX_COMMAND_OPEN:
1445                 /* continue below */
1446                 break;
1447         default:
1448                 fatal("silly mux_command %d", mux_command);
1449         }
1450
1451         /* SSHMUX_COMMAND_OPEN */
1452         buffer_put_cstring(&m, term ? term : "");
1453         buffer_append(&command, "\0", 1);
1454         buffer_put_cstring(&m, buffer_ptr(&command));
1455
1456         if (options.num_send_env == 0 || environ == NULL) {
1457                 buffer_put_int(&m, 0);
1458         } else {
1459                 /* Pass environment */
1460                 num_env = 0;
1461                 for (i = 0; environ[i] != NULL; i++)
1462                         if (env_permitted(environ[i]))
1463                                 num_env++; /* Count */
1464
1465                 buffer_put_int(&m, num_env);
1466
1467                 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1468                         if (env_permitted(environ[i])) {
1469                                 num_env--;
1470                                 buffer_put_cstring(&m, environ[i]);
1471                         }
1472         }
1473
1474         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1475                 fatal("%s: msg_send", __func__);
1476
1477         if (mm_send_fd(sock, STDIN_FILENO) == -1 ||
1478             mm_send_fd(sock, STDOUT_FILENO) == -1 ||
1479             mm_send_fd(sock, STDERR_FILENO) == -1)
1480                 fatal("%s: send fds failed", __func__);
1481
1482         /* Wait for reply, so master has a chance to gather ttymodes */
1483         buffer_clear(&m);
1484         if (ssh_msg_recv(sock, &m) == -1)
1485                 fatal("%s: msg_recv", __func__);
1486         if (buffer_get_char(&m) != SSHMUX_VER)
1487                 fatal("%s: wrong version", __func__);
1488         buffer_free(&m);
1489
1490         signal(SIGHUP, control_client_sighandler);
1491         signal(SIGINT, control_client_sighandler);
1492         signal(SIGTERM, control_client_sighandler);
1493         signal(SIGWINCH, control_client_sigrelay);
1494
1495         if (tty_flag)
1496                 enter_raw_mode();
1497
1498         /*
1499          * Stick around until the controlee closes the client_fd.
1500          * Before it does, it is expected to write this process' exit
1501          * value (one int). This process must read the value and wait for
1502          * the closure of the client_fd; if this one closes early, the 
1503          * multiplex master will terminate early too (possibly losing data).
1504          */
1505         exitval[0] = 0;
1506         for (i = 0; !control_client_terminate && i < (int)sizeof(exitval);) {
1507                 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
1508                 if (r == 0) {
1509                         debug2("Received EOF from master");
1510                         break;
1511                 }
1512                 if (r == -1) {
1513                         if (errno == EINTR)
1514                                 continue;
1515                         fatal("%s: read %s", __func__, strerror(errno));
1516                 }
1517                 i += r;
1518         }
1519
1520         close(sock);
1521         leave_raw_mode();
1522         if (i > (int)sizeof(int))
1523                 fatal("%s: master returned too much data (%d > %lu)",
1524                     __func__, i, sizeof(int));
1525         if (control_client_terminate) {
1526                 debug2("Exiting on signal %d", control_client_terminate);
1527                 exitval[0] = 255;
1528         } else if (i < (int)sizeof(int)) {
1529                 debug2("Control master terminated unexpectedly");
1530                 exitval[0] = 255;
1531         } else
1532                 debug2("Received exit status from master %d", exitval[0]);
1533
1534         if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1535                 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1536
1537         exit(exitval[0]);
1538 }