2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Ssh client program. This program can be used to log into a remote machine.
6 * The software supports strong authentication, encryption, and forwarding
7 * of X11, TCP/IP, and authentication connections.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 1999 Niels Provos. All rights reserved.
16 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
18 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
19 * in Canada (German citizen).
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 RCSID("$OpenBSD: ssh.c,v 1.264 2006/02/20 17:19:54 stevesk Exp $");
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>
56 #include <openssl/evp.h>
57 #include <openssl/err.h>
72 #include "pathnames.h"
74 #include "clientloop.h"
77 #include "sshconnect.h"
84 #include "monitor_fdpass.h"
91 extern char *__progname;
93 /* Flag indicating whether debug mode is on. This can be set on the command line. */
96 /* Flag indicating whether a tty should be allocated */
99 int force_tty_flag = 0;
101 /* don't exec a shell */
102 int no_shell_flag = 0;
105 * Flag indicating that nothing should be read from stdin. This can be set
106 * on the command line.
108 int stdin_null_flag = 0;
111 * Flag indicating that ssh should fork after authentication. This is useful
112 * so that the passphrase can be entered manually, and then ssh goes to the
115 int fork_after_authentication_flag = 0;
118 * General data structure for command line options and options configurable
119 * in configuration files. See readconf.h.
123 /* optional user configfile */
127 * Name of the host we are connecting to. This is the name given on the
128 * command line, or the HostName specified for the user-supplied name in a
129 * configuration file.
133 /* socket address the host resolves to */
134 struct sockaddr_storage hostaddr;
136 /* Private host keys. */
137 Sensitive sensitive_data;
139 /* Original real UID. */
140 uid_t original_real_uid;
141 uid_t original_effective_uid;
143 /* command to be executed */
146 /* Should we execute a command or invoke a subsystem? */
147 int subsystem_flag = 0;
149 /* # of replies received for global requests */
150 static int client_global_request_id = 0;
152 /* pid of proxycommand child process */
153 pid_t proxy_command_pid = 0;
155 /* fd to control socket */
158 /* Multiplexing control command */
159 static u_int mux_command = 0;
161 /* Only used in control client mode */
162 volatile sig_atomic_t control_client_terminate = 0;
163 u_int control_server_pid = 0;
165 /* Prints a help message to the user. This function never returns. */
171 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
172 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
173 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
174 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
175 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
176 " [-w tunnel:tunnel] [user@]hostname [command]\n"
181 static int ssh_session(void);
182 static int ssh_session2(void);
183 static void load_public_identity_files(void);
184 static void control_client(const char *path);
187 * Main program for the ssh client.
190 main(int ac, char **av)
192 int i, opt, exit_status;
193 char *p, *cp, *line, buf[256];
197 extern int optind, optreset;
202 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
205 __progname = ssh_get_progname(av[0]);
209 * Save the original real uid. It will be needed later (uid-swapping
210 * may clobber the real uid).
212 original_real_uid = getuid();
213 original_effective_uid = geteuid();
216 * Use uid-swapping to give up root privileges for the duration of
217 * option processing. We will re-instantiate the rights when we are
218 * ready to create the privileged port, and will permanently drop
219 * them when the port has been created (actually, when the connection
220 * has been made, as we may need to create the port several times).
224 #ifdef HAVE_SETRLIMIT
225 /* If we are installed setuid root be careful to not drop core. */
226 if (original_real_uid != original_effective_uid) {
228 rlim.rlim_cur = rlim.rlim_max = 0;
229 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
230 fatal("setrlimit failed: %.100s", strerror(errno));
234 pw = getpwuid(original_real_uid);
236 logit("You don't exist, go away!");
239 /* Take a copy of the returned structure. */
243 * Set our umask to something reasonable, as some files are created
244 * with the default umask. This will make them world-readable but
245 * writable only by the owner, which is ok for all files for which we
246 * don't set the modes explicitly.
250 /* Initialize option structure to indicate that no values have been set. */
251 initialize_options(&options);
253 /* Parse command-line arguments. */
257 while ((opt = getopt(ac, av,
258 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
261 options.protocol = SSH_PROTO_1;
264 options.protocol = SSH_PROTO_2;
267 options.address_family = AF_INET;
270 options.address_family = AF_INET6;
276 fork_after_authentication_flag = 1;
280 options.forward_x11 = 0;
283 options.forward_x11 = 1;
286 options.forward_x11 = 1;
287 options.forward_x11_trusted = 1;
290 options.gateway_ports = 1;
293 if (strcmp(optarg, "check") == 0)
294 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
295 else if (strcmp(optarg, "exit") == 0)
296 mux_command = SSHMUX_COMMAND_TERMINATE;
298 fatal("Invalid multiplex command.");
300 case 'P': /* deprecated */
301 options.use_privileged_port = 0;
304 options.forward_agent = 0;
307 options.forward_agent = 1;
310 options.gss_deleg_creds = 0;
313 if (stat(optarg, &st) < 0) {
314 fprintf(stderr, "Warning: Identity file %s "
315 "not accessible: %s.\n", optarg,
319 if (options.num_identity_files >=
320 SSH_MAX_IDENTITY_FILES)
321 fatal("Too many identity files specified "
322 "(max %d)", SSH_MAX_IDENTITY_FILES);
323 options.identity_files[options.num_identity_files++] =
328 options.smartcard_device = xstrdup(optarg);
330 fprintf(stderr, "no support for smartcards.\n");
339 if (debug_flag == 0) {
341 options.log_level = SYSLOG_LEVEL_DEBUG1;
343 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
349 fprintf(stderr, "%s, %s\n",
350 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
355 if (options.tun_open == -1)
356 options.tun_open = SSH_TUNMODE_DEFAULT;
357 options.tun_local = a2tun(optarg, &options.tun_remote);
358 if (options.tun_local == SSH_TUNID_ERR) {
359 fprintf(stderr, "Bad tun device '%s'\n", optarg);
364 options.log_level = SYSLOG_LEVEL_QUIET;
367 if (optarg[0] == '^' && optarg[2] == 0 &&
368 (u_char) optarg[1] >= 64 &&
369 (u_char) optarg[1] < 128)
370 options.escape_char = (u_char) optarg[1] & 31;
371 else if (strlen(optarg) == 1)
372 options.escape_char = (u_char) optarg[0];
373 else if (strcmp(optarg, "none") == 0)
374 options.escape_char = SSH_ESCAPECHAR_NONE;
376 fprintf(stderr, "Bad escape character '%s'.\n",
382 if (ciphers_valid(optarg)) {
384 options.ciphers = xstrdup(optarg);
385 options.cipher = SSH_CIPHER_INVALID;
388 options.cipher = cipher_number(optarg);
389 if (options.cipher == -1) {
391 "Unknown cipher type '%s'\n",
395 if (options.cipher == SSH_CIPHER_3DES)
396 options.ciphers = "3des-cbc";
397 else if (options.cipher == SSH_CIPHER_BLOWFISH)
398 options.ciphers = "blowfish-cbc";
400 options.ciphers = (char *)-1;
404 if (mac_valid(optarg))
405 options.macs = xstrdup(optarg);
407 fprintf(stderr, "Unknown mac type '%s'\n",
413 if (options.control_master == SSHCTL_MASTER_YES)
414 options.control_master = SSHCTL_MASTER_ASK;
416 options.control_master = SSHCTL_MASTER_YES;
419 options.port = a2port(optarg);
420 if (options.port == 0) {
421 fprintf(stderr, "Bad port '%s'\n", optarg);
426 options.user = optarg;
430 if (parse_forward(&fwd, optarg))
431 add_local_forward(&options, &fwd);
434 "Bad local forwarding specification '%s'\n",
441 if (parse_forward(&fwd, optarg)) {
442 add_remote_forward(&options, &fwd);
445 "Bad remote forwarding specification "
452 cp = p = xstrdup(optarg);
453 memset(&fwd, '\0', sizeof(fwd));
454 fwd.connect_host = "socks";
455 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
456 fprintf(stderr, "Bad dynamic forwarding "
457 "specification '%.100s'\n", optarg);
461 fwd.listen_port = a2port(cp);
462 fwd.listen_host = cleanhostname(fwd.listen_host);
464 fwd.listen_port = a2port(fwd.listen_host);
465 fwd.listen_host = NULL;
468 if (fwd.listen_port == 0) {
469 fprintf(stderr, "Bad dynamic port '%s'\n",
473 add_local_forward(&options, &fwd);
478 options.compression = 1;
489 line = xstrdup(optarg);
490 if (process_config_line(&options, host ? host : "",
491 line, "command-line", 0, &dummy) != 0)
499 if (options.control_path != NULL)
500 free(options.control_path);
501 options.control_path = xstrdup(optarg);
504 options.bind_address = optarg;
517 if (ac > 0 && !host && **av != '-') {
518 if (strrchr(*av, '@')) {
520 cp = strrchr(p, '@');
521 if (cp == NULL || cp == p)
529 optind = optreset = 1;
535 /* Check that we got a host name. */
539 SSLeay_add_all_algorithms();
540 ERR_load_crypto_strings();
542 /* Initialize the command to execute on remote host. */
543 buffer_init(&command);
546 * Save the command to execute on the remote host in a buffer. There
547 * is no limit on the length of the command, except by the maximum
548 * packet size. Also sets the tty flag if there is no command.
551 /* No command specified - execute shell on a tty. */
553 if (subsystem_flag) {
555 "You must specify a subsystem to invoke.\n");
559 /* A command has been specified. Store it into the buffer. */
560 for (i = 0; i < ac; i++) {
562 buffer_append(&command, " ", 1);
563 buffer_append(&command, av[i], strlen(av[i]));
567 /* Cannot fork to background if no command. */
568 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
569 fatal("Cannot fork into background without a command to execute.");
571 /* Allocate a tty by default if no command specified. */
572 if (buffer_len(&command) == 0)
578 /* Do not allocate a tty if stdin is not a tty. */
579 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
581 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
586 * Initialize "log" output. Since we are the client all output
587 * actually goes to stderr.
589 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
590 SYSLOG_FACILITY_USER, 1);
593 * Read per-user configuration file. Ignore the system wide config
594 * file if the user specifies a config file on the command line.
596 if (config != NULL) {
597 if (!read_config_file(config, host, &options, 0))
598 fatal("Can't open user config file %.100s: "
599 "%.100s", config, strerror(errno));
601 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
602 _PATH_SSH_USER_CONFFILE);
603 (void)read_config_file(buf, host, &options, 1);
605 /* Read systemwide configuration file after use config. */
606 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
610 /* Fill configuration defaults. */
611 fill_default_options(&options);
613 channel_set_af(options.address_family);
616 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
620 if (options.user == NULL)
621 options.user = xstrdup(pw->pw_name);
623 if (options.hostname != NULL)
624 host = options.hostname;
626 /* force lowercase for hostkey matching */
627 if (options.host_key_alias != NULL) {
628 for (p = options.host_key_alias; *p; p++)
633 /* Get default port if port has not been set. */
634 if (options.port == 0) {
635 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
636 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
639 if (options.proxy_command != NULL &&
640 strcmp(options.proxy_command, "none") == 0)
641 options.proxy_command = NULL;
642 if (options.control_path != NULL &&
643 strcmp(options.control_path, "none") == 0)
644 options.control_path = NULL;
646 if (options.control_path != NULL) {
649 if (gethostname(me, sizeof(me)) == -1)
650 fatal("gethostname: %s", strerror(errno));
651 snprintf(buf, sizeof(buf), "%d", options.port);
652 cp = tilde_expand_filename(options.control_path,
654 options.control_path = percent_expand(cp, "p", buf, "h", host,
655 "r", options.user, "l", me, (char *)NULL);
658 if (mux_command != 0 && options.control_path == NULL)
659 fatal("No ControlPath specified for \"-O\" command");
660 if (options.control_path != NULL)
661 control_client(options.control_path);
663 /* Open a connection to the remote host. */
664 if (ssh_connect(host, &hostaddr, options.port,
665 options.address_family, options.connection_attempts,
667 options.use_privileged_port,
669 original_effective_uid == 0 && options.use_privileged_port,
671 options.proxy_command) != 0)
675 * If we successfully made the connection, load the host private key
676 * in case we will need it later for combined rsa-rhosts
677 * authentication. This must be done before releasing extra
678 * privileges, because the file is only readable by root.
679 * If we cannot access the private keys, load the public keys
680 * instead and try to execute the ssh-keysign helper instead.
682 sensitive_data.nkeys = 0;
683 sensitive_data.keys = NULL;
684 sensitive_data.external_keysign = 0;
685 if (options.rhosts_rsa_authentication ||
686 options.hostbased_authentication) {
687 sensitive_data.nkeys = 3;
688 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
692 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
693 _PATH_HOST_KEY_FILE, "", NULL);
694 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
695 _PATH_HOST_DSA_KEY_FILE, "", NULL);
696 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
697 _PATH_HOST_RSA_KEY_FILE, "", NULL);
700 if (options.hostbased_authentication == 1 &&
701 sensitive_data.keys[0] == NULL &&
702 sensitive_data.keys[1] == NULL &&
703 sensitive_data.keys[2] == NULL) {
704 sensitive_data.keys[1] = key_load_public(
705 _PATH_HOST_DSA_KEY_FILE, NULL);
706 sensitive_data.keys[2] = key_load_public(
707 _PATH_HOST_RSA_KEY_FILE, NULL);
708 sensitive_data.external_keysign = 1;
712 * Get rid of any extra privileges that we may have. We will no
713 * longer need them. Also, extra privileges could make it very hard
714 * to read identity files and other non-world-readable files from the
715 * user's home directory if it happens to be on a NFS volume where
716 * root is mapped to nobody.
718 if (original_effective_uid == 0) {
720 permanently_set_uid(pw);
724 * Now that we are back to our own permissions, create ~/.ssh
725 * directory if it doesn't already exist.
727 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
728 if (stat(buf, &st) < 0)
729 if (mkdir(buf, 0700) < 0)
730 error("Could not create directory '%.200s'.", buf);
732 /* load options.identity_files */
733 load_public_identity_files();
735 /* Expand ~ in known host file names. */
737 options.system_hostfile =
738 tilde_expand_filename(options.system_hostfile, original_real_uid);
739 options.user_hostfile =
740 tilde_expand_filename(options.user_hostfile, original_real_uid);
741 options.system_hostfile2 =
742 tilde_expand_filename(options.system_hostfile2, original_real_uid);
743 options.user_hostfile2 =
744 tilde_expand_filename(options.user_hostfile2, original_real_uid);
746 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
748 /* Log into the remote system. This never returns if the login fails. */
749 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
751 /* We no longer need the private host keys. Clear them now. */
752 if (sensitive_data.nkeys != 0) {
753 for (i = 0; i < sensitive_data.nkeys; i++) {
754 if (sensitive_data.keys[i] != NULL) {
755 /* Destroys contents safely */
756 debug3("clear hostkey %d", i);
757 key_free(sensitive_data.keys[i]);
758 sensitive_data.keys[i] = NULL;
761 xfree(sensitive_data.keys);
763 for (i = 0; i < options.num_identity_files; i++) {
764 if (options.identity_files[i]) {
765 xfree(options.identity_files[i]);
766 options.identity_files[i] = NULL;
768 if (options.identity_keys[i]) {
769 key_free(options.identity_keys[i]);
770 options.identity_keys[i] = NULL;
774 exit_status = compat20 ? ssh_session2() : ssh_session();
777 if (options.control_path != NULL && control_fd != -1)
778 unlink(options.control_path);
781 * Send SIGHUP to proxy command if used. We don't wait() in
782 * case it hangs and instead rely on init to reap the child
784 if (proxy_command_pid > 1)
785 kill(proxy_command_pid, SIGHUP);
791 ssh_init_forwarding(void)
796 /* Initiate local TCP/IP port forwardings. */
797 for (i = 0; i < options.num_local_forwards; i++) {
798 debug("Local connections to %.200s:%d forwarded to remote "
800 (options.local_forwards[i].listen_host == NULL) ?
801 (options.gateway_ports ? "*" : "LOCALHOST") :
802 options.local_forwards[i].listen_host,
803 options.local_forwards[i].listen_port,
804 options.local_forwards[i].connect_host,
805 options.local_forwards[i].connect_port);
806 success += channel_setup_local_fwd_listener(
807 options.local_forwards[i].listen_host,
808 options.local_forwards[i].listen_port,
809 options.local_forwards[i].connect_host,
810 options.local_forwards[i].connect_port,
811 options.gateway_ports);
813 if (i > 0 && success == 0)
814 error("Could not request local forwarding.");
816 /* Initiate remote TCP/IP port forwardings. */
817 for (i = 0; i < options.num_remote_forwards; i++) {
818 debug("Remote connections from %.200s:%d forwarded to "
819 "local address %.200s:%d",
820 (options.remote_forwards[i].listen_host == NULL) ?
821 "LOCALHOST" : options.remote_forwards[i].listen_host,
822 options.remote_forwards[i].listen_port,
823 options.remote_forwards[i].connect_host,
824 options.remote_forwards[i].connect_port);
825 channel_request_remote_forwarding(
826 options.remote_forwards[i].listen_host,
827 options.remote_forwards[i].listen_port,
828 options.remote_forwards[i].connect_host,
829 options.remote_forwards[i].connect_port);
834 check_agent_present(void)
836 if (options.forward_agent) {
837 /* Clear agent forwarding if we don't have an agent. */
838 if (!ssh_agent_present())
839 options.forward_agent = 0;
853 /* Enable compression if requested. */
854 if (options.compression) {
855 debug("Requesting compression at level %d.", options.compression_level);
857 if (options.compression_level < 1 || options.compression_level > 9)
858 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
860 /* Send the request. */
861 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
862 packet_put_int(options.compression_level);
865 type = packet_read();
866 if (type == SSH_SMSG_SUCCESS)
867 packet_start_compression(options.compression_level);
868 else if (type == SSH_SMSG_FAILURE)
869 logit("Warning: Remote host refused compression.");
871 packet_disconnect("Protocol error waiting for compression response.");
873 /* Allocate a pseudo tty if appropriate. */
875 debug("Requesting pty.");
877 /* Start the packet. */
878 packet_start(SSH_CMSG_REQUEST_PTY);
880 /* Store TERM in the packet. There is no limit on the
881 length of the string. */
885 packet_put_cstring(cp);
887 /* Store window size in the packet. */
888 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
889 memset(&ws, 0, sizeof(ws));
890 packet_put_int(ws.ws_row);
891 packet_put_int(ws.ws_col);
892 packet_put_int(ws.ws_xpixel);
893 packet_put_int(ws.ws_ypixel);
895 /* Store tty modes in the packet. */
896 tty_make_modes(fileno(stdin), NULL);
898 /* Send the packet, and wait for it to leave. */
902 /* Read response from the server. */
903 type = packet_read();
904 if (type == SSH_SMSG_SUCCESS) {
907 } else if (type == SSH_SMSG_FAILURE)
908 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
910 packet_disconnect("Protocol error waiting for pty request response.");
912 /* Request X11 forwarding if enabled and DISPLAY is set. */
913 display = getenv("DISPLAY");
914 if (options.forward_x11 && display != NULL) {
916 /* Get reasonable local authentication information. */
917 client_x11_get_proto(display, options.xauth_location,
918 options.forward_x11_trusted, &proto, &data);
919 /* Request forwarding with authentication spoofing. */
920 debug("Requesting X11 forwarding with authentication spoofing.");
921 x11_request_forwarding_with_spoofing(0, display, proto, data);
923 /* Read response from the server. */
924 type = packet_read();
925 if (type == SSH_SMSG_SUCCESS) {
927 } else if (type == SSH_SMSG_FAILURE) {
928 logit("Warning: Remote host denied X11 forwarding.");
930 packet_disconnect("Protocol error waiting for X11 forwarding");
933 /* Tell the packet module whether this is an interactive session. */
934 packet_set_interactive(interactive);
936 /* Request authentication agent forwarding if appropriate. */
937 check_agent_present();
939 if (options.forward_agent) {
940 debug("Requesting authentication agent forwarding.");
941 auth_request_forwarding();
943 /* Read response from the server. */
944 type = packet_read();
946 if (type != SSH_SMSG_SUCCESS)
947 logit("Warning: Remote host denied authentication agent forwarding.");
950 /* Initiate port forwardings. */
951 ssh_init_forwarding();
953 /* If requested, let ssh continue in the background. */
954 if (fork_after_authentication_flag)
955 if (daemon(1, 1) < 0)
956 fatal("daemon() failed: %.200s", strerror(errno));
959 * If a command was specified on the command line, execute the
960 * command now. Otherwise request the server to start a shell.
962 if (buffer_len(&command) > 0) {
963 int len = buffer_len(&command);
966 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
967 packet_start(SSH_CMSG_EXEC_CMD);
968 packet_put_string(buffer_ptr(&command), buffer_len(&command));
972 debug("Requesting shell.");
973 packet_start(SSH_CMSG_EXEC_SHELL);
978 /* Enter the interactive session. */
979 return client_loop(have_tty, tty_flag ?
980 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
984 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
988 id = packet_get_int();
989 len = buffer_len(&command);
993 if (type == SSH2_MSG_CHANNEL_FAILURE)
994 fatal("Request for subsystem '%.*s' failed on channel %d",
995 len, (u_char *)buffer_ptr(&command), id);
999 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1003 i = client_global_request_id++;
1004 if (i >= options.num_remote_forwards)
1006 debug("remote forward %s for: listen %d, connect %s:%d",
1007 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1008 options.remote_forwards[i].listen_port,
1009 options.remote_forwards[i].connect_host,
1010 options.remote_forwards[i].connect_port);
1011 if (type == SSH2_MSG_REQUEST_FAILURE)
1012 logit("Warning: remote port forwarding failed for listen "
1013 "port %d", options.remote_forwards[i].listen_port);
1017 ssh_control_listener(void)
1019 struct sockaddr_un addr;
1023 if (options.control_path == NULL ||
1024 options.control_master == SSHCTL_MASTER_NO)
1027 debug("setting up multiplex master socket");
1029 memset(&addr, '\0', sizeof(addr));
1030 addr.sun_family = AF_UNIX;
1031 addr_len = offsetof(struct sockaddr_un, sun_path) +
1032 strlen(options.control_path) + 1;
1034 if (strlcpy(addr.sun_path, options.control_path,
1035 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1036 fatal("ControlPath too long");
1038 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1039 fatal("%s socket(): %s", __func__, strerror(errno));
1041 old_umask = umask(0177);
1042 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1044 if (errno == EINVAL || errno == EADDRINUSE)
1045 fatal("ControlSocket %s already exists",
1046 options.control_path);
1048 fatal("%s bind(): %s", __func__, strerror(errno));
1052 if (listen(control_fd, 64) == -1)
1053 fatal("%s listen(): %s", __func__, strerror(errno));
1055 set_nonblock(control_fd);
1058 /* request pty/x11/agent/tcpfwd/shell for channel */
1060 ssh_session2_setup(int id, void *arg)
1062 extern char **environ;
1063 const char *display;
1064 int interactive = tty_flag;
1066 display = getenv("DISPLAY");
1067 if (options.forward_x11 && display != NULL) {
1069 /* Get reasonable local authentication information. */
1070 client_x11_get_proto(display, options.xauth_location,
1071 options.forward_x11_trusted, &proto, &data);
1072 /* Request forwarding with authentication spoofing. */
1073 debug("Requesting X11 forwarding with authentication spoofing.");
1074 x11_request_forwarding_with_spoofing(id, display, proto, data);
1076 /* XXX wait for reply */
1079 check_agent_present();
1080 if (options.forward_agent) {
1081 debug("Requesting authentication agent forwarding.");
1082 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1086 if (options.tun_open != SSH_TUNMODE_NO) {
1090 debug("Requesting tun.");
1091 if ((fd = tun_open(options.tun_local,
1092 options.tun_open)) >= 0) {
1093 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1094 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1097 #if defined(SSH_TUN_FILTER)
1098 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1099 channel_register_filter(c->self, sys_tun_infilter,
1102 packet_start(SSH2_MSG_CHANNEL_OPEN);
1103 packet_put_cstring("tun@openssh.com");
1104 packet_put_int(c->self);
1105 packet_put_int(c->local_window_max);
1106 packet_put_int(c->local_maxpacket);
1107 packet_put_int(options.tun_open);
1108 packet_put_int(options.tun_remote);
1113 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1114 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1116 packet_set_interactive(interactive);
1119 /* open new channel for a session */
1121 ssh_session2_open(void)
1124 int window, packetmax, in, out, err;
1126 if (stdin_null_flag) {
1127 in = open(_PATH_DEVNULL, O_RDONLY);
1129 in = dup(STDIN_FILENO);
1131 out = dup(STDOUT_FILENO);
1132 err = dup(STDERR_FILENO);
1134 if (in < 0 || out < 0 || err < 0)
1135 fatal("dup() in/out/err failed");
1137 /* enable nonblocking unless tty */
1145 window = CHAN_SES_WINDOW_DEFAULT;
1146 packetmax = CHAN_SES_PACKET_DEFAULT;
1152 "session", SSH_CHANNEL_OPENING, in, out, err,
1153 window, packetmax, CHAN_EXTENDED_WRITE,
1154 "client-session", /*nonblock*/0);
1156 debug3("ssh_session2_open: channel_new: %d", c->self);
1158 channel_send_open(c->self);
1160 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1170 /* XXX should be pre-session */
1171 ssh_init_forwarding();
1172 ssh_control_listener();
1174 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1175 id = ssh_session2_open();
1177 /* Execute a local command */
1178 if (options.local_command != NULL &&
1179 options.permit_local_command)
1180 ssh_local_cmd(options.local_command);
1182 /* If requested, let ssh continue in the background. */
1183 if (fork_after_authentication_flag)
1184 if (daemon(1, 1) < 0)
1185 fatal("daemon() failed: %.200s", strerror(errno));
1187 return client_loop(tty_flag, tty_flag ?
1188 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1192 load_public_identity_files(void)
1200 if (options.smartcard_device != NULL &&
1201 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1202 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1204 for (i = 0; keys[i] != NULL; i++) {
1206 memmove(&options.identity_files[1], &options.identity_files[0],
1207 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1208 memmove(&options.identity_keys[1], &options.identity_keys[0],
1209 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1210 options.num_identity_files++;
1211 options.identity_keys[0] = keys[i];
1212 options.identity_files[0] = sc_get_key_label(keys[i]);
1214 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1215 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1219 #endif /* SMARTCARD */
1220 for (; i < options.num_identity_files; i++) {
1221 filename = tilde_expand_filename(options.identity_files[i],
1223 public = key_load_public(filename, NULL);
1224 debug("identity file %s type %d", filename,
1225 public ? public->type : -1);
1226 xfree(options.identity_files[i]);
1227 options.identity_files[i] = filename;
1228 options.identity_keys[i] = public;
1233 control_client_sighandler(int signo)
1235 control_client_terminate = signo;
1239 control_client_sigrelay(int signo)
1241 if (control_server_pid > 1)
1242 kill(control_server_pid, signo);
1246 env_permitted(char *env)
1249 char name[1024], *cp;
1251 strlcpy(name, env, sizeof(name));
1252 if ((cp = strchr(name, '=')) == NULL)
1257 for (i = 0; i < options.num_send_env; i++)
1258 if (match_pattern(name, options.send_env[i]))
1265 control_client(const char *path)
1267 struct sockaddr_un addr;
1268 int i, r, fd, sock, exitval, num_env, addr_len;
1271 extern char **environ;
1274 if (mux_command == 0)
1275 mux_command = SSHMUX_COMMAND_OPEN;
1277 switch (options.control_master) {
1278 case SSHCTL_MASTER_AUTO:
1279 case SSHCTL_MASTER_AUTO_ASK:
1280 debug("auto-mux: Trying existing master");
1282 case SSHCTL_MASTER_NO:
1288 memset(&addr, '\0', sizeof(addr));
1289 addr.sun_family = AF_UNIX;
1290 addr_len = offsetof(struct sockaddr_un, sun_path) +
1293 if (strlcpy(addr.sun_path, path,
1294 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1295 fatal("ControlPath too long");
1297 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1298 fatal("%s socket(): %s", __func__, strerror(errno));
1300 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1301 if (mux_command != SSHMUX_COMMAND_OPEN) {
1302 fatal("Control socket connect(%.100s): %s", path,
1305 if (errno == ENOENT)
1306 debug("Control socket \"%.100s\" does not exist", path);
1308 error("Control socket connect(%.100s): %s", path,
1315 if (stdin_null_flag) {
1316 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1317 fatal("open(/dev/null): %s", strerror(errno));
1318 if (dup2(fd, STDIN_FILENO) == -1)
1319 fatal("dup2: %s", strerror(errno));
1320 if (fd > STDERR_FILENO)
1324 term = getenv("TERM");
1328 flags |= SSHMUX_FLAG_TTY;
1330 flags |= SSHMUX_FLAG_SUBSYS;
1331 if (options.forward_x11)
1332 flags |= SSHMUX_FLAG_X11_FWD;
1333 if (options.forward_agent)
1334 flags |= SSHMUX_FLAG_AGENT_FWD;
1338 /* Send our command to server */
1339 buffer_put_int(&m, mux_command);
1340 buffer_put_int(&m, flags);
1341 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1342 fatal("%s: msg_send", __func__);
1345 /* Get authorisation status and PID of controlee */
1346 if (ssh_msg_recv(sock, &m) == -1)
1347 fatal("%s: msg_recv", __func__);
1348 if (buffer_get_char(&m) != SSHMUX_VER)
1349 fatal("%s: wrong version", __func__);
1350 if (buffer_get_int(&m) != 1)
1351 fatal("Connection to master denied");
1352 control_server_pid = buffer_get_int(&m);
1356 switch (mux_command) {
1357 case SSHMUX_COMMAND_ALIVE_CHECK:
1358 fprintf(stderr, "Master running (pid=%d)\r\n",
1359 control_server_pid);
1361 case SSHMUX_COMMAND_TERMINATE:
1362 fprintf(stderr, "Exit request sent.\r\n");
1364 case SSHMUX_COMMAND_OPEN:
1365 /* continue below */
1368 fatal("silly mux_command %d", mux_command);
1371 /* SSHMUX_COMMAND_OPEN */
1372 buffer_put_cstring(&m, term ? term : "");
1373 buffer_append(&command, "\0", 1);
1374 buffer_put_cstring(&m, buffer_ptr(&command));
1376 if (options.num_send_env == 0 || environ == NULL) {
1377 buffer_put_int(&m, 0);
1379 /* Pass environment */
1381 for (i = 0; environ[i] != NULL; i++)
1382 if (env_permitted(environ[i]))
1383 num_env++; /* Count */
1385 buffer_put_int(&m, num_env);
1387 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1388 if (env_permitted(environ[i])) {
1390 buffer_put_cstring(&m, environ[i]);
1394 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1395 fatal("%s: msg_send", __func__);
1397 mm_send_fd(sock, STDIN_FILENO);
1398 mm_send_fd(sock, STDOUT_FILENO);
1399 mm_send_fd(sock, STDERR_FILENO);
1401 /* Wait for reply, so master has a chance to gather ttymodes */
1403 if (ssh_msg_recv(sock, &m) == -1)
1404 fatal("%s: msg_recv", __func__);
1405 if (buffer_get_char(&m) != SSHMUX_VER)
1406 fatal("%s: wrong version", __func__);
1409 signal(SIGHUP, control_client_sighandler);
1410 signal(SIGINT, control_client_sighandler);
1411 signal(SIGTERM, control_client_sighandler);
1412 signal(SIGWINCH, control_client_sigrelay);
1417 /* Stick around until the controlee closes the client_fd */
1419 for (;!control_client_terminate;) {
1420 r = read(sock, &exitval, sizeof(exitval));
1422 debug2("Received EOF from master");
1426 debug2("Received exit status from master %d", exitval);
1427 if (r == -1 && errno != EINTR)
1428 fatal("%s: read %s", __func__, strerror(errno));
1431 if (control_client_terminate)
1432 debug2("Exiting on signal %d", control_client_terminate);
1438 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1439 fprintf(stderr, "Connection to master closed.\r\n");