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