1 /* $OpenBSD: ssh.c,v 1.370 2012/07/06 01:47:38 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/param.h>
52 #include <sys/socket.h>
71 #include <netinet/in.h>
72 #include <arpa/inet.h>
74 #include <openssl/evp.h>
75 #include <openssl/err.h>
76 #include "openbsd-compat/openssl-compat.h"
77 #include "openbsd-compat/sys-queue.h"
92 #include "pathnames.h"
94 #include "clientloop.h"
97 #include "sshconnect.h"
109 #include "ssh-pkcs11.h"
112 extern char *__progname;
114 /* Saves a copy of argv for setproctitle emulation */
115 #ifndef HAVE_SETPROCTITLE
116 static char **saved_av;
119 /* Flag indicating whether debug mode is on. May be set on the command line. */
122 /* Flag indicating whether a tty should be requested */
125 /* don't exec a shell */
126 int no_shell_flag = 0;
129 * Flag indicating that nothing should be read from stdin. This can be set
130 * on the command line.
132 int stdin_null_flag = 0;
135 * Flag indicating that the current process should be backgrounded and
136 * a new slave launched in the foreground for ControlPersist.
138 int need_controlpersist_detach = 0;
140 /* Copies of flags for ControlPersist foreground slave */
141 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
144 * Flag indicating that ssh should fork after authentication. This is useful
145 * so that the passphrase can be entered manually, and then ssh goes to the
148 int fork_after_authentication_flag = 0;
150 /* forward stdio to remote host and port */
151 char *stdio_forward_host = NULL;
152 int stdio_forward_port = 0;
155 * General data structure for command line options and options configurable
156 * in configuration files. See readconf.h.
160 /* optional user configfile */
164 * Name of the host we are connecting to. This is the name given on the
165 * command line, or the HostName specified for the user-supplied name in a
166 * configuration file.
170 /* socket address the host resolves to */
171 struct sockaddr_storage hostaddr;
173 /* Private host keys. */
174 Sensitive sensitive_data;
176 /* Original real UID. */
177 uid_t original_real_uid;
178 uid_t original_effective_uid;
180 /* command to be executed */
183 /* Should we execute a command or invoke a subsystem? */
184 int subsystem_flag = 0;
186 /* # of replies received for global requests */
187 static int remote_forward_confirms_received = 0;
190 extern int muxserver_sock;
191 extern u_int muxclient_command;
193 /* Prints a help message to the user. This function never returns. */
199 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
200 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
201 " [-I pkcs11] [-i identity_file]\n"
202 " [-L [bind_address:]port:host:hostport]\n"
203 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
204 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
205 " [-W host:port] [-w local_tun[:remote_tun]]\n"
206 " [user@]hostname [command]\n"
211 static int ssh_session(void);
212 static int ssh_session2(void);
213 static void load_public_identity_files(void);
214 static void main_sigchld_handler(int);
216 /* from muxclient.c */
217 void muxclient(const char *);
218 void muxserver_listen(void);
220 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
222 tilde_expand_paths(char **paths, u_int num_paths)
227 for (i = 0; i < num_paths; i++) {
228 cp = tilde_expand_filename(paths[i], original_real_uid);
235 * Main program for the ssh client.
238 main(int ac, char **av)
240 int i, r, opt, exit_status, use_syslog;
241 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg;
242 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
245 int dummy, timeout_ms;
246 extern int optind, optreset;
252 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
255 __progname = ssh_get_progname(av[0]);
257 #ifndef HAVE_SETPROCTITLE
258 /* Prepare for later setproctitle emulation */
259 /* Save argv so it isn't clobbered by setproctitle() emulation */
260 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
261 for (i = 0; i < ac; i++)
262 saved_av[i] = xstrdup(av[i]);
264 compat_init_setproctitle(ac, av);
269 * Discard other fds that are hanging around. These can cause problem
270 * with backgrounded ssh processes started by ControlPersist.
272 closefrom(STDERR_FILENO + 1);
275 * Save the original real uid. It will be needed later (uid-swapping
276 * may clobber the real uid).
278 original_real_uid = getuid();
279 original_effective_uid = geteuid();
282 * Use uid-swapping to give up root privileges for the duration of
283 * option processing. We will re-instantiate the rights when we are
284 * ready to create the privileged port, and will permanently drop
285 * them when the port has been created (actually, when the connection
286 * has been made, as we may need to create the port several times).
290 #ifdef HAVE_SETRLIMIT
291 /* If we are installed setuid root be careful to not drop core. */
292 if (original_real_uid != original_effective_uid) {
294 rlim.rlim_cur = rlim.rlim_max = 0;
295 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
296 fatal("setrlimit failed: %.100s", strerror(errno));
300 pw = getpwuid(original_real_uid);
302 logit("You don't exist, go away!");
305 /* Take a copy of the returned structure. */
309 * Set our umask to something reasonable, as some files are created
310 * with the default umask. This will make them world-readable but
311 * writable only by the owner, which is ok for all files for which we
312 * don't set the modes explicitly.
317 * Initialize option structure to indicate that no values have been
320 initialize_options(&options);
322 /* Parse command-line arguments. */
328 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
329 "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
332 options.protocol = SSH_PROTO_1;
335 options.protocol = SSH_PROTO_2;
338 options.address_family = AF_INET;
341 options.address_family = AF_INET6;
347 fork_after_authentication_flag = 1;
351 options.forward_x11 = 0;
354 options.forward_x11 = 1;
360 options.forward_x11 = 1;
361 options.forward_x11_trusted = 1;
364 options.gateway_ports = 1;
367 if (stdio_forward_host != NULL)
368 fatal("Cannot specify multiplexing "
370 else if (muxclient_command != 0)
371 fatal("Multiplexing command already specified");
372 if (strcmp(optarg, "check") == 0)
373 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
374 else if (strcmp(optarg, "forward") == 0)
375 muxclient_command = SSHMUX_COMMAND_FORWARD;
376 else if (strcmp(optarg, "exit") == 0)
377 muxclient_command = SSHMUX_COMMAND_TERMINATE;
378 else if (strcmp(optarg, "stop") == 0)
379 muxclient_command = SSHMUX_COMMAND_STOP;
380 else if (strcmp(optarg, "cancel") == 0)
381 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
383 fatal("Invalid multiplex command.");
385 case 'P': /* deprecated */
386 options.use_privileged_port = 0;
389 options.forward_agent = 0;
392 options.forward_agent = 1;
395 options.gss_deleg_creds = 0;
398 options.gss_authentication = 1;
399 options.gss_deleg_creds = 1;
402 if (stat(optarg, &st) < 0) {
403 fprintf(stderr, "Warning: Identity file %s "
404 "not accessible: %s.\n", optarg,
408 if (options.num_identity_files >=
409 SSH_MAX_IDENTITY_FILES)
410 fatal("Too many identity files specified "
411 "(max %d)", SSH_MAX_IDENTITY_FILES);
412 options.identity_files[options.num_identity_files++] =
417 options.pkcs11_provider = xstrdup(optarg);
419 fprintf(stderr, "no support for PKCS#11.\n");
423 if (options.request_tty == REQUEST_TTY_YES)
424 options.request_tty = REQUEST_TTY_FORCE;
426 options.request_tty = REQUEST_TTY_YES;
429 if (debug_flag == 0) {
431 options.log_level = SYSLOG_LEVEL_DEBUG1;
433 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
439 fprintf(stderr, "%s, %s\n",
440 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
445 if (options.tun_open == -1)
446 options.tun_open = SSH_TUNMODE_DEFAULT;
447 options.tun_local = a2tun(optarg, &options.tun_remote);
448 if (options.tun_local == SSH_TUNID_ERR) {
450 "Bad tun device '%s'\n", optarg);
455 if (stdio_forward_host != NULL)
456 fatal("stdio forward already specified");
457 if (muxclient_command != 0)
458 fatal("Cannot specify stdio forward with -O");
459 if (parse_forward(&fwd, optarg, 1, 0)) {
460 stdio_forward_host = fwd.listen_host;
461 stdio_forward_port = fwd.listen_port;
462 xfree(fwd.connect_host);
465 "Bad stdio forwarding specification '%s'\n",
469 options.request_tty = REQUEST_TTY_NO;
471 options.clear_forwardings = 1;
472 options.exit_on_forward_failure = 1;
475 options.log_level = SYSLOG_LEVEL_QUIET;
478 if (optarg[0] == '^' && optarg[2] == 0 &&
479 (u_char) optarg[1] >= 64 &&
480 (u_char) optarg[1] < 128)
481 options.escape_char = (u_char) optarg[1] & 31;
482 else if (strlen(optarg) == 1)
483 options.escape_char = (u_char) optarg[0];
484 else if (strcmp(optarg, "none") == 0)
485 options.escape_char = SSH_ESCAPECHAR_NONE;
487 fprintf(stderr, "Bad escape character '%s'.\n",
493 if (ciphers_valid(optarg)) {
495 options.ciphers = xstrdup(optarg);
496 options.cipher = SSH_CIPHER_INVALID;
499 options.cipher = cipher_number(optarg);
500 if (options.cipher == -1) {
502 "Unknown cipher type '%s'\n",
506 if (options.cipher == SSH_CIPHER_3DES)
507 options.ciphers = "3des-cbc";
508 else if (options.cipher == SSH_CIPHER_BLOWFISH)
509 options.ciphers = "blowfish-cbc";
511 options.ciphers = (char *)-1;
515 if (mac_valid(optarg))
516 options.macs = xstrdup(optarg);
518 fprintf(stderr, "Unknown mac type '%s'\n",
524 if (options.control_master == SSHCTL_MASTER_YES)
525 options.control_master = SSHCTL_MASTER_ASK;
527 options.control_master = SSHCTL_MASTER_YES;
530 options.port = a2port(optarg);
531 if (options.port <= 0) {
532 fprintf(stderr, "Bad port '%s'\n", optarg);
537 options.user = optarg;
541 if (parse_forward(&fwd, optarg, 0, 0))
542 add_local_forward(&options, &fwd);
545 "Bad local forwarding specification '%s'\n",
552 if (parse_forward(&fwd, optarg, 0, 1)) {
553 add_remote_forward(&options, &fwd);
556 "Bad remote forwarding specification "
563 if (parse_forward(&fwd, optarg, 1, 0)) {
564 add_local_forward(&options, &fwd);
567 "Bad dynamic forwarding specification "
574 options.compression = 1;
578 options.request_tty = REQUEST_TTY_NO;
581 options.request_tty = REQUEST_TTY_NO;
585 line = xstrdup(optarg);
586 if (process_config_line(&options, host ? host : "",
587 line, "command-line", 0, &dummy) != 0)
595 if (options.control_path != NULL)
596 free(options.control_path);
597 options.control_path = xstrdup(optarg);
600 options.bind_address = optarg;
613 if (ac > 0 && !host) {
614 if (strrchr(*av, '@')) {
616 cp = strrchr(p, '@');
617 if (cp == NULL || cp == p)
625 optind = optreset = 1;
631 /* Check that we got a host name. */
635 OpenSSL_add_all_algorithms();
636 ERR_load_crypto_strings();
638 /* Initialize the command to execute on remote host. */
639 buffer_init(&command);
642 * Save the command to execute on the remote host in a buffer. There
643 * is no limit on the length of the command, except by the maximum
644 * packet size. Also sets the tty flag if there is no command.
647 /* No command specified - execute shell on a tty. */
648 if (subsystem_flag) {
650 "You must specify a subsystem to invoke.\n");
654 /* A command has been specified. Store it into the buffer. */
655 for (i = 0; i < ac; i++) {
657 buffer_append(&command, " ", 1);
658 buffer_append(&command, av[i], strlen(av[i]));
662 /* Cannot fork to background if no command. */
663 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
665 fatal("Cannot fork into background without a command "
669 * Initialize "log" output. Since we are the client all output
670 * actually goes to stderr.
673 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
674 SYSLOG_FACILITY_USER, !use_syslog);
677 * Read per-user configuration file. Ignore the system wide config
678 * file if the user specifies a config file on the command line.
680 if (config != NULL) {
681 if (!read_config_file(config, host, &options, 0))
682 fatal("Can't open user config file %.100s: "
683 "%.100s", config, strerror(errno));
685 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
686 _PATH_SSH_USER_CONFFILE);
687 if (r > 0 && (size_t)r < sizeof(buf))
688 (void)read_config_file(buf, host, &options, 1);
690 /* Read systemwide configuration file after user config. */
691 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
695 /* Fill configuration defaults. */
696 fill_default_options(&options);
698 channel_set_af(options.address_family);
701 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
703 if (options.request_tty == REQUEST_TTY_YES ||
704 options.request_tty == REQUEST_TTY_FORCE)
707 /* Allocate a tty by default if no command specified. */
708 if (buffer_len(&command) == 0)
709 tty_flag = options.request_tty != REQUEST_TTY_NO;
712 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
714 /* Do not allocate a tty if stdin is not a tty. */
715 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
716 options.request_tty != REQUEST_TTY_FORCE) {
718 logit("Pseudo-terminal will not be allocated because "
719 "stdin is not a terminal.");
725 if (options.user == NULL)
726 options.user = xstrdup(pw->pw_name);
728 /* Get default port if port has not been set. */
729 if (options.port == 0) {
730 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
731 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
734 /* preserve host name given on command line for %n expansion */
736 if (options.hostname != NULL) {
737 host = percent_expand(options.hostname,
738 "h", host, (char *)NULL);
741 if (gethostname(thishost, sizeof(thishost)) == -1)
742 fatal("gethostname: %s", strerror(errno));
743 strlcpy(shorthost, thishost, sizeof(shorthost));
744 shorthost[strcspn(thishost, ".")] = '\0';
745 snprintf(portstr, sizeof(portstr), "%d", options.port);
747 if (options.local_command != NULL) {
748 debug3("expanding LocalCommand: %s", options.local_command);
749 cp = options.local_command;
750 options.local_command = percent_expand(cp, "d", pw->pw_dir,
751 "h", host, "l", thishost, "n", host_arg, "r", options.user,
752 "p", portstr, "u", pw->pw_name, "L", shorthost,
754 debug3("expanded LocalCommand: %s", options.local_command);
758 /* force lowercase for hostkey matching */
759 if (options.host_key_alias != NULL) {
760 for (p = options.host_key_alias; *p; p++)
762 *p = (char)tolower(*p);
765 if (options.proxy_command != NULL &&
766 strcmp(options.proxy_command, "none") == 0) {
767 xfree(options.proxy_command);
768 options.proxy_command = NULL;
770 if (options.control_path != NULL &&
771 strcmp(options.control_path, "none") == 0) {
772 xfree(options.control_path);
773 options.control_path = NULL;
776 if (options.control_path != NULL) {
777 cp = tilde_expand_filename(options.control_path,
779 xfree(options.control_path);
780 options.control_path = percent_expand(cp, "h", host,
781 "l", thishost, "n", host_arg, "r", options.user,
782 "p", portstr, "u", pw->pw_name, "L", shorthost,
786 if (muxclient_command != 0 && options.control_path == NULL)
787 fatal("No ControlPath specified for \"-O\" command");
788 if (options.control_path != NULL)
789 muxclient(options.control_path);
791 timeout_ms = options.connection_timeout * 1000;
793 /* Open a connection to the remote host. */
794 if (ssh_connect(host, &hostaddr, options.port,
795 options.address_family, options.connection_attempts, &timeout_ms,
796 options.tcp_keep_alive,
798 options.use_privileged_port,
800 original_effective_uid == 0 && options.use_privileged_port,
802 options.proxy_command) != 0)
806 debug3("timeout: %d ms remain after connect", timeout_ms);
809 * If we successfully made the connection, load the host private key
810 * in case we will need it later for combined rsa-rhosts
811 * authentication. This must be done before releasing extra
812 * privileges, because the file is only readable by root.
813 * If we cannot access the private keys, load the public keys
814 * instead and try to execute the ssh-keysign helper instead.
816 sensitive_data.nkeys = 0;
817 sensitive_data.keys = NULL;
818 sensitive_data.external_keysign = 0;
819 if (options.rhosts_rsa_authentication ||
820 options.hostbased_authentication) {
821 sensitive_data.nkeys = 7;
822 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
824 for (i = 0; i < sensitive_data.nkeys; i++)
825 sensitive_data.keys[i] = NULL;
828 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
829 _PATH_HOST_KEY_FILE, "", NULL, NULL);
830 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
831 _PATH_HOST_DSA_KEY_FILE, "", NULL);
832 #ifdef OPENSSL_HAS_ECC
833 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
834 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
836 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
837 _PATH_HOST_RSA_KEY_FILE, "", NULL);
838 sensitive_data.keys[4] = key_load_private_type(KEY_DSA,
839 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
840 #ifdef OPENSSL_HAS_ECC
841 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
842 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
844 sensitive_data.keys[6] = key_load_private_type(KEY_RSA,
845 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
848 if (options.hostbased_authentication == 1 &&
849 sensitive_data.keys[0] == NULL &&
850 sensitive_data.keys[4] == NULL &&
851 sensitive_data.keys[5] == NULL &&
852 sensitive_data.keys[6] == NULL) {
853 sensitive_data.keys[1] = key_load_cert(
854 _PATH_HOST_DSA_KEY_FILE);
855 #ifdef OPENSSL_HAS_ECC
856 sensitive_data.keys[2] = key_load_cert(
857 _PATH_HOST_ECDSA_KEY_FILE);
859 sensitive_data.keys[3] = key_load_cert(
860 _PATH_HOST_RSA_KEY_FILE);
861 sensitive_data.keys[4] = key_load_public(
862 _PATH_HOST_DSA_KEY_FILE, NULL);
863 #ifdef OPENSSL_HAS_ECC
864 sensitive_data.keys[5] = key_load_public(
865 _PATH_HOST_ECDSA_KEY_FILE, NULL);
867 sensitive_data.keys[6] = key_load_public(
868 _PATH_HOST_RSA_KEY_FILE, NULL);
869 sensitive_data.external_keysign = 1;
873 * Get rid of any extra privileges that we may have. We will no
874 * longer need them. Also, extra privileges could make it very hard
875 * to read identity files and other non-world-readable files from the
876 * user's home directory if it happens to be on a NFS volume where
877 * root is mapped to nobody.
879 if (original_effective_uid == 0) {
881 permanently_set_uid(pw);
885 * Now that we are back to our own permissions, create ~/.ssh
886 * directory if it doesn't already exist.
888 if (config == NULL) {
889 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
890 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
891 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
893 ssh_selinux_setfscreatecon(buf);
895 if (mkdir(buf, 0700) < 0)
896 error("Could not create directory '%.200s'.",
899 ssh_selinux_setfscreatecon(NULL);
903 /* load options.identity_files */
904 load_public_identity_files();
906 /* Expand ~ in known host file names. */
907 tilde_expand_paths(options.system_hostfiles,
908 options.num_system_hostfiles);
909 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
911 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
912 signal(SIGCHLD, main_sigchld_handler);
914 /* Log into the remote system. Never returns if the login fails. */
915 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
916 options.port, pw, timeout_ms);
918 if (packet_connection_is_on_socket()) {
919 verbose("Authenticated to %s ([%s]:%d).", host,
920 get_remote_ipaddr(), get_remote_port());
922 verbose("Authenticated to %s (via proxy).", host);
925 /* We no longer need the private host keys. Clear them now. */
926 if (sensitive_data.nkeys != 0) {
927 for (i = 0; i < sensitive_data.nkeys; i++) {
928 if (sensitive_data.keys[i] != NULL) {
929 /* Destroys contents safely */
930 debug3("clear hostkey %d", i);
931 key_free(sensitive_data.keys[i]);
932 sensitive_data.keys[i] = NULL;
935 xfree(sensitive_data.keys);
937 for (i = 0; i < options.num_identity_files; i++) {
938 if (options.identity_files[i]) {
939 xfree(options.identity_files[i]);
940 options.identity_files[i] = NULL;
942 if (options.identity_keys[i]) {
943 key_free(options.identity_keys[i]);
944 options.identity_keys[i] = NULL;
948 exit_status = compat20 ? ssh_session2() : ssh_session();
951 if (options.control_path != NULL && muxserver_sock != -1)
952 unlink(options.control_path);
954 /* Kill ProxyCommand if it is running. */
955 ssh_kill_proxy_command();
961 control_persist_detach(void)
966 debug("%s: backgrounding master process", __func__);
969 * master (current process) into the background, and make the
970 * foreground process a client of the backgrounded master.
972 switch ((pid = fork())) {
974 fatal("%s: fork: %s", __func__, strerror(errno));
976 /* Child: master process continues mainloop */
979 /* Parent: set up mux slave to connect to backgrounded master */
980 debug2("%s: background process is %ld", __func__, (long)pid);
981 stdin_null_flag = ostdin_null_flag;
982 options.request_tty = orequest_tty;
983 tty_flag = otty_flag;
984 close(muxserver_sock);
986 options.control_master = SSHCTL_MASTER_NO;
987 muxclient(options.control_path);
988 /* muxclient() doesn't return on success. */
989 fatal("Failed to connect to new control master");
991 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
992 error("%s: open(\"/dev/null\"): %s", __func__,
995 if (dup2(devnull, STDIN_FILENO) == -1 ||
996 dup2(devnull, STDOUT_FILENO) == -1)
997 error("%s: dup2: %s", __func__, strerror(errno));
998 if (devnull > STDERR_FILENO)
1001 setproctitle("%s [mux]", options.control_path);
1004 /* Do fork() after authentication. Used by "ssh -f" */
1008 if (need_controlpersist_detach)
1009 control_persist_detach();
1010 debug("forking to background");
1011 fork_after_authentication_flag = 0;
1012 if (daemon(1, 1) < 0)
1013 fatal("daemon() failed: %.200s", strerror(errno));
1016 /* Callback for remote forward global requests */
1018 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1020 Forward *rfwd = (Forward *)ctxt;
1022 /* XXX verbose() on failure? */
1023 debug("remote forward %s for: listen %d, connect %s:%d",
1024 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1025 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1026 if (rfwd->listen_port == 0) {
1027 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1028 rfwd->allocated_port = packet_get_int();
1029 logit("Allocated port %u for remote forward to %s:%d",
1030 rfwd->allocated_port,
1031 rfwd->connect_host, rfwd->connect_port);
1032 channel_update_permitted_opens(rfwd->handle,
1033 rfwd->allocated_port);
1035 channel_update_permitted_opens(rfwd->handle, -1);
1039 if (type == SSH2_MSG_REQUEST_FAILURE) {
1040 if (options.exit_on_forward_failure)
1041 fatal("Error: remote port forwarding failed for "
1042 "listen port %d", rfwd->listen_port);
1044 logit("Warning: remote port forwarding failed for "
1045 "listen port %d", rfwd->listen_port);
1047 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1048 debug("All remote forwarding requests processed");
1049 if (fork_after_authentication_flag)
1055 client_cleanup_stdio_fwd(int id, void *arg)
1057 debug("stdio forwarding: done");
1062 ssh_init_stdio_forwarding(void)
1067 if (stdio_forward_host == NULL)
1070 fatal("stdio forwarding require Protocol 2");
1072 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1074 if ((in = dup(STDIN_FILENO)) < 0 ||
1075 (out = dup(STDOUT_FILENO)) < 0)
1076 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1077 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1078 stdio_forward_port, in, out)) == NULL)
1079 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1080 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1084 ssh_init_forwarding(void)
1089 /* Initiate local TCP/IP port forwardings. */
1090 for (i = 0; i < options.num_local_forwards; i++) {
1091 debug("Local connections to %.200s:%d forwarded to remote "
1092 "address %.200s:%d",
1093 (options.local_forwards[i].listen_host == NULL) ?
1094 (options.gateway_ports ? "*" : "LOCALHOST") :
1095 options.local_forwards[i].listen_host,
1096 options.local_forwards[i].listen_port,
1097 options.local_forwards[i].connect_host,
1098 options.local_forwards[i].connect_port);
1099 success += channel_setup_local_fwd_listener(
1100 options.local_forwards[i].listen_host,
1101 options.local_forwards[i].listen_port,
1102 options.local_forwards[i].connect_host,
1103 options.local_forwards[i].connect_port,
1104 options.gateway_ports);
1106 if (i > 0 && success != i && options.exit_on_forward_failure)
1107 fatal("Could not request local forwarding.");
1108 if (i > 0 && success == 0)
1109 error("Could not request local forwarding.");
1111 /* Initiate remote TCP/IP port forwardings. */
1112 for (i = 0; i < options.num_remote_forwards; i++) {
1113 debug("Remote connections from %.200s:%d forwarded to "
1114 "local address %.200s:%d",
1115 (options.remote_forwards[i].listen_host == NULL) ?
1116 "LOCALHOST" : options.remote_forwards[i].listen_host,
1117 options.remote_forwards[i].listen_port,
1118 options.remote_forwards[i].connect_host,
1119 options.remote_forwards[i].connect_port);
1120 options.remote_forwards[i].handle =
1121 channel_request_remote_forwarding(
1122 options.remote_forwards[i].listen_host,
1123 options.remote_forwards[i].listen_port,
1124 options.remote_forwards[i].connect_host,
1125 options.remote_forwards[i].connect_port);
1126 if (options.remote_forwards[i].handle < 0) {
1127 if (options.exit_on_forward_failure)
1128 fatal("Could not request remote forwarding.");
1130 logit("Warning: Could not request remote "
1133 client_register_global_confirm(ssh_confirm_remote_forward,
1134 &options.remote_forwards[i]);
1138 /* Initiate tunnel forwarding. */
1139 if (options.tun_open != SSH_TUNMODE_NO) {
1140 if (client_request_tun_fwd(options.tun_open,
1141 options.tun_local, options.tun_remote) == -1) {
1142 if (options.exit_on_forward_failure)
1143 fatal("Could not request tunnel forwarding.");
1145 error("Could not request tunnel forwarding.");
1151 check_agent_present(void)
1153 if (options.forward_agent) {
1154 /* Clear agent forwarding if we don't have an agent. */
1155 if (!ssh_agent_present())
1156 options.forward_agent = 0;
1164 int interactive = 0;
1168 const char *display;
1170 /* Enable compression if requested. */
1171 if (options.compression) {
1172 debug("Requesting compression at level %d.",
1173 options.compression_level);
1175 if (options.compression_level < 1 ||
1176 options.compression_level > 9)
1177 fatal("Compression level must be from 1 (fast) to "
1180 /* Send the request. */
1181 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1182 packet_put_int(options.compression_level);
1184 packet_write_wait();
1185 type = packet_read();
1186 if (type == SSH_SMSG_SUCCESS)
1187 packet_start_compression(options.compression_level);
1188 else if (type == SSH_SMSG_FAILURE)
1189 logit("Warning: Remote host refused compression.");
1191 packet_disconnect("Protocol error waiting for "
1192 "compression response.");
1194 /* Allocate a pseudo tty if appropriate. */
1196 debug("Requesting pty.");
1198 /* Start the packet. */
1199 packet_start(SSH_CMSG_REQUEST_PTY);
1201 /* Store TERM in the packet. There is no limit on the
1202 length of the string. */
1203 cp = getenv("TERM");
1206 packet_put_cstring(cp);
1208 /* Store window size in the packet. */
1209 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1210 memset(&ws, 0, sizeof(ws));
1211 packet_put_int((u_int)ws.ws_row);
1212 packet_put_int((u_int)ws.ws_col);
1213 packet_put_int((u_int)ws.ws_xpixel);
1214 packet_put_int((u_int)ws.ws_ypixel);
1216 /* Store tty modes in the packet. */
1217 tty_make_modes(fileno(stdin), NULL);
1219 /* Send the packet, and wait for it to leave. */
1221 packet_write_wait();
1223 /* Read response from the server. */
1224 type = packet_read();
1225 if (type == SSH_SMSG_SUCCESS) {
1228 } else if (type == SSH_SMSG_FAILURE)
1229 logit("Warning: Remote host failed or refused to "
1230 "allocate a pseudo tty.");
1232 packet_disconnect("Protocol error waiting for pty "
1233 "request response.");
1235 /* Request X11 forwarding if enabled and DISPLAY is set. */
1236 display = getenv("DISPLAY");
1237 if (options.forward_x11 && display != NULL) {
1239 /* Get reasonable local authentication information. */
1240 client_x11_get_proto(display, options.xauth_location,
1241 options.forward_x11_trusted,
1242 options.forward_x11_timeout,
1244 /* Request forwarding with authentication spoofing. */
1245 debug("Requesting X11 forwarding with authentication "
1247 x11_request_forwarding_with_spoofing(0, display, proto,
1249 /* Read response from the server. */
1250 type = packet_read();
1251 if (type == SSH_SMSG_SUCCESS) {
1253 } else if (type == SSH_SMSG_FAILURE) {
1254 logit("Warning: Remote host denied X11 forwarding.");
1256 packet_disconnect("Protocol error waiting for X11 "
1260 /* Tell the packet module whether this is an interactive session. */
1261 packet_set_interactive(interactive,
1262 options.ip_qos_interactive, options.ip_qos_bulk);
1264 /* Request authentication agent forwarding if appropriate. */
1265 check_agent_present();
1267 if (options.forward_agent) {
1268 debug("Requesting authentication agent forwarding.");
1269 auth_request_forwarding();
1271 /* Read response from the server. */
1272 type = packet_read();
1274 if (type != SSH_SMSG_SUCCESS)
1275 logit("Warning: Remote host denied authentication agent forwarding.");
1278 /* Initiate port forwardings. */
1279 ssh_init_stdio_forwarding();
1280 ssh_init_forwarding();
1282 /* Execute a local command */
1283 if (options.local_command != NULL &&
1284 options.permit_local_command)
1285 ssh_local_cmd(options.local_command);
1288 * If requested and we are not interested in replies to remote
1289 * forwarding requests, then let ssh continue in the background.
1291 if (fork_after_authentication_flag) {
1292 if (options.exit_on_forward_failure &&
1293 options.num_remote_forwards > 0) {
1294 debug("deferring postauth fork until remote forward "
1295 "confirmation received");
1301 * If a command was specified on the command line, execute the
1302 * command now. Otherwise request the server to start a shell.
1304 if (buffer_len(&command) > 0) {
1305 int len = buffer_len(&command);
1308 debug("Sending command: %.*s", len,
1309 (u_char *)buffer_ptr(&command));
1310 packet_start(SSH_CMSG_EXEC_CMD);
1311 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1313 packet_write_wait();
1315 debug("Requesting shell.");
1316 packet_start(SSH_CMSG_EXEC_SHELL);
1318 packet_write_wait();
1321 /* Enter the interactive session. */
1322 return client_loop(have_tty, tty_flag ?
1323 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1326 /* request pty/x11/agent/tcpfwd/shell for channel */
1328 ssh_session2_setup(int id, int success, void *arg)
1330 extern char **environ;
1331 const char *display;
1332 int interactive = tty_flag;
1335 return; /* No need for error message, channels code sens one */
1337 display = getenv("DISPLAY");
1338 if (options.forward_x11 && display != NULL) {
1340 /* Get reasonable local authentication information. */
1341 client_x11_get_proto(display, options.xauth_location,
1342 options.forward_x11_trusted,
1343 options.forward_x11_timeout, &proto, &data);
1344 /* Request forwarding with authentication spoofing. */
1345 debug("Requesting X11 forwarding with authentication "
1347 x11_request_forwarding_with_spoofing(id, display, proto,
1349 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1350 /* XXX exit_on_forward_failure */
1354 check_agent_present();
1355 if (options.forward_agent) {
1356 debug("Requesting authentication agent forwarding.");
1357 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1361 /* Tell the packet module whether this is an interactive session. */
1362 packet_set_interactive(interactive,
1363 options.ip_qos_interactive, options.ip_qos_bulk);
1365 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1366 NULL, fileno(stdin), &command, environ);
1369 /* open new channel for a session */
1371 ssh_session2_open(void)
1374 int window, packetmax, in, out, err;
1376 if (stdin_null_flag) {
1377 in = open(_PATH_DEVNULL, O_RDONLY);
1379 in = dup(STDIN_FILENO);
1381 out = dup(STDOUT_FILENO);
1382 err = dup(STDERR_FILENO);
1384 if (in < 0 || out < 0 || err < 0)
1385 fatal("dup() in/out/err failed");
1387 /* enable nonblocking unless tty */
1395 window = CHAN_SES_WINDOW_DEFAULT;
1396 packetmax = CHAN_SES_PACKET_DEFAULT;
1402 "session", SSH_CHANNEL_OPENING, in, out, err,
1403 window, packetmax, CHAN_EXTENDED_WRITE,
1404 "client-session", /*nonblock*/0);
1406 debug3("ssh_session2_open: channel_new: %d", c->self);
1408 channel_send_open(c->self);
1410 channel_register_open_confirm(c->self,
1411 ssh_session2_setup, NULL);
1421 /* XXX should be pre-session */
1422 if (!options.control_persist)
1423 ssh_init_stdio_forwarding();
1424 ssh_init_forwarding();
1426 /* Start listening for multiplex clients */
1430 * If we are in control persist mode and have a working mux listen
1431 * socket, then prepare to background ourselves and have a foreground
1432 * client attach as a control slave.
1433 * NB. we must save copies of the flags that we override for
1434 * the backgrounding, since we defer attachment of the slave until
1435 * after the connection is fully established (in particular,
1436 * async rfwd replies have been received for ExitOnForwardFailure).
1438 if (options.control_persist && muxserver_sock != -1) {
1439 ostdin_null_flag = stdin_null_flag;
1440 ono_shell_flag = no_shell_flag;
1441 orequest_tty = options.request_tty;
1442 otty_flag = tty_flag;
1443 stdin_null_flag = 1;
1446 if (!fork_after_authentication_flag)
1447 need_controlpersist_detach = 1;
1448 fork_after_authentication_flag = 1;
1451 * ControlPersist mux listen socket setup failed, attempt the
1452 * stdio forward setup that we skipped earlier.
1454 if (options.control_persist && muxserver_sock == -1)
1455 ssh_init_stdio_forwarding();
1457 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1458 id = ssh_session2_open();
1460 /* If we don't expect to open a new session, then disallow it */
1461 if (options.control_master == SSHCTL_MASTER_NO &&
1462 (datafellows & SSH_NEW_OPENSSH)) {
1463 debug("Requesting no-more-sessions@openssh.com");
1464 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1465 packet_put_cstring("no-more-sessions@openssh.com");
1470 /* Execute a local command */
1471 if (options.local_command != NULL &&
1472 options.permit_local_command)
1473 ssh_local_cmd(options.local_command);
1476 * If requested and we are not interested in replies to remote
1477 * forwarding requests, then let ssh continue in the background.
1479 if (fork_after_authentication_flag) {
1480 if (options.exit_on_forward_failure &&
1481 options.num_remote_forwards > 0) {
1482 debug("deferring postauth fork until remote forward "
1483 "confirmation received");
1488 if (options.use_roaming)
1491 return client_loop(tty_flag, tty_flag ?
1492 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1496 load_public_identity_files(void)
1498 char *filename, *cp, thishost[NI_MAXHOST];
1499 char *pwdir = NULL, *pwname = NULL;
1504 char *identity_files[SSH_MAX_IDENTITY_FILES];
1505 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1506 #ifdef ENABLE_PKCS11
1512 bzero(identity_files, sizeof(identity_files));
1513 bzero(identity_keys, sizeof(identity_keys));
1515 #ifdef ENABLE_PKCS11
1516 if (options.pkcs11_provider != NULL &&
1517 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1518 (pkcs11_init(!options.batch_mode) == 0) &&
1519 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1521 for (i = 0; i < nkeys; i++) {
1522 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1526 identity_keys[n_ids] = keys[i];
1527 identity_files[n_ids] =
1528 xstrdup(options.pkcs11_provider); /* XXX */
1533 #endif /* ENABLE_PKCS11 */
1534 if ((pw = getpwuid(original_real_uid)) == NULL)
1535 fatal("load_public_identity_files: getpwuid failed");
1536 pwname = xstrdup(pw->pw_name);
1537 pwdir = xstrdup(pw->pw_dir);
1538 if (gethostname(thishost, sizeof(thishost)) == -1)
1539 fatal("load_public_identity_files: gethostname: %s",
1541 for (i = 0; i < options.num_identity_files; i++) {
1542 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1543 xfree(options.identity_files[i]);
1546 cp = tilde_expand_filename(options.identity_files[i],
1548 filename = percent_expand(cp, "d", pwdir,
1549 "u", pwname, "l", thishost, "h", host,
1550 "r", options.user, (char *)NULL);
1552 public = key_load_public(filename, NULL);
1553 debug("identity file %s type %d", filename,
1554 public ? public->type : -1);
1555 xfree(options.identity_files[i]);
1556 identity_files[n_ids] = filename;
1557 identity_keys[n_ids] = public;
1559 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1562 /* Try to add the certificate variant too */
1563 xasprintf(&cp, "%s-cert", filename);
1564 public = key_load_public(cp, NULL);
1565 debug("identity file %s type %d", cp,
1566 public ? public->type : -1);
1567 if (public == NULL) {
1571 if (!key_is_cert(public)) {
1572 debug("%s: key %s type %s is not a certificate",
1573 __func__, cp, key_type(public));
1578 identity_keys[n_ids] = public;
1579 /* point to the original path, most likely the private key */
1580 identity_files[n_ids] = xstrdup(filename);
1583 options.num_identity_files = n_ids;
1584 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1585 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1587 bzero(pwname, strlen(pwname));
1589 bzero(pwdir, strlen(pwdir));
1594 main_sigchld_handler(int sig)
1596 int save_errno = errno;
1600 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1601 (pid < 0 && errno == EINTR))
1604 signal(sig, main_sigchld_handler);