1 /* $OpenBSD: ssh.c,v 1.335 2010/02/26 20:29:54 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
50 #include <sys/resource.h>
51 #include <sys/ioctl.h>
52 #include <sys/param.h>
53 #include <sys/socket.h>
71 #include <netinet/in.h>
72 #include <arpa/inet.h>
74 #include <openssl/evp.h>
75 #include <openssl/err.h>
76 #include "openbsd-compat/openssl-compat.h"
77 #include "openbsd-compat/sys-queue.h"
91 #include "pathnames.h"
93 #include "clientloop.h"
96 #include "sshconnect.h"
108 #include "ssh-pkcs11.h"
111 extern char *__progname;
113 /* Flag indicating whether debug mode is on. May be set on the command line. */
116 /* Flag indicating whether a tty should be allocated */
119 int force_tty_flag = 0;
121 /* don't exec a shell */
122 int no_shell_flag = 0;
125 * Flag indicating that nothing should be read from stdin. This can be set
126 * on the command line.
128 int stdin_null_flag = 0;
131 * Flag indicating that ssh should fork after authentication. This is useful
132 * so that the passphrase can be entered manually, and then ssh goes to the
135 int fork_after_authentication_flag = 0;
137 /* forward stdio to remote host and port */
138 char *stdio_forward_host = NULL;
139 int stdio_forward_port = 0;
142 * General data structure for command line options and options configurable
143 * in configuration files. See readconf.h.
147 /* optional user configfile */
151 * Name of the host we are connecting to. This is the name given on the
152 * command line, or the HostName specified for the user-supplied name in a
153 * configuration file.
157 /* socket address the host resolves to */
158 struct sockaddr_storage hostaddr;
160 /* Private host keys. */
161 Sensitive sensitive_data;
163 /* Original real UID. */
164 uid_t original_real_uid;
165 uid_t original_effective_uid;
167 /* command to be executed */
170 /* Should we execute a command or invoke a subsystem? */
171 int subsystem_flag = 0;
173 /* # of replies received for global requests */
174 static int remote_forward_confirms_received = 0;
176 /* pid of proxycommand child process */
177 pid_t proxy_command_pid = 0;
180 extern int muxserver_sock;
181 extern u_int muxclient_command;
183 /* Prints a help message to the user. This function never returns. */
189 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
190 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
191 " [-I pkcs11] [-i identity_file]\n"
192 " [-L [bind_address:]port:host:hostport]\n"
193 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
194 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
195 " [-W host:port] [-w local_tun[:remote_tun]]\n"
196 " [user@]hostname [command]\n"
201 static int ssh_session(void);
202 static int ssh_session2(void);
203 static void load_public_identity_files(void);
205 /* from muxclient.c */
206 void muxclient(const char *);
207 void muxserver_listen(void);
210 * Main program for the ssh client.
213 main(int ac, char **av)
215 int i, r, opt, exit_status, use_syslog;
216 char *p, *cp, *line, *argv0, buf[MAXPATHLEN];
219 int dummy, timeout_ms;
220 extern int optind, optreset;
225 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
228 __progname = ssh_get_progname(av[0]);
232 * Save the original real uid. It will be needed later (uid-swapping
233 * may clobber the real uid).
235 original_real_uid = getuid();
236 original_effective_uid = geteuid();
239 * Use uid-swapping to give up root privileges for the duration of
240 * option processing. We will re-instantiate the rights when we are
241 * ready to create the privileged port, and will permanently drop
242 * them when the port has been created (actually, when the connection
243 * has been made, as we may need to create the port several times).
247 #ifdef HAVE_SETRLIMIT
248 /* If we are installed setuid root be careful to not drop core. */
249 if (original_real_uid != original_effective_uid) {
251 rlim.rlim_cur = rlim.rlim_max = 0;
252 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
253 fatal("setrlimit failed: %.100s", strerror(errno));
257 pw = getpwuid(original_real_uid);
259 logit("You don't exist, go away!");
262 /* Take a copy of the returned structure. */
266 * Set our umask to something reasonable, as some files are created
267 * with the default umask. This will make them world-readable but
268 * writable only by the owner, which is ok for all files for which we
269 * don't set the modes explicitly.
274 * Initialize option structure to indicate that no values have been
277 initialize_options(&options);
279 /* Parse command-line arguments. */
285 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
286 "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
289 options.protocol = SSH_PROTO_1;
292 options.protocol = SSH_PROTO_2;
295 options.address_family = AF_INET;
298 options.address_family = AF_INET6;
304 fork_after_authentication_flag = 1;
308 options.forward_x11 = 0;
311 options.forward_x11 = 1;
317 options.forward_x11 = 1;
318 options.forward_x11_trusted = 1;
321 options.gateway_ports = 1;
324 if (stdio_forward_host != NULL)
325 fatal("Cannot specify multiplexing "
327 else if (muxclient_command != 0)
328 fatal("Multiplexing command already specified");
329 if (strcmp(optarg, "check") == 0)
330 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
331 else if (strcmp(optarg, "exit") == 0)
332 muxclient_command = SSHMUX_COMMAND_TERMINATE;
334 fatal("Invalid multiplex command.");
336 case 'P': /* deprecated */
337 options.use_privileged_port = 0;
340 options.forward_agent = 0;
343 options.forward_agent = 1;
346 options.gss_deleg_creds = 0;
349 options.gss_authentication = 1;
350 options.gss_deleg_creds = 1;
353 if (stat(optarg, &st) < 0) {
354 fprintf(stderr, "Warning: Identity file %s "
355 "not accessible: %s.\n", optarg,
359 if (options.num_identity_files >=
360 SSH_MAX_IDENTITY_FILES)
361 fatal("Too many identity files specified "
362 "(max %d)", SSH_MAX_IDENTITY_FILES);
363 options.identity_files[options.num_identity_files++] =
368 options.pkcs11_provider = xstrdup(optarg);
370 fprintf(stderr, "no support for PKCS#11.\n");
379 if (debug_flag == 0) {
381 options.log_level = SYSLOG_LEVEL_DEBUG1;
383 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
389 fprintf(stderr, "%s, %s\n",
390 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
395 if (options.tun_open == -1)
396 options.tun_open = SSH_TUNMODE_DEFAULT;
397 options.tun_local = a2tun(optarg, &options.tun_remote);
398 if (options.tun_local == SSH_TUNID_ERR) {
400 "Bad tun device '%s'\n", optarg);
405 if (stdio_forward_host != NULL)
406 fatal("stdio forward already specified");
407 if (muxclient_command != 0)
408 fatal("Cannot specify stdio forward with -O");
409 if (parse_forward(&fwd, optarg, 1, 0)) {
410 stdio_forward_host = fwd.listen_host;
411 stdio_forward_port = fwd.listen_port;
412 xfree(fwd.connect_host);
415 "Bad stdio forwarding specification '%s'\n",
421 options.clear_forwardings = 1;
422 options.exit_on_forward_failure = 1;
425 options.log_level = SYSLOG_LEVEL_QUIET;
428 if (optarg[0] == '^' && optarg[2] == 0 &&
429 (u_char) optarg[1] >= 64 &&
430 (u_char) optarg[1] < 128)
431 options.escape_char = (u_char) optarg[1] & 31;
432 else if (strlen(optarg) == 1)
433 options.escape_char = (u_char) optarg[0];
434 else if (strcmp(optarg, "none") == 0)
435 options.escape_char = SSH_ESCAPECHAR_NONE;
437 fprintf(stderr, "Bad escape character '%s'.\n",
443 if (ciphers_valid(optarg)) {
445 options.ciphers = xstrdup(optarg);
446 options.cipher = SSH_CIPHER_INVALID;
449 options.cipher = cipher_number(optarg);
450 if (options.cipher == -1) {
452 "Unknown cipher type '%s'\n",
456 if (options.cipher == SSH_CIPHER_3DES)
457 options.ciphers = "3des-cbc";
458 else if (options.cipher == SSH_CIPHER_BLOWFISH)
459 options.ciphers = "blowfish-cbc";
461 options.ciphers = (char *)-1;
465 if (mac_valid(optarg))
466 options.macs = xstrdup(optarg);
468 fprintf(stderr, "Unknown mac type '%s'\n",
474 if (options.control_master == SSHCTL_MASTER_YES)
475 options.control_master = SSHCTL_MASTER_ASK;
477 options.control_master = SSHCTL_MASTER_YES;
480 options.port = a2port(optarg);
481 if (options.port <= 0) {
482 fprintf(stderr, "Bad port '%s'\n", optarg);
487 options.user = optarg;
491 if (parse_forward(&fwd, optarg, 0, 0))
492 add_local_forward(&options, &fwd);
495 "Bad local forwarding specification '%s'\n",
502 if (parse_forward(&fwd, optarg, 0, 1)) {
503 add_remote_forward(&options, &fwd);
506 "Bad remote forwarding specification "
513 if (parse_forward(&fwd, optarg, 1, 0)) {
514 add_local_forward(&options, &fwd);
517 "Bad dynamic forwarding specification "
524 options.compression = 1;
535 line = xstrdup(optarg);
536 if (process_config_line(&options, host ? host : "",
537 line, "command-line", 0, &dummy) != 0)
545 if (options.control_path != NULL)
546 free(options.control_path);
547 options.control_path = xstrdup(optarg);
550 options.bind_address = optarg;
563 if (ac > 0 && !host) {
564 if (strrchr(*av, '@')) {
566 cp = strrchr(p, '@');
567 if (cp == NULL || cp == p)
575 optind = optreset = 1;
581 /* Check that we got a host name. */
585 SSLeay_add_all_algorithms();
586 ERR_load_crypto_strings();
588 /* Initialize the command to execute on remote host. */
589 buffer_init(&command);
592 * Save the command to execute on the remote host in a buffer. There
593 * is no limit on the length of the command, except by the maximum
594 * packet size. Also sets the tty flag if there is no command.
597 /* No command specified - execute shell on a tty. */
599 if (subsystem_flag) {
601 "You must specify a subsystem to invoke.\n");
605 /* A command has been specified. Store it into the buffer. */
606 for (i = 0; i < ac; i++) {
608 buffer_append(&command, " ", 1);
609 buffer_append(&command, av[i], strlen(av[i]));
613 /* Cannot fork to background if no command. */
614 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
616 fatal("Cannot fork into background without a command "
619 /* Allocate a tty by default if no command specified. */
620 if (buffer_len(&command) == 0)
626 /* Do not allocate a tty if stdin is not a tty. */
627 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
629 logit("Pseudo-terminal will not be allocated because "
630 "stdin is not a terminal.");
635 * Initialize "log" output. Since we are the client all output
636 * actually goes to stderr.
639 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
640 SYSLOG_FACILITY_USER, !use_syslog);
643 * Read per-user configuration file. Ignore the system wide config
644 * file if the user specifies a config file on the command line.
646 if (config != NULL) {
647 if (!read_config_file(config, host, &options, 0))
648 fatal("Can't open user config file %.100s: "
649 "%.100s", config, strerror(errno));
651 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
652 _PATH_SSH_USER_CONFFILE);
653 if (r > 0 && (size_t)r < sizeof(buf))
654 (void)read_config_file(buf, host, &options, 1);
656 /* Read systemwide configuration file after use config. */
657 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
661 /* Fill configuration defaults. */
662 fill_default_options(&options);
664 channel_set_af(options.address_family);
667 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
671 if (options.user == NULL)
672 options.user = xstrdup(pw->pw_name);
674 /* Get default port if port has not been set. */
675 if (options.port == 0) {
676 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
677 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
680 if (options.local_command != NULL) {
681 char thishost[NI_MAXHOST];
683 if (gethostname(thishost, sizeof(thishost)) == -1)
684 fatal("gethostname: %s", strerror(errno));
685 snprintf(buf, sizeof(buf), "%d", options.port);
686 debug3("expanding LocalCommand: %s", options.local_command);
687 cp = options.local_command;
688 options.local_command = percent_expand(cp, "d", pw->pw_dir,
689 "h", options.hostname? options.hostname : host,
690 "l", thishost, "n", host, "r", options.user, "p", buf,
691 "u", pw->pw_name, (char *)NULL);
692 debug3("expanded LocalCommand: %s", options.local_command);
696 if (options.hostname != NULL)
697 host = options.hostname;
699 /* Find canonic host name. */
700 if (strchr(host, '.') == 0) {
701 struct addrinfo hints;
702 struct addrinfo *ai = NULL;
704 memset(&hints, 0, sizeof(hints));
705 hints.ai_family = options.address_family;
706 hints.ai_flags = AI_CANONNAME;
707 hints.ai_socktype = SOCK_STREAM;
708 errgai = getaddrinfo(host, NULL, &hints, &ai);
710 if (ai->ai_canonname != NULL)
711 host = xstrdup(ai->ai_canonname);
716 /* force lowercase for hostkey matching */
717 if (options.host_key_alias != NULL) {
718 for (p = options.host_key_alias; *p; p++)
720 *p = (char)tolower(*p);
723 if (options.proxy_command != NULL &&
724 strcmp(options.proxy_command, "none") == 0) {
725 xfree(options.proxy_command);
726 options.proxy_command = NULL;
728 if (options.control_path != NULL &&
729 strcmp(options.control_path, "none") == 0) {
730 xfree(options.control_path);
731 options.control_path = NULL;
734 if (options.control_path != NULL) {
735 char thishost[NI_MAXHOST];
737 if (gethostname(thishost, sizeof(thishost)) == -1)
738 fatal("gethostname: %s", strerror(errno));
739 snprintf(buf, sizeof(buf), "%d", options.port);
740 cp = tilde_expand_filename(options.control_path,
742 xfree(options.control_path);
743 options.control_path = percent_expand(cp, "p", buf, "h", host,
744 "r", options.user, "l", thishost, (char *)NULL);
747 if (muxclient_command != 0 && options.control_path == NULL)
748 fatal("No ControlPath specified for \"-O\" command");
749 if (options.control_path != NULL)
750 muxclient(options.control_path);
752 timeout_ms = options.connection_timeout * 1000;
754 /* Open a connection to the remote host. */
755 if (ssh_connect(host, &hostaddr, options.port,
756 options.address_family, options.connection_attempts, &timeout_ms,
757 options.tcp_keep_alive,
759 options.use_privileged_port,
761 original_effective_uid == 0 && options.use_privileged_port,
763 options.proxy_command) != 0)
767 debug3("timeout: %d ms remain after connect", timeout_ms);
770 * If we successfully made the connection, load the host private key
771 * in case we will need it later for combined rsa-rhosts
772 * authentication. This must be done before releasing extra
773 * privileges, because the file is only readable by root.
774 * If we cannot access the private keys, load the public keys
775 * instead and try to execute the ssh-keysign helper instead.
777 sensitive_data.nkeys = 0;
778 sensitive_data.keys = NULL;
779 sensitive_data.external_keysign = 0;
780 if (options.rhosts_rsa_authentication ||
781 options.hostbased_authentication) {
782 sensitive_data.nkeys = 3;
783 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
787 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
788 _PATH_HOST_KEY_FILE, "", NULL, NULL);
789 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
790 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
791 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
792 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
795 if (options.hostbased_authentication == 1 &&
796 sensitive_data.keys[0] == NULL &&
797 sensitive_data.keys[1] == NULL &&
798 sensitive_data.keys[2] == NULL) {
799 sensitive_data.keys[1] = key_load_public(
800 _PATH_HOST_DSA_KEY_FILE, NULL);
801 sensitive_data.keys[2] = key_load_public(
802 _PATH_HOST_RSA_KEY_FILE, NULL);
803 sensitive_data.external_keysign = 1;
807 * Get rid of any extra privileges that we may have. We will no
808 * longer need them. Also, extra privileges could make it very hard
809 * to read identity files and other non-world-readable files from the
810 * user's home directory if it happens to be on a NFS volume where
811 * root is mapped to nobody.
813 if (original_effective_uid == 0) {
815 permanently_set_uid(pw);
819 * Now that we are back to our own permissions, create ~/.ssh
820 * directory if it doesn't already exist.
822 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
823 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
824 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
825 if (mkdir(buf, 0700) < 0)
826 error("Could not create directory '%.200s'.", buf);
828 /* load options.identity_files */
829 load_public_identity_files();
831 /* Expand ~ in known host file names. */
833 options.system_hostfile =
834 tilde_expand_filename(options.system_hostfile, original_real_uid);
835 options.user_hostfile =
836 tilde_expand_filename(options.user_hostfile, original_real_uid);
837 options.system_hostfile2 =
838 tilde_expand_filename(options.system_hostfile2, original_real_uid);
839 options.user_hostfile2 =
840 tilde_expand_filename(options.user_hostfile2, original_real_uid);
842 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
844 /* Log into the remote system. Never returns if the login fails. */
845 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
848 /* We no longer need the private host keys. Clear them now. */
849 if (sensitive_data.nkeys != 0) {
850 for (i = 0; i < sensitive_data.nkeys; i++) {
851 if (sensitive_data.keys[i] != NULL) {
852 /* Destroys contents safely */
853 debug3("clear hostkey %d", i);
854 key_free(sensitive_data.keys[i]);
855 sensitive_data.keys[i] = NULL;
858 xfree(sensitive_data.keys);
860 for (i = 0; i < options.num_identity_files; i++) {
861 if (options.identity_files[i]) {
862 xfree(options.identity_files[i]);
863 options.identity_files[i] = NULL;
865 if (options.identity_keys[i]) {
866 key_free(options.identity_keys[i]);
867 options.identity_keys[i] = NULL;
871 exit_status = compat20 ? ssh_session2() : ssh_session();
874 if (options.control_path != NULL && muxserver_sock != -1)
875 unlink(options.control_path);
878 * Send SIGHUP to proxy command if used. We don't wait() in
879 * case it hangs and instead rely on init to reap the child
881 if (proxy_command_pid > 1)
882 kill(proxy_command_pid, SIGHUP);
887 /* Callback for remote forward global requests */
889 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
891 Forward *rfwd = (Forward *)ctxt;
893 /* XXX verbose() on failure? */
894 debug("remote forward %s for: listen %d, connect %s:%d",
895 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
896 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
897 if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
898 logit("Allocated port %u for remote forward to %s:%d",
900 rfwd->connect_host, rfwd->connect_port);
903 if (type == SSH2_MSG_REQUEST_FAILURE) {
904 if (options.exit_on_forward_failure)
905 fatal("Error: remote port forwarding failed for "
906 "listen port %d", rfwd->listen_port);
908 logit("Warning: remote port forwarding failed for "
909 "listen port %d", rfwd->listen_port);
911 if (++remote_forward_confirms_received == options.num_remote_forwards) {
912 debug("All remote forwarding requests processed");
913 if (fork_after_authentication_flag) {
914 fork_after_authentication_flag = 0;
915 if (daemon(1, 1) < 0)
916 fatal("daemon() failed: %.200s",
923 client_cleanup_stdio_fwd(int id, void *arg)
925 debug("stdio forwarding: done");
930 client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect)
935 debug3("client_setup_stdio_fwd %s:%d", host_to_connect,
938 in = dup(STDIN_FILENO);
939 out = dup(STDOUT_FILENO);
940 if (in < 0 || out < 0)
941 fatal("channel_connect_stdio_fwd: dup() in/out failed");
943 if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect,
946 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
951 ssh_init_forwarding(void)
956 if (stdio_forward_host != NULL) {
958 fatal("stdio forwarding require Protocol 2");
960 if (!client_setup_stdio_fwd(stdio_forward_host,
962 fatal("Failed to connect in stdio forward mode.");
965 /* Initiate local TCP/IP port forwardings. */
966 for (i = 0; i < options.num_local_forwards; i++) {
967 debug("Local connections to %.200s:%d forwarded to remote "
969 (options.local_forwards[i].listen_host == NULL) ?
970 (options.gateway_ports ? "*" : "LOCALHOST") :
971 options.local_forwards[i].listen_host,
972 options.local_forwards[i].listen_port,
973 options.local_forwards[i].connect_host,
974 options.local_forwards[i].connect_port);
975 success += channel_setup_local_fwd_listener(
976 options.local_forwards[i].listen_host,
977 options.local_forwards[i].listen_port,
978 options.local_forwards[i].connect_host,
979 options.local_forwards[i].connect_port,
980 options.gateway_ports);
982 if (i > 0 && success != i && options.exit_on_forward_failure)
983 fatal("Could not request local forwarding.");
984 if (i > 0 && success == 0)
985 error("Could not request local forwarding.");
987 /* Initiate remote TCP/IP port forwardings. */
988 for (i = 0; i < options.num_remote_forwards; i++) {
989 debug("Remote connections from %.200s:%d forwarded to "
990 "local address %.200s:%d",
991 (options.remote_forwards[i].listen_host == NULL) ?
992 "LOCALHOST" : options.remote_forwards[i].listen_host,
993 options.remote_forwards[i].listen_port,
994 options.remote_forwards[i].connect_host,
995 options.remote_forwards[i].connect_port);
996 if (channel_request_remote_forwarding(
997 options.remote_forwards[i].listen_host,
998 options.remote_forwards[i].listen_port,
999 options.remote_forwards[i].connect_host,
1000 options.remote_forwards[i].connect_port) < 0) {
1001 if (options.exit_on_forward_failure)
1002 fatal("Could not request remote forwarding.");
1004 logit("Warning: Could not request remote "
1007 client_register_global_confirm(ssh_confirm_remote_forward,
1008 &options.remote_forwards[i]);
1011 /* Initiate tunnel forwarding. */
1012 if (options.tun_open != SSH_TUNMODE_NO) {
1013 if (client_request_tun_fwd(options.tun_open,
1014 options.tun_local, options.tun_remote) == -1) {
1015 if (options.exit_on_forward_failure)
1016 fatal("Could not request tunnel forwarding.");
1018 error("Could not request tunnel forwarding.");
1024 check_agent_present(void)
1026 if (options.forward_agent) {
1027 /* Clear agent forwarding if we don't have an agent. */
1028 if (!ssh_agent_present())
1029 options.forward_agent = 0;
1037 int interactive = 0;
1041 const char *display;
1043 /* Enable compression if requested. */
1044 if (options.compression) {
1045 debug("Requesting compression at level %d.",
1046 options.compression_level);
1048 if (options.compression_level < 1 ||
1049 options.compression_level > 9)
1050 fatal("Compression level must be from 1 (fast) to "
1053 /* Send the request. */
1054 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1055 packet_put_int(options.compression_level);
1057 packet_write_wait();
1058 type = packet_read();
1059 if (type == SSH_SMSG_SUCCESS)
1060 packet_start_compression(options.compression_level);
1061 else if (type == SSH_SMSG_FAILURE)
1062 logit("Warning: Remote host refused compression.");
1064 packet_disconnect("Protocol error waiting for "
1065 "compression response.");
1067 /* Allocate a pseudo tty if appropriate. */
1069 debug("Requesting pty.");
1071 /* Start the packet. */
1072 packet_start(SSH_CMSG_REQUEST_PTY);
1074 /* Store TERM in the packet. There is no limit on the
1075 length of the string. */
1076 cp = getenv("TERM");
1079 packet_put_cstring(cp);
1081 /* Store window size in the packet. */
1082 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1083 memset(&ws, 0, sizeof(ws));
1084 packet_put_int((u_int)ws.ws_row);
1085 packet_put_int((u_int)ws.ws_col);
1086 packet_put_int((u_int)ws.ws_xpixel);
1087 packet_put_int((u_int)ws.ws_ypixel);
1089 /* Store tty modes in the packet. */
1090 tty_make_modes(fileno(stdin), NULL);
1092 /* Send the packet, and wait for it to leave. */
1094 packet_write_wait();
1096 /* Read response from the server. */
1097 type = packet_read();
1098 if (type == SSH_SMSG_SUCCESS) {
1101 } else if (type == SSH_SMSG_FAILURE)
1102 logit("Warning: Remote host failed or refused to "
1103 "allocate a pseudo tty.");
1105 packet_disconnect("Protocol error waiting for pty "
1106 "request response.");
1108 /* Request X11 forwarding if enabled and DISPLAY is set. */
1109 display = getenv("DISPLAY");
1110 if (options.forward_x11 && display != NULL) {
1112 /* Get reasonable local authentication information. */
1113 client_x11_get_proto(display, options.xauth_location,
1114 options.forward_x11_trusted, &proto, &data);
1115 /* Request forwarding with authentication spoofing. */
1116 debug("Requesting X11 forwarding with authentication "
1118 x11_request_forwarding_with_spoofing(0, display, proto, data);
1120 /* Read response from the server. */
1121 type = packet_read();
1122 if (type == SSH_SMSG_SUCCESS) {
1124 } else if (type == SSH_SMSG_FAILURE) {
1125 logit("Warning: Remote host denied X11 forwarding.");
1127 packet_disconnect("Protocol error waiting for X11 "
1131 /* Tell the packet module whether this is an interactive session. */
1132 packet_set_interactive(interactive);
1134 /* Request authentication agent forwarding if appropriate. */
1135 check_agent_present();
1137 if (options.forward_agent) {
1138 debug("Requesting authentication agent forwarding.");
1139 auth_request_forwarding();
1141 /* Read response from the server. */
1142 type = packet_read();
1144 if (type != SSH_SMSG_SUCCESS)
1145 logit("Warning: Remote host denied authentication agent forwarding.");
1148 /* Initiate port forwardings. */
1149 ssh_init_forwarding();
1151 /* Execute a local command */
1152 if (options.local_command != NULL &&
1153 options.permit_local_command)
1154 ssh_local_cmd(options.local_command);
1157 * If requested and we are not interested in replies to remote
1158 * forwarding requests, then let ssh continue in the background.
1160 if (fork_after_authentication_flag &&
1161 (!options.exit_on_forward_failure ||
1162 options.num_remote_forwards == 0)) {
1163 fork_after_authentication_flag = 0;
1164 if (daemon(1, 1) < 0)
1165 fatal("daemon() failed: %.200s", strerror(errno));
1169 * If a command was specified on the command line, execute the
1170 * command now. Otherwise request the server to start a shell.
1172 if (buffer_len(&command) > 0) {
1173 int len = buffer_len(&command);
1176 debug("Sending command: %.*s", len,
1177 (u_char *)buffer_ptr(&command));
1178 packet_start(SSH_CMSG_EXEC_CMD);
1179 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1181 packet_write_wait();
1183 debug("Requesting shell.");
1184 packet_start(SSH_CMSG_EXEC_SHELL);
1186 packet_write_wait();
1189 /* Enter the interactive session. */
1190 return client_loop(have_tty, tty_flag ?
1191 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1194 /* request pty/x11/agent/tcpfwd/shell for channel */
1196 ssh_session2_setup(int id, void *arg)
1198 extern char **environ;
1199 const char *display;
1200 int interactive = tty_flag;
1202 display = getenv("DISPLAY");
1203 if (options.forward_x11 && display != NULL) {
1205 /* Get reasonable local authentication information. */
1206 client_x11_get_proto(display, options.xauth_location,
1207 options.forward_x11_trusted, &proto, &data);
1208 /* Request forwarding with authentication spoofing. */
1209 debug("Requesting X11 forwarding with authentication "
1211 x11_request_forwarding_with_spoofing(id, display, proto, data);
1213 /* XXX wait for reply */
1216 check_agent_present();
1217 if (options.forward_agent) {
1218 debug("Requesting authentication agent forwarding.");
1219 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1223 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1224 NULL, fileno(stdin), &command, environ);
1226 packet_set_interactive(interactive);
1229 /* open new channel for a session */
1231 ssh_session2_open(void)
1234 int window, packetmax, in, out, err;
1236 if (stdin_null_flag) {
1237 in = open(_PATH_DEVNULL, O_RDONLY);
1239 in = dup(STDIN_FILENO);
1241 out = dup(STDOUT_FILENO);
1242 err = dup(STDERR_FILENO);
1244 if (in < 0 || out < 0 || err < 0)
1245 fatal("dup() in/out/err failed");
1247 /* enable nonblocking unless tty */
1255 window = CHAN_SES_WINDOW_DEFAULT;
1256 packetmax = CHAN_SES_PACKET_DEFAULT;
1262 "session", SSH_CHANNEL_OPENING, in, out, err,
1263 window, packetmax, CHAN_EXTENDED_WRITE,
1264 "client-session", /*nonblock*/0);
1266 debug3("ssh_session2_open: channel_new: %d", c->self);
1268 channel_send_open(c->self);
1270 channel_register_open_confirm(c->self,
1271 ssh_session2_setup, NULL);
1281 /* XXX should be pre-session */
1282 ssh_init_forwarding();
1284 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1285 id = ssh_session2_open();
1287 /* If we don't expect to open a new session, then disallow it */
1288 if (options.control_master == SSHCTL_MASTER_NO &&
1289 (datafellows & SSH_NEW_OPENSSH)) {
1290 debug("Requesting no-more-sessions@openssh.com");
1291 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1292 packet_put_cstring("no-more-sessions@openssh.com");
1297 /* Execute a local command */
1298 if (options.local_command != NULL &&
1299 options.permit_local_command)
1300 ssh_local_cmd(options.local_command);
1302 /* Start listening for multiplex clients */
1305 /* If requested, let ssh continue in the background. */
1306 if (fork_after_authentication_flag) {
1307 fork_after_authentication_flag = 0;
1308 if (daemon(1, 1) < 0)
1309 fatal("daemon() failed: %.200s", strerror(errno));
1312 if (options.use_roaming)
1315 return client_loop(tty_flag, tty_flag ?
1316 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1320 load_public_identity_files(void)
1322 char *filename, *cp, thishost[NI_MAXHOST];
1323 char *pwdir = NULL, *pwname = NULL;
1328 char *identity_files[SSH_MAX_IDENTITY_FILES];
1329 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1330 #ifdef ENABLE_PKCS11
1336 bzero(identity_files, sizeof(identity_files));
1337 bzero(identity_keys, sizeof(identity_keys));
1339 #ifdef ENABLE_PKCS11
1340 if (options.pkcs11_provider != NULL &&
1341 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1342 (pkcs11_init(!options.batch_mode) == 0) &&
1343 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1345 for (i = 0; i < nkeys; i++) {
1346 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1350 identity_keys[n_ids] = keys[i];
1351 identity_files[n_ids] =
1352 xstrdup(options.pkcs11_provider); /* XXX */
1357 #endif /* ENABLE_PKCS11 */
1358 if ((pw = getpwuid(original_real_uid)) == NULL)
1359 fatal("load_public_identity_files: getpwuid failed");
1360 pwname = xstrdup(pw->pw_name);
1361 pwdir = xstrdup(pw->pw_dir);
1362 if (gethostname(thishost, sizeof(thishost)) == -1)
1363 fatal("load_public_identity_files: gethostname: %s",
1365 for (i = 0; i < options.num_identity_files; i++) {
1366 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1367 xfree(options.identity_files[i]);
1370 cp = tilde_expand_filename(options.identity_files[i],
1372 filename = percent_expand(cp, "d", pwdir,
1373 "u", pwname, "l", thishost, "h", host,
1374 "r", options.user, (char *)NULL);
1376 public = key_load_public(filename, NULL);
1377 debug("identity file %s type %d", filename,
1378 public ? public->type : -1);
1379 xfree(options.identity_files[i]);
1380 identity_files[n_ids] = filename;
1381 identity_keys[n_ids] = public;
1383 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1386 /* Try to add the certificate variant too */
1387 xasprintf(&cp, "%s-cert", filename);
1388 public = key_load_public(cp, NULL);
1389 debug("identity file %s type %d", cp,
1390 public ? public->type : -1);
1391 if (public == NULL) {
1395 if (!key_is_cert(public)) {
1396 debug("%s: key %s type %s is not a certificate",
1397 __func__, cp, key_type(public));
1402 identity_keys[n_ids] = public;
1403 /* point to the original path, most likely the private key */
1404 identity_files[n_ids] = xstrdup(filename);
1407 options.num_identity_files = n_ids;
1408 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1409 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1411 bzero(pwname, strlen(pwname));
1413 bzero(pwdir, strlen(pwdir));