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