1 /* $OpenBSD: ssh.c,v 1.280 2006/07/08 21:47:12 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>
61 #include <openssl/evp.h>
62 #include <openssl/err.h>
77 #include "pathnames.h"
79 #include "clientloop.h"
82 #include "sshconnect.h"
89 #include "monitor_fdpass.h"
97 extern char *__progname;
99 /* Flag indicating whether debug mode is on. This can be set on the command line. */
102 /* Flag indicating whether a tty should be allocated */
105 int force_tty_flag = 0;
107 /* don't exec a shell */
108 int no_shell_flag = 0;
111 * Flag indicating that nothing should be read from stdin. This can be set
112 * on the command line.
114 int stdin_null_flag = 0;
117 * Flag indicating that ssh should fork after authentication. This is useful
118 * so that the passphrase can be entered manually, and then ssh goes to the
121 int fork_after_authentication_flag = 0;
124 * General data structure for command line options and options configurable
125 * in configuration files. See readconf.h.
129 /* optional user configfile */
133 * Name of the host we are connecting to. This is the name given on the
134 * command line, or the HostName specified for the user-supplied name in a
135 * configuration file.
139 /* socket address the host resolves to */
140 struct sockaddr_storage hostaddr;
142 /* Private host keys. */
143 Sensitive sensitive_data;
145 /* Original real UID. */
146 uid_t original_real_uid;
147 uid_t original_effective_uid;
149 /* command to be executed */
152 /* Should we execute a command or invoke a subsystem? */
153 int subsystem_flag = 0;
155 /* # of replies received for global requests */
156 static int client_global_request_id = 0;
158 /* pid of proxycommand child process */
159 pid_t proxy_command_pid = 0;
161 /* fd to control socket */
164 /* Multiplexing control command */
165 static u_int mux_command = 0;
167 /* Only used in control client mode */
168 volatile sig_atomic_t control_client_terminate = 0;
169 u_int control_server_pid = 0;
171 /* Prints a help message to the user. This function never returns. */
177 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
178 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
179 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
180 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
181 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
182 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
187 static int ssh_session(void);
188 static int ssh_session2(void);
189 static void load_public_identity_files(void);
190 static void control_client(const char *path);
193 * Main program for the ssh client.
196 main(int ac, char **av)
198 int i, opt, exit_status;
199 char *p, *cp, *line, buf[256];
203 extern int optind, optreset;
208 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
211 __progname = ssh_get_progname(av[0]);
215 * Save the original real uid. It will be needed later (uid-swapping
216 * may clobber the real uid).
218 original_real_uid = getuid();
219 original_effective_uid = geteuid();
222 * Use uid-swapping to give up root privileges for the duration of
223 * option processing. We will re-instantiate the rights when we are
224 * ready to create the privileged port, and will permanently drop
225 * them when the port has been created (actually, when the connection
226 * has been made, as we may need to create the port several times).
230 #ifdef HAVE_SETRLIMIT
231 /* If we are installed setuid root be careful to not drop core. */
232 if (original_real_uid != original_effective_uid) {
234 rlim.rlim_cur = rlim.rlim_max = 0;
235 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
236 fatal("setrlimit failed: %.100s", strerror(errno));
240 pw = getpwuid(original_real_uid);
242 logit("You don't exist, go away!");
245 /* Take a copy of the returned structure. */
249 * Set our umask to something reasonable, as some files are created
250 * with the default umask. This will make them world-readable but
251 * writable only by the owner, which is ok for all files for which we
252 * don't set the modes explicitly.
256 /* Initialize option structure to indicate that no values have been set. */
257 initialize_options(&options);
259 /* Parse command-line arguments. */
263 while ((opt = getopt(ac, av,
264 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
267 options.protocol = SSH_PROTO_1;
270 options.protocol = SSH_PROTO_2;
273 options.address_family = AF_INET;
276 options.address_family = AF_INET6;
282 fork_after_authentication_flag = 1;
286 options.forward_x11 = 0;
289 options.forward_x11 = 1;
292 options.forward_x11 = 1;
293 options.forward_x11_trusted = 1;
296 options.gateway_ports = 1;
299 if (strcmp(optarg, "check") == 0)
300 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
301 else if (strcmp(optarg, "exit") == 0)
302 mux_command = SSHMUX_COMMAND_TERMINATE;
304 fatal("Invalid multiplex command.");
306 case 'P': /* deprecated */
307 options.use_privileged_port = 0;
310 options.forward_agent = 0;
313 options.forward_agent = 1;
316 options.gss_deleg_creds = 0;
319 if (stat(optarg, &st) < 0) {
320 fprintf(stderr, "Warning: Identity file %s "
321 "not accessible: %s.\n", optarg,
325 if (options.num_identity_files >=
326 SSH_MAX_IDENTITY_FILES)
327 fatal("Too many identity files specified "
328 "(max %d)", SSH_MAX_IDENTITY_FILES);
329 options.identity_files[options.num_identity_files++] =
334 options.smartcard_device = xstrdup(optarg);
336 fprintf(stderr, "no support for smartcards.\n");
345 if (debug_flag == 0) {
347 options.log_level = SYSLOG_LEVEL_DEBUG1;
349 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
355 fprintf(stderr, "%s, %s\n",
356 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
361 if (options.tun_open == -1)
362 options.tun_open = SSH_TUNMODE_DEFAULT;
363 options.tun_local = a2tun(optarg, &options.tun_remote);
364 if (options.tun_local == SSH_TUNID_ERR) {
365 fprintf(stderr, "Bad tun device '%s'\n", optarg);
370 options.log_level = SYSLOG_LEVEL_QUIET;
373 if (optarg[0] == '^' && optarg[2] == 0 &&
374 (u_char) optarg[1] >= 64 &&
375 (u_char) optarg[1] < 128)
376 options.escape_char = (u_char) optarg[1] & 31;
377 else if (strlen(optarg) == 1)
378 options.escape_char = (u_char) optarg[0];
379 else if (strcmp(optarg, "none") == 0)
380 options.escape_char = SSH_ESCAPECHAR_NONE;
382 fprintf(stderr, "Bad escape character '%s'.\n",
388 if (ciphers_valid(optarg)) {
390 options.ciphers = xstrdup(optarg);
391 options.cipher = SSH_CIPHER_INVALID;
394 options.cipher = cipher_number(optarg);
395 if (options.cipher == -1) {
397 "Unknown cipher type '%s'\n",
401 if (options.cipher == SSH_CIPHER_3DES)
402 options.ciphers = "3des-cbc";
403 else if (options.cipher == SSH_CIPHER_BLOWFISH)
404 options.ciphers = "blowfish-cbc";
406 options.ciphers = (char *)-1;
410 if (mac_valid(optarg))
411 options.macs = xstrdup(optarg);
413 fprintf(stderr, "Unknown mac type '%s'\n",
419 if (options.control_master == SSHCTL_MASTER_YES)
420 options.control_master = SSHCTL_MASTER_ASK;
422 options.control_master = SSHCTL_MASTER_YES;
425 options.port = a2port(optarg);
426 if (options.port == 0) {
427 fprintf(stderr, "Bad port '%s'\n", optarg);
432 options.user = optarg;
436 if (parse_forward(&fwd, optarg))
437 add_local_forward(&options, &fwd);
440 "Bad local forwarding specification '%s'\n",
447 if (parse_forward(&fwd, optarg)) {
448 add_remote_forward(&options, &fwd);
451 "Bad remote forwarding specification "
458 cp = p = xstrdup(optarg);
459 memset(&fwd, '\0', sizeof(fwd));
460 fwd.connect_host = "socks";
461 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
462 fprintf(stderr, "Bad dynamic forwarding "
463 "specification '%.100s'\n", optarg);
467 fwd.listen_port = a2port(cp);
468 fwd.listen_host = cleanhostname(fwd.listen_host);
470 fwd.listen_port = a2port(fwd.listen_host);
471 fwd.listen_host = NULL;
474 if (fwd.listen_port == 0) {
475 fprintf(stderr, "Bad dynamic port '%s'\n",
479 add_local_forward(&options, &fwd);
484 options.compression = 1;
495 line = xstrdup(optarg);
496 if (process_config_line(&options, host ? host : "",
497 line, "command-line", 0, &dummy) != 0)
505 if (options.control_path != NULL)
506 free(options.control_path);
507 options.control_path = xstrdup(optarg);
510 options.bind_address = optarg;
523 if (ac > 0 && !host && **av != '-') {
524 if (strrchr(*av, '@')) {
526 cp = strrchr(p, '@');
527 if (cp == NULL || cp == p)
535 optind = optreset = 1;
541 /* Check that we got a host name. */
545 SSLeay_add_all_algorithms();
546 ERR_load_crypto_strings();
548 /* Initialize the command to execute on remote host. */
549 buffer_init(&command);
552 * Save the command to execute on the remote host in a buffer. There
553 * is no limit on the length of the command, except by the maximum
554 * packet size. Also sets the tty flag if there is no command.
557 /* No command specified - execute shell on a tty. */
559 if (subsystem_flag) {
561 "You must specify a subsystem to invoke.\n");
565 /* A command has been specified. Store it into the buffer. */
566 for (i = 0; i < ac; i++) {
568 buffer_append(&command, " ", 1);
569 buffer_append(&command, av[i], strlen(av[i]));
573 /* Cannot fork to background if no command. */
574 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
575 fatal("Cannot fork into background without a command to execute.");
577 /* Allocate a tty by default if no command specified. */
578 if (buffer_len(&command) == 0)
584 /* Do not allocate a tty if stdin is not a tty. */
585 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
587 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
592 * Initialize "log" output. Since we are the client all output
593 * actually goes to stderr.
595 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
596 SYSLOG_FACILITY_USER, 1);
599 * Read per-user configuration file. Ignore the system wide config
600 * file if the user specifies a config file on the command line.
602 if (config != NULL) {
603 if (!read_config_file(config, host, &options, 0))
604 fatal("Can't open user config file %.100s: "
605 "%.100s", config, strerror(errno));
607 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
608 _PATH_SSH_USER_CONFFILE);
609 (void)read_config_file(buf, host, &options, 1);
611 /* Read systemwide configuration file after use config. */
612 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
616 /* Fill configuration defaults. */
617 fill_default_options(&options);
619 channel_set_af(options.address_family);
622 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
626 if (options.user == NULL)
627 options.user = xstrdup(pw->pw_name);
629 if (options.hostname != NULL)
630 host = options.hostname;
632 /* force lowercase for hostkey matching */
633 if (options.host_key_alias != NULL) {
634 for (p = options.host_key_alias; *p; p++)
636 *p = (char)tolower(*p);
639 /* Get default port if port has not been set. */
640 if (options.port == 0) {
641 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
642 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
645 if (options.proxy_command != NULL &&
646 strcmp(options.proxy_command, "none") == 0)
647 options.proxy_command = NULL;
648 if (options.control_path != NULL &&
649 strcmp(options.control_path, "none") == 0)
650 options.control_path = NULL;
652 if (options.control_path != NULL) {
653 char thishost[NI_MAXHOST];
655 if (gethostname(thishost, sizeof(thishost)) == -1)
656 fatal("gethostname: %s", strerror(errno));
657 snprintf(buf, sizeof(buf), "%d", options.port);
658 cp = tilde_expand_filename(options.control_path,
660 options.control_path = percent_expand(cp, "p", buf, "h", host,
661 "r", options.user, "l", thishost, (char *)NULL);
664 if (mux_command != 0 && options.control_path == NULL)
665 fatal("No ControlPath specified for \"-O\" command");
666 if (options.control_path != NULL)
667 control_client(options.control_path);
669 /* Open a connection to the remote host. */
670 if (ssh_connect(host, &hostaddr, options.port,
671 options.address_family, options.connection_attempts,
673 options.use_privileged_port,
675 original_effective_uid == 0 && options.use_privileged_port,
677 options.proxy_command) != 0)
681 * If we successfully made the connection, load the host private key
682 * in case we will need it later for combined rsa-rhosts
683 * authentication. This must be done before releasing extra
684 * privileges, because the file is only readable by root.
685 * If we cannot access the private keys, load the public keys
686 * instead and try to execute the ssh-keysign helper instead.
688 sensitive_data.nkeys = 0;
689 sensitive_data.keys = NULL;
690 sensitive_data.external_keysign = 0;
691 if (options.rhosts_rsa_authentication ||
692 options.hostbased_authentication) {
693 sensitive_data.nkeys = 3;
694 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
698 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
699 _PATH_HOST_KEY_FILE, "", NULL, NULL);
700 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
701 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
702 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
703 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
706 if (options.hostbased_authentication == 1 &&
707 sensitive_data.keys[0] == NULL &&
708 sensitive_data.keys[1] == NULL &&
709 sensitive_data.keys[2] == NULL) {
710 sensitive_data.keys[1] = key_load_public(
711 _PATH_HOST_DSA_KEY_FILE, NULL);
712 sensitive_data.keys[2] = key_load_public(
713 _PATH_HOST_RSA_KEY_FILE, NULL);
714 sensitive_data.external_keysign = 1;
718 * Get rid of any extra privileges that we may have. We will no
719 * longer need them. Also, extra privileges could make it very hard
720 * to read identity files and other non-world-readable files from the
721 * user's home directory if it happens to be on a NFS volume where
722 * root is mapped to nobody.
724 if (original_effective_uid == 0) {
726 permanently_set_uid(pw);
730 * Now that we are back to our own permissions, create ~/.ssh
731 * directory if it doesn't already exist.
733 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
734 if (stat(buf, &st) < 0)
735 if (mkdir(buf, 0700) < 0)
736 error("Could not create directory '%.200s'.", buf);
738 /* load options.identity_files */
739 load_public_identity_files();
741 /* Expand ~ in known host file names. */
743 options.system_hostfile =
744 tilde_expand_filename(options.system_hostfile, original_real_uid);
745 options.user_hostfile =
746 tilde_expand_filename(options.user_hostfile, original_real_uid);
747 options.system_hostfile2 =
748 tilde_expand_filename(options.system_hostfile2, original_real_uid);
749 options.user_hostfile2 =
750 tilde_expand_filename(options.user_hostfile2, original_real_uid);
752 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
754 /* Log into the remote system. This never returns if the login fails. */
755 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
757 /* We no longer need the private host keys. Clear them now. */
758 if (sensitive_data.nkeys != 0) {
759 for (i = 0; i < sensitive_data.nkeys; i++) {
760 if (sensitive_data.keys[i] != NULL) {
761 /* Destroys contents safely */
762 debug3("clear hostkey %d", i);
763 key_free(sensitive_data.keys[i]);
764 sensitive_data.keys[i] = NULL;
767 xfree(sensitive_data.keys);
769 for (i = 0; i < options.num_identity_files; i++) {
770 if (options.identity_files[i]) {
771 xfree(options.identity_files[i]);
772 options.identity_files[i] = NULL;
774 if (options.identity_keys[i]) {
775 key_free(options.identity_keys[i]);
776 options.identity_keys[i] = NULL;
780 exit_status = compat20 ? ssh_session2() : ssh_session();
783 if (options.control_path != NULL && control_fd != -1)
784 unlink(options.control_path);
787 * Send SIGHUP to proxy command if used. We don't wait() in
788 * case it hangs and instead rely on init to reap the child
790 if (proxy_command_pid > 1)
791 kill(proxy_command_pid, SIGHUP);
797 ssh_init_forwarding(void)
802 /* Initiate local TCP/IP port forwardings. */
803 for (i = 0; i < options.num_local_forwards; i++) {
804 debug("Local connections to %.200s:%d forwarded to remote "
806 (options.local_forwards[i].listen_host == NULL) ?
807 (options.gateway_ports ? "*" : "LOCALHOST") :
808 options.local_forwards[i].listen_host,
809 options.local_forwards[i].listen_port,
810 options.local_forwards[i].connect_host,
811 options.local_forwards[i].connect_port);
812 success += channel_setup_local_fwd_listener(
813 options.local_forwards[i].listen_host,
814 options.local_forwards[i].listen_port,
815 options.local_forwards[i].connect_host,
816 options.local_forwards[i].connect_port,
817 options.gateway_ports);
819 if (i > 0 && success == 0)
820 error("Could not request local forwarding.");
822 /* Initiate remote TCP/IP port forwardings. */
823 for (i = 0; i < options.num_remote_forwards; i++) {
824 debug("Remote connections from %.200s:%d forwarded to "
825 "local address %.200s:%d",
826 (options.remote_forwards[i].listen_host == NULL) ?
827 "LOCALHOST" : options.remote_forwards[i].listen_host,
828 options.remote_forwards[i].listen_port,
829 options.remote_forwards[i].connect_host,
830 options.remote_forwards[i].connect_port);
831 channel_request_remote_forwarding(
832 options.remote_forwards[i].listen_host,
833 options.remote_forwards[i].listen_port,
834 options.remote_forwards[i].connect_host,
835 options.remote_forwards[i].connect_port);
840 check_agent_present(void)
842 if (options.forward_agent) {
843 /* Clear agent forwarding if we don't have an agent. */
844 if (!ssh_agent_present())
845 options.forward_agent = 0;
859 /* Enable compression if requested. */
860 if (options.compression) {
861 debug("Requesting compression at level %d.", options.compression_level);
863 if (options.compression_level < 1 || options.compression_level > 9)
864 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
866 /* Send the request. */
867 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
868 packet_put_int(options.compression_level);
871 type = packet_read();
872 if (type == SSH_SMSG_SUCCESS)
873 packet_start_compression(options.compression_level);
874 else if (type == SSH_SMSG_FAILURE)
875 logit("Warning: Remote host refused compression.");
877 packet_disconnect("Protocol error waiting for compression response.");
879 /* Allocate a pseudo tty if appropriate. */
881 debug("Requesting pty.");
883 /* Start the packet. */
884 packet_start(SSH_CMSG_REQUEST_PTY);
886 /* Store TERM in the packet. There is no limit on the
887 length of the string. */
891 packet_put_cstring(cp);
893 /* Store window size in the packet. */
894 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
895 memset(&ws, 0, sizeof(ws));
896 packet_put_int((u_int)ws.ws_row);
897 packet_put_int((u_int)ws.ws_col);
898 packet_put_int((u_int)ws.ws_xpixel);
899 packet_put_int((u_int)ws.ws_ypixel);
901 /* Store tty modes in the packet. */
902 tty_make_modes(fileno(stdin), NULL);
904 /* Send the packet, and wait for it to leave. */
908 /* Read response from the server. */
909 type = packet_read();
910 if (type == SSH_SMSG_SUCCESS) {
913 } else if (type == SSH_SMSG_FAILURE)
914 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
916 packet_disconnect("Protocol error waiting for pty request response.");
918 /* Request X11 forwarding if enabled and DISPLAY is set. */
919 display = getenv("DISPLAY");
920 if (options.forward_x11 && display != NULL) {
922 /* Get reasonable local authentication information. */
923 client_x11_get_proto(display, options.xauth_location,
924 options.forward_x11_trusted, &proto, &data);
925 /* Request forwarding with authentication spoofing. */
926 debug("Requesting X11 forwarding with authentication spoofing.");
927 x11_request_forwarding_with_spoofing(0, display, proto, data);
929 /* Read response from the server. */
930 type = packet_read();
931 if (type == SSH_SMSG_SUCCESS) {
933 } else if (type == SSH_SMSG_FAILURE) {
934 logit("Warning: Remote host denied X11 forwarding.");
936 packet_disconnect("Protocol error waiting for X11 forwarding");
939 /* Tell the packet module whether this is an interactive session. */
940 packet_set_interactive(interactive);
942 /* Request authentication agent forwarding if appropriate. */
943 check_agent_present();
945 if (options.forward_agent) {
946 debug("Requesting authentication agent forwarding.");
947 auth_request_forwarding();
949 /* Read response from the server. */
950 type = packet_read();
952 if (type != SSH_SMSG_SUCCESS)
953 logit("Warning: Remote host denied authentication agent forwarding.");
956 /* Initiate port forwardings. */
957 ssh_init_forwarding();
959 /* If requested, let ssh continue in the background. */
960 if (fork_after_authentication_flag)
961 if (daemon(1, 1) < 0)
962 fatal("daemon() failed: %.200s", strerror(errno));
965 * If a command was specified on the command line, execute the
966 * command now. Otherwise request the server to start a shell.
968 if (buffer_len(&command) > 0) {
969 int len = buffer_len(&command);
972 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
973 packet_start(SSH_CMSG_EXEC_CMD);
974 packet_put_string(buffer_ptr(&command), buffer_len(&command));
978 debug("Requesting shell.");
979 packet_start(SSH_CMSG_EXEC_SHELL);
984 /* Enter the interactive session. */
985 return client_loop(have_tty, tty_flag ?
986 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
990 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
994 id = packet_get_int();
995 len = buffer_len(&command);
999 if (type == SSH2_MSG_CHANNEL_FAILURE)
1000 fatal("Request for subsystem '%.*s' failed on channel %d",
1001 len, (u_char *)buffer_ptr(&command), id);
1005 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1009 i = client_global_request_id++;
1010 if (i >= options.num_remote_forwards)
1012 debug("remote forward %s for: listen %d, connect %s:%d",
1013 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1014 options.remote_forwards[i].listen_port,
1015 options.remote_forwards[i].connect_host,
1016 options.remote_forwards[i].connect_port);
1017 if (type == SSH2_MSG_REQUEST_FAILURE)
1018 logit("Warning: remote port forwarding failed for listen "
1019 "port %d", options.remote_forwards[i].listen_port);
1023 ssh_control_listener(void)
1025 struct sockaddr_un addr;
1029 if (options.control_path == NULL ||
1030 options.control_master == SSHCTL_MASTER_NO)
1033 debug("setting up multiplex master socket");
1035 memset(&addr, '\0', sizeof(addr));
1036 addr.sun_family = AF_UNIX;
1037 addr_len = offsetof(struct sockaddr_un, sun_path) +
1038 strlen(options.control_path) + 1;
1040 if (strlcpy(addr.sun_path, options.control_path,
1041 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1042 fatal("ControlPath too long");
1044 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1045 fatal("%s socket(): %s", __func__, strerror(errno));
1047 old_umask = umask(0177);
1048 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1050 if (errno == EINVAL || errno == EADDRINUSE)
1051 fatal("ControlSocket %s already exists",
1052 options.control_path);
1054 fatal("%s bind(): %s", __func__, strerror(errno));
1058 if (listen(control_fd, 64) == -1)
1059 fatal("%s listen(): %s", __func__, strerror(errno));
1061 set_nonblock(control_fd);
1064 /* request pty/x11/agent/tcpfwd/shell for channel */
1066 ssh_session2_setup(int id, void *arg)
1068 extern char **environ;
1069 const char *display;
1070 int interactive = tty_flag;
1072 display = getenv("DISPLAY");
1073 if (options.forward_x11 && display != NULL) {
1075 /* Get reasonable local authentication information. */
1076 client_x11_get_proto(display, options.xauth_location,
1077 options.forward_x11_trusted, &proto, &data);
1078 /* Request forwarding with authentication spoofing. */
1079 debug("Requesting X11 forwarding with authentication spoofing.");
1080 x11_request_forwarding_with_spoofing(id, display, proto, data);
1082 /* XXX wait for reply */
1085 check_agent_present();
1086 if (options.forward_agent) {
1087 debug("Requesting authentication agent forwarding.");
1088 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1092 if (options.tun_open != SSH_TUNMODE_NO) {
1096 debug("Requesting tun.");
1097 if ((fd = tun_open(options.tun_local,
1098 options.tun_open)) >= 0) {
1099 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1100 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1103 #if defined(SSH_TUN_FILTER)
1104 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1105 channel_register_filter(c->self, sys_tun_infilter,
1108 packet_start(SSH2_MSG_CHANNEL_OPEN);
1109 packet_put_cstring("tun@openssh.com");
1110 packet_put_int(c->self);
1111 packet_put_int(c->local_window_max);
1112 packet_put_int(c->local_maxpacket);
1113 packet_put_int(options.tun_open);
1114 packet_put_int(options.tun_remote);
1119 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1120 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1122 packet_set_interactive(interactive);
1125 /* open new channel for a session */
1127 ssh_session2_open(void)
1130 int window, packetmax, in, out, err;
1132 if (stdin_null_flag) {
1133 in = open(_PATH_DEVNULL, O_RDONLY);
1135 in = dup(STDIN_FILENO);
1137 out = dup(STDOUT_FILENO);
1138 err = dup(STDERR_FILENO);
1140 if (in < 0 || out < 0 || err < 0)
1141 fatal("dup() in/out/err failed");
1143 /* enable nonblocking unless tty */
1151 window = CHAN_SES_WINDOW_DEFAULT;
1152 packetmax = CHAN_SES_PACKET_DEFAULT;
1158 "session", SSH_CHANNEL_OPENING, in, out, err,
1159 window, packetmax, CHAN_EXTENDED_WRITE,
1160 "client-session", /*nonblock*/0);
1162 debug3("ssh_session2_open: channel_new: %d", c->self);
1164 channel_send_open(c->self);
1166 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1176 /* XXX should be pre-session */
1177 ssh_init_forwarding();
1178 ssh_control_listener();
1180 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1181 id = ssh_session2_open();
1183 /* Execute a local command */
1184 if (options.local_command != NULL &&
1185 options.permit_local_command)
1186 ssh_local_cmd(options.local_command);
1188 /* If requested, let ssh continue in the background. */
1189 if (fork_after_authentication_flag)
1190 if (daemon(1, 1) < 0)
1191 fatal("daemon() failed: %.200s", strerror(errno));
1193 return client_loop(tty_flag, tty_flag ?
1194 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1198 load_public_identity_files(void)
1200 char *filename, *cp, thishost[NI_MAXHOST];
1207 if (options.smartcard_device != NULL &&
1208 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1209 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1211 for (i = 0; keys[i] != NULL; i++) {
1213 memmove(&options.identity_files[1], &options.identity_files[0],
1214 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1215 memmove(&options.identity_keys[1], &options.identity_keys[0],
1216 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1217 options.num_identity_files++;
1218 options.identity_keys[0] = keys[i];
1219 options.identity_files[0] = sc_get_key_label(keys[i]);
1221 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1222 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1226 #endif /* SMARTCARD */
1227 if ((pw = getpwuid(original_real_uid)) == NULL)
1228 fatal("load_public_identity_files: getpwuid failed");
1229 if (gethostname(thishost, sizeof(thishost)) == -1)
1230 fatal("load_public_identity_files: gethostname: %s",
1232 for (; i < options.num_identity_files; i++) {
1233 cp = tilde_expand_filename(options.identity_files[i],
1235 filename = percent_expand(cp, "d", pw->pw_dir,
1236 "u", pw->pw_name, "l", thishost, "h", host,
1237 "r", options.user, (char *)NULL);
1239 public = key_load_public(filename, NULL);
1240 debug("identity file %s type %d", filename,
1241 public ? public->type : -1);
1242 xfree(options.identity_files[i]);
1243 options.identity_files[i] = filename;
1244 options.identity_keys[i] = public;
1249 control_client_sighandler(int signo)
1251 control_client_terminate = signo;
1255 control_client_sigrelay(int signo)
1257 if (control_server_pid > 1)
1258 kill(control_server_pid, signo);
1262 env_permitted(char *env)
1265 char name[1024], *cp;
1267 if (strlcpy(name, env, sizeof(name)) >= sizeof(name))
1268 fatal("env_permitted: name too long");
1269 if ((cp = strchr(name, '=')) == NULL)
1274 for (i = 0; i < options.num_send_env; i++)
1275 if (match_pattern(name, options.send_env[i]))
1282 control_client(const char *path)
1284 struct sockaddr_un addr;
1285 int i, r, fd, sock, exitval, num_env, addr_len;
1288 extern char **environ;
1291 if (mux_command == 0)
1292 mux_command = SSHMUX_COMMAND_OPEN;
1294 switch (options.control_master) {
1295 case SSHCTL_MASTER_AUTO:
1296 case SSHCTL_MASTER_AUTO_ASK:
1297 debug("auto-mux: Trying existing master");
1299 case SSHCTL_MASTER_NO:
1305 memset(&addr, '\0', sizeof(addr));
1306 addr.sun_family = AF_UNIX;
1307 addr_len = offsetof(struct sockaddr_un, sun_path) +
1310 if (strlcpy(addr.sun_path, path,
1311 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1312 fatal("ControlPath too long");
1314 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1315 fatal("%s socket(): %s", __func__, strerror(errno));
1317 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1318 if (mux_command != SSHMUX_COMMAND_OPEN) {
1319 fatal("Control socket connect(%.100s): %s", path,
1322 if (errno == ENOENT)
1323 debug("Control socket \"%.100s\" does not exist", path);
1325 error("Control socket connect(%.100s): %s", path,
1332 if (stdin_null_flag) {
1333 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1334 fatal("open(/dev/null): %s", strerror(errno));
1335 if (dup2(fd, STDIN_FILENO) == -1)
1336 fatal("dup2: %s", strerror(errno));
1337 if (fd > STDERR_FILENO)
1341 term = getenv("TERM");
1345 flags |= SSHMUX_FLAG_TTY;
1347 flags |= SSHMUX_FLAG_SUBSYS;
1348 if (options.forward_x11)
1349 flags |= SSHMUX_FLAG_X11_FWD;
1350 if (options.forward_agent)
1351 flags |= SSHMUX_FLAG_AGENT_FWD;
1355 /* Send our command to server */
1356 buffer_put_int(&m, mux_command);
1357 buffer_put_int(&m, flags);
1358 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1359 fatal("%s: msg_send", __func__);
1362 /* Get authorisation status and PID of controlee */
1363 if (ssh_msg_recv(sock, &m) == -1)
1364 fatal("%s: msg_recv", __func__);
1365 if (buffer_get_char(&m) != SSHMUX_VER)
1366 fatal("%s: wrong version", __func__);
1367 if (buffer_get_int(&m) != 1)
1368 fatal("Connection to master denied");
1369 control_server_pid = buffer_get_int(&m);
1373 switch (mux_command) {
1374 case SSHMUX_COMMAND_ALIVE_CHECK:
1375 fprintf(stderr, "Master running (pid=%d)\r\n",
1376 control_server_pid);
1378 case SSHMUX_COMMAND_TERMINATE:
1379 fprintf(stderr, "Exit request sent.\r\n");
1381 case SSHMUX_COMMAND_OPEN:
1382 /* continue below */
1385 fatal("silly mux_command %d", mux_command);
1388 /* SSHMUX_COMMAND_OPEN */
1389 buffer_put_cstring(&m, term ? term : "");
1390 buffer_append(&command, "\0", 1);
1391 buffer_put_cstring(&m, buffer_ptr(&command));
1393 if (options.num_send_env == 0 || environ == NULL) {
1394 buffer_put_int(&m, 0);
1396 /* Pass environment */
1398 for (i = 0; environ[i] != NULL; i++)
1399 if (env_permitted(environ[i]))
1400 num_env++; /* Count */
1402 buffer_put_int(&m, num_env);
1404 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1405 if (env_permitted(environ[i])) {
1407 buffer_put_cstring(&m, environ[i]);
1411 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1412 fatal("%s: msg_send", __func__);
1414 mm_send_fd(sock, STDIN_FILENO);
1415 mm_send_fd(sock, STDOUT_FILENO);
1416 mm_send_fd(sock, STDERR_FILENO);
1418 /* Wait for reply, so master has a chance to gather ttymodes */
1420 if (ssh_msg_recv(sock, &m) == -1)
1421 fatal("%s: msg_recv", __func__);
1422 if (buffer_get_char(&m) != SSHMUX_VER)
1423 fatal("%s: wrong version", __func__);
1426 signal(SIGHUP, control_client_sighandler);
1427 signal(SIGINT, control_client_sighandler);
1428 signal(SIGTERM, control_client_sighandler);
1429 signal(SIGWINCH, control_client_sigrelay);
1434 /* Stick around until the controlee closes the client_fd */
1436 for (;!control_client_terminate;) {
1437 r = read(sock, &exitval, sizeof(exitval));
1439 debug2("Received EOF from master");
1443 debug2("Received exit status from master %d", exitval);
1444 if (r == -1 && errno != EINTR)
1445 fatal("%s: read %s", __func__, strerror(errno));
1448 if (control_client_terminate)
1449 debug2("Exiting on signal %d", control_client_terminate);
1455 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1456 fprintf(stderr, "Connection to master closed.\r\n");