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