1 /* $OpenBSD: ssh.c,v 1.310 2008/05/08 12:02:23 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
70 #include <netinet/in.h>
71 #include <arpa/inet.h>
73 #include <openssl/evp.h>
74 #include <openssl/err.h>
75 #include "openbsd-compat/openssl-compat.h"
76 #include "openbsd-compat/sys-queue.h"
90 #include "pathnames.h"
92 #include "clientloop.h"
95 #include "sshconnect.h"
102 #include "monitor_fdpass.h"
110 extern char *__progname;
112 /* Flag indicating whether debug mode is on. This can be set on the command line. */
115 /* Flag indicating whether a tty should be allocated */
118 int force_tty_flag = 0;
120 /* don't exec a shell */
121 int no_shell_flag = 0;
124 * Flag indicating that nothing should be read from stdin. This can be set
125 * on the command line.
127 int stdin_null_flag = 0;
130 * Flag indicating that ssh should fork after authentication. This is useful
131 * so that the passphrase can be entered manually, and then ssh goes to the
134 int fork_after_authentication_flag = 0;
137 * General data structure for command line options and options configurable
138 * in configuration files. See readconf.h.
142 /* optional user configfile */
146 * Name of the host we are connecting to. This is the name given on the
147 * command line, or the HostName specified for the user-supplied name in a
148 * configuration file.
152 /* socket address the host resolves to */
153 struct sockaddr_storage hostaddr;
155 /* Private host keys. */
156 Sensitive sensitive_data;
158 /* Original real UID. */
159 uid_t original_real_uid;
160 uid_t original_effective_uid;
162 /* command to be executed */
165 /* Should we execute a command or invoke a subsystem? */
166 int subsystem_flag = 0;
168 /* # of replies received for global requests */
169 static int client_global_request_id = 0;
171 /* pid of proxycommand child process */
172 pid_t proxy_command_pid = 0;
174 /* fd to control socket */
177 /* Multiplexing control command */
178 static u_int mux_command = 0;
180 /* Only used in control client mode */
181 volatile sig_atomic_t control_client_terminate = 0;
182 u_int control_server_pid = 0;
184 /* Prints a help message to the user. This function never returns. */
190 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
191 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
192 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
193 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
194 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
195 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
200 static int ssh_session(void);
201 static int ssh_session2(void);
202 static void load_public_identity_files(void);
203 static void control_client(const char *path);
206 * Main program for the ssh client.
209 main(int ac, char **av)
211 int i, opt, exit_status;
212 char *p, *cp, *line, buf[256];
215 int dummy, timeout_ms;
216 extern int optind, optreset;
221 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
224 __progname = ssh_get_progname(av[0]);
228 * Save the original real uid. It will be needed later (uid-swapping
229 * may clobber the real uid).
231 original_real_uid = getuid();
232 original_effective_uid = geteuid();
235 * Use uid-swapping to give up root privileges for the duration of
236 * option processing. We will re-instantiate the rights when we are
237 * ready to create the privileged port, and will permanently drop
238 * them when the port has been created (actually, when the connection
239 * has been made, as we may need to create the port several times).
243 #ifdef HAVE_SETRLIMIT
244 /* If we are installed setuid root be careful to not drop core. */
245 if (original_real_uid != original_effective_uid) {
247 rlim.rlim_cur = rlim.rlim_max = 0;
248 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
249 fatal("setrlimit failed: %.100s", strerror(errno));
253 pw = getpwuid(original_real_uid);
255 logit("You don't exist, go away!");
258 /* Take a copy of the returned structure. */
262 * Set our umask to something reasonable, as some files are created
263 * with the default umask. This will make them world-readable but
264 * writable only by the owner, which is ok for all files for which we
265 * don't set the modes explicitly.
269 /* Initialize option structure to indicate that no values have been set. */
270 initialize_options(&options);
272 /* Parse command-line arguments. */
276 while ((opt = getopt(ac, av,
277 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:KL:MNO:PR:S:TVw:XY")) != -1) {
280 options.protocol = SSH_PROTO_1;
283 options.protocol = SSH_PROTO_2;
286 options.address_family = AF_INET;
289 options.address_family = AF_INET6;
295 fork_after_authentication_flag = 1;
299 options.forward_x11 = 0;
302 options.forward_x11 = 1;
305 options.forward_x11 = 1;
306 options.forward_x11_trusted = 1;
309 options.gateway_ports = 1;
312 if (strcmp(optarg, "check") == 0)
313 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
314 else if (strcmp(optarg, "exit") == 0)
315 mux_command = SSHMUX_COMMAND_TERMINATE;
317 fatal("Invalid multiplex command.");
319 case 'P': /* deprecated */
320 options.use_privileged_port = 0;
323 options.forward_agent = 0;
326 options.forward_agent = 1;
329 options.gss_deleg_creds = 0;
332 options.gss_authentication = 1;
333 options.gss_deleg_creds = 1;
336 if (stat(optarg, &st) < 0) {
337 fprintf(stderr, "Warning: Identity file %s "
338 "not accessible: %s.\n", optarg,
342 if (options.num_identity_files >=
343 SSH_MAX_IDENTITY_FILES)
344 fatal("Too many identity files specified "
345 "(max %d)", SSH_MAX_IDENTITY_FILES);
346 options.identity_files[options.num_identity_files++] =
351 options.smartcard_device = xstrdup(optarg);
353 fprintf(stderr, "no support for smartcards.\n");
362 if (debug_flag == 0) {
364 options.log_level = SYSLOG_LEVEL_DEBUG1;
366 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
372 fprintf(stderr, "%s, %s\n",
373 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
378 if (options.tun_open == -1)
379 options.tun_open = SSH_TUNMODE_DEFAULT;
380 options.tun_local = a2tun(optarg, &options.tun_remote);
381 if (options.tun_local == SSH_TUNID_ERR) {
382 fprintf(stderr, "Bad tun device '%s'\n", optarg);
387 options.log_level = SYSLOG_LEVEL_QUIET;
390 if (optarg[0] == '^' && optarg[2] == 0 &&
391 (u_char) optarg[1] >= 64 &&
392 (u_char) optarg[1] < 128)
393 options.escape_char = (u_char) optarg[1] & 31;
394 else if (strlen(optarg) == 1)
395 options.escape_char = (u_char) optarg[0];
396 else if (strcmp(optarg, "none") == 0)
397 options.escape_char = SSH_ESCAPECHAR_NONE;
399 fprintf(stderr, "Bad escape character '%s'.\n",
405 if (ciphers_valid(optarg)) {
407 options.ciphers = xstrdup(optarg);
408 options.cipher = SSH_CIPHER_INVALID;
411 options.cipher = cipher_number(optarg);
412 if (options.cipher == -1) {
414 "Unknown cipher type '%s'\n",
418 if (options.cipher == SSH_CIPHER_3DES)
419 options.ciphers = "3des-cbc";
420 else if (options.cipher == SSH_CIPHER_BLOWFISH)
421 options.ciphers = "blowfish-cbc";
423 options.ciphers = (char *)-1;
427 if (mac_valid(optarg))
428 options.macs = xstrdup(optarg);
430 fprintf(stderr, "Unknown mac type '%s'\n",
436 if (options.control_master == SSHCTL_MASTER_YES)
437 options.control_master = SSHCTL_MASTER_ASK;
439 options.control_master = SSHCTL_MASTER_YES;
442 options.port = a2port(optarg);
443 if (options.port == 0) {
444 fprintf(stderr, "Bad port '%s'\n", optarg);
449 options.user = optarg;
453 if (parse_forward(&fwd, optarg))
454 add_local_forward(&options, &fwd);
457 "Bad local forwarding specification '%s'\n",
464 if (parse_forward(&fwd, optarg)) {
465 add_remote_forward(&options, &fwd);
468 "Bad remote forwarding specification "
475 cp = p = xstrdup(optarg);
476 memset(&fwd, '\0', sizeof(fwd));
477 fwd.connect_host = "socks";
478 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
479 fprintf(stderr, "Bad dynamic forwarding "
480 "specification '%.100s'\n", optarg);
484 fwd.listen_port = a2port(cp);
485 fwd.listen_host = cleanhostname(fwd.listen_host);
487 fwd.listen_port = a2port(fwd.listen_host);
488 fwd.listen_host = NULL;
491 if (fwd.listen_port == 0) {
492 fprintf(stderr, "Bad dynamic port '%s'\n",
496 add_local_forward(&options, &fwd);
501 options.compression = 1;
512 line = xstrdup(optarg);
513 if (process_config_line(&options, host ? host : "",
514 line, "command-line", 0, &dummy) != 0)
522 if (options.control_path != NULL)
523 free(options.control_path);
524 options.control_path = xstrdup(optarg);
527 options.bind_address = optarg;
540 if (ac > 0 && !host && **av != '-') {
541 if (strrchr(*av, '@')) {
543 cp = strrchr(p, '@');
544 if (cp == NULL || cp == p)
552 optind = optreset = 1;
558 /* Check that we got a host name. */
562 SSLeay_add_all_algorithms();
563 ERR_load_crypto_strings();
565 /* Initialize the command to execute on remote host. */
566 buffer_init(&command);
569 * Save the command to execute on the remote host in a buffer. There
570 * is no limit on the length of the command, except by the maximum
571 * packet size. Also sets the tty flag if there is no command.
574 /* No command specified - execute shell on a tty. */
576 if (subsystem_flag) {
578 "You must specify a subsystem to invoke.\n");
582 /* A command has been specified. Store it into the buffer. */
583 for (i = 0; i < ac; i++) {
585 buffer_append(&command, " ", 1);
586 buffer_append(&command, av[i], strlen(av[i]));
590 /* Cannot fork to background if no command. */
591 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
592 fatal("Cannot fork into background without a command to execute.");
594 /* Allocate a tty by default if no command specified. */
595 if (buffer_len(&command) == 0)
601 /* Do not allocate a tty if stdin is not a tty. */
602 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
604 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
609 * Initialize "log" output. Since we are the client all output
610 * actually goes to stderr.
612 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
613 SYSLOG_FACILITY_USER, 1);
616 * Read per-user configuration file. Ignore the system wide config
617 * file if the user specifies a config file on the command line.
619 if (config != NULL) {
620 if (!read_config_file(config, host, &options, 0))
621 fatal("Can't open user config file %.100s: "
622 "%.100s", config, strerror(errno));
624 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
625 _PATH_SSH_USER_CONFFILE);
626 (void)read_config_file(buf, host, &options, 1);
628 /* Read systemwide configuration file after use config. */
629 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
633 /* Fill configuration defaults. */
634 fill_default_options(&options);
636 channel_set_af(options.address_family);
639 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
643 if (options.user == NULL)
644 options.user = xstrdup(pw->pw_name);
646 if (options.hostname != NULL)
647 host = options.hostname;
649 /* force lowercase for hostkey matching */
650 if (options.host_key_alias != NULL) {
651 for (p = options.host_key_alias; *p; p++)
653 *p = (char)tolower(*p);
656 /* Get default port if port has not been set. */
657 if (options.port == 0) {
658 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
659 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
662 if (options.proxy_command != NULL &&
663 strcmp(options.proxy_command, "none") == 0) {
664 xfree(options.proxy_command);
665 options.proxy_command = NULL;
667 if (options.control_path != NULL &&
668 strcmp(options.control_path, "none") == 0) {
669 xfree(options.control_path);
670 options.control_path = NULL;
673 if (options.control_path != NULL) {
674 char thishost[NI_MAXHOST];
676 if (gethostname(thishost, sizeof(thishost)) == -1)
677 fatal("gethostname: %s", strerror(errno));
678 snprintf(buf, sizeof(buf), "%d", options.port);
679 cp = tilde_expand_filename(options.control_path,
681 xfree(options.control_path);
682 options.control_path = percent_expand(cp, "p", buf, "h", host,
683 "r", options.user, "l", thishost, (char *)NULL);
686 if (mux_command != 0 && options.control_path == NULL)
687 fatal("No ControlPath specified for \"-O\" command");
688 if (options.control_path != NULL)
689 control_client(options.control_path);
691 timeout_ms = options.connection_timeout * 1000;
693 /* Open a connection to the remote host. */
694 if (ssh_connect(host, &hostaddr, options.port,
695 options.address_family, options.connection_attempts, &timeout_ms,
696 options.tcp_keep_alive,
698 options.use_privileged_port,
700 original_effective_uid == 0 && options.use_privileged_port,
702 options.proxy_command) != 0)
706 debug3("timeout: %d ms remain after connect", timeout_ms);
709 * If we successfully made the connection, load the host private key
710 * in case we will need it later for combined rsa-rhosts
711 * authentication. This must be done before releasing extra
712 * privileges, because the file is only readable by root.
713 * If we cannot access the private keys, load the public keys
714 * instead and try to execute the ssh-keysign helper instead.
716 sensitive_data.nkeys = 0;
717 sensitive_data.keys = NULL;
718 sensitive_data.external_keysign = 0;
719 if (options.rhosts_rsa_authentication ||
720 options.hostbased_authentication) {
721 sensitive_data.nkeys = 3;
722 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
726 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
727 _PATH_HOST_KEY_FILE, "", NULL, NULL);
728 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
729 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
730 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
731 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
734 if (options.hostbased_authentication == 1 &&
735 sensitive_data.keys[0] == NULL &&
736 sensitive_data.keys[1] == NULL &&
737 sensitive_data.keys[2] == NULL) {
738 sensitive_data.keys[1] = key_load_public(
739 _PATH_HOST_DSA_KEY_FILE, NULL);
740 sensitive_data.keys[2] = key_load_public(
741 _PATH_HOST_RSA_KEY_FILE, NULL);
742 sensitive_data.external_keysign = 1;
746 * Get rid of any extra privileges that we may have. We will no
747 * longer need them. Also, extra privileges could make it very hard
748 * to read identity files and other non-world-readable files from the
749 * user's home directory if it happens to be on a NFS volume where
750 * root is mapped to nobody.
752 if (original_effective_uid == 0) {
754 permanently_set_uid(pw);
758 * Now that we are back to our own permissions, create ~/.ssh
759 * directory if it doesn't already exist.
761 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
762 if (stat(buf, &st) < 0)
763 if (mkdir(buf, 0700) < 0)
764 error("Could not create directory '%.200s'.", buf);
766 /* load options.identity_files */
767 load_public_identity_files();
769 /* Expand ~ in known host file names. */
771 options.system_hostfile =
772 tilde_expand_filename(options.system_hostfile, original_real_uid);
773 options.user_hostfile =
774 tilde_expand_filename(options.user_hostfile, original_real_uid);
775 options.system_hostfile2 =
776 tilde_expand_filename(options.system_hostfile2, original_real_uid);
777 options.user_hostfile2 =
778 tilde_expand_filename(options.user_hostfile2, original_real_uid);
780 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
782 /* Log into the remote system. This never returns if the login fails. */
783 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
786 /* We no longer need the private host keys. Clear them now. */
787 if (sensitive_data.nkeys != 0) {
788 for (i = 0; i < sensitive_data.nkeys; i++) {
789 if (sensitive_data.keys[i] != NULL) {
790 /* Destroys contents safely */
791 debug3("clear hostkey %d", i);
792 key_free(sensitive_data.keys[i]);
793 sensitive_data.keys[i] = NULL;
796 xfree(sensitive_data.keys);
798 for (i = 0; i < options.num_identity_files; i++) {
799 if (options.identity_files[i]) {
800 xfree(options.identity_files[i]);
801 options.identity_files[i] = NULL;
803 if (options.identity_keys[i]) {
804 key_free(options.identity_keys[i]);
805 options.identity_keys[i] = NULL;
809 exit_status = compat20 ? ssh_session2() : ssh_session();
812 if (options.control_path != NULL && control_fd != -1)
813 unlink(options.control_path);
816 * Send SIGHUP to proxy command if used. We don't wait() in
817 * case it hangs and instead rely on init to reap the child
819 if (proxy_command_pid > 1)
820 kill(proxy_command_pid, SIGHUP);
826 ssh_init_forwarding(void)
831 /* Initiate local TCP/IP port forwardings. */
832 for (i = 0; i < options.num_local_forwards; i++) {
833 debug("Local connections to %.200s:%d forwarded to remote "
835 (options.local_forwards[i].listen_host == NULL) ?
836 (options.gateway_ports ? "*" : "LOCALHOST") :
837 options.local_forwards[i].listen_host,
838 options.local_forwards[i].listen_port,
839 options.local_forwards[i].connect_host,
840 options.local_forwards[i].connect_port);
841 success += channel_setup_local_fwd_listener(
842 options.local_forwards[i].listen_host,
843 options.local_forwards[i].listen_port,
844 options.local_forwards[i].connect_host,
845 options.local_forwards[i].connect_port,
846 options.gateway_ports);
848 if (i > 0 && success != i && options.exit_on_forward_failure)
849 fatal("Could not request local forwarding.");
850 if (i > 0 && success == 0)
851 error("Could not request local forwarding.");
853 /* Initiate remote TCP/IP port forwardings. */
854 for (i = 0; i < options.num_remote_forwards; i++) {
855 debug("Remote connections from %.200s:%d forwarded to "
856 "local address %.200s:%d",
857 (options.remote_forwards[i].listen_host == NULL) ?
858 "LOCALHOST" : options.remote_forwards[i].listen_host,
859 options.remote_forwards[i].listen_port,
860 options.remote_forwards[i].connect_host,
861 options.remote_forwards[i].connect_port);
862 if (channel_request_remote_forwarding(
863 options.remote_forwards[i].listen_host,
864 options.remote_forwards[i].listen_port,
865 options.remote_forwards[i].connect_host,
866 options.remote_forwards[i].connect_port) < 0) {
867 if (options.exit_on_forward_failure)
868 fatal("Could not request remote forwarding.");
870 logit("Warning: Could not request remote "
875 /* Initiate tunnel forwarding. */
876 if (options.tun_open != SSH_TUNMODE_NO) {
877 if (client_request_tun_fwd(options.tun_open,
878 options.tun_local, options.tun_remote) == -1) {
879 if (options.exit_on_forward_failure)
880 fatal("Could not request tunnel forwarding.");
882 error("Could not request tunnel forwarding.");
888 check_agent_present(void)
890 if (options.forward_agent) {
891 /* Clear agent forwarding if we don't have an agent. */
892 if (!ssh_agent_present())
893 options.forward_agent = 0;
907 /* Enable compression if requested. */
908 if (options.compression) {
909 debug("Requesting compression at level %d.", options.compression_level);
911 if (options.compression_level < 1 || options.compression_level > 9)
912 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
914 /* Send the request. */
915 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
916 packet_put_int(options.compression_level);
919 type = packet_read();
920 if (type == SSH_SMSG_SUCCESS)
921 packet_start_compression(options.compression_level);
922 else if (type == SSH_SMSG_FAILURE)
923 logit("Warning: Remote host refused compression.");
925 packet_disconnect("Protocol error waiting for compression response.");
927 /* Allocate a pseudo tty if appropriate. */
929 debug("Requesting pty.");
931 /* Start the packet. */
932 packet_start(SSH_CMSG_REQUEST_PTY);
934 /* Store TERM in the packet. There is no limit on the
935 length of the string. */
939 packet_put_cstring(cp);
941 /* Store window size in the packet. */
942 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
943 memset(&ws, 0, sizeof(ws));
944 packet_put_int((u_int)ws.ws_row);
945 packet_put_int((u_int)ws.ws_col);
946 packet_put_int((u_int)ws.ws_xpixel);
947 packet_put_int((u_int)ws.ws_ypixel);
949 /* Store tty modes in the packet. */
950 tty_make_modes(fileno(stdin), NULL);
952 /* Send the packet, and wait for it to leave. */
956 /* Read response from the server. */
957 type = packet_read();
958 if (type == SSH_SMSG_SUCCESS) {
961 } else if (type == SSH_SMSG_FAILURE)
962 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
964 packet_disconnect("Protocol error waiting for pty request response.");
966 /* Request X11 forwarding if enabled and DISPLAY is set. */
967 display = getenv("DISPLAY");
968 if (options.forward_x11 && display != NULL) {
970 /* Get reasonable local authentication information. */
971 client_x11_get_proto(display, options.xauth_location,
972 options.forward_x11_trusted, &proto, &data);
973 /* Request forwarding with authentication spoofing. */
974 debug("Requesting X11 forwarding with authentication spoofing.");
975 x11_request_forwarding_with_spoofing(0, display, proto, data);
977 /* Read response from the server. */
978 type = packet_read();
979 if (type == SSH_SMSG_SUCCESS) {
981 } else if (type == SSH_SMSG_FAILURE) {
982 logit("Warning: Remote host denied X11 forwarding.");
984 packet_disconnect("Protocol error waiting for X11 forwarding");
987 /* Tell the packet module whether this is an interactive session. */
988 packet_set_interactive(interactive);
990 /* Request authentication agent forwarding if appropriate. */
991 check_agent_present();
993 if (options.forward_agent) {
994 debug("Requesting authentication agent forwarding.");
995 auth_request_forwarding();
997 /* Read response from the server. */
998 type = packet_read();
1000 if (type != SSH_SMSG_SUCCESS)
1001 logit("Warning: Remote host denied authentication agent forwarding.");
1004 /* Initiate port forwardings. */
1005 ssh_init_forwarding();
1007 /* Execute a local command */
1008 if (options.local_command != NULL &&
1009 options.permit_local_command)
1010 ssh_local_cmd(options.local_command);
1012 /* If requested, let ssh continue in the background. */
1013 if (fork_after_authentication_flag)
1014 if (daemon(1, 1) < 0)
1015 fatal("daemon() failed: %.200s", strerror(errno));
1018 * If a command was specified on the command line, execute the
1019 * command now. Otherwise request the server to start a shell.
1021 if (buffer_len(&command) > 0) {
1022 int len = buffer_len(&command);
1025 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1026 packet_start(SSH_CMSG_EXEC_CMD);
1027 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1029 packet_write_wait();
1031 debug("Requesting shell.");
1032 packet_start(SSH_CMSG_EXEC_SHELL);
1034 packet_write_wait();
1037 /* Enter the interactive session. */
1038 return client_loop(have_tty, tty_flag ?
1039 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1043 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1047 id = packet_get_int();
1048 len = buffer_len(&command);
1052 if (type == SSH2_MSG_CHANNEL_FAILURE)
1053 fatal("Request for subsystem '%.*s' failed on channel %d",
1054 len, (u_char *)buffer_ptr(&command), id);
1058 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1062 i = client_global_request_id++;
1063 if (i >= options.num_remote_forwards)
1065 debug("remote forward %s for: listen %d, connect %s:%d",
1066 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1067 options.remote_forwards[i].listen_port,
1068 options.remote_forwards[i].connect_host,
1069 options.remote_forwards[i].connect_port);
1070 if (type == SSH2_MSG_REQUEST_FAILURE) {
1071 if (options.exit_on_forward_failure)
1072 fatal("Error: remote port forwarding failed for "
1074 options.remote_forwards[i].listen_port);
1076 logit("Warning: remote port forwarding failed for "
1078 options.remote_forwards[i].listen_port);
1083 ssh_control_listener(void)
1085 struct sockaddr_un addr;
1089 if (options.control_path == NULL ||
1090 options.control_master == SSHCTL_MASTER_NO)
1093 debug("setting up multiplex master socket");
1095 memset(&addr, '\0', sizeof(addr));
1096 addr.sun_family = AF_UNIX;
1097 addr_len = offsetof(struct sockaddr_un, sun_path) +
1098 strlen(options.control_path) + 1;
1100 if (strlcpy(addr.sun_path, options.control_path,
1101 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1102 fatal("ControlPath too long");
1104 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1105 fatal("%s socket(): %s", __func__, strerror(errno));
1107 old_umask = umask(0177);
1108 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1110 if (errno == EINVAL || errno == EADDRINUSE)
1111 fatal("ControlSocket %s already exists",
1112 options.control_path);
1114 fatal("%s bind(): %s", __func__, strerror(errno));
1118 if (listen(control_fd, 64) == -1)
1119 fatal("%s listen(): %s", __func__, strerror(errno));
1121 set_nonblock(control_fd);
1124 /* request pty/x11/agent/tcpfwd/shell for channel */
1126 ssh_session2_setup(int id, void *arg)
1128 extern char **environ;
1129 const char *display;
1130 int interactive = tty_flag;
1132 display = getenv("DISPLAY");
1133 if (options.forward_x11 && display != NULL) {
1135 /* Get reasonable local authentication information. */
1136 client_x11_get_proto(display, options.xauth_location,
1137 options.forward_x11_trusted, &proto, &data);
1138 /* Request forwarding with authentication spoofing. */
1139 debug("Requesting X11 forwarding with authentication spoofing.");
1140 x11_request_forwarding_with_spoofing(id, display, proto, data);
1142 /* XXX wait for reply */
1145 check_agent_present();
1146 if (options.forward_agent) {
1147 debug("Requesting authentication agent forwarding.");
1148 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1152 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1153 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1155 packet_set_interactive(interactive);
1158 /* open new channel for a session */
1160 ssh_session2_open(void)
1163 int window, packetmax, in, out, err;
1165 if (stdin_null_flag) {
1166 in = open(_PATH_DEVNULL, O_RDONLY);
1168 in = dup(STDIN_FILENO);
1170 out = dup(STDOUT_FILENO);
1171 err = dup(STDERR_FILENO);
1173 if (in < 0 || out < 0 || err < 0)
1174 fatal("dup() in/out/err failed");
1176 /* enable nonblocking unless tty */
1184 window = CHAN_SES_WINDOW_DEFAULT;
1185 packetmax = CHAN_SES_PACKET_DEFAULT;
1191 "session", SSH_CHANNEL_OPENING, in, out, err,
1192 window, packetmax, CHAN_EXTENDED_WRITE,
1193 "client-session", /*nonblock*/0);
1195 debug3("ssh_session2_open: channel_new: %d", c->self);
1197 channel_send_open(c->self);
1199 channel_register_open_confirm(c->self,
1200 ssh_session2_setup, NULL);
1210 /* XXX should be pre-session */
1211 ssh_init_forwarding();
1213 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1214 id = ssh_session2_open();
1216 /* Execute a local command */
1217 if (options.local_command != NULL &&
1218 options.permit_local_command)
1219 ssh_local_cmd(options.local_command);
1221 /* Start listening for multiplex clients */
1222 ssh_control_listener();
1224 /* If requested, let ssh continue in the background. */
1225 if (fork_after_authentication_flag)
1226 if (daemon(1, 1) < 0)
1227 fatal("daemon() failed: %.200s", strerror(errno));
1229 return client_loop(tty_flag, tty_flag ?
1230 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1234 load_public_identity_files(void)
1236 char *filename, *cp, thishost[NI_MAXHOST];
1237 char *pwdir = NULL, *pwname = NULL;
1244 if (options.smartcard_device != NULL &&
1245 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1246 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1248 for (i = 0; keys[i] != NULL; i++) {
1250 memmove(&options.identity_files[1], &options.identity_files[0],
1251 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1252 memmove(&options.identity_keys[1], &options.identity_keys[0],
1253 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1254 options.num_identity_files++;
1255 options.identity_keys[0] = keys[i];
1256 options.identity_files[0] = sc_get_key_label(keys[i]);
1258 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1259 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1263 #endif /* SMARTCARD */
1264 if ((pw = getpwuid(original_real_uid)) == NULL)
1265 fatal("load_public_identity_files: getpwuid failed");
1266 pwname = xstrdup(pw->pw_name);
1267 pwdir = xstrdup(pw->pw_dir);
1268 if (gethostname(thishost, sizeof(thishost)) == -1)
1269 fatal("load_public_identity_files: gethostname: %s",
1271 for (; i < options.num_identity_files; i++) {
1272 cp = tilde_expand_filename(options.identity_files[i],
1274 filename = percent_expand(cp, "d", pwdir,
1275 "u", pwname, "l", thishost, "h", host,
1276 "r", options.user, (char *)NULL);
1278 public = key_load_public(filename, NULL);
1279 debug("identity file %s type %d", filename,
1280 public ? public->type : -1);
1281 xfree(options.identity_files[i]);
1282 options.identity_files[i] = filename;
1283 options.identity_keys[i] = public;
1285 bzero(pwname, strlen(pwname));
1287 bzero(pwdir, strlen(pwdir));
1292 control_client_sighandler(int signo)
1294 control_client_terminate = signo;
1298 control_client_sigrelay(int signo)
1300 int save_errno = errno;
1302 if (control_server_pid > 1)
1303 kill(control_server_pid, signo);
1309 env_permitted(char *env)
1312 char name[1024], *cp;
1314 if ((cp = strchr(env, '=')) == NULL || cp == env)
1316 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1317 if (ret <= 0 || (size_t)ret >= sizeof(name))
1318 fatal("env_permitted: name '%.100s...' too long", env);
1320 for (i = 0; i < options.num_send_env; i++)
1321 if (match_pattern(name, options.send_env[i]))
1328 control_client(const char *path)
1330 struct sockaddr_un addr;
1331 int i, r, fd, sock, exitval[2], num_env, addr_len;
1334 extern char **environ;
1337 if (mux_command == 0)
1338 mux_command = SSHMUX_COMMAND_OPEN;
1340 switch (options.control_master) {
1341 case SSHCTL_MASTER_AUTO:
1342 case SSHCTL_MASTER_AUTO_ASK:
1343 debug("auto-mux: Trying existing master");
1345 case SSHCTL_MASTER_NO:
1351 memset(&addr, '\0', sizeof(addr));
1352 addr.sun_family = AF_UNIX;
1353 addr_len = offsetof(struct sockaddr_un, sun_path) +
1356 if (strlcpy(addr.sun_path, path,
1357 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1358 fatal("ControlPath too long");
1360 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1361 fatal("%s socket(): %s", __func__, strerror(errno));
1363 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1364 if (mux_command != SSHMUX_COMMAND_OPEN) {
1365 fatal("Control socket connect(%.100s): %s", path,
1368 if (errno == ENOENT)
1369 debug("Control socket \"%.100s\" does not exist", path);
1371 error("Control socket connect(%.100s): %s", path,
1378 if (stdin_null_flag) {
1379 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1380 fatal("open(/dev/null): %s", strerror(errno));
1381 if (dup2(fd, STDIN_FILENO) == -1)
1382 fatal("dup2: %s", strerror(errno));
1383 if (fd > STDERR_FILENO)
1387 term = getenv("TERM");
1391 flags |= SSHMUX_FLAG_TTY;
1393 flags |= SSHMUX_FLAG_SUBSYS;
1394 if (options.forward_x11)
1395 flags |= SSHMUX_FLAG_X11_FWD;
1396 if (options.forward_agent)
1397 flags |= SSHMUX_FLAG_AGENT_FWD;
1399 signal(SIGPIPE, SIG_IGN);
1403 /* Send our command to server */
1404 buffer_put_int(&m, mux_command);
1405 buffer_put_int(&m, flags);
1406 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1407 fatal("%s: msg_send", __func__);
1410 /* Get authorisation status and PID of controlee */
1411 if (ssh_msg_recv(sock, &m) == -1)
1412 fatal("%s: msg_recv", __func__);
1413 if (buffer_get_char(&m) != SSHMUX_VER)
1414 fatal("%s: wrong version", __func__);
1415 if (buffer_get_int(&m) != 1)
1416 fatal("Connection to master denied");
1417 control_server_pid = buffer_get_int(&m);
1421 switch (mux_command) {
1422 case SSHMUX_COMMAND_ALIVE_CHECK:
1423 fprintf(stderr, "Master running (pid=%d)\r\n",
1424 control_server_pid);
1426 case SSHMUX_COMMAND_TERMINATE:
1427 fprintf(stderr, "Exit request sent.\r\n");
1429 case SSHMUX_COMMAND_OPEN:
1430 /* continue below */
1433 fatal("silly mux_command %d", mux_command);
1436 /* SSHMUX_COMMAND_OPEN */
1437 buffer_put_cstring(&m, term ? term : "");
1438 buffer_append(&command, "\0", 1);
1439 buffer_put_cstring(&m, buffer_ptr(&command));
1441 if (options.num_send_env == 0 || environ == NULL) {
1442 buffer_put_int(&m, 0);
1444 /* Pass environment */
1446 for (i = 0; environ[i] != NULL; i++)
1447 if (env_permitted(environ[i]))
1448 num_env++; /* Count */
1450 buffer_put_int(&m, num_env);
1452 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1453 if (env_permitted(environ[i])) {
1455 buffer_put_cstring(&m, environ[i]);
1459 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1460 fatal("%s: msg_send", __func__);
1462 if (mm_send_fd(sock, STDIN_FILENO) == -1 ||
1463 mm_send_fd(sock, STDOUT_FILENO) == -1 ||
1464 mm_send_fd(sock, STDERR_FILENO) == -1)
1465 fatal("%s: send fds failed", __func__);
1467 /* Wait for reply, so master has a chance to gather ttymodes */
1469 if (ssh_msg_recv(sock, &m) == -1)
1470 fatal("%s: msg_recv", __func__);
1471 if (buffer_get_char(&m) != SSHMUX_VER)
1472 fatal("%s: wrong version", __func__);
1475 signal(SIGHUP, control_client_sighandler);
1476 signal(SIGINT, control_client_sighandler);
1477 signal(SIGTERM, control_client_sighandler);
1478 signal(SIGWINCH, control_client_sigrelay);
1484 * Stick around until the controlee closes the client_fd.
1485 * Before it does, it is expected to write this process' exit
1486 * value (one int). This process must read the value and wait for
1487 * the closure of the client_fd; if this one closes early, the
1488 * multiplex master will terminate early too (possibly losing data).
1491 for (i = 0; !control_client_terminate && i < (int)sizeof(exitval);) {
1492 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
1494 debug2("Received EOF from master");
1500 fatal("%s: read %s", __func__, strerror(errno));
1507 if (i > (int)sizeof(int))
1508 fatal("%s: master returned too much data (%d > %lu)",
1509 __func__, i, sizeof(int));
1510 if (control_client_terminate) {
1511 debug2("Exiting on signal %d", control_client_terminate);
1513 } else if (i < (int)sizeof(int)) {
1514 debug2("Control master terminated unexpectedly");
1517 debug2("Received exit status from master %d", exitval[0]);
1519 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1520 fprintf(stderr, "Shared connection to %s closed.\r\n", host);