1 /* $OpenBSD: ssh.c,v 1.285 2006/07/11 20:27:56 stevesk 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>
63 #include <openssl/evp.h>
64 #include <openssl/err.h>
79 #include "pathnames.h"
81 #include "clientloop.h"
84 #include "sshconnect.h"
91 #include "monitor_fdpass.h"
99 extern char *__progname;
101 /* Flag indicating whether debug mode is on. This can be set on the command line. */
104 /* Flag indicating whether a tty should be allocated */
107 int force_tty_flag = 0;
109 /* don't exec a shell */
110 int no_shell_flag = 0;
113 * Flag indicating that nothing should be read from stdin. This can be set
114 * on the command line.
116 int stdin_null_flag = 0;
119 * Flag indicating that ssh should fork after authentication. This is useful
120 * so that the passphrase can be entered manually, and then ssh goes to the
123 int fork_after_authentication_flag = 0;
126 * General data structure for command line options and options configurable
127 * in configuration files. See readconf.h.
131 /* optional user configfile */
135 * Name of the host we are connecting to. This is the name given on the
136 * command line, or the HostName specified for the user-supplied name in a
137 * configuration file.
141 /* socket address the host resolves to */
142 struct sockaddr_storage hostaddr;
144 /* Private host keys. */
145 Sensitive sensitive_data;
147 /* Original real UID. */
148 uid_t original_real_uid;
149 uid_t original_effective_uid;
151 /* command to be executed */
154 /* Should we execute a command or invoke a subsystem? */
155 int subsystem_flag = 0;
157 /* # of replies received for global requests */
158 static int client_global_request_id = 0;
160 /* pid of proxycommand child process */
161 pid_t proxy_command_pid = 0;
163 /* fd to control socket */
166 /* Multiplexing control command */
167 static u_int mux_command = 0;
169 /* Only used in control client mode */
170 volatile sig_atomic_t control_client_terminate = 0;
171 u_int control_server_pid = 0;
173 /* Prints a help message to the user. This function never returns. */
179 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
180 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
181 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
182 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
183 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
184 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
189 static int ssh_session(void);
190 static int ssh_session2(void);
191 static void load_public_identity_files(void);
192 static void control_client(const char *path);
195 * Main program for the ssh client.
198 main(int ac, char **av)
200 int i, opt, exit_status;
201 char *p, *cp, *line, buf[256];
205 extern int optind, optreset;
210 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
213 __progname = ssh_get_progname(av[0]);
217 * Save the original real uid. It will be needed later (uid-swapping
218 * may clobber the real uid).
220 original_real_uid = getuid();
221 original_effective_uid = geteuid();
224 * Use uid-swapping to give up root privileges for the duration of
225 * option processing. We will re-instantiate the rights when we are
226 * ready to create the privileged port, and will permanently drop
227 * them when the port has been created (actually, when the connection
228 * has been made, as we may need to create the port several times).
232 #ifdef HAVE_SETRLIMIT
233 /* If we are installed setuid root be careful to not drop core. */
234 if (original_real_uid != original_effective_uid) {
236 rlim.rlim_cur = rlim.rlim_max = 0;
237 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
238 fatal("setrlimit failed: %.100s", strerror(errno));
242 pw = getpwuid(original_real_uid);
244 logit("You don't exist, go away!");
247 /* Take a copy of the returned structure. */
251 * Set our umask to something reasonable, as some files are created
252 * with the default umask. This will make them world-readable but
253 * writable only by the owner, which is ok for all files for which we
254 * don't set the modes explicitly.
258 /* Initialize option structure to indicate that no values have been set. */
259 initialize_options(&options);
261 /* Parse command-line arguments. */
265 while ((opt = getopt(ac, av,
266 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
269 options.protocol = SSH_PROTO_1;
272 options.protocol = SSH_PROTO_2;
275 options.address_family = AF_INET;
278 options.address_family = AF_INET6;
284 fork_after_authentication_flag = 1;
288 options.forward_x11 = 0;
291 options.forward_x11 = 1;
294 options.forward_x11 = 1;
295 options.forward_x11_trusted = 1;
298 options.gateway_ports = 1;
301 if (strcmp(optarg, "check") == 0)
302 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
303 else if (strcmp(optarg, "exit") == 0)
304 mux_command = SSHMUX_COMMAND_TERMINATE;
306 fatal("Invalid multiplex command.");
308 case 'P': /* deprecated */
309 options.use_privileged_port = 0;
312 options.forward_agent = 0;
315 options.forward_agent = 1;
318 options.gss_deleg_creds = 0;
321 if (stat(optarg, &st) < 0) {
322 fprintf(stderr, "Warning: Identity file %s "
323 "not accessible: %s.\n", optarg,
327 if (options.num_identity_files >=
328 SSH_MAX_IDENTITY_FILES)
329 fatal("Too many identity files specified "
330 "(max %d)", SSH_MAX_IDENTITY_FILES);
331 options.identity_files[options.num_identity_files++] =
336 options.smartcard_device = xstrdup(optarg);
338 fprintf(stderr, "no support for smartcards.\n");
347 if (debug_flag == 0) {
349 options.log_level = SYSLOG_LEVEL_DEBUG1;
351 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
357 fprintf(stderr, "%s, %s\n",
358 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
363 if (options.tun_open == -1)
364 options.tun_open = SSH_TUNMODE_DEFAULT;
365 options.tun_local = a2tun(optarg, &options.tun_remote);
366 if (options.tun_local == SSH_TUNID_ERR) {
367 fprintf(stderr, "Bad tun device '%s'\n", optarg);
372 options.log_level = SYSLOG_LEVEL_QUIET;
375 if (optarg[0] == '^' && optarg[2] == 0 &&
376 (u_char) optarg[1] >= 64 &&
377 (u_char) optarg[1] < 128)
378 options.escape_char = (u_char) optarg[1] & 31;
379 else if (strlen(optarg) == 1)
380 options.escape_char = (u_char) optarg[0];
381 else if (strcmp(optarg, "none") == 0)
382 options.escape_char = SSH_ESCAPECHAR_NONE;
384 fprintf(stderr, "Bad escape character '%s'.\n",
390 if (ciphers_valid(optarg)) {
392 options.ciphers = xstrdup(optarg);
393 options.cipher = SSH_CIPHER_INVALID;
396 options.cipher = cipher_number(optarg);
397 if (options.cipher == -1) {
399 "Unknown cipher type '%s'\n",
403 if (options.cipher == SSH_CIPHER_3DES)
404 options.ciphers = "3des-cbc";
405 else if (options.cipher == SSH_CIPHER_BLOWFISH)
406 options.ciphers = "blowfish-cbc";
408 options.ciphers = (char *)-1;
412 if (mac_valid(optarg))
413 options.macs = xstrdup(optarg);
415 fprintf(stderr, "Unknown mac type '%s'\n",
421 if (options.control_master == SSHCTL_MASTER_YES)
422 options.control_master = SSHCTL_MASTER_ASK;
424 options.control_master = SSHCTL_MASTER_YES;
427 options.port = a2port(optarg);
428 if (options.port == 0) {
429 fprintf(stderr, "Bad port '%s'\n", optarg);
434 options.user = optarg;
438 if (parse_forward(&fwd, optarg))
439 add_local_forward(&options, &fwd);
442 "Bad local forwarding specification '%s'\n",
449 if (parse_forward(&fwd, optarg)) {
450 add_remote_forward(&options, &fwd);
453 "Bad remote forwarding specification "
460 cp = p = xstrdup(optarg);
461 memset(&fwd, '\0', sizeof(fwd));
462 fwd.connect_host = "socks";
463 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
464 fprintf(stderr, "Bad dynamic forwarding "
465 "specification '%.100s'\n", optarg);
469 fwd.listen_port = a2port(cp);
470 fwd.listen_host = cleanhostname(fwd.listen_host);
472 fwd.listen_port = a2port(fwd.listen_host);
473 fwd.listen_host = NULL;
476 if (fwd.listen_port == 0) {
477 fprintf(stderr, "Bad dynamic port '%s'\n",
481 add_local_forward(&options, &fwd);
486 options.compression = 1;
497 line = xstrdup(optarg);
498 if (process_config_line(&options, host ? host : "",
499 line, "command-line", 0, &dummy) != 0)
507 if (options.control_path != NULL)
508 free(options.control_path);
509 options.control_path = xstrdup(optarg);
512 options.bind_address = optarg;
525 if (ac > 0 && !host && **av != '-') {
526 if (strrchr(*av, '@')) {
528 cp = strrchr(p, '@');
529 if (cp == NULL || cp == p)
537 optind = optreset = 1;
543 /* Check that we got a host name. */
547 SSLeay_add_all_algorithms();
548 ERR_load_crypto_strings();
550 /* Initialize the command to execute on remote host. */
551 buffer_init(&command);
554 * Save the command to execute on the remote host in a buffer. There
555 * is no limit on the length of the command, except by the maximum
556 * packet size. Also sets the tty flag if there is no command.
559 /* No command specified - execute shell on a tty. */
561 if (subsystem_flag) {
563 "You must specify a subsystem to invoke.\n");
567 /* A command has been specified. Store it into the buffer. */
568 for (i = 0; i < ac; i++) {
570 buffer_append(&command, " ", 1);
571 buffer_append(&command, av[i], strlen(av[i]));
575 /* Cannot fork to background if no command. */
576 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
577 fatal("Cannot fork into background without a command to execute.");
579 /* Allocate a tty by default if no command specified. */
580 if (buffer_len(&command) == 0)
586 /* Do not allocate a tty if stdin is not a tty. */
587 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
589 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
594 * Initialize "log" output. Since we are the client all output
595 * actually goes to stderr.
597 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
598 SYSLOG_FACILITY_USER, 1);
601 * Read per-user configuration file. Ignore the system wide config
602 * file if the user specifies a config file on the command line.
604 if (config != NULL) {
605 if (!read_config_file(config, host, &options, 0))
606 fatal("Can't open user config file %.100s: "
607 "%.100s", config, strerror(errno));
609 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
610 _PATH_SSH_USER_CONFFILE);
611 (void)read_config_file(buf, host, &options, 1);
613 /* Read systemwide configuration file after use config. */
614 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
618 /* Fill configuration defaults. */
619 fill_default_options(&options);
621 channel_set_af(options.address_family);
624 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
628 if (options.user == NULL)
629 options.user = xstrdup(pw->pw_name);
631 if (options.hostname != NULL)
632 host = options.hostname;
634 /* force lowercase for hostkey matching */
635 if (options.host_key_alias != NULL) {
636 for (p = options.host_key_alias; *p; p++)
638 *p = (char)tolower(*p);
641 /* Get default port if port has not been set. */
642 if (options.port == 0) {
643 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
644 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
647 if (options.proxy_command != NULL &&
648 strcmp(options.proxy_command, "none") == 0)
649 options.proxy_command = NULL;
650 if (options.control_path != NULL &&
651 strcmp(options.control_path, "none") == 0)
652 options.control_path = NULL;
654 if (options.control_path != NULL) {
655 char thishost[NI_MAXHOST];
657 if (gethostname(thishost, sizeof(thishost)) == -1)
658 fatal("gethostname: %s", strerror(errno));
659 snprintf(buf, sizeof(buf), "%d", options.port);
660 cp = tilde_expand_filename(options.control_path,
662 options.control_path = percent_expand(cp, "p", buf, "h", host,
663 "r", options.user, "l", thishost, (char *)NULL);
666 if (mux_command != 0 && options.control_path == NULL)
667 fatal("No ControlPath specified for \"-O\" command");
668 if (options.control_path != NULL)
669 control_client(options.control_path);
671 /* Open a connection to the remote host. */
672 if (ssh_connect(host, &hostaddr, options.port,
673 options.address_family, options.connection_attempts,
675 options.use_privileged_port,
677 original_effective_uid == 0 && options.use_privileged_port,
679 options.proxy_command) != 0)
683 * If we successfully made the connection, load the host private key
684 * in case we will need it later for combined rsa-rhosts
685 * authentication. This must be done before releasing extra
686 * privileges, because the file is only readable by root.
687 * If we cannot access the private keys, load the public keys
688 * instead and try to execute the ssh-keysign helper instead.
690 sensitive_data.nkeys = 0;
691 sensitive_data.keys = NULL;
692 sensitive_data.external_keysign = 0;
693 if (options.rhosts_rsa_authentication ||
694 options.hostbased_authentication) {
695 sensitive_data.nkeys = 3;
696 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
700 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
701 _PATH_HOST_KEY_FILE, "", NULL, NULL);
702 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
703 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
704 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
705 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
708 if (options.hostbased_authentication == 1 &&
709 sensitive_data.keys[0] == NULL &&
710 sensitive_data.keys[1] == NULL &&
711 sensitive_data.keys[2] == NULL) {
712 sensitive_data.keys[1] = key_load_public(
713 _PATH_HOST_DSA_KEY_FILE, NULL);
714 sensitive_data.keys[2] = key_load_public(
715 _PATH_HOST_RSA_KEY_FILE, NULL);
716 sensitive_data.external_keysign = 1;
720 * Get rid of any extra privileges that we may have. We will no
721 * longer need them. Also, extra privileges could make it very hard
722 * to read identity files and other non-world-readable files from the
723 * user's home directory if it happens to be on a NFS volume where
724 * root is mapped to nobody.
726 if (original_effective_uid == 0) {
728 permanently_set_uid(pw);
732 * Now that we are back to our own permissions, create ~/.ssh
733 * directory if it doesn't already exist.
735 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
736 if (stat(buf, &st) < 0)
737 if (mkdir(buf, 0700) < 0)
738 error("Could not create directory '%.200s'.", buf);
740 /* load options.identity_files */
741 load_public_identity_files();
743 /* Expand ~ in known host file names. */
745 options.system_hostfile =
746 tilde_expand_filename(options.system_hostfile, original_real_uid);
747 options.user_hostfile =
748 tilde_expand_filename(options.user_hostfile, original_real_uid);
749 options.system_hostfile2 =
750 tilde_expand_filename(options.system_hostfile2, original_real_uid);
751 options.user_hostfile2 =
752 tilde_expand_filename(options.user_hostfile2, original_real_uid);
754 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
756 /* Log into the remote system. This never returns if the login fails. */
757 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
759 /* We no longer need the private host keys. Clear them now. */
760 if (sensitive_data.nkeys != 0) {
761 for (i = 0; i < sensitive_data.nkeys; i++) {
762 if (sensitive_data.keys[i] != NULL) {
763 /* Destroys contents safely */
764 debug3("clear hostkey %d", i);
765 key_free(sensitive_data.keys[i]);
766 sensitive_data.keys[i] = NULL;
769 xfree(sensitive_data.keys);
771 for (i = 0; i < options.num_identity_files; i++) {
772 if (options.identity_files[i]) {
773 xfree(options.identity_files[i]);
774 options.identity_files[i] = NULL;
776 if (options.identity_keys[i]) {
777 key_free(options.identity_keys[i]);
778 options.identity_keys[i] = NULL;
782 exit_status = compat20 ? ssh_session2() : ssh_session();
785 if (options.control_path != NULL && control_fd != -1)
786 unlink(options.control_path);
789 * Send SIGHUP to proxy command if used. We don't wait() in
790 * case it hangs and instead rely on init to reap the child
792 if (proxy_command_pid > 1)
793 kill(proxy_command_pid, SIGHUP);
799 ssh_init_forwarding(void)
804 /* Initiate local TCP/IP port forwardings. */
805 for (i = 0; i < options.num_local_forwards; i++) {
806 debug("Local connections to %.200s:%d forwarded to remote "
808 (options.local_forwards[i].listen_host == NULL) ?
809 (options.gateway_ports ? "*" : "LOCALHOST") :
810 options.local_forwards[i].listen_host,
811 options.local_forwards[i].listen_port,
812 options.local_forwards[i].connect_host,
813 options.local_forwards[i].connect_port);
814 success += channel_setup_local_fwd_listener(
815 options.local_forwards[i].listen_host,
816 options.local_forwards[i].listen_port,
817 options.local_forwards[i].connect_host,
818 options.local_forwards[i].connect_port,
819 options.gateway_ports);
821 if (i > 0 && success != i && options.exit_on_forward_failure)
822 fatal("Could not request local forwarding.");
823 if (i > 0 && success == 0)
824 error("Could not request local forwarding.");
826 /* Initiate remote TCP/IP port forwardings. */
827 for (i = 0; i < options.num_remote_forwards; i++) {
828 debug("Remote connections from %.200s:%d forwarded to "
829 "local address %.200s:%d",
830 (options.remote_forwards[i].listen_host == NULL) ?
831 "LOCALHOST" : options.remote_forwards[i].listen_host,
832 options.remote_forwards[i].listen_port,
833 options.remote_forwards[i].connect_host,
834 options.remote_forwards[i].connect_port);
835 if (channel_request_remote_forwarding(
836 options.remote_forwards[i].listen_host,
837 options.remote_forwards[i].listen_port,
838 options.remote_forwards[i].connect_host,
839 options.remote_forwards[i].connect_port) < 0) {
840 if (options.exit_on_forward_failure)
841 fatal("Could not request remote forwarding.");
843 logit("Warning: Could not request remote "
850 check_agent_present(void)
852 if (options.forward_agent) {
853 /* Clear agent forwarding if we don't have an agent. */
854 if (!ssh_agent_present())
855 options.forward_agent = 0;
869 /* Enable compression if requested. */
870 if (options.compression) {
871 debug("Requesting compression at level %d.", options.compression_level);
873 if (options.compression_level < 1 || options.compression_level > 9)
874 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
876 /* Send the request. */
877 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
878 packet_put_int(options.compression_level);
881 type = packet_read();
882 if (type == SSH_SMSG_SUCCESS)
883 packet_start_compression(options.compression_level);
884 else if (type == SSH_SMSG_FAILURE)
885 logit("Warning: Remote host refused compression.");
887 packet_disconnect("Protocol error waiting for compression response.");
889 /* Allocate a pseudo tty if appropriate. */
891 debug("Requesting pty.");
893 /* Start the packet. */
894 packet_start(SSH_CMSG_REQUEST_PTY);
896 /* Store TERM in the packet. There is no limit on the
897 length of the string. */
901 packet_put_cstring(cp);
903 /* Store window size in the packet. */
904 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
905 memset(&ws, 0, sizeof(ws));
906 packet_put_int((u_int)ws.ws_row);
907 packet_put_int((u_int)ws.ws_col);
908 packet_put_int((u_int)ws.ws_xpixel);
909 packet_put_int((u_int)ws.ws_ypixel);
911 /* Store tty modes in the packet. */
912 tty_make_modes(fileno(stdin), NULL);
914 /* Send the packet, and wait for it to leave. */
918 /* Read response from the server. */
919 type = packet_read();
920 if (type == SSH_SMSG_SUCCESS) {
923 } else if (type == SSH_SMSG_FAILURE)
924 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
926 packet_disconnect("Protocol error waiting for pty request response.");
928 /* Request X11 forwarding if enabled and DISPLAY is set. */
929 display = getenv("DISPLAY");
930 if (options.forward_x11 && display != NULL) {
932 /* Get reasonable local authentication information. */
933 client_x11_get_proto(display, options.xauth_location,
934 options.forward_x11_trusted, &proto, &data);
935 /* Request forwarding with authentication spoofing. */
936 debug("Requesting X11 forwarding with authentication spoofing.");
937 x11_request_forwarding_with_spoofing(0, display, proto, data);
939 /* Read response from the server. */
940 type = packet_read();
941 if (type == SSH_SMSG_SUCCESS) {
943 } else if (type == SSH_SMSG_FAILURE) {
944 logit("Warning: Remote host denied X11 forwarding.");
946 packet_disconnect("Protocol error waiting for X11 forwarding");
949 /* Tell the packet module whether this is an interactive session. */
950 packet_set_interactive(interactive);
952 /* Request authentication agent forwarding if appropriate. */
953 check_agent_present();
955 if (options.forward_agent) {
956 debug("Requesting authentication agent forwarding.");
957 auth_request_forwarding();
959 /* Read response from the server. */
960 type = packet_read();
962 if (type != SSH_SMSG_SUCCESS)
963 logit("Warning: Remote host denied authentication agent forwarding.");
966 /* Initiate port forwardings. */
967 ssh_init_forwarding();
969 /* If requested, let ssh continue in the background. */
970 if (fork_after_authentication_flag)
971 if (daemon(1, 1) < 0)
972 fatal("daemon() failed: %.200s", strerror(errno));
975 * If a command was specified on the command line, execute the
976 * command now. Otherwise request the server to start a shell.
978 if (buffer_len(&command) > 0) {
979 int len = buffer_len(&command);
982 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
983 packet_start(SSH_CMSG_EXEC_CMD);
984 packet_put_string(buffer_ptr(&command), buffer_len(&command));
988 debug("Requesting shell.");
989 packet_start(SSH_CMSG_EXEC_SHELL);
994 /* Enter the interactive session. */
995 return client_loop(have_tty, tty_flag ?
996 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1000 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1004 id = packet_get_int();
1005 len = buffer_len(&command);
1009 if (type == SSH2_MSG_CHANNEL_FAILURE)
1010 fatal("Request for subsystem '%.*s' failed on channel %d",
1011 len, (u_char *)buffer_ptr(&command), id);
1015 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1019 i = client_global_request_id++;
1020 if (i >= options.num_remote_forwards)
1022 debug("remote forward %s for: listen %d, connect %s:%d",
1023 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1024 options.remote_forwards[i].listen_port,
1025 options.remote_forwards[i].connect_host,
1026 options.remote_forwards[i].connect_port);
1027 if (type == SSH2_MSG_REQUEST_FAILURE) {
1028 if (options.exit_on_forward_failure)
1029 fatal("Error: remote port forwarding failed for "
1031 options.remote_forwards[i].listen_port);
1033 logit("Warning: remote port forwarding failed for "
1035 options.remote_forwards[i].listen_port);
1040 ssh_control_listener(void)
1042 struct sockaddr_un addr;
1046 if (options.control_path == NULL ||
1047 options.control_master == SSHCTL_MASTER_NO)
1050 debug("setting up multiplex master socket");
1052 memset(&addr, '\0', sizeof(addr));
1053 addr.sun_family = AF_UNIX;
1054 addr_len = offsetof(struct sockaddr_un, sun_path) +
1055 strlen(options.control_path) + 1;
1057 if (strlcpy(addr.sun_path, options.control_path,
1058 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1059 fatal("ControlPath too long");
1061 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1062 fatal("%s socket(): %s", __func__, strerror(errno));
1064 old_umask = umask(0177);
1065 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1067 if (errno == EINVAL || errno == EADDRINUSE)
1068 fatal("ControlSocket %s already exists",
1069 options.control_path);
1071 fatal("%s bind(): %s", __func__, strerror(errno));
1075 if (listen(control_fd, 64) == -1)
1076 fatal("%s listen(): %s", __func__, strerror(errno));
1078 set_nonblock(control_fd);
1081 /* request pty/x11/agent/tcpfwd/shell for channel */
1083 ssh_session2_setup(int id, void *arg)
1085 extern char **environ;
1086 const char *display;
1087 int interactive = tty_flag;
1089 display = getenv("DISPLAY");
1090 if (options.forward_x11 && display != NULL) {
1092 /* Get reasonable local authentication information. */
1093 client_x11_get_proto(display, options.xauth_location,
1094 options.forward_x11_trusted, &proto, &data);
1095 /* Request forwarding with authentication spoofing. */
1096 debug("Requesting X11 forwarding with authentication spoofing.");
1097 x11_request_forwarding_with_spoofing(id, display, proto, data);
1099 /* XXX wait for reply */
1102 check_agent_present();
1103 if (options.forward_agent) {
1104 debug("Requesting authentication agent forwarding.");
1105 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1109 if (options.tun_open != SSH_TUNMODE_NO) {
1113 debug("Requesting tun.");
1114 if ((fd = tun_open(options.tun_local,
1115 options.tun_open)) >= 0) {
1116 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1117 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1120 #if defined(SSH_TUN_FILTER)
1121 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1122 channel_register_filter(c->self, sys_tun_infilter,
1125 packet_start(SSH2_MSG_CHANNEL_OPEN);
1126 packet_put_cstring("tun@openssh.com");
1127 packet_put_int(c->self);
1128 packet_put_int(c->local_window_max);
1129 packet_put_int(c->local_maxpacket);
1130 packet_put_int(options.tun_open);
1131 packet_put_int(options.tun_remote);
1136 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1137 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1139 packet_set_interactive(interactive);
1142 /* open new channel for a session */
1144 ssh_session2_open(void)
1147 int window, packetmax, in, out, err;
1149 if (stdin_null_flag) {
1150 in = open(_PATH_DEVNULL, O_RDONLY);
1152 in = dup(STDIN_FILENO);
1154 out = dup(STDOUT_FILENO);
1155 err = dup(STDERR_FILENO);
1157 if (in < 0 || out < 0 || err < 0)
1158 fatal("dup() in/out/err failed");
1160 /* enable nonblocking unless tty */
1168 window = CHAN_SES_WINDOW_DEFAULT;
1169 packetmax = CHAN_SES_PACKET_DEFAULT;
1175 "session", SSH_CHANNEL_OPENING, in, out, err,
1176 window, packetmax, CHAN_EXTENDED_WRITE,
1177 "client-session", /*nonblock*/0);
1179 debug3("ssh_session2_open: channel_new: %d", c->self);
1181 channel_send_open(c->self);
1183 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1193 /* XXX should be pre-session */
1194 ssh_init_forwarding();
1195 ssh_control_listener();
1197 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1198 id = ssh_session2_open();
1200 /* Execute a local command */
1201 if (options.local_command != NULL &&
1202 options.permit_local_command)
1203 ssh_local_cmd(options.local_command);
1205 /* If requested, let ssh continue in the background. */
1206 if (fork_after_authentication_flag)
1207 if (daemon(1, 1) < 0)
1208 fatal("daemon() failed: %.200s", strerror(errno));
1210 return client_loop(tty_flag, tty_flag ?
1211 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1215 load_public_identity_files(void)
1217 char *filename, *cp, thishost[NI_MAXHOST];
1224 if (options.smartcard_device != NULL &&
1225 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1226 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1228 for (i = 0; keys[i] != NULL; i++) {
1230 memmove(&options.identity_files[1], &options.identity_files[0],
1231 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1232 memmove(&options.identity_keys[1], &options.identity_keys[0],
1233 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1234 options.num_identity_files++;
1235 options.identity_keys[0] = keys[i];
1236 options.identity_files[0] = sc_get_key_label(keys[i]);
1238 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1239 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1243 #endif /* SMARTCARD */
1244 if ((pw = getpwuid(original_real_uid)) == NULL)
1245 fatal("load_public_identity_files: getpwuid failed");
1246 if (gethostname(thishost, sizeof(thishost)) == -1)
1247 fatal("load_public_identity_files: gethostname: %s",
1249 for (; i < options.num_identity_files; i++) {
1250 cp = tilde_expand_filename(options.identity_files[i],
1252 filename = percent_expand(cp, "d", pw->pw_dir,
1253 "u", pw->pw_name, "l", thishost, "h", host,
1254 "r", options.user, (char *)NULL);
1256 public = key_load_public(filename, NULL);
1257 debug("identity file %s type %d", filename,
1258 public ? public->type : -1);
1259 xfree(options.identity_files[i]);
1260 options.identity_files[i] = filename;
1261 options.identity_keys[i] = public;
1266 control_client_sighandler(int signo)
1268 control_client_terminate = signo;
1272 control_client_sigrelay(int signo)
1274 if (control_server_pid > 1)
1275 kill(control_server_pid, signo);
1279 env_permitted(char *env)
1282 char name[1024], *cp;
1284 if ((cp = strchr(env, '=')) == NULL || cp == env)
1286 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1287 if (ret <= 0 || (size_t)ret >= sizeof(name))
1288 fatal("env_permitted: name '%.100s...' too long", env);
1290 for (i = 0; i < options.num_send_env; i++)
1291 if (match_pattern(name, options.send_env[i]))
1298 control_client(const char *path)
1300 struct sockaddr_un addr;
1301 int i, r, fd, sock, exitval, num_env, addr_len;
1304 extern char **environ;
1307 if (mux_command == 0)
1308 mux_command = SSHMUX_COMMAND_OPEN;
1310 switch (options.control_master) {
1311 case SSHCTL_MASTER_AUTO:
1312 case SSHCTL_MASTER_AUTO_ASK:
1313 debug("auto-mux: Trying existing master");
1315 case SSHCTL_MASTER_NO:
1321 memset(&addr, '\0', sizeof(addr));
1322 addr.sun_family = AF_UNIX;
1323 addr_len = offsetof(struct sockaddr_un, sun_path) +
1326 if (strlcpy(addr.sun_path, path,
1327 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1328 fatal("ControlPath too long");
1330 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1331 fatal("%s socket(): %s", __func__, strerror(errno));
1333 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1334 if (mux_command != SSHMUX_COMMAND_OPEN) {
1335 fatal("Control socket connect(%.100s): %s", path,
1338 if (errno == ENOENT)
1339 debug("Control socket \"%.100s\" does not exist", path);
1341 error("Control socket connect(%.100s): %s", path,
1348 if (stdin_null_flag) {
1349 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1350 fatal("open(/dev/null): %s", strerror(errno));
1351 if (dup2(fd, STDIN_FILENO) == -1)
1352 fatal("dup2: %s", strerror(errno));
1353 if (fd > STDERR_FILENO)
1357 term = getenv("TERM");
1361 flags |= SSHMUX_FLAG_TTY;
1363 flags |= SSHMUX_FLAG_SUBSYS;
1364 if (options.forward_x11)
1365 flags |= SSHMUX_FLAG_X11_FWD;
1366 if (options.forward_agent)
1367 flags |= SSHMUX_FLAG_AGENT_FWD;
1371 /* Send our command to server */
1372 buffer_put_int(&m, mux_command);
1373 buffer_put_int(&m, flags);
1374 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1375 fatal("%s: msg_send", __func__);
1378 /* Get authorisation status and PID of controlee */
1379 if (ssh_msg_recv(sock, &m) == -1)
1380 fatal("%s: msg_recv", __func__);
1381 if (buffer_get_char(&m) != SSHMUX_VER)
1382 fatal("%s: wrong version", __func__);
1383 if (buffer_get_int(&m) != 1)
1384 fatal("Connection to master denied");
1385 control_server_pid = buffer_get_int(&m);
1389 switch (mux_command) {
1390 case SSHMUX_COMMAND_ALIVE_CHECK:
1391 fprintf(stderr, "Master running (pid=%d)\r\n",
1392 control_server_pid);
1394 case SSHMUX_COMMAND_TERMINATE:
1395 fprintf(stderr, "Exit request sent.\r\n");
1397 case SSHMUX_COMMAND_OPEN:
1398 /* continue below */
1401 fatal("silly mux_command %d", mux_command);
1404 /* SSHMUX_COMMAND_OPEN */
1405 buffer_put_cstring(&m, term ? term : "");
1406 buffer_append(&command, "\0", 1);
1407 buffer_put_cstring(&m, buffer_ptr(&command));
1409 if (options.num_send_env == 0 || environ == NULL) {
1410 buffer_put_int(&m, 0);
1412 /* Pass environment */
1414 for (i = 0; environ[i] != NULL; i++)
1415 if (env_permitted(environ[i]))
1416 num_env++; /* Count */
1418 buffer_put_int(&m, num_env);
1420 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1421 if (env_permitted(environ[i])) {
1423 buffer_put_cstring(&m, environ[i]);
1427 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1428 fatal("%s: msg_send", __func__);
1430 mm_send_fd(sock, STDIN_FILENO);
1431 mm_send_fd(sock, STDOUT_FILENO);
1432 mm_send_fd(sock, STDERR_FILENO);
1434 /* Wait for reply, so master has a chance to gather ttymodes */
1436 if (ssh_msg_recv(sock, &m) == -1)
1437 fatal("%s: msg_recv", __func__);
1438 if (buffer_get_char(&m) != SSHMUX_VER)
1439 fatal("%s: wrong version", __func__);
1442 signal(SIGHUP, control_client_sighandler);
1443 signal(SIGINT, control_client_sighandler);
1444 signal(SIGTERM, control_client_sighandler);
1445 signal(SIGWINCH, control_client_sigrelay);
1450 /* Stick around until the controlee closes the client_fd */
1452 for (;!control_client_terminate;) {
1453 r = read(sock, &exitval, sizeof(exitval));
1455 debug2("Received EOF from master");
1459 debug2("Received exit status from master %d", exitval);
1460 if (r == -1 && errno != EINTR)
1461 fatal("%s: read %s", __func__, strerror(errno));
1464 if (control_client_terminate)
1465 debug2("Exiting on signal %d", control_client_terminate);
1471 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1472 fprintf(stderr, "Connection to master closed.\r\n");