1 /* $OpenBSD: ssh.c,v 1.311 2008/05/08 13:06:11 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 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1047 i = client_global_request_id++;
1048 if (i >= options.num_remote_forwards)
1050 debug("remote forward %s for: listen %d, connect %s:%d",
1051 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1052 options.remote_forwards[i].listen_port,
1053 options.remote_forwards[i].connect_host,
1054 options.remote_forwards[i].connect_port);
1055 if (type == SSH2_MSG_REQUEST_FAILURE) {
1056 if (options.exit_on_forward_failure)
1057 fatal("Error: remote port forwarding failed for "
1059 options.remote_forwards[i].listen_port);
1061 logit("Warning: remote port forwarding failed for "
1063 options.remote_forwards[i].listen_port);
1068 ssh_control_listener(void)
1070 struct sockaddr_un addr;
1074 if (options.control_path == NULL ||
1075 options.control_master == SSHCTL_MASTER_NO)
1078 debug("setting up multiplex master socket");
1080 memset(&addr, '\0', sizeof(addr));
1081 addr.sun_family = AF_UNIX;
1082 addr_len = offsetof(struct sockaddr_un, sun_path) +
1083 strlen(options.control_path) + 1;
1085 if (strlcpy(addr.sun_path, options.control_path,
1086 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1087 fatal("ControlPath too long");
1089 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1090 fatal("%s socket(): %s", __func__, strerror(errno));
1092 old_umask = umask(0177);
1093 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1095 if (errno == EINVAL || errno == EADDRINUSE)
1096 fatal("ControlSocket %s already exists",
1097 options.control_path);
1099 fatal("%s bind(): %s", __func__, strerror(errno));
1103 if (listen(control_fd, 64) == -1)
1104 fatal("%s listen(): %s", __func__, strerror(errno));
1106 set_nonblock(control_fd);
1109 /* request pty/x11/agent/tcpfwd/shell for channel */
1111 ssh_session2_setup(int id, void *arg)
1113 extern char **environ;
1114 const char *display;
1115 int interactive = tty_flag;
1117 display = getenv("DISPLAY");
1118 if (options.forward_x11 && display != NULL) {
1120 /* Get reasonable local authentication information. */
1121 client_x11_get_proto(display, options.xauth_location,
1122 options.forward_x11_trusted, &proto, &data);
1123 /* Request forwarding with authentication spoofing. */
1124 debug("Requesting X11 forwarding with authentication spoofing.");
1125 x11_request_forwarding_with_spoofing(id, display, proto, data);
1127 /* XXX wait for reply */
1130 check_agent_present();
1131 if (options.forward_agent) {
1132 debug("Requesting authentication agent forwarding.");
1133 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1137 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1138 NULL, fileno(stdin), &command, environ);
1140 packet_set_interactive(interactive);
1143 /* open new channel for a session */
1145 ssh_session2_open(void)
1148 int window, packetmax, in, out, err;
1150 if (stdin_null_flag) {
1151 in = open(_PATH_DEVNULL, O_RDONLY);
1153 in = dup(STDIN_FILENO);
1155 out = dup(STDOUT_FILENO);
1156 err = dup(STDERR_FILENO);
1158 if (in < 0 || out < 0 || err < 0)
1159 fatal("dup() in/out/err failed");
1161 /* enable nonblocking unless tty */
1169 window = CHAN_SES_WINDOW_DEFAULT;
1170 packetmax = CHAN_SES_PACKET_DEFAULT;
1176 "session", SSH_CHANNEL_OPENING, in, out, err,
1177 window, packetmax, CHAN_EXTENDED_WRITE,
1178 "client-session", /*nonblock*/0);
1180 debug3("ssh_session2_open: channel_new: %d", c->self);
1182 channel_send_open(c->self);
1184 channel_register_open_confirm(c->self,
1185 ssh_session2_setup, NULL);
1195 /* XXX should be pre-session */
1196 ssh_init_forwarding();
1198 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1199 id = ssh_session2_open();
1201 /* Execute a local command */
1202 if (options.local_command != NULL &&
1203 options.permit_local_command)
1204 ssh_local_cmd(options.local_command);
1206 /* Start listening for multiplex clients */
1207 ssh_control_listener();
1209 /* If requested, let ssh continue in the background. */
1210 if (fork_after_authentication_flag)
1211 if (daemon(1, 1) < 0)
1212 fatal("daemon() failed: %.200s", strerror(errno));
1214 return client_loop(tty_flag, tty_flag ?
1215 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1219 load_public_identity_files(void)
1221 char *filename, *cp, thishost[NI_MAXHOST];
1222 char *pwdir = NULL, *pwname = NULL;
1229 if (options.smartcard_device != NULL &&
1230 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1231 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1233 for (i = 0; keys[i] != NULL; i++) {
1235 memmove(&options.identity_files[1], &options.identity_files[0],
1236 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1237 memmove(&options.identity_keys[1], &options.identity_keys[0],
1238 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1239 options.num_identity_files++;
1240 options.identity_keys[0] = keys[i];
1241 options.identity_files[0] = sc_get_key_label(keys[i]);
1243 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1244 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1248 #endif /* SMARTCARD */
1249 if ((pw = getpwuid(original_real_uid)) == NULL)
1250 fatal("load_public_identity_files: getpwuid failed");
1251 pwname = xstrdup(pw->pw_name);
1252 pwdir = xstrdup(pw->pw_dir);
1253 if (gethostname(thishost, sizeof(thishost)) == -1)
1254 fatal("load_public_identity_files: gethostname: %s",
1256 for (; i < options.num_identity_files; i++) {
1257 cp = tilde_expand_filename(options.identity_files[i],
1259 filename = percent_expand(cp, "d", pwdir,
1260 "u", pwname, "l", thishost, "h", host,
1261 "r", options.user, (char *)NULL);
1263 public = key_load_public(filename, NULL);
1264 debug("identity file %s type %d", filename,
1265 public ? public->type : -1);
1266 xfree(options.identity_files[i]);
1267 options.identity_files[i] = filename;
1268 options.identity_keys[i] = public;
1270 bzero(pwname, strlen(pwname));
1272 bzero(pwdir, strlen(pwdir));
1277 control_client_sighandler(int signo)
1279 control_client_terminate = signo;
1283 control_client_sigrelay(int signo)
1285 int save_errno = errno;
1287 if (control_server_pid > 1)
1288 kill(control_server_pid, signo);
1294 env_permitted(char *env)
1297 char name[1024], *cp;
1299 if ((cp = strchr(env, '=')) == NULL || cp == env)
1301 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1302 if (ret <= 0 || (size_t)ret >= sizeof(name))
1303 fatal("env_permitted: name '%.100s...' too long", env);
1305 for (i = 0; i < options.num_send_env; i++)
1306 if (match_pattern(name, options.send_env[i]))
1313 control_client(const char *path)
1315 struct sockaddr_un addr;
1316 int i, r, fd, sock, exitval[2], num_env, addr_len;
1319 extern char **environ;
1322 if (mux_command == 0)
1323 mux_command = SSHMUX_COMMAND_OPEN;
1325 switch (options.control_master) {
1326 case SSHCTL_MASTER_AUTO:
1327 case SSHCTL_MASTER_AUTO_ASK:
1328 debug("auto-mux: Trying existing master");
1330 case SSHCTL_MASTER_NO:
1336 memset(&addr, '\0', sizeof(addr));
1337 addr.sun_family = AF_UNIX;
1338 addr_len = offsetof(struct sockaddr_un, sun_path) +
1341 if (strlcpy(addr.sun_path, path,
1342 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1343 fatal("ControlPath too long");
1345 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1346 fatal("%s socket(): %s", __func__, strerror(errno));
1348 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1349 if (mux_command != SSHMUX_COMMAND_OPEN) {
1350 fatal("Control socket connect(%.100s): %s", path,
1353 if (errno == ENOENT)
1354 debug("Control socket \"%.100s\" does not exist", path);
1356 error("Control socket connect(%.100s): %s", path,
1363 if (stdin_null_flag) {
1364 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1365 fatal("open(/dev/null): %s", strerror(errno));
1366 if (dup2(fd, STDIN_FILENO) == -1)
1367 fatal("dup2: %s", strerror(errno));
1368 if (fd > STDERR_FILENO)
1372 term = getenv("TERM");
1376 flags |= SSHMUX_FLAG_TTY;
1378 flags |= SSHMUX_FLAG_SUBSYS;
1379 if (options.forward_x11)
1380 flags |= SSHMUX_FLAG_X11_FWD;
1381 if (options.forward_agent)
1382 flags |= SSHMUX_FLAG_AGENT_FWD;
1384 signal(SIGPIPE, SIG_IGN);
1388 /* Send our command to server */
1389 buffer_put_int(&m, mux_command);
1390 buffer_put_int(&m, flags);
1391 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1392 fatal("%s: msg_send", __func__);
1395 /* Get authorisation status and PID of controlee */
1396 if (ssh_msg_recv(sock, &m) == -1)
1397 fatal("%s: msg_recv", __func__);
1398 if (buffer_get_char(&m) != SSHMUX_VER)
1399 fatal("%s: wrong version", __func__);
1400 if (buffer_get_int(&m) != 1)
1401 fatal("Connection to master denied");
1402 control_server_pid = buffer_get_int(&m);
1406 switch (mux_command) {
1407 case SSHMUX_COMMAND_ALIVE_CHECK:
1408 fprintf(stderr, "Master running (pid=%d)\r\n",
1409 control_server_pid);
1411 case SSHMUX_COMMAND_TERMINATE:
1412 fprintf(stderr, "Exit request sent.\r\n");
1414 case SSHMUX_COMMAND_OPEN:
1415 /* continue below */
1418 fatal("silly mux_command %d", mux_command);
1421 /* SSHMUX_COMMAND_OPEN */
1422 buffer_put_cstring(&m, term ? term : "");
1423 buffer_append(&command, "\0", 1);
1424 buffer_put_cstring(&m, buffer_ptr(&command));
1426 if (options.num_send_env == 0 || environ == NULL) {
1427 buffer_put_int(&m, 0);
1429 /* Pass environment */
1431 for (i = 0; environ[i] != NULL; i++)
1432 if (env_permitted(environ[i]))
1433 num_env++; /* Count */
1435 buffer_put_int(&m, num_env);
1437 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1438 if (env_permitted(environ[i])) {
1440 buffer_put_cstring(&m, environ[i]);
1444 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1445 fatal("%s: msg_send", __func__);
1447 if (mm_send_fd(sock, STDIN_FILENO) == -1 ||
1448 mm_send_fd(sock, STDOUT_FILENO) == -1 ||
1449 mm_send_fd(sock, STDERR_FILENO) == -1)
1450 fatal("%s: send fds failed", __func__);
1452 /* Wait for reply, so master has a chance to gather ttymodes */
1454 if (ssh_msg_recv(sock, &m) == -1)
1455 fatal("%s: msg_recv", __func__);
1456 if (buffer_get_char(&m) != SSHMUX_VER)
1457 fatal("%s: wrong version", __func__);
1460 signal(SIGHUP, control_client_sighandler);
1461 signal(SIGINT, control_client_sighandler);
1462 signal(SIGTERM, control_client_sighandler);
1463 signal(SIGWINCH, control_client_sigrelay);
1469 * Stick around until the controlee closes the client_fd.
1470 * Before it does, it is expected to write this process' exit
1471 * value (one int). This process must read the value and wait for
1472 * the closure of the client_fd; if this one closes early, the
1473 * multiplex master will terminate early too (possibly losing data).
1476 for (i = 0; !control_client_terminate && i < (int)sizeof(exitval);) {
1477 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
1479 debug2("Received EOF from master");
1485 fatal("%s: read %s", __func__, strerror(errno));
1492 if (i > (int)sizeof(int))
1493 fatal("%s: master returned too much data (%d > %lu)",
1494 __func__, i, sizeof(int));
1495 if (control_client_terminate) {
1496 debug2("Exiting on signal %d", control_client_terminate);
1498 } else if (i < (int)sizeof(int)) {
1499 debug2("Control master terminated unexpectedly");
1502 debug2("Received exit status from master %d", exitval[0]);
1504 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1505 fprintf(stderr, "Shared connection to %s closed.\r\n", host);