]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/ssh.c
Merge Cavium Octeon SDK 2.0 Simple Executive; this brings some fixes and new
[FreeBSD/FreeBSD.git] / crypto / openssh / ssh.c
1 /* $OpenBSD: ssh.c,v 1.346 2010/08/12 21:49:44 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 __RCSID("$FreeBSD$");
45
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
49 #endif
50 #include <sys/resource.h>
51 #include <sys/ioctl.h>
52 #include <sys/param.h>
53 #include <sys/socket.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 /* pid of proxycommand child process */
187 pid_t proxy_command_pid = 0;
188
189 /* mux.c */
190 extern int muxserver_sock;
191 extern u_int muxclient_command;
192
193 /* Prints a help message to the user.  This function never returns. */
194
195 static void
196 usage(void)
197 {
198         fprintf(stderr,
199 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
200 "           [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
201 "           [-I pkcs11] [-i identity_file]\n"
202 "           [-L [bind_address:]port:host:hostport]\n"
203 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
204 "           [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
205 "           [-W host:port] [-w local_tun[:remote_tun]]\n"
206 "           [user@]hostname [command]\n"
207         );
208         exit(255);
209 }
210
211 static int ssh_session(void);
212 static int ssh_session2(void);
213 static void load_public_identity_files(void);
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];
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_RELEASE, SSLeay_version(SSLEAY_VERSION));
409                         if (opt == 'V')
410                                 exit(0);
411                         break;
412                 case 'w':
413                         if (options.tun_open == -1)
414                                 options.tun_open = SSH_TUNMODE_DEFAULT;
415                         options.tun_local = a2tun(optarg, &options.tun_remote);
416                         if (options.tun_local == SSH_TUNID_ERR) {
417                                 fprintf(stderr,
418                                     "Bad tun device '%s'\n", optarg);
419                                 exit(255);
420                         }
421                         break;
422                 case 'W':
423                         if (stdio_forward_host != NULL)
424                                 fatal("stdio forward already specified");
425                         if (muxclient_command != 0)
426                                 fatal("Cannot specify stdio forward with -O");
427                         if (parse_forward(&fwd, optarg, 1, 0)) {
428                                 stdio_forward_host = fwd.listen_host;
429                                 stdio_forward_port = fwd.listen_port;
430                                 xfree(fwd.connect_host);
431                         } else {
432                                 fprintf(stderr,
433                                     "Bad stdio forwarding specification '%s'\n",
434                                     optarg);
435                                 exit(255);
436                         }
437                         no_tty_flag = 1;
438                         no_shell_flag = 1;
439                         options.clear_forwardings = 1;
440                         options.exit_on_forward_failure = 1;
441                         break;
442                 case 'q':
443                         options.log_level = SYSLOG_LEVEL_QUIET;
444                         break;
445                 case 'e':
446                         if (optarg[0] == '^' && optarg[2] == 0 &&
447                             (u_char) optarg[1] >= 64 &&
448                             (u_char) optarg[1] < 128)
449                                 options.escape_char = (u_char) optarg[1] & 31;
450                         else if (strlen(optarg) == 1)
451                                 options.escape_char = (u_char) optarg[0];
452                         else if (strcmp(optarg, "none") == 0)
453                                 options.escape_char = SSH_ESCAPECHAR_NONE;
454                         else {
455                                 fprintf(stderr, "Bad escape character '%s'.\n",
456                                     optarg);
457                                 exit(255);
458                         }
459                         break;
460                 case 'c':
461                         if (ciphers_valid(optarg)) {
462                                 /* SSH2 only */
463                                 options.ciphers = xstrdup(optarg);
464                                 options.cipher = SSH_CIPHER_INVALID;
465                         } else {
466                                 /* SSH1 only */
467                                 options.cipher = cipher_number(optarg);
468                                 if (options.cipher == -1) {
469                                         fprintf(stderr,
470                                             "Unknown cipher type '%s'\n",
471                                             optarg);
472                                         exit(255);
473                                 }
474                                 if (options.cipher == SSH_CIPHER_3DES)
475                                         options.ciphers = "3des-cbc";
476                                 else if (options.cipher == SSH_CIPHER_BLOWFISH)
477                                         options.ciphers = "blowfish-cbc";
478                                 else
479                                         options.ciphers = (char *)-1;
480                         }
481                         break;
482                 case 'm':
483                         if (mac_valid(optarg))
484                                 options.macs = xstrdup(optarg);
485                         else {
486                                 fprintf(stderr, "Unknown mac type '%s'\n",
487                                     optarg);
488                                 exit(255);
489                         }
490                         break;
491                 case 'M':
492                         if (options.control_master == SSHCTL_MASTER_YES)
493                                 options.control_master = SSHCTL_MASTER_ASK;
494                         else
495                                 options.control_master = SSHCTL_MASTER_YES;
496                         break;
497                 case 'p':
498                         options.port = a2port(optarg);
499                         if (options.port <= 0) {
500                                 fprintf(stderr, "Bad port '%s'\n", optarg);
501                                 exit(255);
502                         }
503                         break;
504                 case 'l':
505                         options.user = optarg;
506                         break;
507
508                 case 'L':
509                         if (parse_forward(&fwd, optarg, 0, 0))
510                                 add_local_forward(&options, &fwd);
511                         else {
512                                 fprintf(stderr,
513                                     "Bad local forwarding specification '%s'\n",
514                                     optarg);
515                                 exit(255);
516                         }
517                         break;
518
519                 case 'R':
520                         if (parse_forward(&fwd, optarg, 0, 1)) {
521                                 add_remote_forward(&options, &fwd);
522                         } else {
523                                 fprintf(stderr,
524                                     "Bad remote forwarding specification "
525                                     "'%s'\n", optarg);
526                                 exit(255);
527                         }
528                         break;
529
530                 case 'D':
531                         if (parse_forward(&fwd, optarg, 1, 0)) {
532                                 add_local_forward(&options, &fwd);
533                         } else {
534                                 fprintf(stderr,
535                                     "Bad dynamic forwarding specification "
536                                     "'%s'\n", optarg);
537                                 exit(255);
538                         }
539                         break;
540
541                 case 'C':
542                         options.compression = 1;
543                         break;
544                 case 'N':
545                         no_shell_flag = 1;
546                         no_tty_flag = 1;
547                         break;
548                 case 'T':
549                         no_tty_flag = 1;
550                         break;
551                 case 'o':
552                         dummy = 1;
553                         line = xstrdup(optarg);
554                         if (process_config_line(&options, host ? host : "",
555                             line, "command-line", 0, &dummy) != 0)
556                                 exit(255);
557                         xfree(line);
558                         break;
559                 case 's':
560                         subsystem_flag = 1;
561                         break;
562                 case 'S':
563                         if (options.control_path != NULL)
564                                 free(options.control_path);
565                         options.control_path = xstrdup(optarg);
566                         break;
567                 case 'b':
568                         options.bind_address = optarg;
569                         break;
570                 case 'F':
571                         config = optarg;
572                         break;
573                 default:
574                         usage();
575                 }
576         }
577
578         ac -= optind;
579         av += optind;
580
581         if (ac > 0 && !host) {
582                 if (strrchr(*av, '@')) {
583                         p = xstrdup(*av);
584                         cp = strrchr(p, '@');
585                         if (cp == NULL || cp == p)
586                                 usage();
587                         options.user = p;
588                         *cp = '\0';
589                         host = ++cp;
590                 } else
591                         host = *av;
592                 if (ac > 1) {
593                         optind = optreset = 1;
594                         goto again;
595                 }
596                 ac--, av++;
597         }
598
599         /* Check that we got a host name. */
600         if (!host)
601                 usage();
602
603         SSLeay_add_all_algorithms();
604         ERR_load_crypto_strings();
605
606         /* Initialize the command to execute on remote host. */
607         buffer_init(&command);
608
609         /*
610          * Save the command to execute on the remote host in a buffer. There
611          * is no limit on the length of the command, except by the maximum
612          * packet size.  Also sets the tty flag if there is no command.
613          */
614         if (!ac) {
615                 /* No command specified - execute shell on a tty. */
616                 tty_flag = 1;
617                 if (subsystem_flag) {
618                         fprintf(stderr,
619                             "You must specify a subsystem to invoke.\n");
620                         usage();
621                 }
622         } else {
623                 /* A command has been specified.  Store it into the buffer. */
624                 for (i = 0; i < ac; i++) {
625                         if (i)
626                                 buffer_append(&command, " ", 1);
627                         buffer_append(&command, av[i], strlen(av[i]));
628                 }
629         }
630
631         /* Cannot fork to background if no command. */
632         if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
633             !no_shell_flag)
634                 fatal("Cannot fork into background without a command "
635                     "to execute.");
636
637         /* Allocate a tty by default if no command specified. */
638         if (buffer_len(&command) == 0)
639                 tty_flag = 1;
640
641         /* Force no tty */
642         if (no_tty_flag || muxclient_command != 0)
643                 tty_flag = 0;
644         /* Do not allocate a tty if stdin is not a tty. */
645         if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
646                 if (tty_flag)
647                         logit("Pseudo-terminal will not be allocated because "
648                             "stdin is not a terminal.");
649                 tty_flag = 0;
650         }
651
652         /*
653          * Initialize "log" output.  Since we are the client all output
654          * actually goes to stderr.
655          */
656         log_init(argv0,
657             options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
658             SYSLOG_FACILITY_USER, !use_syslog);
659
660         /*
661          * Read per-user configuration file.  Ignore the system wide config
662          * file if the user specifies a config file on the command line.
663          */
664         if (config != NULL) {
665                 if (!read_config_file(config, host, &options, 0))
666                         fatal("Can't open user config file %.100s: "
667                             "%.100s", config, strerror(errno));
668         } else {
669                 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
670                     _PATH_SSH_USER_CONFFILE);
671                 if (r > 0 && (size_t)r < sizeof(buf))
672                         (void)read_config_file(buf, host, &options, 1);
673
674                 /* Read systemwide configuration file after use config. */
675                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
676                     &options, 0);
677         }
678
679         /* Fill configuration defaults. */
680         fill_default_options(&options);
681
682         channel_set_af(options.address_family);
683
684         /* reinit */
685         log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
686
687         seed_rng();
688
689         if (options.user == NULL)
690                 options.user = xstrdup(pw->pw_name);
691
692         /* Get default port if port has not been set. */
693         if (options.port == 0) {
694                 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
695                 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
696         }
697
698         if (options.hostname != NULL) {
699                 host = percent_expand(options.hostname,
700                     "h", host, (char *)NULL);
701         }
702
703         if (options.local_command != NULL) {
704                 char thishost[NI_MAXHOST];
705
706                 if (gethostname(thishost, sizeof(thishost)) == -1)
707                         fatal("gethostname: %s", strerror(errno));
708                 snprintf(buf, sizeof(buf), "%d", options.port);
709                 debug3("expanding LocalCommand: %s", options.local_command);
710                 cp = options.local_command;
711                 options.local_command = percent_expand(cp, "d", pw->pw_dir,
712                     "h", host, "l", thishost, "n", host, "r", options.user,
713                     "p", buf, "u", pw->pw_name, (char *)NULL);
714                 debug3("expanded LocalCommand: %s", options.local_command);
715                 xfree(cp);
716         }
717
718         /* Find canonic host name. */
719         if (strchr(host, '.') == 0) {
720                 struct addrinfo hints;
721                 struct addrinfo *ai = NULL;
722                 int errgai;
723                 memset(&hints, 0, sizeof(hints));
724                 hints.ai_family = options.address_family;
725                 hints.ai_flags = AI_CANONNAME;
726                 hints.ai_socktype = SOCK_STREAM;
727                 errgai = getaddrinfo(host, NULL, &hints, &ai);
728                 if (errgai == 0) {
729                         if (ai->ai_canonname != NULL)
730                                 host = xstrdup(ai->ai_canonname);
731                         freeaddrinfo(ai);
732                 }
733         }
734
735         /* force lowercase for hostkey matching */
736         if (options.host_key_alias != NULL) {
737                 for (p = options.host_key_alias; *p; p++)
738                         if (isupper(*p))
739                                 *p = (char)tolower(*p);
740         }
741
742         if (options.proxy_command != NULL &&
743             strcmp(options.proxy_command, "none") == 0) {
744                 xfree(options.proxy_command);
745                 options.proxy_command = NULL;
746         }
747         if (options.control_path != NULL &&
748             strcmp(options.control_path, "none") == 0) {
749                 xfree(options.control_path);
750                 options.control_path = NULL;
751         }
752
753         if (options.control_path != NULL) {
754                 char thishost[NI_MAXHOST];
755
756                 if (gethostname(thishost, sizeof(thishost)) == -1)
757                         fatal("gethostname: %s", strerror(errno));
758                 snprintf(buf, sizeof(buf), "%d", options.port);
759                 cp = tilde_expand_filename(options.control_path,
760                     original_real_uid);
761                 xfree(options.control_path);
762                 options.control_path = percent_expand(cp, "p", buf, "h", host,
763                     "r", options.user, "l", thishost, (char *)NULL);
764                 xfree(cp);
765         }
766         if (muxclient_command != 0 && options.control_path == NULL)
767                 fatal("No ControlPath specified for \"-O\" command");
768         if (options.control_path != NULL)
769                 muxclient(options.control_path);
770
771         timeout_ms = options.connection_timeout * 1000;
772
773         /* Open a connection to the remote host. */
774         if (ssh_connect(host, &hostaddr, options.port,
775             options.address_family, options.connection_attempts, &timeout_ms,
776             options.tcp_keep_alive, 
777 #ifdef HAVE_CYGWIN
778             options.use_privileged_port,
779 #else
780             original_effective_uid == 0 && options.use_privileged_port,
781 #endif
782             options.proxy_command) != 0)
783                 exit(255);
784
785         if (timeout_ms > 0)
786                 debug3("timeout: %d ms remain after connect", timeout_ms);
787
788         /*
789          * If we successfully made the connection, load the host private key
790          * in case we will need it later for combined rsa-rhosts
791          * authentication. This must be done before releasing extra
792          * privileges, because the file is only readable by root.
793          * If we cannot access the private keys, load the public keys
794          * instead and try to execute the ssh-keysign helper instead.
795          */
796         sensitive_data.nkeys = 0;
797         sensitive_data.keys = NULL;
798         sensitive_data.external_keysign = 0;
799         if (options.rhosts_rsa_authentication ||
800             options.hostbased_authentication) {
801                 sensitive_data.nkeys = 5;
802                 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
803                     sizeof(Key));
804
805                 PRIV_START;
806                 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
807                     _PATH_HOST_KEY_FILE, "", NULL, NULL);
808                 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
809                     _PATH_HOST_DSA_KEY_FILE, "", NULL);
810                 sensitive_data.keys[2] = key_load_private_cert(KEY_RSA,
811                     _PATH_HOST_RSA_KEY_FILE, "", NULL);
812                 sensitive_data.keys[3] = key_load_private_type(KEY_DSA,
813                     _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
814                 sensitive_data.keys[4] = key_load_private_type(KEY_RSA,
815                     _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
816                 PRIV_END;
817
818                 if (options.hostbased_authentication == 1 &&
819                     sensitive_data.keys[0] == NULL &&
820                     sensitive_data.keys[3] == NULL &&
821                     sensitive_data.keys[4] == NULL) {
822                         sensitive_data.keys[1] = key_load_cert(
823                             _PATH_HOST_DSA_KEY_FILE);
824                         sensitive_data.keys[2] = key_load_cert(
825                             _PATH_HOST_RSA_KEY_FILE);
826                         sensitive_data.keys[3] = key_load_public(
827                             _PATH_HOST_DSA_KEY_FILE, NULL);
828                         sensitive_data.keys[4] = key_load_public(
829                             _PATH_HOST_RSA_KEY_FILE, NULL);
830                         sensitive_data.external_keysign = 1;
831                 }
832         }
833         /*
834          * Get rid of any extra privileges that we may have.  We will no
835          * longer need them.  Also, extra privileges could make it very hard
836          * to read identity files and other non-world-readable files from the
837          * user's home directory if it happens to be on a NFS volume where
838          * root is mapped to nobody.
839          */
840         if (original_effective_uid == 0) {
841                 PRIV_START;
842                 permanently_set_uid(pw);
843         }
844
845         /*
846          * Now that we are back to our own permissions, create ~/.ssh
847          * directory if it doesn't already exist.
848          */
849         r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
850             strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
851         if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
852                 if (mkdir(buf, 0700) < 0)
853                         error("Could not create directory '%.200s'.", buf);
854
855         /* load options.identity_files */
856         load_public_identity_files();
857
858         /* Expand ~ in known host file names. */
859         /* XXX mem-leaks: */
860         options.system_hostfile =
861             tilde_expand_filename(options.system_hostfile, original_real_uid);
862         options.user_hostfile =
863             tilde_expand_filename(options.user_hostfile, original_real_uid);
864         options.system_hostfile2 =
865             tilde_expand_filename(options.system_hostfile2, original_real_uid);
866         options.user_hostfile2 =
867             tilde_expand_filename(options.user_hostfile2, original_real_uid);
868
869         signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
870
871         /* Log into the remote system.  Never returns if the login fails. */
872         ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
873             pw, timeout_ms);
874
875         if (packet_connection_is_on_socket()) {
876                 verbose("Authenticated to %s ([%s]:%d).", host,
877                     get_remote_ipaddr(), get_remote_port());
878         } else {
879                 verbose("Authenticated to %s (via proxy).", host);
880         }
881
882         /* We no longer need the private host keys.  Clear them now. */
883         if (sensitive_data.nkeys != 0) {
884                 for (i = 0; i < sensitive_data.nkeys; i++) {
885                         if (sensitive_data.keys[i] != NULL) {
886                                 /* Destroys contents safely */
887                                 debug3("clear hostkey %d", i);
888                                 key_free(sensitive_data.keys[i]);
889                                 sensitive_data.keys[i] = NULL;
890                         }
891                 }
892                 xfree(sensitive_data.keys);
893         }
894         for (i = 0; i < options.num_identity_files; i++) {
895                 if (options.identity_files[i]) {
896                         xfree(options.identity_files[i]);
897                         options.identity_files[i] = NULL;
898                 }
899                 if (options.identity_keys[i]) {
900                         key_free(options.identity_keys[i]);
901                         options.identity_keys[i] = NULL;
902                 }
903         }
904
905         exit_status = compat20 ? ssh_session2() : ssh_session();
906         packet_close();
907
908         if (options.control_path != NULL && muxserver_sock != -1)
909                 unlink(options.control_path);
910
911         /*
912          * Send SIGHUP to proxy command if used. We don't wait() in
913          * case it hangs and instead rely on init to reap the child
914          */
915         if (proxy_command_pid > 1)
916                 kill(proxy_command_pid, SIGHUP);
917
918         return exit_status;
919 }
920
921 static void
922 control_persist_detach(void)
923 {
924         pid_t pid;
925         int devnull;
926
927         debug("%s: backgrounding master process", __func__);
928
929         /*
930          * master (current process) into the background, and make the
931          * foreground process a client of the backgrounded master.
932          */
933         switch ((pid = fork())) {
934         case -1:
935                 fatal("%s: fork: %s", __func__, strerror(errno));
936         case 0:
937                 /* Child: master process continues mainloop */
938                 break;
939         default:
940                 /* Parent: set up mux slave to connect to backgrounded master */
941                 debug2("%s: background process is %ld", __func__, (long)pid);
942                 stdin_null_flag = ostdin_null_flag;
943                 no_shell_flag = ono_shell_flag;
944                 no_tty_flag = ono_tty_flag;
945                 tty_flag = otty_flag;
946                 close(muxserver_sock);
947                 muxserver_sock = -1;
948                 muxclient(options.control_path);
949                 /* muxclient() doesn't return on success. */
950                 fatal("Failed to connect to new control master");
951         }
952         if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
953                 error("%s: open(\"/dev/null\"): %s", __func__,
954                     strerror(errno));
955         } else {
956                 if (dup2(devnull, STDIN_FILENO) == -1 ||
957                     dup2(devnull, STDOUT_FILENO) == -1)
958                         error("%s: dup2: %s", __func__, strerror(errno));
959                 if (devnull > STDERR_FILENO)
960                         close(devnull);
961         }
962 }
963
964 /* Do fork() after authentication. Used by "ssh -f" */
965 static void
966 fork_postauth(void)
967 {
968         if (need_controlpersist_detach)
969                 control_persist_detach();
970         debug("forking to background");
971         fork_after_authentication_flag = 0;
972         if (daemon(1, 1) < 0)
973                 fatal("daemon() failed: %.200s", strerror(errno));
974 }
975
976 /* Callback for remote forward global requests */
977 static void
978 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
979 {
980         Forward *rfwd = (Forward *)ctxt;
981
982         /* XXX verbose() on failure? */
983         debug("remote forward %s for: listen %d, connect %s:%d",
984             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
985             rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
986         if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
987                 rfwd->allocated_port = packet_get_int();
988                 logit("Allocated port %u for remote forward to %s:%d",
989                     rfwd->allocated_port,
990                     rfwd->connect_host, rfwd->connect_port);
991         }
992         
993         if (type == SSH2_MSG_REQUEST_FAILURE) {
994                 if (options.exit_on_forward_failure)
995                         fatal("Error: remote port forwarding failed for "
996                             "listen port %d", rfwd->listen_port);
997                 else
998                         logit("Warning: remote port forwarding failed for "
999                             "listen port %d", rfwd->listen_port);
1000         }
1001         if (++remote_forward_confirms_received == options.num_remote_forwards) {
1002                 debug("All remote forwarding requests processed");
1003                 if (fork_after_authentication_flag)
1004                         fork_postauth();
1005         }
1006 }
1007
1008 static void
1009 client_cleanup_stdio_fwd(int id, void *arg)
1010 {
1011         debug("stdio forwarding: done");
1012         cleanup_exit(0);
1013 }
1014
1015 static int
1016 client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect)
1017 {
1018         Channel *c;
1019         int in, out;
1020
1021         debug3("client_setup_stdio_fwd %s:%d", host_to_connect,
1022             port_to_connect);
1023
1024         in = dup(STDIN_FILENO);
1025         out = dup(STDOUT_FILENO);
1026         if (in < 0 || out < 0)
1027                 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1028
1029         if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect,
1030             in, out)) == NULL)
1031                 return 0;
1032         channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1033         return 1;
1034 }
1035
1036 static void
1037 ssh_init_forwarding(void)
1038 {
1039         int success = 0;
1040         int i;
1041
1042         if (stdio_forward_host != NULL) {
1043                 if (!compat20) {
1044                         fatal("stdio forwarding require Protocol 2");
1045                 }
1046                 if (!client_setup_stdio_fwd(stdio_forward_host,
1047                     stdio_forward_port))
1048                         fatal("Failed to connect in stdio forward mode.");
1049         }
1050
1051         /* Initiate local TCP/IP port forwardings. */
1052         for (i = 0; i < options.num_local_forwards; i++) {
1053                 debug("Local connections to %.200s:%d forwarded to remote "
1054                     "address %.200s:%d",
1055                     (options.local_forwards[i].listen_host == NULL) ?
1056                     (options.gateway_ports ? "*" : "LOCALHOST") :
1057                     options.local_forwards[i].listen_host,
1058                     options.local_forwards[i].listen_port,
1059                     options.local_forwards[i].connect_host,
1060                     options.local_forwards[i].connect_port);
1061                 success += channel_setup_local_fwd_listener(
1062                     options.local_forwards[i].listen_host,
1063                     options.local_forwards[i].listen_port,
1064                     options.local_forwards[i].connect_host,
1065                     options.local_forwards[i].connect_port,
1066                     options.gateway_ports);
1067         }
1068         if (i > 0 && success != i && options.exit_on_forward_failure)
1069                 fatal("Could not request local forwarding.");
1070         if (i > 0 && success == 0)
1071                 error("Could not request local forwarding.");
1072
1073         /* Initiate remote TCP/IP port forwardings. */
1074         for (i = 0; i < options.num_remote_forwards; i++) {
1075                 debug("Remote connections from %.200s:%d forwarded to "
1076                     "local address %.200s:%d",
1077                     (options.remote_forwards[i].listen_host == NULL) ?
1078                     "LOCALHOST" : options.remote_forwards[i].listen_host,
1079                     options.remote_forwards[i].listen_port,
1080                     options.remote_forwards[i].connect_host,
1081                     options.remote_forwards[i].connect_port);
1082                 if (channel_request_remote_forwarding(
1083                     options.remote_forwards[i].listen_host,
1084                     options.remote_forwards[i].listen_port,
1085                     options.remote_forwards[i].connect_host,
1086                     options.remote_forwards[i].connect_port) < 0) {
1087                         if (options.exit_on_forward_failure)
1088                                 fatal("Could not request remote forwarding.");
1089                         else
1090                                 logit("Warning: Could not request remote "
1091                                     "forwarding.");
1092                 }
1093                 client_register_global_confirm(ssh_confirm_remote_forward,
1094                     &options.remote_forwards[i]);
1095         }
1096
1097         /* Initiate tunnel forwarding. */
1098         if (options.tun_open != SSH_TUNMODE_NO) {
1099                 if (client_request_tun_fwd(options.tun_open,
1100                     options.tun_local, options.tun_remote) == -1) {
1101                         if (options.exit_on_forward_failure)
1102                                 fatal("Could not request tunnel forwarding.");
1103                         else
1104                                 error("Could not request tunnel forwarding.");
1105                 }
1106         }                       
1107 }
1108
1109 static void
1110 check_agent_present(void)
1111 {
1112         if (options.forward_agent) {
1113                 /* Clear agent forwarding if we don't have an agent. */
1114                 if (!ssh_agent_present())
1115                         options.forward_agent = 0;
1116         }
1117 }
1118
1119 static int
1120 ssh_session(void)
1121 {
1122         int type;
1123         int interactive = 0;
1124         int have_tty = 0;
1125         struct winsize ws;
1126         char *cp;
1127         const char *display;
1128
1129         /* Enable compression if requested. */
1130         if (options.compression) {
1131                 debug("Requesting compression at level %d.",
1132                     options.compression_level);
1133
1134                 if (options.compression_level < 1 ||
1135                     options.compression_level > 9)
1136                         fatal("Compression level must be from 1 (fast) to "
1137                             "9 (slow, best).");
1138
1139                 /* Send the request. */
1140                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1141                 packet_put_int(options.compression_level);
1142                 packet_send();
1143                 packet_write_wait();
1144                 type = packet_read();
1145                 if (type == SSH_SMSG_SUCCESS)
1146                         packet_start_compression(options.compression_level);
1147                 else if (type == SSH_SMSG_FAILURE)
1148                         logit("Warning: Remote host refused compression.");
1149                 else
1150                         packet_disconnect("Protocol error waiting for "
1151                             "compression response.");
1152         }
1153         /* Allocate a pseudo tty if appropriate. */
1154         if (tty_flag) {
1155                 debug("Requesting pty.");
1156
1157                 /* Start the packet. */
1158                 packet_start(SSH_CMSG_REQUEST_PTY);
1159
1160                 /* Store TERM in the packet.  There is no limit on the
1161                    length of the string. */
1162                 cp = getenv("TERM");
1163                 if (!cp)
1164                         cp = "";
1165                 packet_put_cstring(cp);
1166
1167                 /* Store window size in the packet. */
1168                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1169                         memset(&ws, 0, sizeof(ws));
1170                 packet_put_int((u_int)ws.ws_row);
1171                 packet_put_int((u_int)ws.ws_col);
1172                 packet_put_int((u_int)ws.ws_xpixel);
1173                 packet_put_int((u_int)ws.ws_ypixel);
1174
1175                 /* Store tty modes in the packet. */
1176                 tty_make_modes(fileno(stdin), NULL);
1177
1178                 /* Send the packet, and wait for it to leave. */
1179                 packet_send();
1180                 packet_write_wait();
1181
1182                 /* Read response from the server. */
1183                 type = packet_read();
1184                 if (type == SSH_SMSG_SUCCESS) {
1185                         interactive = 1;
1186                         have_tty = 1;
1187                 } else if (type == SSH_SMSG_FAILURE)
1188                         logit("Warning: Remote host failed or refused to "
1189                             "allocate a pseudo tty.");
1190                 else
1191                         packet_disconnect("Protocol error waiting for pty "
1192                             "request response.");
1193         }
1194         /* Request X11 forwarding if enabled and DISPLAY is set. */
1195         display = getenv("DISPLAY");
1196         if (options.forward_x11 && display != NULL) {
1197                 char *proto, *data;
1198                 /* Get reasonable local authentication information. */
1199                 client_x11_get_proto(display, options.xauth_location,
1200                     options.forward_x11_trusted, 
1201                     options.forward_x11_timeout,
1202                     &proto, &data);
1203                 /* Request forwarding with authentication spoofing. */
1204                 debug("Requesting X11 forwarding with authentication "
1205                     "spoofing.");
1206                 x11_request_forwarding_with_spoofing(0, display, proto, data);
1207
1208                 /* Read response from the server. */
1209                 type = packet_read();
1210                 if (type == SSH_SMSG_SUCCESS) {
1211                         interactive = 1;
1212                 } else if (type == SSH_SMSG_FAILURE) {
1213                         logit("Warning: Remote host denied X11 forwarding.");
1214                 } else {
1215                         packet_disconnect("Protocol error waiting for X11 "
1216                             "forwarding");
1217                 }
1218         }
1219         /* Tell the packet module whether this is an interactive session. */
1220         packet_set_interactive(interactive);
1221
1222         /* Request authentication agent forwarding if appropriate. */
1223         check_agent_present();
1224
1225         if (options.forward_agent) {
1226                 debug("Requesting authentication agent forwarding.");
1227                 auth_request_forwarding();
1228
1229                 /* Read response from the server. */
1230                 type = packet_read();
1231                 packet_check_eom();
1232                 if (type != SSH_SMSG_SUCCESS)
1233                         logit("Warning: Remote host denied authentication agent forwarding.");
1234         }
1235
1236         /* Initiate port forwardings. */
1237         ssh_init_forwarding();
1238
1239         /* Execute a local command */
1240         if (options.local_command != NULL &&
1241             options.permit_local_command)
1242                 ssh_local_cmd(options.local_command);
1243
1244         /*
1245          * If requested and we are not interested in replies to remote
1246          * forwarding requests, then let ssh continue in the background.
1247          */
1248         if (fork_after_authentication_flag) {
1249                 if (options.exit_on_forward_failure &&
1250                     options.num_remote_forwards > 0) {
1251                         debug("deferring postauth fork until remote forward "
1252                             "confirmation received");
1253                 } else
1254                         fork_postauth();
1255         }
1256
1257         /*
1258          * If a command was specified on the command line, execute the
1259          * command now. Otherwise request the server to start a shell.
1260          */
1261         if (buffer_len(&command) > 0) {
1262                 int len = buffer_len(&command);
1263                 if (len > 900)
1264                         len = 900;
1265                 debug("Sending command: %.*s", len,
1266                     (u_char *)buffer_ptr(&command));
1267                 packet_start(SSH_CMSG_EXEC_CMD);
1268                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1269                 packet_send();
1270                 packet_write_wait();
1271         } else {
1272                 debug("Requesting shell.");
1273                 packet_start(SSH_CMSG_EXEC_SHELL);
1274                 packet_send();
1275                 packet_write_wait();
1276         }
1277
1278         /* Enter the interactive session. */
1279         return client_loop(have_tty, tty_flag ?
1280             options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1281 }
1282
1283 /* request pty/x11/agent/tcpfwd/shell for channel */
1284 static void
1285 ssh_session2_setup(int id, int success, void *arg)
1286 {
1287         extern char **environ;
1288         const char *display;
1289         int interactive = tty_flag;
1290
1291         if (!success)
1292                 return; /* No need for error message, channels code sens one */
1293
1294         display = getenv("DISPLAY");
1295         if (options.forward_x11 && display != NULL) {
1296                 char *proto, *data;
1297                 /* Get reasonable local authentication information. */
1298                 client_x11_get_proto(display, options.xauth_location,
1299                     options.forward_x11_trusted,
1300                     options.forward_x11_timeout, &proto, &data);
1301                 /* Request forwarding with authentication spoofing. */
1302                 debug("Requesting X11 forwarding with authentication "
1303                     "spoofing.");
1304                 x11_request_forwarding_with_spoofing(id, display, proto, data);
1305                 interactive = 1;
1306                 /* XXX wait for reply */
1307         }
1308
1309         check_agent_present();
1310         if (options.forward_agent) {
1311                 debug("Requesting authentication agent forwarding.");
1312                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1313                 packet_send();
1314         }
1315
1316         client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1317             NULL, fileno(stdin), &command, environ);
1318
1319         packet_set_interactive(interactive);
1320 }
1321
1322 /* open new channel for a session */
1323 static int
1324 ssh_session2_open(void)
1325 {
1326         Channel *c;
1327         int window, packetmax, in, out, err;
1328
1329         if (stdin_null_flag) {
1330                 in = open(_PATH_DEVNULL, O_RDONLY);
1331         } else {
1332                 in = dup(STDIN_FILENO);
1333         }
1334         out = dup(STDOUT_FILENO);
1335         err = dup(STDERR_FILENO);
1336
1337         if (in < 0 || out < 0 || err < 0)
1338                 fatal("dup() in/out/err failed");
1339
1340         /* enable nonblocking unless tty */
1341         if (!isatty(in))
1342                 set_nonblock(in);
1343         if (!isatty(out))
1344                 set_nonblock(out);
1345         if (!isatty(err))
1346                 set_nonblock(err);
1347
1348         window = CHAN_SES_WINDOW_DEFAULT;
1349         packetmax = CHAN_SES_PACKET_DEFAULT;
1350         if (tty_flag) {
1351                 window >>= 1;
1352                 packetmax >>= 1;
1353         }
1354         c = channel_new(
1355             "session", SSH_CHANNEL_OPENING, in, out, err,
1356             window, packetmax, CHAN_EXTENDED_WRITE,
1357             "client-session", /*nonblock*/0);
1358
1359         debug3("ssh_session2_open: channel_new: %d", c->self);
1360
1361         channel_send_open(c->self);
1362         if (!no_shell_flag)
1363                 channel_register_open_confirm(c->self,
1364                     ssh_session2_setup, NULL);
1365
1366         return c->self;
1367 }
1368
1369 static int
1370 ssh_session2(void)
1371 {
1372         int id = -1;
1373
1374         /* XXX should be pre-session */
1375         ssh_init_forwarding();
1376
1377         /* Start listening for multiplex clients */
1378         muxserver_listen();
1379
1380         /*
1381          * If we are in control persist mode, then prepare to background
1382          * ourselves and have a foreground client attach as a control
1383          * slave. NB. we must save copies of the flags that we override for
1384          * the backgrounding, since we defer attachment of the slave until
1385          * after the connection is fully established (in particular,
1386          * async rfwd replies have been received for ExitOnForwardFailure).
1387          */
1388         if (options.control_persist && muxserver_sock != -1) {
1389                 ostdin_null_flag = stdin_null_flag;
1390                 ono_shell_flag = no_shell_flag;
1391                 ono_tty_flag = no_tty_flag;
1392                 otty_flag = tty_flag;
1393                 stdin_null_flag = 1;
1394                 no_shell_flag = 1;
1395                 no_tty_flag = 1;
1396                 tty_flag = 0;
1397                 if (!fork_after_authentication_flag)
1398                         need_controlpersist_detach = 1;
1399                 fork_after_authentication_flag = 1;
1400         }
1401
1402         if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1403                 id = ssh_session2_open();
1404
1405         /* If we don't expect to open a new session, then disallow it */
1406         if (options.control_master == SSHCTL_MASTER_NO &&
1407             (datafellows & SSH_NEW_OPENSSH)) {
1408                 debug("Requesting no-more-sessions@openssh.com");
1409                 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1410                 packet_put_cstring("no-more-sessions@openssh.com");
1411                 packet_put_char(0);
1412                 packet_send();
1413         }
1414
1415         /* Execute a local command */
1416         if (options.local_command != NULL &&
1417             options.permit_local_command)
1418                 ssh_local_cmd(options.local_command);
1419
1420         /*
1421          * If requested and we are not interested in replies to remote
1422          * forwarding requests, then let ssh continue in the background.
1423          */
1424         if (fork_after_authentication_flag) {
1425                 if (options.exit_on_forward_failure &&
1426                     options.num_remote_forwards > 0) {
1427                         debug("deferring postauth fork until remote forward "
1428                             "confirmation received");
1429                 } else
1430                         fork_postauth();
1431         }
1432
1433         if (options.use_roaming)
1434                 request_roaming();
1435
1436         return client_loop(tty_flag, tty_flag ?
1437             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1438 }
1439
1440 static void
1441 load_public_identity_files(void)
1442 {
1443         char *filename, *cp, thishost[NI_MAXHOST];
1444         char *pwdir = NULL, *pwname = NULL;
1445         int i = 0;
1446         Key *public;
1447         struct passwd *pw;
1448         u_int n_ids;
1449         char *identity_files[SSH_MAX_IDENTITY_FILES];
1450         Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1451 #ifdef ENABLE_PKCS11
1452         Key **keys;
1453         int nkeys;
1454 #endif /* PKCS11 */
1455
1456         n_ids = 0;
1457         bzero(identity_files, sizeof(identity_files));
1458         bzero(identity_keys, sizeof(identity_keys));
1459
1460 #ifdef ENABLE_PKCS11
1461         if (options.pkcs11_provider != NULL &&
1462             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1463             (pkcs11_init(!options.batch_mode) == 0) &&
1464             (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1465             &keys)) > 0) {
1466                 for (i = 0; i < nkeys; i++) {
1467                         if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1468                                 key_free(keys[i]);
1469                                 continue;
1470                         }
1471                         identity_keys[n_ids] = keys[i];
1472                         identity_files[n_ids] =
1473                             xstrdup(options.pkcs11_provider); /* XXX */
1474                         n_ids++;
1475                 }
1476                 xfree(keys);
1477         }
1478 #endif /* ENABLE_PKCS11 */
1479         if ((pw = getpwuid(original_real_uid)) == NULL)
1480                 fatal("load_public_identity_files: getpwuid failed");
1481         pwname = xstrdup(pw->pw_name);
1482         pwdir = xstrdup(pw->pw_dir);
1483         if (gethostname(thishost, sizeof(thishost)) == -1)
1484                 fatal("load_public_identity_files: gethostname: %s",
1485                     strerror(errno));
1486         for (i = 0; i < options.num_identity_files; i++) {
1487                 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1488                         xfree(options.identity_files[i]);
1489                         continue;
1490                 }
1491                 cp = tilde_expand_filename(options.identity_files[i],
1492                     original_real_uid);
1493                 filename = percent_expand(cp, "d", pwdir,
1494                     "u", pwname, "l", thishost, "h", host,
1495                     "r", options.user, (char *)NULL);
1496                 xfree(cp);
1497                 public = key_load_public(filename, NULL);
1498                 debug("identity file %s type %d", filename,
1499                     public ? public->type : -1);
1500                 xfree(options.identity_files[i]);
1501                 identity_files[n_ids] = filename;
1502                 identity_keys[n_ids] = public;
1503
1504                 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1505                         continue;
1506
1507                 /* Try to add the certificate variant too */
1508                 xasprintf(&cp, "%s-cert", filename);
1509                 public = key_load_public(cp, NULL);
1510                 debug("identity file %s type %d", cp,
1511                     public ? public->type : -1);
1512                 if (public == NULL) {
1513                         xfree(cp);
1514                         continue;
1515                 }
1516                 if (!key_is_cert(public)) {
1517                         debug("%s: key %s type %s is not a certificate",
1518                             __func__, cp, key_type(public));
1519                         key_free(public);
1520                         xfree(cp);
1521                         continue;
1522                 }
1523                 identity_keys[n_ids] = public;
1524                 /* point to the original path, most likely the private key */
1525                 identity_files[n_ids] = xstrdup(filename);
1526                 n_ids++;
1527         }
1528         options.num_identity_files = n_ids;
1529         memcpy(options.identity_files, identity_files, sizeof(identity_files));
1530         memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1531
1532         bzero(pwname, strlen(pwname));
1533         xfree(pwname);
1534         bzero(pwdir, strlen(pwdir));
1535         xfree(pwdir);
1536 }