1 /* $OpenBSD: ssh.c,v 1.346 2010/08/12 21:49:44 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/param.h>
53 #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 /* Flag indicating whether debug mode is on. May be set on the command line. */
117 /* Flag indicating whether a tty should be allocated */
120 int force_tty_flag = 0;
122 /* don't exec a shell */
123 int no_shell_flag = 0;
126 * Flag indicating that nothing should be read from stdin. This can be set
127 * on the command line.
129 int stdin_null_flag = 0;
132 * Flag indicating that the current process should be backgrounded and
133 * a new slave launched in the foreground for ControlPersist.
135 int need_controlpersist_detach = 0;
137 /* Copies of flags for ControlPersist foreground slave */
138 int ostdin_null_flag, ono_shell_flag, ono_tty_flag, otty_flag;
141 * Flag indicating that ssh should fork after authentication. This is useful
142 * so that the passphrase can be entered manually, and then ssh goes to the
145 int fork_after_authentication_flag = 0;
147 /* forward stdio to remote host and port */
148 char *stdio_forward_host = NULL;
149 int stdio_forward_port = 0;
152 * General data structure for command line options and options configurable
153 * in configuration files. See readconf.h.
157 /* optional user configfile */
161 * Name of the host we are connecting to. This is the name given on the
162 * command line, or the HostName specified for the user-supplied name in a
163 * configuration file.
167 /* socket address the host resolves to */
168 struct sockaddr_storage hostaddr;
170 /* Private host keys. */
171 Sensitive sensitive_data;
173 /* Original real UID. */
174 uid_t original_real_uid;
175 uid_t original_effective_uid;
177 /* command to be executed */
180 /* Should we execute a command or invoke a subsystem? */
181 int subsystem_flag = 0;
183 /* # of replies received for global requests */
184 static int remote_forward_confirms_received = 0;
186 /* pid of proxycommand child process */
187 pid_t proxy_command_pid = 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);
215 /* from muxclient.c */
216 void muxclient(const char *);
217 void muxserver_listen(void);
220 * Main program for the ssh client.
223 main(int ac, char **av)
225 int i, r, opt, exit_status, use_syslog;
226 char *p, *cp, *line, *argv0, buf[MAXPATHLEN];
229 int dummy, timeout_ms;
230 extern int optind, optreset;
235 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
238 __progname = ssh_get_progname(av[0]);
242 * Discard other fds that are hanging around. These can cause problem
243 * with backgrounded ssh processes started by ControlPersist.
245 closefrom(STDERR_FILENO + 1);
248 * Save the original real uid. It will be needed later (uid-swapping
249 * may clobber the real uid).
251 original_real_uid = getuid();
252 original_effective_uid = geteuid();
255 * Use uid-swapping to give up root privileges for the duration of
256 * option processing. We will re-instantiate the rights when we are
257 * ready to create the privileged port, and will permanently drop
258 * them when the port has been created (actually, when the connection
259 * has been made, as we may need to create the port several times).
263 #ifdef HAVE_SETRLIMIT
264 /* If we are installed setuid root be careful to not drop core. */
265 if (original_real_uid != original_effective_uid) {
267 rlim.rlim_cur = rlim.rlim_max = 0;
268 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
269 fatal("setrlimit failed: %.100s", strerror(errno));
273 pw = getpwuid(original_real_uid);
275 logit("You don't exist, go away!");
278 /* Take a copy of the returned structure. */
282 * Set our umask to something reasonable, as some files are created
283 * with the default umask. This will make them world-readable but
284 * writable only by the owner, which is ok for all files for which we
285 * don't set the modes explicitly.
290 * Initialize option structure to indicate that no values have been
293 initialize_options(&options);
295 /* Parse command-line arguments. */
301 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
302 "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
305 options.protocol = SSH_PROTO_1;
308 options.protocol = SSH_PROTO_2;
311 options.address_family = AF_INET;
314 options.address_family = AF_INET6;
320 fork_after_authentication_flag = 1;
324 options.forward_x11 = 0;
327 options.forward_x11 = 1;
333 options.forward_x11 = 1;
334 options.forward_x11_trusted = 1;
337 options.gateway_ports = 1;
340 if (stdio_forward_host != NULL)
341 fatal("Cannot specify multiplexing "
343 else if (muxclient_command != 0)
344 fatal("Multiplexing command already specified");
345 if (strcmp(optarg, "check") == 0)
346 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
347 else if (strcmp(optarg, "forward") == 0)
348 muxclient_command = SSHMUX_COMMAND_FORWARD;
349 else if (strcmp(optarg, "exit") == 0)
350 muxclient_command = SSHMUX_COMMAND_TERMINATE;
352 fatal("Invalid multiplex command.");
354 case 'P': /* deprecated */
355 options.use_privileged_port = 0;
358 options.forward_agent = 0;
361 options.forward_agent = 1;
364 options.gss_deleg_creds = 0;
367 options.gss_authentication = 1;
368 options.gss_deleg_creds = 1;
371 if (stat(optarg, &st) < 0) {
372 fprintf(stderr, "Warning: Identity file %s "
373 "not accessible: %s.\n", optarg,
377 if (options.num_identity_files >=
378 SSH_MAX_IDENTITY_FILES)
379 fatal("Too many identity files specified "
380 "(max %d)", SSH_MAX_IDENTITY_FILES);
381 options.identity_files[options.num_identity_files++] =
386 options.pkcs11_provider = xstrdup(optarg);
388 fprintf(stderr, "no support for PKCS#11.\n");
397 if (debug_flag == 0) {
399 options.log_level = SYSLOG_LEVEL_DEBUG1;
401 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
407 fprintf(stderr, "%s, %s\n",
408 SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
413 if (options.tun_open == -1)
414 options.tun_open = SSH_TUNMODE_DEFAULT;
415 options.tun_local = a2tun(optarg, &options.tun_remote);
416 if (options.tun_local == SSH_TUNID_ERR) {
418 "Bad tun device '%s'\n", optarg);
423 if (stdio_forward_host != NULL)
424 fatal("stdio forward already specified");
425 if (muxclient_command != 0)
426 fatal("Cannot specify stdio forward with -O");
427 if (parse_forward(&fwd, optarg, 1, 0)) {
428 stdio_forward_host = fwd.listen_host;
429 stdio_forward_port = fwd.listen_port;
430 xfree(fwd.connect_host);
433 "Bad stdio forwarding specification '%s'\n",
439 options.clear_forwardings = 1;
440 options.exit_on_forward_failure = 1;
443 options.log_level = SYSLOG_LEVEL_QUIET;
446 if (optarg[0] == '^' && optarg[2] == 0 &&
447 (u_char) optarg[1] >= 64 &&
448 (u_char) optarg[1] < 128)
449 options.escape_char = (u_char) optarg[1] & 31;
450 else if (strlen(optarg) == 1)
451 options.escape_char = (u_char) optarg[0];
452 else if (strcmp(optarg, "none") == 0)
453 options.escape_char = SSH_ESCAPECHAR_NONE;
455 fprintf(stderr, "Bad escape character '%s'.\n",
461 if (ciphers_valid(optarg)) {
463 options.ciphers = xstrdup(optarg);
464 options.cipher = SSH_CIPHER_INVALID;
467 options.cipher = cipher_number(optarg);
468 if (options.cipher == -1) {
470 "Unknown cipher type '%s'\n",
474 if (options.cipher == SSH_CIPHER_3DES)
475 options.ciphers = "3des-cbc";
476 else if (options.cipher == SSH_CIPHER_BLOWFISH)
477 options.ciphers = "blowfish-cbc";
479 options.ciphers = (char *)-1;
483 if (mac_valid(optarg))
484 options.macs = xstrdup(optarg);
486 fprintf(stderr, "Unknown mac type '%s'\n",
492 if (options.control_master == SSHCTL_MASTER_YES)
493 options.control_master = SSHCTL_MASTER_ASK;
495 options.control_master = SSHCTL_MASTER_YES;
498 options.port = a2port(optarg);
499 if (options.port <= 0) {
500 fprintf(stderr, "Bad port '%s'\n", optarg);
505 options.user = optarg;
509 if (parse_forward(&fwd, optarg, 0, 0))
510 add_local_forward(&options, &fwd);
513 "Bad local forwarding specification '%s'\n",
520 if (parse_forward(&fwd, optarg, 0, 1)) {
521 add_remote_forward(&options, &fwd);
524 "Bad remote forwarding specification "
531 if (parse_forward(&fwd, optarg, 1, 0)) {
532 add_local_forward(&options, &fwd);
535 "Bad dynamic forwarding specification "
542 options.compression = 1;
553 line = xstrdup(optarg);
554 if (process_config_line(&options, host ? host : "",
555 line, "command-line", 0, &dummy) != 0)
563 if (options.control_path != NULL)
564 free(options.control_path);
565 options.control_path = xstrdup(optarg);
568 options.bind_address = optarg;
581 if (ac > 0 && !host) {
582 if (strrchr(*av, '@')) {
584 cp = strrchr(p, '@');
585 if (cp == NULL || cp == p)
593 optind = optreset = 1;
599 /* Check that we got a host name. */
603 SSLeay_add_all_algorithms();
604 ERR_load_crypto_strings();
606 /* Initialize the command to execute on remote host. */
607 buffer_init(&command);
610 * Save the command to execute on the remote host in a buffer. There
611 * is no limit on the length of the command, except by the maximum
612 * packet size. Also sets the tty flag if there is no command.
615 /* No command specified - execute shell on a tty. */
617 if (subsystem_flag) {
619 "You must specify a subsystem to invoke.\n");
623 /* A command has been specified. Store it into the buffer. */
624 for (i = 0; i < ac; i++) {
626 buffer_append(&command, " ", 1);
627 buffer_append(&command, av[i], strlen(av[i]));
631 /* Cannot fork to background if no command. */
632 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
634 fatal("Cannot fork into background without a command "
637 /* Allocate a tty by default if no command specified. */
638 if (buffer_len(&command) == 0)
642 if (no_tty_flag || muxclient_command != 0)
644 /* Do not allocate a tty if stdin is not a tty. */
645 if ((!isatty(fileno(stdin)) || stdin_null_flag) && !force_tty_flag) {
647 logit("Pseudo-terminal will not be allocated because "
648 "stdin is not a terminal.");
653 * Initialize "log" output. Since we are the client all output
654 * actually goes to stderr.
657 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
658 SYSLOG_FACILITY_USER, !use_syslog);
661 * Read per-user configuration file. Ignore the system wide config
662 * file if the user specifies a config file on the command line.
664 if (config != NULL) {
665 if (!read_config_file(config, host, &options, 0))
666 fatal("Can't open user config file %.100s: "
667 "%.100s", config, strerror(errno));
669 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
670 _PATH_SSH_USER_CONFFILE);
671 if (r > 0 && (size_t)r < sizeof(buf))
672 (void)read_config_file(buf, host, &options, 1);
674 /* Read systemwide configuration file after use config. */
675 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
679 /* Fill configuration defaults. */
680 fill_default_options(&options);
682 channel_set_af(options.address_family);
685 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
689 if (options.user == NULL)
690 options.user = xstrdup(pw->pw_name);
692 /* Get default port if port has not been set. */
693 if (options.port == 0) {
694 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
695 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
698 if (options.hostname != NULL) {
699 host = percent_expand(options.hostname,
700 "h", host, (char *)NULL);
703 if (options.local_command != NULL) {
704 char thishost[NI_MAXHOST];
706 if (gethostname(thishost, sizeof(thishost)) == -1)
707 fatal("gethostname: %s", strerror(errno));
708 snprintf(buf, sizeof(buf), "%d", options.port);
709 debug3("expanding LocalCommand: %s", options.local_command);
710 cp = options.local_command;
711 options.local_command = percent_expand(cp, "d", pw->pw_dir,
712 "h", host, "l", thishost, "n", host, "r", options.user,
713 "p", buf, "u", pw->pw_name, (char *)NULL);
714 debug3("expanded LocalCommand: %s", options.local_command);
718 /* Find canonic host name. */
719 if (strchr(host, '.') == 0) {
720 struct addrinfo hints;
721 struct addrinfo *ai = NULL;
723 memset(&hints, 0, sizeof(hints));
724 hints.ai_family = options.address_family;
725 hints.ai_flags = AI_CANONNAME;
726 hints.ai_socktype = SOCK_STREAM;
727 errgai = getaddrinfo(host, NULL, &hints, &ai);
729 if (ai->ai_canonname != NULL)
730 host = xstrdup(ai->ai_canonname);
735 /* force lowercase for hostkey matching */
736 if (options.host_key_alias != NULL) {
737 for (p = options.host_key_alias; *p; p++)
739 *p = (char)tolower(*p);
742 if (options.proxy_command != NULL &&
743 strcmp(options.proxy_command, "none") == 0) {
744 xfree(options.proxy_command);
745 options.proxy_command = NULL;
747 if (options.control_path != NULL &&
748 strcmp(options.control_path, "none") == 0) {
749 xfree(options.control_path);
750 options.control_path = NULL;
753 if (options.control_path != NULL) {
754 char thishost[NI_MAXHOST];
756 if (gethostname(thishost, sizeof(thishost)) == -1)
757 fatal("gethostname: %s", strerror(errno));
758 snprintf(buf, sizeof(buf), "%d", options.port);
759 cp = tilde_expand_filename(options.control_path,
761 xfree(options.control_path);
762 options.control_path = percent_expand(cp, "p", buf, "h", host,
763 "r", options.user, "l", thishost, (char *)NULL);
766 if (muxclient_command != 0 && options.control_path == NULL)
767 fatal("No ControlPath specified for \"-O\" command");
768 if (options.control_path != NULL)
769 muxclient(options.control_path);
771 timeout_ms = options.connection_timeout * 1000;
773 /* Open a connection to the remote host. */
774 if (ssh_connect(host, &hostaddr, options.port,
775 options.address_family, options.connection_attempts, &timeout_ms,
776 options.tcp_keep_alive,
778 options.use_privileged_port,
780 original_effective_uid == 0 && options.use_privileged_port,
782 options.proxy_command) != 0)
786 debug3("timeout: %d ms remain after connect", timeout_ms);
789 * If we successfully made the connection, load the host private key
790 * in case we will need it later for combined rsa-rhosts
791 * authentication. This must be done before releasing extra
792 * privileges, because the file is only readable by root.
793 * If we cannot access the private keys, load the public keys
794 * instead and try to execute the ssh-keysign helper instead.
796 sensitive_data.nkeys = 0;
797 sensitive_data.keys = NULL;
798 sensitive_data.external_keysign = 0;
799 if (options.rhosts_rsa_authentication ||
800 options.hostbased_authentication) {
801 sensitive_data.nkeys = 5;
802 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
806 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
807 _PATH_HOST_KEY_FILE, "", NULL, NULL);
808 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
809 _PATH_HOST_DSA_KEY_FILE, "", NULL);
810 sensitive_data.keys[2] = key_load_private_cert(KEY_RSA,
811 _PATH_HOST_RSA_KEY_FILE, "", NULL);
812 sensitive_data.keys[3] = key_load_private_type(KEY_DSA,
813 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
814 sensitive_data.keys[4] = key_load_private_type(KEY_RSA,
815 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
818 if (options.hostbased_authentication == 1 &&
819 sensitive_data.keys[0] == NULL &&
820 sensitive_data.keys[3] == NULL &&
821 sensitive_data.keys[4] == NULL) {
822 sensitive_data.keys[1] = key_load_cert(
823 _PATH_HOST_DSA_KEY_FILE);
824 sensitive_data.keys[2] = key_load_cert(
825 _PATH_HOST_RSA_KEY_FILE);
826 sensitive_data.keys[3] = key_load_public(
827 _PATH_HOST_DSA_KEY_FILE, NULL);
828 sensitive_data.keys[4] = key_load_public(
829 _PATH_HOST_RSA_KEY_FILE, NULL);
830 sensitive_data.external_keysign = 1;
834 * Get rid of any extra privileges that we may have. We will no
835 * longer need them. Also, extra privileges could make it very hard
836 * to read identity files and other non-world-readable files from the
837 * user's home directory if it happens to be on a NFS volume where
838 * root is mapped to nobody.
840 if (original_effective_uid == 0) {
842 permanently_set_uid(pw);
846 * Now that we are back to our own permissions, create ~/.ssh
847 * directory if it doesn't already exist.
849 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
850 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
851 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0)
852 if (mkdir(buf, 0700) < 0)
853 error("Could not create directory '%.200s'.", buf);
855 /* load options.identity_files */
856 load_public_identity_files();
858 /* Expand ~ in known host file names. */
860 options.system_hostfile =
861 tilde_expand_filename(options.system_hostfile, original_real_uid);
862 options.user_hostfile =
863 tilde_expand_filename(options.user_hostfile, original_real_uid);
864 options.system_hostfile2 =
865 tilde_expand_filename(options.system_hostfile2, original_real_uid);
866 options.user_hostfile2 =
867 tilde_expand_filename(options.user_hostfile2, original_real_uid);
869 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
871 /* Log into the remote system. Never returns if the login fails. */
872 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
875 if (packet_connection_is_on_socket()) {
876 verbose("Authenticated to %s ([%s]:%d).", host,
877 get_remote_ipaddr(), get_remote_port());
879 verbose("Authenticated to %s (via proxy).", host);
882 /* We no longer need the private host keys. Clear them now. */
883 if (sensitive_data.nkeys != 0) {
884 for (i = 0; i < sensitive_data.nkeys; i++) {
885 if (sensitive_data.keys[i] != NULL) {
886 /* Destroys contents safely */
887 debug3("clear hostkey %d", i);
888 key_free(sensitive_data.keys[i]);
889 sensitive_data.keys[i] = NULL;
892 xfree(sensitive_data.keys);
894 for (i = 0; i < options.num_identity_files; i++) {
895 if (options.identity_files[i]) {
896 xfree(options.identity_files[i]);
897 options.identity_files[i] = NULL;
899 if (options.identity_keys[i]) {
900 key_free(options.identity_keys[i]);
901 options.identity_keys[i] = NULL;
905 exit_status = compat20 ? ssh_session2() : ssh_session();
908 if (options.control_path != NULL && muxserver_sock != -1)
909 unlink(options.control_path);
912 * Send SIGHUP to proxy command if used. We don't wait() in
913 * case it hangs and instead rely on init to reap the child
915 if (proxy_command_pid > 1)
916 kill(proxy_command_pid, SIGHUP);
922 control_persist_detach(void)
927 debug("%s: backgrounding master process", __func__);
930 * master (current process) into the background, and make the
931 * foreground process a client of the backgrounded master.
933 switch ((pid = fork())) {
935 fatal("%s: fork: %s", __func__, strerror(errno));
937 /* Child: master process continues mainloop */
940 /* Parent: set up mux slave to connect to backgrounded master */
941 debug2("%s: background process is %ld", __func__, (long)pid);
942 stdin_null_flag = ostdin_null_flag;
943 no_shell_flag = ono_shell_flag;
944 no_tty_flag = ono_tty_flag;
945 tty_flag = otty_flag;
946 close(muxserver_sock);
948 muxclient(options.control_path);
949 /* muxclient() doesn't return on success. */
950 fatal("Failed to connect to new control master");
952 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
953 error("%s: open(\"/dev/null\"): %s", __func__,
956 if (dup2(devnull, STDIN_FILENO) == -1 ||
957 dup2(devnull, STDOUT_FILENO) == -1)
958 error("%s: dup2: %s", __func__, strerror(errno));
959 if (devnull > STDERR_FILENO)
964 /* Do fork() after authentication. Used by "ssh -f" */
968 if (need_controlpersist_detach)
969 control_persist_detach();
970 debug("forking to background");
971 fork_after_authentication_flag = 0;
972 if (daemon(1, 1) < 0)
973 fatal("daemon() failed: %.200s", strerror(errno));
976 /* Callback for remote forward global requests */
978 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
980 Forward *rfwd = (Forward *)ctxt;
982 /* XXX verbose() on failure? */
983 debug("remote forward %s for: listen %d, connect %s:%d",
984 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
985 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
986 if (type == SSH2_MSG_REQUEST_SUCCESS && rfwd->listen_port == 0) {
987 rfwd->allocated_port = packet_get_int();
988 logit("Allocated port %u for remote forward to %s:%d",
989 rfwd->allocated_port,
990 rfwd->connect_host, rfwd->connect_port);
993 if (type == SSH2_MSG_REQUEST_FAILURE) {
994 if (options.exit_on_forward_failure)
995 fatal("Error: remote port forwarding failed for "
996 "listen port %d", rfwd->listen_port);
998 logit("Warning: remote port forwarding failed for "
999 "listen port %d", rfwd->listen_port);
1001 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1002 debug("All remote forwarding requests processed");
1003 if (fork_after_authentication_flag)
1009 client_cleanup_stdio_fwd(int id, void *arg)
1011 debug("stdio forwarding: done");
1016 client_setup_stdio_fwd(const char *host_to_connect, u_short port_to_connect)
1021 debug3("client_setup_stdio_fwd %s:%d", host_to_connect,
1024 in = dup(STDIN_FILENO);
1025 out = dup(STDOUT_FILENO);
1026 if (in < 0 || out < 0)
1027 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1029 if ((c = channel_connect_stdio_fwd(host_to_connect, port_to_connect,
1032 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1037 ssh_init_forwarding(void)
1042 if (stdio_forward_host != NULL) {
1044 fatal("stdio forwarding require Protocol 2");
1046 if (!client_setup_stdio_fwd(stdio_forward_host,
1047 stdio_forward_port))
1048 fatal("Failed to connect in stdio forward mode.");
1051 /* Initiate local TCP/IP port forwardings. */
1052 for (i = 0; i < options.num_local_forwards; i++) {
1053 debug("Local connections to %.200s:%d forwarded to remote "
1054 "address %.200s:%d",
1055 (options.local_forwards[i].listen_host == NULL) ?
1056 (options.gateway_ports ? "*" : "LOCALHOST") :
1057 options.local_forwards[i].listen_host,
1058 options.local_forwards[i].listen_port,
1059 options.local_forwards[i].connect_host,
1060 options.local_forwards[i].connect_port);
1061 success += channel_setup_local_fwd_listener(
1062 options.local_forwards[i].listen_host,
1063 options.local_forwards[i].listen_port,
1064 options.local_forwards[i].connect_host,
1065 options.local_forwards[i].connect_port,
1066 options.gateway_ports);
1068 if (i > 0 && success != i && options.exit_on_forward_failure)
1069 fatal("Could not request local forwarding.");
1070 if (i > 0 && success == 0)
1071 error("Could not request local forwarding.");
1073 /* Initiate remote TCP/IP port forwardings. */
1074 for (i = 0; i < options.num_remote_forwards; i++) {
1075 debug("Remote connections from %.200s:%d forwarded to "
1076 "local address %.200s:%d",
1077 (options.remote_forwards[i].listen_host == NULL) ?
1078 "LOCALHOST" : options.remote_forwards[i].listen_host,
1079 options.remote_forwards[i].listen_port,
1080 options.remote_forwards[i].connect_host,
1081 options.remote_forwards[i].connect_port);
1082 if (channel_request_remote_forwarding(
1083 options.remote_forwards[i].listen_host,
1084 options.remote_forwards[i].listen_port,
1085 options.remote_forwards[i].connect_host,
1086 options.remote_forwards[i].connect_port) < 0) {
1087 if (options.exit_on_forward_failure)
1088 fatal("Could not request remote forwarding.");
1090 logit("Warning: Could not request remote "
1093 client_register_global_confirm(ssh_confirm_remote_forward,
1094 &options.remote_forwards[i]);
1097 /* Initiate tunnel forwarding. */
1098 if (options.tun_open != SSH_TUNMODE_NO) {
1099 if (client_request_tun_fwd(options.tun_open,
1100 options.tun_local, options.tun_remote) == -1) {
1101 if (options.exit_on_forward_failure)
1102 fatal("Could not request tunnel forwarding.");
1104 error("Could not request tunnel forwarding.");
1110 check_agent_present(void)
1112 if (options.forward_agent) {
1113 /* Clear agent forwarding if we don't have an agent. */
1114 if (!ssh_agent_present())
1115 options.forward_agent = 0;
1123 int interactive = 0;
1127 const char *display;
1129 /* Enable compression if requested. */
1130 if (options.compression) {
1131 debug("Requesting compression at level %d.",
1132 options.compression_level);
1134 if (options.compression_level < 1 ||
1135 options.compression_level > 9)
1136 fatal("Compression level must be from 1 (fast) to "
1139 /* Send the request. */
1140 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1141 packet_put_int(options.compression_level);
1143 packet_write_wait();
1144 type = packet_read();
1145 if (type == SSH_SMSG_SUCCESS)
1146 packet_start_compression(options.compression_level);
1147 else if (type == SSH_SMSG_FAILURE)
1148 logit("Warning: Remote host refused compression.");
1150 packet_disconnect("Protocol error waiting for "
1151 "compression response.");
1153 /* Allocate a pseudo tty if appropriate. */
1155 debug("Requesting pty.");
1157 /* Start the packet. */
1158 packet_start(SSH_CMSG_REQUEST_PTY);
1160 /* Store TERM in the packet. There is no limit on the
1161 length of the string. */
1162 cp = getenv("TERM");
1165 packet_put_cstring(cp);
1167 /* Store window size in the packet. */
1168 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1169 memset(&ws, 0, sizeof(ws));
1170 packet_put_int((u_int)ws.ws_row);
1171 packet_put_int((u_int)ws.ws_col);
1172 packet_put_int((u_int)ws.ws_xpixel);
1173 packet_put_int((u_int)ws.ws_ypixel);
1175 /* Store tty modes in the packet. */
1176 tty_make_modes(fileno(stdin), NULL);
1178 /* Send the packet, and wait for it to leave. */
1180 packet_write_wait();
1182 /* Read response from the server. */
1183 type = packet_read();
1184 if (type == SSH_SMSG_SUCCESS) {
1187 } else if (type == SSH_SMSG_FAILURE)
1188 logit("Warning: Remote host failed or refused to "
1189 "allocate a pseudo tty.");
1191 packet_disconnect("Protocol error waiting for pty "
1192 "request response.");
1194 /* Request X11 forwarding if enabled and DISPLAY is set. */
1195 display = getenv("DISPLAY");
1196 if (options.forward_x11 && display != NULL) {
1198 /* Get reasonable local authentication information. */
1199 client_x11_get_proto(display, options.xauth_location,
1200 options.forward_x11_trusted,
1201 options.forward_x11_timeout,
1203 /* Request forwarding with authentication spoofing. */
1204 debug("Requesting X11 forwarding with authentication "
1206 x11_request_forwarding_with_spoofing(0, display, proto, data);
1208 /* Read response from the server. */
1209 type = packet_read();
1210 if (type == SSH_SMSG_SUCCESS) {
1212 } else if (type == SSH_SMSG_FAILURE) {
1213 logit("Warning: Remote host denied X11 forwarding.");
1215 packet_disconnect("Protocol error waiting for X11 "
1219 /* Tell the packet module whether this is an interactive session. */
1220 packet_set_interactive(interactive);
1222 /* Request authentication agent forwarding if appropriate. */
1223 check_agent_present();
1225 if (options.forward_agent) {
1226 debug("Requesting authentication agent forwarding.");
1227 auth_request_forwarding();
1229 /* Read response from the server. */
1230 type = packet_read();
1232 if (type != SSH_SMSG_SUCCESS)
1233 logit("Warning: Remote host denied authentication agent forwarding.");
1236 /* Initiate port forwardings. */
1237 ssh_init_forwarding();
1239 /* Execute a local command */
1240 if (options.local_command != NULL &&
1241 options.permit_local_command)
1242 ssh_local_cmd(options.local_command);
1245 * If requested and we are not interested in replies to remote
1246 * forwarding requests, then let ssh continue in the background.
1248 if (fork_after_authentication_flag) {
1249 if (options.exit_on_forward_failure &&
1250 options.num_remote_forwards > 0) {
1251 debug("deferring postauth fork until remote forward "
1252 "confirmation received");
1258 * If a command was specified on the command line, execute the
1259 * command now. Otherwise request the server to start a shell.
1261 if (buffer_len(&command) > 0) {
1262 int len = buffer_len(&command);
1265 debug("Sending command: %.*s", len,
1266 (u_char *)buffer_ptr(&command));
1267 packet_start(SSH_CMSG_EXEC_CMD);
1268 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1270 packet_write_wait();
1272 debug("Requesting shell.");
1273 packet_start(SSH_CMSG_EXEC_SHELL);
1275 packet_write_wait();
1278 /* Enter the interactive session. */
1279 return client_loop(have_tty, tty_flag ?
1280 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1283 /* request pty/x11/agent/tcpfwd/shell for channel */
1285 ssh_session2_setup(int id, int success, void *arg)
1287 extern char **environ;
1288 const char *display;
1289 int interactive = tty_flag;
1292 return; /* No need for error message, channels code sens one */
1294 display = getenv("DISPLAY");
1295 if (options.forward_x11 && display != NULL) {
1297 /* Get reasonable local authentication information. */
1298 client_x11_get_proto(display, options.xauth_location,
1299 options.forward_x11_trusted,
1300 options.forward_x11_timeout, &proto, &data);
1301 /* Request forwarding with authentication spoofing. */
1302 debug("Requesting X11 forwarding with authentication "
1304 x11_request_forwarding_with_spoofing(id, display, proto, data);
1306 /* XXX wait for reply */
1309 check_agent_present();
1310 if (options.forward_agent) {
1311 debug("Requesting authentication agent forwarding.");
1312 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1316 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1317 NULL, fileno(stdin), &command, environ);
1319 packet_set_interactive(interactive);
1322 /* open new channel for a session */
1324 ssh_session2_open(void)
1327 int window, packetmax, in, out, err;
1329 if (stdin_null_flag) {
1330 in = open(_PATH_DEVNULL, O_RDONLY);
1332 in = dup(STDIN_FILENO);
1334 out = dup(STDOUT_FILENO);
1335 err = dup(STDERR_FILENO);
1337 if (in < 0 || out < 0 || err < 0)
1338 fatal("dup() in/out/err failed");
1340 /* enable nonblocking unless tty */
1348 window = CHAN_SES_WINDOW_DEFAULT;
1349 packetmax = CHAN_SES_PACKET_DEFAULT;
1355 "session", SSH_CHANNEL_OPENING, in, out, err,
1356 window, packetmax, CHAN_EXTENDED_WRITE,
1357 "client-session", /*nonblock*/0);
1359 debug3("ssh_session2_open: channel_new: %d", c->self);
1361 channel_send_open(c->self);
1363 channel_register_open_confirm(c->self,
1364 ssh_session2_setup, NULL);
1374 /* XXX should be pre-session */
1375 ssh_init_forwarding();
1377 /* Start listening for multiplex clients */
1381 * If we are in control persist mode, then prepare to background
1382 * ourselves and have a foreground client attach as a control
1383 * slave. NB. we must save copies of the flags that we override for
1384 * the backgrounding, since we defer attachment of the slave until
1385 * after the connection is fully established (in particular,
1386 * async rfwd replies have been received for ExitOnForwardFailure).
1388 if (options.control_persist && muxserver_sock != -1) {
1389 ostdin_null_flag = stdin_null_flag;
1390 ono_shell_flag = no_shell_flag;
1391 ono_tty_flag = no_tty_flag;
1392 otty_flag = tty_flag;
1393 stdin_null_flag = 1;
1397 if (!fork_after_authentication_flag)
1398 need_controlpersist_detach = 1;
1399 fork_after_authentication_flag = 1;
1402 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1403 id = ssh_session2_open();
1405 /* If we don't expect to open a new session, then disallow it */
1406 if (options.control_master == SSHCTL_MASTER_NO &&
1407 (datafellows & SSH_NEW_OPENSSH)) {
1408 debug("Requesting no-more-sessions@openssh.com");
1409 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1410 packet_put_cstring("no-more-sessions@openssh.com");
1415 /* Execute a local command */
1416 if (options.local_command != NULL &&
1417 options.permit_local_command)
1418 ssh_local_cmd(options.local_command);
1421 * If requested and we are not interested in replies to remote
1422 * forwarding requests, then let ssh continue in the background.
1424 if (fork_after_authentication_flag) {
1425 if (options.exit_on_forward_failure &&
1426 options.num_remote_forwards > 0) {
1427 debug("deferring postauth fork until remote forward "
1428 "confirmation received");
1433 if (options.use_roaming)
1436 return client_loop(tty_flag, tty_flag ?
1437 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1441 load_public_identity_files(void)
1443 char *filename, *cp, thishost[NI_MAXHOST];
1444 char *pwdir = NULL, *pwname = NULL;
1449 char *identity_files[SSH_MAX_IDENTITY_FILES];
1450 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1451 #ifdef ENABLE_PKCS11
1457 bzero(identity_files, sizeof(identity_files));
1458 bzero(identity_keys, sizeof(identity_keys));
1460 #ifdef ENABLE_PKCS11
1461 if (options.pkcs11_provider != NULL &&
1462 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1463 (pkcs11_init(!options.batch_mode) == 0) &&
1464 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1466 for (i = 0; i < nkeys; i++) {
1467 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1471 identity_keys[n_ids] = keys[i];
1472 identity_files[n_ids] =
1473 xstrdup(options.pkcs11_provider); /* XXX */
1478 #endif /* ENABLE_PKCS11 */
1479 if ((pw = getpwuid(original_real_uid)) == NULL)
1480 fatal("load_public_identity_files: getpwuid failed");
1481 pwname = xstrdup(pw->pw_name);
1482 pwdir = xstrdup(pw->pw_dir);
1483 if (gethostname(thishost, sizeof(thishost)) == -1)
1484 fatal("load_public_identity_files: gethostname: %s",
1486 for (i = 0; i < options.num_identity_files; i++) {
1487 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1488 xfree(options.identity_files[i]);
1491 cp = tilde_expand_filename(options.identity_files[i],
1493 filename = percent_expand(cp, "d", pwdir,
1494 "u", pwname, "l", thishost, "h", host,
1495 "r", options.user, (char *)NULL);
1497 public = key_load_public(filename, NULL);
1498 debug("identity file %s type %d", filename,
1499 public ? public->type : -1);
1500 xfree(options.identity_files[i]);
1501 identity_files[n_ids] = filename;
1502 identity_keys[n_ids] = public;
1504 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1507 /* Try to add the certificate variant too */
1508 xasprintf(&cp, "%s-cert", filename);
1509 public = key_load_public(cp, NULL);
1510 debug("identity file %s type %d", cp,
1511 public ? public->type : -1);
1512 if (public == NULL) {
1516 if (!key_is_cert(public)) {
1517 debug("%s: key %s type %s is not a certificate",
1518 __func__, cp, key_type(public));
1523 identity_keys[n_ids] = public;
1524 /* point to the original path, most likely the private key */
1525 identity_files[n_ids] = xstrdup(filename);
1528 options.num_identity_files = n_ids;
1529 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1530 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1532 bzero(pwname, strlen(pwname));
1534 bzero(pwdir, strlen(pwdir));