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.214 2004/06/13 15:03:02 djm 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 #ifdef HAVE___PROGNAME
80 extern char *__progname;
85 /* Flag indicating whether debug mode is on. This can be set on the command line. */
88 /* Flag indicating whether a tty should be allocated */
91 int force_tty_flag = 0;
93 /* don't exec a shell */
94 int no_shell_flag = 0;
97 * Flag indicating that nothing should be read from stdin. This can be set
98 * on the command line.
100 int stdin_null_flag = 0;
103 * Flag indicating that ssh should fork after authentication. This is useful
104 * so that the passphrase can be entered manually, and then ssh goes to the
107 int fork_after_authentication_flag = 0;
110 * General data structure for command line options and options configurable
111 * in configuration files. See readconf.h.
115 /* optional user configfile */
119 * Name of the host we are connecting to. This is the name given on the
120 * command line, or the HostName specified for the user-supplied name in a
121 * configuration file.
125 /* socket address the host resolves to */
126 struct sockaddr_storage hostaddr;
128 /* Private host keys. */
129 Sensitive sensitive_data;
131 /* Original real UID. */
132 uid_t original_real_uid;
133 uid_t original_effective_uid;
135 /* command to be executed */
138 /* Should we execute a command or invoke a subsystem? */
139 int subsystem_flag = 0;
141 /* # of replies received for global requests */
142 static int client_global_request_id = 0;
144 /* pid of proxycommand child process */
145 pid_t proxy_command_pid = 0;
147 /* fd to control socket */
150 /* Only used in control client mode */
151 volatile sig_atomic_t control_client_terminate = 0;
152 u_int control_server_pid = 0;
154 /* Prints a help message to the user. This function never returns. */
160 "usage: ssh [-1246AaCfghkNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
161 " [-D port] [-e escape_char] [-F configfile] [-i identity_file]\n"
162 " [-L port:host:hostport] [-l login_name] [-m mac_spec] [-o option]\n"
163 " [-p port] [-R port:host:hostport] [user@]hostname [command]\n"
168 static int ssh_session(void);
169 static int ssh_session2(void);
170 static void load_public_identity_files(void);
171 static void control_client(const char *path);
174 * Main program for the ssh client.
177 main(int ac, char **av)
179 int i, opt, exit_status;
180 u_short fwd_port, fwd_host_port;
181 char sfwd_port[6], sfwd_host_port[6];
182 char *p, *cp, *line, buf[256];
186 extern int optind, optreset;
189 __progname = ssh_get_progname(av[0]);
193 * Save the original real uid. It will be needed later (uid-swapping
194 * may clobber the real uid).
196 original_real_uid = getuid();
197 original_effective_uid = geteuid();
200 * Use uid-swapping to give up root privileges for the duration of
201 * option processing. We will re-instantiate the rights when we are
202 * ready to create the privileged port, and will permanently drop
203 * them when the port has been created (actually, when the connection
204 * has been made, as we may need to create the port several times).
208 #ifdef HAVE_SETRLIMIT
209 /* If we are installed setuid root be careful to not drop core. */
210 if (original_real_uid != original_effective_uid) {
212 rlim.rlim_cur = rlim.rlim_max = 0;
213 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
214 fatal("setrlimit failed: %.100s", strerror(errno));
218 pw = getpwuid(original_real_uid);
220 logit("You don't exist, go away!");
223 /* Take a copy of the returned structure. */
227 * Set our umask to something reasonable, as some files are created
228 * with the default umask. This will make them world-readable but
229 * writable only by the owner, which is ok for all files for which we
230 * don't set the modes explicitly.
234 /* Initialize option structure to indicate that no values have been set. */
235 initialize_options(&options);
237 /* Parse command-line arguments. */
241 while ((opt = getopt(ac, av,
242 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNPR:S:TVXY")) != -1) {
245 options.protocol = SSH_PROTO_1;
248 options.protocol = SSH_PROTO_2;
251 options.address_family = AF_INET;
254 options.address_family = AF_INET6;
260 fork_after_authentication_flag = 1;
264 options.forward_x11 = 0;
267 options.forward_x11 = 1;
270 options.forward_x11 = 1;
271 options.forward_x11_trusted = 1;
274 options.gateway_ports = 1;
276 case 'P': /* deprecated */
277 options.use_privileged_port = 0;
280 options.forward_agent = 0;
283 options.forward_agent = 1;
286 options.gss_deleg_creds = 0;
289 if (stat(optarg, &st) < 0) {
290 fprintf(stderr, "Warning: Identity file %s "
291 "does not exist.\n", optarg);
294 if (options.num_identity_files >=
295 SSH_MAX_IDENTITY_FILES)
296 fatal("Too many identity files specified "
297 "(max %d)", SSH_MAX_IDENTITY_FILES);
298 options.identity_files[options.num_identity_files++] =
303 options.smartcard_device = xstrdup(optarg);
305 fprintf(stderr, "no support for smartcards.\n");
314 if (debug_flag == 0) {
316 options.log_level = SYSLOG_LEVEL_DEBUG1;
318 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
324 fprintf(stderr, "%s, %s\n",
325 SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
330 options.log_level = SYSLOG_LEVEL_QUIET;
333 if (optarg[0] == '^' && optarg[2] == 0 &&
334 (u_char) optarg[1] >= 64 &&
335 (u_char) optarg[1] < 128)
336 options.escape_char = (u_char) optarg[1] & 31;
337 else if (strlen(optarg) == 1)
338 options.escape_char = (u_char) optarg[0];
339 else if (strcmp(optarg, "none") == 0)
340 options.escape_char = SSH_ESCAPECHAR_NONE;
342 fprintf(stderr, "Bad escape character '%s'.\n",
348 if (ciphers_valid(optarg)) {
350 options.ciphers = xstrdup(optarg);
351 options.cipher = SSH_CIPHER_ILLEGAL;
354 options.cipher = cipher_number(optarg);
355 if (options.cipher == -1) {
357 "Unknown cipher type '%s'\n",
361 if (options.cipher == SSH_CIPHER_3DES)
362 options.ciphers = "3des-cbc";
363 else if (options.cipher == SSH_CIPHER_BLOWFISH)
364 options.ciphers = "blowfish-cbc";
366 options.ciphers = (char *)-1;
370 if (mac_valid(optarg))
371 options.macs = xstrdup(optarg);
373 fprintf(stderr, "Unknown mac type '%s'\n",
379 options.control_master = 1;
382 options.port = a2port(optarg);
383 if (options.port == 0) {
384 fprintf(stderr, "Bad port '%s'\n", optarg);
389 options.user = optarg;
394 if (sscanf(optarg, "%5[0123456789]:%255[^:]:%5[0123456789]",
395 sfwd_port, buf, sfwd_host_port) != 3 &&
396 sscanf(optarg, "%5[0123456789]/%255[^/]/%5[0123456789]",
397 sfwd_port, buf, sfwd_host_port) != 3) {
399 "Bad forwarding specification '%s'\n",
404 if ((fwd_port = a2port(sfwd_port)) == 0 ||
405 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
407 "Bad forwarding port(s) '%s'\n", optarg);
411 add_local_forward(&options, fwd_port, buf,
414 add_remote_forward(&options, fwd_port, buf,
419 fwd_port = a2port(optarg);
421 fprintf(stderr, "Bad dynamic port '%s'\n",
425 add_local_forward(&options, fwd_port, "socks", 0);
429 options.compression = 1;
440 line = xstrdup(optarg);
441 if (process_config_line(&options, host ? host : "",
442 line, "command-line", 0, &dummy) != 0)
450 if (options.control_path != NULL)
451 free(options.control_path);
452 options.control_path = xstrdup(optarg);
453 if (options.control_master == -1)
454 options.control_master = 0;
457 options.bind_address = optarg;
470 if (ac > 0 && !host && **av != '-') {
471 if (strrchr(*av, '@')) {
473 cp = strrchr(p, '@');
474 if (cp == NULL || cp == p)
482 optind = optreset = 1;
488 /* Check that we got a host name. */
492 SSLeay_add_all_algorithms();
493 ERR_load_crypto_strings();
495 /* Initialize the command to execute on remote host. */
496 buffer_init(&command);
499 * Save the command to execute on the remote host in a buffer. There
500 * is no limit on the length of the command, except by the maximum
501 * packet size. Also sets the tty flag if there is no command.
504 /* No command specified - execute shell on a tty. */
506 if (subsystem_flag) {
508 "You must specify a subsystem to invoke.\n");
512 /* A command has been specified. Store it into the buffer. */
513 for (i = 0; i < ac; i++) {
515 buffer_append(&command, " ", 1);
516 buffer_append(&command, av[i], strlen(av[i]));
520 /* Cannot fork to background if no command. */
521 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
522 fatal("Cannot fork into background without a command to execute.");
524 /* Allocate a tty by default if no command specified. */
525 if (buffer_len(&command) == 0)
531 /* Do not allocate a tty if stdin is not a tty. */
532 if (!isatty(fileno(stdin)) && !force_tty_flag) {
534 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
539 * Initialize "log" output. Since we are the client all output
540 * actually goes to stderr.
542 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
543 SYSLOG_FACILITY_USER, 1);
546 * Read per-user configuration file. Ignore the system wide config
547 * file if the user specifies a config file on the command line.
549 if (config != NULL) {
550 if (!read_config_file(config, host, &options, 0))
551 fatal("Can't open user config file %.100s: "
552 "%.100s", config, strerror(errno));
554 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
555 _PATH_SSH_USER_CONFFILE);
556 (void)read_config_file(buf, host, &options, 1);
558 /* Read systemwide configuration file after use config. */
559 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
563 /* Fill configuration defaults. */
564 fill_default_options(&options);
566 channel_set_af(options.address_family);
569 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
573 if (options.user == NULL)
574 options.user = xstrdup(pw->pw_name);
576 if (options.hostname != NULL)
577 host = options.hostname;
579 /* force lowercase for hostkey matching */
580 if (options.host_key_alias != NULL) {
581 for (p = options.host_key_alias; *p; p++)
586 if (options.proxy_command != NULL &&
587 strcmp(options.proxy_command, "none") == 0)
588 options.proxy_command = NULL;
590 if (options.control_path != NULL) {
591 options.control_path = tilde_expand_filename(
592 options.control_path, original_real_uid);
594 if (options.control_path != NULL && options.control_master == 0)
595 control_client(options.control_path); /* This doesn't return */
597 /* Open a connection to the remote host. */
598 if (ssh_connect(host, &hostaddr, options.port,
599 options.address_family, options.connection_attempts,
601 options.use_privileged_port,
603 original_effective_uid == 0 && options.use_privileged_port,
605 options.proxy_command) != 0)
609 * If we successfully made the connection, load the host private key
610 * in case we will need it later for combined rsa-rhosts
611 * authentication. This must be done before releasing extra
612 * privileges, because the file is only readable by root.
613 * If we cannot access the private keys, load the public keys
614 * instead and try to execute the ssh-keysign helper instead.
616 sensitive_data.nkeys = 0;
617 sensitive_data.keys = NULL;
618 sensitive_data.external_keysign = 0;
619 if (options.rhosts_rsa_authentication ||
620 options.hostbased_authentication) {
621 sensitive_data.nkeys = 3;
622 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
626 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
627 _PATH_HOST_KEY_FILE, "", NULL);
628 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
629 _PATH_HOST_DSA_KEY_FILE, "", NULL);
630 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
631 _PATH_HOST_RSA_KEY_FILE, "", NULL);
634 if (options.hostbased_authentication == 1 &&
635 sensitive_data.keys[0] == NULL &&
636 sensitive_data.keys[1] == NULL &&
637 sensitive_data.keys[2] == NULL) {
638 sensitive_data.keys[1] = key_load_public(
639 _PATH_HOST_DSA_KEY_FILE, NULL);
640 sensitive_data.keys[2] = key_load_public(
641 _PATH_HOST_RSA_KEY_FILE, NULL);
642 sensitive_data.external_keysign = 1;
646 * Get rid of any extra privileges that we may have. We will no
647 * longer need them. Also, extra privileges could make it very hard
648 * to read identity files and other non-world-readable files from the
649 * user's home directory if it happens to be on a NFS volume where
650 * root is mapped to nobody.
652 seteuid(original_real_uid);
653 setuid(original_real_uid);
656 * Now that we are back to our own permissions, create ~/.ssh
657 * directory if it doesn\'t already exist.
659 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
660 if (stat(buf, &st) < 0)
661 if (mkdir(buf, 0700) < 0)
662 error("Could not create directory '%.200s'.", buf);
664 /* load options.identity_files */
665 load_public_identity_files();
667 /* Expand ~ in known host file names. */
669 options.system_hostfile =
670 tilde_expand_filename(options.system_hostfile, original_real_uid);
671 options.user_hostfile =
672 tilde_expand_filename(options.user_hostfile, original_real_uid);
673 options.system_hostfile2 =
674 tilde_expand_filename(options.system_hostfile2, original_real_uid);
675 options.user_hostfile2 =
676 tilde_expand_filename(options.user_hostfile2, original_real_uid);
678 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
680 /* Log into the remote system. This never returns if the login fails. */
681 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
683 /* We no longer need the private host keys. Clear them now. */
684 if (sensitive_data.nkeys != 0) {
685 for (i = 0; i < sensitive_data.nkeys; i++) {
686 if (sensitive_data.keys[i] != NULL) {
687 /* Destroys contents safely */
688 debug3("clear hostkey %d", i);
689 key_free(sensitive_data.keys[i]);
690 sensitive_data.keys[i] = NULL;
693 xfree(sensitive_data.keys);
695 for (i = 0; i < options.num_identity_files; i++) {
696 if (options.identity_files[i]) {
697 xfree(options.identity_files[i]);
698 options.identity_files[i] = NULL;
700 if (options.identity_keys[i]) {
701 key_free(options.identity_keys[i]);
702 options.identity_keys[i] = NULL;
706 exit_status = compat20 ? ssh_session2() : ssh_session();
709 if (options.control_path != NULL && control_fd != -1)
710 unlink(options.control_path);
713 * Send SIGHUP to proxy command if used. We don't wait() in
714 * case it hangs and instead rely on init to reap the child
716 if (proxy_command_pid > 1)
717 kill(proxy_command_pid, SIGHUP);
722 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
725 x11_get_proto(char **_proto, char **_data)
730 static char proto[512], data[512];
732 int got_data = 0, generated = 0, do_unlink = 0, i;
733 char *display, *xauthdir, *xauthfile;
736 xauthdir = xauthfile = NULL;
739 proto[0] = data[0] = '\0';
741 if (!options.xauth_location ||
742 (stat(options.xauth_location, &st) == -1)) {
743 debug("No xauth program.");
745 if ((display = getenv("DISPLAY")) == NULL) {
746 debug("x11_get_proto: DISPLAY not set");
750 * Handle FamilyLocal case where $DISPLAY does
751 * not match an authorization entry. For this we
752 * just try "xauth list unix:displaynum.screennum".
753 * XXX: "localhost" match to determine FamilyLocal
756 if (strncmp(display, "localhost:", 10) == 0) {
757 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
761 if (options.forward_x11_trusted == 0) {
762 xauthdir = xmalloc(MAXPATHLEN);
763 xauthfile = xmalloc(MAXPATHLEN);
764 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
765 if (mkdtemp(xauthdir) != NULL) {
767 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
769 snprintf(cmd, sizeof(cmd),
770 "%s -f %s generate %s " SSH_X11_PROTO
771 " untrusted timeout 1200 2>" _PATH_DEVNULL,
772 options.xauth_location, xauthfile, display);
773 debug2("x11_get_proto: %s", cmd);
774 if (system(cmd) == 0)
778 snprintf(cmd, sizeof(cmd),
779 "%s %s%s list %s . 2>" _PATH_DEVNULL,
780 options.xauth_location,
781 generated ? "-f " : "" ,
782 generated ? xauthfile : "",
784 debug2("x11_get_proto: %s", cmd);
786 if (f && fgets(line, sizeof(line), f) &&
787 sscanf(line, "%*s %511s %511s", proto, data) == 2)
803 * If we didn't get authentication data, just make up some
804 * data. The forwarding code will check the validity of the
805 * response anyway, and substitute this data. The X11
806 * server, however, will ignore this fake data and use
807 * whatever authentication mechanisms it was using otherwise
808 * for the local connection.
813 logit("Warning: No xauth data; "
814 "using fake authentication data for X11 forwarding.");
815 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
816 for (i = 0; i < 16; i++) {
819 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
827 ssh_init_forwarding(void)
832 /* Initiate local TCP/IP port forwardings. */
833 for (i = 0; i < options.num_local_forwards; i++) {
834 debug("Connections to local port %d forwarded to remote address %.200s:%d",
835 options.local_forwards[i].port,
836 options.local_forwards[i].host,
837 options.local_forwards[i].host_port);
838 success += channel_setup_local_fwd_listener(
839 options.local_forwards[i].port,
840 options.local_forwards[i].host,
841 options.local_forwards[i].host_port,
842 options.gateway_ports);
844 if (i > 0 && success == 0)
845 error("Could not request local forwarding.");
847 /* Initiate remote TCP/IP port forwardings. */
848 for (i = 0; i < options.num_remote_forwards; i++) {
849 debug("Connections to remote port %d forwarded to local address %.200s:%d",
850 options.remote_forwards[i].port,
851 options.remote_forwards[i].host,
852 options.remote_forwards[i].host_port);
853 channel_request_remote_forwarding(
854 options.remote_forwards[i].port,
855 options.remote_forwards[i].host,
856 options.remote_forwards[i].host_port);
861 check_agent_present(void)
863 if (options.forward_agent) {
864 /* Clear agent forwarding if we don\'t have an agent. */
865 if (!ssh_agent_present())
866 options.forward_agent = 0;
879 /* Enable compression if requested. */
880 if (options.compression) {
881 debug("Requesting compression at level %d.", options.compression_level);
883 if (options.compression_level < 1 || options.compression_level > 9)
884 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
886 /* Send the request. */
887 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
888 packet_put_int(options.compression_level);
891 type = packet_read();
892 if (type == SSH_SMSG_SUCCESS)
893 packet_start_compression(options.compression_level);
894 else if (type == SSH_SMSG_FAILURE)
895 logit("Warning: Remote host refused compression.");
897 packet_disconnect("Protocol error waiting for compression response.");
899 /* Allocate a pseudo tty if appropriate. */
901 debug("Requesting pty.");
903 /* Start the packet. */
904 packet_start(SSH_CMSG_REQUEST_PTY);
906 /* Store TERM in the packet. There is no limit on the
907 length of the string. */
911 packet_put_cstring(cp);
913 /* Store window size in the packet. */
914 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
915 memset(&ws, 0, sizeof(ws));
916 packet_put_int(ws.ws_row);
917 packet_put_int(ws.ws_col);
918 packet_put_int(ws.ws_xpixel);
919 packet_put_int(ws.ws_ypixel);
921 /* Store tty modes in the packet. */
922 tty_make_modes(fileno(stdin), NULL);
924 /* Send the packet, and wait for it to leave. */
928 /* Read response from the server. */
929 type = packet_read();
930 if (type == SSH_SMSG_SUCCESS) {
933 } else if (type == SSH_SMSG_FAILURE)
934 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
936 packet_disconnect("Protocol error waiting for pty request response.");
938 /* Request X11 forwarding if enabled and DISPLAY is set. */
939 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
941 /* Get reasonable local authentication information. */
942 x11_get_proto(&proto, &data);
943 /* Request forwarding with authentication spoofing. */
944 debug("Requesting X11 forwarding with authentication spoofing.");
945 x11_request_forwarding_with_spoofing(0, proto, data);
947 /* Read response from the server. */
948 type = packet_read();
949 if (type == SSH_SMSG_SUCCESS) {
951 } else if (type == SSH_SMSG_FAILURE) {
952 logit("Warning: Remote host denied X11 forwarding.");
954 packet_disconnect("Protocol error waiting for X11 forwarding");
957 /* Tell the packet module whether this is an interactive session. */
958 packet_set_interactive(interactive);
960 /* Request authentication agent forwarding if appropriate. */
961 check_agent_present();
963 if (options.forward_agent) {
964 debug("Requesting authentication agent forwarding.");
965 auth_request_forwarding();
967 /* Read response from the server. */
968 type = packet_read();
970 if (type != SSH_SMSG_SUCCESS)
971 logit("Warning: Remote host denied authentication agent forwarding.");
974 /* Initiate port forwardings. */
975 ssh_init_forwarding();
977 /* If requested, let ssh continue in the background. */
978 if (fork_after_authentication_flag)
979 if (daemon(1, 1) < 0)
980 fatal("daemon() failed: %.200s", strerror(errno));
983 * If a command was specified on the command line, execute the
984 * command now. Otherwise request the server to start a shell.
986 if (buffer_len(&command) > 0) {
987 int len = buffer_len(&command);
990 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
991 packet_start(SSH_CMSG_EXEC_CMD);
992 packet_put_string(buffer_ptr(&command), buffer_len(&command));
996 debug("Requesting shell.");
997 packet_start(SSH_CMSG_EXEC_SHELL);
1002 /* Enter the interactive session. */
1003 return client_loop(have_tty, tty_flag ?
1004 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1008 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1012 id = packet_get_int();
1013 len = buffer_len(&command);
1017 if (type == SSH2_MSG_CHANNEL_FAILURE)
1018 fatal("Request for subsystem '%.*s' failed on channel %d",
1019 len, (u_char *)buffer_ptr(&command), id);
1023 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1027 i = client_global_request_id++;
1028 if (i >= options.num_remote_forwards)
1030 debug("remote forward %s for: listen %d, connect %s:%d",
1031 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1032 options.remote_forwards[i].port,
1033 options.remote_forwards[i].host,
1034 options.remote_forwards[i].host_port);
1035 if (type == SSH2_MSG_REQUEST_FAILURE)
1036 logit("Warning: remote port forwarding failed for listen port %d",
1037 options.remote_forwards[i].port);
1041 ssh_control_listener(void)
1043 struct sockaddr_un addr;
1047 if (options.control_path == NULL || options.control_master != 1)
1050 memset(&addr, '\0', sizeof(addr));
1051 addr.sun_family = AF_UNIX;
1052 addr_len = offsetof(struct sockaddr_un, sun_path) +
1053 strlen(options.control_path) + 1;
1055 if (strlcpy(addr.sun_path, options.control_path,
1056 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1057 fatal("ControlPath too long");
1059 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1060 fatal("%s socket(): %s\n", __func__, strerror(errno));
1062 old_umask = umask(0177);
1063 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1065 if (errno == EINVAL)
1066 fatal("ControlSocket %s already exists",
1067 options.control_path);
1069 fatal("%s bind(): %s\n", __func__, strerror(errno));
1073 if (listen(control_fd, 64) == -1)
1074 fatal("%s listen(): %s\n", __func__, strerror(errno));
1076 set_nonblock(control_fd);
1079 /* request pty/x11/agent/tcpfwd/shell for channel */
1081 ssh_session2_setup(int id, void *arg)
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, &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 control_client(const char *path)
1232 struct sockaddr_un addr;
1233 int r, sock, exitval, addr_len;
1237 memset(&addr, '\0', sizeof(addr));
1238 addr.sun_family = AF_UNIX;
1239 addr_len = offsetof(struct sockaddr_un, sun_path) +
1242 if (strlcpy(addr.sun_path, path,
1243 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1244 fatal("ControlPath too long");
1246 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1247 fatal("%s socket(): %s", __func__, strerror(errno));
1249 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1)
1250 fatal("Couldn't connect to %s: %s", path, strerror(errno));
1252 if ((cp = getenv("TERM")) == NULL)
1255 signal(SIGINT, control_client_sighandler);
1256 signal(SIGTERM, control_client_sighandler);
1257 signal(SIGWINCH, control_client_sigrelay);
1261 /* Get PID of controlee */
1262 if (ssh_msg_recv(sock, &m) == -1)
1263 fatal("%s: msg_recv", __func__);
1264 if (buffer_get_char(&m) != 0)
1265 fatal("%s: wrong version", __func__);
1266 control_server_pid = buffer_get_int(&m);
1268 /* XXX: env passing */
1271 buffer_put_int(&m, tty_flag);
1272 buffer_put_int(&m, subsystem_flag);
1273 buffer_put_cstring(&m, cp);
1275 buffer_append(&command, "\0", 1);
1276 buffer_put_cstring(&m, buffer_ptr(&command));
1278 if (ssh_msg_send(sock, /* version */0, &m) == -1)
1279 fatal("%s: msg_send", __func__);
1281 mm_send_fd(sock, STDIN_FILENO);
1282 mm_send_fd(sock, STDOUT_FILENO);
1283 mm_send_fd(sock, STDERR_FILENO);
1285 /* Wait for reply, so master has a chance to gather ttymodes */
1287 if (ssh_msg_recv(sock, &m) == -1)
1288 fatal("%s: msg_recv", __func__);
1289 if (buffer_get_char(&m) != 0)
1290 fatal("%s: master returned error", __func__);
1296 /* Stick around until the controlee closes the client_fd */
1298 for (;!control_client_terminate;) {
1299 r = read(sock, &exitval, sizeof(exitval));
1301 debug2("Received EOF from master");
1305 debug2("Received exit status from master %d", exitval);
1306 if (r == -1 && errno != EINTR)
1307 fatal("%s: read %s", __func__, strerror(errno));
1310 if (control_client_terminate)
1311 debug2("Exiting on signal %d", control_client_terminate);
1317 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1318 fprintf(stderr, "Connection to master closed.\r\n");