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