1 /* $OpenBSD: ssh.c,v 1.279 2006/07/06 16:03:53 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>
60 #include <openssl/evp.h>
61 #include <openssl/err.h>
76 #include "pathnames.h"
78 #include "clientloop.h"
81 #include "sshconnect.h"
88 #include "monitor_fdpass.h"
96 extern char *__progname;
98 /* Flag indicating whether debug mode is on. This can be set on the command line. */
101 /* Flag indicating whether a tty should be allocated */
104 int force_tty_flag = 0;
106 /* don't exec a shell */
107 int no_shell_flag = 0;
110 * Flag indicating that nothing should be read from stdin. This can be set
111 * on the command line.
113 int stdin_null_flag = 0;
116 * Flag indicating that ssh should fork after authentication. This is useful
117 * so that the passphrase can be entered manually, and then ssh goes to the
120 int fork_after_authentication_flag = 0;
123 * General data structure for command line options and options configurable
124 * in configuration files. See readconf.h.
128 /* optional user configfile */
132 * Name of the host we are connecting to. This is the name given on the
133 * command line, or the HostName specified for the user-supplied name in a
134 * configuration file.
138 /* socket address the host resolves to */
139 struct sockaddr_storage hostaddr;
141 /* Private host keys. */
142 Sensitive sensitive_data;
144 /* Original real UID. */
145 uid_t original_real_uid;
146 uid_t original_effective_uid;
148 /* command to be executed */
151 /* Should we execute a command or invoke a subsystem? */
152 int subsystem_flag = 0;
154 /* # of replies received for global requests */
155 static int client_global_request_id = 0;
157 /* pid of proxycommand child process */
158 pid_t proxy_command_pid = 0;
160 /* fd to control socket */
163 /* Multiplexing control command */
164 static u_int mux_command = 0;
166 /* Only used in control client mode */
167 volatile sig_atomic_t control_client_terminate = 0;
168 u_int control_server_pid = 0;
170 /* Prints a help message to the user. This function never returns. */
176 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
177 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
178 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
179 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
180 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
181 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
186 static int ssh_session(void);
187 static int ssh_session2(void);
188 static void load_public_identity_files(void);
189 static void control_client(const char *path);
192 * Main program for the ssh client.
195 main(int ac, char **av)
197 int i, opt, exit_status;
198 char *p, *cp, *line, buf[256];
202 extern int optind, optreset;
207 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
210 __progname = ssh_get_progname(av[0]);
214 * Save the original real uid. It will be needed later (uid-swapping
215 * may clobber the real uid).
217 original_real_uid = getuid();
218 original_effective_uid = geteuid();
221 * Use uid-swapping to give up root privileges for the duration of
222 * option processing. We will re-instantiate the rights when we are
223 * ready to create the privileged port, and will permanently drop
224 * them when the port has been created (actually, when the connection
225 * has been made, as we may need to create the port several times).
229 #ifdef HAVE_SETRLIMIT
230 /* If we are installed setuid root be careful to not drop core. */
231 if (original_real_uid != original_effective_uid) {
233 rlim.rlim_cur = rlim.rlim_max = 0;
234 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
235 fatal("setrlimit failed: %.100s", strerror(errno));
239 pw = getpwuid(original_real_uid);
241 logit("You don't exist, go away!");
244 /* Take a copy of the returned structure. */
248 * Set our umask to something reasonable, as some files are created
249 * with the default umask. This will make them world-readable but
250 * writable only by the owner, which is ok for all files for which we
251 * don't set the modes explicitly.
255 /* Initialize option structure to indicate that no values have been set. */
256 initialize_options(&options);
258 /* Parse command-line arguments. */
262 while ((opt = getopt(ac, av,
263 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
266 options.protocol = SSH_PROTO_1;
269 options.protocol = SSH_PROTO_2;
272 options.address_family = AF_INET;
275 options.address_family = AF_INET6;
281 fork_after_authentication_flag = 1;
285 options.forward_x11 = 0;
288 options.forward_x11 = 1;
291 options.forward_x11 = 1;
292 options.forward_x11_trusted = 1;
295 options.gateway_ports = 1;
298 if (strcmp(optarg, "check") == 0)
299 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
300 else if (strcmp(optarg, "exit") == 0)
301 mux_command = SSHMUX_COMMAND_TERMINATE;
303 fatal("Invalid multiplex command.");
305 case 'P': /* deprecated */
306 options.use_privileged_port = 0;
309 options.forward_agent = 0;
312 options.forward_agent = 1;
315 options.gss_deleg_creds = 0;
318 if (stat(optarg, &st) < 0) {
319 fprintf(stderr, "Warning: Identity file %s "
320 "not accessible: %s.\n", optarg,
324 if (options.num_identity_files >=
325 SSH_MAX_IDENTITY_FILES)
326 fatal("Too many identity files specified "
327 "(max %d)", SSH_MAX_IDENTITY_FILES);
328 options.identity_files[options.num_identity_files++] =
333 options.smartcard_device = xstrdup(optarg);
335 fprintf(stderr, "no support for smartcards.\n");
344 if (debug_flag == 0) {
346 options.log_level = SYSLOG_LEVEL_DEBUG1;
348 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
354 fprintf(stderr, "%s, %s\n",
355 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
360 if (options.tun_open == -1)
361 options.tun_open = SSH_TUNMODE_DEFAULT;
362 options.tun_local = a2tun(optarg, &options.tun_remote);
363 if (options.tun_local == SSH_TUNID_ERR) {
364 fprintf(stderr, "Bad tun device '%s'\n", optarg);
369 options.log_level = SYSLOG_LEVEL_QUIET;
372 if (optarg[0] == '^' && optarg[2] == 0 &&
373 (u_char) optarg[1] >= 64 &&
374 (u_char) optarg[1] < 128)
375 options.escape_char = (u_char) optarg[1] & 31;
376 else if (strlen(optarg) == 1)
377 options.escape_char = (u_char) optarg[0];
378 else if (strcmp(optarg, "none") == 0)
379 options.escape_char = SSH_ESCAPECHAR_NONE;
381 fprintf(stderr, "Bad escape character '%s'.\n",
387 if (ciphers_valid(optarg)) {
389 options.ciphers = xstrdup(optarg);
390 options.cipher = SSH_CIPHER_INVALID;
393 options.cipher = cipher_number(optarg);
394 if (options.cipher == -1) {
396 "Unknown cipher type '%s'\n",
400 if (options.cipher == SSH_CIPHER_3DES)
401 options.ciphers = "3des-cbc";
402 else if (options.cipher == SSH_CIPHER_BLOWFISH)
403 options.ciphers = "blowfish-cbc";
405 options.ciphers = (char *)-1;
409 if (mac_valid(optarg))
410 options.macs = xstrdup(optarg);
412 fprintf(stderr, "Unknown mac type '%s'\n",
418 if (options.control_master == SSHCTL_MASTER_YES)
419 options.control_master = SSHCTL_MASTER_ASK;
421 options.control_master = SSHCTL_MASTER_YES;
424 options.port = a2port(optarg);
425 if (options.port == 0) {
426 fprintf(stderr, "Bad port '%s'\n", optarg);
431 options.user = optarg;
435 if (parse_forward(&fwd, optarg))
436 add_local_forward(&options, &fwd);
439 "Bad local forwarding specification '%s'\n",
446 if (parse_forward(&fwd, optarg)) {
447 add_remote_forward(&options, &fwd);
450 "Bad remote forwarding specification "
457 cp = p = xstrdup(optarg);
458 memset(&fwd, '\0', sizeof(fwd));
459 fwd.connect_host = "socks";
460 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
461 fprintf(stderr, "Bad dynamic forwarding "
462 "specification '%.100s'\n", optarg);
466 fwd.listen_port = a2port(cp);
467 fwd.listen_host = cleanhostname(fwd.listen_host);
469 fwd.listen_port = a2port(fwd.listen_host);
470 fwd.listen_host = NULL;
473 if (fwd.listen_port == 0) {
474 fprintf(stderr, "Bad dynamic port '%s'\n",
478 add_local_forward(&options, &fwd);
483 options.compression = 1;
494 line = xstrdup(optarg);
495 if (process_config_line(&options, host ? host : "",
496 line, "command-line", 0, &dummy) != 0)
504 if (options.control_path != NULL)
505 free(options.control_path);
506 options.control_path = xstrdup(optarg);
509 options.bind_address = optarg;
522 if (ac > 0 && !host && **av != '-') {
523 if (strrchr(*av, '@')) {
525 cp = strrchr(p, '@');
526 if (cp == NULL || cp == p)
534 optind = optreset = 1;
540 /* Check that we got a host name. */
544 SSLeay_add_all_algorithms();
545 ERR_load_crypto_strings();
547 /* Initialize the command to execute on remote host. */
548 buffer_init(&command);
551 * Save the command to execute on the remote host in a buffer. There
552 * is no limit on the length of the command, except by the maximum
553 * packet size. Also sets the tty flag if there is no command.
556 /* No command specified - execute shell on a tty. */
558 if (subsystem_flag) {
560 "You must specify a subsystem to invoke.\n");
564 /* A command has been specified. Store it into the buffer. */
565 for (i = 0; i < ac; i++) {
567 buffer_append(&command, " ", 1);
568 buffer_append(&command, av[i], strlen(av[i]));
572 /* Cannot fork to background if no command. */
573 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
574 fatal("Cannot fork into background without a command to execute.");
576 /* Allocate a tty by default if no command specified. */
577 if (buffer_len(&command) == 0)
583 /* Do not allocate a tty if stdin is not a tty. */
584 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
586 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
591 * Initialize "log" output. Since we are the client all output
592 * actually goes to stderr.
594 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
595 SYSLOG_FACILITY_USER, 1);
598 * Read per-user configuration file. Ignore the system wide config
599 * file if the user specifies a config file on the command line.
601 if (config != NULL) {
602 if (!read_config_file(config, host, &options, 0))
603 fatal("Can't open user config file %.100s: "
604 "%.100s", config, strerror(errno));
606 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
607 _PATH_SSH_USER_CONFFILE);
608 (void)read_config_file(buf, host, &options, 1);
610 /* Read systemwide configuration file after use config. */
611 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
615 /* Fill configuration defaults. */
616 fill_default_options(&options);
618 channel_set_af(options.address_family);
621 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
625 if (options.user == NULL)
626 options.user = xstrdup(pw->pw_name);
628 if (options.hostname != NULL)
629 host = options.hostname;
631 /* force lowercase for hostkey matching */
632 if (options.host_key_alias != NULL) {
633 for (p = options.host_key_alias; *p; p++)
635 *p = (char)tolower(*p);
638 /* Get default port if port has not been set. */
639 if (options.port == 0) {
640 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
641 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
644 if (options.proxy_command != NULL &&
645 strcmp(options.proxy_command, "none") == 0)
646 options.proxy_command = NULL;
647 if (options.control_path != NULL &&
648 strcmp(options.control_path, "none") == 0)
649 options.control_path = NULL;
651 if (options.control_path != NULL) {
652 char thishost[NI_MAXHOST];
654 if (gethostname(thishost, sizeof(thishost)) == -1)
655 fatal("gethostname: %s", strerror(errno));
656 snprintf(buf, sizeof(buf), "%d", options.port);
657 cp = tilde_expand_filename(options.control_path,
659 options.control_path = percent_expand(cp, "p", buf, "h", host,
660 "r", options.user, "l", thishost, (char *)NULL);
663 if (mux_command != 0 && options.control_path == NULL)
664 fatal("No ControlPath specified for \"-O\" command");
665 if (options.control_path != NULL)
666 control_client(options.control_path);
668 /* Open a connection to the remote host. */
669 if (ssh_connect(host, &hostaddr, options.port,
670 options.address_family, options.connection_attempts,
672 options.use_privileged_port,
674 original_effective_uid == 0 && options.use_privileged_port,
676 options.proxy_command) != 0)
680 * If we successfully made the connection, load the host private key
681 * in case we will need it later for combined rsa-rhosts
682 * authentication. This must be done before releasing extra
683 * privileges, because the file is only readable by root.
684 * If we cannot access the private keys, load the public keys
685 * instead and try to execute the ssh-keysign helper instead.
687 sensitive_data.nkeys = 0;
688 sensitive_data.keys = NULL;
689 sensitive_data.external_keysign = 0;
690 if (options.rhosts_rsa_authentication ||
691 options.hostbased_authentication) {
692 sensitive_data.nkeys = 3;
693 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
697 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
698 _PATH_HOST_KEY_FILE, "", NULL, NULL);
699 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
700 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
701 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
702 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
705 if (options.hostbased_authentication == 1 &&
706 sensitive_data.keys[0] == NULL &&
707 sensitive_data.keys[1] == NULL &&
708 sensitive_data.keys[2] == NULL) {
709 sensitive_data.keys[1] = key_load_public(
710 _PATH_HOST_DSA_KEY_FILE, NULL);
711 sensitive_data.keys[2] = key_load_public(
712 _PATH_HOST_RSA_KEY_FILE, NULL);
713 sensitive_data.external_keysign = 1;
717 * Get rid of any extra privileges that we may have. We will no
718 * longer need them. Also, extra privileges could make it very hard
719 * to read identity files and other non-world-readable files from the
720 * user's home directory if it happens to be on a NFS volume where
721 * root is mapped to nobody.
723 if (original_effective_uid == 0) {
725 permanently_set_uid(pw);
729 * Now that we are back to our own permissions, create ~/.ssh
730 * directory if it doesn't already exist.
732 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
733 if (stat(buf, &st) < 0)
734 if (mkdir(buf, 0700) < 0)
735 error("Could not create directory '%.200s'.", buf);
737 /* load options.identity_files */
738 load_public_identity_files();
740 /* Expand ~ in known host file names. */
742 options.system_hostfile =
743 tilde_expand_filename(options.system_hostfile, original_real_uid);
744 options.user_hostfile =
745 tilde_expand_filename(options.user_hostfile, original_real_uid);
746 options.system_hostfile2 =
747 tilde_expand_filename(options.system_hostfile2, original_real_uid);
748 options.user_hostfile2 =
749 tilde_expand_filename(options.user_hostfile2, original_real_uid);
751 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
753 /* Log into the remote system. This never returns if the login fails. */
754 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
756 /* We no longer need the private host keys. Clear them now. */
757 if (sensitive_data.nkeys != 0) {
758 for (i = 0; i < sensitive_data.nkeys; i++) {
759 if (sensitive_data.keys[i] != NULL) {
760 /* Destroys contents safely */
761 debug3("clear hostkey %d", i);
762 key_free(sensitive_data.keys[i]);
763 sensitive_data.keys[i] = NULL;
766 xfree(sensitive_data.keys);
768 for (i = 0; i < options.num_identity_files; i++) {
769 if (options.identity_files[i]) {
770 xfree(options.identity_files[i]);
771 options.identity_files[i] = NULL;
773 if (options.identity_keys[i]) {
774 key_free(options.identity_keys[i]);
775 options.identity_keys[i] = NULL;
779 exit_status = compat20 ? ssh_session2() : ssh_session();
782 if (options.control_path != NULL && control_fd != -1)
783 unlink(options.control_path);
786 * Send SIGHUP to proxy command if used. We don't wait() in
787 * case it hangs and instead rely on init to reap the child
789 if (proxy_command_pid > 1)
790 kill(proxy_command_pid, SIGHUP);
796 ssh_init_forwarding(void)
801 /* Initiate local TCP/IP port forwardings. */
802 for (i = 0; i < options.num_local_forwards; i++) {
803 debug("Local connections to %.200s:%d forwarded to remote "
805 (options.local_forwards[i].listen_host == NULL) ?
806 (options.gateway_ports ? "*" : "LOCALHOST") :
807 options.local_forwards[i].listen_host,
808 options.local_forwards[i].listen_port,
809 options.local_forwards[i].connect_host,
810 options.local_forwards[i].connect_port);
811 success += channel_setup_local_fwd_listener(
812 options.local_forwards[i].listen_host,
813 options.local_forwards[i].listen_port,
814 options.local_forwards[i].connect_host,
815 options.local_forwards[i].connect_port,
816 options.gateway_ports);
818 if (i > 0 && success == 0)
819 error("Could not request local forwarding.");
821 /* Initiate remote TCP/IP port forwardings. */
822 for (i = 0; i < options.num_remote_forwards; i++) {
823 debug("Remote connections from %.200s:%d forwarded to "
824 "local address %.200s:%d",
825 (options.remote_forwards[i].listen_host == NULL) ?
826 "LOCALHOST" : options.remote_forwards[i].listen_host,
827 options.remote_forwards[i].listen_port,
828 options.remote_forwards[i].connect_host,
829 options.remote_forwards[i].connect_port);
830 channel_request_remote_forwarding(
831 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);
839 check_agent_present(void)
841 if (options.forward_agent) {
842 /* Clear agent forwarding if we don't have an agent. */
843 if (!ssh_agent_present())
844 options.forward_agent = 0;
858 /* Enable compression if requested. */
859 if (options.compression) {
860 debug("Requesting compression at level %d.", options.compression_level);
862 if (options.compression_level < 1 || options.compression_level > 9)
863 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
865 /* Send the request. */
866 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
867 packet_put_int(options.compression_level);
870 type = packet_read();
871 if (type == SSH_SMSG_SUCCESS)
872 packet_start_compression(options.compression_level);
873 else if (type == SSH_SMSG_FAILURE)
874 logit("Warning: Remote host refused compression.");
876 packet_disconnect("Protocol error waiting for compression response.");
878 /* Allocate a pseudo tty if appropriate. */
880 debug("Requesting pty.");
882 /* Start the packet. */
883 packet_start(SSH_CMSG_REQUEST_PTY);
885 /* Store TERM in the packet. There is no limit on the
886 length of the string. */
890 packet_put_cstring(cp);
892 /* Store window size in the packet. */
893 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
894 memset(&ws, 0, sizeof(ws));
895 packet_put_int((u_int)ws.ws_row);
896 packet_put_int((u_int)ws.ws_col);
897 packet_put_int((u_int)ws.ws_xpixel);
898 packet_put_int((u_int)ws.ws_ypixel);
900 /* Store tty modes in the packet. */
901 tty_make_modes(fileno(stdin), NULL);
903 /* Send the packet, and wait for it to leave. */
907 /* Read response from the server. */
908 type = packet_read();
909 if (type == SSH_SMSG_SUCCESS) {
912 } else if (type == SSH_SMSG_FAILURE)
913 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
915 packet_disconnect("Protocol error waiting for pty request response.");
917 /* Request X11 forwarding if enabled and DISPLAY is set. */
918 display = getenv("DISPLAY");
919 if (options.forward_x11 && display != NULL) {
921 /* Get reasonable local authentication information. */
922 client_x11_get_proto(display, options.xauth_location,
923 options.forward_x11_trusted, &proto, &data);
924 /* Request forwarding with authentication spoofing. */
925 debug("Requesting X11 forwarding with authentication spoofing.");
926 x11_request_forwarding_with_spoofing(0, display, proto, data);
928 /* Read response from the server. */
929 type = packet_read();
930 if (type == SSH_SMSG_SUCCESS) {
932 } else if (type == SSH_SMSG_FAILURE) {
933 logit("Warning: Remote host denied X11 forwarding.");
935 packet_disconnect("Protocol error waiting for X11 forwarding");
938 /* Tell the packet module whether this is an interactive session. */
939 packet_set_interactive(interactive);
941 /* Request authentication agent forwarding if appropriate. */
942 check_agent_present();
944 if (options.forward_agent) {
945 debug("Requesting authentication agent forwarding.");
946 auth_request_forwarding();
948 /* Read response from the server. */
949 type = packet_read();
951 if (type != SSH_SMSG_SUCCESS)
952 logit("Warning: Remote host denied authentication agent forwarding.");
955 /* Initiate port forwardings. */
956 ssh_init_forwarding();
958 /* If requested, let ssh continue in the background. */
959 if (fork_after_authentication_flag)
960 if (daemon(1, 1) < 0)
961 fatal("daemon() failed: %.200s", strerror(errno));
964 * If a command was specified on the command line, execute the
965 * command now. Otherwise request the server to start a shell.
967 if (buffer_len(&command) > 0) {
968 int len = buffer_len(&command);
971 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
972 packet_start(SSH_CMSG_EXEC_CMD);
973 packet_put_string(buffer_ptr(&command), buffer_len(&command));
977 debug("Requesting shell.");
978 packet_start(SSH_CMSG_EXEC_SHELL);
983 /* Enter the interactive session. */
984 return client_loop(have_tty, tty_flag ?
985 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
989 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
993 id = packet_get_int();
994 len = buffer_len(&command);
998 if (type == SSH2_MSG_CHANNEL_FAILURE)
999 fatal("Request for subsystem '%.*s' failed on channel %d",
1000 len, (u_char *)buffer_ptr(&command), id);
1004 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1008 i = client_global_request_id++;
1009 if (i >= options.num_remote_forwards)
1011 debug("remote forward %s for: listen %d, connect %s:%d",
1012 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1013 options.remote_forwards[i].listen_port,
1014 options.remote_forwards[i].connect_host,
1015 options.remote_forwards[i].connect_port);
1016 if (type == SSH2_MSG_REQUEST_FAILURE)
1017 logit("Warning: remote port forwarding failed for listen "
1018 "port %d", options.remote_forwards[i].listen_port);
1022 ssh_control_listener(void)
1024 struct sockaddr_un addr;
1028 if (options.control_path == NULL ||
1029 options.control_master == SSHCTL_MASTER_NO)
1032 debug("setting up multiplex master socket");
1034 memset(&addr, '\0', sizeof(addr));
1035 addr.sun_family = AF_UNIX;
1036 addr_len = offsetof(struct sockaddr_un, sun_path) +
1037 strlen(options.control_path) + 1;
1039 if (strlcpy(addr.sun_path, options.control_path,
1040 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1041 fatal("ControlPath too long");
1043 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1044 fatal("%s socket(): %s", __func__, strerror(errno));
1046 old_umask = umask(0177);
1047 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1049 if (errno == EINVAL || errno == EADDRINUSE)
1050 fatal("ControlSocket %s already exists",
1051 options.control_path);
1053 fatal("%s bind(): %s", __func__, strerror(errno));
1057 if (listen(control_fd, 64) == -1)
1058 fatal("%s listen(): %s", __func__, strerror(errno));
1060 set_nonblock(control_fd);
1063 /* request pty/x11/agent/tcpfwd/shell for channel */
1065 ssh_session2_setup(int id, void *arg)
1067 extern char **environ;
1068 const char *display;
1069 int interactive = tty_flag;
1071 display = getenv("DISPLAY");
1072 if (options.forward_x11 && display != NULL) {
1074 /* Get reasonable local authentication information. */
1075 client_x11_get_proto(display, options.xauth_location,
1076 options.forward_x11_trusted, &proto, &data);
1077 /* Request forwarding with authentication spoofing. */
1078 debug("Requesting X11 forwarding with authentication spoofing.");
1079 x11_request_forwarding_with_spoofing(id, display, proto, data);
1081 /* XXX wait for reply */
1084 check_agent_present();
1085 if (options.forward_agent) {
1086 debug("Requesting authentication agent forwarding.");
1087 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1091 if (options.tun_open != SSH_TUNMODE_NO) {
1095 debug("Requesting tun.");
1096 if ((fd = tun_open(options.tun_local,
1097 options.tun_open)) >= 0) {
1098 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1099 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1102 #if defined(SSH_TUN_FILTER)
1103 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1104 channel_register_filter(c->self, sys_tun_infilter,
1107 packet_start(SSH2_MSG_CHANNEL_OPEN);
1108 packet_put_cstring("tun@openssh.com");
1109 packet_put_int(c->self);
1110 packet_put_int(c->local_window_max);
1111 packet_put_int(c->local_maxpacket);
1112 packet_put_int(options.tun_open);
1113 packet_put_int(options.tun_remote);
1118 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1119 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1121 packet_set_interactive(interactive);
1124 /* open new channel for a session */
1126 ssh_session2_open(void)
1129 int window, packetmax, in, out, err;
1131 if (stdin_null_flag) {
1132 in = open(_PATH_DEVNULL, O_RDONLY);
1134 in = dup(STDIN_FILENO);
1136 out = dup(STDOUT_FILENO);
1137 err = dup(STDERR_FILENO);
1139 if (in < 0 || out < 0 || err < 0)
1140 fatal("dup() in/out/err failed");
1142 /* enable nonblocking unless tty */
1150 window = CHAN_SES_WINDOW_DEFAULT;
1151 packetmax = CHAN_SES_PACKET_DEFAULT;
1157 "session", SSH_CHANNEL_OPENING, in, out, err,
1158 window, packetmax, CHAN_EXTENDED_WRITE,
1159 "client-session", /*nonblock*/0);
1161 debug3("ssh_session2_open: channel_new: %d", c->self);
1163 channel_send_open(c->self);
1165 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1175 /* XXX should be pre-session */
1176 ssh_init_forwarding();
1177 ssh_control_listener();
1179 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1180 id = ssh_session2_open();
1182 /* Execute a local command */
1183 if (options.local_command != NULL &&
1184 options.permit_local_command)
1185 ssh_local_cmd(options.local_command);
1187 /* If requested, let ssh continue in the background. */
1188 if (fork_after_authentication_flag)
1189 if (daemon(1, 1) < 0)
1190 fatal("daemon() failed: %.200s", strerror(errno));
1192 return client_loop(tty_flag, tty_flag ?
1193 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1197 load_public_identity_files(void)
1199 char *filename, *cp, thishost[NI_MAXHOST];
1206 if (options.smartcard_device != NULL &&
1207 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1208 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1210 for (i = 0; keys[i] != NULL; i++) {
1212 memmove(&options.identity_files[1], &options.identity_files[0],
1213 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1214 memmove(&options.identity_keys[1], &options.identity_keys[0],
1215 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1216 options.num_identity_files++;
1217 options.identity_keys[0] = keys[i];
1218 options.identity_files[0] = sc_get_key_label(keys[i]);
1220 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1221 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1225 #endif /* SMARTCARD */
1226 if ((pw = getpwuid(original_real_uid)) == NULL)
1227 fatal("load_public_identity_files: getpwuid failed");
1228 if (gethostname(thishost, sizeof(thishost)) == -1)
1229 fatal("load_public_identity_files: gethostname: %s",
1231 for (; i < options.num_identity_files; i++) {
1232 cp = tilde_expand_filename(options.identity_files[i],
1234 filename = percent_expand(cp, "d", pw->pw_dir,
1235 "u", pw->pw_name, "l", thishost, "h", host,
1236 "r", options.user, (char *)NULL);
1238 public = key_load_public(filename, NULL);
1239 debug("identity file %s type %d", filename,
1240 public ? public->type : -1);
1241 xfree(options.identity_files[i]);
1242 options.identity_files[i] = filename;
1243 options.identity_keys[i] = public;
1248 control_client_sighandler(int signo)
1250 control_client_terminate = signo;
1254 control_client_sigrelay(int signo)
1256 if (control_server_pid > 1)
1257 kill(control_server_pid, signo);
1261 env_permitted(char *env)
1264 char name[1024], *cp;
1266 if (strlcpy(name, env, sizeof(name)) >= sizeof(name))
1267 fatal("env_permitted: name too long");
1268 if ((cp = strchr(name, '=')) == NULL)
1273 for (i = 0; i < options.num_send_env; i++)
1274 if (match_pattern(name, options.send_env[i]))
1281 control_client(const char *path)
1283 struct sockaddr_un addr;
1284 int i, r, fd, sock, exitval, num_env, addr_len;
1287 extern char **environ;
1290 if (mux_command == 0)
1291 mux_command = SSHMUX_COMMAND_OPEN;
1293 switch (options.control_master) {
1294 case SSHCTL_MASTER_AUTO:
1295 case SSHCTL_MASTER_AUTO_ASK:
1296 debug("auto-mux: Trying existing master");
1298 case SSHCTL_MASTER_NO:
1304 memset(&addr, '\0', sizeof(addr));
1305 addr.sun_family = AF_UNIX;
1306 addr_len = offsetof(struct sockaddr_un, sun_path) +
1309 if (strlcpy(addr.sun_path, path,
1310 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1311 fatal("ControlPath too long");
1313 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1314 fatal("%s socket(): %s", __func__, strerror(errno));
1316 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1317 if (mux_command != SSHMUX_COMMAND_OPEN) {
1318 fatal("Control socket connect(%.100s): %s", path,
1321 if (errno == ENOENT)
1322 debug("Control socket \"%.100s\" does not exist", path);
1324 error("Control socket connect(%.100s): %s", path,
1331 if (stdin_null_flag) {
1332 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1333 fatal("open(/dev/null): %s", strerror(errno));
1334 if (dup2(fd, STDIN_FILENO) == -1)
1335 fatal("dup2: %s", strerror(errno));
1336 if (fd > STDERR_FILENO)
1340 term = getenv("TERM");
1344 flags |= SSHMUX_FLAG_TTY;
1346 flags |= SSHMUX_FLAG_SUBSYS;
1347 if (options.forward_x11)
1348 flags |= SSHMUX_FLAG_X11_FWD;
1349 if (options.forward_agent)
1350 flags |= SSHMUX_FLAG_AGENT_FWD;
1354 /* Send our command to server */
1355 buffer_put_int(&m, mux_command);
1356 buffer_put_int(&m, flags);
1357 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1358 fatal("%s: msg_send", __func__);
1361 /* Get authorisation status and PID of controlee */
1362 if (ssh_msg_recv(sock, &m) == -1)
1363 fatal("%s: msg_recv", __func__);
1364 if (buffer_get_char(&m) != SSHMUX_VER)
1365 fatal("%s: wrong version", __func__);
1366 if (buffer_get_int(&m) != 1)
1367 fatal("Connection to master denied");
1368 control_server_pid = buffer_get_int(&m);
1372 switch (mux_command) {
1373 case SSHMUX_COMMAND_ALIVE_CHECK:
1374 fprintf(stderr, "Master running (pid=%d)\r\n",
1375 control_server_pid);
1377 case SSHMUX_COMMAND_TERMINATE:
1378 fprintf(stderr, "Exit request sent.\r\n");
1380 case SSHMUX_COMMAND_OPEN:
1381 /* continue below */
1384 fatal("silly mux_command %d", mux_command);
1387 /* SSHMUX_COMMAND_OPEN */
1388 buffer_put_cstring(&m, term ? term : "");
1389 buffer_append(&command, "\0", 1);
1390 buffer_put_cstring(&m, buffer_ptr(&command));
1392 if (options.num_send_env == 0 || environ == NULL) {
1393 buffer_put_int(&m, 0);
1395 /* Pass environment */
1397 for (i = 0; environ[i] != NULL; i++)
1398 if (env_permitted(environ[i]))
1399 num_env++; /* Count */
1401 buffer_put_int(&m, num_env);
1403 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1404 if (env_permitted(environ[i])) {
1406 buffer_put_cstring(&m, environ[i]);
1410 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1411 fatal("%s: msg_send", __func__);
1413 mm_send_fd(sock, STDIN_FILENO);
1414 mm_send_fd(sock, STDOUT_FILENO);
1415 mm_send_fd(sock, STDERR_FILENO);
1417 /* Wait for reply, so master has a chance to gather ttymodes */
1419 if (ssh_msg_recv(sock, &m) == -1)
1420 fatal("%s: msg_recv", __func__);
1421 if (buffer_get_char(&m) != SSHMUX_VER)
1422 fatal("%s: wrong version", __func__);
1425 signal(SIGHUP, control_client_sighandler);
1426 signal(SIGINT, control_client_sighandler);
1427 signal(SIGTERM, control_client_sighandler);
1428 signal(SIGWINCH, control_client_sigrelay);
1433 /* Stick around until the controlee closes the client_fd */
1435 for (;!control_client_terminate;) {
1436 r = read(sock, &exitval, sizeof(exitval));
1438 debug2("Received EOF from master");
1442 debug2("Received exit status from master %d", exitval);
1443 if (r == -1 && errno != EINTR)
1444 fatal("%s: read %s", __func__, strerror(errno));
1447 if (control_client_terminate)
1448 debug2("Exiting on signal %d", control_client_terminate);
1454 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1455 fprintf(stderr, "Connection to master closed.\r\n");