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