]> andersk Git - openssh.git/blame_incremental - ssh.c
- itojun@cvs.openbsd.org 2002/09/17 07:47:02
[openssh.git] / ssh.c
... / ...
CommitLineData
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 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
17 *
18 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
19 * in Canada (German citizen).
20 *
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
23 * are met:
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 */
41
42#include "includes.h"
43RCSID("$OpenBSD: ssh.c,v 1.185 2002/09/11 18:27:26 stevesk Exp $");
44
45#include <openssl/evp.h>
46#include <openssl/err.h>
47
48#include "ssh.h"
49#include "ssh1.h"
50#include "ssh2.h"
51#include "compat.h"
52#include "cipher.h"
53#include "xmalloc.h"
54#include "packet.h"
55#include "buffer.h"
56#include "channels.h"
57#include "key.h"
58#include "authfd.h"
59#include "authfile.h"
60#include "pathnames.h"
61#include "clientloop.h"
62#include "log.h"
63#include "readconf.h"
64#include "sshconnect.h"
65#include "tildexpand.h"
66#include "dispatch.h"
67#include "misc.h"
68#include "kex.h"
69#include "mac.h"
70#include "sshtty.h"
71
72#ifdef SMARTCARD
73#include "scard.h"
74#endif
75
76#ifdef HAVE___PROGNAME
77extern char *__progname;
78#else
79char *__progname;
80#endif
81
82/* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
83 Default value is AF_UNSPEC means both IPv4 and IPv6. */
84#ifdef IPV4_DEFAULT
85int IPv4or6 = AF_INET;
86#else
87int IPv4or6 = AF_UNSPEC;
88#endif
89
90/* Flag indicating whether debug mode is on. This can be set on the command line. */
91int debug_flag = 0;
92
93/* Flag indicating whether a tty should be allocated */
94int tty_flag = 0;
95int no_tty_flag = 0;
96int force_tty_flag = 0;
97
98/* don't exec a shell */
99int no_shell_flag = 0;
100
101/*
102 * Flag indicating that nothing should be read from stdin. This can be set
103 * on the command line.
104 */
105int stdin_null_flag = 0;
106
107/*
108 * Flag indicating that ssh should fork after authentication. This is useful
109 * so that the passphrase can be entered manually, and then ssh goes to the
110 * background.
111 */
112int fork_after_authentication_flag = 0;
113
114/*
115 * General data structure for command line options and options configurable
116 * in configuration files. See readconf.h.
117 */
118Options options;
119
120/* optional user configfile */
121char *config = NULL;
122
123/*
124 * Name of the host we are connecting to. This is the name given on the
125 * command line, or the HostName specified for the user-supplied name in a
126 * configuration file.
127 */
128char *host;
129
130/* socket address the host resolves to */
131struct sockaddr_storage hostaddr;
132
133/* Private host keys. */
134Sensitive sensitive_data;
135
136/* Original real UID. */
137uid_t original_real_uid;
138uid_t original_effective_uid;
139
140/* command to be executed */
141Buffer command;
142
143/* Should we execute a command or invoke a subsystem? */
144int subsystem_flag = 0;
145
146/* # of replies received for global requests */
147static int client_global_request_id = 0;
148
149/* Prints a help message to the user. This function never returns. */
150
151static void
152usage(void)
153{
154 fprintf(stderr, "Usage: %s [options] host [command]\n", __progname);
155 fprintf(stderr, "Options:\n");
156 fprintf(stderr, " -l user Log in using this user name.\n");
157 fprintf(stderr, " -n Redirect input from " _PATH_DEVNULL ".\n");
158 fprintf(stderr, " -F config Config file (default: ~/%s).\n",
159 _PATH_SSH_USER_CONFFILE);
160 fprintf(stderr, " -A Enable authentication agent forwarding.\n");
161 fprintf(stderr, " -a Disable authentication agent forwarding (default).\n");
162#ifdef AFS
163 fprintf(stderr, " -k Disable Kerberos ticket and AFS token forwarding.\n");
164#endif /* AFS */
165 fprintf(stderr, " -X Enable X11 connection forwarding.\n");
166 fprintf(stderr, " -x Disable X11 connection forwarding (default).\n");
167 fprintf(stderr, " -i file Identity for public key authentication "
168 "(default: ~/.ssh/identity)\n");
169#ifdef SMARTCARD
170 fprintf(stderr, " -I reader Set smartcard reader.\n");
171#endif
172 fprintf(stderr, " -t Tty; allocate a tty even if command is given.\n");
173 fprintf(stderr, " -T Do not allocate a tty.\n");
174 fprintf(stderr, " -v Verbose; display verbose debugging messages.\n");
175 fprintf(stderr, " Multiple -v increases verbosity.\n");
176 fprintf(stderr, " -V Display version number only.\n");
177 fprintf(stderr, " -q Quiet; don't display any warning messages.\n");
178 fprintf(stderr, " -f Fork into background after authentication.\n");
179 fprintf(stderr, " -e char Set escape character; ``none'' = disable (default: ~).\n");
180
181 fprintf(stderr, " -c cipher Select encryption algorithm\n");
182 fprintf(stderr, " -m macs Specify MAC algorithms for protocol version 2.\n");
183 fprintf(stderr, " -p port Connect to this port. Server must be on the same port.\n");
184 fprintf(stderr, " -L listen-port:host:port Forward local port to remote address\n");
185 fprintf(stderr, " -R listen-port:host:port Forward remote port to local address\n");
186 fprintf(stderr, " These cause %s to listen for connections on a port, and\n", __progname);
187 fprintf(stderr, " forward them to the other side by connecting to host:port.\n");
188 fprintf(stderr, " -D port Enable dynamic application-level port forwarding.\n");
189 fprintf(stderr, " -C Enable compression.\n");
190 fprintf(stderr, " -N Do not execute a shell or command.\n");
191 fprintf(stderr, " -g Allow remote hosts to connect to forwarded ports.\n");
192 fprintf(stderr, " -1 Force protocol version 1.\n");
193 fprintf(stderr, " -2 Force protocol version 2.\n");
194 fprintf(stderr, " -4 Use IPv4 only.\n");
195 fprintf(stderr, " -6 Use IPv6 only.\n");
196 fprintf(stderr, " -o 'option' Process the option as if it was read from a configuration file.\n");
197 fprintf(stderr, " -s Invoke command (mandatory) as SSH2 subsystem.\n");
198 fprintf(stderr, " -b addr Local IP address.\n");
199 exit(1);
200}
201
202static int ssh_session(void);
203static int ssh_session2(void);
204static void load_public_identity_files(void);
205
206/*
207 * Main program for the ssh client.
208 */
209int
210main(int ac, char **av)
211{
212 int i, opt, exit_status;
213 u_short fwd_port, fwd_host_port;
214 char sfwd_port[6], sfwd_host_port[6];
215 char *p, *cp, buf[256];
216 struct stat st;
217 struct passwd *pw;
218 int dummy;
219 extern int optind, optreset;
220 extern char *optarg;
221
222 __progname = get_progname(av[0]);
223 init_rng();
224
225 /*
226 * Save the original real uid. It will be needed later (uid-swapping
227 * may clobber the real uid).
228 */
229 original_real_uid = getuid();
230 original_effective_uid = geteuid();
231
232 /*
233 * Use uid-swapping to give up root privileges for the duration of
234 * option processing. We will re-instantiate the rights when we are
235 * ready to create the privileged port, and will permanently drop
236 * them when the port has been created (actually, when the connection
237 * has been made, as we may need to create the port several times).
238 */
239 PRIV_END;
240
241#ifdef HAVE_SETRLIMIT
242 /* If we are installed setuid root be careful to not drop core. */
243 if (original_real_uid != original_effective_uid) {
244 struct rlimit rlim;
245 rlim.rlim_cur = rlim.rlim_max = 0;
246 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
247 fatal("setrlimit failed: %.100s", strerror(errno));
248 }
249#endif
250 /* Get user data. */
251 pw = getpwuid(original_real_uid);
252 if (!pw) {
253 log("You don't exist, go away!");
254 exit(1);
255 }
256 /* Take a copy of the returned structure. */
257 pw = pwcopy(pw);
258
259 /*
260 * Set our umask to something reasonable, as some files are created
261 * with the default umask. This will make them world-readable but
262 * writable only by the owner, which is ok for all files for which we
263 * don't set the modes explicitly.
264 */
265 umask(022);
266
267 /* Initialize option structure to indicate that no values have been set. */
268 initialize_options(&options);
269
270 /* Parse command-line arguments. */
271 host = NULL;
272
273again:
274 while ((opt = getopt(ac, av,
275 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:NPR:TVX")) != -1) {
276 switch (opt) {
277 case '1':
278 options.protocol = SSH_PROTO_1;
279 break;
280 case '2':
281 options.protocol = SSH_PROTO_2;
282 break;
283 case '4':
284 IPv4or6 = AF_INET;
285 break;
286 case '6':
287 IPv4or6 = AF_INET6;
288 break;
289 case 'n':
290 stdin_null_flag = 1;
291 break;
292 case 'f':
293 fork_after_authentication_flag = 1;
294 stdin_null_flag = 1;
295 break;
296 case 'x':
297 options.forward_x11 = 0;
298 break;
299 case 'X':
300 options.forward_x11 = 1;
301 break;
302 case 'g':
303 options.gateway_ports = 1;
304 break;
305 case 'P': /* deprecated */
306 options.use_privileged_port = 0;
307 break;
308 case 'a':
309 options.forward_agent = 0;
310 break;
311 case 'A':
312 options.forward_agent = 1;
313 break;
314#ifdef AFS
315 case 'k':
316 options.kerberos_tgt_passing = 0;
317 options.afs_token_passing = 0;
318 break;
319#endif
320 case 'i':
321 if (stat(optarg, &st) < 0) {
322 fprintf(stderr, "Warning: Identity file %s "
323 "does not exist.\n", optarg);
324 break;
325 }
326 if (options.num_identity_files >=
327 SSH_MAX_IDENTITY_FILES)
328 fatal("Too many identity files specified "
329 "(max %d)", SSH_MAX_IDENTITY_FILES);
330 options.identity_files[options.num_identity_files++] =
331 xstrdup(optarg);
332 break;
333 case 'I':
334#ifdef SMARTCARD
335 options.smartcard_device = xstrdup(optarg);
336#else
337 fprintf(stderr, "no support for smartcards.\n");
338#endif
339 break;
340 case 't':
341 if (tty_flag)
342 force_tty_flag = 1;
343 tty_flag = 1;
344 break;
345 case 'v':
346 if (0 == debug_flag) {
347 debug_flag = 1;
348 options.log_level = SYSLOG_LEVEL_DEBUG1;
349 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
350 options.log_level++;
351 break;
352 } else
353 fatal("Too high debugging level.");
354 /* fallthrough */
355 case 'V':
356 fprintf(stderr,
357 "%s, SSH protocols %d.%d/%d.%d, OpenSSL 0x%8.8lx\n",
358 SSH_VERSION,
359 PROTOCOL_MAJOR_1, PROTOCOL_MINOR_1,
360 PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2,
361 SSLeay());
362 if (opt == 'V')
363 exit(0);
364 break;
365 case 'q':
366 options.log_level = SYSLOG_LEVEL_QUIET;
367 break;
368 case 'e':
369 if (optarg[0] == '^' && optarg[2] == 0 &&
370 (u_char) optarg[1] >= 64 &&
371 (u_char) optarg[1] < 128)
372 options.escape_char = (u_char) optarg[1] & 31;
373 else if (strlen(optarg) == 1)
374 options.escape_char = (u_char) optarg[0];
375 else if (strcmp(optarg, "none") == 0)
376 options.escape_char = SSH_ESCAPECHAR_NONE;
377 else {
378 fprintf(stderr, "Bad escape character '%s'.\n",
379 optarg);
380 exit(1);
381 }
382 break;
383 case 'c':
384 if (ciphers_valid(optarg)) {
385 /* SSH2 only */
386 options.ciphers = xstrdup(optarg);
387 options.cipher = SSH_CIPHER_ILLEGAL;
388 } else {
389 /* SSH1 only */
390 options.cipher = cipher_number(optarg);
391 if (options.cipher == -1) {
392 fprintf(stderr,
393 "Unknown cipher type '%s'\n",
394 optarg);
395 exit(1);
396 }
397 if (options.cipher == SSH_CIPHER_3DES)
398 options.ciphers = "3des-cbc";
399 else if (options.cipher == SSH_CIPHER_BLOWFISH)
400 options.ciphers = "blowfish-cbc";
401 else
402 options.ciphers = (char *)-1;
403 }
404 break;
405 case 'm':
406 if (mac_valid(optarg))
407 options.macs = xstrdup(optarg);
408 else {
409 fprintf(stderr, "Unknown mac type '%s'\n",
410 optarg);
411 exit(1);
412 }
413 break;
414 case 'p':
415 options.port = a2port(optarg);
416 if (options.port == 0) {
417 fprintf(stderr, "Bad port '%s'\n", optarg);
418 exit(1);
419 }
420 break;
421 case 'l':
422 options.user = optarg;
423 break;
424
425 case 'L':
426 case 'R':
427 if (sscanf(optarg, "%5[0-9]:%255[^:]:%5[0-9]",
428 sfwd_port, buf, sfwd_host_port) != 3 &&
429 sscanf(optarg, "%5[0-9]/%255[^/]/%5[0-9]",
430 sfwd_port, buf, sfwd_host_port) != 3) {
431 fprintf(stderr,
432 "Bad forwarding specification '%s'\n",
433 optarg);
434 usage();
435 /* NOTREACHED */
436 }
437 if ((fwd_port = a2port(sfwd_port)) == 0 ||
438 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
439 fprintf(stderr,
440 "Bad forwarding port(s) '%s'\n", optarg);
441 exit(1);
442 }
443 if (opt == 'L')
444 add_local_forward(&options, fwd_port, buf,
445 fwd_host_port);
446 else if (opt == 'R')
447 add_remote_forward(&options, fwd_port, buf,
448 fwd_host_port);
449 break;
450
451 case 'D':
452 fwd_port = a2port(optarg);
453 if (fwd_port == 0) {
454 fprintf(stderr, "Bad dynamic port '%s'\n",
455 optarg);
456 exit(1);
457 }
458 add_local_forward(&options, fwd_port, "socks4", 0);
459 break;
460
461 case 'C':
462 options.compression = 1;
463 break;
464 case 'N':
465 no_shell_flag = 1;
466 no_tty_flag = 1;
467 break;
468 case 'T':
469 no_tty_flag = 1;
470 break;
471 case 'o':
472 dummy = 1;
473 if (process_config_line(&options, host ? host : "",
474 optarg, "command-line", 0, &dummy) != 0)
475 exit(1);
476 break;
477 case 's':
478 subsystem_flag = 1;
479 break;
480 case 'b':
481 options.bind_address = optarg;
482 break;
483 case 'F':
484 config = optarg;
485 break;
486 default:
487 usage();
488 }
489 }
490
491 ac -= optind;
492 av += optind;
493
494 if (ac > 0 && !host && **av != '-') {
495 if (strchr(*av, '@')) {
496 p = xstrdup(*av);
497 cp = strchr(p, '@');
498 if (cp == NULL || cp == p)
499 usage();
500 options.user = p;
501 *cp = '\0';
502 host = ++cp;
503 } else
504 host = *av;
505 ac--, av++;
506 if (ac > 0) {
507 optind = 0;
508 optreset = 1;
509 goto again;
510 }
511 }
512
513 /* Check that we got a host name. */
514 if (!host)
515 usage();
516
517 SSLeay_add_all_algorithms();
518 ERR_load_crypto_strings();
519 channel_set_af(IPv4or6);
520
521 /* Initialize the command to execute on remote host. */
522 buffer_init(&command);
523
524 /*
525 * Save the command to execute on the remote host in a buffer. There
526 * is no limit on the length of the command, except by the maximum
527 * packet size. Also sets the tty flag if there is no command.
528 */
529 if (!ac) {
530 /* No command specified - execute shell on a tty. */
531 tty_flag = 1;
532 if (subsystem_flag) {
533 fprintf(stderr,
534 "You must specify a subsystem to invoke.\n");
535 usage();
536 }
537 } else {
538 /* A command has been specified. Store it into the buffer. */
539 for (i = 0; i < ac; i++) {
540 if (i)
541 buffer_append(&command, " ", 1);
542 buffer_append(&command, av[i], strlen(av[i]));
543 }
544 }
545
546 /* Cannot fork to background if no command. */
547 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
548 fatal("Cannot fork into background without a command to execute.");
549
550 /* Allocate a tty by default if no command specified. */
551 if (buffer_len(&command) == 0)
552 tty_flag = 1;
553
554 /* Force no tty */
555 if (no_tty_flag)
556 tty_flag = 0;
557 /* Do not allocate a tty if stdin is not a tty. */
558 if (!isatty(fileno(stdin)) && !force_tty_flag) {
559 if (tty_flag)
560 log("Pseudo-terminal will not be allocated because stdin is not a terminal.");
561 tty_flag = 0;
562 }
563
564 /*
565 * Initialize "log" output. Since we are the client all output
566 * actually goes to stderr.
567 */
568 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
569 SYSLOG_FACILITY_USER, 1);
570
571 /*
572 * Read per-user configuration file. Ignore the system wide config
573 * file if the user specifies a config file on the command line.
574 */
575 if (config != NULL) {
576 if (!read_config_file(config, host, &options))
577 fatal("Can't open user config file %.100s: "
578 "%.100s", config, strerror(errno));
579 } else {
580 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
581 _PATH_SSH_USER_CONFFILE);
582 (void)read_config_file(buf, host, &options);
583
584 /* Read systemwide configuration file after use config. */
585 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host, &options);
586 }
587
588 /* Fill configuration defaults. */
589 fill_default_options(&options);
590
591 /* reinit */
592 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
593
594 seed_rng();
595
596 if (options.user == NULL)
597 options.user = xstrdup(pw->pw_name);
598
599 if (options.hostname != NULL)
600 host = options.hostname;
601
602 /* Disable rhosts authentication if not running as root. */
603#ifdef HAVE_CYGWIN
604 /* Ignore uid if running under Windows */
605 if (!options.use_privileged_port) {
606#else
607 if (original_effective_uid != 0 || !options.use_privileged_port) {
608#endif
609 debug("Rhosts Authentication disabled, "
610 "originating port will not be trusted.");
611 options.rhosts_authentication = 0;
612 }
613 /* Open a connection to the remote host. */
614
615 if (ssh_connect(host, &hostaddr, options.port, IPv4or6,
616 options.connection_attempts,
617#ifdef HAVE_CYGWIN
618 options.use_privileged_port,
619#else
620 original_effective_uid == 0 && options.use_privileged_port,
621#endif
622 options.proxy_command) != 0)
623 exit(1);
624
625 /*
626 * If we successfully made the connection, load the host private key
627 * in case we will need it later for combined rsa-rhosts
628 * authentication. This must be done before releasing extra
629 * privileges, because the file is only readable by root.
630 * If we cannot access the private keys, load the public keys
631 * instead and try to execute the ssh-keysign helper instead.
632 */
633 sensitive_data.nkeys = 0;
634 sensitive_data.keys = NULL;
635 sensitive_data.external_keysign = 0;
636 if (options.rhosts_rsa_authentication ||
637 options.hostbased_authentication) {
638 sensitive_data.nkeys = 3;
639 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
640 sizeof(Key));
641
642 PRIV_START;
643 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
644 _PATH_HOST_KEY_FILE, "", NULL);
645 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
646 _PATH_HOST_DSA_KEY_FILE, "", NULL);
647 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
648 _PATH_HOST_RSA_KEY_FILE, "", NULL);
649 PRIV_END;
650
651 if (options.hostbased_authentication == 1 &&
652 sensitive_data.keys[0] == NULL &&
653 sensitive_data.keys[1] == NULL &&
654 sensitive_data.keys[2] == NULL) {
655 sensitive_data.keys[1] = key_load_public(
656 _PATH_HOST_DSA_KEY_FILE, NULL);
657 sensitive_data.keys[2] = key_load_public(
658 _PATH_HOST_RSA_KEY_FILE, NULL);
659 sensitive_data.external_keysign = 1;
660 }
661 }
662 /*
663 * Get rid of any extra privileges that we may have. We will no
664 * longer need them. Also, extra privileges could make it very hard
665 * to read identity files and other non-world-readable files from the
666 * user's home directory if it happens to be on a NFS volume where
667 * root is mapped to nobody.
668 */
669 seteuid(original_real_uid);
670 setuid(original_real_uid);
671
672 /*
673 * Now that we are back to our own permissions, create ~/.ssh
674 * directory if it doesn\'t already exist.
675 */
676 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
677 if (stat(buf, &st) < 0)
678 if (mkdir(buf, 0700) < 0)
679 error("Could not create directory '%.200s'.", buf);
680
681 /* load options.identity_files */
682 load_public_identity_files();
683
684 /* Expand ~ in known host file names. */
685 /* XXX mem-leaks: */
686 options.system_hostfile =
687 tilde_expand_filename(options.system_hostfile, original_real_uid);
688 options.user_hostfile =
689 tilde_expand_filename(options.user_hostfile, original_real_uid);
690 options.system_hostfile2 =
691 tilde_expand_filename(options.system_hostfile2, original_real_uid);
692 options.user_hostfile2 =
693 tilde_expand_filename(options.user_hostfile2, original_real_uid);
694
695 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
696
697 /* Log into the remote system. This never returns if the login fails. */
698 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
699
700 /* We no longer need the private host keys. Clear them now. */
701 if (sensitive_data.nkeys != 0) {
702 for (i = 0; i < sensitive_data.nkeys; i++) {
703 if (sensitive_data.keys[i] != NULL) {
704 /* Destroys contents safely */
705 debug3("clear hostkey %d", i);
706 key_free(sensitive_data.keys[i]);
707 sensitive_data.keys[i] = NULL;
708 }
709 }
710 xfree(sensitive_data.keys);
711 }
712 for (i = 0; i < options.num_identity_files; i++) {
713 if (options.identity_files[i]) {
714 xfree(options.identity_files[i]);
715 options.identity_files[i] = NULL;
716 }
717 if (options.identity_keys[i]) {
718 key_free(options.identity_keys[i]);
719 options.identity_keys[i] = NULL;
720 }
721 }
722
723 exit_status = compat20 ? ssh_session2() : ssh_session();
724 packet_close();
725 return exit_status;
726}
727
728static void
729x11_get_proto(char **_proto, char **_data)
730{
731 char line[512];
732 static char proto[512], data[512];
733 FILE *f;
734 int got_data = 0, i;
735 char *display;
736 struct stat st;
737
738 *_proto = proto;
739 *_data = data;
740 proto[0] = data[0] = '\0';
741 if (!options.xauth_location ||
742 (stat(options.xauth_location, &st) == -1)) {
743 debug("No xauth program.");
744 } else {
745 if ((display = getenv("DISPLAY")) == NULL) {
746 debug("x11_get_proto: DISPLAY not set");
747 return;
748 }
749 /* Try to get Xauthority information for the display. */
750 if (strncmp(display, "localhost:", 10) == 0)
751 /*
752 * Handle FamilyLocal case where $DISPLAY does
753 * not match an authorization entry. For this we
754 * just try "xauth list unix:displaynum.screennum".
755 * XXX: "localhost" match to determine FamilyLocal
756 * is not perfect.
757 */
758 snprintf(line, sizeof line, "%s list unix:%s 2>"
759 _PATH_DEVNULL, options.xauth_location, display+10);
760 else
761 snprintf(line, sizeof line, "%s list %.200s 2>"
762 _PATH_DEVNULL, options.xauth_location, display);
763 debug2("x11_get_proto: %s", line);
764 f = popen(line, "r");
765 if (f && fgets(line, sizeof(line), f) &&
766 sscanf(line, "%*s %511s %511s", proto, data) == 2)
767 got_data = 1;
768 if (f)
769 pclose(f);
770 }
771 /*
772 * If we didn't get authentication data, just make up some
773 * data. The forwarding code will check the validity of the
774 * response anyway, and substitute this data. The X11
775 * server, however, will ignore this fake data and use
776 * whatever authentication mechanisms it was using otherwise
777 * for the local connection.
778 */
779 if (!got_data) {
780 u_int32_t rand = 0;
781
782 log("Warning: No xauth data; using fake authentication data for X11 forwarding.");
783 strlcpy(proto, "MIT-MAGIC-COOKIE-1", sizeof proto);
784 for (i = 0; i < 16; i++) {
785 if (i % 4 == 0)
786 rand = arc4random();
787 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x", rand & 0xff);
788 rand >>= 8;
789 }
790 }
791}
792
793static void
794ssh_init_forwarding(void)
795{
796 int success = 0;
797 int i;
798
799 /* Initiate local TCP/IP port forwardings. */
800 for (i = 0; i < options.num_local_forwards; i++) {
801 debug("Connections to local port %d forwarded to remote address %.200s:%d",
802 options.local_forwards[i].port,
803 options.local_forwards[i].host,
804 options.local_forwards[i].host_port);
805 success += channel_setup_local_fwd_listener(
806 options.local_forwards[i].port,
807 options.local_forwards[i].host,
808 options.local_forwards[i].host_port,
809 options.gateway_ports);
810 }
811 if (i > 0 && success == 0)
812 error("Could not request local forwarding.");
813
814 /* Initiate remote TCP/IP port forwardings. */
815 for (i = 0; i < options.num_remote_forwards; i++) {
816 debug("Connections to remote port %d forwarded to local address %.200s:%d",
817 options.remote_forwards[i].port,
818 options.remote_forwards[i].host,
819 options.remote_forwards[i].host_port);
820 channel_request_remote_forwarding(
821 options.remote_forwards[i].port,
822 options.remote_forwards[i].host,
823 options.remote_forwards[i].host_port);
824 }
825}
826
827static void
828check_agent_present(void)
829{
830 if (options.forward_agent) {
831 /* Clear agent forwarding if we don\'t have an agent. */
832 if (!ssh_agent_present())
833 options.forward_agent = 0;
834 }
835}
836
837static int
838ssh_session(void)
839{
840 int type;
841 int interactive = 0;
842 int have_tty = 0;
843 struct winsize ws;
844 char *cp;
845
846 /* Enable compression if requested. */
847 if (options.compression) {
848 debug("Requesting compression at level %d.", options.compression_level);
849
850 if (options.compression_level < 1 || options.compression_level > 9)
851 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
852
853 /* Send the request. */
854 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
855 packet_put_int(options.compression_level);
856 packet_send();
857 packet_write_wait();
858 type = packet_read();
859 if (type == SSH_SMSG_SUCCESS)
860 packet_start_compression(options.compression_level);
861 else if (type == SSH_SMSG_FAILURE)
862 log("Warning: Remote host refused compression.");
863 else
864 packet_disconnect("Protocol error waiting for compression response.");
865 }
866 /* Allocate a pseudo tty if appropriate. */
867 if (tty_flag) {
868 debug("Requesting pty.");
869
870 /* Start the packet. */
871 packet_start(SSH_CMSG_REQUEST_PTY);
872
873 /* Store TERM in the packet. There is no limit on the
874 length of the string. */
875 cp = getenv("TERM");
876 if (!cp)
877 cp = "";
878 packet_put_cstring(cp);
879
880 /* Store window size in the packet. */
881 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
882 memset(&ws, 0, sizeof(ws));
883 packet_put_int(ws.ws_row);
884 packet_put_int(ws.ws_col);
885 packet_put_int(ws.ws_xpixel);
886 packet_put_int(ws.ws_ypixel);
887
888 /* Store tty modes in the packet. */
889 tty_make_modes(fileno(stdin), NULL);
890
891 /* Send the packet, and wait for it to leave. */
892 packet_send();
893 packet_write_wait();
894
895 /* Read response from the server. */
896 type = packet_read();
897 if (type == SSH_SMSG_SUCCESS) {
898 interactive = 1;
899 have_tty = 1;
900 } else if (type == SSH_SMSG_FAILURE)
901 log("Warning: Remote host failed or refused to allocate a pseudo tty.");
902 else
903 packet_disconnect("Protocol error waiting for pty request response.");
904 }
905 /* Request X11 forwarding if enabled and DISPLAY is set. */
906 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
907 char *proto, *data;
908 /* Get reasonable local authentication information. */
909 x11_get_proto(&proto, &data);
910 /* Request forwarding with authentication spoofing. */
911 debug("Requesting X11 forwarding with authentication spoofing.");
912 x11_request_forwarding_with_spoofing(0, proto, data);
913
914 /* Read response from the server. */
915 type = packet_read();
916 if (type == SSH_SMSG_SUCCESS) {
917 interactive = 1;
918 } else if (type == SSH_SMSG_FAILURE) {
919 log("Warning: Remote host denied X11 forwarding.");
920 } else {
921 packet_disconnect("Protocol error waiting for X11 forwarding");
922 }
923 }
924 /* Tell the packet module whether this is an interactive session. */
925 packet_set_interactive(interactive);
926
927 /* Request authentication agent forwarding if appropriate. */
928 check_agent_present();
929
930 if (options.forward_agent) {
931 debug("Requesting authentication agent forwarding.");
932 auth_request_forwarding();
933
934 /* Read response from the server. */
935 type = packet_read();
936 packet_check_eom();
937 if (type != SSH_SMSG_SUCCESS)
938 log("Warning: Remote host denied authentication agent forwarding.");
939 }
940
941 /* Initiate port forwardings. */
942 ssh_init_forwarding();
943
944 /* If requested, let ssh continue in the background. */
945 if (fork_after_authentication_flag)
946 if (daemon(1, 1) < 0)
947 fatal("daemon() failed: %.200s", strerror(errno));
948
949 /*
950 * If a command was specified on the command line, execute the
951 * command now. Otherwise request the server to start a shell.
952 */
953 if (buffer_len(&command) > 0) {
954 int len = buffer_len(&command);
955 if (len > 900)
956 len = 900;
957 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
958 packet_start(SSH_CMSG_EXEC_CMD);
959 packet_put_string(buffer_ptr(&command), buffer_len(&command));
960 packet_send();
961 packet_write_wait();
962 } else {
963 debug("Requesting shell.");
964 packet_start(SSH_CMSG_EXEC_SHELL);
965 packet_send();
966 packet_write_wait();
967 }
968
969 /* Enter the interactive session. */
970 return client_loop(have_tty, tty_flag ?
971 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
972}
973
974static void
975client_subsystem_reply(int type, u_int32_t seq, void *ctxt)
976{
977 int id, len;
978
979 id = packet_get_int();
980 len = buffer_len(&command);
981 if (len > 900)
982 len = 900;
983 packet_check_eom();
984 if (type == SSH2_MSG_CHANNEL_FAILURE)
985 fatal("Request for subsystem '%.*s' failed on channel %d",
986 len, (u_char *)buffer_ptr(&command), id);
987}
988
989void
990client_global_request_reply(int type, u_int32_t seq, void *ctxt)
991{
992 int i;
993
994 i = client_global_request_id++;
995 if (i >= options.num_remote_forwards) {
996 debug("client_global_request_reply: too many replies %d > %d",
997 i, options.num_remote_forwards);
998 return;
999 }
1000 debug("remote forward %s for: listen %d, connect %s:%d",
1001 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1002 options.remote_forwards[i].port,
1003 options.remote_forwards[i].host,
1004 options.remote_forwards[i].host_port);
1005 if (type == SSH2_MSG_REQUEST_FAILURE)
1006 log("Warning: remote port forwarding failed for listen port %d",
1007 options.remote_forwards[i].port);
1008}
1009
1010/* request pty/x11/agent/tcpfwd/shell for channel */
1011static void
1012ssh_session2_setup(int id, void *arg)
1013{
1014 int len;
1015 int interactive = 0;
1016 struct termios tio;
1017
1018 debug("ssh_session2_setup: id %d", id);
1019
1020 if (tty_flag) {
1021 struct winsize ws;
1022 char *cp;
1023 cp = getenv("TERM");
1024 if (!cp)
1025 cp = "";
1026 /* Store window size in the packet. */
1027 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1028 memset(&ws, 0, sizeof(ws));
1029
1030 channel_request_start(id, "pty-req", 0);
1031 packet_put_cstring(cp);
1032 packet_put_int(ws.ws_col);
1033 packet_put_int(ws.ws_row);
1034 packet_put_int(ws.ws_xpixel);
1035 packet_put_int(ws.ws_ypixel);
1036 tio = get_saved_tio();
1037 tty_make_modes(/*ignored*/ 0, &tio);
1038 packet_send();
1039 interactive = 1;
1040 /* XXX wait for reply */
1041 }
1042 if (options.forward_x11 &&
1043 getenv("DISPLAY") != NULL) {
1044 char *proto, *data;
1045 /* Get reasonable local authentication information. */
1046 x11_get_proto(&proto, &data);
1047 /* Request forwarding with authentication spoofing. */
1048 debug("Requesting X11 forwarding with authentication spoofing.");
1049 x11_request_forwarding_with_spoofing(id, proto, data);
1050 interactive = 1;
1051 /* XXX wait for reply */
1052 }
1053
1054 check_agent_present();
1055 if (options.forward_agent) {
1056 debug("Requesting authentication agent forwarding.");
1057 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1058 packet_send();
1059 }
1060
1061 len = buffer_len(&command);
1062 if (len > 0) {
1063 if (len > 900)
1064 len = 900;
1065 if (subsystem_flag) {
1066 debug("Sending subsystem: %.*s", len, (u_char *)buffer_ptr(&command));
1067 channel_request_start(id, "subsystem", /*want reply*/ 1);
1068 /* register callback for reply */
1069 /* XXX we assume that client_loop has already been called */
1070 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &client_subsystem_reply);
1071 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &client_subsystem_reply);
1072 } else {
1073 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1074 channel_request_start(id, "exec", 0);
1075 }
1076 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1077 packet_send();
1078 } else {
1079 channel_request_start(id, "shell", 0);
1080 packet_send();
1081 }
1082
1083 packet_set_interactive(interactive);
1084}
1085
1086/* open new channel for a session */
1087static int
1088ssh_session2_open(void)
1089{
1090 Channel *c;
1091 int window, packetmax, in, out, err;
1092
1093 if (stdin_null_flag) {
1094 in = open(_PATH_DEVNULL, O_RDONLY);
1095 } else {
1096 in = dup(STDIN_FILENO);
1097 }
1098 out = dup(STDOUT_FILENO);
1099 err = dup(STDERR_FILENO);
1100
1101 if (in < 0 || out < 0 || err < 0)
1102 fatal("dup() in/out/err failed");
1103
1104 /* enable nonblocking unless tty */
1105 if (!isatty(in))
1106 set_nonblock(in);
1107 if (!isatty(out))
1108 set_nonblock(out);
1109 if (!isatty(err))
1110 set_nonblock(err);
1111
1112 window = CHAN_SES_WINDOW_DEFAULT;
1113 packetmax = CHAN_SES_PACKET_DEFAULT;
1114 if (tty_flag) {
1115 window >>= 1;
1116 packetmax >>= 1;
1117 }
1118 c = channel_new(
1119 "session", SSH_CHANNEL_OPENING, in, out, err,
1120 window, packetmax, CHAN_EXTENDED_WRITE,
1121 xstrdup("client-session"), /*nonblock*/0);
1122
1123 debug3("ssh_session2_open: channel_new: %d", c->self);
1124
1125 channel_send_open(c->self);
1126 if (!no_shell_flag)
1127 channel_register_confirm(c->self, ssh_session2_setup);
1128
1129 return c->self;
1130}
1131
1132static int
1133ssh_session2(void)
1134{
1135 int id = -1;
1136
1137 /* XXX should be pre-session */
1138 ssh_init_forwarding();
1139
1140 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1141 id = ssh_session2_open();
1142
1143 /* If requested, let ssh continue in the background. */
1144 if (fork_after_authentication_flag)
1145 if (daemon(1, 1) < 0)
1146 fatal("daemon() failed: %.200s", strerror(errno));
1147
1148 return client_loop(tty_flag, tty_flag ?
1149 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1150}
1151
1152static void
1153load_public_identity_files(void)
1154{
1155 char *filename;
1156 int i = 0;
1157 Key *public;
1158#ifdef SMARTCARD
1159 Key **keys;
1160
1161 if (options.smartcard_device != NULL &&
1162 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1163 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1164 int count = 0;
1165 for (i = 0; keys[i] != NULL; i++) {
1166 count++;
1167 memmove(&options.identity_files[1], &options.identity_files[0],
1168 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1169 memmove(&options.identity_keys[1], &options.identity_keys[0],
1170 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1171 options.num_identity_files++;
1172 options.identity_keys[0] = keys[i];
1173 options.identity_files[0] = xstrdup("smartcard key");;
1174 }
1175 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1176 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1177 i = count;
1178 xfree(keys);
1179 }
1180#endif /* SMARTCARD */
1181 for (; i < options.num_identity_files; i++) {
1182 filename = tilde_expand_filename(options.identity_files[i],
1183 original_real_uid);
1184 public = key_load_public(filename, NULL);
1185 debug("identity file %s type %d", filename,
1186 public ? public->type : -1);
1187 xfree(options.identity_files[i]);
1188 options.identity_files[i] = filename;
1189 options.identity_keys[i] = public;
1190 }
1191}
This page took 0.0621 seconds and 5 git commands to generate.