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