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.258 2006/02/08 12:15:27 stevesk Exp $");
47 #include <openssl/evp.h>
48 #include <openssl/err.h>
63 #include "pathnames.h"
65 #include "clientloop.h"
68 #include "sshconnect.h"
75 #include "monitor_fdpass.h"
82 extern char *__progname;
84 /* Flag indicating whether debug mode is on. This can be set on the command line. */
87 /* Flag indicating whether a tty should be allocated */
90 int force_tty_flag = 0;
92 /* don't exec a shell */
93 int no_shell_flag = 0;
96 * Flag indicating that nothing should be read from stdin. This can be set
97 * on the command line.
99 int stdin_null_flag = 0;
102 * Flag indicating that ssh should fork after authentication. This is useful
103 * so that the passphrase can be entered manually, and then ssh goes to the
106 int fork_after_authentication_flag = 0;
109 * General data structure for command line options and options configurable
110 * in configuration files. See readconf.h.
114 /* optional user configfile */
118 * Name of the host we are connecting to. This is the name given on the
119 * command line, or the HostName specified for the user-supplied name in a
120 * configuration file.
124 /* socket address the host resolves to */
125 struct sockaddr_storage hostaddr;
127 /* Private host keys. */
128 Sensitive sensitive_data;
130 /* Original real UID. */
131 uid_t original_real_uid;
132 uid_t original_effective_uid;
134 /* command to be executed */
137 /* Should we execute a command or invoke a subsystem? */
138 int subsystem_flag = 0;
140 /* # of replies received for global requests */
141 static int client_global_request_id = 0;
143 /* pid of proxycommand child process */
144 pid_t proxy_command_pid = 0;
146 /* fd to control socket */
149 /* Multiplexing control command */
150 static u_int mux_command = 0;
152 /* Only used in control client mode */
153 volatile sig_atomic_t control_client_terminate = 0;
154 u_int control_server_pid = 0;
156 /* Prints a help message to the user. This function never returns. */
162 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
163 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
164 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
165 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
166 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
167 " [-w tunnel:tunnel] [user@]hostname [command]\n"
172 static int ssh_session(void);
173 static int ssh_session2(void);
174 static void load_public_identity_files(void);
175 static void control_client(const char *path);
178 * Main program for the ssh client.
181 main(int ac, char **av)
183 int i, opt, exit_status;
184 char *p, *cp, *line, buf[256];
188 extern int optind, optreset;
193 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
196 __progname = ssh_get_progname(av[0]);
200 * Save the original real uid. It will be needed later (uid-swapping
201 * may clobber the real uid).
203 original_real_uid = getuid();
204 original_effective_uid = geteuid();
207 * Use uid-swapping to give up root privileges for the duration of
208 * option processing. We will re-instantiate the rights when we are
209 * ready to create the privileged port, and will permanently drop
210 * them when the port has been created (actually, when the connection
211 * has been made, as we may need to create the port several times).
215 #ifdef HAVE_SETRLIMIT
216 /* If we are installed setuid root be careful to not drop core. */
217 if (original_real_uid != original_effective_uid) {
219 rlim.rlim_cur = rlim.rlim_max = 0;
220 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
221 fatal("setrlimit failed: %.100s", strerror(errno));
225 pw = getpwuid(original_real_uid);
227 logit("You don't exist, go away!");
230 /* Take a copy of the returned structure. */
234 * Set our umask to something reasonable, as some files are created
235 * with the default umask. This will make them world-readable but
236 * writable only by the owner, which is ok for all files for which we
237 * don't set the modes explicitly.
241 /* Initialize option structure to indicate that no values have been set. */
242 initialize_options(&options);
244 /* Parse command-line arguments. */
248 while ((opt = getopt(ac, av,
249 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
252 options.protocol = SSH_PROTO_1;
255 options.protocol = SSH_PROTO_2;
258 options.address_family = AF_INET;
261 options.address_family = AF_INET6;
267 fork_after_authentication_flag = 1;
271 options.forward_x11 = 0;
274 options.forward_x11 = 1;
277 options.forward_x11 = 1;
278 options.forward_x11_trusted = 1;
281 options.gateway_ports = 1;
284 if (strcmp(optarg, "check") == 0)
285 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
286 else if (strcmp(optarg, "exit") == 0)
287 mux_command = SSHMUX_COMMAND_TERMINATE;
289 fatal("Invalid multiplex command.");
291 case 'P': /* deprecated */
292 options.use_privileged_port = 0;
295 options.forward_agent = 0;
298 options.forward_agent = 1;
301 options.gss_deleg_creds = 0;
304 if (stat(optarg, &st) < 0) {
305 fprintf(stderr, "Warning: Identity file %s "
306 "not accessible: %s.\n", optarg,
310 if (options.num_identity_files >=
311 SSH_MAX_IDENTITY_FILES)
312 fatal("Too many identity files specified "
313 "(max %d)", SSH_MAX_IDENTITY_FILES);
314 options.identity_files[options.num_identity_files++] =
319 options.smartcard_device = xstrdup(optarg);
321 fprintf(stderr, "no support for smartcards.\n");
330 if (debug_flag == 0) {
332 options.log_level = SYSLOG_LEVEL_DEBUG1;
334 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
340 fprintf(stderr, "%s, %s\n",
341 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
346 if (options.tun_open == -1)
347 options.tun_open = SSH_TUNMODE_DEFAULT;
348 options.tun_local = a2tun(optarg, &options.tun_remote);
349 if (options.tun_local == SSH_TUNID_ERR) {
350 fprintf(stderr, "Bad tun device '%s'\n", optarg);
355 options.log_level = SYSLOG_LEVEL_QUIET;
358 if (optarg[0] == '^' && optarg[2] == 0 &&
359 (u_char) optarg[1] >= 64 &&
360 (u_char) optarg[1] < 128)
361 options.escape_char = (u_char) optarg[1] & 31;
362 else if (strlen(optarg) == 1)
363 options.escape_char = (u_char) optarg[0];
364 else if (strcmp(optarg, "none") == 0)
365 options.escape_char = SSH_ESCAPECHAR_NONE;
367 fprintf(stderr, "Bad escape character '%s'.\n",
373 if (ciphers_valid(optarg)) {
375 options.ciphers = xstrdup(optarg);
376 options.cipher = SSH_CIPHER_INVALID;
379 options.cipher = cipher_number(optarg);
380 if (options.cipher == -1) {
382 "Unknown cipher type '%s'\n",
386 if (options.cipher == SSH_CIPHER_3DES)
387 options.ciphers = "3des-cbc";
388 else if (options.cipher == SSH_CIPHER_BLOWFISH)
389 options.ciphers = "blowfish-cbc";
391 options.ciphers = (char *)-1;
395 if (mac_valid(optarg))
396 options.macs = xstrdup(optarg);
398 fprintf(stderr, "Unknown mac type '%s'\n",
404 if (options.control_master == SSHCTL_MASTER_YES)
405 options.control_master = SSHCTL_MASTER_ASK;
407 options.control_master = SSHCTL_MASTER_YES;
410 options.port = a2port(optarg);
411 if (options.port == 0) {
412 fprintf(stderr, "Bad port '%s'\n", optarg);
417 options.user = optarg;
421 if (parse_forward(&fwd, optarg))
422 add_local_forward(&options, &fwd);
425 "Bad local forwarding specification '%s'\n",
432 if (parse_forward(&fwd, optarg)) {
433 add_remote_forward(&options, &fwd);
436 "Bad remote forwarding specification "
443 cp = p = xstrdup(optarg);
444 memset(&fwd, '\0', sizeof(fwd));
445 fwd.connect_host = "socks";
446 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
447 fprintf(stderr, "Bad dynamic forwarding "
448 "specification '%.100s'\n", optarg);
452 fwd.listen_port = a2port(cp);
453 fwd.listen_host = cleanhostname(fwd.listen_host);
455 fwd.listen_port = a2port(fwd.listen_host);
456 fwd.listen_host = NULL;
459 if (fwd.listen_port == 0) {
460 fprintf(stderr, "Bad dynamic port '%s'\n",
464 add_local_forward(&options, &fwd);
469 options.compression = 1;
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;
508 if (ac > 0 && !host && **av != '-') {
509 if (strrchr(*av, '@')) {
511 cp = strrchr(p, '@');
512 if (cp == NULL || cp == p)
520 optind = optreset = 1;
526 /* Check that we got a host name. */
530 SSLeay_add_all_algorithms();
531 ERR_load_crypto_strings();
533 /* Initialize the command to execute on remote host. */
534 buffer_init(&command);
537 * Save the command to execute on the remote host in a buffer. There
538 * is no limit on the length of the command, except by the maximum
539 * packet size. Also sets the tty flag if there is no command.
542 /* No command specified - execute shell on a tty. */
544 if (subsystem_flag) {
546 "You must specify a subsystem to invoke.\n");
550 /* A command has been specified. Store it into the buffer. */
551 for (i = 0; i < ac; i++) {
553 buffer_append(&command, " ", 1);
554 buffer_append(&command, av[i], strlen(av[i]));
558 /* Cannot fork to background if no command. */
559 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
560 fatal("Cannot fork into background without a command to execute.");
562 /* Allocate a tty by default if no command specified. */
563 if (buffer_len(&command) == 0)
569 /* Do not allocate a tty if stdin is not a tty. */
570 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
572 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
577 * Initialize "log" output. Since we are the client all output
578 * actually goes to stderr.
580 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
581 SYSLOG_FACILITY_USER, 1);
584 * Read per-user configuration file. Ignore the system wide config
585 * file if the user specifies a config file on the command line.
587 if (config != NULL) {
588 if (!read_config_file(config, host, &options, 0))
589 fatal("Can't open user config file %.100s: "
590 "%.100s", config, strerror(errno));
592 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
593 _PATH_SSH_USER_CONFFILE);
594 (void)read_config_file(buf, host, &options, 1);
596 /* Read systemwide configuration file after use config. */
597 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
601 /* Fill configuration defaults. */
602 fill_default_options(&options);
604 channel_set_af(options.address_family);
607 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
611 if (options.user == NULL)
612 options.user = xstrdup(pw->pw_name);
614 if (options.hostname != NULL)
615 host = options.hostname;
617 /* force lowercase for hostkey matching */
618 if (options.host_key_alias != NULL) {
619 for (p = options.host_key_alias; *p; p++)
624 /* Get default port if port has not been set. */
625 if (options.port == 0) {
626 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
627 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
630 if (options.proxy_command != NULL &&
631 strcmp(options.proxy_command, "none") == 0)
632 options.proxy_command = NULL;
633 if (options.control_path != NULL &&
634 strcmp(options.control_path, "none") == 0)
635 options.control_path = NULL;
637 if (options.control_path != NULL) {
638 snprintf(buf, sizeof(buf), "%d", options.port);
639 cp = tilde_expand_filename(options.control_path,
641 options.control_path = percent_expand(cp, "p", buf, "h", host,
642 "r", options.user, (char *)NULL);
645 if (mux_command != 0 && options.control_path == NULL)
646 fatal("No ControlPath specified for \"-O\" command");
647 if (options.control_path != NULL)
648 control_client(options.control_path);
650 /* Open a connection to the remote host. */
651 if (ssh_connect(host, &hostaddr, options.port,
652 options.address_family, options.connection_attempts,
654 options.use_privileged_port,
656 original_effective_uid == 0 && options.use_privileged_port,
658 options.proxy_command) != 0)
662 * If we successfully made the connection, load the host private key
663 * in case we will need it later for combined rsa-rhosts
664 * authentication. This must be done before releasing extra
665 * privileges, because the file is only readable by root.
666 * If we cannot access the private keys, load the public keys
667 * instead and try to execute the ssh-keysign helper instead.
669 sensitive_data.nkeys = 0;
670 sensitive_data.keys = NULL;
671 sensitive_data.external_keysign = 0;
672 if (options.rhosts_rsa_authentication ||
673 options.hostbased_authentication) {
674 sensitive_data.nkeys = 3;
675 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
679 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
680 _PATH_HOST_KEY_FILE, "", NULL);
681 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
682 _PATH_HOST_DSA_KEY_FILE, "", NULL);
683 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
684 _PATH_HOST_RSA_KEY_FILE, "", NULL);
687 if (options.hostbased_authentication == 1 &&
688 sensitive_data.keys[0] == NULL &&
689 sensitive_data.keys[1] == NULL &&
690 sensitive_data.keys[2] == NULL) {
691 sensitive_data.keys[1] = key_load_public(
692 _PATH_HOST_DSA_KEY_FILE, NULL);
693 sensitive_data.keys[2] = key_load_public(
694 _PATH_HOST_RSA_KEY_FILE, NULL);
695 sensitive_data.external_keysign = 1;
699 * Get rid of any extra privileges that we may have. We will no
700 * longer need them. Also, extra privileges could make it very hard
701 * to read identity files and other non-world-readable files from the
702 * user's home directory if it happens to be on a NFS volume where
703 * root is mapped to nobody.
705 if (original_effective_uid == 0) {
707 permanently_set_uid(pw);
711 * Now that we are back to our own permissions, create ~/.ssh
712 * directory if it doesn't already exist.
714 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
715 if (stat(buf, &st) < 0)
716 if (mkdir(buf, 0700) < 0)
717 error("Could not create directory '%.200s'.", buf);
719 /* load options.identity_files */
720 load_public_identity_files();
722 /* Expand ~ in known host file names. */
724 options.system_hostfile =
725 tilde_expand_filename(options.system_hostfile, original_real_uid);
726 options.user_hostfile =
727 tilde_expand_filename(options.user_hostfile, original_real_uid);
728 options.system_hostfile2 =
729 tilde_expand_filename(options.system_hostfile2, original_real_uid);
730 options.user_hostfile2 =
731 tilde_expand_filename(options.user_hostfile2, original_real_uid);
733 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
735 /* Log into the remote system. This never returns if the login fails. */
736 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
738 /* We no longer need the private host keys. Clear them now. */
739 if (sensitive_data.nkeys != 0) {
740 for (i = 0; i < sensitive_data.nkeys; i++) {
741 if (sensitive_data.keys[i] != NULL) {
742 /* Destroys contents safely */
743 debug3("clear hostkey %d", i);
744 key_free(sensitive_data.keys[i]);
745 sensitive_data.keys[i] = NULL;
748 xfree(sensitive_data.keys);
750 for (i = 0; i < options.num_identity_files; i++) {
751 if (options.identity_files[i]) {
752 xfree(options.identity_files[i]);
753 options.identity_files[i] = NULL;
755 if (options.identity_keys[i]) {
756 key_free(options.identity_keys[i]);
757 options.identity_keys[i] = NULL;
761 exit_status = compat20 ? ssh_session2() : ssh_session();
764 if (options.control_path != NULL && control_fd != -1)
765 unlink(options.control_path);
768 * Send SIGHUP to proxy command if used. We don't wait() in
769 * case it hangs and instead rely on init to reap the child
771 if (proxy_command_pid > 1)
772 kill(proxy_command_pid, SIGHUP);
778 ssh_init_forwarding(void)
783 /* Initiate local TCP/IP port forwardings. */
784 for (i = 0; i < options.num_local_forwards; i++) {
785 debug("Local connections to %.200s:%d forwarded to remote "
787 (options.local_forwards[i].listen_host == NULL) ?
788 (options.gateway_ports ? "*" : "LOCALHOST") :
789 options.local_forwards[i].listen_host,
790 options.local_forwards[i].listen_port,
791 options.local_forwards[i].connect_host,
792 options.local_forwards[i].connect_port);
793 success += channel_setup_local_fwd_listener(
794 options.local_forwards[i].listen_host,
795 options.local_forwards[i].listen_port,
796 options.local_forwards[i].connect_host,
797 options.local_forwards[i].connect_port,
798 options.gateway_ports);
800 if (i > 0 && success == 0)
801 error("Could not request local forwarding.");
803 /* Initiate remote TCP/IP port forwardings. */
804 for (i = 0; i < options.num_remote_forwards; i++) {
805 debug("Remote connections from %.200s:%d forwarded to "
806 "local address %.200s:%d",
807 (options.remote_forwards[i].listen_host == NULL) ?
808 "LOCALHOST" : options.remote_forwards[i].listen_host,
809 options.remote_forwards[i].listen_port,
810 options.remote_forwards[i].connect_host,
811 options.remote_forwards[i].connect_port);
812 channel_request_remote_forwarding(
813 options.remote_forwards[i].listen_host,
814 options.remote_forwards[i].listen_port,
815 options.remote_forwards[i].connect_host,
816 options.remote_forwards[i].connect_port);
821 check_agent_present(void)
823 if (options.forward_agent) {
824 /* Clear agent forwarding if we don't have an agent. */
825 if (!ssh_agent_present())
826 options.forward_agent = 0;
840 /* Enable compression if requested. */
841 if (options.compression) {
842 debug("Requesting compression at level %d.", options.compression_level);
844 if (options.compression_level < 1 || options.compression_level > 9)
845 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
847 /* Send the request. */
848 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
849 packet_put_int(options.compression_level);
852 type = packet_read();
853 if (type == SSH_SMSG_SUCCESS)
854 packet_start_compression(options.compression_level);
855 else if (type == SSH_SMSG_FAILURE)
856 logit("Warning: Remote host refused compression.");
858 packet_disconnect("Protocol error waiting for compression response.");
860 /* Allocate a pseudo tty if appropriate. */
862 debug("Requesting pty.");
864 /* Start the packet. */
865 packet_start(SSH_CMSG_REQUEST_PTY);
867 /* Store TERM in the packet. There is no limit on the
868 length of the string. */
872 packet_put_cstring(cp);
874 /* Store window size in the packet. */
875 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
876 memset(&ws, 0, sizeof(ws));
877 packet_put_int(ws.ws_row);
878 packet_put_int(ws.ws_col);
879 packet_put_int(ws.ws_xpixel);
880 packet_put_int(ws.ws_ypixel);
882 /* Store tty modes in the packet. */
883 tty_make_modes(fileno(stdin), NULL);
885 /* Send the packet, and wait for it to leave. */
889 /* Read response from the server. */
890 type = packet_read();
891 if (type == SSH_SMSG_SUCCESS) {
894 } else if (type == SSH_SMSG_FAILURE)
895 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
897 packet_disconnect("Protocol error waiting for pty request response.");
899 /* Request X11 forwarding if enabled and DISPLAY is set. */
900 display = getenv("DISPLAY");
901 if (options.forward_x11 && display != NULL) {
903 /* Get reasonable local authentication information. */
904 client_x11_get_proto(display, options.xauth_location,
905 options.forward_x11_trusted, &proto, &data);
906 /* Request forwarding with authentication spoofing. */
907 debug("Requesting X11 forwarding with authentication spoofing.");
908 x11_request_forwarding_with_spoofing(0, display, proto, data);
910 /* Read response from the server. */
911 type = packet_read();
912 if (type == SSH_SMSG_SUCCESS) {
914 } else if (type == SSH_SMSG_FAILURE) {
915 logit("Warning: Remote host denied X11 forwarding.");
917 packet_disconnect("Protocol error waiting for X11 forwarding");
920 /* Tell the packet module whether this is an interactive session. */
921 packet_set_interactive(interactive);
923 /* Request authentication agent forwarding if appropriate. */
924 check_agent_present();
926 if (options.forward_agent) {
927 debug("Requesting authentication agent forwarding.");
928 auth_request_forwarding();
930 /* Read response from the server. */
931 type = packet_read();
933 if (type != SSH_SMSG_SUCCESS)
934 logit("Warning: Remote host denied authentication agent forwarding.");
937 /* Initiate port forwardings. */
938 ssh_init_forwarding();
940 /* If requested, let ssh continue in the background. */
941 if (fork_after_authentication_flag)
942 if (daemon(1, 1) < 0)
943 fatal("daemon() failed: %.200s", strerror(errno));
946 * If a command was specified on the command line, execute the
947 * command now. Otherwise request the server to start a shell.
949 if (buffer_len(&command) > 0) {
950 int len = buffer_len(&command);
953 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
954 packet_start(SSH_CMSG_EXEC_CMD);
955 packet_put_string(buffer_ptr(&command), buffer_len(&command));
959 debug("Requesting shell.");
960 packet_start(SSH_CMSG_EXEC_SHELL);
965 /* Enter the interactive session. */
966 return client_loop(have_tty, tty_flag ?
967 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
971 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
975 id = packet_get_int();
976 len = buffer_len(&command);
980 if (type == SSH2_MSG_CHANNEL_FAILURE)
981 fatal("Request for subsystem '%.*s' failed on channel %d",
982 len, (u_char *)buffer_ptr(&command), id);
986 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
990 i = client_global_request_id++;
991 if (i >= options.num_remote_forwards)
993 debug("remote forward %s for: listen %d, connect %s:%d",
994 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
995 options.remote_forwards[i].listen_port,
996 options.remote_forwards[i].connect_host,
997 options.remote_forwards[i].connect_port);
998 if (type == SSH2_MSG_REQUEST_FAILURE)
999 logit("Warning: remote port forwarding failed for listen "
1000 "port %d", options.remote_forwards[i].listen_port);
1004 ssh_control_listener(void)
1006 struct sockaddr_un addr;
1010 if (options.control_path == NULL ||
1011 options.control_master == SSHCTL_MASTER_NO)
1014 debug("setting up multiplex master socket");
1016 memset(&addr, '\0', sizeof(addr));
1017 addr.sun_family = AF_UNIX;
1018 addr_len = offsetof(struct sockaddr_un, sun_path) +
1019 strlen(options.control_path) + 1;
1021 if (strlcpy(addr.sun_path, options.control_path,
1022 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1023 fatal("ControlPath too long");
1025 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1026 fatal("%s socket(): %s", __func__, strerror(errno));
1028 old_umask = umask(0177);
1029 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1031 if (errno == EINVAL || errno == EADDRINUSE)
1032 fatal("ControlSocket %s already exists",
1033 options.control_path);
1035 fatal("%s bind(): %s", __func__, strerror(errno));
1039 if (listen(control_fd, 64) == -1)
1040 fatal("%s listen(): %s", __func__, strerror(errno));
1042 set_nonblock(control_fd);
1045 /* request pty/x11/agent/tcpfwd/shell for channel */
1047 ssh_session2_setup(int id, void *arg)
1049 extern char **environ;
1050 const char *display;
1051 int interactive = tty_flag;
1053 display = getenv("DISPLAY");
1054 if (options.forward_x11 && display != NULL) {
1056 /* Get reasonable local authentication information. */
1057 client_x11_get_proto(display, options.xauth_location,
1058 options.forward_x11_trusted, &proto, &data);
1059 /* Request forwarding with authentication spoofing. */
1060 debug("Requesting X11 forwarding with authentication spoofing.");
1061 x11_request_forwarding_with_spoofing(id, display, proto, data);
1063 /* XXX wait for reply */
1066 check_agent_present();
1067 if (options.forward_agent) {
1068 debug("Requesting authentication agent forwarding.");
1069 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1073 if (options.tun_open != SSH_TUNMODE_NO) {
1077 debug("Requesting tun.");
1078 if ((fd = tun_open(options.tun_local,
1079 options.tun_open)) >= 0) {
1080 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1081 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1084 #if defined(SSH_TUN_FILTER)
1085 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1086 channel_register_filter(c->self, sys_tun_infilter,
1089 packet_start(SSH2_MSG_CHANNEL_OPEN);
1090 packet_put_cstring("tun@openssh.com");
1091 packet_put_int(c->self);
1092 packet_put_int(c->local_window_max);
1093 packet_put_int(c->local_maxpacket);
1094 packet_put_int(options.tun_open);
1095 packet_put_int(options.tun_remote);
1100 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1101 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1103 packet_set_interactive(interactive);
1106 /* open new channel for a session */
1108 ssh_session2_open(void)
1111 int window, packetmax, in, out, err;
1113 if (stdin_null_flag) {
1114 in = open(_PATH_DEVNULL, O_RDONLY);
1116 in = dup(STDIN_FILENO);
1118 out = dup(STDOUT_FILENO);
1119 err = dup(STDERR_FILENO);
1121 if (in < 0 || out < 0 || err < 0)
1122 fatal("dup() in/out/err failed");
1124 /* enable nonblocking unless tty */
1132 window = CHAN_SES_WINDOW_DEFAULT;
1133 packetmax = CHAN_SES_PACKET_DEFAULT;
1139 "session", SSH_CHANNEL_OPENING, in, out, err,
1140 window, packetmax, CHAN_EXTENDED_WRITE,
1141 "client-session", /*nonblock*/0);
1143 debug3("ssh_session2_open: channel_new: %d", c->self);
1145 channel_send_open(c->self);
1147 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1157 /* XXX should be pre-session */
1158 ssh_init_forwarding();
1159 ssh_control_listener();
1161 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1162 id = ssh_session2_open();
1164 /* Execute a local command */
1165 if (options.local_command != NULL &&
1166 options.permit_local_command)
1167 ssh_local_cmd(options.local_command);
1169 /* If requested, let ssh continue in the background. */
1170 if (fork_after_authentication_flag)
1171 if (daemon(1, 1) < 0)
1172 fatal("daemon() failed: %.200s", strerror(errno));
1174 return client_loop(tty_flag, tty_flag ?
1175 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1179 load_public_identity_files(void)
1187 if (options.smartcard_device != NULL &&
1188 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1189 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1191 for (i = 0; keys[i] != NULL; i++) {
1193 memmove(&options.identity_files[1], &options.identity_files[0],
1194 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1195 memmove(&options.identity_keys[1], &options.identity_keys[0],
1196 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1197 options.num_identity_files++;
1198 options.identity_keys[0] = keys[i];
1199 options.identity_files[0] = sc_get_key_label(keys[i]);
1201 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1202 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1206 #endif /* SMARTCARD */
1207 for (; i < options.num_identity_files; i++) {
1208 filename = tilde_expand_filename(options.identity_files[i],
1210 public = key_load_public(filename, NULL);
1211 debug("identity file %s type %d", filename,
1212 public ? public->type : -1);
1213 xfree(options.identity_files[i]);
1214 options.identity_files[i] = filename;
1215 options.identity_keys[i] = public;
1220 control_client_sighandler(int signo)
1222 control_client_terminate = signo;
1226 control_client_sigrelay(int signo)
1228 if (control_server_pid > 1)
1229 kill(control_server_pid, signo);
1233 env_permitted(char *env)
1236 char name[1024], *cp;
1238 strlcpy(name, env, sizeof(name));
1239 if ((cp = strchr(name, '=')) == NULL)
1244 for (i = 0; i < options.num_send_env; i++)
1245 if (match_pattern(name, options.send_env[i]))
1252 control_client(const char *path)
1254 struct sockaddr_un addr;
1255 int i, r, fd, sock, exitval, num_env, addr_len;
1258 extern char **environ;
1261 if (mux_command == 0)
1262 mux_command = SSHMUX_COMMAND_OPEN;
1264 switch (options.control_master) {
1265 case SSHCTL_MASTER_AUTO:
1266 case SSHCTL_MASTER_AUTO_ASK:
1267 debug("auto-mux: Trying existing master");
1269 case SSHCTL_MASTER_NO:
1275 memset(&addr, '\0', sizeof(addr));
1276 addr.sun_family = AF_UNIX;
1277 addr_len = offsetof(struct sockaddr_un, sun_path) +
1280 if (strlcpy(addr.sun_path, path,
1281 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1282 fatal("ControlPath too long");
1284 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1285 fatal("%s socket(): %s", __func__, strerror(errno));
1287 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1288 if (mux_command != SSHMUX_COMMAND_OPEN) {
1289 fatal("Control socket connect(%.100s): %s", path,
1292 if (errno == ENOENT)
1293 debug("Control socket \"%.100s\" does not exist", path);
1295 error("Control socket connect(%.100s): %s", path,
1302 if (stdin_null_flag) {
1303 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1304 fatal("open(/dev/null): %s", strerror(errno));
1305 if (dup2(fd, STDIN_FILENO) == -1)
1306 fatal("dup2: %s", strerror(errno));
1307 if (fd > STDERR_FILENO)
1311 term = getenv("TERM");
1315 flags |= SSHMUX_FLAG_TTY;
1317 flags |= SSHMUX_FLAG_SUBSYS;
1318 if (options.forward_x11)
1319 flags |= SSHMUX_FLAG_X11_FWD;
1320 if (options.forward_agent)
1321 flags |= SSHMUX_FLAG_AGENT_FWD;
1325 /* Send our command to server */
1326 buffer_put_int(&m, mux_command);
1327 buffer_put_int(&m, flags);
1328 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1329 fatal("%s: msg_send", __func__);
1332 /* Get authorisation status and PID of controlee */
1333 if (ssh_msg_recv(sock, &m) == -1)
1334 fatal("%s: msg_recv", __func__);
1335 if (buffer_get_char(&m) != SSHMUX_VER)
1336 fatal("%s: wrong version", __func__);
1337 if (buffer_get_int(&m) != 1)
1338 fatal("Connection to master denied");
1339 control_server_pid = buffer_get_int(&m);
1343 switch (mux_command) {
1344 case SSHMUX_COMMAND_ALIVE_CHECK:
1345 fprintf(stderr, "Master running (pid=%d)\r\n",
1346 control_server_pid);
1348 case SSHMUX_COMMAND_TERMINATE:
1349 fprintf(stderr, "Exit request sent.\r\n");
1351 case SSHMUX_COMMAND_OPEN:
1352 /* continue below */
1355 fatal("silly mux_command %d", mux_command);
1358 /* SSHMUX_COMMAND_OPEN */
1359 buffer_put_cstring(&m, term ? term : "");
1360 buffer_append(&command, "\0", 1);
1361 buffer_put_cstring(&m, buffer_ptr(&command));
1363 if (options.num_send_env == 0 || environ == NULL) {
1364 buffer_put_int(&m, 0);
1366 /* Pass environment */
1368 for (i = 0; environ[i] != NULL; i++)
1369 if (env_permitted(environ[i]))
1370 num_env++; /* Count */
1372 buffer_put_int(&m, num_env);
1374 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1375 if (env_permitted(environ[i])) {
1377 buffer_put_cstring(&m, environ[i]);
1381 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1382 fatal("%s: msg_send", __func__);
1384 mm_send_fd(sock, STDIN_FILENO);
1385 mm_send_fd(sock, STDOUT_FILENO);
1386 mm_send_fd(sock, STDERR_FILENO);
1388 /* Wait for reply, so master has a chance to gather ttymodes */
1390 if (ssh_msg_recv(sock, &m) == -1)
1391 fatal("%s: msg_recv", __func__);
1392 if (buffer_get_char(&m) != SSHMUX_VER)
1393 fatal("%s: wrong version", __func__);
1396 signal(SIGHUP, control_client_sighandler);
1397 signal(SIGINT, control_client_sighandler);
1398 signal(SIGTERM, control_client_sighandler);
1399 signal(SIGWINCH, control_client_sigrelay);
1404 /* Stick around until the controlee closes the client_fd */
1406 for (;!control_client_terminate;) {
1407 r = read(sock, &exitval, sizeof(exitval));
1409 debug2("Received EOF from master");
1413 debug2("Received exit status from master %d", exitval);
1414 if (r == -1 && errno != EINTR)
1415 fatal("%s: read %s", __func__, strerror(errno));
1418 if (control_client_terminate)
1419 debug2("Exiting on signal %d", control_client_terminate);
1425 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1426 fprintf(stderr, "Connection to master closed.\r\n");