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