1 /* $OpenBSD: ssh.c,v 1.401 2014/02/26 20:18:37 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>
72 #include <netinet/in.h>
73 #include <arpa/inet.h>
75 #include <openssl/evp.h>
76 #include <openssl/err.h>
77 #include "openbsd-compat/openssl-compat.h"
78 #include "openbsd-compat/sys-queue.h"
93 #include "pathnames.h"
95 #include "clientloop.h"
98 #include "sshconnect.h"
110 #include "ssh-pkcs11.h"
113 extern char *__progname;
115 /* Saves a copy of argv for setproctitle emulation */
116 #ifndef HAVE_SETPROCTITLE
117 static char **saved_av;
120 /* Flag indicating whether debug mode is on. May be set on the command line. */
123 /* Flag indicating whether a tty should be requested */
126 /* don't exec a shell */
127 int no_shell_flag = 0;
130 * Flag indicating that nothing should be read from stdin. This can be set
131 * on the command line.
133 int stdin_null_flag = 0;
136 * Flag indicating that the current process should be backgrounded and
137 * a new slave launched in the foreground for ControlPersist.
139 int need_controlpersist_detach = 0;
141 /* Copies of flags for ControlPersist foreground slave */
142 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
145 * Flag indicating that ssh should fork after authentication. This is useful
146 * so that the passphrase can be entered manually, and then ssh goes to the
149 int fork_after_authentication_flag = 0;
151 /* forward stdio to remote host and port */
152 char *stdio_forward_host = NULL;
153 int stdio_forward_port = 0;
156 * General data structure for command line options and options configurable
157 * in configuration files. See readconf.h.
161 /* optional user configfile */
165 * Name of the host we are connecting to. This is the name given on the
166 * command line, or the HostName specified for the user-supplied name in a
167 * configuration file.
171 /* socket address the host resolves to */
172 struct sockaddr_storage hostaddr;
174 /* Private host keys. */
175 Sensitive sensitive_data;
177 /* Original real UID. */
178 uid_t original_real_uid;
179 uid_t original_effective_uid;
181 /* command to be executed */
184 /* Should we execute a command or invoke a subsystem? */
185 int subsystem_flag = 0;
187 /* # of replies received for global requests */
188 static int remote_forward_confirms_received = 0;
191 extern int muxserver_sock;
192 extern u_int muxclient_command;
194 /* Prints a help message to the user. This function never returns. */
200 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
201 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
202 " [-F configfile] [-I pkcs11] [-i identity_file]\n"
203 " [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]\n"
204 " [-O ctl_cmd] [-o option] [-p port]\n"
205 " [-Q cipher | cipher-auth | mac | kex | key]\n"
206 " [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]\n"
207 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
212 static int ssh_session(void);
213 static int ssh_session2(void);
214 static void load_public_identity_files(void);
215 static void main_sigchld_handler(int);
217 /* from muxclient.c */
218 void muxclient(const char *);
219 void muxserver_listen(void);
221 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
223 tilde_expand_paths(char **paths, u_int num_paths)
228 for (i = 0; i < num_paths; i++) {
229 cp = tilde_expand_filename(paths[i], original_real_uid);
236 * Attempt to resolve a host name / port to a set of addresses and
237 * optionally return any CNAMEs encountered along the way.
238 * Returns NULL on failure.
239 * NB. this function must operate with a options having undefined members.
241 static struct addrinfo *
242 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
244 char strport[NI_MAXSERV];
245 struct addrinfo hints, *res;
246 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
249 port = default_ssh_port();
251 snprintf(strport, sizeof strport, "%u", port);
252 memset(&hints, 0, sizeof(hints));
253 hints.ai_family = options.address_family == -1 ?
254 AF_UNSPEC : options.address_family;
255 hints.ai_socktype = SOCK_STREAM;
257 hints.ai_flags = AI_CANONNAME;
258 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
259 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
260 loglevel = SYSLOG_LEVEL_ERROR;
261 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
262 __progname, name, ssh_gai_strerror(gaierr));
265 if (cname != NULL && res->ai_canonname != NULL) {
266 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
267 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
268 __func__, name, res->ai_canonname, (u_long)clen);
277 * Check whether the cname is a permitted replacement for the hostname
278 * and perform the replacement if it is.
279 * NB. this function must operate with a options having undefined members.
282 check_follow_cname(char **namep, const char *cname)
285 struct allowed_cname *rule;
287 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
288 strcmp(*namep, cname) == 0)
290 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
293 * Don't attempt to canonicalize names that will be interpreted by
294 * a proxy unless the user specifically requests so.
296 if (!option_clear_or_none(options.proxy_command) &&
297 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
299 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
300 for (i = 0; i < options.num_permitted_cnames; i++) {
301 rule = options.permitted_cnames + i;
302 if (match_pattern_list(*namep, rule->source_list,
303 strlen(rule->source_list), 1) != 1 ||
304 match_pattern_list(cname, rule->target_list,
305 strlen(rule->target_list), 1) != 1)
307 verbose("Canonicalized DNS aliased hostname "
308 "\"%s\" => \"%s\"", *namep, cname);
310 *namep = xstrdup(cname);
317 * Attempt to resolve the supplied hostname after applying the user's
318 * canonicalization rules. Returns the address list for the host or NULL
319 * if no name was found after canonicalization.
320 * NB. this function must operate with a options having undefined members.
322 static struct addrinfo *
323 resolve_canonicalize(char **hostp, int port)
326 char *cp, *fullhost, cname_target[NI_MAXHOST];
327 struct addrinfo *addrs;
329 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
333 * Don't attempt to canonicalize names that will be interpreted by
334 * a proxy unless the user specifically requests so.
336 if (!option_clear_or_none(options.proxy_command) &&
337 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
340 /* Don't apply canonicalization to sufficiently-qualified hostnames */
342 for (cp = *hostp; *cp != '\0'; cp++) {
346 if (ndots > options.canonicalize_max_dots) {
347 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
348 __func__, *hostp, options.canonicalize_max_dots);
351 /* Attempt each supplied suffix */
352 for (i = 0; i < options.num_canonical_domains; i++) {
353 *cname_target = '\0';
354 xasprintf(&fullhost, "%s.%s.", *hostp,
355 options.canonical_domains[i]);
356 debug3("%s: attempting \"%s\" => \"%s\"", __func__,
358 if ((addrs = resolve_host(fullhost, port, 0,
359 cname_target, sizeof(cname_target))) == NULL) {
363 /* Remove trailing '.' */
364 fullhost[strlen(fullhost) - 1] = '\0';
365 /* Follow CNAME if requested */
366 if (!check_follow_cname(&fullhost, cname_target)) {
367 debug("Canonicalized hostname \"%s\" => \"%s\"",
374 if (!options.canonicalize_fallback_local)
375 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
376 debug2("%s: host %s not found in any suffix", __func__, *hostp);
381 * Read per-user configuration file. Ignore the system wide config
382 * file if the user specifies a config file on the command line.
385 process_config_files(struct passwd *pw)
387 char buf[MAXPATHLEN];
390 if (config != NULL) {
391 if (strcasecmp(config, "none") != 0 &&
392 !read_config_file(config, pw, host, &options,
394 fatal("Can't open user config file %.100s: "
395 "%.100s", config, strerror(errno));
397 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
398 _PATH_SSH_USER_CONFFILE);
399 if (r > 0 && (size_t)r < sizeof(buf))
400 (void)read_config_file(buf, pw, host, &options,
401 SSHCONF_CHECKPERM|SSHCONF_USERCONF);
403 /* Read systemwide configuration file after user config. */
404 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host,
410 * Main program for the ssh client.
413 main(int ac, char **av)
415 int i, r, opt, exit_status, use_syslog;
416 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile;
417 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
418 char cname[NI_MAXHOST];
422 extern int optind, optreset;
425 struct addrinfo *addrs = NULL;
427 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
430 __progname = ssh_get_progname(av[0]);
432 #ifndef HAVE_SETPROCTITLE
433 /* Prepare for later setproctitle emulation */
434 /* Save argv so it isn't clobbered by setproctitle() emulation */
435 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
436 for (i = 0; i < ac; i++)
437 saved_av[i] = xstrdup(av[i]);
439 compat_init_setproctitle(ac, av);
444 * Discard other fds that are hanging around. These can cause problem
445 * with backgrounded ssh processes started by ControlPersist.
447 closefrom(STDERR_FILENO + 1);
450 * Save the original real uid. It will be needed later (uid-swapping
451 * may clobber the real uid).
453 original_real_uid = getuid();
454 original_effective_uid = geteuid();
457 * Use uid-swapping to give up root privileges for the duration of
458 * option processing. We will re-instantiate the rights when we are
459 * ready to create the privileged port, and will permanently drop
460 * them when the port has been created (actually, when the connection
461 * has been made, as we may need to create the port several times).
465 #ifdef HAVE_SETRLIMIT
466 /* If we are installed setuid root be careful to not drop core. */
467 if (original_real_uid != original_effective_uid) {
469 rlim.rlim_cur = rlim.rlim_max = 0;
470 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
471 fatal("setrlimit failed: %.100s", strerror(errno));
475 pw = getpwuid(original_real_uid);
477 logit("No user exists for uid %lu", (u_long)original_real_uid);
480 /* Take a copy of the returned structure. */
484 * Set our umask to something reasonable, as some files are created
485 * with the default umask. This will make them world-readable but
486 * writable only by the owner, which is ok for all files for which we
487 * don't set the modes explicitly.
492 * Initialize option structure to indicate that no values have been
495 initialize_options(&options);
497 /* Parse command-line arguments. */
504 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
505 "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
508 options.protocol = SSH_PROTO_1;
511 options.protocol = SSH_PROTO_2;
514 options.address_family = AF_INET;
517 options.address_family = AF_INET6;
523 fork_after_authentication_flag = 1;
527 options.forward_x11 = 0;
530 options.forward_x11 = 1;
536 logfile = xstrdup(optarg);
539 options.forward_x11 = 1;
540 options.forward_x11_trusted = 1;
543 options.gateway_ports = 1;
546 if (stdio_forward_host != NULL)
547 fatal("Cannot specify multiplexing "
549 else if (muxclient_command != 0)
550 fatal("Multiplexing command already specified");
551 if (strcmp(optarg, "check") == 0)
552 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
553 else if (strcmp(optarg, "forward") == 0)
554 muxclient_command = SSHMUX_COMMAND_FORWARD;
555 else if (strcmp(optarg, "exit") == 0)
556 muxclient_command = SSHMUX_COMMAND_TERMINATE;
557 else if (strcmp(optarg, "stop") == 0)
558 muxclient_command = SSHMUX_COMMAND_STOP;
559 else if (strcmp(optarg, "cancel") == 0)
560 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
562 fatal("Invalid multiplex command.");
564 case 'P': /* deprecated */
565 options.use_privileged_port = 0;
569 if (strcmp(optarg, "cipher") == 0)
570 cp = cipher_alg_list('\n', 0);
571 else if (strcmp(optarg, "cipher-auth") == 0)
572 cp = cipher_alg_list('\n', 1);
573 else if (strcmp(optarg, "mac") == 0)
574 cp = mac_alg_list('\n');
575 else if (strcmp(optarg, "kex") == 0)
576 cp = kex_alg_list('\n');
577 else if (strcmp(optarg, "key") == 0)
578 cp = key_alg_list(0, 0);
579 else if (strcmp(optarg, "key-cert") == 0)
580 cp = key_alg_list(1, 0);
581 else if (strcmp(optarg, "key-plain") == 0)
582 cp = key_alg_list(0, 1);
584 fatal("Unsupported query \"%s\"", optarg);
590 options.forward_agent = 0;
593 options.forward_agent = 1;
596 options.gss_deleg_creds = 0;
599 options.gss_authentication = 1;
600 options.gss_deleg_creds = 1;
603 if (stat(optarg, &st) < 0) {
604 fprintf(stderr, "Warning: Identity file %s "
605 "not accessible: %s.\n", optarg,
609 add_identity_file(&options, NULL, optarg, 1);
613 options.pkcs11_provider = xstrdup(optarg);
615 fprintf(stderr, "no support for PKCS#11.\n");
619 if (options.request_tty == REQUEST_TTY_YES)
620 options.request_tty = REQUEST_TTY_FORCE;
622 options.request_tty = REQUEST_TTY_YES;
625 if (debug_flag == 0) {
627 options.log_level = SYSLOG_LEVEL_DEBUG1;
629 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
634 if (options.version_addendum &&
635 *options.version_addendum != '\0')
636 fprintf(stderr, "%s %s, %s\n", SSH_RELEASE,
637 options.version_addendum,
638 SSLeay_version(SSLEAY_VERSION));
640 fprintf(stderr, "%s, %s\n", SSH_RELEASE,
641 SSLeay_version(SSLEAY_VERSION));
646 if (options.tun_open == -1)
647 options.tun_open = SSH_TUNMODE_DEFAULT;
648 options.tun_local = a2tun(optarg, &options.tun_remote);
649 if (options.tun_local == SSH_TUNID_ERR) {
651 "Bad tun device '%s'\n", optarg);
656 if (stdio_forward_host != NULL)
657 fatal("stdio forward already specified");
658 if (muxclient_command != 0)
659 fatal("Cannot specify stdio forward with -O");
660 if (parse_forward(&fwd, optarg, 1, 0)) {
661 stdio_forward_host = fwd.listen_host;
662 stdio_forward_port = fwd.listen_port;
663 free(fwd.connect_host);
666 "Bad stdio forwarding specification '%s'\n",
670 options.request_tty = REQUEST_TTY_NO;
672 options.clear_forwardings = 1;
673 options.exit_on_forward_failure = 1;
676 options.log_level = SYSLOG_LEVEL_QUIET;
679 if (optarg[0] == '^' && optarg[2] == 0 &&
680 (u_char) optarg[1] >= 64 &&
681 (u_char) optarg[1] < 128)
682 options.escape_char = (u_char) optarg[1] & 31;
683 else if (strlen(optarg) == 1)
684 options.escape_char = (u_char) optarg[0];
685 else if (strcmp(optarg, "none") == 0)
686 options.escape_char = SSH_ESCAPECHAR_NONE;
688 fprintf(stderr, "Bad escape character '%s'.\n",
694 if (ciphers_valid(optarg)) {
696 options.ciphers = xstrdup(optarg);
697 options.cipher = SSH_CIPHER_INVALID;
700 options.cipher = cipher_number(optarg);
701 if (options.cipher == -1) {
703 "Unknown cipher type '%s'\n",
707 if (options.cipher == SSH_CIPHER_3DES)
708 options.ciphers = "3des-cbc";
709 else if (options.cipher == SSH_CIPHER_BLOWFISH)
710 options.ciphers = "blowfish-cbc";
712 options.ciphers = (char *)-1;
716 if (mac_valid(optarg))
717 options.macs = xstrdup(optarg);
719 fprintf(stderr, "Unknown mac type '%s'\n",
725 if (options.control_master == SSHCTL_MASTER_YES)
726 options.control_master = SSHCTL_MASTER_ASK;
728 options.control_master = SSHCTL_MASTER_YES;
731 options.port = a2port(optarg);
732 if (options.port <= 0) {
733 fprintf(stderr, "Bad port '%s'\n", optarg);
738 options.user = optarg;
742 if (parse_forward(&fwd, optarg, 0, 0))
743 add_local_forward(&options, &fwd);
746 "Bad local forwarding specification '%s'\n",
753 if (parse_forward(&fwd, optarg, 0, 1)) {
754 add_remote_forward(&options, &fwd);
757 "Bad remote forwarding specification "
764 if (parse_forward(&fwd, optarg, 1, 0)) {
765 add_local_forward(&options, &fwd);
768 "Bad dynamic forwarding specification "
775 options.compression = 1;
779 options.request_tty = REQUEST_TTY_NO;
782 options.request_tty = REQUEST_TTY_NO;
785 line = xstrdup(optarg);
786 if (process_config_line(&options, pw, host ? host : "",
787 line, "command-line", 0, NULL, SSHCONF_USERCONF)
796 if (options.control_path != NULL)
797 free(options.control_path);
798 options.control_path = xstrdup(optarg);
801 options.bind_address = optarg;
814 if (ac > 0 && !host) {
815 if (strrchr(*av, '@')) {
817 cp = strrchr(p, '@');
818 if (cp == NULL || cp == p)
822 host = xstrdup(++cp);
826 optind = optreset = 1;
832 /* Check that we got a host name. */
836 host_arg = xstrdup(host);
838 OpenSSL_add_all_algorithms();
839 ERR_load_crypto_strings();
841 /* Initialize the command to execute on remote host. */
842 buffer_init(&command);
845 * Save the command to execute on the remote host in a buffer. There
846 * is no limit on the length of the command, except by the maximum
847 * packet size. Also sets the tty flag if there is no command.
850 /* No command specified - execute shell on a tty. */
851 if (subsystem_flag) {
853 "You must specify a subsystem to invoke.\n");
857 /* A command has been specified. Store it into the buffer. */
858 for (i = 0; i < ac; i++) {
860 buffer_append(&command, " ", 1);
861 buffer_append(&command, av[i], strlen(av[i]));
865 /* Cannot fork to background if no command. */
866 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
868 fatal("Cannot fork into background without a command "
872 * Initialize "log" output. Since we are the client all output
873 * goes to stderr unless otherwise specified by -y or -E.
875 if (use_syslog && logfile != NULL)
876 fatal("Can't specify both -y and -E");
877 if (logfile != NULL) {
878 log_redirect_stderr_to(logfile);
882 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
883 SYSLOG_FACILITY_USER, !use_syslog);
886 logit("%s, %s", SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
888 /* Parse the configuration files */
889 process_config_files(pw);
891 /* Hostname canonicalisation needs a few options filled. */
892 fill_default_options_for_canonicalization(&options);
894 /* If the user has replaced the hostname then take it into use now */
895 if (options.hostname != NULL) {
896 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
897 cp = percent_expand(options.hostname,
898 "h", host, (char *)NULL);
903 /* If canonicalization requested then try to apply it */
905 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
906 addrs = resolve_canonicalize(&host, options.port);
909 * If CanonicalizePermittedCNAMEs have been specified but
910 * other canonicalization did not happen (by not being requested
911 * or by failing with fallback) then the hostname may still be changed
912 * as a result of CNAME following.
914 * Try to resolve the bare hostname name using the system resolver's
915 * usual search rules and then apply the CNAME follow rules.
917 * Skip the lookup if a ProxyCommand is being used unless the user
918 * has specifically requested canonicalisation for this case via
919 * CanonicalizeHostname=always
921 if (addrs == NULL && options.num_permitted_cnames != 0 &&
922 (option_clear_or_none(options.proxy_command) ||
923 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
924 if ((addrs = resolve_host(host, options.port, 1,
925 cname, sizeof(cname))) == NULL)
926 cleanup_exit(255); /* resolve_host logs the error */
927 check_follow_cname(&host, cname);
931 * If the target hostname has changed as a result of canonicalisation
932 * then re-parse the configuration files as new stanzas may match.
934 if (strcasecmp(host_arg, host) != 0) {
935 debug("Hostname has changed; re-reading configuration");
936 process_config_files(pw);
939 /* Fill configuration defaults. */
940 fill_default_options(&options);
942 if (options.port == 0)
943 options.port = default_ssh_port();
944 channel_set_af(options.address_family);
946 /* Tidy and check options */
947 if (options.host_key_alias != NULL)
948 lowercase(options.host_key_alias);
949 if (options.proxy_command != NULL &&
950 strcmp(options.proxy_command, "-") == 0 &&
951 options.proxy_use_fdpass)
952 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
954 if (original_effective_uid != 0)
955 options.use_privileged_port = 0;
959 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
961 if (options.request_tty == REQUEST_TTY_YES ||
962 options.request_tty == REQUEST_TTY_FORCE)
965 /* Allocate a tty by default if no command specified. */
966 if (buffer_len(&command) == 0)
967 tty_flag = options.request_tty != REQUEST_TTY_NO;
970 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
972 /* Do not allocate a tty if stdin is not a tty. */
973 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
974 options.request_tty != REQUEST_TTY_FORCE) {
976 logit("Pseudo-terminal will not be allocated because "
977 "stdin is not a terminal.");
983 if (options.user == NULL)
984 options.user = xstrdup(pw->pw_name);
986 if (gethostname(thishost, sizeof(thishost)) == -1)
987 fatal("gethostname: %s", strerror(errno));
988 strlcpy(shorthost, thishost, sizeof(shorthost));
989 shorthost[strcspn(thishost, ".")] = '\0';
990 snprintf(portstr, sizeof(portstr), "%d", options.port);
992 /* Find canonic host name. */
993 if (strchr(host, '.') == 0) {
994 struct addrinfo hints;
995 struct addrinfo *ai = NULL;
997 memset(&hints, 0, sizeof(hints));
998 hints.ai_family = options.address_family;
999 hints.ai_flags = AI_CANONNAME;
1000 hints.ai_socktype = SOCK_STREAM;
1001 errgai = getaddrinfo(host, NULL, &hints, &ai);
1003 if (ai->ai_canonname != NULL)
1004 host = xstrdup(ai->ai_canonname);
1009 if (options.local_command != NULL) {
1010 debug3("expanding LocalCommand: %s", options.local_command);
1011 cp = options.local_command;
1012 options.local_command = percent_expand(cp, "d", pw->pw_dir,
1013 "h", host, "l", thishost, "n", host_arg, "r", options.user,
1014 "p", portstr, "u", pw->pw_name, "L", shorthost,
1016 debug3("expanded LocalCommand: %s", options.local_command);
1020 if (options.control_path != NULL) {
1021 cp = tilde_expand_filename(options.control_path,
1023 free(options.control_path);
1024 options.control_path = percent_expand(cp, "h", host,
1025 "l", thishost, "n", host_arg, "r", options.user,
1026 "p", portstr, "u", pw->pw_name, "L", shorthost,
1030 if (muxclient_command != 0 && options.control_path == NULL)
1031 fatal("No ControlPath specified for \"-O\" command");
1032 if (options.control_path != NULL)
1033 muxclient(options.control_path);
1036 * If hostname canonicalisation was not enabled, then we may not
1037 * have yet resolved the hostname. Do so now.
1039 if (addrs == NULL && options.proxy_command == NULL) {
1040 if ((addrs = resolve_host(host, options.port, 1,
1041 cname, sizeof(cname))) == NULL)
1042 cleanup_exit(255); /* resolve_host logs the error */
1045 timeout_ms = options.connection_timeout * 1000;
1047 /* Open a connection to the remote host. */
1048 if (ssh_connect(host, addrs, &hostaddr, options.port,
1049 options.address_family, options.connection_attempts,
1050 &timeout_ms, options.tcp_keep_alive,
1051 options.use_privileged_port) != 0)
1055 freeaddrinfo(addrs);
1057 packet_set_timeout(options.server_alive_interval,
1058 options.server_alive_count_max);
1061 debug3("timeout: %d ms remain after connect", timeout_ms);
1064 * If we successfully made the connection, load the host private key
1065 * in case we will need it later for combined rsa-rhosts
1066 * authentication. This must be done before releasing extra
1067 * privileges, because the file is only readable by root.
1068 * If we cannot access the private keys, load the public keys
1069 * instead and try to execute the ssh-keysign helper instead.
1071 sensitive_data.nkeys = 0;
1072 sensitive_data.keys = NULL;
1073 sensitive_data.external_keysign = 0;
1074 if (options.rhosts_rsa_authentication ||
1075 options.hostbased_authentication) {
1076 sensitive_data.nkeys = 9;
1077 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1079 for (i = 0; i < sensitive_data.nkeys; i++)
1080 sensitive_data.keys[i] = NULL;
1083 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1084 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1085 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
1086 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1087 #ifdef OPENSSL_HAS_ECC
1088 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
1089 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1091 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1092 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1093 sensitive_data.keys[4] = key_load_private_cert(KEY_ED25519,
1094 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1095 sensitive_data.keys[5] = key_load_private_type(KEY_DSA,
1096 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1097 #ifdef OPENSSL_HAS_ECC
1098 sensitive_data.keys[6] = key_load_private_type(KEY_ECDSA,
1099 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1101 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1102 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1103 sensitive_data.keys[8] = key_load_private_type(KEY_ED25519,
1104 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1107 if (options.hostbased_authentication == 1 &&
1108 sensitive_data.keys[0] == NULL &&
1109 sensitive_data.keys[5] == NULL &&
1110 sensitive_data.keys[6] == NULL &&
1111 sensitive_data.keys[7] == NULL &&
1112 sensitive_data.keys[8] == NULL) {
1113 sensitive_data.keys[1] = key_load_cert(
1114 _PATH_HOST_DSA_KEY_FILE);
1115 #ifdef OPENSSL_HAS_ECC
1116 sensitive_data.keys[2] = key_load_cert(
1117 _PATH_HOST_ECDSA_KEY_FILE);
1119 sensitive_data.keys[3] = key_load_cert(
1120 _PATH_HOST_RSA_KEY_FILE);
1121 sensitive_data.keys[4] = key_load_cert(
1122 _PATH_HOST_ED25519_KEY_FILE);
1123 sensitive_data.keys[5] = key_load_public(
1124 _PATH_HOST_DSA_KEY_FILE, NULL);
1125 #ifdef OPENSSL_HAS_ECC
1126 sensitive_data.keys[6] = key_load_public(
1127 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1129 sensitive_data.keys[7] = key_load_public(
1130 _PATH_HOST_RSA_KEY_FILE, NULL);
1131 sensitive_data.keys[8] = key_load_public(
1132 _PATH_HOST_ED25519_KEY_FILE, NULL);
1133 sensitive_data.external_keysign = 1;
1137 * Get rid of any extra privileges that we may have. We will no
1138 * longer need them. Also, extra privileges could make it very hard
1139 * to read identity files and other non-world-readable files from the
1140 * user's home directory if it happens to be on a NFS volume where
1141 * root is mapped to nobody.
1143 if (original_effective_uid == 0) {
1145 permanently_set_uid(pw);
1149 * Now that we are back to our own permissions, create ~/.ssh
1150 * directory if it doesn't already exist.
1152 if (config == NULL) {
1153 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1154 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1155 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1157 ssh_selinux_setfscreatecon(buf);
1159 if (mkdir(buf, 0700) < 0)
1160 error("Could not create directory '%.200s'.",
1163 ssh_selinux_setfscreatecon(NULL);
1167 /* load options.identity_files */
1168 load_public_identity_files();
1170 /* Expand ~ in known host file names. */
1171 tilde_expand_paths(options.system_hostfiles,
1172 options.num_system_hostfiles);
1173 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1175 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1176 signal(SIGCHLD, main_sigchld_handler);
1178 /* Log into the remote system. Never returns if the login fails. */
1179 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1180 options.port, pw, timeout_ms);
1182 if (packet_connection_is_on_socket()) {
1183 verbose("Authenticated to %s ([%s]:%d).", host,
1184 get_remote_ipaddr(), get_remote_port());
1186 verbose("Authenticated to %s (via proxy).", host);
1189 /* We no longer need the private host keys. Clear them now. */
1190 if (sensitive_data.nkeys != 0) {
1191 for (i = 0; i < sensitive_data.nkeys; i++) {
1192 if (sensitive_data.keys[i] != NULL) {
1193 /* Destroys contents safely */
1194 debug3("clear hostkey %d", i);
1195 key_free(sensitive_data.keys[i]);
1196 sensitive_data.keys[i] = NULL;
1199 free(sensitive_data.keys);
1201 for (i = 0; i < options.num_identity_files; i++) {
1202 free(options.identity_files[i]);
1203 options.identity_files[i] = NULL;
1204 if (options.identity_keys[i]) {
1205 key_free(options.identity_keys[i]);
1206 options.identity_keys[i] = NULL;
1210 exit_status = compat20 ? ssh_session2() : ssh_session();
1213 if (options.control_path != NULL && muxserver_sock != -1)
1214 unlink(options.control_path);
1216 /* Kill ProxyCommand if it is running. */
1217 ssh_kill_proxy_command();
1223 control_persist_detach(void)
1228 debug("%s: backgrounding master process", __func__);
1231 * master (current process) into the background, and make the
1232 * foreground process a client of the backgrounded master.
1234 switch ((pid = fork())) {
1236 fatal("%s: fork: %s", __func__, strerror(errno));
1238 /* Child: master process continues mainloop */
1241 /* Parent: set up mux slave to connect to backgrounded master */
1242 debug2("%s: background process is %ld", __func__, (long)pid);
1243 stdin_null_flag = ostdin_null_flag;
1244 options.request_tty = orequest_tty;
1245 tty_flag = otty_flag;
1246 close(muxserver_sock);
1247 muxserver_sock = -1;
1248 options.control_master = SSHCTL_MASTER_NO;
1249 muxclient(options.control_path);
1250 /* muxclient() doesn't return on success. */
1251 fatal("Failed to connect to new control master");
1253 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1254 error("%s: open(\"/dev/null\"): %s", __func__,
1257 if (dup2(devnull, STDIN_FILENO) == -1 ||
1258 dup2(devnull, STDOUT_FILENO) == -1)
1259 error("%s: dup2: %s", __func__, strerror(errno));
1260 if (devnull > STDERR_FILENO)
1264 setproctitle("%s [mux]", options.control_path);
1267 /* Do fork() after authentication. Used by "ssh -f" */
1271 if (need_controlpersist_detach)
1272 control_persist_detach();
1273 debug("forking to background");
1274 fork_after_authentication_flag = 0;
1275 if (daemon(1, 1) < 0)
1276 fatal("daemon() failed: %.200s", strerror(errno));
1279 /* Callback for remote forward global requests */
1281 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1283 Forward *rfwd = (Forward *)ctxt;
1285 /* XXX verbose() on failure? */
1286 debug("remote forward %s for: listen %d, connect %s:%d",
1287 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1288 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1289 if (rfwd->listen_port == 0) {
1290 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1291 rfwd->allocated_port = packet_get_int();
1292 logit("Allocated port %u for remote forward to %s:%d",
1293 rfwd->allocated_port,
1294 rfwd->connect_host, rfwd->connect_port);
1295 channel_update_permitted_opens(rfwd->handle,
1296 rfwd->allocated_port);
1298 channel_update_permitted_opens(rfwd->handle, -1);
1302 if (type == SSH2_MSG_REQUEST_FAILURE) {
1303 if (options.exit_on_forward_failure)
1304 fatal("Error: remote port forwarding failed for "
1305 "listen port %d", rfwd->listen_port);
1307 logit("Warning: remote port forwarding failed for "
1308 "listen port %d", rfwd->listen_port);
1310 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1311 debug("All remote forwarding requests processed");
1312 if (fork_after_authentication_flag)
1318 client_cleanup_stdio_fwd(int id, void *arg)
1320 debug("stdio forwarding: done");
1325 ssh_init_stdio_forwarding(void)
1330 if (stdio_forward_host == NULL)
1333 fatal("stdio forwarding require Protocol 2");
1335 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1337 if ((in = dup(STDIN_FILENO)) < 0 ||
1338 (out = dup(STDOUT_FILENO)) < 0)
1339 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1340 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1341 stdio_forward_port, in, out)) == NULL)
1342 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1343 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1347 ssh_init_forwarding(void)
1352 /* Initiate local TCP/IP port forwardings. */
1353 for (i = 0; i < options.num_local_forwards; i++) {
1354 debug("Local connections to %.200s:%d forwarded to remote "
1355 "address %.200s:%d",
1356 (options.local_forwards[i].listen_host == NULL) ?
1357 (options.gateway_ports ? "*" : "LOCALHOST") :
1358 options.local_forwards[i].listen_host,
1359 options.local_forwards[i].listen_port,
1360 options.local_forwards[i].connect_host,
1361 options.local_forwards[i].connect_port);
1362 success += channel_setup_local_fwd_listener(
1363 options.local_forwards[i].listen_host,
1364 options.local_forwards[i].listen_port,
1365 options.local_forwards[i].connect_host,
1366 options.local_forwards[i].connect_port,
1367 options.gateway_ports);
1369 if (i > 0 && success != i && options.exit_on_forward_failure)
1370 fatal("Could not request local forwarding.");
1371 if (i > 0 && success == 0)
1372 error("Could not request local forwarding.");
1374 /* Initiate remote TCP/IP port forwardings. */
1375 for (i = 0; i < options.num_remote_forwards; i++) {
1376 debug("Remote connections from %.200s:%d forwarded to "
1377 "local address %.200s:%d",
1378 (options.remote_forwards[i].listen_host == NULL) ?
1379 "LOCALHOST" : options.remote_forwards[i].listen_host,
1380 options.remote_forwards[i].listen_port,
1381 options.remote_forwards[i].connect_host,
1382 options.remote_forwards[i].connect_port);
1383 options.remote_forwards[i].handle =
1384 channel_request_remote_forwarding(
1385 options.remote_forwards[i].listen_host,
1386 options.remote_forwards[i].listen_port,
1387 options.remote_forwards[i].connect_host,
1388 options.remote_forwards[i].connect_port);
1389 if (options.remote_forwards[i].handle < 0) {
1390 if (options.exit_on_forward_failure)
1391 fatal("Could not request remote forwarding.");
1393 logit("Warning: Could not request remote "
1396 client_register_global_confirm(ssh_confirm_remote_forward,
1397 &options.remote_forwards[i]);
1401 /* Initiate tunnel forwarding. */
1402 if (options.tun_open != SSH_TUNMODE_NO) {
1403 if (client_request_tun_fwd(options.tun_open,
1404 options.tun_local, options.tun_remote) == -1) {
1405 if (options.exit_on_forward_failure)
1406 fatal("Could not request tunnel forwarding.");
1408 error("Could not request tunnel forwarding.");
1414 check_agent_present(void)
1416 if (options.forward_agent) {
1417 /* Clear agent forwarding if we don't have an agent. */
1418 if (!ssh_agent_present())
1419 options.forward_agent = 0;
1427 int interactive = 0;
1431 const char *display;
1433 /* Enable compression if requested. */
1434 if (options.compression) {
1435 debug("Requesting compression at level %d.",
1436 options.compression_level);
1438 if (options.compression_level < 1 ||
1439 options.compression_level > 9)
1440 fatal("Compression level must be from 1 (fast) to "
1443 /* Send the request. */
1444 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1445 packet_put_int(options.compression_level);
1447 packet_write_wait();
1448 type = packet_read();
1449 if (type == SSH_SMSG_SUCCESS)
1450 packet_start_compression(options.compression_level);
1451 else if (type == SSH_SMSG_FAILURE)
1452 logit("Warning: Remote host refused compression.");
1454 packet_disconnect("Protocol error waiting for "
1455 "compression response.");
1457 /* Allocate a pseudo tty if appropriate. */
1459 debug("Requesting pty.");
1461 /* Start the packet. */
1462 packet_start(SSH_CMSG_REQUEST_PTY);
1464 /* Store TERM in the packet. There is no limit on the
1465 length of the string. */
1466 cp = getenv("TERM");
1469 packet_put_cstring(cp);
1471 /* Store window size in the packet. */
1472 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1473 memset(&ws, 0, sizeof(ws));
1474 packet_put_int((u_int)ws.ws_row);
1475 packet_put_int((u_int)ws.ws_col);
1476 packet_put_int((u_int)ws.ws_xpixel);
1477 packet_put_int((u_int)ws.ws_ypixel);
1479 /* Store tty modes in the packet. */
1480 tty_make_modes(fileno(stdin), NULL);
1482 /* Send the packet, and wait for it to leave. */
1484 packet_write_wait();
1486 /* Read response from the server. */
1487 type = packet_read();
1488 if (type == SSH_SMSG_SUCCESS) {
1491 } else if (type == SSH_SMSG_FAILURE)
1492 logit("Warning: Remote host failed or refused to "
1493 "allocate a pseudo tty.");
1495 packet_disconnect("Protocol error waiting for pty "
1496 "request response.");
1498 /* Request X11 forwarding if enabled and DISPLAY is set. */
1499 display = getenv("DISPLAY");
1500 if (options.forward_x11 && display != NULL) {
1502 /* Get reasonable local authentication information. */
1503 client_x11_get_proto(display, options.xauth_location,
1504 options.forward_x11_trusted,
1505 options.forward_x11_timeout,
1507 /* Request forwarding with authentication spoofing. */
1508 debug("Requesting X11 forwarding with authentication "
1510 x11_request_forwarding_with_spoofing(0, display, proto,
1512 /* Read response from the server. */
1513 type = packet_read();
1514 if (type == SSH_SMSG_SUCCESS) {
1516 } else if (type == SSH_SMSG_FAILURE) {
1517 logit("Warning: Remote host denied X11 forwarding.");
1519 packet_disconnect("Protocol error waiting for X11 "
1523 /* Tell the packet module whether this is an interactive session. */
1524 packet_set_interactive(interactive,
1525 options.ip_qos_interactive, options.ip_qos_bulk);
1527 /* Request authentication agent forwarding if appropriate. */
1528 check_agent_present();
1530 if (options.forward_agent) {
1531 debug("Requesting authentication agent forwarding.");
1532 auth_request_forwarding();
1534 /* Read response from the server. */
1535 type = packet_read();
1537 if (type != SSH_SMSG_SUCCESS)
1538 logit("Warning: Remote host denied authentication agent forwarding.");
1541 /* Initiate port forwardings. */
1542 ssh_init_stdio_forwarding();
1543 ssh_init_forwarding();
1545 /* Execute a local command */
1546 if (options.local_command != NULL &&
1547 options.permit_local_command)
1548 ssh_local_cmd(options.local_command);
1551 * If requested and we are not interested in replies to remote
1552 * forwarding requests, then let ssh continue in the background.
1554 if (fork_after_authentication_flag) {
1555 if (options.exit_on_forward_failure &&
1556 options.num_remote_forwards > 0) {
1557 debug("deferring postauth fork until remote forward "
1558 "confirmation received");
1564 * If a command was specified on the command line, execute the
1565 * command now. Otherwise request the server to start a shell.
1567 if (buffer_len(&command) > 0) {
1568 int len = buffer_len(&command);
1571 debug("Sending command: %.*s", len,
1572 (u_char *)buffer_ptr(&command));
1573 packet_start(SSH_CMSG_EXEC_CMD);
1574 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1576 packet_write_wait();
1578 debug("Requesting shell.");
1579 packet_start(SSH_CMSG_EXEC_SHELL);
1581 packet_write_wait();
1584 /* Enter the interactive session. */
1585 return client_loop(have_tty, tty_flag ?
1586 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1589 /* request pty/x11/agent/tcpfwd/shell for channel */
1591 ssh_session2_setup(int id, int success, void *arg)
1593 extern char **environ;
1594 const char *display;
1595 int interactive = tty_flag;
1598 return; /* No need for error message, channels code sens one */
1600 display = getenv("DISPLAY");
1601 if (options.forward_x11 && display != NULL) {
1603 /* Get reasonable local authentication information. */
1604 client_x11_get_proto(display, options.xauth_location,
1605 options.forward_x11_trusted,
1606 options.forward_x11_timeout, &proto, &data);
1607 /* Request forwarding with authentication spoofing. */
1608 debug("Requesting X11 forwarding with authentication "
1610 x11_request_forwarding_with_spoofing(id, display, proto,
1612 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1613 /* XXX exit_on_forward_failure */
1617 check_agent_present();
1618 if (options.forward_agent) {
1619 debug("Requesting authentication agent forwarding.");
1620 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1624 /* Tell the packet module whether this is an interactive session. */
1625 packet_set_interactive(interactive,
1626 options.ip_qos_interactive, options.ip_qos_bulk);
1628 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1629 NULL, fileno(stdin), &command, environ);
1632 /* open new channel for a session */
1634 ssh_session2_open(void)
1637 int window, packetmax, in, out, err;
1639 if (stdin_null_flag) {
1640 in = open(_PATH_DEVNULL, O_RDONLY);
1642 in = dup(STDIN_FILENO);
1644 out = dup(STDOUT_FILENO);
1645 err = dup(STDERR_FILENO);
1647 if (in < 0 || out < 0 || err < 0)
1648 fatal("dup() in/out/err failed");
1650 /* enable nonblocking unless tty */
1658 window = CHAN_SES_WINDOW_DEFAULT;
1659 packetmax = CHAN_SES_PACKET_DEFAULT;
1665 "session", SSH_CHANNEL_OPENING, in, out, err,
1666 window, packetmax, CHAN_EXTENDED_WRITE,
1667 "client-session", /*nonblock*/0);
1669 debug3("ssh_session2_open: channel_new: %d", c->self);
1671 channel_send_open(c->self);
1673 channel_register_open_confirm(c->self,
1674 ssh_session2_setup, NULL);
1684 /* XXX should be pre-session */
1685 if (!options.control_persist)
1686 ssh_init_stdio_forwarding();
1687 ssh_init_forwarding();
1689 /* Start listening for multiplex clients */
1693 * If we are in control persist mode and have a working mux listen
1694 * socket, then prepare to background ourselves and have a foreground
1695 * client attach as a control slave.
1696 * NB. we must save copies of the flags that we override for
1697 * the backgrounding, since we defer attachment of the slave until
1698 * after the connection is fully established (in particular,
1699 * async rfwd replies have been received for ExitOnForwardFailure).
1701 if (options.control_persist && muxserver_sock != -1) {
1702 ostdin_null_flag = stdin_null_flag;
1703 ono_shell_flag = no_shell_flag;
1704 orequest_tty = options.request_tty;
1705 otty_flag = tty_flag;
1706 stdin_null_flag = 1;
1709 if (!fork_after_authentication_flag)
1710 need_controlpersist_detach = 1;
1711 fork_after_authentication_flag = 1;
1714 * ControlPersist mux listen socket setup failed, attempt the
1715 * stdio forward setup that we skipped earlier.
1717 if (options.control_persist && muxserver_sock == -1)
1718 ssh_init_stdio_forwarding();
1720 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1721 id = ssh_session2_open();
1723 packet_set_interactive(
1724 options.control_master == SSHCTL_MASTER_NO,
1725 options.ip_qos_interactive, options.ip_qos_bulk);
1728 /* If we don't expect to open a new session, then disallow it */
1729 if (options.control_master == SSHCTL_MASTER_NO &&
1730 (datafellows & SSH_NEW_OPENSSH)) {
1731 debug("Requesting no-more-sessions@openssh.com");
1732 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1733 packet_put_cstring("no-more-sessions@openssh.com");
1738 /* Execute a local command */
1739 if (options.local_command != NULL &&
1740 options.permit_local_command)
1741 ssh_local_cmd(options.local_command);
1744 * If requested and we are not interested in replies to remote
1745 * forwarding requests, then let ssh continue in the background.
1747 if (fork_after_authentication_flag) {
1748 if (options.exit_on_forward_failure &&
1749 options.num_remote_forwards > 0) {
1750 debug("deferring postauth fork until remote forward "
1751 "confirmation received");
1756 if (options.use_roaming)
1759 return client_loop(tty_flag, tty_flag ?
1760 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1764 load_public_identity_files(void)
1766 char *filename, *cp, thishost[NI_MAXHOST];
1767 char *pwdir = NULL, *pwname = NULL;
1772 char *identity_files[SSH_MAX_IDENTITY_FILES];
1773 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1774 #ifdef ENABLE_PKCS11
1780 memset(identity_files, 0, sizeof(identity_files));
1781 memset(identity_keys, 0, sizeof(identity_keys));
1783 #ifdef ENABLE_PKCS11
1784 if (options.pkcs11_provider != NULL &&
1785 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1786 (pkcs11_init(!options.batch_mode) == 0) &&
1787 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1789 for (i = 0; i < nkeys; i++) {
1790 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1794 identity_keys[n_ids] = keys[i];
1795 identity_files[n_ids] =
1796 xstrdup(options.pkcs11_provider); /* XXX */
1801 #endif /* ENABLE_PKCS11 */
1802 if ((pw = getpwuid(original_real_uid)) == NULL)
1803 fatal("load_public_identity_files: getpwuid failed");
1804 pwname = xstrdup(pw->pw_name);
1805 pwdir = xstrdup(pw->pw_dir);
1806 if (gethostname(thishost, sizeof(thishost)) == -1)
1807 fatal("load_public_identity_files: gethostname: %s",
1809 for (i = 0; i < options.num_identity_files; i++) {
1810 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
1811 strcasecmp(options.identity_files[i], "none") == 0) {
1812 free(options.identity_files[i]);
1815 cp = tilde_expand_filename(options.identity_files[i],
1817 filename = percent_expand(cp, "d", pwdir,
1818 "u", pwname, "l", thishost, "h", host,
1819 "r", options.user, (char *)NULL);
1821 public = key_load_public(filename, NULL);
1822 debug("identity file %s type %d", filename,
1823 public ? public->type : -1);
1824 free(options.identity_files[i]);
1825 identity_files[n_ids] = filename;
1826 identity_keys[n_ids] = public;
1828 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1831 /* Try to add the certificate variant too */
1832 xasprintf(&cp, "%s-cert", filename);
1833 public = key_load_public(cp, NULL);
1834 debug("identity file %s type %d", cp,
1835 public ? public->type : -1);
1836 if (public == NULL) {
1840 if (!key_is_cert(public)) {
1841 debug("%s: key %s type %s is not a certificate",
1842 __func__, cp, key_type(public));
1847 identity_keys[n_ids] = public;
1848 /* point to the original path, most likely the private key */
1849 identity_files[n_ids] = xstrdup(filename);
1852 options.num_identity_files = n_ids;
1853 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1854 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1856 explicit_bzero(pwname, strlen(pwname));
1858 explicit_bzero(pwdir, strlen(pwdir));
1863 main_sigchld_handler(int sig)
1865 int save_errno = errno;
1869 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1870 (pid < 0 && errno == EINTR))
1873 signal(sig, main_sigchld_handler);