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