1 /* $OpenBSD: ssh.c,v 1.371 2013/02/17 23:16:57 dtucker Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * Ssh client program. This program can be used to log into a remote machine.
8 * The software supports strong authentication, encryption, and forwarding
9 * of X11, TCP/IP, and authentication connections.
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
17 * Copyright (c) 1999 Niels Provos. All rights reserved.
18 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
20 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
21 * in Canada (German citizen).
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 #include <sys/types.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h>
51 #include <sys/resource.h>
52 #include <sys/ioctl.h>
53 #include <sys/param.h>
54 #include <sys/socket.h>
73 #include <netinet/in.h>
74 #include <arpa/inet.h>
76 #include <openssl/evp.h>
77 #include <openssl/err.h>
78 #include "openbsd-compat/openssl-compat.h"
79 #include "openbsd-compat/sys-queue.h"
94 #include "pathnames.h"
96 #include "clientloop.h"
99 #include "sshconnect.h"
111 #include "ssh-pkcs11.h"
114 extern char *__progname;
116 /* Saves a copy of argv for setproctitle emulation */
117 #ifndef HAVE_SETPROCTITLE
118 static char **saved_av;
121 /* Flag indicating whether debug mode is on. May be set on the command line. */
124 /* Flag indicating whether a tty should be requested */
127 /* don't exec a shell */
128 int no_shell_flag = 0;
131 * Flag indicating that nothing should be read from stdin. This can be set
132 * on the command line.
134 int stdin_null_flag = 0;
137 * Flag indicating that the current process should be backgrounded and
138 * a new slave launched in the foreground for ControlPersist.
140 int need_controlpersist_detach = 0;
142 /* Copies of flags for ControlPersist foreground slave */
143 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
146 * Flag indicating that ssh should fork after authentication. This is useful
147 * so that the passphrase can be entered manually, and then ssh goes to the
150 int fork_after_authentication_flag = 0;
152 /* forward stdio to remote host and port */
153 char *stdio_forward_host = NULL;
154 int stdio_forward_port = 0;
157 * General data structure for command line options and options configurable
158 * in configuration files. See readconf.h.
162 /* optional user configfile */
166 * Name of the host we are connecting to. This is the name given on the
167 * command line, or the HostName specified for the user-supplied name in a
168 * configuration file.
172 /* socket address the host resolves to */
173 struct sockaddr_storage hostaddr;
175 /* Private host keys. */
176 Sensitive sensitive_data;
178 /* Original real UID. */
179 uid_t original_real_uid;
180 uid_t original_effective_uid;
182 /* command to be executed */
185 /* Should we execute a command or invoke a subsystem? */
186 int subsystem_flag = 0;
188 /* # of replies received for global requests */
189 static int remote_forward_confirms_received = 0;
192 extern int muxserver_sock;
193 extern u_int muxclient_command;
195 /* Prints a help message to the user. This function never returns. */
201 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
202 " [-D [bind_address:]port] [-e escape_char] [-F configfile]\n"
203 " [-I pkcs11] [-i identity_file]\n"
204 " [-L [bind_address:]port:host:hostport]\n"
205 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
206 " [-R [bind_address:]port:host:hostport] [-S ctl_path]\n"
207 " [-W host:port] [-w local_tun[:remote_tun]]\n"
208 " [user@]hostname [command]\n"
213 static int ssh_session(void);
214 static int ssh_session2(void);
215 static void load_public_identity_files(void);
216 static void main_sigchld_handler(int);
218 /* from muxclient.c */
219 void muxclient(const char *);
220 void muxserver_listen(void);
222 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
224 tilde_expand_paths(char **paths, u_int num_paths)
229 for (i = 0; i < num_paths; i++) {
230 cp = tilde_expand_filename(paths[i], original_real_uid);
237 * Main program for the ssh client.
240 main(int ac, char **av)
242 int i, r, opt, exit_status, use_syslog;
243 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg;
244 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
247 int dummy, timeout_ms;
248 extern int optind, optreset;
254 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
257 __progname = ssh_get_progname(av[0]);
259 #ifndef HAVE_SETPROCTITLE
260 /* Prepare for later setproctitle emulation */
261 /* Save argv so it isn't clobbered by setproctitle() emulation */
262 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
263 for (i = 0; i < ac; i++)
264 saved_av[i] = xstrdup(av[i]);
266 compat_init_setproctitle(ac, av);
271 * Discard other fds that are hanging around. These can cause problem
272 * with backgrounded ssh processes started by ControlPersist.
274 closefrom(STDERR_FILENO + 1);
277 * Save the original real uid. It will be needed later (uid-swapping
278 * may clobber the real uid).
280 original_real_uid = getuid();
281 original_effective_uid = geteuid();
284 * Use uid-swapping to give up root privileges for the duration of
285 * option processing. We will re-instantiate the rights when we are
286 * ready to create the privileged port, and will permanently drop
287 * them when the port has been created (actually, when the connection
288 * has been made, as we may need to create the port several times).
292 #ifdef HAVE_SETRLIMIT
293 /* If we are installed setuid root be careful to not drop core. */
294 if (original_real_uid != original_effective_uid) {
296 rlim.rlim_cur = rlim.rlim_max = 0;
297 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
298 fatal("setrlimit failed: %.100s", strerror(errno));
302 pw = getpwuid(original_real_uid);
304 logit("You don't exist, go away!");
307 /* Take a copy of the returned structure. */
311 * Set our umask to something reasonable, as some files are created
312 * with the default umask. This will make them world-readable but
313 * writable only by the owner, which is ok for all files for which we
314 * don't set the modes explicitly.
319 * Initialize option structure to indicate that no values have been
322 initialize_options(&options);
324 /* Parse command-line arguments. */
330 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
331 "ACD:F:I:KL:MNO:PR:S:TVw:W:XYy")) != -1) {
334 options.protocol = SSH_PROTO_1;
337 options.protocol = SSH_PROTO_2;
340 options.address_family = AF_INET;
343 options.address_family = AF_INET6;
349 fork_after_authentication_flag = 1;
353 options.forward_x11 = 0;
356 options.forward_x11 = 1;
362 options.forward_x11 = 1;
363 options.forward_x11_trusted = 1;
366 options.gateway_ports = 1;
369 if (stdio_forward_host != NULL)
370 fatal("Cannot specify multiplexing "
372 else if (muxclient_command != 0)
373 fatal("Multiplexing command already specified");
374 if (strcmp(optarg, "check") == 0)
375 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
376 else if (strcmp(optarg, "forward") == 0)
377 muxclient_command = SSHMUX_COMMAND_FORWARD;
378 else if (strcmp(optarg, "exit") == 0)
379 muxclient_command = SSHMUX_COMMAND_TERMINATE;
380 else if (strcmp(optarg, "stop") == 0)
381 muxclient_command = SSHMUX_COMMAND_STOP;
382 else if (strcmp(optarg, "cancel") == 0)
383 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
385 fatal("Invalid multiplex command.");
387 case 'P': /* deprecated */
388 options.use_privileged_port = 0;
391 options.forward_agent = 0;
394 options.forward_agent = 1;
397 options.gss_deleg_creds = 0;
400 options.gss_authentication = 1;
401 options.gss_deleg_creds = 1;
404 if (stat(optarg, &st) < 0) {
405 fprintf(stderr, "Warning: Identity file %s "
406 "not accessible: %s.\n", optarg,
410 add_identity_file(&options, NULL, optarg, 1);
414 options.pkcs11_provider = xstrdup(optarg);
416 fprintf(stderr, "no support for PKCS#11.\n");
420 if (options.request_tty == REQUEST_TTY_YES)
421 options.request_tty = REQUEST_TTY_FORCE;
423 options.request_tty = REQUEST_TTY_YES;
426 if (debug_flag == 0) {
428 options.log_level = SYSLOG_LEVEL_DEBUG1;
430 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
436 if (options.version_addendum &&
437 *options.version_addendum != '\0')
438 fprintf(stderr, "%s%s %s, %s\n", SSH_RELEASE,
439 options.hpn_disabled ? "" : SSH_VERSION_HPN,
440 options.version_addendum,
441 SSLeay_version(SSLEAY_VERSION));
443 fprintf(stderr, "%s%s, %s\n", SSH_RELEASE,
444 options.hpn_disabled ? "" : SSH_VERSION_HPN,
445 SSLeay_version(SSLEAY_VERSION));
450 if (options.tun_open == -1)
451 options.tun_open = SSH_TUNMODE_DEFAULT;
452 options.tun_local = a2tun(optarg, &options.tun_remote);
453 if (options.tun_local == SSH_TUNID_ERR) {
455 "Bad tun device '%s'\n", optarg);
460 if (stdio_forward_host != NULL)
461 fatal("stdio forward already specified");
462 if (muxclient_command != 0)
463 fatal("Cannot specify stdio forward with -O");
464 if (parse_forward(&fwd, optarg, 1, 0)) {
465 stdio_forward_host = fwd.listen_host;
466 stdio_forward_port = fwd.listen_port;
467 xfree(fwd.connect_host);
470 "Bad stdio forwarding specification '%s'\n",
474 options.request_tty = REQUEST_TTY_NO;
476 options.clear_forwardings = 1;
477 options.exit_on_forward_failure = 1;
480 options.log_level = SYSLOG_LEVEL_QUIET;
483 if (optarg[0] == '^' && optarg[2] == 0 &&
484 (u_char) optarg[1] >= 64 &&
485 (u_char) optarg[1] < 128)
486 options.escape_char = (u_char) optarg[1] & 31;
487 else if (strlen(optarg) == 1)
488 options.escape_char = (u_char) optarg[0];
489 else if (strcmp(optarg, "none") == 0)
490 options.escape_char = SSH_ESCAPECHAR_NONE;
492 fprintf(stderr, "Bad escape character '%s'.\n",
498 if (ciphers_valid(optarg)) {
500 options.ciphers = xstrdup(optarg);
501 options.cipher = SSH_CIPHER_INVALID;
504 options.cipher = cipher_number(optarg);
505 if (options.cipher == -1) {
507 "Unknown cipher type '%s'\n",
511 if (options.cipher == SSH_CIPHER_3DES)
512 options.ciphers = "3des-cbc";
513 else if (options.cipher == SSH_CIPHER_BLOWFISH)
514 options.ciphers = "blowfish-cbc";
516 options.ciphers = (char *)-1;
520 if (mac_valid(optarg))
521 options.macs = xstrdup(optarg);
523 fprintf(stderr, "Unknown mac type '%s'\n",
529 if (options.control_master == SSHCTL_MASTER_YES)
530 options.control_master = SSHCTL_MASTER_ASK;
532 options.control_master = SSHCTL_MASTER_YES;
535 options.port = a2port(optarg);
536 if (options.port <= 0) {
537 fprintf(stderr, "Bad port '%s'\n", optarg);
542 options.user = optarg;
546 if (parse_forward(&fwd, optarg, 0, 0))
547 add_local_forward(&options, &fwd);
550 "Bad local forwarding specification '%s'\n",
557 if (parse_forward(&fwd, optarg, 0, 1)) {
558 add_remote_forward(&options, &fwd);
561 "Bad remote forwarding specification "
568 if (parse_forward(&fwd, optarg, 1, 0)) {
569 add_local_forward(&options, &fwd);
572 "Bad dynamic forwarding specification "
579 options.compression = 1;
583 options.request_tty = REQUEST_TTY_NO;
586 options.request_tty = REQUEST_TTY_NO;
587 #ifdef NONE_CIPHER_ENABLED
589 * Ensure that the user does not try to backdoor a
590 * NONE cipher switch on an interactive session by
591 * explicitly disabling it if the user asks for a
592 * session without a tty.
594 options.none_switch = 0;
599 line = xstrdup(optarg);
600 if (process_config_line(&options, host ? host : "",
601 line, "command-line", 0, &dummy) != 0)
609 if (options.control_path != NULL)
610 free(options.control_path);
611 options.control_path = xstrdup(optarg);
614 options.bind_address = optarg;
627 if (ac > 0 && !host) {
628 if (strrchr(*av, '@')) {
630 cp = strrchr(p, '@');
631 if (cp == NULL || cp == p)
639 optind = optreset = 1;
645 /* Check that we got a host name. */
649 OpenSSL_add_all_algorithms();
650 ERR_load_crypto_strings();
652 /* Initialize the command to execute on remote host. */
653 buffer_init(&command);
656 * Save the command to execute on the remote host in a buffer. There
657 * is no limit on the length of the command, except by the maximum
658 * packet size. Also sets the tty flag if there is no command.
661 /* No command specified - execute shell on a tty. */
662 if (subsystem_flag) {
664 "You must specify a subsystem to invoke.\n");
668 /* A command has been specified. Store it into the buffer. */
669 for (i = 0; i < ac; i++) {
671 buffer_append(&command, " ", 1);
672 buffer_append(&command, av[i], strlen(av[i]));
676 /* Cannot fork to background if no command. */
677 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
679 fatal("Cannot fork into background without a command "
683 * Initialize "log" output. Since we are the client all output
684 * actually goes to stderr.
687 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
688 SYSLOG_FACILITY_USER, !use_syslog);
691 * Read per-user configuration file. Ignore the system wide config
692 * file if the user specifies a config file on the command line.
694 if (config != NULL) {
695 if (!read_config_file(config, host, &options, 0))
696 fatal("Can't open user config file %.100s: "
697 "%.100s", config, strerror(errno));
699 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
700 _PATH_SSH_USER_CONFFILE);
701 if (r > 0 && (size_t)r < sizeof(buf))
702 (void)read_config_file(buf, host, &options, 1);
704 /* Read systemwide configuration file after user config. */
705 (void)read_config_file(_PATH_HOST_CONFIG_FILE, host,
709 /* Fill configuration defaults. */
710 fill_default_options(&options);
712 channel_set_af(options.address_family);
715 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
717 if (options.request_tty == REQUEST_TTY_YES ||
718 options.request_tty == REQUEST_TTY_FORCE)
721 /* Allocate a tty by default if no command specified. */
722 if (buffer_len(&command) == 0)
723 tty_flag = options.request_tty != REQUEST_TTY_NO;
726 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
728 /* Do not allocate a tty if stdin is not a tty. */
729 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
730 options.request_tty != REQUEST_TTY_FORCE) {
732 logit("Pseudo-terminal will not be allocated because "
733 "stdin is not a terminal.");
739 if (options.user == NULL)
740 options.user = xstrdup(pw->pw_name);
742 /* Get default port if port has not been set. */
743 if (options.port == 0) {
744 sp = getservbyname(SSH_SERVICE_NAME, "tcp");
745 options.port = sp ? ntohs(sp->s_port) : SSH_DEFAULT_PORT;
748 /* preserve host name given on command line for %n expansion */
750 if (options.hostname != NULL) {
751 host = percent_expand(options.hostname,
752 "h", host, (char *)NULL);
755 if (gethostname(thishost, sizeof(thishost)) == -1)
756 fatal("gethostname: %s", strerror(errno));
757 strlcpy(shorthost, thishost, sizeof(shorthost));
758 shorthost[strcspn(thishost, ".")] = '\0';
759 snprintf(portstr, sizeof(portstr), "%d", options.port);
761 if (options.local_command != NULL) {
762 debug3("expanding LocalCommand: %s", options.local_command);
763 cp = options.local_command;
764 options.local_command = percent_expand(cp, "d", pw->pw_dir,
765 "h", host, "l", thishost, "n", host_arg, "r", options.user,
766 "p", portstr, "u", pw->pw_name, "L", shorthost,
768 debug3("expanded LocalCommand: %s", options.local_command);
772 /* Find canonic host name. */
773 if (strchr(host, '.') == 0) {
774 struct addrinfo hints;
775 struct addrinfo *ai = NULL;
777 memset(&hints, 0, sizeof(hints));
778 hints.ai_family = options.address_family;
779 hints.ai_flags = AI_CANONNAME;
780 hints.ai_socktype = SOCK_STREAM;
781 errgai = getaddrinfo(host, NULL, &hints, &ai);
783 if (ai->ai_canonname != NULL)
784 host = xstrdup(ai->ai_canonname);
789 /* force lowercase for hostkey matching */
790 if (options.host_key_alias != NULL) {
791 for (p = options.host_key_alias; *p; p++)
793 *p = (char)tolower(*p);
796 if (options.proxy_command != NULL &&
797 strcmp(options.proxy_command, "none") == 0) {
798 xfree(options.proxy_command);
799 options.proxy_command = NULL;
801 if (options.control_path != NULL &&
802 strcmp(options.control_path, "none") == 0) {
803 xfree(options.control_path);
804 options.control_path = NULL;
807 if (options.control_path != NULL) {
808 cp = tilde_expand_filename(options.control_path,
810 xfree(options.control_path);
811 options.control_path = percent_expand(cp, "h", host,
812 "l", thishost, "n", host_arg, "r", options.user,
813 "p", portstr, "u", pw->pw_name, "L", shorthost,
817 if (muxclient_command != 0 && options.control_path == NULL)
818 fatal("No ControlPath specified for \"-O\" command");
819 if (options.control_path != NULL)
820 muxclient(options.control_path);
822 timeout_ms = options.connection_timeout * 1000;
824 /* Open a connection to the remote host. */
825 if (ssh_connect(host, &hostaddr, options.port,
826 options.address_family, options.connection_attempts, &timeout_ms,
827 options.tcp_keep_alive,
829 options.use_privileged_port,
831 original_effective_uid == 0 && options.use_privileged_port,
833 options.proxy_command) != 0)
837 debug3("timeout: %d ms remain after connect", timeout_ms);
840 * If we successfully made the connection, load the host private key
841 * in case we will need it later for combined rsa-rhosts
842 * authentication. This must be done before releasing extra
843 * privileges, because the file is only readable by root.
844 * If we cannot access the private keys, load the public keys
845 * instead and try to execute the ssh-keysign helper instead.
847 sensitive_data.nkeys = 0;
848 sensitive_data.keys = NULL;
849 sensitive_data.external_keysign = 0;
850 if (options.rhosts_rsa_authentication ||
851 options.hostbased_authentication) {
852 sensitive_data.nkeys = 7;
853 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
855 for (i = 0; i < sensitive_data.nkeys; i++)
856 sensitive_data.keys[i] = NULL;
859 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
860 _PATH_HOST_KEY_FILE, "", NULL, NULL);
861 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
862 _PATH_HOST_DSA_KEY_FILE, "", NULL);
863 #ifdef OPENSSL_HAS_ECC
864 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
865 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
867 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
868 _PATH_HOST_RSA_KEY_FILE, "", NULL);
869 sensitive_data.keys[4] = key_load_private_type(KEY_DSA,
870 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
871 #ifdef OPENSSL_HAS_ECC
872 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
873 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
875 sensitive_data.keys[6] = key_load_private_type(KEY_RSA,
876 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
879 if (options.hostbased_authentication == 1 &&
880 sensitive_data.keys[0] == NULL &&
881 sensitive_data.keys[4] == NULL &&
882 sensitive_data.keys[5] == NULL &&
883 sensitive_data.keys[6] == NULL) {
884 sensitive_data.keys[1] = key_load_cert(
885 _PATH_HOST_DSA_KEY_FILE);
886 #ifdef OPENSSL_HAS_ECC
887 sensitive_data.keys[2] = key_load_cert(
888 _PATH_HOST_ECDSA_KEY_FILE);
890 sensitive_data.keys[3] = key_load_cert(
891 _PATH_HOST_RSA_KEY_FILE);
892 sensitive_data.keys[4] = key_load_public(
893 _PATH_HOST_DSA_KEY_FILE, NULL);
894 #ifdef OPENSSL_HAS_ECC
895 sensitive_data.keys[5] = key_load_public(
896 _PATH_HOST_ECDSA_KEY_FILE, NULL);
898 sensitive_data.keys[6] = key_load_public(
899 _PATH_HOST_RSA_KEY_FILE, NULL);
900 sensitive_data.external_keysign = 1;
904 * Get rid of any extra privileges that we may have. We will no
905 * longer need them. Also, extra privileges could make it very hard
906 * to read identity files and other non-world-readable files from the
907 * user's home directory if it happens to be on a NFS volume where
908 * root is mapped to nobody.
910 if (original_effective_uid == 0) {
912 permanently_set_uid(pw);
916 * Now that we are back to our own permissions, create ~/.ssh
917 * directory if it doesn't already exist.
919 if (config == NULL) {
920 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
921 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
922 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
924 ssh_selinux_setfscreatecon(buf);
926 if (mkdir(buf, 0700) < 0)
927 error("Could not create directory '%.200s'.",
930 ssh_selinux_setfscreatecon(NULL);
934 /* load options.identity_files */
935 load_public_identity_files();
937 /* Expand ~ in known host file names. */
938 tilde_expand_paths(options.system_hostfiles,
939 options.num_system_hostfiles);
940 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
942 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
943 signal(SIGCHLD, main_sigchld_handler);
945 /* Log into the remote system. Never returns if the login fails. */
946 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
947 options.port, pw, timeout_ms);
949 if (packet_connection_is_on_socket()) {
950 verbose("Authenticated to %s ([%s]:%d).", host,
951 get_remote_ipaddr(), get_remote_port());
953 verbose("Authenticated to %s (via proxy).", host);
956 /* We no longer need the private host keys. Clear them now. */
957 if (sensitive_data.nkeys != 0) {
958 for (i = 0; i < sensitive_data.nkeys; i++) {
959 if (sensitive_data.keys[i] != NULL) {
960 /* Destroys contents safely */
961 debug3("clear hostkey %d", i);
962 key_free(sensitive_data.keys[i]);
963 sensitive_data.keys[i] = NULL;
966 xfree(sensitive_data.keys);
968 for (i = 0; i < options.num_identity_files; i++) {
969 if (options.identity_files[i]) {
970 xfree(options.identity_files[i]);
971 options.identity_files[i] = NULL;
973 if (options.identity_keys[i]) {
974 key_free(options.identity_keys[i]);
975 options.identity_keys[i] = NULL;
979 exit_status = compat20 ? ssh_session2() : ssh_session();
982 if (options.control_path != NULL && muxserver_sock != -1)
983 unlink(options.control_path);
985 /* Kill ProxyCommand if it is running. */
986 ssh_kill_proxy_command();
992 control_persist_detach(void)
997 debug("%s: backgrounding master process", __func__);
1000 * master (current process) into the background, and make the
1001 * foreground process a client of the backgrounded master.
1003 switch ((pid = fork())) {
1005 fatal("%s: fork: %s", __func__, strerror(errno));
1007 /* Child: master process continues mainloop */
1010 /* Parent: set up mux slave to connect to backgrounded master */
1011 debug2("%s: background process is %ld", __func__, (long)pid);
1012 stdin_null_flag = ostdin_null_flag;
1013 options.request_tty = orequest_tty;
1014 tty_flag = otty_flag;
1015 close(muxserver_sock);
1016 muxserver_sock = -1;
1017 options.control_master = SSHCTL_MASTER_NO;
1018 muxclient(options.control_path);
1019 /* muxclient() doesn't return on success. */
1020 fatal("Failed to connect to new control master");
1022 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1023 error("%s: open(\"/dev/null\"): %s", __func__,
1026 if (dup2(devnull, STDIN_FILENO) == -1 ||
1027 dup2(devnull, STDOUT_FILENO) == -1)
1028 error("%s: dup2: %s", __func__, strerror(errno));
1029 if (devnull > STDERR_FILENO)
1032 setproctitle("%s [mux]", options.control_path);
1035 /* Do fork() after authentication. Used by "ssh -f" */
1039 if (need_controlpersist_detach)
1040 control_persist_detach();
1041 debug("forking to background");
1042 fork_after_authentication_flag = 0;
1043 if (daemon(1, 1) < 0)
1044 fatal("daemon() failed: %.200s", strerror(errno));
1047 /* Callback for remote forward global requests */
1049 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1051 Forward *rfwd = (Forward *)ctxt;
1053 /* XXX verbose() on failure? */
1054 debug("remote forward %s for: listen %d, connect %s:%d",
1055 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1056 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1057 if (rfwd->listen_port == 0) {
1058 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1059 rfwd->allocated_port = packet_get_int();
1060 logit("Allocated port %u for remote forward to %s:%d",
1061 rfwd->allocated_port,
1062 rfwd->connect_host, rfwd->connect_port);
1063 channel_update_permitted_opens(rfwd->handle,
1064 rfwd->allocated_port);
1066 channel_update_permitted_opens(rfwd->handle, -1);
1070 if (type == SSH2_MSG_REQUEST_FAILURE) {
1071 if (options.exit_on_forward_failure)
1072 fatal("Error: remote port forwarding failed for "
1073 "listen port %d", rfwd->listen_port);
1075 logit("Warning: remote port forwarding failed for "
1076 "listen port %d", rfwd->listen_port);
1078 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1079 debug("All remote forwarding requests processed");
1080 if (fork_after_authentication_flag)
1086 client_cleanup_stdio_fwd(int id, void *arg)
1088 debug("stdio forwarding: done");
1093 ssh_init_stdio_forwarding(void)
1098 if (stdio_forward_host == NULL)
1101 fatal("stdio forwarding require Protocol 2");
1103 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1105 if ((in = dup(STDIN_FILENO)) < 0 ||
1106 (out = dup(STDOUT_FILENO)) < 0)
1107 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1108 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1109 stdio_forward_port, in, out)) == NULL)
1110 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1111 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1115 ssh_init_forwarding(void)
1120 /* Initiate local TCP/IP port forwardings. */
1121 for (i = 0; i < options.num_local_forwards; i++) {
1122 debug("Local connections to %.200s:%d forwarded to remote "
1123 "address %.200s:%d",
1124 (options.local_forwards[i].listen_host == NULL) ?
1125 (options.gateway_ports ? "*" : "LOCALHOST") :
1126 options.local_forwards[i].listen_host,
1127 options.local_forwards[i].listen_port,
1128 options.local_forwards[i].connect_host,
1129 options.local_forwards[i].connect_port);
1130 success += channel_setup_local_fwd_listener(
1131 options.local_forwards[i].listen_host,
1132 options.local_forwards[i].listen_port,
1133 options.local_forwards[i].connect_host,
1134 options.local_forwards[i].connect_port,
1135 options.gateway_ports);
1137 if (i > 0 && success != i && options.exit_on_forward_failure)
1138 fatal("Could not request local forwarding.");
1139 if (i > 0 && success == 0)
1140 error("Could not request local forwarding.");
1142 /* Initiate remote TCP/IP port forwardings. */
1143 for (i = 0; i < options.num_remote_forwards; i++) {
1144 debug("Remote connections from %.200s:%d forwarded to "
1145 "local address %.200s:%d",
1146 (options.remote_forwards[i].listen_host == NULL) ?
1147 "LOCALHOST" : options.remote_forwards[i].listen_host,
1148 options.remote_forwards[i].listen_port,
1149 options.remote_forwards[i].connect_host,
1150 options.remote_forwards[i].connect_port);
1151 options.remote_forwards[i].handle =
1152 channel_request_remote_forwarding(
1153 options.remote_forwards[i].listen_host,
1154 options.remote_forwards[i].listen_port,
1155 options.remote_forwards[i].connect_host,
1156 options.remote_forwards[i].connect_port);
1157 if (options.remote_forwards[i].handle < 0) {
1158 if (options.exit_on_forward_failure)
1159 fatal("Could not request remote forwarding.");
1161 logit("Warning: Could not request remote "
1164 client_register_global_confirm(ssh_confirm_remote_forward,
1165 &options.remote_forwards[i]);
1169 /* Initiate tunnel forwarding. */
1170 if (options.tun_open != SSH_TUNMODE_NO) {
1171 if (client_request_tun_fwd(options.tun_open,
1172 options.tun_local, options.tun_remote) == -1) {
1173 if (options.exit_on_forward_failure)
1174 fatal("Could not request tunnel forwarding.");
1176 error("Could not request tunnel forwarding.");
1182 check_agent_present(void)
1184 if (options.forward_agent) {
1185 /* Clear agent forwarding if we don't have an agent. */
1186 if (!ssh_agent_present())
1187 options.forward_agent = 0;
1195 int interactive = 0;
1199 const char *display;
1201 /* Enable compression if requested. */
1202 if (options.compression) {
1203 debug("Requesting compression at level %d.",
1204 options.compression_level);
1206 if (options.compression_level < 1 ||
1207 options.compression_level > 9)
1208 fatal("Compression level must be from 1 (fast) to "
1211 /* Send the request. */
1212 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1213 packet_put_int(options.compression_level);
1215 packet_write_wait();
1216 type = packet_read();
1217 if (type == SSH_SMSG_SUCCESS)
1218 packet_start_compression(options.compression_level);
1219 else if (type == SSH_SMSG_FAILURE)
1220 logit("Warning: Remote host refused compression.");
1222 packet_disconnect("Protocol error waiting for "
1223 "compression response.");
1225 /* Allocate a pseudo tty if appropriate. */
1227 debug("Requesting pty.");
1229 /* Start the packet. */
1230 packet_start(SSH_CMSG_REQUEST_PTY);
1232 /* Store TERM in the packet. There is no limit on the
1233 length of the string. */
1234 cp = getenv("TERM");
1237 packet_put_cstring(cp);
1239 /* Store window size in the packet. */
1240 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1241 memset(&ws, 0, sizeof(ws));
1242 packet_put_int((u_int)ws.ws_row);
1243 packet_put_int((u_int)ws.ws_col);
1244 packet_put_int((u_int)ws.ws_xpixel);
1245 packet_put_int((u_int)ws.ws_ypixel);
1247 /* Store tty modes in the packet. */
1248 tty_make_modes(fileno(stdin), NULL);
1250 /* Send the packet, and wait for it to leave. */
1252 packet_write_wait();
1254 /* Read response from the server. */
1255 type = packet_read();
1256 if (type == SSH_SMSG_SUCCESS) {
1259 } else if (type == SSH_SMSG_FAILURE)
1260 logit("Warning: Remote host failed or refused to "
1261 "allocate a pseudo tty.");
1263 packet_disconnect("Protocol error waiting for pty "
1264 "request response.");
1266 /* Request X11 forwarding if enabled and DISPLAY is set. */
1267 display = getenv("DISPLAY");
1268 if (options.forward_x11 && display != NULL) {
1270 /* Get reasonable local authentication information. */
1271 client_x11_get_proto(display, options.xauth_location,
1272 options.forward_x11_trusted,
1273 options.forward_x11_timeout,
1275 /* Request forwarding with authentication spoofing. */
1276 debug("Requesting X11 forwarding with authentication "
1278 x11_request_forwarding_with_spoofing(0, display, proto,
1280 /* Read response from the server. */
1281 type = packet_read();
1282 if (type == SSH_SMSG_SUCCESS) {
1284 } else if (type == SSH_SMSG_FAILURE) {
1285 logit("Warning: Remote host denied X11 forwarding.");
1287 packet_disconnect("Protocol error waiting for X11 "
1291 /* Tell the packet module whether this is an interactive session. */
1292 packet_set_interactive(interactive,
1293 options.ip_qos_interactive, options.ip_qos_bulk);
1295 /* Request authentication agent forwarding if appropriate. */
1296 check_agent_present();
1298 if (options.forward_agent) {
1299 debug("Requesting authentication agent forwarding.");
1300 auth_request_forwarding();
1302 /* Read response from the server. */
1303 type = packet_read();
1305 if (type != SSH_SMSG_SUCCESS)
1306 logit("Warning: Remote host denied authentication agent forwarding.");
1309 /* Initiate port forwardings. */
1310 ssh_init_stdio_forwarding();
1311 ssh_init_forwarding();
1313 /* Execute a local command */
1314 if (options.local_command != NULL &&
1315 options.permit_local_command)
1316 ssh_local_cmd(options.local_command);
1319 * If requested and we are not interested in replies to remote
1320 * forwarding requests, then let ssh continue in the background.
1322 if (fork_after_authentication_flag) {
1323 if (options.exit_on_forward_failure &&
1324 options.num_remote_forwards > 0) {
1325 debug("deferring postauth fork until remote forward "
1326 "confirmation received");
1332 * If a command was specified on the command line, execute the
1333 * command now. Otherwise request the server to start a shell.
1335 if (buffer_len(&command) > 0) {
1336 int len = buffer_len(&command);
1339 debug("Sending command: %.*s", len,
1340 (u_char *)buffer_ptr(&command));
1341 packet_start(SSH_CMSG_EXEC_CMD);
1342 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1344 packet_write_wait();
1346 debug("Requesting shell.");
1347 packet_start(SSH_CMSG_EXEC_SHELL);
1349 packet_write_wait();
1352 /* Enter the interactive session. */
1353 return client_loop(have_tty, tty_flag ?
1354 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1357 /* request pty/x11/agent/tcpfwd/shell for channel */
1359 ssh_session2_setup(int id, int success, void *arg)
1361 extern char **environ;
1362 const char *display;
1363 int interactive = tty_flag;
1366 return; /* No need for error message, channels code sens one */
1368 display = getenv("DISPLAY");
1369 if (options.forward_x11 && display != NULL) {
1371 /* Get reasonable local authentication information. */
1372 client_x11_get_proto(display, options.xauth_location,
1373 options.forward_x11_trusted,
1374 options.forward_x11_timeout, &proto, &data);
1375 /* Request forwarding with authentication spoofing. */
1376 debug("Requesting X11 forwarding with authentication "
1378 x11_request_forwarding_with_spoofing(id, display, proto,
1380 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1381 /* XXX exit_on_forward_failure */
1385 check_agent_present();
1386 if (options.forward_agent) {
1387 debug("Requesting authentication agent forwarding.");
1388 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1392 /* Tell the packet module whether this is an interactive session. */
1393 packet_set_interactive(interactive,
1394 options.ip_qos_interactive, options.ip_qos_bulk);
1396 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1397 NULL, fileno(stdin), &command, environ);
1400 /* open new channel for a session */
1402 ssh_session2_open(void)
1405 int window, packetmax, in, out, err;
1407 if (stdin_null_flag) {
1408 in = open(_PATH_DEVNULL, O_RDONLY);
1410 in = dup(STDIN_FILENO);
1412 out = dup(STDOUT_FILENO);
1413 err = dup(STDERR_FILENO);
1415 if (in < 0 || out < 0 || err < 0)
1416 fatal("dup() in/out/err failed");
1418 /* enable nonblocking unless tty */
1427 * We need to check to see what to do about buffer sizes here.
1428 * - In an HPN to non-HPN connection we want to limit the window size to
1429 * something reasonable in case the far side has the large window bug.
1430 * - In an HPN to HPN connection we want to use the max window size but
1431 * allow the user to override it.
1432 * - Lastly if HPN is disabled then use the ssh standard window size.
1434 * We cannot just do a getsockopt() here and set the ssh window to that
1435 * as in case of autotuning of socket buffers the window would get stuck
1436 * at the initial buffer size, generally less than 96k. Therefore we
1437 * need to set the maximum ssh window size to the maximum HPN buffer
1438 * size unless the user has set TcpRcvBufPoll to no. In that case we
1439 * can just set the window to the minimum of HPN buffer size and TCP
1440 * receive buffer size.
1443 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1445 options.hpn_buffer_size = CHAN_HPN_MIN_WINDOW_DEFAULT;
1447 if (datafellows & SSH_BUG_LARGEWINDOW) {
1448 debug("HPN to Non-HPN Connection");
1449 } else if (options.tcp_rcv_buf_poll <= 0) {
1450 sock_get_rcvbuf(&options.hpn_buffer_size, 0);
1451 debug("HPNBufferSize set to TCP RWIN: %d",
1452 options.hpn_buffer_size);
1453 } else if (options.tcp_rcv_buf > 0) {
1454 sock_get_rcvbuf(&options.hpn_buffer_size,
1455 options.tcp_rcv_buf);
1456 debug("HPNBufferSize set to user TCPRcvBuf: %d",
1457 options.hpn_buffer_size);
1459 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1460 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1461 window = options.hpn_buffer_size;
1463 packetmax = CHAN_SES_PACKET_DEFAULT;
1465 window = CHAN_SES_WINDOW_DEFAULT;
1470 "session", SSH_CHANNEL_OPENING, in, out, err,
1471 window, packetmax, CHAN_EXTENDED_WRITE,
1472 "client-session", /*nonblock*/0);
1473 if (!options.hpn_disabled && options.tcp_rcv_buf_poll > 0) {
1474 c->dynamic_window = 1;
1475 debug("Enabled Dynamic Window Scaling\n");
1478 debug3("ssh_session2_open: channel_new: %d", c->self);
1480 channel_send_open(c->self);
1482 channel_register_open_confirm(c->self,
1483 ssh_session2_setup, NULL);
1493 /* XXX should be pre-session */
1494 if (!options.control_persist)
1495 ssh_init_stdio_forwarding();
1496 ssh_init_forwarding();
1498 /* Start listening for multiplex clients */
1502 * If we are in control persist mode and have a working mux listen
1503 * socket, then prepare to background ourselves and have a foreground
1504 * client attach as a control slave.
1505 * NB. we must save copies of the flags that we override for
1506 * the backgrounding, since we defer attachment of the slave until
1507 * after the connection is fully established (in particular,
1508 * async rfwd replies have been received for ExitOnForwardFailure).
1510 if (options.control_persist && muxserver_sock != -1) {
1511 ostdin_null_flag = stdin_null_flag;
1512 ono_shell_flag = no_shell_flag;
1513 orequest_tty = options.request_tty;
1514 otty_flag = tty_flag;
1515 stdin_null_flag = 1;
1518 if (!fork_after_authentication_flag)
1519 need_controlpersist_detach = 1;
1520 fork_after_authentication_flag = 1;
1523 * ControlPersist mux listen socket setup failed, attempt the
1524 * stdio forward setup that we skipped earlier.
1526 if (options.control_persist && muxserver_sock == -1)
1527 ssh_init_stdio_forwarding();
1529 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1530 id = ssh_session2_open();
1532 /* If we don't expect to open a new session, then disallow it */
1533 if (options.control_master == SSHCTL_MASTER_NO &&
1534 (datafellows & SSH_NEW_OPENSSH)) {
1535 debug("Requesting no-more-sessions@openssh.com");
1536 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1537 packet_put_cstring("no-more-sessions@openssh.com");
1542 /* Execute a local command */
1543 if (options.local_command != NULL &&
1544 options.permit_local_command)
1545 ssh_local_cmd(options.local_command);
1548 * If requested and we are not interested in replies to remote
1549 * forwarding requests, then let ssh continue in the background.
1551 if (fork_after_authentication_flag) {
1552 if (options.exit_on_forward_failure &&
1553 options.num_remote_forwards > 0) {
1554 debug("deferring postauth fork until remote forward "
1555 "confirmation received");
1560 if (options.use_roaming)
1563 return client_loop(tty_flag, tty_flag ?
1564 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1568 load_public_identity_files(void)
1570 char *filename, *cp, thishost[NI_MAXHOST];
1571 char *pwdir = NULL, *pwname = NULL;
1576 char *identity_files[SSH_MAX_IDENTITY_FILES];
1577 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1578 #ifdef ENABLE_PKCS11
1584 bzero(identity_files, sizeof(identity_files));
1585 bzero(identity_keys, sizeof(identity_keys));
1587 #ifdef ENABLE_PKCS11
1588 if (options.pkcs11_provider != NULL &&
1589 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1590 (pkcs11_init(!options.batch_mode) == 0) &&
1591 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1593 for (i = 0; i < nkeys; i++) {
1594 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1598 identity_keys[n_ids] = keys[i];
1599 identity_files[n_ids] =
1600 xstrdup(options.pkcs11_provider); /* XXX */
1605 #endif /* ENABLE_PKCS11 */
1606 if ((pw = getpwuid(original_real_uid)) == NULL)
1607 fatal("load_public_identity_files: getpwuid failed");
1608 pwname = xstrdup(pw->pw_name);
1609 pwdir = xstrdup(pw->pw_dir);
1610 if (gethostname(thishost, sizeof(thishost)) == -1)
1611 fatal("load_public_identity_files: gethostname: %s",
1613 for (i = 0; i < options.num_identity_files; i++) {
1614 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1615 xfree(options.identity_files[i]);
1618 cp = tilde_expand_filename(options.identity_files[i],
1620 filename = percent_expand(cp, "d", pwdir,
1621 "u", pwname, "l", thishost, "h", host,
1622 "r", options.user, (char *)NULL);
1624 public = key_load_public(filename, NULL);
1625 debug("identity file %s type %d", filename,
1626 public ? public->type : -1);
1627 xfree(options.identity_files[i]);
1628 identity_files[n_ids] = filename;
1629 identity_keys[n_ids] = public;
1631 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1634 /* Try to add the certificate variant too */
1635 xasprintf(&cp, "%s-cert", filename);
1636 public = key_load_public(cp, NULL);
1637 debug("identity file %s type %d", cp,
1638 public ? public->type : -1);
1639 if (public == NULL) {
1643 if (!key_is_cert(public)) {
1644 debug("%s: key %s type %s is not a certificate",
1645 __func__, cp, key_type(public));
1650 identity_keys[n_ids] = public;
1651 /* point to the original path, most likely the private key */
1652 identity_files[n_ids] = xstrdup(filename);
1655 options.num_identity_files = n_ids;
1656 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1657 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1659 bzero(pwname, strlen(pwname));
1661 bzero(pwdir, strlen(pwdir));
1666 main_sigchld_handler(int sig)
1668 int save_errno = errno;
1672 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1673 (pid < 0 && errno == EINTR))
1676 signal(sig, main_sigchld_handler);