summaryrefslogtreecommitdiff
path: root/other/ssharp/ssh.c
diff options
context:
space:
mode:
Diffstat (limited to 'other/ssharp/ssh.c')
-rw-r--r--other/ssharp/ssh.c1064
1 files changed, 1064 insertions, 0 deletions
diff --git a/other/ssharp/ssh.c b/other/ssharp/ssh.c
new file mode 100644
index 0000000..91f08cb
--- /dev/null
+++ b/other/ssharp/ssh.c
@@ -0,0 +1,1064 @@
1/*
2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
5 * Ssh client program. This program can be used to log into a remote machine.
6 * The software supports strong authentication, encryption, and forwarding
7 * of X11, TCP/IP, and authentication connections.
8 *
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
14 *
15 * Copyright (c) 1999 Niels Provos. All rights reserved.
16 *
17 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
18 * in Canada (German citizen).
19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 */
40
41#include "includes.h"
42
43#include <openssl/evp.h>
44#include <openssl/err.h>
45
46#include "ssh.h"
47#include "ssh1.h"
48#include "ssh2.h"
49#include "compat.h"
50#include "cipher.h"
51#include "xmalloc.h"
52#include "packet.h"
53#include "buffer.h"
54#include "uidswap.h"
55#include "channels.h"
56#include "key.h"
57#include "authfd.h"
58#include "authfile.h"
59#include "pathnames.h"
60#include "clientloop.h"
61#include "log.h"
62#include "readconf.h"
63#include "sshconnect.h"
64#include "tildexpand.h"
65#include "dispatch.h"
66#include "misc.h"
67#include "kex.h"
68#include "mac.h"
69#include "sshtty.h"
70#include "ssharp.h"
71
72#ifdef HAVE___PROGNAME
73extern char *__progname;
74#else
75char *__progname;
76#endif
77
78
79/* dummy. If these are 0, then this doesnt affect kex.c
80 */
81int SSH2_mim_only = 0;
82char *SSH2_mim_cipher = NULL;
83
84char *oav[100]; /* Should be enough ... */
85
86/* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
87 Default value is AF_UNSPEC means both IPv4 and IPv6. */
88#ifdef IPV4_DEFAULT
89int IPv4or6 = AF_INET;
90#else
91int IPv4or6 = AF_UNSPEC;
92#endif
93
94/* Flag indicating whether debug mode is on. This can be set on the command line. */
95int debug_flag = 0;
96
97/* The default is *not* to save any information about hosts we are connecting
98to */
99int save_hostinfo = 0;
100
101/* Flag indicating whether a tty should be allocated */
102int tty_flag = 0;
103int no_tty_flag = 0;
104int force_tty_flag = 0;
105
106/* don't exec a shell */
107int no_shell_flag = 0;
108
109/*
110 * Flag indicating that nothing should be read from stdin. This can be set
111 * on the command line.
112 */
113int stdin_null_flag = 0;
114
115/*
116 * Flag indicating that ssh should fork after authentication. This is useful
117 * so that the pasphrase can be entered manually, and then ssh goes to the
118 * background.
119 */
120int fork_after_authentication_flag = 0;
121
122/*
123 * General data structure for command line options and options configurable
124 * in configuration files. See readconf.h.
125 */
126Options options;
127
128/*
129 * Name of the host we are connecting to. This is the name given on the
130 * command line, or the HostName specified for the user-supplied name in a
131 * configuration file.
132 */
133char *host;
134
135/* socket address the host resolves to */
136struct sockaddr_storage hostaddr;
137
138/*
139 * Flag to indicate that we have received a window change signal which has
140 * not yet been processed. This will cause a message indicating the new
141 * window size to be sent to the server a little later. This is volatile
142 * because this is updated in a signal handler.
143 */
144volatile int received_window_change_signal = 0;
145
146char *client_version_string, *server_version_string;
147
148/* Private host keys. */
149struct {
150 Key **keys;
151 int nkeys;
152} sensitive_data;
153
154
155/* command to be executed */
156Buffer command;
157
158/* Should we execute a command or invoke a subsystem? */
159int subsystem_flag = 0;
160
161/* Prints a help message to the user. This function never returns. */
162
163void
164usage(void)
165{
166 fprintf(stderr, "Usage: %s [options] host [command]\n", __progname);
167 fprintf(stderr, "Options:\n");
168 fprintf(stderr, " -l user Log in using this user name.\n");
169 fprintf(stderr, " -Z pass Use 'pass' to login.\n");
170 fprintf(stderr, " -r Use special RSA-mode.\n");
171 fprintf(stderr, " -n Redirect input from " _PATH_DEVNULL ".\n");
172 fprintf(stderr, " -A Enable authentication agent forwarding.\n");
173 fprintf(stderr, " -a Disable authentication agent forwarding.\n");
174 fprintf(stderr, " -X Enable X11 connection forwarding.\n");
175 fprintf(stderr, " -x Disable X11 connection forwarding.\n");
176 fprintf(stderr, " -i file Identity for public key authentication "
177 "(default: ~/.ssh/identity)\n");
178 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n");
179 fprintf(stderr, " -T Do not allocate a tty.\n");
180 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
181 fprintf(stderr, " Multiple -v increases verbosity.\n");
182 fprintf(stderr, " -V Display version number only.\n");
183 fprintf(stderr, " -q Quiet; don't display any warning messages.\n");
184 fprintf(stderr, " -f Fork into background after authentication.\n");
185
186 fprintf(stderr, " -c cipher Select encryption algorithm: "
187 "``3des'', ``blowfish''\n");
188 fprintf(stderr, " -m macs Specify MAC algorithms for protocol version 2.\n");
189 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n");
190 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n");
191 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n");
192 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", __progname);
193 fprintf(stderr, " forward them to the other side by connecting to host:port.\n");
194 fprintf(stderr, " -C Enable compression.\n");
195 fprintf(stderr, " -N Do not execute a shell or command.\n");
196 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n");
197 fprintf(stderr, " -1 Force protocol version 1.\n");
198 fprintf(stderr, " -2 Force protocol version 2.\n");
199 fprintf(stderr, " -4 Use IPv4 only.\n");
200 fprintf(stderr, " -6 Use IPv6 only.\n");
201 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n");
202 fprintf(stderr, " -s Invoke command (mandatory) as SSH2 subsystem.\n");
203 fprintf(stderr, " -$ Act as MiM client.\n");
204 fprintf(stderr, " -P Local port to bind to.\n");
205 exit(1);
206}
207
208/*
209 * Connects to the given host using rsh (or prints an error message and exits
210 * if rsh is not available). This function never returns.
211 */
212void
213rsh_connect(char *host, char *user, Buffer * command)
214{
215 char *args[10];
216 int i;
217
218 log("Using rsh. WARNING: Connection will not be encrypted.");
219 /* Build argument list for rsh. */
220 i = 0;
221 args[i++] = _PATH_RSH;
222 /* host may have to come after user on some systems */
223 args[i++] = host;
224 if (user) {
225 args[i++] = "-l";
226 args[i++] = user;
227 }
228 if (buffer_len(command) > 0) {
229 buffer_append(command, "\0", 1);
230 args[i++] = buffer_ptr(command);
231 }
232 args[i++] = NULL;
233 if (debug_flag) {
234 for (i = 0; args[i]; i++) {
235 if (i != 0)
236 fprintf(stderr, " ");
237 fprintf(stderr, "%s", args[i]);
238 }
239 fprintf(stderr, "\n");
240 }
241 execv(_PATH_RSH, args);
242 perror(_PATH_RSH);
243 exit(1);
244}
245
246int ssh_session(void);
247int ssh_session2(void);
248void load_public_identity_files(void);
249
250/*
251 * Main program for the ssh client.
252 */
253int
254main(int ac, char **av)
255{
256 int i, opt, optind, exit_status, ok;
257 u_short fwd_port, fwd_host_port;
258 char *optarg, *cp, buf[256], *pass = NULL;
259 struct stat st;
260 int dummy, mimi = 0;
261
262 __progname = get_progname(av[0]);
263 init_rng();
264
265
266 /*
267 * Set our umask to something reasonable, as some files are created
268 * with the default umask. This will make them world-readable but
269 * writable only by the owner, which is ok for all files for which we
270 * don't set the modes explicitly.
271 */
272 umask(022);
273
274 /* Initialize option structure to indicate that no values have been set. */
275 initialize_options(&options);
276
277 /* Parse command-line arguments. */
278 host = NULL;
279
280 for (optind = 1; optind < ac; optind++) {
281 if (av[optind][0] != '-') {
282 if (host)
283 break;
284 if ((cp = strchr(av[optind], '@'))) {
285 if(cp == av[optind])
286 usage();
287 options.user = av[optind];
288 *cp = '\0';
289 host = ++cp;
290 } else
291 host = av[optind];
292 continue;
293 }
294 opt = av[optind][1];
295 if (!opt)
296 usage();
297 if (strchr("ZMIeilcmpBLRDoP", opt)) { /* options with arguments */
298 optarg = av[optind] + 2;
299 if (strcmp(optarg, "") == 0) {
300 if (optind >= ac - 1)
301 usage();
302 optarg = av[++optind];
303 }
304 } else {
305 if (av[optind][2])
306 usage();
307 optarg = NULL;
308 }
309 switch (opt) {
310 case '1':
311 options.protocol = SSH_PROTO_1;
312 break;
313 case '2':
314 options.protocol = SSH_PROTO_2;
315 break;
316 case '4':
317 IPv4or6 = AF_INET;
318 break;
319 case '6':
320 IPv4or6 = AF_INET6;
321 break;
322 case 'n':
323 stdin_null_flag = 1;
324 break;
325 case 'f':
326 fork_after_authentication_flag = 1;
327 stdin_null_flag = 1;
328 break;
329 case 'x':
330 options.forward_x11 = 0;
331 break;
332 case 'X':
333 options.forward_x11 = 1;
334 break;
335 case 'g':
336 options.gateway_ports = 1;
337 break;
338 case 'P':
339 options.use_privileged_port = atoi(optarg);
340 break;
341 case 'a':
342 options.forward_agent = 0;
343 break;
344 case 'A':
345 options.forward_agent = 1;
346 break;
347 case 'i':
348 if (stat(optarg, &st) < 0) {
349 fprintf(stderr, "Warning: Identity file %s does not exist.\n",
350 optarg);
351 break;
352 }
353 if (options.num_identity_files >= SSH_MAX_IDENTITY_FILES)
354 fatal("Too many identity files specified (max %d)",
355 SSH_MAX_IDENTITY_FILES);
356 options.identity_files[options.num_identity_files++] = xstrdup(optarg);
357 break;
358 case 't':
359 if (tty_flag)
360 force_tty_flag = 1;
361 tty_flag = 1;
362 break;
363 case 'v':
364 if (0 == debug_flag) {
365 debug_flag = 1;
366 options.log_level = SYSLOG_LEVEL_DEBUG1;
367 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
368 options.log_level++;
369 break;
370 } else {
371 fatal("Too high debugging level.");
372 }
373 /* fallthrough */
374 case 'V':
375 fprintf(stderr,
376 "%s, SSH protocols %d.%d/%d.%d, OpenSSL 0x%8.8lx\n",
377 SSH_VERSION,
378 PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1,
379 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2,
380 SSLeay());
381 if (opt == 'V')
382 exit(0);
383 break;
384 case 'q':
385 options.log_level = SYSLOG_LEVEL_QUIET;
386 break;
387 case 'e':
388 /* SSHARP: no escapes please */
389 fprintf(stderr, "Bad.\n");
390 break;
391 case 'c':
392 if (ciphers_valid(optarg)) {
393 /* SSH2 only */
394 options.ciphers = xstrdup(optarg);
395 options.cipher = SSH_CIPHER_ILLEGAL;
396 } else {
397 /* SSH1 only */
398 options.cipher = cipher_number(optarg);
399 if (options.cipher == -1) {
400 fprintf(stderr, "Unknown cipher type '%s'\n", optarg);
401 exit(1);
402 }
403 if (options.cipher == SSH_CIPHER_3DES) {
404 options.ciphers = "3des-cbc";
405 } else if (options.cipher == SSH_CIPHER_BLOWFISH) {
406 options.ciphers = "blowfish-cbc";
407 } else {
408 options.ciphers = (char *)-1;
409 }
410 }
411 break;
412 case 'm':
413 if (mac_valid(optarg))
414 options.macs = xstrdup(optarg);
415 else {
416 fprintf(stderr, "Unknown mac type '%s'\n", optarg);
417 exit(1);
418 }
419 break;
420 case 'p':
421 options.port = a2port(optarg);
422 if (options.port == 0) {
423 fprintf(stderr, "Bad port '%s'\n", optarg);
424 exit(1);
425 }
426 break;
427 case 'l':
428 options.user = optarg;
429 break;
430 case '$':
431 mimi = 1;
432 break;
433 case 'R':
434 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
435 &fwd_host_port) != 3 &&
436 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
437 &fwd_host_port) != 3) {
438 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
439 usage();
440 /* NOTREACHED */
441 }
442 add_remote_forward(&options, fwd_port, buf, fwd_host_port);
443 break;
444 case 'L':
445 if (sscanf(optarg, "%hu/%255[^/]/%hu", &fwd_port, buf,
446 &fwd_host_port) != 3 &&
447 sscanf(optarg, "%hu:%255[^:]:%hu", &fwd_port, buf,
448 &fwd_host_port) != 3) {
449 fprintf(stderr, "Bad forwarding specification '%s'.\n", optarg);
450 usage();
451 /* NOTREACHED */
452 }
453 add_local_forward(&options, fwd_port, buf, fwd_host_port);
454 break;
455
456 case 'D':
457 fwd_port = a2port(optarg);
458 if (fwd_port == 0) {
459 fprintf(stderr, "Bad dynamic port '%s'\n", optarg);
460 exit(1);
461 }
462 add_local_forward(&options, fwd_port, "socks4", 0);
463 break;
464
465 case 'C':
466 options.compression = 1;
467 break;
468 case 'N':
469 no_shell_flag = 1;
470 no_tty_flag = 1;
471 break;
472 case 'T':
473 no_tty_flag = 1;
474 break;
475 case 'o':
476 dummy = 1;
477 if (process_config_line(&options, host ? host : "", optarg,
478 "command-line", 0, &dummy) != 0)
479 exit(1);
480 break;
481 case 's':
482 subsystem_flag = 1;
483 break;
484 case 'b':
485 fprintf(stderr, "Warning: saving host keys and IP addresses!\n");
486 save_hostinfo = 1;
487 break;
488 case 'Z':
489 pass = strdup(optarg);
490 break;
491 case 'r':
492 options.specialRSA = 1;
493 break;
494 default:
495 usage();
496 }
497 }
498
499 if (options.user == NULL || (pass == NULL && !options.specialRSA)) {
500 fprintf(stderr, "Dumbo. When acting as passwd-MiM I need -Z and"
501 "-l switch. When acting as RSA-mim, need at least -l.\n");
502 exit(1);
503 }
504
505 /* Check that we got a host name. */
506 if (!host)
507 usage();
508
509
510 SSLeay_add_all_algorithms();
511 ERR_load_crypto_strings();
512
513 /* Initialize the command to execute on remote host. */
514 buffer_init(&command);
515
516 /*
517 * Save the command to execute on the remote host in a buffer. There
518 * is no limit on the length of the command, except by the maximum
519 * packet size. Also sets the tty flag if there is no command.
520 */
521 if (optind == ac) {
522 /* No command specified - execute shell on a tty. */
523 tty_flag = 1;
524 if (subsystem_flag) {
525 fprintf(stderr, "You must specify a subsystem to invoke.\n");
526 usage();
527 }
528 } else {
529 /* A command has been specified. Store it into the
530 buffer. */
531 for (i = optind; i < ac; i++) {
532 if (i > optind)
533 buffer_append(&command, " ", 1);
534 buffer_append(&command, av[i], strlen(av[i]));
535 }
536 }
537
538 /* Cannot fork to background if no command. */
539 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
540 fatal("Cannot fork into background without a command to execute.");
541
542 /* Allocate a tty by default if no command specified. */
543 if (buffer_len(&command) == 0)
544 tty_flag = 1;
545
546 /* Force no tty*/
547 if (no_tty_flag)
548 tty_flag = 0;
549 /* Do not allocate a tty if stdin is not a tty. */
550 if (!isatty(fileno(stdin)) && !force_tty_flag) {
551 if (tty_flag)
552 log("Pseudo-terminal will not be allocated because stdin is not a terminal.");
553 tty_flag = 0;
554 }
555
556 /*
557 * Initialize "log" output. Since we are the client all output
558 * actually goes to stderr.
559 */
560 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level, SYSLOG_FACILITY_USER, 1);
561
562
563 /* Read systemwide configuration file. */
564 read_config_file(_PATH_HOST_CONFIG_FILE, host, &options);
565
566 /* Fill configuration defaults. */
567 fill_default_options(&options);
568
569 /* reinit */
570 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
571
572 seed_rng();
573
574
575 if (options.hostname != NULL)
576 host = options.hostname;
577
578
579 /* Open a connection to the remote host. */
580 ok = ssh_connect(host, &hostaddr, options.port,
581 options.connection_attempts,
582 options.use_privileged_port,
583 options.proxy_command);
584
585 /*
586 * If we successfully made the connection, load the host private key
587 * in case we will need it later for combined rsa-rhosts
588 * authentication. This must be done before releasing extra
589 * privileges, because the file is only readable by root.
590 */
591 sensitive_data.nkeys = 0;
592 sensitive_data.keys = NULL;
593 if (ok && (options.rhosts_rsa_authentication ||
594 options.hostbased_authentication)) {
595 sensitive_data.nkeys = 3;
596 sensitive_data.keys = xmalloc(sensitive_data.nkeys*sizeof(Key));
597 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
598 _PATH_HOST_KEY_FILE, "", NULL);
599 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
600 _PATH_HOST_DSA_KEY_FILE, "", NULL);
601 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
602 _PATH_HOST_RSA_KEY_FILE, "", NULL);
603 }
604 /*
605 * Get rid of any extra privileges that we may have. We will no
606 * longer need them. Also, extra privileges could make it very hard
607 * to read identity files and other non-world-readable files from the
608 * user's home directory if it happens to be on a NFS volume where
609 * root is mapped to nobody.
610 */
611
612
613 /* Check if the connection failed, and try "rsh" if appropriate. */
614 if (!ok) {
615 if (options.port != 0)
616 log("Secure connection to %.100s on port %hu refused%.100s.",
617 host, options.port,
618 options.fallback_to_rsh ? "; reverting to insecure method" : "");
619 else
620 log("Secure connection to %.100s refused%.100s.", host,
621 options.fallback_to_rsh ? "; reverting to insecure method" : "");
622
623 exit(1);
624 }
625 /* load options.identity_files */
626 if (!options.specialRSA)
627 load_public_identity_files();
628
629 /* Expand ~ in known host file names. */
630 /* XXX mem-leaks: */
631 options.system_hostfile =
632 tilde_expand_filename(options.system_hostfile, getuid());
633 options.user_hostfile =
634 tilde_expand_filename(options.user_hostfile, getuid());
635 options.system_hostfile2 =
636 tilde_expand_filename(options.system_hostfile2, getuid());
637 options.user_hostfile2 =
638 tilde_expand_filename(options.user_hostfile2, getuid());
639
640 /* Log into the remote system. This never returns if the login fails. */
641 ssh_login(sensitive_data.keys, sensitive_data.nkeys,
642 host, (struct sockaddr *)&hostaddr, options.user, pass);
643
644 /* We no longer need the private host keys. Clear them now. */
645 if (sensitive_data.nkeys != 0) {
646 for (i = 0; i < sensitive_data.nkeys; i++) {
647 if (sensitive_data.keys[i] != NULL) {
648 /* Destroys contents safely */
649 debug3("clear hostkey %d", i);
650 key_free(sensitive_data.keys[i]);
651 sensitive_data.keys[i] = NULL;
652 }
653 }
654 xfree(sensitive_data.keys);
655 }
656
657 exit_status = compat20 ? ssh_session2() : ssh_session();
658 packet_close();
659 return exit_status;
660}
661
662void
663x11_get_proto(char *proto, int proto_len, char *data, int data_len)
664{
665 char line[512];
666 FILE *f;
667 int got_data = 0, i;
668
669 if (options.xauth_location) {
670 /* Try to get Xauthority information for the display. */
671 snprintf(line, sizeof line, "%.100s list %.200s 2>" _PATH_DEVNULL,
672 options.xauth_location, getenv("DISPLAY"));
673 f = popen(line, "r");
674 if (f && fgets(line, sizeof(line), f) &&
675 sscanf(line, "%*s %s %s", proto, data) == 2)
676 got_data = 1;
677 if (f)
678 pclose(f);
679 }
680 /*
681 * If we didn't get authentication data, just make up some
682 * data. The forwarding code will check the validity of the
683 * response anyway, and substitute this data. The X11
684 * server, however, will ignore this fake data and use
685 * whatever authentication mechanisms it was using otherwise
686 * for the local connection.
687 */
688 if (!got_data) {
689 u_int32_t rand = 0;
690
691 strlcpy(proto, "MIT-MAGIC-COOKIE-1", proto_len);
692 for (i = 0; i < 16; i++) {
693 if (i % 4 == 0)
694 rand = arc4random();
695 snprintf(data + 2 * i, data_len - 2 * i, "%02x", rand & 0xff);
696 rand >>= 8;
697 }
698 }
699}
700
701void
702ssh_init_forwarding(void)
703{
704 int success = 0;
705 int i;
706
707 /* Initiate local TCP/IP port forwardings. */
708 for (i = 0; i < options.num_local_forwards; i++) {
709 debug("Connections to local port %d forwarded to remote address %.200s:%d",
710 options.local_forwards[i].port,
711 options.local_forwards[i].host,
712 options.local_forwards[i].host_port);
713 success += channel_request_local_forwarding(
714 options.local_forwards[i].port,
715 options.local_forwards[i].host,
716 options.local_forwards[i].host_port,
717 options.gateway_ports);
718 }
719 if (i > 0 && success == 0)
720 perror("Could not request local forwarding.");
721
722 /* Initiate remote TCP/IP port forwardings. */
723 for (i = 0; i < options.num_remote_forwards; i++) {
724 debug("Connections to remote port %d forwarded to local address %.200s:%d",
725 options.remote_forwards[i].port,
726 options.remote_forwards[i].host,
727 options.remote_forwards[i].host_port);
728 channel_request_remote_forwarding(
729 options.remote_forwards[i].port,
730 options.remote_forwards[i].host,
731 options.remote_forwards[i].host_port);
732 }
733}
734
735void
736check_agent_present(void)
737{
738 if (options.forward_agent) {
739 /* Clear agent forwarding if we don\'t have an agent. */
740 int authfd = ssh_get_authentication_socket();
741 if (authfd < 0)
742 options.forward_agent = 0;
743 else
744 ssh_close_authentication_socket(authfd);
745 }
746}
747
748int
749ssh_session(void)
750{
751 int type;
752 int plen;
753 int interactive = 0;
754 int have_tty = 0;
755 struct winsize ws;
756 char *cp;
757
758 /* Enable compression if requested. */
759 if (options.compression) {
760 debug("Requesting compression at level %d.", options.compression_level);
761
762 if (options.compression_level < 1 || options.compression_level > 9) {
763 fprintf(stderr, "Compression level must be from 1 (fast) to 9 (slow, best).");
764 exit(1);
765 }
766
767 /* Send the request. */
768 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
769 packet_put_int(options.compression_level);
770 packet_send();
771 packet_write_wait();
772 type = packet_read(&plen);
773 if (type == SSH_SMSG_SUCCESS)
774 packet_start_compression(options.compression_level);
775 else if (type == SSH_SMSG_FAILURE)
776 log("Warning: Remote host refused compression.");
777 else
778 packet_disconnect("Protocol error waiting for compression response.");
779 }
780 /* Allocate a pseudo tty if appropriate. */
781 if (tty_flag) {
782 debug("Requesting pty.");
783
784 /* Start the packet. */
785 packet_start(SSH_CMSG_REQUEST_PTY);
786
787 /* Store TERM in the packet. There is no limit on the
788 length of the string. */
789 cp = getenv("TERM");
790 if (!cp)
791 cp = "";
792 packet_put_string(cp, strlen(cp));
793
794 /* Store window size in the packet. */
795 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
796 memset(&ws, 0, sizeof(ws));
797 packet_put_int(ws.ws_row);
798 packet_put_int(ws.ws_col);
799 packet_put_int(ws.ws_xpixel);
800 packet_put_int(ws.ws_ypixel);
801
802 /* Store tty modes in the packet. */
803 tty_make_modes(fileno(stdin), NULL);
804
805 /* Send the packet, and wait for it to leave. */
806 packet_send();
807 packet_write_wait();
808
809 /* Read response from the server. */
810 type = packet_read(&plen);
811 if (type == SSH_SMSG_SUCCESS) {
812 interactive = 1;
813 have_tty = 1;
814 } else if (type == SSH_SMSG_FAILURE)
815 log("Warning: Remote host failed or refused to allocate a pseudo tty.");
816 else
817 packet_disconnect("Protocol error waiting for pty request response.");
818 }
819 /* Request X11 forwarding if enabled and DISPLAY is set. */
820 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
821 char proto[512], data[512];
822 /* Get reasonable local authentication information. */
823 x11_get_proto(proto, sizeof proto, data, sizeof data);
824 /* Request forwarding with authentication spoofing. */
825 debug("Requesting X11 forwarding with authentication spoofing.");
826 x11_request_forwarding_with_spoofing(0, proto, data);
827
828 /* Read response from the server. */
829 type = packet_read(&plen);
830 if (type == SSH_SMSG_SUCCESS) {
831 interactive = 1;
832 } else if (type == SSH_SMSG_FAILURE) {
833 log("Warning: Remote host denied X11 forwarding.");
834 } else {
835 packet_disconnect("Protocol error waiting for X11 forwarding");
836 }
837 }
838 /* Tell the packet module whether this is an interactive session. */
839 packet_set_interactive(interactive);
840
841 /* Request authentication agent forwarding if appropriate. */
842 check_agent_present();
843
844 if (options.forward_agent) {
845 debug("Requesting authentication agent forwarding.");
846 auth_request_forwarding();
847
848 /* Read response from the server. */
849 type = packet_read(&plen);
850 packet_integrity_check(plen, 0, type);
851 if (type != SSH_SMSG_SUCCESS)
852 log("Warning: Remote host denied authentication agent forwarding.");
853 }
854
855 /* Initiate port forwardings. */
856 ssh_init_forwarding();
857
858 /* If requested, let ssh continue in the background. */
859 if (fork_after_authentication_flag)
860 if (daemon(1, 1) < 0) {
861 fprintf(stderr, "daemon() failed: %.200s", strerror(errno));
862 exit(errno);
863 }
864
865 /*
866 * If a command was specified on the command line, execute the
867 * command now. Otherwise request the server to start a shell.
868 */
869 if (buffer_len(&command) > 0) {
870 int len = buffer_len(&command);
871 if (len > 900)
872 len = 900;
873 debug("Sending command: %.*s", len, buffer_ptr(&command));
874 packet_start(SSH_CMSG_EXEC_CMD);
875 packet_put_string(buffer_ptr(&command), buffer_len(&command));
876 packet_send();
877 packet_write_wait();
878 } else {
879 debug("Requesting shell.");
880 packet_start(SSH_CMSG_EXEC_SHELL);
881 packet_send();
882 packet_write_wait();
883 }
884
885 /* Enter the interactive session. */
886 return client_loop(have_tty, -1, 0);
887}
888
889void
890client_subsystem_reply(int type, int plen, void *ctxt)
891{
892 int id, len;
893
894 id = packet_get_int();
895 len = buffer_len(&command);
896 if (len > 900)
897 len = 900;
898 packet_done();
899 if (type == SSH2_MSG_CHANNEL_FAILURE) {
900 fprintf(stderr, "Request for subsystem '%.*s' failed on channel %d",
901 len, buffer_ptr(&command), id);
902 exit(1);
903 }
904}
905
906void
907ssh_session2_callback(int id, void *arg)
908{
909 int len;
910 int interactive = 0;
911 struct termios tio;
912
913 debug("client_init id %d arg %ld", id, (long)arg);
914
915 if (tty_flag) {
916 struct winsize ws;
917 char *cp;
918 cp = getenv("TERM");
919 if (!cp)
920 cp = "";
921 /* Store window size in the packet. */
922 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
923 memset(&ws, 0, sizeof(ws));
924
925 channel_request_start(id, "pty-req", 0);
926 packet_put_cstring(cp);
927 packet_put_int(ws.ws_col);
928 packet_put_int(ws.ws_row);
929 packet_put_int(ws.ws_xpixel);
930 packet_put_int(ws.ws_ypixel);
931 tio = get_saved_tio();
932 tty_make_modes(/*ignored*/ 0, &tio);
933 packet_send();
934 interactive = 1;
935 /* XXX wait for reply */
936 }
937 if (options.forward_x11 &&
938 getenv("DISPLAY") != NULL) {
939 char proto[512], data[512];
940 /* Get reasonable local authentication information. */
941 x11_get_proto(proto, sizeof proto, data, sizeof data);
942 /* Request forwarding with authentication spoofing. */
943 debug("Requesting X11 forwarding with authentication spoofing.");
944 x11_request_forwarding_with_spoofing(id, proto, data);
945 interactive = 1;
946 /* XXX wait for reply */
947 }
948
949 check_agent_present();
950 if (options.forward_agent) {
951 debug("Requesting authentication agent forwarding.");
952 channel_request_start(id, "auth-agent-req@openssh.com", 0);
953 packet_send();
954 }
955
956 len = buffer_len(&command);
957 if (len > 0) {
958 if (len > 900)
959 len = 900;
960 if (subsystem_flag) {
961 debug("Sending subsystem: %.*s", len, buffer_ptr(&command));
962 channel_request_start(id, "subsystem", /*want reply*/ 1);
963 /* register callback for reply */
964 /* XXX we asume that client_loop has already been called */
965 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &client_subsystem_reply);
966 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &client_subsystem_reply);
967 } else {
968 debug("Sending command: %.*s", len, buffer_ptr(&command));
969 channel_request_start(id, "exec", 0);
970 }
971 packet_put_string(buffer_ptr(&command), buffer_len(&command));
972 packet_send();
973 } else {
974 channel_request(id, "shell", 0);
975 }
976 /* channel_callback(id, SSH2_MSG_OPEN_CONFIGMATION, client_init, 0); */
977
978 /* register different callback, etc. XXX */
979 packet_set_interactive(interactive);
980}
981
982int
983ssh_session2_command(void)
984{
985 int id, window, packetmax;
986 int in, out, err;
987
988 if (stdin_null_flag) {
989 in = open(_PATH_DEVNULL, O_RDONLY);
990 } else {
991 in = dup(STDIN_FILENO);
992 }
993 out = dup(STDOUT_FILENO);
994 err = dup(STDERR_FILENO);
995
996 if (in < 0 || out < 0 || err < 0) {
997 perror("dup() in/out/err failed");
998 exit(errno);
999 }
1000
1001 /* enable nonblocking unless tty */
1002 if (!isatty(in))
1003 set_nonblock(in);
1004 if (!isatty(out))
1005 set_nonblock(out);
1006 if (!isatty(err))
1007 set_nonblock(err);
1008
1009 window = CHAN_SES_WINDOW_DEFAULT;
1010 packetmax = CHAN_SES_PACKET_DEFAULT;
1011 if (!tty_flag) {
1012 window *= 2;
1013 packetmax *=2;
1014 }
1015 id = channel_new(
1016 "session", SSH_CHANNEL_OPENING, in, out, err,
1017 window, packetmax, CHAN_EXTENDED_WRITE,
1018 xstrdup("client-session"), /*nonblock*/0);
1019
1020debug("channel_new: %d", id);
1021
1022 channel_open(id);
1023 channel_register_callback(id, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION,
1024 ssh_session2_callback, (void *)0);
1025
1026 return id;
1027}
1028
1029int
1030ssh_session2(void)
1031{
1032 int id;
1033
1034 /* XXX should be pre-session */
1035 ssh_init_forwarding();
1036
1037 id = no_shell_flag ? -1 : ssh_session2_command();
1038
1039 /* If requested, let ssh continue in the background. */
1040 if (fork_after_authentication_flag)
1041 if (daemon(1, 1) < 0)
1042 fatal("daemon() failed: %.200s", strerror(errno));
1043
1044 return client_loop(tty_flag, tty_flag ? options.escape_char : -1, id);
1045}
1046
1047void
1048load_public_identity_files(void)
1049{
1050 char *filename;
1051 Key *public;
1052 int i;
1053
1054 for (i = 0; i < options.num_identity_files; i++) {
1055 filename = tilde_expand_filename(options.identity_files[i],
1056 getuid());
1057 public = key_load_public(filename, NULL);
1058 debug("identity file %s type %d", filename,
1059 public ? public->type : -1);
1060 xfree(options.identity_files[i]);
1061 options.identity_files[i] = filename;
1062 options.identity_keys[i] = public;
1063 }
1064}