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