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