]> andersk Git - gssapi-openssh.git/blob - openssh/ssh.c
7a7adc00ebc8425c81561e7e80100df20a1f1e27
[gssapi-openssh.git] / openssh / 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                         /* ensure that the user doesn't try to backdoor a */
509                         /* null cipher switch on an interactive session */
510                         /* so explicitly disable it no matter what */
511                         options.none_switch=0;
512                         break;
513                 case 'o':
514                         dummy = 1;
515                         line = xstrdup(optarg);
516                         if (process_config_line(&options, host ? host : "",
517                             line, "command-line", 0, &dummy) != 0)
518                                 exit(255);
519                         xfree(line);
520                         break;
521                 case 's':
522                         subsystem_flag = 1;
523                         break;
524                 case 'S':
525                         if (options.control_path != NULL)
526                                 free(options.control_path);
527                         options.control_path = xstrdup(optarg);
528                         break;
529                 case 'b':
530                         options.bind_address = optarg;
531                         break;
532                 case 'F':
533                         config = optarg;
534                         break;
535                 default:
536                         usage();
537                 }
538         }
539
540         ac -= optind;
541         av += optind;
542
543         if (ac > 0 && !host && **av != '-') {
544                 if (strrchr(*av, '@')) {
545                         p = xstrdup(*av);
546                         cp = strrchr(p, '@');
547                         if (cp == NULL || cp == p)
548                                 usage();
549                         options.user = p;
550                         *cp = '\0';
551                         host = ++cp;
552                 } else
553                         host = *av;
554                 if (ac > 1) {
555                         optind = optreset = 1;
556                         goto again;
557                 }
558                 ac--, av++;
559         }
560
561         /* Check that we got a host name. */
562         if (!host)
563                 usage();
564
565         SSLeay_add_all_algorithms();
566         ERR_load_crypto_strings();
567
568         /* Initialize the command to execute on remote host. */
569         buffer_init(&command);
570
571         /*
572          * Save the command to execute on the remote host in a buffer. There
573          * is no limit on the length of the command, except by the maximum
574          * packet size.  Also sets the tty flag if there is no command.
575          */
576         if (!ac) {
577                 /* No command specified - execute shell on a tty. */
578                 tty_flag = 1;
579                 if (subsystem_flag) {
580                         fprintf(stderr,
581                             "You must specify a subsystem to invoke.\n");
582                         usage();
583                 }
584         } else {
585                 /* A command has been specified.  Store it into the buffer. */
586                 for (i = 0; i < ac; i++) {
587                         if (i)
588                                 buffer_append(&command, " ", 1);
589                         buffer_append(&command, av[i], strlen(av[i]));
590                 }
591         }
592
593         /* Cannot fork to background if no command. */
594         if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
595                 fatal("Cannot fork into background without a command to execute.");
596
597         /* Allocate a tty by default if no command specified. */
598         if (buffer_len(&command) == 0)
599                 tty_flag = 1;
600
601         /* Force no tty */
602         if (no_tty_flag)
603                 tty_flag = 0;
604         /* Do not allocate a tty if stdin is not a tty. */
605         if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
606                 if (tty_flag)
607                         logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
608                 tty_flag = 0;
609         }
610
611         /*
612          * Initialize "log" output.  Since we are the client all output
613          * actually goes to stderr.
614          */
615         log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
616             SYSLOG_FACILITY_USER, 1);
617
618         /*
619          * Read per-user configuration file.  Ignore the system wide config
620          * file if the user specifies a config file on the command line.
621          */
622         if (config != NULL) {
623                 if (!read_config_file(config, host, &options, 0))
624                         fatal("Can't open user config file %.100s: "
625                             "%.100s", config, strerror(errno));
626         } else {
627             /*
628              * Since the config file parsing code aborts if it sees
629              * options it doesn't recognize, allow users to put
630              * options specific to compile-time add-ons in alternate
631              * config files so their primary config file will
632              * interoperate SSH versions that don't support those
633              * options.
634              */
635 #ifdef GSSAPI
636                 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
637                     _PATH_SSH_USER_CONFFILE);
638                 (void)read_config_file(buf, host, &options, 1);
639 #ifdef GSI
640                 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
641                     _PATH_SSH_USER_CONFFILE);
642                 (void)read_config_file(buf, host, &options, 1);
643 #endif
644 #if defined(KRB5)
645                 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
646                     _PATH_SSH_USER_CONFFILE);
647                 (void)read_config_file(buf, host, &options, 1);
648 #endif
649 #endif
650                 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
651                     _PATH_SSH_USER_CONFFILE);
652                 (void)read_config_file(buf, host, &options, 1);
653
654                 /* Read systemwide configuration file after use config. */
655                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
656                     &options, 0);
657         }
658
659         /* Fill configuration defaults. */
660         fill_default_options(&options);
661
662         channel_set_af(options.address_family);
663
664         /* reinit */
665         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
666
667         seed_rng();
668
669         if (options.user == NULL) {
670                 options.user = xstrdup(pw->pw_name);
671                 options.implicit = 1;
672         }
673         else options.implicit = 0;
674
675         if (options.hostname != NULL)
676                 host = options.hostname;
677
678         /* force lowercase for hostkey matching */
679         if (options.host_key_alias != NULL) {
680                 for (p = options.host_key_alias; *p; p++)
681                         if (isupper(*p))
682                                 *p = (char)tolower(*p);
683         }
684
685         /* Get default port if port has not been set. */
686         if (options.port == 0) {
687                 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
688                 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
689         }
690
691         if (options.proxy_command != NULL &&
692             strcmp(options.proxy_command, "none") == 0) {
693                 xfree(options.proxy_command);
694                 options.proxy_command = NULL;
695         }
696         if (options.control_path != NULL &&
697             strcmp(options.control_path, "none") == 0) {
698                 xfree(options.control_path);
699                 options.control_path = NULL;
700         }
701
702         if (options.control_path != NULL) {
703                 char thishost[NI_MAXHOST];
704
705                 if (gethostname(thishost, sizeof(thishost)) == -1)
706                         fatal("gethostname: %s", strerror(errno));
707                 snprintf(buf, sizeof(buf), "%d", options.port);
708                 cp = tilde_expand_filename(options.control_path,
709                     original_real_uid);
710                 xfree(options.control_path);
711                 options.control_path = percent_expand(cp, "p", buf, "h", host,
712                     "r", options.user, "l", thishost, (char *)NULL);
713                 xfree(cp);
714         }
715         if (mux_command != 0 && options.control_path == NULL)
716                 fatal("No ControlPath specified for \"-O\" command");
717         if (options.control_path != NULL)
718                 control_client(options.control_path);
719
720         timeout_ms = options.connection_timeout * 1000;
721
722         /* Open a connection to the remote host. */
723         if (ssh_connect(host, &hostaddr, options.port,
724             options.address_family, options.connection_attempts, &timeout_ms,
725             options.tcp_keep_alive, 
726 #ifdef HAVE_CYGWIN
727             options.use_privileged_port,
728 #else
729             original_effective_uid == 0 && options.use_privileged_port,
730 #endif
731             options.proxy_command) != 0)
732                 exit(255);
733
734         if (timeout_ms > 0)
735                 debug3("timeout: %d ms remain after connect", timeout_ms);
736
737         /*
738          * If we successfully made the connection, load the host private key
739          * in case we will need it later for combined rsa-rhosts
740          * authentication. This must be done before releasing extra
741          * privileges, because the file is only readable by root.
742          * If we cannot access the private keys, load the public keys
743          * instead and try to execute the ssh-keysign helper instead.
744          */
745         sensitive_data.nkeys = 0;
746         sensitive_data.keys = NULL;
747         sensitive_data.external_keysign = 0;
748         if (options.rhosts_rsa_authentication ||
749             options.hostbased_authentication) {
750                 sensitive_data.nkeys = 3;
751                 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
752                     sizeof(Key));
753
754                 PRIV_START;
755                 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
756                     _PATH_HOST_KEY_FILE, "", NULL, NULL);
757                 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
758                     _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
759                 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
760                     _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
761                 PRIV_END;
762
763                 if (options.hostbased_authentication == 1 &&
764                     sensitive_data.keys[0] == NULL &&
765                     sensitive_data.keys[1] == NULL &&
766                     sensitive_data.keys[2] == NULL) {
767                         sensitive_data.keys[1] = key_load_public(
768                             _PATH_HOST_DSA_KEY_FILE, NULL);
769                         sensitive_data.keys[2] = key_load_public(
770                             _PATH_HOST_RSA_KEY_FILE, NULL);
771                         sensitive_data.external_keysign = 1;
772                 }
773         }
774         /*
775          * Get rid of any extra privileges that we may have.  We will no
776          * longer need them.  Also, extra privileges could make it very hard
777          * to read identity files and other non-world-readable files from the
778          * user's home directory if it happens to be on a NFS volume where
779          * root is mapped to nobody.
780          */
781         if (original_effective_uid == 0) {
782                 PRIV_START;
783                 permanently_set_uid(pw);
784         }
785
786         /*
787          * Now that we are back to our own permissions, create ~/.ssh
788          * directory if it doesn't already exist.
789          */
790         snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
791         if (stat(buf, &st) < 0)
792                 if (mkdir(buf, 0700) < 0)
793                         error("Could not create directory '%.200s'.", buf);
794
795         /* load options.identity_files */
796         load_public_identity_files();
797
798         /* Expand ~ in known host file names. */
799         /* XXX mem-leaks: */
800         options.system_hostfile =
801             tilde_expand_filename(options.system_hostfile, original_real_uid);
802         options.user_hostfile =
803             tilde_expand_filename(options.user_hostfile, original_real_uid);
804         options.system_hostfile2 =
805             tilde_expand_filename(options.system_hostfile2, original_real_uid);
806         options.user_hostfile2 =
807             tilde_expand_filename(options.user_hostfile2, original_real_uid);
808
809         signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
810
811         /* Log into the remote system.  This never returns if the login fails. */
812         ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
813             pw, timeout_ms);
814
815         /* We no longer need the private host keys.  Clear them now. */
816         if (sensitive_data.nkeys != 0) {
817                 for (i = 0; i < sensitive_data.nkeys; i++) {
818                         if (sensitive_data.keys[i] != NULL) {
819                                 /* Destroys contents safely */
820                                 debug3("clear hostkey %d", i);
821                                 key_free(sensitive_data.keys[i]);
822                                 sensitive_data.keys[i] = NULL;
823                         }
824                 }
825                 xfree(sensitive_data.keys);
826         }
827         for (i = 0; i < options.num_identity_files; i++) {
828                 if (options.identity_files[i]) {
829                         xfree(options.identity_files[i]);
830                         options.identity_files[i] = NULL;
831                 }
832                 if (options.identity_keys[i]) {
833                         key_free(options.identity_keys[i]);
834                         options.identity_keys[i] = NULL;
835                 }
836         }
837
838         exit_status = compat20 ? ssh_session2() : ssh_session();
839         packet_close();
840
841         if (options.control_path != NULL && control_fd != -1)
842                 unlink(options.control_path);
843
844         /*
845          * Send SIGHUP to proxy command if used. We don't wait() in
846          * case it hangs and instead rely on init to reap the child
847          */
848         if (proxy_command_pid > 1)
849                 kill(proxy_command_pid, SIGHUP);
850
851         return exit_status;
852 }
853
854 static void
855 ssh_init_forwarding(void)
856 {
857         int success = 0;
858         int i;
859
860         /* Initiate local TCP/IP port forwardings. */
861         for (i = 0; i < options.num_local_forwards; i++) {
862                 debug("Local connections to %.200s:%d forwarded to remote "
863                     "address %.200s:%d",
864                     (options.local_forwards[i].listen_host == NULL) ?
865                     (options.gateway_ports ? "*" : "LOCALHOST") :
866                     options.local_forwards[i].listen_host,
867                     options.local_forwards[i].listen_port,
868                     options.local_forwards[i].connect_host,
869                     options.local_forwards[i].connect_port);
870                 success += channel_setup_local_fwd_listener(
871                     options.local_forwards[i].listen_host,
872                     options.local_forwards[i].listen_port,
873                     options.local_forwards[i].connect_host,
874                     options.local_forwards[i].connect_port,
875                     options.gateway_ports, options.hpn_disabled,
876                     options.hpn_buffer_size);
877         }
878         if (i > 0 && success != i && options.exit_on_forward_failure)
879                 fatal("Could not request local forwarding.");
880         if (i > 0 && success == 0)
881                 error("Could not request local forwarding.");
882
883         /* Initiate remote TCP/IP port forwardings. */
884         for (i = 0; i < options.num_remote_forwards; i++) {
885                 debug("Remote connections from %.200s:%d forwarded to "
886                     "local address %.200s:%d",
887                     (options.remote_forwards[i].listen_host == NULL) ?
888                     "LOCALHOST" : options.remote_forwards[i].listen_host,
889                     options.remote_forwards[i].listen_port,
890                     options.remote_forwards[i].connect_host,
891                     options.remote_forwards[i].connect_port);
892                 if (channel_request_remote_forwarding(
893                     options.remote_forwards[i].listen_host,
894                     options.remote_forwards[i].listen_port,
895                     options.remote_forwards[i].connect_host,
896                     options.remote_forwards[i].connect_port) < 0) {
897                         if (options.exit_on_forward_failure)
898                                 fatal("Could not request remote forwarding.");
899                         else
900                                 logit("Warning: Could not request remote "
901                                     "forwarding.");
902                 }
903         }
904
905         /* Initiate tunnel forwarding. */
906         if (options.tun_open != SSH_TUNMODE_NO) {
907                 if (client_request_tun_fwd(options.tun_open,
908                     options.tun_local, options.tun_remote) == -1) {
909                         if (options.exit_on_forward_failure)
910                                 fatal("Could not request tunnel forwarding.");
911                         else
912                                 error("Could not request tunnel forwarding.");
913                 }
914         }                       
915 }
916
917 static void
918 check_agent_present(void)
919 {
920         if (options.forward_agent) {
921                 /* Clear agent forwarding if we don't have an agent. */
922                 if (!ssh_agent_present())
923                         options.forward_agent = 0;
924         }
925 }
926
927 static int
928 ssh_session(void)
929 {
930         int type;
931         int interactive = 0;
932         int have_tty = 0;
933         struct winsize ws;
934         char *cp;
935         const char *display;
936
937         /* Enable compression if requested. */
938         if (options.compression) {
939                 debug("Requesting compression at level %d.", options.compression_level);
940
941                 if (options.compression_level < 1 || options.compression_level > 9)
942                         fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
943
944                 /* Send the request. */
945                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
946                 packet_put_int(options.compression_level);
947                 packet_send();
948                 packet_write_wait();
949                 type = packet_read();
950                 if (type == SSH_SMSG_SUCCESS)
951                         packet_start_compression(options.compression_level);
952                 else if (type == SSH_SMSG_FAILURE)
953                         logit("Warning: Remote host refused compression.");
954                 else
955                         packet_disconnect("Protocol error waiting for compression response.");
956         }
957         /* Allocate a pseudo tty if appropriate. */
958         if (tty_flag) {
959                 debug("Requesting pty.");
960
961                 /* Start the packet. */
962                 packet_start(SSH_CMSG_REQUEST_PTY);
963
964                 /* Store TERM in the packet.  There is no limit on the
965                    length of the string. */
966                 cp = getenv("TERM");
967                 if (!cp)
968                         cp = "";
969                 packet_put_cstring(cp);
970
971                 /* Store window size in the packet. */
972                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
973                         memset(&ws, 0, sizeof(ws));
974                 packet_put_int((u_int)ws.ws_row);
975                 packet_put_int((u_int)ws.ws_col);
976                 packet_put_int((u_int)ws.ws_xpixel);
977                 packet_put_int((u_int)ws.ws_ypixel);
978
979                 /* Store tty modes in the packet. */
980                 tty_make_modes(fileno(stdin), NULL);
981
982                 /* Send the packet, and wait for it to leave. */
983                 packet_send();
984                 packet_write_wait();
985
986                 /* Read response from the server. */
987                 type = packet_read();
988                 if (type == SSH_SMSG_SUCCESS) {
989                         interactive = 1;
990                         have_tty = 1;
991                 } else if (type == SSH_SMSG_FAILURE)
992                         logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
993                 else
994                         packet_disconnect("Protocol error waiting for pty request response.");
995         }
996         /* Request X11 forwarding if enabled and DISPLAY is set. */
997         display = getenv("DISPLAY");
998         if (options.forward_x11 && display != NULL) {
999                 char *proto, *data;
1000                 /* Get reasonable local authentication information. */
1001                 client_x11_get_proto(display, options.xauth_location,
1002                     options.forward_x11_trusted, &proto, &data);
1003                 /* Request forwarding with authentication spoofing. */
1004                 debug("Requesting X11 forwarding with authentication spoofing.");
1005                 x11_request_forwarding_with_spoofing(0, display, proto, data);
1006
1007                 /* Read response from the server. */
1008                 type = packet_read();
1009                 if (type == SSH_SMSG_SUCCESS) {
1010                         interactive = 1;
1011                 } else if (type == SSH_SMSG_FAILURE) {
1012                         logit("Warning: Remote host denied X11 forwarding.");
1013                 } else {
1014                         packet_disconnect("Protocol error waiting for X11 forwarding");
1015                 }
1016         }
1017         /* Tell the packet module whether this is an interactive session. */
1018         packet_set_interactive(interactive);
1019
1020         /* Request authentication agent forwarding if appropriate. */
1021         check_agent_present();
1022
1023         if (options.forward_agent) {
1024                 debug("Requesting authentication agent forwarding.");
1025                 auth_request_forwarding();
1026
1027                 /* Read response from the server. */
1028                 type = packet_read();
1029                 packet_check_eom();
1030                 if (type != SSH_SMSG_SUCCESS)
1031                         logit("Warning: Remote host denied authentication agent forwarding.");
1032         }
1033
1034         /* Initiate port forwardings. */
1035         ssh_init_forwarding();
1036
1037         /* Execute a local command */
1038         if (options.local_command != NULL &&
1039             options.permit_local_command)
1040                 ssh_local_cmd(options.local_command);
1041
1042         /* If requested, let ssh continue in the background. */
1043         if (fork_after_authentication_flag)
1044                 if (daemon(1, 1) < 0)
1045                         fatal("daemon() failed: %.200s", strerror(errno));
1046
1047         /*
1048          * If a command was specified on the command line, execute the
1049          * command now. Otherwise request the server to start a shell.
1050          */
1051         if (buffer_len(&command) > 0) {
1052                 int len = buffer_len(&command);
1053                 if (len > 900)
1054                         len = 900;
1055                 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1056                 packet_start(SSH_CMSG_EXEC_CMD);
1057                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1058                 packet_send();
1059                 packet_write_wait();
1060         } else {
1061                 debug("Requesting shell.");
1062                 packet_start(SSH_CMSG_EXEC_SHELL);
1063                 packet_send();
1064                 packet_write_wait();
1065         }
1066
1067         /* Enter the interactive session. */
1068         return client_loop(have_tty, tty_flag ?
1069             options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1070 }
1071
1072 static void
1073 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1074 {
1075         int id, len;
1076
1077         id = packet_get_int();
1078         len = buffer_len(&command);
1079         if (len > 900)
1080                 len = 900;
1081         packet_check_eom();
1082         if (type == SSH2_MSG_CHANNEL_FAILURE)
1083                 fatal("Request for subsystem '%.*s' failed on channel %d",
1084                     len, (u_char *)buffer_ptr(&command), id);
1085 }
1086
1087 void
1088 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1089 {
1090         int i;
1091
1092         i = client_global_request_id++;
1093         if (i >= options.num_remote_forwards)
1094                 return;
1095         debug("remote forward %s for: listen %d, connect %s:%d",
1096             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1097             options.remote_forwards[i].listen_port,
1098             options.remote_forwards[i].connect_host,
1099             options.remote_forwards[i].connect_port);
1100         if (type == SSH2_MSG_REQUEST_FAILURE) {
1101                 if (options.exit_on_forward_failure)
1102                         fatal("Error: remote port forwarding failed for "
1103                             "listen port %d",
1104                             options.remote_forwards[i].listen_port);
1105                 else
1106                         logit("Warning: remote port forwarding failed for "
1107                             "listen port %d",
1108                             options.remote_forwards[i].listen_port);
1109         }
1110 }
1111
1112 static void
1113 ssh_control_listener(void)
1114 {
1115         struct sockaddr_un addr;
1116         mode_t old_umask;
1117         int addr_len;
1118
1119         if (options.control_path == NULL ||
1120             options.control_master == SSHCTL_MASTER_NO)
1121                 return;
1122
1123         debug("setting up multiplex master socket");
1124
1125         memset(&addr, '\0', sizeof(addr));
1126         addr.sun_family = AF_UNIX;
1127         addr_len = offsetof(struct sockaddr_un, sun_path) +
1128             strlen(options.control_path) + 1;
1129
1130         if (strlcpy(addr.sun_path, options.control_path,
1131             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1132                 fatal("ControlPath too long");
1133
1134         if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1135                 fatal("%s socket(): %s", __func__, strerror(errno));
1136
1137         old_umask = umask(0177);
1138         if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1139                 control_fd = -1;
1140                 if (errno == EINVAL || errno == EADDRINUSE)
1141                         fatal("ControlSocket %s already exists",
1142                             options.control_path);
1143                 else
1144                         fatal("%s bind(): %s", __func__, strerror(errno));
1145         }
1146         umask(old_umask);
1147
1148         if (listen(control_fd, 64) == -1)
1149                 fatal("%s listen(): %s", __func__, strerror(errno));
1150
1151         set_nonblock(control_fd);
1152 }
1153
1154 /* request pty/x11/agent/tcpfwd/shell for channel */
1155 static void
1156 ssh_session2_setup(int id, void *arg)
1157 {
1158         extern char **environ;
1159         const char *display;
1160         int interactive = tty_flag;
1161
1162         display = getenv("DISPLAY");
1163         if (options.forward_x11 && display != NULL) {
1164                 char *proto, *data;
1165                 /* Get reasonable local authentication information. */
1166                 client_x11_get_proto(display, options.xauth_location,
1167                     options.forward_x11_trusted, &proto, &data);
1168                 /* Request forwarding with authentication spoofing. */
1169                 debug("Requesting X11 forwarding with authentication spoofing.");
1170                 x11_request_forwarding_with_spoofing(id, display, proto, data);
1171                 interactive = 1;
1172                 /* XXX wait for reply */
1173         }
1174
1175         check_agent_present();
1176         if (options.forward_agent) {
1177                 debug("Requesting authentication agent forwarding.");
1178                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1179                 packet_send();
1180         }
1181
1182         client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1183             NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1184
1185         packet_set_interactive(interactive);
1186 }
1187
1188 /* open new channel for a session */
1189 static int
1190 ssh_session2_open(void)
1191 {
1192         Channel *c;
1193         int window, packetmax, in, out, err;
1194         int sock;
1195         int socksize;
1196         int socksizelen = sizeof(int);
1197
1198         if (stdin_null_flag) {
1199                 in = open(_PATH_DEVNULL, O_RDONLY);
1200         } else {
1201                 in = dup(STDIN_FILENO);
1202         }
1203         out = dup(STDOUT_FILENO);
1204         err = dup(STDERR_FILENO);
1205
1206         if (in < 0 || out < 0 || err < 0)
1207                 fatal("dup() in/out/err failed");
1208
1209         /* enable nonblocking unless tty */
1210         if (!isatty(in))
1211                 set_nonblock(in);
1212         if (!isatty(out))
1213                 set_nonblock(out);
1214         if (!isatty(err))
1215                 set_nonblock(err);
1216
1217         /* we need to check to see if what they want to do about buffer */
1218         /* sizes here. In a hpn to nonhpn connection we want to limit */
1219         /* the window size to something reasonable in case the far side */
1220         /* has the large window bug. In hpn to hpn connection we want to */
1221         /* use the max window size but allow the user to override it */
1222         /* lastly if they disabled hpn then use the ssh std window size */
1223
1224         /* so why don't we just do a getsockopt() here and set the */
1225         /* ssh window to that? In the case of a autotuning receive */
1226         /* window the window would get stuck at the initial buffer */
1227         /* size generally less than 96k. Therefore we need to set the */
1228         /* maximum ssh window size to the maximum hpn buffer size */
1229         /* unless the user has specifically set the tcprcvbufpoll */
1230         /* to no. In which case we *can* just set the window to the */
1231         /* minimum of the hpn buffer size and tcp receive buffer size */
1232         
1233         if(options.hpn_disabled)
1234         {
1235                 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1236         }
1237         else if (datafellows & SSH_BUG_LARGEWINDOW) 
1238         {
1239                 debug("HPN to Non-HPN Connection");
1240                 if (options.hpn_buffer_size < 0)
1241                         options.hpn_buffer_size = 2*1024*1024;
1242         } 
1243         else 
1244         {
1245                 if (options.hpn_buffer_size < 0)
1246                         options.hpn_buffer_size = BUFFER_MAX_LEN_HPN;
1247
1248                 /*create a socket but don't connect it */
1249                 /* we use that the get the rcv socket size */
1250                 sock = socket(AF_INET, SOCK_STREAM, 0);
1251                 /* if they are using the tcp_rcv_buf option */
1252                 /* attempt to set the buffer size to that */
1253                 if (options.tcp_rcv_buf) 
1254                         setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf, 
1255                                    sizeof(options.tcp_rcv_buf));
1256                 getsockopt(sock, SOL_SOCKET, SO_RCVBUF, 
1257                            &socksize, &socksizelen);
1258                 close(sock);
1259                 debug("socksize %d", socksize);
1260                 if (options.tcp_rcv_buf_poll <= 0) 
1261                 {
1262                         options.hpn_buffer_size = MIN(socksize,options.hpn_buffer_size);
1263                         debug ("MIN of TCP RWIN and HPNBufferSize: %d", options.hpn_buffer_size);
1264                 } 
1265                 else
1266                 {
1267                         if (options.tcp_rcv_buf > 0) 
1268                                 options.hpn_buffer_size = MIN(options.tcp_rcv_buf, options.hpn_buffer_size);
1269                                 debug ("MIN of TCPRcvBuf and HPNBufferSize: %d", options.hpn_buffer_size);
1270                 }
1271                 
1272         }
1273
1274         debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1275
1276         window = options.hpn_buffer_size;
1277
1278         packetmax = CHAN_SES_PACKET_DEFAULT;
1279         if (tty_flag) {
1280                 window = 4*CHAN_SES_PACKET_DEFAULT;
1281                 window >>= 1;
1282                 packetmax >>= 1;
1283         }
1284         c = channel_new(
1285             "session", SSH_CHANNEL_OPENING, in, out, err,
1286             window, packetmax, CHAN_EXTENDED_WRITE,
1287             "client-session", /*nonblock*/0);
1288
1289         if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1290                 c->dynamic_window = 1;
1291                 debug ("Enabled Dynamic Window Scaling\n");
1292         }
1293         debug3("ssh_session2_open: channel_new: %d", c->self);
1294
1295         channel_send_open(c->self);
1296         if (!no_shell_flag)
1297                 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1298
1299         return c->self;
1300 }
1301
1302 static int
1303 ssh_session2(void)
1304 {
1305         int id = -1;
1306
1307         /* XXX should be pre-session */
1308         ssh_init_forwarding();
1309
1310         if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1311                 id = ssh_session2_open();
1312
1313         /* Execute a local command */
1314         if (options.local_command != NULL &&
1315             options.permit_local_command)
1316                 ssh_local_cmd(options.local_command);
1317
1318         /* Start listening for multiplex clients */
1319         ssh_control_listener();
1320
1321         /* If requested, let ssh continue in the background. */
1322         if (fork_after_authentication_flag)
1323                 if (daemon(1, 1) < 0)
1324                         fatal("daemon() failed: %.200s", strerror(errno));
1325
1326         return client_loop(tty_flag, tty_flag ?
1327             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1328 }
1329
1330 static void
1331 load_public_identity_files(void)
1332 {
1333         char *filename, *cp, thishost[NI_MAXHOST];
1334         char *pwdir = NULL, *pwname = NULL;
1335         int i = 0;
1336         Key *public;
1337         struct passwd *pw;
1338 #ifdef SMARTCARD
1339         Key **keys;
1340
1341         if (options.smartcard_device != NULL &&
1342             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1343             (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1344                 int count = 0;
1345                 for (i = 0; keys[i] != NULL; i++) {
1346                         count++;
1347                         memmove(&options.identity_files[1], &options.identity_files[0],
1348                             sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1349                         memmove(&options.identity_keys[1], &options.identity_keys[0],
1350                             sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1351                         options.num_identity_files++;
1352                         options.identity_keys[0] = keys[i];
1353                         options.identity_files[0] = sc_get_key_label(keys[i]);
1354                 }
1355                 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1356                         options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1357                 i = count;
1358                 xfree(keys);
1359         }
1360 #endif /* SMARTCARD */
1361         if ((pw = getpwuid(original_real_uid)) == NULL)
1362                 fatal("load_public_identity_files: getpwuid failed");
1363         pwname = xstrdup(pw->pw_name);
1364         pwdir = xstrdup(pw->pw_dir);
1365         if (gethostname(thishost, sizeof(thishost)) == -1)
1366                 fatal("load_public_identity_files: gethostname: %s",
1367                     strerror(errno));
1368         for (; i < options.num_identity_files; i++) {
1369                 cp = tilde_expand_filename(options.identity_files[i],
1370                     original_real_uid);
1371                 filename = percent_expand(cp, "d", pwdir,
1372                     "u", pwname, "l", thishost, "h", host,
1373                     "r", options.user, (char *)NULL);
1374                 xfree(cp);
1375                 public = key_load_public(filename, NULL);
1376                 debug("identity file %s type %d", filename,
1377                     public ? public->type : -1);
1378                 xfree(options.identity_files[i]);
1379                 options.identity_files[i] = filename;
1380                 options.identity_keys[i] = public;
1381         }
1382         bzero(pwname, strlen(pwname));
1383         xfree(pwname);
1384         bzero(pwdir, strlen(pwdir));
1385         xfree(pwdir);
1386 }
1387
1388 static void
1389 control_client_sighandler(int signo)
1390 {
1391         control_client_terminate = signo;
1392 }
1393
1394 static void
1395 control_client_sigrelay(int signo)
1396 {
1397         int save_errno = errno;
1398
1399         if (control_server_pid > 1)
1400                 kill(control_server_pid, signo);
1401
1402         errno = save_errno;
1403 }
1404
1405 static int
1406 env_permitted(char *env)
1407 {
1408         int i, ret;
1409         char name[1024], *cp;
1410
1411         if ((cp = strchr(env, '=')) == NULL || cp == env)
1412                 return (0);
1413         ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1414         if (ret <= 0 || (size_t)ret >= sizeof(name))
1415                 fatal("env_permitted: name '%.100s...' too long", env);
1416
1417         for (i = 0; i < options.num_send_env; i++)
1418                 if (match_pattern(name, options.send_env[i]))
1419                         return (1);
1420
1421         return (0);
1422 }
1423
1424 static void
1425 control_client(const char *path)
1426 {
1427         struct sockaddr_un addr;
1428         int i, r, fd, sock, exitval[2], num_env, addr_len;
1429         Buffer m;
1430         char *term;
1431         extern char **environ;
1432         u_int  flags;
1433
1434         if (mux_command == 0)
1435                 mux_command = SSHMUX_COMMAND_OPEN;
1436
1437         switch (options.control_master) {
1438         case SSHCTL_MASTER_AUTO:
1439         case SSHCTL_MASTER_AUTO_ASK:
1440                 debug("auto-mux: Trying existing master");
1441                 /* FALLTHROUGH */
1442         case SSHCTL_MASTER_NO:
1443                 break;
1444         default:
1445                 return;
1446         }
1447
1448         memset(&addr, '\0', sizeof(addr));
1449         addr.sun_family = AF_UNIX;
1450         addr_len = offsetof(struct sockaddr_un, sun_path) +
1451             strlen(path) + 1;
1452
1453         if (strlcpy(addr.sun_path, path,
1454             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1455                 fatal("ControlPath too long");
1456
1457         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1458                 fatal("%s socket(): %s", __func__, strerror(errno));
1459
1460         if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1461                 if (mux_command != SSHMUX_COMMAND_OPEN) {
1462                         fatal("Control socket connect(%.100s): %s", path,
1463                             strerror(errno));
1464                 }
1465                 if (errno == ENOENT)
1466                         debug("Control socket \"%.100s\" does not exist", path);
1467                 else {
1468                         error("Control socket connect(%.100s): %s", path,
1469                             strerror(errno));
1470                 }
1471                 close(sock);
1472                 return;
1473         }
1474
1475         if (stdin_null_flag) {
1476                 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1477                         fatal("open(/dev/null): %s", strerror(errno));
1478                 if (dup2(fd, STDIN_FILENO) == -1)
1479                         fatal("dup2: %s", strerror(errno));
1480                 if (fd > STDERR_FILENO)
1481                         close(fd);
1482         }
1483
1484         term = getenv("TERM");
1485
1486         flags = 0;
1487         if (tty_flag)
1488                 flags |= SSHMUX_FLAG_TTY;
1489         if (subsystem_flag)
1490                 flags |= SSHMUX_FLAG_SUBSYS;
1491         if (options.forward_x11)
1492                 flags |= SSHMUX_FLAG_X11_FWD;
1493         if (options.forward_agent)
1494                 flags |= SSHMUX_FLAG_AGENT_FWD;
1495
1496         signal(SIGPIPE, SIG_IGN);
1497
1498         buffer_init(&m);
1499
1500         /* Send our command to server */
1501         buffer_put_int(&m, mux_command);
1502         buffer_put_int(&m, flags);
1503         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1504                 fatal("%s: msg_send", __func__);
1505         buffer_clear(&m);
1506
1507         /* Get authorisation status and PID of controlee */
1508         if (ssh_msg_recv(sock, &m) == -1)
1509                 fatal("%s: msg_recv", __func__);
1510         if (buffer_get_char(&m) != SSHMUX_VER)
1511                 fatal("%s: wrong version", __func__);
1512         if (buffer_get_int(&m) != 1)
1513                 fatal("Connection to master denied");
1514         control_server_pid = buffer_get_int(&m);
1515
1516         buffer_clear(&m);
1517
1518         switch (mux_command) {
1519         case SSHMUX_COMMAND_ALIVE_CHECK:
1520                 fprintf(stderr, "Master running (pid=%d)\r\n",
1521                     control_server_pid);
1522                 exit(0);
1523         case SSHMUX_COMMAND_TERMINATE:
1524                 fprintf(stderr, "Exit request sent.\r\n");
1525                 exit(0);
1526         case SSHMUX_COMMAND_OPEN:
1527                 /* continue below */
1528                 break;
1529         default:
1530                 fatal("silly mux_command %d", mux_command);
1531         }
1532
1533         /* SSHMUX_COMMAND_OPEN */
1534         buffer_put_cstring(&m, term ? term : "");
1535         buffer_append(&command, "\0", 1);
1536         buffer_put_cstring(&m, buffer_ptr(&command));
1537
1538         if (options.num_send_env == 0 || environ == NULL) {
1539                 buffer_put_int(&m, 0);
1540         } else {
1541                 /* Pass environment */
1542                 num_env = 0;
1543                 for (i = 0; environ[i] != NULL; i++)
1544                         if (env_permitted(environ[i]))
1545                                 num_env++; /* Count */
1546
1547                 buffer_put_int(&m, num_env);
1548
1549                 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1550                         if (env_permitted(environ[i])) {
1551                                 num_env--;
1552                                 buffer_put_cstring(&m, environ[i]);
1553                         }
1554         }
1555
1556         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1557                 fatal("%s: msg_send", __func__);
1558
1559         if (mm_send_fd(sock, STDIN_FILENO) == -1 ||
1560             mm_send_fd(sock, STDOUT_FILENO) == -1 ||
1561             mm_send_fd(sock, STDERR_FILENO) == -1)
1562                 fatal("%s: send fds failed", __func__);
1563
1564         /* Wait for reply, so master has a chance to gather ttymodes */
1565         buffer_clear(&m);
1566         if (ssh_msg_recv(sock, &m) == -1)
1567                 fatal("%s: msg_recv", __func__);
1568         if (buffer_get_char(&m) != SSHMUX_VER)
1569                 fatal("%s: wrong version", __func__);
1570         buffer_free(&m);
1571
1572         signal(SIGHUP, control_client_sighandler);
1573         signal(SIGINT, control_client_sighandler);
1574         signal(SIGTERM, control_client_sighandler);
1575         signal(SIGWINCH, control_client_sigrelay);
1576
1577         if (tty_flag)
1578                 enter_raw_mode();
1579
1580         /*
1581          * Stick around until the controlee closes the client_fd.
1582          * Before it does, it is expected to write this process' exit
1583          * value (one int). This process must read the value and wait for
1584          * the closure of the client_fd; if this one closes early, the 
1585          * multiplex master will terminate early too (possibly losing data).
1586          */
1587         exitval[0] = 0;
1588         for (i = 0; !control_client_terminate && i < (int)sizeof(exitval);) {
1589                 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
1590                 if (r == 0) {
1591                         debug2("Received EOF from master");
1592                         break;
1593                 }
1594                 if (r == -1) {
1595                         if (errno == EINTR)
1596                                 continue;
1597                         fatal("%s: read %s", __func__, strerror(errno));
1598                 }
1599                 i += r;
1600         }
1601
1602         close(sock);
1603         leave_raw_mode();
1604         if (i > (int)sizeof(int))
1605                 fatal("%s: master returned too much data (%d > %lu)",
1606                     __func__, i, sizeof(int));
1607         if (control_client_terminate) {
1608                 debug2("Exiting on signal %d", control_client_terminate);
1609                 exitval[0] = 255;
1610         } else if (i < (int)sizeof(int)) {
1611                 debug2("Control master terminated unexpectedly");
1612                 exitval[0] = 255;
1613         } else
1614                 debug2("Received exit status from master %d", exitval[0]);
1615
1616         if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1617                 fprintf(stderr, "Shared connection to %s closed.\r\n", host);
1618
1619         exit(exitval[0]);
1620 }
This page took 0.222423 seconds and 3 git commands to generate.