1 /* $OpenBSD: ssh.c,v 1.286 2006/07/12 22:28:52 stevesk Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
57 #if defined(HAVE_NETDB_H)
66 #include <openssl/evp.h>
67 #include <openssl/err.h>
82 #include "pathnames.h"
84 #include "clientloop.h"
87 #include "sshconnect.h"
94 #include "monitor_fdpass.h"
102 extern char *__progname;
104 /* Flag indicating whether debug mode is on. This can be set on the command line. */
107 /* Flag indicating whether a tty should be allocated */
110 int force_tty_flag = 0;
112 /* don't exec a shell */
113 int no_shell_flag = 0;
116 * Flag indicating that nothing should be read from stdin. This can be set
117 * on the command line.
119 int stdin_null_flag = 0;
122 * Flag indicating that ssh should fork after authentication. This is useful
123 * so that the passphrase can be entered manually, and then ssh goes to the
126 int fork_after_authentication_flag = 0;
129 * General data structure for command line options and options configurable
130 * in configuration files. See readconf.h.
134 /* optional user configfile */
138 * Name of the host we are connecting to. This is the name given on the
139 * command line, or the HostName specified for the user-supplied name in a
140 * configuration file.
144 /* socket address the host resolves to */
145 struct sockaddr_storage hostaddr;
147 /* Private host keys. */
148 Sensitive sensitive_data;
150 /* Original real UID. */
151 uid_t original_real_uid;
152 uid_t original_effective_uid;
154 /* command to be executed */
157 /* Should we execute a command or invoke a subsystem? */
158 int subsystem_flag = 0;
160 /* # of replies received for global requests */
161 static int client_global_request_id = 0;
163 /* pid of proxycommand child process */
164 pid_t proxy_command_pid = 0;
166 /* fd to control socket */
169 /* Multiplexing control command */
170 static u_int mux_command = 0;
172 /* Only used in control client mode */
173 volatile sig_atomic_t control_client_terminate = 0;
174 u_int control_server_pid = 0;
176 /* Prints a help message to the user. This function never returns. */
182 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
183 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
184 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
185 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
186 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
187 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
192 static int ssh_session(void);
193 static int ssh_session2(void);
194 static void load_public_identity_files(void);
195 static void control_client(const char *path);
198 * Main program for the ssh client.
201 main(int ac, char **av)
203 int i, opt, exit_status;
204 char *p, *cp, *line, buf[256];
208 extern int optind, optreset;
213 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
216 __progname = ssh_get_progname(av[0]);
220 * Save the original real uid. It will be needed later (uid-swapping
221 * may clobber the real uid).
223 original_real_uid = getuid();
224 original_effective_uid = geteuid();
227 * Use uid-swapping to give up root privileges for the duration of
228 * option processing. We will re-instantiate the rights when we are
229 * ready to create the privileged port, and will permanently drop
230 * them when the port has been created (actually, when the connection
231 * has been made, as we may need to create the port several times).
235 #ifdef HAVE_SETRLIMIT
236 /* If we are installed setuid root be careful to not drop core. */
237 if (original_real_uid != original_effective_uid) {
239 rlim.rlim_cur = rlim.rlim_max = 0;
240 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
241 fatal("setrlimit failed: %.100s", strerror(errno));
245 pw = getpwuid(original_real_uid);
247 logit("You don't exist, go away!");
250 /* Take a copy of the returned structure. */
254 * Set our umask to something reasonable, as some files are created
255 * with the default umask. This will make them world-readable but
256 * writable only by the owner, which is ok for all files for which we
257 * don't set the modes explicitly.
261 /* Initialize option structure to indicate that no values have been set. */
262 initialize_options(&options);
264 /* Parse command-line arguments. */
268 while ((opt = getopt(ac, av,
269 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
272 options.protocol = SSH_PROTO_1;
275 options.protocol = SSH_PROTO_2;
278 options.address_family = AF_INET;
281 options.address_family = AF_INET6;
287 fork_after_authentication_flag = 1;
291 options.forward_x11 = 0;
294 options.forward_x11 = 1;
297 options.forward_x11 = 1;
298 options.forward_x11_trusted = 1;
301 options.gateway_ports = 1;
304 if (strcmp(optarg, "check") == 0)
305 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
306 else if (strcmp(optarg, "exit") == 0)
307 mux_command = SSHMUX_COMMAND_TERMINATE;
309 fatal("Invalid multiplex command.");
311 case 'P': /* deprecated */
312 options.use_privileged_port = 0;
315 options.forward_agent = 0;
318 options.forward_agent = 1;
321 options.gss_deleg_creds = 0;
324 if (stat(optarg, &st) < 0) {
325 fprintf(stderr, "Warning: Identity file %s "
326 "not accessible: %s.\n", optarg,
330 if (options.num_identity_files >=
331 SSH_MAX_IDENTITY_FILES)
332 fatal("Too many identity files specified "
333 "(max %d)", SSH_MAX_IDENTITY_FILES);
334 options.identity_files[options.num_identity_files++] =
339 options.smartcard_device = xstrdup(optarg);
341 fprintf(stderr, "no support for smartcards.\n");
350 if (debug_flag == 0) {
352 options.log_level = SYSLOG_LEVEL_DEBUG1;
354 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
360 fprintf(stderr, "%s, %s\n",
361 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
366 if (options.tun_open == -1)
367 options.tun_open = SSH_TUNMODE_DEFAULT;
368 options.tun_local = a2tun(optarg, &options.tun_remote);
369 if (options.tun_local == SSH_TUNID_ERR) {
370 fprintf(stderr, "Bad tun device '%s'\n", optarg);
375 options.log_level = SYSLOG_LEVEL_QUIET;
378 if (optarg[0] == '^' && optarg[2] == 0 &&
379 (u_char) optarg[1] >= 64 &&
380 (u_char) optarg[1] < 128)
381 options.escape_char = (u_char) optarg[1] & 31;
382 else if (strlen(optarg) == 1)
383 options.escape_char = (u_char) optarg[0];
384 else if (strcmp(optarg, "none") == 0)
385 options.escape_char = SSH_ESCAPECHAR_NONE;
387 fprintf(stderr, "Bad escape character '%s'.\n",
393 if (ciphers_valid(optarg)) {
395 options.ciphers = xstrdup(optarg);
396 options.cipher = SSH_CIPHER_INVALID;
399 options.cipher = cipher_number(optarg);
400 if (options.cipher == -1) {
402 "Unknown cipher type '%s'\n",
406 if (options.cipher == SSH_CIPHER_3DES)
407 options.ciphers = "3des-cbc";
408 else if (options.cipher == SSH_CIPHER_BLOWFISH)
409 options.ciphers = "blowfish-cbc";
411 options.ciphers = (char *)-1;
415 if (mac_valid(optarg))
416 options.macs = xstrdup(optarg);
418 fprintf(stderr, "Unknown mac type '%s'\n",
424 if (options.control_master == SSHCTL_MASTER_YES)
425 options.control_master = SSHCTL_MASTER_ASK;
427 options.control_master = SSHCTL_MASTER_YES;
430 options.port = a2port(optarg);
431 if (options.port == 0) {
432 fprintf(stderr, "Bad port '%s'\n", optarg);
437 options.user = optarg;
441 if (parse_forward(&fwd, optarg))
442 add_local_forward(&options, &fwd);
445 "Bad local forwarding specification '%s'\n",
452 if (parse_forward(&fwd, optarg)) {
453 add_remote_forward(&options, &fwd);
456 "Bad remote forwarding specification "
463 cp = p = xstrdup(optarg);
464 memset(&fwd, '\0', sizeof(fwd));
465 fwd.connect_host = "socks";
466 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
467 fprintf(stderr, "Bad dynamic forwarding "
468 "specification '%.100s'\n", optarg);
472 fwd.listen_port = a2port(cp);
473 fwd.listen_host = cleanhostname(fwd.listen_host);
475 fwd.listen_port = a2port(fwd.listen_host);
476 fwd.listen_host = NULL;
479 if (fwd.listen_port == 0) {
480 fprintf(stderr, "Bad dynamic port '%s'\n",
484 add_local_forward(&options, &fwd);
489 options.compression = 1;
500 line = xstrdup(optarg);
501 if (process_config_line(&options, host ? host : "",
502 line, "command-line", 0, &dummy) != 0)
510 if (options.control_path != NULL)
511 free(options.control_path);
512 options.control_path = xstrdup(optarg);
515 options.bind_address = optarg;
528 if (ac > 0 && !host && **av != '-') {
529 if (strrchr(*av, '@')) {
531 cp = strrchr(p, '@');
532 if (cp == NULL || cp == p)
540 optind = optreset = 1;
546 /* Check that we got a host name. */
550 SSLeay_add_all_algorithms();
551 ERR_load_crypto_strings();
553 /* Initialize the command to execute on remote host. */
554 buffer_init(&command);
557 * Save the command to execute on the remote host in a buffer. There
558 * is no limit on the length of the command, except by the maximum
559 * packet size. Also sets the tty flag if there is no command.
562 /* No command specified - execute shell on a tty. */
564 if (subsystem_flag) {
566 "You must specify a subsystem to invoke.\n");
570 /* A command has been specified. Store it into the buffer. */
571 for (i = 0; i < ac; i++) {
573 buffer_append(&command, " ", 1);
574 buffer_append(&command, av[i], strlen(av[i]));
578 /* Cannot fork to background if no command. */
579 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
580 fatal("Cannot fork into background without a command to execute.");
582 /* Allocate a tty by default if no command specified. */
583 if (buffer_len(&command) == 0)
589 /* Do not allocate a tty if stdin is not a tty. */
590 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
592 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
597 * Initialize "log" output. Since we are the client all output
598 * actually goes to stderr.
600 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
601 SYSLOG_FACILITY_USER, 1);
604 * Read per-user configuration file. Ignore the system wide config
605 * file if the user specifies a config file on the command line.
607 if (config != NULL) {
608 if (!read_config_file(config, host, &options, 0))
609 fatal("Can't open user config file %.100s: "
610 "%.100s", config, strerror(errno));
612 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
613 _PATH_SSH_USER_CONFFILE);
614 (void)read_config_file(buf, host, &options, 1);
616 /* Read systemwide configuration file after use config. */
617 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
621 /* Fill configuration defaults. */
622 fill_default_options(&options);
624 channel_set_af(options.address_family);
627 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
631 if (options.user == NULL)
632 options.user = xstrdup(pw->pw_name);
634 if (options.hostname != NULL)
635 host = options.hostname;
637 /* force lowercase for hostkey matching */
638 if (options.host_key_alias != NULL) {
639 for (p = options.host_key_alias; *p; p++)
641 *p = (char)tolower(*p);
644 /* Get default port if port has not been set. */
645 if (options.port == 0) {
646 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
647 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
650 if (options.proxy_command != NULL &&
651 strcmp(options.proxy_command, "none") == 0)
652 options.proxy_command = NULL;
653 if (options.control_path != NULL &&
654 strcmp(options.control_path, "none") == 0)
655 options.control_path = NULL;
657 if (options.control_path != NULL) {
658 char thishost[NI_MAXHOST];
660 if (gethostname(thishost, sizeof(thishost)) == -1)
661 fatal("gethostname: %s", strerror(errno));
662 snprintf(buf, sizeof(buf), "%d", options.port);
663 cp = tilde_expand_filename(options.control_path,
665 options.control_path = percent_expand(cp, "p", buf, "h", host,
666 "r", options.user, "l", thishost, (char *)NULL);
669 if (mux_command != 0 && options.control_path == NULL)
670 fatal("No ControlPath specified for \"-O\" command");
671 if (options.control_path != NULL)
672 control_client(options.control_path);
674 /* Open a connection to the remote host. */
675 if (ssh_connect(host, &hostaddr, options.port,
676 options.address_family, options.connection_attempts,
678 options.use_privileged_port,
680 original_effective_uid == 0 && options.use_privileged_port,
682 options.proxy_command) != 0)
686 * If we successfully made the connection, load the host private key
687 * in case we will need it later for combined rsa-rhosts
688 * authentication. This must be done before releasing extra
689 * privileges, because the file is only readable by root.
690 * If we cannot access the private keys, load the public keys
691 * instead and try to execute the ssh-keysign helper instead.
693 sensitive_data.nkeys = 0;
694 sensitive_data.keys = NULL;
695 sensitive_data.external_keysign = 0;
696 if (options.rhosts_rsa_authentication ||
697 options.hostbased_authentication) {
698 sensitive_data.nkeys = 3;
699 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
703 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
704 _PATH_HOST_KEY_FILE, "", NULL, NULL);
705 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
706 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
707 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
708 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
711 if (options.hostbased_authentication == 1 &&
712 sensitive_data.keys[0] == NULL &&
713 sensitive_data.keys[1] == NULL &&
714 sensitive_data.keys[2] == NULL) {
715 sensitive_data.keys[1] = key_load_public(
716 _PATH_HOST_DSA_KEY_FILE, NULL);
717 sensitive_data.keys[2] = key_load_public(
718 _PATH_HOST_RSA_KEY_FILE, NULL);
719 sensitive_data.external_keysign = 1;
723 * Get rid of any extra privileges that we may have. We will no
724 * longer need them. Also, extra privileges could make it very hard
725 * to read identity files and other non-world-readable files from the
726 * user's home directory if it happens to be on a NFS volume where
727 * root is mapped to nobody.
729 if (original_effective_uid == 0) {
731 permanently_set_uid(pw);
735 * Now that we are back to our own permissions, create ~/.ssh
736 * directory if it doesn't already exist.
738 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
739 if (stat(buf, &st) < 0)
740 if (mkdir(buf, 0700) < 0)
741 error("Could not create directory '%.200s'.", buf);
743 /* load options.identity_files */
744 load_public_identity_files();
746 /* Expand ~ in known host file names. */
748 options.system_hostfile =
749 tilde_expand_filename(options.system_hostfile, original_real_uid);
750 options.user_hostfile =
751 tilde_expand_filename(options.user_hostfile, original_real_uid);
752 options.system_hostfile2 =
753 tilde_expand_filename(options.system_hostfile2, original_real_uid);
754 options.user_hostfile2 =
755 tilde_expand_filename(options.user_hostfile2, original_real_uid);
757 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
759 /* Log into the remote system. This never returns if the login fails. */
760 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
762 /* We no longer need the private host keys. Clear them now. */
763 if (sensitive_data.nkeys != 0) {
764 for (i = 0; i < sensitive_data.nkeys; i++) {
765 if (sensitive_data.keys[i] != NULL) {
766 /* Destroys contents safely */
767 debug3("clear hostkey %d", i);
768 key_free(sensitive_data.keys[i]);
769 sensitive_data.keys[i] = NULL;
772 xfree(sensitive_data.keys);
774 for (i = 0; i < options.num_identity_files; i++) {
775 if (options.identity_files[i]) {
776 xfree(options.identity_files[i]);
777 options.identity_files[i] = NULL;
779 if (options.identity_keys[i]) {
780 key_free(options.identity_keys[i]);
781 options.identity_keys[i] = NULL;
785 exit_status = compat20 ? ssh_session2() : ssh_session();
788 if (options.control_path != NULL && control_fd != -1)
789 unlink(options.control_path);
792 * Send SIGHUP to proxy command if used. We don't wait() in
793 * case it hangs and instead rely on init to reap the child
795 if (proxy_command_pid > 1)
796 kill(proxy_command_pid, SIGHUP);
802 ssh_init_forwarding(void)
807 /* Initiate local TCP/IP port forwardings. */
808 for (i = 0; i < options.num_local_forwards; i++) {
809 debug("Local connections to %.200s:%d forwarded to remote "
811 (options.local_forwards[i].listen_host == NULL) ?
812 (options.gateway_ports ? "*" : "LOCALHOST") :
813 options.local_forwards[i].listen_host,
814 options.local_forwards[i].listen_port,
815 options.local_forwards[i].connect_host,
816 options.local_forwards[i].connect_port);
817 success += channel_setup_local_fwd_listener(
818 options.local_forwards[i].listen_host,
819 options.local_forwards[i].listen_port,
820 options.local_forwards[i].connect_host,
821 options.local_forwards[i].connect_port,
822 options.gateway_ports);
824 if (i > 0 && success != i && options.exit_on_forward_failure)
825 fatal("Could not request local forwarding.");
826 if (i > 0 && success == 0)
827 error("Could not request local forwarding.");
829 /* Initiate remote TCP/IP port forwardings. */
830 for (i = 0; i < options.num_remote_forwards; i++) {
831 debug("Remote connections from %.200s:%d forwarded to "
832 "local address %.200s:%d",
833 (options.remote_forwards[i].listen_host == NULL) ?
834 "LOCALHOST" : options.remote_forwards[i].listen_host,
835 options.remote_forwards[i].listen_port,
836 options.remote_forwards[i].connect_host,
837 options.remote_forwards[i].connect_port);
838 if (channel_request_remote_forwarding(
839 options.remote_forwards[i].listen_host,
840 options.remote_forwards[i].listen_port,
841 options.remote_forwards[i].connect_host,
842 options.remote_forwards[i].connect_port) < 0) {
843 if (options.exit_on_forward_failure)
844 fatal("Could not request remote forwarding.");
846 logit("Warning: Could not request remote "
853 check_agent_present(void)
855 if (options.forward_agent) {
856 /* Clear agent forwarding if we don't have an agent. */
857 if (!ssh_agent_present())
858 options.forward_agent = 0;
872 /* Enable compression if requested. */
873 if (options.compression) {
874 debug("Requesting compression at level %d.", options.compression_level);
876 if (options.compression_level < 1 || options.compression_level > 9)
877 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
879 /* Send the request. */
880 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
881 packet_put_int(options.compression_level);
884 type = packet_read();
885 if (type == SSH_SMSG_SUCCESS)
886 packet_start_compression(options.compression_level);
887 else if (type == SSH_SMSG_FAILURE)
888 logit("Warning: Remote host refused compression.");
890 packet_disconnect("Protocol error waiting for compression response.");
892 /* Allocate a pseudo tty if appropriate. */
894 debug("Requesting pty.");
896 /* Start the packet. */
897 packet_start(SSH_CMSG_REQUEST_PTY);
899 /* Store TERM in the packet. There is no limit on the
900 length of the string. */
904 packet_put_cstring(cp);
906 /* Store window size in the packet. */
907 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
908 memset(&ws, 0, sizeof(ws));
909 packet_put_int((u_int)ws.ws_row);
910 packet_put_int((u_int)ws.ws_col);
911 packet_put_int((u_int)ws.ws_xpixel);
912 packet_put_int((u_int)ws.ws_ypixel);
914 /* Store tty modes in the packet. */
915 tty_make_modes(fileno(stdin), NULL);
917 /* Send the packet, and wait for it to leave. */
921 /* Read response from the server. */
922 type = packet_read();
923 if (type == SSH_SMSG_SUCCESS) {
926 } else if (type == SSH_SMSG_FAILURE)
927 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
929 packet_disconnect("Protocol error waiting for pty request response.");
931 /* Request X11 forwarding if enabled and DISPLAY is set. */
932 display = getenv("DISPLAY");
933 if (options.forward_x11 && display != NULL) {
935 /* Get reasonable local authentication information. */
936 client_x11_get_proto(display, options.xauth_location,
937 options.forward_x11_trusted, &proto, &data);
938 /* Request forwarding with authentication spoofing. */
939 debug("Requesting X11 forwarding with authentication spoofing.");
940 x11_request_forwarding_with_spoofing(0, display, proto, data);
942 /* Read response from the server. */
943 type = packet_read();
944 if (type == SSH_SMSG_SUCCESS) {
946 } else if (type == SSH_SMSG_FAILURE) {
947 logit("Warning: Remote host denied X11 forwarding.");
949 packet_disconnect("Protocol error waiting for X11 forwarding");
952 /* Tell the packet module whether this is an interactive session. */
953 packet_set_interactive(interactive);
955 /* Request authentication agent forwarding if appropriate. */
956 check_agent_present();
958 if (options.forward_agent) {
959 debug("Requesting authentication agent forwarding.");
960 auth_request_forwarding();
962 /* Read response from the server. */
963 type = packet_read();
965 if (type != SSH_SMSG_SUCCESS)
966 logit("Warning: Remote host denied authentication agent forwarding.");
969 /* Initiate port forwardings. */
970 ssh_init_forwarding();
972 /* If requested, let ssh continue in the background. */
973 if (fork_after_authentication_flag)
974 if (daemon(1, 1) < 0)
975 fatal("daemon() failed: %.200s", strerror(errno));
978 * If a command was specified on the command line, execute the
979 * command now. Otherwise request the server to start a shell.
981 if (buffer_len(&command) > 0) {
982 int len = buffer_len(&command);
985 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
986 packet_start(SSH_CMSG_EXEC_CMD);
987 packet_put_string(buffer_ptr(&command), buffer_len(&command));
991 debug("Requesting shell.");
992 packet_start(SSH_CMSG_EXEC_SHELL);
997 /* Enter the interactive session. */
998 return client_loop(have_tty, tty_flag ?
999 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1003 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1007 id = packet_get_int();
1008 len = buffer_len(&command);
1012 if (type == SSH2_MSG_CHANNEL_FAILURE)
1013 fatal("Request for subsystem '%.*s' failed on channel %d",
1014 len, (u_char *)buffer_ptr(&command), id);
1018 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1022 i = client_global_request_id++;
1023 if (i >= options.num_remote_forwards)
1025 debug("remote forward %s for: listen %d, connect %s:%d",
1026 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1027 options.remote_forwards[i].listen_port,
1028 options.remote_forwards[i].connect_host,
1029 options.remote_forwards[i].connect_port);
1030 if (type == SSH2_MSG_REQUEST_FAILURE) {
1031 if (options.exit_on_forward_failure)
1032 fatal("Error: remote port forwarding failed for "
1034 options.remote_forwards[i].listen_port);
1036 logit("Warning: remote port forwarding failed for "
1038 options.remote_forwards[i].listen_port);
1043 ssh_control_listener(void)
1045 struct sockaddr_un addr;
1049 if (options.control_path == NULL ||
1050 options.control_master == SSHCTL_MASTER_NO)
1053 debug("setting up multiplex master socket");
1055 memset(&addr, '\0', sizeof(addr));
1056 addr.sun_family = AF_UNIX;
1057 addr_len = offsetof(struct sockaddr_un, sun_path) +
1058 strlen(options.control_path) + 1;
1060 if (strlcpy(addr.sun_path, options.control_path,
1061 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1062 fatal("ControlPath too long");
1064 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1065 fatal("%s socket(): %s", __func__, strerror(errno));
1067 old_umask = umask(0177);
1068 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1070 if (errno == EINVAL || errno == EADDRINUSE)
1071 fatal("ControlSocket %s already exists",
1072 options.control_path);
1074 fatal("%s bind(): %s", __func__, strerror(errno));
1078 if (listen(control_fd, 64) == -1)
1079 fatal("%s listen(): %s", __func__, strerror(errno));
1081 set_nonblock(control_fd);
1084 /* request pty/x11/agent/tcpfwd/shell for channel */
1086 ssh_session2_setup(int id, void *arg)
1088 extern char **environ;
1089 const char *display;
1090 int interactive = tty_flag;
1092 display = getenv("DISPLAY");
1093 if (options.forward_x11 && display != NULL) {
1095 /* Get reasonable local authentication information. */
1096 client_x11_get_proto(display, options.xauth_location,
1097 options.forward_x11_trusted, &proto, &data);
1098 /* Request forwarding with authentication spoofing. */
1099 debug("Requesting X11 forwarding with authentication spoofing.");
1100 x11_request_forwarding_with_spoofing(id, display, proto, data);
1102 /* XXX wait for reply */
1105 check_agent_present();
1106 if (options.forward_agent) {
1107 debug("Requesting authentication agent forwarding.");
1108 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1112 if (options.tun_open != SSH_TUNMODE_NO) {
1116 debug("Requesting tun.");
1117 if ((fd = tun_open(options.tun_local,
1118 options.tun_open)) >= 0) {
1119 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1120 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1123 #if defined(SSH_TUN_FILTER)
1124 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1125 channel_register_filter(c->self, sys_tun_infilter,
1128 packet_start(SSH2_MSG_CHANNEL_OPEN);
1129 packet_put_cstring("tun@openssh.com");
1130 packet_put_int(c->self);
1131 packet_put_int(c->local_window_max);
1132 packet_put_int(c->local_maxpacket);
1133 packet_put_int(options.tun_open);
1134 packet_put_int(options.tun_remote);
1139 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1140 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1142 packet_set_interactive(interactive);
1145 /* open new channel for a session */
1147 ssh_session2_open(void)
1150 int window, packetmax, in, out, err;
1152 if (stdin_null_flag) {
1153 in = open(_PATH_DEVNULL, O_RDONLY);
1155 in = dup(STDIN_FILENO);
1157 out = dup(STDOUT_FILENO);
1158 err = dup(STDERR_FILENO);
1160 if (in < 0 || out < 0 || err < 0)
1161 fatal("dup() in/out/err failed");
1163 /* enable nonblocking unless tty */
1171 window = CHAN_SES_WINDOW_DEFAULT;
1172 packetmax = CHAN_SES_PACKET_DEFAULT;
1178 "session", SSH_CHANNEL_OPENING, in, out, err,
1179 window, packetmax, CHAN_EXTENDED_WRITE,
1180 "client-session", /*nonblock*/0);
1182 debug3("ssh_session2_open: channel_new: %d", c->self);
1184 channel_send_open(c->self);
1186 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1196 /* XXX should be pre-session */
1197 ssh_init_forwarding();
1198 ssh_control_listener();
1200 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1201 id = ssh_session2_open();
1203 /* Execute a local command */
1204 if (options.local_command != NULL &&
1205 options.permit_local_command)
1206 ssh_local_cmd(options.local_command);
1208 /* If requested, let ssh continue in the background. */
1209 if (fork_after_authentication_flag)
1210 if (daemon(1, 1) < 0)
1211 fatal("daemon() failed: %.200s", strerror(errno));
1213 return client_loop(tty_flag, tty_flag ?
1214 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1218 load_public_identity_files(void)
1220 char *filename, *cp, thishost[NI_MAXHOST];
1227 if (options.smartcard_device != NULL &&
1228 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1229 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1231 for (i = 0; keys[i] != NULL; i++) {
1233 memmove(&options.identity_files[1], &options.identity_files[0],
1234 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1235 memmove(&options.identity_keys[1], &options.identity_keys[0],
1236 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1237 options.num_identity_files++;
1238 options.identity_keys[0] = keys[i];
1239 options.identity_files[0] = sc_get_key_label(keys[i]);
1241 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1242 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1246 #endif /* SMARTCARD */
1247 if ((pw = getpwuid(original_real_uid)) == NULL)
1248 fatal("load_public_identity_files: getpwuid failed");
1249 if (gethostname(thishost, sizeof(thishost)) == -1)
1250 fatal("load_public_identity_files: gethostname: %s",
1252 for (; i < options.num_identity_files; i++) {
1253 cp = tilde_expand_filename(options.identity_files[i],
1255 filename = percent_expand(cp, "d", pw->pw_dir,
1256 "u", pw->pw_name, "l", thishost, "h", host,
1257 "r", options.user, (char *)NULL);
1259 public = key_load_public(filename, NULL);
1260 debug("identity file %s type %d", filename,
1261 public ? public->type : -1);
1262 xfree(options.identity_files[i]);
1263 options.identity_files[i] = filename;
1264 options.identity_keys[i] = public;
1269 control_client_sighandler(int signo)
1271 control_client_terminate = signo;
1275 control_client_sigrelay(int signo)
1277 if (control_server_pid > 1)
1278 kill(control_server_pid, signo);
1282 env_permitted(char *env)
1285 char name[1024], *cp;
1287 if ((cp = strchr(env, '=')) == NULL || cp == env)
1289 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1290 if (ret <= 0 || (size_t)ret >= sizeof(name))
1291 fatal("env_permitted: name '%.100s...' too long", env);
1293 for (i = 0; i < options.num_send_env; i++)
1294 if (match_pattern(name, options.send_env[i]))
1301 control_client(const char *path)
1303 struct sockaddr_un addr;
1304 int i, r, fd, sock, exitval, num_env, addr_len;
1307 extern char **environ;
1310 if (mux_command == 0)
1311 mux_command = SSHMUX_COMMAND_OPEN;
1313 switch (options.control_master) {
1314 case SSHCTL_MASTER_AUTO:
1315 case SSHCTL_MASTER_AUTO_ASK:
1316 debug("auto-mux: Trying existing master");
1318 case SSHCTL_MASTER_NO:
1324 memset(&addr, '\0', sizeof(addr));
1325 addr.sun_family = AF_UNIX;
1326 addr_len = offsetof(struct sockaddr_un, sun_path) +
1329 if (strlcpy(addr.sun_path, path,
1330 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1331 fatal("ControlPath too long");
1333 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1334 fatal("%s socket(): %s", __func__, strerror(errno));
1336 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1337 if (mux_command != SSHMUX_COMMAND_OPEN) {
1338 fatal("Control socket connect(%.100s): %s", path,
1341 if (errno == ENOENT)
1342 debug("Control socket \"%.100s\" does not exist", path);
1344 error("Control socket connect(%.100s): %s", path,
1351 if (stdin_null_flag) {
1352 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1353 fatal("open(/dev/null): %s", strerror(errno));
1354 if (dup2(fd, STDIN_FILENO) == -1)
1355 fatal("dup2: %s", strerror(errno));
1356 if (fd > STDERR_FILENO)
1360 term = getenv("TERM");
1364 flags |= SSHMUX_FLAG_TTY;
1366 flags |= SSHMUX_FLAG_SUBSYS;
1367 if (options.forward_x11)
1368 flags |= SSHMUX_FLAG_X11_FWD;
1369 if (options.forward_agent)
1370 flags |= SSHMUX_FLAG_AGENT_FWD;
1374 /* Send our command to server */
1375 buffer_put_int(&m, mux_command);
1376 buffer_put_int(&m, flags);
1377 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1378 fatal("%s: msg_send", __func__);
1381 /* Get authorisation status and PID of controlee */
1382 if (ssh_msg_recv(sock, &m) == -1)
1383 fatal("%s: msg_recv", __func__);
1384 if (buffer_get_char(&m) != SSHMUX_VER)
1385 fatal("%s: wrong version", __func__);
1386 if (buffer_get_int(&m) != 1)
1387 fatal("Connection to master denied");
1388 control_server_pid = buffer_get_int(&m);
1392 switch (mux_command) {
1393 case SSHMUX_COMMAND_ALIVE_CHECK:
1394 fprintf(stderr, "Master running (pid=%d)\r\n",
1395 control_server_pid);
1397 case SSHMUX_COMMAND_TERMINATE:
1398 fprintf(stderr, "Exit request sent.\r\n");
1400 case SSHMUX_COMMAND_OPEN:
1401 /* continue below */
1404 fatal("silly mux_command %d", mux_command);
1407 /* SSHMUX_COMMAND_OPEN */
1408 buffer_put_cstring(&m, term ? term : "");
1409 buffer_append(&command, "\0", 1);
1410 buffer_put_cstring(&m, buffer_ptr(&command));
1412 if (options.num_send_env == 0 || environ == NULL) {
1413 buffer_put_int(&m, 0);
1415 /* Pass environment */
1417 for (i = 0; environ[i] != NULL; i++)
1418 if (env_permitted(environ[i]))
1419 num_env++; /* Count */
1421 buffer_put_int(&m, num_env);
1423 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1424 if (env_permitted(environ[i])) {
1426 buffer_put_cstring(&m, environ[i]);
1430 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1431 fatal("%s: msg_send", __func__);
1433 mm_send_fd(sock, STDIN_FILENO);
1434 mm_send_fd(sock, STDOUT_FILENO);
1435 mm_send_fd(sock, STDERR_FILENO);
1437 /* Wait for reply, so master has a chance to gather ttymodes */
1439 if (ssh_msg_recv(sock, &m) == -1)
1440 fatal("%s: msg_recv", __func__);
1441 if (buffer_get_char(&m) != SSHMUX_VER)
1442 fatal("%s: wrong version", __func__);
1445 signal(SIGHUP, control_client_sighandler);
1446 signal(SIGINT, control_client_sighandler);
1447 signal(SIGTERM, control_client_sighandler);
1448 signal(SIGWINCH, control_client_sigrelay);
1453 /* Stick around until the controlee closes the client_fd */
1455 for (;!control_client_terminate;) {
1456 r = read(sock, &exitval, sizeof(exitval));
1458 debug2("Received EOF from master");
1462 debug2("Received exit status from master %d", exitval);
1463 if (r == -1 && errno != EINTR)
1464 fatal("%s: read %s", __func__, strerror(errno));
1467 if (control_client_terminate)
1468 debug2("Exiting on signal %d", control_client_terminate);
1474 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1475 fprintf(stderr, "Connection to master closed.\r\n");