1 /* $OpenBSD: ssh.c,v 1.364 2011/08/02 23:15:03 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;
381 fatal("Invalid multiplex command.");
383 case 'P': /* deprecated */
384 options.use_privileged_port = 0;
387 options.forward_agent = 0;
390 options.forward_agent = 1;
393 options.gss_deleg_creds = 0;
396 options.gss_authentication = 1;
397 options.gss_deleg_creds = 1;
400 if (stat(optarg, &st) < 0) {
401 fprintf(stderr, "Warning: Identity file %s "
402 "not accessible: %s.\n", optarg,
406 if (options.num_identity_files >=
407 SSH_MAX_IDENTITY_FILES)
408 fatal("Too many identity files specified "
409 "(max %d)", SSH_MAX_IDENTITY_FILES);
410 options.identity_files[options.num_identity_files++] =
415 options.pkcs11_provider = xstrdup(optarg);
417 fprintf(stderr, "no support for PKCS#11.\n");
421 if (options.request_tty == REQUEST_TTY_YES)
422 options.request_tty = REQUEST_TTY_FORCE;
424 options.request_tty = REQUEST_TTY_YES;
427 if (debug_flag == 0) {
429 options.log_level = SYSLOG_LEVEL_DEBUG1;
431 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
437 fprintf(stderr, "%s, %s\n",
438 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
443 if (options.tun_open == -1)
444 options.tun_open = SSH_TUNMODE_DEFAULT;
445 options.tun_local = a2tun(optarg, &options.tun_remote);
446 if (options.tun_local == SSH_TUNID_ERR) {
448 "Bad tun device '%s'\n", optarg);
453 if (stdio_forward_host != NULL)
454 fatal("stdio forward already specified");
455 if (muxclient_command != 0)
456 fatal("Cannot specify stdio forward with -O");
457 if (parse_forward(&fwd, optarg, 1, 0)) {
458 stdio_forward_host = fwd.listen_host;
459 stdio_forward_port = fwd.listen_port;
460 xfree(fwd.connect_host);
463 "Bad stdio forwarding specification '%s'\n",
467 options.request_tty = REQUEST_TTY_NO;
469 options.clear_forwardings = 1;
470 options.exit_on_forward_failure = 1;
473 options.log_level = SYSLOG_LEVEL_QUIET;
476 if (optarg[0] == '^' && optarg[2] == 0 &&
477 (u_char) optarg[1] >= 64 &&
478 (u_char) optarg[1] < 128)
479 options.escape_char = (u_char) optarg[1] & 31;
480 else if (strlen(optarg) == 1)
481 options.escape_char = (u_char) optarg[0];
482 else if (strcmp(optarg, "none") == 0)
483 options.escape_char = SSH_ESCAPECHAR_NONE;
485 fprintf(stderr, "Bad escape character '%s'.\n",
491 if (ciphers_valid(optarg)) {
493 options.ciphers = xstrdup(optarg);
494 options.cipher = SSH_CIPHER_INVALID;
497 options.cipher = cipher_number(optarg);
498 if (options.cipher == -1) {
500 "Unknown cipher type '%s'\n",
504 if (options.cipher == SSH_CIPHER_3DES)
505 options.ciphers = "3des-cbc";
506 else if (options.cipher == SSH_CIPHER_BLOWFISH)
507 options.ciphers = "blowfish-cbc";
509 options.ciphers = (char *)-1;
513 if (mac_valid(optarg))
514 options.macs = xstrdup(optarg);
516 fprintf(stderr, "Unknown mac type '%s'\n",
522 if (options.control_master == SSHCTL_MASTER_YES)
523 options.control_master = SSHCTL_MASTER_ASK;
525 options.control_master = SSHCTL_MASTER_YES;
528 options.port = a2port(optarg);
529 if (options.port <= 0) {
530 fprintf(stderr, "Bad port '%s'\n", optarg);
535 options.user = optarg;
539 if (parse_forward(&fwd, optarg, 0, 0))
540 add_local_forward(&options, &fwd);
543 "Bad local forwarding specification '%s'\n",
550 if (parse_forward(&fwd, optarg, 0, 1)) {
551 add_remote_forward(&options, &fwd);
554 "Bad remote forwarding specification "
561 if (parse_forward(&fwd, optarg, 1, 0)) {
562 add_local_forward(&options, &fwd);
565 "Bad dynamic forwarding specification "
572 options.compression = 1;
576 options.request_tty = REQUEST_TTY_NO;
579 options.request_tty = REQUEST_TTY_NO;
583 line = xstrdup(optarg);
584 if (process_config_line(&options, host ? host : "",
585 line, "command-line", 0, &dummy) != 0)
593 if (options.control_path != NULL)
594 free(options.control_path);
595 options.control_path = xstrdup(optarg);
598 options.bind_address = optarg;
611 if (ac > 0 && !host) {
612 if (strrchr(*av, '@')) {
614 cp = strrchr(p, '@');
615 if (cp == NULL || cp == p)
623 optind = optreset = 1;
629 /* Check that we got a host name. */
633 OpenSSL_add_all_algorithms();
634 ERR_load_crypto_strings();
636 /* Initialize the command to execute on remote host. */
637 buffer_init(&command);
639 if (options.request_tty == REQUEST_TTY_YES ||
640 options.request_tty == REQUEST_TTY_FORCE)
644 * Save the command to execute on the remote host in a buffer. There
645 * is no limit on the length of the command, except by the maximum
646 * packet size. Also sets the tty flag if there is no command.
649 /* No command specified - execute shell on a tty. */
650 tty_flag = options.request_tty != REQUEST_TTY_NO;
651 if (subsystem_flag) {
653 "You must specify a subsystem to invoke.\n");
657 /* A command has been specified. Store it into the buffer. */
658 for (i = 0; i < ac; i++) {
660 buffer_append(&command, " ", 1);
661 buffer_append(&command, av[i], strlen(av[i]));
665 /* Cannot fork to background if no command. */
666 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
668 fatal("Cannot fork into background without a command "
671 /* Allocate a tty by default if no command specified. */
672 if (buffer_len(&command) == 0)
673 tty_flag = options.request_tty != REQUEST_TTY_NO;
676 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
678 /* Do not allocate a tty if stdin is not a tty. */
679 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
680 options.request_tty != REQUEST_TTY_FORCE) {
681 if (tty_flag && options.log_level != SYSLOG_LEVEL_QUIET)
682 logit("Pseudo-terminal will not be allocated because "
683 "stdin is not a terminal.");
688 * Initialize "log" output. Since we are the client all output
689 * actually goes to stderr.
692 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
693 SYSLOG_FACILITY_USER, !use_syslog);
696 * Read per-user configuration file. Ignore the system wide config
697 * file if the user specifies a config file on the command line.
699 if (config != NULL) {
700 if (!read_config_file(config, host, &options, 0))
701 fatal("Can't open user config file %.100s: "
702 "%.100s", config, strerror(errno));
704 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
705 _PATH_SSH_USER_CONFFILE);
706 if (r > 0 && (size_t)r < sizeof(buf))
707 (void)read_config_file(buf, host, &options, 1);
709 /* Read systemwide configuration file after user config. */
710 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
714 /* Fill configuration defaults. */
715 fill_default_options(&options);
717 channel_set_af(options.address_family);
720 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
724 if (options.user == NULL)
725 options.user = xstrdup(pw->pw_name);
727 /* Get default port if port has not been set. */
728 if (options.port == 0) {
729 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
730 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
733 /* preserve host name given on command line for %n expansion */
735 if (options.hostname != NULL) {
736 host = percent_expand(options.hostname,
737 "h", host, (char *)NULL);
740 if (gethostname(thishost, sizeof(thishost)) == -1)
741 fatal("gethostname: %s", strerror(errno));
742 strlcpy(shorthost, thishost, sizeof(shorthost));
743 shorthost[strcspn(thishost, ".")] = '\0';
744 snprintf(portstr, sizeof(portstr), "%d", options.port);
746 if (options.local_command != NULL) {
747 debug3("expanding LocalCommand: %s", options.local_command);
748 cp = options.local_command;
749 options.local_command = percent_expand(cp, "d", pw->pw_dir,
750 "h", host, "l", thishost, "n", host_arg, "r", options.user,
751 "p", portstr, "u", pw->pw_name, "L", shorthost,
753 debug3("expanded LocalCommand: %s", options.local_command);
757 /* force lowercase for hostkey matching */
758 if (options.host_key_alias != NULL) {
759 for (p = options.host_key_alias; *p; p++)
761 *p = (char)tolower(*p);
764 if (options.proxy_command != NULL &&
765 strcmp(options.proxy_command, "none") == 0) {
766 xfree(options.proxy_command);
767 options.proxy_command = NULL;
769 if (options.control_path != NULL &&
770 strcmp(options.control_path, "none") == 0) {
771 xfree(options.control_path);
772 options.control_path = NULL;
775 if (options.control_path != NULL) {
776 cp = tilde_expand_filename(options.control_path,
778 xfree(options.control_path);
779 options.control_path = percent_expand(cp, "h", host,
780 "l", thishost, "n", host_arg, "r", options.user,
781 "p", portstr, "u", pw->pw_name, "L", shorthost,
785 if (muxclient_command != 0 && options.control_path == NULL)
786 fatal("No ControlPath specified for \"-O\" command");
787 if (options.control_path != NULL)
788 muxclient(options.control_path);
790 timeout_ms = options.connection_timeout * 1000;
792 /* Open a connection to the remote host. */
793 if (ssh_connect(host, &hostaddr, options.port,
794 options.address_family, options.connection_attempts, &timeout_ms,
795 options.tcp_keep_alive,
797 options.use_privileged_port,
799 original_effective_uid == 0 && options.use_privileged_port,
801 options.proxy_command) != 0)
805 debug3("timeout: %d ms remain after connect", timeout_ms);
808 * If we successfully made the connection, load the host private key
809 * in case we will need it later for combined rsa-rhosts
810 * authentication. This must be done before releasing extra
811 * privileges, because the file is only readable by root.
812 * If we cannot access the private keys, load the public keys
813 * instead and try to execute the ssh-keysign helper instead.
815 sensitive_data.nkeys = 0;
816 sensitive_data.keys = NULL;
817 sensitive_data.external_keysign = 0;
818 if (options.rhosts_rsa_authentication ||
819 options.hostbased_authentication) {
820 sensitive_data.nkeys = 7;
821 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
823 for (i = 0; i < sensitive_data.nkeys; i++)
824 sensitive_data.keys[i] = NULL;
827 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
828 _PATH_HOST_KEY_FILE, "", NULL, NULL);
829 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
830 _PATH_HOST_DSA_KEY_FILE, "", NULL);
831 #ifdef OPENSSL_HAS_ECC
832 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
833 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
835 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
836 _PATH_HOST_RSA_KEY_FILE, "", NULL);
837 sensitive_data.keys[4] = key_load_private_type(KEY_DSA,
838 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
839 #ifdef OPENSSL_HAS_ECC
840 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
841 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
843 sensitive_data.keys[6] = key_load_private_type(KEY_RSA,
844 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
847 if (options.hostbased_authentication == 1 &&
848 sensitive_data.keys[0] == NULL &&
849 sensitive_data.keys[4] == NULL &&
850 sensitive_data.keys[5] == NULL &&
851 sensitive_data.keys[6] == NULL) {
852 sensitive_data.keys[1] = key_load_cert(
853 _PATH_HOST_DSA_KEY_FILE);
854 #ifdef OPENSSL_HAS_ECC
855 sensitive_data.keys[2] = key_load_cert(
856 _PATH_HOST_ECDSA_KEY_FILE);
858 sensitive_data.keys[3] = key_load_cert(
859 _PATH_HOST_RSA_KEY_FILE);
860 sensitive_data.keys[4] = key_load_public(
861 _PATH_HOST_DSA_KEY_FILE, NULL);
862 #ifdef OPENSSL_HAS_ECC
863 sensitive_data.keys[5] = key_load_public(
864 _PATH_HOST_ECDSA_KEY_FILE, NULL);
866 sensitive_data.keys[6] = key_load_public(
867 _PATH_HOST_RSA_KEY_FILE, NULL);
868 sensitive_data.external_keysign = 1;
872 * Get rid of any extra privileges that we may have. We will no
873 * longer need them. Also, extra privileges could make it very hard
874 * to read identity files and other non-world-readable files from the
875 * user's home directory if it happens to be on a NFS volume where
876 * root is mapped to nobody.
878 if (original_effective_uid == 0) {
880 permanently_set_uid(pw);
884 * Now that we are back to our own permissions, create ~/.ssh
885 * directory if it doesn't already exist.
887 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
888 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
889 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
891 ssh_selinux_setfscreatecon(buf);
893 if (mkdir(buf, 0700) < 0)
894 error("Could not create directory '%.200s'.", buf);
896 ssh_selinux_setfscreatecon(NULL);
899 /* load options.identity_files */
900 load_public_identity_files();
902 /* Expand ~ in known host file names. */
903 tilde_expand_paths(options.system_hostfiles,
904 options.num_system_hostfiles);
905 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
907 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
908 signal(SIGCHLD, main_sigchld_handler);
910 /* Log into the remote system. Never returns if the login fails. */
911 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
912 options.port, pw, timeout_ms);
914 if (packet_connection_is_on_socket()) {
915 verbose("Authenticated to %s ([%s]:%d).", host,
916 get_remote_ipaddr(), get_remote_port());
918 verbose("Authenticated to %s (via proxy).", host);
921 /* We no longer need the private host keys. Clear them now. */
922 if (sensitive_data.nkeys != 0) {
923 for (i = 0; i < sensitive_data.nkeys; i++) {
924 if (sensitive_data.keys[i] != NULL) {
925 /* Destroys contents safely */
926 debug3("clear hostkey %d", i);
927 key_free(sensitive_data.keys[i]);
928 sensitive_data.keys[i] = NULL;
931 xfree(sensitive_data.keys);
933 for (i = 0; i < options.num_identity_files; i++) {
934 if (options.identity_files[i]) {
935 xfree(options.identity_files[i]);
936 options.identity_files[i] = NULL;
938 if (options.identity_keys[i]) {
939 key_free(options.identity_keys[i]);
940 options.identity_keys[i] = NULL;
944 exit_status = compat20 ? ssh_session2() : ssh_session();
947 if (options.control_path != NULL && muxserver_sock != -1)
948 unlink(options.control_path);
950 /* Kill ProxyCommand if it is running. */
951 ssh_kill_proxy_command();
957 control_persist_detach(void)
962 debug("%s: backgrounding master process", __func__);
965 * master (current process) into the background, and make the
966 * foreground process a client of the backgrounded master.
968 switch ((pid = fork())) {
970 fatal("%s: fork: %s", __func__, strerror(errno));
972 /* Child: master process continues mainloop */
975 /* Parent: set up mux slave to connect to backgrounded master */
976 debug2("%s: background process is %ld", __func__, (long)pid);
977 stdin_null_flag = ostdin_null_flag;
978 options.request_tty = orequest_tty;
979 tty_flag = otty_flag;
980 close(muxserver_sock);
982 options.control_master = SSHCTL_MASTER_NO;
983 muxclient(options.control_path);
984 /* muxclient() doesn't return on success. */
985 fatal("Failed to connect to new control master");
987 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
988 error("%s: open(\"/dev/null\"): %s", __func__,
991 if (dup2(devnull, STDIN_FILENO) == -1 ||
992 dup2(devnull, STDOUT_FILENO) == -1)
993 error("%s: dup2: %s", __func__, strerror(errno));
994 if (devnull > STDERR_FILENO)
997 setproctitle("%s [mux]", options.control_path);
1000 /* Do fork() after authentication. Used by "ssh -f" */
1004 if (need_controlpersist_detach)
1005 control_persist_detach();
1006 debug("forking to background");
1007 fork_after_authentication_flag = 0;
1008 if (daemon(1, 1) < 0)
1009 fatal("daemon() failed: %.200s", strerror(errno));
1012 /* Callback for remote forward global requests */
1014 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1016 Forward *rfwd = (Forward *)ctxt;
1018 /* XXX verbose() on failure? */
1019 debug("remote forward %s for: listen %d, connect %s:%d",
1020 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1021 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1022 if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
1023 rfwd->allocated_port = packet_get_int();
1024 logit("Allocated port %u for remote forward to %s:%d",
1025 rfwd->allocated_port,
1026 rfwd->connect_host, rfwd->connect_port);
1029 if (type == SSH2_MSG_REQUEST_FAILURE) {
1030 if (options.exit_on_forward_failure)
1031 fatal("Error: remote port forwarding failed for "
1032 "listen port %d", rfwd->listen_port);
1034 logit("Warning: remote port forwarding failed for "
1035 "listen port %d", rfwd->listen_port);
1037 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1038 debug("All remote forwarding requests processed");
1039 if (fork_after_authentication_flag)
1045 client_cleanup_stdio_fwd(int id, void *arg)
1047 debug("stdio forwarding: done");
1052 client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect)
1057 debug3("client_setup_stdio_fwd %s:%d", host_to_connect,
1060 in = dup(STDIN_FILENO);
1061 out = dup(STDOUT_FILENO);
1062 if (in < 0 || out < 0)
1063 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1065 if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect,
1068 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1073 ssh_init_forwarding(void)
1078 if (stdio_forward_host != NULL) {
1080 fatal("stdio forwarding require Protocol 2");
1082 if (!client_setup_stdio_fwd(stdio_forward_host,
1083 stdio_forward_port))
1084 fatal("Failed to connect in stdio forward mode.");
1087 /* Initiate local TCP/IP port forwardings. */
1088 for (i = 0; i < options.num_local_forwards; i++) {
1089 debug("Local connections to %.200s:%d forwarded to remote "
1090 "address %.200s:%d",
1091 (options.local_forwards[i].listen_host == NULL) ?
1092 (options.gateway_ports ? "*" : "LOCALHOST") :
1093 options.local_forwards[i].listen_host,
1094 options.local_forwards[i].listen_port,
1095 options.local_forwards[i].connect_host,
1096 options.local_forwards[i].connect_port);
1097 success += channel_setup_local_fwd_listener(
1098 options.local_forwards[i].listen_host,
1099 options.local_forwards[i].listen_port,
1100 options.local_forwards[i].connect_host,
1101 options.local_forwards[i].connect_port,
1102 options.gateway_ports);
1104 if (i > 0 && success != i && options.exit_on_forward_failure)
1105 fatal("Could not request local forwarding.");
1106 if (i > 0 && success == 0)
1107 error("Could not request local forwarding.");
1109 /* Initiate remote TCP/IP port forwardings. */
1110 for (i = 0; i < options.num_remote_forwards; i++) {
1111 debug("Remote connections from %.200s:%d forwarded to "
1112 "local address %.200s:%d",
1113 (options.remote_forwards[i].listen_host == NULL) ?
1114 "LOCALHOST" : options.remote_forwards[i].listen_host,
1115 options.remote_forwards[i].listen_port,
1116 options.remote_forwards[i].connect_host,
1117 options.remote_forwards[i].connect_port);
1118 if (channel_request_remote_forwarding(
1119 options.remote_forwards[i].listen_host,
1120 options.remote_forwards[i].listen_port,
1121 options.remote_forwards[i].connect_host,
1122 options.remote_forwards[i].connect_port) < 0) {
1123 if (options.exit_on_forward_failure)
1124 fatal("Could not request remote forwarding.");
1126 logit("Warning: Could not request remote "
1129 client_register_global_confirm(ssh_confirm_remote_forward,
1130 &options.remote_forwards[i]);
1133 /* Initiate tunnel forwarding. */
1134 if (options.tun_open != SSH_TUNMODE_NO) {
1135 if (client_request_tun_fwd(options.tun_open,
1136 options.tun_local, options.tun_remote) == -1) {
1137 if (options.exit_on_forward_failure)
1138 fatal("Could not request tunnel forwarding.");
1140 error("Could not request tunnel forwarding.");
1146 check_agent_present(void)
1148 if (options.forward_agent) {
1149 /* Clear agent forwarding if we don't have an agent. */
1150 if (!ssh_agent_present())
1151 options.forward_agent = 0;
1159 int interactive = 0;
1163 const char *display;
1165 /* Enable compression if requested. */
1166 if (options.compression) {
1167 debug("Requesting compression at level %d.",
1168 options.compression_level);
1170 if (options.compression_level < 1 ||
1171 options.compression_level > 9)
1172 fatal("Compression level must be from 1 (fast) to "
1175 /* Send the request. */
1176 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1177 packet_put_int(options.compression_level);
1179 packet_write_wait();
1180 type = packet_read();
1181 if (type == SSH_SMSG_SUCCESS)
1182 packet_start_compression(options.compression_level);
1183 else if (type == SSH_SMSG_FAILURE)
1184 logit("Warning: Remote host refused compression.");
1186 packet_disconnect("Protocol error waiting for "
1187 "compression response.");
1189 /* Allocate a pseudo tty if appropriate. */
1191 debug("Requesting pty.");
1193 /* Start the packet. */
1194 packet_start(SSH_CMSG_REQUEST_PTY);
1196 /* Store TERM in the packet. There is no limit on the
1197 length of the string. */
1198 cp = getenv("TERM");
1201 packet_put_cstring(cp);
1203 /* Store window size in the packet. */
1204 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1205 memset(&ws, 0, sizeof(ws));
1206 packet_put_int((u_int)ws.ws_row);
1207 packet_put_int((u_int)ws.ws_col);
1208 packet_put_int((u_int)ws.ws_xpixel);
1209 packet_put_int((u_int)ws.ws_ypixel);
1211 /* Store tty modes in the packet. */
1212 tty_make_modes(fileno(stdin), NULL);
1214 /* Send the packet, and wait for it to leave. */
1216 packet_write_wait();
1218 /* Read response from the server. */
1219 type = packet_read();
1220 if (type == SSH_SMSG_SUCCESS) {
1223 } else if (type == SSH_SMSG_FAILURE)
1224 logit("Warning: Remote host failed or refused to "
1225 "allocate a pseudo tty.");
1227 packet_disconnect("Protocol error waiting for pty "
1228 "request response.");
1230 /* Request X11 forwarding if enabled and DISPLAY is set. */
1231 display = getenv("DISPLAY");
1232 if (options.forward_x11 && display != NULL) {
1234 /* Get reasonable local authentication information. */
1235 client_x11_get_proto(display, options.xauth_location,
1236 options.forward_x11_trusted,
1237 options.forward_x11_timeout,
1239 /* Request forwarding with authentication spoofing. */
1240 debug("Requesting X11 forwarding with authentication "
1242 x11_request_forwarding_with_spoofing(0, display, proto,
1244 /* Read response from the server. */
1245 type = packet_read();
1246 if (type == SSH_SMSG_SUCCESS) {
1248 } else if (type == SSH_SMSG_FAILURE) {
1249 logit("Warning: Remote host denied X11 forwarding.");
1251 packet_disconnect("Protocol error waiting for X11 "
1255 /* Tell the packet module whether this is an interactive session. */
1256 packet_set_interactive(interactive,
1257 options.ip_qos_interactive, options.ip_qos_bulk);
1259 /* Request authentication agent forwarding if appropriate. */
1260 check_agent_present();
1262 if (options.forward_agent) {
1263 debug("Requesting authentication agent forwarding.");
1264 auth_request_forwarding();
1266 /* Read response from the server. */
1267 type = packet_read();
1269 if (type != SSH_SMSG_SUCCESS)
1270 logit("Warning: Remote host denied authentication agent forwarding.");
1273 /* Initiate port forwardings. */
1274 ssh_init_forwarding();
1276 /* Execute a local command */
1277 if (options.local_command != NULL &&
1278 options.permit_local_command)
1279 ssh_local_cmd(options.local_command);
1282 * If requested and we are not interested in replies to remote
1283 * forwarding requests, then let ssh continue in the background.
1285 if (fork_after_authentication_flag) {
1286 if (options.exit_on_forward_failure &&
1287 options.num_remote_forwards > 0) {
1288 debug("deferring postauth fork until remote forward "
1289 "confirmation received");
1295 * If a command was specified on the command line, execute the
1296 * command now. Otherwise request the server to start a shell.
1298 if (buffer_len(&command) > 0) {
1299 int len = buffer_len(&command);
1302 debug("Sending command: %.*s", len,
1303 (u_char *)buffer_ptr(&command));
1304 packet_start(SSH_CMSG_EXEC_CMD);
1305 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1307 packet_write_wait();
1309 debug("Requesting shell.");
1310 packet_start(SSH_CMSG_EXEC_SHELL);
1312 packet_write_wait();
1315 /* Enter the interactive session. */
1316 return client_loop(have_tty, tty_flag ?
1317 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1320 /* request pty/x11/agent/tcpfwd/shell for channel */
1322 ssh_session2_setup(int id, int success, void *arg)
1324 extern char **environ;
1325 const char *display;
1326 int interactive = tty_flag;
1329 return; /* No need for error message, channels code sens one */
1331 display = getenv("DISPLAY");
1332 if (options.forward_x11 && display != NULL) {
1334 /* Get reasonable local authentication information. */
1335 client_x11_get_proto(display, options.xauth_location,
1336 options.forward_x11_trusted,
1337 options.forward_x11_timeout, &proto, &data);
1338 /* Request forwarding with authentication spoofing. */
1339 debug("Requesting X11 forwarding with authentication "
1341 x11_request_forwarding_with_spoofing(id, display, proto,
1343 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1344 /* XXX exit_on_forward_failure */
1348 check_agent_present();
1349 if (options.forward_agent) {
1350 debug("Requesting authentication agent forwarding.");
1351 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1355 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1356 NULL, fileno(stdin), &command, environ);
1359 /* open new channel for a session */
1361 ssh_session2_open(void)
1364 int window, packetmax, in, out, err;
1366 if (stdin_null_flag) {
1367 in = open(_PATH_DEVNULL, O_RDONLY);
1369 in = dup(STDIN_FILENO);
1371 out = dup(STDOUT_FILENO);
1372 err = dup(STDERR_FILENO);
1374 if (in < 0 || out < 0 || err < 0)
1375 fatal("dup() in/out/err failed");
1377 /* enable nonblocking unless tty */
1385 window = CHAN_SES_WINDOW_DEFAULT;
1386 packetmax = CHAN_SES_PACKET_DEFAULT;
1392 "session", SSH_CHANNEL_OPENING, in, out, err,
1393 window, packetmax, CHAN_EXTENDED_WRITE,
1394 "client-session", /*nonblock*/0);
1396 debug3("ssh_session2_open: channel_new: %d", c->self);
1398 channel_send_open(c->self);
1400 channel_register_open_confirm(c->self,
1401 ssh_session2_setup, NULL);
1411 /* XXX should be pre-session */
1412 ssh_init_forwarding();
1414 /* Start listening for multiplex clients */
1418 * If we are in control persist mode, then prepare to background
1419 * ourselves and have a foreground client attach as a control
1420 * slave. NB. we must save copies of the flags that we override for
1421 * the backgrounding, since we defer attachment of the slave until
1422 * after the connection is fully established (in particular,
1423 * async rfwd replies have been received for ExitOnForwardFailure).
1425 if (options.control_persist && muxserver_sock != -1) {
1426 ostdin_null_flag = stdin_null_flag;
1427 ono_shell_flag = no_shell_flag;
1428 orequest_tty = options.request_tty;
1429 otty_flag = tty_flag;
1430 stdin_null_flag = 1;
1433 if (!fork_after_authentication_flag)
1434 need_controlpersist_detach = 1;
1435 fork_after_authentication_flag = 1;
1438 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1439 id = ssh_session2_open();
1441 /* If we don't expect to open a new session, then disallow it */
1442 if (options.control_master == SSHCTL_MASTER_NO &&
1443 (datafellows & SSH_NEW_OPENSSH)) {
1444 debug("Requesting no-more-sessions@openssh.com");
1445 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1446 packet_put_cstring("no-more-sessions@openssh.com");
1451 /* Execute a local command */
1452 if (options.local_command != NULL &&
1453 options.permit_local_command)
1454 ssh_local_cmd(options.local_command);
1457 * If requested and we are not interested in replies to remote
1458 * forwarding requests, then let ssh continue in the background.
1460 if (fork_after_authentication_flag) {
1461 if (options.exit_on_forward_failure &&
1462 options.num_remote_forwards > 0) {
1463 debug("deferring postauth fork until remote forward "
1464 "confirmation received");
1469 if (options.use_roaming)
1472 return client_loop(tty_flag, tty_flag ?
1473 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1477 load_public_identity_files(void)
1479 char *filename, *cp, thishost[NI_MAXHOST], *fp;
1480 char *pwdir = NULL, *pwname = NULL;
1485 char *identity_files[SSH_MAX_IDENTITY_FILES];
1486 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1487 #ifdef ENABLE_PKCS11
1493 bzero(identity_files, sizeof(identity_files));
1494 bzero(identity_keys, sizeof(identity_keys));
1496 #ifdef ENABLE_PKCS11
1497 if (options.pkcs11_provider != NULL &&
1498 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1499 (pkcs11_init(!options.batch_mode) == 0) &&
1500 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1502 for (i = 0; i < nkeys; i++) {
1503 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1507 identity_keys[n_ids] = keys[i];
1508 identity_files[n_ids] =
1509 xstrdup(options.pkcs11_provider); /* XXX */
1514 #endif /* ENABLE_PKCS11 */
1515 if ((pw = getpwuid(original_real_uid)) == NULL)
1516 fatal("load_public_identity_files: getpwuid failed");
1517 pwname = xstrdup(pw->pw_name);
1518 pwdir = xstrdup(pw->pw_dir);
1519 if (gethostname(thishost, sizeof(thishost)) == -1)
1520 fatal("load_public_identity_files: gethostname: %s",
1522 for (i = 0; i < options.num_identity_files; i++) {
1523 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1524 xfree(options.identity_files[i]);
1527 cp = tilde_expand_filename(options.identity_files[i],
1529 filename = percent_expand(cp, "d", pwdir,
1530 "u", pwname, "l", thishost, "h", host,
1531 "r", options.user, (char *)NULL);
1533 public = key_load_public(filename, NULL);
1534 debug("identity file %s type %d", filename,
1535 public ? public->type : -1);
1536 if (public && blacklisted_key(public, &fp) == 1) {
1537 if (options.use_blacklisted_keys)
1538 logit("Public key %s blacklisted (see "
1539 "ssh-vulnkey(1)); continuing anyway", fp);
1541 logit("Public key %s blacklisted (see "
1542 "ssh-vulnkey(1)); refusing to send it",
1545 if (!options.use_blacklisted_keys) {
1552 xfree(options.identity_files[i]);
1553 identity_files[n_ids] = filename;
1554 identity_keys[n_ids] = public;
1556 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1559 /* Try to add the certificate variant too */
1560 xasprintf(&cp, "%s-cert", filename);
1561 public = key_load_public(cp, NULL);
1562 debug("identity file %s type %d", cp,
1563 public ? public->type : -1);
1564 if (public == NULL) {
1568 if (!key_is_cert(public)) {
1569 debug("%s: key %s type %s is not a certificate",
1570 __func__, cp, key_type(public));
1575 identity_keys[n_ids] = public;
1576 /* point to the original path, most likely the private key */
1577 identity_files[n_ids] = xstrdup(filename);
1580 options.num_identity_files = n_ids;
1581 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1582 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1584 bzero(pwname, strlen(pwname));
1586 bzero(pwdir, strlen(pwdir));
1591 main_sigchld_handler(int sig)
1593 int save_errno = errno;
1597 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1598 (pid < 0 && errno == EINTR))
1601 signal(sig, main_sigchld_handler);