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.
44 #include <sys/types.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
48 #include <sys/resource.h>
49 #include <sys/ioctl.h>
58 #include <openssl/evp.h>
59 #include <openssl/err.h>
74 #include "pathnames.h"
76 #include "clientloop.h"
79 #include "sshconnect.h"
86 #include "monitor_fdpass.h"
93 extern char *__progname;
95 /* Flag indicating whether debug mode is on. This can be set on the command line. */
98 /* Flag indicating whether a tty should be allocated */
101 int force_tty_flag = 0;
103 /* don't exec a shell */
104 int no_shell_flag = 0;
107 * Flag indicating that nothing should be read from stdin. This can be set
108 * on the command line.
110 int stdin_null_flag = 0;
113 * Flag indicating that ssh should fork after authentication. This is useful
114 * so that the passphrase can be entered manually, and then ssh goes to the
117 int fork_after_authentication_flag = 0;
120 * General data structure for command line options and options configurable
121 * in configuration files. See readconf.h.
125 /* optional user configfile */
129 * Name of the host we are connecting to. This is the name given on the
130 * command line, or the HostName specified for the user-supplied name in a
131 * configuration file.
135 /* socket address the host resolves to */
136 struct sockaddr_storage hostaddr;
138 /* Private host keys. */
139 Sensitive sensitive_data;
141 /* Original real UID. */
142 uid_t original_real_uid;
143 uid_t original_effective_uid;
145 /* command to be executed */
148 /* Should we execute a command or invoke a subsystem? */
149 int subsystem_flag = 0;
151 /* # of replies received for global requests */
152 static int client_global_request_id = 0;
154 /* pid of proxycommand child process */
155 pid_t proxy_command_pid = 0;
157 /* fd to control socket */
160 /* Multiplexing control command */
161 static u_int mux_command = 0;
163 /* Only used in control client mode */
164 volatile sig_atomic_t control_client_terminate = 0;
165 u_int control_server_pid = 0;
167 /* Prints a help message to the user. This function never returns. */
173 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
174 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
175 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
176 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
177 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
178 " [-w tunnel:tunnel] [user@]hostname [command]\n"
183 static int ssh_session(void);
184 static int ssh_session2(void);
185 static void load_public_identity_files(void);
186 static void control_client(const char *path);
189 * Main program for the ssh client.
192 main(int ac, char **av)
194 int i, opt, exit_status;
195 char *p, *cp, *line, buf[256];
199 extern int optind, optreset;
204 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
207 __progname = ssh_get_progname(av[0]);
211 * Save the original real uid. It will be needed later (uid-swapping
212 * may clobber the real uid).
214 original_real_uid = getuid();
215 original_effective_uid = geteuid();
218 * Use uid-swapping to give up root privileges for the duration of
219 * option processing. We will re-instantiate the rights when we are
220 * ready to create the privileged port, and will permanently drop
221 * them when the port has been created (actually, when the connection
222 * has been made, as we may need to create the port several times).
226 #ifdef HAVE_SETRLIMIT
227 /* If we are installed setuid root be careful to not drop core. */
228 if (original_real_uid != original_effective_uid) {
230 rlim.rlim_cur = rlim.rlim_max = 0;
231 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
232 fatal("setrlimit failed: %.100s", strerror(errno));
236 pw = getpwuid(original_real_uid);
238 logit("You don't exist, go away!");
241 /* Take a copy of the returned structure. */
245 * Set our umask to something reasonable, as some files are created
246 * with the default umask. This will make them world-readable but
247 * writable only by the owner, which is ok for all files for which we
248 * don't set the modes explicitly.
252 /* Initialize option structure to indicate that no values have been set. */
253 initialize_options(&options);
255 /* Parse command-line arguments. */
259 while ((opt = getopt(ac, av,
260 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
263 options.protocol = SSH_PROTO_1;
266 options.protocol = SSH_PROTO_2;
269 options.address_family = AF_INET;
272 options.address_family = AF_INET6;
278 fork_after_authentication_flag = 1;
282 options.forward_x11 = 0;
285 options.forward_x11 = 1;
288 options.forward_x11 = 1;
289 options.forward_x11_trusted = 1;
292 options.gateway_ports = 1;
295 if (strcmp(optarg, "check") == 0)
296 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
297 else if (strcmp(optarg, "exit") == 0)
298 mux_command = SSHMUX_COMMAND_TERMINATE;
300 fatal("Invalid multiplex command.");
302 case 'P': /* deprecated */
303 options.use_privileged_port = 0;
306 options.forward_agent = 0;
309 options.forward_agent = 1;
312 options.gss_deleg_creds = 0;
315 if (stat(optarg, &st) < 0) {
316 fprintf(stderr, "Warning: Identity file %s "
317 "not accessible: %s.\n", optarg,
321 if (options.num_identity_files >=
322 SSH_MAX_IDENTITY_FILES)
323 fatal("Too many identity files specified "
324 "(max %d)", SSH_MAX_IDENTITY_FILES);
325 options.identity_files[options.num_identity_files++] =
330 options.smartcard_device = xstrdup(optarg);
332 fprintf(stderr, "no support for smartcards.\n");
341 if (debug_flag == 0) {
343 options.log_level = SYSLOG_LEVEL_DEBUG1;
345 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
351 fprintf(stderr, "%s, %s\n",
352 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
357 if (options.tun_open == -1)
358 options.tun_open = SSH_TUNMODE_DEFAULT;
359 options.tun_local = a2tun(optarg, &options.tun_remote);
360 if (options.tun_local == SSH_TUNID_ERR) {
361 fprintf(stderr, "Bad tun device '%s'\n", optarg);
366 options.log_level = SYSLOG_LEVEL_QUIET;
369 if (optarg[0] == '^' && optarg[2] == 0 &&
370 (u_char) optarg[1] >= 64 &&
371 (u_char) optarg[1] < 128)
372 options.escape_char = (u_char) optarg[1] & 31;
373 else if (strlen(optarg) == 1)
374 options.escape_char = (u_char) optarg[0];
375 else if (strcmp(optarg, "none") == 0)
376 options.escape_char = SSH_ESCAPECHAR_NONE;
378 fprintf(stderr, "Bad escape character '%s'.\n",
384 if (ciphers_valid(optarg)) {
386 options.ciphers = xstrdup(optarg);
387 options.cipher = SSH_CIPHER_INVALID;
390 options.cipher = cipher_number(optarg);
391 if (options.cipher == -1) {
393 "Unknown cipher type '%s'\n",
397 if (options.cipher == SSH_CIPHER_3DES)
398 options.ciphers = "3des-cbc";
399 else if (options.cipher == SSH_CIPHER_BLOWFISH)
400 options.ciphers = "blowfish-cbc";
402 options.ciphers = (char *)-1;
406 if (mac_valid(optarg))
407 options.macs = xstrdup(optarg);
409 fprintf(stderr, "Unknown mac type '%s'\n",
415 if (options.control_master == SSHCTL_MASTER_YES)
416 options.control_master = SSHCTL_MASTER_ASK;
418 options.control_master = SSHCTL_MASTER_YES;
421 options.port = a2port(optarg);
422 if (options.port == 0) {
423 fprintf(stderr, "Bad port '%s'\n", optarg);
428 options.user = optarg;
432 if (parse_forward(&fwd, optarg))
433 add_local_forward(&options, &fwd);
436 "Bad local forwarding specification '%s'\n",
443 if (parse_forward(&fwd, optarg)) {
444 add_remote_forward(&options, &fwd);
447 "Bad remote forwarding specification "
454 cp = p = xstrdup(optarg);
455 memset(&fwd, '\0', sizeof(fwd));
456 fwd.connect_host = "socks";
457 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
458 fprintf(stderr, "Bad dynamic forwarding "
459 "specification '%.100s'\n", optarg);
463 fwd.listen_port = a2port(cp);
464 fwd.listen_host = cleanhostname(fwd.listen_host);
466 fwd.listen_port = a2port(fwd.listen_host);
467 fwd.listen_host = NULL;
470 if (fwd.listen_port == 0) {
471 fprintf(stderr, "Bad dynamic port '%s'\n",
475 add_local_forward(&options, &fwd);
480 options.compression = 1;
491 line = xstrdup(optarg);
492 if (process_config_line(&options, host ? host : "",
493 line, "command-line", 0, &dummy) != 0)
501 if (options.control_path != NULL)
502 free(options.control_path);
503 options.control_path = xstrdup(optarg);
506 options.bind_address = optarg;
519 if (ac > 0 && !host && **av != '-') {
520 if (strrchr(*av, '@')) {
522 cp = strrchr(p, '@');
523 if (cp == NULL || cp == p)
531 optind = optreset = 1;
537 /* Check that we got a host name. */
541 SSLeay_add_all_algorithms();
542 ERR_load_crypto_strings();
544 /* Initialize the command to execute on remote host. */
545 buffer_init(&command);
548 * Save the command to execute on the remote host in a buffer. There
549 * is no limit on the length of the command, except by the maximum
550 * packet size. Also sets the tty flag if there is no command.
553 /* No command specified - execute shell on a tty. */
555 if (subsystem_flag) {
557 "You must specify a subsystem to invoke.\n");
561 /* A command has been specified. Store it into the buffer. */
562 for (i = 0; i < ac; i++) {
564 buffer_append(&command, " ", 1);
565 buffer_append(&command, av[i], strlen(av[i]));
569 /* Cannot fork to background if no command. */
570 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
571 fatal("Cannot fork into background without a command to execute.");
573 /* Allocate a tty by default if no command specified. */
574 if (buffer_len(&command) == 0)
580 /* Do not allocate a tty if stdin is not a tty. */
581 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
583 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
588 * Initialize "log" output. Since we are the client all output
589 * actually goes to stderr.
591 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
592 SYSLOG_FACILITY_USER, 1);
595 * Read per-user configuration file. Ignore the system wide config
596 * file if the user specifies a config file on the command line.
598 if (config != NULL) {
599 if (!read_config_file(config, host, &options, 0))
600 fatal("Can't open user config file %.100s: "
601 "%.100s", config, strerror(errno));
603 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
604 _PATH_SSH_USER_CONFFILE);
605 (void)read_config_file(buf, host, &options, 1);
607 /* Read systemwide configuration file after use config. */
608 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
612 /* Fill configuration defaults. */
613 fill_default_options(&options);
615 channel_set_af(options.address_family);
618 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
622 if (options.user == NULL)
623 options.user = xstrdup(pw->pw_name);
625 if (options.hostname != NULL)
626 host = options.hostname;
628 /* force lowercase for hostkey matching */
629 if (options.host_key_alias != NULL) {
630 for (p = options.host_key_alias; *p; p++)
632 *p = (char)tolower(*p);
635 /* Get default port if port has not been set. */
636 if (options.port == 0) {
637 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
638 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
641 if (options.proxy_command != NULL &&
642 strcmp(options.proxy_command, "none") == 0)
643 options.proxy_command = NULL;
644 if (options.control_path != NULL &&
645 strcmp(options.control_path, "none") == 0)
646 options.control_path = NULL;
648 if (options.control_path != NULL) {
651 if (gethostname(me, sizeof(me)) == -1)
652 fatal("gethostname: %s", strerror(errno));
653 snprintf(buf, sizeof(buf), "%d", options.port);
654 cp = tilde_expand_filename(options.control_path,
656 options.control_path = percent_expand(cp, "p", buf, "h", host,
657 "r", options.user, "l", me, (char *)NULL);
660 if (mux_command != 0 && options.control_path == NULL)
661 fatal("No ControlPath specified for \"-O\" command");
662 if (options.control_path != NULL)
663 control_client(options.control_path);
665 /* Open a connection to the remote host. */
666 if (ssh_connect(host, &hostaddr, options.port,
667 options.address_family, options.connection_attempts,
669 options.use_privileged_port,
671 original_effective_uid == 0 && options.use_privileged_port,
673 options.proxy_command) != 0)
677 * If we successfully made the connection, load the host private key
678 * in case we will need it later for combined rsa-rhosts
679 * authentication. This must be done before releasing extra
680 * privileges, because the file is only readable by root.
681 * If we cannot access the private keys, load the public keys
682 * instead and try to execute the ssh-keysign helper instead.
684 sensitive_data.nkeys = 0;
685 sensitive_data.keys = NULL;
686 sensitive_data.external_keysign = 0;
687 if (options.rhosts_rsa_authentication ||
688 options.hostbased_authentication) {
689 sensitive_data.nkeys = 3;
690 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
694 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
695 _PATH_HOST_KEY_FILE, "", NULL);
696 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
697 _PATH_HOST_DSA_KEY_FILE, "", NULL);
698 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
699 _PATH_HOST_RSA_KEY_FILE, "", NULL);
702 if (options.hostbased_authentication == 1 &&
703 sensitive_data.keys[0] == NULL &&
704 sensitive_data.keys[1] == NULL &&
705 sensitive_data.keys[2] == NULL) {
706 sensitive_data.keys[1] = key_load_public(
707 _PATH_HOST_DSA_KEY_FILE, NULL);
708 sensitive_data.keys[2] = key_load_public(
709 _PATH_HOST_RSA_KEY_FILE, NULL);
710 sensitive_data.external_keysign = 1;
714 * Get rid of any extra privileges that we may have. We will no
715 * longer need them. Also, extra privileges could make it very hard
716 * to read identity files and other non-world-readable files from the
717 * user's home directory if it happens to be on a NFS volume where
718 * root is mapped to nobody.
720 if (original_effective_uid == 0) {
722 permanently_set_uid(pw);
726 * Now that we are back to our own permissions, create ~/.ssh
727 * directory if it doesn't already exist.
729 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
730 if (stat(buf, &st) < 0)
731 if (mkdir(buf, 0700) < 0)
732 error("Could not create directory '%.200s'.", buf);
734 /* load options.identity_files */
735 load_public_identity_files();
737 /* Expand ~ in known host file names. */
739 options.system_hostfile =
740 tilde_expand_filename(options.system_hostfile, original_real_uid);
741 options.user_hostfile =
742 tilde_expand_filename(options.user_hostfile, original_real_uid);
743 options.system_hostfile2 =
744 tilde_expand_filename(options.system_hostfile2, original_real_uid);
745 options.user_hostfile2 =
746 tilde_expand_filename(options.user_hostfile2, original_real_uid);
748 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
750 /* Log into the remote system. This never returns if the login fails. */
751 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
753 /* We no longer need the private host keys. Clear them now. */
754 if (sensitive_data.nkeys != 0) {
755 for (i = 0; i < sensitive_data.nkeys; i++) {
756 if (sensitive_data.keys[i] != NULL) {
757 /* Destroys contents safely */
758 debug3("clear hostkey %d", i);
759 key_free(sensitive_data.keys[i]);
760 sensitive_data.keys[i] = NULL;
763 xfree(sensitive_data.keys);
765 for (i = 0; i < options.num_identity_files; i++) {
766 if (options.identity_files[i]) {
767 xfree(options.identity_files[i]);
768 options.identity_files[i] = NULL;
770 if (options.identity_keys[i]) {
771 key_free(options.identity_keys[i]);
772 options.identity_keys[i] = NULL;
776 exit_status = compat20 ? ssh_session2() : ssh_session();
779 if (options.control_path != NULL && control_fd != -1)
780 unlink(options.control_path);
783 * Send SIGHUP to proxy command if used. We don't wait() in
784 * case it hangs and instead rely on init to reap the child
786 if (proxy_command_pid > 1)
787 kill(proxy_command_pid, SIGHUP);
793 ssh_init_forwarding(void)
798 /* Initiate local TCP/IP port forwardings. */
799 for (i = 0; i < options.num_local_forwards; i++) {
800 debug("Local connections to %.200s:%d forwarded to remote "
802 (options.local_forwards[i].listen_host == NULL) ?
803 (options.gateway_ports ? "*" : "LOCALHOST") :
804 options.local_forwards[i].listen_host,
805 options.local_forwards[i].listen_port,
806 options.local_forwards[i].connect_host,
807 options.local_forwards[i].connect_port);
808 success += channel_setup_local_fwd_listener(
809 options.local_forwards[i].listen_host,
810 options.local_forwards[i].listen_port,
811 options.local_forwards[i].connect_host,
812 options.local_forwards[i].connect_port,
813 options.gateway_ports);
815 if (i > 0 && success == 0)
816 error("Could not request local forwarding.");
818 /* Initiate remote TCP/IP port forwardings. */
819 for (i = 0; i < options.num_remote_forwards; i++) {
820 debug("Remote connections from %.200s:%d forwarded to "
821 "local address %.200s:%d",
822 (options.remote_forwards[i].listen_host == NULL) ?
823 "LOCALHOST" : options.remote_forwards[i].listen_host,
824 options.remote_forwards[i].listen_port,
825 options.remote_forwards[i].connect_host,
826 options.remote_forwards[i].connect_port);
827 channel_request_remote_forwarding(
828 options.remote_forwards[i].listen_host,
829 options.remote_forwards[i].listen_port,
830 options.remote_forwards[i].connect_host,
831 options.remote_forwards[i].connect_port);
836 check_agent_present(void)
838 if (options.forward_agent) {
839 /* Clear agent forwarding if we don't have an agent. */
840 if (!ssh_agent_present())
841 options.forward_agent = 0;
855 /* Enable compression if requested. */
856 if (options.compression) {
857 debug("Requesting compression at level %d.", options.compression_level);
859 if (options.compression_level < 1 || options.compression_level > 9)
860 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
862 /* Send the request. */
863 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
864 packet_put_int(options.compression_level);
867 type = packet_read();
868 if (type == SSH_SMSG_SUCCESS)
869 packet_start_compression(options.compression_level);
870 else if (type == SSH_SMSG_FAILURE)
871 logit("Warning: Remote host refused compression.");
873 packet_disconnect("Protocol error waiting for compression response.");
875 /* Allocate a pseudo tty if appropriate. */
877 debug("Requesting pty.");
879 /* Start the packet. */
880 packet_start(SSH_CMSG_REQUEST_PTY);
882 /* Store TERM in the packet. There is no limit on the
883 length of the string. */
887 packet_put_cstring(cp);
889 /* Store window size in the packet. */
890 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
891 memset(&ws, 0, sizeof(ws));
892 packet_put_int((u_int)ws.ws_row);
893 packet_put_int((u_int)ws.ws_col);
894 packet_put_int((u_int)ws.ws_xpixel);
895 packet_put_int((u_int)ws.ws_ypixel);
897 /* Store tty modes in the packet. */
898 tty_make_modes(fileno(stdin), NULL);
900 /* Send the packet, and wait for it to leave. */
904 /* Read response from the server. */
905 type = packet_read();
906 if (type == SSH_SMSG_SUCCESS) {
909 } else if (type == SSH_SMSG_FAILURE)
910 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
912 packet_disconnect("Protocol error waiting for pty request response.");
914 /* Request X11 forwarding if enabled and DISPLAY is set. */
915 display = getenv("DISPLAY");
916 if (options.forward_x11 && display != NULL) {
918 /* Get reasonable local authentication information. */
919 client_x11_get_proto(display, options.xauth_location,
920 options.forward_x11_trusted, &proto, &data);
921 /* Request forwarding with authentication spoofing. */
922 debug("Requesting X11 forwarding with authentication spoofing.");
923 x11_request_forwarding_with_spoofing(0, display, proto, data);
925 /* Read response from the server. */
926 type = packet_read();
927 if (type == SSH_SMSG_SUCCESS) {
929 } else if (type == SSH_SMSG_FAILURE) {
930 logit("Warning: Remote host denied X11 forwarding.");
932 packet_disconnect("Protocol error waiting for X11 forwarding");
935 /* Tell the packet module whether this is an interactive session. */
936 packet_set_interactive(interactive);
938 /* Request authentication agent forwarding if appropriate. */
939 check_agent_present();
941 if (options.forward_agent) {
942 debug("Requesting authentication agent forwarding.");
943 auth_request_forwarding();
945 /* Read response from the server. */
946 type = packet_read();
948 if (type != SSH_SMSG_SUCCESS)
949 logit("Warning: Remote host denied authentication agent forwarding.");
952 /* Initiate port forwardings. */
953 ssh_init_forwarding();
955 /* If requested, let ssh continue in the background. */
956 if (fork_after_authentication_flag)
957 if (daemon(1, 1) < 0)
958 fatal("daemon() failed: %.200s", strerror(errno));
961 * If a command was specified on the command line, execute the
962 * command now. Otherwise request the server to start a shell.
964 if (buffer_len(&command) > 0) {
965 int len = buffer_len(&command);
968 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
969 packet_start(SSH_CMSG_EXEC_CMD);
970 packet_put_string(buffer_ptr(&command), buffer_len(&command));
974 debug("Requesting shell.");
975 packet_start(SSH_CMSG_EXEC_SHELL);
980 /* Enter the interactive session. */
981 return client_loop(have_tty, tty_flag ?
982 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
986 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
990 id = packet_get_int();
991 len = buffer_len(&command);
995 if (type == SSH2_MSG_CHANNEL_FAILURE)
996 fatal("Request for subsystem '%.*s' failed on channel %d",
997 len, (u_char *)buffer_ptr(&command), id);
1001 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
1005 i = client_global_request_id++;
1006 if (i >= options.num_remote_forwards)
1008 debug("remote forward %s for: listen %d, connect %s:%d",
1009 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1010 options.remote_forwards[i].listen_port,
1011 options.remote_forwards[i].connect_host,
1012 options.remote_forwards[i].connect_port);
1013 if (type == SSH2_MSG_REQUEST_FAILURE)
1014 logit("Warning: remote port forwarding failed for listen "
1015 "port %d", options.remote_forwards[i].listen_port);
1019 ssh_control_listener(void)
1021 struct sockaddr_un addr;
1025 if (options.control_path == NULL ||
1026 options.control_master == SSHCTL_MASTER_NO)
1029 debug("setting up multiplex master socket");
1031 memset(&addr, '\0', sizeof(addr));
1032 addr.sun_family = AF_UNIX;
1033 addr_len = offsetof(struct sockaddr_un, sun_path) +
1034 strlen(options.control_path) + 1;
1036 if (strlcpy(addr.sun_path, options.control_path,
1037 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1038 fatal("ControlPath too long");
1040 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1041 fatal("%s socket(): %s", __func__, strerror(errno));
1043 old_umask = umask(0177);
1044 if (bind(control_fd, (struct sockaddr *)&addr, addr_len) == -1) {
1046 if (errno == EINVAL || errno == EADDRINUSE)
1047 fatal("ControlSocket %s already exists",
1048 options.control_path);
1050 fatal("%s bind(): %s", __func__, strerror(errno));
1054 if (listen(control_fd, 64) == -1)
1055 fatal("%s listen(): %s", __func__, strerror(errno));
1057 set_nonblock(control_fd);
1060 /* request pty/x11/agent/tcpfwd/shell for channel */
1062 ssh_session2_setup(int id, void *arg)
1064 extern char **environ;
1065 const char *display;
1066 int interactive = tty_flag;
1068 display = getenv("DISPLAY");
1069 if (options.forward_x11 && display != NULL) {
1071 /* Get reasonable local authentication information. */
1072 client_x11_get_proto(display, options.xauth_location,
1073 options.forward_x11_trusted, &proto, &data);
1074 /* Request forwarding with authentication spoofing. */
1075 debug("Requesting X11 forwarding with authentication spoofing.");
1076 x11_request_forwarding_with_spoofing(id, display, proto, data);
1078 /* XXX wait for reply */
1081 check_agent_present();
1082 if (options.forward_agent) {
1083 debug("Requesting authentication agent forwarding.");
1084 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1088 if (options.tun_open != SSH_TUNMODE_NO) {
1092 debug("Requesting tun.");
1093 if ((fd = tun_open(options.tun_local,
1094 options.tun_open)) >= 0) {
1095 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1096 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1099 #if defined(SSH_TUN_FILTER)
1100 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1101 channel_register_filter(c->self, sys_tun_infilter,
1104 packet_start(SSH2_MSG_CHANNEL_OPEN);
1105 packet_put_cstring("tun@openssh.com");
1106 packet_put_int(c->self);
1107 packet_put_int(c->local_window_max);
1108 packet_put_int(c->local_maxpacket);
1109 packet_put_int(options.tun_open);
1110 packet_put_int(options.tun_remote);
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 /* Execute a local command */
1180 if (options.local_command != NULL &&
1181 options.permit_local_command)
1182 ssh_local_cmd(options.local_command);
1184 /* If requested, let ssh continue in the background. */
1185 if (fork_after_authentication_flag)
1186 if (daemon(1, 1) < 0)
1187 fatal("daemon() failed: %.200s", strerror(errno));
1189 return client_loop(tty_flag, tty_flag ?
1190 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1194 load_public_identity_files(void)
1202 if (options.smartcard_device != NULL &&
1203 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1204 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1206 for (i = 0; keys[i] != NULL; i++) {
1208 memmove(&options.identity_files[1], &options.identity_files[0],
1209 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1210 memmove(&options.identity_keys[1], &options.identity_keys[0],
1211 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1212 options.num_identity_files++;
1213 options.identity_keys[0] = keys[i];
1214 options.identity_files[0] = sc_get_key_label(keys[i]);
1216 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1217 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1221 #endif /* SMARTCARD */
1222 for (; i < options.num_identity_files; i++) {
1223 filename = tilde_expand_filename(options.identity_files[i],
1225 public = key_load_public(filename, NULL);
1226 debug("identity file %s type %d", filename,
1227 public ? public->type : -1);
1228 xfree(options.identity_files[i]);
1229 options.identity_files[i] = filename;
1230 options.identity_keys[i] = public;
1235 control_client_sighandler(int signo)
1237 control_client_terminate = signo;
1241 control_client_sigrelay(int signo)
1243 if (control_server_pid > 1)
1244 kill(control_server_pid, signo);
1248 env_permitted(char *env)
1251 char name[1024], *cp;
1253 if (strlcpy(name, env, sizeof(name)) >= sizeof(name))
1254 fatal("env_permitted: name too long");
1255 if ((cp = strchr(name, '=')) == NULL)
1260 for (i = 0; i < options.num_send_env; i++)
1261 if (match_pattern(name, options.send_env[i]))
1268 control_client(const char *path)
1270 struct sockaddr_un addr;
1271 int i, r, fd, sock, exitval, num_env, addr_len;
1274 extern char **environ;
1277 if (mux_command == 0)
1278 mux_command = SSHMUX_COMMAND_OPEN;
1280 switch (options.control_master) {
1281 case SSHCTL_MASTER_AUTO:
1282 case SSHCTL_MASTER_AUTO_ASK:
1283 debug("auto-mux: Trying existing master");
1285 case SSHCTL_MASTER_NO:
1291 memset(&addr, '\0', sizeof(addr));
1292 addr.sun_family = AF_UNIX;
1293 addr_len = offsetof(struct sockaddr_un, sun_path) +
1296 if (strlcpy(addr.sun_path, path,
1297 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1298 fatal("ControlPath too long");
1300 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1301 fatal("%s socket(): %s", __func__, strerror(errno));
1303 if (connect(sock, (struct sockaddr *)&addr, addr_len) == -1) {
1304 if (mux_command != SSHMUX_COMMAND_OPEN) {
1305 fatal("Control socket connect(%.100s): %s", path,
1308 if (errno == ENOENT)
1309 debug("Control socket \"%.100s\" does not exist", path);
1311 error("Control socket connect(%.100s): %s", path,
1318 if (stdin_null_flag) {
1319 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1320 fatal("open(/dev/null): %s", strerror(errno));
1321 if (dup2(fd, STDIN_FILENO) == -1)
1322 fatal("dup2: %s", strerror(errno));
1323 if (fd > STDERR_FILENO)
1327 term = getenv("TERM");
1331 flags |= SSHMUX_FLAG_TTY;
1333 flags |= SSHMUX_FLAG_SUBSYS;
1334 if (options.forward_x11)
1335 flags |= SSHMUX_FLAG_X11_FWD;
1336 if (options.forward_agent)
1337 flags |= SSHMUX_FLAG_AGENT_FWD;
1341 /* Send our command to server */
1342 buffer_put_int(&m, mux_command);
1343 buffer_put_int(&m, flags);
1344 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1345 fatal("%s: msg_send", __func__);
1348 /* Get authorisation status and PID of controlee */
1349 if (ssh_msg_recv(sock, &m) == -1)
1350 fatal("%s: msg_recv", __func__);
1351 if (buffer_get_char(&m) != SSHMUX_VER)
1352 fatal("%s: wrong version", __func__);
1353 if (buffer_get_int(&m) != 1)
1354 fatal("Connection to master denied");
1355 control_server_pid = buffer_get_int(&m);
1359 switch (mux_command) {
1360 case SSHMUX_COMMAND_ALIVE_CHECK:
1361 fprintf(stderr, "Master running (pid=%d)\r\n",
1362 control_server_pid);
1364 case SSHMUX_COMMAND_TERMINATE:
1365 fprintf(stderr, "Exit request sent.\r\n");
1367 case SSHMUX_COMMAND_OPEN:
1368 /* continue below */
1371 fatal("silly mux_command %d", mux_command);
1374 /* SSHMUX_COMMAND_OPEN */
1375 buffer_put_cstring(&m, term ? term : "");
1376 buffer_append(&command, "\0", 1);
1377 buffer_put_cstring(&m, buffer_ptr(&command));
1379 if (options.num_send_env == 0 || environ == NULL) {
1380 buffer_put_int(&m, 0);
1382 /* Pass environment */
1384 for (i = 0; environ[i] != NULL; i++)
1385 if (env_permitted(environ[i]))
1386 num_env++; /* Count */
1388 buffer_put_int(&m, num_env);
1390 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1391 if (env_permitted(environ[i])) {
1393 buffer_put_cstring(&m, environ[i]);
1397 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1398 fatal("%s: msg_send", __func__);
1400 mm_send_fd(sock, STDIN_FILENO);
1401 mm_send_fd(sock, STDOUT_FILENO);
1402 mm_send_fd(sock, STDERR_FILENO);
1404 /* Wait for reply, so master has a chance to gather ttymodes */
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__);
1412 signal(SIGHUP, control_client_sighandler);
1413 signal(SIGINT, control_client_sighandler);
1414 signal(SIGTERM, control_client_sighandler);
1415 signal(SIGWINCH, control_client_sigrelay);
1420 /* Stick around until the controlee closes the client_fd */
1422 for (;!control_client_terminate;) {
1423 r = read(sock, &exitval, sizeof(exitval));
1425 debug2("Received EOF from master");
1429 debug2("Received exit status from master %d", exitval);
1430 if (r == -1 && errno != EINTR)
1431 fatal("%s: read %s", __func__, strerror(errno));
1434 if (control_client_terminate)
1435 debug2("Exiting on signal %d", control_client_terminate);
1441 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1442 fprintf(stderr, "Connection to master closed.\r\n");