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