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