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.259 2006/02/08 14:31:30 stevesk Exp $");
45 #include <sys/resource.h>
49 #include <openssl/evp.h>
50 #include <openssl/err.h>
65 #include "pathnames.h"
67 #include "clientloop.h"
70 #include "sshconnect.h"
77 #include "monitor_fdpass.h"
84 extern char *__progname;
86 /* Flag indicating whether debug mode is on. This can be set on the command line. */
89 /* Flag indicating whether a tty should be allocated */
92 int force_tty_flag = 0;
94 /* don't exec a shell */
95 int no_shell_flag = 0;
98 * Flag indicating that nothing should be read from stdin. This can be set
99 * on the command line.
101 int stdin_null_flag = 0;
104 * Flag indicating that ssh should fork after authentication. This is useful
105 * so that the passphrase can be entered manually, and then ssh goes to the
108 int fork_after_authentication_flag = 0;
111 * General data structure for command line options and options configurable
112 * in configuration files. See readconf.h.
116 /* optional user configfile */
120 * Name of the host we are connecting to. This is the name given on the
121 * command line, or the HostName specified for the user-supplied name in a
122 * configuration file.
126 /* socket address the host resolves to */
127 struct sockaddr_storage hostaddr;
129 /* Private host keys. */
130 Sensitive sensitive_data;
132 /* Original real UID. */
133 uid_t original_real_uid;
134 uid_t original_effective_uid;
136 /* command to be executed */
139 /* Should we execute a command or invoke a subsystem? */
140 int subsystem_flag = 0;
142 /* # of replies received for global requests */
143 static int client_global_request_id = 0;
145 /* pid of proxycommand child process */
146 pid_t proxy_command_pid = 0;
148 /* fd to control socket */
151 /* Multiplexing control command */
152 static u_int mux_command = 0;
154 /* Only used in control client mode */
155 volatile sig_atomic_t control_client_terminate = 0;
156 u_int control_server_pid = 0;
158 /* Prints a help message to the user. This function never returns. */
164 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
165 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
166 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
167 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
168 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
169 " [-w tunnel:tunnel] [user@]hostname [command]\n"
174 static int ssh_session(void);
175 static int ssh_session2(void);
176 static void load_public_identity_files(void);
177 static void control_client(const char *path);
180 * Main program for the ssh client.
183 main(int ac, char **av)
185 int i, opt, exit_status;
186 char *p, *cp, *line, buf[256];
190 extern int optind, optreset;
195 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
198 __progname = ssh_get_progname(av[0]);
202 * Save the original real uid. It will be needed later (uid-swapping
203 * may clobber the real uid).
205 original_real_uid = getuid();
206 original_effective_uid = geteuid();
209 * Use uid-swapping to give up root privileges for the duration of
210 * option processing. We will re-instantiate the rights when we are
211 * ready to create the privileged port, and will permanently drop
212 * them when the port has been created (actually, when the connection
213 * has been made, as we may need to create the port several times).
217 #ifdef HAVE_SETRLIMIT
218 /* If we are installed setuid root be careful to not drop core. */
219 if (original_real_uid != original_effective_uid) {
221 rlim.rlim_cur = rlim.rlim_max = 0;
222 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
223 fatal("setrlimit failed: %.100s", strerror(errno));
227 pw = getpwuid(original_real_uid);
229 logit("You don't exist, go away!");
232 /* Take a copy of the returned structure. */
236 * Set our umask to something reasonable, as some files are created
237 * with the default umask. This will make them world-readable but
238 * writable only by the owner, which is ok for all files for which we
239 * don't set the modes explicitly.
243 /* Initialize option structure to indicate that no values have been set. */
244 initialize_options(&options);
246 /* Parse command-line arguments. */
250 while ((opt = getopt(ac, av,
251 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
254 options.protocol = SSH_PROTO_1;
257 options.protocol = SSH_PROTO_2;
260 options.address_family = AF_INET;
263 options.address_family = AF_INET6;
269 fork_after_authentication_flag = 1;
273 options.forward_x11 = 0;
276 options.forward_x11 = 1;
279 options.forward_x11 = 1;
280 options.forward_x11_trusted = 1;
283 options.gateway_ports = 1;
286 if (strcmp(optarg, "check") == 0)
287 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
288 else if (strcmp(optarg, "exit") == 0)
289 mux_command = SSHMUX_COMMAND_TERMINATE;
291 fatal("Invalid multiplex command.");
293 case 'P': /* deprecated */
294 options.use_privileged_port = 0;
297 options.forward_agent = 0;
300 options.forward_agent = 1;
303 options.gss_deleg_creds = 0;
306 if (stat(optarg, &st) < 0) {
307 fprintf(stderr, "Warning: Identity file %s "
308 "not accessible: %s.\n", optarg,
312 if (options.num_identity_files >=
313 SSH_MAX_IDENTITY_FILES)
314 fatal("Too many identity files specified "
315 "(max %d)", SSH_MAX_IDENTITY_FILES);
316 options.identity_files[options.num_identity_files++] =
321 options.smartcard_device = xstrdup(optarg);
323 fprintf(stderr, "no support for smartcards.\n");
332 if (debug_flag == 0) {
334 options.log_level = SYSLOG_LEVEL_DEBUG1;
336 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
342 fprintf(stderr, "%s, %s\n",
343 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
348 if (options.tun_open == -1)
349 options.tun_open = SSH_TUNMODE_DEFAULT;
350 options.tun_local = a2tun(optarg, &options.tun_remote);
351 if (options.tun_local == SSH_TUNID_ERR) {
352 fprintf(stderr, "Bad tun device '%s'\n", optarg);
357 options.log_level = SYSLOG_LEVEL_QUIET;
360 if (optarg[0] == '^' && optarg[2] == 0 &&
361 (u_char) optarg[1] >= 64 &&
362 (u_char) optarg[1] < 128)
363 options.escape_char = (u_char) optarg[1] & 31;
364 else if (strlen(optarg) == 1)
365 options.escape_char = (u_char) optarg[0];
366 else if (strcmp(optarg, "none") == 0)
367 options.escape_char = SSH_ESCAPECHAR_NONE;
369 fprintf(stderr, "Bad escape character '%s'.\n",
375 if (ciphers_valid(optarg)) {
377 options.ciphers = xstrdup(optarg);
378 options.cipher = SSH_CIPHER_INVALID;
381 options.cipher = cipher_number(optarg);
382 if (options.cipher == -1) {
384 "Unknown cipher type '%s'\n",
388 if (options.cipher == SSH_CIPHER_3DES)
389 options.ciphers = "3des-cbc";
390 else if (options.cipher == SSH_CIPHER_BLOWFISH)
391 options.ciphers = "blowfish-cbc";
393 options.ciphers = (char *)-1;
397 if (mac_valid(optarg))
398 options.macs = xstrdup(optarg);
400 fprintf(stderr, "Unknown mac type '%s'\n",
406 if (options.control_master == SSHCTL_MASTER_YES)
407 options.control_master = SSHCTL_MASTER_ASK;
409 options.control_master = SSHCTL_MASTER_YES;
412 options.port = a2port(optarg);
413 if (options.port == 0) {
414 fprintf(stderr, "Bad port '%s'\n", optarg);
419 options.user = optarg;
423 if (parse_forward(&fwd, optarg))
424 add_local_forward(&options, &fwd);
427 "Bad local forwarding specification '%s'\n",
434 if (parse_forward(&fwd, optarg)) {
435 add_remote_forward(&options, &fwd);
438 "Bad remote forwarding specification "
445 cp = p = xstrdup(optarg);
446 memset(&fwd, '\0', sizeof(fwd));
447 fwd.connect_host = "socks";
448 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
449 fprintf(stderr, "Bad dynamic forwarding "
450 "specification '%.100s'\n", optarg);
454 fwd.listen_port = a2port(cp);
455 fwd.listen_host = cleanhostname(fwd.listen_host);
457 fwd.listen_port = a2port(fwd.listen_host);
458 fwd.listen_host = NULL;
461 if (fwd.listen_port == 0) {
462 fprintf(stderr, "Bad dynamic port '%s'\n",
466 add_local_forward(&options, &fwd);
471 options.compression = 1;
482 line = xstrdup(optarg);
483 if (process_config_line(&options, host ? host : "",
484 line, "command-line", 0, &dummy) != 0)
492 if (options.control_path != NULL)
493 free(options.control_path);
494 options.control_path = xstrdup(optarg);
497 options.bind_address = optarg;
510 if (ac > 0 && !host && **av != '-') {
511 if (strrchr(*av, '@')) {
513 cp = strrchr(p, '@');
514 if (cp == NULL || cp == p)
522 optind = optreset = 1;
528 /* Check that we got a host name. */
532 SSLeay_add_all_algorithms();
533 ERR_load_crypto_strings();
535 /* Initialize the command to execute on remote host. */
536 buffer_init(&command);
539 * Save the command to execute on the remote host in a buffer. There
540 * is no limit on the length of the command, except by the maximum
541 * packet size. Also sets the tty flag if there is no command.
544 /* No command specified - execute shell on a tty. */
546 if (subsystem_flag) {
548 "You must specify a subsystem to invoke.\n");
552 /* A command has been specified. Store it into the buffer. */
553 for (i = 0; i < ac; i++) {
555 buffer_append(&command, " ", 1);
556 buffer_append(&command, av[i], strlen(av[i]));
560 /* Cannot fork to background if no command. */
561 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
562 fatal("Cannot fork into background without a command to execute.");
564 /* Allocate a tty by default if no command specified. */
565 if (buffer_len(&command) == 0)
571 /* Do not allocate a tty if stdin is not a tty. */
572 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
574 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
579 * Initialize "log" output. Since we are the client all output
580 * actually goes to stderr.
582 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
583 SYSLOG_FACILITY_USER, 1);
586 * Read per-user configuration file. Ignore the system wide config
587 * file if the user specifies a config file on the command line.
589 if (config != NULL) {
590 if (!read_config_file(config, host, &options, 0))
591 fatal("Can't open user config file %.100s: "
592 "%.100s", config, strerror(errno));
594 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
595 _PATH_SSH_USER_CONFFILE);
596 (void)read_config_file(buf, host, &options, 1);
598 /* Read systemwide configuration file after use config. */
599 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
603 /* Fill configuration defaults. */
604 fill_default_options(&options);
606 channel_set_af(options.address_family);
609 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
613 if (options.user == NULL)
614 options.user = xstrdup(pw->pw_name);
616 if (options.hostname != NULL)
617 host = options.hostname;
619 /* force lowercase for hostkey matching */
620 if (options.host_key_alias != NULL) {
621 for (p = options.host_key_alias; *p; p++)
626 /* Get default port if port has not been set. */
627 if (options.port == 0) {
628 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
629 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
632 if (options.proxy_command != NULL &&
633 strcmp(options.proxy_command, "none") == 0)
634 options.proxy_command = NULL;
635 if (options.control_path != NULL &&
636 strcmp(options.control_path, "none") == 0)
637 options.control_path = NULL;
639 if (options.control_path != NULL) {
640 snprintf(buf, sizeof(buf), "%d", options.port);
641 cp = tilde_expand_filename(options.control_path,
643 options.control_path = percent_expand(cp, "p", buf, "h", host,
644 "r", options.user, (char *)NULL);
647 if (mux_command != 0 && options.control_path == NULL)
648 fatal("No ControlPath specified for \"-O\" command");
649 if (options.control_path != NULL)
650 control_client(options.control_path);
652 /* Open a connection to the remote host. */
653 if (ssh_connect(host, &hostaddr, options.port,
654 options.address_family, options.connection_attempts,
656 options.use_privileged_port,
658 original_effective_uid == 0 && options.use_privileged_port,
660 options.proxy_command) != 0)
664 * If we successfully made the connection, load the host private key
665 * in case we will need it later for combined rsa-rhosts
666 * authentication. This must be done before releasing extra
667 * privileges, because the file is only readable by root.
668 * If we cannot access the private keys, load the public keys
669 * instead and try to execute the ssh-keysign helper instead.
671 sensitive_data.nkeys = 0;
672 sensitive_data.keys = NULL;
673 sensitive_data.external_keysign = 0;
674 if (options.rhosts_rsa_authentication ||
675 options.hostbased_authentication) {
676 sensitive_data.nkeys = 3;
677 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
681 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
682 _PATH_HOST_KEY_FILE, "", NULL);
683 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
684 _PATH_HOST_DSA_KEY_FILE, "", NULL);
685 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
686 _PATH_HOST_RSA_KEY_FILE, "", NULL);
689 if (options.hostbased_authentication == 1 &&
690 sensitive_data.keys[0] == NULL &&
691 sensitive_data.keys[1] == NULL &&
692 sensitive_data.keys[2] == NULL) {
693 sensitive_data.keys[1] = key_load_public(
694 _PATH_HOST_DSA_KEY_FILE, NULL);
695 sensitive_data.keys[2] = key_load_public(
696 _PATH_HOST_RSA_KEY_FILE, NULL);
697 sensitive_data.external_keysign = 1;
701 * Get rid of any extra privileges that we may have. We will no
702 * longer need them. Also, extra privileges could make it very hard
703 * to read identity files and other non-world-readable files from the
704 * user's home directory if it happens to be on a NFS volume where
705 * root is mapped to nobody.
707 if (original_effective_uid == 0) {
709 permanently_set_uid(pw);
713 * Now that we are back to our own permissions, create ~/.ssh
714 * directory if it doesn't already exist.
716 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
717 if (stat(buf, &st) < 0)
718 if (mkdir(buf, 0700) < 0)
719 error("Could not create directory '%.200s'.", buf);
721 /* load options.identity_files */
722 load_public_identity_files();
724 /* Expand ~ in known host file names. */
726 options.system_hostfile =
727 tilde_expand_filename(options.system_hostfile, original_real_uid);
728 options.user_hostfile =
729 tilde_expand_filename(options.user_hostfile, original_real_uid);
730 options.system_hostfile2 =
731 tilde_expand_filename(options.system_hostfile2, original_real_uid);
732 options.user_hostfile2 =
733 tilde_expand_filename(options.user_hostfile2, original_real_uid);
735 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
737 /* Log into the remote system. This never returns if the login fails. */
738 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
740 /* We no longer need the private host keys. Clear them now. */
741 if (sensitive_data.nkeys != 0) {
742 for (i = 0; i < sensitive_data.nkeys; i++) {
743 if (sensitive_data.keys[i] != NULL) {
744 /* Destroys contents safely */
745 debug3("clear hostkey %d", i);
746 key_free(sensitive_data.keys[i]);
747 sensitive_data.keys[i] = NULL;
750 xfree(sensitive_data.keys);
752 for (i = 0; i < options.num_identity_files; i++) {
753 if (options.identity_files[i]) {
754 xfree(options.identity_files[i]);
755 options.identity_files[i] = NULL;
757 if (options.identity_keys[i]) {
758 key_free(options.identity_keys[i]);
759 options.identity_keys[i] = NULL;
763 exit_status = compat20 ? ssh_session2() : ssh_session();
766 if (options.control_path != NULL && control_fd != -1)
767 unlink(options.control_path);
770 * Send SIGHUP to proxy command if used. We don't wait() in
771 * case it hangs and instead rely on init to reap the child
773 if (proxy_command_pid > 1)
774 kill(proxy_command_pid, SIGHUP);
780 ssh_init_forwarding(void)
785 /* Initiate local TCP/IP port forwardings. */
786 for (i = 0; i < options.num_local_forwards; i++) {
787 debug("Local connections to %.200s:%d forwarded to remote "
789 (options.local_forwards[i].listen_host == NULL) ?
790 (options.gateway_ports ? "*" : "LOCALHOST") :
791 options.local_forwards[i].listen_host,
792 options.local_forwards[i].listen_port,
793 options.local_forwards[i].connect_host,
794 options.local_forwards[i].connect_port);
795 success += channel_setup_local_fwd_listener(
796 options.local_forwards[i].listen_host,
797 options.local_forwards[i].listen_port,
798 options.local_forwards[i].connect_host,
799 options.local_forwards[i].connect_port,
800 options.gateway_ports);
802 if (i > 0 && success == 0)
803 error("Could not request local forwarding.");
805 /* Initiate remote TCP/IP port forwardings. */
806 for (i = 0; i < options.num_remote_forwards; i++) {
807 debug("Remote connections from %.200s:%d forwarded to "
808 "local address %.200s:%d",
809 (options.remote_forwards[i].listen_host == NULL) ?
810 "LOCALHOST" : options.remote_forwards[i].listen_host,
811 options.remote_forwards[i].listen_port,
812 options.remote_forwards[i].connect_host,
813 options.remote_forwards[i].connect_port);
814 channel_request_remote_forwarding(
815 options.remote_forwards[i].listen_host,
816 options.remote_forwards[i].listen_port,
817 options.remote_forwards[i].connect_host,
818 options.remote_forwards[i].connect_port);
823 check_agent_present(void)
825 if (options.forward_agent) {
826 /* Clear agent forwarding if we don't have an agent. */
827 if (!ssh_agent_present())
828 options.forward_agent = 0;
842 /* Enable compression if requested. */
843 if (options.compression) {
844 debug("Requesting compression at level %d.", options.compression_level);
846 if (options.compression_level < 1 || options.compression_level > 9)
847 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
849 /* Send the request. */
850 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
851 packet_put_int(options.compression_level);
854 type = packet_read();
855 if (type == SSH_SMSG_SUCCESS)
856 packet_start_compression(options.compression_level);
857 else if (type == SSH_SMSG_FAILURE)
858 logit("Warning: Remote host refused compression.");
860 packet_disconnect("Protocol error waiting for compression response.");
862 /* Allocate a pseudo tty if appropriate. */
864 debug("Requesting pty.");
866 /* Start the packet. */
867 packet_start(SSH_CMSG_REQUEST_PTY);
869 /* Store TERM in the packet. There is no limit on the
870 length of the string. */
874 packet_put_cstring(cp);
876 /* Store window size in the packet. */
877 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
878 memset(&ws, 0, sizeof(ws));
879 packet_put_int(ws.ws_row);
880 packet_put_int(ws.ws_col);
881 packet_put_int(ws.ws_xpixel);
882 packet_put_int(ws.ws_ypixel);
884 /* Store tty modes in the packet. */
885 tty_make_modes(fileno(stdin), NULL);
887 /* Send the packet, and wait for it to leave. */
891 /* Read response from the server. */
892 type = packet_read();
893 if (type == SSH_SMSG_SUCCESS) {
896 } else if (type == SSH_SMSG_FAILURE)
897 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
899 packet_disconnect("Protocol error waiting for pty request response.");
901 /* Request X11 forwarding if enabled and DISPLAY is set. */
902 display = getenv("DISPLAY");
903 if (options.forward_x11 && display != NULL) {
905 /* Get reasonable local authentication information. */
906 client_x11_get_proto(display, options.xauth_location,
907 options.forward_x11_trusted, &proto, &data);
908 /* Request forwarding with authentication spoofing. */
909 debug("Requesting X11 forwarding with authentication spoofing.");
910 x11_request_forwarding_with_spoofing(0, display, proto, data);
912 /* Read response from the server. */
913 type = packet_read();
914 if (type == SSH_SMSG_SUCCESS) {
916 } else if (type == SSH_SMSG_FAILURE) {
917 logit("Warning: Remote host denied X11 forwarding.");
919 packet_disconnect("Protocol error waiting for X11 forwarding");
922 /* Tell the packet module whether this is an interactive session. */
923 packet_set_interactive(interactive);
925 /* Request authentication agent forwarding if appropriate. */
926 check_agent_present();
928 if (options.forward_agent) {
929 debug("Requesting authentication agent forwarding.");
930 auth_request_forwarding();
932 /* Read response from the server. */
933 type = packet_read();
935 if (type != SSH_SMSG_SUCCESS)
936 logit("Warning: Remote host denied authentication agent forwarding.");
939 /* Initiate port forwardings. */
940 ssh_init_forwarding();
942 /* If requested, let ssh continue in the background. */
943 if (fork_after_authentication_flag)
944 if (daemon(1, 1) < 0)
945 fatal("daemon() failed: %.200s", strerror(errno));
948 * If a command was specified on the command line, execute the
949 * command now. Otherwise request the server to start a shell.
951 if (buffer_len(&command) > 0) {
952 int len = buffer_len(&command);
955 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
956 packet_start(SSH_CMSG_EXEC_CMD);
957 packet_put_string(buffer_ptr(&command), buffer_len(&command));
961 debug("Requesting shell.");
962 packet_start(SSH_CMSG_EXEC_SHELL);
967 /* Enter the interactive session. */
968 return client_loop(have_tty, tty_flag ?
969 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
973 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
977 id = packet_get_int();
978 len = buffer_len(&command);
982 if (type == SSH2_MSG_CHANNEL_FAILURE)
983 fatal("Request for subsystem '%.*s' failed on channel %d",
984 len, (u_char *)buffer_ptr(&command), id);
988 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
992 i = client_global_request_id++;
993 if (i >= options.num_remote_forwards)
995 debug("remote forward %s for: listen %d, connect %s:%d",
996 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
997 options.remote_forwards[i].listen_port,
998 options.remote_forwards[i].connect_host,
999 options.remote_forwards[i].connect_port);
1000 if (type == SSH2_MSG_REQUEST_FAILURE)
1001 logit("Warning: remote port forwarding failed for listen "
1002 "port %d", options.remote_forwards[i].listen_port);
1006 ssh_control_listener(void)
1008 struct sockaddr_un addr;
1012 if (options.control_path == NULL ||
1013 options.control_master == SSHCTL_MASTER_NO)
1016 debug("setting up multiplex master socket");
1018 memset(&addr, '\0', sizeof(addr));
1019 addr.sun_family = AF_UNIX;
1020 addr_len = offsetof(struct sockaddr_un, sun_path) +
1021 strlen(options.control_path) + 1;
1023 if (strlcpy(addr.sun_path, options.control_path,
1024 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1025 fatal("ControlPath too long");
1027 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1028 fatal("%s socket(): %s", __func__, strerror(errno));
1030 old_umask = umask(0177);
1031 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1033 if (errno == EINVAL || errno == EADDRINUSE)
1034 fatal("ControlSocket %s already exists",
1035 options.control_path);
1037 fatal("%s bind(): %s", __func__, strerror(errno));
1041 if (listen(control_fd, 64) == -1)
1042 fatal("%s listen(): %s", __func__, strerror(errno));
1044 set_nonblock(control_fd);
1047 /* request pty/x11/agent/tcpfwd/shell for channel */
1049 ssh_session2_setup(int id, void *arg)
1051 extern char **environ;
1052 const char *display;
1053 int interactive = tty_flag;
1055 display = getenv("DISPLAY");
1056 if (options.forward_x11 && display != NULL) {
1058 /* Get reasonable local authentication information. */
1059 client_x11_get_proto(display, options.xauth_location,
1060 options.forward_x11_trusted, &proto, &data);
1061 /* Request forwarding with authentication spoofing. */
1062 debug("Requesting X11 forwarding with authentication spoofing.");
1063 x11_request_forwarding_with_spoofing(id, display, proto, data);
1065 /* XXX wait for reply */
1068 check_agent_present();
1069 if (options.forward_agent) {
1070 debug("Requesting authentication agent forwarding.");
1071 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1075 if (options.tun_open != SSH_TUNMODE_NO) {
1079 debug("Requesting tun.");
1080 if ((fd = tun_open(options.tun_local,
1081 options.tun_open)) >= 0) {
1082 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1083 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1086 #if defined(SSH_TUN_FILTER)
1087 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1088 channel_register_filter(c->self, sys_tun_infilter,
1091 packet_start(SSH2_MSG_CHANNEL_OPEN);
1092 packet_put_cstring("tun@openssh.com");
1093 packet_put_int(c->self);
1094 packet_put_int(c->local_window_max);
1095 packet_put_int(c->local_maxpacket);
1096 packet_put_int(options.tun_open);
1097 packet_put_int(options.tun_remote);
1102 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1103 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1105 packet_set_interactive(interactive);
1108 /* open new channel for a session */
1110 ssh_session2_open(void)
1113 int window, packetmax, in, out, err;
1115 if (stdin_null_flag) {
1116 in = open(_PATH_DEVNULL, O_RDONLY);
1118 in = dup(STDIN_FILENO);
1120 out = dup(STDOUT_FILENO);
1121 err = dup(STDERR_FILENO);
1123 if (in < 0 || out < 0 || err < 0)
1124 fatal("dup() in/out/err failed");
1126 /* enable nonblocking unless tty */
1134 window = CHAN_SES_WINDOW_DEFAULT;
1135 packetmax = CHAN_SES_PACKET_DEFAULT;
1141 "session", SSH_CHANNEL_OPENING, in, out, err,
1142 window, packetmax, CHAN_EXTENDED_WRITE,
1143 "client-session", /*nonblock*/0);
1145 debug3("ssh_session2_open: channel_new: %d", c->self);
1147 channel_send_open(c->self);
1149 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1159 /* XXX should be pre-session */
1160 ssh_init_forwarding();
1161 ssh_control_listener();
1163 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1164 id = ssh_session2_open();
1166 /* Execute a local command */
1167 if (options.local_command != NULL &&
1168 options.permit_local_command)
1169 ssh_local_cmd(options.local_command);
1171 /* If requested, let ssh continue in the background. */
1172 if (fork_after_authentication_flag)
1173 if (daemon(1, 1) < 0)
1174 fatal("daemon() failed: %.200s", strerror(errno));
1176 return client_loop(tty_flag, tty_flag ?
1177 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1181 load_public_identity_files(void)
1189 if (options.smartcard_device != NULL &&
1190 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1191 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1193 for (i = 0; keys[i] != NULL; i++) {
1195 memmove(&options.identity_files[1], &options.identity_files[0],
1196 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1197 memmove(&options.identity_keys[1], &options.identity_keys[0],
1198 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1199 options.num_identity_files++;
1200 options.identity_keys[0] = keys[i];
1201 options.identity_files[0] = sc_get_key_label(keys[i]);
1203 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1204 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1208 #endif /* SMARTCARD */
1209 for (; i < options.num_identity_files; i++) {
1210 filename = tilde_expand_filename(options.identity_files[i],
1212 public = key_load_public(filename, NULL);
1213 debug("identity file %s type %d", filename,
1214 public ? public->type : -1);
1215 xfree(options.identity_files[i]);
1216 options.identity_files[i] = filename;
1217 options.identity_keys[i] = public;
1222 control_client_sighandler(int signo)
1224 control_client_terminate = signo;
1228 control_client_sigrelay(int signo)
1230 if (control_server_pid > 1)
1231 kill(control_server_pid, signo);
1235 env_permitted(char *env)
1238 char name[1024], *cp;
1240 strlcpy(name, env, sizeof(name));
1241 if ((cp = strchr(name, '=')) == NULL)
1246 for (i = 0; i < options.num_send_env; i++)
1247 if (match_pattern(name, options.send_env[i]))
1254 control_client(const char *path)
1256 struct sockaddr_un addr;
1257 int i, r, fd, sock, exitval, num_env, addr_len;
1260 extern char **environ;
1263 if (mux_command == 0)
1264 mux_command = SSHMUX_COMMAND_OPEN;
1266 switch (options.control_master) {
1267 case SSHCTL_MASTER_AUTO:
1268 case SSHCTL_MASTER_AUTO_ASK:
1269 debug("auto-mux: Trying existing master");
1271 case SSHCTL_MASTER_NO:
1277 memset(&addr, '\0', sizeof(addr));
1278 addr.sun_family = AF_UNIX;
1279 addr_len = offsetof(struct sockaddr_un, sun_path) +
1282 if (strlcpy(addr.sun_path, path,
1283 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1284 fatal("ControlPath too long");
1286 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1287 fatal("%s socket(): %s", __func__, strerror(errno));
1289 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1290 if (mux_command != SSHMUX_COMMAND_OPEN) {
1291 fatal("Control socket connect(%.100s): %s", path,
1294 if (errno == ENOENT)
1295 debug("Control socket \"%.100s\" does not exist", path);
1297 error("Control socket connect(%.100s): %s", path,
1304 if (stdin_null_flag) {
1305 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1306 fatal("open(/dev/null): %s", strerror(errno));
1307 if (dup2(fd, STDIN_FILENO) == -1)
1308 fatal("dup2: %s", strerror(errno));
1309 if (fd > STDERR_FILENO)
1313 term = getenv("TERM");
1317 flags |= SSHMUX_FLAG_TTY;
1319 flags |= SSHMUX_FLAG_SUBSYS;
1320 if (options.forward_x11)
1321 flags |= SSHMUX_FLAG_X11_FWD;
1322 if (options.forward_agent)
1323 flags |= SSHMUX_FLAG_AGENT_FWD;
1327 /* Send our command to server */
1328 buffer_put_int(&m, mux_command);
1329 buffer_put_int(&m, flags);
1330 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1331 fatal("%s: msg_send", __func__);
1334 /* Get authorisation status and PID of controlee */
1335 if (ssh_msg_recv(sock, &m) == -1)
1336 fatal("%s: msg_recv", __func__);
1337 if (buffer_get_char(&m) != SSHMUX_VER)
1338 fatal("%s: wrong version", __func__);
1339 if (buffer_get_int(&m) != 1)
1340 fatal("Connection to master denied");
1341 control_server_pid = buffer_get_int(&m);
1345 switch (mux_command) {
1346 case SSHMUX_COMMAND_ALIVE_CHECK:
1347 fprintf(stderr, "Master running (pid=%d)\r\n",
1348 control_server_pid);
1350 case SSHMUX_COMMAND_TERMINATE:
1351 fprintf(stderr, "Exit request sent.\r\n");
1353 case SSHMUX_COMMAND_OPEN:
1354 /* continue below */
1357 fatal("silly mux_command %d", mux_command);
1360 /* SSHMUX_COMMAND_OPEN */
1361 buffer_put_cstring(&m, term ? term : "");
1362 buffer_append(&command, "\0", 1);
1363 buffer_put_cstring(&m, buffer_ptr(&command));
1365 if (options.num_send_env == 0 || environ == NULL) {
1366 buffer_put_int(&m, 0);
1368 /* Pass environment */
1370 for (i = 0; environ[i] != NULL; i++)
1371 if (env_permitted(environ[i]))
1372 num_env++; /* Count */
1374 buffer_put_int(&m, num_env);
1376 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1377 if (env_permitted(environ[i])) {
1379 buffer_put_cstring(&m, environ[i]);
1383 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1384 fatal("%s: msg_send", __func__);
1386 mm_send_fd(sock, STDIN_FILENO);
1387 mm_send_fd(sock, STDOUT_FILENO);
1388 mm_send_fd(sock, STDERR_FILENO);
1390 /* Wait for reply, so master has a chance to gather ttymodes */
1392 if (ssh_msg_recv(sock, &m) == -1)
1393 fatal("%s: msg_recv", __func__);
1394 if (buffer_get_char(&m) != SSHMUX_VER)
1395 fatal("%s: wrong version", __func__);
1398 signal(SIGHUP, control_client_sighandler);
1399 signal(SIGINT, control_client_sighandler);
1400 signal(SIGTERM, control_client_sighandler);
1401 signal(SIGWINCH, control_client_sigrelay);
1406 /* Stick around until the controlee closes the client_fd */
1408 for (;!control_client_terminate;) {
1409 r = read(sock, &exitval, sizeof(exitval));
1411 debug2("Received EOF from master");
1415 debug2("Received exit status from master %d", exitval);
1416 if (r == -1 && errno != EINTR)
1417 fatal("%s: read %s", __func__, strerror(errno));
1420 if (control_client_terminate)
1421 debug2("Exiting on signal %d", control_client_terminate);
1427 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1428 fprintf(stderr, "Connection to master closed.\r\n");