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