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