1 /* $OpenBSD: ssh.c,v 1.324 2009/02/12 03:00:56 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.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
69 #include <netinet/in.h>
70 #include <arpa/inet.h>
72 #include <openssl/evp.h>
73 #include <openssl/err.h>
74 #include "openbsd-compat/openssl-compat.h"
75 #include "openbsd-compat/sys-queue.h"
89 #include "pathnames.h"
91 #include "clientloop.h"
94 #include "sshconnect.h"
108 extern char *__progname;
110 /* Flag indicating whether debug mode is on. May be set on the command line. */
113 /* Flag indicating whether a tty should be allocated */
116 int force_tty_flag = 0;
118 /* don't exec a shell */
119 int no_shell_flag = 0;
122 * Flag indicating that nothing should be read from stdin. This can be set
123 * on the command line.
125 int stdin_null_flag = 0;
128 * Flag indicating that ssh should fork after authentication. This is useful
129 * so that the passphrase can be entered manually, and then ssh goes to the
132 int fork_after_authentication_flag = 0;
135 * General data structure for command line options and options configurable
136 * in configuration files. See readconf.h.
140 /* optional user configfile */
144 * Name of the host we are connecting to. This is the name given on the
145 * command line, or the HostName specified for the user-supplied name in a
146 * configuration file.
150 /* socket address the host resolves to */
151 struct sockaddr_storage hostaddr;
153 /* Private host keys. */
154 Sensitive sensitive_data;
156 /* Original real UID. */
157 uid_t original_real_uid;
158 uid_t original_effective_uid;
160 /* command to be executed */
163 /* Should we execute a command or invoke a subsystem? */
164 int subsystem_flag = 0;
166 /* # of replies received for global requests */
167 static int remote_forward_confirms_received = 0;
169 /* pid of proxycommand child process */
170 pid_t proxy_command_pid = 0;
173 extern int muxserver_sock;
174 extern u_int muxclient_command;
176 /* Prints a help message to the user. This function never returns. */
182 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
183 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
184 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
185 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
186 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
187 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
192 static int ssh_session(void);
193 static int ssh_session2(void);
194 static void load_public_identity_files(void);
196 /* from muxclient.c */
197 void muxclient(const char *);
198 void muxserver_listen(void);
201 * Main program for the ssh client.
204 main(int ac, char **av)
206 int i, opt, exit_status, use_syslog;
207 char *p, *cp, *line, buf[256];
210 int dummy, timeout_ms;
211 extern int optind, optreset;
216 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
219 __progname = ssh_get_progname(av[0]);
224 * Save the original real uid. It will be needed later (uid-swapping
225 * may clobber the real uid).
227 original_real_uid = getuid();
228 original_effective_uid = geteuid();
231 * Use uid-swapping to give up root privileges for the duration of
232 * option processing. We will re-instantiate the rights when we are
233 * ready to create the privileged port, and will permanently drop
234 * them when the port has been created (actually, when the connection
235 * has been made, as we may need to create the port several times).
239 #ifdef HAVE_SETRLIMIT
240 /* If we are installed setuid root be careful to not drop core. */
241 if (original_real_uid != original_effective_uid) {
243 rlim.rlim_cur = rlim.rlim_max = 0;
244 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
245 fatal("setrlimit failed: %.100s", strerror(errno));
249 pw = getpwuid(original_real_uid);
251 logit("You don't exist, go away!");
254 /* Take a copy of the returned structure. */
258 * Set our umask to something reasonable, as some files are created
259 * with the default umask. This will make them world-readable but
260 * writable only by the owner, which is ok for all files for which we
261 * don't set the modes explicitly.
266 * Initialize option structure to indicate that no values have been
269 initialize_options(&options);
271 /* Parse command-line arguments. */
276 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
277 "ACD:F:I:KL:MNO:PR:S:TVw:XYy")) != -1) {
280 options.protocol = SSH_PROTO_1;
283 options.protocol = SSH_PROTO_2;
286 options.address_family = AF_INET;
289 options.address_family = AF_INET6;
295 fork_after_authentication_flag = 1;
299 options.forward_x11 = 0;
302 options.forward_x11 = 1;
308 options.forward_x11 = 1;
309 options.forward_x11_trusted = 1;
312 options.gateway_ports = 1;
315 if (strcmp(optarg, "check") == 0)
316 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
317 else if (strcmp(optarg, "exit") == 0)
318 muxclient_command = SSHMUX_COMMAND_TERMINATE;
320 fatal("Invalid multiplex command.");
322 case 'P': /* deprecated */
323 options.use_privileged_port = 0;
326 options.forward_agent = 0;
329 options.forward_agent = 1;
332 options.gss_deleg_creds = 0;
335 options.gss_authentication = 1;
336 options.gss_deleg_creds = 1;
339 if (stat(optarg, &st) < 0) {
340 fprintf(stderr, "Warning: Identity file %s "
341 "not accessible: %s.\n", optarg,
345 if (options.num_identity_files >=
346 SSH_MAX_IDENTITY_FILES)
347 fatal("Too many identity files specified "
348 "(max %d)", SSH_MAX_IDENTITY_FILES);
349 options.identity_files[options.num_identity_files++] =
354 options.smartcard_device = xstrdup(optarg);
356 fprintf(stderr, "no support for smartcards.\n");
365 if (debug_flag == 0) {
367 options.log_level = SYSLOG_LEVEL_DEBUG1;
369 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
375 fprintf(stderr, "%s, %s\n",
376 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
381 if (options.tun_open == -1)
382 options.tun_open = SSH_TUNMODE_DEFAULT;
383 options.tun_local = a2tun(optarg, &options.tun_remote);
384 if (options.tun_local == SSH_TUNID_ERR) {
386 "Bad tun device '%s'\n", optarg);
391 options.log_level = SYSLOG_LEVEL_QUIET;
394 if (optarg[0] == '^' && optarg[2] == 0 &&
395 (u_char) optarg[1] >= 64 &&
396 (u_char) optarg[1] < 128)
397 options.escape_char = (u_char) optarg[1] & 31;
398 else if (strlen(optarg) == 1)
399 options.escape_char = (u_char) optarg[0];
400 else if (strcmp(optarg, "none") == 0)
401 options.escape_char = SSH_ESCAPECHAR_NONE;
403 fprintf(stderr, "Bad escape character '%s'.\n",
409 if (ciphers_valid(optarg)) {
411 options.ciphers = xstrdup(optarg);
412 options.cipher = SSH_CIPHER_INVALID;
415 options.cipher = cipher_number(optarg);
416 if (options.cipher == -1) {
418 "Unknown cipher type '%s'\n",
422 if (options.cipher == SSH_CIPHER_3DES)
423 options.ciphers = "3des-cbc";
424 else if (options.cipher == SSH_CIPHER_BLOWFISH)
425 options.ciphers = "blowfish-cbc";
427 options.ciphers = (char *)-1;
431 if (mac_valid(optarg))
432 options.macs = xstrdup(optarg);
434 fprintf(stderr, "Unknown mac type '%s'\n",
440 if (options.control_master == SSHCTL_MASTER_YES)
441 options.control_master = SSHCTL_MASTER_ASK;
443 options.control_master = SSHCTL_MASTER_YES;
446 options.port = a2port(optarg);
447 if (options.port <= 0) {
448 fprintf(stderr, "Bad port '%s'\n", optarg);
453 options.user = optarg;
457 if (parse_forward(&fwd, optarg, 0, 0))
458 add_local_forward(&options, &fwd);
461 "Bad local forwarding specification '%s'\n",
468 if (parse_forward(&fwd, optarg, 0, 1)) {
469 add_remote_forward(&options, &fwd);
472 "Bad remote forwarding specification "
479 if (parse_forward(&fwd, optarg, 1, 0)) {
480 add_local_forward(&options, &fwd);
483 "Bad dynamic forwarding specification "
490 options.compression = 1;
498 line = xstrdup(optarg);
499 if (process_config_line(&options, host ? host : "",
500 line, "command-line", 0, &dummy) != 0)
506 /* ensure that the user doesn't try to backdoor a */
507 /* null cipher switch on an interactive session */
508 /* so explicitly disable it no matter what */
509 options.none_switch=0;
515 if (options.control_path != NULL)
516 free(options.control_path);
517 options.control_path = xstrdup(optarg);
520 options.bind_address = optarg;
533 if (ac > 0 && !host && **av != '-') {
534 if (strrchr(*av, '@')) {
536 cp = strrchr(p, '@');
537 if (cp == NULL || cp == p)
545 optind = optreset = 1;
551 /* Check that we got a host name. */
555 SSLeay_add_all_algorithms();
556 ERR_load_crypto_strings();
558 /* Initialize the command to execute on remote host. */
559 buffer_init(&command);
562 * Save the command to execute on the remote host in a buffer. There
563 * is no limit on the length of the command, except by the maximum
564 * packet size. Also sets the tty flag if there is no command.
567 /* No command specified - execute shell on a tty. */
569 if (subsystem_flag) {
571 "You must specify a subsystem to invoke.\n");
575 /* A command has been specified. Store it into the buffer. */
576 for (i = 0; i < ac; i++) {
578 buffer_append(&command, " ", 1);
579 buffer_append(&command, av[i], strlen(av[i]));
583 /* Cannot fork to background if no command. */
584 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
586 fatal("Cannot fork into background without a command "
589 /* Allocate a tty by default if no command specified. */
590 if (buffer_len(&command) == 0)
596 /* Do not allocate a tty if stdin is not a tty. */
597 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
599 logit("Pseudo-terminal will not be allocated because "
600 "stdin is not a terminal.");
605 * Initialize "log" output. Since we are the client all output
606 * actually goes to stderr.
609 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
610 SYSLOG_FACILITY_USER, !use_syslog);
613 * Read per-user configuration file. Ignore the system wide config
614 * file if the user specifies a config file on the command line.
616 if (config != NULL) {
617 if (!read_config_file(config, host, &options, 0))
618 fatal("Can't open user config file %.100s: "
619 "%.100s", config, strerror(errno));
622 * Since the config file parsing code aborts if it sees
623 * options it doesn't recognize, allow users to put
624 * options specific to compile-time add-ons in alternate
625 * config files so their primary config file will
626 * interoperate SSH versions that don't support those
630 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
631 _PATH_SSH_USER_CONFFILE);
632 (void)read_config_file(buf, host, &options, 1);
634 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
635 _PATH_SSH_USER_CONFFILE);
636 (void)read_config_file(buf, host, &options, 1);
639 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
640 _PATH_SSH_USER_CONFFILE);
641 (void)read_config_file(buf, host, &options, 1);
644 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
645 _PATH_SSH_USER_CONFFILE);
646 (void)read_config_file(buf, host, &options, 1);
648 /* Read systemwide configuration file after use config. */
649 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
653 /* Fill configuration defaults. */
654 fill_default_options(&options);
656 channel_set_af(options.address_family);
659 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
663 if (options.user == NULL) {
664 options.user = xstrdup(pw->pw_name);
665 options.implicit = 1;
667 else options.implicit = 0;
669 /* Get default port if port has not been set. */
670 if (options.port == 0) {
671 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
672 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
675 if (options.local_command != NULL) {
676 char thishost[NI_MAXHOST];
678 if (gethostname(thishost, sizeof(thishost)) == -1)
679 fatal("gethostname: %s", strerror(errno));
680 snprintf(buf, sizeof(buf), "%d", options.port);
681 debug3("expanding LocalCommand: %s", options.local_command);
682 cp = options.local_command;
683 options.local_command = percent_expand(cp, "d", pw->pw_dir,
684 "h", options.hostname? options.hostname : host,
685 "l", thishost, "n", host, "r", options.user, "p", buf,
686 "u", pw->pw_name, (char *)NULL);
687 debug3("expanded LocalCommand: %s", options.local_command);
691 if (options.hostname != NULL)
692 host = options.hostname;
694 /* force lowercase for hostkey matching */
695 if (options.host_key_alias != NULL) {
696 for (p = options.host_key_alias; *p; p++)
698 *p = (char)tolower(*p);
701 if (options.proxy_command != NULL &&
702 strcmp(options.proxy_command, "none") == 0) {
703 xfree(options.proxy_command);
704 options.proxy_command = NULL;
706 if (options.control_path != NULL &&
707 strcmp(options.control_path, "none") == 0) {
708 xfree(options.control_path);
709 options.control_path = NULL;
712 if (options.control_path != NULL) {
713 char thishost[NI_MAXHOST];
715 if (gethostname(thishost, sizeof(thishost)) == -1)
716 fatal("gethostname: %s", strerror(errno));
717 snprintf(buf, sizeof(buf), "%d", options.port);
718 cp = tilde_expand_filename(options.control_path,
720 xfree(options.control_path);
721 options.control_path = percent_expand(cp, "p", buf, "h", host,
722 "r", options.user, "l", thishost, (char *)NULL);
725 if (muxclient_command != 0 && options.control_path == NULL)
726 fatal("No ControlPath specified for \"-O\" command");
727 if (options.control_path != NULL)
728 muxclient(options.control_path);
730 timeout_ms = options.connection_timeout * 1000;
732 /* Open a connection to the remote host. */
733 if (ssh_connect(host, &hostaddr, options.port,
734 options.address_family, options.connection_attempts, &timeout_ms,
735 options.tcp_keep_alive,
737 options.use_privileged_port,
739 original_effective_uid == 0 && options.use_privileged_port,
741 options.proxy_command) != 0)
745 debug3("timeout: %d ms remain after connect", timeout_ms);
748 * If we successfully made the connection, load the host private key
749 * in case we will need it later for combined rsa-rhosts
750 * authentication. This must be done before releasing extra
751 * privileges, because the file is only readable by root.
752 * If we cannot access the private keys, load the public keys
753 * instead and try to execute the ssh-keysign helper instead.
755 sensitive_data.nkeys = 0;
756 sensitive_data.keys = NULL;
757 sensitive_data.external_keysign = 0;
758 if (options.rhosts_rsa_authentication ||
759 options.hostbased_authentication) {
760 sensitive_data.nkeys = 3;
761 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
765 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
766 _PATH_HOST_KEY_FILE, "", NULL, NULL);
767 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
768 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
769 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
770 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
773 if (options.hostbased_authentication == 1 &&
774 sensitive_data.keys[0] == NULL &&
775 sensitive_data.keys[1] == NULL &&
776 sensitive_data.keys[2] == NULL) {
777 sensitive_data.keys[1] = key_load_public(
778 _PATH_HOST_DSA_KEY_FILE, NULL);
779 sensitive_data.keys[2] = key_load_public(
780 _PATH_HOST_RSA_KEY_FILE, NULL);
781 sensitive_data.external_keysign = 1;
785 * Get rid of any extra privileges that we may have. We will no
786 * longer need them. Also, extra privileges could make it very hard
787 * to read identity files and other non-world-readable files from the
788 * user's home directory if it happens to be on a NFS volume where
789 * root is mapped to nobody.
791 if (original_effective_uid == 0) {
793 permanently_set_uid(pw);
797 * Now that we are back to our own permissions, create ~/.ssh
798 * directory if it doesn't already exist.
800 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir,
801 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
802 if (stat(buf, &st) < 0)
803 if (mkdir(buf, 0700) < 0)
804 error("Could not create directory '%.200s'.", buf);
806 /* load options.identity_files */
807 load_public_identity_files();
809 /* Expand ~ in known host file names. */
811 options.system_hostfile =
812 tilde_expand_filename(options.system_hostfile, original_real_uid);
813 options.user_hostfile =
814 tilde_expand_filename(options.user_hostfile, original_real_uid);
815 options.system_hostfile2 =
816 tilde_expand_filename(options.system_hostfile2, original_real_uid);
817 options.user_hostfile2 =
818 tilde_expand_filename(options.user_hostfile2, original_real_uid);
820 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
822 /* Log into the remote system. Never returns if the login fails. */
823 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
826 /* We no longer need the private host keys. Clear them now. */
827 if (sensitive_data.nkeys != 0) {
828 for (i = 0; i < sensitive_data.nkeys; i++) {
829 if (sensitive_data.keys[i] != NULL) {
830 /* Destroys contents safely */
831 debug3("clear hostkey %d", i);
832 key_free(sensitive_data.keys[i]);
833 sensitive_data.keys[i] = NULL;
836 xfree(sensitive_data.keys);
838 for (i = 0; i < options.num_identity_files; i++) {
839 if (options.identity_files[i]) {
840 xfree(options.identity_files[i]);
841 options.identity_files[i] = NULL;
843 if (options.identity_keys[i]) {
844 key_free(options.identity_keys[i]);
845 options.identity_keys[i] = NULL;
849 exit_status = compat20 ? ssh_session2() : ssh_session();
852 if (options.control_path != NULL && muxserver_sock != -1)
853 unlink(options.control_path);
856 * Send SIGHUP to proxy command if used. We don't wait() in
857 * case it hangs and instead rely on init to reap the child
859 if (proxy_command_pid > 1)
860 kill(proxy_command_pid, SIGHUP);
865 /* Callback for remote forward global requests */
867 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
869 Forward *rfwd = (Forward *)ctxt;
871 /* XXX verbose() on failure? */
872 debug("remote forward %s for: listen %d, connect %s:%d",
873 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
874 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
875 if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
876 logit("Allocated port %u for remote forward to %s:%d",
878 rfwd->connect_host, rfwd->connect_port);
881 if (type == SSH2_MSG_REQUEST_FAILURE) {
882 if (options.exit_on_forward_failure)
883 fatal("Error: remote port forwarding failed for "
884 "listen port %d", rfwd->listen_port);
886 logit("Warning: remote port forwarding failed for "
887 "listen port %d", rfwd->listen_port);
889 if (++remote_forward_confirms_received == options.num_remote_forwards) {
890 debug("All remote forwarding requests processed");
891 if (fork_after_authentication_flag) {
892 fork_after_authentication_flag = 0;
893 if (daemon(1, 1) < 0)
894 fatal("daemon() failed: %.200s",
901 ssh_init_forwarding(void)
906 /* Initiate local TCP/IP port forwardings. */
907 for (i = 0; i < options.num_local_forwards; i++) {
908 debug("Local connections to %.200s:%d forwarded to remote "
910 (options.local_forwards[i].listen_host == NULL) ?
911 (options.gateway_ports ? "*" : "LOCALHOST") :
912 options.local_forwards[i].listen_host,
913 options.local_forwards[i].listen_port,
914 options.local_forwards[i].connect_host,
915 options.local_forwards[i].connect_port);
916 success += channel_setup_local_fwd_listener(
917 options.local_forwards[i].listen_host,
918 options.local_forwards[i].listen_port,
919 options.local_forwards[i].connect_host,
920 options.local_forwards[i].connect_port,
921 options.gateway_ports);
923 if (i > 0 && success != i && options.exit_on_forward_failure)
924 fatal("Could not request local forwarding.");
925 if (i > 0 && success == 0)
926 error("Could not request local forwarding.");
928 /* Initiate remote TCP/IP port forwardings. */
929 for (i = 0; i < options.num_remote_forwards; i++) {
930 debug("Remote connections from %.200s:%d forwarded to "
931 "local address %.200s:%d",
932 (options.remote_forwards[i].listen_host == NULL) ?
933 "LOCALHOST" : options.remote_forwards[i].listen_host,
934 options.remote_forwards[i].listen_port,
935 options.remote_forwards[i].connect_host,
936 options.remote_forwards[i].connect_port);
937 if (channel_request_remote_forwarding(
938 options.remote_forwards[i].listen_host,
939 options.remote_forwards[i].listen_port,
940 options.remote_forwards[i].connect_host,
941 options.remote_forwards[i].connect_port) < 0) {
942 if (options.exit_on_forward_failure)
943 fatal("Could not request remote forwarding.");
945 logit("Warning: Could not request remote "
948 client_register_global_confirm(ssh_confirm_remote_forward,
949 &options.remote_forwards[i]);
952 /* Initiate tunnel forwarding. */
953 if (options.tun_open != SSH_TUNMODE_NO) {
954 if (client_request_tun_fwd(options.tun_open,
955 options.tun_local, options.tun_remote) == -1) {
956 if (options.exit_on_forward_failure)
957 fatal("Could not request tunnel forwarding.");
959 error("Could not request tunnel forwarding.");
965 check_agent_present(void)
967 if (options.forward_agent) {
968 /* Clear agent forwarding if we don't have an agent. */
969 if (!ssh_agent_present())
970 options.forward_agent = 0;
984 /* Enable compression if requested. */
985 if (options.compression) {
986 debug("Requesting compression at level %d.",
987 options.compression_level);
989 if (options.compression_level < 1 ||
990 options.compression_level > 9)
991 fatal("Compression level must be from 1 (fast) to "
994 /* Send the request. */
995 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
996 packet_put_int(options.compression_level);
999 type = packet_read();
1000 if (type == SSH_SMSG_SUCCESS)
1001 packet_start_compression(options.compression_level);
1002 else if (type == SSH_SMSG_FAILURE)
1003 logit("Warning: Remote host refused compression.");
1005 packet_disconnect("Protocol error waiting for "
1006 "compression response.");
1008 /* Allocate a pseudo tty if appropriate. */
1010 debug("Requesting pty.");
1012 /* Start the packet. */
1013 packet_start(SSH_CMSG_REQUEST_PTY);
1015 /* Store TERM in the packet. There is no limit on the
1016 length of the string. */
1017 cp = getenv("TERM");
1020 packet_put_cstring(cp);
1022 /* Store window size in the packet. */
1023 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1024 memset(&ws, 0, sizeof(ws));
1025 packet_put_int((u_int)ws.ws_row);
1026 packet_put_int((u_int)ws.ws_col);
1027 packet_put_int((u_int)ws.ws_xpixel);
1028 packet_put_int((u_int)ws.ws_ypixel);
1030 /* Store tty modes in the packet. */
1031 tty_make_modes(fileno(stdin), NULL);
1033 /* Send the packet, and wait for it to leave. */
1035 packet_write_wait();
1037 /* Read response from the server. */
1038 type = packet_read();
1039 if (type == SSH_SMSG_SUCCESS) {
1042 } else if (type == SSH_SMSG_FAILURE)
1043 logit("Warning: Remote host failed or refused to "
1044 "allocate a pseudo tty.");
1046 packet_disconnect("Protocol error waiting for pty "
1047 "request response.");
1049 /* Request X11 forwarding if enabled and DISPLAY is set. */
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 "
1059 x11_request_forwarding_with_spoofing(0, display, proto, data);
1061 /* Read response from the server. */
1062 type = packet_read();
1063 if (type == SSH_SMSG_SUCCESS) {
1065 } else if (type == SSH_SMSG_FAILURE) {
1066 logit("Warning: Remote host denied X11 forwarding.");
1068 packet_disconnect("Protocol error waiting for X11 "
1072 /* Tell the packet module whether this is an interactive session. */
1073 packet_set_interactive(interactive);
1075 /* Request authentication agent forwarding if appropriate. */
1076 check_agent_present();
1078 if (options.forward_agent) {
1079 debug("Requesting authentication agent forwarding.");
1080 auth_request_forwarding();
1082 /* Read response from the server. */
1083 type = packet_read();
1085 if (type != SSH_SMSG_SUCCESS)
1086 logit("Warning: Remote host denied authentication agent forwarding.");
1089 /* Initiate port forwardings. */
1090 ssh_init_forwarding();
1092 /* Execute a local command */
1093 if (options.local_command != NULL &&
1094 options.permit_local_command)
1095 ssh_local_cmd(options.local_command);
1098 * If requested and we are not interested in replies to remote
1099 * forwarding requests, then let ssh continue in the background.
1101 if (fork_after_authentication_flag &&
1102 (!options.exit_on_forward_failure ||
1103 options.num_remote_forwards == 0)) {
1104 fork_after_authentication_flag = 0;
1105 if (daemon(1, 1) < 0)
1106 fatal("daemon() failed: %.200s", strerror(errno));
1110 * If a command was specified on the command line, execute the
1111 * command now. Otherwise request the server to start a shell.
1113 if (buffer_len(&command) > 0) {
1114 int len = buffer_len(&command);
1117 debug("Sending command: %.*s", len,
1118 (u_char *)buffer_ptr(&command));
1119 packet_start(SSH_CMSG_EXEC_CMD);
1120 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1122 packet_write_wait();
1124 debug("Requesting shell.");
1125 packet_start(SSH_CMSG_EXEC_SHELL);
1127 packet_write_wait();
1130 /* Enter the interactive session. */
1131 return client_loop(have_tty, tty_flag ?
1132 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1135 /* request pty/x11/agent/tcpfwd/shell for channel */
1137 ssh_session2_setup(int id, void *arg)
1139 extern char **environ;
1140 const char *display;
1141 int interactive = tty_flag;
1143 display = getenv("DISPLAY");
1144 if (options.forward_x11 && display != NULL) {
1146 /* Get reasonable local authentication information. */
1147 client_x11_get_proto(display, options.xauth_location,
1148 options.forward_x11_trusted, &proto, &data);
1149 /* Request forwarding with authentication spoofing. */
1150 debug("Requesting X11 forwarding with authentication "
1152 x11_request_forwarding_with_spoofing(id, display, proto, data);
1154 /* XXX wait for reply */
1157 check_agent_present();
1158 if (options.forward_agent) {
1159 debug("Requesting authentication agent forwarding.");
1160 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1164 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1165 NULL, fileno(stdin), &command, environ);
1167 packet_set_interactive(interactive);
1170 /* open new channel for a session */
1172 ssh_session2_open(void)
1175 int window, packetmax, in, out, err;
1178 int socksizelen = sizeof(int);
1180 if (stdin_null_flag) {
1181 in = open(_PATH_DEVNULL, O_RDONLY);
1183 in = dup(STDIN_FILENO);
1185 out = dup(STDOUT_FILENO);
1186 err = dup(STDERR_FILENO);
1188 if (in < 0 || out < 0 || err < 0)
1189 fatal("dup() in/out/err failed");
1191 /* enable nonblocking unless tty */
1199 /* we need to check to see if what they want to do about buffer */
1200 /* sizes here. In a hpn to nonhpn connection we want to limit */
1201 /* the window size to something reasonable in case the far side */
1202 /* has the large window bug. In hpn to hpn connection we want to */
1203 /* use the max window size but allow the user to override it */
1204 /* lastly if they disabled hpn then use the ssh std window size */
1206 /* so why don't we just do a getsockopt() here and set the */
1207 /* ssh window to that? In the case of a autotuning receive */
1208 /* window the window would get stuck at the initial buffer */
1209 /* size generally less than 96k. Therefore we need to set the */
1210 /* maximum ssh window size to the maximum hpn buffer size */
1211 /* unless the user has specifically set the tcprcvbufpoll */
1212 /* to no. In which case we *can* just set the window to the */
1213 /* minimum of the hpn buffer size and tcp receive buffer size */
1216 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1218 options.hpn_buffer_size = 2*1024*1024;
1220 if (datafellows & SSH_BUG_LARGEWINDOW)
1222 debug("HPN to Non-HPN Connection");
1226 if (options.tcp_rcv_buf_poll <= 0)
1228 sock = socket(AF_INET, SOCK_STREAM, 0);
1229 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1230 &socksize, &socksizelen);
1232 debug("socksize %d", socksize);
1233 options.hpn_buffer_size = socksize;
1234 debug ("HPNBufferSize set to TCP RWIN: %d", options.hpn_buffer_size);
1238 if (options.tcp_rcv_buf > 0)
1240 /*create a socket but don't connect it */
1241 /* we use that the get the rcv socket size */
1242 sock = socket(AF_INET, SOCK_STREAM, 0);
1243 /* if they are using the tcp_rcv_buf option */
1244 /* attempt to set the buffer size to that */
1245 if (options.tcp_rcv_buf)
1246 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf,
1247 sizeof(options.tcp_rcv_buf));
1248 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1249 &socksize, &socksizelen);
1251 debug("socksize %d", socksize);
1252 options.hpn_buffer_size = socksize;
1253 debug ("HPNBufferSize set to user TCPRcvBuf: %d", options.hpn_buffer_size);
1259 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1261 window = options.hpn_buffer_size;
1263 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1265 packetmax = CHAN_SES_PACKET_DEFAULT;
1267 window = 4*CHAN_SES_PACKET_DEFAULT;
1272 "session", SSH_CHANNEL_OPENING, in, out, err,
1273 window, packetmax, CHAN_EXTENDED_WRITE,
1274 "client-session", /*nonblock*/0);
1275 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1276 c->dynamic_window = 1;
1277 debug ("Enabled Dynamic Window Scaling\n");
1279 debug3("ssh_session2_open: channel_new: %d", c->self);
1281 channel_send_open(c->self);
1283 channel_register_open_confirm(c->self,
1284 ssh_session2_setup, NULL);
1294 /* XXX should be pre-session */
1295 ssh_init_forwarding();
1297 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1298 id = ssh_session2_open();
1300 /* If we don't expect to open a new session, then disallow it */
1301 if (options.control_master == SSHCTL_MASTER_NO &&
1302 (datafellows & SSH_NEW_OPENSSH)) {
1303 debug("Requesting no-more-sessions@openssh.com");
1304 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1305 packet_put_cstring("no-more-sessions@openssh.com");
1310 /* Execute a local command */
1311 if (options.local_command != NULL &&
1312 options.permit_local_command)
1313 ssh_local_cmd(options.local_command);
1315 /* Start listening for multiplex clients */
1318 /* If requested, let ssh continue in the background. */
1319 if (fork_after_authentication_flag) {
1320 fork_after_authentication_flag = 0;
1321 if (daemon(1, 1) < 0)
1322 fatal("daemon() failed: %.200s", strerror(errno));
1325 return client_loop(tty_flag, tty_flag ?
1326 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1330 load_public_identity_files(void)
1332 char *filename, *cp, thishost[NI_MAXHOST];
1333 char *pwdir = NULL, *pwname = NULL;
1340 if (options.smartcard_device != NULL &&
1341 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1342 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1344 for (i = 0; keys[i] != NULL; i++) {
1346 memmove(&options.identity_files[1],
1347 &options.identity_files[0],
1348 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1349 memmove(&options.identity_keys[1],
1350 &options.identity_keys[0],
1351 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1352 options.num_identity_files++;
1353 options.identity_keys[0] = keys[i];
1354 options.identity_files[0] = sc_get_key_label(keys[i]);
1356 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1357 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1361 #endif /* SMARTCARD */
1362 if ((pw = getpwuid(original_real_uid)) == NULL)
1363 fatal("load_public_identity_files: getpwuid failed");
1364 pwname = xstrdup(pw->pw_name);
1365 pwdir = xstrdup(pw->pw_dir);
1366 if (gethostname(thishost, sizeof(thishost)) == -1)
1367 fatal("load_public_identity_files: gethostname: %s",
1369 for (; i < options.num_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 options.identity_files[i] = filename;
1381 options.identity_keys[i] = public;
1383 bzero(pwname, strlen(pwname));
1385 bzero(pwdir, strlen(pwdir));