2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * Ssh client program. This program can be used to log into a remote machine.
6 * The software supports strong authentication, encryption, and forwarding
7 * of X11, TCP/IP, and authentication connections.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 1999 Niels Provos. All rights reserved.
16 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
18 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
19 * in Canada (German citizen).
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 RCSID("$OpenBSD: ssh.c,v 1.224 2004/07/28 09:40:29 markus Exp $");
45 #include <openssl/evp.h>
46 #include <openssl/err.h>
61 #include "pathnames.h"
63 #include "clientloop.h"
66 #include "sshconnect.h"
73 #include "monitor_fdpass.h"
80 extern char *__progname;
82 /* Flag indicating whether debug mode is on. This can be set on the command line. */
85 /* Flag indicating whether a tty should be allocated */
88 int force_tty_flag = 0;
90 /* don't exec a shell */
91 int no_shell_flag = 0;
94 * Flag indicating that nothing should be read from stdin. This can be set
95 * on the command line.
97 int stdin_null_flag = 0;
100 * Flag indicating that ssh should fork after authentication. This is useful
101 * so that the passphrase can be entered manually, and then ssh goes to the
104 int fork_after_authentication_flag = 0;
107 * General data structure for command line options and options configurable
108 * in configuration files. See readconf.h.
112 /* optional user configfile */
116 * Name of the host we are connecting to. This is the name given on the
117 * command line, or the HostName specified for the user-supplied name in a
118 * configuration file.
122 /* socket address the host resolves to */
123 struct sockaddr_storage hostaddr;
125 /* Private host keys. */
126 Sensitive sensitive_data;
128 /* Original real UID. */
129 uid_t original_real_uid;
130 uid_t original_effective_uid;
132 /* command to be executed */
135 /* Should we execute a command or invoke a subsystem? */
136 int subsystem_flag = 0;
138 /* # of replies received for global requests */
139 static int client_global_request_id = 0;
141 /* pid of proxycommand child process */
142 pid_t proxy_command_pid = 0;
144 /* fd to control socket */
147 /* Only used in control client mode */
148 volatile sig_atomic_t control_client_terminate = 0;
149 u_int control_server_pid = 0;
151 /* Prints a help message to the user. This function never returns. */
157 "usage: ssh [-1246AaCfghkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
158 " [-D port] [-e escape_char] [-F configfile] [-i identity_file]\n"
159 " [-L port:host:hostport] [-l login_name] [-m mac_spec] [-o option]\n"
160 " [-p port] [-R port:host:hostport] [-S ctl] [user@]hostname [command]\n"
165 static int ssh_session(void);
166 static int ssh_session2(void);
167 static void load_public_identity_files(void);
168 static void control_client(const char *path);
171 * Main program for the ssh client.
174 main(int ac, char **av)
176 int i, opt, exit_status;
177 u_short fwd_port, fwd_host_port;
178 char sfwd_port[6], sfwd_host_port[6];
179 char *p, *cp, *line, buf[256];
183 extern int optind, optreset;
186 __progname = ssh_get_progname(av[0]);
190 * Save the original real uid. It will be needed later (uid-swapping
191 * may clobber the real uid).
193 original_real_uid = getuid();
194 original_effective_uid = geteuid();
197 * Use uid-swapping to give up root privileges for the duration of
198 * option processing. We will re-instantiate the rights when we are
199 * ready to create the privileged port, and will permanently drop
200 * them when the port has been created (actually, when the connection
201 * has been made, as we may need to create the port several times).
205 #ifdef HAVE_SETRLIMIT
206 /* If we are installed setuid root be careful to not drop core. */
207 if (original_real_uid != original_effective_uid) {
209 rlim.rlim_cur = rlim.rlim_max = 0;
210 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
211 fatal("setrlimit failed: %.100s", strerror(errno));
215 pw = getpwuid(original_real_uid);
217 logit("You don't exist, go away!");
220 /* Take a copy of the returned structure. */
224 * Set our umask to something reasonable, as some files are created
225 * with the default umask. This will make them world-readable but
226 * writable only by the owner, which is ok for all files for which we
227 * don't set the modes explicitly.
231 /* Initialize option structure to indicate that no values have been set. */
232 initialize_options(&options);
234 /* Parse command-line arguments. */
238 while ((opt = getopt(ac, av,
239 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNPR:S:TVXY")) != -1) {
242 options.protocol = SSH_PROTO_1;
245 options.protocol = SSH_PROTO_2;
248 options.address_family = AF_INET;
251 options.address_family = AF_INET6;
257 fork_after_authentication_flag = 1;
261 options.forward_x11 = 0;
264 options.forward_x11 = 1;
267 options.forward_x11 = 1;
268 options.forward_x11_trusted = 1;
271 options.gateway_ports = 1;
273 case 'P': /* deprecated */
274 options.use_privileged_port = 0;
277 options.forward_agent = 0;
280 options.forward_agent = 1;
283 options.gss_deleg_creds = 0;
286 if (stat(optarg, &st) < 0) {
287 fprintf(stderr, "Warning: Identity file %s "
288 "does not exist.\n", optarg);
291 if (options.num_identity_files >=
292 SSH_MAX_IDENTITY_FILES)
293 fatal("Too many identity files specified "
294 "(max %d)", SSH_MAX_IDENTITY_FILES);
295 options.identity_files[options.num_identity_files++] =
300 options.smartcard_device = xstrdup(optarg);
302 fprintf(stderr, "no support for smartcards.\n");
311 if (debug_flag == 0) {
313 options.log_level = SYSLOG_LEVEL_DEBUG1;
315 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
321 fprintf(stderr, "%s, %s\n",
322 SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
327 options.log_level = SYSLOG_LEVEL_QUIET;
330 if (optarg[0] == '^' && optarg[2] == 0 &&
331 (u_char) optarg[1] >= 64 &&
332 (u_char) optarg[1] < 128)
333 options.escape_char = (u_char) optarg[1] & 31;
334 else if (strlen(optarg) == 1)
335 options.escape_char = (u_char) optarg[0];
336 else if (strcmp(optarg, "none") == 0)
337 options.escape_char = SSH_ESCAPECHAR_NONE;
339 fprintf(stderr, "Bad escape character '%s'.\n",
345 if (ciphers_valid(optarg)) {
347 options.ciphers = xstrdup(optarg);
348 options.cipher = SSH_CIPHER_INVALID;
351 options.cipher = cipher_number(optarg);
352 if (options.cipher == -1) {
354 "Unknown cipher type '%s'\n",
358 if (options.cipher == SSH_CIPHER_3DES)
359 options.ciphers = "3des-cbc";
360 else if (options.cipher == SSH_CIPHER_BLOWFISH)
361 options.ciphers = "blowfish-cbc";
363 options.ciphers = (char *)-1;
367 if (mac_valid(optarg))
368 options.macs = xstrdup(optarg);
370 fprintf(stderr, "Unknown mac type '%s'\n",
376 options.control_master =
377 (options.control_master >= 1) ? 2 : 1;
380 options.port = a2port(optarg);
381 if (options.port == 0) {
382 fprintf(stderr, "Bad port '%s'\n", optarg);
387 options.user = optarg;
392 if (sscanf(optarg, "%5[0123456789]:%255[^:]:%5[0123456789]",
393 sfwd_port, buf, sfwd_host_port) != 3 &&
394 sscanf(optarg, "%5[0123456789]/%255[^/]/%5[0123456789]",
395 sfwd_port, buf, sfwd_host_port) != 3) {
397 "Bad forwarding specification '%s'\n",
402 if ((fwd_port = a2port(sfwd_port)) == 0 ||
403 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
405 "Bad forwarding port(s) '%s'\n", optarg);
409 add_local_forward(&options, fwd_port, buf,
412 add_remote_forward(&options, fwd_port, buf,
417 fwd_port = a2port(optarg);
419 fprintf(stderr, "Bad dynamic port '%s'\n",
423 add_local_forward(&options, fwd_port, "socks", 0);
427 options.compression = 1;
438 line = xstrdup(optarg);
439 if (process_config_line(&options, host ? host : "",
440 line, "command-line", 0, &dummy) != 0)
448 if (options.control_path != NULL)
449 free(options.control_path);
450 options.control_path = xstrdup(optarg);
453 options.bind_address = optarg;
466 if (ac > 0 && !host && **av != '-') {
467 if (strrchr(*av, '@')) {
469 cp = strrchr(p, '@');
470 if (cp == NULL || cp == p)
478 optind = optreset = 1;
484 /* Check that we got a host name. */
488 SSLeay_add_all_algorithms();
489 ERR_load_crypto_strings();
491 /* Initialize the command to execute on remote host. */
492 buffer_init(&command);
495 * Save the command to execute on the remote host in a buffer. There
496 * is no limit on the length of the command, except by the maximum
497 * packet size. Also sets the tty flag if there is no command.
500 /* No command specified - execute shell on a tty. */
502 if (subsystem_flag) {
504 "You must specify a subsystem to invoke.\n");
508 /* A command has been specified. Store it into the buffer. */
509 for (i = 0; i < ac; i++) {
511 buffer_append(&command, " ", 1);
512 buffer_append(&command, av[i], strlen(av[i]));
516 /* Cannot fork to background if no command. */
517 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
518 fatal("Cannot fork into background without a command to execute.");
520 /* Allocate a tty by default if no command specified. */
521 if (buffer_len(&command) == 0)
527 /* Do not allocate a tty if stdin is not a tty. */
528 if (!isatty(fileno(stdin)) && !force_tty_flag) {
530 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
535 * Initialize "log" output. Since we are the client all output
536 * actually goes to stderr.
538 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
539 SYSLOG_FACILITY_USER, 1);
542 * Read per-user configuration file. Ignore the system wide config
543 * file if the user specifies a config file on the command line.
545 if (config != NULL) {
546 if (!read_config_file(config, host, &options, 0))
547 fatal("Can't open user config file %.100s: "
548 "%.100s", config, strerror(errno));
550 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
551 _PATH_SSH_USER_CONFFILE);
552 (void)read_config_file(buf, host, &options, 1);
554 /* Read systemwide configuration file after use config. */
555 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
559 /* Fill configuration defaults. */
560 fill_default_options(&options);
562 channel_set_af(options.address_family);
565 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
569 if (options.user == NULL)
570 options.user = xstrdup(pw->pw_name);
572 if (options.hostname != NULL)
573 host = options.hostname;
575 /* force lowercase for hostkey matching */
576 if (options.host_key_alias != NULL) {
577 for (p = options.host_key_alias; *p; p++)
582 if (options.proxy_command != NULL &&
583 strcmp(options.proxy_command, "none") == 0)
584 options.proxy_command = NULL;
586 if (options.control_path != NULL) {
587 options.control_path = tilde_expand_filename(
588 options.control_path, original_real_uid);
590 if (options.control_path != NULL && options.control_master == 0)
591 control_client(options.control_path); /* This doesn't return */
593 /* Open a connection to the remote host. */
594 if (ssh_connect(host, &hostaddr, options.port,
595 options.address_family, options.connection_attempts,
597 options.use_privileged_port,
599 original_effective_uid == 0 && options.use_privileged_port,
601 options.proxy_command) != 0)
605 * If we successfully made the connection, load the host private key
606 * in case we will need it later for combined rsa-rhosts
607 * authentication. This must be done before releasing extra
608 * privileges, because the file is only readable by root.
609 * If we cannot access the private keys, load the public keys
610 * instead and try to execute the ssh-keysign helper instead.
612 sensitive_data.nkeys = 0;
613 sensitive_data.keys = NULL;
614 sensitive_data.external_keysign = 0;
615 if (options.rhosts_rsa_authentication ||
616 options.hostbased_authentication) {
617 sensitive_data.nkeys = 3;
618 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
622 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
623 _PATH_HOST_KEY_FILE, "", NULL);
624 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
625 _PATH_HOST_DSA_KEY_FILE, "", NULL);
626 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
627 _PATH_HOST_RSA_KEY_FILE, "", NULL);
630 if (options.hostbased_authentication == 1 &&
631 sensitive_data.keys[0] == NULL &&
632 sensitive_data.keys[1] == NULL &&
633 sensitive_data.keys[2] == NULL) {
634 sensitive_data.keys[1] = key_load_public(
635 _PATH_HOST_DSA_KEY_FILE, NULL);
636 sensitive_data.keys[2] = key_load_public(
637 _PATH_HOST_RSA_KEY_FILE, NULL);
638 sensitive_data.external_keysign = 1;
642 * Get rid of any extra privileges that we may have. We will no
643 * longer need them. Also, extra privileges could make it very hard
644 * to read identity files and other non-world-readable files from the
645 * user's home directory if it happens to be on a NFS volume where
646 * root is mapped to nobody.
648 if (original_effective_uid == 0) {
650 permanently_set_uid(pw);
654 * Now that we are back to our own permissions, create ~/.ssh
655 * directory if it doesn\'t already exist.
657 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
658 if (stat(buf, &st) < 0)
659 if (mkdir(buf, 0700) < 0)
660 error("Could not create directory '%.200s'.", buf);
662 /* load options.identity_files */
663 load_public_identity_files();
665 /* Expand ~ in known host file names. */
667 options.system_hostfile =
668 tilde_expand_filename(options.system_hostfile, original_real_uid);
669 options.user_hostfile =
670 tilde_expand_filename(options.user_hostfile, original_real_uid);
671 options.system_hostfile2 =
672 tilde_expand_filename(options.system_hostfile2, original_real_uid);
673 options.user_hostfile2 =
674 tilde_expand_filename(options.user_hostfile2, original_real_uid);
676 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
678 /* Log into the remote system. This never returns if the login fails. */
679 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
681 /* We no longer need the private host keys. Clear them now. */
682 if (sensitive_data.nkeys != 0) {
683 for (i = 0; i < sensitive_data.nkeys; i++) {
684 if (sensitive_data.keys[i] != NULL) {
685 /* Destroys contents safely */
686 debug3("clear hostkey %d", i);
687 key_free(sensitive_data.keys[i]);
688 sensitive_data.keys[i] = NULL;
691 xfree(sensitive_data.keys);
693 for (i = 0; i < options.num_identity_files; i++) {
694 if (options.identity_files[i]) {
695 xfree(options.identity_files[i]);
696 options.identity_files[i] = NULL;
698 if (options.identity_keys[i]) {
699 key_free(options.identity_keys[i]);
700 options.identity_keys[i] = NULL;
704 exit_status = compat20 ? ssh_session2() : ssh_session();
707 if (options.control_path != NULL && control_fd != -1)
708 unlink(options.control_path);
711 * Send SIGHUP to proxy command if used. We don't wait() in
712 * case it hangs and instead rely on init to reap the child
714 if (proxy_command_pid > 1)
715 kill(proxy_command_pid, SIGHUP);
720 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
723 x11_get_proto(char **_proto, char **_data)
728 static char proto[512], data[512];
730 int got_data = 0, generated = 0, do_unlink = 0, i;
731 char *display, *xauthdir, *xauthfile;
734 xauthdir = xauthfile = NULL;
737 proto[0] = data[0] = '\0';
739 if (!options.xauth_location ||
740 (stat(options.xauth_location, &st) == -1)) {
741 debug("No xauth program.");
743 if ((display = getenv("DISPLAY")) == NULL) {
744 debug("x11_get_proto: DISPLAY not set");
748 * Handle FamilyLocal case where $DISPLAY does
749 * not match an authorization entry. For this we
750 * just try "xauth list unix:displaynum.screennum".
751 * XXX: "localhost" match to determine FamilyLocal
754 if (strncmp(display, "localhost:", 10) == 0) {
755 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
759 if (options.forward_x11_trusted == 0) {
760 xauthdir = xmalloc(MAXPATHLEN);
761 xauthfile = xmalloc(MAXPATHLEN);
762 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
763 if (mkdtemp(xauthdir) != NULL) {
765 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
767 snprintf(cmd, sizeof(cmd),
768 "%s -f %s generate %s " SSH_X11_PROTO
769 " untrusted timeout 1200 2>" _PATH_DEVNULL,
770 options.xauth_location, xauthfile, display);
771 debug2("x11_get_proto: %s", cmd);
772 if (system(cmd) == 0)
776 snprintf(cmd, sizeof(cmd),
777 "%s %s%s list %s . 2>" _PATH_DEVNULL,
778 options.xauth_location,
779 generated ? "-f " : "" ,
780 generated ? xauthfile : "",
782 debug2("x11_get_proto: %s", cmd);
784 if (f && fgets(line, sizeof(line), f) &&
785 sscanf(line, "%*s %511s %511s", proto, data) == 2)
801 * If we didn't get authentication data, just make up some
802 * data. The forwarding code will check the validity of the
803 * response anyway, and substitute this data. The X11
804 * server, however, will ignore this fake data and use
805 * whatever authentication mechanisms it was using otherwise
806 * for the local connection.
811 logit("Warning: No xauth data; "
812 "using fake authentication data for X11 forwarding.");
813 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
814 for (i = 0; i < 16; i++) {
817 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
825 ssh_init_forwarding(void)
830 /* Initiate local TCP/IP port forwardings. */
831 for (i = 0; i < options.num_local_forwards; i++) {
832 debug("Connections to local port %d forwarded to remote address %.200s:%d",
833 options.local_forwards[i].port,
834 options.local_forwards[i].host,
835 options.local_forwards[i].host_port);
836 success += channel_setup_local_fwd_listener(
837 options.local_forwards[i].port,
838 options.local_forwards[i].host,
839 options.local_forwards[i].host_port,
840 options.gateway_ports);
842 if (i > 0 && success == 0)
843 error("Could not request local forwarding.");
845 /* Initiate remote TCP/IP port forwardings. */
846 for (i = 0; i < options.num_remote_forwards; i++) {
847 debug("Connections to remote port %d forwarded to local address %.200s:%d",
848 options.remote_forwards[i].port,
849 options.remote_forwards[i].host,
850 options.remote_forwards[i].host_port);
851 channel_request_remote_forwarding(
852 options.remote_forwards[i].port,
853 options.remote_forwards[i].host,
854 options.remote_forwards[i].host_port);
859 check_agent_present(void)
861 if (options.forward_agent) {
862 /* Clear agent forwarding if we don\'t have an agent. */
863 if (!ssh_agent_present())
864 options.forward_agent = 0;
877 /* Enable compression if requested. */
878 if (options.compression) {
879 debug("Requesting compression at level %d.", options.compression_level);
881 if (options.compression_level < 1 || options.compression_level > 9)
882 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
884 /* Send the request. */
885 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
886 packet_put_int(options.compression_level);
889 type = packet_read();
890 if (type == SSH_SMSG_SUCCESS)
891 packet_start_compression(options.compression_level);
892 else if (type == SSH_SMSG_FAILURE)
893 logit("Warning: Remote host refused compression.");
895 packet_disconnect("Protocol error waiting for compression response.");
897 /* Allocate a pseudo tty if appropriate. */
899 debug("Requesting pty.");
901 /* Start the packet. */
902 packet_start(SSH_CMSG_REQUEST_PTY);
904 /* Store TERM in the packet. There is no limit on the
905 length of the string. */
909 packet_put_cstring(cp);
911 /* Store window size in the packet. */
912 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
913 memset(&ws, 0, sizeof(ws));
914 packet_put_int(ws.ws_row);
915 packet_put_int(ws.ws_col);
916 packet_put_int(ws.ws_xpixel);
917 packet_put_int(ws.ws_ypixel);
919 /* Store tty modes in the packet. */
920 tty_make_modes(fileno(stdin), NULL);
922 /* Send the packet, and wait for it to leave. */
926 /* Read response from the server. */
927 type = packet_read();
928 if (type == SSH_SMSG_SUCCESS) {
931 } else if (type == SSH_SMSG_FAILURE)
932 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
934 packet_disconnect("Protocol error waiting for pty request response.");
936 /* Request X11 forwarding if enabled and DISPLAY is set. */
937 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
939 /* Get reasonable local authentication information. */
940 x11_get_proto(&proto, &data);
941 /* Request forwarding with authentication spoofing. */
942 debug("Requesting X11 forwarding with authentication spoofing.");
943 x11_request_forwarding_with_spoofing(0, proto, data);
945 /* Read response from the server. */
946 type = packet_read();
947 if (type == SSH_SMSG_SUCCESS) {
949 } else if (type == SSH_SMSG_FAILURE) {
950 logit("Warning: Remote host denied X11 forwarding.");
952 packet_disconnect("Protocol error waiting for X11 forwarding");
955 /* Tell the packet module whether this is an interactive session. */
956 packet_set_interactive(interactive);
958 /* Request authentication agent forwarding if appropriate. */
959 check_agent_present();
961 if (options.forward_agent) {
962 debug("Requesting authentication agent forwarding.");
963 auth_request_forwarding();
965 /* Read response from the server. */
966 type = packet_read();
968 if (type != SSH_SMSG_SUCCESS)
969 logit("Warning: Remote host denied authentication agent forwarding.");
972 /* Initiate port forwardings. */
973 ssh_init_forwarding();
975 /* If requested, let ssh continue in the background. */
976 if (fork_after_authentication_flag)
977 if (daemon(1, 1) < 0)
978 fatal("daemon() failed: %.200s", strerror(errno));
981 * If a command was specified on the command line, execute the
982 * command now. Otherwise request the server to start a shell.
984 if (buffer_len(&command) > 0) {
985 int len = buffer_len(&command);
988 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
989 packet_start(SSH_CMSG_EXEC_CMD);
990 packet_put_string(buffer_ptr(&command), buffer_len(&command));
994 debug("Requesting shell.");
995 packet_start(SSH_CMSG_EXEC_SHELL);
1000 /* Enter the interactive session. */
1001 return client_loop(have_tty, tty_flag ?
1002 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1006 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1010 id = packet_get_int();
1011 len = buffer_len(&command);
1015 if (type == SSH2_MSG_CHANNEL_FAILURE)
1016 fatal("Request for subsystem '%.*s' failed on channel %d",
1017 len, (u_char *)buffer_ptr(&command), id);
1021 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1025 i = client_global_request_id++;
1026 if (i >= options.num_remote_forwards)
1028 debug("remote forward %s for: listen %d, connect %s:%d",
1029 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1030 options.remote_forwards[i].port,
1031 options.remote_forwards[i].host,
1032 options.remote_forwards[i].host_port);
1033 if (type == SSH2_MSG_REQUEST_FAILURE)
1034 logit("Warning: remote port forwarding failed for listen port %d",
1035 options.remote_forwards[i].port);
1039 ssh_control_listener(void)
1041 struct sockaddr_un addr;
1045 if (options.control_path == NULL || options.control_master <= 0)
1048 memset(&addr, '\0', sizeof(addr));
1049 addr.sun_family = AF_UNIX;
1050 addr_len = offsetof(struct sockaddr_un, sun_path) +
1051 strlen(options.control_path) + 1;
1053 if (strlcpy(addr.sun_path, options.control_path,
1054 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1055 fatal("ControlPath too long");
1057 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1058 fatal("%s socket(): %s\n", __func__, strerror(errno));
1060 old_umask = umask(0177);
1061 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1063 if (errno == EINVAL)
1064 fatal("ControlSocket %s already exists",
1065 options.control_path);
1067 fatal("%s bind(): %s\n", __func__, strerror(errno));
1071 if (listen(control_fd, 64) == -1)
1072 fatal("%s listen(): %s\n", __func__, strerror(errno));
1074 set_nonblock(control_fd);
1077 /* request pty/x11/agent/tcpfwd/shell for channel */
1079 ssh_session2_setup(int id, void *arg)
1081 extern char **environ;
1083 int interactive = tty_flag;
1084 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1086 /* Get reasonable local authentication information. */
1087 x11_get_proto(&proto, &data);
1088 /* Request forwarding with authentication spoofing. */
1089 debug("Requesting X11 forwarding with authentication spoofing.");
1090 x11_request_forwarding_with_spoofing(id, proto, data);
1092 /* XXX wait for reply */
1095 check_agent_present();
1096 if (options.forward_agent) {
1097 debug("Requesting authentication agent forwarding.");
1098 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1102 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1103 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1105 packet_set_interactive(interactive);
1108 /* open new channel for a session */
1110 ssh_session2_open(void)
1113 int window, packetmax, in, out, err;
1115 if (stdin_null_flag) {
1116 in = open(_PATH_DEVNULL, O_RDONLY);
1118 in = dup(STDIN_FILENO);
1120 out = dup(STDOUT_FILENO);
1121 err = dup(STDERR_FILENO);
1123 if (in < 0 || out < 0 || err < 0)
1124 fatal("dup() in/out/err failed");
1126 /* enable nonblocking unless tty */
1134 window = CHAN_SES_WINDOW_DEFAULT;
1135 packetmax = CHAN_SES_PACKET_DEFAULT;
1141 "session", SSH_CHANNEL_OPENING, in, out, err,
1142 window, packetmax, CHAN_EXTENDED_WRITE,
1143 "client-session", /*nonblock*/0);
1145 debug3("ssh_session2_open: channel_new: %d", c->self);
1147 channel_send_open(c->self);
1149 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1159 /* XXX should be pre-session */
1160 ssh_init_forwarding();
1161 ssh_control_listener();
1163 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1164 id = ssh_session2_open();
1166 /* If requested, let ssh continue in the background. */
1167 if (fork_after_authentication_flag)
1168 if (daemon(1, 1) < 0)
1169 fatal("daemon() failed: %.200s", strerror(errno));
1171 return client_loop(tty_flag, tty_flag ?
1172 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1176 load_public_identity_files(void)
1184 if (options.smartcard_device != NULL &&
1185 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1186 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1188 for (i = 0; keys[i] != NULL; i++) {
1190 memmove(&options.identity_files[1], &options.identity_files[0],
1191 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1192 memmove(&options.identity_keys[1], &options.identity_keys[0],
1193 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1194 options.num_identity_files++;
1195 options.identity_keys[0] = keys[i];
1196 options.identity_files[0] = sc_get_key_label(keys[i]);
1198 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1199 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1203 #endif /* SMARTCARD */
1204 for (; i < options.num_identity_files; i++) {
1205 filename = tilde_expand_filename(options.identity_files[i],
1207 public = key_load_public(filename, NULL);
1208 debug("identity file %s type %d", filename,
1209 public ? public->type : -1);
1210 xfree(options.identity_files[i]);
1211 options.identity_files[i] = filename;
1212 options.identity_keys[i] = public;
1217 control_client_sighandler(int signo)
1219 control_client_terminate = signo;
1223 control_client_sigrelay(int signo)
1225 if (control_server_pid > 1)
1226 kill(control_server_pid, signo);
1230 env_permitted(char *env)
1233 char name[1024], *cp;
1235 strlcpy(name, env, sizeof(name));
1236 if ((cp = strchr(name, '=')) == NULL)
1241 for (i = 0; i < options.num_send_env; i++)
1242 if (match_pattern(name, options.send_env[i]))
1249 control_client(const char *path)
1251 struct sockaddr_un addr;
1252 int i, r, sock, exitval, num_env, addr_len;
1255 extern char **environ;
1257 memset(&addr, '\0', sizeof(addr));
1258 addr.sun_family = AF_UNIX;
1259 addr_len = offsetof(struct sockaddr_un, sun_path) +
1262 if (strlcpy(addr.sun_path, path,
1263 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1264 fatal("ControlPath too long");
1266 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1267 fatal("%s socket(): %s", __func__, strerror(errno));
1269 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1)
1270 fatal("Couldn't connect to %s: %s", path, strerror(errno));
1272 if ((cp = getenv("TERM")) == NULL)
1277 /* Get PID of controlee */
1278 if (ssh_msg_recv(sock, &m) == -1)
1279 fatal("%s: msg_recv", __func__);
1280 if (buffer_get_char(&m) != 0)
1281 fatal("%s: wrong version", __func__);
1282 /* Connection allowed? */
1283 if (buffer_get_int(&m) != 1)
1284 fatal("Connection to master denied");
1285 control_server_pid = buffer_get_int(&m);
1288 buffer_put_int(&m, tty_flag);
1289 buffer_put_int(&m, subsystem_flag);
1290 buffer_put_cstring(&m, cp);
1292 buffer_append(&command, "\0", 1);
1293 buffer_put_cstring(&m, buffer_ptr(&command));
1295 if (options.num_send_env == 0 || environ == NULL) {
1296 buffer_put_int(&m, 0);
1298 /* Pass environment */
1300 for (i = 0; environ[i] != NULL; i++)
1301 if (env_permitted(environ[i]))
1302 num_env++; /* Count */
1304 buffer_put_int(&m, num_env);
1306 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1307 if (env_permitted(environ[i])) {
1309 buffer_put_cstring(&m, environ[i]);
1313 if (ssh_msg_send(sock, /* version */0, &m) == -1)
1314 fatal("%s: msg_send", __func__);
1316 mm_send_fd(sock, STDIN_FILENO);
1317 mm_send_fd(sock, STDOUT_FILENO);
1318 mm_send_fd(sock, STDERR_FILENO);
1320 /* Wait for reply, so master has a chance to gather ttymodes */
1322 if (ssh_msg_recv(sock, &m) == -1)
1323 fatal("%s: msg_recv", __func__);
1324 if (buffer_get_char(&m) != 0)
1325 fatal("%s: master returned error", __func__);
1328 signal(SIGINT, control_client_sighandler);
1329 signal(SIGTERM, control_client_sighandler);
1330 signal(SIGWINCH, control_client_sigrelay);
1335 /* Stick around until the controlee closes the client_fd */
1337 for (;!control_client_terminate;) {
1338 r = read(sock, &exitval, sizeof(exitval));
1340 debug2("Received EOF from master");
1344 debug2("Received exit status from master %d", exitval);
1345 if (r == -1 && errno != EINTR)
1346 fatal("%s: read %s", __func__, strerror(errno));
1349 if (control_client_terminate)
1350 debug2("Exiting on signal %d", control_client_terminate);
1356 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1357 fprintf(stderr, "Connection to master closed.\r\n");