1 /* $OpenBSD: ssh.c,v 1.294 2006/10/06 02:29:19 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 [-1246AaCfgkMNnqsTtVvXxY] [-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]);
227 * Save the original real uid. It will be needed later (uid-swapping
228 * may clobber the real uid).
230 original_real_uid = getuid();
231 original_effective_uid = geteuid();
234 * Use uid-swapping to give up root privileges for the duration of
235 * option processing. We will re-instantiate the rights when we are
236 * ready to create the privileged port, and will permanently drop
237 * them when the port has been created (actually, when the connection
238 * has been made, as we may need to create the port several times).
242 #ifdef HAVE_SETRLIMIT
243 /* If we are installed setuid root be careful to not drop core. */
244 if (original_real_uid != original_effective_uid) {
246 rlim.rlim_cur = rlim.rlim_max = 0;
247 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
248 fatal("setrlimit failed: %.100s", strerror(errno));
252 pw = getpwuid(original_real_uid);
254 logit("You don't exist, go away!");
257 /* Take a copy of the returned structure. */
261 * Set our umask to something reasonable, as some files are created
262 * with the default umask. This will make them world-readable but
263 * writable only by the owner, which is ok for all files for which we
264 * don't set the modes explicitly.
268 /* Initialize option structure to indicate that no values have been set. */
269 initialize_options(&options);
271 /* Parse command-line arguments. */
275 while ((opt = getopt(ac, av,
276 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
279 options.protocol = SSH_PROTO_1;
282 options.protocol = SSH_PROTO_2;
285 options.address_family = AF_INET;
288 options.address_family = AF_INET6;
294 fork_after_authentication_flag = 1;
298 options.forward_x11 = 0;
301 options.forward_x11 = 1;
304 options.forward_x11 = 1;
305 options.forward_x11_trusted = 1;
308 options.gateway_ports = 1;
311 if (strcmp(optarg, "check") == 0)
312 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
313 else if (strcmp(optarg, "exit") == 0)
314 mux_command = SSHMUX_COMMAND_TERMINATE;
316 fatal("Invalid multiplex command.");
318 case 'P': /* deprecated */
319 options.use_privileged_port = 0;
322 options.forward_agent = 0;
325 options.forward_agent = 1;
328 options.gss_deleg_creds = 0;
331 if (stat(optarg, &st) < 0) {
332 fprintf(stderr, "Warning: Identity file %s "
333 "not accessible: %s.\n", optarg,
337 if (options.num_identity_files >=
338 SSH_MAX_IDENTITY_FILES)
339 fatal("Too many identity files specified "
340 "(max %d)", SSH_MAX_IDENTITY_FILES);
341 options.identity_files[options.num_identity_files++] =
346 options.smartcard_device = xstrdup(optarg);
348 fprintf(stderr, "no support for smartcards.\n");
357 if (debug_flag == 0) {
359 options.log_level = SYSLOG_LEVEL_DEBUG1;
361 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
367 fprintf(stderr, "%s, %s\n",
368 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
373 if (options.tun_open == -1)
374 options.tun_open = SSH_TUNMODE_DEFAULT;
375 options.tun_local = a2tun(optarg, &options.tun_remote);
376 if (options.tun_local == SSH_TUNID_ERR) {
377 fprintf(stderr, "Bad tun device '%s'\n", optarg);
382 options.log_level = SYSLOG_LEVEL_QUIET;
385 if (optarg[0] == '^' && optarg[2] == 0 &&
386 (u_char) optarg[1] >= 64 &&
387 (u_char) optarg[1] < 128)
388 options.escape_char = (u_char) optarg[1] & 31;
389 else if (strlen(optarg) == 1)
390 options.escape_char = (u_char) optarg[0];
391 else if (strcmp(optarg, "none") == 0)
392 options.escape_char = SSH_ESCAPECHAR_NONE;
394 fprintf(stderr, "Bad escape character '%s'.\n",
400 if (ciphers_valid(optarg)) {
402 options.ciphers = xstrdup(optarg);
403 options.cipher = SSH_CIPHER_INVALID;
406 options.cipher = cipher_number(optarg);
407 if (options.cipher == -1) {
409 "Unknown cipher type '%s'\n",
413 if (options.cipher == SSH_CIPHER_3DES)
414 options.ciphers = "3des-cbc";
415 else if (options.cipher == SSH_CIPHER_BLOWFISH)
416 options.ciphers = "blowfish-cbc";
418 options.ciphers = (char *)-1;
422 if (mac_valid(optarg))
423 options.macs = xstrdup(optarg);
425 fprintf(stderr, "Unknown mac type '%s'\n",
431 if (options.control_master == SSHCTL_MASTER_YES)
432 options.control_master = SSHCTL_MASTER_ASK;
434 options.control_master = SSHCTL_MASTER_YES;
437 options.port = a2port(optarg);
438 if (options.port == 0) {
439 fprintf(stderr, "Bad port '%s'\n", optarg);
444 options.user = optarg;
448 if (parse_forward(&fwd, optarg))
449 add_local_forward(&options, &fwd);
452 "Bad local forwarding specification '%s'\n",
459 if (parse_forward(&fwd, optarg)) {
460 add_remote_forward(&options, &fwd);
463 "Bad remote forwarding specification "
470 cp = p = xstrdup(optarg);
471 memset(&fwd, '\0', sizeof(fwd));
472 fwd.connect_host = "socks";
473 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
474 fprintf(stderr, "Bad dynamic forwarding "
475 "specification '%.100s'\n", optarg);
479 fwd.listen_port = a2port(cp);
480 fwd.listen_host = cleanhostname(fwd.listen_host);
482 fwd.listen_port = a2port(fwd.listen_host);
483 fwd.listen_host = NULL;
486 if (fwd.listen_port == 0) {
487 fprintf(stderr, "Bad dynamic port '%s'\n",
491 add_local_forward(&options, &fwd);
496 options.compression = 1;
504 line = xstrdup(optarg);
505 if (process_config_line(&options, host ? host : "",
506 line, "command-line", 0, &dummy) != 0)
512 /* ensure that the user doesn't try to backdoor a */
513 /* null cipher switch on an interactive session */
514 /* so explicitly disable it no matter what */
515 options.none_switch=0;
521 if (options.control_path != NULL)
522 free(options.control_path);
523 options.control_path = xstrdup(optarg);
526 options.bind_address = optarg;
539 if (ac > 0 && !host && **av != '-') {
540 if (strrchr(*av, '@')) {
542 cp = strrchr(p, '@');
543 if (cp == NULL || cp == p)
551 optind = optreset = 1;
557 /* Check that we got a host name. */
561 SSLeay_add_all_algorithms();
562 ERR_load_crypto_strings();
564 /* Initialize the command to execute on remote host. */
565 buffer_init(&command);
568 * Save the command to execute on the remote host in a buffer. There
569 * is no limit on the length of the command, except by the maximum
570 * packet size. Also sets the tty flag if there is no command.
573 /* No command specified - execute shell on a tty. */
575 if (subsystem_flag) {
577 "You must specify a subsystem to invoke.\n");
581 /* A command has been specified. Store it into the buffer. */
582 for (i = 0; i < ac; i++) {
584 buffer_append(&command, " ", 1);
585 buffer_append(&command, av[i], strlen(av[i]));
589 /* Cannot fork to background if no command. */
590 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
591 fatal("Cannot fork into background without a command to execute.");
593 /* Allocate a tty by default if no command specified. */
594 if (buffer_len(&command) == 0)
600 /* Do not allocate a tty if stdin is not a tty. */
601 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
603 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
608 * Initialize "log" output. Since we are the client all output
609 * actually goes to stderr.
611 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
612 SYSLOG_FACILITY_USER, 1);
615 * Read per-user configuration file. Ignore the system wide config
616 * file if the user specifies a config file on the command line.
618 if (config != NULL) {
619 if (!read_config_file(config, host, &options, 0))
620 fatal("Can't open user config file %.100s: "
621 "%.100s", config, strerror(errno));
624 * Since the config file parsing code aborts if it sees
625 * options it doesn't recognize, allow users to put
626 * options specific to compile-time add-ons in alternate
627 * config files so their primary config file will
628 * interoperate SSH versions that don't support those
632 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
633 _PATH_SSH_USER_CONFFILE);
634 (void)read_config_file(buf, host, &options, 1);
636 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
637 _PATH_SSH_USER_CONFFILE);
638 (void)read_config_file(buf, host, &options, 1);
641 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
642 _PATH_SSH_USER_CONFFILE);
643 (void)read_config_file(buf, host, &options, 1);
646 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
647 _PATH_SSH_USER_CONFFILE);
648 (void)read_config_file(buf, host, &options, 1);
650 /* Read systemwide configuration file after use config. */
651 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
655 /* Fill configuration defaults. */
656 fill_default_options(&options);
658 channel_set_af(options.address_family);
661 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
665 if (options.user == NULL) {
666 options.user = xstrdup(pw->pw_name);
667 options.implicit = 1;
669 else options.implicit = 0;
671 if (options.hostname != NULL)
672 host = options.hostname;
674 /* force lowercase for hostkey matching */
675 if (options.host_key_alias != NULL) {
676 for (p = options.host_key_alias; *p; p++)
678 *p = (char)tolower(*p);
681 /* Get default port if port has not been set. */
682 if (options.port == 0) {
683 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
684 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
687 if (options.proxy_command != NULL &&
688 strcmp(options.proxy_command, "none") == 0)
689 options.proxy_command = NULL;
690 if (options.control_path != NULL &&
691 strcmp(options.control_path, "none") == 0)
692 options.control_path = NULL;
694 if (options.control_path != NULL) {
695 char thishost[NI_MAXHOST];
697 if (gethostname(thishost, sizeof(thishost)) == -1)
698 fatal("gethostname: %s", strerror(errno));
699 snprintf(buf, sizeof(buf), "%d", options.port);
700 cp = tilde_expand_filename(options.control_path,
702 options.control_path = percent_expand(cp, "p", buf, "h", host,
703 "r", options.user, "l", thishost, (char *)NULL);
706 if (mux_command != 0 && options.control_path == NULL)
707 fatal("No ControlPath specified for \"-O\" command");
708 if (options.control_path != NULL)
709 control_client(options.control_path);
711 /* Open a connection to the remote host. */
712 if (ssh_connect(host, &hostaddr, options.port,
713 options.address_family, options.connection_attempts,
715 options.use_privileged_port,
717 original_effective_uid == 0 && options.use_privileged_port,
719 options.proxy_command) != 0)
723 * If we successfully made the connection, load the host private key
724 * in case we will need it later for combined rsa-rhosts
725 * authentication. This must be done before releasing extra
726 * privileges, because the file is only readable by root.
727 * If we cannot access the private keys, load the public keys
728 * instead and try to execute the ssh-keysign helper instead.
730 sensitive_data.nkeys = 0;
731 sensitive_data.keys = NULL;
732 sensitive_data.external_keysign = 0;
733 if (options.rhosts_rsa_authentication ||
734 options.hostbased_authentication) {
735 sensitive_data.nkeys = 3;
736 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
740 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
741 _PATH_HOST_KEY_FILE, "", NULL, NULL);
742 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
743 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
744 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
745 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
748 if (options.hostbased_authentication == 1 &&
749 sensitive_data.keys[0] == NULL &&
750 sensitive_data.keys[1] == NULL &&
751 sensitive_data.keys[2] == NULL) {
752 sensitive_data.keys[1] = key_load_public(
753 _PATH_HOST_DSA_KEY_FILE, NULL);
754 sensitive_data.keys[2] = key_load_public(
755 _PATH_HOST_RSA_KEY_FILE, NULL);
756 sensitive_data.external_keysign = 1;
760 * Get rid of any extra privileges that we may have. We will no
761 * longer need them. Also, extra privileges could make it very hard
762 * to read identity files and other non-world-readable files from the
763 * user's home directory if it happens to be on a NFS volume where
764 * root is mapped to nobody.
766 if (original_effective_uid == 0) {
768 permanently_set_uid(pw);
772 * Now that we are back to our own permissions, create ~/.ssh
773 * directory if it doesn't already exist.
775 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
776 if (stat(buf, &st) < 0)
777 if (mkdir(buf, 0700) < 0)
778 error("Could not create directory '%.200s'.", buf);
780 /* load options.identity_files */
781 load_public_identity_files();
783 /* Expand ~ in known host file names. */
785 options.system_hostfile =
786 tilde_expand_filename(options.system_hostfile, original_real_uid);
787 options.user_hostfile =
788 tilde_expand_filename(options.user_hostfile, original_real_uid);
789 options.system_hostfile2 =
790 tilde_expand_filename(options.system_hostfile2, original_real_uid);
791 options.user_hostfile2 =
792 tilde_expand_filename(options.user_hostfile2, original_real_uid);
794 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
796 /* Log into the remote system. This never returns if the login fails. */
797 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
799 /* We no longer need the private host keys. Clear them now. */
800 if (sensitive_data.nkeys != 0) {
801 for (i = 0; i < sensitive_data.nkeys; i++) {
802 if (sensitive_data.keys[i] != NULL) {
803 /* Destroys contents safely */
804 debug3("clear hostkey %d", i);
805 key_free(sensitive_data.keys[i]);
806 sensitive_data.keys[i] = NULL;
809 xfree(sensitive_data.keys);
811 for (i = 0; i < options.num_identity_files; i++) {
812 if (options.identity_files[i]) {
813 xfree(options.identity_files[i]);
814 options.identity_files[i] = NULL;
816 if (options.identity_keys[i]) {
817 key_free(options.identity_keys[i]);
818 options.identity_keys[i] = NULL;
822 exit_status = compat20 ? ssh_session2() : ssh_session();
825 if (options.control_path != NULL && control_fd != -1)
826 unlink(options.control_path);
829 * Send SIGHUP to proxy command if used. We don't wait() in
830 * case it hangs and instead rely on init to reap the child
832 if (proxy_command_pid > 1)
833 kill(proxy_command_pid, SIGHUP);
839 ssh_init_forwarding(void)
844 /* Initiate local TCP/IP port forwardings. */
845 for (i = 0; i < options.num_local_forwards; i++) {
846 debug("Local connections to %.200s:%d forwarded to remote "
848 (options.local_forwards[i].listen_host == NULL) ?
849 (options.gateway_ports ? "*" : "LOCALHOST") :
850 options.local_forwards[i].listen_host,
851 options.local_forwards[i].listen_port,
852 options.local_forwards[i].connect_host,
853 options.local_forwards[i].connect_port);
854 success += channel_setup_local_fwd_listener(
855 options.local_forwards[i].listen_host,
856 options.local_forwards[i].listen_port,
857 options.local_forwards[i].connect_host,
858 options.local_forwards[i].connect_port,
859 options.gateway_ports, options.hpn_disabled,
860 options.hpn_buffer_size);
862 if (i > 0 && success != i && options.exit_on_forward_failure)
863 fatal("Could not request local forwarding.");
864 if (i > 0 && success == 0)
865 error("Could not request local forwarding.");
867 /* Initiate remote TCP/IP port forwardings. */
868 for (i = 0; i < options.num_remote_forwards; i++) {
869 debug("Remote connections from %.200s:%d forwarded to "
870 "local address %.200s:%d",
871 (options.remote_forwards[i].listen_host == NULL) ?
872 "LOCALHOST" : options.remote_forwards[i].listen_host,
873 options.remote_forwards[i].listen_port,
874 options.remote_forwards[i].connect_host,
875 options.remote_forwards[i].connect_port);
876 if (channel_request_remote_forwarding(
877 options.remote_forwards[i].listen_host,
878 options.remote_forwards[i].listen_port,
879 options.remote_forwards[i].connect_host,
880 options.remote_forwards[i].connect_port) < 0) {
881 if (options.exit_on_forward_failure)
882 fatal("Could not request remote forwarding.");
884 logit("Warning: Could not request remote "
891 check_agent_present(void)
893 if (options.forward_agent) {
894 /* Clear agent forwarding if we don't have an agent. */
895 if (!ssh_agent_present())
896 options.forward_agent = 0;
910 /* Enable compression if requested. */
911 if (options.compression) {
912 debug("Requesting compression at level %d.", options.compression_level);
914 if (options.compression_level < 1 || options.compression_level > 9)
915 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
917 /* Send the request. */
918 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
919 packet_put_int(options.compression_level);
922 type = packet_read();
923 if (type == SSH_SMSG_SUCCESS)
924 packet_start_compression(options.compression_level);
925 else if (type == SSH_SMSG_FAILURE)
926 logit("Warning: Remote host refused compression.");
928 packet_disconnect("Protocol error waiting for compression response.");
930 /* Allocate a pseudo tty if appropriate. */
932 debug("Requesting pty.");
934 /* Start the packet. */
935 packet_start(SSH_CMSG_REQUEST_PTY);
937 /* Store TERM in the packet. There is no limit on the
938 length of the string. */
942 packet_put_cstring(cp);
944 /* Store window size in the packet. */
945 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
946 memset(&ws, 0, sizeof(ws));
947 packet_put_int((u_int)ws.ws_row);
948 packet_put_int((u_int)ws.ws_col);
949 packet_put_int((u_int)ws.ws_xpixel);
950 packet_put_int((u_int)ws.ws_ypixel);
952 /* Store tty modes in the packet. */
953 tty_make_modes(fileno(stdin), NULL);
955 /* Send the packet, and wait for it to leave. */
959 /* Read response from the server. */
960 type = packet_read();
961 if (type == SSH_SMSG_SUCCESS) {
964 } else if (type == SSH_SMSG_FAILURE)
965 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
967 packet_disconnect("Protocol error waiting for pty request response.");
969 /* Request X11 forwarding if enabled and DISPLAY is set. */
970 display = getenv("DISPLAY");
971 if (options.forward_x11 && display != NULL) {
973 /* Get reasonable local authentication information. */
974 client_x11_get_proto(display, options.xauth_location,
975 options.forward_x11_trusted, &proto, &data);
976 /* Request forwarding with authentication spoofing. */
977 debug("Requesting X11 forwarding with authentication spoofing.");
978 x11_request_forwarding_with_spoofing(0, display, proto, data);
980 /* Read response from the server. */
981 type = packet_read();
982 if (type == SSH_SMSG_SUCCESS) {
984 } else if (type == SSH_SMSG_FAILURE) {
985 logit("Warning: Remote host denied X11 forwarding.");
987 packet_disconnect("Protocol error waiting for X11 forwarding");
990 /* Tell the packet module whether this is an interactive session. */
991 packet_set_interactive(interactive);
993 /* Request authentication agent forwarding if appropriate. */
994 check_agent_present();
996 if (options.forward_agent) {
997 debug("Requesting authentication agent forwarding.");
998 auth_request_forwarding();
1000 /* Read response from the server. */
1001 type = packet_read();
1003 if (type != SSH_SMSG_SUCCESS)
1004 logit("Warning: Remote host denied authentication agent forwarding.");
1007 /* Initiate port forwardings. */
1008 ssh_init_forwarding();
1010 /* If requested, let ssh continue in the background. */
1011 if (fork_after_authentication_flag)
1012 if (daemon(1, 1) < 0)
1013 fatal("daemon() failed: %.200s", strerror(errno));
1016 * If a command was specified on the command line, execute the
1017 * command now. Otherwise request the server to start a shell.
1019 if (buffer_len(&command) > 0) {
1020 int len = buffer_len(&command);
1023 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1024 packet_start(SSH_CMSG_EXEC_CMD);
1025 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1027 packet_write_wait();
1029 debug("Requesting shell.");
1030 packet_start(SSH_CMSG_EXEC_SHELL);
1032 packet_write_wait();
1035 /* Enter the interactive session. */
1036 return client_loop(have_tty, tty_flag ?
1037 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1041 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1045 id = packet_get_int();
1046 len = buffer_len(&command);
1050 if (type == SSH2_MSG_CHANNEL_FAILURE)
1051 fatal("Request for subsystem '%.*s' failed on channel %d",
1052 len, (u_char *)buffer_ptr(&command), id);
1056 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1060 i = client_global_request_id++;
1061 if (i >= options.num_remote_forwards)
1063 debug("remote forward %s for: listen %d, connect %s:%d",
1064 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1065 options.remote_forwards[i].listen_port,
1066 options.remote_forwards[i].connect_host,
1067 options.remote_forwards[i].connect_port);
1068 if (type == SSH2_MSG_REQUEST_FAILURE) {
1069 if (options.exit_on_forward_failure)
1070 fatal("Error: remote port forwarding failed for "
1072 options.remote_forwards[i].listen_port);
1074 logit("Warning: remote port forwarding failed for "
1076 options.remote_forwards[i].listen_port);
1081 ssh_control_listener(void)
1083 struct sockaddr_un addr;
1087 if (options.control_path == NULL ||
1088 options.control_master == SSHCTL_MASTER_NO)
1091 debug("setting up multiplex master socket");
1093 memset(&addr, '\0', sizeof(addr));
1094 addr.sun_family = AF_UNIX;
1095 addr_len = offsetof(struct sockaddr_un, sun_path) +
1096 strlen(options.control_path) + 1;
1098 if (strlcpy(addr.sun_path, options.control_path,
1099 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1100 fatal("ControlPath too long");
1102 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1103 fatal("%s socket(): %s", __func__, strerror(errno));
1105 old_umask = umask(0177);
1106 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1108 if (errno == EINVAL || errno == EADDRINUSE)
1109 fatal("ControlSocket %s already exists",
1110 options.control_path);
1112 fatal("%s bind(): %s", __func__, strerror(errno));
1116 if (listen(control_fd, 64) == -1)
1117 fatal("%s listen(): %s", __func__, strerror(errno));
1119 set_nonblock(control_fd);
1122 /* request pty/x11/agent/tcpfwd/shell for channel */
1124 ssh_session2_setup(int id, void *arg)
1126 extern char **environ;
1127 const char *display;
1128 int interactive = tty_flag;
1130 display = getenv("DISPLAY");
1131 if (options.forward_x11 && display != NULL) {
1133 /* Get reasonable local authentication information. */
1134 client_x11_get_proto(display, options.xauth_location,
1135 options.forward_x11_trusted, &proto, &data);
1136 /* Request forwarding with authentication spoofing. */
1137 debug("Requesting X11 forwarding with authentication spoofing.");
1138 x11_request_forwarding_with_spoofing(id, display, proto, data);
1140 /* XXX wait for reply */
1143 check_agent_present();
1144 if (options.forward_agent) {
1145 debug("Requesting authentication agent forwarding.");
1146 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1150 if (options.tun_open != SSH_TUNMODE_NO) {
1154 debug("Requesting tun.");
1155 if ((fd = tun_open(options.tun_local,
1156 options.tun_open)) >= 0) {
1157 if(options.hpn_disabled)
1158 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1159 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1162 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1163 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1166 #if defined(SSH_TUN_FILTER)
1167 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1168 channel_register_filter(c->self, sys_tun_infilter,
1171 packet_start(SSH2_MSG_CHANNEL_OPEN);
1172 packet_put_cstring("tun@openssh.com");
1173 packet_put_int(c->self);
1174 packet_put_int(c->local_window_max);
1175 packet_put_int(c->local_maxpacket);
1176 packet_put_int(options.tun_open);
1177 packet_put_int(options.tun_remote);
1182 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1183 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1185 packet_set_interactive(interactive);
1188 /* open new channel for a session */
1190 ssh_session2_open(void)
1193 int window, packetmax, in, out, err;
1196 int socksizelen = sizeof(int);
1198 if (stdin_null_flag) {
1199 in = open(_PATH_DEVNULL, O_RDONLY);
1201 in = dup(STDIN_FILENO);
1203 out = dup(STDOUT_FILENO);
1204 err = dup(STDERR_FILENO);
1206 if (in < 0 || out < 0 || err < 0)
1207 fatal("dup() in/out/err failed");
1209 /* enable nonblocking unless tty */
1217 /* we need to check to see if what they want to do about buffer */
1218 /* sizes here. In a hpn to nonhpn connection we want to limit */
1219 /* the window size to something reasonable in case the far side */
1220 /* has the large window bug. In hpn to hpn connection we want to */
1221 /* use the max window size but allow the user to override it */
1222 /* lastly if they disabled hpn then use the ssh std window size */
1224 /* so why don't we just do a getsockopt() here and set the */
1225 /* ssh window to that? In the case of a autotuning receive */
1226 /* window the window would get stuck at the initial buffer */
1227 /* size generally less than 96k. Therefore we need to set the */
1228 /* maximum ssh window size to the maximum hpn buffer size */
1229 /* unless the user hasspecifically set the hpnrcvbufpoll */
1230 /* to no. In which case we *can* just set the window to the */
1231 /* minimum of the hpn buffer size and tcp receive buffer size */
1233 if(options.hpn_disabled)
1235 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1237 else if (datafellows & SSH_BUG_LARGEWINDOW)
1239 debug("HPN to Non-HPN Connection");
1240 if (options.hpn_buffer_size < 0)
1241 options.hpn_buffer_size = 2*1024*1024;
1245 if (options.hpn_buffer_size < 0)
1246 options.hpn_buffer_size = BUFFER_MAX_LEN_HPN;
1248 /*create a socket but don't connect it */
1249 /* we use that the get the rcv socket size */
1250 sock = socket(AF_INET, SOCK_STREAM, 0);
1251 /* if they are using the tcp_rcv_buf option */
1252 /* attempt to set the buffer size to that */
1253 if (options.tcp_rcv_buf)
1254 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf,
1255 sizeof(options.tcp_rcv_buf));
1256 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1257 &socksize, &socksizelen);
1259 debug("socksize %d", socksize);
1260 if (options.tcp_rcv_buf_poll <= 0)
1262 options.hpn_buffer_size = MIN(socksize,options.hpn_buffer_size);
1263 debug ("MIN of TCP RWIN and HPNBufferSize: %d", options.hpn_buffer_size);
1267 if (options.tcp_rcv_buf > 0)
1268 options.hpn_buffer_size = MIN(options.tcp_rcv_buf, options.hpn_buffer_size);
1269 debug ("MIN of TCPRcvBuf and HPNBufferSize: %d", options.hpn_buffer_size);
1274 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1276 window = options.hpn_buffer_size;
1278 packetmax = CHAN_SES_PACKET_DEFAULT;
1280 window = 4*CHAN_SES_PACKET_DEFAULT;
1285 "session", SSH_CHANNEL_OPENING, in, out, err,
1286 window, packetmax, CHAN_EXTENDED_WRITE,
1287 "client-session", /*nonblock*/0);
1288 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1289 c->dynamic_window = 1;
1290 debug ("Enabled Dynamic Window Scaling\n");
1292 debug3("ssh_session2_open: channel_new: %d", c->self);
1294 channel_send_open(c->self);
1296 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1306 /* XXX should be pre-session */
1307 ssh_init_forwarding();
1308 ssh_control_listener();
1310 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1311 id = ssh_session2_open();
1313 /* Execute a local command */
1314 if (options.local_command != NULL &&
1315 options.permit_local_command)
1316 ssh_local_cmd(options.local_command);
1318 /* If requested, let ssh continue in the background. */
1319 if (fork_after_authentication_flag)
1320 if (daemon(1, 1) < 0)
1321 fatal("daemon() failed: %.200s", strerror(errno));
1323 return client_loop(tty_flag, tty_flag ?
1324 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1328 load_public_identity_files(void)
1330 char *filename, *cp, thishost[NI_MAXHOST];
1337 if (options.smartcard_device != NULL &&
1338 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1339 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1341 for (i = 0; keys[i] != NULL; i++) {
1343 memmove(&options.identity_files[1], &options.identity_files[0],
1344 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1345 memmove(&options.identity_keys[1], &options.identity_keys[0],
1346 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1347 options.num_identity_files++;
1348 options.identity_keys[0] = keys[i];
1349 options.identity_files[0] = sc_get_key_label(keys[i]);
1351 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1352 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1356 #endif /* SMARTCARD */
1357 if ((pw = getpwuid(original_real_uid)) == NULL)
1358 fatal("load_public_identity_files: getpwuid failed");
1359 if (gethostname(thishost, sizeof(thishost)) == -1)
1360 fatal("load_public_identity_files: gethostname: %s",
1362 for (; i < options.num_identity_files; i++) {
1363 cp = tilde_expand_filename(options.identity_files[i],
1365 filename = percent_expand(cp, "d", pw->pw_dir,
1366 "u", pw->pw_name, "l", thishost, "h", host,
1367 "r", options.user, (char *)NULL);
1369 public = key_load_public(filename, NULL);
1370 debug("identity file %s type %d", filename,
1371 public ? public->type : -1);
1372 xfree(options.identity_files[i]);
1373 options.identity_files[i] = filename;
1374 options.identity_keys[i] = public;
1379 control_client_sighandler(int signo)
1381 control_client_terminate = signo;
1385 control_client_sigrelay(int signo)
1387 if (control_server_pid > 1)
1388 kill(control_server_pid, signo);
1392 env_permitted(char *env)
1395 char name[1024], *cp;
1397 if ((cp = strchr(env, '=')) == NULL || cp == env)
1399 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1400 if (ret <= 0 || (size_t)ret >= sizeof(name))
1401 fatal("env_permitted: name '%.100s...' too long", env);
1403 for (i = 0; i < options.num_send_env; i++)
1404 if (match_pattern(name, options.send_env[i]))
1411 control_client(const char *path)
1413 struct sockaddr_un addr;
1414 int i, r, fd, sock, exitval, num_env, addr_len;
1417 extern char **environ;
1420 if (mux_command == 0)
1421 mux_command = SSHMUX_COMMAND_OPEN;
1423 switch (options.control_master) {
1424 case SSHCTL_MASTER_AUTO:
1425 case SSHCTL_MASTER_AUTO_ASK:
1426 debug("auto-mux: Trying existing master");
1428 case SSHCTL_MASTER_NO:
1434 memset(&addr, '\0', sizeof(addr));
1435 addr.sun_family = AF_UNIX;
1436 addr_len = offsetof(struct sockaddr_un, sun_path) +
1439 if (strlcpy(addr.sun_path, path,
1440 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1441 fatal("ControlPath too long");
1443 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1444 fatal("%s socket(): %s", __func__, strerror(errno));
1446 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1447 if (mux_command != SSHMUX_COMMAND_OPEN) {
1448 fatal("Control socket connect(%.100s): %s", path,
1451 if (errno == ENOENT)
1452 debug("Control socket \"%.100s\" does not exist", path);
1454 error("Control socket connect(%.100s): %s", path,
1461 if (stdin_null_flag) {
1462 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1463 fatal("open(/dev/null): %s", strerror(errno));
1464 if (dup2(fd, STDIN_FILENO) == -1)
1465 fatal("dup2: %s", strerror(errno));
1466 if (fd > STDERR_FILENO)
1470 term = getenv("TERM");
1474 flags |= SSHMUX_FLAG_TTY;
1476 flags |= SSHMUX_FLAG_SUBSYS;
1477 if (options.forward_x11)
1478 flags |= SSHMUX_FLAG_X11_FWD;
1479 if (options.forward_agent)
1480 flags |= SSHMUX_FLAG_AGENT_FWD;
1481 if (options.num_local_forwards > 0)
1482 flags |= SSHMUX_FLAG_PORTFORWARD;
1485 /* Send our command to server */
1486 buffer_put_int(&m, mux_command);
1487 buffer_put_int(&m, flags);
1488 if (options.num_local_forwards > 0)
1490 if (options.local_forwards[0].listen_host == NULL)
1491 buffer_put_string(&m,"LOCALHOST",11);
1493 buffer_put_string(&m,options.local_forwards[0].listen_host,512);
1494 buffer_put_int(&m,options.local_forwards[0].listen_port);
1495 buffer_put_string(&m,options.local_forwards[0].connect_host,512);
1496 buffer_put_int(&m,options.local_forwards[0].connect_port);
1498 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1499 fatal("%s: msg_send", __func__);
1502 /* Get authorisation status and PID of controlee */
1503 if (ssh_msg_recv(sock, &m) == -1)
1504 fatal("%s: msg_recv", __func__);
1505 if (buffer_get_char(&m) != SSHMUX_VER)
1506 fatal("%s: wrong version", __func__);
1507 if (buffer_get_int(&m) != 1)
1508 fatal("Connection to master denied");
1509 control_server_pid = buffer_get_int(&m);
1513 switch (mux_command) {
1514 case SSHMUX_COMMAND_ALIVE_CHECK:
1515 fprintf(stderr, "Master running (pid=%d)\r\n",
1516 control_server_pid);
1518 case SSHMUX_COMMAND_TERMINATE:
1519 fprintf(stderr, "Exit request sent.\r\n");
1521 case SSHMUX_COMMAND_OPEN:
1522 /* continue below */
1525 fatal("silly mux_command %d", mux_command);
1528 /* SSHMUX_COMMAND_OPEN */
1529 buffer_put_cstring(&m, term ? term : "");
1530 buffer_append(&command, "\0", 1);
1531 buffer_put_cstring(&m, buffer_ptr(&command));
1533 if (options.num_send_env == 0 || environ == NULL) {
1534 buffer_put_int(&m, 0);
1536 /* Pass environment */
1538 for (i = 0; environ[i] != NULL; i++)
1539 if (env_permitted(environ[i]))
1540 num_env++; /* Count */
1542 buffer_put_int(&m, num_env);
1544 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1545 if (env_permitted(environ[i])) {
1547 buffer_put_cstring(&m, environ[i]);
1551 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1552 fatal("%s: msg_send", __func__);
1554 mm_send_fd(sock, STDIN_FILENO);
1555 mm_send_fd(sock, STDOUT_FILENO);
1556 mm_send_fd(sock, STDERR_FILENO);
1558 /* Wait for reply, so master has a chance to gather ttymodes */
1560 if (ssh_msg_recv(sock, &m) == -1)
1561 fatal("%s: msg_recv", __func__);
1562 if (buffer_get_char(&m) != SSHMUX_VER)
1563 fatal("%s: wrong version", __func__);
1566 signal(SIGHUP, control_client_sighandler);
1567 signal(SIGINT, control_client_sighandler);
1568 signal(SIGTERM, control_client_sighandler);
1569 signal(SIGWINCH, control_client_sigrelay);
1574 /* Stick around until the controlee closes the client_fd */
1576 for (;!control_client_terminate;) {
1577 r = read(sock, &exitval, sizeof(exitval));
1579 debug2("Received EOF from master");
1583 debug2("Received exit status from master %d", exitval);
1584 if (r == -1 && errno != EINTR)
1585 fatal("%s: read %s", __func__, strerror(errno));
1588 if (control_client_terminate)
1589 debug2("Exiting on signal %d", control_client_terminate);
1595 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1596 fprintf(stderr, "Connection to master closed.\r\n");