We will need more resource-limiting compliance work done before these
[dragonfly.git] / crypto / openssh / ssh.c
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * Ssh client program.  This program can be used to log into a remote machine.
6  * The software supports strong authentication, encryption, and forwarding
7  * of X11, TCP/IP, and authentication connections.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  * Copyright (c) 1999 Niels Provos.  All rights reserved.
16  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
17  *
18  * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
19  * in Canada (German citizen).
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 #include "includes.h"
43 RCSID("$OpenBSD: ssh.c,v 1.186 2002/09/19 01:58:18 djm Exp $");
44 RCSID("$FreeBSD: src/crypto/openssh/ssh.c,v 1.4.2.7 2003/02/03 17:31:07 des Exp $");
45 RCSID("$DragonFly: src/crypto/openssh/Attic/ssh.c,v 1.2 2003/06/17 04:24:36 dillon Exp $");
46
47 #include <openssl/evp.h>
48 #include <openssl/err.h>
49
50 #include "ssh.h"
51 #include "ssh1.h"
52 #include "ssh2.h"
53 #include "compat.h"
54 #include "cipher.h"
55 #include "xmalloc.h"
56 #include "packet.h"
57 #include "buffer.h"
58 #include "channels.h"
59 #include "key.h"
60 #include "authfd.h"
61 #include "authfile.h"
62 #include "pathnames.h"
63 #include "clientloop.h"
64 #include "log.h"
65 #include "readconf.h"
66 #include "sshconnect.h"
67 #include "tildexpand.h"
68 #include "dispatch.h"
69 #include "misc.h"
70 #include "kex.h"
71 #include "mac.h"
72 #include "sshtty.h"
73
74 #ifdef SMARTCARD
75 #include "scard.h"
76 #endif
77
78 #ifdef HAVE___PROGNAME
79 extern char *__progname;
80 #else
81 char *__progname;
82 #endif
83
84 /* Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
85    Default value is AF_UNSPEC means both IPv4 and IPv6. */
86 #ifdef IPV4_DEFAULT
87 int IPv4or6 = AF_INET;
88 #else
89 int IPv4or6 = AF_UNSPEC;
90 #endif
91
92 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
93 int debug_flag = 0;
94
95 /* Flag indicating whether a tty should be allocated */
96 int tty_flag = 0;
97 int no_tty_flag = 0;
98 int force_tty_flag = 0;
99
100 /* don't exec a shell */
101 int no_shell_flag = 0;
102
103 /*
104  * Flag indicating that nothing should be read from stdin.  This can be set
105  * on the command line.
106  */
107 int stdin_null_flag = 0;
108
109 /*
110  * Flag indicating that ssh should fork after authentication.  This is useful
111  * so that the passphrase can be entered manually, and then ssh goes to the
112  * background.
113  */
114 int fork_after_authentication_flag = 0;
115
116 /*
117  * General data structure for command line options and options configurable
118  * in configuration files.  See readconf.h.
119  */
120 Options options;
121
122 /* optional user configfile */
123 char *config = NULL;
124
125 /*
126  * Name of the host we are connecting to.  This is the name given on the
127  * command line, or the HostName specified for the user-supplied name in a
128  * configuration file.
129  */
130 char *host;
131
132 /* socket address the host resolves to */
133 struct sockaddr_storage hostaddr;
134
135 /* Private host keys. */
136 Sensitive sensitive_data;
137
138 /* Original real UID. */
139 uid_t original_real_uid;
140 uid_t original_effective_uid;
141
142 /* command to be executed */
143 Buffer command;
144
145 /* Should we execute a command or invoke a subsystem? */
146 int subsystem_flag = 0;
147
148 /* # of replies received for global requests */
149 static int client_global_request_id = 0;
150
151 /* pid of proxycommand child process */
152 pid_t proxy_command_pid = 0;
153
154 /* Prints a help message to the user.  This function never returns. */
155
156 static void
157 usage(void)
158 {
159         fprintf(stderr, "Usage: %s [options] host [command]\n", __progname);
160         fprintf(stderr, "Options:\n");
161         fprintf(stderr, "  -l user     Log in using this user name.\n");
162         fprintf(stderr, "  -n          Redirect input from " _PATH_DEVNULL ".\n");
163         fprintf(stderr, "  -F config   Config file (default: ~/%s).\n",
164              _PATH_SSH_USER_CONFFILE);
165         fprintf(stderr, "  -A          Enable authentication agent forwarding.\n");
166         fprintf(stderr, "  -a          Disable authentication agent forwarding (default).\n");
167 #ifdef AFS
168         fprintf(stderr, "  -k          Disable Kerberos ticket and AFS token forwarding.\n");
169 #endif                          /* AFS */
170         fprintf(stderr, "  -X          Enable X11 connection forwarding.\n");
171         fprintf(stderr, "  -x          Disable X11 connection forwarding (default).\n");
172         fprintf(stderr, "  -i file     Identity for public key authentication "
173             "(default: ~/.ssh/identity)\n");
174 #ifdef SMARTCARD
175         fprintf(stderr, "  -I reader   Set smartcard reader.\n");
176 #endif
177         fprintf(stderr, "  -t          Tty; allocate a tty even if command is given.\n");
178         fprintf(stderr, "  -T          Do not allocate a tty.\n");
179         fprintf(stderr, "  -v          Verbose; display verbose debugging messages.\n");
180         fprintf(stderr, "              Multiple -v increases verbosity.\n");
181         fprintf(stderr, "  -V          Display version number only.\n");
182         fprintf(stderr, "  -q          Quiet; don't display any warning messages.\n");
183         fprintf(stderr, "  -f          Fork into background after authentication.\n");
184         fprintf(stderr, "  -e char     Set escape character; ``none'' = disable (default: ~).\n");
185
186         fprintf(stderr, "  -c cipher   Select encryption algorithm\n");
187         fprintf(stderr, "  -m macs     Specify MAC algorithms for protocol version 2.\n");
188         fprintf(stderr, "  -p port     Connect to this port.  Server must be on the same port.\n");
189         fprintf(stderr, "  -L listen-port:host:port   Forward local port to remote address\n");
190         fprintf(stderr, "  -R listen-port:host:port   Forward remote port to local address\n");
191         fprintf(stderr, "              These cause %s to listen for connections on a port, and\n", __progname);
192         fprintf(stderr, "              forward them to the other side by connecting to host:port.\n");
193         fprintf(stderr, "  -D port     Enable dynamic application-level port forwarding.\n");
194         fprintf(stderr, "  -C          Enable compression.\n");
195         fprintf(stderr, "  -N          Do not execute a shell or command.\n");
196         fprintf(stderr, "  -g          Allow remote hosts to connect to forwarded ports.\n");
197         fprintf(stderr, "  -1          Force protocol version 1.\n");
198         fprintf(stderr, "  -2          Force protocol version 2.\n");
199         fprintf(stderr, "  -4          Use IPv4 only.\n");
200         fprintf(stderr, "  -6          Use IPv6 only.\n");
201         fprintf(stderr, "  -o 'option' Process the option as if it was read from a configuration file.\n");
202         fprintf(stderr, "  -s          Invoke command (mandatory) as SSH2 subsystem.\n");
203         fprintf(stderr, "  -b addr     Local IP address.\n");
204         exit(1);
205 }
206
207 static int ssh_session(void);
208 static int ssh_session2(void);
209 static void load_public_identity_files(void);
210
211 /*
212  * Main program for the ssh client.
213  */
214 int
215 main(int ac, char **av)
216 {
217         int i, opt, exit_status;
218         u_short fwd_port, fwd_host_port;
219         char sfwd_port[6], sfwd_host_port[6];
220         char *p, *cp, buf[256];
221         struct stat st;
222         struct passwd *pw;
223         int dummy;
224         extern int optind, optreset;
225         extern char *optarg;
226
227         __progname = get_progname(av[0]);
228         init_rng();
229
230         /*
231          * Save the original real uid.  It will be needed later (uid-swapping
232          * may clobber the real uid).
233          */
234         original_real_uid = getuid();
235         original_effective_uid = geteuid();
236  
237         /*
238          * Use uid-swapping to give up root privileges for the duration of
239          * option processing.  We will re-instantiate the rights when we are
240          * ready to create the privileged port, and will permanently drop
241          * them when the port has been created (actually, when the connection
242          * has been made, as we may need to create the port several times).
243          */
244         PRIV_END;
245
246 #ifdef HAVE_SETRLIMIT
247         /* If we are installed setuid root be careful to not drop core. */
248         if (original_real_uid != original_effective_uid) {
249                 struct rlimit rlim;
250                 rlim.rlim_cur = rlim.rlim_max = 0;
251                 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
252                         fatal("setrlimit failed: %.100s", strerror(errno));
253         }
254 #endif
255         /* Get user data. */
256         pw = getpwuid(original_real_uid);
257         if (!pw) {
258                 log("unknown user %d", original_real_uid);
259                 exit(1);
260         }
261         /* Take a copy of the returned structure. */
262         pw = pwcopy(pw);
263
264         /*
265          * Set our umask to something reasonable, as some files are created
266          * with the default umask.  This will make them world-readable but
267          * writable only by the owner, which is ok for all files for which we
268          * don't set the modes explicitly.
269          */
270         umask(022);
271
272         /* Initialize option structure to indicate that no values have been set. */
273         initialize_options(&options);
274
275         /* Parse command-line arguments. */
276         host = NULL;
277
278 again:
279         while ((opt = getopt(ac, av,
280             "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:NPR:TVX")) != -1) {
281                 switch (opt) {
282                 case '1':
283                         options.protocol = SSH_PROTO_1;
284                         break;
285                 case '2':
286                         options.protocol = SSH_PROTO_2;
287                         break;
288                 case '4':
289                         IPv4or6 = AF_INET;
290                         break;
291                 case '6':
292                         IPv4or6 = AF_INET6;
293                         break;
294                 case 'n':
295                         stdin_null_flag = 1;
296                         break;
297                 case 'f':
298                         fork_after_authentication_flag = 1;
299                         stdin_null_flag = 1;
300                         break;
301                 case 'x':
302                         options.forward_x11 = 0;
303                         break;
304                 case 'X':
305                         options.forward_x11 = 1;
306                         break;
307                 case 'g':
308                         options.gateway_ports = 1;
309                         break;
310                 case 'P':       /* deprecated */
311                         options.use_privileged_port = 0;
312                         break;
313                 case 'a':
314                         options.forward_agent = 0;
315                         break;
316                 case 'A':
317                         options.forward_agent = 1;
318                         break;
319 #ifdef AFS
320                 case 'k':
321                         options.kerberos_tgt_passing = 0;
322                         options.afs_token_passing = 0;
323                         break;
324 #endif
325                 case 'i':
326                         if (stat(optarg, &st) < 0) {
327                                 fprintf(stderr, "Warning: Identity file %s "
328                                     "does not exist.\n", optarg);
329                                 break;
330                         }
331                         if (options.num_identity_files >=
332                             SSH_MAX_IDENTITY_FILES)
333                                 fatal("Too many identity files specified "
334                                     "(max %d)", SSH_MAX_IDENTITY_FILES);
335                         options.identity_files[options.num_identity_files++] =
336                             xstrdup(optarg);
337                         break;
338                 case 'I':
339 #ifdef SMARTCARD
340                         options.smartcard_device = xstrdup(optarg);
341 #else
342                         fprintf(stderr, "no support for smartcards.\n");
343 #endif
344                         break;
345                 case 't':
346                         if (tty_flag)
347                                 force_tty_flag = 1;
348                         tty_flag = 1;
349                         break;
350                 case 'v':
351                         if (0 == debug_flag) {
352                                 debug_flag = 1;
353                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
354                         } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
355                                 options.log_level++;
356                                 break;
357                         } else
358                                 fatal("Too high debugging level.");
359                         /* fallthrough */
360                 case 'V':
361                         fprintf(stderr,
362                             "%s, SSH protocols %d.%d/%d.%d, OpenSSL 0x%8.8lx\n",
363                             SSH_VERSION,
364                             PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1,
365                             PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2,
366                             SSLeay());
367                         if (opt == 'V')
368                                 exit(0);
369                         break;
370                 case 'q':
371                         options.log_level = SYSLOG_LEVEL_QUIET;
372                         break;
373                 case 'e':
374                         if (optarg[0] == '^' && optarg[2] == 0 &&
375                             (u_char) optarg[1] >= 64 &&
376                             (u_char) optarg[1] < 128)
377                                 options.escape_char = (u_char) optarg[1] & 31;
378                         else if (strlen(optarg) == 1)
379                                 options.escape_char = (u_char) optarg[0];
380                         else if (strcmp(optarg, "none") == 0)
381                                 options.escape_char = SSH_ESCAPECHAR_NONE;
382                         else {
383                                 fprintf(stderr, "Bad escape character '%s'.\n",
384                                     optarg);
385                                 exit(1);
386                         }
387                         break;
388                 case 'c':
389                         if (ciphers_valid(optarg)) {
390                                 /* SSH2 only */
391                                 options.ciphers = xstrdup(optarg);
392                                 options.cipher = SSH_CIPHER_ILLEGAL;
393                         } else {
394                                 /* SSH1 only */
395                                 options.cipher = cipher_number(optarg);
396                                 if (options.cipher == -1) {
397                                         fprintf(stderr,
398                                             "Unknown cipher type '%s'\n",
399                                             optarg);
400                                         exit(1);
401                                 }
402                                 if (options.cipher == SSH_CIPHER_3DES)
403                                         options.ciphers = "3des-cbc";
404                                 else if (options.cipher == SSH_CIPHER_BLOWFISH)
405                                         options.ciphers = "blowfish-cbc";
406                                 else
407                                         options.ciphers = (char *)-1;
408                         }
409                         break;
410                 case 'm':
411                         if (mac_valid(optarg))
412                                 options.macs = xstrdup(optarg);
413                         else {
414                                 fprintf(stderr, "Unknown mac type '%s'\n",
415                                     optarg);
416                                 exit(1);
417                         }
418                         break;
419                 case 'p':
420                         options.port = a2port(optarg);
421                         if (options.port == 0) {
422                                 fprintf(stderr, "Bad port '%s'\n", optarg);
423                                 exit(1);
424                         }
425                         break;
426                 case 'l':
427                         options.user = optarg;
428                         break;
429
430                 case 'L':
431                 case 'R':
432                         if (sscanf(optarg, "%5[0-9]:%255[^:]:%5[0-9]",
433                             sfwd_port, buf, sfwd_host_port) != 3 &&
434                             sscanf(optarg, "%5[0-9]/%255[^/]/%5[0-9]",
435                             sfwd_port, buf, sfwd_host_port) != 3) {
436                                 fprintf(stderr,
437                                     "Bad forwarding specification '%s'\n",
438                                     optarg);
439                                 usage();
440                                 /* NOTREACHED */
441                         }
442                         if ((fwd_port = a2port(sfwd_port)) == 0 ||
443                             (fwd_host_port = a2port(sfwd_host_port)) == 0) {
444                                 fprintf(stderr,
445                                     "Bad forwarding port(s) '%s'\n", optarg);
446                                 exit(1);
447                         }
448                         if (opt == 'L')
449                                 add_local_forward(&options, fwd_port, buf,
450                                     fwd_host_port);
451                         else if (opt == 'R')
452                                 add_remote_forward(&options, fwd_port, buf,
453                                     fwd_host_port);
454                         break;
455
456                 case 'D':
457                         fwd_port = a2port(optarg);
458                         if (fwd_port == 0) {
459                                 fprintf(stderr, "Bad dynamic port '%s'\n",
460                                     optarg);
461                                 exit(1);
462                         }
463                         add_local_forward(&options, fwd_port, "socks4", 0);
464                         break;
465
466                 case 'C':
467                         options.compression = 1;
468                         break;
469                 case 'N':
470                         no_shell_flag = 1;
471                         no_tty_flag = 1;
472                         break;
473                 case 'T':
474                         no_tty_flag = 1;
475                         break;
476                 case 'o':
477                         dummy = 1;
478                         if (process_config_line(&options, host ? host : "",
479                             optarg, "command-line", 0, &dummy) != 0)
480                                 exit(1);
481                         break;
482                 case 's':
483                         subsystem_flag = 1;
484                         break;
485                 case 'b':
486                         options.bind_address = optarg;
487                         break;
488                 case 'F':
489                         config = optarg;
490                         break;
491                 default:
492                         usage();
493                 }
494         }
495
496         ac -= optind;
497         av += optind;
498
499         if (ac > 0 && !host && **av != '-') {
500                 if (strchr(*av, '@')) {
501                         p = xstrdup(*av);
502                         cp = strchr(p, '@');
503                         if (cp == NULL || cp == p)
504                                 usage();
505                         options.user = p;
506                         *cp = '\0';
507                         host = ++cp;
508                 } else
509                         host = *av;
510                 ac--, av++;
511                 if (ac > 0) {
512                         optind = 0;
513                         optreset = 1;
514                         goto again;
515                 }
516         }
517
518         /* Check that we got a host name. */
519         if (!host)
520                 usage();
521
522         SSLeay_add_all_algorithms();
523         ERR_load_crypto_strings();
524         channel_set_af(IPv4or6);
525
526         /* Initialize the command to execute on remote host. */
527         buffer_init(&command);
528
529         /*
530          * Save the command to execute on the remote host in a buffer. There
531          * is no limit on the length of the command, except by the maximum
532          * packet size.  Also sets the tty flag if there is no command.
533          */
534         if (!ac) {
535                 /* No command specified - execute shell on a tty. */
536                 tty_flag = 1;
537                 if (subsystem_flag) {
538                         fprintf(stderr,
539                             "You must specify a subsystem to invoke.\n");
540                         usage();
541                 }
542         } else {
543                 /* A command has been specified.  Store it into the buffer. */
544                 for (i = 0; i < ac; i++) {
545                         if (i)
546                                 buffer_append(&command, " ", 1);
547                         buffer_append(&command, av[i], strlen(av[i]));
548                 }
549         }
550
551         /* Cannot fork to background if no command. */
552         if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
553                 fatal("Cannot fork into background without a command to execute.");
554
555         /* Allocate a tty by default if no command specified. */
556         if (buffer_len(&command) == 0)
557                 tty_flag = 1;
558
559         /* Force no tty */
560         if (no_tty_flag)
561                 tty_flag = 0;
562         /* Do not allocate a tty if stdin is not a tty. */
563         if (!isatty(fileno(stdin)) && !force_tty_flag) {
564                 if (tty_flag)
565                         log("Pseudo-terminal will not be allocated because stdin is not a terminal.");
566                 tty_flag = 0;
567         }
568
569         /*
570          * Initialize "log" output.  Since we are the client all output
571          * actually goes to stderr.
572          */
573         log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
574             SYSLOG_FACILITY_USER, 1);
575
576         /*
577          * Read per-user configuration file.  Ignore the system wide config
578          * file if the user specifies a config file on the command line.
579          */
580         if (config != NULL) {
581                 if (!read_config_file(config, host, &options))
582                         fatal("Can't open user config file %.100s: "
583                             "%.100s", config, strerror(errno));
584         } else  {
585                 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
586                     _PATH_SSH_USER_CONFFILE);
587                 (void)read_config_file(buf, host, &options);
588
589                 /* Read systemwide configuration file after use config. */
590                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host, &options);
591         }
592
593         /* Fill configuration defaults. */
594         fill_default_options(&options);
595
596         /* reinit */
597         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
598
599         seed_rng();
600
601         if (options.user == NULL)
602                 options.user = xstrdup(pw->pw_name);
603
604         if (options.hostname != NULL)
605                 host = options.hostname;
606
607         /* Find canonic host name. */
608         if (strchr(host, '.') == 0) {
609                 struct addrinfo hints;
610                 struct addrinfo *ai = NULL;
611                 int errgai;
612                 memset(&hints, 0, sizeof(hints));
613                 hints.ai_family = IPv4or6;
614                 hints.ai_flags = AI_CANONNAME;
615                 hints.ai_socktype = SOCK_STREAM;
616                 errgai = getaddrinfo(host, NULL, &hints, &ai);
617                 if (errgai == 0) {
618                         if (ai->ai_canonname != NULL)
619                                 host = xstrdup(ai->ai_canonname);
620                         freeaddrinfo(ai);
621                 }
622         }
623
624         /* Disable rhosts authentication if not running as root. */
625 #ifdef HAVE_CYGWIN
626         /* Ignore uid if running under Windows */
627         if (!options.use_privileged_port) {
628 #else
629         if (original_effective_uid != 0 || !options.use_privileged_port) {
630 #endif
631                 debug("Rhosts Authentication disabled, "
632                     "originating port will not be trusted.");
633                 options.rhosts_authentication = 0;
634         }
635         /* Open a connection to the remote host. */
636
637         if (ssh_connect(host, &hostaddr, options.port, IPv4or6,
638             options.connection_attempts,
639 #ifdef HAVE_CYGWIN
640             options.use_privileged_port,
641 #else
642             original_effective_uid == 0 && options.use_privileged_port,
643 #endif
644             options.proxy_command) != 0)
645                 exit(1);
646
647         /*
648          * If we successfully made the connection, load the host private key
649          * in case we will need it later for combined rsa-rhosts
650          * authentication. This must be done before releasing extra
651          * privileges, because the file is only readable by root.
652          * If we cannot access the private keys, load the public keys
653          * instead and try to execute the ssh-keysign helper instead.
654          */
655         sensitive_data.nkeys = 0;
656         sensitive_data.keys = NULL;
657         sensitive_data.external_keysign = 0;
658         if (options.rhosts_rsa_authentication ||
659             options.hostbased_authentication) {
660                 sensitive_data.nkeys = 3;
661                 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
662                     sizeof(Key));
663
664                 PRIV_START;
665                 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
666                     _PATH_HOST_KEY_FILE, "", NULL);
667                 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
668                     _PATH_HOST_DSA_KEY_FILE, "", NULL);
669                 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
670                     _PATH_HOST_RSA_KEY_FILE, "", NULL);
671                 PRIV_END;
672
673                 if (options.hostbased_authentication == 1 &&
674                     sensitive_data.keys[0] == NULL &&
675                     sensitive_data.keys[1] == NULL &&
676                     sensitive_data.keys[2] == NULL) {
677                         sensitive_data.keys[1] = key_load_public(
678                             _PATH_HOST_DSA_KEY_FILE, NULL);
679                         sensitive_data.keys[2] = key_load_public(
680                             _PATH_HOST_RSA_KEY_FILE, NULL);
681                         sensitive_data.external_keysign = 1;
682                 }
683         }
684         /*
685          * Get rid of any extra privileges that we may have.  We will no
686          * longer need them.  Also, extra privileges could make it very hard
687          * to read identity files and other non-world-readable files from the
688          * user's home directory if it happens to be on a NFS volume where
689          * root is mapped to nobody.
690          */
691         seteuid(original_real_uid);
692         setuid(original_real_uid);
693
694         /*
695          * Now that we are back to our own permissions, create ~/.ssh
696          * directory if it doesn\'t already exist.
697          */
698         snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
699         if (stat(buf, &st) < 0)
700                 if (mkdir(buf, 0700) < 0)
701                         error("Could not create directory '%.200s'.", buf);
702
703         /* load options.identity_files */
704         load_public_identity_files();
705
706         /* Expand ~ in known host file names. */
707         /* XXX mem-leaks: */
708         options.system_hostfile =
709             tilde_expand_filename(options.system_hostfile, original_real_uid);
710         options.user_hostfile =
711             tilde_expand_filename(options.user_hostfile, original_real_uid);
712         options.system_hostfile2 =
713             tilde_expand_filename(options.system_hostfile2, original_real_uid);
714         options.user_hostfile2 =
715             tilde_expand_filename(options.user_hostfile2, original_real_uid);
716
717         signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
718
719         /* Log into the remote system.  This never returns if the login fails. */
720         ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
721
722         /* We no longer need the private host keys.  Clear them now. */
723         if (sensitive_data.nkeys != 0) {
724                 for (i = 0; i < sensitive_data.nkeys; i++) {
725                         if (sensitive_data.keys[i] != NULL) {
726                                 /* Destroys contents safely */
727                                 debug3("clear hostkey %d", i);
728                                 key_free(sensitive_data.keys[i]);
729                                 sensitive_data.keys[i] = NULL;
730                         }
731                 }
732                 xfree(sensitive_data.keys);
733         }
734         for (i = 0; i < options.num_identity_files; i++) {
735                 if (options.identity_files[i]) {
736                         xfree(options.identity_files[i]);
737                         options.identity_files[i] = NULL;
738                 }
739                 if (options.identity_keys[i]) {
740                         key_free(options.identity_keys[i]);
741                         options.identity_keys[i] = NULL;
742                 }
743         }
744
745         exit_status = compat20 ? ssh_session2() : ssh_session();
746         packet_close();
747
748         /*
749          * Send SIGHUP to proxy command if used. We don't wait() in 
750          * case it hangs and instead rely on init to reap the child
751          */
752         if (proxy_command_pid > 1)
753                 kill(proxy_command_pid, SIGHUP);
754
755         return exit_status;
756 }
757
758 static void
759 x11_get_proto(char **_proto, char **_data)
760 {
761         char line[512];
762         static char proto[512], data[512];
763         FILE *f;
764         int got_data = 0, i;
765         char *display;
766         struct stat st;
767
768         *_proto = proto;
769         *_data = data;
770         proto[0] = data[0] = '\0';
771         if (!options.xauth_location ||
772             (stat(options.xauth_location, &st) == -1)) {
773                 debug("No xauth program.");
774         } else {
775                 if ((display = getenv("DISPLAY")) == NULL) {
776                         debug("x11_get_proto: DISPLAY not set");
777                         return;
778                 }
779                 /* Try to get Xauthority information for the display. */
780                 if (strncmp(display, "localhost:", 10) == 0)
781                         /*
782                          * Handle FamilyLocal case where $DISPLAY does
783                          * not match an authorization entry.  For this we
784                          * just try "xauth list unix:displaynum.screennum".
785                          * XXX: "localhost" match to determine FamilyLocal
786                          *      is not perfect.
787                          */
788                         snprintf(line, sizeof line, "%s list unix:%s 2>"
789                             _PATH_DEVNULL, options.xauth_location, display+10);
790                 else
791                         snprintf(line, sizeof line, "%s list %.200s 2>"
792                             _PATH_DEVNULL, options.xauth_location, display);
793                 debug2("x11_get_proto: %s", line);
794                 f = popen(line, "r");
795                 if (f && fgets(line, sizeof(line), f) &&
796                     sscanf(line, "%*s %511s %511s", proto, data) == 2)
797                         got_data = 1;
798                 if (f)
799                         pclose(f);
800         }
801         /*
802          * If we didn't get authentication data, just make up some
803          * data.  The forwarding code will check the validity of the
804          * response anyway, and substitute this data.  The X11
805          * server, however, will ignore this fake data and use
806          * whatever authentication mechanisms it was using otherwise
807          * for the local connection.
808          */
809         if (!got_data) {
810                 u_int32_t rand = 0;
811
812                 log("Warning: No xauth data; using fake authentication data for X11 forwarding.");
813                 strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
814                 for (i = 0; i < 16; i++) {
815                         if (i % 4 == 0)
816                                 rand = arc4random();
817                         snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
818                         rand >>= 8;
819                 }
820         }
821 }
822
823 static void
824 ssh_init_forwarding(void)
825 {
826         int success = 0;
827         int i;
828
829         /* Initiate local TCP/IP port forwardings. */
830         for (i = 0; i < options.num_local_forwards; i++) {
831                 debug("Connections to local port %d forwarded to remote address %.200s:%d",
832                     options.local_forwards[i].port,
833                     options.local_forwards[i].host,
834                     options.local_forwards[i].host_port);
835                 success += channel_setup_local_fwd_listener(
836                     options.local_forwards[i].port,
837                     options.local_forwards[i].host,
838                     options.local_forwards[i].host_port,
839                     options.gateway_ports);
840         }
841         if (i > 0 && success == 0)
842                 error("Could not request local forwarding.");
843
844         /* Initiate remote TCP/IP port forwardings. */
845         for (i = 0; i < options.num_remote_forwards; i++) {
846                 debug("Connections to remote port %d forwarded to local address %.200s:%d",
847                     options.remote_forwards[i].port,
848                     options.remote_forwards[i].host,
849                     options.remote_forwards[i].host_port);
850                 channel_request_remote_forwarding(
851                     options.remote_forwards[i].port,
852                     options.remote_forwards[i].host,
853                     options.remote_forwards[i].host_port);
854         }
855 }
856
857 static void
858 check_agent_present(void)
859 {
860         if (options.forward_agent) {
861                 /* Clear agent forwarding if we don\'t have an agent. */
862                 if (!ssh_agent_present())
863                         options.forward_agent = 0;
864         }
865 }
866
867 static int
868 ssh_session(void)
869 {
870         int type;
871         int interactive = 0;
872         int have_tty = 0;
873         struct winsize ws;
874         char *cp;
875
876         /* Enable compression if requested. */
877         if (options.compression) {
878                 debug("Requesting compression at level %d.", options.compression_level);
879
880                 if (options.compression_level < 1 || options.compression_level > 9)
881                         fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
882
883                 /* Send the request. */
884                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
885                 packet_put_int(options.compression_level);
886                 packet_send();
887                 packet_write_wait();
888                 type = packet_read();
889                 if (type == SSH_SMSG_SUCCESS)
890                         packet_start_compression(options.compression_level);
891                 else if (type == SSH_SMSG_FAILURE)
892                         log("Warning: Remote host refused compression.");
893                 else
894                         packet_disconnect("Protocol error waiting for compression response.");
895         }
896         /* Allocate a pseudo tty if appropriate. */
897         if (tty_flag) {
898                 debug("Requesting pty.");
899
900                 /* Start the packet. */
901                 packet_start(SSH_CMSG_REQUEST_PTY);
902
903                 /* Store TERM in the packet.  There is no limit on the
904                    length of the string. */
905                 cp = getenv("TERM");
906                 if (!cp)
907                         cp = "";
908                 packet_put_cstring(cp);
909
910                 /* Store window size in the packet. */
911                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
912                         memset(&ws, 0, sizeof(ws));
913                 packet_put_int(ws.ws_row);
914                 packet_put_int(ws.ws_col);
915                 packet_put_int(ws.ws_xpixel);
916                 packet_put_int(ws.ws_ypixel);
917
918                 /* Store tty modes in the packet. */
919                 tty_make_modes(fileno(stdin), NULL);
920
921                 /* Send the packet, and wait for it to leave. */
922                 packet_send();
923                 packet_write_wait();
924
925                 /* Read response from the server. */
926                 type = packet_read();
927                 if (type == SSH_SMSG_SUCCESS) {
928                         interactive = 1;
929                         have_tty = 1;
930                 } else if (type == SSH_SMSG_FAILURE)
931                         log("Warning: Remote host failed or refused to allocate a pseudo tty.");
932                 else
933                         packet_disconnect("Protocol error waiting for pty request response.");
934         }
935         /* Request X11 forwarding if enabled and DISPLAY is set. */
936         if (options.forward_x11 && getenv("DISPLAY") != NULL) {
937                 char *proto, *data;
938                 /* Get reasonable local authentication information. */
939                 x11_get_proto(&proto, &data);
940                 /* Request forwarding with authentication spoofing. */
941                 debug("Requesting X11 forwarding with authentication spoofing.");
942                 x11_request_forwarding_with_spoofing(0, proto, data);
943
944                 /* Read response from the server. */
945                 type = packet_read();
946                 if (type == SSH_SMSG_SUCCESS) {
947                         interactive = 1;
948                 } else if (type == SSH_SMSG_FAILURE) {
949                         log("Warning: Remote host denied X11 forwarding.");
950                 } else {
951                         packet_disconnect("Protocol error waiting for X11 forwarding");
952                 }
953         }
954         /* Tell the packet module whether this is an interactive session. */
955         packet_set_interactive(interactive);
956
957         /* Request authentication agent forwarding if appropriate. */
958         check_agent_present();
959
960         if (options.forward_agent) {
961                 debug("Requesting authentication agent forwarding.");
962                 auth_request_forwarding();
963
964                 /* Read response from the server. */
965                 type = packet_read();
966                 packet_check_eom();
967                 if (type != SSH_SMSG_SUCCESS)
968                         log("Warning: Remote host denied authentication agent forwarding.");
969         }
970
971         /* Initiate port forwardings. */
972         ssh_init_forwarding();
973
974         /* If requested, let ssh continue in the background. */
975         if (fork_after_authentication_flag)
976                 if (daemon(1, 1) < 0)
977                         fatal("daemon() failed: %.200s", strerror(errno));
978
979         /*
980          * If a command was specified on the command line, execute the
981          * command now. Otherwise request the server to start a shell.
982          */
983         if (buffer_len(&command) > 0) {
984                 int len = buffer_len(&command);
985                 if (len > 900)
986                         len = 900;
987                 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
988                 packet_start(SSH_CMSG_EXEC_CMD);
989                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
990                 packet_send();
991                 packet_write_wait();
992         } else {
993                 debug("Requesting shell.");
994                 packet_start(SSH_CMSG_EXEC_SHELL);
995                 packet_send();
996                 packet_write_wait();
997         }
998
999         /* Enter the interactive session. */
1000         return client_loop(have_tty, tty_flag ?
1001             options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1002 }
1003
1004 static void
1005 client_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1006 {
1007         int id, len;
1008
1009         id = packet_get_int();
1010         len = buffer_len(&command);
1011         if (len > 900)
1012                 len = 900;
1013         packet_check_eom();
1014         if (type == SSH2_MSG_CHANNEL_FAILURE)
1015                 fatal("Request for subsystem '%.*s' failed on channel %d",
1016                     len, (u_char *)buffer_ptr(&command), id);
1017 }
1018
1019 void
1020 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
1021 {
1022         int i;
1023
1024         i = client_global_request_id++;
1025         if (i >= options.num_remote_forwards) {
1026                 debug("client_global_request_reply: too many replies %d > %d",
1027                     i, options.num_remote_forwards);
1028                 return;
1029         }
1030         debug("remote forward %s for: listen %d, connect %s:%d",
1031             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1032             options.remote_forwards[i].port,
1033             options.remote_forwards[i].host,
1034             options.remote_forwards[i].host_port);
1035         if (type == SSH2_MSG_REQUEST_FAILURE)
1036                 log("Warning: remote port forwarding failed for listen port %d",
1037                     options.remote_forwards[i].port);
1038 }
1039
1040 /* request pty/x11/agent/tcpfwd/shell for channel */
1041 static void
1042 ssh_session2_setup(int id, void *arg)
1043 {
1044         int len;
1045         int interactive = 0;
1046         struct termios tio;
1047
1048         debug("ssh_session2_setup: id %d", id);
1049
1050         if (tty_flag) {
1051                 struct winsize ws;
1052                 char *cp;
1053                 cp = getenv("TERM");
1054                 if (!cp)
1055                         cp = "";
1056                 /* Store window size in the packet. */
1057                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1058                         memset(&ws, 0, sizeof(ws));
1059
1060                 channel_request_start(id, "pty-req", 0);
1061                 packet_put_cstring(cp);
1062                 packet_put_int(ws.ws_col);
1063                 packet_put_int(ws.ws_row);
1064                 packet_put_int(ws.ws_xpixel);
1065                 packet_put_int(ws.ws_ypixel);
1066                 tio = get_saved_tio();
1067                 tty_make_modes(/*ignored*/ 0, &tio);
1068                 packet_send();
1069                 interactive = 1;
1070                 /* XXX wait for reply */
1071         }
1072         if (options.forward_x11 &&
1073             getenv("DISPLAY") != NULL) {
1074                 char *proto, *data;
1075                 /* Get reasonable local authentication information. */
1076                 x11_get_proto(&proto, &data);
1077                 /* Request forwarding with authentication spoofing. */
1078                 debug("Requesting X11 forwarding with authentication spoofing.");
1079                 x11_request_forwarding_with_spoofing(id, proto, data);
1080                 interactive = 1;
1081                 /* XXX wait for reply */
1082         }
1083
1084         check_agent_present();
1085         if (options.forward_agent) {
1086                 debug("Requesting authentication agent forwarding.");
1087                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1088                 packet_send();
1089         }
1090
1091         len = buffer_len(&command);
1092         if (len > 0) {
1093                 if (len > 900)
1094                         len = 900;
1095                 if (subsystem_flag) {
1096                         debug("Sending subsystem: %.*s", len, (u_char *)buffer_ptr(&command));
1097                         channel_request_start(id, "subsystem", /*want reply*/ 1);
1098                         /* register callback for reply */
1099                         /* XXX we assume that client_loop has already been called */
1100                         dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &client_subsystem_reply);
1101                         dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &client_subsystem_reply);
1102                 } else {
1103                         debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1104                         channel_request_start(id, "exec", 0);
1105                 }
1106                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1107                 packet_send();
1108         } else {
1109                 channel_request_start(id, "shell", 0);
1110                 packet_send();
1111         }
1112
1113         packet_set_interactive(interactive);
1114 }
1115
1116 /* open new channel for a session */
1117 static int
1118 ssh_session2_open(void)
1119 {
1120         Channel *c;
1121         int window, packetmax, in, out, err;
1122
1123         if (stdin_null_flag) {
1124                 in = open(_PATH_DEVNULL, O_RDONLY);
1125         } else {
1126                 in = dup(STDIN_FILENO);
1127         }
1128         out = dup(STDOUT_FILENO);
1129         err = dup(STDERR_FILENO);
1130
1131         if (in < 0 || out < 0 || err < 0)
1132                 fatal("dup() in/out/err failed");
1133
1134         /* enable nonblocking unless tty */
1135         if (!isatty(in))
1136                 set_nonblock(in);
1137         if (!isatty(out))
1138                 set_nonblock(out);
1139         if (!isatty(err))
1140                 set_nonblock(err);
1141
1142         window = CHAN_SES_WINDOW_DEFAULT;
1143         packetmax = CHAN_SES_PACKET_DEFAULT;
1144         if (tty_flag) {
1145                 window >>= 1;
1146                 packetmax >>= 1;
1147         }
1148         c = channel_new(
1149             "session", SSH_CHANNEL_OPENING, in, out, err,
1150             window, packetmax, CHAN_EXTENDED_WRITE,
1151             xstrdup("client-session"), /*nonblock*/0);
1152
1153         debug3("ssh_session2_open: channel_new: %d", c->self);
1154
1155         channel_send_open(c->self);
1156         if (!no_shell_flag)
1157                 channel_register_confirm(c->self, ssh_session2_setup);
1158
1159         return c->self;
1160 }
1161
1162 static int
1163 ssh_session2(void)
1164 {
1165         int id = -1;
1166
1167         /* XXX should be pre-session */
1168         ssh_init_forwarding();
1169
1170         if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1171                 id = ssh_session2_open();
1172
1173         /* If requested, let ssh continue in the background. */
1174         if (fork_after_authentication_flag)
1175                 if (daemon(1, 1) < 0)
1176                         fatal("daemon() failed: %.200s", strerror(errno));
1177
1178         return client_loop(tty_flag, tty_flag ?
1179             options.escape_char : SSH_ESCAPECHAR_NONE, id);
1180 }
1181
1182 static void
1183 load_public_identity_files(void)
1184 {
1185         char *filename;
1186         int i = 0;
1187         Key *public;
1188 #ifdef SMARTCARD
1189         Key **keys;
1190
1191         if (options.smartcard_device != NULL &&
1192             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1193             (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1194                 int count = 0;
1195                 for (i = 0; keys[i] != NULL; i++) {
1196                         count++;
1197                         memmove(&options.identity_files[1], &options.identity_files[0],
1198                             sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1199                         memmove(&options.identity_keys[1], &options.identity_keys[0],
1200                             sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1201                         options.num_identity_files++;
1202                         options.identity_keys[0] = keys[i];
1203                         options.identity_files[0] = xstrdup("smartcard key");;
1204                 }
1205                 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1206                         options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1207                 i = count;
1208                 xfree(keys);
1209         }
1210 #endif /* SMARTCARD */
1211         for (; i < options.num_identity_files; i++) {
1212                 filename = tilde_expand_filename(options.identity_files[i],
1213                     original_real_uid);
1214                 public = key_load_public(filename, NULL);
1215                 debug("identity file %s type %d", filename,
1216                     public ? public->type : -1);
1217                 xfree(options.identity_files[i]);
1218                 options.identity_files[i] = filename;
1219                 options.identity_keys[i] = public;
1220         }
1221 }