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