1 /* $OpenBSD: ssh.c,v 1.318 2008/07/02 13:47:39 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 [-1246AaCfgKkMNnqsTtVvXxY] [-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;
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]);
223 * Save the original real uid. It will be needed later (uid-swapping
224 * may clobber the real uid).
226 original_real_uid = getuid();
227 original_effective_uid = geteuid();
230 * Use uid-swapping to give up root privileges for the duration of
231 * option processing. We will re-instantiate the rights when we are
232 * ready to create the privileged port, and will permanently drop
233 * them when the port has been created (actually, when the connection
234 * has been made, as we may need to create the port several times).
238 #ifdef HAVE_SETRLIMIT
239 /* If we are installed setuid root be careful to not drop core. */
240 if (original_real_uid != original_effective_uid) {
242 rlim.rlim_cur = rlim.rlim_max = 0;
243 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
244 fatal("setrlimit failed: %.100s", strerror(errno));
248 pw = getpwuid(original_real_uid);
250 logit("You don't exist, go away!");
253 /* Take a copy of the returned structure. */
257 * Set our umask to something reasonable, as some files are created
258 * with the default umask. This will make them world-readable but
259 * writable only by the owner, which is ok for all files for which we
260 * don't set the modes explicitly.
265 * Initialize option structure to indicate that no values have been
268 initialize_options(&options);
270 /* Parse command-line arguments. */
274 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
275 "ACD:F:I:KL:MNO:PR:S:TVw:XY")) != -1) {
278 options.protocol = SSH_PROTO_1;
281 options.protocol = SSH_PROTO_2;
284 options.address_family = AF_INET;
287 options.address_family = AF_INET6;
293 fork_after_authentication_flag = 1;
297 options.forward_x11 = 0;
300 options.forward_x11 = 1;
303 options.forward_x11 = 1;
304 options.forward_x11_trusted = 1;
307 options.gateway_ports = 1;
310 if (strcmp(optarg, "check") == 0)
311 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
312 else if (strcmp(optarg, "exit") == 0)
313 muxclient_command = SSHMUX_COMMAND_TERMINATE;
315 fatal("Invalid multiplex command.");
317 case 'P': /* deprecated */
318 options.use_privileged_port = 0;
321 options.forward_agent = 0;
324 options.forward_agent = 1;
327 options.gss_deleg_creds = 0;
330 options.gss_authentication = 1;
331 options.gss_deleg_creds = 1;
334 if (stat(optarg, &st) < 0) {
335 fprintf(stderr, "Warning: Identity file %s "
336 "not accessible: %s.\n", optarg,
340 if (options.num_identity_files >=
341 SSH_MAX_IDENTITY_FILES)
342 fatal("Too many identity files specified "
343 "(max %d)", SSH_MAX_IDENTITY_FILES);
344 options.identity_files[options.num_identity_files++] =
349 options.smartcard_device = xstrdup(optarg);
351 fprintf(stderr, "no support for smartcards.\n");
360 if (debug_flag == 0) {
362 options.log_level = SYSLOG_LEVEL_DEBUG1;
364 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
370 fprintf(stderr, "%s, %s\n",
371 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
376 if (options.tun_open == -1)
377 options.tun_open = SSH_TUNMODE_DEFAULT;
378 options.tun_local = a2tun(optarg, &options.tun_remote);
379 if (options.tun_local == SSH_TUNID_ERR) {
381 "Bad tun device '%s'\n", optarg);
386 options.log_level = SYSLOG_LEVEL_QUIET;
389 if (optarg[0] == '^' && optarg[2] == 0 &&
390 (u_char) optarg[1] >= 64 &&
391 (u_char) optarg[1] < 128)
392 options.escape_char = (u_char) optarg[1] & 31;
393 else if (strlen(optarg) == 1)
394 options.escape_char = (u_char) optarg[0];
395 else if (strcmp(optarg, "none") == 0)
396 options.escape_char = SSH_ESCAPECHAR_NONE;
398 fprintf(stderr, "Bad escape character '%s'.\n",
404 if (ciphers_valid(optarg)) {
406 options.ciphers = xstrdup(optarg);
407 options.cipher = SSH_CIPHER_INVALID;
410 options.cipher = cipher_number(optarg);
411 if (options.cipher == -1) {
413 "Unknown cipher type '%s'\n",
417 if (options.cipher == SSH_CIPHER_3DES)
418 options.ciphers = "3des-cbc";
419 else if (options.cipher == SSH_CIPHER_BLOWFISH)
420 options.ciphers = "blowfish-cbc";
422 options.ciphers = (char *)-1;
426 if (mac_valid(optarg))
427 options.macs = xstrdup(optarg);
429 fprintf(stderr, "Unknown mac type '%s'\n",
435 if (options.control_master == SSHCTL_MASTER_YES)
436 options.control_master = SSHCTL_MASTER_ASK;
438 options.control_master = SSHCTL_MASTER_YES;
441 options.port = a2port(optarg);
442 if (options.port == 0) {
443 fprintf(stderr, "Bad port '%s'\n", optarg);
448 options.user = optarg;
452 if (parse_forward(&fwd, optarg))
453 add_local_forward(&options, &fwd);
456 "Bad local forwarding specification '%s'\n",
463 if (parse_forward(&fwd, optarg)) {
464 add_remote_forward(&options, &fwd);
467 "Bad remote forwarding specification "
474 cp = p = xstrdup(optarg);
475 memset(&fwd, '\0', sizeof(fwd));
476 fwd.connect_host = "socks";
477 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
478 fprintf(stderr, "Bad dynamic forwarding "
479 "specification '%.100s'\n", optarg);
483 fwd.listen_port = a2port(cp);
485 cleanhostname(fwd.listen_host);
487 fwd.listen_port = a2port(fwd.listen_host);
488 fwd.listen_host = NULL;
491 if (fwd.listen_port == 0) {
492 fprintf(stderr, "Bad dynamic port '%s'\n",
496 add_local_forward(&options, &fwd);
501 options.compression = 1;
509 /* ensure that the user doesn't try to backdoor a */
510 /* null cipher switch on an interactive session */
511 /* so explicitly disable it no matter what */
512 options.none_switch=0;
516 line = xstrdup(optarg);
517 if (process_config_line(&options, host ? host : "",
518 line, "command-line", 0, &dummy) != 0)
526 if (options.control_path != NULL)
527 free(options.control_path);
528 options.control_path = xstrdup(optarg);
531 options.bind_address = optarg;
544 if (ac > 0 && !host && **av != '-') {
545 if (strrchr(*av, '@')) {
547 cp = strrchr(p, '@');
548 if (cp == NULL || cp == p)
556 optind = optreset = 1;
562 /* Check that we got a host name. */
566 SSLeay_add_all_algorithms();
567 ERR_load_crypto_strings();
569 /* Initialize the command to execute on remote host. */
570 buffer_init(&command);
573 * Save the command to execute on the remote host in a buffer. There
574 * is no limit on the length of the command, except by the maximum
575 * packet size. Also sets the tty flag if there is no command.
578 /* No command specified - execute shell on a tty. */
580 if (subsystem_flag) {
582 "You must specify a subsystem to invoke.\n");
586 /* A command has been specified. Store it into the buffer. */
587 for (i = 0; i < ac; i++) {
589 buffer_append(&command, " ", 1);
590 buffer_append(&command, av[i], strlen(av[i]));
594 /* Cannot fork to background if no command. */
595 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
597 fatal("Cannot fork into background without a command "
600 /* Allocate a tty by default if no command specified. */
601 if (buffer_len(&command) == 0)
607 /* Do not allocate a tty if stdin is not a tty. */
608 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
610 logit("Pseudo-terminal will not be allocated because "
611 "stdin is not a terminal.");
616 * Initialize "log" output. Since we are the client all output
617 * actually goes to stderr.
620 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
621 SYSLOG_FACILITY_USER, 1);
624 * Read per-user configuration file. Ignore the system wide config
625 * file if the user specifies a config file on the command line.
627 if (config != NULL) {
628 if (!read_config_file(config, host, &options, 0))
629 fatal("Can't open user config file %.100s: "
630 "%.100s", config, strerror(errno));
633 * Since the config file parsing code aborts if it sees
634 * options it doesn't recognize, allow users to put
635 * options specific to compile-time add-ons in alternate
636 * config files so their primary config file will
637 * interoperate SSH versions that don't support those
641 snprintf(buf, sizeof buf, "%.100s/%.100s.gssapi", pw->pw_dir,
642 _PATH_SSH_USER_CONFFILE);
643 (void)read_config_file(buf, host, &options, 1);
645 snprintf(buf, sizeof buf, "%.100s/%.100s.gsi", pw->pw_dir,
646 _PATH_SSH_USER_CONFFILE);
647 (void)read_config_file(buf, host, &options, 1);
650 snprintf(buf, sizeof buf, "%.100s/%.100s.krb", pw->pw_dir,
651 _PATH_SSH_USER_CONFFILE);
652 (void)read_config_file(buf, host, &options, 1);
655 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
656 _PATH_SSH_USER_CONFFILE);
657 (void)read_config_file(buf, host, &options, 1);
659 /* Read systemwide configuration file after use config. */
660 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
664 /* Fill configuration defaults. */
665 fill_default_options(&options);
667 channel_set_af(options.address_family);
670 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
674 if (options.user == NULL) {
675 options.user = xstrdup(pw->pw_name);
676 options.implicit = 1;
678 else options.implicit = 0;
680 /* Get default port if port has not been set. */
681 if (options.port == 0) {
682 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
683 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
686 if (options.local_command != NULL) {
687 char thishost[NI_MAXHOST];
689 if (gethostname(thishost, sizeof(thishost)) == -1)
690 fatal("gethostname: %s", strerror(errno));
691 snprintf(buf, sizeof(buf), "%d", options.port);
692 debug3("expanding LocalCommand: %s", options.local_command);
693 cp = options.local_command;
694 options.local_command = percent_expand(cp, "d", pw->pw_dir,
695 "h", options.hostname? options.hostname : host,
696 "l", thishost, "n", host, "r", options.user, "p", buf,
697 "u", pw->pw_name, (char *)NULL);
698 debug3("expanded LocalCommand: %s", options.local_command);
702 if (options.hostname != NULL)
703 host = options.hostname;
705 /* force lowercase for hostkey matching */
706 if (options.host_key_alias != NULL) {
707 for (p = options.host_key_alias; *p; p++)
709 *p = (char)tolower(*p);
712 if (options.proxy_command != NULL &&
713 strcmp(options.proxy_command, "none") == 0) {
714 xfree(options.proxy_command);
715 options.proxy_command = NULL;
717 if (options.control_path != NULL &&
718 strcmp(options.control_path, "none") == 0) {
719 xfree(options.control_path);
720 options.control_path = NULL;
723 if (options.control_path != NULL) {
724 char thishost[NI_MAXHOST];
726 if (gethostname(thishost, sizeof(thishost)) == -1)
727 fatal("gethostname: %s", strerror(errno));
728 snprintf(buf, sizeof(buf), "%d", options.port);
729 cp = tilde_expand_filename(options.control_path,
731 xfree(options.control_path);
732 options.control_path = percent_expand(cp, "p", buf, "h", host,
733 "r", options.user, "l", thishost, (char *)NULL);
736 if (muxclient_command != 0 && options.control_path == NULL)
737 fatal("No ControlPath specified for \"-O\" command");
738 if (options.control_path != NULL)
739 muxclient(options.control_path);
741 timeout_ms = options.connection_timeout * 1000;
743 /* Open a connection to the remote host. */
744 if (ssh_connect(host, &hostaddr, options.port,
745 options.address_family, options.connection_attempts, &timeout_ms,
746 options.tcp_keep_alive,
748 options.use_privileged_port,
750 original_effective_uid == 0 && options.use_privileged_port,
752 options.proxy_command) != 0)
756 debug3("timeout: %d ms remain after connect", timeout_ms);
759 * If we successfully made the connection, load the host private key
760 * in case we will need it later for combined rsa-rhosts
761 * authentication. This must be done before releasing extra
762 * privileges, because the file is only readable by root.
763 * If we cannot access the private keys, load the public keys
764 * instead and try to execute the ssh-keysign helper instead.
766 sensitive_data.nkeys = 0;
767 sensitive_data.keys = NULL;
768 sensitive_data.external_keysign = 0;
769 if (options.rhosts_rsa_authentication ||
770 options.hostbased_authentication) {
771 sensitive_data.nkeys = 3;
772 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
776 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
777 _PATH_HOST_KEY_FILE, "", NULL, NULL);
778 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
779 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
780 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
781 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
784 if (options.hostbased_authentication == 1 &&
785 sensitive_data.keys[0] == NULL &&
786 sensitive_data.keys[1] == NULL &&
787 sensitive_data.keys[2] == NULL) {
788 sensitive_data.keys[1] = key_load_public(
789 _PATH_HOST_DSA_KEY_FILE, NULL);
790 sensitive_data.keys[2] = key_load_public(
791 _PATH_HOST_RSA_KEY_FILE, NULL);
792 sensitive_data.external_keysign = 1;
796 * Get rid of any extra privileges that we may have. We will no
797 * longer need them. Also, extra privileges could make it very hard
798 * to read identity files and other non-world-readable files from the
799 * user's home directory if it happens to be on a NFS volume where
800 * root is mapped to nobody.
802 if (original_effective_uid == 0) {
804 permanently_set_uid(pw);
808 * Now that we are back to our own permissions, create ~/.ssh
809 * directory if it doesn't already exist.
811 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir,
812 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
813 if (stat(buf, &st) < 0)
814 if (mkdir(buf, 0700) < 0)
815 error("Could not create directory '%.200s'.", buf);
817 /* load options.identity_files */
818 load_public_identity_files();
820 /* Expand ~ in known host file names. */
822 options.system_hostfile =
823 tilde_expand_filename(options.system_hostfile, original_real_uid);
824 options.user_hostfile =
825 tilde_expand_filename(options.user_hostfile, original_real_uid);
826 options.system_hostfile2 =
827 tilde_expand_filename(options.system_hostfile2, original_real_uid);
828 options.user_hostfile2 =
829 tilde_expand_filename(options.user_hostfile2, original_real_uid);
831 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
833 /* Log into the remote system. Never returns if the login fails. */
834 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
837 /* We no longer need the private host keys. Clear them now. */
838 if (sensitive_data.nkeys != 0) {
839 for (i = 0; i < sensitive_data.nkeys; i++) {
840 if (sensitive_data.keys[i] != NULL) {
841 /* Destroys contents safely */
842 debug3("clear hostkey %d", i);
843 key_free(sensitive_data.keys[i]);
844 sensitive_data.keys[i] = NULL;
847 xfree(sensitive_data.keys);
849 for (i = 0; i < options.num_identity_files; i++) {
850 if (options.identity_files[i]) {
851 xfree(options.identity_files[i]);
852 options.identity_files[i] = NULL;
854 if (options.identity_keys[i]) {
855 key_free(options.identity_keys[i]);
856 options.identity_keys[i] = NULL;
860 exit_status = compat20 ? ssh_session2() : ssh_session();
863 if (options.control_path != NULL && muxserver_sock != -1)
864 unlink(options.control_path);
867 * Send SIGHUP to proxy command if used. We don't wait() in
868 * case it hangs and instead rely on init to reap the child
870 if (proxy_command_pid > 1)
871 kill(proxy_command_pid, SIGHUP);
876 /* Callback for remote forward global requests */
878 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
880 Forward *rfwd = (Forward *)ctxt;
882 debug("remote forward %s for: listen %d, connect %s:%d",
883 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
884 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
885 if (type == SSH2_MSG_REQUEST_FAILURE) {
886 if (options.exit_on_forward_failure)
887 fatal("Error: remote port forwarding failed for "
888 "listen port %d", rfwd->listen_port);
890 logit("Warning: remote port forwarding failed for "
891 "listen port %d", rfwd->listen_port);
893 if (++remote_forward_confirms_received == options.num_remote_forwards) {
894 debug("All remote forwarding requests processed");
895 if (fork_after_authentication_flag) {
896 fork_after_authentication_flag = 0;
897 if (daemon(1, 1) < 0)
898 fatal("daemon() failed: %.200s",
905 ssh_init_forwarding(void)
910 /* Initiate local TCP/IP port forwardings. */
911 for (i = 0; i < options.num_local_forwards; i++) {
912 debug("Local connections to %.200s:%d forwarded to remote "
914 (options.local_forwards[i].listen_host == NULL) ?
915 (options.gateway_ports ? "*" : "LOCALHOST") :
916 options.local_forwards[i].listen_host,
917 options.local_forwards[i].listen_port,
918 options.local_forwards[i].connect_host,
919 options.local_forwards[i].connect_port);
920 success += channel_setup_local_fwd_listener(
921 options.local_forwards[i].listen_host,
922 options.local_forwards[i].listen_port,
923 options.local_forwards[i].connect_host,
924 options.local_forwards[i].connect_port,
925 options.gateway_ports, options.hpn_disabled,
926 options.hpn_buffer_size);
928 if (i > 0 && success != i && options.exit_on_forward_failure)
929 fatal("Could not request local forwarding.");
930 if (i > 0 && success == 0)
931 error("Could not request local forwarding.");
933 /* Initiate remote TCP/IP port forwardings. */
934 for (i = 0; i < options.num_remote_forwards; i++) {
935 debug("Remote connections from %.200s:%d forwarded to "
936 "local address %.200s:%d",
937 (options.remote_forwards[i].listen_host == NULL) ?
938 "LOCALHOST" : 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);
942 if (channel_request_remote_forwarding(
943 options.remote_forwards[i].listen_host,
944 options.remote_forwards[i].listen_port,
945 options.remote_forwards[i].connect_host,
946 options.remote_forwards[i].connect_port) < 0) {
947 if (options.exit_on_forward_failure)
948 fatal("Could not request remote forwarding.");
950 logit("Warning: Could not request remote "
953 client_register_global_confirm(ssh_confirm_remote_forward,
954 &options.remote_forwards[i]);
957 /* Initiate tunnel forwarding. */
958 if (options.tun_open != SSH_TUNMODE_NO) {
959 if (client_request_tun_fwd(options.tun_open,
960 options.tun_local, options.tun_remote) == -1) {
961 if (options.exit_on_forward_failure)
962 fatal("Could not request tunnel forwarding.");
964 error("Could not request tunnel forwarding.");
970 check_agent_present(void)
972 if (options.forward_agent) {
973 /* Clear agent forwarding if we don't have an agent. */
974 if (!ssh_agent_present())
975 options.forward_agent = 0;
989 /* Enable compression if requested. */
990 if (options.compression) {
991 debug("Requesting compression at level %d.",
992 options.compression_level);
994 if (options.compression_level < 1 ||
995 options.compression_level > 9)
996 fatal("Compression level must be from 1 (fast) to "
999 /* Send the request. */
1000 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1001 packet_put_int(options.compression_level);
1003 packet_write_wait();
1004 type = packet_read();
1005 if (type == SSH_SMSG_SUCCESS)
1006 packet_start_compression(options.compression_level);
1007 else if (type == SSH_SMSG_FAILURE)
1008 logit("Warning: Remote host refused compression.");
1010 packet_disconnect("Protocol error waiting for "
1011 "compression response.");
1013 /* Allocate a pseudo tty if appropriate. */
1015 debug("Requesting pty.");
1017 /* Start the packet. */
1018 packet_start(SSH_CMSG_REQUEST_PTY);
1020 /* Store TERM in the packet. There is no limit on the
1021 length of the string. */
1022 cp = getenv("TERM");
1025 packet_put_cstring(cp);
1027 /* Store window size in the packet. */
1028 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1029 memset(&ws, 0, sizeof(ws));
1030 packet_put_int((u_int)ws.ws_row);
1031 packet_put_int((u_int)ws.ws_col);
1032 packet_put_int((u_int)ws.ws_xpixel);
1033 packet_put_int((u_int)ws.ws_ypixel);
1035 /* Store tty modes in the packet. */
1036 tty_make_modes(fileno(stdin), NULL);
1038 /* Send the packet, and wait for it to leave. */
1040 packet_write_wait();
1042 /* Read response from the server. */
1043 type = packet_read();
1044 if (type == SSH_SMSG_SUCCESS) {
1047 } else if (type == SSH_SMSG_FAILURE)
1048 logit("Warning: Remote host failed or refused to "
1049 "allocate a pseudo tty.");
1051 packet_disconnect("Protocol error waiting for pty "
1052 "request response.");
1054 /* Request X11 forwarding if enabled and DISPLAY is set. */
1055 display = getenv("DISPLAY");
1056 if (options.forward_x11 && display != NULL) {
1058 /* Get reasonable local authentication information. */
1059 client_x11_get_proto(display, options.xauth_location,
1060 options.forward_x11_trusted, &proto, &data);
1061 /* Request forwarding with authentication spoofing. */
1062 debug("Requesting X11 forwarding with authentication "
1064 x11_request_forwarding_with_spoofing(0, display, proto, data);
1066 /* Read response from the server. */
1067 type = packet_read();
1068 if (type == SSH_SMSG_SUCCESS) {
1070 } else if (type == SSH_SMSG_FAILURE) {
1071 logit("Warning: Remote host denied X11 forwarding.");
1073 packet_disconnect("Protocol error waiting for X11 "
1077 /* Tell the packet module whether this is an interactive session. */
1078 packet_set_interactive(interactive);
1080 /* Request authentication agent forwarding if appropriate. */
1081 check_agent_present();
1083 if (options.forward_agent) {
1084 debug("Requesting authentication agent forwarding.");
1085 auth_request_forwarding();
1087 /* Read response from the server. */
1088 type = packet_read();
1090 if (type != SSH_SMSG_SUCCESS)
1091 logit("Warning: Remote host denied authentication agent forwarding.");
1094 /* Initiate port forwardings. */
1095 ssh_init_forwarding();
1097 /* Execute a local command */
1098 if (options.local_command != NULL &&
1099 options.permit_local_command)
1100 ssh_local_cmd(options.local_command);
1103 * If requested and we are not interested in replies to remote
1104 * forwarding requests, then let ssh continue in the background.
1106 if (fork_after_authentication_flag &&
1107 (!options.exit_on_forward_failure ||
1108 options.num_remote_forwards == 0)) {
1109 fork_after_authentication_flag = 0;
1110 if (daemon(1, 1) < 0)
1111 fatal("daemon() failed: %.200s", strerror(errno));
1115 * If a command was specified on the command line, execute the
1116 * command now. Otherwise request the server to start a shell.
1118 if (buffer_len(&command) > 0) {
1119 int len = buffer_len(&command);
1122 debug("Sending command: %.*s", len,
1123 (u_char *)buffer_ptr(&command));
1124 packet_start(SSH_CMSG_EXEC_CMD);
1125 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1127 packet_write_wait();
1129 debug("Requesting shell.");
1130 packet_start(SSH_CMSG_EXEC_SHELL);
1132 packet_write_wait();
1135 /* Enter the interactive session. */
1136 return client_loop(have_tty, tty_flag ?
1137 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1140 /* request pty/x11/agent/tcpfwd/shell for channel */
1142 ssh_session2_setup(int id, void *arg)
1144 extern char **environ;
1145 const char *display;
1146 int interactive = tty_flag;
1148 display = getenv("DISPLAY");
1149 if (options.forward_x11 && display != NULL) {
1151 /* Get reasonable local authentication information. */
1152 client_x11_get_proto(display, options.xauth_location,
1153 options.forward_x11_trusted, &proto, &data);
1154 /* Request forwarding with authentication spoofing. */
1155 debug("Requesting X11 forwarding with authentication "
1157 x11_request_forwarding_with_spoofing(id, display, proto, data);
1159 /* XXX wait for reply */
1162 check_agent_present();
1163 if (options.forward_agent) {
1164 debug("Requesting authentication agent forwarding.");
1165 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1169 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1170 NULL, fileno(stdin), &command, environ);
1172 packet_set_interactive(interactive);
1175 /* open new channel for a session */
1177 ssh_session2_open(void)
1180 int window, packetmax, in, out, err;
1183 int socksizelen = sizeof(int);
1185 if (stdin_null_flag) {
1186 in = open(_PATH_DEVNULL, O_RDONLY);
1188 in = dup(STDIN_FILENO);
1190 out = dup(STDOUT_FILENO);
1191 err = dup(STDERR_FILENO);
1193 if (in < 0 || out < 0 || err < 0)
1194 fatal("dup() in/out/err failed");
1196 /* enable nonblocking unless tty */
1204 /* we need to check to see if what they want to do about buffer */
1205 /* sizes here. In a hpn to nonhpn connection we want to limit */
1206 /* the window size to something reasonable in case the far side */
1207 /* has the large window bug. In hpn to hpn connection we want to */
1208 /* use the max window size but allow the user to override it */
1209 /* lastly if they disabled hpn then use the ssh std window size */
1211 /* so why don't we just do a getsockopt() here and set the */
1212 /* ssh window to that? In the case of a autotuning receive */
1213 /* window the window would get stuck at the initial buffer */
1214 /* size generally less than 96k. Therefore we need to set the */
1215 /* maximum ssh window size to the maximum hpn buffer size */
1216 /* unless the user has specifically set the tcprcvbufpoll */
1217 /* to no. In which case we *can* just set the window to the */
1218 /* minimum of the hpn buffer size and tcp receive buffer size */
1220 if(options.hpn_disabled)
1222 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1224 else if (datafellows & SSH_BUG_LARGEWINDOW)
1226 debug("HPN to Non-HPN Connection");
1227 if (options.hpn_buffer_size < 0)
1228 options.hpn_buffer_size = 2*1024*1024;
1232 if (options.hpn_buffer_size < 0)
1233 options.hpn_buffer_size = BUFFER_MAX_LEN_HPN;
1235 /*create a socket but don't connect it */
1236 /* we use that the get the rcv socket size */
1237 sock = socket(AF_INET, SOCK_STREAM, 0);
1238 /* if they are using the tcp_rcv_buf option */
1239 /* attempt to set the buffer size to that */
1240 if (options.tcp_rcv_buf)
1241 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf,
1242 sizeof(options.tcp_rcv_buf));
1243 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1244 &socksize, &socksizelen);
1246 debug("socksize %d", socksize);
1247 if (options.tcp_rcv_buf_poll <= 0)
1249 options.hpn_buffer_size = MIN(socksize,options.hpn_buffer_size);
1250 debug ("MIN of TCP RWIN and HPNBufferSize: %d", options.hpn_buffer_size);
1254 if (options.tcp_rcv_buf > 0)
1255 options.hpn_buffer_size = MIN(options.tcp_rcv_buf, options.hpn_buffer_size);
1256 debug ("MIN of TCPRcvBuf and HPNBufferSize: %d", options.hpn_buffer_size);
1261 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1263 window = 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);
1276 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1277 c->dynamic_window = 1;
1278 debug ("Enabled Dynamic Window Scaling\n");
1280 debug3("ssh_session2_open: channel_new: %d", c->self);
1282 channel_send_open(c->self);
1284 channel_register_open_confirm(c->self,
1285 ssh_session2_setup, NULL);
1295 /* XXX should be pre-session */
1296 ssh_init_forwarding();
1298 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1299 id = ssh_session2_open();
1301 /* If we don't expect to open a new session, then disallow it */
1302 if (options.control_master == SSHCTL_MASTER_NO) {
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));