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.253 2005/10/30 04:03:24 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 [bind_address:]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 "LOCALHOST" : options.remote_forwards[i].listen_host,
798 options.remote_forwards[i].listen_port,
799 options.remote_forwards[i].connect_host,
800 options.remote_forwards[i].connect_port);
801 channel_request_remote_forwarding(
802 options.remote_forwards[i].listen_host,
803 options.remote_forwards[i].listen_port,
804 options.remote_forwards[i].connect_host,
805 options.remote_forwards[i].connect_port);
810 check_agent_present(void)
812 if (options.forward_agent) {
813 /* Clear agent forwarding if we don\'t have an agent. */
814 if (!ssh_agent_present())
815 options.forward_agent = 0;
829 /* Enable compression if requested. */
830 if (options.compression) {
831 debug("Requesting compression at level %d.", options.compression_level);
833 if (options.compression_level < 1 || options.compression_level > 9)
834 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
836 /* Send the request. */
837 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
838 packet_put_int(options.compression_level);
841 type = packet_read();
842 if (type == SSH_SMSG_SUCCESS)
843 packet_start_compression(options.compression_level);
844 else if (type == SSH_SMSG_FAILURE)
845 logit("Warning: Remote host refused compression.");
847 packet_disconnect("Protocol error waiting for compression response.");
849 /* Allocate a pseudo tty if appropriate. */
851 debug("Requesting pty.");
853 /* Start the packet. */
854 packet_start(SSH_CMSG_REQUEST_PTY);
856 /* Store TERM in the packet. There is no limit on the
857 length of the string. */
861 packet_put_cstring(cp);
863 /* Store window size in the packet. */
864 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
865 memset(&ws, 0, sizeof(ws));
866 packet_put_int(ws.ws_row);
867 packet_put_int(ws.ws_col);
868 packet_put_int(ws.ws_xpixel);
869 packet_put_int(ws.ws_ypixel);
871 /* Store tty modes in the packet. */
872 tty_make_modes(fileno(stdin), NULL);
874 /* Send the packet, and wait for it to leave. */
878 /* Read response from the server. */
879 type = packet_read();
880 if (type == SSH_SMSG_SUCCESS) {
883 } else if (type == SSH_SMSG_FAILURE)
884 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
886 packet_disconnect("Protocol error waiting for pty request response.");
888 /* Request X11 forwarding if enabled and DISPLAY is set. */
889 display = getenv("DISPLAY");
890 if (options.forward_x11 && display != NULL) {
892 /* Get reasonable local authentication information. */
893 client_x11_get_proto(display, options.xauth_location,
894 options.forward_x11_trusted, &proto, &data);
895 /* Request forwarding with authentication spoofing. */
896 debug("Requesting X11 forwarding with authentication spoofing.");
897 x11_request_forwarding_with_spoofing(0, display, proto, data);
899 /* Read response from the server. */
900 type = packet_read();
901 if (type == SSH_SMSG_SUCCESS) {
903 } else if (type == SSH_SMSG_FAILURE) {
904 logit("Warning: Remote host denied X11 forwarding.");
906 packet_disconnect("Protocol error waiting for X11 forwarding");
909 /* Tell the packet module whether this is an interactive session. */
910 packet_set_interactive(interactive);
912 /* Request authentication agent forwarding if appropriate. */
913 check_agent_present();
915 if (options.forward_agent) {
916 debug("Requesting authentication agent forwarding.");
917 auth_request_forwarding();
919 /* Read response from the server. */
920 type = packet_read();
922 if (type != SSH_SMSG_SUCCESS)
923 logit("Warning: Remote host denied authentication agent forwarding.");
926 /* Initiate port forwardings. */
927 ssh_init_forwarding();
929 /* If requested, let ssh continue in the background. */
930 if (fork_after_authentication_flag)
931 if (daemon(1, 1) < 0)
932 fatal("daemon() failed: %.200s", strerror(errno));
935 * If a command was specified on the command line, execute the
936 * command now. Otherwise request the server to start a shell.
938 if (buffer_len(&command) > 0) {
939 int len = buffer_len(&command);
942 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
943 packet_start(SSH_CMSG_EXEC_CMD);
944 packet_put_string(buffer_ptr(&command), buffer_len(&command));
948 debug("Requesting shell.");
949 packet_start(SSH_CMSG_EXEC_SHELL);
954 /* Enter the interactive session. */
955 return client_loop(have_tty, tty_flag ?
956 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
960 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
964 id = packet_get_int();
965 len = buffer_len(&command);
969 if (type == SSH2_MSG_CHANNEL_FAILURE)
970 fatal("Request for subsystem '%.*s' failed on channel %d",
971 len, (u_char *)buffer_ptr(&command), id);
975 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
979 i = client_global_request_id++;
980 if (i >= options.num_remote_forwards)
982 debug("remote forward %s for: listen %d, connect %s:%d",
983 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
984 options.remote_forwards[i].listen_port,
985 options.remote_forwards[i].connect_host,
986 options.remote_forwards[i].connect_port);
987 if (type == SSH2_MSG_REQUEST_FAILURE)
988 logit("Warning: remote port forwarding failed for listen "
989 "port %d", options.remote_forwards[i].listen_port);
993 ssh_control_listener(void)
995 struct sockaddr_un addr;
999 if (options.control_path == NULL ||
1000 options.control_master == SSHCTL_MASTER_NO)
1003 debug("setting up multiplex master socket");
1005 memset(&addr, '\0', sizeof(addr));
1006 addr.sun_family = AF_UNIX;
1007 addr_len = offsetof(struct sockaddr_un, sun_path) +
1008 strlen(options.control_path) + 1;
1010 if (strlcpy(addr.sun_path, options.control_path,
1011 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1012 fatal("ControlPath too long");
1014 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1015 fatal("%s socket(): %s", __func__, strerror(errno));
1017 old_umask = umask(0177);
1018 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1020 if (errno == EINVAL || errno == EADDRINUSE)
1021 fatal("ControlSocket %s already exists",
1022 options.control_path);
1024 fatal("%s bind(): %s", __func__, strerror(errno));
1028 if (listen(control_fd, 64) == -1)
1029 fatal("%s listen(): %s", __func__, strerror(errno));
1031 set_nonblock(control_fd);
1034 /* request pty/x11/agent/tcpfwd/shell for channel */
1036 ssh_session2_setup(int id, void *arg)
1038 extern char **environ;
1039 const char *display;
1040 int interactive = tty_flag;
1042 display = getenv("DISPLAY");
1043 if (options.forward_x11 && display != NULL) {
1045 /* Get reasonable local authentication information. */
1046 client_x11_get_proto(display, options.xauth_location,
1047 options.forward_x11_trusted, &proto, &data);
1048 /* Request forwarding with authentication spoofing. */
1049 debug("Requesting X11 forwarding with authentication spoofing.");
1050 x11_request_forwarding_with_spoofing(id, display, proto, data);
1052 /* XXX wait for reply */
1055 check_agent_present();
1056 if (options.forward_agent) {
1057 debug("Requesting authentication agent forwarding.");
1058 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1062 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1063 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1065 packet_set_interactive(interactive);
1068 /* open new channel for a session */
1070 ssh_session2_open(void)
1073 int window, packetmax, in, out, err;
1075 if (stdin_null_flag) {
1076 in = open(_PATH_DEVNULL, O_RDONLY);
1078 in = dup(STDIN_FILENO);
1080 out = dup(STDOUT_FILENO);
1081 err = dup(STDERR_FILENO);
1083 if (in < 0 || out < 0 || err < 0)
1084 fatal("dup() in/out/err failed");
1086 /* enable nonblocking unless tty */
1094 window = CHAN_SES_WINDOW_DEFAULT;
1095 packetmax = CHAN_SES_PACKET_DEFAULT;
1101 "session", SSH_CHANNEL_OPENING, in, out, err,
1102 window, packetmax, CHAN_EXTENDED_WRITE,
1103 "client-session", /*nonblock*/0);
1105 debug3("ssh_session2_open: channel_new: %d", c->self);
1107 channel_send_open(c->self);
1109 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1119 /* XXX should be pre-session */
1120 ssh_init_forwarding();
1121 ssh_control_listener();
1123 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1124 id = ssh_session2_open();
1126 /* If requested, let ssh continue in the background. */
1127 if (fork_after_authentication_flag)
1128 if (daemon(1, 1) < 0)
1129 fatal("daemon() failed: %.200s", strerror(errno));
1131 return client_loop(tty_flag, tty_flag ?
1132 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1136 load_public_identity_files(void)
1144 if (options.smartcard_device != NULL &&
1145 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1146 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1148 for (i = 0; keys[i] != NULL; i++) {
1150 memmove(&options.identity_files[1], &options.identity_files[0],
1151 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1152 memmove(&options.identity_keys[1], &options.identity_keys[0],
1153 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1154 options.num_identity_files++;
1155 options.identity_keys[0] = keys[i];
1156 options.identity_files[0] = sc_get_key_label(keys[i]);
1158 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1159 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1163 #endif /* SMARTCARD */
1164 for (; i < options.num_identity_files; i++) {
1165 filename = tilde_expand_filename(options.identity_files[i],
1167 public = key_load_public(filename, NULL);
1168 debug("identity file %s type %d", filename,
1169 public ? public->type : -1);
1170 xfree(options.identity_files[i]);
1171 options.identity_files[i] = filename;
1172 options.identity_keys[i] = public;
1177 control_client_sighandler(int signo)
1179 control_client_terminate = signo;
1183 control_client_sigrelay(int signo)
1185 if (control_server_pid > 1)
1186 kill(control_server_pid, signo);
1190 env_permitted(char *env)
1193 char name[1024], *cp;
1195 strlcpy(name, env, sizeof(name));
1196 if ((cp = strchr(name, '=')) == NULL)
1201 for (i = 0; i < options.num_send_env; i++)
1202 if (match_pattern(name, options.send_env[i]))
1209 control_client(const char *path)
1211 struct sockaddr_un addr;
1212 int i, r, fd, sock, exitval, num_env, addr_len;
1215 extern char **environ;
1218 if (mux_command == 0)
1219 mux_command = SSHMUX_COMMAND_OPEN;
1221 switch (options.control_master) {
1222 case SSHCTL_MASTER_AUTO:
1223 case SSHCTL_MASTER_AUTO_ASK:
1224 debug("auto-mux: Trying existing master");
1226 case SSHCTL_MASTER_NO:
1232 memset(&addr, '\0', sizeof(addr));
1233 addr.sun_family = AF_UNIX;
1234 addr_len = offsetof(struct sockaddr_un, sun_path) +
1237 if (strlcpy(addr.sun_path, path,
1238 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1239 fatal("ControlPath too long");
1241 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1242 fatal("%s socket(): %s", __func__, strerror(errno));
1244 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1245 if (mux_command != SSHMUX_COMMAND_OPEN) {
1246 fatal("Control socket connect(%.100s): %s", path,
1249 if (errno == ENOENT)
1250 debug("Control socket \"%.100s\" does not exist", path);
1252 error("Control socket connect(%.100s): %s", path,
1259 if (stdin_null_flag) {
1260 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1261 fatal("open(/dev/null): %s", strerror(errno));
1262 if (dup2(fd, STDIN_FILENO) == -1)
1263 fatal("dup2: %s", strerror(errno));
1264 if (fd > STDERR_FILENO)
1268 term = getenv("TERM");
1272 flags |= SSHMUX_FLAG_TTY;
1274 flags |= SSHMUX_FLAG_SUBSYS;
1275 if (options.forward_x11)
1276 flags |= SSHMUX_FLAG_X11_FWD;
1277 if (options.forward_agent)
1278 flags |= SSHMUX_FLAG_AGENT_FWD;
1282 /* Send our command to server */
1283 buffer_put_int(&m, mux_command);
1284 buffer_put_int(&m, flags);
1285 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1286 fatal("%s: msg_send", __func__);
1289 /* Get authorisation status and PID of controlee */
1290 if (ssh_msg_recv(sock, &m) == -1)
1291 fatal("%s: msg_recv", __func__);
1292 if (buffer_get_char(&m) != SSHMUX_VER)
1293 fatal("%s: wrong version", __func__);
1294 if (buffer_get_int(&m) != 1)
1295 fatal("Connection to master denied");
1296 control_server_pid = buffer_get_int(&m);
1300 switch (mux_command) {
1301 case SSHMUX_COMMAND_ALIVE_CHECK:
1302 fprintf(stderr, "Master running (pid=%d)\r\n",
1303 control_server_pid);
1305 case SSHMUX_COMMAND_TERMINATE:
1306 fprintf(stderr, "Exit request sent.\r\n");
1308 case SSHMUX_COMMAND_OPEN:
1309 /* continue below */
1312 fatal("silly mux_command %d", mux_command);
1315 /* SSHMUX_COMMAND_OPEN */
1316 buffer_put_cstring(&m, term ? term : "");
1317 buffer_append(&command, "\0", 1);
1318 buffer_put_cstring(&m, buffer_ptr(&command));
1320 if (options.num_send_env == 0 || environ == NULL) {
1321 buffer_put_int(&m, 0);
1323 /* Pass environment */
1325 for (i = 0; environ[i] != NULL; i++)
1326 if (env_permitted(environ[i]))
1327 num_env++; /* Count */
1329 buffer_put_int(&m, num_env);
1331 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1332 if (env_permitted(environ[i])) {
1334 buffer_put_cstring(&m, environ[i]);
1338 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1339 fatal("%s: msg_send", __func__);
1341 mm_send_fd(sock, STDIN_FILENO);
1342 mm_send_fd(sock, STDOUT_FILENO);
1343 mm_send_fd(sock, STDERR_FILENO);
1345 /* Wait for reply, so master has a chance to gather ttymodes */
1347 if (ssh_msg_recv(sock, &m) == -1)
1348 fatal("%s: msg_recv", __func__);
1349 if (buffer_get_char(&m) != SSHMUX_VER)
1350 fatal("%s: wrong version", __func__);
1353 signal(SIGHUP, control_client_sighandler);
1354 signal(SIGINT, control_client_sighandler);
1355 signal(SIGTERM, control_client_sighandler);
1356 signal(SIGWINCH, control_client_sigrelay);
1361 /* Stick around until the controlee closes the client_fd */
1363 for (;!control_client_terminate;) {
1364 r = read(sock, &exitval, sizeof(exitval));
1366 debug2("Received EOF from master");
1370 debug2("Received exit status from master %d", exitval);
1371 if (r == -1 && errno != EINTR)
1372 fatal("%s: read %s", __func__, strerror(errno));
1375 if (control_client_terminate)
1376 debug2("Exiting on signal %d", control_client_terminate);
1382 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1383 fprintf(stderr, "Connection to master closed.\r\n");