1 /* $OpenBSD: ssh.c,v 1.289 2006/07/22 20:48:23 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>
57 #if defined(HAVE_NETDB_H)
69 #include <openssl/evp.h>
70 #include <openssl/err.h>
85 #include "pathnames.h"
87 #include "clientloop.h"
90 #include "sshconnect.h"
97 #include "monitor_fdpass.h"
105 extern char *__progname;
107 /* Flag indicating whether debug mode is on. This can be set on the command line. */
110 /* Flag indicating whether a tty should be allocated */
113 int force_tty_flag = 0;
115 /* don't exec a shell */
116 int no_shell_flag = 0;
119 * Flag indicating that nothing should be read from stdin. This can be set
120 * on the command line.
122 int stdin_null_flag = 0;
125 * Flag indicating that ssh should fork after authentication. This is useful
126 * so that the passphrase can be entered manually, and then ssh goes to the
129 int fork_after_authentication_flag = 0;
132 * General data structure for command line options and options configurable
133 * in configuration files. See readconf.h.
137 /* optional user configfile */
141 * Name of the host we are connecting to. This is the name given on the
142 * command line, or the HostName specified for the user-supplied name in a
143 * configuration file.
147 /* socket address the host resolves to */
148 struct sockaddr_storage hostaddr;
150 /* Private host keys. */
151 Sensitive sensitive_data;
153 /* Original real UID. */
154 uid_t original_real_uid;
155 uid_t original_effective_uid;
157 /* command to be executed */
160 /* Should we execute a command or invoke a subsystem? */
161 int subsystem_flag = 0;
163 /* # of replies received for global requests */
164 static int client_global_request_id = 0;
166 /* pid of proxycommand child process */
167 pid_t proxy_command_pid = 0;
169 /* fd to control socket */
172 /* Multiplexing control command */
173 static u_int mux_command = 0;
175 /* Only used in control client mode */
176 volatile sig_atomic_t control_client_terminate = 0;
177 u_int control_server_pid = 0;
179 /* Prints a help message to the user. This function never returns. */
185 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
186 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
187 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
188 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
189 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
190 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
195 static int ssh_session(void);
196 static int ssh_session2(void);
197 static void load_public_identity_files(void);
198 static void control_client(const char *path);
201 * Main program for the ssh client.
204 main(int ac, char **av)
206 int i, opt, exit_status;
207 char *p, *cp, *line, buf[256];
211 extern int optind, optreset;
216 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
219 __progname = ssh_get_progname(av[0]);
223 * Save the original real uid. It will be needed later (uid-swapping
224 * may clobber the real uid).
226 original_real_uid = getuid();
227 original_effective_uid = geteuid();
230 * Use uid-swapping to give up root privileges for the duration of
231 * option processing. We will re-instantiate the rights when we are
232 * ready to create the privileged port, and will permanently drop
233 * them when the port has been created (actually, when the connection
234 * has been made, as we may need to create the port several times).
238 #ifdef HAVE_SETRLIMIT
239 /* If we are installed setuid root be careful to not drop core. */
240 if (original_real_uid != original_effective_uid) {
242 rlim.rlim_cur = rlim.rlim_max = 0;
243 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
244 fatal("setrlimit failed: %.100s", strerror(errno));
248 pw = getpwuid(original_real_uid);
250 logit("You don't exist, go away!");
253 /* Take a copy of the returned structure. */
257 * Set our umask to something reasonable, as some files are created
258 * with the default umask. This will make them world-readable but
259 * writable only by the owner, which is ok for all files for which we
260 * don't set the modes explicitly.
264 /* Initialize option structure to indicate that no values have been set. */
265 initialize_options(&options);
267 /* Parse command-line arguments. */
271 while ((opt = getopt(ac, av,
272 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
275 options.protocol = SSH_PROTO_1;
278 options.protocol = SSH_PROTO_2;
281 options.address_family = AF_INET;
284 options.address_family = AF_INET6;
290 fork_after_authentication_flag = 1;
294 options.forward_x11 = 0;
297 options.forward_x11 = 1;
300 options.forward_x11 = 1;
301 options.forward_x11_trusted = 1;
304 options.gateway_ports = 1;
307 if (strcmp(optarg, "check") == 0)
308 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
309 else if (strcmp(optarg, "exit") == 0)
310 mux_command = SSHMUX_COMMAND_TERMINATE;
312 fatal("Invalid multiplex command.");
314 case 'P': /* deprecated */
315 options.use_privileged_port = 0;
318 options.forward_agent = 0;
321 options.forward_agent = 1;
324 options.gss_deleg_creds = 0;
327 if (stat(optarg, &st) < 0) {
328 fprintf(stderr, "Warning: Identity file %s "
329 "not accessible: %s.\n", optarg,
333 if (options.num_identity_files >=
334 SSH_MAX_IDENTITY_FILES)
335 fatal("Too many identity files specified "
336 "(max %d)", SSH_MAX_IDENTITY_FILES);
337 options.identity_files[options.num_identity_files++] =
342 options.smartcard_device = xstrdup(optarg);
344 fprintf(stderr, "no support for smartcards.\n");
353 if (debug_flag == 0) {
355 options.log_level = SYSLOG_LEVEL_DEBUG1;
357 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
363 fprintf(stderr, "%s, %s\n",
364 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
369 if (options.tun_open == -1)
370 options.tun_open = SSH_TUNMODE_DEFAULT;
371 options.tun_local = a2tun(optarg, &options.tun_remote);
372 if (options.tun_local == SSH_TUNID_ERR) {
373 fprintf(stderr, "Bad tun device '%s'\n", optarg);
378 options.log_level = SYSLOG_LEVEL_QUIET;
381 if (optarg[0] == '^' && optarg[2] == 0 &&
382 (u_char) optarg[1] >= 64 &&
383 (u_char) optarg[1] < 128)
384 options.escape_char = (u_char) optarg[1] & 31;
385 else if (strlen(optarg) == 1)
386 options.escape_char = (u_char) optarg[0];
387 else if (strcmp(optarg, "none") == 0)
388 options.escape_char = SSH_ESCAPECHAR_NONE;
390 fprintf(stderr, "Bad escape character '%s'.\n",
396 if (ciphers_valid(optarg)) {
398 options.ciphers = xstrdup(optarg);
399 options.cipher = SSH_CIPHER_INVALID;
402 options.cipher = cipher_number(optarg);
403 if (options.cipher == -1) {
405 "Unknown cipher type '%s'\n",
409 if (options.cipher == SSH_CIPHER_3DES)
410 options.ciphers = "3des-cbc";
411 else if (options.cipher == SSH_CIPHER_BLOWFISH)
412 options.ciphers = "blowfish-cbc";
414 options.ciphers = (char *)-1;
418 if (mac_valid(optarg))
419 options.macs = xstrdup(optarg);
421 fprintf(stderr, "Unknown mac type '%s'\n",
427 if (options.control_master == SSHCTL_MASTER_YES)
428 options.control_master = SSHCTL_MASTER_ASK;
430 options.control_master = SSHCTL_MASTER_YES;
433 options.port = a2port(optarg);
434 if (options.port == 0) {
435 fprintf(stderr, "Bad port '%s'\n", optarg);
440 options.user = optarg;
444 if (parse_forward(&fwd, optarg))
445 add_local_forward(&options, &fwd);
448 "Bad local forwarding specification '%s'\n",
455 if (parse_forward(&fwd, optarg)) {
456 add_remote_forward(&options, &fwd);
459 "Bad remote forwarding specification "
466 cp = p = xstrdup(optarg);
467 memset(&fwd, '\0', sizeof(fwd));
468 fwd.connect_host = "socks";
469 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
470 fprintf(stderr, "Bad dynamic forwarding "
471 "specification '%.100s'\n", optarg);
475 fwd.listen_port = a2port(cp);
476 fwd.listen_host = cleanhostname(fwd.listen_host);
478 fwd.listen_port = a2port(fwd.listen_host);
479 fwd.listen_host = NULL;
482 if (fwd.listen_port == 0) {
483 fprintf(stderr, "Bad dynamic port '%s'\n",
487 add_local_forward(&options, &fwd);
492 options.compression = 1;
503 line = xstrdup(optarg);
504 if (process_config_line(&options, host ? host : "",
505 line, "command-line", 0, &dummy) != 0)
513 if (options.control_path != NULL)
514 free(options.control_path);
515 options.control_path = xstrdup(optarg);
518 options.bind_address = optarg;
531 if (ac > 0 && !host && **av != '-') {
532 if (strrchr(*av, '@')) {
534 cp = strrchr(p, '@');
535 if (cp == NULL || cp == p)
543 optind = optreset = 1;
549 /* Check that we got a host name. */
553 SSLeay_add_all_algorithms();
554 ERR_load_crypto_strings();
556 /* Initialize the command to execute on remote host. */
557 buffer_init(&command);
560 * Save the command to execute on the remote host in a buffer. There
561 * is no limit on the length of the command, except by the maximum
562 * packet size. Also sets the tty flag if there is no command.
565 /* No command specified - execute shell on a tty. */
567 if (subsystem_flag) {
569 "You must specify a subsystem to invoke.\n");
573 /* A command has been specified. Store it into the buffer. */
574 for (i = 0; i < ac; i++) {
576 buffer_append(&command, " ", 1);
577 buffer_append(&command, av[i], strlen(av[i]));
581 /* Cannot fork to background if no command. */
582 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
583 fatal("Cannot fork into background without a command to execute.");
585 /* Allocate a tty by default if no command specified. */
586 if (buffer_len(&command) == 0)
592 /* Do not allocate a tty if stdin is not a tty. */
593 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
595 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
600 * Initialize "log" output. Since we are the client all output
601 * actually goes to stderr.
603 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
604 SYSLOG_FACILITY_USER, 1);
607 * Read per-user configuration file. Ignore the system wide config
608 * file if the user specifies a config file on the command line.
610 if (config != NULL) {
611 if (!read_config_file(config, host, &options, 0))
612 fatal("Can't open user config file %.100s: "
613 "%.100s", config, strerror(errno));
615 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
616 _PATH_SSH_USER_CONFFILE);
617 (void)read_config_file(buf, host, &options, 1);
619 /* Read systemwide configuration file after use config. */
620 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
624 /* Fill configuration defaults. */
625 fill_default_options(&options);
627 channel_set_af(options.address_family);
630 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
634 if (options.user == NULL)
635 options.user = xstrdup(pw->pw_name);
637 if (options.hostname != NULL)
638 host = options.hostname;
640 /* force lowercase for hostkey matching */
641 if (options.host_key_alias != NULL) {
642 for (p = options.host_key_alias; *p; p++)
644 *p = (char)tolower(*p);
647 /* Get default port if port has not been set. */
648 if (options.port == 0) {
649 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
650 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
653 if (options.proxy_command != NULL &&
654 strcmp(options.proxy_command, "none") == 0)
655 options.proxy_command = NULL;
656 if (options.control_path != NULL &&
657 strcmp(options.control_path, "none") == 0)
658 options.control_path = NULL;
660 if (options.control_path != NULL) {
661 char thishost[NI_MAXHOST];
663 if (gethostname(thishost, sizeof(thishost)) == -1)
664 fatal("gethostname: %s", strerror(errno));
665 snprintf(buf, sizeof(buf), "%d", options.port);
666 cp = tilde_expand_filename(options.control_path,
668 options.control_path = percent_expand(cp, "p", buf, "h", host,
669 "r", options.user, "l", thishost, (char *)NULL);
672 if (mux_command != 0 && options.control_path == NULL)
673 fatal("No ControlPath specified for \"-O\" command");
674 if (options.control_path != NULL)
675 control_client(options.control_path);
677 /* Open a connection to the remote host. */
678 if (ssh_connect(host, &hostaddr, options.port,
679 options.address_family, options.connection_attempts,
681 options.use_privileged_port,
683 original_effective_uid == 0 && options.use_privileged_port,
685 options.proxy_command) != 0)
689 * If we successfully made the connection, load the host private key
690 * in case we will need it later for combined rsa-rhosts
691 * authentication. This must be done before releasing extra
692 * privileges, because the file is only readable by root.
693 * If we cannot access the private keys, load the public keys
694 * instead and try to execute the ssh-keysign helper instead.
696 sensitive_data.nkeys = 0;
697 sensitive_data.keys = NULL;
698 sensitive_data.external_keysign = 0;
699 if (options.rhosts_rsa_authentication ||
700 options.hostbased_authentication) {
701 sensitive_data.nkeys = 3;
702 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
706 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
707 _PATH_HOST_KEY_FILE, "", NULL, NULL);
708 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
709 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
710 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
711 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
714 if (options.hostbased_authentication == 1 &&
715 sensitive_data.keys[0] == NULL &&
716 sensitive_data.keys[1] == NULL &&
717 sensitive_data.keys[2] == NULL) {
718 sensitive_data.keys[1] = key_load_public(
719 _PATH_HOST_DSA_KEY_FILE, NULL);
720 sensitive_data.keys[2] = key_load_public(
721 _PATH_HOST_RSA_KEY_FILE, NULL);
722 sensitive_data.external_keysign = 1;
726 * Get rid of any extra privileges that we may have. We will no
727 * longer need them. Also, extra privileges could make it very hard
728 * to read identity files and other non-world-readable files from the
729 * user's home directory if it happens to be on a NFS volume where
730 * root is mapped to nobody.
732 if (original_effective_uid == 0) {
734 permanently_set_uid(pw);
738 * Now that we are back to our own permissions, create ~/.ssh
739 * directory if it doesn't already exist.
741 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
742 if (stat(buf, &st) < 0)
743 if (mkdir(buf, 0700) < 0)
744 error("Could not create directory '%.200s'.", buf);
746 /* load options.identity_files */
747 load_public_identity_files();
749 /* Expand ~ in known host file names. */
751 options.system_hostfile =
752 tilde_expand_filename(options.system_hostfile, original_real_uid);
753 options.user_hostfile =
754 tilde_expand_filename(options.user_hostfile, original_real_uid);
755 options.system_hostfile2 =
756 tilde_expand_filename(options.system_hostfile2, original_real_uid);
757 options.user_hostfile2 =
758 tilde_expand_filename(options.user_hostfile2, original_real_uid);
760 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
762 /* Log into the remote system. This never returns if the login fails. */
763 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
765 /* We no longer need the private host keys. Clear them now. */
766 if (sensitive_data.nkeys != 0) {
767 for (i = 0; i < sensitive_data.nkeys; i++) {
768 if (sensitive_data.keys[i] != NULL) {
769 /* Destroys contents safely */
770 debug3("clear hostkey %d", i);
771 key_free(sensitive_data.keys[i]);
772 sensitive_data.keys[i] = NULL;
775 xfree(sensitive_data.keys);
777 for (i = 0; i < options.num_identity_files; i++) {
778 if (options.identity_files[i]) {
779 xfree(options.identity_files[i]);
780 options.identity_files[i] = NULL;
782 if (options.identity_keys[i]) {
783 key_free(options.identity_keys[i]);
784 options.identity_keys[i] = NULL;
788 exit_status = compat20 ? ssh_session2() : ssh_session();
791 if (options.control_path != NULL && control_fd != -1)
792 unlink(options.control_path);
795 * Send SIGHUP to proxy command if used. We don't wait() in
796 * case it hangs and instead rely on init to reap the child
798 if (proxy_command_pid > 1)
799 kill(proxy_command_pid, SIGHUP);
805 ssh_init_forwarding(void)
810 /* Initiate local TCP/IP port forwardings. */
811 for (i = 0; i < options.num_local_forwards; i++) {
812 debug("Local connections to %.200s:%d forwarded to remote "
814 (options.local_forwards[i].listen_host == NULL) ?
815 (options.gateway_ports ? "*" : "LOCALHOST") :
816 options.local_forwards[i].listen_host,
817 options.local_forwards[i].listen_port,
818 options.local_forwards[i].connect_host,
819 options.local_forwards[i].connect_port);
820 success += channel_setup_local_fwd_listener(
821 options.local_forwards[i].listen_host,
822 options.local_forwards[i].listen_port,
823 options.local_forwards[i].connect_host,
824 options.local_forwards[i].connect_port,
825 options.gateway_ports);
827 if (i > 0 && success != i && options.exit_on_forward_failure)
828 fatal("Could not request local forwarding.");
829 if (i > 0 && success == 0)
830 error("Could not request local forwarding.");
832 /* Initiate remote TCP/IP port forwardings. */
833 for (i = 0; i < options.num_remote_forwards; i++) {
834 debug("Remote connections from %.200s:%d forwarded to "
835 "local address %.200s:%d",
836 (options.remote_forwards[i].listen_host == NULL) ?
837 "LOCALHOST" : options.remote_forwards[i].listen_host,
838 options.remote_forwards[i].listen_port,
839 options.remote_forwards[i].connect_host,
840 options.remote_forwards[i].connect_port);
841 if (channel_request_remote_forwarding(
842 options.remote_forwards[i].listen_host,
843 options.remote_forwards[i].listen_port,
844 options.remote_forwards[i].connect_host,
845 options.remote_forwards[i].connect_port) < 0) {
846 if (options.exit_on_forward_failure)
847 fatal("Could not request remote forwarding.");
849 logit("Warning: Could not request remote "
856 check_agent_present(void)
858 if (options.forward_agent) {
859 /* Clear agent forwarding if we don't have an agent. */
860 if (!ssh_agent_present())
861 options.forward_agent = 0;
875 /* Enable compression if requested. */
876 if (options.compression) {
877 debug("Requesting compression at level %d.", options.compression_level);
879 if (options.compression_level < 1 || options.compression_level > 9)
880 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
882 /* Send the request. */
883 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
884 packet_put_int(options.compression_level);
887 type = packet_read();
888 if (type == SSH_SMSG_SUCCESS)
889 packet_start_compression(options.compression_level);
890 else if (type == SSH_SMSG_FAILURE)
891 logit("Warning: Remote host refused compression.");
893 packet_disconnect("Protocol error waiting for compression response.");
895 /* Allocate a pseudo tty if appropriate. */
897 debug("Requesting pty.");
899 /* Start the packet. */
900 packet_start(SSH_CMSG_REQUEST_PTY);
902 /* Store TERM in the packet. There is no limit on the
903 length of the string. */
907 packet_put_cstring(cp);
909 /* Store window size in the packet. */
910 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
911 memset(&ws, 0, sizeof(ws));
912 packet_put_int((u_int)ws.ws_row);
913 packet_put_int((u_int)ws.ws_col);
914 packet_put_int((u_int)ws.ws_xpixel);
915 packet_put_int((u_int)ws.ws_ypixel);
917 /* Store tty modes in the packet. */
918 tty_make_modes(fileno(stdin), NULL);
920 /* Send the packet, and wait for it to leave. */
924 /* Read response from the server. */
925 type = packet_read();
926 if (type == SSH_SMSG_SUCCESS) {
929 } else if (type == SSH_SMSG_FAILURE)
930 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
932 packet_disconnect("Protocol error waiting for pty request response.");
934 /* Request X11 forwarding if enabled and DISPLAY is set. */
935 display = getenv("DISPLAY");
936 if (options.forward_x11 && display != NULL) {
938 /* Get reasonable local authentication information. */
939 client_x11_get_proto(display, options.xauth_location,
940 options.forward_x11_trusted, &proto, &data);
941 /* Request forwarding with authentication spoofing. */
942 debug("Requesting X11 forwarding with authentication spoofing.");
943 x11_request_forwarding_with_spoofing(0, display, proto, data);
945 /* Read response from the server. */
946 type = packet_read();
947 if (type == SSH_SMSG_SUCCESS) {
949 } else if (type == SSH_SMSG_FAILURE) {
950 logit("Warning: Remote host denied X11 forwarding.");
952 packet_disconnect("Protocol error waiting for X11 forwarding");
955 /* Tell the packet module whether this is an interactive session. */
956 packet_set_interactive(interactive);
958 /* Request authentication agent forwarding if appropriate. */
959 check_agent_present();
961 if (options.forward_agent) {
962 debug("Requesting authentication agent forwarding.");
963 auth_request_forwarding();
965 /* Read response from the server. */
966 type = packet_read();
968 if (type != SSH_SMSG_SUCCESS)
969 logit("Warning: Remote host denied authentication agent forwarding.");
972 /* Initiate port forwardings. */
973 ssh_init_forwarding();
975 /* If requested, let ssh continue in the background. */
976 if (fork_after_authentication_flag)
977 if (daemon(1, 1) < 0)
978 fatal("daemon() failed: %.200s", strerror(errno));
981 * If a command was specified on the command line, execute the
982 * command now. Otherwise request the server to start a shell.
984 if (buffer_len(&command) > 0) {
985 int len = buffer_len(&command);
988 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
989 packet_start(SSH_CMSG_EXEC_CMD);
990 packet_put_string(buffer_ptr(&command), buffer_len(&command));
994 debug("Requesting shell.");
995 packet_start(SSH_CMSG_EXEC_SHELL);
1000 /* Enter the interactive session. */
1001 return client_loop(have_tty, tty_flag ?
1002 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1006 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1010 id = packet_get_int();
1011 len = buffer_len(&command);
1015 if (type == SSH2_MSG_CHANNEL_FAILURE)
1016 fatal("Request for subsystem '%.*s' failed on channel %d",
1017 len, (u_char *)buffer_ptr(&command), id);
1021 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1025 i = client_global_request_id++;
1026 if (i >= options.num_remote_forwards)
1028 debug("remote forward %s for: listen %d, connect %s:%d",
1029 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1030 options.remote_forwards[i].listen_port,
1031 options.remote_forwards[i].connect_host,
1032 options.remote_forwards[i].connect_port);
1033 if (type == SSH2_MSG_REQUEST_FAILURE) {
1034 if (options.exit_on_forward_failure)
1035 fatal("Error: remote port forwarding failed for "
1037 options.remote_forwards[i].listen_port);
1039 logit("Warning: remote port forwarding failed for "
1041 options.remote_forwards[i].listen_port);
1046 ssh_control_listener(void)
1048 struct sockaddr_un addr;
1052 if (options.control_path == NULL ||
1053 options.control_master == SSHCTL_MASTER_NO)
1056 debug("setting up multiplex master socket");
1058 memset(&addr, '\0', sizeof(addr));
1059 addr.sun_family = AF_UNIX;
1060 addr_len = offsetof(struct sockaddr_un, sun_path) +
1061 strlen(options.control_path) + 1;
1063 if (strlcpy(addr.sun_path, options.control_path,
1064 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1065 fatal("ControlPath too long");
1067 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1068 fatal("%s socket(): %s", __func__, strerror(errno));
1070 old_umask = umask(0177);
1071 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1073 if (errno == EINVAL || errno == EADDRINUSE)
1074 fatal("ControlSocket %s already exists",
1075 options.control_path);
1077 fatal("%s bind(): %s", __func__, strerror(errno));
1081 if (listen(control_fd, 64) == -1)
1082 fatal("%s listen(): %s", __func__, strerror(errno));
1084 set_nonblock(control_fd);
1087 /* request pty/x11/agent/tcpfwd/shell for channel */
1089 ssh_session2_setup(int id, void *arg)
1091 extern char **environ;
1092 const char *display;
1093 int interactive = tty_flag;
1095 display = getenv("DISPLAY");
1096 if (options.forward_x11 && display != NULL) {
1098 /* Get reasonable local authentication information. */
1099 client_x11_get_proto(display, options.xauth_location,
1100 options.forward_x11_trusted, &proto, &data);
1101 /* Request forwarding with authentication spoofing. */
1102 debug("Requesting X11 forwarding with authentication spoofing.");
1103 x11_request_forwarding_with_spoofing(id, display, proto, data);
1105 /* XXX wait for reply */
1108 check_agent_present();
1109 if (options.forward_agent) {
1110 debug("Requesting authentication agent forwarding.");
1111 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1115 if (options.tun_open != SSH_TUNMODE_NO) {
1119 debug("Requesting tun.");
1120 if ((fd = tun_open(options.tun_local,
1121 options.tun_open)) >= 0) {
1122 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1123 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1126 #if defined(SSH_TUN_FILTER)
1127 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1128 channel_register_filter(c->self, sys_tun_infilter,
1131 packet_start(SSH2_MSG_CHANNEL_OPEN);
1132 packet_put_cstring("tun@openssh.com");
1133 packet_put_int(c->self);
1134 packet_put_int(c->local_window_max);
1135 packet_put_int(c->local_maxpacket);
1136 packet_put_int(options.tun_open);
1137 packet_put_int(options.tun_remote);
1142 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1143 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1145 packet_set_interactive(interactive);
1148 /* open new channel for a session */
1150 ssh_session2_open(void)
1153 int window, packetmax, in, out, err;
1155 if (stdin_null_flag) {
1156 in = open(_PATH_DEVNULL, O_RDONLY);
1158 in = dup(STDIN_FILENO);
1160 out = dup(STDOUT_FILENO);
1161 err = dup(STDERR_FILENO);
1163 if (in < 0 || out < 0 || err < 0)
1164 fatal("dup() in/out/err failed");
1166 /* enable nonblocking unless tty */
1174 window = CHAN_SES_WINDOW_DEFAULT;
1175 packetmax = CHAN_SES_PACKET_DEFAULT;
1181 "session", SSH_CHANNEL_OPENING, in, out, err,
1182 window, packetmax, CHAN_EXTENDED_WRITE,
1183 "client-session", /*nonblock*/0);
1185 debug3("ssh_session2_open: channel_new: %d", c->self);
1187 channel_send_open(c->self);
1189 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1199 /* XXX should be pre-session */
1200 ssh_init_forwarding();
1201 ssh_control_listener();
1203 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1204 id = ssh_session2_open();
1206 /* Execute a local command */
1207 if (options.local_command != NULL &&
1208 options.permit_local_command)
1209 ssh_local_cmd(options.local_command);
1211 /* If requested, let ssh continue in the background. */
1212 if (fork_after_authentication_flag)
1213 if (daemon(1, 1) < 0)
1214 fatal("daemon() failed: %.200s", strerror(errno));
1216 return client_loop(tty_flag, tty_flag ?
1217 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1221 load_public_identity_files(void)
1223 char *filename, *cp, thishost[NI_MAXHOST];
1230 if (options.smartcard_device != NULL &&
1231 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1232 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1234 for (i = 0; keys[i] != NULL; i++) {
1236 memmove(&options.identity_files[1], &options.identity_files[0],
1237 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1238 memmove(&options.identity_keys[1], &options.identity_keys[0],
1239 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1240 options.num_identity_files++;
1241 options.identity_keys[0] = keys[i];
1242 options.identity_files[0] = sc_get_key_label(keys[i]);
1244 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1245 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1249 #endif /* SMARTCARD */
1250 if ((pw = getpwuid(original_real_uid)) == NULL)
1251 fatal("load_public_identity_files: getpwuid failed");
1252 if (gethostname(thishost, sizeof(thishost)) == -1)
1253 fatal("load_public_identity_files: gethostname: %s",
1255 for (; i < options.num_identity_files; i++) {
1256 cp = tilde_expand_filename(options.identity_files[i],
1258 filename = percent_expand(cp, "d", pw->pw_dir,
1259 "u", pw->pw_name, "l", thishost, "h", host,
1260 "r", options.user, (char *)NULL);
1262 public = key_load_public(filename, NULL);
1263 debug("identity file %s type %d", filename,
1264 public ? public->type : -1);
1265 xfree(options.identity_files[i]);
1266 options.identity_files[i] = filename;
1267 options.identity_keys[i] = public;
1272 control_client_sighandler(int signo)
1274 control_client_terminate = signo;
1278 control_client_sigrelay(int signo)
1280 if (control_server_pid > 1)
1281 kill(control_server_pid, signo);
1285 env_permitted(char *env)
1288 char name[1024], *cp;
1290 if ((cp = strchr(env, '=')) == NULL || cp == env)
1292 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1293 if (ret <= 0 || (size_t)ret >= sizeof(name))
1294 fatal("env_permitted: name '%.100s...' too long", env);
1296 for (i = 0; i < options.num_send_env; i++)
1297 if (match_pattern(name, options.send_env[i]))
1304 control_client(const char *path)
1306 struct sockaddr_un addr;
1307 int i, r, fd, sock, exitval, num_env, addr_len;
1310 extern char **environ;
1313 if (mux_command == 0)
1314 mux_command = SSHMUX_COMMAND_OPEN;
1316 switch (options.control_master) {
1317 case SSHCTL_MASTER_AUTO:
1318 case SSHCTL_MASTER_AUTO_ASK:
1319 debug("auto-mux: Trying existing master");
1321 case SSHCTL_MASTER_NO:
1327 memset(&addr, '\0', sizeof(addr));
1328 addr.sun_family = AF_UNIX;
1329 addr_len = offsetof(struct sockaddr_un, sun_path) +
1332 if (strlcpy(addr.sun_path, path,
1333 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1334 fatal("ControlPath too long");
1336 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1337 fatal("%s socket(): %s", __func__, strerror(errno));
1339 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1340 if (mux_command != SSHMUX_COMMAND_OPEN) {
1341 fatal("Control socket connect(%.100s): %s", path,
1344 if (errno == ENOENT)
1345 debug("Control socket \"%.100s\" does not exist", path);
1347 error("Control socket connect(%.100s): %s", path,
1354 if (stdin_null_flag) {
1355 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1356 fatal("open(/dev/null): %s", strerror(errno));
1357 if (dup2(fd, STDIN_FILENO) == -1)
1358 fatal("dup2: %s", strerror(errno));
1359 if (fd > STDERR_FILENO)
1363 term = getenv("TERM");
1367 flags |= SSHMUX_FLAG_TTY;
1369 flags |= SSHMUX_FLAG_SUBSYS;
1370 if (options.forward_x11)
1371 flags |= SSHMUX_FLAG_X11_FWD;
1372 if (options.forward_agent)
1373 flags |= SSHMUX_FLAG_AGENT_FWD;
1377 /* Send our command to server */
1378 buffer_put_int(&m, mux_command);
1379 buffer_put_int(&m, flags);
1380 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1381 fatal("%s: msg_send", __func__);
1384 /* Get authorisation status and PID of controlee */
1385 if (ssh_msg_recv(sock, &m) == -1)
1386 fatal("%s: msg_recv", __func__);
1387 if (buffer_get_char(&m) != SSHMUX_VER)
1388 fatal("%s: wrong version", __func__);
1389 if (buffer_get_int(&m) != 1)
1390 fatal("Connection to master denied");
1391 control_server_pid = buffer_get_int(&m);
1395 switch (mux_command) {
1396 case SSHMUX_COMMAND_ALIVE_CHECK:
1397 fprintf(stderr, "Master running (pid=%d)\r\n",
1398 control_server_pid);
1400 case SSHMUX_COMMAND_TERMINATE:
1401 fprintf(stderr, "Exit request sent.\r\n");
1403 case SSHMUX_COMMAND_OPEN:
1404 /* continue below */
1407 fatal("silly mux_command %d", mux_command);
1410 /* SSHMUX_COMMAND_OPEN */
1411 buffer_put_cstring(&m, term ? term : "");
1412 buffer_append(&command, "\0", 1);
1413 buffer_put_cstring(&m, buffer_ptr(&command));
1415 if (options.num_send_env == 0 || environ == NULL) {
1416 buffer_put_int(&m, 0);
1418 /* Pass environment */
1420 for (i = 0; environ[i] != NULL; i++)
1421 if (env_permitted(environ[i]))
1422 num_env++; /* Count */
1424 buffer_put_int(&m, num_env);
1426 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1427 if (env_permitted(environ[i])) {
1429 buffer_put_cstring(&m, environ[i]);
1433 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1434 fatal("%s: msg_send", __func__);
1436 mm_send_fd(sock, STDIN_FILENO);
1437 mm_send_fd(sock, STDOUT_FILENO);
1438 mm_send_fd(sock, STDERR_FILENO);
1440 /* Wait for reply, so master has a chance to gather ttymodes */
1442 if (ssh_msg_recv(sock, &m) == -1)
1443 fatal("%s: msg_recv", __func__);
1444 if (buffer_get_char(&m) != SSHMUX_VER)
1445 fatal("%s: wrong version", __func__);
1448 signal(SIGHUP, control_client_sighandler);
1449 signal(SIGINT, control_client_sighandler);
1450 signal(SIGTERM, control_client_sighandler);
1451 signal(SIGWINCH, control_client_sigrelay);
1456 /* Stick around until the controlee closes the client_fd */
1458 for (;!control_client_terminate;) {
1459 r = read(sock, &exitval, sizeof(exitval));
1461 debug2("Received EOF from master");
1465 debug2("Received exit status from master %d", exitval);
1466 if (r == -1 && errno != EINTR)
1467 fatal("%s: read %s", __func__, strerror(errno));
1470 if (control_client_terminate)
1471 debug2("Exiting on signal %d", control_client_terminate);
1477 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1478 fprintf(stderr, "Connection to master closed.\r\n");