1 /* $OpenBSD: ssh.c,v 1.273 2006/03/25 13:17:02 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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>
59 #include <openssl/evp.h>
60 #include <openssl/err.h>
75 #include "pathnames.h"
77 #include "clientloop.h"
80 #include "sshconnect.h"
87 #include "monitor_fdpass.h"
94 extern char *__progname;
96 /* Flag indicating whether debug mode is on. This can be set on the command line. */
99 /* Flag indicating whether a tty should be allocated */
102 int force_tty_flag = 0;
104 /* don't exec a shell */
105 int no_shell_flag = 0;
108 * Flag indicating that nothing should be read from stdin. This can be set
109 * on the command line.
111 int stdin_null_flag = 0;
114 * Flag indicating that ssh should fork after authentication. This is useful
115 * so that the passphrase can be entered manually, and then ssh goes to the
118 int fork_after_authentication_flag = 0;
121 * General data structure for command line options and options configurable
122 * in configuration files. See readconf.h.
126 /* optional user configfile */
130 * Name of the host we are connecting to. This is the name given on the
131 * command line, or the HostName specified for the user-supplied name in a
132 * configuration file.
136 /* socket address the host resolves to */
137 struct sockaddr_storage hostaddr;
139 /* Private host keys. */
140 Sensitive sensitive_data;
142 /* Original real UID. */
143 uid_t original_real_uid;
144 uid_t original_effective_uid;
146 /* command to be executed */
149 /* Should we execute a command or invoke a subsystem? */
150 int subsystem_flag = 0;
152 /* # of replies received for global requests */
153 static int client_global_request_id = 0;
155 /* pid of proxycommand child process */
156 pid_t proxy_command_pid = 0;
158 /* fd to control socket */
161 /* Multiplexing control command */
162 static u_int mux_command = 0;
164 /* Only used in control client mode */
165 volatile sig_atomic_t control_client_terminate = 0;
166 u_int control_server_pid = 0;
168 /* Prints a help message to the user. This function never returns. */
174 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
175 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
176 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
177 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
178 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
179 " [-w tunnel:tunnel] [user@]hostname [command]\n"
184 static int ssh_session(void);
185 static int ssh_session2(void);
186 static void load_public_identity_files(void);
187 static void control_client(const char *path);
190 * Main program for the ssh client.
193 main(int ac, char **av)
195 int i, opt, exit_status;
196 char *p, *cp, *line, buf[256];
200 extern int optind, optreset;
205 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
208 __progname = ssh_get_progname(av[0]);
212 * Save the original real uid. It will be needed later (uid-swapping
213 * may clobber the real uid).
215 original_real_uid = getuid();
216 original_effective_uid = geteuid();
219 * Use uid-swapping to give up root privileges for the duration of
220 * option processing. We will re-instantiate the rights when we are
221 * ready to create the privileged port, and will permanently drop
222 * them when the port has been created (actually, when the connection
223 * has been made, as we may need to create the port several times).
227 #ifdef HAVE_SETRLIMIT
228 /* If we are installed setuid root be careful to not drop core. */
229 if (original_real_uid != original_effective_uid) {
231 rlim.rlim_cur = rlim.rlim_max = 0;
232 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
233 fatal("setrlimit failed: %.100s", strerror(errno));
237 pw = getpwuid(original_real_uid);
239 logit("You don't exist, go away!");
242 /* Take a copy of the returned structure. */
246 * Set our umask to something reasonable, as some files are created
247 * with the default umask. This will make them world-readable but
248 * writable only by the owner, which is ok for all files for which we
249 * don't set the modes explicitly.
253 /* Initialize option structure to indicate that no values have been set. */
254 initialize_options(&options);
256 /* Parse command-line arguments. */
260 while ((opt = getopt(ac, av,
261 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
264 options.protocol = SSH_PROTO_1;
267 options.protocol = SSH_PROTO_2;
270 options.address_family = AF_INET;
273 options.address_family = AF_INET6;
279 fork_after_authentication_flag = 1;
283 options.forward_x11 = 0;
286 options.forward_x11 = 1;
289 options.forward_x11 = 1;
290 options.forward_x11_trusted = 1;
293 options.gateway_ports = 1;
296 if (strcmp(optarg, "check") == 0)
297 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
298 else if (strcmp(optarg, "exit") == 0)
299 mux_command = SSHMUX_COMMAND_TERMINATE;
301 fatal("Invalid multiplex command.");
303 case 'P': /* deprecated */
304 options.use_privileged_port = 0;
307 options.forward_agent = 0;
310 options.forward_agent = 1;
313 options.gss_deleg_creds = 0;
316 if (stat(optarg, &st) < 0) {
317 fprintf(stderr, "Warning: Identity file %s "
318 "not accessible: %s.\n", optarg,
322 if (options.num_identity_files >=
323 SSH_MAX_IDENTITY_FILES)
324 fatal("Too many identity files specified "
325 "(max %d)", SSH_MAX_IDENTITY_FILES);
326 options.identity_files[options.num_identity_files++] =
331 options.smartcard_device = xstrdup(optarg);
333 fprintf(stderr, "no support for smartcards.\n");
342 if (debug_flag == 0) {
344 options.log_level = SYSLOG_LEVEL_DEBUG1;
346 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
352 fprintf(stderr, "%s, %s\n",
353 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
358 if (options.tun_open == -1)
359 options.tun_open = SSH_TUNMODE_DEFAULT;
360 options.tun_local = a2tun(optarg, &options.tun_remote);
361 if (options.tun_local == SSH_TUNID_ERR) {
362 fprintf(stderr, "Bad tun device '%s'\n", optarg);
367 options.log_level = SYSLOG_LEVEL_QUIET;
370 if (optarg[0] == '^' && optarg[2] == 0 &&
371 (u_char) optarg[1] >= 64 &&
372 (u_char) optarg[1] < 128)
373 options.escape_char = (u_char) optarg[1] & 31;
374 else if (strlen(optarg) == 1)
375 options.escape_char = (u_char) optarg[0];
376 else if (strcmp(optarg, "none") == 0)
377 options.escape_char = SSH_ESCAPECHAR_NONE;
379 fprintf(stderr, "Bad escape character '%s'.\n",
385 if (ciphers_valid(optarg)) {
387 options.ciphers = xstrdup(optarg);
388 options.cipher = SSH_CIPHER_INVALID;
391 options.cipher = cipher_number(optarg);
392 if (options.cipher == -1) {
394 "Unknown cipher type '%s'\n",
398 if (options.cipher == SSH_CIPHER_3DES)
399 options.ciphers = "3des-cbc";
400 else if (options.cipher == SSH_CIPHER_BLOWFISH)
401 options.ciphers = "blowfish-cbc";
403 options.ciphers = (char *)-1;
407 if (mac_valid(optarg))
408 options.macs = xstrdup(optarg);
410 fprintf(stderr, "Unknown mac type '%s'\n",
416 if (options.control_master == SSHCTL_MASTER_YES)
417 options.control_master = SSHCTL_MASTER_ASK;
419 options.control_master = SSHCTL_MASTER_YES;
422 options.port = a2port(optarg);
423 if (options.port == 0) {
424 fprintf(stderr, "Bad port '%s'\n", optarg);
429 options.user = optarg;
433 if (parse_forward(&fwd, optarg))
434 add_local_forward(&options, &fwd);
437 "Bad local forwarding specification '%s'\n",
444 if (parse_forward(&fwd, optarg)) {
445 add_remote_forward(&options, &fwd);
448 "Bad remote forwarding specification "
455 cp = p = xstrdup(optarg);
456 memset(&fwd, '\0', sizeof(fwd));
457 fwd.connect_host = "socks";
458 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
459 fprintf(stderr, "Bad dynamic forwarding "
460 "specification '%.100s'\n", optarg);
464 fwd.listen_port = a2port(cp);
465 fwd.listen_host = cleanhostname(fwd.listen_host);
467 fwd.listen_port = a2port(fwd.listen_host);
468 fwd.listen_host = NULL;
471 if (fwd.listen_port == 0) {
472 fprintf(stderr, "Bad dynamic port '%s'\n",
476 add_local_forward(&options, &fwd);
481 options.compression = 1;
492 line = xstrdup(optarg);
493 if (process_config_line(&options, host ? host : "",
494 line, "command-line", 0, &dummy) != 0)
502 if (options.control_path != NULL)
503 free(options.control_path);
504 options.control_path = xstrdup(optarg);
507 options.bind_address = optarg;
520 if (ac > 0 && !host && **av != '-') {
521 if (strrchr(*av, '@')) {
523 cp = strrchr(p, '@');
524 if (cp == NULL || cp == p)
532 optind = optreset = 1;
538 /* Check that we got a host name. */
542 SSLeay_add_all_algorithms();
543 ERR_load_crypto_strings();
545 /* Initialize the command to execute on remote host. */
546 buffer_init(&command);
549 * Save the command to execute on the remote host in a buffer. There
550 * is no limit on the length of the command, except by the maximum
551 * packet size. Also sets the tty flag if there is no command.
554 /* No command specified - execute shell on a tty. */
556 if (subsystem_flag) {
558 "You must specify a subsystem to invoke.\n");
562 /* A command has been specified. Store it into the buffer. */
563 for (i = 0; i < ac; i++) {
565 buffer_append(&command, " ", 1);
566 buffer_append(&command, av[i], strlen(av[i]));
570 /* Cannot fork to background if no command. */
571 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
572 fatal("Cannot fork into background without a command to execute.");
574 /* Allocate a tty by default if no command specified. */
575 if (buffer_len(&command) == 0)
581 /* Do not allocate a tty if stdin is not a tty. */
582 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
584 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
589 * Initialize "log" output. Since we are the client all output
590 * actually goes to stderr.
592 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
593 SYSLOG_FACILITY_USER, 1);
596 * Read per-user configuration file. Ignore the system wide config
597 * file if the user specifies a config file on the command line.
599 if (config != NULL) {
600 if (!read_config_file(config, host, &options, 0))
601 fatal("Can't open user config file %.100s: "
602 "%.100s", config, strerror(errno));
604 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
605 _PATH_SSH_USER_CONFFILE);
606 (void)read_config_file(buf, host, &options, 1);
608 /* Read systemwide configuration file after use config. */
609 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
613 /* Fill configuration defaults. */
614 fill_default_options(&options);
616 channel_set_af(options.address_family);
619 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
623 if (options.user == NULL)
624 options.user = xstrdup(pw->pw_name);
626 if (options.hostname != NULL)
627 host = options.hostname;
629 /* force lowercase for hostkey matching */
630 if (options.host_key_alias != NULL) {
631 for (p = options.host_key_alias; *p; p++)
633 *p = (char)tolower(*p);
636 /* Get default port if port has not been set. */
637 if (options.port == 0) {
638 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
639 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
642 if (options.proxy_command != NULL &&
643 strcmp(options.proxy_command, "none") == 0)
644 options.proxy_command = NULL;
645 if (options.control_path != NULL &&
646 strcmp(options.control_path, "none") == 0)
647 options.control_path = NULL;
649 if (options.control_path != NULL) {
652 if (gethostname(me, sizeof(me)) == -1)
653 fatal("gethostname: %s", strerror(errno));
654 snprintf(buf, sizeof(buf), "%d", options.port);
655 cp = tilde_expand_filename(options.control_path,
657 options.control_path = percent_expand(cp, "p", buf, "h", host,
658 "r", options.user, "l", me, (char *)NULL);
661 if (mux_command != 0 && options.control_path == NULL)
662 fatal("No ControlPath specified for \"-O\" command");
663 if (options.control_path != NULL)
664 control_client(options.control_path);
666 /* Open a connection to the remote host. */
667 if (ssh_connect(host, &hostaddr, options.port,
668 options.address_family, options.connection_attempts,
670 options.use_privileged_port,
672 original_effective_uid == 0 && options.use_privileged_port,
674 options.proxy_command) != 0)
678 * If we successfully made the connection, load the host private key
679 * in case we will need it later for combined rsa-rhosts
680 * authentication. This must be done before releasing extra
681 * privileges, because the file is only readable by root.
682 * If we cannot access the private keys, load the public keys
683 * instead and try to execute the ssh-keysign helper instead.
685 sensitive_data.nkeys = 0;
686 sensitive_data.keys = NULL;
687 sensitive_data.external_keysign = 0;
688 if (options.rhosts_rsa_authentication ||
689 options.hostbased_authentication) {
690 sensitive_data.nkeys = 3;
691 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
695 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
696 _PATH_HOST_KEY_FILE, "", NULL);
697 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
698 _PATH_HOST_DSA_KEY_FILE, "", NULL);
699 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
700 _PATH_HOST_RSA_KEY_FILE, "", NULL);
703 if (options.hostbased_authentication == 1 &&
704 sensitive_data.keys[0] == NULL &&
705 sensitive_data.keys[1] == NULL &&
706 sensitive_data.keys[2] == NULL) {
707 sensitive_data.keys[1] = key_load_public(
708 _PATH_HOST_DSA_KEY_FILE, NULL);
709 sensitive_data.keys[2] = key_load_public(
710 _PATH_HOST_RSA_KEY_FILE, NULL);
711 sensitive_data.external_keysign = 1;
715 * Get rid of any extra privileges that we may have. We will no
716 * longer need them. Also, extra privileges could make it very hard
717 * to read identity files and other non-world-readable files from the
718 * user's home directory if it happens to be on a NFS volume where
719 * root is mapped to nobody.
721 if (original_effective_uid == 0) {
723 permanently_set_uid(pw);
727 * Now that we are back to our own permissions, create ~/.ssh
728 * directory if it doesn't already exist.
730 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
731 if (stat(buf, &st) < 0)
732 if (mkdir(buf, 0700) < 0)
733 error("Could not create directory '%.200s'.", buf);
735 /* load options.identity_files */
736 load_public_identity_files();
738 /* Expand ~ in known host file names. */
740 options.system_hostfile =
741 tilde_expand_filename(options.system_hostfile, original_real_uid);
742 options.user_hostfile =
743 tilde_expand_filename(options.user_hostfile, original_real_uid);
744 options.system_hostfile2 =
745 tilde_expand_filename(options.system_hostfile2, original_real_uid);
746 options.user_hostfile2 =
747 tilde_expand_filename(options.user_hostfile2, original_real_uid);
749 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
751 /* Log into the remote system. This never returns if the login fails. */
752 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
754 /* We no longer need the private host keys. Clear them now. */
755 if (sensitive_data.nkeys != 0) {
756 for (i = 0; i < sensitive_data.nkeys; i++) {
757 if (sensitive_data.keys[i] != NULL) {
758 /* Destroys contents safely */
759 debug3("clear hostkey %d", i);
760 key_free(sensitive_data.keys[i]);
761 sensitive_data.keys[i] = NULL;
764 xfree(sensitive_data.keys);
766 for (i = 0; i < options.num_identity_files; i++) {
767 if (options.identity_files[i]) {
768 xfree(options.identity_files[i]);
769 options.identity_files[i] = NULL;
771 if (options.identity_keys[i]) {
772 key_free(options.identity_keys[i]);
773 options.identity_keys[i] = NULL;
777 exit_status = compat20 ? ssh_session2() : ssh_session();
780 if (options.control_path != NULL && control_fd != -1)
781 unlink(options.control_path);
784 * Send SIGHUP to proxy command if used. We don't wait() in
785 * case it hangs and instead rely on init to reap the child
787 if (proxy_command_pid > 1)
788 kill(proxy_command_pid, SIGHUP);
794 ssh_init_forwarding(void)
799 /* Initiate local TCP/IP port forwardings. */
800 for (i = 0; i < options.num_local_forwards; i++) {
801 debug("Local connections to %.200s:%d forwarded to remote "
803 (options.local_forwards[i].listen_host == NULL) ?
804 (options.gateway_ports ? "*" : "LOCALHOST") :
805 options.local_forwards[i].listen_host,
806 options.local_forwards[i].listen_port,
807 options.local_forwards[i].connect_host,
808 options.local_forwards[i].connect_port);
809 success += channel_setup_local_fwd_listener(
810 options.local_forwards[i].listen_host,
811 options.local_forwards[i].listen_port,
812 options.local_forwards[i].connect_host,
813 options.local_forwards[i].connect_port,
814 options.gateway_ports);
816 if (i > 0 && success == 0)
817 error("Could not request local forwarding.");
819 /* Initiate remote TCP/IP port forwardings. */
820 for (i = 0; i < options.num_remote_forwards; i++) {
821 debug("Remote connections from %.200s:%d forwarded to "
822 "local address %.200s:%d",
823 (options.remote_forwards[i].listen_host == NULL) ?
824 "LOCALHOST" : options.remote_forwards[i].listen_host,
825 options.remote_forwards[i].listen_port,
826 options.remote_forwards[i].connect_host,
827 options.remote_forwards[i].connect_port);
828 channel_request_remote_forwarding(
829 options.remote_forwards[i].listen_host,
830 options.remote_forwards[i].listen_port,
831 options.remote_forwards[i].connect_host,
832 options.remote_forwards[i].connect_port);
837 check_agent_present(void)
839 if (options.forward_agent) {
840 /* Clear agent forwarding if we don't have an agent. */
841 if (!ssh_agent_present())
842 options.forward_agent = 0;
856 /* Enable compression if requested. */
857 if (options.compression) {
858 debug("Requesting compression at level %d.", options.compression_level);
860 if (options.compression_level < 1 || options.compression_level > 9)
861 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
863 /* Send the request. */
864 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
865 packet_put_int(options.compression_level);
868 type = packet_read();
869 if (type == SSH_SMSG_SUCCESS)
870 packet_start_compression(options.compression_level);
871 else if (type == SSH_SMSG_FAILURE)
872 logit("Warning: Remote host refused compression.");
874 packet_disconnect("Protocol error waiting for compression response.");
876 /* Allocate a pseudo tty if appropriate. */
878 debug("Requesting pty.");
880 /* Start the packet. */
881 packet_start(SSH_CMSG_REQUEST_PTY);
883 /* Store TERM in the packet. There is no limit on the
884 length of the string. */
888 packet_put_cstring(cp);
890 /* Store window size in the packet. */
891 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
892 memset(&ws, 0, sizeof(ws));
893 packet_put_int((u_int)ws.ws_row);
894 packet_put_int((u_int)ws.ws_col);
895 packet_put_int((u_int)ws.ws_xpixel);
896 packet_put_int((u_int)ws.ws_ypixel);
898 /* Store tty modes in the packet. */
899 tty_make_modes(fileno(stdin), NULL);
901 /* Send the packet, and wait for it to leave. */
905 /* Read response from the server. */
906 type = packet_read();
907 if (type == SSH_SMSG_SUCCESS) {
910 } else if (type == SSH_SMSG_FAILURE)
911 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
913 packet_disconnect("Protocol error waiting for pty request response.");
915 /* Request X11 forwarding if enabled and DISPLAY is set. */
916 display = getenv("DISPLAY");
917 if (options.forward_x11 && display != NULL) {
919 /* Get reasonable local authentication information. */
920 client_x11_get_proto(display, options.xauth_location,
921 options.forward_x11_trusted, &proto, &data);
922 /* Request forwarding with authentication spoofing. */
923 debug("Requesting X11 forwarding with authentication spoofing.");
924 x11_request_forwarding_with_spoofing(0, display, proto, data);
926 /* Read response from the server. */
927 type = packet_read();
928 if (type == SSH_SMSG_SUCCESS) {
930 } else if (type == SSH_SMSG_FAILURE) {
931 logit("Warning: Remote host denied X11 forwarding.");
933 packet_disconnect("Protocol error waiting for X11 forwarding");
936 /* Tell the packet module whether this is an interactive session. */
937 packet_set_interactive(interactive);
939 /* Request authentication agent forwarding if appropriate. */
940 check_agent_present();
942 if (options.forward_agent) {
943 debug("Requesting authentication agent forwarding.");
944 auth_request_forwarding();
946 /* Read response from the server. */
947 type = packet_read();
949 if (type != SSH_SMSG_SUCCESS)
950 logit("Warning: Remote host denied authentication agent forwarding.");
953 /* Initiate port forwardings. */
954 ssh_init_forwarding();
956 /* If requested, let ssh continue in the background. */
957 if (fork_after_authentication_flag)
958 if (daemon(1, 1) < 0)
959 fatal("daemon() failed: %.200s", strerror(errno));
962 * If a command was specified on the command line, execute the
963 * command now. Otherwise request the server to start a shell.
965 if (buffer_len(&command) > 0) {
966 int len = buffer_len(&command);
969 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
970 packet_start(SSH_CMSG_EXEC_CMD);
971 packet_put_string(buffer_ptr(&command), buffer_len(&command));
975 debug("Requesting shell.");
976 packet_start(SSH_CMSG_EXEC_SHELL);
981 /* Enter the interactive session. */
982 return client_loop(have_tty, tty_flag ?
983 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
987 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
991 id = packet_get_int();
992 len = buffer_len(&command);
996 if (type == SSH2_MSG_CHANNEL_FAILURE)
997 fatal("Request for subsystem '%.*s' failed on channel %d",
998 len, (u_char *)buffer_ptr(&command), id);
1002 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1006 i = client_global_request_id++;
1007 if (i >= options.num_remote_forwards)
1009 debug("remote forward %s for: listen %d, connect %s:%d",
1010 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1011 options.remote_forwards[i].listen_port,
1012 options.remote_forwards[i].connect_host,
1013 options.remote_forwards[i].connect_port);
1014 if (type == SSH2_MSG_REQUEST_FAILURE)
1015 logit("Warning: remote port forwarding failed for listen "
1016 "port %d", options.remote_forwards[i].listen_port);
1020 ssh_control_listener(void)
1022 struct sockaddr_un addr;
1026 if (options.control_path == NULL ||
1027 options.control_master == SSHCTL_MASTER_NO)
1030 debug("setting up multiplex master socket");
1032 memset(&addr, '\0', sizeof(addr));
1033 addr.sun_family = AF_UNIX;
1034 addr_len = offsetof(struct sockaddr_un, sun_path) +
1035 strlen(options.control_path) + 1;
1037 if (strlcpy(addr.sun_path, options.control_path,
1038 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1039 fatal("ControlPath too long");
1041 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1042 fatal("%s socket(): %s", __func__, strerror(errno));
1044 old_umask = umask(0177);
1045 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1047 if (errno == EINVAL || errno == EADDRINUSE)
1048 fatal("ControlSocket %s already exists",
1049 options.control_path);
1051 fatal("%s bind(): %s", __func__, strerror(errno));
1055 if (listen(control_fd, 64) == -1)
1056 fatal("%s listen(): %s", __func__, strerror(errno));
1058 set_nonblock(control_fd);
1061 /* request pty/x11/agent/tcpfwd/shell for channel */
1063 ssh_session2_setup(int id, void *arg)
1065 extern char **environ;
1066 const char *display;
1067 int interactive = tty_flag;
1069 display = getenv("DISPLAY");
1070 if (options.forward_x11 && display != NULL) {
1072 /* Get reasonable local authentication information. */
1073 client_x11_get_proto(display, options.xauth_location,
1074 options.forward_x11_trusted, &proto, &data);
1075 /* Request forwarding with authentication spoofing. */
1076 debug("Requesting X11 forwarding with authentication spoofing.");
1077 x11_request_forwarding_with_spoofing(id, display, proto, data);
1079 /* XXX wait for reply */
1082 check_agent_present();
1083 if (options.forward_agent) {
1084 debug("Requesting authentication agent forwarding.");
1085 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1089 if (options.tun_open != SSH_TUNMODE_NO) {
1093 debug("Requesting tun.");
1094 if ((fd = tun_open(options.tun_local,
1095 options.tun_open)) >= 0) {
1096 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1097 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1100 #if defined(SSH_TUN_FILTER)
1101 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1102 channel_register_filter(c->self, sys_tun_infilter,
1105 packet_start(SSH2_MSG_CHANNEL_OPEN);
1106 packet_put_cstring("tun@openssh.com");
1107 packet_put_int(c->self);
1108 packet_put_int(c->local_window_max);
1109 packet_put_int(c->local_maxpacket);
1110 packet_put_int(options.tun_open);
1111 packet_put_int(options.tun_remote);
1116 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1117 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1119 packet_set_interactive(interactive);
1122 /* open new channel for a session */
1124 ssh_session2_open(void)
1127 int window, packetmax, in, out, err;
1129 if (stdin_null_flag) {
1130 in = open(_PATH_DEVNULL, O_RDONLY);
1132 in = dup(STDIN_FILENO);
1134 out = dup(STDOUT_FILENO);
1135 err = dup(STDERR_FILENO);
1137 if (in < 0 || out < 0 || err < 0)
1138 fatal("dup() in/out/err failed");
1140 /* enable nonblocking unless tty */
1148 window = CHAN_SES_WINDOW_DEFAULT;
1149 packetmax = CHAN_SES_PACKET_DEFAULT;
1155 "session", SSH_CHANNEL_OPENING, in, out, err,
1156 window, packetmax, CHAN_EXTENDED_WRITE,
1157 "client-session", /*nonblock*/0);
1159 debug3("ssh_session2_open: channel_new: %d", c->self);
1161 channel_send_open(c->self);
1163 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1173 /* XXX should be pre-session */
1174 ssh_init_forwarding();
1175 ssh_control_listener();
1177 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1178 id = ssh_session2_open();
1180 /* Execute a local command */
1181 if (options.local_command != NULL &&
1182 options.permit_local_command)
1183 ssh_local_cmd(options.local_command);
1185 /* If requested, let ssh continue in the background. */
1186 if (fork_after_authentication_flag)
1187 if (daemon(1, 1) < 0)
1188 fatal("daemon() failed: %.200s", strerror(errno));
1190 return client_loop(tty_flag, tty_flag ?
1191 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1195 load_public_identity_files(void)
1203 if (options.smartcard_device != NULL &&
1204 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1205 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1207 for (i = 0; keys[i] != NULL; i++) {
1209 memmove(&options.identity_files[1], &options.identity_files[0],
1210 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1211 memmove(&options.identity_keys[1], &options.identity_keys[0],
1212 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1213 options.num_identity_files++;
1214 options.identity_keys[0] = keys[i];
1215 options.identity_files[0] = sc_get_key_label(keys[i]);
1217 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1218 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1222 #endif /* SMARTCARD */
1223 for (; i < options.num_identity_files; i++) {
1224 filename = tilde_expand_filename(options.identity_files[i],
1226 public = key_load_public(filename, NULL);
1227 debug("identity file %s type %d", filename,
1228 public ? public->type : -1);
1229 xfree(options.identity_files[i]);
1230 options.identity_files[i] = filename;
1231 options.identity_keys[i] = public;
1236 control_client_sighandler(int signo)
1238 control_client_terminate = signo;
1242 control_client_sigrelay(int signo)
1244 if (control_server_pid > 1)
1245 kill(control_server_pid, signo);
1249 env_permitted(char *env)
1252 char name[1024], *cp;
1254 if (strlcpy(name, env, sizeof(name)) >= sizeof(name))
1255 fatal("env_permitted: name too long");
1256 if ((cp = strchr(name, '=')) == NULL)
1261 for (i = 0; i < options.num_send_env; i++)
1262 if (match_pattern(name, options.send_env[i]))
1269 control_client(const char *path)
1271 struct sockaddr_un addr;
1272 int i, r, fd, sock, exitval, num_env, addr_len;
1275 extern char **environ;
1278 if (mux_command == 0)
1279 mux_command = SSHMUX_COMMAND_OPEN;
1281 switch (options.control_master) {
1282 case SSHCTL_MASTER_AUTO:
1283 case SSHCTL_MASTER_AUTO_ASK:
1284 debug("auto-mux: Trying existing master");
1286 case SSHCTL_MASTER_NO:
1292 memset(&addr, '\0', sizeof(addr));
1293 addr.sun_family = AF_UNIX;
1294 addr_len = offsetof(struct sockaddr_un, sun_path) +
1297 if (strlcpy(addr.sun_path, path,
1298 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1299 fatal("ControlPath too long");
1301 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1302 fatal("%s socket(): %s", __func__, strerror(errno));
1304 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1305 if (mux_command != SSHMUX_COMMAND_OPEN) {
1306 fatal("Control socket connect(%.100s): %s", path,
1309 if (errno == ENOENT)
1310 debug("Control socket \"%.100s\" does not exist", path);
1312 error("Control socket connect(%.100s): %s", path,
1319 if (stdin_null_flag) {
1320 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1321 fatal("open(/dev/null): %s", strerror(errno));
1322 if (dup2(fd, STDIN_FILENO) == -1)
1323 fatal("dup2: %s", strerror(errno));
1324 if (fd > STDERR_FILENO)
1328 term = getenv("TERM");
1332 flags |= SSHMUX_FLAG_TTY;
1334 flags |= SSHMUX_FLAG_SUBSYS;
1335 if (options.forward_x11)
1336 flags |= SSHMUX_FLAG_X11_FWD;
1337 if (options.forward_agent)
1338 flags |= SSHMUX_FLAG_AGENT_FWD;
1342 /* Send our command to server */
1343 buffer_put_int(&m, mux_command);
1344 buffer_put_int(&m, flags);
1345 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1346 fatal("%s: msg_send", __func__);
1349 /* Get authorisation status and PID of controlee */
1350 if (ssh_msg_recv(sock, &m) == -1)
1351 fatal("%s: msg_recv", __func__);
1352 if (buffer_get_char(&m) != SSHMUX_VER)
1353 fatal("%s: wrong version", __func__);
1354 if (buffer_get_int(&m) != 1)
1355 fatal("Connection to master denied");
1356 control_server_pid = buffer_get_int(&m);
1360 switch (mux_command) {
1361 case SSHMUX_COMMAND_ALIVE_CHECK:
1362 fprintf(stderr, "Master running (pid=%d)\r\n",
1363 control_server_pid);
1365 case SSHMUX_COMMAND_TERMINATE:
1366 fprintf(stderr, "Exit request sent.\r\n");
1368 case SSHMUX_COMMAND_OPEN:
1369 /* continue below */
1372 fatal("silly mux_command %d", mux_command);
1375 /* SSHMUX_COMMAND_OPEN */
1376 buffer_put_cstring(&m, term ? term : "");
1377 buffer_append(&command, "\0", 1);
1378 buffer_put_cstring(&m, buffer_ptr(&command));
1380 if (options.num_send_env == 0 || environ == NULL) {
1381 buffer_put_int(&m, 0);
1383 /* Pass environment */
1385 for (i = 0; environ[i] != NULL; i++)
1386 if (env_permitted(environ[i]))
1387 num_env++; /* Count */
1389 buffer_put_int(&m, num_env);
1391 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1392 if (env_permitted(environ[i])) {
1394 buffer_put_cstring(&m, environ[i]);
1398 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1399 fatal("%s: msg_send", __func__);
1401 mm_send_fd(sock, STDIN_FILENO);
1402 mm_send_fd(sock, STDOUT_FILENO);
1403 mm_send_fd(sock, STDERR_FILENO);
1405 /* Wait for reply, so master has a chance to gather ttymodes */
1407 if (ssh_msg_recv(sock, &m) == -1)
1408 fatal("%s: msg_recv", __func__);
1409 if (buffer_get_char(&m) != SSHMUX_VER)
1410 fatal("%s: wrong version", __func__);
1413 signal(SIGHUP, control_client_sighandler);
1414 signal(SIGINT, control_client_sighandler);
1415 signal(SIGTERM, control_client_sighandler);
1416 signal(SIGWINCH, control_client_sigrelay);
1421 /* Stick around until the controlee closes the client_fd */
1423 for (;!control_client_terminate;) {
1424 r = read(sock, &exitval, sizeof(exitval));
1426 debug2("Received EOF from master");
1430 debug2("Received exit status from master %d", exitval);
1431 if (r == -1 && errno != EINTR)
1432 fatal("%s: read %s", __func__, strerror(errno));
1435 if (control_client_terminate)
1436 debug2("Exiting on signal %d", control_client_terminate);
1442 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1443 fprintf(stderr, "Connection to master closed.\r\n");