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.231 2005/02/16 09:56:44 otto 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 /* Multiplexing control command */
148 static u_int mux_command = SSHMUX_COMMAND_OPEN;
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 [-1246AaCfgkMNnqsTtVvXxY] [-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 ctl_cmd]\n"
163 " [-o option] [-p port] [-R port:host:hostport] [-S ctl_path]\n"
164 " [user@]hostname [command]\n"
169 static int ssh_session(void);
170 static int ssh_session2(void);
171 static void load_public_identity_files(void);
172 static void control_client(const char *path);
175 * Main program for the ssh client.
178 main(int ac, char **av)
180 int i, opt, exit_status;
181 u_short fwd_port, fwd_host_port;
182 char sfwd_port[6], sfwd_host_port[6];
183 char *p, *cp, *line, buf[256];
187 extern int optind, optreset;
190 __progname = ssh_get_progname(av[0]);
194 * Save the original real uid. It will be needed later (uid-swapping
195 * may clobber the real uid).
197 original_real_uid = getuid();
198 original_effective_uid = geteuid();
201 * Use uid-swapping to give up root privileges for the duration of
202 * option processing. We will re-instantiate the rights when we are
203 * ready to create the privileged port, and will permanently drop
204 * them when the port has been created (actually, when the connection
205 * has been made, as we may need to create the port several times).
209 #ifdef HAVE_SETRLIMIT
210 /* If we are installed setuid root be careful to not drop core. */
211 if (original_real_uid != original_effective_uid) {
213 rlim.rlim_cur = rlim.rlim_max = 0;
214 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
215 fatal("setrlimit failed: %.100s", strerror(errno));
219 pw = getpwuid(original_real_uid);
221 logit("You don't exist, go away!");
224 /* Take a copy of the returned structure. */
228 * Set our umask to something reasonable, as some files are created
229 * with the default umask. This will make them world-readable but
230 * writable only by the owner, which is ok for all files for which we
231 * don't set the modes explicitly.
235 /* Initialize option structure to indicate that no values have been set. */
236 initialize_options(&options);
238 /* Parse command-line arguments. */
242 while ((opt = getopt(ac, av,
243 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVXY")) != -1) {
246 options.protocol = SSH_PROTO_1;
249 options.protocol = SSH_PROTO_2;
252 options.address_family = AF_INET;
255 options.address_family = AF_INET6;
261 fork_after_authentication_flag = 1;
265 options.forward_x11 = 0;
268 options.forward_x11 = 1;
271 options.forward_x11 = 1;
272 options.forward_x11_trusted = 1;
275 options.gateway_ports = 1;
278 if (strcmp(optarg, "check") == 0)
279 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
280 else if (strcmp(optarg, "exit") == 0)
281 mux_command = SSHMUX_COMMAND_TERMINATE;
283 fatal("Invalid multiplex command.");
285 case 'P': /* deprecated */
286 options.use_privileged_port = 0;
289 options.forward_agent = 0;
292 options.forward_agent = 1;
295 options.gss_deleg_creds = 0;
298 if (stat(optarg, &st) < 0) {
299 fprintf(stderr, "Warning: Identity file %s "
300 "not accessible: %s.\n", optarg,
304 if (options.num_identity_files >=
305 SSH_MAX_IDENTITY_FILES)
306 fatal("Too many identity files specified "
307 "(max %d)", SSH_MAX_IDENTITY_FILES);
308 options.identity_files[options.num_identity_files++] =
313 options.smartcard_device = xstrdup(optarg);
315 fprintf(stderr, "no support for smartcards.\n");
324 if (debug_flag == 0) {
326 options.log_level = SYSLOG_LEVEL_DEBUG1;
328 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
334 fprintf(stderr, "%s, %s\n",
335 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
340 options.log_level = SYSLOG_LEVEL_QUIET;
343 if (optarg[0] == '^' && optarg[2] == 0 &&
344 (u_char) optarg[1] >= 64 &&
345 (u_char) optarg[1] < 128)
346 options.escape_char = (u_char) optarg[1] & 31;
347 else if (strlen(optarg) == 1)
348 options.escape_char = (u_char) optarg[0];
349 else if (strcmp(optarg, "none") == 0)
350 options.escape_char = SSH_ESCAPECHAR_NONE;
352 fprintf(stderr, "Bad escape character '%s'.\n",
358 if (ciphers_valid(optarg)) {
360 options.ciphers = xstrdup(optarg);
361 options.cipher = SSH_CIPHER_INVALID;
364 options.cipher = cipher_number(optarg);
365 if (options.cipher == -1) {
367 "Unknown cipher type '%s'\n",
371 if (options.cipher == SSH_CIPHER_3DES)
372 options.ciphers = "3des-cbc";
373 else if (options.cipher == SSH_CIPHER_BLOWFISH)
374 options.ciphers = "blowfish-cbc";
376 options.ciphers = (char *)-1;
380 if (mac_valid(optarg))
381 options.macs = xstrdup(optarg);
383 fprintf(stderr, "Unknown mac type '%s'\n",
389 options.control_master =
390 (options.control_master >= 1) ? 2 : 1;
393 options.port = a2port(optarg);
394 if (options.port == 0) {
395 fprintf(stderr, "Bad port '%s'\n", optarg);
400 options.user = optarg;
405 if (sscanf(optarg, "%5[0123456789]:%255[^:]:%5[0123456789]",
406 sfwd_port, buf, sfwd_host_port) != 3 &&
407 sscanf(optarg, "%5[0123456789]/%255[^/]/%5[0123456789]",
408 sfwd_port, buf, sfwd_host_port) != 3) {
410 "Bad forwarding specification '%s'\n",
415 if ((fwd_port = a2port(sfwd_port)) == 0 ||
416 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
418 "Bad forwarding port(s) '%s'\n", optarg);
422 add_local_forward(&options, fwd_port, buf,
425 add_remote_forward(&options, fwd_port, buf,
430 fwd_port = a2port(optarg);
432 fprintf(stderr, "Bad dynamic port '%s'\n",
436 add_local_forward(&options, fwd_port, "socks", 0);
440 options.compression = 1;
451 line = xstrdup(optarg);
452 if (process_config_line(&options, host ? host : "",
453 line, "command-line", 0, &dummy) != 0)
461 if (options.control_path != NULL)
462 free(options.control_path);
463 options.control_path = xstrdup(optarg);
466 options.bind_address = optarg;
479 if (ac > 0 && !host && **av != '-') {
480 if (strrchr(*av, '@')) {
482 cp = strrchr(p, '@');
483 if (cp == NULL || cp == p)
491 optind = optreset = 1;
497 /* Check that we got a host name. */
501 SSLeay_add_all_algorithms();
502 ERR_load_crypto_strings();
504 /* Initialize the command to execute on remote host. */
505 buffer_init(&command);
508 * Save the command to execute on the remote host in a buffer. There
509 * is no limit on the length of the command, except by the maximum
510 * packet size. Also sets the tty flag if there is no command.
513 /* No command specified - execute shell on a tty. */
515 if (subsystem_flag) {
517 "You must specify a subsystem to invoke.\n");
521 /* A command has been specified. Store it into the buffer. */
522 for (i = 0; i < ac; i++) {
524 buffer_append(&command, " ", 1);
525 buffer_append(&command, av[i], strlen(av[i]));
529 /* Cannot fork to background if no command. */
530 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
531 fatal("Cannot fork into background without a command to execute.");
533 /* Allocate a tty by default if no command specified. */
534 if (buffer_len(&command) == 0)
540 /* Do not allocate a tty if stdin is not a tty. */
541 if (!isatty(fileno(stdin)) && !force_tty_flag) {
543 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
548 * Initialize "log" output. Since we are the client all output
549 * actually goes to stderr.
551 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
552 SYSLOG_FACILITY_USER, 1);
555 * Read per-user configuration file. Ignore the system wide config
556 * file if the user specifies a config file on the command line.
558 if (config != NULL) {
559 if (!read_config_file(config, host, &options, 0))
560 fatal("Can't open user config file %.100s: "
561 "%.100s", config, strerror(errno));
563 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
564 _PATH_SSH_USER_CONFFILE);
565 (void)read_config_file(buf, host, &options, 1);
567 /* Read systemwide configuration file after use config. */
568 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
572 /* Fill configuration defaults. */
573 fill_default_options(&options);
575 channel_set_af(options.address_family);
578 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
582 if (options.user == NULL)
583 options.user = xstrdup(pw->pw_name);
585 if (options.hostname != NULL)
586 host = options.hostname;
588 /* force lowercase for hostkey matching */
589 if (options.host_key_alias != NULL) {
590 for (p = options.host_key_alias; *p; p++)
595 if (options.proxy_command != NULL &&
596 strcmp(options.proxy_command, "none") == 0)
597 options.proxy_command = NULL;
599 if (options.control_path != NULL) {
600 options.control_path = tilde_expand_filename(
601 options.control_path, original_real_uid);
603 if (options.control_path != NULL && options.control_master == 0)
604 control_client(options.control_path); /* This doesn't return */
606 /* Open a connection to the remote host. */
607 if (ssh_connect(host, &hostaddr, options.port,
608 options.address_family, options.connection_attempts,
610 options.use_privileged_port,
612 original_effective_uid == 0 && options.use_privileged_port,
614 options.proxy_command) != 0)
618 * If we successfully made the connection, load the host private key
619 * in case we will need it later for combined rsa-rhosts
620 * authentication. This must be done before releasing extra
621 * privileges, because the file is only readable by root.
622 * If we cannot access the private keys, load the public keys
623 * instead and try to execute the ssh-keysign helper instead.
625 sensitive_data.nkeys = 0;
626 sensitive_data.keys = NULL;
627 sensitive_data.external_keysign = 0;
628 if (options.rhosts_rsa_authentication ||
629 options.hostbased_authentication) {
630 sensitive_data.nkeys = 3;
631 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
635 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
636 _PATH_HOST_KEY_FILE, "", NULL);
637 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
638 _PATH_HOST_DSA_KEY_FILE, "", NULL);
639 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
640 _PATH_HOST_RSA_KEY_FILE, "", NULL);
643 if (options.hostbased_authentication == 1 &&
644 sensitive_data.keys[0] == NULL &&
645 sensitive_data.keys[1] == NULL &&
646 sensitive_data.keys[2] == NULL) {
647 sensitive_data.keys[1] = key_load_public(
648 _PATH_HOST_DSA_KEY_FILE, NULL);
649 sensitive_data.keys[2] = key_load_public(
650 _PATH_HOST_RSA_KEY_FILE, NULL);
651 sensitive_data.external_keysign = 1;
655 * Get rid of any extra privileges that we may have. We will no
656 * longer need them. Also, extra privileges could make it very hard
657 * to read identity files and other non-world-readable files from the
658 * user's home directory if it happens to be on a NFS volume where
659 * root is mapped to nobody.
661 if (original_effective_uid == 0) {
663 permanently_set_uid(pw);
667 * Now that we are back to our own permissions, create ~/.ssh
668 * directory if it doesn\'t already exist.
670 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
671 if (stat(buf, &st) < 0)
672 if (mkdir(buf, 0700) < 0)
673 error("Could not create directory '%.200s'.", buf);
675 /* load options.identity_files */
676 load_public_identity_files();
678 /* Expand ~ in known host file names. */
680 options.system_hostfile =
681 tilde_expand_filename(options.system_hostfile, original_real_uid);
682 options.user_hostfile =
683 tilde_expand_filename(options.user_hostfile, original_real_uid);
684 options.system_hostfile2 =
685 tilde_expand_filename(options.system_hostfile2, original_real_uid);
686 options.user_hostfile2 =
687 tilde_expand_filename(options.user_hostfile2, original_real_uid);
689 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
691 /* Log into the remote system. This never returns if the login fails. */
692 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
694 /* We no longer need the private host keys. Clear them now. */
695 if (sensitive_data.nkeys != 0) {
696 for (i = 0; i < sensitive_data.nkeys; i++) {
697 if (sensitive_data.keys[i] != NULL) {
698 /* Destroys contents safely */
699 debug3("clear hostkey %d", i);
700 key_free(sensitive_data.keys[i]);
701 sensitive_data.keys[i] = NULL;
704 xfree(sensitive_data.keys);
706 for (i = 0; i < options.num_identity_files; i++) {
707 if (options.identity_files[i]) {
708 xfree(options.identity_files[i]);
709 options.identity_files[i] = NULL;
711 if (options.identity_keys[i]) {
712 key_free(options.identity_keys[i]);
713 options.identity_keys[i] = NULL;
717 exit_status = compat20 ? ssh_session2() : ssh_session();
720 if (options.control_path != NULL && control_fd != -1)
721 unlink(options.control_path);
724 * Send SIGHUP to proxy command if used. We don't wait() in
725 * case it hangs and instead rely on init to reap the child
727 if (proxy_command_pid > 1)
728 kill(proxy_command_pid, SIGHUP);
733 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
736 x11_get_proto(char **_proto, char **_data)
741 static char proto[512], data[512];
743 int got_data = 0, generated = 0, do_unlink = 0, i;
744 char *display, *xauthdir, *xauthfile;
747 xauthdir = xauthfile = NULL;
750 proto[0] = data[0] = '\0';
752 if (!options.xauth_location ||
753 (stat(options.xauth_location, &st) == -1)) {
754 debug("No xauth program.");
756 if ((display = getenv("DISPLAY")) == NULL) {
757 debug("x11_get_proto: DISPLAY not set");
761 * Handle FamilyLocal case where $DISPLAY does
762 * not match an authorization entry. For this we
763 * just try "xauth list unix:displaynum.screennum".
764 * XXX: "localhost" match to determine FamilyLocal
767 if (strncmp(display, "localhost:", 10) == 0) {
768 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
772 if (options.forward_x11_trusted == 0) {
773 xauthdir = xmalloc(MAXPATHLEN);
774 xauthfile = xmalloc(MAXPATHLEN);
775 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
776 if (mkdtemp(xauthdir) != NULL) {
778 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
780 snprintf(cmd, sizeof(cmd),
781 "%s -f %s generate %s " SSH_X11_PROTO
782 " untrusted timeout 1200 2>" _PATH_DEVNULL,
783 options.xauth_location, xauthfile, display);
784 debug2("x11_get_proto: %s", cmd);
785 if (system(cmd) == 0)
789 snprintf(cmd, sizeof(cmd),
790 "%s %s%s list %s . 2>" _PATH_DEVNULL,
791 options.xauth_location,
792 generated ? "-f " : "" ,
793 generated ? xauthfile : "",
795 debug2("x11_get_proto: %s", cmd);
797 if (f && fgets(line, sizeof(line), f) &&
798 sscanf(line, "%*s %511s %511s", proto, data) == 2)
814 * If we didn't get authentication data, just make up some
815 * data. The forwarding code will check the validity of the
816 * response anyway, and substitute this data. The X11
817 * server, however, will ignore this fake data and use
818 * whatever authentication mechanisms it was using otherwise
819 * for the local connection.
824 logit("Warning: No xauth data; "
825 "using fake authentication data for X11 forwarding.");
826 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
827 for (i = 0; i < 16; i++) {
830 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
838 ssh_init_forwarding(void)
843 /* Initiate local TCP/IP port forwardings. */
844 for (i = 0; i < options.num_local_forwards; i++) {
845 debug("Connections to local port %d forwarded to remote address %.200s:%d",
846 options.local_forwards[i].port,
847 options.local_forwards[i].host,
848 options.local_forwards[i].host_port);
849 success += channel_setup_local_fwd_listener(
850 options.local_forwards[i].port,
851 options.local_forwards[i].host,
852 options.local_forwards[i].host_port,
853 options.gateway_ports);
855 if (i > 0 && success == 0)
856 error("Could not request local forwarding.");
858 /* Initiate remote TCP/IP port forwardings. */
859 for (i = 0; i < options.num_remote_forwards; i++) {
860 debug("Connections to remote port %d forwarded to local address %.200s:%d",
861 options.remote_forwards[i].port,
862 options.remote_forwards[i].host,
863 options.remote_forwards[i].host_port);
864 channel_request_remote_forwarding(
865 options.remote_forwards[i].port,
866 options.remote_forwards[i].host,
867 options.remote_forwards[i].host_port);
872 check_agent_present(void)
874 if (options.forward_agent) {
875 /* Clear agent forwarding if we don\'t have an agent. */
876 if (!ssh_agent_present())
877 options.forward_agent = 0;
890 /* Enable compression if requested. */
891 if (options.compression) {
892 debug("Requesting compression at level %d.", options.compression_level);
894 if (options.compression_level < 1 || options.compression_level > 9)
895 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
897 /* Send the request. */
898 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
899 packet_put_int(options.compression_level);
902 type = packet_read();
903 if (type == SSH_SMSG_SUCCESS)
904 packet_start_compression(options.compression_level);
905 else if (type == SSH_SMSG_FAILURE)
906 logit("Warning: Remote host refused compression.");
908 packet_disconnect("Protocol error waiting for compression response.");
910 /* Allocate a pseudo tty if appropriate. */
912 debug("Requesting pty.");
914 /* Start the packet. */
915 packet_start(SSH_CMSG_REQUEST_PTY);
917 /* Store TERM in the packet. There is no limit on the
918 length of the string. */
922 packet_put_cstring(cp);
924 /* Store window size in the packet. */
925 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
926 memset(&ws, 0, sizeof(ws));
927 packet_put_int(ws.ws_row);
928 packet_put_int(ws.ws_col);
929 packet_put_int(ws.ws_xpixel);
930 packet_put_int(ws.ws_ypixel);
932 /* Store tty modes in the packet. */
933 tty_make_modes(fileno(stdin), NULL);
935 /* Send the packet, and wait for it to leave. */
939 /* Read response from the server. */
940 type = packet_read();
941 if (type == SSH_SMSG_SUCCESS) {
944 } else if (type == SSH_SMSG_FAILURE)
945 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
947 packet_disconnect("Protocol error waiting for pty request response.");
949 /* Request X11 forwarding if enabled and DISPLAY is set. */
950 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
952 /* Get reasonable local authentication information. */
953 x11_get_proto(&proto, &data);
954 /* Request forwarding with authentication spoofing. */
955 debug("Requesting X11 forwarding with authentication spoofing.");
956 x11_request_forwarding_with_spoofing(0, proto, data);
958 /* Read response from the server. */
959 type = packet_read();
960 if (type == SSH_SMSG_SUCCESS) {
962 } else if (type == SSH_SMSG_FAILURE) {
963 logit("Warning: Remote host denied X11 forwarding.");
965 packet_disconnect("Protocol error waiting for X11 forwarding");
968 /* Tell the packet module whether this is an interactive session. */
969 packet_set_interactive(interactive);
971 /* Request authentication agent forwarding if appropriate. */
972 check_agent_present();
974 if (options.forward_agent) {
975 debug("Requesting authentication agent forwarding.");
976 auth_request_forwarding();
978 /* Read response from the server. */
979 type = packet_read();
981 if (type != SSH_SMSG_SUCCESS)
982 logit("Warning: Remote host denied authentication agent forwarding.");
985 /* Initiate port forwardings. */
986 ssh_init_forwarding();
988 /* If requested, let ssh continue in the background. */
989 if (fork_after_authentication_flag)
990 if (daemon(1, 1) < 0)
991 fatal("daemon() failed: %.200s", strerror(errno));
994 * If a command was specified on the command line, execute the
995 * command now. Otherwise request the server to start a shell.
997 if (buffer_len(&command) > 0) {
998 int len = buffer_len(&command);
1001 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1002 packet_start(SSH_CMSG_EXEC_CMD);
1003 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1005 packet_write_wait();
1007 debug("Requesting shell.");
1008 packet_start(SSH_CMSG_EXEC_SHELL);
1010 packet_write_wait();
1013 /* Enter the interactive session. */
1014 return client_loop(have_tty, tty_flag ?
1015 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1019 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1023 id = packet_get_int();
1024 len = buffer_len(&command);
1028 if (type == SSH2_MSG_CHANNEL_FAILURE)
1029 fatal("Request for subsystem '%.*s' failed on channel %d",
1030 len, (u_char *)buffer_ptr(&command), id);
1034 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1038 i = client_global_request_id++;
1039 if (i >= options.num_remote_forwards)
1041 debug("remote forward %s for: listen %d, connect %s:%d",
1042 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1043 options.remote_forwards[i].port,
1044 options.remote_forwards[i].host,
1045 options.remote_forwards[i].host_port);
1046 if (type == SSH2_MSG_REQUEST_FAILURE)
1047 logit("Warning: remote port forwarding failed for listen port %d",
1048 options.remote_forwards[i].port);
1052 ssh_control_listener(void)
1054 struct sockaddr_un addr;
1058 if (options.control_path == NULL || options.control_master <= 0)
1061 memset(&addr, '\0', sizeof(addr));
1062 addr.sun_family = AF_UNIX;
1063 addr_len = offsetof(struct sockaddr_un, sun_path) +
1064 strlen(options.control_path) + 1;
1066 if (strlcpy(addr.sun_path, options.control_path,
1067 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1068 fatal("ControlPath too long");
1070 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1071 fatal("%s socket(): %s\n", __func__, strerror(errno));
1073 old_umask = umask(0177);
1074 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1076 if (errno == EINVAL)
1077 fatal("ControlSocket %s already exists",
1078 options.control_path);
1080 fatal("%s bind(): %s\n", __func__, strerror(errno));
1084 if (listen(control_fd, 64) == -1)
1085 fatal("%s listen(): %s\n", __func__, strerror(errno));
1087 set_nonblock(control_fd);
1090 /* request pty/x11/agent/tcpfwd/shell for channel */
1092 ssh_session2_setup(int id, void *arg)
1094 extern char **environ;
1096 int interactive = tty_flag;
1097 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1099 /* Get reasonable local authentication information. */
1100 x11_get_proto(&proto, &data);
1101 /* Request forwarding with authentication spoofing. */
1102 debug("Requesting X11 forwarding with authentication spoofing.");
1103 x11_request_forwarding_with_spoofing(id, proto, data);
1105 /* XXX wait for reply */
1108 check_agent_present();
1109 if (options.forward_agent) {
1110 debug("Requesting authentication agent forwarding.");
1111 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1115 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1116 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1118 packet_set_interactive(interactive);
1121 /* open new channel for a session */
1123 ssh_session2_open(void)
1126 int window, packetmax, in, out, err;
1128 if (stdin_null_flag) {
1129 in = open(_PATH_DEVNULL, O_RDONLY);
1131 in = dup(STDIN_FILENO);
1133 out = dup(STDOUT_FILENO);
1134 err = dup(STDERR_FILENO);
1136 if (in < 0 || out < 0 || err < 0)
1137 fatal("dup() in/out/err failed");
1139 /* enable nonblocking unless tty */
1147 window = CHAN_SES_WINDOW_DEFAULT;
1148 packetmax = CHAN_SES_PACKET_DEFAULT;
1154 "session", SSH_CHANNEL_OPENING, in, out, err,
1155 window, packetmax, CHAN_EXTENDED_WRITE,
1156 "client-session", /*nonblock*/0);
1158 debug3("ssh_session2_open: channel_new: %d", c->self);
1160 channel_send_open(c->self);
1162 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1172 /* XXX should be pre-session */
1173 ssh_init_forwarding();
1174 ssh_control_listener();
1176 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1177 id = ssh_session2_open();
1179 /* If requested, let ssh continue in the background. */
1180 if (fork_after_authentication_flag)
1181 if (daemon(1, 1) < 0)
1182 fatal("daemon() failed: %.200s", strerror(errno));
1184 return client_loop(tty_flag, tty_flag ?
1185 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1189 load_public_identity_files(void)
1197 if (options.smartcard_device != NULL &&
1198 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1199 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1201 for (i = 0; keys[i] != NULL; i++) {
1203 memmove(&options.identity_files[1], &options.identity_files[0],
1204 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1205 memmove(&options.identity_keys[1], &options.identity_keys[0],
1206 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1207 options.num_identity_files++;
1208 options.identity_keys[0] = keys[i];
1209 options.identity_files[0] = sc_get_key_label(keys[i]);
1211 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1212 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1216 #endif /* SMARTCARD */
1217 for (; i < options.num_identity_files; i++) {
1218 filename = tilde_expand_filename(options.identity_files[i],
1220 public = key_load_public(filename, NULL);
1221 debug("identity file %s type %d", filename,
1222 public ? public->type : -1);
1223 xfree(options.identity_files[i]);
1224 options.identity_files[i] = filename;
1225 options.identity_keys[i] = public;
1230 control_client_sighandler(int signo)
1232 control_client_terminate = signo;
1236 control_client_sigrelay(int signo)
1238 if (control_server_pid > 1)
1239 kill(control_server_pid, signo);
1243 env_permitted(char *env)
1246 char name[1024], *cp;
1248 strlcpy(name, env, sizeof(name));
1249 if ((cp = strchr(name, '=')) == NULL)
1254 for (i = 0; i < options.num_send_env; i++)
1255 if (match_pattern(name, options.send_env[i]))
1262 control_client(const char *path)
1264 struct sockaddr_un addr;
1265 int i, r, fd, sock, exitval, num_env, addr_len;
1268 extern char **environ;
1271 if (stdin_null_flag) {
1272 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1273 fatal("open(/dev/null): %s", strerror(errno));
1274 if (dup2(fd, STDIN_FILENO) == -1)
1275 fatal("dup2: %s", strerror(errno));
1276 if (fd > STDERR_FILENO)
1280 memset(&addr, '\0', sizeof(addr));
1281 addr.sun_family = AF_UNIX;
1282 addr_len = offsetof(struct sockaddr_un, sun_path) +
1285 if (strlcpy(addr.sun_path, path,
1286 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1287 fatal("ControlPath too long");
1289 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1290 fatal("%s socket(): %s", __func__, strerror(errno));
1292 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1)
1293 fatal("Couldn't connect to %s: %s", path, strerror(errno));
1295 if ((term = getenv("TERM")) == NULL)
1300 flags |= SSHMUX_FLAG_TTY;
1302 flags |= SSHMUX_FLAG_SUBSYS;
1306 /* Send our command to server */
1307 buffer_put_int(&m, mux_command);
1308 buffer_put_int(&m, flags);
1309 if (ssh_msg_send(sock, /* version */1, &m) == -1)
1310 fatal("%s: msg_send", __func__);
1313 /* Get authorisation status and PID of controlee */
1314 if (ssh_msg_recv(sock, &m) == -1)
1315 fatal("%s: msg_recv", __func__);
1316 if (buffer_get_char(&m) != 1)
1317 fatal("%s: wrong version", __func__);
1318 if (buffer_get_int(&m) != 1)
1319 fatal("Connection to master denied");
1320 control_server_pid = buffer_get_int(&m);
1324 switch (mux_command) {
1325 case SSHMUX_COMMAND_ALIVE_CHECK:
1326 fprintf(stderr, "Master running (pid=%d)\r\n",
1327 control_server_pid);
1329 case SSHMUX_COMMAND_TERMINATE:
1330 fprintf(stderr, "Exit request sent.\r\n");
1332 case SSHMUX_COMMAND_OPEN:
1333 /* continue below */
1336 fatal("silly mux_command %d", mux_command);
1339 /* SSHMUX_COMMAND_OPEN */
1340 buffer_put_cstring(&m, term);
1341 buffer_append(&command, "\0", 1);
1342 buffer_put_cstring(&m, buffer_ptr(&command));
1344 if (options.num_send_env == 0 || environ == NULL) {
1345 buffer_put_int(&m, 0);
1347 /* Pass environment */
1349 for (i = 0; environ[i] != NULL; i++)
1350 if (env_permitted(environ[i]))
1351 num_env++; /* Count */
1353 buffer_put_int(&m, num_env);
1355 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1356 if (env_permitted(environ[i])) {
1358 buffer_put_cstring(&m, environ[i]);
1362 if (ssh_msg_send(sock, /* version */1, &m) == -1)
1363 fatal("%s: msg_send", __func__);
1365 mm_send_fd(sock, STDIN_FILENO);
1366 mm_send_fd(sock, STDOUT_FILENO);
1367 mm_send_fd(sock, STDERR_FILENO);
1369 /* Wait for reply, so master has a chance to gather ttymodes */
1371 if (ssh_msg_recv(sock, &m) == -1)
1372 fatal("%s: msg_recv", __func__);
1373 if (buffer_get_char(&m) != 1)
1374 fatal("%s: wrong version", __func__);
1377 signal(SIGHUP, control_client_sighandler);
1378 signal(SIGINT, control_client_sighandler);
1379 signal(SIGTERM, control_client_sighandler);
1380 signal(SIGWINCH, control_client_sigrelay);
1385 /* Stick around until the controlee closes the client_fd */
1387 for (;!control_client_terminate;) {
1388 r = read(sock, &exitval, sizeof(exitval));
1390 debug2("Received EOF from master");
1394 debug2("Received exit status from master %d", exitval);
1395 if (r == -1 && errno != EINTR)
1396 fatal("%s: read %s", __func__, strerror(errno));
1399 if (control_client_terminate)
1400 debug2("Exiting on signal %d", control_client_terminate);
1406 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1407 fprintf(stderr, "Connection to master closed.\r\n");