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.233 2005/03/01 17:22:06 jmc 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]\n"
162 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
163 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
164 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
165 " [user@]hostname [command]\n"
170 static int ssh_session(void);
171 static int ssh_session2(void);
172 static void load_public_identity_files(void);
173 static void control_client(const char *path);
176 * Main program for the ssh client.
179 main(int ac, char **av)
181 int i, opt, exit_status;
182 char *p, *cp, *line, buf[256];
186 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;
404 if (parse_forward(&fwd, optarg))
405 add_local_forward(&options, &fwd);
408 "Bad local forwarding specification '%s'\n",
415 if (parse_forward(&fwd, optarg)) {
416 add_remote_forward(&options, &fwd);
419 "Bad remote forwarding specification "
426 cp = p = xstrdup(optarg);
427 memset(&fwd, '\0', sizeof(fwd));
428 fwd.connect_host = "socks";
429 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
430 fprintf(stderr, "Bad dynamic forwarding "
431 "specification '%.100s'\n", optarg);
435 fwd.listen_port = a2port(cp);
436 fwd.listen_host = cleanhostname(fwd.listen_host);
438 fwd.listen_port = a2port(fwd.listen_host);
439 fwd.listen_host = "";
442 if (fwd.listen_port == 0) {
443 fprintf(stderr, "Bad dynamic port '%s'\n",
447 add_local_forward(&options, &fwd);
452 options.compression = 1;
463 line = xstrdup(optarg);
464 if (process_config_line(&options, host ? host : "",
465 line, "command-line", 0, &dummy) != 0)
473 if (options.control_path != NULL)
474 free(options.control_path);
475 options.control_path = xstrdup(optarg);
478 options.bind_address = optarg;
491 if (ac > 0 && !host && **av != '-') {
492 if (strrchr(*av, '@')) {
494 cp = strrchr(p, '@');
495 if (cp == NULL || cp == p)
503 optind = optreset = 1;
509 /* Check that we got a host name. */
513 SSLeay_add_all_algorithms();
514 ERR_load_crypto_strings();
516 /* Initialize the command to execute on remote host. */
517 buffer_init(&command);
520 * Save the command to execute on the remote host in a buffer. There
521 * is no limit on the length of the command, except by the maximum
522 * packet size. Also sets the tty flag if there is no command.
525 /* No command specified - execute shell on a tty. */
527 if (subsystem_flag) {
529 "You must specify a subsystem to invoke.\n");
533 /* A command has been specified. Store it into the buffer. */
534 for (i = 0; i < ac; i++) {
536 buffer_append(&command, " ", 1);
537 buffer_append(&command, av[i], strlen(av[i]));
541 /* Cannot fork to background if no command. */
542 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
543 fatal("Cannot fork into background without a command to execute.");
545 /* Allocate a tty by default if no command specified. */
546 if (buffer_len(&command) == 0)
552 /* Do not allocate a tty if stdin is not a tty. */
553 if (!isatty(fileno(stdin)) && !force_tty_flag) {
555 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
560 * Initialize "log" output. Since we are the client all output
561 * actually goes to stderr.
563 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
564 SYSLOG_FACILITY_USER, 1);
567 * Read per-user configuration file. Ignore the system wide config
568 * file if the user specifies a config file on the command line.
570 if (config != NULL) {
571 if (!read_config_file(config, host, &options, 0))
572 fatal("Can't open user config file %.100s: "
573 "%.100s", config, strerror(errno));
576 * Since the config file parsing code aborts if it sees
577 * options it doesn't recognize, allow users to put
578 * options specific to compile-time add-ons in alternate
579 * config files so their primary config file will
580 * interoperate SSH versions that don't support those
584 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
585 _PATH_SSH_USER_CONFFILE);
586 (void)read_config_file(buf, host, &options, 1);
588 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
589 _PATH_SSH_USER_CONFFILE);
590 (void)read_config_file(buf, host, &options, 1);
593 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
594 _PATH_SSH_USER_CONFFILE);
595 (void)read_config_file(buf, host, &options, 1);
598 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
599 _PATH_SSH_USER_CONFFILE);
600 (void)read_config_file(buf, host, &options, 1);
602 /* Read systemwide configuration file after use config. */
603 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
607 /* Fill configuration defaults. */
608 fill_default_options(&options);
610 channel_set_af(options.address_family);
613 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
617 if (options.user == NULL) {
618 options.user = xstrdup(pw->pw_name);
619 options.implicit = 1;
621 else options.implicit = 0;
623 if (options.hostname != NULL)
624 host = options.hostname;
626 /* force lowercase for hostkey matching */
627 if (options.host_key_alias != NULL) {
628 for (p = options.host_key_alias; *p; p++)
633 if (options.proxy_command != NULL &&
634 strcmp(options.proxy_command, "none") == 0)
635 options.proxy_command = NULL;
637 if (options.control_path != NULL) {
638 options.control_path = tilde_expand_filename(
639 options.control_path, original_real_uid);
641 if (options.control_path != NULL && options.control_master == 0)
642 control_client(options.control_path); /* This doesn't return */
644 /* Open a connection to the remote host. */
645 if (ssh_connect(host, &hostaddr, options.port,
646 options.address_family, options.connection_attempts,
648 options.use_privileged_port,
650 original_effective_uid == 0 && options.use_privileged_port,
652 options.proxy_command) != 0)
656 * If we successfully made the connection, load the host private key
657 * in case we will need it later for combined rsa-rhosts
658 * authentication. This must be done before releasing extra
659 * privileges, because the file is only readable by root.
660 * If we cannot access the private keys, load the public keys
661 * instead and try to execute the ssh-keysign helper instead.
663 sensitive_data.nkeys = 0;
664 sensitive_data.keys = NULL;
665 sensitive_data.external_keysign = 0;
666 if (options.rhosts_rsa_authentication ||
667 options.hostbased_authentication) {
668 sensitive_data.nkeys = 3;
669 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
673 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
674 _PATH_HOST_KEY_FILE, "", NULL);
675 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
676 _PATH_HOST_DSA_KEY_FILE, "", NULL);
677 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
678 _PATH_HOST_RSA_KEY_FILE, "", NULL);
681 if (options.hostbased_authentication == 1 &&
682 sensitive_data.keys[0] == NULL &&
683 sensitive_data.keys[1] == NULL &&
684 sensitive_data.keys[2] == NULL) {
685 sensitive_data.keys[1] = key_load_public(
686 _PATH_HOST_DSA_KEY_FILE, NULL);
687 sensitive_data.keys[2] = key_load_public(
688 _PATH_HOST_RSA_KEY_FILE, NULL);
689 sensitive_data.external_keysign = 1;
693 * Get rid of any extra privileges that we may have. We will no
694 * longer need them. Also, extra privileges could make it very hard
695 * to read identity files and other non-world-readable files from the
696 * user's home directory if it happens to be on a NFS volume where
697 * root is mapped to nobody.
699 if (original_effective_uid == 0) {
701 permanently_set_uid(pw);
705 * Now that we are back to our own permissions, create ~/.ssh
706 * directory if it doesn\'t already exist.
708 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
709 if (stat(buf, &st) < 0)
710 if (mkdir(buf, 0700) < 0)
711 error("Could not create directory '%.200s'.", buf);
713 /* load options.identity_files */
714 load_public_identity_files();
716 /* Expand ~ in known host file names. */
718 options.system_hostfile =
719 tilde_expand_filename(options.system_hostfile, original_real_uid);
720 options.user_hostfile =
721 tilde_expand_filename(options.user_hostfile, original_real_uid);
722 options.system_hostfile2 =
723 tilde_expand_filename(options.system_hostfile2, original_real_uid);
724 options.user_hostfile2 =
725 tilde_expand_filename(options.user_hostfile2, original_real_uid);
727 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
729 /* Log into the remote system. This never returns if the login fails. */
730 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
732 /* We no longer need the private host keys. Clear them now. */
733 if (sensitive_data.nkeys != 0) {
734 for (i = 0; i < sensitive_data.nkeys; i++) {
735 if (sensitive_data.keys[i] != NULL) {
736 /* Destroys contents safely */
737 debug3("clear hostkey %d", i);
738 key_free(sensitive_data.keys[i]);
739 sensitive_data.keys[i] = NULL;
742 xfree(sensitive_data.keys);
744 for (i = 0; i < options.num_identity_files; i++) {
745 if (options.identity_files[i]) {
746 xfree(options.identity_files[i]);
747 options.identity_files[i] = NULL;
749 if (options.identity_keys[i]) {
750 key_free(options.identity_keys[i]);
751 options.identity_keys[i] = NULL;
755 exit_status = compat20 ? ssh_session2() : ssh_session();
758 if (options.control_path != NULL && control_fd != -1)
759 unlink(options.control_path);
762 * Send SIGHUP to proxy command if used. We don't wait() in
763 * case it hangs and instead rely on init to reap the child
765 if (proxy_command_pid > 1)
766 kill(proxy_command_pid, SIGHUP);
771 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
774 x11_get_proto(char **_proto, char **_data)
779 static char proto[512], data[512];
781 int got_data = 0, generated = 0, do_unlink = 0, i;
782 char *display, *xauthdir, *xauthfile;
785 xauthdir = xauthfile = NULL;
788 proto[0] = data[0] = '\0';
790 if (!options.xauth_location ||
791 (stat(options.xauth_location, &st) == -1)) {
792 debug("No xauth program.");
794 if ((display = getenv("DISPLAY")) == NULL) {
795 debug("x11_get_proto: DISPLAY not set");
799 * Handle FamilyLocal case where $DISPLAY does
800 * not match an authorization entry. For this we
801 * just try "xauth list unix:displaynum.screennum".
802 * XXX: "localhost" match to determine FamilyLocal
805 if (strncmp(display, "localhost:", 10) == 0) {
806 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
810 if (options.forward_x11_trusted == 0) {
811 xauthdir = xmalloc(MAXPATHLEN);
812 xauthfile = xmalloc(MAXPATHLEN);
813 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
814 if (mkdtemp(xauthdir) != NULL) {
816 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
818 snprintf(cmd, sizeof(cmd),
819 "%s -f %s generate %s " SSH_X11_PROTO
820 " untrusted timeout 1200 2>" _PATH_DEVNULL,
821 options.xauth_location, xauthfile, display);
822 debug2("x11_get_proto: %s", cmd);
823 if (system(cmd) == 0)
827 snprintf(cmd, sizeof(cmd),
828 "%s %s%s list %s . 2>" _PATH_DEVNULL,
829 options.xauth_location,
830 generated ? "-f " : "" ,
831 generated ? xauthfile : "",
833 debug2("x11_get_proto: %s", cmd);
835 if (f && fgets(line, sizeof(line), f) &&
836 sscanf(line, "%*s %511s %511s", proto, data) == 2)
852 * If we didn't get authentication data, just make up some
853 * data. The forwarding code will check the validity of the
854 * response anyway, and substitute this data. The X11
855 * server, however, will ignore this fake data and use
856 * whatever authentication mechanisms it was using otherwise
857 * for the local connection.
862 logit("Warning: No xauth data; "
863 "using fake authentication data for X11 forwarding.");
864 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
865 for (i = 0; i < 16; i++) {
868 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
876 ssh_init_forwarding(void)
881 /* Initiate local TCP/IP port forwardings. */
882 for (i = 0; i < options.num_local_forwards; i++) {
883 debug("Local connections to %.200s:%d forwarded to remote "
885 (options.local_forwards[i].listen_host == NULL) ?
886 (options.gateway_ports ? "*" : "LOCALHOST") :
887 options.local_forwards[i].listen_host,
888 options.local_forwards[i].listen_port,
889 options.local_forwards[i].connect_host,
890 options.local_forwards[i].connect_port);
891 success += channel_setup_local_fwd_listener(
892 options.local_forwards[i].listen_host,
893 options.local_forwards[i].listen_port,
894 options.local_forwards[i].connect_host,
895 options.local_forwards[i].connect_port,
896 options.gateway_ports);
898 if (i > 0 && success == 0)
899 error("Could not request local forwarding.");
901 /* Initiate remote TCP/IP port forwardings. */
902 for (i = 0; i < options.num_remote_forwards; i++) {
903 debug("Remote connections from %.200s:%d forwarded to "
904 "local address %.200s:%d",
905 options.remote_forwards[i].listen_host,
906 options.remote_forwards[i].listen_port,
907 options.remote_forwards[i].connect_host,
908 options.remote_forwards[i].connect_port);
909 channel_request_remote_forwarding(
910 options.remote_forwards[i].listen_host,
911 options.remote_forwards[i].listen_port,
912 options.remote_forwards[i].connect_host,
913 options.remote_forwards[i].connect_port);
918 check_agent_present(void)
920 if (options.forward_agent) {
921 /* Clear agent forwarding if we don\'t have an agent. */
922 if (!ssh_agent_present())
923 options.forward_agent = 0;
936 /* Enable compression if requested. */
937 if (options.compression) {
938 debug("Requesting compression at level %d.", options.compression_level);
940 if (options.compression_level < 1 || options.compression_level > 9)
941 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
943 /* Send the request. */
944 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
945 packet_put_int(options.compression_level);
948 type = packet_read();
949 if (type == SSH_SMSG_SUCCESS)
950 packet_start_compression(options.compression_level);
951 else if (type == SSH_SMSG_FAILURE)
952 logit("Warning: Remote host refused compression.");
954 packet_disconnect("Protocol error waiting for compression response.");
956 /* Allocate a pseudo tty if appropriate. */
958 debug("Requesting pty.");
960 /* Start the packet. */
961 packet_start(SSH_CMSG_REQUEST_PTY);
963 /* Store TERM in the packet. There is no limit on the
964 length of the string. */
968 packet_put_cstring(cp);
970 /* Store window size in the packet. */
971 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
972 memset(&ws, 0, sizeof(ws));
973 packet_put_int(ws.ws_row);
974 packet_put_int(ws.ws_col);
975 packet_put_int(ws.ws_xpixel);
976 packet_put_int(ws.ws_ypixel);
978 /* Store tty modes in the packet. */
979 tty_make_modes(fileno(stdin), NULL);
981 /* Send the packet, and wait for it to leave. */
985 /* Read response from the server. */
986 type = packet_read();
987 if (type == SSH_SMSG_SUCCESS) {
990 } else if (type == SSH_SMSG_FAILURE)
991 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
993 packet_disconnect("Protocol error waiting for pty request response.");
995 /* Request X11 forwarding if enabled and DISPLAY is set. */
996 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
998 /* Get reasonable local authentication information. */
999 x11_get_proto(&proto, &data);
1000 /* Request forwarding with authentication spoofing. */
1001 debug("Requesting X11 forwarding with authentication spoofing.");
1002 x11_request_forwarding_with_spoofing(0, proto, data);
1004 /* Read response from the server. */
1005 type = packet_read();
1006 if (type == SSH_SMSG_SUCCESS) {
1008 } else if (type == SSH_SMSG_FAILURE) {
1009 logit("Warning: Remote host denied X11 forwarding.");
1011 packet_disconnect("Protocol error waiting for X11 forwarding");
1014 /* Tell the packet module whether this is an interactive session. */
1015 packet_set_interactive(interactive);
1017 /* Request authentication agent forwarding if appropriate. */
1018 check_agent_present();
1020 if (options.forward_agent) {
1021 debug("Requesting authentication agent forwarding.");
1022 auth_request_forwarding();
1024 /* Read response from the server. */
1025 type = packet_read();
1027 if (type != SSH_SMSG_SUCCESS)
1028 logit("Warning: Remote host denied authentication agent forwarding.");
1031 /* Initiate port forwardings. */
1032 ssh_init_forwarding();
1034 /* If requested, let ssh continue in the background. */
1035 if (fork_after_authentication_flag)
1036 if (daemon(1, 1) < 0)
1037 fatal("daemon() failed: %.200s", strerror(errno));
1040 * If a command was specified on the command line, execute the
1041 * command now. Otherwise request the server to start a shell.
1043 if (buffer_len(&command) > 0) {
1044 int len = buffer_len(&command);
1047 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1048 packet_start(SSH_CMSG_EXEC_CMD);
1049 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1051 packet_write_wait();
1053 debug("Requesting shell.");
1054 packet_start(SSH_CMSG_EXEC_SHELL);
1056 packet_write_wait();
1059 /* Enter the interactive session. */
1060 return client_loop(have_tty, tty_flag ?
1061 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1065 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1069 id = packet_get_int();
1070 len = buffer_len(&command);
1074 if (type == SSH2_MSG_CHANNEL_FAILURE)
1075 fatal("Request for subsystem '%.*s' failed on channel %d",
1076 len, (u_char *)buffer_ptr(&command), id);
1080 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1084 i = client_global_request_id++;
1085 if (i >= options.num_remote_forwards)
1087 debug("remote forward %s for: listen %d, connect %s:%d",
1088 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1089 options.remote_forwards[i].listen_port,
1090 options.remote_forwards[i].connect_host,
1091 options.remote_forwards[i].connect_port);
1092 if (type == SSH2_MSG_REQUEST_FAILURE)
1093 logit("Warning: remote port forwarding failed for listen "
1094 "port %d", options.remote_forwards[i].listen_port);
1098 ssh_control_listener(void)
1100 struct sockaddr_un addr;
1104 if (options.control_path == NULL || options.control_master <= 0)
1107 memset(&addr, '\0', sizeof(addr));
1108 addr.sun_family = AF_UNIX;
1109 addr_len = offsetof(struct sockaddr_un, sun_path) +
1110 strlen(options.control_path) + 1;
1112 if (strlcpy(addr.sun_path, options.control_path,
1113 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1114 fatal("ControlPath too long");
1116 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1117 fatal("%s socket(): %s\n", __func__, strerror(errno));
1119 old_umask = umask(0177);
1120 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1122 if (errno == EINVAL)
1123 fatal("ControlSocket %s already exists",
1124 options.control_path);
1126 fatal("%s bind(): %s\n", __func__, strerror(errno));
1130 if (listen(control_fd, 64) == -1)
1131 fatal("%s listen(): %s\n", __func__, strerror(errno));
1133 set_nonblock(control_fd);
1136 /* request pty/x11/agent/tcpfwd/shell for channel */
1138 ssh_session2_setup(int id, void *arg)
1140 extern char **environ;
1142 int interactive = tty_flag;
1143 if (options.forward_x11 && getenv("DISPLAY") != NULL) {
1145 /* Get reasonable local authentication information. */
1146 x11_get_proto(&proto, &data);
1147 /* Request forwarding with authentication spoofing. */
1148 debug("Requesting X11 forwarding with authentication spoofing.");
1149 x11_request_forwarding_with_spoofing(id, proto, data);
1151 /* XXX wait for reply */
1154 check_agent_present();
1155 if (options.forward_agent) {
1156 debug("Requesting authentication agent forwarding.");
1157 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1161 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1162 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1164 packet_set_interactive(interactive);
1167 /* open new channel for a session */
1169 ssh_session2_open(void)
1172 int window, packetmax, in, out, err;
1174 if (stdin_null_flag) {
1175 in = open(_PATH_DEVNULL, O_RDONLY);
1177 in = dup(STDIN_FILENO);
1179 out = dup(STDOUT_FILENO);
1180 err = dup(STDERR_FILENO);
1182 if (in < 0 || out < 0 || err < 0)
1183 fatal("dup() in/out/err failed");
1185 /* enable nonblocking unless tty */
1193 window = CHAN_SES_WINDOW_DEFAULT;
1194 packetmax = CHAN_SES_PACKET_DEFAULT;
1200 "session", SSH_CHANNEL_OPENING, in, out, err,
1201 window, packetmax, CHAN_EXTENDED_WRITE,
1202 "client-session", /*nonblock*/0);
1204 debug3("ssh_session2_open: channel_new: %d", c->self);
1206 channel_send_open(c->self);
1208 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1218 /* XXX should be pre-session */
1219 ssh_init_forwarding();
1220 ssh_control_listener();
1222 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1223 id = ssh_session2_open();
1225 /* If requested, let ssh continue in the background. */
1226 if (fork_after_authentication_flag)
1227 if (daemon(1, 1) < 0)
1228 fatal("daemon() failed: %.200s", strerror(errno));
1230 return client_loop(tty_flag, tty_flag ?
1231 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1235 load_public_identity_files(void)
1243 if (options.smartcard_device != NULL &&
1244 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1245 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1247 for (i = 0; keys[i] != NULL; i++) {
1249 memmove(&options.identity_files[1], &options.identity_files[0],
1250 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1251 memmove(&options.identity_keys[1], &options.identity_keys[0],
1252 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1253 options.num_identity_files++;
1254 options.identity_keys[0] = keys[i];
1255 options.identity_files[0] = sc_get_key_label(keys[i]);
1257 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1258 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1262 #endif /* SMARTCARD */
1263 for (; i < options.num_identity_files; i++) {
1264 filename = tilde_expand_filename(options.identity_files[i],
1266 public = key_load_public(filename, NULL);
1267 debug("identity file %s type %d", filename,
1268 public ? public->type : -1);
1269 xfree(options.identity_files[i]);
1270 options.identity_files[i] = filename;
1271 options.identity_keys[i] = public;
1276 control_client_sighandler(int signo)
1278 control_client_terminate = signo;
1282 control_client_sigrelay(int signo)
1284 if (control_server_pid > 1)
1285 kill(control_server_pid, signo);
1289 env_permitted(char *env)
1292 char name[1024], *cp;
1294 strlcpy(name, env, sizeof(name));
1295 if ((cp = strchr(name, '=')) == NULL)
1300 for (i = 0; i < options.num_send_env; i++)
1301 if (match_pattern(name, options.send_env[i]))
1308 control_client(const char *path)
1310 struct sockaddr_un addr;
1311 int i, r, fd, sock, exitval, num_env, addr_len;
1314 extern char **environ;
1317 if (stdin_null_flag) {
1318 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1319 fatal("open(/dev/null): %s", strerror(errno));
1320 if (dup2(fd, STDIN_FILENO) == -1)
1321 fatal("dup2: %s", strerror(errno));
1322 if (fd > STDERR_FILENO)
1326 memset(&addr, '\0', sizeof(addr));
1327 addr.sun_family = AF_UNIX;
1328 addr_len = offsetof(struct sockaddr_un, sun_path) +
1331 if (strlcpy(addr.sun_path, path,
1332 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1333 fatal("ControlPath too long");
1335 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1336 fatal("%s socket(): %s", __func__, strerror(errno));
1338 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1)
1339 fatal("Couldn't connect to %s: %s", path, strerror(errno));
1341 if ((term = getenv("TERM")) == NULL)
1346 flags |= SSHMUX_FLAG_TTY;
1348 flags |= SSHMUX_FLAG_SUBSYS;
1352 /* Send our command to server */
1353 buffer_put_int(&m, mux_command);
1354 buffer_put_int(&m, flags);
1355 if (ssh_msg_send(sock, /* version */1, &m) == -1)
1356 fatal("%s: msg_send", __func__);
1359 /* Get authorisation status and PID of controlee */
1360 if (ssh_msg_recv(sock, &m) == -1)
1361 fatal("%s: msg_recv", __func__);
1362 if (buffer_get_char(&m) != 1)
1363 fatal("%s: wrong version", __func__);
1364 if (buffer_get_int(&m) != 1)
1365 fatal("Connection to master denied");
1366 control_server_pid = buffer_get_int(&m);
1370 switch (mux_command) {
1371 case SSHMUX_COMMAND_ALIVE_CHECK:
1372 fprintf(stderr, "Master running (pid=%d)\r\n",
1373 control_server_pid);
1375 case SSHMUX_COMMAND_TERMINATE:
1376 fprintf(stderr, "Exit request sent.\r\n");
1378 case SSHMUX_COMMAND_OPEN:
1379 /* continue below */
1382 fatal("silly mux_command %d", mux_command);
1385 /* SSHMUX_COMMAND_OPEN */
1386 buffer_put_cstring(&m, term);
1387 buffer_append(&command, "\0", 1);
1388 buffer_put_cstring(&m, buffer_ptr(&command));
1390 if (options.num_send_env == 0 || environ == NULL) {
1391 buffer_put_int(&m, 0);
1393 /* Pass environment */
1395 for (i = 0; environ[i] != NULL; i++)
1396 if (env_permitted(environ[i]))
1397 num_env++; /* Count */
1399 buffer_put_int(&m, num_env);
1401 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1402 if (env_permitted(environ[i])) {
1404 buffer_put_cstring(&m, environ[i]);
1408 if (ssh_msg_send(sock, /* version */1, &m) == -1)
1409 fatal("%s: msg_send", __func__);
1411 mm_send_fd(sock, STDIN_FILENO);
1412 mm_send_fd(sock, STDOUT_FILENO);
1413 mm_send_fd(sock, STDERR_FILENO);
1415 /* Wait for reply, so master has a chance to gather ttymodes */
1417 if (ssh_msg_recv(sock, &m) == -1)
1418 fatal("%s: msg_recv", __func__);
1419 if (buffer_get_char(&m) != 1)
1420 fatal("%s: wrong version", __func__);
1423 signal(SIGHUP, control_client_sighandler);
1424 signal(SIGINT, control_client_sighandler);
1425 signal(SIGTERM, control_client_sighandler);
1426 signal(SIGWINCH, control_client_sigrelay);
1431 /* Stick around until the controlee closes the client_fd */
1433 for (;!control_client_terminate;) {
1434 r = read(sock, &exitval, sizeof(exitval));
1436 debug2("Received EOF from master");
1440 debug2("Received exit status from master %d", exitval);
1441 if (r == -1 && errno != EINTR)
1442 fatal("%s: read %s", __func__, strerror(errno));
1445 if (control_client_terminate)
1446 debug2("Exiting on signal %d", control_client_terminate);
1452 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1453 fprintf(stderr, "Connection to master closed.\r\n");