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.
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 [-1246AaCfgKkMNnqsTtVvXxY] [-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;
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. */
275 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
276 "ACD:F:I:KL:MNO:PR:S:TVw:XY")) != -1) {
279 options.protocol = SSH_PROTO_1;
282 options.protocol = SSH_PROTO_2;
285 options.address_family = AF_INET;
288 options.address_family = AF_INET6;
294 fork_after_authentication_flag = 1;
298 options.forward_x11 = 0;
301 options.forward_x11 = 1;
304 options.forward_x11 = 1;
305 options.forward_x11_trusted = 1;
308 options.gateway_ports = 1;
311 if (strcmp(optarg, "check") == 0)
312 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
313 else if (strcmp(optarg, "exit") == 0)
314 muxclient_command = SSHMUX_COMMAND_TERMINATE;
316 fatal("Invalid multiplex command.");
318 case 'P': /* deprecated */
319 options.use_privileged_port = 0;
322 options.forward_agent = 0;
325 options.forward_agent = 1;
328 options.gss_deleg_creds = 0;
331 options.gss_authentication = 1;
332 options.gss_deleg_creds = 1;
335 if (stat(optarg, &st) < 0) {
336 fprintf(stderr, "Warning: Identity file %s "
337 "not accessible: %s.\n", optarg,
341 if (options.num_identity_files >=
342 SSH_MAX_IDENTITY_FILES)
343 fatal("Too many identity files specified "
344 "(max %d)", SSH_MAX_IDENTITY_FILES);
345 options.identity_files[options.num_identity_files++] =
350 options.smartcard_device = xstrdup(optarg);
352 fprintf(stderr, "no support for smartcards.\n");
361 if (debug_flag == 0) {
363 options.log_level = SYSLOG_LEVEL_DEBUG1;
365 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
371 fprintf(stderr, "%s, %s\n",
372 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
377 if (options.tun_open == -1)
378 options.tun_open = SSH_TUNMODE_DEFAULT;
379 options.tun_local = a2tun(optarg, &options.tun_remote);
380 if (options.tun_local == SSH_TUNID_ERR) {
382 "Bad tun device '%s'\n", optarg);
387 options.log_level = SYSLOG_LEVEL_QUIET;
390 if (optarg[0] == '^' && optarg[2] == 0 &&
391 (u_char) optarg[1] >= 64 &&
392 (u_char) optarg[1] < 128)
393 options.escape_char = (u_char) optarg[1] & 31;
394 else if (strlen(optarg) == 1)
395 options.escape_char = (u_char) optarg[0];
396 else if (strcmp(optarg, "none") == 0)
397 options.escape_char = SSH_ESCAPECHAR_NONE;
399 fprintf(stderr, "Bad escape character '%s'.\n",
405 if (ciphers_valid(optarg)) {
407 options.ciphers = xstrdup(optarg);
408 options.cipher = SSH_CIPHER_INVALID;
411 options.cipher = cipher_number(optarg);
412 if (options.cipher == -1) {
414 "Unknown cipher type '%s'\n",
418 if (options.cipher == SSH_CIPHER_3DES)
419 options.ciphers = "3des-cbc";
420 else if (options.cipher == SSH_CIPHER_BLOWFISH)
421 options.ciphers = "blowfish-cbc";
423 options.ciphers = (char *)-1;
427 if (mac_valid(optarg))
428 options.macs = xstrdup(optarg);
430 fprintf(stderr, "Unknown mac type '%s'\n",
436 if (options.control_master == SSHCTL_MASTER_YES)
437 options.control_master = SSHCTL_MASTER_ASK;
439 options.control_master = SSHCTL_MASTER_YES;
442 options.port = a2port(optarg);
443 if (options.port == 0) {
444 fprintf(stderr, "Bad port '%s'\n", optarg);
449 options.user = optarg;
453 if (parse_forward(&fwd, optarg))
454 add_local_forward(&options, &fwd);
457 "Bad local forwarding specification '%s'\n",
464 if (parse_forward(&fwd, optarg)) {
465 add_remote_forward(&options, &fwd);
468 "Bad remote forwarding specification "
475 cp = p = xstrdup(optarg);
476 memset(&fwd, '\0', sizeof(fwd));
477 fwd.connect_host = "socks";
478 if ((fwd.listen_host = hpdelim(&cp)) == NULL) {
479 fprintf(stderr, "Bad dynamic forwarding "
480 "specification '%.100s'\n", optarg);
484 fwd.listen_port = a2port(cp);
486 cleanhostname(fwd.listen_host);
488 fwd.listen_port = a2port(fwd.listen_host);
489 fwd.listen_host = NULL;
492 if (fwd.listen_port == 0) {
493 fprintf(stderr, "Bad dynamic port '%s'\n",
497 add_local_forward(&options, &fwd);
502 options.compression = 1;
513 line = xstrdup(optarg);
514 if (process_config_line(&options, host ? host : "",
515 line, "command-line", 0, &dummy) != 0)
523 if (options.control_path != NULL)
524 free(options.control_path);
525 options.control_path = xstrdup(optarg);
528 options.bind_address = optarg;
541 if (ac > 0 && !host && **av != '-') {
542 if (strrchr(*av, '@')) {
544 cp = strrchr(p, '@');
545 if (cp == NULL || cp == p)
553 optind = optreset = 1;
559 /* Check that we got a host name. */
563 SSLeay_add_all_algorithms();
564 ERR_load_crypto_strings();
566 /* Initialize the command to execute on remote host. */
567 buffer_init(&command);
570 * Save the command to execute on the remote host in a buffer. There
571 * is no limit on the length of the command, except by the maximum
572 * packet size. Also sets the tty flag if there is no command.
575 /* No command specified - execute shell on a tty. */
577 if (subsystem_flag) {
579 "You must specify a subsystem to invoke.\n");
583 /* A command has been specified. Store it into the buffer. */
584 for (i = 0; i < ac; i++) {
586 buffer_append(&command, " ", 1);
587 buffer_append(&command, av[i], strlen(av[i]));
591 /* Cannot fork to background if no command. */
592 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
594 fatal("Cannot fork into background without a command "
597 /* Allocate a tty by default if no command specified. */
598 if (buffer_len(&command) == 0)
604 /* Do not allocate a tty if stdin is not a tty. */
605 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
607 logit("Pseudo-terminal will not be allocated because "
608 "stdin is not a terminal.");
613 * Initialize "log" output. Since we are the client all output
614 * actually goes to stderr.
617 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
618 SYSLOG_FACILITY_USER, 1);
621 * Read per-user configuration file. Ignore the system wide config
622 * file if the user specifies a config file on the command line.
624 if (config != NULL) {
625 if (!read_config_file(config, host, &options, 0))
626 fatal("Can't open user config file %.100s: "
627 "%.100s", config, strerror(errno));
629 snprintf(buf, sizeof buf, "%.100s/%.100s", pw->pw_dir,
630 _PATH_SSH_USER_CONFFILE);
631 (void)read_config_file(buf, host, &options, 1);
633 /* Read systemwide configuration file after use config. */
634 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
638 /* Fill configuration defaults. */
639 fill_default_options(&options);
641 channel_set_af(options.address_family);
644 log_init(av[0], options.log_level, SYSLOG_FACILITY_USER, 1);
648 if (options.user == NULL)
649 options.user = xstrdup(pw->pw_name);
651 /* Get default port if port has not been set. */
652 if (options.port == 0) {
653 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
654 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
657 if (options.local_command != NULL) {
658 char thishost[NI_MAXHOST];
660 if (gethostname(thishost, sizeof(thishost)) == -1)
661 fatal("gethostname: %s", strerror(errno));
662 snprintf(buf, sizeof(buf), "%d", options.port);
663 debug3("expanding LocalCommand: %s", options.local_command);
664 cp = options.local_command;
665 options.local_command = percent_expand(cp, "d", pw->pw_dir,
666 "h", options.hostname? options.hostname : host,
667 "l", thishost, "n", host, "r", options.user, "p", buf,
668 "u", pw->pw_name, (char *)NULL);
669 debug3("expanded LocalCommand: %s", options.local_command);
673 if (options.hostname != NULL)
674 host = options.hostname;
676 /* Find canonic host name. */
677 if (strchr(host, '.') == 0) {
678 struct addrinfo hints;
679 struct addrinfo *ai = NULL;
681 memset(&hints, 0, sizeof(hints));
682 hints.ai_family = options.address_family;
683 hints.ai_flags = AI_CANONNAME;
684 hints.ai_socktype = SOCK_STREAM;
685 errgai = getaddrinfo(host, NULL, &hints, &ai);
687 if (ai->ai_canonname != NULL)
688 host = xstrdup(ai->ai_canonname);
693 /* force lowercase for hostkey matching */
694 if (options.host_key_alias != NULL) {
695 for (p = options.host_key_alias; *p; p++)
697 *p = (char)tolower(*p);
700 if (options.proxy_command != NULL &&
701 strcmp(options.proxy_command, "none") == 0) {
702 xfree(options.proxy_command);
703 options.proxy_command = NULL;
705 if (options.control_path != NULL &&
706 strcmp(options.control_path, "none") == 0) {
707 xfree(options.control_path);
708 options.control_path = NULL;
711 if (options.control_path != NULL) {
712 char thishost[NI_MAXHOST];
714 if (gethostname(thishost, sizeof(thishost)) == -1)
715 fatal("gethostname: %s", strerror(errno));
716 snprintf(buf, sizeof(buf), "%d", options.port);
717 cp = tilde_expand_filename(options.control_path,
719 xfree(options.control_path);
720 options.control_path = percent_expand(cp, "p", buf, "h", host,
721 "r", options.user, "l", thishost, (char *)NULL);
724 if (muxclient_command != 0 && options.control_path == NULL)
725 fatal("No ControlPath specified for \"-O\" command");
726 if (options.control_path != NULL)
727 muxclient(options.control_path);
729 timeout_ms = options.connection_timeout * 1000;
731 /* Open a connection to the remote host. */
732 if (ssh_connect(host, &hostaddr, options.port,
733 options.address_family, options.connection_attempts, &timeout_ms,
734 options.tcp_keep_alive,
736 options.use_privileged_port,
738 original_effective_uid == 0 && options.use_privileged_port,
740 options.proxy_command) != 0)
744 debug3("timeout: %d ms remain after connect", timeout_ms);
747 * If we successfully made the connection, load the host private key
748 * in case we will need it later for combined rsa-rhosts
749 * authentication. This must be done before releasing extra
750 * privileges, because the file is only readable by root.
751 * If we cannot access the private keys, load the public keys
752 * instead and try to execute the ssh-keysign helper instead.
754 sensitive_data.nkeys = 0;
755 sensitive_data.keys = NULL;
756 sensitive_data.external_keysign = 0;
757 if (options.rhosts_rsa_authentication ||
758 options.hostbased_authentication) {
759 sensitive_data.nkeys = 3;
760 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
764 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
765 _PATH_HOST_KEY_FILE, "", NULL, NULL);
766 sensitive_data.keys[1] = key_load_private_type(KEY_DSA,
767 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
768 sensitive_data.keys[2] = key_load_private_type(KEY_RSA,
769 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
772 if (options.hostbased_authentication == 1 &&
773 sensitive_data.keys[0] == NULL &&
774 sensitive_data.keys[1] == NULL &&
775 sensitive_data.keys[2] == NULL) {
776 sensitive_data.keys[1] = key_load_public(
777 _PATH_HOST_DSA_KEY_FILE, NULL);
778 sensitive_data.keys[2] = key_load_public(
779 _PATH_HOST_RSA_KEY_FILE, NULL);
780 sensitive_data.external_keysign = 1;
784 * Get rid of any extra privileges that we may have. We will no
785 * longer need them. Also, extra privileges could make it very hard
786 * to read identity files and other non-world-readable files from the
787 * user's home directory if it happens to be on a NFS volume where
788 * root is mapped to nobody.
790 if (original_effective_uid == 0) {
792 permanently_set_uid(pw);
796 * Now that we are back to our own permissions, create ~/.ssh
797 * directory if it doesn't already exist.
799 snprintf(buf, sizeof buf, "%.100s%s%.100s", pw->pw_dir,
800 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
801 if (stat(buf, &st) < 0)
802 if (mkdir(buf, 0700) < 0)
803 error("Could not create directory '%.200s'.", buf);
805 /* load options.identity_files */
806 load_public_identity_files();
808 /* Expand ~ in known host file names. */
810 options.system_hostfile =
811 tilde_expand_filename(options.system_hostfile, original_real_uid);
812 options.user_hostfile =
813 tilde_expand_filename(options.user_hostfile, original_real_uid);
814 options.system_hostfile2 =
815 tilde_expand_filename(options.system_hostfile2, original_real_uid);
816 options.user_hostfile2 =
817 tilde_expand_filename(options.user_hostfile2, original_real_uid);
819 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
821 /* Log into the remote system. Never returns if the login fails. */
822 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
825 /* We no longer need the private host keys. Clear them now. */
826 if (sensitive_data.nkeys != 0) {
827 for (i = 0; i < sensitive_data.nkeys; i++) {
828 if (sensitive_data.keys[i] != NULL) {
829 /* Destroys contents safely */
830 debug3("clear hostkey %d", i);
831 key_free(sensitive_data.keys[i]);
832 sensitive_data.keys[i] = NULL;
835 xfree(sensitive_data.keys);
837 for (i = 0; i < options.num_identity_files; i++) {
838 if (options.identity_files[i]) {
839 xfree(options.identity_files[i]);
840 options.identity_files[i] = NULL;
842 if (options.identity_keys[i]) {
843 key_free(options.identity_keys[i]);
844 options.identity_keys[i] = NULL;
848 exit_status = compat20 ? ssh_session2() : ssh_session();
851 if (options.control_path != NULL && muxserver_sock != -1)
852 unlink(options.control_path);
855 * Send SIGHUP to proxy command if used. We don't wait() in
856 * case it hangs and instead rely on init to reap the child
858 if (proxy_command_pid > 1)
859 kill(proxy_command_pid, SIGHUP);
864 /* Callback for remote forward global requests */
866 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
868 Forward *rfwd = (Forward *)ctxt;
870 debug("remote forward %s for: listen %d, connect %s:%d",
871 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
872 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
873 if (type == SSH2_MSG_REQUEST_FAILURE) {
874 if (options.exit_on_forward_failure)
875 fatal("Error: remote port forwarding failed for "
876 "listen port %d", rfwd->listen_port);
878 logit("Warning: remote port forwarding failed for "
879 "listen port %d", rfwd->listen_port);
881 if (++remote_forward_confirms_received == options.num_remote_forwards) {
882 debug("All remote forwarding requests processed");
883 if (fork_after_authentication_flag) {
884 fork_after_authentication_flag = 0;
885 if (daemon(1, 1) < 0)
886 fatal("daemon() failed: %.200s",
893 ssh_init_forwarding(void)
898 /* Initiate local TCP/IP port forwardings. */
899 for (i = 0; i < options.num_local_forwards; i++) {
900 debug("Local connections to %.200s:%d forwarded to remote "
902 (options.local_forwards[i].listen_host == NULL) ?
903 (options.gateway_ports ? "*" : "LOCALHOST") :
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 success += channel_setup_local_fwd_listener(
909 options.local_forwards[i].listen_host,
910 options.local_forwards[i].listen_port,
911 options.local_forwards[i].connect_host,
912 options.local_forwards[i].connect_port,
913 options.gateway_ports);
915 if (i > 0 && success != i && options.exit_on_forward_failure)
916 fatal("Could not request local forwarding.");
917 if (i > 0 && success == 0)
918 error("Could not request local forwarding.");
920 /* Initiate remote TCP/IP port forwardings. */
921 for (i = 0; i < options.num_remote_forwards; i++) {
922 debug("Remote connections from %.200s:%d forwarded to "
923 "local address %.200s:%d",
924 (options.remote_forwards[i].listen_host == NULL) ?
925 "LOCALHOST" : 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);
929 if (channel_request_remote_forwarding(
930 options.remote_forwards[i].listen_host,
931 options.remote_forwards[i].listen_port,
932 options.remote_forwards[i].connect_host,
933 options.remote_forwards[i].connect_port) < 0) {
934 if (options.exit_on_forward_failure)
935 fatal("Could not request remote forwarding.");
937 logit("Warning: Could not request remote "
940 client_register_global_confirm(ssh_confirm_remote_forward,
941 &options.remote_forwards[i]);
944 /* Initiate tunnel forwarding. */
945 if (options.tun_open != SSH_TUNMODE_NO) {
946 if (client_request_tun_fwd(options.tun_open,
947 options.tun_local, options.tun_remote) == -1) {
948 if (options.exit_on_forward_failure)
949 fatal("Could not request tunnel forwarding.");
951 error("Could not request tunnel forwarding.");
957 check_agent_present(void)
959 if (options.forward_agent) {
960 /* Clear agent forwarding if we don't have an agent. */
961 if (!ssh_agent_present())
962 options.forward_agent = 0;
976 /* Enable compression if requested. */
977 if (options.compression) {
978 debug("Requesting compression at level %d.",
979 options.compression_level);
981 if (options.compression_level < 1 ||
982 options.compression_level > 9)
983 fatal("Compression level must be from 1 (fast) to "
986 /* Send the request. */
987 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
988 packet_put_int(options.compression_level);
991 type = packet_read();
992 if (type == SSH_SMSG_SUCCESS)
993 packet_start_compression(options.compression_level);
994 else if (type == SSH_SMSG_FAILURE)
995 logit("Warning: Remote host refused compression.");
997 packet_disconnect("Protocol error waiting for "
998 "compression response.");
1000 /* Allocate a pseudo tty if appropriate. */
1002 debug("Requesting pty.");
1004 /* Start the packet. */
1005 packet_start(SSH_CMSG_REQUEST_PTY);
1007 /* Store TERM in the packet. There is no limit on the
1008 length of the string. */
1009 cp = getenv("TERM");
1012 packet_put_cstring(cp);
1014 /* Store window size in the packet. */
1015 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1016 memset(&ws, 0, sizeof(ws));
1017 packet_put_int((u_int)ws.ws_row);
1018 packet_put_int((u_int)ws.ws_col);
1019 packet_put_int((u_int)ws.ws_xpixel);
1020 packet_put_int((u_int)ws.ws_ypixel);
1022 /* Store tty modes in the packet. */
1023 tty_make_modes(fileno(stdin), NULL);
1025 /* Send the packet, and wait for it to leave. */
1027 packet_write_wait();
1029 /* Read response from the server. */
1030 type = packet_read();
1031 if (type == SSH_SMSG_SUCCESS) {
1034 } else if (type == SSH_SMSG_FAILURE)
1035 logit("Warning: Remote host failed or refused to "
1036 "allocate a pseudo tty.");
1038 packet_disconnect("Protocol error waiting for pty "
1039 "request response.");
1041 /* Request X11 forwarding if enabled and DISPLAY is set. */
1042 display = getenv("DISPLAY");
1043 if (options.forward_x11 && display != NULL) {
1045 /* Get reasonable local authentication information. */
1046 client_x11_get_proto(display, options.xauth_location,
1047 options.forward_x11_trusted, &proto, &data);
1048 /* Request forwarding with authentication spoofing. */
1049 debug("Requesting X11 forwarding with authentication "
1051 x11_request_forwarding_with_spoofing(0, display, proto, data);
1053 /* Read response from the server. */
1054 type = packet_read();
1055 if (type == SSH_SMSG_SUCCESS) {
1057 } else if (type == SSH_SMSG_FAILURE) {
1058 logit("Warning: Remote host denied X11 forwarding.");
1060 packet_disconnect("Protocol error waiting for X11 "
1064 /* Tell the packet module whether this is an interactive session. */
1065 packet_set_interactive(interactive);
1067 /* Request authentication agent forwarding if appropriate. */
1068 check_agent_present();
1070 if (options.forward_agent) {
1071 debug("Requesting authentication agent forwarding.");
1072 auth_request_forwarding();
1074 /* Read response from the server. */
1075 type = packet_read();
1077 if (type != SSH_SMSG_SUCCESS)
1078 logit("Warning: Remote host denied authentication agent forwarding.");
1081 /* Initiate port forwardings. */
1082 ssh_init_forwarding();
1084 /* Execute a local command */
1085 if (options.local_command != NULL &&
1086 options.permit_local_command)
1087 ssh_local_cmd(options.local_command);
1090 * If requested and we are not interested in replies to remote
1091 * forwarding requests, then let ssh continue in the background.
1093 if (fork_after_authentication_flag &&
1094 (!options.exit_on_forward_failure ||
1095 options.num_remote_forwards == 0)) {
1096 fork_after_authentication_flag = 0;
1097 if (daemon(1, 1) < 0)
1098 fatal("daemon() failed: %.200s", strerror(errno));
1102 * If a command was specified on the command line, execute the
1103 * command now. Otherwise request the server to start a shell.
1105 if (buffer_len(&command) > 0) {
1106 int len = buffer_len(&command);
1109 debug("Sending command: %.*s", len,
1110 (u_char *)buffer_ptr(&command));
1111 packet_start(SSH_CMSG_EXEC_CMD);
1112 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1114 packet_write_wait();
1116 debug("Requesting shell.");
1117 packet_start(SSH_CMSG_EXEC_SHELL);
1119 packet_write_wait();
1122 /* Enter the interactive session. */
1123 return client_loop(have_tty, tty_flag ?
1124 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1127 /* request pty/x11/agent/tcpfwd/shell for channel */
1129 ssh_session2_setup(int id, void *arg)
1131 extern char **environ;
1132 const char *display;
1133 int interactive = tty_flag;
1135 display = getenv("DISPLAY");
1136 if (options.forward_x11 && display != NULL) {
1138 /* Get reasonable local authentication information. */
1139 client_x11_get_proto(display, options.xauth_location,
1140 options.forward_x11_trusted, &proto, &data);
1141 /* Request forwarding with authentication spoofing. */
1142 debug("Requesting X11 forwarding with authentication "
1144 x11_request_forwarding_with_spoofing(id, display, proto, data);
1146 /* XXX wait for reply */
1149 check_agent_present();
1150 if (options.forward_agent) {
1151 debug("Requesting authentication agent forwarding.");
1152 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1156 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1157 NULL, fileno(stdin), &command, environ);
1159 packet_set_interactive(interactive);
1162 /* open new channel for a session */
1164 ssh_session2_open(void)
1167 int window, packetmax, in, out, err;
1169 if (stdin_null_flag) {
1170 in = open(_PATH_DEVNULL, O_RDONLY);
1172 in = dup(STDIN_FILENO);
1174 out = dup(STDOUT_FILENO);
1175 err = dup(STDERR_FILENO);
1177 if (in < 0 || out < 0 || err < 0)
1178 fatal("dup() in/out/err failed");
1180 /* enable nonblocking unless tty */
1188 window = CHAN_SES_WINDOW_DEFAULT;
1189 packetmax = CHAN_SES_PACKET_DEFAULT;
1195 "session", SSH_CHANNEL_OPENING, in, out, err,
1196 window, packetmax, CHAN_EXTENDED_WRITE,
1197 "client-session", /*nonblock*/0);
1199 debug3("ssh_session2_open: channel_new: %d", c->self);
1201 channel_send_open(c->self);
1203 channel_register_open_confirm(c->self,
1204 ssh_session2_setup, NULL);
1214 /* XXX should be pre-session */
1215 ssh_init_forwarding();
1217 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1218 id = ssh_session2_open();
1220 /* If we don't expect to open a new session, then disallow it */
1221 if (options.control_master == SSHCTL_MASTER_NO) {
1222 debug("Requesting no-more-sessions@openssh.com");
1223 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1224 packet_put_cstring("no-more-sessions@openssh.com");
1229 /* Execute a local command */
1230 if (options.local_command != NULL &&
1231 options.permit_local_command)
1232 ssh_local_cmd(options.local_command);
1234 /* Start listening for multiplex clients */
1237 /* If requested, let ssh continue in the background. */
1238 if (fork_after_authentication_flag) {
1239 fork_after_authentication_flag = 0;
1240 if (daemon(1, 1) < 0)
1241 fatal("daemon() failed: %.200s", strerror(errno));
1244 return client_loop(tty_flag, tty_flag ?
1245 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1249 load_public_identity_files(void)
1251 char *filename, *cp, thishost[NI_MAXHOST];
1252 char *pwdir = NULL, *pwname = NULL;
1259 if (options.smartcard_device != NULL &&
1260 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1261 (keys = sc_get_keys(options.smartcard_device, NULL)) != NULL) {
1263 for (i = 0; keys[i] != NULL; i++) {
1265 memmove(&options.identity_files[1],
1266 &options.identity_files[0],
1267 sizeof(char *) * (SSH_MAX_IDENTITY_FILES - 1));
1268 memmove(&options.identity_keys[1],
1269 &options.identity_keys[0],
1270 sizeof(Key *) * (SSH_MAX_IDENTITY_FILES - 1));
1271 options.num_identity_files++;
1272 options.identity_keys[0] = keys[i];
1273 options.identity_files[0] = sc_get_key_label(keys[i]);
1275 if (options.num_identity_files > SSH_MAX_IDENTITY_FILES)
1276 options.num_identity_files = SSH_MAX_IDENTITY_FILES;
1280 #endif /* SMARTCARD */
1281 if ((pw = getpwuid(original_real_uid)) == NULL)
1282 fatal("load_public_identity_files: getpwuid failed");
1283 pwname = xstrdup(pw->pw_name);
1284 pwdir = xstrdup(pw->pw_dir);
1285 if (gethostname(thishost, sizeof(thishost)) == -1)
1286 fatal("load_public_identity_files: gethostname: %s",
1288 for (; i < options.num_identity_files; i++) {
1289 cp = tilde_expand_filename(options.identity_files[i],
1291 filename = percent_expand(cp, "d", pwdir,
1292 "u", pwname, "l", thishost, "h", host,
1293 "r", options.user, (char *)NULL);
1295 public = key_load_public(filename, NULL);
1296 debug("identity file %s type %d", filename,
1297 public ? public->type : -1);
1298 xfree(options.identity_files[i]);
1299 options.identity_files[i] = filename;
1300 options.identity_keys[i] = public;
1302 bzero(pwname, strlen(pwname));
1304 bzero(pwdir, strlen(pwdir));