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.261 2006/02/12 06:45:34 djm Exp $");
45 #include <sys/resource.h>
46 #include <sys/ioctl.h>
50 #include <openssl/evp.h>
51 #include <openssl/err.h>
66 #include "pathnames.h"
68 #include "clientloop.h"
71 #include "sshconnect.h"
78 #include "monitor_fdpass.h"
85 extern char *__progname;
87 /* Flag indicating whether debug mode is on. This can be set on the command line. */
90 /* Flag indicating whether a tty should be allocated */
93 int force_tty_flag = 0;
95 /* don't exec a shell */
96 int no_shell_flag = 0;
99 * Flag indicating that nothing should be read from stdin. This can be set
100 * on the command line.
102 int stdin_null_flag = 0;
105 * Flag indicating that ssh should fork after authentication. This is useful
106 * so that the passphrase can be entered manually, and then ssh goes to the
109 int fork_after_authentication_flag = 0;
112 * General data structure for command line options and options configurable
113 * in configuration files. See readconf.h.
117 /* optional user configfile */
121 * Name of the host we are connecting to. This is the name given on the
122 * command line, or the HostName specified for the user-supplied name in a
123 * configuration file.
127 /* socket address the host resolves to */
128 struct sockaddr_storage hostaddr;
130 /* Private host keys. */
131 Sensitive sensitive_data;
133 /* Original real UID. */
134 uid_t original_real_uid;
135 uid_t original_effective_uid;
137 /* command to be executed */
140 /* Should we execute a command or invoke a subsystem? */
141 int subsystem_flag = 0;
143 /* # of replies received for global requests */
144 static int client_global_request_id = 0;
146 /* pid of proxycommand child process */
147 pid_t proxy_command_pid = 0;
149 /* fd to control socket */
152 /* Multiplexing control command */
153 static u_int mux_command = 0;
155 /* Only used in control client mode */
156 volatile sig_atomic_t control_client_terminate = 0;
157 u_int control_server_pid = 0;
159 /* Prints a help message to the user. This function never returns. */
165 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
166 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
167 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
168 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
169 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
170 " [-w tunnel:tunnel] [user@]hostname [command]\n"
175 static int ssh_session(void);
176 static int ssh_session2(void);
177 static void load_public_identity_files(void);
178 static void control_client(const char *path);
181 * Main program for the ssh client.
184 main(int ac, char **av)
186 int i, opt, exit_status;
187 char *p, *cp, *line, buf[256];
191 extern int optind, optreset;
196 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
199 __progname = ssh_get_progname(av[0]);
203 * Save the original real uid. It will be needed later (uid-swapping
204 * may clobber the real uid).
206 original_real_uid = getuid();
207 original_effective_uid = geteuid();
210 * Use uid-swapping to give up root privileges for the duration of
211 * option processing. We will re-instantiate the rights when we are
212 * ready to create the privileged port, and will permanently drop
213 * them when the port has been created (actually, when the connection
214 * has been made, as we may need to create the port several times).
218 #ifdef HAVE_SETRLIMIT
219 /* If we are installed setuid root be careful to not drop core. */
220 if (original_real_uid != original_effective_uid) {
222 rlim.rlim_cur = rlim.rlim_max = 0;
223 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
224 fatal("setrlimit failed: %.100s", strerror(errno));
228 pw = getpwuid(original_real_uid);
230 logit("You don't exist, go away!");
233 /* Take a copy of the returned structure. */
237 * Set our umask to something reasonable, as some files are created
238 * with the default umask. This will make them world-readable but
239 * writable only by the owner, which is ok for all files for which we
240 * don't set the modes explicitly.
244 /* Initialize option structure to indicate that no values have been set. */
245 initialize_options(&options);
247 /* Parse command-line arguments. */
251 while ((opt = getopt(ac, av,
252 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
255 options.protocol = SSH_PROTO_1;
258 options.protocol = SSH_PROTO_2;
261 options.address_family = AF_INET;
264 options.address_family = AF_INET6;
270 fork_after_authentication_flag = 1;
274 options.forward_x11 = 0;
277 options.forward_x11 = 1;
280 options.forward_x11 = 1;
281 options.forward_x11_trusted = 1;
284 options.gateway_ports = 1;
287 if (strcmp(optarg, "check") == 0)
288 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
289 else if (strcmp(optarg, "exit") == 0)
290 mux_command = SSHMUX_COMMAND_TERMINATE;
292 fatal("Invalid multiplex command.");
294 case 'P': /* deprecated */
295 options.use_privileged_port = 0;
298 options.forward_agent = 0;
301 options.forward_agent = 1;
304 options.gss_deleg_creds = 0;
307 if (stat(optarg, &st) < 0) {
308 fprintf(stderr, "Warning: Identity file %s "
309 "not accessible: %s.\n", optarg,
313 if (options.num_identity_files >=
314 SSH_MAX_IDENTITY_FILES)
315 fatal("Too many identity files specified "
316 "(max %d)", SSH_MAX_IDENTITY_FILES);
317 options.identity_files[options.num_identity_files++] =
322 options.smartcard_device = xstrdup(optarg);
324 fprintf(stderr, "no support for smartcards.\n");
333 if (debug_flag == 0) {
335 options.log_level = SYSLOG_LEVEL_DEBUG1;
337 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
343 fprintf(stderr, "%s, %s\n",
344 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
349 if (options.tun_open == -1)
350 options.tun_open = SSH_TUNMODE_DEFAULT;
351 options.tun_local = a2tun(optarg, &options.tun_remote);
352 if (options.tun_local == SSH_TUNID_ERR) {
353 fprintf(stderr, "Bad tun device '%s'\n", optarg);
358 options.log_level = SYSLOG_LEVEL_QUIET;
361 if (optarg[0] == '^' && optarg[2] == 0 &&
362 (u_char) optarg[1] >= 64 &&
363 (u_char) optarg[1] < 128)
364 options.escape_char = (u_char) optarg[1] & 31;
365 else if (strlen(optarg) == 1)
366 options.escape_char = (u_char) optarg[0];
367 else if (strcmp(optarg, "none") == 0)
368 options.escape_char = SSH_ESCAPECHAR_NONE;
370 fprintf(stderr, "Bad escape character '%s'.\n",
376 if (ciphers_valid(optarg)) {
378 options.ciphers = xstrdup(optarg);
379 options.cipher = SSH_CIPHER_INVALID;
382 options.cipher = cipher_number(optarg);
383 if (options.cipher == -1) {
385 "Unknown cipher type '%s'\n",
389 if (options.cipher == SSH_CIPHER_3DES)
390 options.ciphers = "3des-cbc";
391 else if (options.cipher == SSH_CIPHER_BLOWFISH)
392 options.ciphers = "blowfish-cbc";
394 options.ciphers = (char *)-1;
398 if (mac_valid(optarg))
399 options.macs = xstrdup(optarg);
401 fprintf(stderr, "Unknown mac type '%s'\n",
407 if (options.control_master == SSHCTL_MASTER_YES)
408 options.control_master = SSHCTL_MASTER_ASK;
410 options.control_master = SSHCTL_MASTER_YES;
413 options.port = a2port(optarg);
414 if (options.port == 0) {
415 fprintf(stderr, "Bad port '%s'\n", optarg);
420 options.user = optarg;
424 if (parse_forward(&fwd, optarg))
425 add_local_forward(&options, &fwd);
428 "Bad local forwarding specification '%s'\n",
435 if (parse_forward(&fwd, optarg)) {
436 add_remote_forward(&options, &fwd);
439 "Bad remote forwarding specification "
446 cp = p = xstrdup(optarg);
447 memset(&fwd, '\0', sizeof(fwd));
448 fwd.connect_host = "socks";
449 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
450 fprintf(stderr, "Bad dynamic forwarding "
451 "specification '%.100s'\n", optarg);
455 fwd.listen_port = a2port(cp);
456 fwd.listen_host = cleanhostname(fwd.listen_host);
458 fwd.listen_port = a2port(fwd.listen_host);
459 fwd.listen_host = NULL;
462 if (fwd.listen_port == 0) {
463 fprintf(stderr, "Bad dynamic port '%s'\n",
467 add_local_forward(&options, &fwd);
472 options.compression = 1;
483 line = xstrdup(optarg);
484 if (process_config_line(&options, host ? host : "",
485 line, "command-line", 0, &dummy) != 0)
493 if (options.control_path != NULL)
494 free(options.control_path);
495 options.control_path = xstrdup(optarg);
498 options.bind_address = optarg;
511 if (ac > 0 && !host && **av != '-') {
512 if (strrchr(*av, '@')) {
514 cp = strrchr(p, '@');
515 if (cp == NULL || cp == p)
523 optind = optreset = 1;
529 /* Check that we got a host name. */
533 SSLeay_add_all_algorithms();
534 ERR_load_crypto_strings();
536 /* Initialize the command to execute on remote host. */
537 buffer_init(&command);
540 * Save the command to execute on the remote host in a buffer. There
541 * is no limit on the length of the command, except by the maximum
542 * packet size. Also sets the tty flag if there is no command.
545 /* No command specified - execute shell on a tty. */
547 if (subsystem_flag) {
549 "You must specify a subsystem to invoke.\n");
553 /* A command has been specified. Store it into the buffer. */
554 for (i = 0; i < ac; i++) {
556 buffer_append(&command, " ", 1);
557 buffer_append(&command, av[i], strlen(av[i]));
561 /* Cannot fork to background if no command. */
562 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
563 fatal("Cannot fork into background without a command to execute.");
565 /* Allocate a tty by default if no command specified. */
566 if (buffer_len(&command) == 0)
572 /* Do not allocate a tty if stdin is not a tty. */
573 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
575 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
580 * Initialize "log" output. Since we are the client all output
581 * actually goes to stderr.
583 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
584 SYSLOG_FACILITY_USER, 1);
587 * Read per-user configuration file. Ignore the system wide config
588 * file if the user specifies a config file on the command line.
590 if (config != NULL) {
591 if (!read_config_file(config, host, &options, 0))
592 fatal("Can't open user config file %.100s: "
593 "%.100s", config, strerror(errno));
595 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
596 _PATH_SSH_USER_CONFFILE);
597 (void)read_config_file(buf, host, &options, 1);
599 /* Read systemwide configuration file after use config. */
600 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
604 /* Fill configuration defaults. */
605 fill_default_options(&options);
607 channel_set_af(options.address_family);
610 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
614 if (options.user == NULL)
615 options.user = xstrdup(pw->pw_name);
617 if (options.hostname != NULL)
618 host = options.hostname;
620 /* force lowercase for hostkey matching */
621 if (options.host_key_alias != NULL) {
622 for (p = options.host_key_alias; *p; p++)
627 /* Get default port if port has not been set. */
628 if (options.port == 0) {
629 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
630 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
633 if (options.proxy_command != NULL &&
634 strcmp(options.proxy_command, "none") == 0)
635 options.proxy_command = NULL;
636 if (options.control_path != NULL &&
637 strcmp(options.control_path, "none") == 0)
638 options.control_path = NULL;
640 if (options.control_path != NULL) {
643 if (gethostname(me, sizeof(me)) == -1)
644 fatal("gethostname: %s", strerror(errno));
645 snprintf(buf, sizeof(buf), "%d", options.port);
646 cp = tilde_expand_filename(options.control_path,
648 options.control_path = percent_expand(cp, "p", buf, "h", host,
649 "r", options.user, "l", me, (char *)NULL);
652 if (mux_command != 0 && options.control_path == NULL)
653 fatal("No ControlPath specified for \"-O\" command");
654 if (options.control_path != NULL)
655 control_client(options.control_path);
657 /* Open a connection to the remote host. */
658 if (ssh_connect(host, &hostaddr, options.port,
659 options.address_family, options.connection_attempts,
661 options.use_privileged_port,
663 original_effective_uid == 0 && options.use_privileged_port,
665 options.proxy_command) != 0)
669 * If we successfully made the connection, load the host private key
670 * in case we will need it later for combined rsa-rhosts
671 * authentication. This must be done before releasing extra
672 * privileges, because the file is only readable by root.
673 * If we cannot access the private keys, load the public keys
674 * instead and try to execute the ssh-keysign helper instead.
676 sensitive_data.nkeys = 0;
677 sensitive_data.keys = NULL;
678 sensitive_data.external_keysign = 0;
679 if (options.rhosts_rsa_authentication ||
680 options.hostbased_authentication) {
681 sensitive_data.nkeys = 3;
682 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
686 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
687 _PATH_HOST_KEY_FILE, "", NULL);
688 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
689 _PATH_HOST_DSA_KEY_FILE, "", NULL);
690 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
691 _PATH_HOST_RSA_KEY_FILE, "", NULL);
694 if (options.hostbased_authentication == 1 &&
695 sensitive_data.keys[0] == NULL &&
696 sensitive_data.keys[1] == NULL &&
697 sensitive_data.keys[2] == NULL) {
698 sensitive_data.keys[1] = key_load_public(
699 _PATH_HOST_DSA_KEY_FILE, NULL);
700 sensitive_data.keys[2] = key_load_public(
701 _PATH_HOST_RSA_KEY_FILE, NULL);
702 sensitive_data.external_keysign = 1;
706 * Get rid of any extra privileges that we may have. We will no
707 * longer need them. Also, extra privileges could make it very hard
708 * to read identity files and other non-world-readable files from the
709 * user's home directory if it happens to be on a NFS volume where
710 * root is mapped to nobody.
712 if (original_effective_uid == 0) {
714 permanently_set_uid(pw);
718 * Now that we are back to our own permissions, create ~/.ssh
719 * directory if it doesn't already exist.
721 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
722 if (stat(buf, &st) < 0)
723 if (mkdir(buf, 0700) < 0)
724 error("Could not create directory '%.200s'.", buf);
726 /* load options.identity_files */
727 load_public_identity_files();
729 /* Expand ~ in known host file names. */
731 options.system_hostfile =
732 tilde_expand_filename(options.system_hostfile, original_real_uid);
733 options.user_hostfile =
734 tilde_expand_filename(options.user_hostfile, original_real_uid);
735 options.system_hostfile2 =
736 tilde_expand_filename(options.system_hostfile2, original_real_uid);
737 options.user_hostfile2 =
738 tilde_expand_filename(options.user_hostfile2, original_real_uid);
740 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
742 /* Log into the remote system. This never returns if the login fails. */
743 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
745 /* We no longer need the private host keys. Clear them now. */
746 if (sensitive_data.nkeys != 0) {
747 for (i = 0; i < sensitive_data.nkeys; i++) {
748 if (sensitive_data.keys[i] != NULL) {
749 /* Destroys contents safely */
750 debug3("clear hostkey %d", i);
751 key_free(sensitive_data.keys[i]);
752 sensitive_data.keys[i] = NULL;
755 xfree(sensitive_data.keys);
757 for (i = 0; i < options.num_identity_files; i++) {
758 if (options.identity_files[i]) {
759 xfree(options.identity_files[i]);
760 options.identity_files[i] = NULL;
762 if (options.identity_keys[i]) {
763 key_free(options.identity_keys[i]);
764 options.identity_keys[i] = NULL;
768 exit_status = compat20 ? ssh_session2() : ssh_session();
771 if (options.control_path != NULL && control_fd != -1)
772 unlink(options.control_path);
775 * Send SIGHUP to proxy command if used. We don't wait() in
776 * case it hangs and instead rely on init to reap the child
778 if (proxy_command_pid > 1)
779 kill(proxy_command_pid, SIGHUP);
785 ssh_init_forwarding(void)
790 /* Initiate local TCP/IP port forwardings. */
791 for (i = 0; i < options.num_local_forwards; i++) {
792 debug("Local connections to %.200s:%d forwarded to remote "
794 (options.local_forwards[i].listen_host == NULL) ?
795 (options.gateway_ports ? "*" : "LOCALHOST") :
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 success += channel_setup_local_fwd_listener(
801 options.local_forwards[i].listen_host,
802 options.local_forwards[i].listen_port,
803 options.local_forwards[i].connect_host,
804 options.local_forwards[i].connect_port,
805 options.gateway_ports);
807 if (i > 0 && success == 0)
808 error("Could not request local forwarding.");
810 /* Initiate remote TCP/IP port forwardings. */
811 for (i = 0; i < options.num_remote_forwards; i++) {
812 debug("Remote connections from %.200s:%d forwarded to "
813 "local address %.200s:%d",
814 (options.remote_forwards[i].listen_host == NULL) ?
815 "LOCALHOST" : 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);
819 channel_request_remote_forwarding(
820 options.remote_forwards[i].listen_host,
821 options.remote_forwards[i].listen_port,
822 options.remote_forwards[i].connect_host,
823 options.remote_forwards[i].connect_port);
828 check_agent_present(void)
830 if (options.forward_agent) {
831 /* Clear agent forwarding if we don't have an agent. */
832 if (!ssh_agent_present())
833 options.forward_agent = 0;
847 /* Enable compression if requested. */
848 if (options.compression) {
849 debug("Requesting compression at level %d.", options.compression_level);
851 if (options.compression_level < 1 || options.compression_level > 9)
852 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
854 /* Send the request. */
855 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
856 packet_put_int(options.compression_level);
859 type = packet_read();
860 if (type == SSH_SMSG_SUCCESS)
861 packet_start_compression(options.compression_level);
862 else if (type == SSH_SMSG_FAILURE)
863 logit("Warning: Remote host refused compression.");
865 packet_disconnect("Protocol error waiting for compression response.");
867 /* Allocate a pseudo tty if appropriate. */
869 debug("Requesting pty.");
871 /* Start the packet. */
872 packet_start(SSH_CMSG_REQUEST_PTY);
874 /* Store TERM in the packet. There is no limit on the
875 length of the string. */
879 packet_put_cstring(cp);
881 /* Store window size in the packet. */
882 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
883 memset(&ws, 0, sizeof(ws));
884 packet_put_int(ws.ws_row);
885 packet_put_int(ws.ws_col);
886 packet_put_int(ws.ws_xpixel);
887 packet_put_int(ws.ws_ypixel);
889 /* Store tty modes in the packet. */
890 tty_make_modes(fileno(stdin), NULL);
892 /* Send the packet, and wait for it to leave. */
896 /* Read response from the server. */
897 type = packet_read();
898 if (type == SSH_SMSG_SUCCESS) {
901 } else if (type == SSH_SMSG_FAILURE)
902 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
904 packet_disconnect("Protocol error waiting for pty request response.");
906 /* Request X11 forwarding if enabled and DISPLAY is set. */
907 display = getenv("DISPLAY");
908 if (options.forward_x11 && display != NULL) {
910 /* Get reasonable local authentication information. */
911 client_x11_get_proto(display, options.xauth_location,
912 options.forward_x11_trusted, &proto, &data);
913 /* Request forwarding with authentication spoofing. */
914 debug("Requesting X11 forwarding with authentication spoofing.");
915 x11_request_forwarding_with_spoofing(0, display, proto, data);
917 /* Read response from the server. */
918 type = packet_read();
919 if (type == SSH_SMSG_SUCCESS) {
921 } else if (type == SSH_SMSG_FAILURE) {
922 logit("Warning: Remote host denied X11 forwarding.");
924 packet_disconnect("Protocol error waiting for X11 forwarding");
927 /* Tell the packet module whether this is an interactive session. */
928 packet_set_interactive(interactive);
930 /* Request authentication agent forwarding if appropriate. */
931 check_agent_present();
933 if (options.forward_agent) {
934 debug("Requesting authentication agent forwarding.");
935 auth_request_forwarding();
937 /* Read response from the server. */
938 type = packet_read();
940 if (type != SSH_SMSG_SUCCESS)
941 logit("Warning: Remote host denied authentication agent forwarding.");
944 /* Initiate port forwardings. */
945 ssh_init_forwarding();
947 /* If requested, let ssh continue in the background. */
948 if (fork_after_authentication_flag)
949 if (daemon(1, 1) < 0)
950 fatal("daemon() failed: %.200s", strerror(errno));
953 * If a command was specified on the command line, execute the
954 * command now. Otherwise request the server to start a shell.
956 if (buffer_len(&command) > 0) {
957 int len = buffer_len(&command);
960 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
961 packet_start(SSH_CMSG_EXEC_CMD);
962 packet_put_string(buffer_ptr(&command), buffer_len(&command));
966 debug("Requesting shell.");
967 packet_start(SSH_CMSG_EXEC_SHELL);
972 /* Enter the interactive session. */
973 return client_loop(have_tty, tty_flag ?
974 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
978 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
982 id = packet_get_int();
983 len = buffer_len(&command);
987 if (type == SSH2_MSG_CHANNEL_FAILURE)
988 fatal("Request for subsystem '%.*s' failed on channel %d",
989 len, (u_char *)buffer_ptr(&command), id);
993 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
997 i = client_global_request_id++;
998 if (i >= options.num_remote_forwards)
1000 debug("remote forward %s for: listen %d, connect %s:%d",
1001 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1002 options.remote_forwards[i].listen_port,
1003 options.remote_forwards[i].connect_host,
1004 options.remote_forwards[i].connect_port);
1005 if (type == SSH2_MSG_REQUEST_FAILURE)
1006 logit("Warning: remote port forwarding failed for listen "
1007 "port %d", options.remote_forwards[i].listen_port);
1011 ssh_control_listener(void)
1013 struct sockaddr_un addr;
1017 if (options.control_path == NULL ||
1018 options.control_master == SSHCTL_MASTER_NO)
1021 debug("setting up multiplex master socket");
1023 memset(&addr, '\0', sizeof(addr));
1024 addr.sun_family = AF_UNIX;
1025 addr_len = offsetof(struct sockaddr_un, sun_path) +
1026 strlen(options.control_path) + 1;
1028 if (strlcpy(addr.sun_path, options.control_path,
1029 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1030 fatal("ControlPath too long");
1032 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1033 fatal("%s socket(): %s", __func__, strerror(errno));
1035 old_umask = umask(0177);
1036 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1038 if (errno == EINVAL || errno == EADDRINUSE)
1039 fatal("ControlSocket %s already exists",
1040 options.control_path);
1042 fatal("%s bind(): %s", __func__, strerror(errno));
1046 if (listen(control_fd, 64) == -1)
1047 fatal("%s listen(): %s", __func__, strerror(errno));
1049 set_nonblock(control_fd);
1052 /* request pty/x11/agent/tcpfwd/shell for channel */
1054 ssh_session2_setup(int id, void *arg)
1056 extern char **environ;
1057 const char *display;
1058 int interactive = tty_flag;
1060 display = getenv("DISPLAY");
1061 if (options.forward_x11 && display != NULL) {
1063 /* Get reasonable local authentication information. */
1064 client_x11_get_proto(display, options.xauth_location,
1065 options.forward_x11_trusted, &proto, &data);
1066 /* Request forwarding with authentication spoofing. */
1067 debug("Requesting X11 forwarding with authentication spoofing.");
1068 x11_request_forwarding_with_spoofing(id, display, proto, data);
1070 /* XXX wait for reply */
1073 check_agent_present();
1074 if (options.forward_agent) {
1075 debug("Requesting authentication agent forwarding.");
1076 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1080 if (options.tun_open != SSH_TUNMODE_NO) {
1084 debug("Requesting tun.");
1085 if ((fd = tun_open(options.tun_local,
1086 options.tun_open)) >= 0) {
1087 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1088 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1091 #if defined(SSH_TUN_FILTER)
1092 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1093 channel_register_filter(c->self, sys_tun_infilter,
1096 packet_start(SSH2_MSG_CHANNEL_OPEN);
1097 packet_put_cstring("tun@openssh.com");
1098 packet_put_int(c->self);
1099 packet_put_int(c->local_window_max);
1100 packet_put_int(c->local_maxpacket);
1101 packet_put_int(options.tun_open);
1102 packet_put_int(options.tun_remote);
1107 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1108 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1110 packet_set_interactive(interactive);
1113 /* open new channel for a session */
1115 ssh_session2_open(void)
1118 int window, packetmax, in, out, err;
1120 if (stdin_null_flag) {
1121 in = open(_PATH_DEVNULL, O_RDONLY);
1123 in = dup(STDIN_FILENO);
1125 out = dup(STDOUT_FILENO);
1126 err = dup(STDERR_FILENO);
1128 if (in < 0 || out < 0 || err < 0)
1129 fatal("dup() in/out/err failed");
1131 /* enable nonblocking unless tty */
1139 window = CHAN_SES_WINDOW_DEFAULT;
1140 packetmax = CHAN_SES_PACKET_DEFAULT;
1146 "session", SSH_CHANNEL_OPENING, in, out, err,
1147 window, packetmax, CHAN_EXTENDED_WRITE,
1148 "client-session", /*nonblock*/0);
1150 debug3("ssh_session2_open: channel_new: %d", c->self);
1152 channel_send_open(c->self);
1154 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1164 /* XXX should be pre-session */
1165 ssh_init_forwarding();
1166 ssh_control_listener();
1168 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1169 id = ssh_session2_open();
1171 /* Execute a local command */
1172 if (options.local_command != NULL &&
1173 options.permit_local_command)
1174 ssh_local_cmd(options.local_command);
1176 /* If requested, let ssh continue in the background. */
1177 if (fork_after_authentication_flag)
1178 if (daemon(1, 1) < 0)
1179 fatal("daemon() failed: %.200s", strerror(errno));
1181 return client_loop(tty_flag, tty_flag ?
1182 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1186 load_public_identity_files(void)
1194 if (options.smartcard_device != NULL &&
1195 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1196 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1198 for (i = 0; keys[i] != NULL; i++) {
1200 memmove(&options.identity_files[1], &options.identity_files[0],
1201 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1202 memmove(&options.identity_keys[1], &options.identity_keys[0],
1203 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1204 options.num_identity_files++;
1205 options.identity_keys[0] = keys[i];
1206 options.identity_files[0] = sc_get_key_label(keys[i]);
1208 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1209 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1213 #endif /* SMARTCARD */
1214 for (; i < options.num_identity_files; i++) {
1215 filename = tilde_expand_filename(options.identity_files[i],
1217 public = key_load_public(filename, NULL);
1218 debug("identity file %s type %d", filename,
1219 public ? public->type : -1);
1220 xfree(options.identity_files[i]);
1221 options.identity_files[i] = filename;
1222 options.identity_keys[i] = public;
1227 control_client_sighandler(int signo)
1229 control_client_terminate = signo;
1233 control_client_sigrelay(int signo)
1235 if (control_server_pid > 1)
1236 kill(control_server_pid, signo);
1240 env_permitted(char *env)
1243 char name[1024], *cp;
1245 strlcpy(name, env, sizeof(name));
1246 if ((cp = strchr(name, '=')) == NULL)
1251 for (i = 0; i < options.num_send_env; i++)
1252 if (match_pattern(name, options.send_env[i]))
1259 control_client(const char *path)
1261 struct sockaddr_un addr;
1262 int i, r, fd, sock, exitval, num_env, addr_len;
1265 extern char **environ;
1268 if (mux_command == 0)
1269 mux_command = SSHMUX_COMMAND_OPEN;
1271 switch (options.control_master) {
1272 case SSHCTL_MASTER_AUTO:
1273 case SSHCTL_MASTER_AUTO_ASK:
1274 debug("auto-mux: Trying existing master");
1276 case SSHCTL_MASTER_NO:
1282 memset(&addr, '\0', sizeof(addr));
1283 addr.sun_family = AF_UNIX;
1284 addr_len = offsetof(struct sockaddr_un, sun_path) +
1287 if (strlcpy(addr.sun_path, path,
1288 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1289 fatal("ControlPath too long");
1291 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1292 fatal("%s socket(): %s", __func__, strerror(errno));
1294 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1295 if (mux_command != SSHMUX_COMMAND_OPEN) {
1296 fatal("Control socket connect(%.100s): %s", path,
1299 if (errno == ENOENT)
1300 debug("Control socket \"%.100s\" does not exist", path);
1302 error("Control socket connect(%.100s): %s", path,
1309 if (stdin_null_flag) {
1310 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1311 fatal("open(/dev/null): %s", strerror(errno));
1312 if (dup2(fd, STDIN_FILENO) == -1)
1313 fatal("dup2: %s", strerror(errno));
1314 if (fd > STDERR_FILENO)
1318 term = getenv("TERM");
1322 flags |= SSHMUX_FLAG_TTY;
1324 flags |= SSHMUX_FLAG_SUBSYS;
1325 if (options.forward_x11)
1326 flags |= SSHMUX_FLAG_X11_FWD;
1327 if (options.forward_agent)
1328 flags |= SSHMUX_FLAG_AGENT_FWD;
1332 /* Send our command to server */
1333 buffer_put_int(&m, mux_command);
1334 buffer_put_int(&m, flags);
1335 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1336 fatal("%s: msg_send", __func__);
1339 /* Get authorisation status and PID of controlee */
1340 if (ssh_msg_recv(sock, &m) == -1)
1341 fatal("%s: msg_recv", __func__);
1342 if (buffer_get_char(&m) != SSHMUX_VER)
1343 fatal("%s: wrong version", __func__);
1344 if (buffer_get_int(&m) != 1)
1345 fatal("Connection to master denied");
1346 control_server_pid = buffer_get_int(&m);
1350 switch (mux_command) {
1351 case SSHMUX_COMMAND_ALIVE_CHECK:
1352 fprintf(stderr, "Master running (pid=%d)\r\n",
1353 control_server_pid);
1355 case SSHMUX_COMMAND_TERMINATE:
1356 fprintf(stderr, "Exit request sent.\r\n");
1358 case SSHMUX_COMMAND_OPEN:
1359 /* continue below */
1362 fatal("silly mux_command %d", mux_command);
1365 /* SSHMUX_COMMAND_OPEN */
1366 buffer_put_cstring(&m, term ? term : "");
1367 buffer_append(&command, "\0", 1);
1368 buffer_put_cstring(&m, buffer_ptr(&command));
1370 if (options.num_send_env == 0 || environ == NULL) {
1371 buffer_put_int(&m, 0);
1373 /* Pass environment */
1375 for (i = 0; environ[i] != NULL; i++)
1376 if (env_permitted(environ[i]))
1377 num_env++; /* Count */
1379 buffer_put_int(&m, num_env);
1381 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1382 if (env_permitted(environ[i])) {
1384 buffer_put_cstring(&m, environ[i]);
1388 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1389 fatal("%s: msg_send", __func__);
1391 mm_send_fd(sock, STDIN_FILENO);
1392 mm_send_fd(sock, STDOUT_FILENO);
1393 mm_send_fd(sock, STDERR_FILENO);
1395 /* Wait for reply, so master has a chance to gather ttymodes */
1397 if (ssh_msg_recv(sock, &m) == -1)
1398 fatal("%s: msg_recv", __func__);
1399 if (buffer_get_char(&m) != SSHMUX_VER)
1400 fatal("%s: wrong version", __func__);
1403 signal(SIGHUP, control_client_sighandler);
1404 signal(SIGINT, control_client_sighandler);
1405 signal(SIGTERM, control_client_sighandler);
1406 signal(SIGWINCH, control_client_sigrelay);
1411 /* Stick around until the controlee closes the client_fd */
1413 for (;!control_client_terminate;) {
1414 r = read(sock, &exitval, sizeof(exitval));
1416 debug2("Received EOF from master");
1420 debug2("Received exit status from master %d", exitval);
1421 if (r == -1 && errno != EINTR)
1422 fatal("%s: read %s", __func__, strerror(errno));
1425 if (control_client_terminate)
1426 debug2("Exiting on signal %d", control_client_terminate);
1432 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1433 fprintf(stderr, "Connection to master closed.\r\n");