1 /* $OpenBSD: ssh.c,v 1.294 2006/10/06 02:29:19 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
50 #include <sys/resource.h>
51 #include <sys/ioctl.h>
52 #include <sys/socket.h>
71 #include <netinet/in.h>
72 #include <arpa/inet.h>
74 #include <openssl/evp.h>
75 #include <openssl/err.h>
89 #include "pathnames.h"
91 #include "clientloop.h"
94 #include "sshconnect.h"
101 #include "monitor_fdpass.h"
109 extern char *__progname;
111 /* Flag indicating whether debug mode is on. This can be set on the command line. */
114 /* Flag indicating whether a tty should be allocated */
117 int force_tty_flag = 0;
119 /* don't exec a shell */
120 int no_shell_flag = 0;
123 * Flag indicating that nothing should be read from stdin. This can be set
124 * on the command line.
126 int stdin_null_flag = 0;
129 * Flag indicating that ssh should fork after authentication. This is useful
130 * so that the passphrase can be entered manually, and then ssh goes to the
133 int fork_after_authentication_flag = 0;
136 * General data structure for command line options and options configurable
137 * in configuration files. See readconf.h.
141 /* optional user configfile */
145 * Name of the host we are connecting to. This is the name given on the
146 * command line, or the HostName specified for the user-supplied name in a
147 * configuration file.
151 /* socket address the host resolves to */
152 struct sockaddr_storage hostaddr;
154 /* Private host keys. */
155 Sensitive sensitive_data;
157 /* Original real UID. */
158 uid_t original_real_uid;
159 uid_t original_effective_uid;
161 /* command to be executed */
164 /* Should we execute a command or invoke a subsystem? */
165 int subsystem_flag = 0;
167 /* # of replies received for global requests */
168 static int client_global_request_id = 0;
170 /* pid of proxycommand child process */
171 pid_t proxy_command_pid = 0;
173 /* fd to control socket */
176 /* Multiplexing control command */
177 static u_int mux_command = 0;
179 /* Only used in control client mode */
180 volatile sig_atomic_t control_client_terminate = 0;
181 u_int control_server_pid = 0;
183 /* Prints a help message to the user. This function never returns. */
189 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
190 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
191 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
192 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
193 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
194 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
199 static int ssh_session(void);
200 static int ssh_session2(void);
201 static void load_public_identity_files(void);
202 static void control_client(const char *path);
205 * Main program for the ssh client.
208 main(int ac, char **av)
210 int i, opt, exit_status;
211 char *p, *cp, *line, buf[256];
215 extern int optind, optreset;
220 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
223 __progname = ssh_get_progname(av[0]);
227 * Save the original real uid. It will be needed later (uid-swapping
228 * may clobber the real uid).
230 original_real_uid = getuid();
231 original_effective_uid = geteuid();
234 * Use uid-swapping to give up root privileges for the duration of
235 * option processing. We will re-instantiate the rights when we are
236 * ready to create the privileged port, and will permanently drop
237 * them when the port has been created (actually, when the connection
238 * has been made, as we may need to create the port several times).
242 #ifdef HAVE_SETRLIMIT
243 /* If we are installed setuid root be careful to not drop core. */
244 if (original_real_uid != original_effective_uid) {
246 rlim.rlim_cur = rlim.rlim_max = 0;
247 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
248 fatal("setrlimit failed: %.100s", strerror(errno));
252 pw = getpwuid(original_real_uid);
254 logit("You don't exist, go away!");
257 /* Take a copy of the returned structure. */
261 * Set our umask to something reasonable, as some files are created
262 * with the default umask. This will make them world-readable but
263 * writable only by the owner, which is ok for all files for which we
264 * don't set the modes explicitly.
268 /* Initialize option structure to indicate that no values have been set. */
269 initialize_options(&options);
271 /* Parse command-line arguments. */
275 while ((opt = getopt(ac, av,
276 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
279 options.protocol = SSH_PROTO_1;
282 options.protocol = SSH_PROTO_2;
285 options.address_family = AF_INET;
288 options.address_family = AF_INET6;
294 fork_after_authentication_flag = 1;
298 options.forward_x11 = 0;
301 options.forward_x11 = 1;
304 options.forward_x11 = 1;
305 options.forward_x11_trusted = 1;
308 options.gateway_ports = 1;
311 if (strcmp(optarg, "check") == 0)
312 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
313 else if (strcmp(optarg, "exit") == 0)
314 mux_command = SSHMUX_COMMAND_TERMINATE;
316 fatal("Invalid multiplex command.");
318 case 'P': /* deprecated */
319 options.use_privileged_port = 0;
322 options.forward_agent = 0;
325 options.forward_agent = 1;
328 options.gss_deleg_creds = 0;
331 if (stat(optarg, &st) < 0) {
332 fprintf(stderr, "Warning: Identity file %s "
333 "not accessible: %s.\n", optarg,
337 if (options.num_identity_files >=
338 SSH_MAX_IDENTITY_FILES)
339 fatal("Too many identity files specified "
340 "(max %d)", SSH_MAX_IDENTITY_FILES);
341 options.identity_files[options.num_identity_files++] =
346 options.smartcard_device = xstrdup(optarg);
348 fprintf(stderr, "no support for smartcards.\n");
357 if (debug_flag == 0) {
359 options.log_level = SYSLOG_LEVEL_DEBUG1;
361 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
367 fprintf(stderr, "%s, %s\n",
368 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
373 if (options.tun_open == -1)
374 options.tun_open = SSH_TUNMODE_DEFAULT;
375 options.tun_local = a2tun(optarg, &options.tun_remote);
376 if (options.tun_local == SSH_TUNID_ERR) {
377 fprintf(stderr, "Bad tun device '%s'\n", optarg);
382 options.log_level = SYSLOG_LEVEL_QUIET;
385 if (optarg[0] == '^' && optarg[2] == 0 &&
386 (u_char) optarg[1] >= 64 &&
387 (u_char) optarg[1] < 128)
388 options.escape_char = (u_char) optarg[1] & 31;
389 else if (strlen(optarg) == 1)
390 options.escape_char = (u_char) optarg[0];
391 else if (strcmp(optarg, "none") == 0)
392 options.escape_char = SSH_ESCAPECHAR_NONE;
394 fprintf(stderr, "Bad escape character '%s'.\n",
400 if (ciphers_valid(optarg)) {
402 options.ciphers = xstrdup(optarg);
403 options.cipher = SSH_CIPHER_INVALID;
406 options.cipher = cipher_number(optarg);
407 if (options.cipher == -1) {
409 "Unknown cipher type '%s'\n",
413 if (options.cipher == SSH_CIPHER_3DES)
414 options.ciphers = "3des-cbc";
415 else if (options.cipher == SSH_CIPHER_BLOWFISH)
416 options.ciphers = "blowfish-cbc";
418 options.ciphers = (char *)-1;
422 if (mac_valid(optarg))
423 options.macs = xstrdup(optarg);
425 fprintf(stderr, "Unknown mac type '%s'\n",
431 if (options.control_master == SSHCTL_MASTER_YES)
432 options.control_master = SSHCTL_MASTER_ASK;
434 options.control_master = SSHCTL_MASTER_YES;
437 options.port = a2port(optarg);
438 if (options.port == 0) {
439 fprintf(stderr, "Bad port '%s'\n", optarg);
444 options.user = optarg;
448 if (parse_forward(&fwd, optarg))
449 add_local_forward(&options, &fwd);
452 "Bad local forwarding specification '%s'\n",
459 if (parse_forward(&fwd, optarg)) {
460 add_remote_forward(&options, &fwd);
463 "Bad remote forwarding specification "
470 cp = p = xstrdup(optarg);
471 memset(&fwd, '\0', sizeof(fwd));
472 fwd.connect_host = "socks";
473 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
474 fprintf(stderr, "Bad dynamic forwarding "
475 "specification '%.100s'\n", optarg);
479 fwd.listen_port = a2port(cp);
480 fwd.listen_host = cleanhostname(fwd.listen_host);
482 fwd.listen_port = a2port(fwd.listen_host);
483 fwd.listen_host = NULL;
486 if (fwd.listen_port == 0) {
487 fprintf(stderr, "Bad dynamic port '%s'\n",
491 add_local_forward(&options, &fwd);
496 options.compression = 1;
507 line = xstrdup(optarg);
508 if (process_config_line(&options, host ? host : "",
509 line, "command-line", 0, &dummy) != 0)
517 if (options.control_path != NULL)
518 free(options.control_path);
519 options.control_path = xstrdup(optarg);
522 options.bind_address = optarg;
535 if (ac > 0 && !host && **av != '-') {
536 if (strrchr(*av, '@')) {
538 cp = strrchr(p, '@');
539 if (cp == NULL || cp == p)
547 optind = optreset = 1;
553 /* Check that we got a host name. */
557 SSLeay_add_all_algorithms();
558 ERR_load_crypto_strings();
560 /* Initialize the command to execute on remote host. */
561 buffer_init(&command);
564 * Save the command to execute on the remote host in a buffer. There
565 * is no limit on the length of the command, except by the maximum
566 * packet size. Also sets the tty flag if there is no command.
569 /* No command specified - execute shell on a tty. */
571 if (subsystem_flag) {
573 "You must specify a subsystem to invoke.\n");
577 /* A command has been specified. Store it into the buffer. */
578 for (i = 0; i < ac; i++) {
580 buffer_append(&command, " ", 1);
581 buffer_append(&command, av[i], strlen(av[i]));
585 /* Cannot fork to background if no command. */
586 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
587 fatal("Cannot fork into background without a command to execute.");
589 /* Allocate a tty by default if no command specified. */
590 if (buffer_len(&command) == 0)
596 /* Do not allocate a tty if stdin is not a tty. */
597 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
599 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
604 * Initialize "log" output. Since we are the client all output
605 * actually goes to stderr.
607 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
608 SYSLOG_FACILITY_USER, 1);
611 * Read per-user configuration file. Ignore the system wide config
612 * file if the user specifies a config file on the command line.
614 if (config != NULL) {
615 if (!read_config_file(config, host, &options, 0))
616 fatal("Can't open user config file %.100s: "
617 "%.100s", config, strerror(errno));
619 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
620 _PATH_SSH_USER_CONFFILE);
621 (void)read_config_file(buf, host, &options, 1);
623 /* Read systemwide configuration file after use config. */
624 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
628 /* Fill configuration defaults. */
629 fill_default_options(&options);
631 channel_set_af(options.address_family);
634 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
638 if (options.user == NULL)
639 options.user = xstrdup(pw->pw_name);
641 if (options.hostname != NULL)
642 host = options.hostname;
644 /* Find canonic host name. */
645 if (strchr(host, '.') == 0) {
646 struct addrinfo hints;
647 struct addrinfo *ai = NULL;
649 memset(&hints, 0, sizeof(hints));
650 hints.ai_family = options.address_family;
651 hints.ai_flags = AI_CANONNAME;
652 hints.ai_socktype = SOCK_STREAM;
653 errgai = getaddrinfo(host, NULL, &hints, &ai);
655 if (ai->ai_canonname != NULL)
656 host = xstrdup(ai->ai_canonname);
661 /* force lowercase for hostkey matching */
662 if (options.host_key_alias != NULL) {
663 for (p = options.host_key_alias; *p; p++)
665 *p = (char)tolower(*p);
668 /* Get default port if port has not been set. */
669 if (options.port == 0) {
670 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
671 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
674 if (options.proxy_command != NULL &&
675 strcmp(options.proxy_command, "none") == 0)
676 options.proxy_command = NULL;
677 if (options.control_path != NULL &&
678 strcmp(options.control_path, "none") == 0)
679 options.control_path = NULL;
681 if (options.control_path != NULL) {
682 char thishost[NI_MAXHOST];
684 if (gethostname(thishost, sizeof(thishost)) == -1)
685 fatal("gethostname: %s", strerror(errno));
686 snprintf(buf, sizeof(buf), "%d", options.port);
687 cp = tilde_expand_filename(options.control_path,
689 options.control_path = percent_expand(cp, "p", buf, "h", host,
690 "r", options.user, "l", thishost, (char *)NULL);
693 if (mux_command != 0 && options.control_path == NULL)
694 fatal("No ControlPath specified for \"-O\" command");
695 if (options.control_path != NULL)
696 control_client(options.control_path);
698 /* Open a connection to the remote host. */
699 if (ssh_connect(host, &hostaddr, options.port,
700 options.address_family, options.connection_attempts,
702 options.use_privileged_port,
704 original_effective_uid == 0 && options.use_privileged_port,
706 options.proxy_command) != 0)
710 * If we successfully made the connection, load the host private key
711 * in case we will need it later for combined rsa-rhosts
712 * authentication. This must be done before releasing extra
713 * privileges, because the file is only readable by root.
714 * If we cannot access the private keys, load the public keys
715 * instead and try to execute the ssh-keysign helper instead.
717 sensitive_data.nkeys = 0;
718 sensitive_data.keys = NULL;
719 sensitive_data.external_keysign = 0;
720 if (options.rhosts_rsa_authentication ||
721 options.hostbased_authentication) {
722 sensitive_data.nkeys = 3;
723 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
727 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
728 _PATH_HOST_KEY_FILE, "", NULL, NULL);
729 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
730 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
731 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
732 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
735 if (options.hostbased_authentication == 1 &&
736 sensitive_data.keys[0] == NULL &&
737 sensitive_data.keys[1] == NULL &&
738 sensitive_data.keys[2] == NULL) {
739 sensitive_data.keys[1] = key_load_public(
740 _PATH_HOST_DSA_KEY_FILE, NULL);
741 sensitive_data.keys[2] = key_load_public(
742 _PATH_HOST_RSA_KEY_FILE, NULL);
743 sensitive_data.external_keysign = 1;
747 * Get rid of any extra privileges that we may have. We will no
748 * longer need them. Also, extra privileges could make it very hard
749 * to read identity files and other non-world-readable files from the
750 * user's home directory if it happens to be on a NFS volume where
751 * root is mapped to nobody.
753 if (original_effective_uid == 0) {
755 permanently_set_uid(pw);
759 * Now that we are back to our own permissions, create ~/.ssh
760 * directory if it doesn't already exist.
762 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
763 if (stat(buf, &st) < 0)
764 if (mkdir(buf, 0700) < 0)
765 error("Could not create directory '%.200s'.", buf);
767 /* load options.identity_files */
768 load_public_identity_files();
770 /* Expand ~ in known host file names. */
772 options.system_hostfile =
773 tilde_expand_filename(options.system_hostfile, original_real_uid);
774 options.user_hostfile =
775 tilde_expand_filename(options.user_hostfile, original_real_uid);
776 options.system_hostfile2 =
777 tilde_expand_filename(options.system_hostfile2, original_real_uid);
778 options.user_hostfile2 =
779 tilde_expand_filename(options.user_hostfile2, original_real_uid);
781 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
783 /* Log into the remote system. This never returns if the login fails. */
784 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
786 /* We no longer need the private host keys. Clear them now. */
787 if (sensitive_data.nkeys != 0) {
788 for (i = 0; i < sensitive_data.nkeys; i++) {
789 if (sensitive_data.keys[i] != NULL) {
790 /* Destroys contents safely */
791 debug3("clear hostkey %d", i);
792 key_free(sensitive_data.keys[i]);
793 sensitive_data.keys[i] = NULL;
796 xfree(sensitive_data.keys);
798 for (i = 0; i < options.num_identity_files; i++) {
799 if (options.identity_files[i]) {
800 xfree(options.identity_files[i]);
801 options.identity_files[i] = NULL;
803 if (options.identity_keys[i]) {
804 key_free(options.identity_keys[i]);
805 options.identity_keys[i] = NULL;
809 exit_status = compat20 ? ssh_session2() : ssh_session();
812 if (options.control_path != NULL && control_fd != -1)
813 unlink(options.control_path);
816 * Send SIGHUP to proxy command if used. We don't wait() in
817 * case it hangs and instead rely on init to reap the child
819 if (proxy_command_pid > 1)
820 kill(proxy_command_pid, SIGHUP);
826 ssh_init_forwarding(void)
831 /* Initiate local TCP/IP port forwardings. */
832 for (i = 0; i < options.num_local_forwards; i++) {
833 debug("Local connections to %.200s:%d forwarded to remote "
835 (options.local_forwards[i].listen_host == NULL) ?
836 (options.gateway_ports ? "*" : "LOCALHOST") :
837 options.local_forwards[i].listen_host,
838 options.local_forwards[i].listen_port,
839 options.local_forwards[i].connect_host,
840 options.local_forwards[i].connect_port);
841 success += channel_setup_local_fwd_listener(
842 options.local_forwards[i].listen_host,
843 options.local_forwards[i].listen_port,
844 options.local_forwards[i].connect_host,
845 options.local_forwards[i].connect_port,
846 options.gateway_ports);
848 if (i > 0 && success != i && options.exit_on_forward_failure)
849 fatal("Could not request local forwarding.");
850 if (i > 0 && success == 0)
851 error("Could not request local forwarding.");
853 /* Initiate remote TCP/IP port forwardings. */
854 for (i = 0; i < options.num_remote_forwards; i++) {
855 debug("Remote connections from %.200s:%d forwarded to "
856 "local address %.200s:%d",
857 (options.remote_forwards[i].listen_host == NULL) ?
858 "LOCALHOST" : options.remote_forwards[i].listen_host,
859 options.remote_forwards[i].listen_port,
860 options.remote_forwards[i].connect_host,
861 options.remote_forwards[i].connect_port);
862 if (channel_request_remote_forwarding(
863 options.remote_forwards[i].listen_host,
864 options.remote_forwards[i].listen_port,
865 options.remote_forwards[i].connect_host,
866 options.remote_forwards[i].connect_port) < 0) {
867 if (options.exit_on_forward_failure)
868 fatal("Could not request remote forwarding.");
870 logit("Warning: Could not request remote "
877 check_agent_present(void)
879 if (options.forward_agent) {
880 /* Clear agent forwarding if we don't have an agent. */
881 if (!ssh_agent_present())
882 options.forward_agent = 0;
896 /* Enable compression if requested. */
897 if (options.compression) {
898 debug("Requesting compression at level %d.", options.compression_level);
900 if (options.compression_level < 1 || options.compression_level > 9)
901 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
903 /* Send the request. */
904 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
905 packet_put_int(options.compression_level);
908 type = packet_read();
909 if (type == SSH_SMSG_SUCCESS)
910 packet_start_compression(options.compression_level);
911 else if (type == SSH_SMSG_FAILURE)
912 logit("Warning: Remote host refused compression.");
914 packet_disconnect("Protocol error waiting for compression response.");
916 /* Allocate a pseudo tty if appropriate. */
918 debug("Requesting pty.");
920 /* Start the packet. */
921 packet_start(SSH_CMSG_REQUEST_PTY);
923 /* Store TERM in the packet. There is no limit on the
924 length of the string. */
928 packet_put_cstring(cp);
930 /* Store window size in the packet. */
931 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
932 memset(&ws, 0, sizeof(ws));
933 packet_put_int((u_int)ws.ws_row);
934 packet_put_int((u_int)ws.ws_col);
935 packet_put_int((u_int)ws.ws_xpixel);
936 packet_put_int((u_int)ws.ws_ypixel);
938 /* Store tty modes in the packet. */
939 tty_make_modes(fileno(stdin), NULL);
941 /* Send the packet, and wait for it to leave. */
945 /* Read response from the server. */
946 type = packet_read();
947 if (type == SSH_SMSG_SUCCESS) {
950 } else if (type == SSH_SMSG_FAILURE)
951 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
953 packet_disconnect("Protocol error waiting for pty request response.");
955 /* Request X11 forwarding if enabled and DISPLAY is set. */
956 display = getenv("DISPLAY");
957 if (options.forward_x11 && display != NULL) {
959 /* Get reasonable local authentication information. */
960 client_x11_get_proto(display, options.xauth_location,
961 options.forward_x11_trusted, &proto, &data);
962 /* Request forwarding with authentication spoofing. */
963 debug("Requesting X11 forwarding with authentication spoofing.");
964 x11_request_forwarding_with_spoofing(0, display, proto, data);
966 /* Read response from the server. */
967 type = packet_read();
968 if (type == SSH_SMSG_SUCCESS) {
970 } else if (type == SSH_SMSG_FAILURE) {
971 logit("Warning: Remote host denied X11 forwarding.");
973 packet_disconnect("Protocol error waiting for X11 forwarding");
976 /* Tell the packet module whether this is an interactive session. */
977 packet_set_interactive(interactive);
979 /* Request authentication agent forwarding if appropriate. */
980 check_agent_present();
982 if (options.forward_agent) {
983 debug("Requesting authentication agent forwarding.");
984 auth_request_forwarding();
986 /* Read response from the server. */
987 type = packet_read();
989 if (type != SSH_SMSG_SUCCESS)
990 logit("Warning: Remote host denied authentication agent forwarding.");
993 /* Initiate port forwardings. */
994 ssh_init_forwarding();
996 /* If requested, let ssh continue in the background. */
997 if (fork_after_authentication_flag)
998 if (daemon(1, 1) < 0)
999 fatal("daemon() failed: %.200s", strerror(errno));
1002 * If a command was specified on the command line, execute the
1003 * command now. Otherwise request the server to start a shell.
1005 if (buffer_len(&command) > 0) {
1006 int len = buffer_len(&command);
1009 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
1010 packet_start(SSH_CMSG_EXEC_CMD);
1011 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1013 packet_write_wait();
1015 debug("Requesting shell.");
1016 packet_start(SSH_CMSG_EXEC_SHELL);
1018 packet_write_wait();
1021 /* Enter the interactive session. */
1022 return client_loop(have_tty, tty_flag ?
1023 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1027 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
1031 id = packet_get_int();
1032 len = buffer_len(&command);
1036 if (type == SSH2_MSG_CHANNEL_FAILURE)
1037 fatal("Request for subsystem '%.*s' failed on channel %d",
1038 len, (u_char *)buffer_ptr(&command), id);
1042 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1046 i = client_global_request_id++;
1047 if (i >= options.num_remote_forwards)
1049 debug("remote forward %s for: listen %d, connect %s:%d",
1050 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1051 options.remote_forwards[i].listen_port,
1052 options.remote_forwards[i].connect_host,
1053 options.remote_forwards[i].connect_port);
1054 if (type == SSH2_MSG_REQUEST_FAILURE) {
1055 if (options.exit_on_forward_failure)
1056 fatal("Error: remote port forwarding failed for "
1058 options.remote_forwards[i].listen_port);
1060 logit("Warning: remote port forwarding failed for "
1062 options.remote_forwards[i].listen_port);
1067 ssh_control_listener(void)
1069 struct sockaddr_un addr;
1073 if (options.control_path == NULL ||
1074 options.control_master == SSHCTL_MASTER_NO)
1077 debug("setting up multiplex master socket");
1079 memset(&addr, '\0', sizeof(addr));
1080 addr.sun_family = AF_UNIX;
1081 addr_len = offsetof(struct sockaddr_un, sun_path) +
1082 strlen(options.control_path) + 1;
1084 if (strlcpy(addr.sun_path, options.control_path,
1085 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1086 fatal("ControlPath too long");
1088 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1089 fatal("%s socket(): %s", __func__, strerror(errno));
1091 old_umask = umask(0177);
1092 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1094 if (errno == EINVAL || errno == EADDRINUSE)
1095 fatal("ControlSocket %s already exists",
1096 options.control_path);
1098 fatal("%s bind(): %s", __func__, strerror(errno));
1102 if (listen(control_fd, 64) == -1)
1103 fatal("%s listen(): %s", __func__, strerror(errno));
1105 set_nonblock(control_fd);
1108 /* request pty/x11/agent/tcpfwd/shell for channel */
1110 ssh_session2_setup(int id, void *arg)
1112 extern char **environ;
1113 const char *display;
1114 int interactive = tty_flag;
1116 display = getenv("DISPLAY");
1117 if (options.forward_x11 && display != NULL) {
1119 /* Get reasonable local authentication information. */
1120 client_x11_get_proto(display, options.xauth_location,
1121 options.forward_x11_trusted, &proto, &data);
1122 /* Request forwarding with authentication spoofing. */
1123 debug("Requesting X11 forwarding with authentication spoofing.");
1124 x11_request_forwarding_with_spoofing(id, display, proto, data);
1126 /* XXX wait for reply */
1129 check_agent_present();
1130 if (options.forward_agent) {
1131 debug("Requesting authentication agent forwarding.");
1132 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1136 if (options.tun_open != SSH_TUNMODE_NO) {
1140 debug("Requesting tun.");
1141 if ((fd = tun_open(options.tun_local,
1142 options.tun_open)) >= 0) {
1143 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1144 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1147 #if defined(SSH_TUN_FILTER)
1148 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1149 channel_register_filter(c->self, sys_tun_infilter,
1152 packet_start(SSH2_MSG_CHANNEL_OPEN);
1153 packet_put_cstring("tun@openssh.com");
1154 packet_put_int(c->self);
1155 packet_put_int(c->local_window_max);
1156 packet_put_int(c->local_maxpacket);
1157 packet_put_int(options.tun_open);
1158 packet_put_int(options.tun_remote);
1163 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1164 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1166 packet_set_interactive(interactive);
1169 /* open new channel for a session */
1171 ssh_session2_open(void)
1174 int window, packetmax, in, out, err;
1176 if (stdin_null_flag) {
1177 in = open(_PATH_DEVNULL, O_RDONLY);
1179 in = dup(STDIN_FILENO);
1181 out = dup(STDOUT_FILENO);
1182 err = dup(STDERR_FILENO);
1184 if (in < 0 || out < 0 || err < 0)
1185 fatal("dup() in/out/err failed");
1187 /* enable nonblocking unless tty */
1195 window = CHAN_SES_WINDOW_DEFAULT;
1196 packetmax = CHAN_SES_PACKET_DEFAULT;
1202 "session", SSH_CHANNEL_OPENING, in, out, err,
1203 window, packetmax, CHAN_EXTENDED_WRITE,
1204 "client-session", /*nonblock*/0);
1206 debug3("ssh_session2_open: channel_new: %d", c->self);
1208 channel_send_open(c->self);
1210 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1220 /* XXX should be pre-session */
1221 ssh_init_forwarding();
1222 ssh_control_listener();
1224 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1225 id = ssh_session2_open();
1227 /* Execute a local command */
1228 if (options.local_command != NULL &&
1229 options.permit_local_command)
1230 ssh_local_cmd(options.local_command);
1232 /* If requested, let ssh continue in the background. */
1233 if (fork_after_authentication_flag)
1234 if (daemon(1, 1) < 0)
1235 fatal("daemon() failed: %.200s", strerror(errno));
1237 return client_loop(tty_flag, tty_flag ?
1238 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1242 load_public_identity_files(void)
1244 char *filename, *cp, thishost[NI_MAXHOST];
1251 if (options.smartcard_device != NULL &&
1252 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1253 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1255 for (i = 0; keys[i] != NULL; i++) {
1257 memmove(&options.identity_files[1], &options.identity_files[0],
1258 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1259 memmove(&options.identity_keys[1], &options.identity_keys[0],
1260 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1261 options.num_identity_files++;
1262 options.identity_keys[0] = keys[i];
1263 options.identity_files[0] = sc_get_key_label(keys[i]);
1265 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1266 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1270 #endif /* SMARTCARD */
1271 if ((pw = getpwuid(original_real_uid)) == NULL)
1272 fatal("load_public_identity_files: getpwuid failed");
1273 if (gethostname(thishost, sizeof(thishost)) == -1)
1274 fatal("load_public_identity_files: gethostname: %s",
1276 for (; i < options.num_identity_files; i++) {
1277 cp = tilde_expand_filename(options.identity_files[i],
1279 filename = percent_expand(cp, "d", pw->pw_dir,
1280 "u", pw->pw_name, "l", thishost, "h", host,
1281 "r", options.user, (char *)NULL);
1283 public = key_load_public(filename, NULL);
1284 debug("identity file %s type %d", filename,
1285 public ? public->type : -1);
1286 xfree(options.identity_files[i]);
1287 options.identity_files[i] = filename;
1288 options.identity_keys[i] = public;
1293 control_client_sighandler(int signo)
1295 control_client_terminate = signo;
1299 control_client_sigrelay(int signo)
1301 if (control_server_pid > 1)
1302 kill(control_server_pid, signo);
1306 env_permitted(char *env)
1309 char name[1024], *cp;
1311 if ((cp = strchr(env, '=')) == NULL || cp == env)
1313 ret = snprintf(name, sizeof(name), "%.*s", (int)(cp - env), env);
1314 if (ret <= 0 || (size_t)ret >= sizeof(name))
1315 fatal("env_permitted: name '%.100s...' too long", env);
1317 for (i = 0; i < options.num_send_env; i++)
1318 if (match_pattern(name, options.send_env[i]))
1325 control_client(const char *path)
1327 struct sockaddr_un addr;
1328 int i, r, fd, sock, exitval, num_env, addr_len;
1331 extern char **environ;
1334 if (mux_command == 0)
1335 mux_command = SSHMUX_COMMAND_OPEN;
1337 switch (options.control_master) {
1338 case SSHCTL_MASTER_AUTO:
1339 case SSHCTL_MASTER_AUTO_ASK:
1340 debug("auto-mux: Trying existing master");
1342 case SSHCTL_MASTER_NO:
1348 memset(&addr, '\0', sizeof(addr));
1349 addr.sun_family = AF_UNIX;
1350 addr_len = offsetof(struct sockaddr_un, sun_path) +
1353 if (strlcpy(addr.sun_path, path,
1354 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1355 fatal("ControlPath too long");
1357 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1358 fatal("%s socket(): %s", __func__, strerror(errno));
1360 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1361 if (mux_command != SSHMUX_COMMAND_OPEN) {
1362 fatal("Control socket connect(%.100s): %s", path,
1365 if (errno == ENOENT)
1366 debug("Control socket \"%.100s\" does not exist", path);
1368 error("Control socket connect(%.100s): %s", path,
1375 if (stdin_null_flag) {
1376 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1377 fatal("open(/dev/null): %s", strerror(errno));
1378 if (dup2(fd, STDIN_FILENO) == -1)
1379 fatal("dup2: %s", strerror(errno));
1380 if (fd > STDERR_FILENO)
1384 term = getenv("TERM");
1388 flags |= SSHMUX_FLAG_TTY;
1390 flags |= SSHMUX_FLAG_SUBSYS;
1391 if (options.forward_x11)
1392 flags |= SSHMUX_FLAG_X11_FWD;
1393 if (options.forward_agent)
1394 flags |= SSHMUX_FLAG_AGENT_FWD;
1398 /* Send our command to server */
1399 buffer_put_int(&m, mux_command);
1400 buffer_put_int(&m, flags);
1401 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1402 fatal("%s: msg_send", __func__);
1405 /* Get authorisation status and PID of controlee */
1406 if (ssh_msg_recv(sock, &m) == -1)
1407 fatal("%s: msg_recv", __func__);
1408 if (buffer_get_char(&m) != SSHMUX_VER)
1409 fatal("%s: wrong version", __func__);
1410 if (buffer_get_int(&m) != 1)
1411 fatal("Connection to master denied");
1412 control_server_pid = buffer_get_int(&m);
1416 switch (mux_command) {
1417 case SSHMUX_COMMAND_ALIVE_CHECK:
1418 fprintf(stderr, "Master running (pid=%d)\r\n",
1419 control_server_pid);
1421 case SSHMUX_COMMAND_TERMINATE:
1422 fprintf(stderr, "Exit request sent.\r\n");
1424 case SSHMUX_COMMAND_OPEN:
1425 /* continue below */
1428 fatal("silly mux_command %d", mux_command);
1431 /* SSHMUX_COMMAND_OPEN */
1432 buffer_put_cstring(&m, term ? term : "");
1433 buffer_append(&command, "\0", 1);
1434 buffer_put_cstring(&m, buffer_ptr(&command));
1436 if (options.num_send_env == 0 || environ == NULL) {
1437 buffer_put_int(&m, 0);
1439 /* Pass environment */
1441 for (i = 0; environ[i] != NULL; i++)
1442 if (env_permitted(environ[i]))
1443 num_env++; /* Count */
1445 buffer_put_int(&m, num_env);
1447 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1448 if (env_permitted(environ[i])) {
1450 buffer_put_cstring(&m, environ[i]);
1454 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1455 fatal("%s: msg_send", __func__);
1457 mm_send_fd(sock, STDIN_FILENO);
1458 mm_send_fd(sock, STDOUT_FILENO);
1459 mm_send_fd(sock, STDERR_FILENO);
1461 /* Wait for reply, so master has a chance to gather ttymodes */
1463 if (ssh_msg_recv(sock, &m) == -1)
1464 fatal("%s: msg_recv", __func__);
1465 if (buffer_get_char(&m) != SSHMUX_VER)
1466 fatal("%s: wrong version", __func__);
1469 signal(SIGHUP, control_client_sighandler);
1470 signal(SIGINT, control_client_sighandler);
1471 signal(SIGTERM, control_client_sighandler);
1472 signal(SIGWINCH, control_client_sigrelay);
1477 /* Stick around until the controlee closes the client_fd */
1479 for (;!control_client_terminate;) {
1480 r = read(sock, &exitval, sizeof(exitval));
1482 debug2("Received EOF from master");
1486 debug2("Received exit status from master %d", exitval);
1487 if (r == -1 && errno != EINTR)
1488 fatal("%s: read %s", __func__, strerror(errno));
1491 if (control_client_terminate)
1492 debug2("Exiting on signal %d", control_client_terminate);
1498 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1499 fprintf(stderr, "Connection to master closed.\r\n");