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.249 2005/07/30 01:26:16 djm Exp $");
46 #include <openssl/evp.h>
47 #include <openssl/err.h>
62 #include "pathnames.h"
64 #include "clientloop.h"
67 #include "sshconnect.h"
74 #include "monitor_fdpass.h"
81 extern char *__progname;
83 /* Flag indicating whether debug mode is on. This can be set on the command line. */
86 /* Flag indicating whether a tty should be allocated */
89 int force_tty_flag = 0;
91 /* don't exec a shell */
92 int no_shell_flag = 0;
95 * Flag indicating that nothing should be read from stdin. This can be set
96 * on the command line.
98 int stdin_null_flag = 0;
101 * Flag indicating that ssh should fork after authentication. This is useful
102 * so that the passphrase can be entered manually, and then ssh goes to the
105 int fork_after_authentication_flag = 0;
108 * General data structure for command line options and options configurable
109 * in configuration files. See readconf.h.
113 /* optional user configfile */
117 * Name of the host we are connecting to. This is the name given on the
118 * command line, or the HostName specified for the user-supplied name in a
119 * configuration file.
123 /* socket address the host resolves to */
124 struct sockaddr_storage hostaddr;
126 /* Private host keys. */
127 Sensitive sensitive_data;
129 /* Original real UID. */
130 uid_t original_real_uid;
131 uid_t original_effective_uid;
133 /* command to be executed */
136 /* Should we execute a command or invoke a subsystem? */
137 int subsystem_flag = 0;
139 /* # of replies received for global requests */
140 static int client_global_request_id = 0;
142 /* pid of proxycommand child process */
143 pid_t proxy_command_pid = 0;
145 /* fd to control socket */
148 /* Multiplexing control command */
149 static u_int mux_command = 0;
151 /* Only used in control client mode */
152 volatile sig_atomic_t control_client_terminate = 0;
153 u_int control_server_pid = 0;
155 /* Prints a help message to the user. This function never returns. */
161 "usage: ssh [-1246AaCfgkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]\n"
162 " [-D port] [-e escape_char] [-F configfile]\n"
163 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
164 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
165 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
166 " [user@]hostname [command]\n"
171 static int ssh_session(void);
172 static int ssh_session2(void);
173 static void load_public_identity_files(void);
174 static void control_client(const char *path);
177 * Main program for the ssh client.
180 main(int ac, char **av)
182 int i, opt, exit_status;
183 char *p, *cp, *line, buf[256];
187 extern int optind, optreset;
192 __progname = ssh_get_progname(av[0]);
196 * Save the original real uid. It will be needed later (uid-swapping
197 * may clobber the real uid).
199 original_real_uid = getuid();
200 original_effective_uid = geteuid();
203 * Use uid-swapping to give up root privileges for the duration of
204 * option processing. We will re-instantiate the rights when we are
205 * ready to create the privileged port, and will permanently drop
206 * them when the port has been created (actually, when the connection
207 * has been made, as we may need to create the port several times).
211 #ifdef HAVE_SETRLIMIT
212 /* If we are installed setuid root be careful to not drop core. */
213 if (original_real_uid != original_effective_uid) {
215 rlim.rlim_cur = rlim.rlim_max = 0;
216 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
217 fatal("setrlimit failed: %.100s", strerror(errno));
221 pw = getpwuid(original_real_uid);
223 logit("You don't exist, go away!");
226 /* Take a copy of the returned structure. */
230 * Set our umask to something reasonable, as some files are created
231 * with the default umask. This will make them world-readable but
232 * writable only by the owner, which is ok for all files for which we
233 * don't set the modes explicitly.
237 /* Initialize option structure to indicate that no values have been set. */
238 initialize_options(&options);
240 /* Parse command-line arguments. */
244 while ((opt = getopt(ac, av,
245 "1246ab:c:e:fgi:kl:m:no:p:qstvxACD:F:I:L:MNO:PR:S:TVXY")) != -1) {
248 options.protocol = SSH_PROTO_1;
251 options.protocol = SSH_PROTO_2;
254 options.address_family = AF_INET;
257 options.address_family = AF_INET6;
263 fork_after_authentication_flag = 1;
267 options.forward_x11 = 0;
270 options.forward_x11 = 1;
273 options.forward_x11 = 1;
274 options.forward_x11_trusted = 1;
277 options.gateway_ports = 1;
280 if (strcmp(optarg, "check") == 0)
281 mux_command = SSHMUX_COMMAND_ALIVE_CHECK;
282 else if (strcmp(optarg, "exit") == 0)
283 mux_command = SSHMUX_COMMAND_TERMINATE;
285 fatal("Invalid multiplex command.");
287 case 'P': /* deprecated */
288 options.use_privileged_port = 0;
291 options.forward_agent = 0;
294 options.forward_agent = 1;
297 options.gss_deleg_creds = 0;
300 if (stat(optarg, &st) < 0) {
301 fprintf(stderr, "Warning: Identity file %s "
302 "not accessible: %s.\n", optarg,
306 if (options.num_identity_files >=
307 SSH_MAX_IDENTITY_FILES)
308 fatal("Too many identity files specified "
309 "(max %d)", SSH_MAX_IDENTITY_FILES);
310 options.identity_files[options.num_identity_files++] =
315 options.smartcard_device = xstrdup(optarg);
317 fprintf(stderr, "no support for smartcards.\n");
326 if (debug_flag == 0) {
328 options.log_level = SYSLOG_LEVEL_DEBUG1;
330 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
336 fprintf(stderr, "%s, %s\n",
337 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
342 options.log_level = SYSLOG_LEVEL_QUIET;
345 if (optarg[0] == '^' && optarg[2] == 0 &&
346 (u_char) optarg[1] >= 64 &&
347 (u_char) optarg[1] < 128)
348 options.escape_char = (u_char) optarg[1] & 31;
349 else if (strlen(optarg) == 1)
350 options.escape_char = (u_char) optarg[0];
351 else if (strcmp(optarg, "none") == 0)
352 options.escape_char = SSH_ESCAPECHAR_NONE;
354 fprintf(stderr, "Bad escape character '%s'.\n",
360 if (ciphers_valid(optarg)) {
362 options.ciphers = xstrdup(optarg);
363 options.cipher = SSH_CIPHER_INVALID;
366 options.cipher = cipher_number(optarg);
367 if (options.cipher == -1) {
369 "Unknown cipher type '%s'\n",
373 if (options.cipher == SSH_CIPHER_3DES)
374 options.ciphers = "3des-cbc";
375 else if (options.cipher == SSH_CIPHER_BLOWFISH)
376 options.ciphers = "blowfish-cbc";
378 options.ciphers = (char *)-1;
382 if (mac_valid(optarg))
383 options.macs = xstrdup(optarg);
385 fprintf(stderr, "Unknown mac type '%s'\n",
391 if (options.control_master == SSHCTL_MASTER_YES)
392 options.control_master = SSHCTL_MASTER_ASK;
394 options.control_master = SSHCTL_MASTER_YES;
397 options.port = a2port(optarg);
398 if (options.port == 0) {
399 fprintf(stderr, "Bad port '%s'\n", optarg);
404 options.user = optarg;
408 if (parse_forward(&fwd, optarg))
409 add_local_forward(&options, &fwd);
412 "Bad local forwarding specification '%s'\n",
419 if (parse_forward(&fwd, optarg)) {
420 add_remote_forward(&options, &fwd);
423 "Bad remote forwarding specification "
430 cp = p = xstrdup(optarg);
431 memset(&fwd, '\0', sizeof(fwd));
432 fwd.connect_host = "socks";
433 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
434 fprintf(stderr, "Bad dynamic forwarding "
435 "specification '%.100s'\n", optarg);
439 fwd.listen_port = a2port(cp);
440 fwd.listen_host = cleanhostname(fwd.listen_host);
442 fwd.listen_port = a2port(fwd.listen_host);
443 fwd.listen_host = NULL;
446 if (fwd.listen_port == 0) {
447 fprintf(stderr, "Bad dynamic port '%s'\n",
451 add_local_forward(&options, &fwd);
456 options.compression = 1;
467 line = xstrdup(optarg);
468 if (process_config_line(&options, host ? host : "",
469 line, "command-line", 0, &dummy) != 0)
477 if (options.control_path != NULL)
478 free(options.control_path);
479 options.control_path = xstrdup(optarg);
482 options.bind_address = optarg;
495 if (ac > 0 && !host && **av != '-') {
496 if (strrchr(*av, '@')) {
498 cp = strrchr(p, '@');
499 if (cp == NULL || cp == p)
507 optind = optreset = 1;
513 /* Check that we got a host name. */
517 SSLeay_add_all_algorithms();
518 ERR_load_crypto_strings();
520 /* Initialize the command to execute on remote host. */
521 buffer_init(&command);
524 * Save the command to execute on the remote host in a buffer. There
525 * is no limit on the length of the command, except by the maximum
526 * packet size. Also sets the tty flag if there is no command.
529 /* No command specified - execute shell on a tty. */
531 if (subsystem_flag) {
533 "You must specify a subsystem to invoke.\n");
537 /* A command has been specified. Store it into the buffer. */
538 for (i = 0; i < ac; i++) {
540 buffer_append(&command, " ", 1);
541 buffer_append(&command, av[i], strlen(av[i]));
545 /* Cannot fork to background if no command. */
546 if (fork_after_authentication_flag && buffer_len(&command) == 0 && !no_shell_flag)
547 fatal("Cannot fork into background without a command to execute.");
549 /* Allocate a tty by default if no command specified. */
550 if (buffer_len(&command) == 0)
556 /* Do not allocate a tty if stdin is not a tty. */
557 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
559 logit("Pseudo-terminal will not be allocated because stdin is not a terminal.");
564 * Initialize "log" output. Since we are the client all output
565 * actually goes to stderr.
567 log_init(av[0], options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
568 SYSLOG_FACILITY_USER, 1);
571 * Read per-user configuration file. Ignore the system wide config
572 * file if the user specifies a config file on the command line.
574 if (config != NULL) {
575 if (!read_config_file(config, host, &options, 0))
576 fatal("Can't open user config file %.100s: "
577 "%.100s", config, strerror(errno));
579 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
580 _PATH_SSH_USER_CONFFILE);
581 (void)read_config_file(buf, host, &options, 1);
583 /* Read systemwide configuration file after use config. */
584 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
588 /* Fill configuration defaults. */
589 fill_default_options(&options);
591 channel_set_af(options.address_family);
594 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
598 if (options.user == NULL)
599 options.user = xstrdup(pw->pw_name);
601 if (options.hostname != NULL)
602 host = options.hostname;
604 /* Find canonic host name. */
605 if (strchr(host, '.') == 0) {
606 struct addrinfo hints;
607 struct addrinfo *ai = NULL;
609 memset(&hints, 0, sizeof(hints));
610 hints.ai_family = options.address_family;
611 hints.ai_flags = AI_CANONNAME;
612 hints.ai_socktype = SOCK_STREAM;
613 errgai = getaddrinfo(host, NULL, &hints, &ai);
615 if (ai->ai_canonname != NULL)
616 host = xstrdup(ai->ai_canonname);
621 /* force lowercase for hostkey matching */
622 if (options.host_key_alias != NULL) {
623 for (p = options.host_key_alias; *p; p++)
628 /* Get default port if port has not been set. */
629 if (options.port == 0) {
630 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
631 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
634 if (options.proxy_command != NULL &&
635 strcmp(options.proxy_command, "none") == 0)
636 options.proxy_command = NULL;
637 if (options.control_path != NULL &&
638 strcmp(options.control_path, "none") == 0)
639 options.control_path = NULL;
641 if (options.control_path != NULL) {
642 snprintf(buf, sizeof(buf), "%d", options.port);
643 cp = tilde_expand_filename(options.control_path,
645 options.control_path = percent_expand(cp, "p", buf, "h", host,
646 "r", options.user, (char *)NULL);
649 if (mux_command != 0 && options.control_path == NULL)
650 fatal("No ControlPath specified for \"-O\" command");
651 if (options.control_path != NULL)
652 control_client(options.control_path);
654 /* Open a connection to the remote host. */
655 if (ssh_connect(host, &hostaddr, options.port,
656 options.address_family, options.connection_attempts,
658 options.use_privileged_port,
660 original_effective_uid == 0 && options.use_privileged_port,
662 options.proxy_command) != 0)
666 * If we successfully made the connection, load the host private key
667 * in case we will need it later for combined rsa-rhosts
668 * authentication. This must be done before releasing extra
669 * privileges, because the file is only readable by root.
670 * If we cannot access the private keys, load the public keys
671 * instead and try to execute the ssh-keysign helper instead.
673 sensitive_data.nkeys = 0;
674 sensitive_data.keys = NULL;
675 sensitive_data.external_keysign = 0;
676 if (options.rhosts_rsa_authentication ||
677 options.hostbased_authentication) {
678 sensitive_data.nkeys = 3;
679 sensitive_data.keys = xmalloc(sensitive_data.nkeys *
683 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
684 _PATH_HOST_KEY_FILE, "", NULL);
685 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
686 _PATH_HOST_DSA_KEY_FILE, "", NULL);
687 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
688 _PATH_HOST_RSA_KEY_FILE, "", NULL);
691 if (options.hostbased_authentication == 1 &&
692 sensitive_data.keys[0] == NULL &&
693 sensitive_data.keys[1] == NULL &&
694 sensitive_data.keys[2] == NULL) {
695 sensitive_data.keys[1] = key_load_public(
696 _PATH_HOST_DSA_KEY_FILE, NULL);
697 sensitive_data.keys[2] = key_load_public(
698 _PATH_HOST_RSA_KEY_FILE, NULL);
699 sensitive_data.external_keysign = 1;
703 * Get rid of any extra privileges that we may have. We will no
704 * longer need them. Also, extra privileges could make it very hard
705 * to read identity files and other non-world-readable files from the
706 * user's home directory if it happens to be on a NFS volume where
707 * root is mapped to nobody.
709 if (original_effective_uid == 0) {
711 permanently_set_uid(pw);
715 * Now that we are back to our own permissions, create ~/.ssh
716 * directory if it doesn\'t already exist.
718 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir, strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
719 if (stat(buf, &st) < 0)
720 if (mkdir(buf, 0700) < 0)
721 error("Could not create directory '%.200s'.", buf);
723 /* load options.identity_files */
724 load_public_identity_files();
726 /* Expand ~ in known host file names. */
728 options.system_hostfile =
729 tilde_expand_filename(options.system_hostfile, original_real_uid);
730 options.user_hostfile =
731 tilde_expand_filename(options.user_hostfile, original_real_uid);
732 options.system_hostfile2 =
733 tilde_expand_filename(options.system_hostfile2, original_real_uid);
734 options.user_hostfile2 =
735 tilde_expand_filename(options.user_hostfile2, original_real_uid);
737 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
739 /* Log into the remote system. This never returns if the login fails. */
740 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr, pw);
742 /* We no longer need the private host keys. Clear them now. */
743 if (sensitive_data.nkeys != 0) {
744 for (i = 0; i < sensitive_data.nkeys; i++) {
745 if (sensitive_data.keys[i] != NULL) {
746 /* Destroys contents safely */
747 debug3("clear hostkey %d", i);
748 key_free(sensitive_data.keys[i]);
749 sensitive_data.keys[i] = NULL;
752 xfree(sensitive_data.keys);
754 for (i = 0; i < options.num_identity_files; i++) {
755 if (options.identity_files[i]) {
756 xfree(options.identity_files[i]);
757 options.identity_files[i] = NULL;
759 if (options.identity_keys[i]) {
760 key_free(options.identity_keys[i]);
761 options.identity_keys[i] = NULL;
765 exit_status = compat20 ? ssh_session2() : ssh_session();
768 if (options.control_path != NULL && control_fd != -1)
769 unlink(options.control_path);
772 * Send SIGHUP to proxy command if used. We don't wait() in
773 * case it hangs and instead rely on init to reap the child
775 if (proxy_command_pid > 1)
776 kill(proxy_command_pid, SIGHUP);
782 ssh_init_forwarding(void)
787 /* Initiate local TCP/IP port forwardings. */
788 for (i = 0; i < options.num_local_forwards; i++) {
789 debug("Local connections to %.200s:%d forwarded to remote "
791 (options.local_forwards[i].listen_host == NULL) ?
792 (options.gateway_ports ? "*" : "LOCALHOST") :
793 options.local_forwards[i].listen_host,
794 options.local_forwards[i].listen_port,
795 options.local_forwards[i].connect_host,
796 options.local_forwards[i].connect_port);
797 success += channel_setup_local_fwd_listener(
798 options.local_forwards[i].listen_host,
799 options.local_forwards[i].listen_port,
800 options.local_forwards[i].connect_host,
801 options.local_forwards[i].connect_port,
802 options.gateway_ports);
804 if (i > 0 && success == 0)
805 error("Could not request local forwarding.");
807 /* Initiate remote TCP/IP port forwardings. */
808 for (i = 0; i < options.num_remote_forwards; i++) {
809 debug("Remote connections from %.200s:%d forwarded to "
810 "local address %.200s:%d",
811 (options.remote_forwards[i].listen_host == NULL) ?
812 (options.gateway_ports ? "*" : "LOCALHOST") :
813 options.remote_forwards[i].listen_host,
814 options.remote_forwards[i].listen_port,
815 options.remote_forwards[i].connect_host,
816 options.remote_forwards[i].connect_port);
817 channel_request_remote_forwarding(
818 options.remote_forwards[i].listen_host,
819 options.remote_forwards[i].listen_port,
820 options.remote_forwards[i].connect_host,
821 options.remote_forwards[i].connect_port);
826 check_agent_present(void)
828 if (options.forward_agent) {
829 /* Clear agent forwarding if we don\'t have an agent. */
830 if (!ssh_agent_present())
831 options.forward_agent = 0;
845 /* Enable compression if requested. */
846 if (options.compression) {
847 debug("Requesting compression at level %d.", options.compression_level);
849 if (options.compression_level < 1 || options.compression_level > 9)
850 fatal("Compression level must be from 1 (fast) to 9 (slow, best).");
852 /* Send the request. */
853 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
854 packet_put_int(options.compression_level);
857 type = packet_read();
858 if (type == SSH_SMSG_SUCCESS)
859 packet_start_compression(options.compression_level);
860 else if (type == SSH_SMSG_FAILURE)
861 logit("Warning: Remote host refused compression.");
863 packet_disconnect("Protocol error waiting for compression response.");
865 /* Allocate a pseudo tty if appropriate. */
867 debug("Requesting pty.");
869 /* Start the packet. */
870 packet_start(SSH_CMSG_REQUEST_PTY);
872 /* Store TERM in the packet. There is no limit on the
873 length of the string. */
877 packet_put_cstring(cp);
879 /* Store window size in the packet. */
880 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
881 memset(&ws, 0, sizeof(ws));
882 packet_put_int(ws.ws_row);
883 packet_put_int(ws.ws_col);
884 packet_put_int(ws.ws_xpixel);
885 packet_put_int(ws.ws_ypixel);
887 /* Store tty modes in the packet. */
888 tty_make_modes(fileno(stdin), NULL);
890 /* Send the packet, and wait for it to leave. */
894 /* Read response from the server. */
895 type = packet_read();
896 if (type == SSH_SMSG_SUCCESS) {
899 } else if (type == SSH_SMSG_FAILURE)
900 logit("Warning: Remote host failed or refused to allocate a pseudo tty.");
902 packet_disconnect("Protocol error waiting for pty request response.");
904 /* Request X11 forwarding if enabled and DISPLAY is set. */
905 display = getenv("DISPLAY");
906 if (options.forward_x11 && display != NULL) {
908 /* Get reasonable local authentication information. */
909 client_x11_get_proto(display, options.xauth_location,
910 options.forward_x11_trusted, &proto, &data);
911 /* Request forwarding with authentication spoofing. */
912 debug("Requesting X11 forwarding with authentication spoofing.");
913 x11_request_forwarding_with_spoofing(0, display, proto, data);
915 /* Read response from the server. */
916 type = packet_read();
917 if (type == SSH_SMSG_SUCCESS) {
919 } else if (type == SSH_SMSG_FAILURE) {
920 logit("Warning: Remote host denied X11 forwarding.");
922 packet_disconnect("Protocol error waiting for X11 forwarding");
925 /* Tell the packet module whether this is an interactive session. */
926 packet_set_interactive(interactive);
928 /* Request authentication agent forwarding if appropriate. */
929 check_agent_present();
931 if (options.forward_agent) {
932 debug("Requesting authentication agent forwarding.");
933 auth_request_forwarding();
935 /* Read response from the server. */
936 type = packet_read();
938 if (type != SSH_SMSG_SUCCESS)
939 logit("Warning: Remote host denied authentication agent forwarding.");
942 /* Initiate port forwardings. */
943 ssh_init_forwarding();
945 /* If requested, let ssh continue in the background. */
946 if (fork_after_authentication_flag)
947 if (daemon(1, 1) < 0)
948 fatal("daemon() failed: %.200s", strerror(errno));
951 * If a command was specified on the command line, execute the
952 * command now. Otherwise request the server to start a shell.
954 if (buffer_len(&command) > 0) {
955 int len = buffer_len(&command);
958 debug("Sending command: %.*s", len, (u_char *)buffer_ptr(&command));
959 packet_start(SSH_CMSG_EXEC_CMD);
960 packet_put_string(buffer_ptr(&command), buffer_len(&command));
964 debug("Requesting shell.");
965 packet_start(SSH_CMSG_EXEC_SHELL);
970 /* Enter the interactive session. */
971 return client_loop(have_tty, tty_flag ?
972 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
976 ssh_subsystem_reply(int type, u_int32_t seq, void *ctxt)
980 id = packet_get_int();
981 len = buffer_len(&command);
985 if (type == SSH2_MSG_CHANNEL_FAILURE)
986 fatal("Request for subsystem '%.*s' failed on channel %d",
987 len, (u_char *)buffer_ptr(&command), id);
991 client_global_request_reply_fwd(int type, u_int32_t seq, void *ctxt)
995 i = client_global_request_id++;
996 if (i >= options.num_remote_forwards)
998 debug("remote forward %s for: listen %d, connect %s:%d",
999 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1000 options.remote_forwards[i].listen_port,
1001 options.remote_forwards[i].connect_host,
1002 options.remote_forwards[i].connect_port);
1003 if (type == SSH2_MSG_REQUEST_FAILURE)
1004 logit("Warning: remote port forwarding failed for listen "
1005 "port %d", options.remote_forwards[i].listen_port);
1009 ssh_control_listener(void)
1011 struct sockaddr_un addr;
1015 if (options.control_path == NULL ||
1016 options.control_master == SSHCTL_MASTER_NO)
1019 debug("setting up multiplex master socket");
1021 memset(&addr, '\0', sizeof(addr));
1022 addr.sun_family = AF_UNIX;
1023 addr_len = offsetof(struct sockaddr_un, sun_path) +
1024 strlen(options.control_path) + 1;
1026 if (strlcpy(addr.sun_path, options.control_path,
1027 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1028 fatal("ControlPath too long");
1030 if ((control_fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1031 fatal("%s socket(): %s\n", __func__, strerror(errno));
1033 old_umask = umask(0177);
1034 if (bind(control_fd, (struct sockaddr*)&addr, addr_len) == -1) {
1036 if (errno == EINVAL || errno == EADDRINUSE)
1037 fatal("ControlSocket %s already exists",
1038 options.control_path);
1040 fatal("%s bind(): %s\n", __func__, strerror(errno));
1044 if (listen(control_fd, 64) == -1)
1045 fatal("%s listen(): %s\n", __func__, strerror(errno));
1047 set_nonblock(control_fd);
1050 /* request pty/x11/agent/tcpfwd/shell for channel */
1052 ssh_session2_setup(int id, void *arg)
1054 extern char **environ;
1055 const char *display;
1056 int interactive = tty_flag;
1058 display = getenv("DISPLAY");
1059 if (options.forward_x11 && display != NULL) {
1061 /* Get reasonable local authentication information. */
1062 client_x11_get_proto(display, options.xauth_location,
1063 options.forward_x11_trusted, &proto, &data);
1064 /* Request forwarding with authentication spoofing. */
1065 debug("Requesting X11 forwarding with authentication spoofing.");
1066 x11_request_forwarding_with_spoofing(id, display, proto, data);
1068 /* XXX wait for reply */
1071 check_agent_present();
1072 if (options.forward_agent) {
1073 debug("Requesting authentication agent forwarding.");
1074 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1078 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1079 NULL, fileno(stdin), &command, environ, &ssh_subsystem_reply);
1081 packet_set_interactive(interactive);
1084 /* open new channel for a session */
1086 ssh_session2_open(void)
1089 int window, packetmax, in, out, err;
1091 if (stdin_null_flag) {
1092 in = open(_PATH_DEVNULL, O_RDONLY);
1094 in = dup(STDIN_FILENO);
1096 out = dup(STDOUT_FILENO);
1097 err = dup(STDERR_FILENO);
1099 if (in < 0 || out < 0 || err < 0)
1100 fatal("dup() in/out/err failed");
1102 /* enable nonblocking unless tty */
1110 window = CHAN_SES_WINDOW_DEFAULT;
1111 packetmax = CHAN_SES_PACKET_DEFAULT;
1117 "session", SSH_CHANNEL_OPENING, in, out, err,
1118 window, packetmax, CHAN_EXTENDED_WRITE,
1119 "client-session", /*nonblock*/0);
1121 debug3("ssh_session2_open: channel_new: %d", c->self);
1123 channel_send_open(c->self);
1125 channel_register_confirm(c->self, ssh_session2_setup, NULL);
1135 /* XXX should be pre-session */
1136 ssh_init_forwarding();
1137 ssh_control_listener();
1139 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1140 id = ssh_session2_open();
1142 /* If requested, let ssh continue in the background. */
1143 if (fork_after_authentication_flag)
1144 if (daemon(1, 1) < 0)
1145 fatal("daemon() failed: %.200s", strerror(errno));
1147 return client_loop(tty_flag, tty_flag ?
1148 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1152 load_public_identity_files(void)
1160 if (options.smartcard_device != NULL &&
1161 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1162 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL ) {
1164 for (i = 0; keys[i] != NULL; i++) {
1166 memmove(&options.identity_files[1], &options.identity_files[0],
1167 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1168 memmove(&options.identity_keys[1], &options.identity_keys[0],
1169 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1170 options.num_identity_files++;
1171 options.identity_keys[0] = keys[i];
1172 options.identity_files[0] = sc_get_key_label(keys[i]);
1174 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1175 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1179 #endif /* SMARTCARD */
1180 for (; i < options.num_identity_files; i++) {
1181 filename = tilde_expand_filename(options.identity_files[i],
1183 public = key_load_public(filename, NULL);
1184 debug("identity file %s type %d", filename,
1185 public ? public->type : -1);
1186 xfree(options.identity_files[i]);
1187 options.identity_files[i] = filename;
1188 options.identity_keys[i] = public;
1193 control_client_sighandler(int signo)
1195 control_client_terminate = signo;
1199 control_client_sigrelay(int signo)
1201 if (control_server_pid > 1)
1202 kill(control_server_pid, signo);
1206 env_permitted(char *env)
1209 char name[1024], *cp;
1211 strlcpy(name, env, sizeof(name));
1212 if ((cp = strchr(name, '=')) == NULL)
1217 for (i = 0; i < options.num_send_env; i++)
1218 if (match_pattern(name, options.send_env[i]))
1225 control_client(const char *path)
1227 struct sockaddr_un addr;
1228 int i, r, fd, sock, exitval, num_env, addr_len;
1231 extern char **environ;
1234 if (mux_command == 0)
1235 mux_command = SSHMUX_COMMAND_OPEN;
1237 switch (options.control_master) {
1238 case SSHCTL_MASTER_AUTO:
1239 case SSHCTL_MASTER_AUTO_ASK:
1240 debug("auto-mux: Trying existing master");
1242 case SSHCTL_MASTER_NO:
1248 memset(&addr, '\0', sizeof(addr));
1249 addr.sun_family = AF_UNIX;
1250 addr_len = offsetof(struct sockaddr_un, sun_path) +
1253 if (strlcpy(addr.sun_path, path,
1254 sizeof(addr.sun_path)) >= sizeof(addr.sun_path))
1255 fatal("ControlPath too long");
1257 if ((sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0)
1258 fatal("%s socket(): %s", __func__, strerror(errno));
1260 if (connect(sock, (struct sockaddr*)&addr, addr_len) == -1) {
1261 if (mux_command != SSHMUX_COMMAND_OPEN) {
1262 fatal("Control socket connect(%.100s): %s", path,
1265 if (errno == ENOENT)
1266 debug("Control socket \"%.100s\" does not exist", path);
1268 error("Control socket connect(%.100s): %s", path,
1275 if (stdin_null_flag) {
1276 if ((fd = open(_PATH_DEVNULL, O_RDONLY)) == -1)
1277 fatal("open(/dev/null): %s", strerror(errno));
1278 if (dup2(fd, STDIN_FILENO) == -1)
1279 fatal("dup2: %s", strerror(errno));
1280 if (fd > STDERR_FILENO)
1284 term = getenv("TERM");
1288 flags |= SSHMUX_FLAG_TTY;
1290 flags |= SSHMUX_FLAG_SUBSYS;
1291 if (options.forward_x11)
1292 flags |= SSHMUX_FLAG_X11_FWD;
1293 if (options.forward_agent)
1294 flags |= SSHMUX_FLAG_AGENT_FWD;
1298 /* Send our command to server */
1299 buffer_put_int(&m, mux_command);
1300 buffer_put_int(&m, flags);
1301 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1302 fatal("%s: msg_send", __func__);
1305 /* Get authorisation status and PID of controlee */
1306 if (ssh_msg_recv(sock, &m) == -1)
1307 fatal("%s: msg_recv", __func__);
1308 if (buffer_get_char(&m) != SSHMUX_VER)
1309 fatal("%s: wrong version", __func__);
1310 if (buffer_get_int(&m) != 1)
1311 fatal("Connection to master denied");
1312 control_server_pid = buffer_get_int(&m);
1316 switch (mux_command) {
1317 case SSHMUX_COMMAND_ALIVE_CHECK:
1318 fprintf(stderr, "Master running (pid=%d)\r\n",
1319 control_server_pid);
1321 case SSHMUX_COMMAND_TERMINATE:
1322 fprintf(stderr, "Exit request sent.\r\n");
1324 case SSHMUX_COMMAND_OPEN:
1325 /* continue below */
1328 fatal("silly mux_command %d", mux_command);
1331 /* SSHMUX_COMMAND_OPEN */
1332 buffer_put_cstring(&m, term ? term : "");
1333 buffer_append(&command, "\0", 1);
1334 buffer_put_cstring(&m, buffer_ptr(&command));
1336 if (options.num_send_env == 0 || environ == NULL) {
1337 buffer_put_int(&m, 0);
1339 /* Pass environment */
1341 for (i = 0; environ[i] != NULL; i++)
1342 if (env_permitted(environ[i]))
1343 num_env++; /* Count */
1345 buffer_put_int(&m, num_env);
1347 for (i = 0; environ[i] != NULL && num_env >= 0; i++)
1348 if (env_permitted(environ[i])) {
1350 buffer_put_cstring(&m, environ[i]);
1354 if (ssh_msg_send(sock, SSHMUX_VER, &m) == -1)
1355 fatal("%s: msg_send", __func__);
1357 mm_send_fd(sock, STDIN_FILENO);
1358 mm_send_fd(sock, STDOUT_FILENO);
1359 mm_send_fd(sock, STDERR_FILENO);
1361 /* Wait for reply, so master has a chance to gather ttymodes */
1363 if (ssh_msg_recv(sock, &m) == -1)
1364 fatal("%s: msg_recv", __func__);
1365 if (buffer_get_char(&m) != SSHMUX_VER)
1366 fatal("%s: wrong version", __func__);
1369 signal(SIGHUP, control_client_sighandler);
1370 signal(SIGINT, control_client_sighandler);
1371 signal(SIGTERM, control_client_sighandler);
1372 signal(SIGWINCH, control_client_sigrelay);
1377 /* Stick around until the controlee closes the client_fd */
1379 for (;!control_client_terminate;) {
1380 r = read(sock, &exitval, sizeof(exitval));
1382 debug2("Received EOF from master");
1386 debug2("Received exit status from master %d", exitval);
1387 if (r == -1 && errno != EINTR)
1388 fatal("%s: read %s", __func__, strerror(errno));
1391 if (control_client_terminate)
1392 debug2("Exiting on signal %d", control_client_terminate);
1398 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
1399 fprintf(stderr, "Connection to master closed.\r\n");