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;
475 options.none_switch = 0;
479 line = xstrdup(optarg);
480 if (process_config_line(&options, host ? host : "",
481 line, "command-line", 0, &dummy) != 0)
489 if (options.control_path != NULL)
490 free(options.control_path);
491 options.control_path = xstrdup(optarg);
494 options.bind_address = optarg;
500 /* make sure we can't turn on the none_switch */
501 /* if they try to force a no tty flag on a tty session */
503 options.none_switch = 1;
515 if (ac > 0 && !host && **av != '-') {
516 if (strrchr(*av, '@')) {
518 cp = strrchr(p, '@');
519 if (cp == NULL || cp == p)
527 optind = optreset = 1;
533 /* Check that we got a host name. */
537 SSLeay_add_all_algorithms();
538 ERR_load_crypto_strings();
540 /* Initialize the command to execute on remote host. */
541 buffer_init(&command);
544 * Save the command to execute on the remote host in a buffer. There
545 * is no limit on the length of the command, except by the maximum
546 * packet size. Also sets the tty flag if there is no command.
549 /* No command specified - execute shell on a tty. */
551 if (subsystem_flag) {
553 "You must specify a subsystem to invoke.\n");
557 /* A command has been specified. Store it into the buffer. */
558 for (i = 0; i < ac; i++) {
560 buffer_append(&command, " ", 1);
561 buffer_append(&command, av[i], strlen(av[i]));
565 /* Cannot fork to background if no command. */
566 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
567 fatal("Cannot fork into background without a command to execute.");
569 /* Allocate a tty by default if no command specified. */
570 if (buffer_len(&command) == 0)
576 /* Do not allocate a tty if stdin is not a tty. */
577 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
579 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
584 * Initialize "log" output. Since we are the client all output
585 * actually goes to stderr.
587 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
588 SYSLOG_FACILITY_USER, 1);
591 * Read per-user configuration file. Ignore the system wide config
592 * file if the user specifies a config file on the command line.
594 if (config != NULL) {
595 if (!read_config_file(config, host, &options, 0))
596 fatal("Can't open user config file %.100s: "
597 "%.100s", config, strerror(errno));
599 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
600 _PATH_SSH_USER_CONFFILE);
601 (void)read_config_file(buf, host, &options, 1);
603 /* Read systemwide configuration file after use config. */
604 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
608 /* Fill configuration defaults. */
609 fill_default_options(&options);
611 channel_set_af(options.address_family);
614 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
618 if (options.user == NULL)
619 options.user = xstrdup(pw->pw_name);
621 if (options.hostname != NULL)
622 host = options.hostname;
624 /* force lowercase for hostkey matching */
625 if (options.host_key_alias != NULL) {
626 for (p = options.host_key_alias; *p; p++)
631 /* Get default port if port has not been set. */
632 if (options.port == 0) {
633 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
634 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
637 if (options.proxy_command != NULL &&
638 strcmp(options.proxy_command, "none") == 0)
639 options.proxy_command = NULL;
640 if (options.control_path != NULL &&
641 strcmp(options.control_path, "none") == 0)
642 options.control_path = NULL;
644 if (options.control_path != NULL) {
645 snprintf(buf, sizeof(buf), "%d", options.port);
646 cp = tilde_expand_filename(options.control_path,
648 options.control_path = percent_expand(cp, "p", buf, "h", host,
649 "r", options.user, (char *)NULL);
652 if (mux_command != 0 && options.control_path == NULL)
653 fatal("No ControlPath specified for \"-O\" command");
654 if (options.control_path != NULL)
655 control_client(options.control_path);
657 /* Open a connection to the remote host. */
658 if (ssh_connect(host, &hostaddr, options.port,
659 options.address_family, options.connection_attempts,
661 options.use_privileged_port,
663 original_effective_uid == 0 && options.use_privileged_port,
665 options.proxy_command) != 0)
669 * If we successfully made the connection, load the host private key
670 * in case we will need it later for combined rsa-rhosts
671 * authentication. This must be done before releasing extra
672 * privileges, because the file is only readable by root.
673 * If we cannot access the private keys, load the public keys
674 * instead and try to execute the ssh-keysign helper instead.
676 sensitive_data.nkeys = 0;
677 sensitive_data.keys = NULL;
678 sensitive_data.external_keysign = 0;
679 if (options.rhosts_rsa_authentication ||
680 options.hostbased_authentication) {
681 sensitive_data.nkeys = 3;
682 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
686 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
687 _PATH_HOST_KEY_FILE, "", NULL);
688 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
689 _PATH_HOST_DSA_KEY_FILE, "", NULL);
690 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
691 _PATH_HOST_RSA_KEY_FILE, "", NULL);
694 if (options.hostbased_authentication == 1 &&
695 sensitive_data.keys[0] == NULL &&
696 sensitive_data.keys[1] == NULL &&
697 sensitive_data.keys[2] == NULL) {
698 sensitive_data.keys[1] = key_load_public(
699 _PATH_HOST_DSA_KEY_FILE, NULL);
700 sensitive_data.keys[2] = key_load_public(
701 _PATH_HOST_RSA_KEY_FILE, NULL);
702 sensitive_data.external_keysign = 1;
706 * Get rid of any extra privileges that we may have. We will no
707 * longer need them. Also, extra privileges could make it very hard
708 * to read identity files and other non-world-readable files from the
709 * user's home directory if it happens to be on a NFS volume where
710 * root is mapped to nobody.
712 if (original_effective_uid == 0) {
714 permanently_set_uid(pw);
718 * Now that we are back to our own permissions, create ~/.ssh
719 * directory if it doesn't already exist.
721 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
722 if (stat(buf, &st) < 0)
723 if (mkdir(buf, 0700) < 0)
724 error("Could not create directory '%.200s'.", buf);
726 /* load options.identity_files */
727 load_public_identity_files();
729 /* Expand ~ in known host file names. */
731 options.system_hostfile =
732 tilde_expand_filename(options.system_hostfile, original_real_uid);
733 options.user_hostfile =
734 tilde_expand_filename(options.user_hostfile, original_real_uid);
735 options.system_hostfile2 =
736 tilde_expand_filename(options.system_hostfile2, original_real_uid);
737 options.user_hostfile2 =
738 tilde_expand_filename(options.user_hostfile2, original_real_uid);
740 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
742 /* Log into the remote system. This never returns if the login fails. */
743 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
745 /* We no longer need the private host keys. Clear them now. */
746 if (sensitive_data.nkeys != 0) {
747 for (i = 0; i < sensitive_data.nkeys; i++) {
748 if (sensitive_data.keys[i] != NULL) {
749 /* Destroys contents safely */
750 debug3("clear hostkey %d", i);
751 key_free(sensitive_data.keys[i]);
752 sensitive_data.keys[i] = NULL;
755 xfree(sensitive_data.keys);
757 for (i = 0; i < options.num_identity_files; i++) {
758 if (options.identity_files[i]) {
759 xfree(options.identity_files[i]);
760 options.identity_files[i] = NULL;
762 if (options.identity_keys[i]) {
763 key_free(options.identity_keys[i]);
764 options.identity_keys[i] = NULL;
768 exit_status = compat20 ? ssh_session2() : ssh_session();
771 if (options.control_path != NULL && control_fd != -1)
772 unlink(options.control_path);
775 * Send SIGHUP to proxy command if used. We don't wait() in
776 * case it hangs and instead rely on init to reap the child
778 if (proxy_command_pid > 1)
779 kill(proxy_command_pid, SIGHUP);
785 ssh_init_forwarding(void)
790 /* Initiate local TCP/IP port forwardings. */
791 for (i = 0; i < options.num_local_forwards; i++) {
792 debug("Local connections to %.200s:%d forwarded to remote "
794 (options.local_forwards[i].listen_host == NULL) ?
795 (options.gateway_ports ? "*" : "LOCALHOST") :
796 options.local_forwards[i].listen_host,
797 options.local_forwards[i].listen_port,
798 options.local_forwards[i].connect_host,
799 options.local_forwards[i].connect_port);
800 success += channel_setup_local_fwd_listener(
801 options.local_forwards[i].listen_host,
802 options.local_forwards[i].listen_port,
803 options.local_forwards[i].connect_host,
804 options.local_forwards[i].connect_port,
805 options.gateway_ports, options.hpn_disabled,
806 options.hpn_buffer_size);
808 if (i > 0 && success == 0)
809 error("Could not request local forwarding.");
811 /* Initiate remote TCP/IP port forwardings. */
812 for (i = 0; i < options.num_remote_forwards; i++) {
813 debug("Remote connections from %.200s:%d forwarded to "
814 "local address %.200s:%d",
815 (options.remote_forwards[i].listen_host == NULL) ?
816 "LOCALHOST" : options.remote_forwards[i].listen_host,
817 options.remote_forwards[i].listen_port,
818 options.remote_forwards[i].connect_host,
819 options.remote_forwards[i].connect_port);
820 channel_request_remote_forwarding(
821 options.remote_forwards[i].listen_host,
822 options.remote_forwards[i].listen_port,
823 options.remote_forwards[i].connect_host,
824 options.remote_forwards[i].connect_port);
829 check_agent_present(void)
831 if (options.forward_agent) {
832 /* Clear agent forwarding if we don't have an agent. */
833 if (!ssh_agent_present())
834 options.forward_agent = 0;
848 /* Enable compression if requested. */
849 if (options.compression) {
850 debug("Requesting compression at level %d.", options.compression_level);
852 if (options.compression_level < 1 || options.compression_level > 9)
853 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
855 /* Send the request. */
856 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
857 packet_put_int(options.compression_level);
860 type = packet_read();
861 if (type == SSH_SMSG_SUCCESS)
862 packet_start_compression(options.compression_level);
863 else if (type == SSH_SMSG_FAILURE)
864 logit("Warning: Remote host refused compression.");
866 packet_disconnect("Protocol error waiting for compression response.");
868 /* Allocate a pseudo tty if appropriate. */
870 debug("Requesting pty.");
872 /* Start the packet. */
873 packet_start(SSH_CMSG_REQUEST_PTY);
875 /* Store TERM in the packet. There is no limit on the
876 length of the string. */
880 packet_put_cstring(cp);
882 /* Store window size in the packet. */
883 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
884 memset(&ws, 0, sizeof(ws));
885 packet_put_int(ws.ws_row);
886 packet_put_int(ws.ws_col);
887 packet_put_int(ws.ws_xpixel);
888 packet_put_int(ws.ws_ypixel);
890 /* Store tty modes in the packet. */
891 tty_make_modes(fileno(stdin), NULL);
893 /* Send the packet, and wait for it to leave. */
897 /* Read response from the server. */
898 type = packet_read();
899 if (type == SSH_SMSG_SUCCESS) {
902 } else if (type == SSH_SMSG_FAILURE)
903 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
905 packet_disconnect("Protocol error waiting for pty request response.");
907 /* Request X11 forwarding if enabled and DISPLAY is set. */
908 display = getenv("DISPLAY");
909 if (options.forward_x11 && display != NULL) {
911 /* Get reasonable local authentication information. */
912 client_x11_get_proto(display, options.xauth_location,
913 options.forward_x11_trusted, &proto, &data);
914 /* Request forwarding with authentication spoofing. */
915 debug("Requesting X11 forwarding with authentication spoofing.");
916 x11_request_forwarding_with_spoofing(0, display, proto, data);
918 /* Read response from the server. */
919 type = packet_read();
920 if (type == SSH_SMSG_SUCCESS) {
922 } else if (type == SSH_SMSG_FAILURE) {
923 logit("Warning: Remote host denied X11 forwarding.");
925 packet_disconnect("Protocol error waiting for X11 forwarding");
928 /* Tell the packet module whether this is an interactive session. */
929 packet_set_interactive(interactive);
931 /* Request authentication agent forwarding if appropriate. */
932 check_agent_present();
934 if (options.forward_agent) {
935 debug("Requesting authentication agent forwarding.");
936 auth_request_forwarding();
938 /* Read response from the server. */
939 type = packet_read();
941 if (type != SSH_SMSG_SUCCESS)
942 logit("Warning: Remote host denied authentication agent forwarding.");
945 /* Initiate port forwardings. */
946 ssh_init_forwarding();
948 /* If requested, let ssh continue in the background. */
949 if (fork_after_authentication_flag)
950 if (daemon(1, 1) < 0)
951 fatal("daemon() failed: %.200s", strerror(errno));
954 * If a command was specified on the command line, execute the
955 * command now. Otherwise request the server to start a shell.
957 if (buffer_len(&command) > 0) {
958 int len = buffer_len(&command);
961 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
962 packet_start(SSH_CMSG_EXEC_CMD);
963 packet_put_string(buffer_ptr(&command), buffer_len(&command));
967 debug("Requesting shell.");
968 packet_start(SSH_CMSG_EXEC_SHELL);
973 /* Enter the interactive session. */
974 return client_loop(have_tty, tty_flag ?
975 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
979 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
983 id = packet_get_int();
984 len = buffer_len(&command);
988 if (type == SSH2_MSG_CHANNEL_FAILURE)
989 fatal("Request for subsystem '%.*s' failed on channel %d",
990 len, (u_char *)buffer_ptr(&command), id);
994 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
998 i = client_global_request_id++;
999 if (i >= options.num_remote_forwards)
1001 debug("remote forward %s for: listen %d, connect %s:%d",
1002 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1003 options.remote_forwards[i].listen_port,
1004 options.remote_forwards[i].connect_host,
1005 options.remote_forwards[i].connect_port);
1006 if (type == SSH2_MSG_REQUEST_FAILURE)
1007 logit("Warning: remote port forwarding failed for listen "
1008 "port %d", options.remote_forwards[i].listen_port);
1012 ssh_control_listener(void)
1014 struct sockaddr_un addr;
1018 if (options.control_path == NULL ||
1019 options.control_master == SSHCTL_MASTER_NO)
1022 debug("setting up multiplex master socket");
1024 memset(&addr, '\0', sizeof(addr));
1025 addr.sun_family = AF_UNIX;
1026 addr_len = offsetof(struct sockaddr_un, sun_path) +
1027 strlen(options.control_path) + 1;
1029 if (strlcpy(addr.sun_path, options.control_path,
1030 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1031 fatal("ControlPath too long");
1033 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1034 fatal("%s socket(): %s", __func__, strerror(errno));
1036 old_umask = umask(0177);
1037 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1039 if (errno == EINVAL || errno == EADDRINUSE)
1040 fatal("ControlSocket %s already exists",
1041 options.control_path);
1043 fatal("%s bind(): %s", __func__, strerror(errno));
1047 if (listen(control_fd, 64) == -1)
1048 fatal("%s listen(): %s", __func__, strerror(errno));
1050 set_nonblock(control_fd);
1053 /* request pty/x11/agent/tcpfwd/shell for channel */
1055 ssh_session2_setup(int id, void *arg)
1057 extern char **environ;
1058 const char *display;
1059 int interactive = tty_flag;
1061 display = getenv("DISPLAY");
1062 if (options.forward_x11 && display != NULL) {
1064 /* Get reasonable local authentication information. */
1065 client_x11_get_proto(display, options.xauth_location,
1066 options.forward_x11_trusted, &proto, &data);
1067 /* Request forwarding with authentication spoofing. */
1068 debug("Requesting X11 forwarding with authentication spoofing.");
1069 x11_request_forwarding_with_spoofing(id, display, proto, data);
1071 /* XXX wait for reply */
1074 check_agent_present();
1075 if (options.forward_agent) {
1076 debug("Requesting authentication agent forwarding.");
1077 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1081 if (options.tun_open != SSH_TUNMODE_NO) {
1085 debug("Requesting tun.");
1086 if ((fd = tun_open(options.tun_local,
1087 options.tun_open)) >= 0) {
1088 if(options.hpn_disabled)
1089 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1090 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1093 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1094 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1097 #if defined(SSH_TUN_FILTER)
1098 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1099 channel_register_filter(c->self, sys_tun_infilter,
1102 packet_start(SSH2_MSG_CHANNEL_OPEN);
1103 packet_put_cstring("tun@openssh.com");
1104 packet_put_int(c->self);
1105 packet_put_int(c->local_window_max);
1106 packet_put_int(c->local_maxpacket);
1107 packet_put_int(options.tun_open);
1108 packet_put_int(options.tun_remote);
1113 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1114 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1116 packet_set_interactive(interactive);
1119 /* open new channel for a session */
1121 ssh_session2_open(void)
1124 int window, packetmax, in, out, err;
1126 if (stdin_null_flag) {
1127 in = open(_PATH_DEVNULL, O_RDONLY);
1129 in = dup(STDIN_FILENO);
1131 out = dup(STDOUT_FILENO);
1132 err = dup(STDERR_FILENO);
1134 if (in < 0 || out < 0 || err < 0)
1135 fatal("dup() in/out/err failed");
1137 /* enable nonblocking unless tty */
1145 if(options.hpn_disabled)
1146 window = CHAN_SES_WINDOW_DEFAULT;
1148 window = options.hpn_buffer_size;
1149 packetmax = CHAN_SES_PACKET_DEFAULT;
1151 window = 4*CHAN_SES_PACKET_DEFAULT;
1156 "session", SSH_CHANNEL_OPENING, in, out, err,
1157 window, packetmax, CHAN_EXTENDED_WRITE,
1158 "client-session", /*nonblock*/0);
1159 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1160 c->dynamic_window = 1;
1161 debug ("Enabled Dynamic Window Scaling\n");
1163 debug3("ssh_session2_open: channel_new: %d", c->self);
1165 channel_send_open(c->self);
1167 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1177 /* XXX should be pre-session */
1178 ssh_init_forwarding();
1179 ssh_control_listener();
1181 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1182 id = ssh_session2_open();
1184 /* Execute a local command */
1185 if (options.local_command != NULL &&
1186 options.permit_local_command)
1187 ssh_local_cmd(options.local_command);
1189 /* If requested, let ssh continue in the background. */
1190 if (fork_after_authentication_flag)
1191 if (daemon(1, 1) < 0)
1192 fatal("daemon() failed: %.200s", strerror(errno));
1194 return client_loop(tty_flag, tty_flag ?
1195 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1199 load_public_identity_files(void)
1207 if (options.smartcard_device != NULL &&
1208 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1209 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1211 for (i = 0; keys[i] != NULL; i++) {
1213 memmove(&options.identity_files[1], &options.identity_files[0],
1214 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1215 memmove(&options.identity_keys[1], &options.identity_keys[0],
1216 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1217 options.num_identity_files++;
1218 options.identity_keys[0] = keys[i];
1219 options.identity_files[0] = sc_get_key_label(keys[i]);
1221 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1222 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1226 #endif /* SMARTCARD */
1227 for (; i < options.num_identity_files; i++) {
1228 filename = tilde_expand_filename(options.identity_files[i],
1230 public = key_load_public(filename, NULL);
1231 debug("identity file %s type %d", filename,
1232 public ? public->type : -1);
1233 xfree(options.identity_files[i]);
1234 options.identity_files[i] = filename;
1235 options.identity_keys[i] = public;
1240 control_client_sighandler(int signo)
1242 control_client_terminate = signo;
1246 control_client_sigrelay(int signo)
1248 if (control_server_pid > 1)
1249 kill(control_server_pid, signo);
1253 env_permitted(char *env)
1256 char name[1024], *cp;
1258 strlcpy(name, env, sizeof(name));
1259 if ((cp = strchr(name, '=')) == NULL)
1264 for (i = 0; i < options.num_send_env; i++)
1265 if (match_pattern(name, options.send_env[i]))
1272 control_client(const char *path)
1274 struct sockaddr_un addr;
1275 int i, r, fd, sock, exitval, num_env, addr_len;
1278 extern char **environ;
1281 if (mux_command == 0)
1282 mux_command = SSHMUX_COMMAND_OPEN;
1284 switch (options.control_master) {
1285 case SSHCTL_MASTER_AUTO:
1286 case SSHCTL_MASTER_AUTO_ASK:
1287 debug("auto-mux: Trying existing master");
1289 case SSHCTL_MASTER_NO:
1295 memset(&addr, '\0', sizeof(addr));
1296 addr.sun_family = AF_UNIX;
1297 addr_len = offsetof(struct sockaddr_un, sun_path) +
1300 if (strlcpy(addr.sun_path, path,
1301 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1302 fatal("ControlPath too long");
1304 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1305 fatal("%s socket(): %s", __func__, strerror(errno));
1307 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1308 if (mux_command != SSHMUX_COMMAND_OPEN) {
1309 fatal("Control socket connect(%.100s): %s", path,
1312 if (errno == ENOENT)
1313 debug("Control socket \"%.100s\" does not exist", path);
1315 error("Control socket connect(%.100s): %s", path,
1322 if (stdin_null_flag) {
1323 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1324 fatal("open(/dev/null): %s", strerror(errno));
1325 if (dup2(fd, STDIN_FILENO) == -1)
1326 fatal("dup2: %s", strerror(errno));
1327 if (fd > STDERR_FILENO)
1331 term = getenv("TERM");
1335 flags |= SSHMUX_FLAG_TTY;
1337 flags |= SSHMUX_FLAG_SUBSYS;
1338 if (options.forward_x11)
1339 flags |= SSHMUX_FLAG_X11_FWD;
1340 if (options.forward_agent)
1341 flags |= SSHMUX_FLAG_AGENT_FWD;
1342 if (options.num_local_forwards > 0)
1343 flags |= SSHMUX_FLAG_PORTFORWARD;
1346 /* Send our command to server */
1347 buffer_put_int(&m, mux_command);
1348 buffer_put_int(&m, flags);
1349 if (options.num_local_forwards > 0)
1351 if (options.local_forwards[0].listen_host == NULL)
1352 buffer_put_string(&m,"LOCALHOST",11);
1354 buffer_put_string(&m,options.local_forwards[0].listen_host,512);
1355 buffer_put_int(&m,options.local_forwards[0].listen_port);
1356 buffer_put_string(&m,options.local_forwards[0].connect_host,512);
1357 buffer_put_int(&m,options.local_forwards[0].connect_port);
1359 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1360 fatal("%s: msg_send", __func__);
1363 /* Get authorisation status and PID of controlee */
1364 if (ssh_msg_recv(sock, &m) == -1)
1365 fatal("%s: msg_recv", __func__);
1366 if (buffer_get_char(&m) != SSHMUX_VER)
1367 fatal("%s: wrong version", __func__);
1368 if (buffer_get_int(&m) != 1)
1369 fatal("Connection to master denied");
1370 control_server_pid = buffer_get_int(&m);
1374 switch (mux_command) {
1375 case SSHMUX_COMMAND_ALIVE_CHECK:
1376 fprintf(stderr, "Master running (pid=%d)\r\n",
1377 control_server_pid);
1379 case SSHMUX_COMMAND_TERMINATE:
1380 fprintf(stderr, "Exit request sent.\r\n");
1382 case SSHMUX_COMMAND_OPEN:
1383 /* continue below */
1386 fatal("silly mux_command %d", mux_command);
1389 /* SSHMUX_COMMAND_OPEN */
1390 buffer_put_cstring(&m, term ? term : "");
1391 buffer_append(&command, "\0", 1);
1392 buffer_put_cstring(&m, buffer_ptr(&command));
1394 if (options.num_send_env == 0 || environ == NULL) {
1395 buffer_put_int(&m, 0);
1397 /* Pass environment */
1399 for (i = 0; environ[i] != NULL; i++)
1400 if (env_permitted(environ[i]))
1401 num_env++; /* Count */
1403 buffer_put_int(&m, num_env);
1405 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1406 if (env_permitted(environ[i])) {
1408 buffer_put_cstring(&m, environ[i]);
1412 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1413 fatal("%s: msg_send", __func__);
1415 mm_send_fd(sock, STDIN_FILENO);
1416 mm_send_fd(sock, STDOUT_FILENO);
1417 mm_send_fd(sock, STDERR_FILENO);
1419 /* Wait for reply, so master has a chance to gather ttymodes */
1421 if (ssh_msg_recv(sock, &m) == -1)
1422 fatal("%s: msg_recv", __func__);
1423 if (buffer_get_char(&m) != SSHMUX_VER)
1424 fatal("%s: wrong version", __func__);
1427 signal(SIGHUP, control_client_sighandler);
1428 signal(SIGINT, control_client_sighandler);
1429 signal(SIGTERM, control_client_sighandler);
1430 signal(SIGWINCH, control_client_sigrelay);
1435 /* Stick around until the controlee closes the client_fd */
1437 for (;!control_client_terminate;) {
1438 r = read(sock, &exitval, sizeof(exitval));
1440 debug2("Received EOF from master");
1444 debug2("Received exit status from master %d", exitval);
1445 if (r == -1 && errno != EINTR)
1446 fatal("%s: read %s", __func__, strerror(errno));
1449 if (control_client_terminate)
1450 debug2("Exiting on signal %d", control_client_terminate);
1456 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1457 fprintf(stderr, "Connection to master closed.\r\n");