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