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.
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
50 #include <sys/resource.h>
51 #include <sys/ioctl.h>
52 #include <sys/socket.h>
70 #include <netinet/in.h>
71 #include <arpa/inet.h>
73 #include <openssl/evp.h>
74 #include <openssl/err.h>
75 #include "openbsd-compat/openssl-compat.h"
76 #include "openbsd-compat/sys-queue.h"
90 #include "pathnames.h"
92 #include "clientloop.h"
95 #include "sshconnect.h"
109 extern char *__progname;
111 /* Flag indicating whether debug mode is on. May be set on the command line. */
114 /* Flag indicating whether a tty should be allocated */
117 int force_tty_flag = 0;
119 /* don't exec a shell */
120 int no_shell_flag = 0;
123 * Flag indicating that nothing should be read from stdin. This can be set
124 * on the command line.
126 int stdin_null_flag = 0;
129 * Flag indicating that ssh should fork after authentication. This is useful
130 * so that the passphrase can be entered manually, and then ssh goes to the
133 int fork_after_authentication_flag = 0;
136 * General data structure for command line options and options configurable
137 * in configuration files. See readconf.h.
141 /* optional user configfile */
145 * Name of the host we are connecting to. This is the name given on the
146 * command line, or the HostName specified for the user-supplied name in a
147 * configuration file.
151 /* socket address the host resolves to */
152 struct sockaddr_storage hostaddr;
154 /* Private host keys. */
155 Sensitive sensitive_data;
157 /* Original real UID. */
158 uid_t original_real_uid;
159 uid_t original_effective_uid;
161 /* command to be executed */
164 /* Should we execute a command or invoke a subsystem? */
165 int subsystem_flag = 0;
167 /* # of replies received for global requests */
168 static int remote_forward_confirms_received = 0;
170 /* pid of proxycommand child process */
171 pid_t proxy_command_pid = 0;
174 extern int muxserver_sock;
175 extern u_int muxclient_command;
177 /* Prints a help message to the user. This function never returns. */
183 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
184 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
185 " [-i identity_file] [-L [bind_address:]port:host:hostport]\n"
186 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
187 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
188 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
193 static int ssh_session(void);
194 static int ssh_session2(void);
195 static void load_public_identity_files(void);
197 /* from muxclient.c */
198 void muxclient(const char *);
199 void muxserver_listen(void);
202 * Main program for the ssh client.
205 main(int ac, char **av)
207 int i, opt, exit_status, use_syslog;
208 char *p, *cp, *line, buf[256];
211 int dummy, timeout_ms;
212 extern int optind, optreset;
217 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
220 __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;
501 line = xstrdup(optarg);
502 if (process_config_line(&options, host ? host : "",
503 line, "command-line", 0, &dummy) != 0)
511 if (options.control_path != NULL)
512 free(options.control_path);
513 options.control_path = xstrdup(optarg);
516 options.bind_address = optarg;
529 if (ac > 0 && !host && **av != '-') {
530 if (strrchr(*av, '@')) {
532 cp = strrchr(p, '@');
533 if (cp == NULL || cp == p)
541 optind = optreset = 1;
547 /* Check that we got a host name. */
551 SSLeay_add_all_algorithms();
552 ERR_load_crypto_strings();
554 /* Initialize the command to execute on remote host. */
555 buffer_init(&command);
558 * Save the command to execute on the remote host in a buffer. There
559 * is no limit on the length of the command, except by the maximum
560 * packet size. Also sets the tty flag if there is no command.
563 /* No command specified - execute shell on a tty. */
565 if (subsystem_flag) {
567 "You must specify a subsystem to invoke.\n");
571 /* A command has been specified. Store it into the buffer. */
572 for (i = 0; i < ac; i++) {
574 buffer_append(&command, " ", 1);
575 buffer_append(&command, av[i], strlen(av[i]));
579 /* Cannot fork to background if no command. */
580 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
582 fatal("Cannot fork into background without a command "
585 /* Allocate a tty by default if no command specified. */
586 if (buffer_len(&command) == 0)
592 /* Do not allocate a tty if stdin is not a tty. */
593 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
595 logit("Pseudo-terminal will not be allocated because "
596 "stdin is not a terminal.");
601 * Initialize "log" output. Since we are the client all output
602 * actually goes to stderr.
605 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
606 SYSLOG_FACILITY_USER, !use_syslog);
609 * Read per-user configuration file. Ignore the system wide config
610 * file if the user specifies a config file on the command line.
612 if (config != NULL) {
613 if (!read_config_file(config, host, &options, 0))
614 fatal("Can't open user config file %.100s: "
615 "%.100s", config, strerror(errno));
617 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
618 _PATH_SSH_USER_CONFFILE);
619 (void)read_config_file(buf, host, &options, 1);
621 /* Read systemwide configuration file after use config. */
622 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
626 /* Fill configuration defaults. */
627 fill_default_options(&options);
629 channel_set_af(options.address_family);
632 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
636 if (options.user == NULL)
637 options.user = xstrdup(pw->pw_name);
639 /* Get default port if port has not been set. */
640 if (options.port == 0) {
641 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
642 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
645 if (options.local_command != NULL) {
646 char thishost[NI_MAXHOST];
648 if (gethostname(thishost, sizeof(thishost)) == -1)
649 fatal("gethostname: %s", strerror(errno));
650 snprintf(buf, sizeof(buf), "%d", options.port);
651 debug3("expanding LocalCommand: %s", options.local_command);
652 cp = options.local_command;
653 options.local_command = percent_expand(cp, "d", pw->pw_dir,
654 "h", options.hostname? options.hostname : host,
655 "l", thishost, "n", host, "r", options.user, "p", buf,
656 "u", pw->pw_name, (char *)NULL);
657 debug3("expanded LocalCommand: %s", options.local_command);
661 if (options.hostname != NULL)
662 host = options.hostname;
664 /* Find canonic host name. */
665 if (strchr(host, '.') == 0) {
666 struct addrinfo hints;
667 struct addrinfo *ai = NULL;
669 memset(&hints, 0, sizeof(hints));
670 hints.ai_family = options.address_family;
671 hints.ai_flags = AI_CANONNAME;
672 hints.ai_socktype = SOCK_STREAM;
673 errgai = getaddrinfo(host, NULL, &hints, &ai);
675 if (ai->ai_canonname != NULL)
676 host = xstrdup(ai->ai_canonname);
681 /* force lowercase for hostkey matching */
682 if (options.host_key_alias != NULL) {
683 for (p = options.host_key_alias; *p; p++)
685 *p = (char)tolower(*p);
688 if (options.proxy_command != NULL &&
689 strcmp(options.proxy_command, "none") == 0) {
690 xfree(options.proxy_command);
691 options.proxy_command = NULL;
693 if (options.control_path != NULL &&
694 strcmp(options.control_path, "none") == 0) {
695 xfree(options.control_path);
696 options.control_path = NULL;
699 if (options.control_path != NULL) {
700 char thishost[NI_MAXHOST];
702 if (gethostname(thishost, sizeof(thishost)) == -1)
703 fatal("gethostname: %s", strerror(errno));
704 snprintf(buf, sizeof(buf), "%d", options.port);
705 cp = tilde_expand_filename(options.control_path,
707 xfree(options.control_path);
708 options.control_path = percent_expand(cp, "p", buf, "h", host,
709 "r", options.user, "l", thishost, (char *)NULL);
712 if (muxclient_command != 0 && options.control_path == NULL)
713 fatal("No ControlPath specified for \"-O\" command");
714 if (options.control_path != NULL)
715 muxclient(options.control_path);
717 timeout_ms = options.connection_timeout * 1000;
719 /* Open a connection to the remote host. */
720 if (ssh_connect(host, &hostaddr, options.port,
721 options.address_family, options.connection_attempts, &timeout_ms,
722 options.tcp_keep_alive,
724 options.use_privileged_port,
726 original_effective_uid == 0 && options.use_privileged_port,
728 options.proxy_command) != 0)
732 debug3("timeout: %d ms remain after connect", timeout_ms);
735 * If we successfully made the connection, load the host private key
736 * in case we will need it later for combined rsa-rhosts
737 * authentication. This must be done before releasing extra
738 * privileges, because the file is only readable by root.
739 * If we cannot access the private keys, load the public keys
740 * instead and try to execute the ssh-keysign helper instead.
742 sensitive_data.nkeys = 0;
743 sensitive_data.keys = NULL;
744 sensitive_data.external_keysign = 0;
745 if (options.rhosts_rsa_authentication ||
746 options.hostbased_authentication) {
747 sensitive_data.nkeys = 3;
748 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
752 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
753 _PATH_HOST_KEY_FILE, "", NULL, NULL);
754 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
755 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
756 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
757 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
760 if (options.hostbased_authentication == 1 &&
761 sensitive_data.keys[0] == NULL &&
762 sensitive_data.keys[1] == NULL &&
763 sensitive_data.keys[2] == NULL) {
764 sensitive_data.keys[1] = key_load_public(
765 _PATH_HOST_DSA_KEY_FILE, NULL);
766 sensitive_data.keys[2] = key_load_public(
767 _PATH_HOST_RSA_KEY_FILE, NULL);
768 sensitive_data.external_keysign = 1;
772 * Get rid of any extra privileges that we may have. We will no
773 * longer need them. Also, extra privileges could make it very hard
774 * to read identity files and other non-world-readable files from the
775 * user's home directory if it happens to be on a NFS volume where
776 * root is mapped to nobody.
778 if (original_effective_uid == 0) {
780 permanently_set_uid(pw);
784 * Now that we are back to our own permissions, create ~/.ssh
785 * directory if it doesn't already exist.
787 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir,
788 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
789 if (stat(buf, &st) < 0)
790 if (mkdir(buf, 0700) < 0)
791 error("Could not create directory '%.200s'.", buf);
793 /* load options.identity_files */
794 load_public_identity_files();
796 /* Expand ~ in known host file names. */
798 options.system_hostfile =
799 tilde_expand_filename(options.system_hostfile, original_real_uid);
800 options.user_hostfile =
801 tilde_expand_filename(options.user_hostfile, original_real_uid);
802 options.system_hostfile2 =
803 tilde_expand_filename(options.system_hostfile2, original_real_uid);
804 options.user_hostfile2 =
805 tilde_expand_filename(options.user_hostfile2, original_real_uid);
807 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
809 /* Log into the remote system. Never returns if the login fails. */
810 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
813 /* We no longer need the private host keys. Clear them now. */
814 if (sensitive_data.nkeys != 0) {
815 for (i = 0; i < sensitive_data.nkeys; i++) {
816 if (sensitive_data.keys[i] != NULL) {
817 /* Destroys contents safely */
818 debug3("clear hostkey %d", i);
819 key_free(sensitive_data.keys[i]);
820 sensitive_data.keys[i] = NULL;
823 xfree(sensitive_data.keys);
825 for (i = 0; i < options.num_identity_files; i++) {
826 if (options.identity_files[i]) {
827 xfree(options.identity_files[i]);
828 options.identity_files[i] = NULL;
830 if (options.identity_keys[i]) {
831 key_free(options.identity_keys[i]);
832 options.identity_keys[i] = NULL;
836 exit_status = compat20 ? ssh_session2() : ssh_session();
839 if (options.control_path != NULL && muxserver_sock != -1)
840 unlink(options.control_path);
843 * Send SIGHUP to proxy command if used. We don't wait() in
844 * case it hangs and instead rely on init to reap the child
846 if (proxy_command_pid > 1)
847 kill(proxy_command_pid, SIGHUP);
852 /* Callback for remote forward global requests */
854 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
856 Forward *rfwd = (Forward *)ctxt;
858 /* XXX verbose() on failure? */
859 debug("remote forward %s for: listen %d, connect %s:%d",
860 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
861 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
862 if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
863 logit("Allocated port %u for remote forward to %s:%d",
865 rfwd->connect_host, rfwd->connect_port);
868 if (type == SSH2_MSG_REQUEST_FAILURE) {
869 if (options.exit_on_forward_failure)
870 fatal("Error: remote port forwarding failed for "
871 "listen port %d", rfwd->listen_port);
873 logit("Warning: remote port forwarding failed for "
874 "listen port %d", rfwd->listen_port);
876 if (++remote_forward_confirms_received == options.num_remote_forwards) {
877 debug("All remote forwarding requests processed");
878 if (fork_after_authentication_flag) {
879 fork_after_authentication_flag = 0;
880 if (daemon(1, 1) < 0)
881 fatal("daemon() failed: %.200s",
888 ssh_init_forwarding(void)
893 /* Initiate local TCP/IP port forwardings. */
894 for (i = 0; i < options.num_local_forwards; i++) {
895 debug("Local connections to %.200s:%d forwarded to remote "
897 (options.local_forwards[i].listen_host == NULL) ?
898 (options.gateway_ports ? "*" : "LOCALHOST") :
899 options.local_forwards[i].listen_host,
900 options.local_forwards[i].listen_port,
901 options.local_forwards[i].connect_host,
902 options.local_forwards[i].connect_port);
903 success += channel_setup_local_fwd_listener(
904 options.local_forwards[i].listen_host,
905 options.local_forwards[i].listen_port,
906 options.local_forwards[i].connect_host,
907 options.local_forwards[i].connect_port,
908 options.gateway_ports);
910 if (i > 0 && success != i && options.exit_on_forward_failure)
911 fatal("Could not request local forwarding.");
912 if (i > 0 && success == 0)
913 error("Could not request local forwarding.");
915 /* Initiate remote TCP/IP port forwardings. */
916 for (i = 0; i < options.num_remote_forwards; i++) {
917 debug("Remote connections from %.200s:%d forwarded to "
918 "local address %.200s:%d",
919 (options.remote_forwards[i].listen_host == NULL) ?
920 "LOCALHOST" : options.remote_forwards[i].listen_host,
921 options.remote_forwards[i].listen_port,
922 options.remote_forwards[i].connect_host,
923 options.remote_forwards[i].connect_port);
924 if (channel_request_remote_forwarding(
925 options.remote_forwards[i].listen_host,
926 options.remote_forwards[i].listen_port,
927 options.remote_forwards[i].connect_host,
928 options.remote_forwards[i].connect_port) < 0) {
929 if (options.exit_on_forward_failure)
930 fatal("Could not request remote forwarding.");
932 logit("Warning: Could not request remote "
935 client_register_global_confirm(ssh_confirm_remote_forward,
936 &options.remote_forwards[i]);
939 /* Initiate tunnel forwarding. */
940 if (options.tun_open != SSH_TUNMODE_NO) {
941 if (client_request_tun_fwd(options.tun_open,
942 options.tun_local, options.tun_remote) == -1) {
943 if (options.exit_on_forward_failure)
944 fatal("Could not request tunnel forwarding.");
946 error("Could not request tunnel forwarding.");
952 check_agent_present(void)
954 if (options.forward_agent) {
955 /* Clear agent forwarding if we don't have an agent. */
956 if (!ssh_agent_present())
957 options.forward_agent = 0;
971 /* Enable compression if requested. */
972 if (options.compression) {
973 debug("Requesting compression at level %d.",
974 options.compression_level);
976 if (options.compression_level < 1 ||
977 options.compression_level > 9)
978 fatal("Compression level must be from 1 (fast) to "
981 /* Send the request. */
982 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
983 packet_put_int(options.compression_level);
986 type = packet_read();
987 if (type == SSH_SMSG_SUCCESS)
988 packet_start_compression(options.compression_level);
989 else if (type == SSH_SMSG_FAILURE)
990 logit("Warning: Remote host refused compression.");
992 packet_disconnect("Protocol error waiting for "
993 "compression response.");
995 /* Allocate a pseudo tty if appropriate. */
997 debug("Requesting pty.");
999 /* Start the packet. */
1000 packet_start(SSH_CMSG_REQUEST_PTY);
1002 /* Store TERM in the packet. There is no limit on the
1003 length of the string. */
1004 cp = getenv("TERM");
1007 packet_put_cstring(cp);
1009 /* Store window size in the packet. */
1010 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1011 memset(&ws, 0, sizeof(ws));
1012 packet_put_int((u_int)ws.ws_row);
1013 packet_put_int((u_int)ws.ws_col);
1014 packet_put_int((u_int)ws.ws_xpixel);
1015 packet_put_int((u_int)ws.ws_ypixel);
1017 /* Store tty modes in the packet. */
1018 tty_make_modes(fileno(stdin), NULL);
1020 /* Send the packet, and wait for it to leave. */
1022 packet_write_wait();
1024 /* Read response from the server. */
1025 type = packet_read();
1026 if (type == SSH_SMSG_SUCCESS) {
1029 } else if (type == SSH_SMSG_FAILURE)
1030 logit("Warning: Remote host failed or refused to "
1031 "allocate a pseudo tty.");
1033 packet_disconnect("Protocol error waiting for pty "
1034 "request response.");
1036 /* Request X11 forwarding if enabled and DISPLAY is set. */
1037 display = getenv("DISPLAY");
1038 if (options.forward_x11 && display != NULL) {
1040 /* Get reasonable local authentication information. */
1041 client_x11_get_proto(display, options.xauth_location,
1042 options.forward_x11_trusted, &proto, &data);
1043 /* Request forwarding with authentication spoofing. */
1044 debug("Requesting X11 forwarding with authentication "
1046 x11_request_forwarding_with_spoofing(0, display, proto, data);
1048 /* Read response from the server. */
1049 type = packet_read();
1050 if (type == SSH_SMSG_SUCCESS) {
1052 } else if (type == SSH_SMSG_FAILURE) {
1053 logit("Warning: Remote host denied X11 forwarding.");
1055 packet_disconnect("Protocol error waiting for X11 "
1059 /* Tell the packet module whether this is an interactive session. */
1060 packet_set_interactive(interactive);
1062 /* Request authentication agent forwarding if appropriate. */
1063 check_agent_present();
1065 if (options.forward_agent) {
1066 debug("Requesting authentication agent forwarding.");
1067 auth_request_forwarding();
1069 /* Read response from the server. */
1070 type = packet_read();
1072 if (type != SSH_SMSG_SUCCESS)
1073 logit("Warning: Remote host denied authentication agent forwarding.");
1076 /* Initiate port forwardings. */
1077 ssh_init_forwarding();
1079 /* Execute a local command */
1080 if (options.local_command != NULL &&
1081 options.permit_local_command)
1082 ssh_local_cmd(options.local_command);
1085 * If requested and we are not interested in replies to remote
1086 * forwarding requests, then let ssh continue in the background.
1088 if (fork_after_authentication_flag &&
1089 (!options.exit_on_forward_failure ||
1090 options.num_remote_forwards == 0)) {
1091 fork_after_authentication_flag = 0;
1092 if (daemon(1, 1) < 0)
1093 fatal("daemon() failed: %.200s", strerror(errno));
1097 * If a command was specified on the command line, execute the
1098 * command now. Otherwise request the server to start a shell.
1100 if (buffer_len(&command) > 0) {
1101 int len = buffer_len(&command);
1104 debug("Sending command: %.*s", len,
1105 (u_char *)buffer_ptr(&command));
1106 packet_start(SSH_CMSG_EXEC_CMD);
1107 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1109 packet_write_wait();
1111 debug("Requesting shell.");
1112 packet_start(SSH_CMSG_EXEC_SHELL);
1114 packet_write_wait();
1117 /* Enter the interactive session. */
1118 return client_loop(have_tty, tty_flag ?
1119 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1122 /* request pty/x11/agent/tcpfwd/shell for channel */
1124 ssh_session2_setup(int id, void *arg)
1126 extern char **environ;
1127 const char *display;
1128 int interactive = tty_flag;
1130 display = getenv("DISPLAY");
1131 if (options.forward_x11 && display != NULL) {
1133 /* Get reasonable local authentication information. */
1134 client_x11_get_proto(display, options.xauth_location,
1135 options.forward_x11_trusted, &proto, &data);
1136 /* Request forwarding with authentication spoofing. */
1137 debug("Requesting X11 forwarding with authentication "
1139 x11_request_forwarding_with_spoofing(id, display, proto, data);
1141 /* XXX wait for reply */
1144 check_agent_present();
1145 if (options.forward_agent) {
1146 debug("Requesting authentication agent forwarding.");
1147 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1151 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1152 NULL, fileno(stdin), &command, environ);
1154 packet_set_interactive(interactive);
1157 /* open new channel for a session */
1159 ssh_session2_open(void)
1162 int window, packetmax, in, out, err;
1164 if (stdin_null_flag) {
1165 in = open(_PATH_DEVNULL, O_RDONLY);
1167 in = dup(STDIN_FILENO);
1169 out = dup(STDOUT_FILENO);
1170 err = dup(STDERR_FILENO);
1172 if (in < 0 || out < 0 || err < 0)
1173 fatal("dup() in/out/err failed");
1175 /* enable nonblocking unless tty */
1183 window = CHAN_SES_WINDOW_DEFAULT;
1184 packetmax = CHAN_SES_PACKET_DEFAULT;
1190 "session", SSH_CHANNEL_OPENING, in, out, err,
1191 window, packetmax, CHAN_EXTENDED_WRITE,
1192 "client-session", /*nonblock*/0);
1194 debug3("ssh_session2_open: channel_new: %d", c->self);
1196 channel_send_open(c->self);
1198 channel_register_open_confirm(c->self,
1199 ssh_session2_setup, NULL);
1209 /* XXX should be pre-session */
1210 ssh_init_forwarding();
1212 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1213 id = ssh_session2_open();
1215 /* If we don't expect to open a new session, then disallow it */
1216 if (options.control_master == SSHCTL_MASTER_NO &&
1217 (datafellows & SSH_NEW_OPENSSH)) {
1218 debug("Requesting no-more-sessions@openssh.com");
1219 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1220 packet_put_cstring("no-more-sessions@openssh.com");
1225 /* Execute a local command */
1226 if (options.local_command != NULL &&
1227 options.permit_local_command)
1228 ssh_local_cmd(options.local_command);
1230 /* Start listening for multiplex clients */
1233 /* If requested, let ssh continue in the background. */
1234 if (fork_after_authentication_flag) {
1235 fork_after_authentication_flag = 0;
1236 if (daemon(1, 1) < 0)
1237 fatal("daemon() failed: %.200s", strerror(errno));
1240 return client_loop(tty_flag, tty_flag ?
1241 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1245 load_public_identity_files(void)
1247 char *filename, *cp, thishost[NI_MAXHOST];
1248 char *pwdir = NULL, *pwname = NULL;
1255 if (options.smartcard_device != NULL &&
1256 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1257 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1259 for (i = 0; keys[i] != NULL; i++) {
1261 memmove(&options.identity_files[1],
1262 &options.identity_files[0],
1263 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1264 memmove(&options.identity_keys[1],
1265 &options.identity_keys[0],
1266 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1267 options.num_identity_files++;
1268 options.identity_keys[0] = keys[i];
1269 options.identity_files[0] = sc_get_key_label(keys[i]);
1271 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1272 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1276 #endif /* SMARTCARD */
1277 if ((pw = getpwuid(original_real_uid)) == NULL)
1278 fatal("load_public_identity_files: getpwuid failed");
1279 pwname = xstrdup(pw->pw_name);
1280 pwdir = xstrdup(pw->pw_dir);
1281 if (gethostname(thishost, sizeof(thishost)) == -1)
1282 fatal("load_public_identity_files: gethostname: %s",
1284 for (; i < options.num_identity_files; i++) {
1285 cp = tilde_expand_filename(options.identity_files[i],
1287 filename = percent_expand(cp, "d", pwdir,
1288 "u", pwname, "l", thishost, "h", host,
1289 "r", options.user, (char *)NULL);
1291 public = key_load_public(filename, NULL);
1292 debug("identity file %s type %d", filename,
1293 public ? public->type : -1);
1294 xfree(options.identity_files[i]);
1295 options.identity_files[i] = filename;
1296 options.identity_keys[i] = public;
1298 bzero(pwname, strlen(pwname));
1300 bzero(pwdir, strlen(pwdir));