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.250 2005/09/13 23:40:07 djm Exp $");
45 #include <openssl/evp.h>
46 #include <openssl/err.h>
61 #include "pathnames.h"
63 #include "clientloop.h"
66 #include "sshconnect.h"
73 #include "monitor_fdpass.h"
80 extern char *__progname;
82 /* Flag indicating whether debug mode is on. This can be set on the command line. */
85 /* Flag indicating whether a tty should be allocated */
88 int force_tty_flag = 0;
90 /* don't exec a shell */
91 int no_shell_flag = 0;
94 * Flag indicating that nothing should be read from stdin. This can be set
95 * on the command line.
97 int stdin_null_flag = 0;
100 * Flag indicating that ssh should fork after authentication. This is useful
101 * so that the passphrase can be entered manually, and then ssh goes to the
104 int fork_after_authentication_flag = 0;
107 * General data structure for command line options and options configurable
108 * in configuration files. See readconf.h.
112 /* optional user configfile */
116 * Name of the host we are connecting to. This is the name given on the
117 * command line, or the HostName specified for the user-supplied name in a
118 * configuration file.
122 /* socket address the host resolves to */
123 struct sockaddr_storage hostaddr;
125 /* Private host keys. */
126 Sensitive sensitive_data;
128 /* Original real UID. */
129 uid_t original_real_uid;
130 uid_t original_effective_uid;
132 /* command to be executed */
135 /* Should we execute a command or invoke a subsystem? */
136 int subsystem_flag = 0;
138 /* # of replies received for global requests */
139 static int client_global_request_id = 0;
141 /* pid of proxycommand child process */
142 pid_t proxy_command_pid = 0;
144 /* fd to control socket */
147 /* Multiplexing control command */
148 static u_int mux_command = 0;
150 /* Only used in control client mode */
151 volatile sig_atomic_t control_client_terminate = 0;
152 u_int control_server_pid = 0;
154 /* Prints a help message to the user. This function never returns. */
160 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
161 " [-D port] [-e escape_char] [-F configfile]\n"
162 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
163 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
164 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
165 " [user@]hostname [command]\n"
170 static int ssh_session(void);
171 static int ssh_session2(void);
172 static void load_public_identity_files(void);
173 static void control_client(const char *path);
176 * Main program for the ssh client.
179 main(int ac, char **av)
181 int i, opt, exit_status;
182 char *p, *cp, *line, buf[256];
186 extern int optind, optreset;
191 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
194 __progname = ssh_get_progname(av[0]);
198 * Save the original real uid. It will be needed later (uid-swapping
199 * may clobber the real uid).
201 original_real_uid = getuid();
202 original_effective_uid = geteuid();
205 * Use uid-swapping to give up root privileges for the duration of
206 * option processing. We will re-instantiate the rights when we are
207 * ready to create the privileged port, and will permanently drop
208 * them when the port has been created (actually, when the connection
209 * has been made, as we may need to create the port several times).
213 #ifdef HAVE_SETRLIMIT
214 /* If we are installed setuid root be careful to not drop core. */
215 if (original_real_uid != original_effective_uid) {
217 rlim.rlim_cur = rlim.rlim_max = 0;
218 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
219 fatal("setrlimit failed: %.100s", strerror(errno));
223 pw = getpwuid(original_real_uid);
225 logit("You don't exist, go away!");
228 /* Take a copy of the returned structure. */
232 * Set our umask to something reasonable, as some files are created
233 * with the default umask. This will make them world-readable but
234 * writable only by the owner, which is ok for all files for which we
235 * don't set the modes explicitly.
239 /* Initialize option structure to indicate that no values have been set. */
240 initialize_options(&options);
242 /* Parse command-line arguments. */
246 while ((opt = getopt(ac, av,
247 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVXY")) != -1) {
250 options.protocol = SSH_PROTO_1;
253 options.protocol = SSH_PROTO_2;
256 options.address_family = AF_INET;
259 options.address_family = AF_INET6;
265 fork_after_authentication_flag = 1;
269 options.forward_x11 = 0;
272 options.forward_x11 = 1;
275 options.forward_x11 = 1;
276 options.forward_x11_trusted = 1;
279 options.gateway_ports = 1;
282 if (strcmp(optarg, "check") == 0)
283 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
284 else if (strcmp(optarg, "exit") == 0)
285 mux_command = SSHMUX_COMMAND_TERMINATE;
287 fatal("Invalid multiplex command.");
289 case 'P': /* deprecated */
290 options.use_privileged_port = 0;
293 options.forward_agent = 0;
296 options.forward_agent = 1;
299 options.gss_deleg_creds = 0;
302 if (stat(optarg, &st) < 0) {
303 fprintf(stderr, "Warning: Identity file %s "
304 "not accessible: %s.\n", optarg,
308 if (options.num_identity_files >=
309 SSH_MAX_IDENTITY_FILES)
310 fatal("Too many identity files specified "
311 "(max %d)", SSH_MAX_IDENTITY_FILES);
312 options.identity_files[options.num_identity_files++] =
317 options.smartcard_device = xstrdup(optarg);
319 fprintf(stderr, "no support for smartcards.\n");
328 if (debug_flag == 0) {
330 options.log_level = SYSLOG_LEVEL_DEBUG1;
332 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
338 fprintf(stderr, "%s, %s\n",
339 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
344 options.log_level = SYSLOG_LEVEL_QUIET;
347 if (optarg[0] == '^' && optarg[2] == 0 &&
348 (u_char) optarg[1] >= 64 &&
349 (u_char) optarg[1] < 128)
350 options.escape_char = (u_char) optarg[1] & 31;
351 else if (strlen(optarg) == 1)
352 options.escape_char = (u_char) optarg[0];
353 else if (strcmp(optarg, "none") == 0)
354 options.escape_char = SSH_ESCAPECHAR_NONE;
356 fprintf(stderr, "Bad escape character '%s'.\n",
362 if (ciphers_valid(optarg)) {
364 options.ciphers = xstrdup(optarg);
365 options.cipher = SSH_CIPHER_INVALID;
368 options.cipher = cipher_number(optarg);
369 if (options.cipher == -1) {
371 "Unknown cipher type '%s'\n",
375 if (options.cipher == SSH_CIPHER_3DES)
376 options.ciphers = "3des-cbc";
377 else if (options.cipher == SSH_CIPHER_BLOWFISH)
378 options.ciphers = "blowfish-cbc";
380 options.ciphers = (char *)-1;
384 if (mac_valid(optarg))
385 options.macs = xstrdup(optarg);
387 fprintf(stderr, "Unknown mac type '%s'\n",
393 if (options.control_master == SSHCTL_MASTER_YES)
394 options.control_master = SSHCTL_MASTER_ASK;
396 options.control_master = SSHCTL_MASTER_YES;
399 options.port = a2port(optarg);
400 if (options.port == 0) {
401 fprintf(stderr, "Bad port '%s'\n", optarg);
406 options.user = optarg;
410 if (parse_forward(&fwd, optarg))
411 add_local_forward(&options, &fwd);
414 "Bad local forwarding specification '%s'\n",
421 if (parse_forward(&fwd, optarg)) {
422 add_remote_forward(&options, &fwd);
425 "Bad remote forwarding specification "
432 cp = p = xstrdup(optarg);
433 memset(&fwd, '\0', sizeof(fwd));
434 fwd.connect_host = "socks";
435 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
436 fprintf(stderr, "Bad dynamic forwarding "
437 "specification '%.100s'\n", optarg);
441 fwd.listen_port = a2port(cp);
442 fwd.listen_host = cleanhostname(fwd.listen_host);
444 fwd.listen_port = a2port(fwd.listen_host);
445 fwd.listen_host = NULL;
448 if (fwd.listen_port == 0) {
449 fprintf(stderr, "Bad dynamic port '%s'\n",
453 add_local_forward(&options, &fwd);
458 options.compression = 1;
469 line = xstrdup(optarg);
470 if (process_config_line(&options, host ? host : "",
471 line, "command-line", 0, &dummy) != 0)
479 if (options.control_path != NULL)
480 free(options.control_path);
481 options.control_path = xstrdup(optarg);
484 options.bind_address = optarg;
497 if (ac > 0 && !host && **av != '-') {
498 if (strrchr(*av, '@')) {
500 cp = strrchr(p, '@');
501 if (cp == NULL || cp == p)
509 optind = optreset = 1;
515 /* Check that we got a host name. */
519 SSLeay_add_all_algorithms();
520 ERR_load_crypto_strings();
522 /* Initialize the command to execute on remote host. */
523 buffer_init(&command);
526 * Save the command to execute on the remote host in a buffer. There
527 * is no limit on the length of the command, except by the maximum
528 * packet size. Also sets the tty flag if there is no command.
531 /* No command specified - execute shell on a tty. */
533 if (subsystem_flag) {
535 "You must specify a subsystem to invoke.\n");
539 /* A command has been specified. Store it into the buffer. */
540 for (i = 0; i < ac; i++) {
542 buffer_append(&command, " ", 1);
543 buffer_append(&command, av[i], strlen(av[i]));
547 /* Cannot fork to background if no command. */
548 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
549 fatal("Cannot fork into background without a command to execute.");
551 /* Allocate a tty by default if no command specified. */
552 if (buffer_len(&command) == 0)
558 /* Do not allocate a tty if stdin is not a tty. */
559 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
561 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
566 * Initialize "log" output. Since we are the client all output
567 * actually goes to stderr.
569 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
570 SYSLOG_FACILITY_USER, 1);
573 * Read per-user configuration file. Ignore the system wide config
574 * file if the user specifies a config file on the command line.
576 if (config != NULL) {
577 if (!read_config_file(config, host, &options, 0))
578 fatal("Can't open user config file %.100s: "
579 "%.100s", config, strerror(errno));
581 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
582 _PATH_SSH_USER_CONFFILE);
583 (void)read_config_file(buf, host, &options, 1);
585 /* Read systemwide configuration file after use config. */
586 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
590 /* Fill configuration defaults. */
591 fill_default_options(&options);
593 channel_set_af(options.address_family);
596 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
600 if (options.user == NULL)
601 options.user = xstrdup(pw->pw_name);
603 if (options.hostname != NULL)
604 host = options.hostname;
606 /* force lowercase for hostkey matching */
607 if (options.host_key_alias != NULL) {
608 for (p = options.host_key_alias; *p; p++)
613 /* Get default port if port has not been set. */
614 if (options.port == 0) {
615 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
616 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
619 if (options.proxy_command != NULL &&
620 strcmp(options.proxy_command, "none") == 0)
621 options.proxy_command = NULL;
622 if (options.control_path != NULL &&
623 strcmp(options.control_path, "none") == 0)
624 options.control_path = NULL;
626 if (options.control_path != NULL) {
627 snprintf(buf, sizeof(buf), "%d", options.port);
628 cp = tilde_expand_filename(options.control_path,
630 options.control_path = percent_expand(cp, "p", buf, "h", host,
631 "r", options.user, (char *)NULL);
634 if (mux_command != 0 && options.control_path == NULL)
635 fatal("No ControlPath specified for \"-O\" command");
636 if (options.control_path != NULL)
637 control_client(options.control_path);
639 /* Open a connection to the remote host. */
640 if (ssh_connect(host, &hostaddr, options.port,
641 options.address_family, options.connection_attempts,
643 options.use_privileged_port,
645 original_effective_uid == 0 && options.use_privileged_port,
647 options.proxy_command) != 0)
651 * If we successfully made the connection, load the host private key
652 * in case we will need it later for combined rsa-rhosts
653 * authentication. This must be done before releasing extra
654 * privileges, because the file is only readable by root.
655 * If we cannot access the private keys, load the public keys
656 * instead and try to execute the ssh-keysign helper instead.
658 sensitive_data.nkeys = 0;
659 sensitive_data.keys = NULL;
660 sensitive_data.external_keysign = 0;
661 if (options.rhosts_rsa_authentication ||
662 options.hostbased_authentication) {
663 sensitive_data.nkeys = 3;
664 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
668 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
669 _PATH_HOST_KEY_FILE, "", NULL);
670 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
671 _PATH_HOST_DSA_KEY_FILE, "", NULL);
672 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
673 _PATH_HOST_RSA_KEY_FILE, "", NULL);
676 if (options.hostbased_authentication == 1 &&
677 sensitive_data.keys[0] == NULL &&
678 sensitive_data.keys[1] == NULL &&
679 sensitive_data.keys[2] == NULL) {
680 sensitive_data.keys[1] = key_load_public(
681 _PATH_HOST_DSA_KEY_FILE, NULL);
682 sensitive_data.keys[2] = key_load_public(
683 _PATH_HOST_RSA_KEY_FILE, NULL);
684 sensitive_data.external_keysign = 1;
688 * Get rid of any extra privileges that we may have. We will no
689 * longer need them. Also, extra privileges could make it very hard
690 * to read identity files and other non-world-readable files from the
691 * user's home directory if it happens to be on a NFS volume where
692 * root is mapped to nobody.
694 if (original_effective_uid == 0) {
696 permanently_set_uid(pw);
700 * Now that we are back to our own permissions, create ~/.ssh
701 * directory if it doesn\'t already exist.
703 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
704 if (stat(buf, &st) < 0)
705 if (mkdir(buf, 0700) < 0)
706 error("Could not create directory '%.200s'.", buf);
708 /* load options.identity_files */
709 load_public_identity_files();
711 /* Expand ~ in known host file names. */
713 options.system_hostfile =
714 tilde_expand_filename(options.system_hostfile, original_real_uid);
715 options.user_hostfile =
716 tilde_expand_filename(options.user_hostfile, original_real_uid);
717 options.system_hostfile2 =
718 tilde_expand_filename(options.system_hostfile2, original_real_uid);
719 options.user_hostfile2 =
720 tilde_expand_filename(options.user_hostfile2, original_real_uid);
722 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
724 /* Log into the remote system. This never returns if the login fails. */
725 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
727 /* We no longer need the private host keys. Clear them now. */
728 if (sensitive_data.nkeys != 0) {
729 for (i = 0; i < sensitive_data.nkeys; i++) {
730 if (sensitive_data.keys[i] != NULL) {
731 /* Destroys contents safely */
732 debug3("clear hostkey %d", i);
733 key_free(sensitive_data.keys[i]);
734 sensitive_data.keys[i] = NULL;
737 xfree(sensitive_data.keys);
739 for (i = 0; i < options.num_identity_files; i++) {
740 if (options.identity_files[i]) {
741 xfree(options.identity_files[i]);
742 options.identity_files[i] = NULL;
744 if (options.identity_keys[i]) {
745 key_free(options.identity_keys[i]);
746 options.identity_keys[i] = NULL;
750 exit_status = compat20 ? ssh_session2() : ssh_session();
753 if (options.control_path != NULL && control_fd != -1)
754 unlink(options.control_path);
757 * Send SIGHUP to proxy command if used. We don't wait() in
758 * case it hangs and instead rely on init to reap the child
760 if (proxy_command_pid > 1)
761 kill(proxy_command_pid, SIGHUP);
767 ssh_init_forwarding(void)
772 /* Initiate local TCP/IP port forwardings. */
773 for (i = 0; i < options.num_local_forwards; i++) {
774 debug("Local connections to %.200s:%d forwarded to remote "
776 (options.local_forwards[i].listen_host == NULL) ?
777 (options.gateway_ports ? "*" : "LOCALHOST") :
778 options.local_forwards[i].listen_host,
779 options.local_forwards[i].listen_port,
780 options.local_forwards[i].connect_host,
781 options.local_forwards[i].connect_port);
782 success += channel_setup_local_fwd_listener(
783 options.local_forwards[i].listen_host,
784 options.local_forwards[i].listen_port,
785 options.local_forwards[i].connect_host,
786 options.local_forwards[i].connect_port,
787 options.gateway_ports);
789 if (i > 0 && success == 0)
790 error("Could not request local forwarding.");
792 /* Initiate remote TCP/IP port forwardings. */
793 for (i = 0; i < options.num_remote_forwards; i++) {
794 debug("Remote connections from %.200s:%d forwarded to "
795 "local address %.200s:%d",
796 (options.remote_forwards[i].listen_host == NULL) ?
797 (options.gateway_ports ? "*" : "LOCALHOST") :
798 options.remote_forwards[i].listen_host,
799 options.remote_forwards[i].listen_port,
800 options.remote_forwards[i].connect_host,
801 options.remote_forwards[i].connect_port);
802 channel_request_remote_forwarding(
803 options.remote_forwards[i].listen_host,
804 options.remote_forwards[i].listen_port,
805 options.remote_forwards[i].connect_host,
806 options.remote_forwards[i].connect_port);
811 check_agent_present(void)
813 if (options.forward_agent) {
814 /* Clear agent forwarding if we don\'t have an agent. */
815 if (!ssh_agent_present())
816 options.forward_agent = 0;
830 /* Enable compression if requested. */
831 if (options.compression) {
832 debug("Requesting compression at level %d.", options.compression_level);
834 if (options.compression_level < 1 || options.compression_level > 9)
835 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
837 /* Send the request. */
838 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
839 packet_put_int(options.compression_level);
842 type = packet_read();
843 if (type == SSH_SMSG_SUCCESS)
844 packet_start_compression(options.compression_level);
845 else if (type == SSH_SMSG_FAILURE)
846 logit("Warning: Remote host refused compression.");
848 packet_disconnect("Protocol error waiting for compression response.");
850 /* Allocate a pseudo tty if appropriate. */
852 debug("Requesting pty.");
854 /* Start the packet. */
855 packet_start(SSH_CMSG_REQUEST_PTY);
857 /* Store TERM in the packet. There is no limit on the
858 length of the string. */
862 packet_put_cstring(cp);
864 /* Store window size in the packet. */
865 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
866 memset(&ws, 0, sizeof(ws));
867 packet_put_int(ws.ws_row);
868 packet_put_int(ws.ws_col);
869 packet_put_int(ws.ws_xpixel);
870 packet_put_int(ws.ws_ypixel);
872 /* Store tty modes in the packet. */
873 tty_make_modes(fileno(stdin), NULL);
875 /* Send the packet, and wait for it to leave. */
879 /* Read response from the server. */
880 type = packet_read();
881 if (type == SSH_SMSG_SUCCESS) {
884 } else if (type == SSH_SMSG_FAILURE)
885 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
887 packet_disconnect("Protocol error waiting for pty request response.");
889 /* Request X11 forwarding if enabled and DISPLAY is set. */
890 display = getenv("DISPLAY");
891 if (options.forward_x11 && display != NULL) {
893 /* Get reasonable local authentication information. */
894 client_x11_get_proto(display, options.xauth_location,
895 options.forward_x11_trusted, &proto, &data);
896 /* Request forwarding with authentication spoofing. */
897 debug("Requesting X11 forwarding with authentication spoofing.");
898 x11_request_forwarding_with_spoofing(0, display, proto, data);
900 /* Read response from the server. */
901 type = packet_read();
902 if (type == SSH_SMSG_SUCCESS) {
904 } else if (type == SSH_SMSG_FAILURE) {
905 logit("Warning: Remote host denied X11 forwarding.");
907 packet_disconnect("Protocol error waiting for X11 forwarding");
910 /* Tell the packet module whether this is an interactive session. */
911 packet_set_interactive(interactive);
913 /* Request authentication agent forwarding if appropriate. */
914 check_agent_present();
916 if (options.forward_agent) {
917 debug("Requesting authentication agent forwarding.");
918 auth_request_forwarding();
920 /* Read response from the server. */
921 type = packet_read();
923 if (type != SSH_SMSG_SUCCESS)
924 logit("Warning: Remote host denied authentication agent forwarding.");
927 /* Initiate port forwardings. */
928 ssh_init_forwarding();
930 /* If requested, let ssh continue in the background. */
931 if (fork_after_authentication_flag)
932 if (daemon(1, 1) < 0)
933 fatal("daemon() failed: %.200s", strerror(errno));
936 * If a command was specified on the command line, execute the
937 * command now. Otherwise request the server to start a shell.
939 if (buffer_len(&command) > 0) {
940 int len = buffer_len(&command);
943 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
944 packet_start(SSH_CMSG_EXEC_CMD);
945 packet_put_string(buffer_ptr(&command), buffer_len(&command));
949 debug("Requesting shell.");
950 packet_start(SSH_CMSG_EXEC_SHELL);
955 /* Enter the interactive session. */
956 return client_loop(have_tty, tty_flag ?
957 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
961 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
965 id = packet_get_int();
966 len = buffer_len(&command);
970 if (type == SSH2_MSG_CHANNEL_FAILURE)
971 fatal("Request for subsystem '%.*s' failed on channel %d",
972 len, (u_char *)buffer_ptr(&command), id);
976 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
980 i = client_global_request_id++;
981 if (i >= options.num_remote_forwards)
983 debug("remote forward %s for: listen %d, connect %s:%d",
984 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
985 options.remote_forwards[i].listen_port,
986 options.remote_forwards[i].connect_host,
987 options.remote_forwards[i].connect_port);
988 if (type == SSH2_MSG_REQUEST_FAILURE)
989 logit("Warning: remote port forwarding failed for listen "
990 "port %d", options.remote_forwards[i].listen_port);
994 ssh_control_listener(void)
996 struct sockaddr_un addr;
1000 if (options.control_path == NULL ||
1001 options.control_master == SSHCTL_MASTER_NO)
1004 debug("setting up multiplex master socket");
1006 memset(&addr, '\0', sizeof(addr));
1007 addr.sun_family = AF_UNIX;
1008 addr_len = offsetof(struct sockaddr_un, sun_path) +
1009 strlen(options.control_path) + 1;
1011 if (strlcpy(addr.sun_path, options.control_path,
1012 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1013 fatal("ControlPath too long");
1015 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1016 fatal("%s socket(): %s\n", __func__, strerror(errno));
1018 old_umask = umask(0177);
1019 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1021 if (errno == EINVAL || errno == EADDRINUSE)
1022 fatal("ControlSocket %s already exists",
1023 options.control_path);
1025 fatal("%s bind(): %s\n", __func__, strerror(errno));
1029 if (listen(control_fd, 64) == -1)
1030 fatal("%s listen(): %s\n", __func__, strerror(errno));
1032 set_nonblock(control_fd);
1035 /* request pty/x11/agent/tcpfwd/shell for channel */
1037 ssh_session2_setup(int id, void *arg)
1039 extern char **environ;
1040 const char *display;
1041 int interactive = tty_flag;
1043 display = getenv("DISPLAY");
1044 if (options.forward_x11 && display != NULL) {
1046 /* Get reasonable local authentication information. */
1047 client_x11_get_proto(display, options.xauth_location,
1048 options.forward_x11_trusted, &proto, &data);
1049 /* Request forwarding with authentication spoofing. */
1050 debug("Requesting X11 forwarding with authentication spoofing.");
1051 x11_request_forwarding_with_spoofing(id, display, proto, data);
1053 /* XXX wait for reply */
1056 check_agent_present();
1057 if (options.forward_agent) {
1058 debug("Requesting authentication agent forwarding.");
1059 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1063 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1064 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1066 packet_set_interactive(interactive);
1069 /* open new channel for a session */
1071 ssh_session2_open(void)
1074 int window, packetmax, in, out, err;
1076 if (stdin_null_flag) {
1077 in = open(_PATH_DEVNULL, O_RDONLY);
1079 in = dup(STDIN_FILENO);
1081 out = dup(STDOUT_FILENO);
1082 err = dup(STDERR_FILENO);
1084 if (in < 0 || out < 0 || err < 0)
1085 fatal("dup() in/out/err failed");
1087 /* enable nonblocking unless tty */
1095 window = CHAN_SES_WINDOW_DEFAULT;
1096 packetmax = CHAN_SES_PACKET_DEFAULT;
1102 "session", SSH_CHANNEL_OPENING, in, out, err,
1103 window, packetmax, CHAN_EXTENDED_WRITE,
1104 "client-session", /*nonblock*/0);
1106 debug3("ssh_session2_open: channel_new: %d", c->self);
1108 channel_send_open(c->self);
1110 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1120 /* XXX should be pre-session */
1121 ssh_init_forwarding();
1122 ssh_control_listener();
1124 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1125 id = ssh_session2_open();
1127 /* If requested, let ssh continue in the background. */
1128 if (fork_after_authentication_flag)
1129 if (daemon(1, 1) < 0)
1130 fatal("daemon() failed: %.200s", strerror(errno));
1132 return client_loop(tty_flag, tty_flag ?
1133 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1137 load_public_identity_files(void)
1145 if (options.smartcard_device != NULL &&
1146 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1147 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1149 for (i = 0; keys[i] != NULL; i++) {
1151 memmove(&options.identity_files[1], &options.identity_files[0],
1152 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1153 memmove(&options.identity_keys[1], &options.identity_keys[0],
1154 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1155 options.num_identity_files++;
1156 options.identity_keys[0] = keys[i];
1157 options.identity_files[0] = sc_get_key_label(keys[i]);
1159 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1160 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1164 #endif /* SMARTCARD */
1165 for (; i < options.num_identity_files; i++) {
1166 filename = tilde_expand_filename(options.identity_files[i],
1168 public = key_load_public(filename, NULL);
1169 debug("identity file %s type %d", filename,
1170 public ? public->type : -1);
1171 xfree(options.identity_files[i]);
1172 options.identity_files[i] = filename;
1173 options.identity_keys[i] = public;
1178 control_client_sighandler(int signo)
1180 control_client_terminate = signo;
1184 control_client_sigrelay(int signo)
1186 if (control_server_pid > 1)
1187 kill(control_server_pid, signo);
1191 env_permitted(char *env)
1194 char name[1024], *cp;
1196 strlcpy(name, env, sizeof(name));
1197 if ((cp = strchr(name, '=')) == NULL)
1202 for (i = 0; i < options.num_send_env; i++)
1203 if (match_pattern(name, options.send_env[i]))
1210 control_client(const char *path)
1212 struct sockaddr_un addr;
1213 int i, r, fd, sock, exitval, num_env, addr_len;
1216 extern char **environ;
1219 if (mux_command == 0)
1220 mux_command = SSHMUX_COMMAND_OPEN;
1222 switch (options.control_master) {
1223 case SSHCTL_MASTER_AUTO:
1224 case SSHCTL_MASTER_AUTO_ASK:
1225 debug("auto-mux: Trying existing master");
1227 case SSHCTL_MASTER_NO:
1233 memset(&addr, '\0', sizeof(addr));
1234 addr.sun_family = AF_UNIX;
1235 addr_len = offsetof(struct sockaddr_un, sun_path) +
1238 if (strlcpy(addr.sun_path, path,
1239 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1240 fatal("ControlPath too long");
1242 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1243 fatal("%s socket(): %s", __func__, strerror(errno));
1245 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1246 if (mux_command != SSHMUX_COMMAND_OPEN) {
1247 fatal("Control socket connect(%.100s): %s", path,
1250 if (errno == ENOENT)
1251 debug("Control socket \"%.100s\" does not exist", path);
1253 error("Control socket connect(%.100s): %s", path,
1260 if (stdin_null_flag) {
1261 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1262 fatal("open(/dev/null): %s", strerror(errno));
1263 if (dup2(fd, STDIN_FILENO) == -1)
1264 fatal("dup2: %s", strerror(errno));
1265 if (fd > STDERR_FILENO)
1269 term = getenv("TERM");
1273 flags |= SSHMUX_FLAG_TTY;
1275 flags |= SSHMUX_FLAG_SUBSYS;
1276 if (options.forward_x11)
1277 flags |= SSHMUX_FLAG_X11_FWD;
1278 if (options.forward_agent)
1279 flags |= SSHMUX_FLAG_AGENT_FWD;
1283 /* Send our command to server */
1284 buffer_put_int(&m, mux_command);
1285 buffer_put_int(&m, flags);
1286 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1287 fatal("%s: msg_send", __func__);
1290 /* Get authorisation status and PID of controlee */
1291 if (ssh_msg_recv(sock, &m) == -1)
1292 fatal("%s: msg_recv", __func__);
1293 if (buffer_get_char(&m) != SSHMUX_VER)
1294 fatal("%s: wrong version", __func__);
1295 if (buffer_get_int(&m) != 1)
1296 fatal("Connection to master denied");
1297 control_server_pid = buffer_get_int(&m);
1301 switch (mux_command) {
1302 case SSHMUX_COMMAND_ALIVE_CHECK:
1303 fprintf(stderr, "Master running (pid=%d)\r\n",
1304 control_server_pid);
1306 case SSHMUX_COMMAND_TERMINATE:
1307 fprintf(stderr, "Exit request sent.\r\n");
1309 case SSHMUX_COMMAND_OPEN:
1310 /* continue below */
1313 fatal("silly mux_command %d", mux_command);
1316 /* SSHMUX_COMMAND_OPEN */
1317 buffer_put_cstring(&m, term ? term : "");
1318 buffer_append(&command, "\0", 1);
1319 buffer_put_cstring(&m, buffer_ptr(&command));
1321 if (options.num_send_env == 0 || environ == NULL) {
1322 buffer_put_int(&m, 0);
1324 /* Pass environment */
1326 for (i = 0; environ[i] != NULL; i++)
1327 if (env_permitted(environ[i]))
1328 num_env++; /* Count */
1330 buffer_put_int(&m, num_env);
1332 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1333 if (env_permitted(environ[i])) {
1335 buffer_put_cstring(&m, environ[i]);
1339 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1340 fatal("%s: msg_send", __func__);
1342 mm_send_fd(sock, STDIN_FILENO);
1343 mm_send_fd(sock, STDOUT_FILENO);
1344 mm_send_fd(sock, STDERR_FILENO);
1346 /* Wait for reply, so master has a chance to gather ttymodes */
1348 if (ssh_msg_recv(sock, &m) == -1)
1349 fatal("%s: msg_recv", __func__);
1350 if (buffer_get_char(&m) != SSHMUX_VER)
1351 fatal("%s: wrong version", __func__);
1354 signal(SIGHUP, control_client_sighandler);
1355 signal(SIGINT, control_client_sighandler);
1356 signal(SIGTERM, control_client_sighandler);
1357 signal(SIGWINCH, control_client_sigrelay);
1362 /* Stick around until the controlee closes the client_fd */
1364 for (;!control_client_terminate;) {
1365 r = read(sock, &exitval, sizeof(exitval));
1367 debug2("Received EOF from master");
1371 debug2("Received exit status from master %d", exitval);
1372 if (r == -1 && errno != EINTR)
1373 fatal("%s: read %s", __func__, strerror(errno));
1376 if (control_client_terminate)
1377 debug2("Exiting on signal %d", control_client_terminate);
1383 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1384 fprintf(stderr, "Connection to master closed.\r\n");