]> andersk Git - gssapi-openssh.git/blob - openssh/ssh.c
add KEX_GSS_GRP14_SHA1 handling
[gssapi-openssh.git] / openssh / ssh.c
1 /* $OpenBSD: ssh.c,v 1.294 2006/10/06 02:29:19 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * Ssh client program.  This program can be used to log into a remote machine.
7  * The software supports strong authentication, encryption, and forwarding
8  * of X11, TCP/IP, and authentication connections.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * Copyright (c) 1999 Niels Provos.  All rights reserved.
17  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
18  *
19  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20  * in Canada (German citizen).
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the above copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41  */
42
43 #include "includes.h"
44
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #include <sys/un.h>
53
54 #include <ctype.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <netdb.h>
58 #ifdef HAVE_PATHS_H
59 #include <paths.h>
60 #endif
61 #include <pwd.h>
62 #include <signal.h>
63 #include <stdarg.h>
64 #include <stddef.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69
70 #include <netinet/in.h>
71 #include <arpa/inet.h>
72
73 #include <openssl/evp.h>
74 #include <openssl/err.h>
75
76 #include "xmalloc.h"
77 #include "ssh.h"
78 #include "ssh1.h"
79 #include "ssh2.h"
80 #include "compat.h"
81 #include "cipher.h"
82 #include "packet.h"
83 #include "buffer.h"
84 #include "channels.h"
85 #include "key.h"
86 #include "authfd.h"
87 #include "authfile.h"
88 #include "pathnames.h"
89 #include "dispatch.h"
90 #include "clientloop.h"
91 #include "log.h"
92 #include "readconf.h"
93 #include "sshconnect.h"
94 #include "misc.h"
95 #include "kex.h"
96 #include "mac.h"
97 #include "sshpty.h"
98 #include "match.h"
99 #include "msg.h"
100 #include "monitor_fdpass.h"
101 #include "uidswap.h"
102 #include "version.h"
103
104 #ifdef SMARTCARD
105 #include "scard.h"
106 #endif
107
108 extern char *__progname;
109
110 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
111 int debug_flag = 0;
112
113 /* Flag indicating whether a tty should be allocated */
114 int tty_flag = 0;
115 int no_tty_flag = 0;
116 int force_tty_flag = 0;
117
118 /* don't exec a shell */
119 int no_shell_flag = 0;
120
121 /*
122  * Flag indicating that nothing should be read from stdin.  This can be set
123  * on the command line.
124  */
125 int stdin_null_flag = 0;
126
127 /*
128  * Flag indicating that ssh should fork after authentication.  This is useful
129  * so that the passphrase can be entered manually, and then ssh goes to the
130  * background.
131  */
132 int fork_after_authentication_flag = 0;
133
134 /*
135  * General data structure for command line options and options configurable
136  * in configuration files.  See readconf.h.
137  */
138 Options options;
139
140 /* optional user configfile */
141 char *config = NULL;
142
143 /*
144  * Name of the host we are connecting to.  This is the name given on the
145  * command line, or the HostName specified for the user-supplied name in a
146  * configuration file.
147  */
148 char *host;
149
150 /* socket address the host resolves to */
151 struct sockaddr_storage hostaddr;
152
153 /* Private host keys. */
154 Sensitive sensitive_data;
155
156 /* Original real UID. */
157 uid_t original_real_uid;
158 uid_t original_effective_uid;
159
160 /* command to be executed */
161 Buffer command;
162
163 /* Should we execute a command or invoke a subsystem? */
164 int subsystem_flag = 0;
165
166 /* # of replies received for global requests */
167 static int client_global_request_id = 0;
168
169 /* pid of proxycommand child process */
170 pid_t proxy_command_pid = 0;
171
172 /* fd to control socket */
173 int control_fd = -1;
174
175 /* Multiplexing control command */
176 static u_int mux_command = 0;
177
178 /* Only used in control client mode */
179 volatile sig_atomic_t control_client_terminate = 0;
180 u_int control_server_pid = 0;
181
182 /* Prints a help message to the user.  This function never returns. */
183
184 static void
185 usage(void)
186 {
187         fprintf(stderr,
188 "usage: ssh [-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                         break;
501                 case 'o':
502                         dummy = 1;
503                         line = xstrdup(optarg);
504                         if (process_config_line(&options, host ? host : "",
505                             line, "command-line", 0, &dummy) != 0)
506                                 exit(255);
507                         xfree(line);
508                         break;
509                 case 'T':
510                         no_tty_flag = 1;
511                         /* ensure that the user doesn't try to backdoor a */
512                         /* null cipher switch on an interactive session */
513                         /* so explicitly disable it no matter what */
514                         options.none_switch=0;
515                         break;
516                 case 's':
517                         subsystem_flag = 1;
518                         break;
519                 case 'S':
520                         if (options.control_path != NULL)
521                                 free(options.control_path);
522                         options.control_path = xstrdup(optarg);
523                         break;
524                 case 'b':
525                         options.bind_address = optarg;
526                         break;
527                 case 'F':
528                         config = optarg;
529                         break;
530                 default:
531                         usage();
532                 }
533         }
534
535         ac -= optind;
536         av += optind;
537
538         if (ac > 0 && !host && **av != '-') {
539                 if (strrchr(*av, '@')) {
540                         p = xstrdup(*av);
541                         cp = strrchr(p, '@');
542                         if (cp == NULL || cp == p)
543                                 usage();
544                         options.user = p;
545                         *cp = '\0';
546                         host = ++cp;
547                 } else
548                         host = *av;
549                 if (ac > 1) {
550                         optind = optreset = 1;
551                         goto again;
552                 }
553                 ac--, av++;
554         }
555
556         /* Check that we got a host name. */
557         if (!host)
558                 usage();
559
560         SSLeay_add_all_algorithms();
561         ERR_load_crypto_strings();
562
563         /* Initialize the command to execute on remote host. */
564         buffer_init(&command);
565
566         /*
567          * Save the command to execute on the remote host in a buffer. There
568          * is no limit on the length of the command, except by the maximum
569          * packet size.  Also sets the tty flag if there is no command.
570          */
571         if (!ac) {
572                 /* No command specified - execute shell on a tty. */
573                 tty_flag = 1;
574                 if (subsystem_flag) {
575                         fprintf(stderr,
576                             "You must specify a subsystem to invoke.\n");
577                         usage();
578                 }
579         } else {
580                 /* A command has been specified.  Store it into the buffer. */
581                 for (i = 0; i < ac; i++) {
582                         if (i)
583                                 buffer_append(&command, " ", 1);
584                         buffer_append(&command, av[i], strlen(av[i]));
585                 }
586         }
587
588         /* Cannot fork to background if no command. */
589         if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
590                 fatal("Cannot fork into background without a command to execute.");
591
592         /* Allocate a tty by default if no command specified. */
593         if (buffer_len(&command) == 0)
594                 tty_flag = 1;
595
596         /* Force no tty */
597         if (no_tty_flag)
598                 tty_flag = 0;
599         /* Do not allocate a tty if stdin is not a tty. */
600         if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
601                 if (tty_flag)
602                         logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
603                 tty_flag = 0;
604         }
605
606         /*
607          * Initialize "log" output.  Since we are the client all output
608          * actually goes to stderr.
609          */
610         log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
611             SYSLOG_FACILITY_USER, 1);
612
613         /*
614          * Read per-user configuration file.  Ignore the system wide config
615          * file if the user specifies a config file on the command line.
616          */
617         if (config != NULL) {
618                 if (!read_config_file(config, host, &options, 0))
619                         fatal("Can't open user config file %.100s: "
620                             "%.100s", config, strerror(errno));
621         } else  {
622             /*
623              * Since the config file parsing code aborts if it sees
624              * options it doesn't recognize, allow users to put
625              * options specific to compile-time add-ons in alternate
626              * config files so their primary config file will
627              * interoperate SSH versions that don't support those
628              * options.
629              */
630 #ifdef GSSAPI
631                 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
632                     _PATH_SSH_USER_CONFFILE);
633                 (void)read_config_file(buf, host, &options, 1);
634 #ifdef GSI
635                 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
636                     _PATH_SSH_USER_CONFFILE);
637                 (void)read_config_file(buf, host, &options, 1);
638 #endif
639 #if defined(KRB5)
640                 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
641                     _PATH_SSH_USER_CONFFILE);
642                 (void)read_config_file(buf, host, &options, 1);
643 #endif
644 #endif
645                 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
646                     _PATH_SSH_USER_CONFFILE);
647                 (void)read_config_file(buf, host, &options, 1);
648
649                 /* Read systemwide configuration file after use config. */
650                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
651                     &options, 0);
652         }
653
654         /* Fill configuration defaults. */
655         fill_default_options(&options);
656
657         channel_set_af(options.address_family);
658
659         /* reinit */
660         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
661
662         seed_rng();
663
664         if (options.user == NULL) {
665                 options.user = xstrdup(pw->pw_name);
666                 options.implicit = 1;
667         }
668         else options.implicit = 0;
669
670         if (options.hostname != NULL)
671                 host = options.hostname;
672
673         /* force lowercase for hostkey matching */
674         if (options.host_key_alias != NULL) {
675                 for (p = options.host_key_alias; *p; p++)
676                         if (isupper(*p))
677                                 *p = (char)tolower(*p);
678         }
679
680         /* Get default port if port has not been set. */
681         if (options.port == 0) {
682                 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
683                 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
684         }
685
686         if (options.proxy_command != NULL &&
687             strcmp(options.proxy_command, "none") == 0)
688                 options.proxy_command = NULL;
689         if (options.control_path != NULL &&
690             strcmp(options.control_path, "none") == 0)
691                 options.control_path = NULL;
692
693         if (options.control_path != NULL) {
694                 char thishost[NI_MAXHOST];
695
696                 if (gethostname(thishost, sizeof(thishost)) == -1)
697                         fatal("gethostname: %s", strerror(errno));
698                 snprintf(buf, sizeof(buf), "%d", options.port);
699                 cp = tilde_expand_filename(options.control_path,
700                     original_real_uid);
701                 options.control_path = percent_expand(cp, "p", buf, "h", host,
702                     "r", options.user, "l", thishost, (char *)NULL);
703                 xfree(cp);
704         }
705         if (mux_command != 0 && options.control_path == NULL)
706                 fatal("No ControlPath specified for \"-O\" command");
707         if (options.control_path != NULL)
708                 control_client(options.control_path);
709
710         /* Open a connection to the remote host. */
711         if (ssh_connect(host, &hostaddr, options.port,
712             options.address_family, options.connection_attempts,
713 #ifdef HAVE_CYGWIN
714             options.use_privileged_port,
715 #else
716             original_effective_uid == 0 && options.use_privileged_port,
717 #endif
718             options.proxy_command) != 0)
719                 exit(255);
720
721         /*
722          * If we successfully made the connection, load the host private key
723          * in case we will need it later for combined rsa-rhosts
724          * authentication. This must be done before releasing extra
725          * privileges, because the file is only readable by root.
726          * If we cannot access the private keys, load the public keys
727          * instead and try to execute the ssh-keysign helper instead.
728          */
729         sensitive_data.nkeys = 0;
730         sensitive_data.keys = NULL;
731         sensitive_data.external_keysign = 0;
732         if (options.rhosts_rsa_authentication ||
733             options.hostbased_authentication) {
734                 sensitive_data.nkeys = 3;
735                 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
736                     sizeof(Key));
737
738                 PRIV_START;
739                 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
740                     _PATH_HOST_KEY_FILE, "", NULL, NULL);
741                 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
742                     _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
743                 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
744                     _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
745                 PRIV_END;
746
747                 if (options.hostbased_authentication == 1 &&
748                     sensitive_data.keys[0] == NULL &&
749                     sensitive_data.keys[1] == NULL &&
750                     sensitive_data.keys[2] == NULL) {
751                         sensitive_data.keys[1] = key_load_public(
752                             _PATH_HOST_DSA_KEY_FILE, NULL);
753                         sensitive_data.keys[2] = key_load_public(
754                             _PATH_HOST_RSA_KEY_FILE, NULL);
755                         sensitive_data.external_keysign = 1;
756                 }
757         }
758         /*
759          * Get rid of any extra privileges that we may have.  We will no
760          * longer need them.  Also, extra privileges could make it very hard
761          * to read identity files and other non-world-readable files from the
762          * user's home directory if it happens to be on a NFS volume where
763          * root is mapped to nobody.
764          */
765         if (original_effective_uid == 0) {
766                 PRIV_START;
767                 permanently_set_uid(pw);
768         }
769
770         /*
771          * Now that we are back to our own permissions, create ~/.ssh
772          * directory if it doesn't already exist.
773          */
774         snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
775         if (stat(buf, &st) < 0)
776                 if (mkdir(buf, 0700) < 0)
777                         error("Could not create directory '%.200s'.", buf);
778
779         /* load options.identity_files */
780         load_public_identity_files();
781
782         /* Expand ~ in known host file names. */
783         /* XXX mem-leaks: */
784         options.system_hostfile =
785             tilde_expand_filename(options.system_hostfile, original_real_uid);
786         options.user_hostfile =
787             tilde_expand_filename(options.user_hostfile, original_real_uid);
788         options.system_hostfile2 =
789             tilde_expand_filename(options.system_hostfile2, original_real_uid);
790         options.user_hostfile2 =
791             tilde_expand_filename(options.user_hostfile2, original_real_uid);
792
793         signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
794
795         /* Log into the remote system.  This never returns if the login fails. */
796         ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
797
798         /* We no longer need the private host keys.  Clear them now. */
799         if (sensitive_data.nkeys != 0) {
800                 for (i = 0; i < sensitive_data.nkeys; i++) {
801                         if (sensitive_data.keys[i] != NULL) {
802                                 /* Destroys contents safely */
803                                 debug3("clear hostkey %d", i);
804                                 key_free(sensitive_data.keys[i]);
805                                 sensitive_data.keys[i] = NULL;
806                         }
807                 }
808                 xfree(sensitive_data.keys);
809         }
810         for (i = 0; i < options.num_identity_files; i++) {
811                 if (options.identity_files[i]) {
812                         xfree(options.identity_files[i]);
813                         options.identity_files[i] = NULL;
814                 }
815                 if (options.identity_keys[i]) {
816                         key_free(options.identity_keys[i]);
817                         options.identity_keys[i] = NULL;
818                 }
819         }
820
821         exit_status = compat20 ? ssh_session2() : ssh_session();
822         packet_close();
823
824         if (options.control_path != NULL && control_fd != -1)
825                 unlink(options.control_path);
826
827         /*
828          * Send SIGHUP to proxy command if used. We don't wait() in
829          * case it hangs and instead rely on init to reap the child
830          */
831         if (proxy_command_pid > 1)
832                 kill(proxy_command_pid, SIGHUP);
833
834         return exit_status;
835 }
836
837 static void
838 ssh_init_forwarding(void)
839 {
840         int success = 0;
841         int i;
842
843         /* Initiate local TCP/IP port forwardings. */
844         for (i = 0; i < options.num_local_forwards; i++) {
845                 debug("Local connections to %.200s:%d forwarded to remote "
846                     "address %.200s:%d",
847                     (options.local_forwards[i].listen_host == NULL) ?
848                     (options.gateway_ports ? "*" : "LOCALHOST") :
849                     options.local_forwards[i].listen_host,
850                     options.local_forwards[i].listen_port,
851                     options.local_forwards[i].connect_host,
852                     options.local_forwards[i].connect_port);
853                 success += channel_setup_local_fwd_listener(
854                     options.local_forwards[i].listen_host,
855                     options.local_forwards[i].listen_port,
856                     options.local_forwards[i].connect_host,
857                     options.local_forwards[i].connect_port,
858                     options.gateway_ports, options.hpn_disabled,
859                     options.hpn_buffer_size);
860         }
861         if (i > 0 && success != i && options.exit_on_forward_failure)
862                 fatal("Could not request local forwarding.");
863         if (i > 0 && success == 0)
864                 error("Could not request local forwarding.");
865
866         /* Initiate remote TCP/IP port forwardings. */
867         for (i = 0; i < options.num_remote_forwards; i++) {
868                 debug("Remote connections from %.200s:%d forwarded to "
869                     "local address %.200s:%d",
870                     (options.remote_forwards[i].listen_host == NULL) ?
871                     "LOCALHOST" : options.remote_forwards[i].listen_host,
872                     options.remote_forwards[i].listen_port,
873                     options.remote_forwards[i].connect_host,
874                     options.remote_forwards[i].connect_port);
875                 if (channel_request_remote_forwarding(
876                     options.remote_forwards[i].listen_host,
877                     options.remote_forwards[i].listen_port,
878                     options.remote_forwards[i].connect_host,
879                     options.remote_forwards[i].connect_port) < 0) {
880                         if (options.exit_on_forward_failure)
881                                 fatal("Could not request remote forwarding.");
882                         else
883                                 logit("Warning: Could not request remote "
884                                     "forwarding.");
885                 }
886         }
887 }
888
889 static void
890 check_agent_present(void)
891 {
892         if (options.forward_agent) {
893                 /* Clear agent forwarding if we don't have an agent. */
894                 if (!ssh_agent_present())
895                         options.forward_agent = 0;
896         }
897 }
898
899 static int
900 ssh_session(void)
901 {
902         int type;
903         int interactive = 0;
904         int have_tty = 0;
905         struct winsize ws;
906         char *cp;
907         const char *display;
908
909         /* Enable compression if requested. */
910         if (options.compression) {
911                 debug("Requesting compression at level %d.", options.compression_level);
912
913                 if (options.compression_level < 1 || options.compression_level > 9)
914                         fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
915
916                 /* Send the request. */
917                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
918                 packet_put_int(options.compression_level);
919                 packet_send();
920                 packet_write_wait();
921                 type = packet_read();
922                 if (type == SSH_SMSG_SUCCESS)
923                         packet_start_compression(options.compression_level);
924                 else if (type == SSH_SMSG_FAILURE)
925                         logit("Warning: Remote host refused compression.");
926                 else
927                         packet_disconnect("Protocol error waiting for compression response.");
928         }
929         /* Allocate a pseudo tty if appropriate. */
930         if (tty_flag) {
931                 debug("Requesting pty.");
932
933                 /* Start the packet. */
934                 packet_start(SSH_CMSG_REQUEST_PTY);
935
936                 /* Store TERM in the packet.  There is no limit on the
937                    length of the string. */
938                 cp = getenv("TERM");
939                 if (!cp)
940                         cp = "";
941                 packet_put_cstring(cp);
942
943                 /* Store window size in the packet. */
944                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
945                         memset(&ws, 0, sizeof(ws));
946                 packet_put_int((u_int)ws.ws_row);
947                 packet_put_int((u_int)ws.ws_col);
948                 packet_put_int((u_int)ws.ws_xpixel);
949                 packet_put_int((u_int)ws.ws_ypixel);
950
951                 /* Store tty modes in the packet. */
952                 tty_make_modes(fileno(stdin), NULL);
953
954                 /* Send the packet, and wait for it to leave. */
955                 packet_send();
956                 packet_write_wait();
957
958                 /* Read response from the server. */
959                 type = packet_read();
960                 if (type == SSH_SMSG_SUCCESS) {
961                         interactive = 1;
962                         have_tty = 1;
963                 } else if (type == SSH_SMSG_FAILURE)
964                         logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
965                 else
966                         packet_disconnect("Protocol error waiting for pty request response.");
967         }
968         /* Request X11 forwarding if enabled and DISPLAY is set. */
969         display = getenv("DISPLAY");
970         if (options.forward_x11 && display != NULL) {
971                 char *proto, *data;
972                 /* Get reasonable local authentication information. */
973                 client_x11_get_proto(display, options.xauth_location,
974                     options.forward_x11_trusted, &proto, &data);
975                 /* Request forwarding with authentication spoofing. */
976                 debug("Requesting X11 forwarding with authentication spoofing.");
977                 x11_request_forwarding_with_spoofing(0, display, proto, data);
978
979                 /* Read response from the server. */
980                 type = packet_read();
981                 if (type == SSH_SMSG_SUCCESS) {
982                         interactive = 1;
983                 } else if (type == SSH_SMSG_FAILURE) {
984                         logit("Warning: Remote host denied X11 forwarding.");
985                 } else {
986                         packet_disconnect("Protocol error waiting for X11 forwarding");
987                 }
988         }
989         /* Tell the packet module whether this is an interactive session. */
990         packet_set_interactive(interactive);
991
992         /* Request authentication agent forwarding if appropriate. */
993         check_agent_present();
994
995         if (options.forward_agent) {
996                 debug("Requesting authentication agent forwarding.");
997                 auth_request_forwarding();
998
999                 /* Read response from the server. */
1000                 type = packet_read();
1001                 packet_check_eom();
1002                 if (type != SSH_SMSG_SUCCESS)
1003                         logit("Warning: Remote host denied authentication agent forwarding.");
1004         }
1005
1006         /* Initiate port forwardings. */
1007         ssh_init_forwarding();
1008
1009         /* If requested, let ssh continue in the background. */
1010         if (fork_after_authentication_flag)
1011                 if (daemon(1, 1) < 0)
1012                         fatal("daemon() failed: %.200s", strerror(errno));
1013
1014         /*
1015          * If a command was specified on the command line, execute the
1016          * command now. Otherwise request the server to start a shell.
1017          */
1018         if (buffer_len(&command) > 0) {
1019                 int len = buffer_len(&command);
1020                 if (len > 900)
1021                         len = 900;
1022                 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1023                 packet_start(SSH_CMSG_EXEC_CMD);
1024                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1025                 packet_send();
1026                 packet_write_wait();
1027         } else {
1028                 debug("Requesting shell.");
1029                 packet_start(SSH_CMSG_EXEC_SHELL);
1030                 packet_send();
1031                 packet_write_wait();
1032         }
1033
1034         /* Enter the interactive session. */
1035         return client_loop(have_tty, tty_flag ?
1036             options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1037 }
1038
1039 static void
1040 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1041 {
1042         int id, len;
1043
1044         id = packet_get_int();
1045         len = buffer_len(&command);
1046         if (len > 900)
1047                 len = 900;
1048         packet_check_eom();
1049         if (type == SSH2_MSG_CHANNEL_FAILURE)
1050                 fatal("Request for subsystem '%.*s' failed on channel %d",
1051                     len, (u_char *)buffer_ptr(&command), id);
1052 }
1053
1054 void
1055 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1056 {
1057         int i;
1058
1059         i = client_global_request_id++;
1060         if (i >= options.num_remote_forwards)
1061                 return;
1062         debug("remote forward %s for: listen %d, connect %s:%d",
1063             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1064             options.remote_forwards[i].listen_port,
1065             options.remote_forwards[i].connect_host,
1066             options.remote_forwards[i].connect_port);
1067         if (type == SSH2_MSG_REQUEST_FAILURE) {
1068                 if (options.exit_on_forward_failure)
1069                         fatal("Error: remote port forwarding failed for "
1070                             "listen port %d",
1071                             options.remote_forwards[i].listen_port);
1072                 else
1073                         logit("Warning: remote port forwarding failed for "
1074                             "listen port %d",
1075                             options.remote_forwards[i].listen_port);
1076         }
1077 }
1078
1079 static void
1080 ssh_control_listener(void)
1081 {
1082         struct sockaddr_un addr;
1083         mode_t old_umask;
1084         int addr_len;
1085
1086         if (options.control_path == NULL ||
1087             options.control_master == SSHCTL_MASTER_NO)
1088                 return;
1089
1090         debug("setting up multiplex master socket");
1091
1092         memset(&addr, '\0', sizeof(addr));
1093         addr.sun_family = AF_UNIX;
1094         addr_len = offsetof(struct sockaddr_un, sun_path) +
1095             strlen(options.control_path) + 1;
1096
1097         if (strlcpy(addr.sun_path, options.control_path,
1098             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1099                 fatal("ControlPath too long");
1100
1101         if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1102                 fatal("%s socket(): %s", __func__, strerror(errno));
1103
1104         old_umask = umask(0177);
1105         if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1106                 control_fd = -1;
1107                 if (errno == EINVAL || errno == EADDRINUSE)
1108                         fatal("ControlSocket %s already exists",
1109                             options.control_path);
1110                 else
1111                         fatal("%s bind(): %s", __func__, strerror(errno));
1112         }
1113         umask(old_umask);
1114
1115         if (listen(control_fd, 64) == -1)
1116                 fatal("%s listen(): %s", __func__, strerror(errno));
1117
1118         set_nonblock(control_fd);
1119 }
1120
1121 /* request pty/x11/agent/tcpfwd/shell for channel */
1122 static void
1123 ssh_session2_setup(int id, void *arg)
1124 {
1125         extern char **environ;
1126         const char *display;
1127         int interactive = tty_flag;
1128
1129         display = getenv("DISPLAY");
1130         if (options.forward_x11 && display != NULL) {
1131                 char *proto, *data;
1132                 /* Get reasonable local authentication information. */
1133                 client_x11_get_proto(display, options.xauth_location,
1134                     options.forward_x11_trusted, &proto, &data);
1135                 /* Request forwarding with authentication spoofing. */
1136                 debug("Requesting X11 forwarding with authentication spoofing.");
1137                 x11_request_forwarding_with_spoofing(id, display, proto, data);
1138                 interactive = 1;
1139                 /* XXX wait for reply */
1140         }
1141
1142         check_agent_present();
1143         if (options.forward_agent) {
1144                 debug("Requesting authentication agent forwarding.");
1145                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1146                 packet_send();
1147         }
1148
1149         if (options.tun_open != SSH_TUNMODE_NO) {
1150                 Channel *c;
1151                 int fd;
1152
1153                 debug("Requesting tun.");
1154                 if ((fd = tun_open(options.tun_local,
1155                     options.tun_open)) >= 0) {
1156                         if(options.hpn_disabled)
1157                                 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1158                                     CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1159                                     0, "tun", 1);
1160                         else
1161                                 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1162                                     options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1163                                     0, "tun", 1);
1164                         c->datagram = 1;
1165 #if defined(SSH_TUN_FILTER)
1166                         if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1167                                 channel_register_filter(c->self, sys_tun_infilter,
1168                                     sys_tun_outfilter);
1169 #endif
1170                         packet_start(SSH2_MSG_CHANNEL_OPEN);
1171                         packet_put_cstring("tun@openssh.com");
1172                         packet_put_int(c->self);
1173                         packet_put_int(c->local_window_max);
1174                         packet_put_int(c->local_maxpacket);
1175                         packet_put_int(options.tun_open);
1176                         packet_put_int(options.tun_remote);
1177                         packet_send();
1178                 }
1179         }
1180
1181         client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1182             NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1183
1184         packet_set_interactive(interactive);
1185 }
1186
1187 /* open new channel for a session */
1188 static int
1189 ssh_session2_open(void)
1190 {
1191         Channel *c;
1192         int window, packetmax, in, out, err;
1193         int sock;
1194         int socksize;
1195         int socksizelen = sizeof(int);
1196
1197         if (stdin_null_flag) {
1198                 in = open(_PATH_DEVNULL, O_RDONLY);
1199         } else {
1200                 in = dup(STDIN_FILENO);
1201         }
1202         out = dup(STDOUT_FILENO);
1203         err = dup(STDERR_FILENO);
1204
1205         if (in < 0 || out < 0 || err < 0)
1206                 fatal("dup() in/out/err failed");
1207
1208         /* enable nonblocking unless tty */
1209         if (!isatty(in))
1210                 set_nonblock(in);
1211         if (!isatty(out))
1212                 set_nonblock(out);
1213         if (!isatty(err))
1214                 set_nonblock(err);
1215
1216         /* we need to check to see if what they want to do about buffer */
1217         /* sizes here. In a hpn to nonhpn connection we want to limit */
1218         /* the window size to something reasonable in case the far side */
1219         /* has the large window bug. In hpn to hpn connection we want to */
1220         /* use the max window size but allow the user to override it */
1221         /* lastly if they disabled hpn then use the ssh std window size */
1222
1223         /* so why don't we just do a getsockopt() here and set the */
1224         /* ssh window to that? In the case of a autotuning receive */
1225         /* window the window would get stuck at the initial buffer */
1226         /* size generally less than 96k. Therefore we need to set the */
1227         /* maximum ssh window size to the maximum hpn buffer size */
1228         /* unless the user hasspecifically set the hpnrcvbufpoll */
1229         /* to no. In which case we *can* just set the window to the */
1230         /* minimum of the hpn buffer size and tcp receive buffer size */
1231         
1232         if(options.hpn_disabled)
1233         {
1234                 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1235         }
1236         else if (datafellows & SSH_BUG_LARGEWINDOW) 
1237         {
1238                 debug("HPN to Non-HPN Connection");
1239                 if (options.hpn_buffer_size < 0)
1240                         options.hpn_buffer_size = 2*1024*1024;
1241         } 
1242         else 
1243         {
1244                 if (options.hpn_buffer_size < 0)
1245                         options.hpn_buffer_size = BUFFER_MAX_LEN_HPN;
1246                 if (options.tcp_rcv_buf_poll <= 0) 
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                         options.hpn_buffer_size = MIN(socksize,options.hpn_buffer_size);                        
1261                 } 
1262                 else
1263                 {
1264                         if (options.tcp_rcv_buf > 0) 
1265                                 options.hpn_buffer_size = MIN(options.tcp_rcv_buf, options.hpn_buffer_size);
1266                 }
1267                 
1268         }
1269
1270         debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1271
1272         window = options.hpn_buffer_size;
1273
1274         packetmax = CHAN_SES_PACKET_DEFAULT;
1275         if (tty_flag) {
1276                 window = 4*CHAN_SES_PACKET_DEFAULT;
1277                 window >>= 1;
1278                 packetmax >>= 1;
1279         }
1280         c = channel_new(
1281             "session", SSH_CHANNEL_OPENING, in, out, err,
1282             window, packetmax, CHAN_EXTENDED_WRITE,
1283             "client-session", /*nonblock*/0);
1284         if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1285                 c->dynamic_window = 1;
1286                 debug ("Enabled Dynamic Window Scaling\n");
1287         }
1288         debug3("ssh_session2_open: channel_new: %d", c->self);
1289
1290         channel_send_open(c->self);
1291         if (!no_shell_flag)
1292                 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1293
1294         return c->self;
1295 }
1296
1297 static int
1298 ssh_session2(void)
1299 {
1300         int id = -1;
1301
1302         /* XXX should be pre-session */
1303         ssh_init_forwarding();
1304         ssh_control_listener();
1305
1306         if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1307                 id = ssh_session2_open();
1308
1309         /* Execute a local command */
1310         if (options.local_command != NULL &&
1311             options.permit_local_command)
1312                 ssh_local_cmd(options.local_command);
1313
1314         /* If requested, let ssh continue in the background. */
1315         if (fork_after_authentication_flag)
1316                 if (daemon(1, 1) < 0)
1317                         fatal("daemon() failed: %.200s", strerror(errno));
1318
1319         return client_loop(tty_flag, tty_flag ?
1320             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1321 }
1322
1323 static void
1324 load_public_identity_files(void)
1325 {
1326         char *filename, *cp, thishost[NI_MAXHOST];
1327         int i = 0;
1328         Key *public;
1329         struct passwd *pw;
1330 #ifdef SMARTCARD
1331         Key **keys;
1332
1333         if (options.smartcard_device != NULL &&
1334             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1335             (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1336                 int count = 0;
1337                 for (i = 0; keys[i] != NULL; i++) {
1338                         count++;
1339                         memmove(&options.identity_files[1], &options.identity_files[0],
1340                             sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1341                         memmove(&options.identity_keys[1], &options.identity_keys[0],
1342                             sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1343                         options.num_identity_files++;
1344                         options.identity_keys[0] = keys[i];
1345                         options.identity_files[0] = sc_get_key_label(keys[i]);
1346                 }
1347                 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1348                         options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1349                 i = count;
1350                 xfree(keys);
1351         }
1352 #endif /* SMARTCARD */
1353         if ((pw = getpwuid(original_real_uid)) == NULL)
1354                 fatal("load_public_identity_files: getpwuid failed");
1355         if (gethostname(thishost, sizeof(thishost)) == -1)
1356                 fatal("load_public_identity_files: gethostname: %s",
1357                     strerror(errno));
1358         for (; i < options.num_identity_files; i++) {
1359                 cp = tilde_expand_filename(options.identity_files[i],
1360                     original_real_uid);
1361                 filename = percent_expand(cp, "d", pw->pw_dir,
1362                     "u", pw->pw_name, "l", thishost, "h", host,
1363                     "r", options.user, (char *)NULL);
1364                 xfree(cp);
1365                 public = key_load_public(filename, NULL);
1366                 debug("identity file %s type %d", filename,
1367                     public ? public->type : -1);
1368                 xfree(options.identity_files[i]);
1369                 options.identity_files[i] = filename;
1370                 options.identity_keys[i] = public;
1371         }
1372 }
1373
1374 static void
1375 control_client_sighandler(int signo)
1376 {
1377         control_client_terminate = signo;
1378 }
1379
1380 static void
1381 control_client_sigrelay(int signo)
1382 {
1383         if (control_server_pid > 1)
1384                 kill(control_server_pid, signo);
1385 }
1386
1387 static int
1388 env_permitted(char *env)
1389 {
1390         int i, ret;
1391         char name[1024], *cp;
1392
1393         if ((cp = strchr(env, '=')) == NULL || cp == env)
1394                 return (0);
1395         ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1396         if (ret <= 0 || (size_t)ret >= sizeof(name))
1397                 fatal("env_permitted: name '%.100s...' too long", env);
1398
1399         for (i = 0; i < options.num_send_env; i++)
1400                 if (match_pattern(name, options.send_env[i]))
1401                         return (1);
1402
1403         return (0);
1404 }
1405
1406 static void
1407 control_client(const char *path)
1408 {
1409         struct sockaddr_un addr;
1410         int i, r, fd, sock, exitval, num_env, addr_len;
1411         Buffer m;
1412         char *term;
1413         extern char **environ;
1414         u_int  flags;
1415
1416         if (mux_command == 0)
1417                 mux_command = SSHMUX_COMMAND_OPEN;
1418
1419         switch (options.control_master) {
1420         case SSHCTL_MASTER_AUTO:
1421         case SSHCTL_MASTER_AUTO_ASK:
1422                 debug("auto-mux: Trying existing master");
1423                 /* FALLTHROUGH */
1424         case SSHCTL_MASTER_NO:
1425                 break;
1426         default:
1427                 return;
1428         }
1429
1430         memset(&addr, '\0', sizeof(addr));
1431         addr.sun_family = AF_UNIX;
1432         addr_len = offsetof(struct sockaddr_un, sun_path) +
1433             strlen(path) + 1;
1434
1435         if (strlcpy(addr.sun_path, path,
1436             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1437                 fatal("ControlPath too long");
1438
1439         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1440                 fatal("%s socket(): %s", __func__, strerror(errno));
1441
1442         if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1443                 if (mux_command != SSHMUX_COMMAND_OPEN) {
1444                         fatal("Control socket connect(%.100s): %s", path,
1445                             strerror(errno));
1446                 }
1447                 if (errno == ENOENT)
1448                         debug("Control socket \"%.100s\" does not exist", path);
1449                 else {
1450                         error("Control socket connect(%.100s): %s", path,
1451                             strerror(errno));
1452                 }
1453                 close(sock);
1454                 return;
1455         }
1456
1457         if (stdin_null_flag) {
1458                 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1459                         fatal("open(/dev/null): %s", strerror(errno));
1460                 if (dup2(fd, STDIN_FILENO) == -1)
1461                         fatal("dup2: %s", strerror(errno));
1462                 if (fd > STDERR_FILENO)
1463                         close(fd);
1464         }
1465
1466         term = getenv("TERM");
1467
1468         flags = 0;
1469         if (tty_flag)
1470                 flags |= SSHMUX_FLAG_TTY;
1471         if (subsystem_flag)
1472                 flags |= SSHMUX_FLAG_SUBSYS;
1473         if (options.forward_x11)
1474                 flags |= SSHMUX_FLAG_X11_FWD;
1475         if (options.forward_agent)
1476                 flags |= SSHMUX_FLAG_AGENT_FWD;
1477         if (options.num_local_forwards > 0)
1478                 flags |= SSHMUX_FLAG_PORTFORWARD;
1479         buffer_init(&m);
1480
1481         /* Send our command to server */
1482         buffer_put_int(&m, mux_command);
1483         buffer_put_int(&m, flags);
1484         if (options.num_local_forwards > 0)
1485         {
1486                 if (options.local_forwards[0].listen_host == NULL)
1487                         buffer_put_string(&m,"LOCALHOST",11);
1488                 else
1489                         buffer_put_string(&m,options.local_forwards[0].listen_host,512);
1490                 buffer_put_int(&m,options.local_forwards[0].listen_port);
1491                 buffer_put_string(&m,options.local_forwards[0].connect_host,512);       
1492                 buffer_put_int(&m,options.local_forwards[0].connect_port);
1493         }
1494         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1495                 fatal("%s: msg_send", __func__);
1496         buffer_clear(&m);
1497
1498         /* Get authorisation status and PID of controlee */
1499         if (ssh_msg_recv(sock, &m) == -1)
1500                 fatal("%s: msg_recv", __func__);
1501         if (buffer_get_char(&m) != SSHMUX_VER)
1502                 fatal("%s: wrong version", __func__);
1503         if (buffer_get_int(&m) != 1)
1504                 fatal("Connection to master denied");
1505         control_server_pid = buffer_get_int(&m);
1506
1507         buffer_clear(&m);
1508
1509         switch (mux_command) {
1510         case SSHMUX_COMMAND_ALIVE_CHECK:
1511                 fprintf(stderr, "Master running (pid=%d)\r\n",
1512                     control_server_pid);
1513                 exit(0);
1514         case SSHMUX_COMMAND_TERMINATE:
1515                 fprintf(stderr, "Exit request sent.\r\n");
1516                 exit(0);
1517         case SSHMUX_COMMAND_OPEN:
1518                 /* continue below */
1519                 break;
1520         default:
1521                 fatal("silly mux_command %d", mux_command);
1522         }
1523
1524         /* SSHMUX_COMMAND_OPEN */
1525         buffer_put_cstring(&m, term ? term : "");
1526         buffer_append(&command, "\0", 1);
1527         buffer_put_cstring(&m, buffer_ptr(&command));
1528
1529         if (options.num_send_env == 0 || environ == NULL) {
1530                 buffer_put_int(&m, 0);
1531         } else {
1532                 /* Pass environment */
1533                 num_env = 0;
1534                 for (i = 0; environ[i] != NULL; i++)
1535                         if (env_permitted(environ[i]))
1536                                 num_env++; /* Count */
1537
1538                 buffer_put_int(&m, num_env);
1539
1540                 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1541                         if (env_permitted(environ[i])) {
1542                                 num_env--;
1543                                 buffer_put_cstring(&m, environ[i]);
1544                         }
1545         }
1546
1547         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1548                 fatal("%s: msg_send", __func__);
1549
1550         mm_send_fd(sock, STDIN_FILENO);
1551         mm_send_fd(sock, STDOUT_FILENO);
1552         mm_send_fd(sock, STDERR_FILENO);
1553
1554         /* Wait for reply, so master has a chance to gather ttymodes */
1555         buffer_clear(&m);
1556         if (ssh_msg_recv(sock, &m) == -1)
1557                 fatal("%s: msg_recv", __func__);
1558         if (buffer_get_char(&m) != SSHMUX_VER)
1559                 fatal("%s: wrong version", __func__);
1560         buffer_free(&m);
1561
1562         signal(SIGHUP, control_client_sighandler);
1563         signal(SIGINT, control_client_sighandler);
1564         signal(SIGTERM, control_client_sighandler);
1565         signal(SIGWINCH, control_client_sigrelay);
1566
1567         if (tty_flag)
1568                 enter_raw_mode();
1569
1570         /* Stick around until the controlee closes the client_fd */
1571         exitval = 0;
1572         for (;!control_client_terminate;) {
1573                 r = read(sock, &exitval, sizeof(exitval));
1574                 if (r == 0) {
1575                         debug2("Received EOF from master");
1576                         break;
1577                 }
1578                 if (r > 0)
1579                         debug2("Received exit status from master %d", exitval);
1580                 if (r == -1 && errno != EINTR)
1581                         fatal("%s: read %s", __func__, strerror(errno));
1582         }
1583
1584         if (control_client_terminate)
1585                 debug2("Exiting on signal %d", control_client_terminate);
1586
1587         close(sock);
1588
1589         leave_raw_mode();
1590
1591         if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1592                 fprintf(stderr, "Connection to master closed.\r\n");
1593
1594         exit(exitval);
1595 }
This page took 3.225464 seconds and 5 git commands to generate.