]> andersk Git - openssh.git/blob - ssh.c
20001203
[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.75 2000/11/30 07:02:35 markus Exp $");
43
44 #include <openssl/evp.h>
45 #include <openssl/dsa.h>
46 #include <openssl/rsa.h>
47 #include <openssl/err.h>
48
49 #include "xmalloc.h"
50 #include "ssh.h"
51 #include "packet.h"
52 #include "buffer.h"
53 #include "readconf.h"
54 #include "uidswap.h"
55
56 #include "ssh2.h"
57 #include "compat.h"
58 #include "channels.h"
59 #include "key.h"
60 #include "authfd.h"
61 #include "authfile.h"
62
63 #ifdef HAVE___PROGNAME
64 extern char *__progname;
65 #else
66 char *__progname;
67 #endif
68
69 /* Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
70    Default value is AF_UNSPEC means both IPv4 and IPv6. */
71 #ifdef IPV4_DEFAULT
72 int IPv4or6 = AF_INET;
73 #else
74 int IPv4or6 = AF_UNSPEC;
75 #endif
76
77 /* Flag indicating whether debug mode is on.  This can be set on the command line. */
78 int debug_flag = 0;
79
80 /* Flag indicating whether a tty should be allocated */
81 int tty_flag = 0;
82
83 /* don't exec a shell */
84 int no_shell_flag = 0;
85 int no_tty_flag = 0;
86
87 /*
88  * Flag indicating that nothing should be read from stdin.  This can be set
89  * on the command line.
90  */
91 int stdin_null_flag = 0;
92
93 /*
94  * Flag indicating that ssh should fork after authentication.  This is useful
95  * so that the pasphrase can be entered manually, and then ssh goes to the
96  * background.
97  */
98 int fork_after_authentication_flag = 0;
99
100 /*
101  * General data structure for command line options and options configurable
102  * in configuration files.  See readconf.h.
103  */
104 Options options;
105
106 /*
107  * Name of the host we are connecting to.  This is the name given on the
108  * command line, or the HostName specified for the user-supplied name in a
109  * configuration file.
110  */
111 char *host;
112
113 /* socket address the host resolves to */
114 struct sockaddr_storage hostaddr;
115
116 /*
117  * Flag to indicate that we have received a window change signal which has
118  * not yet been processed.  This will cause a message indicating the new
119  * window size to be sent to the server a little later.  This is volatile
120  * because this is updated in a signal handler.
121  */
122 volatile int received_window_change_signal = 0;
123
124 /* Value of argv[0] (set in the main program). */
125 char *av0;
126
127 /* Flag indicating whether we have a valid host private key loaded. */
128 int host_private_key_loaded = 0;
129
130 /* Host private key. */
131 RSA *host_private_key = NULL;
132
133 /* Original real UID. */
134 uid_t original_real_uid;
135
136 /* command to be executed */
137 Buffer command;
138
139 /* Prints a help message to the user.  This function never returns. */
140
141 void
142 usage()
143 {
144         fprintf(stderr, "Usage: %s [options] host [command]\n", av0);
145         fprintf(stderr, "Options:\n");
146         fprintf(stderr, "  -l user     Log in using this user name.\n");
147         fprintf(stderr, "  -n          Redirect input from /dev/null.\n");
148         fprintf(stderr, "  -A          Enable authentication agent forwarding.\n");
149         fprintf(stderr, "  -a          Disable authentication agent forwarding.\n");
150 #ifdef AFS
151         fprintf(stderr, "  -k          Disable Kerberos ticket and AFS token forwarding.\n");
152 #endif                          /* AFS */
153         fprintf(stderr, "  -X          Enable X11 connection forwarding.\n");
154         fprintf(stderr, "  -x          Disable X11 connection forwarding.\n");
155         fprintf(stderr, "  -i file     Identity for RSA authentication (default: ~/.ssh/identity).\n");
156         fprintf(stderr, "  -t          Tty; allocate a tty even if command is given.\n");
157         fprintf(stderr, "  -T          Do not allocate a tty.\n");
158         fprintf(stderr, "  -v          Verbose; display verbose debugging messages.\n");
159         fprintf(stderr, "              Multiple -v increases verbosity.\n");
160         fprintf(stderr, "  -V          Display version number only.\n");
161         fprintf(stderr, "  -P          Don't allocate a privileged port.\n");
162         fprintf(stderr, "  -q          Quiet; don't display any warning messages.\n");
163         fprintf(stderr, "  -f          Fork into background after authentication.\n");
164         fprintf(stderr, "  -e char     Set escape character; ``none'' = disable (default: ~).\n");
165
166         fprintf(stderr, "  -c cipher   Select encryption algorithm: "
167                         "``3des'', "
168                         "``blowfish''\n");
169         fprintf(stderr, "  -p port     Connect to this port.  Server must be on the same port.\n");
170         fprintf(stderr, "  -L listen-port:host:port   Forward local port to remote address\n");
171         fprintf(stderr, "  -R listen-port:host:port   Forward remote port to local address\n");
172         fprintf(stderr, "              These cause %s to listen for connections on a port, and\n", av0);
173         fprintf(stderr, "              forward them to the other side by connecting to host:port.\n");
174         fprintf(stderr, "  -C          Enable compression.\n");
175         fprintf(stderr, "  -N          Do not execute a shell or command.\n");
176         fprintf(stderr, "  -g          Allow remote hosts to connect to forwarded ports.\n");
177         fprintf(stderr, "  -4          Use IPv4 only.\n");
178         fprintf(stderr, "  -6          Use IPv6 only.\n");
179         fprintf(stderr, "  -2          Force protocol version 2.\n");
180         fprintf(stderr, "  -o 'option' Process the option as if it was read from a configuration file.\n");
181         exit(1);
182 }
183
184 /*
185  * Connects to the given host using rsh (or prints an error message and exits
186  * if rsh is not available).  This function never returns.
187  */
188 void
189 rsh_connect(char *host, char *user, Buffer * command)
190 {
191         char *args[10];
192         int i;
193
194         log("Using rsh.  WARNING: Connection will not be encrypted.");
195         /* Build argument list for rsh. */
196         i = 0;
197         args[i++] = _PATH_RSH;
198         /* host may have to come after user on some systems */
199         args[i++] = host;
200         if (user) {
201                 args[i++] = "-l";
202                 args[i++] = user;
203         }
204         if (buffer_len(command) > 0) {
205                 buffer_append(command, "\0", 1);
206                 args[i++] = buffer_ptr(command);
207         }
208         args[i++] = NULL;
209         if (debug_flag) {
210                 for (i = 0; args[i]; i++) {
211                         if (i != 0)
212                                 fprintf(stderr, " ");
213                         fprintf(stderr, "%s", args[i]);
214                 }
215                 fprintf(stderr, "\n");
216         }
217         execv(_PATH_RSH, args);
218         perror(_PATH_RSH);
219         exit(1);
220 }
221
222 int     ssh_session(void);
223 int     ssh_session2(void);
224 int     guess_identity_file_type(const char *filename);
225
226 /*
227  * Main program for the ssh client.
228  */
229 int
230 main(int ac, char **av)
231 {
232         int i, opt, optind, exit_status, ok;
233         u_short fwd_port, fwd_host_port;
234         char *optarg, *cp, buf[256];
235         struct stat st;
236         struct passwd *pw, pwcopy;
237         int dummy;
238         uid_t original_effective_uid;
239
240         __progname = get_progname(av[0]);
241         init_rng();
242
243         /*
244          * Save the original real uid.  It will be needed later (uid-swapping
245          * may clobber the real uid).
246          */
247         original_real_uid = getuid();
248         original_effective_uid = geteuid();
249
250 #ifdef HAVE_SETRLIMIT
251         /* If we are installed setuid root be careful to not drop core. */
252         if (original_real_uid != original_effective_uid) {
253                 struct rlimit rlim;
254                 rlim.rlim_cur = rlim.rlim_max = 0;
255                 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
256                         fatal("setrlimit failed: %.100s", strerror(errno));
257         }
258 #endif
259         /*
260          * Use uid-swapping to give up root privileges for the duration of
261          * option processing.  We will re-instantiate the rights when we are
262          * ready to create the privileged port, and will permanently drop
263          * them when the port has been created (actually, when the connection
264          * has been made, as we may need to create the port several times).
265          */
266         temporarily_use_uid(original_real_uid);
267
268         /*
269          * Set our umask to something reasonable, as some files are created
270          * with the default umask.  This will make them world-readable but
271          * writable only by the owner, which is ok for all files for which we
272          * don't set the modes explicitly.
273          */
274         umask(022);
275
276         /* Save our own name. */
277         av0 = av[0];
278
279         /* Initialize option structure to indicate that no values have been set. */
280         initialize_options(&options);
281
282         /* Parse command-line arguments. */
283         host = NULL;
284
285         /* If program name is not one of the standard names, use it as host name. */
286         if (strchr(av0, '/'))
287                 cp = strrchr(av0, '/') + 1;
288         else
289                 cp = av0;
290 #ifdef HAVE_CYGWIN
291         if (strcasecmp(cp, "rsh") && strcasecmp(cp, "ssh") &&
292             strcasecmp(cp, "rlogin") && strcasecmp(cp, "slogin") &&
293             strcasecmp(cp, "remsh") &&
294             strcasecmp(cp, "rsh.exe") && strcasecmp(cp, "ssh.exe") &&
295             strcasecmp(cp, "rlogin.exe") && strcasecmp(cp, "slogin.exe") &&
296             strcasecmp(cp, "remsh.exe"))
297 #else
298         if (strcmp(cp, "rsh") && strcmp(cp, "ssh") && strcmp(cp, "rlogin") &&
299             strcmp(cp, "slogin") && strcmp(cp, "remsh"))
300 #endif
301                 host = cp;
302
303         for (optind = 1; optind < ac; optind++) {
304                 if (av[optind][0] != '-') {
305                         if (host)
306                                 break;
307                         if ((cp = strchr(av[optind], '@'))) {
308                                 if(cp == av[optind])
309                                         usage();
310                                 options.user = av[optind];
311                                 *cp = '\0';
312                                 host = ++cp;
313                         } else
314                                 host = av[optind];
315                         continue;
316                 }
317                 opt = av[optind][1];
318                 if (!opt)
319                         usage();
320                 if (strchr("eilcpLRo", opt)) {  /* options with arguments */
321                         optarg = av[optind] + 2;
322                         if (strcmp(optarg, "") == 0) {
323                                 if (optind >= ac - 1)
324                                         usage();
325                                 optarg = av[++optind];
326                         }
327                 } else {
328                         if (av[optind][2])
329                                 usage();
330                         optarg = NULL;
331                 }
332                 switch (opt) {
333                 case '2':
334                         options.protocol = SSH_PROTO_2;
335                         break;
336                 case '4':
337                         IPv4or6 = AF_INET;
338                         break;
339                 case '6':
340                         IPv4or6 = AF_INET6;
341                         break;
342                 case 'n':
343                         stdin_null_flag = 1;
344                         break;
345                 case 'f':
346                         fork_after_authentication_flag = 1;
347                         stdin_null_flag = 1;
348                         break;
349                 case 'x':
350                         options.forward_x11 = 0;
351                         break;
352                 case 'X':
353                         options.forward_x11 = 1;
354                         break;
355                 case 'g':
356                         options.gateway_ports = 1;
357                         break;
358                 case 'P':
359                         options.use_privileged_port = 0;
360                         break;
361                 case 'a':
362                         options.forward_agent = 0;
363                         break;
364                 case 'A':
365                         options.forward_agent = 1;
366                         break;
367 #ifdef AFS
368                 case 'k':
369                         options.kerberos_tgt_passing = 0;
370                         options.afs_token_passing = 0;
371                         break;
372 #endif
373                 case 'i':
374                         if (stat(optarg, &st) < 0) {
375                                 fprintf(stderr, "Warning: Identity file %s does not exist.\n",
376                                     optarg);
377                                 break;
378                         }
379                         if (options.num_identity_files >= SSH_MAX_IDENTITY_FILES)
380                                 fatal("Too many identity files specified (max %d)",
381                                     SSH_MAX_IDENTITY_FILES);
382                         options.identity_files[options.num_identity_files++] = xstrdup(optarg);
383                         break;
384                 case 't':
385                         tty_flag = 1;
386                         break;
387                 case 'v':
388                         if (0 == debug_flag) {
389                                 debug_flag = 1;
390                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
391                         } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
392                                 options.log_level++;
393                                 break;
394                         } else {
395                                 fatal("Too high debugging level.\n");
396                         }
397                         /* fallthrough */
398                 case 'V':
399                         fprintf(stderr, "SSH Version %s, protocol versions %d.%d/%d.%d.\n",
400                             SSH_VERSION,
401                             PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1,
402                             PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
403                         fprintf(stderr, "Compiled with SSL (0x%8.8lx).\n", SSLeay());
404                         if (opt == 'V')
405                                 exit(0);
406                         break;
407                 case 'q':
408                         options.log_level = SYSLOG_LEVEL_QUIET;
409                         break;
410                 case 'e':
411                         if (optarg[0] == '^' && optarg[2] == 0 &&
412                             (unsigned char) optarg[1] >= 64 && (unsigned char) optarg[1] < 128)
413                                 options.escape_char = (unsigned char) optarg[1] & 31;
414                         else if (strlen(optarg) == 1)
415                                 options.escape_char = (unsigned char) optarg[0];
416                         else if (strcmp(optarg, "none") == 0)
417                                 options.escape_char = -2;
418                         else {
419                                 fprintf(stderr, "Bad escape character '%s'.\n", optarg);
420                                 exit(1);
421                         }
422                         break;
423                 case 'c':
424                         if (ciphers_valid(optarg)) {
425                                 /* SSH2 only */
426                                 options.ciphers = xstrdup(optarg);
427                                 options.cipher = SSH_CIPHER_ILLEGAL;
428                         } else {
429                                 /* SSH1 only */
430                                 options.cipher = cipher_number(optarg);
431                                 if (options.cipher == -1) {
432                                         fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
433                                         exit(1);
434                                 }
435                                 if (options.cipher == SSH_CIPHER_3DES) {
436                                         options.ciphers = "3des-cbc";
437                                 } else if (options.cipher == SSH_CIPHER_BLOWFISH) {
438                                         options.ciphers = "blowfish-cbc";
439                                 } else {
440                                         options.ciphers = (char *)-1;
441                                 }
442                         }
443                         break;
444                 case 'p':
445                         options.port = atoi(optarg);
446                         break;
447                 case 'l':
448                         options.user = optarg;
449                         break;
450                 case 'R':
451                         if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
452                             &fwd_host_port) != 3 &&
453                             sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
454                             &fwd_host_port) != 3) {
455                                 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
456                                 usage();
457                                 /* NOTREACHED */
458                         }
459                         add_remote_forward(&options, fwd_port, buf, fwd_host_port);
460                         break;
461                 case 'L':
462                         if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
463                             &fwd_host_port) != 3 &&
464                             sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
465                             &fwd_host_port) != 3) {
466                                 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
467                                 usage();
468                                 /* NOTREACHED */
469                         }
470                         add_local_forward(&options, fwd_port, buf, fwd_host_port);
471                         break;
472                 case 'C':
473                         options.compression = 1;
474                         break;
475                 case 'N':
476                         no_shell_flag = 1;
477                         no_tty_flag = 1;
478                         break;
479                 case 'T':
480                         no_tty_flag = 1;
481                         break;
482                 case 'o':
483                         dummy = 1;
484                         if (process_config_line(&options, host ? host : "", optarg,
485                                          "command-line", 0, &dummy) != 0)
486                                 exit(1);
487                         break;
488                 default:
489                         usage();
490                 }
491         }
492
493         /* Check that we got a host name. */
494         if (!host)
495                 usage();
496
497         SSLeay_add_all_algorithms();
498         ERR_load_crypto_strings();
499
500         /* Initialize the command to execute on remote host. */
501         buffer_init(&command);
502
503         /*
504          * Save the command to execute on the remote host in a buffer. There
505          * is no limit on the length of the command, except by the maximum
506          * packet size.  Also sets the tty flag if there is no command.
507          */
508         if (optind == ac) {
509                 /* No command specified - execute shell on a tty. */
510                 tty_flag = 1;
511         } else {
512                 /* A command has been specified.  Store it into the
513                    buffer. */
514                 for (i = optind; i < ac; i++) {
515                         if (i > optind)
516                                 buffer_append(&command, " ", 1);
517                         buffer_append(&command, av[i], strlen(av[i]));
518                 }
519         }
520
521         /* Cannot fork to background if no command. */
522         if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
523                 fatal("Cannot fork into background without a command to execute.");
524
525         /* Allocate a tty by default if no command specified. */
526         if (buffer_len(&command) == 0)
527                 tty_flag = 1;
528
529         /* Force no tty*/
530         if (no_tty_flag)
531                 tty_flag = 0;
532         /* Do not allocate a tty if stdin is not a tty. */
533         if (!isatty(fileno(stdin))) {
534                 if (tty_flag)
535                         fprintf(stderr, "Pseudo-terminal will not be allocated because stdin is not a terminal.\n");
536                 tty_flag = 0;
537         }
538
539         /* Get user data. */
540         pw = getpwuid(original_real_uid);
541         if (!pw) {
542                 fprintf(stderr, "You don't exist, go away!\n");
543                 exit(1);
544         }
545         /* Take a copy of the returned structure. */
546         memset(&pwcopy, 0, sizeof(pwcopy));
547         pwcopy.pw_name = xstrdup(pw->pw_name);
548         pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
549         pwcopy.pw_uid = pw->pw_uid;
550         pwcopy.pw_gid = pw->pw_gid;
551 #ifdef HAVE_PW_CLASS_IN_PASSWD
552         pwcopy.pw_class = xstrdup(pw->pw_class);
553 #endif
554         pwcopy.pw_dir = xstrdup(pw->pw_dir);
555         pwcopy.pw_shell = xstrdup(pw->pw_shell);
556         pw = &pwcopy;
557
558         /* Initialize "log" output.  Since we are the client all output
559            actually goes to the terminal. */
560         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
561
562         /* Read per-user configuration file. */
563         snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_CONFFILE);
564         read_config_file(buf, host, &options);
565
566         /* Read systemwide configuration file. */
567         read_config_file(HOST_CONFIG_FILE, host, &options);
568
569         /* Fill configuration defaults. */
570         fill_default_options(&options);
571
572         /* reinit */
573         log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 0);
574
575         if (options.user == NULL)
576                 options.user = xstrdup(pw->pw_name);
577
578         if (options.hostname != NULL)
579                 host = options.hostname;
580
581         /* Disable rhosts authentication if not running as root. */
582 #ifdef HAVE_CYGWIN
583         /* Ignore uid if running under Windows */
584         if (!options.use_privileged_port) {
585 #else
586         if (original_effective_uid != 0 || !options.use_privileged_port) {
587                 debug("Rhosts Authentication methods disabled, "
588                     "originating port will not be trusted.");
589 #endif
590                 options.rhosts_authentication = 0;
591                 options.rhosts_rsa_authentication = 0;
592         }
593         /*
594          * If using rsh has been selected, exec it now (without trying
595          * anything else).  Note that we must release privileges first.
596          */
597         if (options.use_rsh) {
598                 /*
599                  * Restore our superuser privileges.  This must be done
600                  * before permanently setting the uid.
601                  */
602                 restore_uid();
603
604                 /* Switch to the original uid permanently. */
605                 permanently_set_uid(original_real_uid);
606
607                 /* Execute rsh. */
608                 rsh_connect(host, options.user, &command);
609                 fatal("rsh_connect returned");
610         }
611         /* Restore our superuser privileges. */
612         restore_uid();
613
614         /*
615          * Open a connection to the remote host.  This needs root privileges
616          * if rhosts_{rsa_}authentication is enabled.
617          */
618
619         ok = ssh_connect(host, &hostaddr, options.port,
620                          options.connection_attempts,
621                          !options.rhosts_authentication &&
622                          !options.rhosts_rsa_authentication,
623                          original_real_uid,
624                          options.proxy_command);
625
626         /*
627          * If we successfully made the connection, load the host private key
628          * in case we will need it later for combined rsa-rhosts
629          * authentication. This must be done before releasing extra
630          * privileges, because the file is only readable by root.
631          */
632         if (ok && (options.protocol & SSH_PROTO_1)) {
633                 Key k;
634                 host_private_key = RSA_new();
635                 k.type = KEY_RSA1;
636                 k.rsa = host_private_key;
637                 if (load_private_key(HOST_KEY_FILE, "", &k, NULL))
638                         host_private_key_loaded = 1;
639         }
640         /*
641          * Get rid of any extra privileges that we may have.  We will no
642          * longer need them.  Also, extra privileges could make it very hard
643          * to read identity files and other non-world-readable files from the
644          * user's home directory if it happens to be on a NFS volume where
645          * root is mapped to nobody.
646          */
647
648         /*
649          * Note that some legacy systems need to postpone the following call
650          * to permanently_set_uid() until the private hostkey is destroyed
651          * with RSA_free().  Otherwise the calling user could ptrace() the
652          * process, read the private hostkey and impersonate the host.
653          * OpenBSD does not allow ptracing of setuid processes.
654          */
655         permanently_set_uid(original_real_uid);
656
657         /*
658          * Now that we are back to our own permissions, create ~/.ssh
659          * directory if it doesn\'t already exist.
660          */
661         snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir, SSH_USER_DIR);
662         if (stat(buf, &st) < 0)
663                 if (mkdir(buf, 0700) < 0)
664                         error("Could not create directory '%.200s'.", buf);
665
666         /* Check if the connection failed, and try "rsh" if appropriate. */
667         if (!ok) {
668                 if (options.port != 0)
669                         log("Secure connection to %.100s on port %hu refused%.100s.",
670                             host, options.port,
671                             options.fallback_to_rsh ? "; reverting to insecure method" : "");
672                 else
673                         log("Secure connection to %.100s refused%.100s.", host,
674                             options.fallback_to_rsh ? "; reverting to insecure method" : "");
675
676                 if (options.fallback_to_rsh) {
677                         rsh_connect(host, options.user, &command);
678                         fatal("rsh_connect returned");
679                 }
680                 exit(1);
681         }
682         /* Expand ~ in options.identity_files, known host file names. */
683         /* XXX mem-leaks */
684         for (i = 0; i < options.num_identity_files; i++) {
685                 options.identity_files[i] =
686                     tilde_expand_filename(options.identity_files[i], original_real_uid);
687                 options.identity_files_type[i] = guess_identity_file_type(options.identity_files[i]);
688                 debug("identity file %s type %d", options.identity_files[i],
689                     options.identity_files_type[i]);
690         }
691         options.system_hostfile =
692             tilde_expand_filename(options.system_hostfile, original_real_uid);
693         options.user_hostfile =
694             tilde_expand_filename(options.user_hostfile, original_real_uid);
695         options.system_hostfile2 =
696             tilde_expand_filename(options.system_hostfile2, original_real_uid);
697         options.user_hostfile2 =
698             tilde_expand_filename(options.user_hostfile2, original_real_uid);
699
700         /* Log into the remote system.  This never returns if the login fails. */
701         ssh_login(host_private_key_loaded, host_private_key,
702                   host, (struct sockaddr *)&hostaddr, original_real_uid);
703
704         /* We no longer need the host private key.  Clear it now. */
705         if (host_private_key_loaded)
706                 RSA_free(host_private_key);     /* Destroys contents safely */
707
708         exit_status = compat20 ? ssh_session2() : ssh_session();
709         packet_close();
710         return exit_status;
711 }
712
713 void
714 x11_get_proto(char *proto, int proto_len, char *data, int data_len)
715 {
716         char line[512];
717         FILE *f;
718         int got_data = 0, i;
719
720         if (options.xauth_location) {
721                 /* Try to get Xauthority information for the display. */
722                 snprintf(line, sizeof line, "%.100s list %.200s 2>/dev/null",
723                     options.xauth_location, getenv("DISPLAY"));
724                 f = popen(line, "r");
725                 if (f && fgets(line, sizeof(line), f) &&
726                     sscanf(line, "%*s %s %s", proto, data) == 2)
727                         got_data = 1;
728                 if (f)
729                         pclose(f);
730         }
731         /*
732          * If we didn't get authentication data, just make up some
733          * data.  The forwarding code will check the validity of the
734          * response anyway, and substitute this data.  The X11
735          * server, however, will ignore this fake data and use
736          * whatever authentication mechanisms it was using otherwise
737          * for the local connection.
738          */
739         if (!got_data) {
740                 u_int32_t rand = 0;
741
742                 strlcpy(proto, "MIT-MAGIC-COOKIE-1", proto_len);
743                 for (i = 0; i < 16; i++) {
744                         if (i % 4 == 0)
745                                 rand = arc4random();
746                         snprintf(data + 2 * i, data_len - 2 * i, "%02x", rand & 0xff);
747                         rand >>= 8;
748                 }
749         }
750 }
751
752 void
753 ssh_init_forwarding(void)
754 {
755         int i;
756         /* Initiate local TCP/IP port forwardings. */
757         for (i = 0; i < options.num_local_forwards; i++) {
758                 debug("Connections to local port %d forwarded to remote address %.200s:%d",
759                     options.local_forwards[i].port,
760                     options.local_forwards[i].host,
761                     options.local_forwards[i].host_port);
762                 channel_request_local_forwarding(
763                     options.local_forwards[i].port,
764                     options.local_forwards[i].host,
765                     options.local_forwards[i].host_port,
766                     options.gateway_ports);
767         }
768
769         /* Initiate remote TCP/IP port forwardings. */
770         for (i = 0; i < options.num_remote_forwards; i++) {
771                 debug("Connections to remote port %d forwarded to local address %.200s:%d",
772                     options.remote_forwards[i].port,
773                     options.remote_forwards[i].host,
774                     options.remote_forwards[i].host_port);
775                 channel_request_remote_forwarding(
776                     options.remote_forwards[i].port,
777                     options.remote_forwards[i].host,
778                     options.remote_forwards[i].host_port);
779         }
780 }
781
782 void
783 check_agent_present(void)
784 {
785         if (options.forward_agent) {
786                 /* Clear agent forwarding if we don\'t have an agent. */
787                 int authfd = ssh_get_authentication_socket();
788                 if (authfd < 0)
789                         options.forward_agent = 0;
790                 else
791                         ssh_close_authentication_socket(authfd);
792         }
793 }
794
795 int
796 ssh_session(void)
797 {
798         int type;
799         int plen;
800         int interactive = 0;
801         int have_tty = 0;
802         struct winsize ws;
803         char *cp;
804
805         /* Enable compression if requested. */
806         if (options.compression) {
807                 debug("Requesting compression at level %d.", options.compression_level);
808
809                 if (options.compression_level < 1 || options.compression_level > 9)
810                         fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
811
812                 /* Send the request. */
813                 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
814                 packet_put_int(options.compression_level);
815                 packet_send();
816                 packet_write_wait();
817                 type = packet_read(&plen);
818                 if (type == SSH_SMSG_SUCCESS)
819                         packet_start_compression(options.compression_level);
820                 else if (type == SSH_SMSG_FAILURE)
821                         log("Warning: Remote host refused compression.");
822                 else
823                         packet_disconnect("Protocol error waiting for compression response.");
824         }
825         /* Allocate a pseudo tty if appropriate. */
826         if (tty_flag) {
827                 debug("Requesting pty.");
828
829                 /* Start the packet. */
830                 packet_start(SSH_CMSG_REQUEST_PTY);
831
832                 /* Store TERM in the packet.  There is no limit on the
833                    length of the string. */
834                 cp = getenv("TERM");
835                 if (!cp)
836                         cp = "";
837                 packet_put_string(cp, strlen(cp));
838
839                 /* Store window size in the packet. */
840                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
841                         memset(&ws, 0, sizeof(ws));
842                 packet_put_int(ws.ws_row);
843                 packet_put_int(ws.ws_col);
844                 packet_put_int(ws.ws_xpixel);
845                 packet_put_int(ws.ws_ypixel);
846
847                 /* Store tty modes in the packet. */
848                 tty_make_modes(fileno(stdin));
849
850                 /* Send the packet, and wait for it to leave. */
851                 packet_send();
852                 packet_write_wait();
853
854                 /* Read response from the server. */
855                 type = packet_read(&plen);
856                 if (type == SSH_SMSG_SUCCESS) {
857                         interactive = 1;
858                         have_tty = 1;
859                 } else if (type == SSH_SMSG_FAILURE)
860                         log("Warning: Remote host failed or refused to allocate a pseudo tty.");
861                 else
862                         packet_disconnect("Protocol error waiting for pty request response.");
863         }
864         /* Request X11 forwarding if enabled and DISPLAY is set. */
865         if (options.forward_x11 && getenv("DISPLAY") != NULL) {
866                 char proto[512], data[512];
867                 /* Get reasonable local authentication information. */
868                 x11_get_proto(proto, sizeof proto, data, sizeof data);
869                 /* Request forwarding with authentication spoofing. */
870                 debug("Requesting X11 forwarding with authentication spoofing.");
871                 x11_request_forwarding_with_spoofing(0, proto, data);
872
873                 /* Read response from the server. */
874                 type = packet_read(&plen);
875                 if (type == SSH_SMSG_SUCCESS) {
876                         interactive = 1;
877                 } else if (type == SSH_SMSG_FAILURE) {
878                         log("Warning: Remote host denied X11 forwarding.");
879                 } else {
880                         packet_disconnect("Protocol error waiting for X11 forwarding");
881                 }
882         }
883         /* Tell the packet module whether this is an interactive session. */
884         packet_set_interactive(interactive, options.keepalives);
885
886
887         /* Request authentication agent forwarding if appropriate. */
888         check_agent_present();
889
890         if (options.forward_agent) {
891                 debug("Requesting authentication agent forwarding.");
892                 auth_request_forwarding();
893
894                 /* Read response from the server. */
895                 type = packet_read(&plen);
896                 packet_integrity_check(plen, 0, type);
897                 if (type != SSH_SMSG_SUCCESS)
898                         log("Warning: Remote host denied authentication agent forwarding.");
899         }
900
901         /* Initiate port forwardings. */
902         ssh_init_forwarding();
903
904         /* If requested, let ssh continue in the background. */
905         if (fork_after_authentication_flag)
906                 if (daemon(1, 1) < 0)
907                         fatal("daemon() failed: %.200s", strerror(errno));
908
909         /*
910          * If a command was specified on the command line, execute the
911          * command now. Otherwise request the server to start a shell.
912          */
913         if (buffer_len(&command) > 0) {
914                 int len = buffer_len(&command);
915                 if (len > 900)
916                         len = 900;
917                 debug("Sending command: %.*s", len, buffer_ptr(&command));
918                 packet_start(SSH_CMSG_EXEC_CMD);
919                 packet_put_string(buffer_ptr(&command), buffer_len(&command));
920                 packet_send();
921                 packet_write_wait();
922         } else {
923                 debug("Requesting shell.");
924                 packet_start(SSH_CMSG_EXEC_SHELL);
925                 packet_send();
926                 packet_write_wait();
927         }
928
929         /* Enter the interactive session. */
930         return client_loop(have_tty, tty_flag ? options.escape_char : -1, 0);
931 }
932
933 extern void client_set_session_ident(int id);
934
935 void
936 ssh_session2_callback(int id, void *arg)
937 {
938         int len;
939         debug("client_init id %d arg %d", id, (int)arg);
940
941         if (no_shell_flag)
942                 goto done;
943
944         if (tty_flag) {
945                 struct winsize ws;
946                 char *cp;
947                 cp = getenv("TERM");
948                 if (!cp)
949                         cp = "";
950                 /* Store window size in the packet. */
951                 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
952                         memset(&ws, 0, sizeof(ws));
953
954                 channel_request_start(id, "pty-req", 0);
955                 packet_put_cstring(cp);
956                 packet_put_int(ws.ws_col);
957                 packet_put_int(ws.ws_row);
958                 packet_put_int(ws.ws_xpixel);
959                 packet_put_int(ws.ws_ypixel);
960                 packet_put_cstring("");         /* XXX: encode terminal modes */
961                 packet_send();
962                 /* XXX wait for reply */
963         }
964         if (options.forward_x11 &&
965             getenv("DISPLAY") != NULL) {
966                 char proto[512], data[512];
967                 /* Get reasonable local authentication information. */
968                 x11_get_proto(proto, sizeof proto, data, sizeof data);
969                 /* Request forwarding with authentication spoofing. */
970                 debug("Requesting X11 forwarding with authentication spoofing.");
971                 x11_request_forwarding_with_spoofing(id, proto, data);
972                 /* XXX wait for reply */
973         }
974
975         check_agent_present();
976         if (options.forward_agent) {
977                 debug("Requesting authentication agent forwarding.");
978                 channel_request_start(id, "auth-agent-req@openssh.com", 0);
979                 packet_send();
980         }
981
982         len = buffer_len(&command);
983         if (len > 0) {
984                 if (len > 900)
985                         len = 900;
986                 debug("Sending command: %.*s", len, buffer_ptr(&command));
987                 channel_request_start(id, "exec", 0);
988                 packet_put_string(buffer_ptr(&command), len);
989                 packet_send();
990         } else {
991                 channel_request(id, "shell", 0);
992         }
993         /* channel_callback(id, SSH2_MSG_OPEN_CONFIGMATION, client_init, 0); */
994 done:
995         /* register different callback, etc. XXX */
996         client_set_session_ident(id);
997 }
998
999 int
1000 ssh_session2(void)
1001 {
1002         int window, packetmax, id;
1003         int in, out, err;
1004
1005         if (stdin_null_flag) {
1006                 in = open("/dev/null", O_RDONLY);
1007         } else {
1008                 in = dup(STDIN_FILENO);
1009         }
1010         out = dup(STDOUT_FILENO);
1011         err = dup(STDERR_FILENO);
1012
1013         if (in < 0 || out < 0 || err < 0)
1014                 fatal("dup() in/out/err failed");
1015
1016         /* enable nonblocking unless tty */
1017         if (!isatty(in))
1018                 set_nonblock(in);
1019         if (!isatty(out))
1020                 set_nonblock(out);
1021         if (!isatty(err))
1022                 set_nonblock(err);
1023
1024         /* XXX should be pre-session */
1025         ssh_init_forwarding();
1026         
1027         /* If requested, let ssh continue in the background. */
1028         if (fork_after_authentication_flag)
1029                 if (daemon(1, 1) < 0)
1030                         fatal("daemon() failed: %.200s", strerror(errno));
1031
1032         window = CHAN_SES_WINDOW_DEFAULT;
1033         packetmax = CHAN_SES_PACKET_DEFAULT;
1034         if (!tty_flag) {
1035                 window *= 2;
1036                 packetmax *=2;
1037         }
1038         id = channel_new(
1039             "session", SSH_CHANNEL_OPENING, in, out, err,
1040             window, packetmax, CHAN_EXTENDED_WRITE,
1041             xstrdup("client-session"), /*nonblock*/0);
1042
1043         channel_open(id);
1044         channel_register_callback(id, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION,
1045              ssh_session2_callback, (void *)0);
1046
1047         return client_loop(tty_flag, tty_flag ? options.escape_char : -1, id);
1048 }
1049
1050 int
1051 guess_identity_file_type(const char *filename)
1052 {
1053         struct stat st;
1054         Key *public;
1055         int type = KEY_RSA1; /* default */
1056
1057         if (stat(filename, &st) < 0) {
1058                 /* ignore this key */
1059                 return KEY_UNSPEC;
1060         }
1061         public = key_new(type);
1062         if (!load_public_key(filename, public, NULL)) {
1063                 /* ok, so we will assume this is 'some' key */
1064                 type = KEY_UNSPEC;
1065         }
1066         key_free(public);
1067         return type;
1068 }
This page took 0.116763 seconds and 5 git commands to generate.