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 [-1246AaCfgkMNnqrsTtVvXxY] [-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"
166 " [-r Receive Buffer Size in K]\n"
171 static int ssh_session(void);
172 static int ssh_session2(void);
173 static void load_public_identity_files(void);
174 static void control_client(const char *path);
177 * Main program for the ssh client.
180 main(int ac, char **av)
182 int i, opt, exit_status;
183 char *p, *cp, *line, buf[256];
187 extern int optind, optreset;
192 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
195 __progname = ssh_get_progname(av[0]);
199 * Save the original real uid. It will be needed later (uid-swapping
200 * may clobber the real uid).
202 original_real_uid = getuid();
203 original_effective_uid = geteuid();
206 * Use uid-swapping to give up root privileges for the duration of
207 * option processing. We will re-instantiate the rights when we are
208 * ready to create the privileged port, and will permanently drop
209 * them when the port has been created (actually, when the connection
210 * has been made, as we may need to create the port several times).
214 #ifdef HAVE_SETRLIMIT
215 /* If we are installed setuid root be careful to not drop core. */
216 if (original_real_uid != original_effective_uid) {
218 rlim.rlim_cur = rlim.rlim_max = 0;
219 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
220 fatal("setrlimit failed: %.100s", strerror(errno));
224 pw = getpwuid(original_real_uid);
226 logit("You don't exist, go away!");
229 /* Take a copy of the returned structure. */
233 * Set our umask to something reasonable, as some files are created
234 * with the default umask. This will make them world-readable but
235 * writable only by the owner, which is ok for all files for which we
236 * don't set the modes explicitly.
240 /* Initialize option structure to indicate that no values have been set. */
241 initialize_options(&options);
243 /* Parse command-line arguments. */
245 /* need to set options.tcp_rcv_buf to 0 */
246 options.tcp_rcv_buf = 0;
249 while ((opt = getopt(ac, av,
250 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XYz")) != -1) {
253 options.protocol = SSH_PROTO_1;
256 options.protocol = SSH_PROTO_2;
259 options.address_family = AF_INET;
262 options.address_family = AF_INET6;
268 fork_after_authentication_flag = 1;
272 options.forward_x11 = 0;
275 options.forward_x11 = 1;
278 options.forward_x11 = 1;
279 options.forward_x11_trusted = 1;
282 options.gateway_ports = 1;
285 if (strcmp(optarg, "check") == 0)
286 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
287 else if (strcmp(optarg, "exit") == 0)
288 mux_command = SSHMUX_COMMAND_TERMINATE;
290 fatal("Invalid multiplex command.");
292 case 'P': /* deprecated */
293 options.use_privileged_port = 0;
296 options.forward_agent = 0;
299 options.forward_agent = 1;
302 options.gss_deleg_creds = 0;
305 if (stat(optarg, &st) < 0) {
306 fprintf(stderr, "Warning: Identity file %s "
307 "not accessible: %s.\n", optarg,
311 if (options.num_identity_files >=
312 SSH_MAX_IDENTITY_FILES)
313 fatal("Too many identity files specified "
314 "(max %d)", SSH_MAX_IDENTITY_FILES);
315 options.identity_files[options.num_identity_files++] =
320 options.smartcard_device = xstrdup(optarg);
322 fprintf(stderr, "no support for smartcards.\n");
331 if (debug_flag == 0) {
333 options.log_level = SYSLOG_LEVEL_DEBUG1;
335 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
341 fprintf(stderr, "%s, %s\n",
342 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
347 if (options.tun_open == -1)
348 options.tun_open = SSH_TUNMODE_DEFAULT;
349 options.tun_local = a2tun(optarg, &options.tun_remote);
350 if (options.tun_local == SSH_TUNID_ERR) {
351 fprintf(stderr, "Bad tun device '%s'\n", optarg);
356 options.log_level = SYSLOG_LEVEL_QUIET;
359 if (optarg[0] == '^' && optarg[2] == 0 &&
360 (u_char) optarg[1] >= 64 &&
361 (u_char) optarg[1] < 128)
362 options.escape_char = (u_char) optarg[1] & 31;
363 else if (strlen(optarg) == 1)
364 options.escape_char = (u_char) optarg[0];
365 else if (strcmp(optarg, "none") == 0)
366 options.escape_char = SSH_ESCAPECHAR_NONE;
368 fprintf(stderr, "Bad escape character '%s'.\n",
374 if (ciphers_valid(optarg)) {
376 options.ciphers = xstrdup(optarg);
377 options.cipher = SSH_CIPHER_INVALID;
380 options.cipher = cipher_number(optarg);
381 if (options.cipher == -1) {
383 "Unknown cipher type '%s'\n",
387 if (options.cipher == SSH_CIPHER_3DES)
388 options.ciphers = "3des-cbc";
389 else if (options.cipher == SSH_CIPHER_BLOWFISH)
390 options.ciphers = "blowfish-cbc";
392 options.ciphers = (char *)-1;
396 if (mac_valid(optarg))
397 options.macs = xstrdup(optarg);
399 fprintf(stderr, "Unknown mac type '%s'\n",
405 if (options.control_master == SSHCTL_MASTER_YES)
406 options.control_master = SSHCTL_MASTER_ASK;
408 options.control_master = SSHCTL_MASTER_YES;
411 options.port = a2port(optarg);
412 if (options.port == 0) {
413 fprintf(stderr, "Bad port '%s'\n", optarg);
418 options.user = optarg;
422 if (parse_forward(&fwd, optarg))
423 add_local_forward(&options, &fwd);
426 "Bad local forwarding specification '%s'\n",
433 if (parse_forward(&fwd, optarg)) {
434 add_remote_forward(&options, &fwd);
437 "Bad remote forwarding specification "
444 cp = p = xstrdup(optarg);
445 memset(&fwd, '\0', sizeof(fwd));
446 fwd.connect_host = "socks";
447 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
448 fprintf(stderr, "Bad dynamic forwarding "
449 "specification '%.100s'\n", optarg);
453 fwd.listen_port = a2port(cp);
454 fwd.listen_host = cleanhostname(fwd.listen_host);
456 fwd.listen_port = a2port(fwd.listen_host);
457 fwd.listen_host = NULL;
460 if (fwd.listen_port == 0) {
461 fprintf(stderr, "Bad dynamic port '%s'\n",
465 add_local_forward(&options, &fwd);
470 options.compression = 1;
475 options.none_switch = 0;
479 options.none_switch = 0;
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;
504 options.tcp_rcv_buf = atoi(optarg) * 1024;
507 /* make sure we can't turn on the none_switch */
508 /* if they try to force a no tty flag on a tty session */
510 options.none_switch = 1;
522 if (ac > 0 && !host && **av != '-') {
523 if (strrchr(*av, '@')) {
525 cp = strrchr(p, '@');
526 if (cp == NULL || cp == p)
534 optind = optreset = 1;
540 /* Check that we got a host name. */
544 SSLeay_add_all_algorithms();
545 ERR_load_crypto_strings();
547 /* Initialize the command to execute on remote host. */
548 buffer_init(&command);
551 * Save the command to execute on the remote host in a buffer. There
552 * is no limit on the length of the command, except by the maximum
553 * packet size. Also sets the tty flag if there is no command.
556 /* No command specified - execute shell on a tty. */
558 if (subsystem_flag) {
560 "You must specify a subsystem to invoke.\n");
564 /* A command has been specified. Store it into the buffer. */
565 for (i = 0; i < ac; i++) {
567 buffer_append(&command, " ", 1);
568 buffer_append(&command, av[i], strlen(av[i]));
572 /* Cannot fork to background if no command. */
573 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
574 fatal("Cannot fork into background without a command to execute.");
576 /* Allocate a tty by default if no command specified. */
577 if (buffer_len(&command) == 0)
583 /* Do not allocate a tty if stdin is not a tty. */
584 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
586 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
591 * Initialize "log" output. Since we are the client all output
592 * actually goes to stderr.
594 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
595 SYSLOG_FACILITY_USER, 1);
598 * Read per-user configuration file. Ignore the system wide config
599 * file if the user specifies a config file on the command line.
601 if (config != NULL) {
602 if (!read_config_file(config, host, &options, 0))
603 fatal("Can't open user config file %.100s: "
604 "%.100s", config, strerror(errno));
607 * Since the config file parsing code aborts if it sees
608 * options it doesn't recognize, allow users to put
609 * options specific to compile-time add-ons in alternate
610 * config files so their primary config file will
611 * interoperate SSH versions that don't support those
615 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
616 _PATH_SSH_USER_CONFFILE);
617 (void)read_config_file(buf, host, &options, 1);
619 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
620 _PATH_SSH_USER_CONFFILE);
621 (void)read_config_file(buf, host, &options, 1);
624 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
625 _PATH_SSH_USER_CONFFILE);
626 (void)read_config_file(buf, host, &options, 1);
629 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
630 _PATH_SSH_USER_CONFFILE);
631 (void)read_config_file(buf, host, &options, 1);
633 /* Read systemwide configuration file after use config. */
634 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
638 /* Fill configuration defaults. */
639 fill_default_options(&options);
641 channel_set_af(options.address_family);
644 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
648 if (options.user == NULL) {
649 options.user = xstrdup(pw->pw_name);
650 options.implicit = 1;
652 else options.implicit = 0;
654 if (options.hostname != NULL)
655 host = options.hostname;
657 /* force lowercase for hostkey matching */
658 if (options.host_key_alias != NULL) {
659 for (p = options.host_key_alias; *p; p++)
664 /* Get default port if port has not been set. */
665 if (options.port == 0) {
666 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
667 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
670 if (options.proxy_command != NULL &&
671 strcmp(options.proxy_command, "none") == 0)
672 options.proxy_command = NULL;
673 if (options.control_path != NULL &&
674 strcmp(options.control_path, "none") == 0)
675 options.control_path = NULL;
677 if (options.control_path != NULL) {
678 snprintf(buf, sizeof(buf), "%d", options.port);
679 cp = tilde_expand_filename(options.control_path,
681 options.control_path = percent_expand(cp, "p", buf, "h", host,
682 "r", options.user, (char *)NULL);
685 if (mux_command != 0 && options.control_path == NULL)
686 fatal("No ControlPath specified for \"-O\" command");
687 if (options.control_path != NULL)
688 control_client(options.control_path);
690 /* Open a connection to the remote host. */
691 if (ssh_connect(host, &hostaddr, options.port,
692 options.address_family, options.connection_attempts,
694 options.use_privileged_port,
696 original_effective_uid == 0 && options.use_privileged_port,
698 options.proxy_command) != 0)
702 * If we successfully made the connection, load the host private key
703 * in case we will need it later for combined rsa-rhosts
704 * authentication. This must be done before releasing extra
705 * privileges, because the file is only readable by root.
706 * If we cannot access the private keys, load the public keys
707 * instead and try to execute the ssh-keysign helper instead.
709 sensitive_data.nkeys = 0;
710 sensitive_data.keys = NULL;
711 sensitive_data.external_keysign = 0;
712 if (options.rhosts_rsa_authentication ||
713 options.hostbased_authentication) {
714 sensitive_data.nkeys = 3;
715 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
719 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
720 _PATH_HOST_KEY_FILE, "", NULL);
721 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
722 _PATH_HOST_DSA_KEY_FILE, "", NULL);
723 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
724 _PATH_HOST_RSA_KEY_FILE, "", NULL);
727 if (options.hostbased_authentication == 1 &&
728 sensitive_data.keys[0] == NULL &&
729 sensitive_data.keys[1] == NULL &&
730 sensitive_data.keys[2] == NULL) {
731 sensitive_data.keys[1] = key_load_public(
732 _PATH_HOST_DSA_KEY_FILE, NULL);
733 sensitive_data.keys[2] = key_load_public(
734 _PATH_HOST_RSA_KEY_FILE, NULL);
735 sensitive_data.external_keysign = 1;
739 * Get rid of any extra privileges that we may have. We will no
740 * longer need them. Also, extra privileges could make it very hard
741 * to read identity files and other non-world-readable files from the
742 * user's home directory if it happens to be on a NFS volume where
743 * root is mapped to nobody.
745 if (original_effective_uid == 0) {
747 permanently_set_uid(pw);
751 * Now that we are back to our own permissions, create ~/.ssh
752 * directory if it doesn't already exist.
754 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
755 if (stat(buf, &st) < 0)
756 if (mkdir(buf, 0700) < 0)
757 error("Could not create directory '%.200s'.", buf);
759 /* load options.identity_files */
760 load_public_identity_files();
762 /* Expand ~ in known host file names. */
764 options.system_hostfile =
765 tilde_expand_filename(options.system_hostfile, original_real_uid);
766 options.user_hostfile =
767 tilde_expand_filename(options.user_hostfile, original_real_uid);
768 options.system_hostfile2 =
769 tilde_expand_filename(options.system_hostfile2, original_real_uid);
770 options.user_hostfile2 =
771 tilde_expand_filename(options.user_hostfile2, original_real_uid);
773 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
775 /* Log into the remote system. This never returns if the login fails. */
776 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
778 /* We no longer need the private host keys. Clear them now. */
779 if (sensitive_data.nkeys != 0) {
780 for (i = 0; i < sensitive_data.nkeys; i++) {
781 if (sensitive_data.keys[i] != NULL) {
782 /* Destroys contents safely */
783 debug3("clear hostkey %d", i);
784 key_free(sensitive_data.keys[i]);
785 sensitive_data.keys[i] = NULL;
788 xfree(sensitive_data.keys);
790 for (i = 0; i < options.num_identity_files; i++) {
791 if (options.identity_files[i]) {
792 xfree(options.identity_files[i]);
793 options.identity_files[i] = NULL;
795 if (options.identity_keys[i]) {
796 key_free(options.identity_keys[i]);
797 options.identity_keys[i] = NULL;
801 exit_status = compat20 ? ssh_session2() : ssh_session();
804 if (options.control_path != NULL && control_fd != -1)
805 unlink(options.control_path);
808 * Send SIGHUP to proxy command if used. We don't wait() in
809 * case it hangs and instead rely on init to reap the child
811 if (proxy_command_pid > 1)
812 kill(proxy_command_pid, SIGHUP);
818 ssh_init_forwarding(void)
823 /* Initiate local TCP/IP port forwardings. */
824 for (i = 0; i < options.num_local_forwards; i++) {
825 debug("Local connections to %.200s:%d forwarded to remote "
827 (options.local_forwards[i].listen_host == NULL) ?
828 (options.gateway_ports ? "*" : "LOCALHOST") :
829 options.local_forwards[i].listen_host,
830 options.local_forwards[i].listen_port,
831 options.local_forwards[i].connect_host,
832 options.local_forwards[i].connect_port);
833 success += channel_setup_local_fwd_listener(
834 options.local_forwards[i].listen_host,
835 options.local_forwards[i].listen_port,
836 options.local_forwards[i].connect_host,
837 options.local_forwards[i].connect_port,
838 options.gateway_ports);
840 if (i > 0 && success == 0)
841 error("Could not request local forwarding.");
843 /* Initiate remote TCP/IP port forwardings. */
844 for (i = 0; i < options.num_remote_forwards; i++) {
845 debug("Remote connections from %.200s:%d forwarded to "
846 "local address %.200s:%d",
847 (options.remote_forwards[i].listen_host == NULL) ?
848 "LOCALHOST" : options.remote_forwards[i].listen_host,
849 options.remote_forwards[i].listen_port,
850 options.remote_forwards[i].connect_host,
851 options.remote_forwards[i].connect_port);
852 channel_request_remote_forwarding(
853 options.remote_forwards[i].listen_host,
854 options.remote_forwards[i].listen_port,
855 options.remote_forwards[i].connect_host,
856 options.remote_forwards[i].connect_port);
861 check_agent_present(void)
863 if (options.forward_agent) {
864 /* Clear agent forwarding if we don't have an agent. */
865 if (!ssh_agent_present())
866 options.forward_agent = 0;
880 /* Enable compression if requested. */
881 if (options.compression) {
882 debug("Requesting compression at level %d.", options.compression_level);
884 if (options.compression_level < 1 || options.compression_level > 9)
885 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
887 /* Send the request. */
888 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
889 packet_put_int(options.compression_level);
892 type = packet_read();
893 if (type == SSH_SMSG_SUCCESS)
894 packet_start_compression(options.compression_level);
895 else if (type == SSH_SMSG_FAILURE)
896 logit("Warning: Remote host refused compression.");
898 packet_disconnect("Protocol error waiting for compression response.");
900 /* Allocate a pseudo tty if appropriate. */
902 debug("Requesting pty.");
904 /* Start the packet. */
905 packet_start(SSH_CMSG_REQUEST_PTY);
907 /* Store TERM in the packet. There is no limit on the
908 length of the string. */
912 packet_put_cstring(cp);
914 /* Store window size in the packet. */
915 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
916 memset(&ws, 0, sizeof(ws));
917 packet_put_int(ws.ws_row);
918 packet_put_int(ws.ws_col);
919 packet_put_int(ws.ws_xpixel);
920 packet_put_int(ws.ws_ypixel);
922 /* Store tty modes in the packet. */
923 tty_make_modes(fileno(stdin), NULL);
925 /* Send the packet, and wait for it to leave. */
929 /* Read response from the server. */
930 type = packet_read();
931 if (type == SSH_SMSG_SUCCESS) {
934 } else if (type == SSH_SMSG_FAILURE)
935 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
937 packet_disconnect("Protocol error waiting for pty request response.");
939 /* Request X11 forwarding if enabled and DISPLAY is set. */
940 display = getenv("DISPLAY");
941 if (options.forward_x11 && display != NULL) {
943 /* Get reasonable local authentication information. */
944 client_x11_get_proto(display, options.xauth_location,
945 options.forward_x11_trusted, &proto, &data);
946 /* Request forwarding with authentication spoofing. */
947 debug("Requesting X11 forwarding with authentication spoofing.");
948 x11_request_forwarding_with_spoofing(0, display, proto, data);
950 /* Read response from the server. */
951 type = packet_read();
952 if (type == SSH_SMSG_SUCCESS) {
954 } else if (type == SSH_SMSG_FAILURE) {
955 logit("Warning: Remote host denied X11 forwarding.");
957 packet_disconnect("Protocol error waiting for X11 forwarding");
960 /* Tell the packet module whether this is an interactive session. */
961 packet_set_interactive(interactive);
963 /* Request authentication agent forwarding if appropriate. */
964 check_agent_present();
966 if (options.forward_agent) {
967 debug("Requesting authentication agent forwarding.");
968 auth_request_forwarding();
970 /* Read response from the server. */
971 type = packet_read();
973 if (type != SSH_SMSG_SUCCESS)
974 logit("Warning: Remote host denied authentication agent forwarding.");
977 /* Initiate port forwardings. */
978 ssh_init_forwarding();
980 /* If requested, let ssh continue in the background. */
981 if (fork_after_authentication_flag)
982 if (daemon(1, 1) < 0)
983 fatal("daemon() failed: %.200s", strerror(errno));
986 * If a command was specified on the command line, execute the
987 * command now. Otherwise request the server to start a shell.
989 if (buffer_len(&command) > 0) {
990 int len = buffer_len(&command);
993 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
994 packet_start(SSH_CMSG_EXEC_CMD);
995 packet_put_string(buffer_ptr(&command), buffer_len(&command));
999 debug("Requesting shell.");
1000 packet_start(SSH_CMSG_EXEC_SHELL);
1002 packet_write_wait();
1005 /* Enter the interactive session. */
1006 return client_loop(have_tty, tty_flag ?
1007 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1011 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1015 id = packet_get_int();
1016 len = buffer_len(&command);
1020 if (type == SSH2_MSG_CHANNEL_FAILURE)
1021 fatal("Request for subsystem '%.*s' failed on channel %d",
1022 len, (u_char *)buffer_ptr(&command), id);
1026 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1030 i = client_global_request_id++;
1031 if (i >= options.num_remote_forwards)
1033 debug("remote forward %s for: listen %d, connect %s:%d",
1034 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1035 options.remote_forwards[i].listen_port,
1036 options.remote_forwards[i].connect_host,
1037 options.remote_forwards[i].connect_port);
1038 if (type == SSH2_MSG_REQUEST_FAILURE)
1039 logit("Warning: remote port forwarding failed for listen "
1040 "port %d", options.remote_forwards[i].listen_port);
1044 ssh_control_listener(void)
1046 struct sockaddr_un addr;
1050 if (options.control_path == NULL ||
1051 options.control_master == SSHCTL_MASTER_NO)
1054 debug("setting up multiplex master socket");
1056 memset(&addr, '\0', sizeof(addr));
1057 addr.sun_family = AF_UNIX;
1058 addr_len = offsetof(struct sockaddr_un, sun_path) +
1059 strlen(options.control_path) + 1;
1061 if (strlcpy(addr.sun_path, options.control_path,
1062 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1063 fatal("ControlPath too long");
1065 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1066 fatal("%s socket(): %s", __func__, strerror(errno));
1068 old_umask = umask(0177);
1069 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1071 if (errno == EINVAL || errno == EADDRINUSE)
1072 fatal("ControlSocket %s already exists",
1073 options.control_path);
1075 fatal("%s bind(): %s", __func__, strerror(errno));
1079 if (listen(control_fd, 64) == -1)
1080 fatal("%s listen(): %s", __func__, strerror(errno));
1082 set_nonblock(control_fd);
1085 /* request pty/x11/agent/tcpfwd/shell for channel */
1087 ssh_session2_setup(int id, void *arg)
1089 extern char **environ;
1090 const char *display;
1091 int interactive = tty_flag;
1093 display = getenv("DISPLAY");
1094 if (options.forward_x11 && display != NULL) {
1096 /* Get reasonable local authentication information. */
1097 client_x11_get_proto(display, options.xauth_location,
1098 options.forward_x11_trusted, &proto, &data);
1099 /* Request forwarding with authentication spoofing. */
1100 debug("Requesting X11 forwarding with authentication spoofing.");
1101 x11_request_forwarding_with_spoofing(id, display, proto, data);
1103 /* XXX wait for reply */
1106 check_agent_present();
1107 if (options.forward_agent) {
1108 debug("Requesting authentication agent forwarding.");
1109 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1113 if (options.tun_open != SSH_TUNMODE_NO) {
1117 debug("Requesting tun.");
1118 if ((fd = tun_open(options.tun_local,
1119 options.tun_open)) >= 0) {
1120 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1121 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1124 #if defined(SSH_TUN_FILTER)
1125 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1126 channel_register_filter(c->self, sys_tun_infilter,
1129 packet_start(SSH2_MSG_CHANNEL_OPEN);
1130 packet_put_cstring("tun@openssh.com");
1131 packet_put_int(c->self);
1132 packet_put_int(c->local_window_max);
1133 packet_put_int(c->local_maxpacket);
1134 packet_put_int(options.tun_open);
1135 packet_put_int(options.tun_remote);
1140 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1141 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1143 packet_set_interactive(interactive);
1146 /* open new channel for a session */
1148 ssh_session2_open(void)
1151 int window, packetmax, in, out, err;
1153 if (stdin_null_flag) {
1154 in = open(_PATH_DEVNULL, O_RDONLY);
1156 in = dup(STDIN_FILENO);
1158 out = dup(STDOUT_FILENO);
1159 err = dup(STDERR_FILENO);
1161 if (in < 0 || out < 0 || err < 0)
1162 fatal("dup() in/out/err failed");
1164 /* enable nonblocking unless tty */
1172 window = CHAN_SES_WINDOW_DEFAULT;
1173 packetmax = CHAN_SES_PACKET_DEFAULT;
1175 window = 4*CHAN_SES_PACKET_DEFAULT;
1180 "session", SSH_CHANNEL_OPENING, in, out, err,
1181 window, packetmax, CHAN_EXTENDED_WRITE,
1182 "client-session", /*nonblock*/0);
1183 if (!tty_flag && (!(datafellows & SSH_BUG_LARGEWINDOW))) {
1184 c->dynamic_window = 1;
1186 debug3("ssh_session2_open: channel_new: %d", c->self);
1188 channel_send_open(c->self);
1190 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1200 /* XXX should be pre-session */
1201 ssh_init_forwarding();
1202 ssh_control_listener();
1204 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1205 id = ssh_session2_open();
1207 /* Execute a local command */
1208 if (options.local_command != NULL &&
1209 options.permit_local_command)
1210 ssh_local_cmd(options.local_command);
1212 /* If requested, let ssh continue in the background. */
1213 if (fork_after_authentication_flag)
1214 if (daemon(1, 1) < 0)
1215 fatal("daemon() failed: %.200s", strerror(errno));
1217 return client_loop(tty_flag, tty_flag ?
1218 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1222 load_public_identity_files(void)
1230 if (options.smartcard_device != NULL &&
1231 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1232 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1234 for (i = 0; keys[i] != NULL; i++) {
1236 memmove(&options.identity_files[1], &options.identity_files[0],
1237 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1238 memmove(&options.identity_keys[1], &options.identity_keys[0],
1239 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1240 options.num_identity_files++;
1241 options.identity_keys[0] = keys[i];
1242 options.identity_files[0] = sc_get_key_label(keys[i]);
1244 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1245 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1249 #endif /* SMARTCARD */
1250 for (; i < options.num_identity_files; i++) {
1251 filename = tilde_expand_filename(options.identity_files[i],
1253 public = key_load_public(filename, NULL);
1254 debug("identity file %s type %d", filename,
1255 public ? public->type : -1);
1256 xfree(options.identity_files[i]);
1257 options.identity_files[i] = filename;
1258 options.identity_keys[i] = public;
1263 control_client_sighandler(int signo)
1265 control_client_terminate = signo;
1269 control_client_sigrelay(int signo)
1271 if (control_server_pid > 1)
1272 kill(control_server_pid, signo);
1276 env_permitted(char *env)
1279 char name[1024], *cp;
1281 strlcpy(name, env, sizeof(name));
1282 if ((cp = strchr(name, '=')) == NULL)
1287 for (i = 0; i < options.num_send_env; i++)
1288 if (match_pattern(name, options.send_env[i]))
1295 control_client(const char *path)
1297 struct sockaddr_un addr;
1298 int i, r, fd, sock, exitval, num_env, addr_len;
1301 extern char **environ;
1304 if (mux_command == 0)
1305 mux_command = SSHMUX_COMMAND_OPEN;
1307 switch (options.control_master) {
1308 case SSHCTL_MASTER_AUTO:
1309 case SSHCTL_MASTER_AUTO_ASK:
1310 debug("auto-mux: Trying existing master");
1312 case SSHCTL_MASTER_NO:
1318 memset(&addr, '\0', sizeof(addr));
1319 addr.sun_family = AF_UNIX;
1320 addr_len = offsetof(struct sockaddr_un, sun_path) +
1323 if (strlcpy(addr.sun_path, path,
1324 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1325 fatal("ControlPath too long");
1327 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1328 fatal("%s socket(): %s", __func__, strerror(errno));
1330 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1331 if (mux_command != SSHMUX_COMMAND_OPEN) {
1332 fatal("Control socket connect(%.100s): %s", path,
1335 if (errno == ENOENT)
1336 debug("Control socket \"%.100s\" does not exist", path);
1338 error("Control socket connect(%.100s): %s", path,
1345 if (stdin_null_flag) {
1346 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1347 fatal("open(/dev/null): %s", strerror(errno));
1348 if (dup2(fd, STDIN_FILENO) == -1)
1349 fatal("dup2: %s", strerror(errno));
1350 if (fd > STDERR_FILENO)
1354 term = getenv("TERM");
1358 flags |= SSHMUX_FLAG_TTY;
1360 flags |= SSHMUX_FLAG_SUBSYS;
1361 if (options.forward_x11)
1362 flags |= SSHMUX_FLAG_X11_FWD;
1363 if (options.forward_agent)
1364 flags |= SSHMUX_FLAG_AGENT_FWD;
1368 /* Send our command to server */
1369 buffer_put_int(&m, mux_command);
1370 buffer_put_int(&m, flags);
1371 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1372 fatal("%s: msg_send", __func__);
1375 /* Get authorisation status and PID of controlee */
1376 if (ssh_msg_recv(sock, &m) == -1)
1377 fatal("%s: msg_recv", __func__);
1378 if (buffer_get_char(&m) != SSHMUX_VER)
1379 fatal("%s: wrong version", __func__);
1380 if (buffer_get_int(&m) != 1)
1381 fatal("Connection to master denied");
1382 control_server_pid = buffer_get_int(&m);
1386 switch (mux_command) {
1387 case SSHMUX_COMMAND_ALIVE_CHECK:
1388 fprintf(stderr, "Master running (pid=%d)\r\n",
1389 control_server_pid);
1391 case SSHMUX_COMMAND_TERMINATE:
1392 fprintf(stderr, "Exit request sent.\r\n");
1394 case SSHMUX_COMMAND_OPEN:
1395 /* continue below */
1398 fatal("silly mux_command %d", mux_command);
1401 /* SSHMUX_COMMAND_OPEN */
1402 buffer_put_cstring(&m, term ? term : "");
1403 buffer_append(&command, "\0", 1);
1404 buffer_put_cstring(&m, buffer_ptr(&command));
1406 if (options.num_send_env == 0 || environ == NULL) {
1407 buffer_put_int(&m, 0);
1409 /* Pass environment */
1411 for (i = 0; environ[i] != NULL; i++)
1412 if (env_permitted(environ[i]))
1413 num_env++; /* Count */
1415 buffer_put_int(&m, num_env);
1417 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1418 if (env_permitted(environ[i])) {
1420 buffer_put_cstring(&m, environ[i]);
1424 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1425 fatal("%s: msg_send", __func__);
1427 mm_send_fd(sock, STDIN_FILENO);
1428 mm_send_fd(sock, STDOUT_FILENO);
1429 mm_send_fd(sock, STDERR_FILENO);
1431 /* Wait for reply, so master has a chance to gather ttymodes */
1433 if (ssh_msg_recv(sock, &m) == -1)
1434 fatal("%s: msg_recv", __func__);
1435 if (buffer_get_char(&m) != SSHMUX_VER)
1436 fatal("%s: wrong version", __func__);
1439 signal(SIGHUP, control_client_sighandler);
1440 signal(SIGINT, control_client_sighandler);
1441 signal(SIGTERM, control_client_sighandler);
1442 signal(SIGWINCH, control_client_sigrelay);
1447 /* Stick around until the controlee closes the client_fd */
1449 for (;!control_client_terminate;) {
1450 r = read(sock, &exitval, sizeof(exitval));
1452 debug2("Received EOF from master");
1456 debug2("Received exit status from master %d", exitval);
1457 if (r == -1 && errno != EINTR)
1458 fatal("%s: read %s", __func__, strerror(errno));
1461 if (control_client_terminate)
1462 debug2("Exiting on signal %d", control_client_terminate);
1468 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1469 fprintf(stderr, "Connection to master closed.\r\n");