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 line = xstrdup(optarg);
510 if (process_config_line(&options, host ? host : "",
511 line, "command-line", 0, &dummy) != 0)
517 /* ensure that the user doesn't try to backdoor a */
518 /* null cipher switch on an interactive session */
519 /* so explicitly disable it no matter what */
520 options.none_switch=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);
927 if (i > 0 && success != i && options.exit_on_forward_failure)
928 fatal("Could not request local forwarding.");
929 if (i > 0 && success == 0)
930 error("Could not request local forwarding.");
932 /* Initiate remote TCP/IP port forwardings. */
933 for (i = 0; i < options.num_remote_forwards; i++) {
934 debug("Remote connections from %.200s:%d forwarded to "
935 "local address %.200s:%d",
936 (options.remote_forwards[i].listen_host == NULL) ?
937 "LOCALHOST" : options.remote_forwards[i].listen_host,
938 options.remote_forwards[i].listen_port,
939 options.remote_forwards[i].connect_host,
940 options.remote_forwards[i].connect_port);
941 if (channel_request_remote_forwarding(
942 options.remote_forwards[i].listen_host,
943 options.remote_forwards[i].listen_port,
944 options.remote_forwards[i].connect_host,
945 options.remote_forwards[i].connect_port) < 0) {
946 if (options.exit_on_forward_failure)
947 fatal("Could not request remote forwarding.");
949 logit("Warning: Could not request remote "
952 client_register_global_confirm(ssh_confirm_remote_forward,
953 &options.remote_forwards[i]);
956 /* Initiate tunnel forwarding. */
957 if (options.tun_open != SSH_TUNMODE_NO) {
958 if (client_request_tun_fwd(options.tun_open,
959 options.tun_local, options.tun_remote) == -1) {
960 if (options.exit_on_forward_failure)
961 fatal("Could not request tunnel forwarding.");
963 error("Could not request tunnel forwarding.");
969 check_agent_present(void)
971 if (options.forward_agent) {
972 /* Clear agent forwarding if we don't have an agent. */
973 if (!ssh_agent_present())
974 options.forward_agent = 0;
988 /* Enable compression if requested. */
989 if (options.compression) {
990 debug("Requesting compression at level %d.",
991 options.compression_level);
993 if (options.compression_level < 1 ||
994 options.compression_level > 9)
995 fatal("Compression level must be from 1 (fast) to "
998 /* Send the request. */
999 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1000 packet_put_int(options.compression_level);
1002 packet_write_wait();
1003 type = packet_read();
1004 if (type == SSH_SMSG_SUCCESS)
1005 packet_start_compression(options.compression_level);
1006 else if (type == SSH_SMSG_FAILURE)
1007 logit("Warning: Remote host refused compression.");
1009 packet_disconnect("Protocol error waiting for "
1010 "compression response.");
1012 /* Allocate a pseudo tty if appropriate. */
1014 debug("Requesting pty.");
1016 /* Start the packet. */
1017 packet_start(SSH_CMSG_REQUEST_PTY);
1019 /* Store TERM in the packet. There is no limit on the
1020 length of the string. */
1021 cp = getenv("TERM");
1024 packet_put_cstring(cp);
1026 /* Store window size in the packet. */
1027 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1028 memset(&ws, 0, sizeof(ws));
1029 packet_put_int((u_int)ws.ws_row);
1030 packet_put_int((u_int)ws.ws_col);
1031 packet_put_int((u_int)ws.ws_xpixel);
1032 packet_put_int((u_int)ws.ws_ypixel);
1034 /* Store tty modes in the packet. */
1035 tty_make_modes(fileno(stdin), NULL);
1037 /* Send the packet, and wait for it to leave. */
1039 packet_write_wait();
1041 /* Read response from the server. */
1042 type = packet_read();
1043 if (type == SSH_SMSG_SUCCESS) {
1046 } else if (type == SSH_SMSG_FAILURE)
1047 logit("Warning: Remote host failed or refused to "
1048 "allocate a pseudo tty.");
1050 packet_disconnect("Protocol error waiting for pty "
1051 "request response.");
1053 /* Request X11 forwarding if enabled and DISPLAY is set. */
1054 display = getenv("DISPLAY");
1055 if (options.forward_x11 && display != NULL) {
1057 /* Get reasonable local authentication information. */
1058 client_x11_get_proto(display, options.xauth_location,
1059 options.forward_x11_trusted, &proto, &data);
1060 /* Request forwarding with authentication spoofing. */
1061 debug("Requesting X11 forwarding with authentication "
1063 x11_request_forwarding_with_spoofing(0, display, proto, data);
1065 /* Read response from the server. */
1066 type = packet_read();
1067 if (type == SSH_SMSG_SUCCESS) {
1069 } else if (type == SSH_SMSG_FAILURE) {
1070 logit("Warning: Remote host denied X11 forwarding.");
1072 packet_disconnect("Protocol error waiting for X11 "
1076 /* Tell the packet module whether this is an interactive session. */
1077 packet_set_interactive(interactive);
1079 /* Request authentication agent forwarding if appropriate. */
1080 check_agent_present();
1082 if (options.forward_agent) {
1083 debug("Requesting authentication agent forwarding.");
1084 auth_request_forwarding();
1086 /* Read response from the server. */
1087 type = packet_read();
1089 if (type != SSH_SMSG_SUCCESS)
1090 logit("Warning: Remote host denied authentication agent forwarding.");
1093 /* Initiate port forwardings. */
1094 ssh_init_forwarding();
1096 /* Execute a local command */
1097 if (options.local_command != NULL &&
1098 options.permit_local_command)
1099 ssh_local_cmd(options.local_command);
1102 * If requested and we are not interested in replies to remote
1103 * forwarding requests, then let ssh continue in the background.
1105 if (fork_after_authentication_flag &&
1106 (!options.exit_on_forward_failure ||
1107 options.num_remote_forwards == 0)) {
1108 fork_after_authentication_flag = 0;
1109 if (daemon(1, 1) < 0)
1110 fatal("daemon() failed: %.200s", strerror(errno));
1114 * If a command was specified on the command line, execute the
1115 * command now. Otherwise request the server to start a shell.
1117 if (buffer_len(&command) > 0) {
1118 int len = buffer_len(&command);
1121 debug("Sending command: %.*s", len,
1122 (u_char *)buffer_ptr(&command));
1123 packet_start(SSH_CMSG_EXEC_CMD);
1124 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1126 packet_write_wait();
1128 debug("Requesting shell.");
1129 packet_start(SSH_CMSG_EXEC_SHELL);
1131 packet_write_wait();
1134 /* Enter the interactive session. */
1135 return client_loop(have_tty, tty_flag ?
1136 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1139 /* request pty/x11/agent/tcpfwd/shell for channel */
1141 ssh_session2_setup(int id, void *arg)
1143 extern char **environ;
1144 const char *display;
1145 int interactive = tty_flag;
1147 display = getenv("DISPLAY");
1148 if (options.forward_x11 && display != NULL) {
1150 /* Get reasonable local authentication information. */
1151 client_x11_get_proto(display, options.xauth_location,
1152 options.forward_x11_trusted, &proto, &data);
1153 /* Request forwarding with authentication spoofing. */
1154 debug("Requesting X11 forwarding with authentication "
1156 x11_request_forwarding_with_spoofing(id, display, proto, data);
1158 /* XXX wait for reply */
1161 check_agent_present();
1162 if (options.forward_agent) {
1163 debug("Requesting authentication agent forwarding.");
1164 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1168 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1169 NULL, fileno(stdin), &command, environ);
1171 packet_set_interactive(interactive);
1174 /* open new channel for a session */
1176 ssh_session2_open(void)
1179 int window, packetmax, in, out, err;
1182 int socksizelen = sizeof(int);
1184 if (stdin_null_flag) {
1185 in = open(_PATH_DEVNULL, O_RDONLY);
1187 in = dup(STDIN_FILENO);
1189 out = dup(STDOUT_FILENO);
1190 err = dup(STDERR_FILENO);
1192 if (in < 0 || out < 0 || err < 0)
1193 fatal("dup() in/out/err failed");
1195 /* enable nonblocking unless tty */
1203 /* we need to check to see if what they want to do about buffer */
1204 /* sizes here. In a hpn to nonhpn connection we want to limit */
1205 /* the window size to something reasonable in case the far side */
1206 /* has the large window bug. In hpn to hpn connection we want to */
1207 /* use the max window size but allow the user to override it */
1208 /* lastly if they disabled hpn then use the ssh std window size */
1210 /* so why don't we just do a getsockopt() here and set the */
1211 /* ssh window to that? In the case of a autotuning receive */
1212 /* window the window would get stuck at the initial buffer */
1213 /* size generally less than 96k. Therefore we need to set the */
1214 /* maximum ssh window size to the maximum hpn buffer size */
1215 /* unless the user has specifically set the tcprcvbufpoll */
1216 /* to no. In which case we *can* just set the window to the */
1217 /* minimum of the hpn buffer size and tcp receive buffer size */
1220 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1222 options.hpn_buffer_size = 2*1024*1024;
1224 if (datafellows & SSH_BUG_LARGEWINDOW)
1226 debug("HPN to Non-HPN Connection");
1230 if (options.tcp_rcv_buf_poll <= 0)
1232 sock = socket(AF_INET, SOCK_STREAM, 0);
1233 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1234 &socksize, &socksizelen);
1236 debug("socksize %d", socksize);
1237 options.hpn_buffer_size = socksize;
1238 debug ("HPNBufferSize set to TCP RWIN: %d", options.hpn_buffer_size);
1242 if (options.tcp_rcv_buf > 0)
1244 /*create a socket but don't connect it */
1245 /* we use that the get the rcv socket size */
1246 sock = socket(AF_INET, SOCK_STREAM, 0);
1247 /* if they are using the tcp_rcv_buf option */
1248 /* attempt to set the buffer size to that */
1249 if (options.tcp_rcv_buf)
1250 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf,
1251 sizeof(options.tcp_rcv_buf));
1252 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1253 &socksize, &socksizelen);
1255 debug("socksize %d", socksize);
1256 options.hpn_buffer_size = socksize;
1257 debug ("HPNBufferSize set to user TCPRcvBuf: %d", options.hpn_buffer_size);
1263 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1265 window = options.hpn_buffer_size;
1267 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1269 packetmax = CHAN_SES_PACKET_DEFAULT;
1271 window = 4*CHAN_SES_PACKET_DEFAULT;
1276 "session", SSH_CHANNEL_OPENING, in, out, err,
1277 window, packetmax, CHAN_EXTENDED_WRITE,
1278 "client-session", /*nonblock*/0);
1279 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1280 c->dynamic_window = 1;
1281 debug ("Enabled Dynamic Window Scaling\n");
1283 debug3("ssh_session2_open: channel_new: %d", c->self);
1285 channel_send_open(c->self);
1287 channel_register_open_confirm(c->self,
1288 ssh_session2_setup, NULL);
1298 /* XXX should be pre-session */
1299 ssh_init_forwarding();
1301 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1302 id = ssh_session2_open();
1304 /* If we don't expect to open a new session, then disallow it */
1305 if (options.control_master == SSHCTL_MASTER_NO) {
1306 debug("Requesting no-more-sessions@openssh.com");
1307 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1308 packet_put_cstring("no-more-sessions@openssh.com");
1313 /* Execute a local command */
1314 if (options.local_command != NULL &&
1315 options.permit_local_command)
1316 ssh_local_cmd(options.local_command);
1318 /* Start listening for multiplex clients */
1321 /* If requested, let ssh continue in the background. */
1322 if (fork_after_authentication_flag) {
1323 fork_after_authentication_flag = 0;
1324 if (daemon(1, 1) < 0)
1325 fatal("daemon() failed: %.200s", strerror(errno));
1328 return client_loop(tty_flag, tty_flag ?
1329 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1333 load_public_identity_files(void)
1335 char *filename, *cp, thishost[NI_MAXHOST];
1336 char *pwdir = NULL, *pwname = NULL;
1343 if (options.smartcard_device != NULL &&
1344 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1345 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1347 for (i = 0; keys[i] != NULL; i++) {
1349 memmove(&options.identity_files[1],
1350 &options.identity_files[0],
1351 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1352 memmove(&options.identity_keys[1],
1353 &options.identity_keys[0],
1354 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1355 options.num_identity_files++;
1356 options.identity_keys[0] = keys[i];
1357 options.identity_files[0] = sc_get_key_label(keys[i]);
1359 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1360 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1364 #endif /* SMARTCARD */
1365 if ((pw = getpwuid(original_real_uid)) == NULL)
1366 fatal("load_public_identity_files: getpwuid failed");
1367 pwname = xstrdup(pw->pw_name);
1368 pwdir = xstrdup(pw->pw_dir);
1369 if (gethostname(thishost, sizeof(thishost)) == -1)
1370 fatal("load_public_identity_files: gethostname: %s",
1372 for (; i < options.num_identity_files; i++) {
1373 cp = tilde_expand_filename(options.identity_files[i],
1375 filename = percent_expand(cp, "d", pwdir,
1376 "u", pwname, "l", thishost, "h", host,
1377 "r", options.user, (char *)NULL);
1379 public = key_load_public(filename, NULL);
1380 debug("identity file %s type %d", filename,
1381 public ? public->type : -1);
1382 xfree(options.identity_files[i]);
1383 options.identity_files[i] = filename;
1384 options.identity_keys[i] = public;
1386 bzero(pwname, strlen(pwname));
1388 bzero(pwdir, strlen(pwdir));