1 /* $OpenBSD: ssh.c,v 1.278 2006/07/03 08:54:20 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>
59 #include <openssl/evp.h>
60 #include <openssl/err.h>
75 #include "pathnames.h"
77 #include "clientloop.h"
80 #include "sshconnect.h"
87 #include "monitor_fdpass.h"
95 extern char *__progname;
97 /* Flag indicating whether debug mode is on. This can be set on the command line. */
100 /* Flag indicating whether a tty should be allocated */
103 int force_tty_flag = 0;
105 /* don't exec a shell */
106 int no_shell_flag = 0;
109 * Flag indicating that nothing should be read from stdin. This can be set
110 * on the command line.
112 int stdin_null_flag = 0;
115 * Flag indicating that ssh should fork after authentication. This is useful
116 * so that the passphrase can be entered manually, and then ssh goes to the
119 int fork_after_authentication_flag = 0;
122 * General data structure for command line options and options configurable
123 * in configuration files. See readconf.h.
127 /* optional user configfile */
131 * Name of the host we are connecting to. This is the name given on the
132 * command line, or the HostName specified for the user-supplied name in a
133 * configuration file.
137 /* socket address the host resolves to */
138 struct sockaddr_storage hostaddr;
140 /* Private host keys. */
141 Sensitive sensitive_data;
143 /* Original real UID. */
144 uid_t original_real_uid;
145 uid_t original_effective_uid;
147 /* command to be executed */
150 /* Should we execute a command or invoke a subsystem? */
151 int subsystem_flag = 0;
153 /* # of replies received for global requests */
154 static int client_global_request_id = 0;
156 /* pid of proxycommand child process */
157 pid_t proxy_command_pid = 0;
159 /* fd to control socket */
162 /* Multiplexing control command */
163 static u_int mux_command = 0;
165 /* Only used in control client mode */
166 volatile sig_atomic_t control_client_terminate = 0;
167 u_int control_server_pid = 0;
169 /* Prints a help message to the user. This function never returns. */
175 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
176 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
177 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
178 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
179 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
180 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
185 static int ssh_session(void);
186 static int ssh_session2(void);
187 static void load_public_identity_files(void);
188 static void control_client(const char *path);
191 * Main program for the ssh client.
194 main(int ac, char **av)
196 int i, opt, exit_status;
197 char *p, *cp, *line, buf[256];
201 extern int optind, optreset;
206 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
209 __progname = ssh_get_progname(av[0]);
213 * Save the original real uid. It will be needed later (uid-swapping
214 * may clobber the real uid).
216 original_real_uid = getuid();
217 original_effective_uid = geteuid();
220 * Use uid-swapping to give up root privileges for the duration of
221 * option processing. We will re-instantiate the rights when we are
222 * ready to create the privileged port, and will permanently drop
223 * them when the port has been created (actually, when the connection
224 * has been made, as we may need to create the port several times).
228 #ifdef HAVE_SETRLIMIT
229 /* If we are installed setuid root be careful to not drop core. */
230 if (original_real_uid != original_effective_uid) {
232 rlim.rlim_cur = rlim.rlim_max = 0;
233 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
234 fatal("setrlimit failed: %.100s", strerror(errno));
238 pw = getpwuid(original_real_uid);
240 logit("You don't exist, go away!");
243 /* Take a copy of the returned structure. */
247 * Set our umask to something reasonable, as some files are created
248 * with the default umask. This will make them world-readable but
249 * writable only by the owner, which is ok for all files for which we
250 * don't set the modes explicitly.
254 /* Initialize option structure to indicate that no values have been set. */
255 initialize_options(&options);
257 /* Parse command-line arguments. */
261 while ((opt = getopt(ac, av,
262 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
265 options.protocol = SSH_PROTO_1;
268 options.protocol = SSH_PROTO_2;
271 options.address_family = AF_INET;
274 options.address_family = AF_INET6;
280 fork_after_authentication_flag = 1;
284 options.forward_x11 = 0;
287 options.forward_x11 = 1;
290 options.forward_x11 = 1;
291 options.forward_x11_trusted = 1;
294 options.gateway_ports = 1;
297 if (strcmp(optarg, "check") == 0)
298 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
299 else if (strcmp(optarg, "exit") == 0)
300 mux_command = SSHMUX_COMMAND_TERMINATE;
302 fatal("Invalid multiplex command.");
304 case 'P': /* deprecated */
305 options.use_privileged_port = 0;
308 options.forward_agent = 0;
311 options.forward_agent = 1;
314 options.gss_deleg_creds = 0;
317 if (stat(optarg, &st) < 0) {
318 fprintf(stderr, "Warning: Identity file %s "
319 "not accessible: %s.\n", optarg,
323 if (options.num_identity_files >=
324 SSH_MAX_IDENTITY_FILES)
325 fatal("Too many identity files specified "
326 "(max %d)", SSH_MAX_IDENTITY_FILES);
327 options.identity_files[options.num_identity_files++] =
332 options.smartcard_device = xstrdup(optarg);
334 fprintf(stderr, "no support for smartcards.\n");
343 if (debug_flag == 0) {
345 options.log_level = SYSLOG_LEVEL_DEBUG1;
347 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
353 fprintf(stderr, "%s, %s\n",
354 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
359 if (options.tun_open == -1)
360 options.tun_open = SSH_TUNMODE_DEFAULT;
361 options.tun_local = a2tun(optarg, &options.tun_remote);
362 if (options.tun_local == SSH_TUNID_ERR) {
363 fprintf(stderr, "Bad tun device '%s'\n", optarg);
368 options.log_level = SYSLOG_LEVEL_QUIET;
371 if (optarg[0] == '^' && optarg[2] == 0 &&
372 (u_char) optarg[1] >= 64 &&
373 (u_char) optarg[1] < 128)
374 options.escape_char = (u_char) optarg[1] & 31;
375 else if (strlen(optarg) == 1)
376 options.escape_char = (u_char) optarg[0];
377 else if (strcmp(optarg, "none") == 0)
378 options.escape_char = SSH_ESCAPECHAR_NONE;
380 fprintf(stderr, "Bad escape character '%s'.\n",
386 if (ciphers_valid(optarg)) {
388 options.ciphers = xstrdup(optarg);
389 options.cipher = SSH_CIPHER_INVALID;
392 options.cipher = cipher_number(optarg);
393 if (options.cipher == -1) {
395 "Unknown cipher type '%s'\n",
399 if (options.cipher == SSH_CIPHER_3DES)
400 options.ciphers = "3des-cbc";
401 else if (options.cipher == SSH_CIPHER_BLOWFISH)
402 options.ciphers = "blowfish-cbc";
404 options.ciphers = (char *)-1;
408 if (mac_valid(optarg))
409 options.macs = xstrdup(optarg);
411 fprintf(stderr, "Unknown mac type '%s'\n",
417 if (options.control_master == SSHCTL_MASTER_YES)
418 options.control_master = SSHCTL_MASTER_ASK;
420 options.control_master = SSHCTL_MASTER_YES;
423 options.port = a2port(optarg);
424 if (options.port == 0) {
425 fprintf(stderr, "Bad port '%s'\n", optarg);
430 options.user = optarg;
434 if (parse_forward(&fwd, optarg))
435 add_local_forward(&options, &fwd);
438 "Bad local forwarding specification '%s'\n",
445 if (parse_forward(&fwd, optarg)) {
446 add_remote_forward(&options, &fwd);
449 "Bad remote forwarding specification "
456 cp = p = xstrdup(optarg);
457 memset(&fwd, '\0', sizeof(fwd));
458 fwd.connect_host = "socks";
459 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
460 fprintf(stderr, "Bad dynamic forwarding "
461 "specification '%.100s'\n", optarg);
465 fwd.listen_port = a2port(cp);
466 fwd.listen_host = cleanhostname(fwd.listen_host);
468 fwd.listen_port = a2port(fwd.listen_host);
469 fwd.listen_host = NULL;
472 if (fwd.listen_port == 0) {
473 fprintf(stderr, "Bad dynamic port '%s'\n",
477 add_local_forward(&options, &fwd);
482 options.compression = 1;
493 line = xstrdup(optarg);
494 if (process_config_line(&options, host ? host : "",
495 line, "command-line", 0, &dummy) != 0)
503 if (options.control_path != NULL)
504 free(options.control_path);
505 options.control_path = xstrdup(optarg);
508 options.bind_address = optarg;
521 if (ac > 0 && !host && **av != '-') {
522 if (strrchr(*av, '@')) {
524 cp = strrchr(p, '@');
525 if (cp == NULL || cp == p)
533 optind = optreset = 1;
539 /* Check that we got a host name. */
543 SSLeay_add_all_algorithms();
544 ERR_load_crypto_strings();
546 /* Initialize the command to execute on remote host. */
547 buffer_init(&command);
550 * Save the command to execute on the remote host in a buffer. There
551 * is no limit on the length of the command, except by the maximum
552 * packet size. Also sets the tty flag if there is no command.
555 /* No command specified - execute shell on a tty. */
557 if (subsystem_flag) {
559 "You must specify a subsystem to invoke.\n");
563 /* A command has been specified. Store it into the buffer. */
564 for (i = 0; i < ac; i++) {
566 buffer_append(&command, " ", 1);
567 buffer_append(&command, av[i], strlen(av[i]));
571 /* Cannot fork to background if no command. */
572 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
573 fatal("Cannot fork into background without a command to execute.");
575 /* Allocate a tty by default if no command specified. */
576 if (buffer_len(&command) == 0)
582 /* Do not allocate a tty if stdin is not a tty. */
583 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
585 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
590 * Initialize "log" output. Since we are the client all output
591 * actually goes to stderr.
593 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
594 SYSLOG_FACILITY_USER, 1);
597 * Read per-user configuration file. Ignore the system wide config
598 * file if the user specifies a config file on the command line.
600 if (config != NULL) {
601 if (!read_config_file(config, host, &options, 0))
602 fatal("Can't open user config file %.100s: "
603 "%.100s", config, strerror(errno));
605 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
606 _PATH_SSH_USER_CONFFILE);
607 (void)read_config_file(buf, host, &options, 1);
609 /* Read systemwide configuration file after use config. */
610 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
614 /* Fill configuration defaults. */
615 fill_default_options(&options);
617 channel_set_af(options.address_family);
620 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
624 if (options.user == NULL)
625 options.user = xstrdup(pw->pw_name);
627 if (options.hostname != NULL)
628 host = options.hostname;
630 /* force lowercase for hostkey matching */
631 if (options.host_key_alias != NULL) {
632 for (p = options.host_key_alias; *p; p++)
634 *p = (char)tolower(*p);
637 /* Get default port if port has not been set. */
638 if (options.port == 0) {
639 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
640 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
643 if (options.proxy_command != NULL &&
644 strcmp(options.proxy_command, "none") == 0)
645 options.proxy_command = NULL;
646 if (options.control_path != NULL &&
647 strcmp(options.control_path, "none") == 0)
648 options.control_path = NULL;
650 if (options.control_path != NULL) {
651 char thishost[NI_MAXHOST];
653 if (gethostname(thishost, sizeof(thishost)) == -1)
654 fatal("gethostname: %s", strerror(errno));
655 snprintf(buf, sizeof(buf), "%d", options.port);
656 cp = tilde_expand_filename(options.control_path,
658 options.control_path = percent_expand(cp, "p", buf, "h", host,
659 "r", options.user, "l", thishost, (char *)NULL);
662 if (mux_command != 0 && options.control_path == NULL)
663 fatal("No ControlPath specified for \"-O\" command");
664 if (options.control_path != NULL)
665 control_client(options.control_path);
667 /* Open a connection to the remote host. */
668 if (ssh_connect(host, &hostaddr, options.port,
669 options.address_family, options.connection_attempts,
671 options.use_privileged_port,
673 original_effective_uid == 0 && options.use_privileged_port,
675 options.proxy_command) != 0)
679 * If we successfully made the connection, load the host private key
680 * in case we will need it later for combined rsa-rhosts
681 * authentication. This must be done before releasing extra
682 * privileges, because the file is only readable by root.
683 * If we cannot access the private keys, load the public keys
684 * instead and try to execute the ssh-keysign helper instead.
686 sensitive_data.nkeys = 0;
687 sensitive_data.keys = NULL;
688 sensitive_data.external_keysign = 0;
689 if (options.rhosts_rsa_authentication ||
690 options.hostbased_authentication) {
691 sensitive_data.nkeys = 3;
692 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
696 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
697 _PATH_HOST_KEY_FILE, "", NULL, NULL);
698 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
699 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
700 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
701 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
704 if (options.hostbased_authentication == 1 &&
705 sensitive_data.keys[0] == NULL &&
706 sensitive_data.keys[1] == NULL &&
707 sensitive_data.keys[2] == NULL) {
708 sensitive_data.keys[1] = key_load_public(
709 _PATH_HOST_DSA_KEY_FILE, NULL);
710 sensitive_data.keys[2] = key_load_public(
711 _PATH_HOST_RSA_KEY_FILE, NULL);
712 sensitive_data.external_keysign = 1;
716 * Get rid of any extra privileges that we may have. We will no
717 * longer need them. Also, extra privileges could make it very hard
718 * to read identity files and other non-world-readable files from the
719 * user's home directory if it happens to be on a NFS volume where
720 * root is mapped to nobody.
722 if (original_effective_uid == 0) {
724 permanently_set_uid(pw);
728 * Now that we are back to our own permissions, create ~/.ssh
729 * directory if it doesn't already exist.
731 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
732 if (stat(buf, &st) < 0)
733 if (mkdir(buf, 0700) < 0)
734 error("Could not create directory '%.200s'.", buf);
736 /* load options.identity_files */
737 load_public_identity_files();
739 /* Expand ~ in known host file names. */
741 options.system_hostfile =
742 tilde_expand_filename(options.system_hostfile, original_real_uid);
743 options.user_hostfile =
744 tilde_expand_filename(options.user_hostfile, original_real_uid);
745 options.system_hostfile2 =
746 tilde_expand_filename(options.system_hostfile2, original_real_uid);
747 options.user_hostfile2 =
748 tilde_expand_filename(options.user_hostfile2, original_real_uid);
750 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
752 /* Log into the remote system. This never returns if the login fails. */
753 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
755 /* We no longer need the private host keys. Clear them now. */
756 if (sensitive_data.nkeys != 0) {
757 for (i = 0; i < sensitive_data.nkeys; i++) {
758 if (sensitive_data.keys[i] != NULL) {
759 /* Destroys contents safely */
760 debug3("clear hostkey %d", i);
761 key_free(sensitive_data.keys[i]);
762 sensitive_data.keys[i] = NULL;
765 xfree(sensitive_data.keys);
767 for (i = 0; i < options.num_identity_files; i++) {
768 if (options.identity_files[i]) {
769 xfree(options.identity_files[i]);
770 options.identity_files[i] = NULL;
772 if (options.identity_keys[i]) {
773 key_free(options.identity_keys[i]);
774 options.identity_keys[i] = NULL;
778 exit_status = compat20 ? ssh_session2() : ssh_session();
781 if (options.control_path != NULL && control_fd != -1)
782 unlink(options.control_path);
785 * Send SIGHUP to proxy command if used. We don't wait() in
786 * case it hangs and instead rely on init to reap the child
788 if (proxy_command_pid > 1)
789 kill(proxy_command_pid, SIGHUP);
795 ssh_init_forwarding(void)
800 /* Initiate local TCP/IP port forwardings. */
801 for (i = 0; i < options.num_local_forwards; i++) {
802 debug("Local connections to %.200s:%d forwarded to remote "
804 (options.local_forwards[i].listen_host == NULL) ?
805 (options.gateway_ports ? "*" : "LOCALHOST") :
806 options.local_forwards[i].listen_host,
807 options.local_forwards[i].listen_port,
808 options.local_forwards[i].connect_host,
809 options.local_forwards[i].connect_port);
810 success += channel_setup_local_fwd_listener(
811 options.local_forwards[i].listen_host,
812 options.local_forwards[i].listen_port,
813 options.local_forwards[i].connect_host,
814 options.local_forwards[i].connect_port,
815 options.gateway_ports);
817 if (i > 0 && success == 0)
818 error("Could not request local forwarding.");
820 /* Initiate remote TCP/IP port forwardings. */
821 for (i = 0; i < options.num_remote_forwards; i++) {
822 debug("Remote connections from %.200s:%d forwarded to "
823 "local address %.200s:%d",
824 (options.remote_forwards[i].listen_host == NULL) ?
825 "LOCALHOST" : options.remote_forwards[i].listen_host,
826 options.remote_forwards[i].listen_port,
827 options.remote_forwards[i].connect_host,
828 options.remote_forwards[i].connect_port);
829 channel_request_remote_forwarding(
830 options.remote_forwards[i].listen_host,
831 options.remote_forwards[i].listen_port,
832 options.remote_forwards[i].connect_host,
833 options.remote_forwards[i].connect_port);
838 check_agent_present(void)
840 if (options.forward_agent) {
841 /* Clear agent forwarding if we don't have an agent. */
842 if (!ssh_agent_present())
843 options.forward_agent = 0;
857 /* Enable compression if requested. */
858 if (options.compression) {
859 debug("Requesting compression at level %d.", options.compression_level);
861 if (options.compression_level < 1 || options.compression_level > 9)
862 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
864 /* Send the request. */
865 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
866 packet_put_int(options.compression_level);
869 type = packet_read();
870 if (type == SSH_SMSG_SUCCESS)
871 packet_start_compression(options.compression_level);
872 else if (type == SSH_SMSG_FAILURE)
873 logit("Warning: Remote host refused compression.");
875 packet_disconnect("Protocol error waiting for compression response.");
877 /* Allocate a pseudo tty if appropriate. */
879 debug("Requesting pty.");
881 /* Start the packet. */
882 packet_start(SSH_CMSG_REQUEST_PTY);
884 /* Store TERM in the packet. There is no limit on the
885 length of the string. */
889 packet_put_cstring(cp);
891 /* Store window size in the packet. */
892 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
893 memset(&ws, 0, sizeof(ws));
894 packet_put_int((u_int)ws.ws_row);
895 packet_put_int((u_int)ws.ws_col);
896 packet_put_int((u_int)ws.ws_xpixel);
897 packet_put_int((u_int)ws.ws_ypixel);
899 /* Store tty modes in the packet. */
900 tty_make_modes(fileno(stdin), NULL);
902 /* Send the packet, and wait for it to leave. */
906 /* Read response from the server. */
907 type = packet_read();
908 if (type == SSH_SMSG_SUCCESS) {
911 } else if (type == SSH_SMSG_FAILURE)
912 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
914 packet_disconnect("Protocol error waiting for pty request response.");
916 /* Request X11 forwarding if enabled and DISPLAY is set. */
917 display = getenv("DISPLAY");
918 if (options.forward_x11 && display != NULL) {
920 /* Get reasonable local authentication information. */
921 client_x11_get_proto(display, options.xauth_location,
922 options.forward_x11_trusted, &proto, &data);
923 /* Request forwarding with authentication spoofing. */
924 debug("Requesting X11 forwarding with authentication spoofing.");
925 x11_request_forwarding_with_spoofing(0, display, proto, data);
927 /* Read response from the server. */
928 type = packet_read();
929 if (type == SSH_SMSG_SUCCESS) {
931 } else if (type == SSH_SMSG_FAILURE) {
932 logit("Warning: Remote host denied X11 forwarding.");
934 packet_disconnect("Protocol error waiting for X11 forwarding");
937 /* Tell the packet module whether this is an interactive session. */
938 packet_set_interactive(interactive);
940 /* Request authentication agent forwarding if appropriate. */
941 check_agent_present();
943 if (options.forward_agent) {
944 debug("Requesting authentication agent forwarding.");
945 auth_request_forwarding();
947 /* Read response from the server. */
948 type = packet_read();
950 if (type != SSH_SMSG_SUCCESS)
951 logit("Warning: Remote host denied authentication agent forwarding.");
954 /* Initiate port forwardings. */
955 ssh_init_forwarding();
957 /* If requested, let ssh continue in the background. */
958 if (fork_after_authentication_flag)
959 if (daemon(1, 1) < 0)
960 fatal("daemon() failed: %.200s", strerror(errno));
963 * If a command was specified on the command line, execute the
964 * command now. Otherwise request the server to start a shell.
966 if (buffer_len(&command) > 0) {
967 int len = buffer_len(&command);
970 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
971 packet_start(SSH_CMSG_EXEC_CMD);
972 packet_put_string(buffer_ptr(&command), buffer_len(&command));
976 debug("Requesting shell.");
977 packet_start(SSH_CMSG_EXEC_SHELL);
982 /* Enter the interactive session. */
983 return client_loop(have_tty, tty_flag ?
984 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
988 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
992 id = packet_get_int();
993 len = buffer_len(&command);
997 if (type == SSH2_MSG_CHANNEL_FAILURE)
998 fatal("Request for subsystem '%.*s' failed on channel %d",
999 len, (u_char *)buffer_ptr(&command), id);
1003 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1007 i = client_global_request_id++;
1008 if (i >= options.num_remote_forwards)
1010 debug("remote forward %s for: listen %d, connect %s:%d",
1011 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1012 options.remote_forwards[i].listen_port,
1013 options.remote_forwards[i].connect_host,
1014 options.remote_forwards[i].connect_port);
1015 if (type == SSH2_MSG_REQUEST_FAILURE)
1016 logit("Warning: remote port forwarding failed for listen "
1017 "port %d", options.remote_forwards[i].listen_port);
1021 ssh_control_listener(void)
1023 struct sockaddr_un addr;
1027 if (options.control_path == NULL ||
1028 options.control_master == SSHCTL_MASTER_NO)
1031 debug("setting up multiplex master socket");
1033 memset(&addr, '\0', sizeof(addr));
1034 addr.sun_family = AF_UNIX;
1035 addr_len = offsetof(struct sockaddr_un, sun_path) +
1036 strlen(options.control_path) + 1;
1038 if (strlcpy(addr.sun_path, options.control_path,
1039 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1040 fatal("ControlPath too long");
1042 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1043 fatal("%s socket(): %s", __func__, strerror(errno));
1045 old_umask = umask(0177);
1046 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1048 if (errno == EINVAL || errno == EADDRINUSE)
1049 fatal("ControlSocket %s already exists",
1050 options.control_path);
1052 fatal("%s bind(): %s", __func__, strerror(errno));
1056 if (listen(control_fd, 64) == -1)
1057 fatal("%s listen(): %s", __func__, strerror(errno));
1059 set_nonblock(control_fd);
1062 /* request pty/x11/agent/tcpfwd/shell for channel */
1064 ssh_session2_setup(int id, void *arg)
1066 extern char **environ;
1067 const char *display;
1068 int interactive = tty_flag;
1070 display = getenv("DISPLAY");
1071 if (options.forward_x11 && display != NULL) {
1073 /* Get reasonable local authentication information. */
1074 client_x11_get_proto(display, options.xauth_location,
1075 options.forward_x11_trusted, &proto, &data);
1076 /* Request forwarding with authentication spoofing. */
1077 debug("Requesting X11 forwarding with authentication spoofing.");
1078 x11_request_forwarding_with_spoofing(id, display, proto, data);
1080 /* XXX wait for reply */
1083 check_agent_present();
1084 if (options.forward_agent) {
1085 debug("Requesting authentication agent forwarding.");
1086 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1090 if (options.tun_open != SSH_TUNMODE_NO) {
1094 debug("Requesting tun.");
1095 if ((fd = tun_open(options.tun_local,
1096 options.tun_open)) >= 0) {
1097 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1098 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1101 #if defined(SSH_TUN_FILTER)
1102 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1103 channel_register_filter(c->self, sys_tun_infilter,
1106 packet_start(SSH2_MSG_CHANNEL_OPEN);
1107 packet_put_cstring("tun@openssh.com");
1108 packet_put_int(c->self);
1109 packet_put_int(c->local_window_max);
1110 packet_put_int(c->local_maxpacket);
1111 packet_put_int(options.tun_open);
1112 packet_put_int(options.tun_remote);
1117 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1118 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1120 packet_set_interactive(interactive);
1123 /* open new channel for a session */
1125 ssh_session2_open(void)
1128 int window, packetmax, in, out, err;
1130 if (stdin_null_flag) {
1131 in = open(_PATH_DEVNULL, O_RDONLY);
1133 in = dup(STDIN_FILENO);
1135 out = dup(STDOUT_FILENO);
1136 err = dup(STDERR_FILENO);
1138 if (in < 0 || out < 0 || err < 0)
1139 fatal("dup() in/out/err failed");
1141 /* enable nonblocking unless tty */
1149 window = CHAN_SES_WINDOW_DEFAULT;
1150 packetmax = CHAN_SES_PACKET_DEFAULT;
1156 "session", SSH_CHANNEL_OPENING, in, out, err,
1157 window, packetmax, CHAN_EXTENDED_WRITE,
1158 "client-session", /*nonblock*/0);
1160 debug3("ssh_session2_open: channel_new: %d", c->self);
1162 channel_send_open(c->self);
1164 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1174 /* XXX should be pre-session */
1175 ssh_init_forwarding();
1176 ssh_control_listener();
1178 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1179 id = ssh_session2_open();
1181 /* Execute a local command */
1182 if (options.local_command != NULL &&
1183 options.permit_local_command)
1184 ssh_local_cmd(options.local_command);
1186 /* If requested, let ssh continue in the background. */
1187 if (fork_after_authentication_flag)
1188 if (daemon(1, 1) < 0)
1189 fatal("daemon() failed: %.200s", strerror(errno));
1191 return client_loop(tty_flag, tty_flag ?
1192 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1196 load_public_identity_files(void)
1198 char *filename, *cp, thishost[NI_MAXHOST];
1205 if (options.smartcard_device != NULL &&
1206 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1207 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1209 for (i = 0; keys[i] != NULL; i++) {
1211 memmove(&options.identity_files[1], &options.identity_files[0],
1212 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1213 memmove(&options.identity_keys[1], &options.identity_keys[0],
1214 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1215 options.num_identity_files++;
1216 options.identity_keys[0] = keys[i];
1217 options.identity_files[0] = sc_get_key_label(keys[i]);
1219 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1220 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1224 #endif /* SMARTCARD */
1225 if ((pw = getpwuid(original_real_uid)) == NULL)
1226 fatal("load_public_identity_files: getpwuid failed");
1227 if (gethostname(thishost, sizeof(thishost)) == -1)
1228 fatal("load_public_identity_files: gethostname: %s",
1230 for (; i < options.num_identity_files; i++) {
1231 cp = tilde_expand_filename(options.identity_files[i],
1233 filename = percent_expand(cp, "d", pw->pw_dir,
1234 "u", pw->pw_name, "l", thishost, "h", host,
1235 "r", options.user, (char *)NULL);
1237 public = key_load_public(filename, NULL);
1238 debug("identity file %s type %d", filename,
1239 public ? public->type : -1);
1240 xfree(options.identity_files[i]);
1241 options.identity_files[i] = filename;
1242 options.identity_keys[i] = public;
1247 control_client_sighandler(int signo)
1249 control_client_terminate = signo;
1253 control_client_sigrelay(int signo)
1255 if (control_server_pid > 1)
1256 kill(control_server_pid, signo);
1260 env_permitted(char *env)
1263 char name[1024], *cp;
1265 if (strlcpy(name, env, sizeof(name)) >= sizeof(name))
1266 fatal("env_permitted: name too long");
1267 if ((cp = strchr(name, '=')) == NULL)
1272 for (i = 0; i < options.num_send_env; i++)
1273 if (match_pattern(name, options.send_env[i]))
1280 control_client(const char *path)
1282 struct sockaddr_un addr;
1283 int i, r, fd, sock, exitval, num_env, addr_len;
1286 extern char **environ;
1289 if (mux_command == 0)
1290 mux_command = SSHMUX_COMMAND_OPEN;
1292 switch (options.control_master) {
1293 case SSHCTL_MASTER_AUTO:
1294 case SSHCTL_MASTER_AUTO_ASK:
1295 debug("auto-mux: Trying existing master");
1297 case SSHCTL_MASTER_NO:
1303 memset(&addr, '\0', sizeof(addr));
1304 addr.sun_family = AF_UNIX;
1305 addr_len = offsetof(struct sockaddr_un, sun_path) +
1308 if (strlcpy(addr.sun_path, path,
1309 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1310 fatal("ControlPath too long");
1312 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1313 fatal("%s socket(): %s", __func__, strerror(errno));
1315 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1316 if (mux_command != SSHMUX_COMMAND_OPEN) {
1317 fatal("Control socket connect(%.100s): %s", path,
1320 if (errno == ENOENT)
1321 debug("Control socket \"%.100s\" does not exist", path);
1323 error("Control socket connect(%.100s): %s", path,
1330 if (stdin_null_flag) {
1331 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1332 fatal("open(/dev/null): %s", strerror(errno));
1333 if (dup2(fd, STDIN_FILENO) == -1)
1334 fatal("dup2: %s", strerror(errno));
1335 if (fd > STDERR_FILENO)
1339 term = getenv("TERM");
1343 flags |= SSHMUX_FLAG_TTY;
1345 flags |= SSHMUX_FLAG_SUBSYS;
1346 if (options.forward_x11)
1347 flags |= SSHMUX_FLAG_X11_FWD;
1348 if (options.forward_agent)
1349 flags |= SSHMUX_FLAG_AGENT_FWD;
1353 /* Send our command to server */
1354 buffer_put_int(&m, mux_command);
1355 buffer_put_int(&m, flags);
1356 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1357 fatal("%s: msg_send", __func__);
1360 /* Get authorisation status and PID of controlee */
1361 if (ssh_msg_recv(sock, &m) == -1)
1362 fatal("%s: msg_recv", __func__);
1363 if (buffer_get_char(&m) != SSHMUX_VER)
1364 fatal("%s: wrong version", __func__);
1365 if (buffer_get_int(&m) != 1)
1366 fatal("Connection to master denied");
1367 control_server_pid = buffer_get_int(&m);
1371 switch (mux_command) {
1372 case SSHMUX_COMMAND_ALIVE_CHECK:
1373 fprintf(stderr, "Master running (pid=%d)\r\n",
1374 control_server_pid);
1376 case SSHMUX_COMMAND_TERMINATE:
1377 fprintf(stderr, "Exit request sent.\r\n");
1379 case SSHMUX_COMMAND_OPEN:
1380 /* continue below */
1383 fatal("silly mux_command %d", mux_command);
1386 /* SSHMUX_COMMAND_OPEN */
1387 buffer_put_cstring(&m, term ? term : "");
1388 buffer_append(&command, "\0", 1);
1389 buffer_put_cstring(&m, buffer_ptr(&command));
1391 if (options.num_send_env == 0 || environ == NULL) {
1392 buffer_put_int(&m, 0);
1394 /* Pass environment */
1396 for (i = 0; environ[i] != NULL; i++)
1397 if (env_permitted(environ[i]))
1398 num_env++; /* Count */
1400 buffer_put_int(&m, num_env);
1402 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1403 if (env_permitted(environ[i])) {
1405 buffer_put_cstring(&m, environ[i]);
1409 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1410 fatal("%s: msg_send", __func__);
1412 mm_send_fd(sock, STDIN_FILENO);
1413 mm_send_fd(sock, STDOUT_FILENO);
1414 mm_send_fd(sock, STDERR_FILENO);
1416 /* Wait for reply, so master has a chance to gather ttymodes */
1418 if (ssh_msg_recv(sock, &m) == -1)
1419 fatal("%s: msg_recv", __func__);
1420 if (buffer_get_char(&m) != SSHMUX_VER)
1421 fatal("%s: wrong version", __func__);
1424 signal(SIGHUP, control_client_sighandler);
1425 signal(SIGINT, control_client_sighandler);
1426 signal(SIGTERM, control_client_sighandler);
1427 signal(SIGWINCH, control_client_sigrelay);
1432 /* Stick around until the controlee closes the client_fd */
1434 for (;!control_client_terminate;) {
1435 r = read(sock, &exitval, sizeof(exitval));
1437 debug2("Received EOF from master");
1441 debug2("Received exit status from master %d", exitval);
1442 if (r == -1 && errno != EINTR)
1443 fatal("%s: read %s", __func__, strerror(errno));
1446 if (control_client_terminate)
1447 debug2("Exiting on signal %d", control_client_terminate);
1453 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1454 fprintf(stderr, "Connection to master closed.\r\n");