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.264 2006/02/20 17:19:54 stevesk Exp $");
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
55 #include <openssl/evp.h>
56 #include <openssl/err.h>
71 #include "pathnames.h"
73 #include "clientloop.h"
76 #include "sshconnect.h"
83 #include "monitor_fdpass.h"
90 extern char *__progname;
92 /* Flag indicating whether debug mode is on. This can be set on the command line. */
95 /* Flag indicating whether a tty should be allocated */
98 int force_tty_flag = 0;
100 /* don't exec a shell */
101 int no_shell_flag = 0;
104 * Flag indicating that nothing should be read from stdin. This can be set
105 * on the command line.
107 int stdin_null_flag = 0;
110 * Flag indicating that ssh should fork after authentication. This is useful
111 * so that the passphrase can be entered manually, and then ssh goes to the
114 int fork_after_authentication_flag = 0;
117 * General data structure for command line options and options configurable
118 * in configuration files. See readconf.h.
122 /* optional user configfile */
126 * Name of the host we are connecting to. This is the name given on the
127 * command line, or the HostName specified for the user-supplied name in a
128 * configuration file.
132 /* socket address the host resolves to */
133 struct sockaddr_storage hostaddr;
135 /* Private host keys. */
136 Sensitive sensitive_data;
138 /* Original real UID. */
139 uid_t original_real_uid;
140 uid_t original_effective_uid;
142 /* command to be executed */
145 /* Should we execute a command or invoke a subsystem? */
146 int subsystem_flag = 0;
148 /* # of replies received for global requests */
149 static int client_global_request_id = 0;
151 /* pid of proxycommand child process */
152 pid_t proxy_command_pid = 0;
154 /* fd to control socket */
157 /* Multiplexing control command */
158 static u_int mux_command = 0;
160 /* Only used in control client mode */
161 volatile sig_atomic_t control_client_terminate = 0;
162 u_int control_server_pid = 0;
164 /* Prints a help message to the user. This function never returns. */
170 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
171 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
172 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
173 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
174 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
175 " [-w tunnel:tunnel] [user@]hostname [command]\n"
180 static int ssh_session(void);
181 static int ssh_session2(void);
182 static void load_public_identity_files(void);
183 static void control_client(const char *path);
186 * Main program for the ssh client.
189 main(int ac, char **av)
191 int i, opt, exit_status;
192 char *p, *cp, *line, buf[256];
196 extern int optind, optreset;
201 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
204 __progname = ssh_get_progname(av[0]);
208 * Save the original real uid. It will be needed later (uid-swapping
209 * may clobber the real uid).
211 original_real_uid = getuid();
212 original_effective_uid = geteuid();
215 * Use uid-swapping to give up root privileges for the duration of
216 * option processing. We will re-instantiate the rights when we are
217 * ready to create the privileged port, and will permanently drop
218 * them when the port has been created (actually, when the connection
219 * has been made, as we may need to create the port several times).
223 #ifdef HAVE_SETRLIMIT
224 /* If we are installed setuid root be careful to not drop core. */
225 if (original_real_uid != original_effective_uid) {
227 rlim.rlim_cur = rlim.rlim_max = 0;
228 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
229 fatal("setrlimit failed: %.100s", strerror(errno));
233 pw = getpwuid(original_real_uid);
235 logit("You don't exist, go away!");
238 /* Take a copy of the returned structure. */
242 * Set our umask to something reasonable, as some files are created
243 * with the default umask. This will make them world-readable but
244 * writable only by the owner, which is ok for all files for which we
245 * don't set the modes explicitly.
249 /* Initialize option structure to indicate that no values have been set. */
250 initialize_options(&options);
252 /* Parse command-line arguments. */
256 while ((opt = getopt(ac, av,
257 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
260 options.protocol = SSH_PROTO_1;
263 options.protocol = SSH_PROTO_2;
266 options.address_family = AF_INET;
269 options.address_family = AF_INET6;
275 fork_after_authentication_flag = 1;
279 options.forward_x11 = 0;
282 options.forward_x11 = 1;
285 options.forward_x11 = 1;
286 options.forward_x11_trusted = 1;
289 options.gateway_ports = 1;
292 if (strcmp(optarg, "check") == 0)
293 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
294 else if (strcmp(optarg, "exit") == 0)
295 mux_command = SSHMUX_COMMAND_TERMINATE;
297 fatal("Invalid multiplex command.");
299 case 'P': /* deprecated */
300 options.use_privileged_port = 0;
303 options.forward_agent = 0;
306 options.forward_agent = 1;
309 options.gss_deleg_creds = 0;
312 if (stat(optarg, &st) < 0) {
313 fprintf(stderr, "Warning: Identity file %s "
314 "not accessible: %s.\n", optarg,
318 if (options.num_identity_files >=
319 SSH_MAX_IDENTITY_FILES)
320 fatal("Too many identity files specified "
321 "(max %d)", SSH_MAX_IDENTITY_FILES);
322 options.identity_files[options.num_identity_files++] =
327 options.smartcard_device = xstrdup(optarg);
329 fprintf(stderr, "no support for smartcards.\n");
338 if (debug_flag == 0) {
340 options.log_level = SYSLOG_LEVEL_DEBUG1;
342 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
348 fprintf(stderr, "%s, %s\n",
349 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
354 if (options.tun_open == -1)
355 options.tun_open = SSH_TUNMODE_DEFAULT;
356 options.tun_local = a2tun(optarg, &options.tun_remote);
357 if (options.tun_local == SSH_TUNID_ERR) {
358 fprintf(stderr, "Bad tun device '%s'\n", optarg);
363 options.log_level = SYSLOG_LEVEL_QUIET;
366 if (optarg[0] == '^' && optarg[2] == 0 &&
367 (u_char) optarg[1] >= 64 &&
368 (u_char) optarg[1] < 128)
369 options.escape_char = (u_char) optarg[1] & 31;
370 else if (strlen(optarg) == 1)
371 options.escape_char = (u_char) optarg[0];
372 else if (strcmp(optarg, "none") == 0)
373 options.escape_char = SSH_ESCAPECHAR_NONE;
375 fprintf(stderr, "Bad escape character '%s'.\n",
381 if (ciphers_valid(optarg)) {
383 options.ciphers = xstrdup(optarg);
384 options.cipher = SSH_CIPHER_INVALID;
387 options.cipher = cipher_number(optarg);
388 if (options.cipher == -1) {
390 "Unknown cipher type '%s'\n",
394 if (options.cipher == SSH_CIPHER_3DES)
395 options.ciphers = "3des-cbc";
396 else if (options.cipher == SSH_CIPHER_BLOWFISH)
397 options.ciphers = "blowfish-cbc";
399 options.ciphers = (char *)-1;
403 if (mac_valid(optarg))
404 options.macs = xstrdup(optarg);
406 fprintf(stderr, "Unknown mac type '%s'\n",
412 if (options.control_master == SSHCTL_MASTER_YES)
413 options.control_master = SSHCTL_MASTER_ASK;
415 options.control_master = SSHCTL_MASTER_YES;
418 options.port = a2port(optarg);
419 if (options.port == 0) {
420 fprintf(stderr, "Bad port '%s'\n", optarg);
425 options.user = optarg;
429 if (parse_forward(&fwd, optarg))
430 add_local_forward(&options, &fwd);
433 "Bad local forwarding specification '%s'\n",
440 if (parse_forward(&fwd, optarg)) {
441 add_remote_forward(&options, &fwd);
444 "Bad remote forwarding specification "
451 cp = p = xstrdup(optarg);
452 memset(&fwd, '\0', sizeof(fwd));
453 fwd.connect_host = "socks";
454 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
455 fprintf(stderr, "Bad dynamic forwarding "
456 "specification '%.100s'\n", optarg);
460 fwd.listen_port = a2port(cp);
461 fwd.listen_host = cleanhostname(fwd.listen_host);
463 fwd.listen_port = a2port(fwd.listen_host);
464 fwd.listen_host = NULL;
467 if (fwd.listen_port == 0) {
468 fprintf(stderr, "Bad dynamic port '%s'\n",
472 add_local_forward(&options, &fwd);
477 options.compression = 1;
488 line = xstrdup(optarg);
489 if (process_config_line(&options, host ? host : "",
490 line, "command-line", 0, &dummy) != 0)
498 if (options.control_path != NULL)
499 free(options.control_path);
500 options.control_path = xstrdup(optarg);
503 options.bind_address = optarg;
516 if (ac > 0 && !host && **av != '-') {
517 if (strrchr(*av, '@')) {
519 cp = strrchr(p, '@');
520 if (cp == NULL || cp == p)
528 optind = optreset = 1;
534 /* Check that we got a host name. */
538 SSLeay_add_all_algorithms();
539 ERR_load_crypto_strings();
541 /* Initialize the command to execute on remote host. */
542 buffer_init(&command);
545 * Save the command to execute on the remote host in a buffer. There
546 * is no limit on the length of the command, except by the maximum
547 * packet size. Also sets the tty flag if there is no command.
550 /* No command specified - execute shell on a tty. */
552 if (subsystem_flag) {
554 "You must specify a subsystem to invoke.\n");
558 /* A command has been specified. Store it into the buffer. */
559 for (i = 0; i < ac; i++) {
561 buffer_append(&command, " ", 1);
562 buffer_append(&command, av[i], strlen(av[i]));
566 /* Cannot fork to background if no command. */
567 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
568 fatal("Cannot fork into background without a command to execute.");
570 /* Allocate a tty by default if no command specified. */
571 if (buffer_len(&command) == 0)
577 /* Do not allocate a tty if stdin is not a tty. */
578 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
580 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
585 * Initialize "log" output. Since we are the client all output
586 * actually goes to stderr.
588 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
589 SYSLOG_FACILITY_USER, 1);
592 * Read per-user configuration file. Ignore the system wide config
593 * file if the user specifies a config file on the command line.
595 if (config != NULL) {
596 if (!read_config_file(config, host, &options, 0))
597 fatal("Can't open user config file %.100s: "
598 "%.100s", config, strerror(errno));
600 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
601 _PATH_SSH_USER_CONFFILE);
602 (void)read_config_file(buf, host, &options, 1);
604 /* Read systemwide configuration file after use config. */
605 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
609 /* Fill configuration defaults. */
610 fill_default_options(&options);
612 channel_set_af(options.address_family);
615 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
619 if (options.user == NULL)
620 options.user = xstrdup(pw->pw_name);
622 if (options.hostname != NULL)
623 host = options.hostname;
625 /* force lowercase for hostkey matching */
626 if (options.host_key_alias != NULL) {
627 for (p = options.host_key_alias; *p; p++)
632 /* Get default port if port has not been set. */
633 if (options.port == 0) {
634 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
635 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
638 if (options.proxy_command != NULL &&
639 strcmp(options.proxy_command, "none") == 0)
640 options.proxy_command = NULL;
641 if (options.control_path != NULL &&
642 strcmp(options.control_path, "none") == 0)
643 options.control_path = NULL;
645 if (options.control_path != NULL) {
648 if (gethostname(me, sizeof(me)) == -1)
649 fatal("gethostname: %s", strerror(errno));
650 snprintf(buf, sizeof(buf), "%d", options.port);
651 cp = tilde_expand_filename(options.control_path,
653 options.control_path = percent_expand(cp, "p", buf, "h", host,
654 "r", options.user, "l", me, (char *)NULL);
657 if (mux_command != 0 && options.control_path == NULL)
658 fatal("No ControlPath specified for \"-O\" command");
659 if (options.control_path != NULL)
660 control_client(options.control_path);
662 /* Open a connection to the remote host. */
663 if (ssh_connect(host, &hostaddr, options.port,
664 options.address_family, options.connection_attempts,
666 options.use_privileged_port,
668 original_effective_uid == 0 && options.use_privileged_port,
670 options.proxy_command) != 0)
674 * If we successfully made the connection, load the host private key
675 * in case we will need it later for combined rsa-rhosts
676 * authentication. This must be done before releasing extra
677 * privileges, because the file is only readable by root.
678 * If we cannot access the private keys, load the public keys
679 * instead and try to execute the ssh-keysign helper instead.
681 sensitive_data.nkeys = 0;
682 sensitive_data.keys = NULL;
683 sensitive_data.external_keysign = 0;
684 if (options.rhosts_rsa_authentication ||
685 options.hostbased_authentication) {
686 sensitive_data.nkeys = 3;
687 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
691 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
692 _PATH_HOST_KEY_FILE, "", NULL);
693 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
694 _PATH_HOST_DSA_KEY_FILE, "", NULL);
695 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
696 _PATH_HOST_RSA_KEY_FILE, "", NULL);
699 if (options.hostbased_authentication == 1 &&
700 sensitive_data.keys[0] == NULL &&
701 sensitive_data.keys[1] == NULL &&
702 sensitive_data.keys[2] == NULL) {
703 sensitive_data.keys[1] = key_load_public(
704 _PATH_HOST_DSA_KEY_FILE, NULL);
705 sensitive_data.keys[2] = key_load_public(
706 _PATH_HOST_RSA_KEY_FILE, NULL);
707 sensitive_data.external_keysign = 1;
711 * Get rid of any extra privileges that we may have. We will no
712 * longer need them. Also, extra privileges could make it very hard
713 * to read identity files and other non-world-readable files from the
714 * user's home directory if it happens to be on a NFS volume where
715 * root is mapped to nobody.
717 if (original_effective_uid == 0) {
719 permanently_set_uid(pw);
723 * Now that we are back to our own permissions, create ~/.ssh
724 * directory if it doesn't already exist.
726 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
727 if (stat(buf, &st) < 0)
728 if (mkdir(buf, 0700) < 0)
729 error("Could not create directory '%.200s'.", buf);
731 /* load options.identity_files */
732 load_public_identity_files();
734 /* Expand ~ in known host file names. */
736 options.system_hostfile =
737 tilde_expand_filename(options.system_hostfile, original_real_uid);
738 options.user_hostfile =
739 tilde_expand_filename(options.user_hostfile, original_real_uid);
740 options.system_hostfile2 =
741 tilde_expand_filename(options.system_hostfile2, original_real_uid);
742 options.user_hostfile2 =
743 tilde_expand_filename(options.user_hostfile2, original_real_uid);
745 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
747 /* Log into the remote system. This never returns if the login fails. */
748 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
750 /* We no longer need the private host keys. Clear them now. */
751 if (sensitive_data.nkeys != 0) {
752 for (i = 0; i < sensitive_data.nkeys; i++) {
753 if (sensitive_data.keys[i] != NULL) {
754 /* Destroys contents safely */
755 debug3("clear hostkey %d", i);
756 key_free(sensitive_data.keys[i]);
757 sensitive_data.keys[i] = NULL;
760 xfree(sensitive_data.keys);
762 for (i = 0; i < options.num_identity_files; i++) {
763 if (options.identity_files[i]) {
764 xfree(options.identity_files[i]);
765 options.identity_files[i] = NULL;
767 if (options.identity_keys[i]) {
768 key_free(options.identity_keys[i]);
769 options.identity_keys[i] = NULL;
773 exit_status = compat20 ? ssh_session2() : ssh_session();
776 if (options.control_path != NULL && control_fd != -1)
777 unlink(options.control_path);
780 * Send SIGHUP to proxy command if used. We don't wait() in
781 * case it hangs and instead rely on init to reap the child
783 if (proxy_command_pid > 1)
784 kill(proxy_command_pid, SIGHUP);
790 ssh_init_forwarding(void)
795 /* Initiate local TCP/IP port forwardings. */
796 for (i = 0; i < options.num_local_forwards; i++) {
797 debug("Local connections to %.200s:%d forwarded to remote "
799 (options.local_forwards[i].listen_host == NULL) ?
800 (options.gateway_ports ? "*" : "LOCALHOST") :
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 success += channel_setup_local_fwd_listener(
806 options.local_forwards[i].listen_host,
807 options.local_forwards[i].listen_port,
808 options.local_forwards[i].connect_host,
809 options.local_forwards[i].connect_port,
810 options.gateway_ports);
812 if (i > 0 && success == 0)
813 error("Could not request local forwarding.");
815 /* Initiate remote TCP/IP port forwardings. */
816 for (i = 0; i < options.num_remote_forwards; i++) {
817 debug("Remote connections from %.200s:%d forwarded to "
818 "local address %.200s:%d",
819 (options.remote_forwards[i].listen_host == NULL) ?
820 "LOCALHOST" : 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);
824 channel_request_remote_forwarding(
825 options.remote_forwards[i].listen_host,
826 options.remote_forwards[i].listen_port,
827 options.remote_forwards[i].connect_host,
828 options.remote_forwards[i].connect_port);
833 check_agent_present(void)
835 if (options.forward_agent) {
836 /* Clear agent forwarding if we don't have an agent. */
837 if (!ssh_agent_present())
838 options.forward_agent = 0;
852 /* Enable compression if requested. */
853 if (options.compression) {
854 debug("Requesting compression at level %d.", options.compression_level);
856 if (options.compression_level < 1 || options.compression_level > 9)
857 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
859 /* Send the request. */
860 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
861 packet_put_int(options.compression_level);
864 type = packet_read();
865 if (type == SSH_SMSG_SUCCESS)
866 packet_start_compression(options.compression_level);
867 else if (type == SSH_SMSG_FAILURE)
868 logit("Warning: Remote host refused compression.");
870 packet_disconnect("Protocol error waiting for compression response.");
872 /* Allocate a pseudo tty if appropriate. */
874 debug("Requesting pty.");
876 /* Start the packet. */
877 packet_start(SSH_CMSG_REQUEST_PTY);
879 /* Store TERM in the packet. There is no limit on the
880 length of the string. */
884 packet_put_cstring(cp);
886 /* Store window size in the packet. */
887 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
888 memset(&ws, 0, sizeof(ws));
889 packet_put_int(ws.ws_row);
890 packet_put_int(ws.ws_col);
891 packet_put_int(ws.ws_xpixel);
892 packet_put_int(ws.ws_ypixel);
894 /* Store tty modes in the packet. */
895 tty_make_modes(fileno(stdin), NULL);
897 /* Send the packet, and wait for it to leave. */
901 /* Read response from the server. */
902 type = packet_read();
903 if (type == SSH_SMSG_SUCCESS) {
906 } else if (type == SSH_SMSG_FAILURE)
907 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
909 packet_disconnect("Protocol error waiting for pty request response.");
911 /* Request X11 forwarding if enabled and DISPLAY is set. */
912 display = getenv("DISPLAY");
913 if (options.forward_x11 && display != NULL) {
915 /* Get reasonable local authentication information. */
916 client_x11_get_proto(display, options.xauth_location,
917 options.forward_x11_trusted, &proto, &data);
918 /* Request forwarding with authentication spoofing. */
919 debug("Requesting X11 forwarding with authentication spoofing.");
920 x11_request_forwarding_with_spoofing(0, display, proto, data);
922 /* Read response from the server. */
923 type = packet_read();
924 if (type == SSH_SMSG_SUCCESS) {
926 } else if (type == SSH_SMSG_FAILURE) {
927 logit("Warning: Remote host denied X11 forwarding.");
929 packet_disconnect("Protocol error waiting for X11 forwarding");
932 /* Tell the packet module whether this is an interactive session. */
933 packet_set_interactive(interactive);
935 /* Request authentication agent forwarding if appropriate. */
936 check_agent_present();
938 if (options.forward_agent) {
939 debug("Requesting authentication agent forwarding.");
940 auth_request_forwarding();
942 /* Read response from the server. */
943 type = packet_read();
945 if (type != SSH_SMSG_SUCCESS)
946 logit("Warning: Remote host denied authentication agent forwarding.");
949 /* Initiate port forwardings. */
950 ssh_init_forwarding();
952 /* If requested, let ssh continue in the background. */
953 if (fork_after_authentication_flag)
954 if (daemon(1, 1) < 0)
955 fatal("daemon() failed: %.200s", strerror(errno));
958 * If a command was specified on the command line, execute the
959 * command now. Otherwise request the server to start a shell.
961 if (buffer_len(&command) > 0) {
962 int len = buffer_len(&command);
965 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
966 packet_start(SSH_CMSG_EXEC_CMD);
967 packet_put_string(buffer_ptr(&command), buffer_len(&command));
971 debug("Requesting shell.");
972 packet_start(SSH_CMSG_EXEC_SHELL);
977 /* Enter the interactive session. */
978 return client_loop(have_tty, tty_flag ?
979 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
983 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
987 id = packet_get_int();
988 len = buffer_len(&command);
992 if (type == SSH2_MSG_CHANNEL_FAILURE)
993 fatal("Request for subsystem '%.*s' failed on channel %d",
994 len, (u_char *)buffer_ptr(&command), id);
998 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1002 i = client_global_request_id++;
1003 if (i >= options.num_remote_forwards)
1005 debug("remote forward %s for: listen %d, connect %s:%d",
1006 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1007 options.remote_forwards[i].listen_port,
1008 options.remote_forwards[i].connect_host,
1009 options.remote_forwards[i].connect_port);
1010 if (type == SSH2_MSG_REQUEST_FAILURE)
1011 logit("Warning: remote port forwarding failed for listen "
1012 "port %d", options.remote_forwards[i].listen_port);
1016 ssh_control_listener(void)
1018 struct sockaddr_un addr;
1022 if (options.control_path == NULL ||
1023 options.control_master == SSHCTL_MASTER_NO)
1026 debug("setting up multiplex master socket");
1028 memset(&addr, '\0', sizeof(addr));
1029 addr.sun_family = AF_UNIX;
1030 addr_len = offsetof(struct sockaddr_un, sun_path) +
1031 strlen(options.control_path) + 1;
1033 if (strlcpy(addr.sun_path, options.control_path,
1034 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1035 fatal("ControlPath too long");
1037 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1038 fatal("%s socket(): %s", __func__, strerror(errno));
1040 old_umask = umask(0177);
1041 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1043 if (errno == EINVAL || errno == EADDRINUSE)
1044 fatal("ControlSocket %s already exists",
1045 options.control_path);
1047 fatal("%s bind(): %s", __func__, strerror(errno));
1051 if (listen(control_fd, 64) == -1)
1052 fatal("%s listen(): %s", __func__, strerror(errno));
1054 set_nonblock(control_fd);
1057 /* request pty/x11/agent/tcpfwd/shell for channel */
1059 ssh_session2_setup(int id, void *arg)
1061 extern char **environ;
1062 const char *display;
1063 int interactive = tty_flag;
1065 display = getenv("DISPLAY");
1066 if (options.forward_x11 && display != NULL) {
1068 /* Get reasonable local authentication information. */
1069 client_x11_get_proto(display, options.xauth_location,
1070 options.forward_x11_trusted, &proto, &data);
1071 /* Request forwarding with authentication spoofing. */
1072 debug("Requesting X11 forwarding with authentication spoofing.");
1073 x11_request_forwarding_with_spoofing(id, display, proto, data);
1075 /* XXX wait for reply */
1078 check_agent_present();
1079 if (options.forward_agent) {
1080 debug("Requesting authentication agent forwarding.");
1081 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1085 if (options.tun_open != SSH_TUNMODE_NO) {
1089 debug("Requesting tun.");
1090 if ((fd = tun_open(options.tun_local,
1091 options.tun_open)) >= 0) {
1092 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1093 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1096 #if defined(SSH_TUN_FILTER)
1097 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1098 channel_register_filter(c->self, sys_tun_infilter,
1101 packet_start(SSH2_MSG_CHANNEL_OPEN);
1102 packet_put_cstring("tun@openssh.com");
1103 packet_put_int(c->self);
1104 packet_put_int(c->local_window_max);
1105 packet_put_int(c->local_maxpacket);
1106 packet_put_int(options.tun_open);
1107 packet_put_int(options.tun_remote);
1112 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1113 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1115 packet_set_interactive(interactive);
1118 /* open new channel for a session */
1120 ssh_session2_open(void)
1123 int window, packetmax, in, out, err;
1125 if (stdin_null_flag) {
1126 in = open(_PATH_DEVNULL, O_RDONLY);
1128 in = dup(STDIN_FILENO);
1130 out = dup(STDOUT_FILENO);
1131 err = dup(STDERR_FILENO);
1133 if (in < 0 || out < 0 || err < 0)
1134 fatal("dup() in/out/err failed");
1136 /* enable nonblocking unless tty */
1144 window = CHAN_SES_WINDOW_DEFAULT;
1145 packetmax = CHAN_SES_PACKET_DEFAULT;
1151 "session", SSH_CHANNEL_OPENING, in, out, err,
1152 window, packetmax, CHAN_EXTENDED_WRITE,
1153 "client-session", /*nonblock*/0);
1155 debug3("ssh_session2_open: channel_new: %d", c->self);
1157 channel_send_open(c->self);
1159 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1169 /* XXX should be pre-session */
1170 ssh_init_forwarding();
1171 ssh_control_listener();
1173 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1174 id = ssh_session2_open();
1176 /* Execute a local command */
1177 if (options.local_command != NULL &&
1178 options.permit_local_command)
1179 ssh_local_cmd(options.local_command);
1181 /* If requested, let ssh continue in the background. */
1182 if (fork_after_authentication_flag)
1183 if (daemon(1, 1) < 0)
1184 fatal("daemon() failed: %.200s", strerror(errno));
1186 return client_loop(tty_flag, tty_flag ?
1187 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1191 load_public_identity_files(void)
1199 if (options.smartcard_device != NULL &&
1200 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1201 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1203 for (i = 0; keys[i] != NULL; i++) {
1205 memmove(&options.identity_files[1], &options.identity_files[0],
1206 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1207 memmove(&options.identity_keys[1], &options.identity_keys[0],
1208 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1209 options.num_identity_files++;
1210 options.identity_keys[0] = keys[i];
1211 options.identity_files[0] = sc_get_key_label(keys[i]);
1213 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1214 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1218 #endif /* SMARTCARD */
1219 for (; i < options.num_identity_files; i++) {
1220 filename = tilde_expand_filename(options.identity_files[i],
1222 public = key_load_public(filename, NULL);
1223 debug("identity file %s type %d", filename,
1224 public ? public->type : -1);
1225 xfree(options.identity_files[i]);
1226 options.identity_files[i] = filename;
1227 options.identity_keys[i] = public;
1232 control_client_sighandler(int signo)
1234 control_client_terminate = signo;
1238 control_client_sigrelay(int signo)
1240 if (control_server_pid > 1)
1241 kill(control_server_pid, signo);
1245 env_permitted(char *env)
1248 char name[1024], *cp;
1250 strlcpy(name, env, sizeof(name));
1251 if ((cp = strchr(name, '=')) == NULL)
1256 for (i = 0; i < options.num_send_env; i++)
1257 if (match_pattern(name, options.send_env[i]))
1264 control_client(const char *path)
1266 struct sockaddr_un addr;
1267 int i, r, fd, sock, exitval, num_env, addr_len;
1270 extern char **environ;
1273 if (mux_command == 0)
1274 mux_command = SSHMUX_COMMAND_OPEN;
1276 switch (options.control_master) {
1277 case SSHCTL_MASTER_AUTO:
1278 case SSHCTL_MASTER_AUTO_ASK:
1279 debug("auto-mux: Trying existing master");
1281 case SSHCTL_MASTER_NO:
1287 memset(&addr, '\0', sizeof(addr));
1288 addr.sun_family = AF_UNIX;
1289 addr_len = offsetof(struct sockaddr_un, sun_path) +
1292 if (strlcpy(addr.sun_path, path,
1293 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1294 fatal("ControlPath too long");
1296 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1297 fatal("%s socket(): %s", __func__, strerror(errno));
1299 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1300 if (mux_command != SSHMUX_COMMAND_OPEN) {
1301 fatal("Control socket connect(%.100s): %s", path,
1304 if (errno == ENOENT)
1305 debug("Control socket \"%.100s\" does not exist", path);
1307 error("Control socket connect(%.100s): %s", path,
1314 if (stdin_null_flag) {
1315 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1316 fatal("open(/dev/null): %s", strerror(errno));
1317 if (dup2(fd, STDIN_FILENO) == -1)
1318 fatal("dup2: %s", strerror(errno));
1319 if (fd > STDERR_FILENO)
1323 term = getenv("TERM");
1327 flags |= SSHMUX_FLAG_TTY;
1329 flags |= SSHMUX_FLAG_SUBSYS;
1330 if (options.forward_x11)
1331 flags |= SSHMUX_FLAG_X11_FWD;
1332 if (options.forward_agent)
1333 flags |= SSHMUX_FLAG_AGENT_FWD;
1337 /* Send our command to server */
1338 buffer_put_int(&m, mux_command);
1339 buffer_put_int(&m, flags);
1340 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1341 fatal("%s: msg_send", __func__);
1344 /* Get authorisation status and PID of controlee */
1345 if (ssh_msg_recv(sock, &m) == -1)
1346 fatal("%s: msg_recv", __func__);
1347 if (buffer_get_char(&m) != SSHMUX_VER)
1348 fatal("%s: wrong version", __func__);
1349 if (buffer_get_int(&m) != 1)
1350 fatal("Connection to master denied");
1351 control_server_pid = buffer_get_int(&m);
1355 switch (mux_command) {
1356 case SSHMUX_COMMAND_ALIVE_CHECK:
1357 fprintf(stderr, "Master running (pid=%d)\r\n",
1358 control_server_pid);
1360 case SSHMUX_COMMAND_TERMINATE:
1361 fprintf(stderr, "Exit request sent.\r\n");
1363 case SSHMUX_COMMAND_OPEN:
1364 /* continue below */
1367 fatal("silly mux_command %d", mux_command);
1370 /* SSHMUX_COMMAND_OPEN */
1371 buffer_put_cstring(&m, term ? term : "");
1372 buffer_append(&command, "\0", 1);
1373 buffer_put_cstring(&m, buffer_ptr(&command));
1375 if (options.num_send_env == 0 || environ == NULL) {
1376 buffer_put_int(&m, 0);
1378 /* Pass environment */
1380 for (i = 0; environ[i] != NULL; i++)
1381 if (env_permitted(environ[i]))
1382 num_env++; /* Count */
1384 buffer_put_int(&m, num_env);
1386 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1387 if (env_permitted(environ[i])) {
1389 buffer_put_cstring(&m, environ[i]);
1393 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1394 fatal("%s: msg_send", __func__);
1396 mm_send_fd(sock, STDIN_FILENO);
1397 mm_send_fd(sock, STDOUT_FILENO);
1398 mm_send_fd(sock, STDERR_FILENO);
1400 /* Wait for reply, so master has a chance to gather ttymodes */
1402 if (ssh_msg_recv(sock, &m) == -1)
1403 fatal("%s: msg_recv", __func__);
1404 if (buffer_get_char(&m) != SSHMUX_VER)
1405 fatal("%s: wrong version", __func__);
1408 signal(SIGHUP, control_client_sighandler);
1409 signal(SIGINT, control_client_sighandler);
1410 signal(SIGTERM, control_client_sighandler);
1411 signal(SIGWINCH, control_client_sigrelay);
1416 /* Stick around until the controlee closes the client_fd */
1418 for (;!control_client_terminate;) {
1419 r = read(sock, &exitval, sizeof(exitval));
1421 debug2("Received EOF from master");
1425 debug2("Received exit status from master %d", exitval);
1426 if (r == -1 && errno != EINTR)
1427 fatal("%s: read %s", __func__, strerror(errno));
1430 if (control_client_terminate)
1431 debug2("Exiting on signal %d", control_client_terminate);
1437 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1438 fprintf(stderr, "Connection to master closed.\r\n");