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.255 2005/12/06 22:38:27 reyk 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 = 0;
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 [bind_address:]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 " [-w tunnel:tunnel] [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;
191 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
194 __progname = ssh_get_progname(av[0]);
198 * Save the original real uid. It will be needed later (uid-swapping
199 * may clobber the real uid).
201 original_real_uid = getuid();
202 original_effective_uid = geteuid();
205 * Use uid-swapping to give up root privileges for the duration of
206 * option processing. We will re-instantiate the rights when we are
207 * ready to create the privileged port, and will permanently drop
208 * them when the port has been created (actually, when the connection
209 * has been made, as we may need to create the port several times).
213 #ifdef HAVE_SETRLIMIT
214 /* If we are installed setuid root be careful to not drop core. */
215 if (original_real_uid != original_effective_uid) {
217 rlim.rlim_cur = rlim.rlim_max = 0;
218 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
219 fatal("setrlimit failed: %.100s", strerror(errno));
223 pw = getpwuid(original_real_uid);
225 logit("You don't exist, go away!");
228 /* Take a copy of the returned structure. */
232 * Set our umask to something reasonable, as some files are created
233 * with the default umask. This will make them world-readable but
234 * writable only by the owner, which is ok for all files for which we
235 * don't set the modes explicitly.
239 /* Initialize option structure to indicate that no values have been set. */
240 initialize_options(&options);
242 /* Parse command-line arguments. */
246 while ((opt = getopt(ac, av,
247 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVw:XY")) != -1) {
250 options.protocol = SSH_PROTO_1;
253 options.protocol = SSH_PROTO_2;
256 options.address_family = AF_INET;
259 options.address_family = AF_INET6;
265 fork_after_authentication_flag = 1;
269 options.forward_x11 = 0;
272 options.forward_x11 = 1;
275 options.forward_x11 = 1;
276 options.forward_x11_trusted = 1;
279 options.gateway_ports = 1;
282 if (strcmp(optarg, "check") == 0)
283 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
284 else if (strcmp(optarg, "exit") == 0)
285 mux_command = SSHMUX_COMMAND_TERMINATE;
287 fatal("Invalid multiplex command.");
289 case 'P': /* deprecated */
290 options.use_privileged_port = 0;
293 options.forward_agent = 0;
296 options.forward_agent = 1;
299 options.gss_deleg_creds = 0;
302 if (stat(optarg, &st) < 0) {
303 fprintf(stderr, "Warning: Identity file %s "
304 "not accessible: %s.\n", optarg,
308 if (options.num_identity_files >=
309 SSH_MAX_IDENTITY_FILES)
310 fatal("Too many identity files specified "
311 "(max %d)", SSH_MAX_IDENTITY_FILES);
312 options.identity_files[options.num_identity_files++] =
317 options.smartcard_device = xstrdup(optarg);
319 fprintf(stderr, "no support for smartcards.\n");
328 if (debug_flag == 0) {
330 options.log_level = SYSLOG_LEVEL_DEBUG1;
332 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
338 fprintf(stderr, "%s, %s\n",
339 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
344 options.tun_open = 1;
345 options.tun_local = a2tun(optarg, &options.tun_remote);
346 if (options.tun_local < -1) {
347 fprintf(stderr, "Bad tun device '%s'\n", optarg);
352 options.log_level = SYSLOG_LEVEL_QUIET;
355 if (optarg[0] == '^' && optarg[2] == 0 &&
356 (u_char) optarg[1] >= 64 &&
357 (u_char) optarg[1] < 128)
358 options.escape_char = (u_char) optarg[1] & 31;
359 else if (strlen(optarg) == 1)
360 options.escape_char = (u_char) optarg[0];
361 else if (strcmp(optarg, "none") == 0)
362 options.escape_char = SSH_ESCAPECHAR_NONE;
364 fprintf(stderr, "Bad escape character '%s'.\n",
370 if (ciphers_valid(optarg)) {
372 options.ciphers = xstrdup(optarg);
373 options.cipher = SSH_CIPHER_INVALID;
376 options.cipher = cipher_number(optarg);
377 if (options.cipher == -1) {
379 "Unknown cipher type '%s'\n",
383 if (options.cipher == SSH_CIPHER_3DES)
384 options.ciphers = "3des-cbc";
385 else if (options.cipher == SSH_CIPHER_BLOWFISH)
386 options.ciphers = "blowfish-cbc";
388 options.ciphers = (char *)-1;
392 if (mac_valid(optarg))
393 options.macs = xstrdup(optarg);
395 fprintf(stderr, "Unknown mac type '%s'\n",
401 if (options.control_master == SSHCTL_MASTER_YES)
402 options.control_master = SSHCTL_MASTER_ASK;
404 options.control_master = SSHCTL_MASTER_YES;
407 options.port = a2port(optarg);
408 if (options.port == 0) {
409 fprintf(stderr, "Bad port '%s'\n", optarg);
414 options.user = optarg;
418 if (parse_forward(&fwd, optarg))
419 add_local_forward(&options, &fwd);
422 "Bad local forwarding specification '%s'\n",
429 if (parse_forward(&fwd, optarg)) {
430 add_remote_forward(&options, &fwd);
433 "Bad remote forwarding specification "
440 cp = p = xstrdup(optarg);
441 memset(&fwd, '\0', sizeof(fwd));
442 fwd.connect_host = "socks";
443 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
444 fprintf(stderr, "Bad dynamic forwarding "
445 "specification '%.100s'\n", optarg);
449 fwd.listen_port = a2port(cp);
450 fwd.listen_host = cleanhostname(fwd.listen_host);
452 fwd.listen_port = a2port(fwd.listen_host);
453 fwd.listen_host = NULL;
456 if (fwd.listen_port == 0) {
457 fprintf(stderr, "Bad dynamic port '%s'\n",
461 add_local_forward(&options, &fwd);
466 options.compression = 1;
477 line = xstrdup(optarg);
478 if (process_config_line(&options, host ? host : "",
479 line, "command-line", 0, &dummy) != 0)
487 if (options.control_path != NULL)
488 free(options.control_path);
489 options.control_path = xstrdup(optarg);
492 options.bind_address = optarg;
505 if (ac > 0 && !host && **av != '-') {
506 if (strrchr(*av, '@')) {
508 cp = strrchr(p, '@');
509 if (cp == NULL || cp == p)
517 optind = optreset = 1;
523 /* Check that we got a host name. */
527 SSLeay_add_all_algorithms();
528 ERR_load_crypto_strings();
530 /* Initialize the command to execute on remote host. */
531 buffer_init(&command);
534 * Save the command to execute on the remote host in a buffer. There
535 * is no limit on the length of the command, except by the maximum
536 * packet size. Also sets the tty flag if there is no command.
539 /* No command specified - execute shell on a tty. */
541 if (subsystem_flag) {
543 "You must specify a subsystem to invoke.\n");
547 /* A command has been specified. Store it into the buffer. */
548 for (i = 0; i < ac; i++) {
550 buffer_append(&command, " ", 1);
551 buffer_append(&command, av[i], strlen(av[i]));
555 /* Cannot fork to background if no command. */
556 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
557 fatal("Cannot fork into background without a command to execute.");
559 /* Allocate a tty by default if no command specified. */
560 if (buffer_len(&command) == 0)
566 /* Do not allocate a tty if stdin is not a tty. */
567 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
569 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
574 * Initialize "log" output. Since we are the client all output
575 * actually goes to stderr.
577 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
578 SYSLOG_FACILITY_USER, 1);
581 * Read per-user configuration file. Ignore the system wide config
582 * file if the user specifies a config file on the command line.
584 if (config != NULL) {
585 if (!read_config_file(config, host, &options, 0))
586 fatal("Can't open user config file %.100s: "
587 "%.100s", config, strerror(errno));
589 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
590 _PATH_SSH_USER_CONFFILE);
591 (void)read_config_file(buf, host, &options, 1);
593 /* Read systemwide configuration file after use config. */
594 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
598 /* Fill configuration defaults. */
599 fill_default_options(&options);
601 channel_set_af(options.address_family);
604 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
608 if (options.user == NULL)
609 options.user = xstrdup(pw->pw_name);
611 if (options.hostname != NULL)
612 host = options.hostname;
614 /* force lowercase for hostkey matching */
615 if (options.host_key_alias != NULL) {
616 for (p = options.host_key_alias; *p; p++)
621 /* Get default port if port has not been set. */
622 if (options.port == 0) {
623 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
624 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
627 if (options.proxy_command != NULL &&
628 strcmp(options.proxy_command, "none") == 0)
629 options.proxy_command = NULL;
630 if (options.control_path != NULL &&
631 strcmp(options.control_path, "none") == 0)
632 options.control_path = NULL;
634 if (options.control_path != NULL) {
635 snprintf(buf, sizeof(buf), "%d", options.port);
636 cp = tilde_expand_filename(options.control_path,
638 options.control_path = percent_expand(cp, "p", buf, "h", host,
639 "r", options.user, (char *)NULL);
642 if (mux_command != 0 && options.control_path == NULL)
643 fatal("No ControlPath specified for \"-O\" command");
644 if (options.control_path != NULL)
645 control_client(options.control_path);
647 /* Open a connection to the remote host. */
648 if (ssh_connect(host, &hostaddr, options.port,
649 options.address_family, options.connection_attempts,
651 options.use_privileged_port,
653 original_effective_uid == 0 && options.use_privileged_port,
655 options.proxy_command) != 0)
659 * If we successfully made the connection, load the host private key
660 * in case we will need it later for combined rsa-rhosts
661 * authentication. This must be done before releasing extra
662 * privileges, because the file is only readable by root.
663 * If we cannot access the private keys, load the public keys
664 * instead and try to execute the ssh-keysign helper instead.
666 sensitive_data.nkeys = 0;
667 sensitive_data.keys = NULL;
668 sensitive_data.external_keysign = 0;
669 if (options.rhosts_rsa_authentication ||
670 options.hostbased_authentication) {
671 sensitive_data.nkeys = 3;
672 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
676 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
677 _PATH_HOST_KEY_FILE, "", NULL);
678 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
679 _PATH_HOST_DSA_KEY_FILE, "", NULL);
680 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
681 _PATH_HOST_RSA_KEY_FILE, "", NULL);
684 if (options.hostbased_authentication == 1 &&
685 sensitive_data.keys[0] == NULL &&
686 sensitive_data.keys[1] == NULL &&
687 sensitive_data.keys[2] == NULL) {
688 sensitive_data.keys[1] = key_load_public(
689 _PATH_HOST_DSA_KEY_FILE, NULL);
690 sensitive_data.keys[2] = key_load_public(
691 _PATH_HOST_RSA_KEY_FILE, NULL);
692 sensitive_data.external_keysign = 1;
696 * Get rid of any extra privileges that we may have. We will no
697 * longer need them. Also, extra privileges could make it very hard
698 * to read identity files and other non-world-readable files from the
699 * user's home directory if it happens to be on a NFS volume where
700 * root is mapped to nobody.
702 if (original_effective_uid == 0) {
704 permanently_set_uid(pw);
708 * Now that we are back to our own permissions, create ~/.ssh
709 * directory if it doesn't already exist.
711 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
712 if (stat(buf, &st) < 0)
713 if (mkdir(buf, 0700) < 0)
714 error("Could not create directory '%.200s'.", buf);
716 /* load options.identity_files */
717 load_public_identity_files();
719 /* Expand ~ in known host file names. */
721 options.system_hostfile =
722 tilde_expand_filename(options.system_hostfile, original_real_uid);
723 options.user_hostfile =
724 tilde_expand_filename(options.user_hostfile, original_real_uid);
725 options.system_hostfile2 =
726 tilde_expand_filename(options.system_hostfile2, original_real_uid);
727 options.user_hostfile2 =
728 tilde_expand_filename(options.user_hostfile2, original_real_uid);
730 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
732 /* Log into the remote system. This never returns if the login fails. */
733 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
735 /* We no longer need the private host keys. Clear them now. */
736 if (sensitive_data.nkeys != 0) {
737 for (i = 0; i < sensitive_data.nkeys; i++) {
738 if (sensitive_data.keys[i] != NULL) {
739 /* Destroys contents safely */
740 debug3("clear hostkey %d", i);
741 key_free(sensitive_data.keys[i]);
742 sensitive_data.keys[i] = NULL;
745 xfree(sensitive_data.keys);
747 for (i = 0; i < options.num_identity_files; i++) {
748 if (options.identity_files[i]) {
749 xfree(options.identity_files[i]);
750 options.identity_files[i] = NULL;
752 if (options.identity_keys[i]) {
753 key_free(options.identity_keys[i]);
754 options.identity_keys[i] = NULL;
758 exit_status = compat20 ? ssh_session2() : ssh_session();
761 if (options.control_path != NULL && control_fd != -1)
762 unlink(options.control_path);
765 * Send SIGHUP to proxy command if used. We don't wait() in
766 * case it hangs and instead rely on init to reap the child
768 if (proxy_command_pid > 1)
769 kill(proxy_command_pid, SIGHUP);
775 ssh_init_forwarding(void)
780 /* Initiate local TCP/IP port forwardings. */
781 for (i = 0; i < options.num_local_forwards; i++) {
782 debug("Local connections to %.200s:%d forwarded to remote "
784 (options.local_forwards[i].listen_host == NULL) ?
785 (options.gateway_ports ? "*" : "LOCALHOST") :
786 options.local_forwards[i].listen_host,
787 options.local_forwards[i].listen_port,
788 options.local_forwards[i].connect_host,
789 options.local_forwards[i].connect_port);
790 success += channel_setup_local_fwd_listener(
791 options.local_forwards[i].listen_host,
792 options.local_forwards[i].listen_port,
793 options.local_forwards[i].connect_host,
794 options.local_forwards[i].connect_port,
795 options.gateway_ports);
797 if (i > 0 && success == 0)
798 error("Could not request local forwarding.");
800 /* Initiate remote TCP/IP port forwardings. */
801 for (i = 0; i < options.num_remote_forwards; i++) {
802 debug("Remote connections from %.200s:%d forwarded to "
803 "local address %.200s:%d",
804 (options.remote_forwards[i].listen_host == NULL) ?
805 "LOCALHOST" : options.remote_forwards[i].listen_host,
806 options.remote_forwards[i].listen_port,
807 options.remote_forwards[i].connect_host,
808 options.remote_forwards[i].connect_port);
809 channel_request_remote_forwarding(
810 options.remote_forwards[i].listen_host,
811 options.remote_forwards[i].listen_port,
812 options.remote_forwards[i].connect_host,
813 options.remote_forwards[i].connect_port);
818 check_agent_present(void)
820 if (options.forward_agent) {
821 /* Clear agent forwarding if we don't have an agent. */
822 if (!ssh_agent_present())
823 options.forward_agent = 0;
837 /* Enable compression if requested. */
838 if (options.compression) {
839 debug("Requesting compression at level %d.", options.compression_level);
841 if (options.compression_level < 1 || options.compression_level > 9)
842 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
844 /* Send the request. */
845 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
846 packet_put_int(options.compression_level);
849 type = packet_read();
850 if (type == SSH_SMSG_SUCCESS)
851 packet_start_compression(options.compression_level);
852 else if (type == SSH_SMSG_FAILURE)
853 logit("Warning: Remote host refused compression.");
855 packet_disconnect("Protocol error waiting for compression response.");
857 /* Allocate a pseudo tty if appropriate. */
859 debug("Requesting pty.");
861 /* Start the packet. */
862 packet_start(SSH_CMSG_REQUEST_PTY);
864 /* Store TERM in the packet. There is no limit on the
865 length of the string. */
869 packet_put_cstring(cp);
871 /* Store window size in the packet. */
872 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
873 memset(&ws, 0, sizeof(ws));
874 packet_put_int(ws.ws_row);
875 packet_put_int(ws.ws_col);
876 packet_put_int(ws.ws_xpixel);
877 packet_put_int(ws.ws_ypixel);
879 /* Store tty modes in the packet. */
880 tty_make_modes(fileno(stdin), NULL);
882 /* Send the packet, and wait for it to leave. */
886 /* Read response from the server. */
887 type = packet_read();
888 if (type == SSH_SMSG_SUCCESS) {
891 } else if (type == SSH_SMSG_FAILURE)
892 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
894 packet_disconnect("Protocol error waiting for pty request response.");
896 /* Request X11 forwarding if enabled and DISPLAY is set. */
897 display = getenv("DISPLAY");
898 if (options.forward_x11 && display != NULL) {
900 /* Get reasonable local authentication information. */
901 client_x11_get_proto(display, options.xauth_location,
902 options.forward_x11_trusted, &proto, &data);
903 /* Request forwarding with authentication spoofing. */
904 debug("Requesting X11 forwarding with authentication spoofing.");
905 x11_request_forwarding_with_spoofing(0, display, proto, data);
907 /* Read response from the server. */
908 type = packet_read();
909 if (type == SSH_SMSG_SUCCESS) {
911 } else if (type == SSH_SMSG_FAILURE) {
912 logit("Warning: Remote host denied X11 forwarding.");
914 packet_disconnect("Protocol error waiting for X11 forwarding");
917 /* Tell the packet module whether this is an interactive session. */
918 packet_set_interactive(interactive);
920 /* Request authentication agent forwarding if appropriate. */
921 check_agent_present();
923 if (options.forward_agent) {
924 debug("Requesting authentication agent forwarding.");
925 auth_request_forwarding();
927 /* Read response from the server. */
928 type = packet_read();
930 if (type != SSH_SMSG_SUCCESS)
931 logit("Warning: Remote host denied authentication agent forwarding.");
934 /* Initiate port forwardings. */
935 ssh_init_forwarding();
937 /* If requested, let ssh continue in the background. */
938 if (fork_after_authentication_flag)
939 if (daemon(1, 1) < 0)
940 fatal("daemon() failed: %.200s", strerror(errno));
943 * If a command was specified on the command line, execute the
944 * command now. Otherwise request the server to start a shell.
946 if (buffer_len(&command) > 0) {
947 int len = buffer_len(&command);
950 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
951 packet_start(SSH_CMSG_EXEC_CMD);
952 packet_put_string(buffer_ptr(&command), buffer_len(&command));
956 debug("Requesting shell.");
957 packet_start(SSH_CMSG_EXEC_SHELL);
962 /* Enter the interactive session. */
963 return client_loop(have_tty, tty_flag ?
964 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
968 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
972 id = packet_get_int();
973 len = buffer_len(&command);
977 if (type == SSH2_MSG_CHANNEL_FAILURE)
978 fatal("Request for subsystem '%.*s' failed on channel %d",
979 len, (u_char *)buffer_ptr(&command), id);
983 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
987 i = client_global_request_id++;
988 if (i >= options.num_remote_forwards)
990 debug("remote forward %s for: listen %d, connect %s:%d",
991 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
992 options.remote_forwards[i].listen_port,
993 options.remote_forwards[i].connect_host,
994 options.remote_forwards[i].connect_port);
995 if (type == SSH2_MSG_REQUEST_FAILURE)
996 logit("Warning: remote port forwarding failed for listen "
997 "port %d", options.remote_forwards[i].listen_port);
1001 ssh_control_listener(void)
1003 struct sockaddr_un addr;
1007 if (options.control_path == NULL ||
1008 options.control_master == SSHCTL_MASTER_NO)
1011 debug("setting up multiplex master socket");
1013 memset(&addr, '\0', sizeof(addr));
1014 addr.sun_family = AF_UNIX;
1015 addr_len = offsetof(struct sockaddr_un, sun_path) +
1016 strlen(options.control_path) + 1;
1018 if (strlcpy(addr.sun_path, options.control_path,
1019 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1020 fatal("ControlPath too long");
1022 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1023 fatal("%s socket(): %s", __func__, strerror(errno));
1025 old_umask = umask(0177);
1026 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1028 if (errno == EINVAL || errno == EADDRINUSE)
1029 fatal("ControlSocket %s already exists",
1030 options.control_path);
1032 fatal("%s bind(): %s", __func__, strerror(errno));
1036 if (listen(control_fd, 64) == -1)
1037 fatal("%s listen(): %s", __func__, strerror(errno));
1039 set_nonblock(control_fd);
1042 /* request pty/x11/agent/tcpfwd/shell for channel */
1044 ssh_session2_setup(int id, void *arg)
1046 extern char **environ;
1047 const char *display;
1048 int interactive = tty_flag;
1050 display = getenv("DISPLAY");
1051 if (options.forward_x11 && display != NULL) {
1053 /* Get reasonable local authentication information. */
1054 client_x11_get_proto(display, options.xauth_location,
1055 options.forward_x11_trusted, &proto, &data);
1056 /* Request forwarding with authentication spoofing. */
1057 debug("Requesting X11 forwarding with authentication spoofing.");
1058 x11_request_forwarding_with_spoofing(id, display, proto, data);
1060 /* XXX wait for reply */
1063 check_agent_present();
1064 if (options.forward_agent) {
1065 debug("Requesting authentication agent forwarding.");
1066 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1070 if (options.tun_open) {
1074 debug("Requesting tun.");
1075 if ((fd = tun_open(options.tun_local)) >= 0) {
1076 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1077 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1080 packet_start(SSH2_MSG_CHANNEL_OPEN);
1081 packet_put_cstring("tun@openssh.com");
1082 packet_put_int(c->self);
1083 packet_put_int(c->local_window_max);
1084 packet_put_int(c->local_maxpacket);
1085 packet_put_int(options.tun_remote);
1090 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1091 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1093 packet_set_interactive(interactive);
1096 /* open new channel for a session */
1098 ssh_session2_open(void)
1101 int window, packetmax, in, out, err;
1103 if (stdin_null_flag) {
1104 in = open(_PATH_DEVNULL, O_RDONLY);
1106 in = dup(STDIN_FILENO);
1108 out = dup(STDOUT_FILENO);
1109 err = dup(STDERR_FILENO);
1111 if (in < 0 || out < 0 || err < 0)
1112 fatal("dup() in/out/err failed");
1114 /* enable nonblocking unless tty */
1122 window = CHAN_SES_WINDOW_DEFAULT;
1123 packetmax = CHAN_SES_PACKET_DEFAULT;
1129 "session", SSH_CHANNEL_OPENING, in, out, err,
1130 window, packetmax, CHAN_EXTENDED_WRITE,
1131 "client-session", /*nonblock*/0);
1133 debug3("ssh_session2_open: channel_new: %d", c->self);
1135 channel_send_open(c->self);
1137 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1147 /* XXX should be pre-session */
1148 ssh_init_forwarding();
1149 ssh_control_listener();
1151 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1152 id = ssh_session2_open();
1154 /* Execute a local command */
1155 if (options.local_command != NULL &&
1156 options.permit_local_command)
1157 ssh_local_cmd(options.local_command);
1159 /* If requested, let ssh continue in the background. */
1160 if (fork_after_authentication_flag)
1161 if (daemon(1, 1) < 0)
1162 fatal("daemon() failed: %.200s", strerror(errno));
1164 return client_loop(tty_flag, tty_flag ?
1165 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1169 load_public_identity_files(void)
1177 if (options.smartcard_device != NULL &&
1178 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1179 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1181 for (i = 0; keys[i] != NULL; i++) {
1183 memmove(&options.identity_files[1], &options.identity_files[0],
1184 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1185 memmove(&options.identity_keys[1], &options.identity_keys[0],
1186 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1187 options.num_identity_files++;
1188 options.identity_keys[0] = keys[i];
1189 options.identity_files[0] = sc_get_key_label(keys[i]);
1191 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1192 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1196 #endif /* SMARTCARD */
1197 for (; i < options.num_identity_files; i++) {
1198 filename = tilde_expand_filename(options.identity_files[i],
1200 public = key_load_public(filename, NULL);
1201 debug("identity file %s type %d", filename,
1202 public ? public->type : -1);
1203 xfree(options.identity_files[i]);
1204 options.identity_files[i] = filename;
1205 options.identity_keys[i] = public;
1210 control_client_sighandler(int signo)
1212 control_client_terminate = signo;
1216 control_client_sigrelay(int signo)
1218 if (control_server_pid > 1)
1219 kill(control_server_pid, signo);
1223 env_permitted(char *env)
1226 char name[1024], *cp;
1228 strlcpy(name, env, sizeof(name));
1229 if ((cp = strchr(name, '=')) == NULL)
1234 for (i = 0; i < options.num_send_env; i++)
1235 if (match_pattern(name, options.send_env[i]))
1242 control_client(const char *path)
1244 struct sockaddr_un addr;
1245 int i, r, fd, sock, exitval, num_env, addr_len;
1248 extern char **environ;
1251 if (mux_command == 0)
1252 mux_command = SSHMUX_COMMAND_OPEN;
1254 switch (options.control_master) {
1255 case SSHCTL_MASTER_AUTO:
1256 case SSHCTL_MASTER_AUTO_ASK:
1257 debug("auto-mux: Trying existing master");
1259 case SSHCTL_MASTER_NO:
1265 memset(&addr, '\0', sizeof(addr));
1266 addr.sun_family = AF_UNIX;
1267 addr_len = offsetof(struct sockaddr_un, sun_path) +
1270 if (strlcpy(addr.sun_path, path,
1271 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1272 fatal("ControlPath too long");
1274 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1275 fatal("%s socket(): %s", __func__, strerror(errno));
1277 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1278 if (mux_command != SSHMUX_COMMAND_OPEN) {
1279 fatal("Control socket connect(%.100s): %s", path,
1282 if (errno == ENOENT)
1283 debug("Control socket \"%.100s\" does not exist", path);
1285 error("Control socket connect(%.100s): %s", path,
1292 if (stdin_null_flag) {
1293 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1294 fatal("open(/dev/null): %s", strerror(errno));
1295 if (dup2(fd, STDIN_FILENO) == -1)
1296 fatal("dup2: %s", strerror(errno));
1297 if (fd > STDERR_FILENO)
1301 term = getenv("TERM");
1305 flags |= SSHMUX_FLAG_TTY;
1307 flags |= SSHMUX_FLAG_SUBSYS;
1308 if (options.forward_x11)
1309 flags |= SSHMUX_FLAG_X11_FWD;
1310 if (options.forward_agent)
1311 flags |= SSHMUX_FLAG_AGENT_FWD;
1315 /* Send our command to server */
1316 buffer_put_int(&m, mux_command);
1317 buffer_put_int(&m, flags);
1318 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1319 fatal("%s: msg_send", __func__);
1322 /* Get authorisation status and PID of controlee */
1323 if (ssh_msg_recv(sock, &m) == -1)
1324 fatal("%s: msg_recv", __func__);
1325 if (buffer_get_char(&m) != SSHMUX_VER)
1326 fatal("%s: wrong version", __func__);
1327 if (buffer_get_int(&m) != 1)
1328 fatal("Connection to master denied");
1329 control_server_pid = buffer_get_int(&m);
1333 switch (mux_command) {
1334 case SSHMUX_COMMAND_ALIVE_CHECK:
1335 fprintf(stderr, "Master running (pid=%d)\r\n",
1336 control_server_pid);
1338 case SSHMUX_COMMAND_TERMINATE:
1339 fprintf(stderr, "Exit request sent.\r\n");
1341 case SSHMUX_COMMAND_OPEN:
1342 /* continue below */
1345 fatal("silly mux_command %d", mux_command);
1348 /* SSHMUX_COMMAND_OPEN */
1349 buffer_put_cstring(&m, term ? term : "");
1350 buffer_append(&command, "\0", 1);
1351 buffer_put_cstring(&m, buffer_ptr(&command));
1353 if (options.num_send_env == 0 || environ == NULL) {
1354 buffer_put_int(&m, 0);
1356 /* Pass environment */
1358 for (i = 0; environ[i] != NULL; i++)
1359 if (env_permitted(environ[i]))
1360 num_env++; /* Count */
1362 buffer_put_int(&m, num_env);
1364 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1365 if (env_permitted(environ[i])) {
1367 buffer_put_cstring(&m, environ[i]);
1371 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1372 fatal("%s: msg_send", __func__);
1374 mm_send_fd(sock, STDIN_FILENO);
1375 mm_send_fd(sock, STDOUT_FILENO);
1376 mm_send_fd(sock, STDERR_FILENO);
1378 /* Wait for reply, so master has a chance to gather ttymodes */
1380 if (ssh_msg_recv(sock, &m) == -1)
1381 fatal("%s: msg_recv", __func__);
1382 if (buffer_get_char(&m) != SSHMUX_VER)
1383 fatal("%s: wrong version", __func__);
1386 signal(SIGHUP, control_client_sighandler);
1387 signal(SIGINT, control_client_sighandler);
1388 signal(SIGTERM, control_client_sighandler);
1389 signal(SIGWINCH, control_client_sigrelay);
1394 /* Stick around until the controlee closes the client_fd */
1396 for (;!control_client_terminate;) {
1397 r = read(sock, &exitval, sizeof(exitval));
1399 debug2("Received EOF from master");
1403 debug2("Received exit status from master %d", exitval);
1404 if (r == -1 && errno != EINTR)
1405 fatal("%s: read %s", __func__, strerror(errno));
1408 if (control_client_terminate)
1409 debug2("Exiting on signal %d", control_client_terminate);
1415 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1416 fprintf(stderr, "Connection to master closed.\r\n");