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