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