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.257 2005/12/20 04:41:07 dtucker 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 " [-w tunnel:tunnel] [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:TVw:XY")) != -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 if (options.tun_open == -1)
345 options.tun_open = SSH_TUNMODE_DEFAULT;
346 options.tun_local = a2tun(optarg, &options.tun_remote);
347 if (options.tun_local == SSH_TUNID_ERR) {
348 fprintf(stderr, "Bad tun device '%s'\n", optarg);
353 options.log_level = SYSLOG_LEVEL_QUIET;
356 if (optarg[0] == '^' && optarg[2] == 0 &&
357 (u_char) optarg[1] >= 64 &&
358 (u_char) optarg[1] < 128)
359 options.escape_char = (u_char) optarg[1] & 31;
360 else if (strlen(optarg) == 1)
361 options.escape_char = (u_char) optarg[0];
362 else if (strcmp(optarg, "none") == 0)
363 options.escape_char = SSH_ESCAPECHAR_NONE;
365 fprintf(stderr, "Bad escape character '%s'.\n",
371 if (ciphers_valid(optarg)) {
373 options.ciphers = xstrdup(optarg);
374 options.cipher = SSH_CIPHER_INVALID;
377 options.cipher = cipher_number(optarg);
378 if (options.cipher == -1) {
380 "Unknown cipher type '%s'\n",
384 if (options.cipher == SSH_CIPHER_3DES)
385 options.ciphers = "3des-cbc";
386 else if (options.cipher == SSH_CIPHER_BLOWFISH)
387 options.ciphers = "blowfish-cbc";
389 options.ciphers = (char *)-1;
393 if (mac_valid(optarg))
394 options.macs = xstrdup(optarg);
396 fprintf(stderr, "Unknown mac type '%s'\n",
402 if (options.control_master == SSHCTL_MASTER_YES)
403 options.control_master = SSHCTL_MASTER_ASK;
405 options.control_master = SSHCTL_MASTER_YES;
408 options.port = a2port(optarg);
409 if (options.port == 0) {
410 fprintf(stderr, "Bad port '%s'\n", optarg);
415 options.user = optarg;
419 if (parse_forward(&fwd, optarg))
420 add_local_forward(&options, &fwd);
423 "Bad local forwarding specification '%s'\n",
430 if (parse_forward(&fwd, optarg)) {
431 add_remote_forward(&options, &fwd);
434 "Bad remote forwarding specification "
441 cp = p = xstrdup(optarg);
442 memset(&fwd, '\0', sizeof(fwd));
443 fwd.connect_host = "socks";
444 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
445 fprintf(stderr, "Bad dynamic forwarding "
446 "specification '%.100s'\n", optarg);
450 fwd.listen_port = a2port(cp);
451 fwd.listen_host = cleanhostname(fwd.listen_host);
453 fwd.listen_port = a2port(fwd.listen_host);
454 fwd.listen_host = NULL;
457 if (fwd.listen_port == 0) {
458 fprintf(stderr, "Bad dynamic port '%s'\n",
462 add_local_forward(&options, &fwd);
467 options.compression = 1;
478 line = xstrdup(optarg);
479 if (process_config_line(&options, host ? host : "",
480 line, "command-line", 0, &dummy) != 0)
488 if (options.control_path != NULL)
489 free(options.control_path);
490 options.control_path = xstrdup(optarg);
493 options.bind_address = optarg;
506 if (ac > 0 && !host && **av != '-') {
507 if (strrchr(*av, '@')) {
509 cp = strrchr(p, '@');
510 if (cp == NULL || cp == p)
518 optind = optreset = 1;
524 /* Check that we got a host name. */
528 SSLeay_add_all_algorithms();
529 ERR_load_crypto_strings();
531 /* Initialize the command to execute on remote host. */
532 buffer_init(&command);
535 * Save the command to execute on the remote host in a buffer. There
536 * is no limit on the length of the command, except by the maximum
537 * packet size. Also sets the tty flag if there is no command.
540 /* No command specified - execute shell on a tty. */
542 if (subsystem_flag) {
544 "You must specify a subsystem to invoke.\n");
548 /* A command has been specified. Store it into the buffer. */
549 for (i = 0; i < ac; i++) {
551 buffer_append(&command, " ", 1);
552 buffer_append(&command, av[i], strlen(av[i]));
556 /* Cannot fork to background if no command. */
557 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
558 fatal("Cannot fork into background without a command to execute.");
560 /* Allocate a tty by default if no command specified. */
561 if (buffer_len(&command) == 0)
567 /* Do not allocate a tty if stdin is not a tty. */
568 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
570 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
575 * Initialize "log" output. Since we are the client all output
576 * actually goes to stderr.
578 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
579 SYSLOG_FACILITY_USER, 1);
582 * Read per-user configuration file. Ignore the system wide config
583 * file if the user specifies a config file on the command line.
585 if (config != NULL) {
586 if (!read_config_file(config, host, &options, 0))
587 fatal("Can't open user config file %.100s: "
588 "%.100s", config, strerror(errno));
590 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
591 _PATH_SSH_USER_CONFFILE);
592 (void)read_config_file(buf, host, &options, 1);
594 /* Read systemwide configuration file after use config. */
595 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
599 /* Fill configuration defaults. */
600 fill_default_options(&options);
602 channel_set_af(options.address_family);
605 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
609 if (options.user == NULL)
610 options.user = xstrdup(pw->pw_name);
612 if (options.hostname != NULL)
613 host = options.hostname;
615 /* force lowercase for hostkey matching */
616 if (options.host_key_alias != NULL) {
617 for (p = options.host_key_alias; *p; p++)
622 /* Get default port if port has not been set. */
623 if (options.port == 0) {
624 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
625 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
628 if (options.proxy_command != NULL &&
629 strcmp(options.proxy_command, "none") == 0)
630 options.proxy_command = NULL;
631 if (options.control_path != NULL &&
632 strcmp(options.control_path, "none") == 0)
633 options.control_path = NULL;
635 if (options.control_path != NULL) {
636 snprintf(buf, sizeof(buf), "%d", options.port);
637 cp = tilde_expand_filename(options.control_path,
639 options.control_path = percent_expand(cp, "p", buf, "h", host,
640 "r", options.user, (char *)NULL);
643 if (mux_command != 0 && options.control_path == NULL)
644 fatal("No ControlPath specified for \"-O\" command");
645 if (options.control_path != NULL)
646 control_client(options.control_path);
648 /* Open a connection to the remote host. */
649 if (ssh_connect(host, &hostaddr, options.port,
650 options.address_family, options.connection_attempts,
652 options.use_privileged_port,
654 original_effective_uid == 0 && options.use_privileged_port,
656 options.proxy_command) != 0)
660 * If we successfully made the connection, load the host private key
661 * in case we will need it later for combined rsa-rhosts
662 * authentication. This must be done before releasing extra
663 * privileges, because the file is only readable by root.
664 * If we cannot access the private keys, load the public keys
665 * instead and try to execute the ssh-keysign helper instead.
667 sensitive_data.nkeys = 0;
668 sensitive_data.keys = NULL;
669 sensitive_data.external_keysign = 0;
670 if (options.rhosts_rsa_authentication ||
671 options.hostbased_authentication) {
672 sensitive_data.nkeys = 3;
673 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
677 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
678 _PATH_HOST_KEY_FILE, "", NULL);
679 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
680 _PATH_HOST_DSA_KEY_FILE, "", NULL);
681 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
682 _PATH_HOST_RSA_KEY_FILE, "", NULL);
685 if (options.hostbased_authentication == 1 &&
686 sensitive_data.keys[0] == NULL &&
687 sensitive_data.keys[1] == NULL &&
688 sensitive_data.keys[2] == NULL) {
689 sensitive_data.keys[1] = key_load_public(
690 _PATH_HOST_DSA_KEY_FILE, NULL);
691 sensitive_data.keys[2] = key_load_public(
692 _PATH_HOST_RSA_KEY_FILE, NULL);
693 sensitive_data.external_keysign = 1;
697 * Get rid of any extra privileges that we may have. We will no
698 * longer need them. Also, extra privileges could make it very hard
699 * to read identity files and other non-world-readable files from the
700 * user's home directory if it happens to be on a NFS volume where
701 * root is mapped to nobody.
703 if (original_effective_uid == 0) {
705 permanently_set_uid(pw);
709 * Now that we are back to our own permissions, create ~/.ssh
710 * directory if it doesn't already exist.
712 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
713 if (stat(buf, &st) < 0)
714 if (mkdir(buf, 0700) < 0)
715 error("Could not create directory '%.200s'.", buf);
717 /* load options.identity_files */
718 load_public_identity_files();
720 /* Expand ~ in known host file names. */
722 options.system_hostfile =
723 tilde_expand_filename(options.system_hostfile, original_real_uid);
724 options.user_hostfile =
725 tilde_expand_filename(options.user_hostfile, original_real_uid);
726 options.system_hostfile2 =
727 tilde_expand_filename(options.system_hostfile2, original_real_uid);
728 options.user_hostfile2 =
729 tilde_expand_filename(options.user_hostfile2, original_real_uid);
731 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
733 /* Log into the remote system. This never returns if the login fails. */
734 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
736 /* We no longer need the private host keys. Clear them now. */
737 if (sensitive_data.nkeys != 0) {
738 for (i = 0; i < sensitive_data.nkeys; i++) {
739 if (sensitive_data.keys[i] != NULL) {
740 /* Destroys contents safely */
741 debug3("clear hostkey %d", i);
742 key_free(sensitive_data.keys[i]);
743 sensitive_data.keys[i] = NULL;
746 xfree(sensitive_data.keys);
748 for (i = 0; i < options.num_identity_files; i++) {
749 if (options.identity_files[i]) {
750 xfree(options.identity_files[i]);
751 options.identity_files[i] = NULL;
753 if (options.identity_keys[i]) {
754 key_free(options.identity_keys[i]);
755 options.identity_keys[i] = NULL;
759 exit_status = compat20 ? ssh_session2() : ssh_session();
762 if (options.control_path != NULL && control_fd != -1)
763 unlink(options.control_path);
766 * Send SIGHUP to proxy command if used. We don't wait() in
767 * case it hangs and instead rely on init to reap the child
769 if (proxy_command_pid > 1)
770 kill(proxy_command_pid, SIGHUP);
776 ssh_init_forwarding(void)
781 /* Initiate local TCP/IP port forwardings. */
782 for (i = 0; i < options.num_local_forwards; i++) {
783 debug("Local connections to %.200s:%d forwarded to remote "
785 (options.local_forwards[i].listen_host == NULL) ?
786 (options.gateway_ports ? "*" : "LOCALHOST") :
787 options.local_forwards[i].listen_host,
788 options.local_forwards[i].listen_port,
789 options.local_forwards[i].connect_host,
790 options.local_forwards[i].connect_port);
791 success += channel_setup_local_fwd_listener(
792 options.local_forwards[i].listen_host,
793 options.local_forwards[i].listen_port,
794 options.local_forwards[i].connect_host,
795 options.local_forwards[i].connect_port,
796 options.gateway_ports);
798 if (i > 0 && success == 0)
799 error("Could not request local forwarding.");
801 /* Initiate remote TCP/IP port forwardings. */
802 for (i = 0; i < options.num_remote_forwards; i++) {
803 debug("Remote connections from %.200s:%d forwarded to "
804 "local address %.200s:%d",
805 (options.remote_forwards[i].listen_host == NULL) ?
806 "LOCALHOST" : options.remote_forwards[i].listen_host,
807 options.remote_forwards[i].listen_port,
808 options.remote_forwards[i].connect_host,
809 options.remote_forwards[i].connect_port);
810 channel_request_remote_forwarding(
811 options.remote_forwards[i].listen_host,
812 options.remote_forwards[i].listen_port,
813 options.remote_forwards[i].connect_host,
814 options.remote_forwards[i].connect_port);
819 check_agent_present(void)
821 if (options.forward_agent) {
822 /* Clear agent forwarding if we don't have an agent. */
823 if (!ssh_agent_present())
824 options.forward_agent = 0;
838 /* Enable compression if requested. */
839 if (options.compression) {
840 debug("Requesting compression at level %d.", options.compression_level);
842 if (options.compression_level < 1 || options.compression_level > 9)
843 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
845 /* Send the request. */
846 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
847 packet_put_int(options.compression_level);
850 type = packet_read();
851 if (type == SSH_SMSG_SUCCESS)
852 packet_start_compression(options.compression_level);
853 else if (type == SSH_SMSG_FAILURE)
854 logit("Warning: Remote host refused compression.");
856 packet_disconnect("Protocol error waiting for compression response.");
858 /* Allocate a pseudo tty if appropriate. */
860 debug("Requesting pty.");
862 /* Start the packet. */
863 packet_start(SSH_CMSG_REQUEST_PTY);
865 /* Store TERM in the packet. There is no limit on the
866 length of the string. */
870 packet_put_cstring(cp);
872 /* Store window size in the packet. */
873 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
874 memset(&ws, 0, sizeof(ws));
875 packet_put_int(ws.ws_row);
876 packet_put_int(ws.ws_col);
877 packet_put_int(ws.ws_xpixel);
878 packet_put_int(ws.ws_ypixel);
880 /* Store tty modes in the packet. */
881 tty_make_modes(fileno(stdin), NULL);
883 /* Send the packet, and wait for it to leave. */
887 /* Read response from the server. */
888 type = packet_read();
889 if (type == SSH_SMSG_SUCCESS) {
892 } else if (type == SSH_SMSG_FAILURE)
893 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
895 packet_disconnect("Protocol error waiting for pty request response.");
897 /* Request X11 forwarding if enabled and DISPLAY is set. */
898 display = getenv("DISPLAY");
899 if (options.forward_x11 && display != NULL) {
901 /* Get reasonable local authentication information. */
902 client_x11_get_proto(display, options.xauth_location,
903 options.forward_x11_trusted, &proto, &data);
904 /* Request forwarding with authentication spoofing. */
905 debug("Requesting X11 forwarding with authentication spoofing.");
906 x11_request_forwarding_with_spoofing(0, display, proto, data);
908 /* Read response from the server. */
909 type = packet_read();
910 if (type == SSH_SMSG_SUCCESS) {
912 } else if (type == SSH_SMSG_FAILURE) {
913 logit("Warning: Remote host denied X11 forwarding.");
915 packet_disconnect("Protocol error waiting for X11 forwarding");
918 /* Tell the packet module whether this is an interactive session. */
919 packet_set_interactive(interactive);
921 /* Request authentication agent forwarding if appropriate. */
922 check_agent_present();
924 if (options.forward_agent) {
925 debug("Requesting authentication agent forwarding.");
926 auth_request_forwarding();
928 /* Read response from the server. */
929 type = packet_read();
931 if (type != SSH_SMSG_SUCCESS)
932 logit("Warning: Remote host denied authentication agent forwarding.");
935 /* Initiate port forwardings. */
936 ssh_init_forwarding();
938 /* If requested, let ssh continue in the background. */
939 if (fork_after_authentication_flag)
940 if (daemon(1, 1) < 0)
941 fatal("daemon() failed: %.200s", strerror(errno));
944 * If a command was specified on the command line, execute the
945 * command now. Otherwise request the server to start a shell.
947 if (buffer_len(&command) > 0) {
948 int len = buffer_len(&command);
951 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
952 packet_start(SSH_CMSG_EXEC_CMD);
953 packet_put_string(buffer_ptr(&command), buffer_len(&command));
957 debug("Requesting shell.");
958 packet_start(SSH_CMSG_EXEC_SHELL);
963 /* Enter the interactive session. */
964 return client_loop(have_tty, tty_flag ?
965 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
969 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
973 id = packet_get_int();
974 len = buffer_len(&command);
978 if (type == SSH2_MSG_CHANNEL_FAILURE)
979 fatal("Request for subsystem '%.*s' failed on channel %d",
980 len, (u_char *)buffer_ptr(&command), id);
984 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
988 i = client_global_request_id++;
989 if (i >= options.num_remote_forwards)
991 debug("remote forward %s for: listen %d, connect %s:%d",
992 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
993 options.remote_forwards[i].listen_port,
994 options.remote_forwards[i].connect_host,
995 options.remote_forwards[i].connect_port);
996 if (type == SSH2_MSG_REQUEST_FAILURE)
997 logit("Warning: remote port forwarding failed for listen "
998 "port %d", options.remote_forwards[i].listen_port);
1002 ssh_control_listener(void)
1004 struct sockaddr_un addr;
1008 if (options.control_path == NULL ||
1009 options.control_master == SSHCTL_MASTER_NO)
1012 debug("setting up multiplex master socket");
1014 memset(&addr, '\0', sizeof(addr));
1015 addr.sun_family = AF_UNIX;
1016 addr_len = offsetof(struct sockaddr_un, sun_path) +
1017 strlen(options.control_path) + 1;
1019 if (strlcpy(addr.sun_path, options.control_path,
1020 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1021 fatal("ControlPath too long");
1023 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1024 fatal("%s socket(): %s", __func__, strerror(errno));
1026 old_umask = umask(0177);
1027 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1029 if (errno == EINVAL || errno == EADDRINUSE)
1030 fatal("ControlSocket %s already exists",
1031 options.control_path);
1033 fatal("%s bind(): %s", __func__, strerror(errno));
1037 if (listen(control_fd, 64) == -1)
1038 fatal("%s listen(): %s", __func__, strerror(errno));
1040 set_nonblock(control_fd);
1043 /* request pty/x11/agent/tcpfwd/shell for channel */
1045 ssh_session2_setup(int id, void *arg)
1047 extern char **environ;
1048 const char *display;
1049 int interactive = tty_flag;
1051 display = getenv("DISPLAY");
1052 if (options.forward_x11 && display != NULL) {
1054 /* Get reasonable local authentication information. */
1055 client_x11_get_proto(display, options.xauth_location,
1056 options.forward_x11_trusted, &proto, &data);
1057 /* Request forwarding with authentication spoofing. */
1058 debug("Requesting X11 forwarding with authentication spoofing.");
1059 x11_request_forwarding_with_spoofing(id, display, proto, data);
1061 /* XXX wait for reply */
1064 check_agent_present();
1065 if (options.forward_agent) {
1066 debug("Requesting authentication agent forwarding.");
1067 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1071 if (options.tun_open != SSH_TUNMODE_NO) {
1075 debug("Requesting tun.");
1076 if ((fd = tun_open(options.tun_local,
1077 options.tun_open)) >= 0) {
1078 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1079 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1082 #if defined(SSH_TUN_FILTER)
1083 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1084 channel_register_filter(c->self, sys_tun_infilter,
1087 packet_start(SSH2_MSG_CHANNEL_OPEN);
1088 packet_put_cstring("tun@openssh.com");
1089 packet_put_int(c->self);
1090 packet_put_int(c->local_window_max);
1091 packet_put_int(c->local_maxpacket);
1092 packet_put_int(options.tun_open);
1093 packet_put_int(options.tun_remote);
1098 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1099 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1101 packet_set_interactive(interactive);
1104 /* open new channel for a session */
1106 ssh_session2_open(void)
1109 int window, packetmax, in, out, err;
1111 if (stdin_null_flag) {
1112 in = open(_PATH_DEVNULL, O_RDONLY);
1114 in = dup(STDIN_FILENO);
1116 out = dup(STDOUT_FILENO);
1117 err = dup(STDERR_FILENO);
1119 if (in < 0 || out < 0 || err < 0)
1120 fatal("dup() in/out/err failed");
1122 /* enable nonblocking unless tty */
1130 window = CHAN_SES_WINDOW_DEFAULT;
1131 packetmax = CHAN_SES_PACKET_DEFAULT;
1137 "session", SSH_CHANNEL_OPENING, in, out, err,
1138 window, packetmax, CHAN_EXTENDED_WRITE,
1139 "client-session", /*nonblock*/0);
1141 debug3("ssh_session2_open: channel_new: %d", c->self);
1143 channel_send_open(c->self);
1145 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1155 /* XXX should be pre-session */
1156 ssh_init_forwarding();
1157 ssh_control_listener();
1159 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1160 id = ssh_session2_open();
1162 /* Execute a local command */
1163 if (options.local_command != NULL &&
1164 options.permit_local_command)
1165 ssh_local_cmd(options.local_command);
1167 /* If requested, let ssh continue in the background. */
1168 if (fork_after_authentication_flag)
1169 if (daemon(1, 1) < 0)
1170 fatal("daemon() failed: %.200s", strerror(errno));
1172 return client_loop(tty_flag, tty_flag ?
1173 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1177 load_public_identity_files(void)
1185 if (options.smartcard_device != NULL &&
1186 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1187 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1189 for (i = 0; keys[i] != NULL; i++) {
1191 memmove(&options.identity_files[1], &options.identity_files[0],
1192 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1193 memmove(&options.identity_keys[1], &options.identity_keys[0],
1194 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1195 options.num_identity_files++;
1196 options.identity_keys[0] = keys[i];
1197 options.identity_files[0] = sc_get_key_label(keys[i]);
1199 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1200 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1204 #endif /* SMARTCARD */
1205 for (; i < options.num_identity_files; i++) {
1206 filename = tilde_expand_filename(options.identity_files[i],
1208 public = key_load_public(filename, NULL);
1209 debug("identity file %s type %d", filename,
1210 public ? public->type : -1);
1211 xfree(options.identity_files[i]);
1212 options.identity_files[i] = filename;
1213 options.identity_keys[i] = public;
1218 control_client_sighandler(int signo)
1220 control_client_terminate = signo;
1224 control_client_sigrelay(int signo)
1226 if (control_server_pid > 1)
1227 kill(control_server_pid, signo);
1231 env_permitted(char *env)
1234 char name[1024], *cp;
1236 strlcpy(name, env, sizeof(name));
1237 if ((cp = strchr(name, '=')) == NULL)
1242 for (i = 0; i < options.num_send_env; i++)
1243 if (match_pattern(name, options.send_env[i]))
1250 control_client(const char *path)
1252 struct sockaddr_un addr;
1253 int i, r, fd, sock, exitval, num_env, addr_len;
1256 extern char **environ;
1259 if (mux_command == 0)
1260 mux_command = SSHMUX_COMMAND_OPEN;
1262 switch (options.control_master) {
1263 case SSHCTL_MASTER_AUTO:
1264 case SSHCTL_MASTER_AUTO_ASK:
1265 debug("auto-mux: Trying existing master");
1267 case SSHCTL_MASTER_NO:
1273 memset(&addr, '\0', sizeof(addr));
1274 addr.sun_family = AF_UNIX;
1275 addr_len = offsetof(struct sockaddr_un, sun_path) +
1278 if (strlcpy(addr.sun_path, path,
1279 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1280 fatal("ControlPath too long");
1282 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1283 fatal("%s socket(): %s", __func__, strerror(errno));
1285 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1286 if (mux_command != SSHMUX_COMMAND_OPEN) {
1287 fatal("Control socket connect(%.100s): %s", path,
1290 if (errno == ENOENT)
1291 debug("Control socket \"%.100s\" does not exist", path);
1293 error("Control socket connect(%.100s): %s", path,
1300 if (stdin_null_flag) {
1301 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1302 fatal("open(/dev/null): %s", strerror(errno));
1303 if (dup2(fd, STDIN_FILENO) == -1)
1304 fatal("dup2: %s", strerror(errno));
1305 if (fd > STDERR_FILENO)
1309 term = getenv("TERM");
1313 flags |= SSHMUX_FLAG_TTY;
1315 flags |= SSHMUX_FLAG_SUBSYS;
1316 if (options.forward_x11)
1317 flags |= SSHMUX_FLAG_X11_FWD;
1318 if (options.forward_agent)
1319 flags |= SSHMUX_FLAG_AGENT_FWD;
1323 /* Send our command to server */
1324 buffer_put_int(&m, mux_command);
1325 buffer_put_int(&m, flags);
1326 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1327 fatal("%s: msg_send", __func__);
1330 /* Get authorisation status and PID of controlee */
1331 if (ssh_msg_recv(sock, &m) == -1)
1332 fatal("%s: msg_recv", __func__);
1333 if (buffer_get_char(&m) != SSHMUX_VER)
1334 fatal("%s: wrong version", __func__);
1335 if (buffer_get_int(&m) != 1)
1336 fatal("Connection to master denied");
1337 control_server_pid = buffer_get_int(&m);
1341 switch (mux_command) {
1342 case SSHMUX_COMMAND_ALIVE_CHECK:
1343 fprintf(stderr, "Master running (pid=%d)\r\n",
1344 control_server_pid);
1346 case SSHMUX_COMMAND_TERMINATE:
1347 fprintf(stderr, "Exit request sent.\r\n");
1349 case SSHMUX_COMMAND_OPEN:
1350 /* continue below */
1353 fatal("silly mux_command %d", mux_command);
1356 /* SSHMUX_COMMAND_OPEN */
1357 buffer_put_cstring(&m, term ? term : "");
1358 buffer_append(&command, "\0", 1);
1359 buffer_put_cstring(&m, buffer_ptr(&command));
1361 if (options.num_send_env == 0 || environ == NULL) {
1362 buffer_put_int(&m, 0);
1364 /* Pass environment */
1366 for (i = 0; environ[i] != NULL; i++)
1367 if (env_permitted(environ[i]))
1368 num_env++; /* Count */
1370 buffer_put_int(&m, num_env);
1372 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1373 if (env_permitted(environ[i])) {
1375 buffer_put_cstring(&m, environ[i]);
1379 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1380 fatal("%s: msg_send", __func__);
1382 mm_send_fd(sock, STDIN_FILENO);
1383 mm_send_fd(sock, STDOUT_FILENO);
1384 mm_send_fd(sock, STDERR_FILENO);
1386 /* Wait for reply, so master has a chance to gather ttymodes */
1388 if (ssh_msg_recv(sock, &m) == -1)
1389 fatal("%s: msg_recv", __func__);
1390 if (buffer_get_char(&m) != SSHMUX_VER)
1391 fatal("%s: wrong version", __func__);
1394 signal(SIGHUP, control_client_sighandler);
1395 signal(SIGINT, control_client_sighandler);
1396 signal(SIGTERM, control_client_sighandler);
1397 signal(SIGWINCH, control_client_sigrelay);
1402 /* Stick around until the controlee closes the client_fd */
1404 for (;!control_client_terminate;) {
1405 r = read(sock, &exitval, sizeof(exitval));
1407 debug2("Received EOF from master");
1411 debug2("Received exit status from master %d", exitval);
1412 if (r == -1 && errno != EINTR)
1413 fatal("%s: read %s", __func__, strerror(errno));
1416 if (control_client_terminate)
1417 debug2("Exiting on signal %d", control_client_terminate);
1423 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1424 fprintf(stderr, "Connection to master closed.\r\n");