2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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.
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".
15 * Copyright (c) 1999 Niels Provos. All rights reserved.
16 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
18 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
19 * in Canada (German citizen).
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
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.
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.
43 RCSID("$OpenBSD: ssh.c,v 1.257 2005/12/20 04:41:07 dtucker Exp $");
45 #include <openssl/evp.h>
46 #include <openssl/err.h>
61 #include "pathnames.h"
63 #include "clientloop.h"
66 #include "sshconnect.h"
73 #include "monitor_fdpass.h"
80 extern char *__progname;
82 /* Flag indicating whether debug mode is on. This can be set on the command line. */
85 /* Flag indicating whether a tty should be allocated */
88 int force_tty_flag = 0;
90 /* don't exec a shell */
91 int no_shell_flag = 0;
94 * Flag indicating that nothing should be read from stdin. This can be set
95 * on the command line.
97 int stdin_null_flag = 0;
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
104 int fork_after_authentication_flag = 0;
107 * General data structure for command line options and options configurable
108 * in configuration files. See readconf.h.
112 /* optional user configfile */
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.
122 /* socket address the host resolves to */
123 struct sockaddr_storage hostaddr;
125 /* Private host keys. */
126 Sensitive sensitive_data;
128 /* Original real UID. */
129 uid_t original_real_uid;
130 uid_t original_effective_uid;
132 /* command to be executed */
135 /* Should we execute a command or invoke a subsystem? */
136 int subsystem_flag = 0;
138 /* # of replies received for global requests */
139 static int client_global_request_id = 0;
141 /* pid of proxycommand child process */
142 pid_t proxy_command_pid = 0;
144 /* fd to control socket */
147 /* Multiplexing control command */
148 static u_int mux_command = 0;
150 /* Only used in control client mode */
151 volatile sig_atomic_t control_client_terminate = 0;
152 u_int control_server_pid = 0;
154 /* Prints a help message to the user. This function never returns. */
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 " [-w tunnel:tunnel] [user@]hostname [command]\n"
170 static int ssh_session(void);
171 static int ssh_session2(void);
172 static void load_public_identity_files(void);
173 static void control_client(const char *path);
176 * Main program for the ssh client.
179 main(int ac, char **av)
181 int i, opt, exit_status;
182 char *p, *cp, *line, buf[256];
186 extern int optind, optreset;
191 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
194 __progname = ssh_get_progname(av[0]);
198 * Save the original real uid. It will be needed later (uid-swapping
199 * may clobber the real uid).
201 original_real_uid = getuid();
202 original_effective_uid = geteuid();
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).
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) {
217 rlim.rlim_cur = rlim.rlim_max = 0;
218 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
219 fatal("setrlimit failed: %.100s", strerror(errno));
223 pw = getpwuid(original_real_uid);
225 logit("You don't exist, go away!");
228 /* Take a copy of the returned structure. */
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.
239 /* Initialize option structure to indicate that no values have been set. */
240 initialize_options(&options);
242 /* Parse command-line arguments. */
246 while ((opt = getopt(ac, av,
247 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
250 options.protocol = SSH_PROTO_1;
253 options.protocol = SSH_PROTO_2;
256 options.address_family = AF_INET;
259 options.address_family = AF_INET6;
265 fork_after_authentication_flag = 1;
269 options.forward_x11 = 0;
272 options.forward_x11 = 1;
275 options.forward_x11 = 1;
276 options.forward_x11_trusted = 1;
279 options.gateway_ports = 1;
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;
287 fatal("Invalid multiplex command.");
289 case 'P': /* deprecated */
290 options.use_privileged_port = 0;
293 options.forward_agent = 0;
296 options.forward_agent = 1;
299 options.gss_deleg_creds = 0;
302 if (stat(optarg, &st) < 0) {
303 fprintf(stderr, "Warning: Identity file %s "
304 "not accessible: %s.\n", optarg,
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++] =
317 options.smartcard_device = xstrdup(optarg);
319 fprintf(stderr, "no support for smartcards.\n");
328 if (debug_flag == 0) {
330 options.log_level = SYSLOG_LEVEL_DEBUG1;
332 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
338 fprintf(stderr, "%s, %s\n",
339 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
344 if (options.tun_open == -1)
345 options.tun_open = SSH_TUNMODE_DEFAULT;
346 options.tun_local = a2tun(optarg, &options.tun_remote);
347 if (options.tun_local == SSH_TUNID_ERR) {
348 fprintf(stderr, "Bad tun device '%s'\n", optarg);
353 options.log_level = SYSLOG_LEVEL_QUIET;
356 if (optarg[0] == '^' && optarg[2] == 0 &&
357 (u_char) optarg[1] >= 64 &&
358 (u_char) optarg[1] < 128)
359 options.escape_char = (u_char) optarg[1] & 31;
360 else if (strlen(optarg) == 1)
361 options.escape_char = (u_char) optarg[0];
362 else if (strcmp(optarg, "none") == 0)
363 options.escape_char = SSH_ESCAPECHAR_NONE;
365 fprintf(stderr, "Bad escape character '%s'.\n",
371 if (ciphers_valid(optarg)) {
373 options.ciphers = xstrdup(optarg);
374 options.cipher = SSH_CIPHER_INVALID;
377 options.cipher = cipher_number(optarg);
378 if (options.cipher == -1) {
380 "Unknown cipher type '%s'\n",
384 if (options.cipher == SSH_CIPHER_3DES)
385 options.ciphers = "3des-cbc";
386 else if (options.cipher == SSH_CIPHER_BLOWFISH)
387 options.ciphers = "blowfish-cbc";
389 options.ciphers = (char *)-1;
393 if (mac_valid(optarg))
394 options.macs = xstrdup(optarg);
396 fprintf(stderr, "Unknown mac type '%s'\n",
402 if (options.control_master == SSHCTL_MASTER_YES)
403 options.control_master = SSHCTL_MASTER_ASK;
405 options.control_master = SSHCTL_MASTER_YES;
408 options.port = a2port(optarg);
409 if (options.port == 0) {
410 fprintf(stderr, "Bad port '%s'\n", optarg);
415 options.user = optarg;
419 if (parse_forward(&fwd, optarg))
420 add_local_forward(&options, &fwd);
423 "Bad local forwarding specification '%s'\n",
430 if (parse_forward(&fwd, optarg)) {
431 add_remote_forward(&options, &fwd);
434 "Bad remote forwarding specification "
441 cp = p = xstrdup(optarg);
442 memset(&fwd, '\0', sizeof(fwd));
443 fwd.connect_host = "socks";
444 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
445 fprintf(stderr, "Bad dynamic forwarding "
446 "specification '%.100s'\n", optarg);
450 fwd.listen_port = a2port(cp);
451 fwd.listen_host = cleanhostname(fwd.listen_host);
453 fwd.listen_port = a2port(fwd.listen_host);
454 fwd.listen_host = NULL;
457 if (fwd.listen_port == 0) {
458 fprintf(stderr, "Bad dynamic port '%s'\n",
462 add_local_forward(&options, &fwd);
467 options.compression = 1;
472 options.none_switch = 0;
476 options.none_switch = 0;
480 line = xstrdup(optarg);
481 if (process_config_line(&options, host ? host : "",
482 line, "command-line", 0, &dummy) != 0)
490 if (options.control_path != NULL)
491 free(options.control_path);
492 options.control_path = xstrdup(optarg);
495 options.bind_address = optarg;
501 /* make sure we can't turn on the none_switch */
502 /* if they try to force a no tty flag on a tty session */
504 options.none_switch = 1;
516 if (ac > 0 && !host && **av != '-') {
517 if (strrchr(*av, '@')) {
519 cp = strrchr(p, '@');
520 if (cp == NULL || cp == p)
528 optind = optreset = 1;
534 /* Check that we got a host name. */
538 SSLeay_add_all_algorithms();
539 ERR_load_crypto_strings();
541 /* Initialize the command to execute on remote host. */
542 buffer_init(&command);
545 * Save the command to execute on the remote host in a buffer. There
546 * is no limit on the length of the command, except by the maximum
547 * packet size. Also sets the tty flag if there is no command.
550 /* No command specified - execute shell on a tty. */
552 if (subsystem_flag) {
554 "You must specify a subsystem to invoke.\n");
558 /* A command has been specified. Store it into the buffer. */
559 for (i = 0; i < ac; i++) {
561 buffer_append(&command, " ", 1);
562 buffer_append(&command, av[i], strlen(av[i]));
566 /* Cannot fork to background if no command. */
567 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
568 fatal("Cannot fork into background without a command to execute.");
570 /* Allocate a tty by default if no command specified. */
571 if (buffer_len(&command) == 0)
577 /* Do not allocate a tty if stdin is not a tty. */
578 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
580 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
585 * Initialize "log" output. Since we are the client all output
586 * actually goes to stderr.
588 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
589 SYSLOG_FACILITY_USER, 1);
592 * Read per-user configuration file. Ignore the system wide config
593 * file if the user specifies a config file on the command line.
595 if (config != NULL) {
596 if (!read_config_file(config, host, &options, 0))
597 fatal("Can't open user config file %.100s: "
598 "%.100s", config, strerror(errno));
601 * Since the config file parsing code aborts if it sees
602 * options it doesn't recognize, allow users to put
603 * options specific to compile-time add-ons in alternate
604 * config files so their primary config file will
605 * interoperate SSH versions that don't support those
609 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
610 _PATH_SSH_USER_CONFFILE);
611 (void)read_config_file(buf, host, &options, 1);
613 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
614 _PATH_SSH_USER_CONFFILE);
615 (void)read_config_file(buf, host, &options, 1);
618 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
619 _PATH_SSH_USER_CONFFILE);
620 (void)read_config_file(buf, host, &options, 1);
623 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
624 _PATH_SSH_USER_CONFFILE);
625 (void)read_config_file(buf, host, &options, 1);
627 /* Read systemwide configuration file after use config. */
628 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
632 /* Fill configuration defaults. */
633 fill_default_options(&options);
635 channel_set_af(options.address_family);
638 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
642 if (options.user == NULL) {
643 options.user = xstrdup(pw->pw_name);
644 options.implicit = 1;
646 else options.implicit = 0;
648 if (options.hostname != NULL)
649 host = options.hostname;
651 /* force lowercase for hostkey matching */
652 if (options.host_key_alias != NULL) {
653 for (p = options.host_key_alias; *p; p++)
658 /* Get default port if port has not been set. */
659 if (options.port == 0) {
660 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
661 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
664 if (options.proxy_command != NULL &&
665 strcmp(options.proxy_command, "none") == 0)
666 options.proxy_command = NULL;
667 if (options.control_path != NULL &&
668 strcmp(options.control_path, "none") == 0)
669 options.control_path = NULL;
671 if (options.control_path != NULL) {
672 snprintf(buf, sizeof(buf), "%d", options.port);
673 cp = tilde_expand_filename(options.control_path,
675 options.control_path = percent_expand(cp, "p", buf, "h", host,
676 "r", options.user, (char *)NULL);
679 if (mux_command != 0 && options.control_path == NULL)
680 fatal("No ControlPath specified for \"-O\" command");
681 if (options.control_path != NULL)
682 control_client(options.control_path);
684 /* Open a connection to the remote host. */
685 if (ssh_connect(host, &hostaddr, options.port,
686 options.address_family, options.connection_attempts,
688 options.use_privileged_port,
690 original_effective_uid == 0 && options.use_privileged_port,
692 options.proxy_command) != 0)
696 * If we successfully made the connection, load the host private key
697 * in case we will need it later for combined rsa-rhosts
698 * authentication. This must be done before releasing extra
699 * privileges, because the file is only readable by root.
700 * If we cannot access the private keys, load the public keys
701 * instead and try to execute the ssh-keysign helper instead.
703 sensitive_data.nkeys = 0;
704 sensitive_data.keys = NULL;
705 sensitive_data.external_keysign = 0;
706 if (options.rhosts_rsa_authentication ||
707 options.hostbased_authentication) {
708 sensitive_data.nkeys = 3;
709 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
713 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
714 _PATH_HOST_KEY_FILE, "", NULL);
715 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
716 _PATH_HOST_DSA_KEY_FILE, "", NULL);
717 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
718 _PATH_HOST_RSA_KEY_FILE, "", NULL);
721 if (options.hostbased_authentication == 1 &&
722 sensitive_data.keys[0] == NULL &&
723 sensitive_data.keys[1] == NULL &&
724 sensitive_data.keys[2] == NULL) {
725 sensitive_data.keys[1] = key_load_public(
726 _PATH_HOST_DSA_KEY_FILE, NULL);
727 sensitive_data.keys[2] = key_load_public(
728 _PATH_HOST_RSA_KEY_FILE, NULL);
729 sensitive_data.external_keysign = 1;
733 * Get rid of any extra privileges that we may have. We will no
734 * longer need them. Also, extra privileges could make it very hard
735 * to read identity files and other non-world-readable files from the
736 * user's home directory if it happens to be on a NFS volume where
737 * root is mapped to nobody.
739 if (original_effective_uid == 0) {
741 permanently_set_uid(pw);
745 * Now that we are back to our own permissions, create ~/.ssh
746 * directory if it doesn't already exist.
748 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
749 if (stat(buf, &st) < 0)
750 if (mkdir(buf, 0700) < 0)
751 error("Could not create directory '%.200s'.", buf);
753 /* load options.identity_files */
754 load_public_identity_files();
756 /* Expand ~ in known host file names. */
758 options.system_hostfile =
759 tilde_expand_filename(options.system_hostfile, original_real_uid);
760 options.user_hostfile =
761 tilde_expand_filename(options.user_hostfile, original_real_uid);
762 options.system_hostfile2 =
763 tilde_expand_filename(options.system_hostfile2, original_real_uid);
764 options.user_hostfile2 =
765 tilde_expand_filename(options.user_hostfile2, original_real_uid);
767 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
769 /* Log into the remote system. This never returns if the login fails. */
770 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
772 /* We no longer need the private host keys. Clear them now. */
773 if (sensitive_data.nkeys != 0) {
774 for (i = 0; i < sensitive_data.nkeys; i++) {
775 if (sensitive_data.keys[i] != NULL) {
776 /* Destroys contents safely */
777 debug3("clear hostkey %d", i);
778 key_free(sensitive_data.keys[i]);
779 sensitive_data.keys[i] = NULL;
782 xfree(sensitive_data.keys);
784 for (i = 0; i < options.num_identity_files; i++) {
785 if (options.identity_files[i]) {
786 xfree(options.identity_files[i]);
787 options.identity_files[i] = NULL;
789 if (options.identity_keys[i]) {
790 key_free(options.identity_keys[i]);
791 options.identity_keys[i] = NULL;
795 exit_status = compat20 ? ssh_session2() : ssh_session();
798 if (options.control_path != NULL && control_fd != -1)
799 unlink(options.control_path);
802 * Send SIGHUP to proxy command if used. We don't wait() in
803 * case it hangs and instead rely on init to reap the child
805 if (proxy_command_pid > 1)
806 kill(proxy_command_pid, SIGHUP);
812 ssh_init_forwarding(void)
817 /* Initiate local TCP/IP port forwardings. */
818 for (i = 0; i < options.num_local_forwards; i++) {
819 debug("Local connections to %.200s:%d forwarded to remote "
821 (options.local_forwards[i].listen_host == NULL) ?
822 (options.gateway_ports ? "*" : "LOCALHOST") :
823 options.local_forwards[i].listen_host,
824 options.local_forwards[i].listen_port,
825 options.local_forwards[i].connect_host,
826 options.local_forwards[i].connect_port);
827 success += channel_setup_local_fwd_listener(
828 options.local_forwards[i].listen_host,
829 options.local_forwards[i].listen_port,
830 options.local_forwards[i].connect_host,
831 options.local_forwards[i].connect_port,
832 options.gateway_ports, options.hpn_disabled,
833 options.hpn_buffer_size);
835 if (i > 0 && success == 0)
836 error("Could not request local forwarding.");
838 /* Initiate remote TCP/IP port forwardings. */
839 for (i = 0; i < options.num_remote_forwards; i++) {
840 debug("Remote connections from %.200s:%d forwarded to "
841 "local address %.200s:%d",
842 (options.remote_forwards[i].listen_host == NULL) ?
843 "LOCALHOST" : options.remote_forwards[i].listen_host,
844 options.remote_forwards[i].listen_port,
845 options.remote_forwards[i].connect_host,
846 options.remote_forwards[i].connect_port);
847 channel_request_remote_forwarding(
848 options.remote_forwards[i].listen_host,
849 options.remote_forwards[i].listen_port,
850 options.remote_forwards[i].connect_host,
851 options.remote_forwards[i].connect_port);
856 check_agent_present(void)
858 if (options.forward_agent) {
859 /* Clear agent forwarding if we don't have an agent. */
860 if (!ssh_agent_present())
861 options.forward_agent = 0;
875 /* Enable compression if requested. */
876 if (options.compression) {
877 debug("Requesting compression at level %d.", options.compression_level);
879 if (options.compression_level < 1 || options.compression_level > 9)
880 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
882 /* Send the request. */
883 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
884 packet_put_int(options.compression_level);
887 type = packet_read();
888 if (type == SSH_SMSG_SUCCESS)
889 packet_start_compression(options.compression_level);
890 else if (type == SSH_SMSG_FAILURE)
891 logit("Warning: Remote host refused compression.");
893 packet_disconnect("Protocol error waiting for compression response.");
895 /* Allocate a pseudo tty if appropriate. */
897 debug("Requesting pty.");
899 /* Start the packet. */
900 packet_start(SSH_CMSG_REQUEST_PTY);
902 /* Store TERM in the packet. There is no limit on the
903 length of the string. */
907 packet_put_cstring(cp);
909 /* Store window size in the packet. */
910 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
911 memset(&ws, 0, sizeof(ws));
912 packet_put_int(ws.ws_row);
913 packet_put_int(ws.ws_col);
914 packet_put_int(ws.ws_xpixel);
915 packet_put_int(ws.ws_ypixel);
917 /* Store tty modes in the packet. */
918 tty_make_modes(fileno(stdin), NULL);
920 /* Send the packet, and wait for it to leave. */
924 /* Read response from the server. */
925 type = packet_read();
926 if (type == SSH_SMSG_SUCCESS) {
929 } else if (type == SSH_SMSG_FAILURE)
930 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
932 packet_disconnect("Protocol error waiting for pty request response.");
934 /* Request X11 forwarding if enabled and DISPLAY is set. */
935 display = getenv("DISPLAY");
936 if (options.forward_x11 && display != NULL) {
938 /* Get reasonable local authentication information. */
939 client_x11_get_proto(display, options.xauth_location,
940 options.forward_x11_trusted, &proto, &data);
941 /* Request forwarding with authentication spoofing. */
942 debug("Requesting X11 forwarding with authentication spoofing.");
943 x11_request_forwarding_with_spoofing(0, display, proto, data);
945 /* Read response from the server. */
946 type = packet_read();
947 if (type == SSH_SMSG_SUCCESS) {
949 } else if (type == SSH_SMSG_FAILURE) {
950 logit("Warning: Remote host denied X11 forwarding.");
952 packet_disconnect("Protocol error waiting for X11 forwarding");
955 /* Tell the packet module whether this is an interactive session. */
956 packet_set_interactive(interactive);
958 /* Request authentication agent forwarding if appropriate. */
959 check_agent_present();
961 if (options.forward_agent) {
962 debug("Requesting authentication agent forwarding.");
963 auth_request_forwarding();
965 /* Read response from the server. */
966 type = packet_read();
968 if (type != SSH_SMSG_SUCCESS)
969 logit("Warning: Remote host denied authentication agent forwarding.");
972 /* Initiate port forwardings. */
973 ssh_init_forwarding();
975 /* If requested, let ssh continue in the background. */
976 if (fork_after_authentication_flag)
977 if (daemon(1, 1) < 0)
978 fatal("daemon() failed: %.200s", strerror(errno));
981 * If a command was specified on the command line, execute the
982 * command now. Otherwise request the server to start a shell.
984 if (buffer_len(&command) > 0) {
985 int len = buffer_len(&command);
988 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
989 packet_start(SSH_CMSG_EXEC_CMD);
990 packet_put_string(buffer_ptr(&command), buffer_len(&command));
994 debug("Requesting shell.");
995 packet_start(SSH_CMSG_EXEC_SHELL);
1000 /* Enter the interactive session. */
1001 return client_loop(have_tty, tty_flag ?
1002 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1006 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1010 id = packet_get_int();
1011 len = buffer_len(&command);
1015 if (type == SSH2_MSG_CHANNEL_FAILURE)
1016 fatal("Request for subsystem '%.*s' failed on channel %d",
1017 len, (u_char *)buffer_ptr(&command), id);
1021 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1025 i = client_global_request_id++;
1026 if (i >= options.num_remote_forwards)
1028 debug("remote forward %s for: listen %d, connect %s:%d",
1029 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1030 options.remote_forwards[i].listen_port,
1031 options.remote_forwards[i].connect_host,
1032 options.remote_forwards[i].connect_port);
1033 if (type == SSH2_MSG_REQUEST_FAILURE)
1034 logit("Warning: remote port forwarding failed for listen "
1035 "port %d", options.remote_forwards[i].listen_port);
1039 ssh_control_listener(void)
1041 struct sockaddr_un addr;
1045 if (options.control_path == NULL ||
1046 options.control_master == SSHCTL_MASTER_NO)
1049 debug("setting up multiplex master socket");
1051 memset(&addr, '\0', sizeof(addr));
1052 addr.sun_family = AF_UNIX;
1053 addr_len = offsetof(struct sockaddr_un, sun_path) +
1054 strlen(options.control_path) + 1;
1056 if (strlcpy(addr.sun_path, options.control_path,
1057 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1058 fatal("ControlPath too long");
1060 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1061 fatal("%s socket(): %s", __func__, strerror(errno));
1063 old_umask = umask(0177);
1064 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1066 if (errno == EINVAL || errno == EADDRINUSE)
1067 fatal("ControlSocket %s already exists",
1068 options.control_path);
1070 fatal("%s bind(): %s", __func__, strerror(errno));
1074 if (listen(control_fd, 64) == -1)
1075 fatal("%s listen(): %s", __func__, strerror(errno));
1077 set_nonblock(control_fd);
1080 /* request pty/x11/agent/tcpfwd/shell for channel */
1082 ssh_session2_setup(int id, void *arg)
1084 extern char **environ;
1085 const char *display;
1086 int interactive = tty_flag;
1088 display = getenv("DISPLAY");
1089 if (options.forward_x11 && display != NULL) {
1091 /* Get reasonable local authentication information. */
1092 client_x11_get_proto(display, options.xauth_location,
1093 options.forward_x11_trusted, &proto, &data);
1094 /* Request forwarding with authentication spoofing. */
1095 debug("Requesting X11 forwarding with authentication spoofing.");
1096 x11_request_forwarding_with_spoofing(id, display, proto, data);
1098 /* XXX wait for reply */
1101 check_agent_present();
1102 if (options.forward_agent) {
1103 debug("Requesting authentication agent forwarding.");
1104 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1108 if (options.tun_open != SSH_TUNMODE_NO) {
1112 debug("Requesting tun.");
1113 if ((fd = tun_open(options.tun_local,
1114 options.tun_open)) >= 0) {
1115 if(options.hpn_disabled)
1116 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1117 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1120 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1121 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1124 #if defined(SSH_TUN_FILTER)
1125 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1126 channel_register_filter(c->self, sys_tun_infilter,
1129 packet_start(SSH2_MSG_CHANNEL_OPEN);
1130 packet_put_cstring("tun@openssh.com");
1131 packet_put_int(c->self);
1132 packet_put_int(c->local_window_max);
1133 packet_put_int(c->local_maxpacket);
1134 packet_put_int(options.tun_open);
1135 packet_put_int(options.tun_remote);
1140 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1141 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1143 packet_set_interactive(interactive);
1146 /* open new channel for a session */
1148 ssh_session2_open(void)
1151 int window, packetmax, in, out, err;
1153 if (stdin_null_flag) {
1154 in = open(_PATH_DEVNULL, O_RDONLY);
1156 in = dup(STDIN_FILENO);
1158 out = dup(STDOUT_FILENO);
1159 err = dup(STDERR_FILENO);
1161 if (in < 0 || out < 0 || err < 0)
1162 fatal("dup() in/out/err failed");
1164 /* enable nonblocking unless tty */
1172 if(options.hpn_disabled)
1173 window = CHAN_SES_WINDOW_DEFAULT;
1175 window = options.hpn_buffer_size;
1176 packetmax = CHAN_SES_PACKET_DEFAULT;
1178 window = 4*CHAN_SES_PACKET_DEFAULT;
1183 "session", SSH_CHANNEL_OPENING, in, out, err,
1184 window, packetmax, CHAN_EXTENDED_WRITE,
1185 "client-session", /*nonblock*/0);
1186 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1187 c->dynamic_window = 1;
1188 debug ("Enabled Dynamic Window Scaling\n");
1190 debug3("ssh_session2_open: channel_new: %d", c->self);
1192 channel_send_open(c->self);
1194 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1204 /* XXX should be pre-session */
1205 ssh_init_forwarding();
1206 ssh_control_listener();
1208 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1209 id = ssh_session2_open();
1211 /* Execute a local command */
1212 if (options.local_command != NULL &&
1213 options.permit_local_command)
1214 ssh_local_cmd(options.local_command);
1216 /* If requested, let ssh continue in the background. */
1217 if (fork_after_authentication_flag)
1218 if (daemon(1, 1) < 0)
1219 fatal("daemon() failed: %.200s", strerror(errno));
1221 return client_loop(tty_flag, tty_flag ?
1222 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1226 load_public_identity_files(void)
1234 if (options.smartcard_device != NULL &&
1235 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1236 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1238 for (i = 0; keys[i] != NULL; i++) {
1240 memmove(&options.identity_files[1], &options.identity_files[0],
1241 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1242 memmove(&options.identity_keys[1], &options.identity_keys[0],
1243 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1244 options.num_identity_files++;
1245 options.identity_keys[0] = keys[i];
1246 options.identity_files[0] = sc_get_key_label(keys[i]);
1248 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1249 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1253 #endif /* SMARTCARD */
1254 for (; i < options.num_identity_files; i++) {
1255 filename = tilde_expand_filename(options.identity_files[i],
1257 public = key_load_public(filename, NULL);
1258 debug("identity file %s type %d", filename,
1259 public ? public->type : -1);
1260 xfree(options.identity_files[i]);
1261 options.identity_files[i] = filename;
1262 options.identity_keys[i] = public;
1267 control_client_sighandler(int signo)
1269 control_client_terminate = signo;
1273 control_client_sigrelay(int signo)
1275 if (control_server_pid > 1)
1276 kill(control_server_pid, signo);
1280 env_permitted(char *env)
1283 char name[1024], *cp;
1285 strlcpy(name, env, sizeof(name));
1286 if ((cp = strchr(name, '=')) == NULL)
1291 for (i = 0; i < options.num_send_env; i++)
1292 if (match_pattern(name, options.send_env[i]))
1299 control_client(const char *path)
1301 struct sockaddr_un addr;
1302 int i, r, fd, sock, exitval, num_env, addr_len;
1305 extern char **environ;
1308 if (mux_command == 0)
1309 mux_command = SSHMUX_COMMAND_OPEN;
1311 switch (options.control_master) {
1312 case SSHCTL_MASTER_AUTO:
1313 case SSHCTL_MASTER_AUTO_ASK:
1314 debug("auto-mux: Trying existing master");
1316 case SSHCTL_MASTER_NO:
1322 memset(&addr, '\0', sizeof(addr));
1323 addr.sun_family = AF_UNIX;
1324 addr_len = offsetof(struct sockaddr_un, sun_path) +
1327 if (strlcpy(addr.sun_path, path,
1328 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1329 fatal("ControlPath too long");
1331 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1332 fatal("%s socket(): %s", __func__, strerror(errno));
1334 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1335 if (mux_command != SSHMUX_COMMAND_OPEN) {
1336 fatal("Control socket connect(%.100s): %s", path,
1339 if (errno == ENOENT)
1340 debug("Control socket \"%.100s\" does not exist", path);
1342 error("Control socket connect(%.100s): %s", path,
1349 if (stdin_null_flag) {
1350 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1351 fatal("open(/dev/null): %s", strerror(errno));
1352 if (dup2(fd, STDIN_FILENO) == -1)
1353 fatal("dup2: %s", strerror(errno));
1354 if (fd > STDERR_FILENO)
1358 term = getenv("TERM");
1362 flags |= SSHMUX_FLAG_TTY;
1364 flags |= SSHMUX_FLAG_SUBSYS;
1365 if (options.forward_x11)
1366 flags |= SSHMUX_FLAG_X11_FWD;
1367 if (options.forward_agent)
1368 flags |= SSHMUX_FLAG_AGENT_FWD;
1369 if (options.num_local_forwards > 0)
1370 flags |= SSHMUX_FLAG_PORTFORWARD;
1373 /* Send our command to server */
1374 buffer_put_int(&m, mux_command);
1375 buffer_put_int(&m, flags);
1376 if (options.num_local_forwards > 0)
1378 if (options.local_forwards[0].listen_host == NULL)
1379 buffer_put_string(&m,"LOCALHOST",11);
1381 buffer_put_string(&m,options.local_forwards[0].listen_host,512);
1382 buffer_put_int(&m,options.local_forwards[0].listen_port);
1383 buffer_put_string(&m,options.local_forwards[0].connect_host,512);
1384 buffer_put_int(&m,options.local_forwards[0].connect_port);
1386 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1387 fatal("%s: msg_send", __func__);
1390 /* Get authorisation status and PID of controlee */
1391 if (ssh_msg_recv(sock, &m) == -1)
1392 fatal("%s: msg_recv", __func__);
1393 if (buffer_get_char(&m) != SSHMUX_VER)
1394 fatal("%s: wrong version", __func__);
1395 if (buffer_get_int(&m) != 1)
1396 fatal("Connection to master denied");
1397 control_server_pid = buffer_get_int(&m);
1401 switch (mux_command) {
1402 case SSHMUX_COMMAND_ALIVE_CHECK:
1403 fprintf(stderr, "Master running (pid=%d)\r\n",
1404 control_server_pid);
1406 case SSHMUX_COMMAND_TERMINATE:
1407 fprintf(stderr, "Exit request sent.\r\n");
1409 case SSHMUX_COMMAND_OPEN:
1410 /* continue below */
1413 fatal("silly mux_command %d", mux_command);
1416 /* SSHMUX_COMMAND_OPEN */
1417 buffer_put_cstring(&m, term ? term : "");
1418 buffer_append(&command, "\0", 1);
1419 buffer_put_cstring(&m, buffer_ptr(&command));
1421 if (options.num_send_env == 0 || environ == NULL) {
1422 buffer_put_int(&m, 0);
1424 /* Pass environment */
1426 for (i = 0; environ[i] != NULL; i++)
1427 if (env_permitted(environ[i]))
1428 num_env++; /* Count */
1430 buffer_put_int(&m, num_env);
1432 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1433 if (env_permitted(environ[i])) {
1435 buffer_put_cstring(&m, environ[i]);
1439 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1440 fatal("%s: msg_send", __func__);
1442 mm_send_fd(sock, STDIN_FILENO);
1443 mm_send_fd(sock, STDOUT_FILENO);
1444 mm_send_fd(sock, STDERR_FILENO);
1446 /* Wait for reply, so master has a chance to gather ttymodes */
1448 if (ssh_msg_recv(sock, &m) == -1)
1449 fatal("%s: msg_recv", __func__);
1450 if (buffer_get_char(&m) != SSHMUX_VER)
1451 fatal("%s: wrong version", __func__);
1454 signal(SIGHUP, control_client_sighandler);
1455 signal(SIGINT, control_client_sighandler);
1456 signal(SIGTERM, control_client_sighandler);
1457 signal(SIGWINCH, control_client_sigrelay);
1462 /* Stick around until the controlee closes the client_fd */
1464 for (;!control_client_terminate;) {
1465 r = read(sock, &exitval, sizeof(exitval));
1467 debug2("Received EOF from master");
1471 debug2("Received exit status from master %d", exitval);
1472 if (r == -1 && errno != EINTR)
1473 fatal("%s: read %s", __func__, strerror(errno));
1476 if (control_client_terminate)
1477 debug2("Exiting on signal %d", control_client_terminate);
1483 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1484 fprintf(stderr, "Connection to master closed.\r\n");