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