1 /* $OpenBSD: ssh.c,v 1.309 2008/01/19 20:51:26 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"
89 #include "pathnames.h"
91 #include "clientloop.h"
94 #include "sshconnect.h"
101 #include "monitor_fdpass.h"
109 extern char *__progname;
111 /* Flag indicating whether debug mode is on. This can be set on the command line. */
114 /* Flag indicating whether a tty should be allocated */
117 int force_tty_flag = 0;
119 /* don't exec a shell */
120 int no_shell_flag = 0;
123 * Flag indicating that nothing should be read from stdin. This can be set
124 * on the command line.
126 int stdin_null_flag = 0;
129 * Flag indicating that ssh should fork after authentication. This is useful
130 * so that the passphrase can be entered manually, and then ssh goes to the
133 int fork_after_authentication_flag = 0;
136 * General data structure for command line options and options configurable
137 * in configuration files. See readconf.h.
141 /* optional user configfile */
145 * Name of the host we are connecting to. This is the name given on the
146 * command line, or the HostName specified for the user-supplied name in a
147 * configuration file.
151 /* socket address the host resolves to */
152 struct sockaddr_storage hostaddr;
154 /* Private host keys. */
155 Sensitive sensitive_data;
157 /* Original real UID. */
158 uid_t original_real_uid;
159 uid_t original_effective_uid;
161 /* command to be executed */
164 /* Should we execute a command or invoke a subsystem? */
165 int subsystem_flag = 0;
167 /* # of replies received for global requests */
168 static int client_global_request_id = 0;
170 /* pid of proxycommand child process */
171 pid_t proxy_command_pid = 0;
173 /* fd to control socket */
176 /* Multiplexing control command */
177 static u_int mux_command = 0;
179 /* Only used in control client mode */
180 volatile sig_atomic_t control_client_terminate = 0;
181 u_int control_server_pid = 0;
183 /* Prints a help message to the user. This function never returns. */
189 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
190 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
191 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
192 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
193 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
194 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
199 static int ssh_session(void);
200 static int ssh_session2(void);
201 static void load_public_identity_files(void);
202 static void control_client(const char *path);
205 * Main program for the ssh client.
208 main(int ac, char **av)
210 int i, opt, exit_status;
211 char *p, *cp, *line, buf[256];
214 int dummy, timeout_ms;
215 extern int optind, optreset;
220 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
223 __progname = ssh_get_progname(av[0]);
227 * Save the original real uid. It will be needed later (uid-swapping
228 * may clobber the real uid).
230 original_real_uid = getuid();
231 original_effective_uid = geteuid();
234 * Use uid-swapping to give up root privileges for the duration of
235 * option processing. We will re-instantiate the rights when we are
236 * ready to create the privileged port, and will permanently drop
237 * them when the port has been created (actually, when the connection
238 * has been made, as we may need to create the port several times).
242 #ifdef HAVE_SETRLIMIT
243 /* If we are installed setuid root be careful to not drop core. */
244 if (original_real_uid != original_effective_uid) {
246 rlim.rlim_cur = rlim.rlim_max = 0;
247 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
248 fatal("setrlimit failed: %.100s", strerror(errno));
252 pw = getpwuid(original_real_uid);
254 logit("You don't exist, go away!");
257 /* Take a copy of the returned structure. */
261 * Set our umask to something reasonable, as some files are created
262 * with the default umask. This will make them world-readable but
263 * writable only by the owner, which is ok for all files for which we
264 * don't set the modes explicitly.
268 /* Initialize option structure to indicate that no values have been set. */
269 initialize_options(&options);
271 /* Parse command-line arguments. */
275 while ((opt = getopt(ac, av,
276 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:KL:MNO:PR:S:TVw:XY")) != -1) {
279 options.protocol = SSH_PROTO_1;
282 options.protocol = SSH_PROTO_2;
285 options.address_family = AF_INET;
288 options.address_family = AF_INET6;
294 fork_after_authentication_flag = 1;
298 options.forward_x11 = 0;
301 options.forward_x11 = 1;
304 options.forward_x11 = 1;
305 options.forward_x11_trusted = 1;
308 options.gateway_ports = 1;
311 if (strcmp(optarg, "check") == 0)
312 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
313 else if (strcmp(optarg, "exit") == 0)
314 mux_command = SSHMUX_COMMAND_TERMINATE;
316 fatal("Invalid multiplex command.");
318 case 'P': /* deprecated */
319 options.use_privileged_port = 0;
322 options.forward_agent = 0;
325 options.forward_agent = 1;
328 options.gss_deleg_creds = 0;
331 options.gss_authentication = 1;
332 options.gss_deleg_creds = 1;
335 if (stat(optarg, &st) < 0) {
336 fprintf(stderr, "Warning: Identity file %s "
337 "not accessible: %s.\n", optarg,
341 if (options.num_identity_files >=
342 SSH_MAX_IDENTITY_FILES)
343 fatal("Too many identity files specified "
344 "(max %d)", SSH_MAX_IDENTITY_FILES);
345 options.identity_files[options.num_identity_files++] =
350 options.smartcard_device = xstrdup(optarg);
352 fprintf(stderr, "no support for smartcards.\n");
361 if (debug_flag == 0) {
363 options.log_level = SYSLOG_LEVEL_DEBUG1;
365 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
371 fprintf(stderr, "%s, %s\n",
372 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
377 if (options.tun_open == -1)
378 options.tun_open = SSH_TUNMODE_DEFAULT;
379 options.tun_local = a2tun(optarg, &options.tun_remote);
380 if (options.tun_local == SSH_TUNID_ERR) {
381 fprintf(stderr, "Bad tun device '%s'\n", optarg);
386 options.log_level = SYSLOG_LEVEL_QUIET;
389 if (optarg[0] == '^' && optarg[2] == 0 &&
390 (u_char) optarg[1] >= 64 &&
391 (u_char) optarg[1] < 128)
392 options.escape_char = (u_char) optarg[1] & 31;
393 else if (strlen(optarg) == 1)
394 options.escape_char = (u_char) optarg[0];
395 else if (strcmp(optarg, "none") == 0)
396 options.escape_char = SSH_ESCAPECHAR_NONE;
398 fprintf(stderr, "Bad escape character '%s'.\n",
404 if (ciphers_valid(optarg)) {
406 options.ciphers = xstrdup(optarg);
407 options.cipher = SSH_CIPHER_INVALID;
410 options.cipher = cipher_number(optarg);
411 if (options.cipher == -1) {
413 "Unknown cipher type '%s'\n",
417 if (options.cipher == SSH_CIPHER_3DES)
418 options.ciphers = "3des-cbc";
419 else if (options.cipher == SSH_CIPHER_BLOWFISH)
420 options.ciphers = "blowfish-cbc";
422 options.ciphers = (char *)-1;
426 if (mac_valid(optarg))
427 options.macs = xstrdup(optarg);
429 fprintf(stderr, "Unknown mac type '%s'\n",
435 if (options.control_master == SSHCTL_MASTER_YES)
436 options.control_master = SSHCTL_MASTER_ASK;
438 options.control_master = SSHCTL_MASTER_YES;
441 options.port = a2port(optarg);
442 if (options.port == 0) {
443 fprintf(stderr, "Bad port '%s'\n", optarg);
448 options.user = optarg;
452 if (parse_forward(&fwd, optarg))
453 add_local_forward(&options, &fwd);
456 "Bad local forwarding specification '%s'\n",
463 if (parse_forward(&fwd, optarg)) {
464 add_remote_forward(&options, &fwd);
467 "Bad remote forwarding specification "
474 cp = p = xstrdup(optarg);
475 memset(&fwd, '\0', sizeof(fwd));
476 fwd.connect_host = "socks";
477 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
478 fprintf(stderr, "Bad dynamic forwarding "
479 "specification '%.100s'\n", optarg);
483 fwd.listen_port = a2port(cp);
484 fwd.listen_host = cleanhostname(fwd.listen_host);
486 fwd.listen_port = a2port(fwd.listen_host);
487 fwd.listen_host = NULL;
490 if (fwd.listen_port == 0) {
491 fprintf(stderr, "Bad dynamic port '%s'\n",
495 add_local_forward(&options, &fwd);
500 options.compression = 1;
511 line = xstrdup(optarg);
512 if (process_config_line(&options, host ? host : "",
513 line, "command-line", 0, &dummy) != 0)
521 if (options.control_path != NULL)
522 free(options.control_path);
523 options.control_path = xstrdup(optarg);
526 options.bind_address = optarg;
539 if (ac > 0 && !host && **av != '-') {
540 if (strrchr(*av, '@')) {
542 cp = strrchr(p, '@');
543 if (cp == NULL || cp == p)
551 optind = optreset = 1;
557 /* Check that we got a host name. */
561 SSLeay_add_all_algorithms();
562 ERR_load_crypto_strings();
564 /* Initialize the command to execute on remote host. */
565 buffer_init(&command);
568 * Save the command to execute on the remote host in a buffer. There
569 * is no limit on the length of the command, except by the maximum
570 * packet size. Also sets the tty flag if there is no command.
573 /* No command specified - execute shell on a tty. */
575 if (subsystem_flag) {
577 "You must specify a subsystem to invoke.\n");
581 /* A command has been specified. Store it into the buffer. */
582 for (i = 0; i < ac; i++) {
584 buffer_append(&command, " ", 1);
585 buffer_append(&command, av[i], strlen(av[i]));
589 /* Cannot fork to background if no command. */
590 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
591 fatal("Cannot fork into background without a command to execute.");
593 /* Allocate a tty by default if no command specified. */
594 if (buffer_len(&command) == 0)
600 /* Do not allocate a tty if stdin is not a tty. */
601 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
603 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
608 * Initialize "log" output. Since we are the client all output
609 * actually goes to stderr.
611 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
612 SYSLOG_FACILITY_USER, 1);
615 * Read per-user configuration file. Ignore the system wide config
616 * file if the user specifies a config file on the command line.
618 if (config != NULL) {
619 if (!read_config_file(config, host, &options, 0))
620 fatal("Can't open user config file %.100s: "
621 "%.100s", config, strerror(errno));
623 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
624 _PATH_SSH_USER_CONFFILE);
625 (void)read_config_file(buf, host, &options, 1);
627 /* Read systemwide configuration file after use config. */
628 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
632 /* Fill configuration defaults. */
633 fill_default_options(&options);
635 channel_set_af(options.address_family);
638 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
642 if (options.user == NULL)
643 options.user = xstrdup(pw->pw_name);
645 if (options.hostname != NULL)
646 host = options.hostname;
648 /* force lowercase for hostkey matching */
649 if (options.host_key_alias != NULL) {
650 for (p = options.host_key_alias; *p; p++)
652 *p = (char)tolower(*p);
655 /* Get default port if port has not been set. */
656 if (options.port == 0) {
657 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
658 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
661 if (options.proxy_command != NULL &&
662 strcmp(options.proxy_command, "none") == 0) {
663 xfree(options.proxy_command);
664 options.proxy_command = NULL;
666 if (options.control_path != NULL &&
667 strcmp(options.control_path, "none") == 0) {
668 xfree(options.control_path);
669 options.control_path = NULL;
672 if (options.control_path != NULL) {
673 char thishost[NI_MAXHOST];
675 if (gethostname(thishost, sizeof(thishost)) == -1)
676 fatal("gethostname: %s", strerror(errno));
677 snprintf(buf, sizeof(buf), "%d", options.port);
678 cp = tilde_expand_filename(options.control_path,
680 xfree(options.control_path);
681 options.control_path = percent_expand(cp, "p", buf, "h", host,
682 "r", options.user, "l", thishost, (char *)NULL);
685 if (mux_command != 0 && options.control_path == NULL)
686 fatal("No ControlPath specified for \"-O\" command");
687 if (options.control_path != NULL)
688 control_client(options.control_path);
690 timeout_ms = options.connection_timeout * 1000;
692 /* Open a connection to the remote host. */
693 if (ssh_connect(host, &hostaddr, options.port,
694 options.address_family, options.connection_attempts, &timeout_ms,
695 options.tcp_keep_alive,
697 options.use_privileged_port,
699 original_effective_uid == 0 && options.use_privileged_port,
701 options.proxy_command) != 0)
705 debug3("timeout: %d ms remain after connect", timeout_ms);
708 * If we successfully made the connection, load the host private key
709 * in case we will need it later for combined rsa-rhosts
710 * authentication. This must be done before releasing extra
711 * privileges, because the file is only readable by root.
712 * If we cannot access the private keys, load the public keys
713 * instead and try to execute the ssh-keysign helper instead.
715 sensitive_data.nkeys = 0;
716 sensitive_data.keys = NULL;
717 sensitive_data.external_keysign = 0;
718 if (options.rhosts_rsa_authentication ||
719 options.hostbased_authentication) {
720 sensitive_data.nkeys = 3;
721 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
725 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
726 _PATH_HOST_KEY_FILE, "", NULL, NULL);
727 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
728 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
729 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
730 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
733 if (options.hostbased_authentication == 1 &&
734 sensitive_data.keys[0] == NULL &&
735 sensitive_data.keys[1] == NULL &&
736 sensitive_data.keys[2] == NULL) {
737 sensitive_data.keys[1] = key_load_public(
738 _PATH_HOST_DSA_KEY_FILE, NULL);
739 sensitive_data.keys[2] = key_load_public(
740 _PATH_HOST_RSA_KEY_FILE, NULL);
741 sensitive_data.external_keysign = 1;
745 * Get rid of any extra privileges that we may have. We will no
746 * longer need them. Also, extra privileges could make it very hard
747 * to read identity files and other non-world-readable files from the
748 * user's home directory if it happens to be on a NFS volume where
749 * root is mapped to nobody.
751 if (original_effective_uid == 0) {
753 permanently_set_uid(pw);
757 * Now that we are back to our own permissions, create ~/.ssh
758 * directory if it doesn't already exist.
760 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
761 if (stat(buf, &st) < 0)
762 if (mkdir(buf, 0700) < 0)
763 error("Could not create directory '%.200s'.", buf);
765 /* load options.identity_files */
766 load_public_identity_files();
768 /* Expand ~ in known host file names. */
770 options.system_hostfile =
771 tilde_expand_filename(options.system_hostfile, original_real_uid);
772 options.user_hostfile =
773 tilde_expand_filename(options.user_hostfile, original_real_uid);
774 options.system_hostfile2 =
775 tilde_expand_filename(options.system_hostfile2, original_real_uid);
776 options.user_hostfile2 =
777 tilde_expand_filename(options.user_hostfile2, original_real_uid);
779 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
781 /* Log into the remote system. This never returns if the login fails. */
782 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
785 /* We no longer need the private host keys. Clear them now. */
786 if (sensitive_data.nkeys != 0) {
787 for (i = 0; i < sensitive_data.nkeys; i++) {
788 if (sensitive_data.keys[i] != NULL) {
789 /* Destroys contents safely */
790 debug3("clear hostkey %d", i);
791 key_free(sensitive_data.keys[i]);
792 sensitive_data.keys[i] = NULL;
795 xfree(sensitive_data.keys);
797 for (i = 0; i < options.num_identity_files; i++) {
798 if (options.identity_files[i]) {
799 xfree(options.identity_files[i]);
800 options.identity_files[i] = NULL;
802 if (options.identity_keys[i]) {
803 key_free(options.identity_keys[i]);
804 options.identity_keys[i] = NULL;
808 exit_status = compat20 ? ssh_session2() : ssh_session();
811 if (options.control_path != NULL && control_fd != -1)
812 unlink(options.control_path);
815 * Send SIGHUP to proxy command if used. We don't wait() in
816 * case it hangs and instead rely on init to reap the child
818 if (proxy_command_pid > 1)
819 kill(proxy_command_pid, SIGHUP);
825 ssh_init_forwarding(void)
830 /* Initiate local TCP/IP port forwardings. */
831 for (i = 0; i < options.num_local_forwards; i++) {
832 debug("Local connections to %.200s:%d forwarded to remote "
834 (options.local_forwards[i].listen_host == NULL) ?
835 (options.gateway_ports ? "*" : "LOCALHOST") :
836 options.local_forwards[i].listen_host,
837 options.local_forwards[i].listen_port,
838 options.local_forwards[i].connect_host,
839 options.local_forwards[i].connect_port);
840 success += channel_setup_local_fwd_listener(
841 options.local_forwards[i].listen_host,
842 options.local_forwards[i].listen_port,
843 options.local_forwards[i].connect_host,
844 options.local_forwards[i].connect_port,
845 options.gateway_ports);
847 if (i > 0 && success != i && options.exit_on_forward_failure)
848 fatal("Could not request local forwarding.");
849 if (i > 0 && success == 0)
850 error("Could not request local forwarding.");
852 /* Initiate remote TCP/IP port forwardings. */
853 for (i = 0; i < options.num_remote_forwards; i++) {
854 debug("Remote connections from %.200s:%d forwarded to "
855 "local address %.200s:%d",
856 (options.remote_forwards[i].listen_host == NULL) ?
857 "LOCALHOST" : options.remote_forwards[i].listen_host,
858 options.remote_forwards[i].listen_port,
859 options.remote_forwards[i].connect_host,
860 options.remote_forwards[i].connect_port);
861 if (channel_request_remote_forwarding(
862 options.remote_forwards[i].listen_host,
863 options.remote_forwards[i].listen_port,
864 options.remote_forwards[i].connect_host,
865 options.remote_forwards[i].connect_port) < 0) {
866 if (options.exit_on_forward_failure)
867 fatal("Could not request remote forwarding.");
869 logit("Warning: Could not request remote "
874 /* Initiate tunnel forwarding. */
875 if (options.tun_open != SSH_TUNMODE_NO) {
876 if (client_request_tun_fwd(options.tun_open,
877 options.tun_local, options.tun_remote) == -1) {
878 if (options.exit_on_forward_failure)
879 fatal("Could not request tunnel forwarding.");
881 error("Could not request tunnel forwarding.");
887 check_agent_present(void)
889 if (options.forward_agent) {
890 /* Clear agent forwarding if we don't have an agent. */
891 if (!ssh_agent_present())
892 options.forward_agent = 0;
906 /* Enable compression if requested. */
907 if (options.compression) {
908 debug("Requesting compression at level %d.", options.compression_level);
910 if (options.compression_level < 1 || options.compression_level > 9)
911 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
913 /* Send the request. */
914 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
915 packet_put_int(options.compression_level);
918 type = packet_read();
919 if (type == SSH_SMSG_SUCCESS)
920 packet_start_compression(options.compression_level);
921 else if (type == SSH_SMSG_FAILURE)
922 logit("Warning: Remote host refused compression.");
924 packet_disconnect("Protocol error waiting for compression response.");
926 /* Allocate a pseudo tty if appropriate. */
928 debug("Requesting pty.");
930 /* Start the packet. */
931 packet_start(SSH_CMSG_REQUEST_PTY);
933 /* Store TERM in the packet. There is no limit on the
934 length of the string. */
938 packet_put_cstring(cp);
940 /* Store window size in the packet. */
941 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
942 memset(&ws, 0, sizeof(ws));
943 packet_put_int((u_int)ws.ws_row);
944 packet_put_int((u_int)ws.ws_col);
945 packet_put_int((u_int)ws.ws_xpixel);
946 packet_put_int((u_int)ws.ws_ypixel);
948 /* Store tty modes in the packet. */
949 tty_make_modes(fileno(stdin), NULL);
951 /* Send the packet, and wait for it to leave. */
955 /* Read response from the server. */
956 type = packet_read();
957 if (type == SSH_SMSG_SUCCESS) {
960 } else if (type == SSH_SMSG_FAILURE)
961 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
963 packet_disconnect("Protocol error waiting for pty request response.");
965 /* Request X11 forwarding if enabled and DISPLAY is set. */
966 display = getenv("DISPLAY");
967 if (options.forward_x11 && display != NULL) {
969 /* Get reasonable local authentication information. */
970 client_x11_get_proto(display, options.xauth_location,
971 options.forward_x11_trusted, &proto, &data);
972 /* Request forwarding with authentication spoofing. */
973 debug("Requesting X11 forwarding with authentication spoofing.");
974 x11_request_forwarding_with_spoofing(0, display, proto, data);
976 /* Read response from the server. */
977 type = packet_read();
978 if (type == SSH_SMSG_SUCCESS) {
980 } else if (type == SSH_SMSG_FAILURE) {
981 logit("Warning: Remote host denied X11 forwarding.");
983 packet_disconnect("Protocol error waiting for X11 forwarding");
986 /* Tell the packet module whether this is an interactive session. */
987 packet_set_interactive(interactive);
989 /* Request authentication agent forwarding if appropriate. */
990 check_agent_present();
992 if (options.forward_agent) {
993 debug("Requesting authentication agent forwarding.");
994 auth_request_forwarding();
996 /* Read response from the server. */
997 type = packet_read();
999 if (type != SSH_SMSG_SUCCESS)
1000 logit("Warning: Remote host denied authentication agent forwarding.");
1003 /* Initiate port forwardings. */
1004 ssh_init_forwarding();
1006 /* Execute a local command */
1007 if (options.local_command != NULL &&
1008 options.permit_local_command)
1009 ssh_local_cmd(options.local_command);
1011 /* If requested, let ssh continue in the background. */
1012 if (fork_after_authentication_flag)
1013 if (daemon(1, 1) < 0)
1014 fatal("daemon() failed: %.200s", strerror(errno));
1017 * If a command was specified on the command line, execute the
1018 * command now. Otherwise request the server to start a shell.
1020 if (buffer_len(&command) > 0) {
1021 int len = buffer_len(&command);
1024 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1025 packet_start(SSH_CMSG_EXEC_CMD);
1026 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1028 packet_write_wait();
1030 debug("Requesting shell.");
1031 packet_start(SSH_CMSG_EXEC_SHELL);
1033 packet_write_wait();
1036 /* Enter the interactive session. */
1037 return client_loop(have_tty, tty_flag ?
1038 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1042 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1046 id = packet_get_int();
1047 len = buffer_len(&command);
1051 if (type == SSH2_MSG_CHANNEL_FAILURE)
1052 fatal("Request for subsystem '%.*s' failed on channel %d",
1053 len, (u_char *)buffer_ptr(&command), id);
1057 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1061 i = client_global_request_id++;
1062 if (i >= options.num_remote_forwards)
1064 debug("remote forward %s for: listen %d, connect %s:%d",
1065 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1066 options.remote_forwards[i].listen_port,
1067 options.remote_forwards[i].connect_host,
1068 options.remote_forwards[i].connect_port);
1069 if (type == SSH2_MSG_REQUEST_FAILURE) {
1070 if (options.exit_on_forward_failure)
1071 fatal("Error: remote port forwarding failed for "
1073 options.remote_forwards[i].listen_port);
1075 logit("Warning: remote port forwarding failed for "
1077 options.remote_forwards[i].listen_port);
1082 ssh_control_listener(void)
1084 struct sockaddr_un addr;
1088 if (options.control_path == NULL ||
1089 options.control_master == SSHCTL_MASTER_NO)
1092 debug("setting up multiplex master socket");
1094 memset(&addr, '\0', sizeof(addr));
1095 addr.sun_family = AF_UNIX;
1096 addr_len = offsetof(struct sockaddr_un, sun_path) +
1097 strlen(options.control_path) + 1;
1099 if (strlcpy(addr.sun_path, options.control_path,
1100 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1101 fatal("ControlPath too long");
1103 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1104 fatal("%s socket(): %s", __func__, strerror(errno));
1106 old_umask = umask(0177);
1107 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1109 if (errno == EINVAL || errno == EADDRINUSE)
1110 fatal("ControlSocket %s already exists",
1111 options.control_path);
1113 fatal("%s bind(): %s", __func__, strerror(errno));
1117 if (listen(control_fd, 64) == -1)
1118 fatal("%s listen(): %s", __func__, strerror(errno));
1120 set_nonblock(control_fd);
1123 /* request pty/x11/agent/tcpfwd/shell for channel */
1125 ssh_session2_setup(int id, void *arg)
1127 extern char **environ;
1128 const char *display;
1129 int interactive = tty_flag;
1131 display = getenv("DISPLAY");
1132 if (options.forward_x11 && display != NULL) {
1134 /* Get reasonable local authentication information. */
1135 client_x11_get_proto(display, options.xauth_location,
1136 options.forward_x11_trusted, &proto, &data);
1137 /* Request forwarding with authentication spoofing. */
1138 debug("Requesting X11 forwarding with authentication spoofing.");
1139 x11_request_forwarding_with_spoofing(id, display, proto, data);
1141 /* XXX wait for reply */
1144 check_agent_present();
1145 if (options.forward_agent) {
1146 debug("Requesting authentication agent forwarding.");
1147 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1151 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1152 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1154 packet_set_interactive(interactive);
1157 /* open new channel for a session */
1159 ssh_session2_open(void)
1162 int window, packetmax, in, out, err;
1164 if (stdin_null_flag) {
1165 in = open(_PATH_DEVNULL, O_RDONLY);
1167 in = dup(STDIN_FILENO);
1169 out = dup(STDOUT_FILENO);
1170 err = dup(STDERR_FILENO);
1172 if (in < 0 || out < 0 || err < 0)
1173 fatal("dup() in/out/err failed");
1175 /* enable nonblocking unless tty */
1183 window = CHAN_SES_WINDOW_DEFAULT;
1184 packetmax = CHAN_SES_PACKET_DEFAULT;
1190 "session", SSH_CHANNEL_OPENING, in, out, err,
1191 window, packetmax, CHAN_EXTENDED_WRITE,
1192 "client-session", /*nonblock*/0);
1194 debug3("ssh_session2_open: channel_new: %d", c->self);
1196 channel_send_open(c->self);
1198 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1208 /* XXX should be pre-session */
1209 ssh_init_forwarding();
1211 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1212 id = ssh_session2_open();
1214 /* Execute a local command */
1215 if (options.local_command != NULL &&
1216 options.permit_local_command)
1217 ssh_local_cmd(options.local_command);
1219 /* Start listening for multiplex clients */
1220 ssh_control_listener();
1222 /* If requested, let ssh continue in the background. */
1223 if (fork_after_authentication_flag)
1224 if (daemon(1, 1) < 0)
1225 fatal("daemon() failed: %.200s", strerror(errno));
1227 return client_loop(tty_flag, tty_flag ?
1228 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1232 load_public_identity_files(void)
1234 char *filename, *cp, thishost[NI_MAXHOST];
1235 char *pwdir = NULL, *pwname = NULL;
1242 if (options.smartcard_device != NULL &&
1243 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1244 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1246 for (i = 0; keys[i] != NULL; i++) {
1248 memmove(&options.identity_files[1], &options.identity_files[0],
1249 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1250 memmove(&options.identity_keys[1], &options.identity_keys[0],
1251 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1252 options.num_identity_files++;
1253 options.identity_keys[0] = keys[i];
1254 options.identity_files[0] = sc_get_key_label(keys[i]);
1256 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1257 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1261 #endif /* SMARTCARD */
1262 if ((pw = getpwuid(original_real_uid)) == NULL)
1263 fatal("load_public_identity_files: getpwuid failed");
1264 pwname = xstrdup(pw->pw_name);
1265 pwdir = xstrdup(pw->pw_dir);
1266 if (gethostname(thishost, sizeof(thishost)) == -1)
1267 fatal("load_public_identity_files: gethostname: %s",
1269 for (; i < options.num_identity_files; i++) {
1270 cp = tilde_expand_filename(options.identity_files[i],
1272 filename = percent_expand(cp, "d", pwdir,
1273 "u", pwname, "l", thishost, "h", host,
1274 "r", options.user, (char *)NULL);
1276 public = key_load_public(filename, NULL);
1277 debug("identity file %s type %d", filename,
1278 public ? public->type : -1);
1279 xfree(options.identity_files[i]);
1280 options.identity_files[i] = filename;
1281 options.identity_keys[i] = public;
1283 bzero(pwname, strlen(pwname));
1285 bzero(pwdir, strlen(pwdir));
1290 control_client_sighandler(int signo)
1292 control_client_terminate = signo;
1296 control_client_sigrelay(int signo)
1298 int save_errno = errno;
1300 if (control_server_pid > 1)
1301 kill(control_server_pid, signo);
1307 env_permitted(char *env)
1310 char name[1024], *cp;
1312 if ((cp = strchr(env, '=')) == NULL || cp == env)
1314 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1315 if (ret <= 0 || (size_t)ret >= sizeof(name))
1316 fatal("env_permitted: name '%.100s...' too long", env);
1318 for (i = 0; i < options.num_send_env; i++)
1319 if (match_pattern(name, options.send_env[i]))
1326 control_client(const char *path)
1328 struct sockaddr_un addr;
1329 int i, r, fd, sock, exitval[2], num_env, addr_len;
1332 extern char **environ;
1335 if (mux_command == 0)
1336 mux_command = SSHMUX_COMMAND_OPEN;
1338 switch (options.control_master) {
1339 case SSHCTL_MASTER_AUTO:
1340 case SSHCTL_MASTER_AUTO_ASK:
1341 debug("auto-mux: Trying existing master");
1343 case SSHCTL_MASTER_NO:
1349 memset(&addr, '\0', sizeof(addr));
1350 addr.sun_family = AF_UNIX;
1351 addr_len = offsetof(struct sockaddr_un, sun_path) +
1354 if (strlcpy(addr.sun_path, path,
1355 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1356 fatal("ControlPath too long");
1358 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1359 fatal("%s socket(): %s", __func__, strerror(errno));
1361 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1362 if (mux_command != SSHMUX_COMMAND_OPEN) {
1363 fatal("Control socket connect(%.100s): %s", path,
1366 if (errno == ENOENT)
1367 debug("Control socket \"%.100s\" does not exist", path);
1369 error("Control socket connect(%.100s): %s", path,
1376 if (stdin_null_flag) {
1377 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1378 fatal("open(/dev/null): %s", strerror(errno));
1379 if (dup2(fd, STDIN_FILENO) == -1)
1380 fatal("dup2: %s", strerror(errno));
1381 if (fd > STDERR_FILENO)
1385 term = getenv("TERM");
1389 flags |= SSHMUX_FLAG_TTY;
1391 flags |= SSHMUX_FLAG_SUBSYS;
1392 if (options.forward_x11)
1393 flags |= SSHMUX_FLAG_X11_FWD;
1394 if (options.forward_agent)
1395 flags |= SSHMUX_FLAG_AGENT_FWD;
1397 signal(SIGPIPE, SIG_IGN);
1401 /* Send our command to server */
1402 buffer_put_int(&m, mux_command);
1403 buffer_put_int(&m, flags);
1404 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1405 fatal("%s: msg_send", __func__);
1408 /* Get authorisation status and PID of controlee */
1409 if (ssh_msg_recv(sock, &m) == -1)
1410 fatal("%s: msg_recv", __func__);
1411 if (buffer_get_char(&m) != SSHMUX_VER)
1412 fatal("%s: wrong version", __func__);
1413 if (buffer_get_int(&m) != 1)
1414 fatal("Connection to master denied");
1415 control_server_pid = buffer_get_int(&m);
1419 switch (mux_command) {
1420 case SSHMUX_COMMAND_ALIVE_CHECK:
1421 fprintf(stderr, "Master running (pid=%d)\r\n",
1422 control_server_pid);
1424 case SSHMUX_COMMAND_TERMINATE:
1425 fprintf(stderr, "Exit request sent.\r\n");
1427 case SSHMUX_COMMAND_OPEN:
1428 /* continue below */
1431 fatal("silly mux_command %d", mux_command);
1434 /* SSHMUX_COMMAND_OPEN */
1435 buffer_put_cstring(&m, term ? term : "");
1436 buffer_append(&command, "\0", 1);
1437 buffer_put_cstring(&m, buffer_ptr(&command));
1439 if (options.num_send_env == 0 || environ == NULL) {
1440 buffer_put_int(&m, 0);
1442 /* Pass environment */
1444 for (i = 0; environ[i] != NULL; i++)
1445 if (env_permitted(environ[i]))
1446 num_env++; /* Count */
1448 buffer_put_int(&m, num_env);
1450 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1451 if (env_permitted(environ[i])) {
1453 buffer_put_cstring(&m, environ[i]);
1457 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1458 fatal("%s: msg_send", __func__);
1460 if (mm_send_fd(sock, STDIN_FILENO) == -1 ||
1461 mm_send_fd(sock, STDOUT_FILENO) == -1 ||
1462 mm_send_fd(sock, STDERR_FILENO) == -1)
1463 fatal("%s: send fds failed", __func__);
1465 /* Wait for reply, so master has a chance to gather ttymodes */
1467 if (ssh_msg_recv(sock, &m) == -1)
1468 fatal("%s: msg_recv", __func__);
1469 if (buffer_get_char(&m) != SSHMUX_VER)
1470 fatal("%s: wrong version", __func__);
1473 signal(SIGHUP, control_client_sighandler);
1474 signal(SIGINT, control_client_sighandler);
1475 signal(SIGTERM, control_client_sighandler);
1476 signal(SIGWINCH, control_client_sigrelay);
1482 * Stick around until the controlee closes the client_fd.
1483 * Before it does, it is expected to write this process' exit
1484 * value (one int). This process must read the value and wait for
1485 * the closure of the client_fd; if this one closes early, the
1486 * multiplex master will terminate early too (possibly losing data).
1489 for (i = 0; !control_client_terminate && i < (int)sizeof(exitval);) {
1490 r = read(sock, (char *)exitval + i, sizeof(exitval) - i);
1492 debug2("Received EOF from master");
1498 fatal("%s: read %s", __func__, strerror(errno));
1505 if (i > (int)sizeof(int))
1506 fatal("%s: master returned too much data (%d > %lu)",
1507 __func__, i, sizeof(int));
1508 if (control_client_terminate) {
1509 debug2("Exiting on signal %d", control_client_terminate);
1511 } else if (i < (int)sizeof(int)) {
1512 debug2("Control master terminated unexpectedly");
1515 debug2("Received exit status from master %d", exitval[0]);
1517 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1518 fprintf(stderr, "Shared connection to %s closed.\r\n", host);