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"
79 extern char *__progname;
81 /* Flag indicating whether debug mode is on. This can be set on the command line. */
84 /* Flag indicating whether a tty should be allocated */
87 int force_tty_flag = 0;
89 /* don't exec a shell */
90 int no_shell_flag = 0;
93 * Flag indicating that nothing should be read from stdin. This can be set
94 * on the command line.
96 int stdin_null_flag = 0;
99 * Flag indicating that ssh should fork after authentication. This is useful
100 * so that the passphrase can be entered manually, and then ssh goes to the
103 int fork_after_authentication_flag = 0;
106 * General data structure for command line options and options configurable
107 * in configuration files. See readconf.h.
111 /* optional user configfile */
115 * Name of the host we are connecting to. This is the name given on the
116 * command line, or the HostName specified for the user-supplied name in a
117 * configuration file.
121 /* socket address the host resolves to */
122 struct sockaddr_storage hostaddr;
124 /* Private host keys. */
125 Sensitive sensitive_data;
127 /* Original real UID. */
128 uid_t original_real_uid;
129 uid_t original_effective_uid;
131 /* command to be executed */
134 /* Should we execute a command or invoke a subsystem? */
135 int subsystem_flag = 0;
137 /* # of replies received for global requests */
138 static int client_global_request_id = 0;
140 /* pid of proxycommand child process */
141 pid_t proxy_command_pid = 0;
143 /* fd to control socket */
146 /* Only used in control client mode */
147 volatile sig_atomic_t control_client_terminate = 0;
148 u_int control_server_pid = 0;
150 /* Prints a help message to the user. This function never returns. */
156 "usage: ssh [-1246AaCfghkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
157 " [-D port] [-e escape_char] [-F configfile] [-i identity_file]\n"
158 " [-L port:host:hostport] [-l login_name] [-m mac_spec] [-o option]\n"
159 " [-p port] [-R port:host:hostport] [-S ctl] [user@]hostname [command]\n"
164 static int ssh_session(void);
165 static int ssh_session2(void);
166 static void load_public_identity_files(void);
167 static void control_client(const char *path);
170 * Main program for the ssh client.
173 main(int ac, char **av)
175 int i, opt, exit_status;
176 u_short fwd_port, fwd_host_port;
177 char sfwd_port[6], sfwd_host_port[6];
178 char *p, *cp, *line, buf[256];
182 extern int optind, optreset;
185 __progname = ssh_get_progname(av[0]);
189 * Save the original real uid. It will be needed later (uid-swapping
190 * may clobber the real uid).
192 original_real_uid = getuid();
193 original_effective_uid = geteuid();
196 * Use uid-swapping to give up root privileges for the duration of
197 * option processing. We will re-instantiate the rights when we are
198 * ready to create the privileged port, and will permanently drop
199 * them when the port has been created (actually, when the connection
200 * has been made, as we may need to create the port several times).
204 #ifdef HAVE_SETRLIMIT
205 /* If we are installed setuid root be careful to not drop core. */
206 if (original_real_uid != original_effective_uid) {
208 rlim.rlim_cur = rlim.rlim_max = 0;
209 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
210 fatal("setrlimit failed: %.100s", strerror(errno));
214 pw = getpwuid(original_real_uid);
216 logit("You don't exist, go away!");
219 /* Take a copy of the returned structure. */
223 * Set our umask to something reasonable, as some files are created
224 * with the default umask. This will make them world-readable but
225 * writable only by the owner, which is ok for all files for which we
226 * don't set the modes explicitly.
230 /* Initialize option structure to indicate that no values have been set. */
231 initialize_options(&options);
233 /* Parse command-line arguments. */
237 while ((opt = getopt(ac, av,
238 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNPR:S:TVXY")) != -1) {
241 options.protocol = SSH_PROTO_1;
244 options.protocol = SSH_PROTO_2;
247 options.address_family = AF_INET;
250 options.address_family = AF_INET6;
256 fork_after_authentication_flag = 1;
260 options.forward_x11 = 0;
263 options.forward_x11 = 1;
266 options.forward_x11 = 1;
267 options.forward_x11_trusted = 1;
270 options.gateway_ports = 1;
272 case 'P': /* deprecated */
273 options.use_privileged_port = 0;
276 options.forward_agent = 0;
279 options.forward_agent = 1;
282 options.gss_deleg_creds = 0;
285 if (stat(optarg, &st) < 0) {
286 fprintf(stderr, "Warning: Identity file %s "
287 "does not exist.\n", optarg);
290 if (options.num_identity_files >=
291 SSH_MAX_IDENTITY_FILES)
292 fatal("Too many identity files specified "
293 "(max %d)", SSH_MAX_IDENTITY_FILES);
294 options.identity_files[options.num_identity_files++] =
299 options.smartcard_device = xstrdup(optarg);
301 fprintf(stderr, "no support for smartcards.\n");
310 if (debug_flag == 0) {
312 options.log_level = SYSLOG_LEVEL_DEBUG1;
314 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
320 fprintf(stderr, "%s, %s\n",
321 SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
326 options.log_level = SYSLOG_LEVEL_QUIET;
329 if (optarg[0] == '^' && optarg[2] == 0 &&
330 (u_char) optarg[1] >= 64 &&
331 (u_char) optarg[1] < 128)
332 options.escape_char = (u_char) optarg[1] & 31;
333 else if (strlen(optarg) == 1)
334 options.escape_char = (u_char) optarg[0];
335 else if (strcmp(optarg, "none") == 0)
336 options.escape_char = SSH_ESCAPECHAR_NONE;
338 fprintf(stderr, "Bad escape character '%s'.\n",
344 if (ciphers_valid(optarg)) {
346 options.ciphers = xstrdup(optarg);
347 options.cipher = SSH_CIPHER_INVALID;
350 options.cipher = cipher_number(optarg);
351 if (options.cipher == -1) {
353 "Unknown cipher type '%s'\n",
357 if (options.cipher == SSH_CIPHER_3DES)
358 options.ciphers = "3des-cbc";
359 else if (options.cipher == SSH_CIPHER_BLOWFISH)
360 options.ciphers = "blowfish-cbc";
362 options.ciphers = (char *)-1;
366 if (mac_valid(optarg))
367 options.macs = xstrdup(optarg);
369 fprintf(stderr, "Unknown mac type '%s'\n",
375 options.control_master =
376 (options.control_master >= 1) ? 2 : 1;
379 options.port = a2port(optarg);
380 if (options.port == 0) {
381 fprintf(stderr, "Bad port '%s'\n", optarg);
386 options.user = optarg;
391 if (sscanf(optarg, "%5[0123456789]:%255[^:]:%5[0123456789]",
392 sfwd_port, buf, sfwd_host_port) != 3 &&
393 sscanf(optarg, "%5[0123456789]/%255[^/]/%5[0123456789]",
394 sfwd_port, buf, sfwd_host_port) != 3) {
396 "Bad forwarding specification '%s'\n",
401 if ((fwd_port = a2port(sfwd_port)) == 0 ||
402 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
404 "Bad forwarding port(s) '%s'\n", optarg);
408 add_local_forward(&options, fwd_port, buf,
411 add_remote_forward(&options, fwd_port, buf,
416 fwd_port = a2port(optarg);
418 fprintf(stderr, "Bad dynamic port '%s'\n",
422 add_local_forward(&options, fwd_port, "socks", 0);
426 options.compression = 1;
437 line = xstrdup(optarg);
438 if (process_config_line(&options, host ? host : "",
439 line, "command-line", 0, &dummy) != 0)
447 if (options.control_path != NULL)
448 free(options.control_path);
449 options.control_path = xstrdup(optarg);
452 options.bind_address = optarg;
465 if (ac > 0 && !host && **av != '-') {
466 if (strrchr(*av, '@')) {
468 cp = strrchr(p, '@');
469 if (cp == NULL || cp == p)
477 optind = optreset = 1;
483 /* Check that we got a host name. */
487 SSLeay_add_all_algorithms();
488 ERR_load_crypto_strings();
490 /* Initialize the command to execute on remote host. */
491 buffer_init(&command);
494 * Save the command to execute on the remote host in a buffer. There
495 * is no limit on the length of the command, except by the maximum
496 * packet size. Also sets the tty flag if there is no command.
499 /* No command specified - execute shell on a tty. */
501 if (subsystem_flag) {
503 "You must specify a subsystem to invoke.\n");
507 /* A command has been specified. Store it into the buffer. */
508 for (i = 0; i < ac; i++) {
510 buffer_append(&command, " ", 1);
511 buffer_append(&command, av[i], strlen(av[i]));
515 /* Cannot fork to background if no command. */
516 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
517 fatal("Cannot fork into background without a command to execute.");
519 /* Allocate a tty by default if no command specified. */
520 if (buffer_len(&command) == 0)
526 /* Do not allocate a tty if stdin is not a tty. */
527 if (!isatty(fileno(stdin)) && !force_tty_flag) {
529 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
534 * Initialize "log" output. Since we are the client all output
535 * actually goes to stderr.
537 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
538 SYSLOG_FACILITY_USER, 1);
541 * Read per-user configuration file. Ignore the system wide config
542 * file if the user specifies a config file on the command line.
544 if (config != NULL) {
545 if (!read_config_file(config, host, &options, 0))
546 fatal("Can't open user config file %.100s: "
547 "%.100s", config, strerror(errno));
549 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
550 _PATH_SSH_USER_CONFFILE);
551 (void)read_config_file(buf, host, &options, 1);
553 /* Read systemwide configuration file after use config. */
554 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
558 /* Fill configuration defaults. */
559 fill_default_options(&options);
561 channel_set_af(options.address_family);
564 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
568 if (options.user == NULL)
569 options.user = xstrdup(pw->pw_name);
571 if (options.hostname != NULL)
572 host = options.hostname;
574 /* force lowercase for hostkey matching */
575 if (options.host_key_alias != NULL) {
576 for (p = options.host_key_alias; *p; p++)
581 if (options.proxy_command != NULL &&
582 strcmp(options.proxy_command, "none") == 0)
583 options.proxy_command = NULL;
585 if (options.control_path != NULL) {
586 options.control_path = tilde_expand_filename(
587 options.control_path, original_real_uid);
589 if (options.control_path != NULL && options.control_master == 0)
590 control_client(options.control_path); /* This doesn't return */
592 /* Open a connection to the remote host. */
593 if (ssh_connect(host, &hostaddr, options.port,
594 options.address_family, options.connection_attempts,
596 options.use_privileged_port,
598 original_effective_uid == 0 && options.use_privileged_port,
600 options.proxy_command) != 0)
604 * If we successfully made the connection, load the host private key
605 * in case we will need it later for combined rsa-rhosts
606 * authentication. This must be done before releasing extra
607 * privileges, because the file is only readable by root.
608 * If we cannot access the private keys, load the public keys
609 * instead and try to execute the ssh-keysign helper instead.
611 sensitive_data.nkeys = 0;
612 sensitive_data.keys = NULL;
613 sensitive_data.external_keysign = 0;
614 if (options.rhosts_rsa_authentication ||
615 options.hostbased_authentication) {
616 sensitive_data.nkeys = 3;
617 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
621 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
622 _PATH_HOST_KEY_FILE, "", NULL);
623 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
624 _PATH_HOST_DSA_KEY_FILE, "", NULL);
625 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
626 _PATH_HOST_RSA_KEY_FILE, "", NULL);
629 if (options.hostbased_authentication == 1 &&
630 sensitive_data.keys[0] == NULL &&
631 sensitive_data.keys[1] == NULL &&
632 sensitive_data.keys[2] == NULL) {
633 sensitive_data.keys[1] = key_load_public(
634 _PATH_HOST_DSA_KEY_FILE, NULL);
635 sensitive_data.keys[2] = key_load_public(
636 _PATH_HOST_RSA_KEY_FILE, NULL);
637 sensitive_data.external_keysign = 1;
641 * Get rid of any extra privileges that we may have. We will no
642 * longer need them. Also, extra privileges could make it very hard
643 * to read identity files and other non-world-readable files from the
644 * user's home directory if it happens to be on a NFS volume where
645 * root is mapped to nobody.
647 seteuid(original_real_uid);
648 setuid(original_real_uid);
651 * Now that we are back to our own permissions, create ~/.ssh
652 * directory if it doesn\'t already exist.
654 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
655 if (stat(buf, &st) < 0)
656 if (mkdir(buf, 0700) < 0)
657 error("Could not create directory '%.200s'.", buf);
659 /* load options.identity_files */
660 load_public_identity_files();
662 /* Expand ~ in known host file names. */
664 options.system_hostfile =
665 tilde_expand_filename(options.system_hostfile, original_real_uid);
666 options.user_hostfile =
667 tilde_expand_filename(options.user_hostfile, original_real_uid);
668 options.system_hostfile2 =
669 tilde_expand_filename(options.system_hostfile2, original_real_uid);
670 options.user_hostfile2 =
671 tilde_expand_filename(options.user_hostfile2, original_real_uid);
673 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
675 /* Log into the remote system. This never returns if the login fails. */
676 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
678 /* We no longer need the private host keys. Clear them now. */
679 if (sensitive_data.nkeys != 0) {
680 for (i = 0; i < sensitive_data.nkeys; i++) {
681 if (sensitive_data.keys[i] != NULL) {
682 /* Destroys contents safely */
683 debug3("clear hostkey %d", i);
684 key_free(sensitive_data.keys[i]);
685 sensitive_data.keys[i] = NULL;
688 xfree(sensitive_data.keys);
690 for (i = 0; i < options.num_identity_files; i++) {
691 if (options.identity_files[i]) {
692 xfree(options.identity_files[i]);
693 options.identity_files[i] = NULL;
695 if (options.identity_keys[i]) {
696 key_free(options.identity_keys[i]);
697 options.identity_keys[i] = NULL;
701 exit_status = compat20 ? ssh_session2() : ssh_session();
704 if (options.control_path != NULL && control_fd != -1)
705 unlink(options.control_path);
708 * Send SIGHUP to proxy command if used. We don't wait() in
709 * case it hangs and instead rely on init to reap the child
711 if (proxy_command_pid > 1)
712 kill(proxy_command_pid, SIGHUP);
717 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
720 x11_get_proto(char **_proto, char **_data)
725 static char proto[512], data[512];
727 int got_data = 0, generated = 0, do_unlink = 0, i;
728 char *display, *xauthdir, *xauthfile;
731 xauthdir = xauthfile = NULL;
734 proto[0] = data[0] = '\0';
736 if (!options.xauth_location ||
737 (stat(options.xauth_location, &st) == -1)) {
738 debug("No xauth program.");
740 if ((display = getenv("DISPLAY")) == NULL) {
741 debug("x11_get_proto: DISPLAY not set");
745 * Handle FamilyLocal case where $DISPLAY does
746 * not match an authorization entry. For this we
747 * just try "xauth list unix:displaynum.screennum".
748 * XXX: "localhost" match to determine FamilyLocal
751 if (strncmp(display, "localhost:", 10) == 0) {
752 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
756 if (options.forward_x11_trusted == 0) {
757 xauthdir = xmalloc(MAXPATHLEN);
758 xauthfile = xmalloc(MAXPATHLEN);
759 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
760 if (mkdtemp(xauthdir) != NULL) {
762 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
764 snprintf(cmd, sizeof(cmd),
765 "%s -f %s generate %s " SSH_X11_PROTO
766 " untrusted timeout 1200 2>" _PATH_DEVNULL,
767 options.xauth_location, xauthfile, display);
768 debug2("x11_get_proto: %s", cmd);
769 if (system(cmd) == 0)
773 snprintf(cmd, sizeof(cmd),
774 "%s %s%s list %s . 2>" _PATH_DEVNULL,
775 options.xauth_location,
776 generated ? "-f " : "" ,
777 generated ? xauthfile : "",
779 debug2("x11_get_proto: %s", cmd);
781 if (f && fgets(line, sizeof(line), f) &&
782 sscanf(line, "%*s %511s %511s", proto, data) == 2)
798 * If we didn't get authentication data, just make up some
799 * data. The forwarding code will check the validity of the
800 * response anyway, and substitute this data. The X11
801 * server, however, will ignore this fake data and use
802 * whatever authentication mechanisms it was using otherwise
803 * for the local connection.
808 logit("Warning: No xauth data; "
809 "using fake authentication data for X11 forwarding.");
810 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
811 for (i = 0; i < 16; i++) {
814 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
822 ssh_init_forwarding(void)
827 /* Initiate local TCP/IP port forwardings. */
828 for (i = 0; i < options.num_local_forwards; i++) {
829 debug("Connections to local port %d forwarded to remote address %.200s:%d",
830 options.local_forwards[i].port,
831 options.local_forwards[i].host,
832 options.local_forwards[i].host_port);
833 success += channel_setup_local_fwd_listener(
834 options.local_forwards[i].port,
835 options.local_forwards[i].host,
836 options.local_forwards[i].host_port,
837 options.gateway_ports);
839 if (i > 0 && success == 0)
840 error("Could not request local forwarding.");
842 /* Initiate remote TCP/IP port forwardings. */
843 for (i = 0; i < options.num_remote_forwards; i++) {
844 debug("Connections to remote port %d forwarded to local address %.200s:%d",
845 options.remote_forwards[i].port,
846 options.remote_forwards[i].host,
847 options.remote_forwards[i].host_port);
848 channel_request_remote_forwarding(
849 options.remote_forwards[i].port,
850 options.remote_forwards[i].host,
851 options.remote_forwards[i].host_port);
856 check_agent_present(void)
858 if (options.forward_agent) {
859 /* Clear agent forwarding if we don\'t have an agent. */
860 if (!ssh_agent_present())
861 options.forward_agent = 0;
874 /* Enable compression if requested. */
875 if (options.compression) {
876 debug("Requesting compression at level %d.", options.compression_level);
878 if (options.compression_level < 1 || options.compression_level > 9)
879 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
881 /* Send the request. */
882 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
883 packet_put_int(options.compression_level);
886 type = packet_read();
887 if (type == SSH_SMSG_SUCCESS)
888 packet_start_compression(options.compression_level);
889 else if (type == SSH_SMSG_FAILURE)
890 logit("Warning: Remote host refused compression.");
892 packet_disconnect("Protocol error waiting for compression response.");
894 /* Allocate a pseudo tty if appropriate. */
896 debug("Requesting pty.");
898 /* Start the packet. */
899 packet_start(SSH_CMSG_REQUEST_PTY);
901 /* Store TERM in the packet. There is no limit on the
902 length of the string. */
906 packet_put_cstring(cp);
908 /* Store window size in the packet. */
909 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
910 memset(&ws, 0, sizeof(ws));
911 packet_put_int(ws.ws_row);
912 packet_put_int(ws.ws_col);
913 packet_put_int(ws.ws_xpixel);
914 packet_put_int(ws.ws_ypixel);
916 /* Store tty modes in the packet. */
917 tty_make_modes(fileno(stdin), NULL);
919 /* Send the packet, and wait for it to leave. */
923 /* Read response from the server. */
924 type = packet_read();
925 if (type == SSH_SMSG_SUCCESS) {
928 } else if (type == SSH_SMSG_FAILURE)
929 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
931 packet_disconnect("Protocol error waiting for pty request response.");
933 /* Request X11 forwarding if enabled and DISPLAY is set. */
934 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
936 /* Get reasonable local authentication information. */
937 x11_get_proto(&proto, &data);
938 /* Request forwarding with authentication spoofing. */
939 debug("Requesting X11 forwarding with authentication spoofing.");
940 x11_request_forwarding_with_spoofing(0, proto, data);
942 /* Read response from the server. */
943 type = packet_read();
944 if (type == SSH_SMSG_SUCCESS) {
946 } else if (type == SSH_SMSG_FAILURE) {
947 logit("Warning: Remote host denied X11 forwarding.");
949 packet_disconnect("Protocol error waiting for X11 forwarding");
952 /* Tell the packet module whether this is an interactive session. */
953 packet_set_interactive(interactive);
955 /* Request authentication agent forwarding if appropriate. */
956 check_agent_present();
958 if (options.forward_agent) {
959 debug("Requesting authentication agent forwarding.");
960 auth_request_forwarding();
962 /* Read response from the server. */
963 type = packet_read();
965 if (type != SSH_SMSG_SUCCESS)
966 logit("Warning: Remote host denied authentication agent forwarding.");
969 /* Initiate port forwardings. */
970 ssh_init_forwarding();
972 /* If requested, let ssh continue in the background. */
973 if (fork_after_authentication_flag)
974 if (daemon(1, 1) < 0)
975 fatal("daemon() failed: %.200s", strerror(errno));
978 * If a command was specified on the command line, execute the
979 * command now. Otherwise request the server to start a shell.
981 if (buffer_len(&command) > 0) {
982 int len = buffer_len(&command);
985 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
986 packet_start(SSH_CMSG_EXEC_CMD);
987 packet_put_string(buffer_ptr(&command), buffer_len(&command));
991 debug("Requesting shell.");
992 packet_start(SSH_CMSG_EXEC_SHELL);
997 /* Enter the interactive session. */
998 return client_loop(have_tty, tty_flag ?
999 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1003 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1007 id = packet_get_int();
1008 len = buffer_len(&command);
1012 if (type == SSH2_MSG_CHANNEL_FAILURE)
1013 fatal("Request for subsystem '%.*s' failed on channel %d",
1014 len, (u_char *)buffer_ptr(&command), id);
1018 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1022 i = client_global_request_id++;
1023 if (i >= options.num_remote_forwards)
1025 debug("remote forward %s for: listen %d, connect %s:%d",
1026 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1027 options.remote_forwards[i].port,
1028 options.remote_forwards[i].host,
1029 options.remote_forwards[i].host_port);
1030 if (type == SSH2_MSG_REQUEST_FAILURE)
1031 logit("Warning: remote port forwarding failed for listen port %d",
1032 options.remote_forwards[i].port);
1036 ssh_control_listener(void)
1038 struct sockaddr_un addr;
1042 if (options.control_path == NULL || options.control_master <= 0)
1045 memset(&addr, '\0', sizeof(addr));
1046 addr.sun_family = AF_UNIX;
1047 addr_len = offsetof(struct sockaddr_un, sun_path) +
1048 strlen(options.control_path) + 1;
1050 if (strlcpy(addr.sun_path, options.control_path,
1051 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1052 fatal("ControlPath too long");
1054 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1055 fatal("%s socket(): %s\n", __func__, strerror(errno));
1057 old_umask = umask(0177);
1058 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1060 if (errno == EINVAL)
1061 fatal("ControlSocket %s already exists",
1062 options.control_path);
1064 fatal("%s bind(): %s\n", __func__, strerror(errno));
1068 if (listen(control_fd, 64) == -1)
1069 fatal("%s listen(): %s\n", __func__, strerror(errno));
1071 set_nonblock(control_fd);
1074 /* request pty/x11/agent/tcpfwd/shell for channel */
1076 ssh_session2_setup(int id, void *arg)
1078 extern char **environ;
1080 int interactive = tty_flag;
1081 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1083 /* Get reasonable local authentication information. */
1084 x11_get_proto(&proto, &data);
1085 /* Request forwarding with authentication spoofing. */
1086 debug("Requesting X11 forwarding with authentication spoofing.");
1087 x11_request_forwarding_with_spoofing(id, proto, data);
1089 /* XXX wait for reply */
1092 check_agent_present();
1093 if (options.forward_agent) {
1094 debug("Requesting authentication agent forwarding.");
1095 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1099 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1100 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1102 packet_set_interactive(interactive);
1105 /* open new channel for a session */
1107 ssh_session2_open(void)
1110 int window, packetmax, in, out, err;
1112 if (stdin_null_flag) {
1113 in = open(_PATH_DEVNULL, O_RDONLY);
1115 in = dup(STDIN_FILENO);
1117 out = dup(STDOUT_FILENO);
1118 err = dup(STDERR_FILENO);
1120 if (in < 0 || out < 0 || err < 0)
1121 fatal("dup() in/out/err failed");
1123 /* enable nonblocking unless tty */
1131 window = CHAN_SES_WINDOW_DEFAULT;
1132 packetmax = CHAN_SES_PACKET_DEFAULT;
1138 "session", SSH_CHANNEL_OPENING, in, out, err,
1139 window, packetmax, CHAN_EXTENDED_WRITE,
1140 "client-session", /*nonblock*/0);
1142 debug3("ssh_session2_open: channel_new: %d", c->self);
1144 channel_send_open(c->self);
1146 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1156 /* XXX should be pre-session */
1157 ssh_init_forwarding();
1158 ssh_control_listener();
1160 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1161 id = ssh_session2_open();
1163 /* If requested, let ssh continue in the background. */
1164 if (fork_after_authentication_flag)
1165 if (daemon(1, 1) < 0)
1166 fatal("daemon() failed: %.200s", strerror(errno));
1168 return client_loop(tty_flag, tty_flag ?
1169 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1173 load_public_identity_files(void)
1181 if (options.smartcard_device != NULL &&
1182 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1183 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1185 for (i = 0; keys[i] != NULL; i++) {
1187 memmove(&options.identity_files[1], &options.identity_files[0],
1188 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1189 memmove(&options.identity_keys[1], &options.identity_keys[0],
1190 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1191 options.num_identity_files++;
1192 options.identity_keys[0] = keys[i];
1193 options.identity_files[0] = sc_get_key_label(keys[i]);
1195 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1196 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1200 #endif /* SMARTCARD */
1201 for (; i < options.num_identity_files; i++) {
1202 filename = tilde_expand_filename(options.identity_files[i],
1204 public = key_load_public(filename, NULL);
1205 debug("identity file %s type %d", filename,
1206 public ? public->type : -1);
1207 xfree(options.identity_files[i]);
1208 options.identity_files[i] = filename;
1209 options.identity_keys[i] = public;
1214 control_client_sighandler(int signo)
1216 control_client_terminate = signo;
1220 control_client_sigrelay(int signo)
1222 if (control_server_pid > 1)
1223 kill(control_server_pid, signo);
1227 env_permitted(char *env)
1230 char name[1024], *cp;
1232 strlcpy(name, env, sizeof(name));
1233 if ((cp = strchr(name, '=')) == NULL)
1238 for (i = 0; i < options.num_send_env; i++)
1239 if (match_pattern(name, options.send_env[i]))
1246 control_client(const char *path)
1248 struct sockaddr_un addr;
1249 int i, r, sock, exitval, num_env, addr_len;
1252 extern char **environ;
1254 memset(&addr, '\0', sizeof(addr));
1255 addr.sun_family = AF_UNIX;
1256 addr_len = offsetof(struct sockaddr_un, sun_path) +
1259 if (strlcpy(addr.sun_path, path,
1260 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1261 fatal("ControlPath too long");
1263 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1264 fatal("%s socket(): %s", __func__, strerror(errno));
1266 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1)
1267 fatal("Couldn't connect to %s: %s", path, strerror(errno));
1269 if ((cp = getenv("TERM")) == NULL)
1274 /* Get PID of controlee */
1275 if (ssh_msg_recv(sock, &m) == -1)
1276 fatal("%s: msg_recv", __func__);
1277 if (buffer_get_char(&m) != 0)
1278 fatal("%s: wrong version", __func__);
1279 /* Connection allowed? */
1280 if (buffer_get_int(&m) != 1)
1281 fatal("Connection to master denied");
1282 control_server_pid = buffer_get_int(&m);
1285 buffer_put_int(&m, tty_flag);
1286 buffer_put_int(&m, subsystem_flag);
1287 buffer_put_cstring(&m, cp);
1289 buffer_append(&command, "\0", 1);
1290 buffer_put_cstring(&m, buffer_ptr(&command));
1292 if (options.num_send_env == 0 || environ == NULL) {
1293 buffer_put_int(&m, 0);
1295 /* Pass environment */
1297 for (i = 0; environ[i] != NULL; i++)
1298 if (env_permitted(environ[i]))
1299 num_env++; /* Count */
1301 buffer_put_int(&m, num_env);
1303 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1304 if (env_permitted(environ[i])) {
1306 buffer_put_cstring(&m, environ[i]);
1310 if (ssh_msg_send(sock, /* version */0, &m) == -1)
1311 fatal("%s: msg_send", __func__);
1313 mm_send_fd(sock, STDIN_FILENO);
1314 mm_send_fd(sock, STDOUT_FILENO);
1315 mm_send_fd(sock, STDERR_FILENO);
1317 /* Wait for reply, so master has a chance to gather ttymodes */
1319 if (ssh_msg_recv(sock, &m) == -1)
1320 fatal("%s: msg_recv", __func__);
1321 if (buffer_get_char(&m) != 0)
1322 fatal("%s: master returned error", __func__);
1325 signal(SIGINT, control_client_sighandler);
1326 signal(SIGTERM, control_client_sighandler);
1327 signal(SIGWINCH, control_client_sigrelay);
1332 /* Stick around until the controlee closes the client_fd */
1334 for (;!control_client_terminate;) {
1335 r = read(sock, &exitval, sizeof(exitval));
1337 debug2("Received EOF from master");
1341 debug2("Received exit status from master %d", exitval);
1342 if (r == -1 && errno != EINTR)
1343 fatal("%s: read %s", __func__, strerror(errno));
1346 if (control_client_terminate)
1347 debug2("Exiting on signal %d", control_client_terminate);
1353 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1354 fprintf(stderr, "Connection to master closed.\r\n");