]> andersk Git - openssh.git/blame_incremental - ssh.c
- djm@cvs.openbsd.org 2005/10/30 04:01:03
[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, 2003 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.252 2005/10/14 02:17:59 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 "bufaux.h"
57#include "channels.h"
58#include "key.h"
59#include "authfd.h"
60#include "authfile.h"
61#include "pathnames.h"
62#include "dispatch.h"
63#include "clientloop.h"
64#include "log.h"
65#include "readconf.h"
66#include "sshconnect.h"
67#include "misc.h"
68#include "kex.h"
69#include "mac.h"
70#include "sshpty.h"
71#include "match.h"
72#include "msg.h"
73#include "monitor_fdpass.h"
74#include "uidswap.h"
75
76#ifdef SMARTCARD
77#include "scard.h"
78#endif
79
80extern char *__progname;
81
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
101 * so that the passphrase can be entered manually, and then ssh goes to the
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. */
126Sensitive sensitive_data;
127
128/* Original real UID. */
129uid_t original_real_uid;
130uid_t original_effective_uid;
131
132/* command to be executed */
133Buffer command;
134
135/* Should we execute a command or invoke a subsystem? */
136int subsystem_flag = 0;
137
138/* # of replies received for global requests */
139static int client_global_request_id = 0;
140
141/* pid of proxycommand child process */
142pid_t proxy_command_pid = 0;
143
144/* fd to control socket */
145int control_fd = -1;
146
147/* Multiplexing control command */
148static u_int mux_command = 0;
149
150/* Only used in control client mode */
151volatile sig_atomic_t control_client_terminate = 0;
152u_int control_server_pid = 0;
153
154/* Prints a help message to the user. This function never returns. */
155
156static void
157usage(void)
158{
159 fprintf(stderr,
160"usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
161" [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
162" [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
163" [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
164" [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
165" [user@]hostname [command]\n"
166 );
167 exit(1);
168}
169
170static int ssh_session(void);
171static int ssh_session2(void);
172static void load_public_identity_files(void);
173static void control_client(const char *path);
174
175/*
176 * Main program for the ssh client.
177 */
178int
179main(int ac, char **av)
180{
181 int i, opt, exit_status;
182 char *p, *cp, *line, buf[256];
183 struct stat st;
184 struct passwd *pw;
185 int dummy;
186 extern int optind, optreset;
187 extern char *optarg;
188 struct servent *sp;
189 Forward fwd;
190
191 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
192 sanitise_stdfd();
193
194 __progname = ssh_get_progname(av[0]);
195 init_rng();
196
197 /*
198 * Save the original real uid. It will be needed later (uid-swapping
199 * may clobber the real uid).
200 */
201 original_real_uid = getuid();
202 original_effective_uid = geteuid();
203
204 /*
205 * Use uid-swapping to give up root privileges for the duration of
206 * option processing. We will re-instantiate the rights when we are
207 * ready to create the privileged port, and will permanently drop
208 * them when the port has been created (actually, when the connection
209 * has been made, as we may need to create the port several times).
210 */
211 PRIV_END;
212
213#ifdef HAVE_SETRLIMIT
214 /* If we are installed setuid root be careful to not drop core. */
215 if (original_real_uid != original_effective_uid) {
216 struct rlimit rlim;
217 rlim.rlim_cur = rlim.rlim_max = 0;
218 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
219 fatal("setrlimit failed: %.100s", strerror(errno));
220 }
221#endif
222 /* Get user data. */
223 pw = getpwuid(original_real_uid);
224 if (!pw) {
225 logit("You don't exist, go away!");
226 exit(1);
227 }
228 /* Take a copy of the returned structure. */
229 pw = pwcopy(pw);
230
231 /*
232 * Set our umask to something reasonable, as some files are created
233 * with the default umask. This will make them world-readable but
234 * writable only by the owner, which is ok for all files for which we
235 * don't set the modes explicitly.
236 */
237 umask(022);
238
239 /* Initialize option structure to indicate that no values have been set. */
240 initialize_options(&options);
241
242 /* Parse command-line arguments. */
243 host = NULL;
244
245again:
246 while ((opt = getopt(ac, av,
247 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVXY")) != -1) {
248 switch (opt) {
249 case '1':
250 options.protocol = SSH_PROTO_1;
251 break;
252 case '2':
253 options.protocol = SSH_PROTO_2;
254 break;
255 case '4':
256 options.address_family = AF_INET;
257 break;
258 case '6':
259 options.address_family = AF_INET6;
260 break;
261 case 'n':
262 stdin_null_flag = 1;
263 break;
264 case 'f':
265 fork_after_authentication_flag = 1;
266 stdin_null_flag = 1;
267 break;
268 case 'x':
269 options.forward_x11 = 0;
270 break;
271 case 'X':
272 options.forward_x11 = 1;
273 break;
274 case 'Y':
275 options.forward_x11 = 1;
276 options.forward_x11_trusted = 1;
277 break;
278 case 'g':
279 options.gateway_ports = 1;
280 break;
281 case 'O':
282 if (strcmp(optarg, "check") == 0)
283 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
284 else if (strcmp(optarg, "exit") == 0)
285 mux_command = SSHMUX_COMMAND_TERMINATE;
286 else
287 fatal("Invalid multiplex command.");
288 break;
289 case 'P': /* deprecated */
290 options.use_privileged_port = 0;
291 break;
292 case 'a':
293 options.forward_agent = 0;
294 break;
295 case 'A':
296 options.forward_agent = 1;
297 break;
298 case 'k':
299 options.gss_deleg_creds = 0;
300 break;
301 case 'i':
302 if (stat(optarg, &st) < 0) {
303 fprintf(stderr, "Warning: Identity file %s "
304 "not accessible: %s.\n", optarg,
305 strerror(errno));
306 break;
307 }
308 if (options.num_identity_files >=
309 SSH_MAX_IDENTITY_FILES)
310 fatal("Too many identity files specified "
311 "(max %d)", SSH_MAX_IDENTITY_FILES);
312 options.identity_files[options.num_identity_files++] =
313 xstrdup(optarg);
314 break;
315 case 'I':
316#ifdef SMARTCARD
317 options.smartcard_device = xstrdup(optarg);
318#else
319 fprintf(stderr, "no support for smartcards.\n");
320#endif
321 break;
322 case 't':
323 if (tty_flag)
324 force_tty_flag = 1;
325 tty_flag = 1;
326 break;
327 case 'v':
328 if (debug_flag == 0) {
329 debug_flag = 1;
330 options.log_level = SYSLOG_LEVEL_DEBUG1;
331 } else {
332 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
333 options.log_level++;
334 break;
335 }
336 /* FALLTHROUGH */
337 case 'V':
338 fprintf(stderr, "%s, %s\n",
339 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
340 if (opt == 'V')
341 exit(0);
342 break;
343 case 'q':
344 options.log_level = SYSLOG_LEVEL_QUIET;
345 break;
346 case 'e':
347 if (optarg[0] == '^' && optarg[2] == 0 &&
348 (u_char) optarg[1] >= 64 &&
349 (u_char) optarg[1] < 128)
350 options.escape_char = (u_char) optarg[1] & 31;
351 else if (strlen(optarg) == 1)
352 options.escape_char = (u_char) optarg[0];
353 else if (strcmp(optarg, "none") == 0)
354 options.escape_char = SSH_ESCAPECHAR_NONE;
355 else {
356 fprintf(stderr, "Bad escape character '%s'.\n",
357 optarg);
358 exit(1);
359 }
360 break;
361 case 'c':
362 if (ciphers_valid(optarg)) {
363 /* SSH2 only */
364 options.ciphers = xstrdup(optarg);
365 options.cipher = SSH_CIPHER_INVALID;
366 } else {
367 /* SSH1 only */
368 options.cipher = cipher_number(optarg);
369 if (options.cipher == -1) {
370 fprintf(stderr,
371 "Unknown cipher type '%s'\n",
372 optarg);
373 exit(1);
374 }
375 if (options.cipher == SSH_CIPHER_3DES)
376 options.ciphers = "3des-cbc";
377 else if (options.cipher == SSH_CIPHER_BLOWFISH)
378 options.ciphers = "blowfish-cbc";
379 else
380 options.ciphers = (char *)-1;
381 }
382 break;
383 case 'm':
384 if (mac_valid(optarg))
385 options.macs = xstrdup(optarg);
386 else {
387 fprintf(stderr, "Unknown mac type '%s'\n",
388 optarg);
389 exit(1);
390 }
391 break;
392 case 'M':
393 if (options.control_master == SSHCTL_MASTER_YES)
394 options.control_master = SSHCTL_MASTER_ASK;
395 else
396 options.control_master = SSHCTL_MASTER_YES;
397 break;
398 case 'p':
399 options.port = a2port(optarg);
400 if (options.port == 0) {
401 fprintf(stderr, "Bad port '%s'\n", optarg);
402 exit(1);
403 }
404 break;
405 case 'l':
406 options.user = optarg;
407 break;
408
409 case 'L':
410 if (parse_forward(&fwd, optarg))
411 add_local_forward(&options, &fwd);
412 else {
413 fprintf(stderr,
414 "Bad local forwarding specification '%s'\n",
415 optarg);
416 exit(1);
417 }
418 break;
419
420 case 'R':
421 if (parse_forward(&fwd, optarg)) {
422 add_remote_forward(&options, &fwd);
423 } else {
424 fprintf(stderr,
425 "Bad remote forwarding specification "
426 "'%s'\n", optarg);
427 exit(1);
428 }
429 break;
430
431 case 'D':
432 cp = p = xstrdup(optarg);
433 memset(&fwd, '\0', sizeof(fwd));
434 fwd.connect_host = "socks";
435 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
436 fprintf(stderr, "Bad dynamic forwarding "
437 "specification '%.100s'\n", optarg);
438 exit(1);
439 }
440 if (cp != NULL) {
441 fwd.listen_port = a2port(cp);
442 fwd.listen_host = cleanhostname(fwd.listen_host);
443 } else {
444 fwd.listen_port = a2port(fwd.listen_host);
445 fwd.listen_host = NULL;
446 }
447
448 if (fwd.listen_port == 0) {
449 fprintf(stderr, "Bad dynamic port '%s'\n",
450 optarg);
451 exit(1);
452 }
453 add_local_forward(&options, &fwd);
454 xfree(p);
455 break;
456
457 case 'C':
458 options.compression = 1;
459 break;
460 case 'N':
461 no_shell_flag = 1;
462 no_tty_flag = 1;
463 break;
464 case 'T':
465 no_tty_flag = 1;
466 break;
467 case 'o':
468 dummy = 1;
469 line = xstrdup(optarg);
470 if (process_config_line(&options, host ? host : "",
471 line, "command-line", 0, &dummy) != 0)
472 exit(1);
473 xfree(line);
474 break;
475 case 's':
476 subsystem_flag = 1;
477 break;
478 case 'S':
479 if (options.control_path != NULL)
480 free(options.control_path);
481 options.control_path = xstrdup(optarg);
482 break;
483 case 'b':
484 options.bind_address = optarg;
485 break;
486 case 'F':
487 config = optarg;
488 break;
489 default:
490 usage();
491 }
492 }
493
494 ac -= optind;
495 av += optind;
496
497 if (ac > 0 && !host && **av != '-') {
498 if (strrchr(*av, '@')) {
499 p = xstrdup(*av);
500 cp = strrchr(p, '@');
501 if (cp == NULL || cp == p)
502 usage();
503 options.user = p;
504 *cp = '\0';
505 host = ++cp;
506 } else
507 host = *av;
508 if (ac > 1) {
509 optind = optreset = 1;
510 goto again;
511 }
512 ac--, av++;
513 }
514
515 /* Check that we got a host name. */
516 if (!host)
517 usage();
518
519 SSLeay_add_all_algorithms();
520 ERR_load_crypto_strings();
521
522 /* Initialize the command to execute on remote host. */
523 buffer_init(&command);
524
525 /*
526 * Save the command to execute on the remote host in a buffer. There
527 * is no limit on the length of the command, except by the maximum
528 * packet size. Also sets the tty flag if there is no command.
529 */
530 if (!ac) {
531 /* No command specified - execute shell on a tty. */
532 tty_flag = 1;
533 if (subsystem_flag) {
534 fprintf(stderr,
535 "You must specify a subsystem to invoke.\n");
536 usage();
537 }
538 } else {
539 /* A command has been specified. Store it into the buffer. */
540 for (i = 0; i < ac; i++) {
541 if (i)
542 buffer_append(&command, " ", 1);
543 buffer_append(&command, av[i], strlen(av[i]));
544 }
545 }
546
547 /* Cannot fork to background if no command. */
548 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
549 fatal("Cannot fork into background without a command to execute.");
550
551 /* Allocate a tty by default if no command specified. */
552 if (buffer_len(&command) == 0)
553 tty_flag = 1;
554
555 /* Force no tty */
556 if (no_tty_flag)
557 tty_flag = 0;
558 /* Do not allocate a tty if stdin is not a tty. */
559 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
560 if (tty_flag)
561 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
562 tty_flag = 0;
563 }
564
565 /*
566 * Initialize "log" output. Since we are the client all output
567 * actually goes to stderr.
568 */
569 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
570 SYSLOG_FACILITY_USER, 1);
571
572 /*
573 * Read per-user configuration file. Ignore the system wide config
574 * file if the user specifies a config file on the command line.
575 */
576 if (config != NULL) {
577 if (!read_config_file(config, host, &options, 0))
578 fatal("Can't open user config file %.100s: "
579 "%.100s", config, strerror(errno));
580 } else {
581 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
582 _PATH_SSH_USER_CONFFILE);
583 (void)read_config_file(buf, host, &options, 1);
584
585 /* Read systemwide configuration file after use config. */
586 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
587 &options, 0);
588 }
589
590 /* Fill configuration defaults. */
591 fill_default_options(&options);
592
593 channel_set_af(options.address_family);
594
595 /* reinit */
596 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
597
598 seed_rng();
599
600 if (options.user == NULL)
601 options.user = xstrdup(pw->pw_name);
602
603 if (options.hostname != NULL)
604 host = options.hostname;
605
606 /* force lowercase for hostkey matching */
607 if (options.host_key_alias != NULL) {
608 for (p = options.host_key_alias; *p; p++)
609 if (isupper(*p))
610 *p = tolower(*p);
611 }
612
613 /* Get default port if port has not been set. */
614 if (options.port == 0) {
615 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
616 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
617 }
618
619 if (options.proxy_command != NULL &&
620 strcmp(options.proxy_command, "none") == 0)
621 options.proxy_command = NULL;
622 if (options.control_path != NULL &&
623 strcmp(options.control_path, "none") == 0)
624 options.control_path = NULL;
625
626 if (options.control_path != NULL) {
627 snprintf(buf, sizeof(buf), "%d", options.port);
628 cp = tilde_expand_filename(options.control_path,
629 original_real_uid);
630 options.control_path = percent_expand(cp, "p", buf, "h", host,
631 "r", options.user, (char *)NULL);
632 xfree(cp);
633 }
634 if (mux_command != 0 && options.control_path == NULL)
635 fatal("No ControlPath specified for \"-O\" command");
636 if (options.control_path != NULL)
637 control_client(options.control_path);
638
639 /* Open a connection to the remote host. */
640 if (ssh_connect(host, &hostaddr, options.port,
641 options.address_family, options.connection_attempts,
642#ifdef HAVE_CYGWIN
643 options.use_privileged_port,
644#else
645 original_effective_uid == 0 && options.use_privileged_port,
646#endif
647 options.proxy_command) != 0)
648 exit(1);
649
650 /*
651 * If we successfully made the connection, load the host private key
652 * in case we will need it later for combined rsa-rhosts
653 * authentication. This must be done before releasing extra
654 * privileges, because the file is only readable by root.
655 * If we cannot access the private keys, load the public keys
656 * instead and try to execute the ssh-keysign helper instead.
657 */
658 sensitive_data.nkeys = 0;
659 sensitive_data.keys = NULL;
660 sensitive_data.external_keysign = 0;
661 if (options.rhosts_rsa_authentication ||
662 options.hostbased_authentication) {
663 sensitive_data.nkeys = 3;
664 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
665 sizeof(Key));
666
667 PRIV_START;
668 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
669 _PATH_HOST_KEY_FILE, "", NULL);
670 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
671 _PATH_HOST_DSA_KEY_FILE, "", NULL);
672 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
673 _PATH_HOST_RSA_KEY_FILE, "", NULL);
674 PRIV_END;
675
676 if (options.hostbased_authentication == 1 &&
677 sensitive_data.keys[0] == NULL &&
678 sensitive_data.keys[1] == NULL &&
679 sensitive_data.keys[2] == NULL) {
680 sensitive_data.keys[1] = key_load_public(
681 _PATH_HOST_DSA_KEY_FILE, NULL);
682 sensitive_data.keys[2] = key_load_public(
683 _PATH_HOST_RSA_KEY_FILE, NULL);
684 sensitive_data.external_keysign = 1;
685 }
686 }
687 /*
688 * Get rid of any extra privileges that we may have. We will no
689 * longer need them. Also, extra privileges could make it very hard
690 * to read identity files and other non-world-readable files from the
691 * user's home directory if it happens to be on a NFS volume where
692 * root is mapped to nobody.
693 */
694 if (original_effective_uid == 0) {
695 PRIV_START;
696 permanently_set_uid(pw);
697 }
698
699 /*
700 * Now that we are back to our own permissions, create ~/.ssh
701 * directory if it doesn\'t already exist.
702 */
703 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
704 if (stat(buf, &st) < 0)
705 if (mkdir(buf, 0700) < 0)
706 error("Could not create directory '%.200s'.", buf);
707
708 /* load options.identity_files */
709 load_public_identity_files();
710
711 /* Expand ~ in known host file names. */
712 /* XXX mem-leaks: */
713 options.system_hostfile =
714 tilde_expand_filename(options.system_hostfile, original_real_uid);
715 options.user_hostfile =
716 tilde_expand_filename(options.user_hostfile, original_real_uid);
717 options.system_hostfile2 =
718 tilde_expand_filename(options.system_hostfile2, original_real_uid);
719 options.user_hostfile2 =
720 tilde_expand_filename(options.user_hostfile2, original_real_uid);
721
722 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
723
724 /* Log into the remote system. This never returns if the login fails. */
725 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
726
727 /* We no longer need the private host keys. Clear them now. */
728 if (sensitive_data.nkeys != 0) {
729 for (i = 0; i < sensitive_data.nkeys; i++) {
730 if (sensitive_data.keys[i] != NULL) {
731 /* Destroys contents safely */
732 debug3("clear hostkey %d", i);
733 key_free(sensitive_data.keys[i]);
734 sensitive_data.keys[i] = NULL;
735 }
736 }
737 xfree(sensitive_data.keys);
738 }
739 for (i = 0; i < options.num_identity_files; i++) {
740 if (options.identity_files[i]) {
741 xfree(options.identity_files[i]);
742 options.identity_files[i] = NULL;
743 }
744 if (options.identity_keys[i]) {
745 key_free(options.identity_keys[i]);
746 options.identity_keys[i] = NULL;
747 }
748 }
749
750 exit_status = compat20 ? ssh_session2() : ssh_session();
751 packet_close();
752
753 if (options.control_path != NULL && control_fd != -1)
754 unlink(options.control_path);
755
756 /*
757 * Send SIGHUP to proxy command if used. We don't wait() in
758 * case it hangs and instead rely on init to reap the child
759 */
760 if (proxy_command_pid > 1)
761 kill(proxy_command_pid, SIGHUP);
762
763 return exit_status;
764}
765
766static void
767ssh_init_forwarding(void)
768{
769 int success = 0;
770 int i;
771
772 /* Initiate local TCP/IP port forwardings. */
773 for (i = 0; i < options.num_local_forwards; i++) {
774 debug("Local connections to %.200s:%d forwarded to remote "
775 "address %.200s:%d",
776 (options.local_forwards[i].listen_host == NULL) ?
777 (options.gateway_ports ? "*" : "LOCALHOST") :
778 options.local_forwards[i].listen_host,
779 options.local_forwards[i].listen_port,
780 options.local_forwards[i].connect_host,
781 options.local_forwards[i].connect_port);
782 success += channel_setup_local_fwd_listener(
783 options.local_forwards[i].listen_host,
784 options.local_forwards[i].listen_port,
785 options.local_forwards[i].connect_host,
786 options.local_forwards[i].connect_port,
787 options.gateway_ports);
788 }
789 if (i > 0 && success == 0)
790 error("Could not request local forwarding.");
791
792 /* Initiate remote TCP/IP port forwardings. */
793 for (i = 0; i < options.num_remote_forwards; i++) {
794 debug("Remote connections from %.200s:%d forwarded to "
795 "local address %.200s:%d",
796 (options.remote_forwards[i].listen_host == NULL) ?
797 (options.gateway_ports ? "*" : "LOCALHOST") :
798 options.remote_forwards[i].listen_host,
799 options.remote_forwards[i].listen_port,
800 options.remote_forwards[i].connect_host,
801 options.remote_forwards[i].connect_port);
802 channel_request_remote_forwarding(
803 options.remote_forwards[i].listen_host,
804 options.remote_forwards[i].listen_port,
805 options.remote_forwards[i].connect_host,
806 options.remote_forwards[i].connect_port);
807 }
808}
809
810static void
811check_agent_present(void)
812{
813 if (options.forward_agent) {
814 /* Clear agent forwarding if we don\'t have an agent. */
815 if (!ssh_agent_present())
816 options.forward_agent = 0;
817 }
818}
819
820static int
821ssh_session(void)
822{
823 int type;
824 int interactive = 0;
825 int have_tty = 0;
826 struct winsize ws;
827 char *cp;
828 const char *display;
829
830 /* Enable compression if requested. */
831 if (options.compression) {
832 debug("Requesting compression at level %d.", options.compression_level);
833
834 if (options.compression_level < 1 || options.compression_level > 9)
835 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
836
837 /* Send the request. */
838 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
839 packet_put_int(options.compression_level);
840 packet_send();
841 packet_write_wait();
842 type = packet_read();
843 if (type == SSH_SMSG_SUCCESS)
844 packet_start_compression(options.compression_level);
845 else if (type == SSH_SMSG_FAILURE)
846 logit("Warning: Remote host refused compression.");
847 else
848 packet_disconnect("Protocol error waiting for compression response.");
849 }
850 /* Allocate a pseudo tty if appropriate. */
851 if (tty_flag) {
852 debug("Requesting pty.");
853
854 /* Start the packet. */
855 packet_start(SSH_CMSG_REQUEST_PTY);
856
857 /* Store TERM in the packet. There is no limit on the
858 length of the string. */
859 cp = getenv("TERM");
860 if (!cp)
861 cp = "";
862 packet_put_cstring(cp);
863
864 /* Store window size in the packet. */
865 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
866 memset(&ws, 0, sizeof(ws));
867 packet_put_int(ws.ws_row);
868 packet_put_int(ws.ws_col);
869 packet_put_int(ws.ws_xpixel);
870 packet_put_int(ws.ws_ypixel);
871
872 /* Store tty modes in the packet. */
873 tty_make_modes(fileno(stdin), NULL);
874
875 /* Send the packet, and wait for it to leave. */
876 packet_send();
877 packet_write_wait();
878
879 /* Read response from the server. */
880 type = packet_read();
881 if (type == SSH_SMSG_SUCCESS) {
882 interactive = 1;
883 have_tty = 1;
884 } else if (type == SSH_SMSG_FAILURE)
885 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
886 else
887 packet_disconnect("Protocol error waiting for pty request response.");
888 }
889 /* Request X11 forwarding if enabled and DISPLAY is set. */
890 display = getenv("DISPLAY");
891 if (options.forward_x11 && display != NULL) {
892 char *proto, *data;
893 /* Get reasonable local authentication information. */
894 client_x11_get_proto(display, options.xauth_location,
895 options.forward_x11_trusted, &proto, &data);
896 /* Request forwarding with authentication spoofing. */
897 debug("Requesting X11 forwarding with authentication spoofing.");
898 x11_request_forwarding_with_spoofing(0, display, proto, data);
899
900 /* Read response from the server. */
901 type = packet_read();
902 if (type == SSH_SMSG_SUCCESS) {
903 interactive = 1;
904 } else if (type == SSH_SMSG_FAILURE) {
905 logit("Warning: Remote host denied X11 forwarding.");
906 } else {
907 packet_disconnect("Protocol error waiting for X11 forwarding");
908 }
909 }
910 /* Tell the packet module whether this is an interactive session. */
911 packet_set_interactive(interactive);
912
913 /* Request authentication agent forwarding if appropriate. */
914 check_agent_present();
915
916 if (options.forward_agent) {
917 debug("Requesting authentication agent forwarding.");
918 auth_request_forwarding();
919
920 /* Read response from the server. */
921 type = packet_read();
922 packet_check_eom();
923 if (type != SSH_SMSG_SUCCESS)
924 logit("Warning: Remote host denied authentication agent forwarding.");
925 }
926
927 /* Initiate port forwardings. */
928 ssh_init_forwarding();
929
930 /* If requested, let ssh continue in the background. */
931 if (fork_after_authentication_flag)
932 if (daemon(1, 1) < 0)
933 fatal("daemon() failed: %.200s", strerror(errno));
934
935 /*
936 * If a command was specified on the command line, execute the
937 * command now. Otherwise request the server to start a shell.
938 */
939 if (buffer_len(&command) > 0) {
940 int len = buffer_len(&command);
941 if (len > 900)
942 len = 900;
943 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
944 packet_start(SSH_CMSG_EXEC_CMD);
945 packet_put_string(buffer_ptr(&command), buffer_len(&command));
946 packet_send();
947 packet_write_wait();
948 } else {
949 debug("Requesting shell.");
950 packet_start(SSH_CMSG_EXEC_SHELL);
951 packet_send();
952 packet_write_wait();
953 }
954
955 /* Enter the interactive session. */
956 return client_loop(have_tty, tty_flag ?
957 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
958}
959
960static void
961ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
962{
963 int id, len;
964
965 id = packet_get_int();
966 len = buffer_len(&command);
967 if (len > 900)
968 len = 900;
969 packet_check_eom();
970 if (type == SSH2_MSG_CHANNEL_FAILURE)
971 fatal("Request for subsystem '%.*s' failed on channel %d",
972 len, (u_char *)buffer_ptr(&command), id);
973}
974
975void
976client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
977{
978 int i;
979
980 i = client_global_request_id++;
981 if (i >= options.num_remote_forwards)
982 return;
983 debug("remote forward %s for: listen %d, connect %s:%d",
984 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
985 options.remote_forwards[i].listen_port,
986 options.remote_forwards[i].connect_host,
987 options.remote_forwards[i].connect_port);
988 if (type == SSH2_MSG_REQUEST_FAILURE)
989 logit("Warning: remote port forwarding failed for listen "
990 "port %d", options.remote_forwards[i].listen_port);
991}
992
993static void
994ssh_control_listener(void)
995{
996 struct sockaddr_un addr;
997 mode_t old_umask;
998 int addr_len;
999
1000 if (options.control_path == NULL ||
1001 options.control_master == SSHCTL_MASTER_NO)
1002 return;
1003
1004 debug("setting up multiplex master socket");
1005
1006 memset(&addr, '\0', sizeof(addr));
1007 addr.sun_family = AF_UNIX;
1008 addr_len = offsetof(struct sockaddr_un, sun_path) +
1009 strlen(options.control_path) + 1;
1010
1011 if (strlcpy(addr.sun_path, options.control_path,
1012 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1013 fatal("ControlPath too long");
1014
1015 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1016 fatal("%s socket(): %s", __func__, strerror(errno));
1017
1018 old_umask = umask(0177);
1019 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1020 control_fd = -1;
1021 if (errno == EINVAL || errno == EADDRINUSE)
1022 fatal("ControlSocket %s already exists",
1023 options.control_path);
1024 else
1025 fatal("%s bind(): %s", __func__, strerror(errno));
1026 }
1027 umask(old_umask);
1028
1029 if (listen(control_fd, 64) == -1)
1030 fatal("%s listen(): %s", __func__, strerror(errno));
1031
1032 set_nonblock(control_fd);
1033}
1034
1035/* request pty/x11/agent/tcpfwd/shell for channel */
1036static void
1037ssh_session2_setup(int id, void *arg)
1038{
1039 extern char **environ;
1040 const char *display;
1041 int interactive = tty_flag;
1042
1043 display = getenv("DISPLAY");
1044 if (options.forward_x11 && display != NULL) {
1045 char *proto, *data;
1046 /* Get reasonable local authentication information. */
1047 client_x11_get_proto(display, options.xauth_location,
1048 options.forward_x11_trusted, &proto, &data);
1049 /* Request forwarding with authentication spoofing. */
1050 debug("Requesting X11 forwarding with authentication spoofing.");
1051 x11_request_forwarding_with_spoofing(id, display, proto, data);
1052 interactive = 1;
1053 /* XXX wait for reply */
1054 }
1055
1056 check_agent_present();
1057 if (options.forward_agent) {
1058 debug("Requesting authentication agent forwarding.");
1059 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1060 packet_send();
1061 }
1062
1063 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1064 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1065
1066 packet_set_interactive(interactive);
1067}
1068
1069/* open new channel for a session */
1070static int
1071ssh_session2_open(void)
1072{
1073 Channel *c;
1074 int window, packetmax, in, out, err;
1075
1076 if (stdin_null_flag) {
1077 in = open(_PATH_DEVNULL, O_RDONLY);
1078 } else {
1079 in = dup(STDIN_FILENO);
1080 }
1081 out = dup(STDOUT_FILENO);
1082 err = dup(STDERR_FILENO);
1083
1084 if (in < 0 || out < 0 || err < 0)
1085 fatal("dup() in/out/err failed");
1086
1087 /* enable nonblocking unless tty */
1088 if (!isatty(in))
1089 set_nonblock(in);
1090 if (!isatty(out))
1091 set_nonblock(out);
1092 if (!isatty(err))
1093 set_nonblock(err);
1094
1095 window = CHAN_SES_WINDOW_DEFAULT;
1096 packetmax = CHAN_SES_PACKET_DEFAULT;
1097 if (tty_flag) {
1098 window >>= 1;
1099 packetmax >>= 1;
1100 }
1101 c = channel_new(
1102 "session", SSH_CHANNEL_OPENING, in, out, err,
1103 window, packetmax, CHAN_EXTENDED_WRITE,
1104 "client-session", /*nonblock*/0);
1105
1106 debug3("ssh_session2_open: channel_new: %d", c->self);
1107
1108 channel_send_open(c->self);
1109 if (!no_shell_flag)
1110 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1111
1112 return c->self;
1113}
1114
1115static int
1116ssh_session2(void)
1117{
1118 int id = -1;
1119
1120 /* XXX should be pre-session */
1121 ssh_init_forwarding();
1122 ssh_control_listener();
1123
1124 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1125 id = ssh_session2_open();
1126
1127 /* If requested, let ssh continue in the background. */
1128 if (fork_after_authentication_flag)
1129 if (daemon(1, 1) < 0)
1130 fatal("daemon() failed: %.200s", strerror(errno));
1131
1132 return client_loop(tty_flag, tty_flag ?
1133 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1134}
1135
1136static void
1137load_public_identity_files(void)
1138{
1139 char *filename;
1140 int i = 0;
1141 Key *public;
1142#ifdef SMARTCARD
1143 Key **keys;
1144
1145 if (options.smartcard_device != NULL &&
1146 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1147 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1148 int count = 0;
1149 for (i = 0; keys[i] != NULL; i++) {
1150 count++;
1151 memmove(&options.identity_files[1], &options.identity_files[0],
1152 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1153 memmove(&options.identity_keys[1], &options.identity_keys[0],
1154 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1155 options.num_identity_files++;
1156 options.identity_keys[0] = keys[i];
1157 options.identity_files[0] = sc_get_key_label(keys[i]);
1158 }
1159 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1160 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1161 i = count;
1162 xfree(keys);
1163 }
1164#endif /* SMARTCARD */
1165 for (; i < options.num_identity_files; i++) {
1166 filename = tilde_expand_filename(options.identity_files[i],
1167 original_real_uid);
1168 public = key_load_public(filename, NULL);
1169 debug("identity file %s type %d", filename,
1170 public ? public->type : -1);
1171 xfree(options.identity_files[i]);
1172 options.identity_files[i] = filename;
1173 options.identity_keys[i] = public;
1174 }
1175}
1176
1177static void
1178control_client_sighandler(int signo)
1179{
1180 control_client_terminate = signo;
1181}
1182
1183static void
1184control_client_sigrelay(int signo)
1185{
1186 if (control_server_pid > 1)
1187 kill(control_server_pid, signo);
1188}
1189
1190static int
1191env_permitted(char *env)
1192{
1193 int i;
1194 char name[1024], *cp;
1195
1196 strlcpy(name, env, sizeof(name));
1197 if ((cp = strchr(name, '=')) == NULL)
1198 return (0);
1199
1200 *cp = '\0';
1201
1202 for (i = 0; i < options.num_send_env; i++)
1203 if (match_pattern(name, options.send_env[i]))
1204 return (1);
1205
1206 return (0);
1207}
1208
1209static void
1210control_client(const char *path)
1211{
1212 struct sockaddr_un addr;
1213 int i, r, fd, sock, exitval, num_env, addr_len;
1214 Buffer m;
1215 char *term;
1216 extern char **environ;
1217 u_int flags;
1218
1219 if (mux_command == 0)
1220 mux_command = SSHMUX_COMMAND_OPEN;
1221
1222 switch (options.control_master) {
1223 case SSHCTL_MASTER_AUTO:
1224 case SSHCTL_MASTER_AUTO_ASK:
1225 debug("auto-mux: Trying existing master");
1226 /* FALLTHROUGH */
1227 case SSHCTL_MASTER_NO:
1228 break;
1229 default:
1230 return;
1231 }
1232
1233 memset(&addr, '\0', sizeof(addr));
1234 addr.sun_family = AF_UNIX;
1235 addr_len = offsetof(struct sockaddr_un, sun_path) +
1236 strlen(path) + 1;
1237
1238 if (strlcpy(addr.sun_path, path,
1239 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1240 fatal("ControlPath too long");
1241
1242 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1243 fatal("%s socket(): %s", __func__, strerror(errno));
1244
1245 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1246 if (mux_command != SSHMUX_COMMAND_OPEN) {
1247 fatal("Control socket connect(%.100s): %s", path,
1248 strerror(errno));
1249 }
1250 if (errno == ENOENT)
1251 debug("Control socket \"%.100s\" does not exist", path);
1252 else {
1253 error("Control socket connect(%.100s): %s", path,
1254 strerror(errno));
1255 }
1256 close(sock);
1257 return;
1258 }
1259
1260 if (stdin_null_flag) {
1261 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1262 fatal("open(/dev/null): %s", strerror(errno));
1263 if (dup2(fd, STDIN_FILENO) == -1)
1264 fatal("dup2: %s", strerror(errno));
1265 if (fd > STDERR_FILENO)
1266 close(fd);
1267 }
1268
1269 term = getenv("TERM");
1270
1271 flags = 0;
1272 if (tty_flag)
1273 flags |= SSHMUX_FLAG_TTY;
1274 if (subsystem_flag)
1275 flags |= SSHMUX_FLAG_SUBSYS;
1276 if (options.forward_x11)
1277 flags |= SSHMUX_FLAG_X11_FWD;
1278 if (options.forward_agent)
1279 flags |= SSHMUX_FLAG_AGENT_FWD;
1280
1281 buffer_init(&m);
1282
1283 /* Send our command to server */
1284 buffer_put_int(&m, mux_command);
1285 buffer_put_int(&m, flags);
1286 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1287 fatal("%s: msg_send", __func__);
1288 buffer_clear(&m);
1289
1290 /* Get authorisation status and PID of controlee */
1291 if (ssh_msg_recv(sock, &m) == -1)
1292 fatal("%s: msg_recv", __func__);
1293 if (buffer_get_char(&m) != SSHMUX_VER)
1294 fatal("%s: wrong version", __func__);
1295 if (buffer_get_int(&m) != 1)
1296 fatal("Connection to master denied");
1297 control_server_pid = buffer_get_int(&m);
1298
1299 buffer_clear(&m);
1300
1301 switch (mux_command) {
1302 case SSHMUX_COMMAND_ALIVE_CHECK:
1303 fprintf(stderr, "Master running (pid=%d)\r\n",
1304 control_server_pid);
1305 exit(0);
1306 case SSHMUX_COMMAND_TERMINATE:
1307 fprintf(stderr, "Exit request sent.\r\n");
1308 exit(0);
1309 case SSHMUX_COMMAND_OPEN:
1310 /* continue below */
1311 break;
1312 default:
1313 fatal("silly mux_command %d", mux_command);
1314 }
1315
1316 /* SSHMUX_COMMAND_OPEN */
1317 buffer_put_cstring(&m, term ? term : "");
1318 buffer_append(&command, "\0", 1);
1319 buffer_put_cstring(&m, buffer_ptr(&command));
1320
1321 if (options.num_send_env == 0 || environ == NULL) {
1322 buffer_put_int(&m, 0);
1323 } else {
1324 /* Pass environment */
1325 num_env = 0;
1326 for (i = 0; environ[i] != NULL; i++)
1327 if (env_permitted(environ[i]))
1328 num_env++; /* Count */
1329
1330 buffer_put_int(&m, num_env);
1331
1332 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1333 if (env_permitted(environ[i])) {
1334 num_env--;
1335 buffer_put_cstring(&m, environ[i]);
1336 }
1337 }
1338
1339 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1340 fatal("%s: msg_send", __func__);
1341
1342 mm_send_fd(sock, STDIN_FILENO);
1343 mm_send_fd(sock, STDOUT_FILENO);
1344 mm_send_fd(sock, STDERR_FILENO);
1345
1346 /* Wait for reply, so master has a chance to gather ttymodes */
1347 buffer_clear(&m);
1348 if (ssh_msg_recv(sock, &m) == -1)
1349 fatal("%s: msg_recv", __func__);
1350 if (buffer_get_char(&m) != SSHMUX_VER)
1351 fatal("%s: wrong version", __func__);
1352 buffer_free(&m);
1353
1354 signal(SIGHUP, control_client_sighandler);
1355 signal(SIGINT, control_client_sighandler);
1356 signal(SIGTERM, control_client_sighandler);
1357 signal(SIGWINCH, control_client_sigrelay);
1358
1359 if (tty_flag)
1360 enter_raw_mode();
1361
1362 /* Stick around until the controlee closes the client_fd */
1363 exitval = 0;
1364 for (;!control_client_terminate;) {
1365 r = read(sock, &exitval, sizeof(exitval));
1366 if (r == 0) {
1367 debug2("Received EOF from master");
1368 break;
1369 }
1370 if (r > 0)
1371 debug2("Received exit status from master %d", exitval);
1372 if (r == -1 && errno != EINTR)
1373 fatal("%s: read %s", __func__, strerror(errno));
1374 }
1375
1376 if (control_client_terminate)
1377 debug2("Exiting on signal %d", control_client_terminate);
1378
1379 close(sock);
1380
1381 leave_raw_mode();
1382
1383 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1384 fprintf(stderr, "Connection to master closed.\r\n");
1385
1386 exit(exitval);
1387}
This page took 1.05195 seconds and 5 git commands to generate.