1 /* $OpenBSD: ssh.c,v 1.301 2007/08/07 07:32:53 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
70 #include <netinet/in.h>
71 #include <arpa/inet.h>
73 #include <openssl/evp.h>
74 #include <openssl/err.h>
88 #include "pathnames.h"
90 #include "clientloop.h"
93 #include "sshconnect.h"
100 #include "monitor_fdpass.h"
108 extern char *__progname;
110 /* Flag indicating whether debug mode is on. This can be set on the command line. */
113 /* Flag indicating whether a tty should be allocated */
116 int force_tty_flag = 0;
118 /* don't exec a shell */
119 int no_shell_flag = 0;
122 * Flag indicating that nothing should be read from stdin. This can be set
123 * on the command line.
125 int stdin_null_flag = 0;
128 * Flag indicating that ssh should fork after authentication. This is useful
129 * so that the passphrase can be entered manually, and then ssh goes to the
132 int fork_after_authentication_flag = 0;
135 * General data structure for command line options and options configurable
136 * in configuration files. See readconf.h.
140 /* optional user configfile */
144 * Name of the host we are connecting to. This is the name given on the
145 * command line, or the HostName specified for the user-supplied name in a
146 * configuration file.
150 /* socket address the host resolves to */
151 struct sockaddr_storage hostaddr;
153 /* Private host keys. */
154 Sensitive sensitive_data;
156 /* Original real UID. */
157 uid_t original_real_uid;
158 uid_t original_effective_uid;
160 /* command to be executed */
163 /* Should we execute a command or invoke a subsystem? */
164 int subsystem_flag = 0;
166 /* # of replies received for global requests */
167 static int client_global_request_id = 0;
169 /* pid of proxycommand child process */
170 pid_t proxy_command_pid = 0;
172 /* fd to control socket */
175 /* Multiplexing control command */
176 static u_int mux_command = 0;
178 /* Only used in control client mode */
179 volatile sig_atomic_t control_client_terminate = 0;
180 u_int control_server_pid = 0;
182 /* Prints a help message to the user. This function never returns. */
188 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
189 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
190 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
191 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
192 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
193 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
198 static int ssh_session(void);
199 static int ssh_session2(void);
200 static void load_public_identity_files(void);
201 static void control_client(const char *path);
204 * Main program for the ssh client.
207 main(int ac, char **av)
209 int i, opt, exit_status;
210 char *p, *cp, *line, buf[256];
214 extern int optind, optreset;
219 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
222 __progname = ssh_get_progname(av[0]);
226 * Save the original real uid. It will be needed later (uid-swapping
227 * may clobber the real uid).
229 original_real_uid = getuid();
230 original_effective_uid = geteuid();
233 * Use uid-swapping to give up root privileges for the duration of
234 * option processing. We will re-instantiate the rights when we are
235 * ready to create the privileged port, and will permanently drop
236 * them when the port has been created (actually, when the connection
237 * has been made, as we may need to create the port several times).
241 #ifdef HAVE_SETRLIMIT
242 /* If we are installed setuid root be careful to not drop core. */
243 if (original_real_uid != original_effective_uid) {
245 rlim.rlim_cur = rlim.rlim_max = 0;
246 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
247 fatal("setrlimit failed: %.100s", strerror(errno));
251 pw = getpwuid(original_real_uid);
253 logit("You don't exist, go away!");
256 /* Take a copy of the returned structure. */
260 * Set our umask to something reasonable, as some files are created
261 * with the default umask. This will make them world-readable but
262 * writable only by the owner, which is ok for all files for which we
263 * don't set the modes explicitly.
267 /* Initialize option structure to indicate that no values have been set. */
268 initialize_options(&options);
270 /* Parse command-line arguments. */
274 while ((opt = getopt(ac, av,
275 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:KL:MNO:PR:S:TVw:XY")) != -1) {
278 options.protocol = SSH_PROTO_1;
281 options.protocol = SSH_PROTO_2;
284 options.address_family = AF_INET;
287 options.address_family = AF_INET6;
293 fork_after_authentication_flag = 1;
297 options.forward_x11 = 0;
300 options.forward_x11 = 1;
303 options.forward_x11 = 1;
304 options.forward_x11_trusted = 1;
307 options.gateway_ports = 1;
310 if (strcmp(optarg, "check") == 0)
311 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
312 else if (strcmp(optarg, "exit") == 0)
313 mux_command = SSHMUX_COMMAND_TERMINATE;
315 fatal("Invalid multiplex command.");
317 case 'P': /* deprecated */
318 options.use_privileged_port = 0;
321 options.forward_agent = 0;
324 options.forward_agent = 1;
327 options.gss_deleg_creds = 0;
330 options.gss_authentication = 1;
331 options.gss_deleg_creds = 1;
334 if (stat(optarg, &st) < 0) {
335 fprintf(stderr, "Warning: Identity file %s "
336 "not accessible: %s.\n", optarg,
340 if (options.num_identity_files >=
341 SSH_MAX_IDENTITY_FILES)
342 fatal("Too many identity files specified "
343 "(max %d)", SSH_MAX_IDENTITY_FILES);
344 options.identity_files[options.num_identity_files++] =
349 options.smartcard_device = xstrdup(optarg);
351 fprintf(stderr, "no support for smartcards.\n");
360 if (debug_flag == 0) {
362 options.log_level = SYSLOG_LEVEL_DEBUG1;
364 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
370 fprintf(stderr, "%s, %s\n",
371 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
376 if (options.tun_open == -1)
377 options.tun_open = SSH_TUNMODE_DEFAULT;
378 options.tun_local = a2tun(optarg, &options.tun_remote);
379 if (options.tun_local == SSH_TUNID_ERR) {
380 fprintf(stderr, "Bad tun device '%s'\n", optarg);
385 options.log_level = SYSLOG_LEVEL_QUIET;
388 if (optarg[0] == '^' && optarg[2] == 0 &&
389 (u_char) optarg[1] >= 64 &&
390 (u_char) optarg[1] < 128)
391 options.escape_char = (u_char) optarg[1] & 31;
392 else if (strlen(optarg) == 1)
393 options.escape_char = (u_char) optarg[0];
394 else if (strcmp(optarg, "none") == 0)
395 options.escape_char = SSH_ESCAPECHAR_NONE;
397 fprintf(stderr, "Bad escape character '%s'.\n",
403 if (ciphers_valid(optarg)) {
405 options.ciphers = xstrdup(optarg);
406 options.cipher = SSH_CIPHER_INVALID;
409 options.cipher = cipher_number(optarg);
410 if (options.cipher == -1) {
412 "Unknown cipher type '%s'\n",
416 if (options.cipher == SSH_CIPHER_3DES)
417 options.ciphers = "3des-cbc";
418 else if (options.cipher == SSH_CIPHER_BLOWFISH)
419 options.ciphers = "blowfish-cbc";
421 options.ciphers = (char *)-1;
425 if (mac_valid(optarg))
426 options.macs = xstrdup(optarg);
428 fprintf(stderr, "Unknown mac type '%s'\n",
434 if (options.control_master == SSHCTL_MASTER_YES)
435 options.control_master = SSHCTL_MASTER_ASK;
437 options.control_master = SSHCTL_MASTER_YES;
440 options.port = a2port(optarg);
441 if (options.port == 0) {
442 fprintf(stderr, "Bad port '%s'\n", optarg);
447 options.user = optarg;
451 if (parse_forward(&fwd, optarg))
452 add_local_forward(&options, &fwd);
455 "Bad local forwarding specification '%s'\n",
462 if (parse_forward(&fwd, optarg)) {
463 add_remote_forward(&options, &fwd);
466 "Bad remote forwarding specification "
473 cp = p = xstrdup(optarg);
474 memset(&fwd, '\0', sizeof(fwd));
475 fwd.connect_host = "socks";
476 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
477 fprintf(stderr, "Bad dynamic forwarding "
478 "specification '%.100s'\n", optarg);
482 fwd.listen_port = a2port(cp);
483 fwd.listen_host = cleanhostname(fwd.listen_host);
485 fwd.listen_port = a2port(fwd.listen_host);
486 fwd.listen_host = NULL;
489 if (fwd.listen_port == 0) {
490 fprintf(stderr, "Bad dynamic port '%s'\n",
494 add_local_forward(&options, &fwd);
499 options.compression = 1;
507 line = xstrdup(optarg);
508 if (process_config_line(&options, host ? host : "",
509 line, "command-line", 0, &dummy) != 0)
515 /* ensure that the user doesn't try to backdoor a */
516 /* null cipher switch on an interactive session */
517 /* so explicitly disable it no matter what */
518 options.none_switch=0;
524 if (options.control_path != NULL)
525 free(options.control_path);
526 options.control_path = xstrdup(optarg);
529 options.bind_address = optarg;
542 if (ac > 0 && !host && **av != '-') {
543 if (strrchr(*av, '@')) {
545 cp = strrchr(p, '@');
546 if (cp == NULL || cp == p)
554 optind = optreset = 1;
560 /* Check that we got a host name. */
564 SSLeay_add_all_algorithms();
565 ERR_load_crypto_strings();
567 /* Initialize the command to execute on remote host. */
568 buffer_init(&command);
571 * Save the command to execute on the remote host in a buffer. There
572 * is no limit on the length of the command, except by the maximum
573 * packet size. Also sets the tty flag if there is no command.
576 /* No command specified - execute shell on a tty. */
578 if (subsystem_flag) {
580 "You must specify a subsystem to invoke.\n");
584 /* A command has been specified. Store it into the buffer. */
585 for (i = 0; i < ac; i++) {
587 buffer_append(&command, " ", 1);
588 buffer_append(&command, av[i], strlen(av[i]));
592 /* Cannot fork to background if no command. */
593 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
594 fatal("Cannot fork into background without a command to execute.");
596 /* Allocate a tty by default if no command specified. */
597 if (buffer_len(&command) == 0)
603 /* Do not allocate a tty if stdin is not a tty. */
604 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
606 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
611 * Initialize "log" output. Since we are the client all output
612 * actually goes to stderr.
614 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
615 SYSLOG_FACILITY_USER, 1);
618 * Read per-user configuration file. Ignore the system wide config
619 * file if the user specifies a config file on the command line.
621 if (config != NULL) {
622 if (!read_config_file(config, host, &options, 0))
623 fatal("Can't open user config file %.100s: "
624 "%.100s", config, strerror(errno));
627 * Since the config file parsing code aborts if it sees
628 * options it doesn't recognize, allow users to put
629 * options specific to compile-time add-ons in alternate
630 * config files so their primary config file will
631 * interoperate SSH versions that don't support those
635 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
636 _PATH_SSH_USER_CONFFILE);
637 (void)read_config_file(buf, host, &options, 1);
639 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
640 _PATH_SSH_USER_CONFFILE);
641 (void)read_config_file(buf, host, &options, 1);
644 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
645 _PATH_SSH_USER_CONFFILE);
646 (void)read_config_file(buf, host, &options, 1);
649 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
650 _PATH_SSH_USER_CONFFILE);
651 (void)read_config_file(buf, host, &options, 1);
653 /* Read systemwide configuration file after use config. */
654 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
658 /* Fill configuration defaults. */
659 fill_default_options(&options);
661 channel_set_af(options.address_family);
664 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
668 if (options.user == NULL) {
669 options.user = xstrdup(pw->pw_name);
670 options.implicit = 1;
672 else options.implicit = 0;
674 if (options.hostname != NULL)
675 host = options.hostname;
677 /* force lowercase for hostkey matching */
678 if (options.host_key_alias != NULL) {
679 for (p = options.host_key_alias; *p; p++)
681 *p = (char)tolower(*p);
684 /* Get default port if port has not been set. */
685 if (options.port == 0) {
686 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
687 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
690 if (options.proxy_command != NULL &&
691 strcmp(options.proxy_command, "none") == 0)
692 options.proxy_command = NULL;
693 if (options.control_path != NULL &&
694 strcmp(options.control_path, "none") == 0)
695 options.control_path = NULL;
697 if (options.control_path != NULL) {
698 char thishost[NI_MAXHOST];
700 if (gethostname(thishost, sizeof(thishost)) == -1)
701 fatal("gethostname: %s", strerror(errno));
702 snprintf(buf, sizeof(buf), "%d", options.port);
703 cp = tilde_expand_filename(options.control_path,
705 options.control_path = percent_expand(cp, "p", buf, "h", host,
706 "r", options.user, "l", thishost, (char *)NULL);
709 if (mux_command != 0 && options.control_path == NULL)
710 fatal("No ControlPath specified for \"-O\" command");
711 if (options.control_path != NULL)
712 control_client(options.control_path);
714 /* Open a connection to the remote host. */
715 if (ssh_connect(host, &hostaddr, options.port,
716 options.address_family, options.connection_attempts,
718 options.use_privileged_port,
720 original_effective_uid == 0 && options.use_privileged_port,
722 options.proxy_command) != 0)
726 * If we successfully made the connection, load the host private key
727 * in case we will need it later for combined rsa-rhosts
728 * authentication. This must be done before releasing extra
729 * privileges, because the file is only readable by root.
730 * If we cannot access the private keys, load the public keys
731 * instead and try to execute the ssh-keysign helper instead.
733 sensitive_data.nkeys = 0;
734 sensitive_data.keys = NULL;
735 sensitive_data.external_keysign = 0;
736 if (options.rhosts_rsa_authentication ||
737 options.hostbased_authentication) {
738 sensitive_data.nkeys = 3;
739 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
743 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
744 _PATH_HOST_KEY_FILE, "", NULL, NULL);
745 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
746 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
747 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
748 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
751 if (options.hostbased_authentication == 1 &&
752 sensitive_data.keys[0] == NULL &&
753 sensitive_data.keys[1] == NULL &&
754 sensitive_data.keys[2] == NULL) {
755 sensitive_data.keys[1] = key_load_public(
756 _PATH_HOST_DSA_KEY_FILE, NULL);
757 sensitive_data.keys[2] = key_load_public(
758 _PATH_HOST_RSA_KEY_FILE, NULL);
759 sensitive_data.external_keysign = 1;
763 * Get rid of any extra privileges that we may have. We will no
764 * longer need them. Also, extra privileges could make it very hard
765 * to read identity files and other non-world-readable files from the
766 * user's home directory if it happens to be on a NFS volume where
767 * root is mapped to nobody.
769 if (original_effective_uid == 0) {
771 permanently_set_uid(pw);
775 * Now that we are back to our own permissions, create ~/.ssh
776 * directory if it doesn't already exist.
778 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
779 if (stat(buf, &st) < 0)
780 if (mkdir(buf, 0700) < 0)
781 error("Could not create directory '%.200s'.", buf);
783 /* load options.identity_files */
784 load_public_identity_files();
786 /* Expand ~ in known host file names. */
788 options.system_hostfile =
789 tilde_expand_filename(options.system_hostfile, original_real_uid);
790 options.user_hostfile =
791 tilde_expand_filename(options.user_hostfile, original_real_uid);
792 options.system_hostfile2 =
793 tilde_expand_filename(options.system_hostfile2, original_real_uid);
794 options.user_hostfile2 =
795 tilde_expand_filename(options.user_hostfile2, original_real_uid);
797 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
799 /* Log into the remote system. This never returns if the login fails. */
800 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
802 /* We no longer need the private host keys. Clear them now. */
803 if (sensitive_data.nkeys != 0) {
804 for (i = 0; i < sensitive_data.nkeys; i++) {
805 if (sensitive_data.keys[i] != NULL) {
806 /* Destroys contents safely */
807 debug3("clear hostkey %d", i);
808 key_free(sensitive_data.keys[i]);
809 sensitive_data.keys[i] = NULL;
812 xfree(sensitive_data.keys);
814 for (i = 0; i < options.num_identity_files; i++) {
815 if (options.identity_files[i]) {
816 xfree(options.identity_files[i]);
817 options.identity_files[i] = NULL;
819 if (options.identity_keys[i]) {
820 key_free(options.identity_keys[i]);
821 options.identity_keys[i] = NULL;
825 exit_status = compat20 ? ssh_session2() : ssh_session();
828 if (options.control_path != NULL && control_fd != -1)
829 unlink(options.control_path);
832 * Send SIGHUP to proxy command if used. We don't wait() in
833 * case it hangs and instead rely on init to reap the child
835 if (proxy_command_pid > 1)
836 kill(proxy_command_pid, SIGHUP);
842 ssh_init_forwarding(void)
847 /* Initiate local TCP/IP port forwardings. */
848 for (i = 0; i < options.num_local_forwards; i++) {
849 debug("Local connections to %.200s:%d forwarded to remote "
851 (options.local_forwards[i].listen_host == NULL) ?
852 (options.gateway_ports ? "*" : "LOCALHOST") :
853 options.local_forwards[i].listen_host,
854 options.local_forwards[i].listen_port,
855 options.local_forwards[i].connect_host,
856 options.local_forwards[i].connect_port);
857 success += channel_setup_local_fwd_listener(
858 options.local_forwards[i].listen_host,
859 options.local_forwards[i].listen_port,
860 options.local_forwards[i].connect_host,
861 options.local_forwards[i].connect_port,
862 options.gateway_ports, options.hpn_disabled,
863 options.hpn_buffer_size);
865 if (i > 0 && success != i && options.exit_on_forward_failure)
866 fatal("Could not request local forwarding.");
867 if (i > 0 && success == 0)
868 error("Could not request local forwarding.");
870 /* Initiate remote TCP/IP port forwardings. */
871 for (i = 0; i < options.num_remote_forwards; i++) {
872 debug("Remote connections from %.200s:%d forwarded to "
873 "local address %.200s:%d",
874 (options.remote_forwards[i].listen_host == NULL) ?
875 "LOCALHOST" : options.remote_forwards[i].listen_host,
876 options.remote_forwards[i].listen_port,
877 options.remote_forwards[i].connect_host,
878 options.remote_forwards[i].connect_port);
879 if (channel_request_remote_forwarding(
880 options.remote_forwards[i].listen_host,
881 options.remote_forwards[i].listen_port,
882 options.remote_forwards[i].connect_host,
883 options.remote_forwards[i].connect_port) < 0) {
884 if (options.exit_on_forward_failure)
885 fatal("Could not request remote forwarding.");
887 logit("Warning: Could not request remote "
892 /* Initiate tunnel forwarding. */
893 if (options.tun_open != SSH_TUNMODE_NO) {
894 if (client_request_tun_fwd(options.tun_open,
895 options.tun_local, options.tun_remote) == -1) {
896 if (options.exit_on_forward_failure)
897 fatal("Could not request tunnel forwarding.");
899 error("Could not request tunnel forwarding.");
905 check_agent_present(void)
907 if (options.forward_agent) {
908 /* Clear agent forwarding if we don't have an agent. */
909 if (!ssh_agent_present())
910 options.forward_agent = 0;
924 /* Enable compression if requested. */
925 if (options.compression) {
926 debug("Requesting compression at level %d.", options.compression_level);
928 if (options.compression_level < 1 || options.compression_level > 9)
929 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
931 /* Send the request. */
932 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
933 packet_put_int(options.compression_level);
936 type = packet_read();
937 if (type == SSH_SMSG_SUCCESS)
938 packet_start_compression(options.compression_level);
939 else if (type == SSH_SMSG_FAILURE)
940 logit("Warning: Remote host refused compression.");
942 packet_disconnect("Protocol error waiting for compression response.");
944 /* Allocate a pseudo tty if appropriate. */
946 debug("Requesting pty.");
948 /* Start the packet. */
949 packet_start(SSH_CMSG_REQUEST_PTY);
951 /* Store TERM in the packet. There is no limit on the
952 length of the string. */
956 packet_put_cstring(cp);
958 /* Store window size in the packet. */
959 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
960 memset(&ws, 0, sizeof(ws));
961 packet_put_int((u_int)ws.ws_row);
962 packet_put_int((u_int)ws.ws_col);
963 packet_put_int((u_int)ws.ws_xpixel);
964 packet_put_int((u_int)ws.ws_ypixel);
966 /* Store tty modes in the packet. */
967 tty_make_modes(fileno(stdin), NULL);
969 /* Send the packet, and wait for it to leave. */
973 /* Read response from the server. */
974 type = packet_read();
975 if (type == SSH_SMSG_SUCCESS) {
978 } else if (type == SSH_SMSG_FAILURE)
979 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
981 packet_disconnect("Protocol error waiting for pty request response.");
983 /* Request X11 forwarding if enabled and DISPLAY is set. */
984 display = getenv("DISPLAY");
985 if (options.forward_x11 && display != NULL) {
987 /* Get reasonable local authentication information. */
988 client_x11_get_proto(display, options.xauth_location,
989 options.forward_x11_trusted, &proto, &data);
990 /* Request forwarding with authentication spoofing. */
991 debug("Requesting X11 forwarding with authentication spoofing.");
992 x11_request_forwarding_with_spoofing(0, display, proto, data);
994 /* Read response from the server. */
995 type = packet_read();
996 if (type == SSH_SMSG_SUCCESS) {
998 } else if (type == SSH_SMSG_FAILURE) {
999 logit("Warning: Remote host denied X11 forwarding.");
1001 packet_disconnect("Protocol error waiting for X11 forwarding");
1004 /* Tell the packet module whether this is an interactive session. */
1005 packet_set_interactive(interactive);
1007 /* Request authentication agent forwarding if appropriate. */
1008 check_agent_present();
1010 if (options.forward_agent) {
1011 debug("Requesting authentication agent forwarding.");
1012 auth_request_forwarding();
1014 /* Read response from the server. */
1015 type = packet_read();
1017 if (type != SSH_SMSG_SUCCESS)
1018 logit("Warning: Remote host denied authentication agent forwarding.");
1021 /* Initiate port forwardings. */
1022 ssh_init_forwarding();
1024 /* If requested, let ssh continue in the background. */
1025 if (fork_after_authentication_flag)
1026 if (daemon(1, 1) < 0)
1027 fatal("daemon() failed: %.200s", strerror(errno));
1030 * If a command was specified on the command line, execute the
1031 * command now. Otherwise request the server to start a shell.
1033 if (buffer_len(&command) > 0) {
1034 int len = buffer_len(&command);
1037 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1038 packet_start(SSH_CMSG_EXEC_CMD);
1039 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1041 packet_write_wait();
1043 debug("Requesting shell.");
1044 packet_start(SSH_CMSG_EXEC_SHELL);
1046 packet_write_wait();
1049 /* Enter the interactive session. */
1050 return client_loop(have_tty, tty_flag ?
1051 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1055 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1059 id = packet_get_int();
1060 len = buffer_len(&command);
1064 if (type == SSH2_MSG_CHANNEL_FAILURE)
1065 fatal("Request for subsystem '%.*s' failed on channel %d",
1066 len, (u_char *)buffer_ptr(&command), id);
1070 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1074 i = client_global_request_id++;
1075 if (i >= options.num_remote_forwards)
1077 debug("remote forward %s for: listen %d, connect %s:%d",
1078 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1079 options.remote_forwards[i].listen_port,
1080 options.remote_forwards[i].connect_host,
1081 options.remote_forwards[i].connect_port);
1082 if (type == SSH2_MSG_REQUEST_FAILURE) {
1083 if (options.exit_on_forward_failure)
1084 fatal("Error: remote port forwarding failed for "
1086 options.remote_forwards[i].listen_port);
1088 logit("Warning: remote port forwarding failed for "
1090 options.remote_forwards[i].listen_port);
1095 ssh_control_listener(void)
1097 struct sockaddr_un addr;
1101 if (options.control_path == NULL ||
1102 options.control_master == SSHCTL_MASTER_NO)
1105 debug("setting up multiplex master socket");
1107 memset(&addr, '\0', sizeof(addr));
1108 addr.sun_family = AF_UNIX;
1109 addr_len = offsetof(struct sockaddr_un, sun_path) +
1110 strlen(options.control_path) + 1;
1112 if (strlcpy(addr.sun_path, options.control_path,
1113 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1114 fatal("ControlPath too long");
1116 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1117 fatal("%s socket(): %s", __func__, strerror(errno));
1119 old_umask = umask(0177);
1120 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1122 if (errno == EINVAL || errno == EADDRINUSE)
1123 fatal("ControlSocket %s already exists",
1124 options.control_path);
1126 fatal("%s bind(): %s", __func__, strerror(errno));
1130 if (listen(control_fd, 64) == -1)
1131 fatal("%s listen(): %s", __func__, strerror(errno));
1133 set_nonblock(control_fd);
1136 /* request pty/x11/agent/tcpfwd/shell for channel */
1138 ssh_session2_setup(int id, void *arg)
1140 extern char **environ;
1141 const char *display;
1142 int interactive = tty_flag;
1144 display = getenv("DISPLAY");
1145 if (options.forward_x11 && display != NULL) {
1147 /* Get reasonable local authentication information. */
1148 client_x11_get_proto(display, options.xauth_location,
1149 options.forward_x11_trusted, &proto, &data);
1150 /* Request forwarding with authentication spoofing. */
1151 debug("Requesting X11 forwarding with authentication spoofing.");
1152 x11_request_forwarding_with_spoofing(id, display, proto, data);
1154 /* XXX wait for reply */
1157 check_agent_present();
1158 if (options.forward_agent) {
1159 debug("Requesting authentication agent forwarding.");
1160 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1164 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1165 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1167 packet_set_interactive(interactive);
1170 /* open new channel for a session */
1172 ssh_session2_open(void)
1175 int window, packetmax, in, out, err;
1178 int socksizelen = sizeof(int);
1180 if (stdin_null_flag) {
1181 in = open(_PATH_DEVNULL, O_RDONLY);
1183 in = dup(STDIN_FILENO);
1185 out = dup(STDOUT_FILENO);
1186 err = dup(STDERR_FILENO);
1188 if (in < 0 || out < 0 || err < 0)
1189 fatal("dup() in/out/err failed");
1191 /* enable nonblocking unless tty */
1199 /* we need to check to see if what they want to do about buffer */
1200 /* sizes here. In a hpn to nonhpn connection we want to limit */
1201 /* the window size to something reasonable in case the far side */
1202 /* has the large window bug. In hpn to hpn connection we want to */
1203 /* use the max window size but allow the user to override it */
1204 /* lastly if they disabled hpn then use the ssh std window size */
1206 /* so why don't we just do a getsockopt() here and set the */
1207 /* ssh window to that? In the case of a autotuning receive */
1208 /* window the window would get stuck at the initial buffer */
1209 /* size generally less than 96k. Therefore we need to set the */
1210 /* maximum ssh window size to the maximum hpn buffer size */
1211 /* unless the user has specifically set the tcprcvbufpoll */
1212 /* to no. In which case we *can* just set the window to the */
1213 /* minimum of the hpn buffer size and tcp receive buffer size */
1215 if(options.hpn_disabled)
1217 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1219 else if (datafellows & SSH_BUG_LARGEWINDOW)
1221 debug("HPN to Non-HPN Connection");
1222 if (options.hpn_buffer_size < 0)
1223 options.hpn_buffer_size = 2*1024*1024;
1227 if (options.hpn_buffer_size < 0)
1228 options.hpn_buffer_size = BUFFER_MAX_LEN_HPN;
1230 /*create a socket but don't connect it */
1231 /* we use that the get the rcv socket size */
1232 sock = socket(AF_INET, SOCK_STREAM, 0);
1233 /* if they are using the tcp_rcv_buf option */
1234 /* attempt to set the buffer size to that */
1235 if (options.tcp_rcv_buf)
1236 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf,
1237 sizeof(options.tcp_rcv_buf));
1238 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1239 &socksize, &socksizelen);
1241 debug("socksize %d", socksize);
1242 if (options.tcp_rcv_buf_poll <= 0)
1244 options.hpn_buffer_size = MIN(socksize,options.hpn_buffer_size);
1245 debug ("MIN of TCP RWIN and HPNBufferSize: %d", options.hpn_buffer_size);
1249 if (options.tcp_rcv_buf > 0)
1250 options.hpn_buffer_size = MIN(options.tcp_rcv_buf, options.hpn_buffer_size);
1251 debug ("MIN of TCPRcvBuf and HPNBufferSize: %d", options.hpn_buffer_size);
1256 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1258 window = options.hpn_buffer_size;
1260 packetmax = CHAN_SES_PACKET_DEFAULT;
1262 window = 4*CHAN_SES_PACKET_DEFAULT;
1267 "session", SSH_CHANNEL_OPENING, in, out, err,
1268 window, packetmax, CHAN_EXTENDED_WRITE,
1269 "client-session", /*nonblock*/0);
1271 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1272 c->dynamic_window = 1;
1273 debug ("Enabled Dynamic Window Scaling\n");
1275 debug3("ssh_session2_open: channel_new: %d", c->self);
1277 channel_send_open(c->self);
1279 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1289 /* XXX should be pre-session */
1290 ssh_init_forwarding();
1292 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1293 id = ssh_session2_open();
1295 /* Execute a local command */
1296 if (options.local_command != NULL &&
1297 options.permit_local_command)
1298 ssh_local_cmd(options.local_command);
1300 /* Start listening for multiplex clients */
1301 ssh_control_listener();
1303 /* If requested, let ssh continue in the background. */
1304 if (fork_after_authentication_flag)
1305 if (daemon(1, 1) < 0)
1306 fatal("daemon() failed: %.200s", strerror(errno));
1308 return client_loop(tty_flag, tty_flag ?
1309 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1313 load_public_identity_files(void)
1315 char *filename, *cp, thishost[NI_MAXHOST];
1322 if (options.smartcard_device != NULL &&
1323 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1324 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1326 for (i = 0; keys[i] != NULL; i++) {
1328 memmove(&options.identity_files[1], &options.identity_files[0],
1329 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1330 memmove(&options.identity_keys[1], &options.identity_keys[0],
1331 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1332 options.num_identity_files++;
1333 options.identity_keys[0] = keys[i];
1334 options.identity_files[0] = sc_get_key_label(keys[i]);
1336 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1337 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1341 #endif /* SMARTCARD */
1342 if ((pw = getpwuid(original_real_uid)) == NULL)
1343 fatal("load_public_identity_files: getpwuid failed");
1344 if (gethostname(thishost, sizeof(thishost)) == -1)
1345 fatal("load_public_identity_files: gethostname: %s",
1347 for (; i < options.num_identity_files; i++) {
1348 cp = tilde_expand_filename(options.identity_files[i],
1350 filename = percent_expand(cp, "d", pw->pw_dir,
1351 "u", pw->pw_name, "l", thishost, "h", host,
1352 "r", options.user, (char *)NULL);
1354 public = key_load_public(filename, NULL);
1355 debug("identity file %s type %d", filename,
1356 public ? public->type : -1);
1357 xfree(options.identity_files[i]);
1358 options.identity_files[i] = filename;
1359 options.identity_keys[i] = public;
1364 control_client_sighandler(int signo)
1366 control_client_terminate = signo;
1370 control_client_sigrelay(int signo)
1372 if (control_server_pid > 1)
1373 kill(control_server_pid, signo);
1377 env_permitted(char *env)
1380 char name[1024], *cp;
1382 if ((cp = strchr(env, '=')) == NULL || cp == env)
1384 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1385 if (ret <= 0 || (size_t)ret >= sizeof(name))
1386 fatal("env_permitted: name '%.100s...' too long", env);
1388 for (i = 0; i < options.num_send_env; i++)
1389 if (match_pattern(name, options.send_env[i]))
1396 control_client(const char *path)
1398 struct sockaddr_un addr;
1399 int i, r, fd, sock, exitval[2], num_env, addr_len;
1402 extern char **environ;
1405 if (mux_command == 0)
1406 mux_command = SSHMUX_COMMAND_OPEN;
1408 switch (options.control_master) {
1409 case SSHCTL_MASTER_AUTO:
1410 case SSHCTL_MASTER_AUTO_ASK:
1411 debug("auto-mux: Trying existing master");
1413 case SSHCTL_MASTER_NO:
1419 memset(&addr, '\0', sizeof(addr));
1420 addr.sun_family = AF_UNIX;
1421 addr_len = offsetof(struct sockaddr_un, sun_path) +
1424 if (strlcpy(addr.sun_path, path,
1425 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1426 fatal("ControlPath too long");
1428 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1429 fatal("%s socket(): %s", __func__, strerror(errno));
1431 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1432 if (mux_command != SSHMUX_COMMAND_OPEN) {
1433 fatal("Control socket connect(%.100s): %s", path,
1436 if (errno == ENOENT)
1437 debug("Control socket \"%.100s\" does not exist", path);
1439 error("Control socket connect(%.100s): %s", path,
1446 if (stdin_null_flag) {
1447 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1448 fatal("open(/dev/null): %s", strerror(errno));
1449 if (dup2(fd, STDIN_FILENO) == -1)
1450 fatal("dup2: %s", strerror(errno));
1451 if (fd > STDERR_FILENO)
1455 term = getenv("TERM");
1459 flags |= SSHMUX_FLAG_TTY;
1461 flags |= SSHMUX_FLAG_SUBSYS;
1462 if (options.forward_x11)
1463 flags |= SSHMUX_FLAG_X11_FWD;
1464 if (options.forward_agent)
1465 flags |= SSHMUX_FLAG_AGENT_FWD;
1469 /* Send our command to server */
1470 buffer_put_int(&m, mux_command);
1471 buffer_put_int(&m, flags);
1472 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1473 fatal("%s: msg_send", __func__);
1476 /* Get authorisation status and PID of controlee */
1477 if (ssh_msg_recv(sock, &m) == -1)
1478 fatal("%s: msg_recv", __func__);
1479 if (buffer_get_char(&m) != SSHMUX_VER)
1480 fatal("%s: wrong version", __func__);
1481 if (buffer_get_int(&m) != 1)
1482 fatal("Connection to master denied");
1483 control_server_pid = buffer_get_int(&m);
1487 switch (mux_command) {
1488 case SSHMUX_COMMAND_ALIVE_CHECK:
1489 fprintf(stderr, "Master running (pid=%d)\r\n",
1490 control_server_pid);
1492 case SSHMUX_COMMAND_TERMINATE:
1493 fprintf(stderr, "Exit request sent.\r\n");
1495 case SSHMUX_COMMAND_OPEN:
1496 /* continue below */
1499 fatal("silly mux_command %d", mux_command);
1502 /* SSHMUX_COMMAND_OPEN */
1503 buffer_put_cstring(&m, term ? term : "");
1504 buffer_append(&command, "\0", 1);
1505 buffer_put_cstring(&m, buffer_ptr(&command));
1507 if (options.num_send_env == 0 || environ == NULL) {
1508 buffer_put_int(&m, 0);
1510 /* Pass environment */
1512 for (i = 0; environ[i] != NULL; i++)
1513 if (env_permitted(environ[i]))
1514 num_env++; /* Count */
1516 buffer_put_int(&m, num_env);
1518 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1519 if (env_permitted(environ[i])) {
1521 buffer_put_cstring(&m, environ[i]);
1525 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1526 fatal("%s: msg_send", __func__);
1528 mm_send_fd(sock, STDIN_FILENO);
1529 mm_send_fd(sock, STDOUT_FILENO);
1530 mm_send_fd(sock, STDERR_FILENO);
1532 /* Wait for reply, so master has a chance to gather ttymodes */
1534 if (ssh_msg_recv(sock, &m) == -1)
1535 fatal("%s: msg_recv", __func__);
1536 if (buffer_get_char(&m) != SSHMUX_VER)
1537 fatal("%s: wrong version", __func__);
1540 signal(SIGHUP, control_client_sighandler);
1541 signal(SIGINT, control_client_sighandler);
1542 signal(SIGTERM, control_client_sighandler);
1543 signal(SIGWINCH, control_client_sigrelay);
1549 * Stick around until the controlee closes the client_fd.
1550 * Before it does, it is expected to write this process' exit
1551 * value (one int). This process must read the value and wait for
1552 * the closure of the client_fd; if this one closes early, the
1553 * multiplex master will terminate early too (possibly losing data).
1556 for (i = 0; !control_client_terminate && i < (int)sizeof(exitval);) {
1557 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
1559 debug2("Received EOF from master");
1565 fatal("%s: read %s", __func__, strerror(errno));
1572 if (i > (int)sizeof(int))
1573 fatal("%s: master returned too much data (%d > %lu)",
1574 __func__, i, sizeof(int));
1575 if (control_client_terminate) {
1576 debug2("Exiting on signal %d", control_client_terminate);
1578 } else if (i < (int)sizeof(int)) {
1579 debug2("Control master terminated unexpectedly");
1582 debug2("Received exit status from master %d", exitval[0]);
1584 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1585 fprintf(stderr, "Shared connection to %s closed.\r\n", host);