1 /* $OpenBSD: ssh.c,v 1.281 2006/07/09 15:15:11 stevesk 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>
51 #include <sys/socket.h>
62 #include <openssl/evp.h>
63 #include <openssl/err.h>
78 #include "pathnames.h"
80 #include "clientloop.h"
83 #include "sshconnect.h"
90 #include "monitor_fdpass.h"
98 extern char *__progname;
100 /* Flag indicating whether debug mode is on. This can be set on the command line. */
103 /* Flag indicating whether a tty should be allocated */
106 int force_tty_flag = 0;
108 /* don't exec a shell */
109 int no_shell_flag = 0;
112 * Flag indicating that nothing should be read from stdin. This can be set
113 * on the command line.
115 int stdin_null_flag = 0;
118 * Flag indicating that ssh should fork after authentication. This is useful
119 * so that the passphrase can be entered manually, and then ssh goes to the
122 int fork_after_authentication_flag = 0;
125 * General data structure for command line options and options configurable
126 * in configuration files. See readconf.h.
130 /* optional user configfile */
134 * Name of the host we are connecting to. This is the name given on the
135 * command line, or the HostName specified for the user-supplied name in a
136 * configuration file.
140 /* socket address the host resolves to */
141 struct sockaddr_storage hostaddr;
143 /* Private host keys. */
144 Sensitive sensitive_data;
146 /* Original real UID. */
147 uid_t original_real_uid;
148 uid_t original_effective_uid;
150 /* command to be executed */
153 /* Should we execute a command or invoke a subsystem? */
154 int subsystem_flag = 0;
156 /* # of replies received for global requests */
157 static int client_global_request_id = 0;
159 /* pid of proxycommand child process */
160 pid_t proxy_command_pid = 0;
162 /* fd to control socket */
165 /* Multiplexing control command */
166 static u_int mux_command = 0;
168 /* Only used in control client mode */
169 volatile sig_atomic_t control_client_terminate = 0;
170 u_int control_server_pid = 0;
172 /* Prints a help message to the user. This function never returns. */
178 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
179 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
180 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
181 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
182 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
183 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
188 static int ssh_session(void);
189 static int ssh_session2(void);
190 static void load_public_identity_files(void);
191 static void control_client(const char *path);
194 * Main program for the ssh client.
197 main(int ac, char **av)
199 int i, opt, exit_status;
200 char *p, *cp, *line, buf[256];
204 extern int optind, optreset;
209 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
212 __progname = ssh_get_progname(av[0]);
216 * Save the original real uid. It will be needed later (uid-swapping
217 * may clobber the real uid).
219 original_real_uid = getuid();
220 original_effective_uid = geteuid();
223 * Use uid-swapping to give up root privileges for the duration of
224 * option processing. We will re-instantiate the rights when we are
225 * ready to create the privileged port, and will permanently drop
226 * them when the port has been created (actually, when the connection
227 * has been made, as we may need to create the port several times).
231 #ifdef HAVE_SETRLIMIT
232 /* If we are installed setuid root be careful to not drop core. */
233 if (original_real_uid != original_effective_uid) {
235 rlim.rlim_cur = rlim.rlim_max = 0;
236 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
237 fatal("setrlimit failed: %.100s", strerror(errno));
241 pw = getpwuid(original_real_uid);
243 logit("You don't exist, go away!");
246 /* Take a copy of the returned structure. */
250 * Set our umask to something reasonable, as some files are created
251 * with the default umask. This will make them world-readable but
252 * writable only by the owner, which is ok for all files for which we
253 * don't set the modes explicitly.
257 /* Initialize option structure to indicate that no values have been set. */
258 initialize_options(&options);
260 /* Parse command-line arguments. */
264 while ((opt = getopt(ac, av,
265 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
268 options.protocol = SSH_PROTO_1;
271 options.protocol = SSH_PROTO_2;
274 options.address_family = AF_INET;
277 options.address_family = AF_INET6;
283 fork_after_authentication_flag = 1;
287 options.forward_x11 = 0;
290 options.forward_x11 = 1;
293 options.forward_x11 = 1;
294 options.forward_x11_trusted = 1;
297 options.gateway_ports = 1;
300 if (strcmp(optarg, "check") == 0)
301 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
302 else if (strcmp(optarg, "exit") == 0)
303 mux_command = SSHMUX_COMMAND_TERMINATE;
305 fatal("Invalid multiplex command.");
307 case 'P': /* deprecated */
308 options.use_privileged_port = 0;
311 options.forward_agent = 0;
314 options.forward_agent = 1;
317 options.gss_deleg_creds = 0;
320 if (stat(optarg, &st) < 0) {
321 fprintf(stderr, "Warning: Identity file %s "
322 "not accessible: %s.\n", optarg,
326 if (options.num_identity_files >=
327 SSH_MAX_IDENTITY_FILES)
328 fatal("Too many identity files specified "
329 "(max %d)", SSH_MAX_IDENTITY_FILES);
330 options.identity_files[options.num_identity_files++] =
335 options.smartcard_device = xstrdup(optarg);
337 fprintf(stderr, "no support for smartcards.\n");
346 if (debug_flag == 0) {
348 options.log_level = SYSLOG_LEVEL_DEBUG1;
350 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
356 fprintf(stderr, "%s, %s\n",
357 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
362 if (options.tun_open == -1)
363 options.tun_open = SSH_TUNMODE_DEFAULT;
364 options.tun_local = a2tun(optarg, &options.tun_remote);
365 if (options.tun_local == SSH_TUNID_ERR) {
366 fprintf(stderr, "Bad tun device '%s'\n", optarg);
371 options.log_level = SYSLOG_LEVEL_QUIET;
374 if (optarg[0] == '^' && optarg[2] == 0 &&
375 (u_char) optarg[1] >= 64 &&
376 (u_char) optarg[1] < 128)
377 options.escape_char = (u_char) optarg[1] & 31;
378 else if (strlen(optarg) == 1)
379 options.escape_char = (u_char) optarg[0];
380 else if (strcmp(optarg, "none") == 0)
381 options.escape_char = SSH_ESCAPECHAR_NONE;
383 fprintf(stderr, "Bad escape character '%s'.\n",
389 if (ciphers_valid(optarg)) {
391 options.ciphers = xstrdup(optarg);
392 options.cipher = SSH_CIPHER_INVALID;
395 options.cipher = cipher_number(optarg);
396 if (options.cipher == -1) {
398 "Unknown cipher type '%s'\n",
402 if (options.cipher == SSH_CIPHER_3DES)
403 options.ciphers = "3des-cbc";
404 else if (options.cipher == SSH_CIPHER_BLOWFISH)
405 options.ciphers = "blowfish-cbc";
407 options.ciphers = (char *)-1;
411 if (mac_valid(optarg))
412 options.macs = xstrdup(optarg);
414 fprintf(stderr, "Unknown mac type '%s'\n",
420 if (options.control_master == SSHCTL_MASTER_YES)
421 options.control_master = SSHCTL_MASTER_ASK;
423 options.control_master = SSHCTL_MASTER_YES;
426 options.port = a2port(optarg);
427 if (options.port == 0) {
428 fprintf(stderr, "Bad port '%s'\n", optarg);
433 options.user = optarg;
437 if (parse_forward(&fwd, optarg))
438 add_local_forward(&options, &fwd);
441 "Bad local forwarding specification '%s'\n",
448 if (parse_forward(&fwd, optarg)) {
449 add_remote_forward(&options, &fwd);
452 "Bad remote forwarding specification "
459 cp = p = xstrdup(optarg);
460 memset(&fwd, '\0', sizeof(fwd));
461 fwd.connect_host = "socks";
462 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
463 fprintf(stderr, "Bad dynamic forwarding "
464 "specification '%.100s'\n", optarg);
468 fwd.listen_port = a2port(cp);
469 fwd.listen_host = cleanhostname(fwd.listen_host);
471 fwd.listen_port = a2port(fwd.listen_host);
472 fwd.listen_host = NULL;
475 if (fwd.listen_port == 0) {
476 fprintf(stderr, "Bad dynamic port '%s'\n",
480 add_local_forward(&options, &fwd);
485 options.compression = 1;
496 line = xstrdup(optarg);
497 if (process_config_line(&options, host ? host : "",
498 line, "command-line", 0, &dummy) != 0)
506 if (options.control_path != NULL)
507 free(options.control_path);
508 options.control_path = xstrdup(optarg);
511 options.bind_address = optarg;
524 if (ac > 0 && !host && **av != '-') {
525 if (strrchr(*av, '@')) {
527 cp = strrchr(p, '@');
528 if (cp == NULL || cp == p)
536 optind = optreset = 1;
542 /* Check that we got a host name. */
546 SSLeay_add_all_algorithms();
547 ERR_load_crypto_strings();
549 /* Initialize the command to execute on remote host. */
550 buffer_init(&command);
553 * Save the command to execute on the remote host in a buffer. There
554 * is no limit on the length of the command, except by the maximum
555 * packet size. Also sets the tty flag if there is no command.
558 /* No command specified - execute shell on a tty. */
560 if (subsystem_flag) {
562 "You must specify a subsystem to invoke.\n");
566 /* A command has been specified. Store it into the buffer. */
567 for (i = 0; i < ac; i++) {
569 buffer_append(&command, " ", 1);
570 buffer_append(&command, av[i], strlen(av[i]));
574 /* Cannot fork to background if no command. */
575 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
576 fatal("Cannot fork into background without a command to execute.");
578 /* Allocate a tty by default if no command specified. */
579 if (buffer_len(&command) == 0)
585 /* Do not allocate a tty if stdin is not a tty. */
586 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
588 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
593 * Initialize "log" output. Since we are the client all output
594 * actually goes to stderr.
596 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
597 SYSLOG_FACILITY_USER, 1);
600 * Read per-user configuration file. Ignore the system wide config
601 * file if the user specifies a config file on the command line.
603 if (config != NULL) {
604 if (!read_config_file(config, host, &options, 0))
605 fatal("Can't open user config file %.100s: "
606 "%.100s", config, strerror(errno));
608 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
609 _PATH_SSH_USER_CONFFILE);
610 (void)read_config_file(buf, host, &options, 1);
612 /* Read systemwide configuration file after use config. */
613 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
617 /* Fill configuration defaults. */
618 fill_default_options(&options);
620 channel_set_af(options.address_family);
623 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
627 if (options.user == NULL)
628 options.user = xstrdup(pw->pw_name);
630 if (options.hostname != NULL)
631 host = options.hostname;
633 /* force lowercase for hostkey matching */
634 if (options.host_key_alias != NULL) {
635 for (p = options.host_key_alias; *p; p++)
637 *p = (char)tolower(*p);
640 /* Get default port if port has not been set. */
641 if (options.port == 0) {
642 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
643 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
646 if (options.proxy_command != NULL &&
647 strcmp(options.proxy_command, "none") == 0)
648 options.proxy_command = NULL;
649 if (options.control_path != NULL &&
650 strcmp(options.control_path, "none") == 0)
651 options.control_path = NULL;
653 if (options.control_path != NULL) {
654 char thishost[NI_MAXHOST];
656 if (gethostname(thishost, sizeof(thishost)) == -1)
657 fatal("gethostname: %s", strerror(errno));
658 snprintf(buf, sizeof(buf), "%d", options.port);
659 cp = tilde_expand_filename(options.control_path,
661 options.control_path = percent_expand(cp, "p", buf, "h", host,
662 "r", options.user, "l", thishost, (char *)NULL);
665 if (mux_command != 0 && options.control_path == NULL)
666 fatal("No ControlPath specified for \"-O\" command");
667 if (options.control_path != NULL)
668 control_client(options.control_path);
670 /* Open a connection to the remote host. */
671 if (ssh_connect(host, &hostaddr, options.port,
672 options.address_family, options.connection_attempts,
674 options.use_privileged_port,
676 original_effective_uid == 0 && options.use_privileged_port,
678 options.proxy_command) != 0)
682 * If we successfully made the connection, load the host private key
683 * in case we will need it later for combined rsa-rhosts
684 * authentication. This must be done before releasing extra
685 * privileges, because the file is only readable by root.
686 * If we cannot access the private keys, load the public keys
687 * instead and try to execute the ssh-keysign helper instead.
689 sensitive_data.nkeys = 0;
690 sensitive_data.keys = NULL;
691 sensitive_data.external_keysign = 0;
692 if (options.rhosts_rsa_authentication ||
693 options.hostbased_authentication) {
694 sensitive_data.nkeys = 3;
695 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
699 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
700 _PATH_HOST_KEY_FILE, "", NULL, NULL);
701 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
702 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
703 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
704 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
707 if (options.hostbased_authentication == 1 &&
708 sensitive_data.keys[0] == NULL &&
709 sensitive_data.keys[1] == NULL &&
710 sensitive_data.keys[2] == NULL) {
711 sensitive_data.keys[1] = key_load_public(
712 _PATH_HOST_DSA_KEY_FILE, NULL);
713 sensitive_data.keys[2] = key_load_public(
714 _PATH_HOST_RSA_KEY_FILE, NULL);
715 sensitive_data.external_keysign = 1;
719 * Get rid of any extra privileges that we may have. We will no
720 * longer need them. Also, extra privileges could make it very hard
721 * to read identity files and other non-world-readable files from the
722 * user's home directory if it happens to be on a NFS volume where
723 * root is mapped to nobody.
725 if (original_effective_uid == 0) {
727 permanently_set_uid(pw);
731 * Now that we are back to our own permissions, create ~/.ssh
732 * directory if it doesn't already exist.
734 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
735 if (stat(buf, &st) < 0)
736 if (mkdir(buf, 0700) < 0)
737 error("Could not create directory '%.200s'.", buf);
739 /* load options.identity_files */
740 load_public_identity_files();
742 /* Expand ~ in known host file names. */
744 options.system_hostfile =
745 tilde_expand_filename(options.system_hostfile, original_real_uid);
746 options.user_hostfile =
747 tilde_expand_filename(options.user_hostfile, original_real_uid);
748 options.system_hostfile2 =
749 tilde_expand_filename(options.system_hostfile2, original_real_uid);
750 options.user_hostfile2 =
751 tilde_expand_filename(options.user_hostfile2, original_real_uid);
753 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
755 /* Log into the remote system. This never returns if the login fails. */
756 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
758 /* We no longer need the private host keys. Clear them now. */
759 if (sensitive_data.nkeys != 0) {
760 for (i = 0; i < sensitive_data.nkeys; i++) {
761 if (sensitive_data.keys[i] != NULL) {
762 /* Destroys contents safely */
763 debug3("clear hostkey %d", i);
764 key_free(sensitive_data.keys[i]);
765 sensitive_data.keys[i] = NULL;
768 xfree(sensitive_data.keys);
770 for (i = 0; i < options.num_identity_files; i++) {
771 if (options.identity_files[i]) {
772 xfree(options.identity_files[i]);
773 options.identity_files[i] = NULL;
775 if (options.identity_keys[i]) {
776 key_free(options.identity_keys[i]);
777 options.identity_keys[i] = NULL;
781 exit_status = compat20 ? ssh_session2() : ssh_session();
784 if (options.control_path != NULL && control_fd != -1)
785 unlink(options.control_path);
788 * Send SIGHUP to proxy command if used. We don't wait() in
789 * case it hangs and instead rely on init to reap the child
791 if (proxy_command_pid > 1)
792 kill(proxy_command_pid, SIGHUP);
798 ssh_init_forwarding(void)
803 /* Initiate local TCP/IP port forwardings. */
804 for (i = 0; i < options.num_local_forwards; i++) {
805 debug("Local connections to %.200s:%d forwarded to remote "
807 (options.local_forwards[i].listen_host == NULL) ?
808 (options.gateway_ports ? "*" : "LOCALHOST") :
809 options.local_forwards[i].listen_host,
810 options.local_forwards[i].listen_port,
811 options.local_forwards[i].connect_host,
812 options.local_forwards[i].connect_port);
813 success += channel_setup_local_fwd_listener(
814 options.local_forwards[i].listen_host,
815 options.local_forwards[i].listen_port,
816 options.local_forwards[i].connect_host,
817 options.local_forwards[i].connect_port,
818 options.gateway_ports);
820 if (i > 0 && success == 0)
821 error("Could not request local forwarding.");
823 /* Initiate remote TCP/IP port forwardings. */
824 for (i = 0; i < options.num_remote_forwards; i++) {
825 debug("Remote connections from %.200s:%d forwarded to "
826 "local address %.200s:%d",
827 (options.remote_forwards[i].listen_host == NULL) ?
828 "LOCALHOST" : options.remote_forwards[i].listen_host,
829 options.remote_forwards[i].listen_port,
830 options.remote_forwards[i].connect_host,
831 options.remote_forwards[i].connect_port);
832 channel_request_remote_forwarding(
833 options.remote_forwards[i].listen_host,
834 options.remote_forwards[i].listen_port,
835 options.remote_forwards[i].connect_host,
836 options.remote_forwards[i].connect_port);
841 check_agent_present(void)
843 if (options.forward_agent) {
844 /* Clear agent forwarding if we don't have an agent. */
845 if (!ssh_agent_present())
846 options.forward_agent = 0;
860 /* Enable compression if requested. */
861 if (options.compression) {
862 debug("Requesting compression at level %d.", options.compression_level);
864 if (options.compression_level < 1 || options.compression_level > 9)
865 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
867 /* Send the request. */
868 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
869 packet_put_int(options.compression_level);
872 type = packet_read();
873 if (type == SSH_SMSG_SUCCESS)
874 packet_start_compression(options.compression_level);
875 else if (type == SSH_SMSG_FAILURE)
876 logit("Warning: Remote host refused compression.");
878 packet_disconnect("Protocol error waiting for compression response.");
880 /* Allocate a pseudo tty if appropriate. */
882 debug("Requesting pty.");
884 /* Start the packet. */
885 packet_start(SSH_CMSG_REQUEST_PTY);
887 /* Store TERM in the packet. There is no limit on the
888 length of the string. */
892 packet_put_cstring(cp);
894 /* Store window size in the packet. */
895 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
896 memset(&ws, 0, sizeof(ws));
897 packet_put_int((u_int)ws.ws_row);
898 packet_put_int((u_int)ws.ws_col);
899 packet_put_int((u_int)ws.ws_xpixel);
900 packet_put_int((u_int)ws.ws_ypixel);
902 /* Store tty modes in the packet. */
903 tty_make_modes(fileno(stdin), NULL);
905 /* Send the packet, and wait for it to leave. */
909 /* Read response from the server. */
910 type = packet_read();
911 if (type == SSH_SMSG_SUCCESS) {
914 } else if (type == SSH_SMSG_FAILURE)
915 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
917 packet_disconnect("Protocol error waiting for pty request response.");
919 /* Request X11 forwarding if enabled and DISPLAY is set. */
920 display = getenv("DISPLAY");
921 if (options.forward_x11 && display != NULL) {
923 /* Get reasonable local authentication information. */
924 client_x11_get_proto(display, options.xauth_location,
925 options.forward_x11_trusted, &proto, &data);
926 /* Request forwarding with authentication spoofing. */
927 debug("Requesting X11 forwarding with authentication spoofing.");
928 x11_request_forwarding_with_spoofing(0, display, proto, data);
930 /* Read response from the server. */
931 type = packet_read();
932 if (type == SSH_SMSG_SUCCESS) {
934 } else if (type == SSH_SMSG_FAILURE) {
935 logit("Warning: Remote host denied X11 forwarding.");
937 packet_disconnect("Protocol error waiting for X11 forwarding");
940 /* Tell the packet module whether this is an interactive session. */
941 packet_set_interactive(interactive);
943 /* Request authentication agent forwarding if appropriate. */
944 check_agent_present();
946 if (options.forward_agent) {
947 debug("Requesting authentication agent forwarding.");
948 auth_request_forwarding();
950 /* Read response from the server. */
951 type = packet_read();
953 if (type != SSH_SMSG_SUCCESS)
954 logit("Warning: Remote host denied authentication agent forwarding.");
957 /* Initiate port forwardings. */
958 ssh_init_forwarding();
960 /* If requested, let ssh continue in the background. */
961 if (fork_after_authentication_flag)
962 if (daemon(1, 1) < 0)
963 fatal("daemon() failed: %.200s", strerror(errno));
966 * If a command was specified on the command line, execute the
967 * command now. Otherwise request the server to start a shell.
969 if (buffer_len(&command) > 0) {
970 int len = buffer_len(&command);
973 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
974 packet_start(SSH_CMSG_EXEC_CMD);
975 packet_put_string(buffer_ptr(&command), buffer_len(&command));
979 debug("Requesting shell.");
980 packet_start(SSH_CMSG_EXEC_SHELL);
985 /* Enter the interactive session. */
986 return client_loop(have_tty, tty_flag ?
987 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
991 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
995 id = packet_get_int();
996 len = buffer_len(&command);
1000 if (type == SSH2_MSG_CHANNEL_FAILURE)
1001 fatal("Request for subsystem '%.*s' failed on channel %d",
1002 len, (u_char *)buffer_ptr(&command), id);
1006 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1010 i = client_global_request_id++;
1011 if (i >= options.num_remote_forwards)
1013 debug("remote forward %s for: listen %d, connect %s:%d",
1014 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1015 options.remote_forwards[i].listen_port,
1016 options.remote_forwards[i].connect_host,
1017 options.remote_forwards[i].connect_port);
1018 if (type == SSH2_MSG_REQUEST_FAILURE)
1019 logit("Warning: remote port forwarding failed for listen "
1020 "port %d", options.remote_forwards[i].listen_port);
1024 ssh_control_listener(void)
1026 struct sockaddr_un addr;
1030 if (options.control_path == NULL ||
1031 options.control_master == SSHCTL_MASTER_NO)
1034 debug("setting up multiplex master socket");
1036 memset(&addr, '\0', sizeof(addr));
1037 addr.sun_family = AF_UNIX;
1038 addr_len = offsetof(struct sockaddr_un, sun_path) +
1039 strlen(options.control_path) + 1;
1041 if (strlcpy(addr.sun_path, options.control_path,
1042 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1043 fatal("ControlPath too long");
1045 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1046 fatal("%s socket(): %s", __func__, strerror(errno));
1048 old_umask = umask(0177);
1049 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1051 if (errno == EINVAL || errno == EADDRINUSE)
1052 fatal("ControlSocket %s already exists",
1053 options.control_path);
1055 fatal("%s bind(): %s", __func__, strerror(errno));
1059 if (listen(control_fd, 64) == -1)
1060 fatal("%s listen(): %s", __func__, strerror(errno));
1062 set_nonblock(control_fd);
1065 /* request pty/x11/agent/tcpfwd/shell for channel */
1067 ssh_session2_setup(int id, void *arg)
1069 extern char **environ;
1070 const char *display;
1071 int interactive = tty_flag;
1073 display = getenv("DISPLAY");
1074 if (options.forward_x11 && display != NULL) {
1076 /* Get reasonable local authentication information. */
1077 client_x11_get_proto(display, options.xauth_location,
1078 options.forward_x11_trusted, &proto, &data);
1079 /* Request forwarding with authentication spoofing. */
1080 debug("Requesting X11 forwarding with authentication spoofing.");
1081 x11_request_forwarding_with_spoofing(id, display, proto, data);
1083 /* XXX wait for reply */
1086 check_agent_present();
1087 if (options.forward_agent) {
1088 debug("Requesting authentication agent forwarding.");
1089 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1093 if (options.tun_open != SSH_TUNMODE_NO) {
1097 debug("Requesting tun.");
1098 if ((fd = tun_open(options.tun_local,
1099 options.tun_open)) >= 0) {
1100 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1101 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1104 #if defined(SSH_TUN_FILTER)
1105 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1106 channel_register_filter(c->self, sys_tun_infilter,
1109 packet_start(SSH2_MSG_CHANNEL_OPEN);
1110 packet_put_cstring("tun@openssh.com");
1111 packet_put_int(c->self);
1112 packet_put_int(c->local_window_max);
1113 packet_put_int(c->local_maxpacket);
1114 packet_put_int(options.tun_open);
1115 packet_put_int(options.tun_remote);
1120 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1121 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1123 packet_set_interactive(interactive);
1126 /* open new channel for a session */
1128 ssh_session2_open(void)
1131 int window, packetmax, in, out, err;
1133 if (stdin_null_flag) {
1134 in = open(_PATH_DEVNULL, O_RDONLY);
1136 in = dup(STDIN_FILENO);
1138 out = dup(STDOUT_FILENO);
1139 err = dup(STDERR_FILENO);
1141 if (in < 0 || out < 0 || err < 0)
1142 fatal("dup() in/out/err failed");
1144 /* enable nonblocking unless tty */
1152 window = CHAN_SES_WINDOW_DEFAULT;
1153 packetmax = CHAN_SES_PACKET_DEFAULT;
1159 "session", SSH_CHANNEL_OPENING, in, out, err,
1160 window, packetmax, CHAN_EXTENDED_WRITE,
1161 "client-session", /*nonblock*/0);
1163 debug3("ssh_session2_open: channel_new: %d", c->self);
1165 channel_send_open(c->self);
1167 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1177 /* XXX should be pre-session */
1178 ssh_init_forwarding();
1179 ssh_control_listener();
1181 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1182 id = ssh_session2_open();
1184 /* Execute a local command */
1185 if (options.local_command != NULL &&
1186 options.permit_local_command)
1187 ssh_local_cmd(options.local_command);
1189 /* If requested, let ssh continue in the background. */
1190 if (fork_after_authentication_flag)
1191 if (daemon(1, 1) < 0)
1192 fatal("daemon() failed: %.200s", strerror(errno));
1194 return client_loop(tty_flag, tty_flag ?
1195 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1199 load_public_identity_files(void)
1201 char *filename, *cp, thishost[NI_MAXHOST];
1208 if (options.smartcard_device != NULL &&
1209 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1210 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1212 for (i = 0; keys[i] != NULL; i++) {
1214 memmove(&options.identity_files[1], &options.identity_files[0],
1215 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1216 memmove(&options.identity_keys[1], &options.identity_keys[0],
1217 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1218 options.num_identity_files++;
1219 options.identity_keys[0] = keys[i];
1220 options.identity_files[0] = sc_get_key_label(keys[i]);
1222 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1223 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1227 #endif /* SMARTCARD */
1228 if ((pw = getpwuid(original_real_uid)) == NULL)
1229 fatal("load_public_identity_files: getpwuid failed");
1230 if (gethostname(thishost, sizeof(thishost)) == -1)
1231 fatal("load_public_identity_files: gethostname: %s",
1233 for (; i < options.num_identity_files; i++) {
1234 cp = tilde_expand_filename(options.identity_files[i],
1236 filename = percent_expand(cp, "d", pw->pw_dir,
1237 "u", pw->pw_name, "l", thishost, "h", host,
1238 "r", options.user, (char *)NULL);
1240 public = key_load_public(filename, NULL);
1241 debug("identity file %s type %d", filename,
1242 public ? public->type : -1);
1243 xfree(options.identity_files[i]);
1244 options.identity_files[i] = filename;
1245 options.identity_keys[i] = public;
1250 control_client_sighandler(int signo)
1252 control_client_terminate = signo;
1256 control_client_sigrelay(int signo)
1258 if (control_server_pid > 1)
1259 kill(control_server_pid, signo);
1263 env_permitted(char *env)
1266 char name[1024], *cp;
1268 if (strlcpy(name, env, sizeof(name)) >= sizeof(name))
1269 fatal("env_permitted: name too long");
1270 if ((cp = strchr(name, '=')) == NULL)
1275 for (i = 0; i < options.num_send_env; i++)
1276 if (match_pattern(name, options.send_env[i]))
1283 control_client(const char *path)
1285 struct sockaddr_un addr;
1286 int i, r, fd, sock, exitval, num_env, addr_len;
1289 extern char **environ;
1292 if (mux_command == 0)
1293 mux_command = SSHMUX_COMMAND_OPEN;
1295 switch (options.control_master) {
1296 case SSHCTL_MASTER_AUTO:
1297 case SSHCTL_MASTER_AUTO_ASK:
1298 debug("auto-mux: Trying existing master");
1300 case SSHCTL_MASTER_NO:
1306 memset(&addr, '\0', sizeof(addr));
1307 addr.sun_family = AF_UNIX;
1308 addr_len = offsetof(struct sockaddr_un, sun_path) +
1311 if (strlcpy(addr.sun_path, path,
1312 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1313 fatal("ControlPath too long");
1315 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1316 fatal("%s socket(): %s", __func__, strerror(errno));
1318 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1319 if (mux_command != SSHMUX_COMMAND_OPEN) {
1320 fatal("Control socket connect(%.100s): %s", path,
1323 if (errno == ENOENT)
1324 debug("Control socket \"%.100s\" does not exist", path);
1326 error("Control socket connect(%.100s): %s", path,
1333 if (stdin_null_flag) {
1334 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1335 fatal("open(/dev/null): %s", strerror(errno));
1336 if (dup2(fd, STDIN_FILENO) == -1)
1337 fatal("dup2: %s", strerror(errno));
1338 if (fd > STDERR_FILENO)
1342 term = getenv("TERM");
1346 flags |= SSHMUX_FLAG_TTY;
1348 flags |= SSHMUX_FLAG_SUBSYS;
1349 if (options.forward_x11)
1350 flags |= SSHMUX_FLAG_X11_FWD;
1351 if (options.forward_agent)
1352 flags |= SSHMUX_FLAG_AGENT_FWD;
1356 /* Send our command to server */
1357 buffer_put_int(&m, mux_command);
1358 buffer_put_int(&m, flags);
1359 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1360 fatal("%s: msg_send", __func__);
1363 /* Get authorisation status and PID of controlee */
1364 if (ssh_msg_recv(sock, &m) == -1)
1365 fatal("%s: msg_recv", __func__);
1366 if (buffer_get_char(&m) != SSHMUX_VER)
1367 fatal("%s: wrong version", __func__);
1368 if (buffer_get_int(&m) != 1)
1369 fatal("Connection to master denied");
1370 control_server_pid = buffer_get_int(&m);
1374 switch (mux_command) {
1375 case SSHMUX_COMMAND_ALIVE_CHECK:
1376 fprintf(stderr, "Master running (pid=%d)\r\n",
1377 control_server_pid);
1379 case SSHMUX_COMMAND_TERMINATE:
1380 fprintf(stderr, "Exit request sent.\r\n");
1382 case SSHMUX_COMMAND_OPEN:
1383 /* continue below */
1386 fatal("silly mux_command %d", mux_command);
1389 /* SSHMUX_COMMAND_OPEN */
1390 buffer_put_cstring(&m, term ? term : "");
1391 buffer_append(&command, "\0", 1);
1392 buffer_put_cstring(&m, buffer_ptr(&command));
1394 if (options.num_send_env == 0 || environ == NULL) {
1395 buffer_put_int(&m, 0);
1397 /* Pass environment */
1399 for (i = 0; environ[i] != NULL; i++)
1400 if (env_permitted(environ[i]))
1401 num_env++; /* Count */
1403 buffer_put_int(&m, num_env);
1405 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1406 if (env_permitted(environ[i])) {
1408 buffer_put_cstring(&m, environ[i]);
1412 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1413 fatal("%s: msg_send", __func__);
1415 mm_send_fd(sock, STDIN_FILENO);
1416 mm_send_fd(sock, STDOUT_FILENO);
1417 mm_send_fd(sock, STDERR_FILENO);
1419 /* Wait for reply, so master has a chance to gather ttymodes */
1421 if (ssh_msg_recv(sock, &m) == -1)
1422 fatal("%s: msg_recv", __func__);
1423 if (buffer_get_char(&m) != SSHMUX_VER)
1424 fatal("%s: wrong version", __func__);
1427 signal(SIGHUP, control_client_sighandler);
1428 signal(SIGINT, control_client_sighandler);
1429 signal(SIGTERM, control_client_sighandler);
1430 signal(SIGWINCH, control_client_sigrelay);
1435 /* Stick around until the controlee closes the client_fd */
1437 for (;!control_client_terminate;) {
1438 r = read(sock, &exitval, sizeof(exitval));
1440 debug2("Received EOF from master");
1444 debug2("Received exit status from master %d", exitval);
1445 if (r == -1 && errno != EINTR)
1446 fatal("%s: read %s", __func__, strerror(errno));
1449 if (control_client_terminate)
1450 debug2("Exiting on signal %d", control_client_terminate);
1456 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1457 fprintf(stderr, "Connection to master closed.\r\n");