]> andersk Git - gssapi-openssh.git/blob - openssh/ssh.c
OPENSSH_4_5P1_20070215 merged to GPT branch
[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_pathnames();
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:L: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 'i':
331                         if (stat(optarg, &st) < 0) {
332                                 fprintf(stderr, "Warning: Identity file %s "
333                                     "not accessible: %s.\n", optarg,
334                                     strerror(errno));
335                                 break;
336                         }
337                         if (options.num_identity_files >=
338                             SSH_MAX_IDENTITY_FILES)
339                                 fatal("Too many identity files specified "
340                                     "(max %d)", SSH_MAX_IDENTITY_FILES);
341                         options.identity_files[options.num_identity_files++] =
342                             xstrdup(optarg);
343                         break;
344                 case 'I':
345 #ifdef SMARTCARD
346                         options.smartcard_device = xstrdup(optarg);
347 #else
348                         fprintf(stderr, "no support for smartcards.\n");
349 #endif
350                         break;
351                 case 't':
352                         if (tty_flag)
353                                 force_tty_flag = 1;
354                         tty_flag = 1;
355                         break;
356                 case 'v':
357                         if (debug_flag == 0) {
358                                 debug_flag = 1;
359                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
360                         } else {
361                                 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
362                                         options.log_level++;
363                                 break;
364                         }
365                         /* FALLTHROUGH */
366                 case 'V':
367                         fprintf(stderr, "%s, %s\n",
368                             SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
369                         if (opt == 'V')
370                                 exit(0);
371                         break;
372                 case 'w':
373                         if (options.tun_open == -1)
374                                 options.tun_open = SSH_TUNMODE_DEFAULT;
375                         options.tun_local = a2tun(optarg, &options.tun_remote);
376                         if (options.tun_local == SSH_TUNID_ERR) {
377                                 fprintf(stderr, "Bad tun device '%s'\n", optarg);
378                                 exit(255);
379                         }
380                         break;
381                 case 'q':
382                         options.log_level = SYSLOG_LEVEL_QUIET;
383                         break;
384                 case 'e':
385                         if (optarg[0] == '^' && optarg[2] == 0 &&
386                             (u_char) optarg[1] >= 64 &&
387                             (u_char) optarg[1] < 128)
388                                 options.escape_char = (u_char) optarg[1] & 31;
389                         else if (strlen(optarg) == 1)
390                                 options.escape_char = (u_char) optarg[0];
391                         else if (strcmp(optarg, "none") == 0)
392                                 options.escape_char = SSH_ESCAPECHAR_NONE;
393                         else {
394                                 fprintf(stderr, "Bad escape character '%s'.\n",
395                                     optarg);
396                                 exit(255);
397                         }
398                         break;
399                 case 'c':
400                         if (ciphers_valid(optarg)) {
401                                 /* SSH2 only */
402                                 options.ciphers = xstrdup(optarg);
403                                 options.cipher = SSH_CIPHER_INVALID;
404                         } else {
405                                 /* SSH1 only */
406                                 options.cipher = cipher_number(optarg);
407                                 if (options.cipher == -1) {
408                                         fprintf(stderr,
409                                             "Unknown cipher type '%s'\n",
410                                             optarg);
411                                         exit(255);
412                                 }
413                                 if (options.cipher == SSH_CIPHER_3DES)
414                                         options.ciphers = "3des-cbc";
415                                 else if (options.cipher == SSH_CIPHER_BLOWFISH)
416                                         options.ciphers = "blowfish-cbc";
417                                 else
418                                         options.ciphers = (char *)-1;
419                         }
420                         break;
421                 case 'm':
422                         if (mac_valid(optarg))
423                                 options.macs = xstrdup(optarg);
424                         else {
425                                 fprintf(stderr, "Unknown mac type '%s'\n",
426                                     optarg);
427                                 exit(255);
428                         }
429                         break;
430                 case 'M':
431                         if (options.control_master == SSHCTL_MASTER_YES)
432                                 options.control_master = SSHCTL_MASTER_ASK;
433                         else
434                                 options.control_master = SSHCTL_MASTER_YES;
435                         break;
436                 case 'p':
437                         options.port = a2port(optarg);
438                         if (options.port == 0) {
439                                 fprintf(stderr, "Bad port '%s'\n", optarg);
440                                 exit(255);
441                         }
442                         break;
443                 case 'l':
444                         options.user = optarg;
445                         break;
446
447                 case 'L':
448                         if (parse_forward(&fwd, optarg))
449                                 add_local_forward(&options, &fwd);
450                         else {
451                                 fprintf(stderr,
452                                     "Bad local forwarding specification '%s'\n",
453                                     optarg);
454                                 exit(255);
455                         }
456                         break;
457
458                 case 'R':
459                         if (parse_forward(&fwd, optarg)) {
460                                 add_remote_forward(&options, &fwd);
461                         } else {
462                                 fprintf(stderr,
463                                     "Bad remote forwarding specification "
464                                     "'%s'\n", optarg);
465                                 exit(255);
466                         }
467                         break;
468
469                 case 'D':
470                         cp = p = xstrdup(optarg);
471                         memset(&fwd, '\0', sizeof(fwd));
472                         fwd.connect_host = "socks";
473                         if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
474                                 fprintf(stderr, "Bad dynamic forwarding "
475                                     "specification '%.100s'\n", optarg);
476                                 exit(255);
477                         }
478                         if (cp != NULL) {
479                                 fwd.listen_port = a2port(cp);
480                                 fwd.listen_host = cleanhostname(fwd.listen_host);
481                         } else {
482                                 fwd.listen_port = a2port(fwd.listen_host);
483                                 fwd.listen_host = NULL;
484                         }
485
486                         if (fwd.listen_port == 0) {
487                                 fprintf(stderr, "Bad dynamic port '%s'\n",
488                                     optarg);
489                                 exit(255);
490                         }
491                         add_local_forward(&options, &fwd);
492                         xfree(p);
493                         break;
494
495                 case 'C':
496                         options.compression = 1;
497                         break;
498                 case 'N':
499                         no_shell_flag = 1;
500                         no_tty_flag = 1;
501                         break;
502                 case 'o':
503                         dummy = 1;
504                         line = xstrdup(optarg);
505                         if (process_config_line(&options, host ? host : "",
506                             line, "command-line", 0, &dummy) != 0)
507                                 exit(255);
508                         xfree(line);
509                         break;
510                 case 'T':
511                         no_tty_flag = 1;
512                         /* ensure that the user doesn't try to backdoor a */
513                         /* null cipher switch on an interactive session */
514                         /* so explicitly disable it no matter what */
515                         options.none_switch=0;
516                         break;
517                 case 's':
518                         subsystem_flag = 1;
519                         break;
520                 case 'S':
521                         if (options.control_path != NULL)
522                                 free(options.control_path);
523                         options.control_path = xstrdup(optarg);
524                         break;
525                 case 'b':
526                         options.bind_address = optarg;
527                         break;
528                 case 'F':
529                         config = optarg;
530                         break;
531                 default:
532                         usage();
533                 }
534         }
535
536         ac -= optind;
537         av += optind;
538
539         if (ac > 0 && !host && **av != '-') {
540                 if (strrchr(*av, '@')) {
541                         p = xstrdup(*av);
542                         cp = strrchr(p, '@');
543                         if (cp == NULL || cp == p)
544                                 usage();
545                         options.user = p;
546                         *cp = '\0';
547                         host = ++cp;
548                 } else
549                         host = *av;
550                 if (ac > 1) {
551                         optind = optreset = 1;
552                         goto again;
553                 }
554                 ac--, av++;
555         }
556
557         /* Check that we got a host name. */
558         if (!host)
559                 usage();
560
561         SSLeay_add_all_algorithms();
562         ERR_load_crypto_strings();
563
564         /* Initialize the command to execute on remote host. */
565         buffer_init(&command);
566
567         /*
568          * Save the command to execute on the remote host in a buffer. There
569          * is no limit on the length of the command, except by the maximum
570          * packet size.  Also sets the tty flag if there is no command.
571          */
572         if (!ac) {
573                 /* No command specified - execute shell on a tty. */
574                 tty_flag = 1;
575                 if (subsystem_flag) {
576                         fprintf(stderr,
577                             "You must specify a subsystem to invoke.\n");
578                         usage();
579                 }
580         } else {
581                 /* A command has been specified.  Store it into the buffer. */
582                 for (i = 0; i < ac; i++) {
583                         if (i)
584                                 buffer_append(&command, " ", 1);
585                         buffer_append(&command, av[i], strlen(av[i]));
586                 }
587         }
588
589         /* Cannot fork to background if no command. */
590         if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
591                 fatal("Cannot fork into background without a command to execute.");
592
593         /* Allocate a tty by default if no command specified. */
594         if (buffer_len(&command) == 0)
595                 tty_flag = 1;
596
597         /* Force no tty */
598         if (no_tty_flag)
599                 tty_flag = 0;
600         /* Do not allocate a tty if stdin is not a tty. */
601         if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
602                 if (tty_flag)
603                         logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
604                 tty_flag = 0;
605         }
606
607         /*
608          * Initialize "log" output.  Since we are the client all output
609          * actually goes to stderr.
610          */
611         log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
612             SYSLOG_FACILITY_USER, 1);
613
614         /*
615          * Read per-user configuration file.  Ignore the system wide config
616          * file if the user specifies a config file on the command line.
617          */
618         if (config != NULL) {
619                 if (!read_config_file(config, host, &options, 0))
620                         fatal("Can't open user config file %.100s: "
621                             "%.100s", config, strerror(errno));
622         } else  {
623             /*
624              * Since the config file parsing code aborts if it sees
625              * options it doesn't recognize, allow users to put
626              * options specific to compile-time add-ons in alternate
627              * config files so their primary config file will
628              * interoperate SSH versions that don't support those
629              * options.
630              */
631 #ifdef GSSAPI
632                 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
633                     _PATH_SSH_USER_CONFFILE);
634                 (void)read_config_file(buf, host, &options, 1);
635 #ifdef GSI
636                 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
637                     _PATH_SSH_USER_CONFFILE);
638                 (void)read_config_file(buf, host, &options, 1);
639 #endif
640 #if defined(KRB5)
641                 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
642                     _PATH_SSH_USER_CONFFILE);
643                 (void)read_config_file(buf, host, &options, 1);
644 #endif
645 #endif
646                 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
647                     _PATH_SSH_USER_CONFFILE);
648                 (void)read_config_file(buf, host, &options, 1);
649
650                 /* Read systemwide configuration file after use config. */
651                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
652                     &options, 0);
653         }
654
655         /* Fill configuration defaults. */
656         fill_default_options(&options);
657
658         channel_set_af(options.address_family);
659
660         /* reinit */
661         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
662
663         seed_rng();
664
665         if (options.user == NULL) {
666                 options.user = xstrdup(pw->pw_name);
667                 options.implicit = 1;
668         }
669         else options.implicit = 0;
670
671         if (options.hostname != NULL)
672                 host = options.hostname;
673
674         /* force lowercase for hostkey matching */
675         if (options.host_key_alias != NULL) {
676                 for (p = options.host_key_alias; *p; p++)
677                         if (isupper(*p))
678                                 *p = (char)tolower(*p);
679         }
680
681         /* Get default port if port has not been set. */
682         if (options.port == 0) {
683                 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
684                 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
685         }
686
687         if (options.proxy_command != NULL &&
688             strcmp(options.proxy_command, "none") == 0)
689                 options.proxy_command = NULL;
690         if (options.control_path != NULL &&
691             strcmp(options.control_path, "none") == 0)
692                 options.control_path = NULL;
693
694         if (options.control_path != NULL) {
695                 char thishost[NI_MAXHOST];
696
697                 if (gethostname(thishost, sizeof(thishost)) == -1)
698                         fatal("gethostname: %s", strerror(errno));
699                 snprintf(buf, sizeof(buf), "%d", options.port);
700                 cp = tilde_expand_filename(options.control_path,
701                     original_real_uid);
702                 options.control_path = percent_expand(cp, "p", buf, "h", host,
703                     "r", options.user, "l", thishost, (char *)NULL);
704                 xfree(cp);
705         }
706         if (mux_command != 0 && options.control_path == NULL)
707                 fatal("No ControlPath specified for \"-O\" command");
708         if (options.control_path != NULL)
709                 control_client(options.control_path);
710
711         /* Open a connection to the remote host. */
712         if (ssh_connect(host, &hostaddr, options.port,
713             options.address_family, options.connection_attempts,
714 #ifdef HAVE_CYGWIN
715             options.use_privileged_port,
716 #else
717             original_effective_uid == 0 && options.use_privileged_port,
718 #endif
719             options.proxy_command) != 0)
720                 exit(255);
721
722         /*
723          * If we successfully made the connection, load the host private key
724          * in case we will need it later for combined rsa-rhosts
725          * authentication. This must be done before releasing extra
726          * privileges, because the file is only readable by root.
727          * If we cannot access the private keys, load the public keys
728          * instead and try to execute the ssh-keysign helper instead.
729          */
730         sensitive_data.nkeys = 0;
731         sensitive_data.keys = NULL;
732         sensitive_data.external_keysign = 0;
733         if (options.rhosts_rsa_authentication ||
734             options.hostbased_authentication) {
735                 sensitive_data.nkeys = 3;
736                 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
737                     sizeof(Key));
738
739                 PRIV_START;
740                 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
741                     _PATH_HOST_KEY_FILE, "", NULL, NULL);
742                 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
743                     _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
744                 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
745                     _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
746                 PRIV_END;
747
748                 if (options.hostbased_authentication == 1 &&
749                     sensitive_data.keys[0] == NULL &&
750                     sensitive_data.keys[1] == NULL &&
751                     sensitive_data.keys[2] == NULL) {
752                         sensitive_data.keys[1] = key_load_public(
753                             _PATH_HOST_DSA_KEY_FILE, NULL);
754                         sensitive_data.keys[2] = key_load_public(
755                             _PATH_HOST_RSA_KEY_FILE, NULL);
756                         sensitive_data.external_keysign = 1;
757                 }
758         }
759         /*
760          * Get rid of any extra privileges that we may have.  We will no
761          * longer need them.  Also, extra privileges could make it very hard
762          * to read identity files and other non-world-readable files from the
763          * user's home directory if it happens to be on a NFS volume where
764          * root is mapped to nobody.
765          */
766         if (original_effective_uid == 0) {
767                 PRIV_START;
768                 permanently_set_uid(pw);
769         }
770
771         /*
772          * Now that we are back to our own permissions, create ~/.ssh
773          * directory if it doesn't already exist.
774          */
775         snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
776         if (stat(buf, &st) < 0)
777                 if (mkdir(buf, 0700) < 0)
778                         error("Could not create directory '%.200s'.", buf);
779
780         /* load options.identity_files */
781         load_public_identity_files();
782
783         /* Expand ~ in known host file names. */
784         /* XXX mem-leaks: */
785         options.system_hostfile =
786             tilde_expand_filename(options.system_hostfile, original_real_uid);
787         options.user_hostfile =
788             tilde_expand_filename(options.user_hostfile, original_real_uid);
789         options.system_hostfile2 =
790             tilde_expand_filename(options.system_hostfile2, original_real_uid);
791         options.user_hostfile2 =
792             tilde_expand_filename(options.user_hostfile2, original_real_uid);
793
794         signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
795
796         /* Log into the remote system.  This never returns if the login fails. */
797         ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
798
799         /* We no longer need the private host keys.  Clear them now. */
800         if (sensitive_data.nkeys != 0) {
801                 for (i = 0; i < sensitive_data.nkeys; i++) {
802                         if (sensitive_data.keys[i] != NULL) {
803                                 /* Destroys contents safely */
804                                 debug3("clear hostkey %d", i);
805                                 key_free(sensitive_data.keys[i]);
806                                 sensitive_data.keys[i] = NULL;
807                         }
808                 }
809                 xfree(sensitive_data.keys);
810         }
811         for (i = 0; i < options.num_identity_files; i++) {
812                 if (options.identity_files[i]) {
813                         xfree(options.identity_files[i]);
814                         options.identity_files[i] = NULL;
815                 }
816                 if (options.identity_keys[i]) {
817                         key_free(options.identity_keys[i]);
818                         options.identity_keys[i] = NULL;
819                 }
820         }
821
822         exit_status = compat20 ? ssh_session2() : ssh_session();
823         packet_close();
824
825         if (options.control_path != NULL && control_fd != -1)
826                 unlink(options.control_path);
827
828         /*
829          * Send SIGHUP to proxy command if used. We don't wait() in
830          * case it hangs and instead rely on init to reap the child
831          */
832         if (proxy_command_pid > 1)
833                 kill(proxy_command_pid, SIGHUP);
834
835         return exit_status;
836 }
837
838 static void
839 ssh_init_forwarding(void)
840 {
841         int success = 0;
842         int i;
843
844         /* Initiate local TCP/IP port forwardings. */
845         for (i = 0; i < options.num_local_forwards; i++) {
846                 debug("Local connections to %.200s:%d forwarded to remote "
847                     "address %.200s:%d",
848                     (options.local_forwards[i].listen_host == NULL) ?
849                     (options.gateway_ports ? "*" : "LOCALHOST") :
850                     options.local_forwards[i].listen_host,
851                     options.local_forwards[i].listen_port,
852                     options.local_forwards[i].connect_host,
853                     options.local_forwards[i].connect_port);
854                 success += channel_setup_local_fwd_listener(
855                     options.local_forwards[i].listen_host,
856                     options.local_forwards[i].listen_port,
857                     options.local_forwards[i].connect_host,
858                     options.local_forwards[i].connect_port,
859                     options.gateway_ports, options.hpn_disabled,
860                     options.hpn_buffer_size);
861         }
862         if (i > 0 && success != i && options.exit_on_forward_failure)
863                 fatal("Could not request local forwarding.");
864         if (i > 0 && success == 0)
865                 error("Could not request local forwarding.");
866
867         /* Initiate remote TCP/IP port forwardings. */
868         for (i = 0; i < options.num_remote_forwards; i++) {
869                 debug("Remote connections from %.200s:%d forwarded to "
870                     "local address %.200s:%d",
871                     (options.remote_forwards[i].listen_host == NULL) ?
872                     "LOCALHOST" : options.remote_forwards[i].listen_host,
873                     options.remote_forwards[i].listen_port,
874                     options.remote_forwards[i].connect_host,
875                     options.remote_forwards[i].connect_port);
876                 if (channel_request_remote_forwarding(
877                     options.remote_forwards[i].listen_host,
878                     options.remote_forwards[i].listen_port,
879                     options.remote_forwards[i].connect_host,
880                     options.remote_forwards[i].connect_port) < 0) {
881                         if (options.exit_on_forward_failure)
882                                 fatal("Could not request remote forwarding.");
883                         else
884                                 logit("Warning: Could not request remote "
885                                     "forwarding.");
886                 }
887         }
888 }
889
890 static void
891 check_agent_present(void)
892 {
893         if (options.forward_agent) {
894                 /* Clear agent forwarding if we don't have an agent. */
895                 if (!ssh_agent_present())
896                         options.forward_agent = 0;
897         }
898 }
899
900 static int
901 ssh_session(void)
902 {
903         int type;
904         int interactive = 0;
905         int have_tty = 0;
906         struct winsize ws;
907         char *cp;
908         const char *display;
909
910         /* Enable compression if requested. */
911         if (options.compression) {
912                 debug("Requesting compression at level %d.", options.compression_level);
913
914                 if (options.compression_level < 1 || options.compression_level > 9)
915                         fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
916
917                 /* Send the request. */
918                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
919                 packet_put_int(options.compression_level);
920                 packet_send();
921                 packet_write_wait();
922                 type = packet_read();
923                 if (type == SSH_SMSG_SUCCESS)
924                         packet_start_compression(options.compression_level);
925                 else if (type == SSH_SMSG_FAILURE)
926                         logit("Warning: Remote host refused compression.");
927                 else
928                         packet_disconnect("Protocol error waiting for compression response.");
929         }
930         /* Allocate a pseudo tty if appropriate. */
931         if (tty_flag) {
932                 debug("Requesting pty.");
933
934                 /* Start the packet. */
935                 packet_start(SSH_CMSG_REQUEST_PTY);
936
937                 /* Store TERM in the packet.  There is no limit on the
938                    length of the string. */
939                 cp = getenv("TERM");
940                 if (!cp)
941                         cp = "";
942                 packet_put_cstring(cp);
943
944                 /* Store window size in the packet. */
945                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
946                         memset(&ws, 0, sizeof(ws));
947                 packet_put_int((u_int)ws.ws_row);
948                 packet_put_int((u_int)ws.ws_col);
949                 packet_put_int((u_int)ws.ws_xpixel);
950                 packet_put_int((u_int)ws.ws_ypixel);
951
952                 /* Store tty modes in the packet. */
953                 tty_make_modes(fileno(stdin), NULL);
954
955                 /* Send the packet, and wait for it to leave. */
956                 packet_send();
957                 packet_write_wait();
958
959                 /* Read response from the server. */
960                 type = packet_read();
961                 if (type == SSH_SMSG_SUCCESS) {
962                         interactive = 1;
963                         have_tty = 1;
964                 } else if (type == SSH_SMSG_FAILURE)
965                         logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
966                 else
967                         packet_disconnect("Protocol error waiting for pty request response.");
968         }
969         /* Request X11 forwarding if enabled and DISPLAY is set. */
970         display = getenv("DISPLAY");
971         if (options.forward_x11 && display != NULL) {
972                 char *proto, *data;
973                 /* Get reasonable local authentication information. */
974                 client_x11_get_proto(display, options.xauth_location,
975                     options.forward_x11_trusted, &proto, &data);
976                 /* Request forwarding with authentication spoofing. */
977                 debug("Requesting X11 forwarding with authentication spoofing.");
978                 x11_request_forwarding_with_spoofing(0, display, proto, data);
979
980                 /* Read response from the server. */
981                 type = packet_read();
982                 if (type == SSH_SMSG_SUCCESS) {
983                         interactive = 1;
984                 } else if (type == SSH_SMSG_FAILURE) {
985                         logit("Warning: Remote host denied X11 forwarding.");
986                 } else {
987                         packet_disconnect("Protocol error waiting for X11 forwarding");
988                 }
989         }
990         /* Tell the packet module whether this is an interactive session. */
991         packet_set_interactive(interactive);
992
993         /* Request authentication agent forwarding if appropriate. */
994         check_agent_present();
995
996         if (options.forward_agent) {
997                 debug("Requesting authentication agent forwarding.");
998                 auth_request_forwarding();
999
1000                 /* Read response from the server. */
1001                 type = packet_read();
1002                 packet_check_eom();
1003                 if (type != SSH_SMSG_SUCCESS)
1004                         logit("Warning: Remote host denied authentication agent forwarding.");
1005         }
1006
1007         /* Initiate port forwardings. */
1008         ssh_init_forwarding();
1009
1010         /* If requested, let ssh continue in the background. */
1011         if (fork_after_authentication_flag)
1012                 if (daemon(1, 1) < 0)
1013                         fatal("daemon() failed: %.200s", strerror(errno));
1014
1015         /*
1016          * If a command was specified on the command line, execute the
1017          * command now. Otherwise request the server to start a shell.
1018          */
1019         if (buffer_len(&command) > 0) {
1020                 int len = buffer_len(&command);
1021                 if (len > 900)
1022                         len = 900;
1023                 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1024                 packet_start(SSH_CMSG_EXEC_CMD);
1025                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1026                 packet_send();
1027                 packet_write_wait();
1028         } else {
1029                 debug("Requesting shell.");
1030                 packet_start(SSH_CMSG_EXEC_SHELL);
1031                 packet_send();
1032                 packet_write_wait();
1033         }
1034
1035         /* Enter the interactive session. */
1036         return client_loop(have_tty, tty_flag ?
1037             options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1038 }
1039
1040 static void
1041 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1042 {
1043         int id, len;
1044
1045         id = packet_get_int();
1046         len = buffer_len(&command);
1047         if (len > 900)
1048                 len = 900;
1049         packet_check_eom();
1050         if (type == SSH2_MSG_CHANNEL_FAILURE)
1051                 fatal("Request for subsystem '%.*s' failed on channel %d",
1052                     len, (u_char *)buffer_ptr(&command), id);
1053 }
1054
1055 void
1056 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1057 {
1058         int i;
1059
1060         i = client_global_request_id++;
1061         if (i >= options.num_remote_forwards)
1062                 return;
1063         debug("remote forward %s for: listen %d, connect %s:%d",
1064             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1065             options.remote_forwards[i].listen_port,
1066             options.remote_forwards[i].connect_host,
1067             options.remote_forwards[i].connect_port);
1068         if (type == SSH2_MSG_REQUEST_FAILURE) {
1069                 if (options.exit_on_forward_failure)
1070                         fatal("Error: remote port forwarding failed for "
1071                             "listen port %d",
1072                             options.remote_forwards[i].listen_port);
1073                 else
1074                         logit("Warning: remote port forwarding failed for "
1075                             "listen port %d",
1076                             options.remote_forwards[i].listen_port);
1077         }
1078 }
1079
1080 static void
1081 ssh_control_listener(void)
1082 {
1083         struct sockaddr_un addr;
1084         mode_t old_umask;
1085         int addr_len;
1086
1087         if (options.control_path == NULL ||
1088             options.control_master == SSHCTL_MASTER_NO)
1089                 return;
1090
1091         debug("setting up multiplex master socket");
1092
1093         memset(&addr, '\0', sizeof(addr));
1094         addr.sun_family = AF_UNIX;
1095         addr_len = offsetof(struct sockaddr_un, sun_path) +
1096             strlen(options.control_path) + 1;
1097
1098         if (strlcpy(addr.sun_path, options.control_path,
1099             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1100                 fatal("ControlPath too long");
1101
1102         if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1103                 fatal("%s socket(): %s", __func__, strerror(errno));
1104
1105         old_umask = umask(0177);
1106         if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1107                 control_fd = -1;
1108                 if (errno == EINVAL || errno == EADDRINUSE)
1109                         fatal("ControlSocket %s already exists",
1110                             options.control_path);
1111                 else
1112                         fatal("%s bind(): %s", __func__, strerror(errno));
1113         }
1114         umask(old_umask);
1115
1116         if (listen(control_fd, 64) == -1)
1117                 fatal("%s listen(): %s", __func__, strerror(errno));
1118
1119         set_nonblock(control_fd);
1120 }
1121
1122 /* request pty/x11/agent/tcpfwd/shell for channel */
1123 static void
1124 ssh_session2_setup(int id, void *arg)
1125 {
1126         extern char **environ;
1127         const char *display;
1128         int interactive = tty_flag;
1129
1130         display = getenv("DISPLAY");
1131         if (options.forward_x11 && display != NULL) {
1132                 char *proto, *data;
1133                 /* Get reasonable local authentication information. */
1134                 client_x11_get_proto(display, options.xauth_location,
1135                     options.forward_x11_trusted, &proto, &data);
1136                 /* Request forwarding with authentication spoofing. */
1137                 debug("Requesting X11 forwarding with authentication spoofing.");
1138                 x11_request_forwarding_with_spoofing(id, display, proto, data);
1139                 interactive = 1;
1140                 /* XXX wait for reply */
1141         }
1142
1143         check_agent_present();
1144         if (options.forward_agent) {
1145                 debug("Requesting authentication agent forwarding.");
1146                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1147                 packet_send();
1148         }
1149
1150         if (options.tun_open != SSH_TUNMODE_NO) {
1151                 Channel *c;
1152                 int fd;
1153
1154                 debug("Requesting tun.");
1155                 if ((fd = tun_open(options.tun_local,
1156                     options.tun_open)) >= 0) {
1157                         if(options.hpn_disabled)
1158                                 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1159                                     CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1160                                     0, "tun", 1);
1161                         else
1162                                 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1163                                     options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1164                                     0, "tun", 1);
1165                         c->datagram = 1;
1166 #if defined(SSH_TUN_FILTER)
1167                         if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1168                                 channel_register_filter(c->self, sys_tun_infilter,
1169                                     sys_tun_outfilter);
1170 #endif
1171                         packet_start(SSH2_MSG_CHANNEL_OPEN);
1172                         packet_put_cstring("tun@openssh.com");
1173                         packet_put_int(c->self);
1174                         packet_put_int(c->local_window_max);
1175                         packet_put_int(c->local_maxpacket);
1176                         packet_put_int(options.tun_open);
1177                         packet_put_int(options.tun_remote);
1178                         packet_send();
1179                 }
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 hasspecifically set the hpnrcvbufpoll */
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         if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1289                 c->dynamic_window = 1;
1290                 debug ("Enabled Dynamic Window Scaling\n");
1291         }
1292         debug3("ssh_session2_open: channel_new: %d", c->self);
1293
1294         channel_send_open(c->self);
1295         if (!no_shell_flag)
1296                 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1297
1298         return c->self;
1299 }
1300
1301 static int
1302 ssh_session2(void)
1303 {
1304         int id = -1;
1305
1306         /* XXX should be pre-session */
1307         ssh_init_forwarding();
1308         ssh_control_listener();
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         /* If requested, let ssh continue in the background. */
1319         if (fork_after_authentication_flag)
1320                 if (daemon(1, 1) < 0)
1321                         fatal("daemon() failed: %.200s", strerror(errno));
1322
1323         return client_loop(tty_flag, tty_flag ?
1324             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1325 }
1326
1327 static void
1328 load_public_identity_files(void)
1329 {
1330         char *filename, *cp, thishost[NI_MAXHOST];
1331         int i = 0;
1332         Key *public;
1333         struct passwd *pw;
1334 #ifdef SMARTCARD
1335         Key **keys;
1336
1337         if (options.smartcard_device != NULL &&
1338             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1339             (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1340                 int count = 0;
1341                 for (i = 0; keys[i] != NULL; i++) {
1342                         count++;
1343                         memmove(&options.identity_files[1], &options.identity_files[0],
1344                             sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1345                         memmove(&options.identity_keys[1], &options.identity_keys[0],
1346                             sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1347                         options.num_identity_files++;
1348                         options.identity_keys[0] = keys[i];
1349                         options.identity_files[0] = sc_get_key_label(keys[i]);
1350                 }
1351                 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1352                         options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1353                 i = count;
1354                 xfree(keys);
1355         }
1356 #endif /* SMARTCARD */
1357         if ((pw = getpwuid(original_real_uid)) == NULL)
1358                 fatal("load_public_identity_files: getpwuid failed");
1359         if (gethostname(thishost, sizeof(thishost)) == -1)
1360                 fatal("load_public_identity_files: gethostname: %s",
1361                     strerror(errno));
1362         for (; i < options.num_identity_files; i++) {
1363                 cp = tilde_expand_filename(options.identity_files[i],
1364                     original_real_uid);
1365                 filename = percent_expand(cp, "d", pw->pw_dir,
1366                     "u", pw->pw_name, "l", thishost, "h", host,
1367                     "r", options.user, (char *)NULL);
1368                 xfree(cp);
1369                 public = key_load_public(filename, NULL);
1370                 debug("identity file %s type %d", filename,
1371                     public ? public->type : -1);
1372                 xfree(options.identity_files[i]);
1373                 options.identity_files[i] = filename;
1374                 options.identity_keys[i] = public;
1375         }
1376 }
1377
1378 static void
1379 control_client_sighandler(int signo)
1380 {
1381         control_client_terminate = signo;
1382 }
1383
1384 static void
1385 control_client_sigrelay(int signo)
1386 {
1387         if (control_server_pid > 1)
1388                 kill(control_server_pid, signo);
1389 }
1390
1391 static int
1392 env_permitted(char *env)
1393 {
1394         int i, ret;
1395         char name[1024], *cp;
1396
1397         if ((cp = strchr(env, '=')) == NULL || cp == env)
1398                 return (0);
1399         ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1400         if (ret <= 0 || (size_t)ret >= sizeof(name))
1401                 fatal("env_permitted: name '%.100s...' too long", env);
1402
1403         for (i = 0; i < options.num_send_env; i++)
1404                 if (match_pattern(name, options.send_env[i]))
1405                         return (1);
1406
1407         return (0);
1408 }
1409
1410 static void
1411 control_client(const char *path)
1412 {
1413         struct sockaddr_un addr;
1414         int i, r, fd, sock, exitval, num_env, addr_len;
1415         Buffer m;
1416         char *term;
1417         extern char **environ;
1418         u_int  flags;
1419
1420         if (mux_command == 0)
1421                 mux_command = SSHMUX_COMMAND_OPEN;
1422
1423         switch (options.control_master) {
1424         case SSHCTL_MASTER_AUTO:
1425         case SSHCTL_MASTER_AUTO_ASK:
1426                 debug("auto-mux: Trying existing master");
1427                 /* FALLTHROUGH */
1428         case SSHCTL_MASTER_NO:
1429                 break;
1430         default:
1431                 return;
1432         }
1433
1434         memset(&addr, '\0', sizeof(addr));
1435         addr.sun_family = AF_UNIX;
1436         addr_len = offsetof(struct sockaddr_un, sun_path) +
1437             strlen(path) + 1;
1438
1439         if (strlcpy(addr.sun_path, path,
1440             sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1441                 fatal("ControlPath too long");
1442
1443         if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1444                 fatal("%s socket(): %s", __func__, strerror(errno));
1445
1446         if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1447                 if (mux_command != SSHMUX_COMMAND_OPEN) {
1448                         fatal("Control socket connect(%.100s): %s", path,
1449                             strerror(errno));
1450                 }
1451                 if (errno == ENOENT)
1452                         debug("Control socket \"%.100s\" does not exist", path);
1453                 else {
1454                         error("Control socket connect(%.100s): %s", path,
1455                             strerror(errno));
1456                 }
1457                 close(sock);
1458                 return;
1459         }
1460
1461         if (stdin_null_flag) {
1462                 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1463                         fatal("open(/dev/null): %s", strerror(errno));
1464                 if (dup2(fd, STDIN_FILENO) == -1)
1465                         fatal("dup2: %s", strerror(errno));
1466                 if (fd > STDERR_FILENO)
1467                         close(fd);
1468         }
1469
1470         term = getenv("TERM");
1471
1472         flags = 0;
1473         if (tty_flag)
1474                 flags |= SSHMUX_FLAG_TTY;
1475         if (subsystem_flag)
1476                 flags |= SSHMUX_FLAG_SUBSYS;
1477         if (options.forward_x11)
1478                 flags |= SSHMUX_FLAG_X11_FWD;
1479         if (options.forward_agent)
1480                 flags |= SSHMUX_FLAG_AGENT_FWD;
1481         if (options.num_local_forwards > 0)
1482                 flags |= SSHMUX_FLAG_PORTFORWARD;
1483         buffer_init(&m);
1484
1485         /* Send our command to server */
1486         buffer_put_int(&m, mux_command);
1487         buffer_put_int(&m, flags);
1488         if (options.num_local_forwards > 0)
1489         {
1490                 if (options.local_forwards[0].listen_host == NULL)
1491                         buffer_put_string(&m,"LOCALHOST",11);
1492                 else
1493                         buffer_put_string(&m,options.local_forwards[0].listen_host,512);
1494                 buffer_put_int(&m,options.local_forwards[0].listen_port);
1495                 buffer_put_string(&m,options.local_forwards[0].connect_host,512);       
1496                 buffer_put_int(&m,options.local_forwards[0].connect_port);
1497         }
1498         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1499                 fatal("%s: msg_send", __func__);
1500         buffer_clear(&m);
1501
1502         /* Get authorisation status and PID of controlee */
1503         if (ssh_msg_recv(sock, &m) == -1)
1504                 fatal("%s: msg_recv", __func__);
1505         if (buffer_get_char(&m) != SSHMUX_VER)
1506                 fatal("%s: wrong version", __func__);
1507         if (buffer_get_int(&m) != 1)
1508                 fatal("Connection to master denied");
1509         control_server_pid = buffer_get_int(&m);
1510
1511         buffer_clear(&m);
1512
1513         switch (mux_command) {
1514         case SSHMUX_COMMAND_ALIVE_CHECK:
1515                 fprintf(stderr, "Master running (pid=%d)\r\n",
1516                     control_server_pid);
1517                 exit(0);
1518         case SSHMUX_COMMAND_TERMINATE:
1519                 fprintf(stderr, "Exit request sent.\r\n");
1520                 exit(0);
1521         case SSHMUX_COMMAND_OPEN:
1522                 /* continue below */
1523                 break;
1524         default:
1525                 fatal("silly mux_command %d", mux_command);
1526         }
1527
1528         /* SSHMUX_COMMAND_OPEN */
1529         buffer_put_cstring(&m, term ? term : "");
1530         buffer_append(&command, "\0", 1);
1531         buffer_put_cstring(&m, buffer_ptr(&command));
1532
1533         if (options.num_send_env == 0 || environ == NULL) {
1534                 buffer_put_int(&m, 0);
1535         } else {
1536                 /* Pass environment */
1537                 num_env = 0;
1538                 for (i = 0; environ[i] != NULL; i++)
1539                         if (env_permitted(environ[i]))
1540                                 num_env++; /* Count */
1541
1542                 buffer_put_int(&m, num_env);
1543
1544                 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1545                         if (env_permitted(environ[i])) {
1546                                 num_env--;
1547                                 buffer_put_cstring(&m, environ[i]);
1548                         }
1549         }
1550
1551         if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1552                 fatal("%s: msg_send", __func__);
1553
1554         mm_send_fd(sock, STDIN_FILENO);
1555         mm_send_fd(sock, STDOUT_FILENO);
1556         mm_send_fd(sock, STDERR_FILENO);
1557
1558         /* Wait for reply, so master has a chance to gather ttymodes */
1559         buffer_clear(&m);
1560         if (ssh_msg_recv(sock, &m) == -1)
1561                 fatal("%s: msg_recv", __func__);
1562         if (buffer_get_char(&m) != SSHMUX_VER)
1563                 fatal("%s: wrong version", __func__);
1564         buffer_free(&m);
1565
1566         signal(SIGHUP, control_client_sighandler);
1567         signal(SIGINT, control_client_sighandler);
1568         signal(SIGTERM, control_client_sighandler);
1569         signal(SIGWINCH, control_client_sigrelay);
1570
1571         if (tty_flag)
1572                 enter_raw_mode();
1573
1574         /* Stick around until the controlee closes the client_fd */
1575         exitval = 0;
1576         for (;!control_client_terminate;) {
1577                 r = read(sock, &exitval, sizeof(exitval));
1578                 if (r == 0) {
1579                         debug2("Received EOF from master");
1580                         break;
1581                 }
1582                 if (r > 0)
1583                         debug2("Received exit status from master %d", exitval);
1584                 if (r == -1 && errno != EINTR)
1585                         fatal("%s: read %s", __func__, strerror(errno));
1586         }
1587
1588         if (control_client_terminate)
1589                 debug2("Exiting on signal %d", control_client_terminate);
1590
1591         close(sock);
1592
1593         leave_raw_mode();
1594
1595         if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1596                 fprintf(stderr, "Connection to master closed.\r\n");
1597
1598         exit(exitval);
1599 }
This page took 2.753229 seconds and 5 git commands to generate.