1 /* $OpenBSD: ssh.c,v 1.585 2023/02/10 04:40:28 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 SSLeay by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
73 #include <netinet/in.h>
74 #include <arpa/inet.h>
77 #include <openssl/evp.h>
78 #include <openssl/err.h>
80 #include "openbsd-compat/openssl-compat.h"
81 #include "openbsd-compat/sys-queue.h"
95 #include "pathnames.h"
97 #include "clientloop.h"
100 #include "readconf.h"
101 #include "sshconnect.h"
109 #include "myproposal.h"
113 #include "ssh-pkcs11.h"
116 extern char *__progname;
118 /* Saves a copy of argv for setproctitle emulation */
119 #ifndef HAVE_SETPROCTITLE
120 static char **saved_av;
123 /* Flag indicating whether debug mode is on. May be set on the command line. */
126 /* Flag indicating whether a tty should be requested */
130 * Flag indicating that the current process should be backgrounded and
131 * a new mux-client launched in the foreground for ControlPersist.
133 int need_controlpersist_detach = 0;
135 /* Copies of flags for ControlPersist foreground mux-client */
136 int ostdin_null_flag, osession_type, otty_flag, orequest_tty;
139 * General data structure for command line options and options configurable
140 * in configuration files. See readconf.h.
144 /* optional user configfile */
148 * Name of the host we are connecting to. This is the name given on the
149 * command line, or the Hostname specified for the user-supplied name in a
150 * configuration file.
155 * A config can specify a path to forward, overriding SSH_AUTH_SOCK. If this is
156 * not NULL, forward the socket at this path instead.
158 char *forward_agent_sock_path = NULL;
160 /* socket address the host resolves to */
161 struct sockaddr_storage hostaddr;
163 /* Private host keys. */
164 Sensitive sensitive_data;
166 /* command to be executed */
167 struct sshbuf *command;
169 /* # of replies received for global requests */
170 static int forward_confirms_pending = -1;
173 extern int muxserver_sock;
174 extern u_int muxclient_command;
176 /* Prints a help message to the user. This function never returns. */
182 "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]\n"
183 " [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]\n"
184 " [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]\n"
185 " [-i identity_file] [-J [user@]host[:port]] [-L address]\n"
186 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
187 " [-Q query_option] [-R address] [-S ctl_path] [-W host:port]\n"
188 " [-w local_tun[:remote_tun]] destination [command [argument ...]]\n"
193 static int ssh_session2(struct ssh *, const struct ssh_conn_info *);
194 static void load_public_identity_files(const struct ssh_conn_info *);
195 static void main_sigchld_handler(int);
197 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
199 tilde_expand_paths(char **paths, u_int num_paths)
204 for (i = 0; i < num_paths; i++) {
205 cp = tilde_expand_filename(paths[i], getuid());
212 * Expands the set of percent_expand options used by the majority of keywords
213 * in the client that support percent expansion.
214 * Caller must free returned string.
217 default_client_percent_expand(const char *str,
218 const struct ssh_conn_info *cinfo)
220 return percent_expand(str,
221 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
226 * Expands the set of percent_expand options used by the majority of keywords
227 * AND perform environment variable substitution.
228 * Caller must free returned string.
231 default_client_percent_dollar_expand(const char *str,
232 const struct ssh_conn_info *cinfo)
236 ret = percent_dollar_expand(str,
237 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
240 fatal("invalid environment variable expansion");
245 * Attempt to resolve a host name / port to a set of addresses and
246 * optionally return any CNAMEs encountered along the way.
247 * Returns NULL on failure.
248 * NB. this function must operate with a options having undefined members.
250 static struct addrinfo *
251 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
253 char strport[NI_MAXSERV];
254 const char *errstr = NULL;
255 struct addrinfo hints, *res;
257 LogLevel loglevel = SYSLOG_LEVEL_DEBUG1;
260 port = default_ssh_port();
263 debug3_f("lookup %s:%d", name, port);
265 snprintf(strport, sizeof strport, "%d", port);
266 memset(&hints, 0, sizeof(hints));
267 hints.ai_family = options.address_family == -1 ?
268 AF_UNSPEC : options.address_family;
269 hints.ai_socktype = SOCK_STREAM;
271 hints.ai_flags = AI_CANONNAME;
272 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
273 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
274 loglevel = SYSLOG_LEVEL_ERROR;
275 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
276 __progname, name, ssh_gai_strerror(gaierr));
279 if (cname != NULL && res->ai_canonname != NULL) {
280 if (!valid_domain(res->ai_canonname, 0, &errstr)) {
281 error("ignoring bad CNAME \"%s\" for host \"%s\": %s",
282 res->ai_canonname, name, errstr);
283 } else if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
284 error_f("host \"%s\" cname \"%s\" too long (max %lu)",
285 name, res->ai_canonname, (u_long)clen);
293 /* Returns non-zero if name can only be an address and not a hostname */
295 is_addr_fast(const char *name)
297 return (strchr(name, '%') != NULL || strchr(name, ':') != NULL ||
298 strspn(name, "0123456789.") == strlen(name));
301 /* Returns non-zero if name represents a valid, single address */
303 is_addr(const char *name)
305 char strport[NI_MAXSERV];
306 struct addrinfo hints, *res;
308 if (is_addr_fast(name))
311 snprintf(strport, sizeof strport, "%u", default_ssh_port());
312 memset(&hints, 0, sizeof(hints));
313 hints.ai_family = options.address_family == -1 ?
314 AF_UNSPEC : options.address_family;
315 hints.ai_socktype = SOCK_STREAM;
316 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
317 if (getaddrinfo(name, strport, &hints, &res) != 0)
319 if (res == NULL || res->ai_next != NULL) {
328 * Attempt to resolve a numeric host address / port to a single address.
329 * Returns a canonical address string.
330 * Returns NULL on failure.
331 * NB. this function must operate with a options having undefined members.
333 static struct addrinfo *
334 resolve_addr(const char *name, int port, char *caddr, size_t clen)
336 char addr[NI_MAXHOST], strport[NI_MAXSERV];
337 struct addrinfo hints, *res;
341 port = default_ssh_port();
342 snprintf(strport, sizeof strport, "%u", port);
343 memset(&hints, 0, sizeof(hints));
344 hints.ai_family = options.address_family == -1 ?
345 AF_UNSPEC : options.address_family;
346 hints.ai_socktype = SOCK_STREAM;
347 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
348 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
349 debug2_f("could not resolve name %.100s as address: %s",
350 name, ssh_gai_strerror(gaierr));
354 debug_f("getaddrinfo %.100s returned no addresses", name);
357 if (res->ai_next != NULL) {
358 debug_f("getaddrinfo %.100s returned multiple addresses", name);
361 if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
362 addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
363 debug_f("Could not format address for name %.100s: %s",
364 name, ssh_gai_strerror(gaierr));
367 if (strlcpy(caddr, addr, clen) >= clen) {
368 error_f("host \"%s\" addr \"%s\" too long (max %lu)",
369 name, addr, (u_long)clen);
380 * Check whether the cname is a permitted replacement for the hostname
381 * and perform the replacement if it is.
382 * NB. this function must operate with a options having undefined members.
385 check_follow_cname(int direct, char **namep, const char *cname)
388 struct allowed_cname *rule;
390 if (*cname == '\0' || !config_has_permitted_cnames(&options) ||
391 strcmp(*namep, cname) == 0)
393 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
396 * Don't attempt to canonicalize names that will be interpreted by
397 * a proxy or jump host unless the user specifically requests so.
400 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
402 debug3_f("check \"%s\" CNAME \"%s\"", *namep, cname);
403 for (i = 0; i < options.num_permitted_cnames; i++) {
404 rule = options.permitted_cnames + i;
405 if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
406 match_pattern_list(cname, rule->target_list, 1) != 1)
408 verbose("Canonicalized DNS aliased hostname "
409 "\"%s\" => \"%s\"", *namep, cname);
411 *namep = xstrdup(cname);
418 * Attempt to resolve the supplied hostname after applying the user's
419 * canonicalization rules. Returns the address list for the host or NULL
420 * if no name was found after canonicalization.
421 * NB. this function must operate with a options having undefined members.
423 static struct addrinfo *
424 resolve_canonicalize(char **hostp, int port)
426 int i, direct, ndots;
427 char *cp, *fullhost, newname[NI_MAXHOST];
428 struct addrinfo *addrs;
431 * Attempt to canonicalise addresses, regardless of
432 * whether hostname canonicalisation was requested
434 if ((addrs = resolve_addr(*hostp, port,
435 newname, sizeof(newname))) != NULL) {
436 debug2_f("hostname %.100s is address", *hostp);
437 if (strcasecmp(*hostp, newname) != 0) {
438 debug2_f("canonicalised address \"%s\" => \"%s\"",
441 *hostp = xstrdup(newname);
447 * If this looks like an address but didn't parse as one, it might
448 * be an address with an invalid interface scope. Skip further
449 * attempts at canonicalisation.
451 if (is_addr_fast(*hostp)) {
452 debug_f("hostname %.100s is an unrecognised address", *hostp);
456 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
460 * Don't attempt to canonicalize names that will be interpreted by
461 * a proxy unless the user specifically requests so.
463 direct = option_clear_or_none(options.proxy_command) &&
464 options.jump_host == NULL;
466 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
469 /* If domain name is anchored, then resolve it now */
470 if ((*hostp)[strlen(*hostp) - 1] == '.') {
471 debug3_f("name is fully qualified");
472 fullhost = xstrdup(*hostp);
473 if ((addrs = resolve_host(fullhost, port, 0,
474 newname, sizeof(newname))) != NULL)
480 /* Don't apply canonicalization to sufficiently-qualified hostnames */
482 for (cp = *hostp; *cp != '\0'; cp++) {
486 if (ndots > options.canonicalize_max_dots) {
487 debug3_f("not canonicalizing hostname \"%s\" (max dots %d)",
488 *hostp, options.canonicalize_max_dots);
491 /* Attempt each supplied suffix */
492 for (i = 0; i < options.num_canonical_domains; i++) {
493 if (strcasecmp(options.canonical_domains[i], "none") == 0)
495 xasprintf(&fullhost, "%s.%s.", *hostp,
496 options.canonical_domains[i]);
497 debug3_f("attempting \"%s\" => \"%s\"", *hostp, fullhost);
498 if ((addrs = resolve_host(fullhost, port, 0,
499 newname, sizeof(newname))) == NULL) {
504 /* Remove trailing '.' */
505 fullhost[strlen(fullhost) - 1] = '\0';
506 /* Follow CNAME if requested */
507 if (!check_follow_cname(direct, &fullhost, newname)) {
508 debug("Canonicalized hostname \"%s\" => \"%s\"",
516 if (!options.canonicalize_fallback_local)
517 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
518 debug2_f("host %s not found in any suffix", *hostp);
523 * Check the result of hostkey loading, ignoring some errors and either
524 * discarding the key or fatal()ing for others.
527 check_load(int r, struct sshkey **k, const char *path, const char *message)
531 /* Check RSA keys size and discard if undersized */
532 if (k != NULL && *k != NULL &&
533 (r = sshkey_check_rsa_length(*k,
534 options.required_rsa_size)) != 0) {
535 error_r(r, "load %s \"%s\"", message, path);
540 case SSH_ERR_INTERNAL_ERROR:
541 case SSH_ERR_ALLOC_FAIL:
542 fatal_r(r, "load %s \"%s\"", message, path);
543 case SSH_ERR_SYSTEM_ERROR:
544 /* Ignore missing files */
549 error_r(r, "load %s \"%s\"", message, path);
555 * Read per-user configuration file. Ignore the system wide config
556 * file if the user specifies a config file on the command line.
559 process_config_files(const char *host_name, struct passwd *pw, int final_pass,
560 int *want_final_pass)
565 if (config != NULL) {
566 if (strcasecmp(config, "none") != 0 &&
567 !read_config_file(config, pw, host, host_name, &options,
568 SSHCONF_USERCONF | (final_pass ? SSHCONF_FINAL : 0),
570 fatal("Can't open user config file %.100s: "
571 "%.100s", config, strerror(errno));
573 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
574 _PATH_SSH_USER_CONFFILE);
575 if (r > 0 && (size_t)r < sizeof(buf))
576 (void)read_config_file(buf, pw, host, host_name,
577 &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
578 (final_pass ? SSHCONF_FINAL : 0), want_final_pass);
580 /* Read systemwide configuration file after user config. */
581 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
582 host, host_name, &options,
583 final_pass ? SSHCONF_FINAL : 0, want_final_pass);
587 /* Rewrite the port number in an addrinfo list of addresses */
589 set_addrinfo_port(struct addrinfo *addrs, int port)
591 struct addrinfo *addr;
593 for (addr = addrs; addr != NULL; addr = addr->ai_next) {
594 switch (addr->ai_family) {
596 ((struct sockaddr_in *)addr->ai_addr)->
597 sin_port = htons(port);
600 ((struct sockaddr_in6 *)addr->ai_addr)->
601 sin6_port = htons(port);
608 ssh_conn_info_free(struct ssh_conn_info *cinfo)
612 free(cinfo->conn_hash_hex);
613 free(cinfo->shorthost);
615 free(cinfo->keyalias);
616 free(cinfo->thishost);
617 free(cinfo->host_arg);
618 free(cinfo->portstr);
619 free(cinfo->remhost);
620 free(cinfo->remuser);
621 free(cinfo->homedir);
622 free(cinfo->locuser);
627 * Main program for the ssh client.
630 main(int ac, char **av)
632 struct ssh *ssh = NULL;
633 int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
634 int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0;
635 char *p, *cp, *line, *argv0, *logfile;
636 char cname[NI_MAXHOST], thishost[NI_MAXHOST];
639 extern int optind, optreset;
642 struct addrinfo *addrs = NULL;
645 struct ssh_conn_info *cinfo = NULL;
647 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
651 * Discard other fds that are hanging around. These can cause problem
652 * with backgrounded ssh processes started by ControlPersist.
654 closefrom(STDERR_FILENO + 1);
656 __progname = ssh_get_progname(av[0]);
658 #ifndef HAVE_SETPROCTITLE
659 /* Prepare for later setproctitle emulation */
660 /* Save argv so it isn't clobbered by setproctitle() emulation */
661 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
662 for (i = 0; i < ac; i++)
663 saved_av[i] = xstrdup(av[i]);
665 compat_init_setproctitle(ac, av);
672 pw = getpwuid(getuid());
674 logit("No user exists for uid %lu", (u_long)getuid());
677 /* Take a copy of the returned structure. */
681 * Set our umask to something reasonable, as some files are created
682 * with the default umask. This will make them world-readable but
683 * writable only by the owner, which is ok for all files for which we
684 * don't set the modes explicitly.
686 umask(022 | umask(077));
691 * Initialize option structure to indicate that no values have been
694 initialize_options(&options);
697 * Prepare main ssh transport/connection structures
699 if ((ssh = ssh_alloc_session_state()) == NULL)
700 fatal("Couldn't allocate session state");
701 channel_init_channels(ssh);
703 /* Parse command-line arguments. */
710 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
711 "AB:CD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) { /* HUZdhjruz */
714 fatal("SSH protocol v.1 is no longer supported");
720 options.address_family = AF_INET;
723 options.address_family = AF_INET6;
726 options.stdin_null = 1;
729 options.fork_after_authentication = 1;
730 options.stdin_null = 1;
733 options.forward_x11 = 0;
736 options.forward_x11 = 1;
748 options.forward_x11 = 1;
749 options.forward_x11_trusted = 1;
752 options.fwd_opts.gateway_ports = 1;
755 if (options.stdio_forward_host != NULL)
756 fatal("Cannot specify multiplexing "
758 else if (muxclient_command != 0)
759 fatal("Multiplexing command already specified");
760 if (strcmp(optarg, "check") == 0)
761 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
762 else if (strcmp(optarg, "forward") == 0)
763 muxclient_command = SSHMUX_COMMAND_FORWARD;
764 else if (strcmp(optarg, "exit") == 0)
765 muxclient_command = SSHMUX_COMMAND_TERMINATE;
766 else if (strcmp(optarg, "stop") == 0)
767 muxclient_command = SSHMUX_COMMAND_STOP;
768 else if (strcmp(optarg, "cancel") == 0)
769 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
770 else if (strcmp(optarg, "proxy") == 0)
771 muxclient_command = SSHMUX_COMMAND_PROXY;
773 fatal("Invalid multiplex command.");
775 case 'P': /* deprecated */
779 if (strcmp(optarg, "cipher") == 0 ||
780 strcasecmp(optarg, "Ciphers") == 0)
781 cp = cipher_alg_list('\n', 0);
782 else if (strcmp(optarg, "cipher-auth") == 0)
783 cp = cipher_alg_list('\n', 1);
784 else if (strcmp(optarg, "mac") == 0 ||
785 strcasecmp(optarg, "MACs") == 0)
786 cp = mac_alg_list('\n');
787 else if (strcmp(optarg, "kex") == 0 ||
788 strcasecmp(optarg, "KexAlgorithms") == 0)
789 cp = kex_alg_list('\n');
790 else if (strcmp(optarg, "key") == 0)
791 cp = sshkey_alg_list(0, 0, 0, '\n');
792 else if (strcmp(optarg, "key-cert") == 0)
793 cp = sshkey_alg_list(1, 0, 0, '\n');
794 else if (strcmp(optarg, "key-plain") == 0)
795 cp = sshkey_alg_list(0, 1, 0, '\n');
796 else if (strcmp(optarg, "key-sig") == 0 ||
797 strcasecmp(optarg, "CASignatureAlgorithms") == 0 ||
798 strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
799 strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
800 strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
801 strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
802 strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
803 strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
804 cp = sshkey_alg_list(0, 0, 1, '\n');
805 else if (strcmp(optarg, "sig") == 0)
806 cp = sshkey_alg_list(0, 1, 1, '\n');
807 else if (strcmp(optarg, "protocol-version") == 0)
809 else if (strcmp(optarg, "compression") == 0) {
810 cp = xstrdup(compression_alg_list(0));
812 for (n = 0; n < len; n++)
815 } else if (strcmp(optarg, "help") == 0) {
817 "cipher\ncipher-auth\ncompression\nkex\n"
818 "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
819 "protocol-version\nsig");
822 fatal("Unsupported query \"%s\"", optarg);
828 options.forward_agent = 0;
831 options.forward_agent = 1;
834 options.gss_deleg_creds = 0;
837 options.gss_authentication = 1;
838 options.gss_deleg_creds = 1;
841 p = tilde_expand_filename(optarg, getuid());
842 if (stat(p, &st) == -1)
843 fprintf(stderr, "Warning: Identity file %s "
844 "not accessible: %s.\n", p,
847 add_identity_file(&options, NULL, p, 1);
852 free(options.pkcs11_provider);
853 options.pkcs11_provider = xstrdup(optarg);
855 fprintf(stderr, "no support for PKCS#11.\n");
859 if (options.jump_host != NULL) {
860 fatal("Only a single -J option is permitted "
861 "(use commas to separate multiple "
864 if (options.proxy_command != NULL)
865 fatal("Cannot specify -J with ProxyCommand");
866 if (parse_jump(optarg, &options, 1) == -1)
867 fatal("Invalid -J argument");
868 options.proxy_command = xstrdup("none");
871 if (options.request_tty == REQUEST_TTY_YES)
872 options.request_tty = REQUEST_TTY_FORCE;
874 options.request_tty = REQUEST_TTY_YES;
877 if (debug_flag == 0) {
879 options.log_level = SYSLOG_LEVEL_DEBUG1;
881 if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
888 fprintf(stderr, "%s, %s\n",
889 SSH_RELEASE, SSH_OPENSSL_VERSION);
893 if (options.tun_open == -1)
894 options.tun_open = SSH_TUNMODE_DEFAULT;
895 options.tun_local = a2tun(optarg, &options.tun_remote);
896 if (options.tun_local == SSH_TUNID_ERR) {
898 "Bad tun device '%s'\n", optarg);
903 if (options.stdio_forward_host != NULL)
904 fatal("stdio forward already specified");
905 if (muxclient_command != 0)
906 fatal("Cannot specify stdio forward with -O");
907 if (parse_forward(&fwd, optarg, 1, 0)) {
908 options.stdio_forward_host = fwd.listen_host;
909 options.stdio_forward_port = fwd.listen_port;
910 free(fwd.connect_host);
913 "Bad stdio forwarding specification '%s'\n",
917 options.request_tty = REQUEST_TTY_NO;
918 options.session_type = SESSION_TYPE_NONE;
921 options.log_level = SYSLOG_LEVEL_QUIET;
924 if (optarg[0] == '^' && optarg[2] == 0 &&
925 (u_char) optarg[1] >= 64 &&
926 (u_char) optarg[1] < 128)
927 options.escape_char = (u_char) optarg[1] & 31;
928 else if (strlen(optarg) == 1)
929 options.escape_char = (u_char) optarg[0];
930 else if (strcmp(optarg, "none") == 0)
931 options.escape_char = SSH_ESCAPECHAR_NONE;
933 fprintf(stderr, "Bad escape character '%s'.\n",
939 if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
940 optarg + 1 : optarg)) {
941 fprintf(stderr, "Unknown cipher type '%s'\n",
945 free(options.ciphers);
946 options.ciphers = xstrdup(optarg);
949 if (mac_valid(optarg)) {
951 options.macs = xstrdup(optarg);
953 fprintf(stderr, "Unknown mac type '%s'\n",
959 if (options.control_master == SSHCTL_MASTER_YES)
960 options.control_master = SSHCTL_MASTER_ASK;
962 options.control_master = SSHCTL_MASTER_YES;
965 if (options.port == -1) {
966 options.port = a2port(optarg);
967 if (options.port <= 0) {
968 fprintf(stderr, "Bad port '%s'\n",
975 if (options.user == NULL)
976 options.user = optarg;
980 if (parse_forward(&fwd, optarg, 0, 0))
981 add_local_forward(&options, &fwd);
984 "Bad local forwarding specification '%s'\n",
991 if (parse_forward(&fwd, optarg, 0, 1) ||
992 parse_forward(&fwd, optarg, 1, 1)) {
993 add_remote_forward(&options, &fwd);
996 "Bad remote forwarding specification "
1003 if (parse_forward(&fwd, optarg, 1, 0)) {
1004 add_local_forward(&options, &fwd);
1007 "Bad dynamic forwarding specification "
1015 options.compression = 1;
1017 error("Compression not supported, disabling.");
1021 if (options.session_type != -1 &&
1022 options.session_type != SESSION_TYPE_NONE)
1023 fatal("Cannot specify -N with -s/SessionType");
1024 options.session_type = SESSION_TYPE_NONE;
1025 options.request_tty = REQUEST_TTY_NO;
1028 options.request_tty = REQUEST_TTY_NO;
1031 line = xstrdup(optarg);
1032 if (process_config_line(&options, pw,
1033 host ? host : "", host ? host : "", line,
1034 "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1039 if (options.session_type != -1 &&
1040 options.session_type != SESSION_TYPE_SUBSYSTEM)
1041 fatal("Cannot specify -s with -N/SessionType");
1042 options.session_type = SESSION_TYPE_SUBSYSTEM;
1045 free(options.control_path);
1046 options.control_path = xstrdup(optarg);
1049 options.bind_address = optarg;
1052 options.bind_interface = optarg;
1062 if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1068 if (ac > 0 && !host) {
1071 switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1076 if (options.user == NULL) {
1077 options.user = tuser;
1081 if (options.port == -1 && tport != -1)
1082 options.port = tport;
1086 cp = strrchr(p, '@');
1090 if (options.user == NULL) {
1101 if (ac > 1 && !opt_terminated) {
1102 optind = optreset = 1;
1108 /* Check that we got a host name. */
1112 options.host_arg = xstrdup(host);
1114 /* Initialize the command to execute on remote host. */
1115 if ((command = sshbuf_new()) == NULL)
1116 fatal("sshbuf_new failed");
1119 * Save the command to execute on the remote host in a buffer. There
1120 * is no limit on the length of the command, except by the maximum
1121 * packet size. Also sets the tty flag if there is no command.
1124 /* No command specified - execute shell on a tty. */
1125 if (options.session_type == SESSION_TYPE_SUBSYSTEM) {
1127 "You must specify a subsystem to invoke.\n");
1131 /* A command has been specified. Store it into the buffer. */
1132 for (i = 0; i < ac; i++) {
1133 if ((r = sshbuf_putf(command, "%s%s",
1134 i ? " " : "", av[i])) != 0)
1135 fatal_fr(r, "buffer error");
1139 ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1142 * Initialize "log" output. Since we are the client all output
1143 * goes to stderr unless otherwise specified by -y or -E.
1145 if (use_syslog && logfile != NULL)
1146 fatal("Can't specify both -y and -E");
1147 if (logfile != NULL)
1148 log_redirect_stderr_to(logfile);
1150 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1151 SYSLOG_LEVEL_INFO : options.log_level,
1152 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1153 SYSLOG_FACILITY_USER : options.log_facility,
1157 logit("%s, %s", SSH_RELEASE, SSH_OPENSSL_VERSION);
1159 /* Parse the configuration files */
1160 process_config_files(options.host_arg, pw, 0, &want_final_pass);
1161 if (want_final_pass)
1162 debug("configuration requests final Match pass");
1164 /* Hostname canonicalisation needs a few options filled. */
1165 fill_default_options_for_canonicalization(&options);
1167 /* If the user has replaced the hostname then take it into use now */
1168 if (options.hostname != NULL) {
1169 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1170 cp = percent_expand(options.hostname,
1171 "h", host, (char *)NULL);
1174 free(options.hostname);
1175 options.hostname = xstrdup(host);
1178 /* Don't lowercase addresses, they will be explicitly canonicalised */
1179 if ((was_addr = is_addr(host)) == 0)
1183 * Try to canonicalize if requested by configuration or the
1184 * hostname is an address.
1186 if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1187 addrs = resolve_canonicalize(&host, options.port);
1190 * If CanonicalizePermittedCNAMEs have been specified but
1191 * other canonicalization did not happen (by not being requested
1192 * or by failing with fallback) then the hostname may still be changed
1193 * as a result of CNAME following.
1195 * Try to resolve the bare hostname name using the system resolver's
1196 * usual search rules and then apply the CNAME follow rules.
1198 * Skip the lookup if a ProxyCommand is being used unless the user
1199 * has specifically requested canonicalisation for this case via
1200 * CanonicalizeHostname=always
1202 direct = option_clear_or_none(options.proxy_command) &&
1203 options.jump_host == NULL;
1204 if (addrs == NULL && config_has_permitted_cnames(&options) && (direct ||
1205 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1206 if ((addrs = resolve_host(host, options.port,
1207 direct, cname, sizeof(cname))) == NULL) {
1208 /* Don't fatal proxied host names not in the DNS */
1210 cleanup_exit(255); /* logged in resolve_host */
1212 check_follow_cname(direct, &host, cname);
1216 * If canonicalisation is enabled then re-parse the configuration
1217 * files as new stanzas may match.
1219 if (options.canonicalize_hostname != 0 && !want_final_pass) {
1220 debug("hostname canonicalisation enabled, "
1221 "will re-parse configuration");
1222 want_final_pass = 1;
1225 if (want_final_pass) {
1226 debug("re-parsing configuration");
1227 free(options.hostname);
1228 options.hostname = xstrdup(host);
1229 process_config_files(options.host_arg, pw, 1, NULL);
1231 * Address resolution happens early with canonicalisation
1232 * enabled and the port number may have changed since, so
1233 * reset it in address list
1235 if (addrs != NULL && options.port > 0)
1236 set_addrinfo_port(addrs, options.port);
1239 /* Fill configuration defaults. */
1240 if (fill_default_options(&options) != 0)
1243 if (options.user == NULL)
1244 options.user = xstrdup(pw->pw_name);
1247 * If ProxyJump option specified, then construct a ProxyCommand now.
1249 if (options.jump_host != NULL) {
1251 const char *jumpuser = options.jump_user, *sshbin = argv0;
1252 int port = options.port, jumpport = options.jump_port;
1255 port = default_ssh_port();
1257 jumpport = default_ssh_port();
1258 if (jumpuser == NULL)
1259 jumpuser = options.user;
1260 if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1261 strcmp(options.user, jumpuser) == 0)
1262 fatal("jumphost loop via %s", options.jump_host);
1265 * Try to use SSH indicated by argv[0], but fall back to
1266 * "ssh" if it appears unavailable.
1268 if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1271 /* Consistency check */
1272 if (options.proxy_command != NULL)
1273 fatal("inconsistent options: ProxyCommand+ProxyJump");
1274 /* Never use FD passing for ProxyJump */
1275 options.proxy_use_fdpass = 0;
1276 snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1277 xasprintf(&options.proxy_command,
1278 "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1280 /* Optional "-l user" argument if jump_user set */
1281 options.jump_user == NULL ? "" : " -l ",
1282 options.jump_user == NULL ? "" : options.jump_user,
1283 /* Optional "-p port" argument if jump_port set */
1284 options.jump_port <= 0 ? "" : " -p ",
1285 options.jump_port <= 0 ? "" : port_s,
1286 /* Optional additional jump hosts ",..." */
1287 options.jump_extra == NULL ? "" : " -J ",
1288 options.jump_extra == NULL ? "" : options.jump_extra,
1289 /* Optional "-F" argument if -F specified */
1290 config == NULL ? "" : " -F ",
1291 config == NULL ? "" : config,
1292 /* Optional "-v" arguments if -v set */
1293 debug_flag ? " -" : "",
1295 /* Mandatory hostname */
1297 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1298 options.proxy_command);
1301 if (options.port == 0)
1302 options.port = default_ssh_port();
1303 channel_set_af(ssh, options.address_family);
1305 /* Tidy and check options */
1306 if (options.host_key_alias != NULL)
1307 lowercase(options.host_key_alias);
1308 if (options.proxy_command != NULL &&
1309 strcmp(options.proxy_command, "-") == 0 &&
1310 options.proxy_use_fdpass)
1311 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1312 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1313 if (options.control_persist && options.control_path != NULL) {
1314 debug("UpdateHostKeys=ask is incompatible with "
1315 "ControlPersist; disabling");
1316 options.update_hostkeys = 0;
1317 } else if (sshbuf_len(command) != 0 ||
1318 options.remote_command != NULL ||
1319 options.request_tty == REQUEST_TTY_NO) {
1320 debug("UpdateHostKeys=ask is incompatible with "
1321 "remote command execution; disabling");
1322 options.update_hostkeys = 0;
1323 } else if (options.log_level < SYSLOG_LEVEL_INFO) {
1324 /* no point logging anything; user won't see it */
1325 options.update_hostkeys = 0;
1328 if (options.connection_attempts <= 0)
1329 fatal("Invalid number of ConnectionAttempts");
1331 if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1332 fatal("Cannot execute command-line and remote command.");
1334 /* Cannot fork to background if no command. */
1335 if (options.fork_after_authentication && sshbuf_len(command) == 0 &&
1336 options.remote_command == NULL &&
1337 options.session_type != SESSION_TYPE_NONE)
1338 fatal("Cannot fork into background without a command "
1342 log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1343 for (j = 0; j < options.num_log_verbose; j++) {
1344 if (strcasecmp(options.log_verbose[j], "none") == 0)
1346 log_verbose_add(options.log_verbose[j]);
1349 if (options.request_tty == REQUEST_TTY_YES ||
1350 options.request_tty == REQUEST_TTY_FORCE)
1353 /* Allocate a tty by default if no command specified. */
1354 if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1355 tty_flag = options.request_tty != REQUEST_TTY_NO;
1358 if (options.request_tty == REQUEST_TTY_NO ||
1359 (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY) ||
1360 options.session_type == SESSION_TYPE_NONE)
1362 /* Do not allocate a tty if stdin is not a tty. */
1363 if ((!isatty(fileno(stdin)) || options.stdin_null) &&
1364 options.request_tty != REQUEST_TTY_FORCE) {
1366 logit("Pseudo-terminal will not be allocated because "
1367 "stdin is not a terminal.");
1371 /* Set up strings used to percent_expand() arguments */
1372 cinfo = xcalloc(1, sizeof(*cinfo));
1373 if (gethostname(thishost, sizeof(thishost)) == -1)
1374 fatal("gethostname: %s", strerror(errno));
1375 cinfo->thishost = xstrdup(thishost);
1376 thishost[strcspn(thishost, ".")] = '\0';
1377 cinfo->shorthost = xstrdup(thishost);
1378 xasprintf(&cinfo->portstr, "%d", options.port);
1379 xasprintf(&cinfo->uidstr, "%llu",
1380 (unsigned long long)pw->pw_uid);
1381 cinfo->keyalias = xstrdup(options.host_key_alias ?
1382 options.host_key_alias : options.host_arg);
1383 cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
1384 cinfo->portstr, options.user);
1385 cinfo->host_arg = xstrdup(options.host_arg);
1386 cinfo->remhost = xstrdup(host);
1387 cinfo->remuser = xstrdup(options.user);
1388 cinfo->homedir = xstrdup(pw->pw_dir);
1389 cinfo->locuser = xstrdup(pw->pw_name);
1391 /* Find canonic host name. */
1392 if (strchr(host, '.') == NULL) {
1393 struct addrinfo hints;
1394 struct addrinfo *ai = NULL;
1397 memset(&hints, 0, sizeof(hints));
1398 hints.ai_family = options.address_family;
1399 hints.ai_flags = AI_CANONNAME;
1400 hints.ai_socktype = SOCK_STREAM;
1401 errgai = getaddrinfo(host, NULL, &hints, &ai);
1403 if (ai->ai_canonname != NULL) {
1405 host = xstrdup(ai->ai_canonname);
1412 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1413 * after port-forwarding is set up, so it may pick up any local
1414 * tunnel interface name allocated.
1416 if (options.remote_command != NULL) {
1417 debug3("expanding RemoteCommand: %s", options.remote_command);
1418 cp = options.remote_command;
1419 options.remote_command = default_client_percent_expand(cp,
1421 debug3("expanded RemoteCommand: %s", options.remote_command);
1423 if ((r = sshbuf_put(command, options.remote_command,
1424 strlen(options.remote_command))) != 0)
1425 fatal_fr(r, "buffer error");
1428 if (options.control_path != NULL) {
1429 cp = tilde_expand_filename(options.control_path, getuid());
1430 free(options.control_path);
1431 options.control_path = default_client_percent_dollar_expand(cp,
1436 if (options.identity_agent != NULL) {
1437 p = tilde_expand_filename(options.identity_agent, getuid());
1438 cp = default_client_percent_dollar_expand(p, cinfo);
1440 free(options.identity_agent);
1441 options.identity_agent = cp;
1444 if (options.forward_agent_sock_path != NULL) {
1445 p = tilde_expand_filename(options.forward_agent_sock_path,
1447 cp = default_client_percent_dollar_expand(p, cinfo);
1449 free(options.forward_agent_sock_path);
1450 options.forward_agent_sock_path = cp;
1451 if (stat(options.forward_agent_sock_path, &st) != 0) {
1452 error("Cannot forward agent socket path \"%s\": %s",
1453 options.forward_agent_sock_path, strerror(errno));
1454 if (options.exit_on_forward_failure)
1459 if (options.num_system_hostfiles > 0 &&
1460 strcasecmp(options.system_hostfiles[0], "none") == 0) {
1461 if (options.num_system_hostfiles > 1)
1462 fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1463 "appears with other entries");
1464 free(options.system_hostfiles[0]);
1465 options.system_hostfiles[0] = NULL;
1466 options.num_system_hostfiles = 0;
1469 if (options.num_user_hostfiles > 0 &&
1470 strcasecmp(options.user_hostfiles[0], "none") == 0) {
1471 if (options.num_user_hostfiles > 1)
1472 fatal("Invalid UserKnownHostsFiles: \"none\" "
1473 "appears with other entries");
1474 free(options.user_hostfiles[0]);
1475 options.user_hostfiles[0] = NULL;
1476 options.num_user_hostfiles = 0;
1478 for (j = 0; j < options.num_user_hostfiles; j++) {
1479 if (options.user_hostfiles[j] == NULL)
1481 cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1482 p = default_client_percent_dollar_expand(cp, cinfo);
1483 if (strcmp(options.user_hostfiles[j], p) != 0)
1484 debug3("expanded UserKnownHostsFile '%s' -> "
1485 "'%s'", options.user_hostfiles[j], p);
1486 free(options.user_hostfiles[j]);
1488 options.user_hostfiles[j] = p;
1491 for (i = 0; i < options.num_local_forwards; i++) {
1492 if (options.local_forwards[i].listen_path != NULL) {
1493 cp = options.local_forwards[i].listen_path;
1494 p = options.local_forwards[i].listen_path =
1495 default_client_percent_expand(cp, cinfo);
1496 if (strcmp(cp, p) != 0)
1497 debug3("expanded LocalForward listen path "
1498 "'%s' -> '%s'", cp, p);
1501 if (options.local_forwards[i].connect_path != NULL) {
1502 cp = options.local_forwards[i].connect_path;
1503 p = options.local_forwards[i].connect_path =
1504 default_client_percent_expand(cp, cinfo);
1505 if (strcmp(cp, p) != 0)
1506 debug3("expanded LocalForward connect path "
1507 "'%s' -> '%s'", cp, p);
1512 for (i = 0; i < options.num_remote_forwards; i++) {
1513 if (options.remote_forwards[i].listen_path != NULL) {
1514 cp = options.remote_forwards[i].listen_path;
1515 p = options.remote_forwards[i].listen_path =
1516 default_client_percent_expand(cp, cinfo);
1517 if (strcmp(cp, p) != 0)
1518 debug3("expanded RemoteForward listen path "
1519 "'%s' -> '%s'", cp, p);
1522 if (options.remote_forwards[i].connect_path != NULL) {
1523 cp = options.remote_forwards[i].connect_path;
1524 p = options.remote_forwards[i].connect_path =
1525 default_client_percent_expand(cp, cinfo);
1526 if (strcmp(cp, p) != 0)
1527 debug3("expanded RemoteForward connect path "
1528 "'%s' -> '%s'", cp, p);
1534 dump_client_config(&options, host);
1538 /* Expand SecurityKeyProvider if it refers to an environment variable */
1539 if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1540 strlen(options.sk_provider) > 1) {
1541 if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1542 debug("Authenticator provider %s did not resolve; "
1543 "disabling", options.sk_provider);
1544 free(options.sk_provider);
1545 options.sk_provider = NULL;
1547 debug2("resolved SecurityKeyProvider %s => %s",
1548 options.sk_provider, cp);
1549 free(options.sk_provider);
1550 options.sk_provider = xstrdup(cp);
1554 if (muxclient_command != 0 && options.control_path == NULL)
1555 fatal("No ControlPath specified for \"-O\" command");
1556 if (options.control_path != NULL) {
1558 if ((sock = muxclient(options.control_path)) >= 0) {
1559 ssh_packet_set_connection(ssh, sock, sock);
1560 ssh_packet_set_mux(ssh);
1566 * If hostname canonicalisation was not enabled, then we may not
1567 * have yet resolved the hostname. Do so now.
1569 if (addrs == NULL && options.proxy_command == NULL) {
1570 debug2("resolving \"%s\" port %d", host, options.port);
1571 if ((addrs = resolve_host(host, options.port, 1,
1572 cname, sizeof(cname))) == NULL)
1573 cleanup_exit(255); /* resolve_host logs the error */
1576 if (options.connection_timeout >= INT_MAX/1000)
1577 timeout_ms = INT_MAX;
1579 timeout_ms = options.connection_timeout * 1000;
1581 /* Open a connection to the remote host. */
1582 if (ssh_connect(ssh, host, options.host_arg, addrs, &hostaddr,
1583 options.port, options.connection_attempts,
1584 &timeout_ms, options.tcp_keep_alive) != 0)
1588 freeaddrinfo(addrs);
1590 ssh_packet_set_timeout(ssh, options.server_alive_interval,
1591 options.server_alive_count_max);
1594 debug3("timeout: %d ms remain after connect", timeout_ms);
1597 * If we successfully made the connection and we have hostbased auth
1598 * enabled, load the public keys so we can later use the ssh-keysign
1599 * helper to sign challenges.
1601 sensitive_data.nkeys = 0;
1602 sensitive_data.keys = NULL;
1603 if (options.hostbased_authentication) {
1606 sensitive_data.nkeys = 10;
1607 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1608 sizeof(*sensitive_data.keys));
1610 /* XXX check errors? */
1611 #define L_PUBKEY(p,o) do { \
1612 if ((o) >= sensitive_data.nkeys) \
1613 fatal_f("pubkey out of array bounds"); \
1614 check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1615 &(sensitive_data.keys[o]), p, "pubkey"); \
1616 if (sensitive_data.keys[o] != NULL) { \
1617 debug2("hostbased key %d: %s key from \"%s\"", o, \
1618 sshkey_ssh_name(sensitive_data.keys[o]), p); \
1622 #define L_CERT(p,o) do { \
1623 if ((o) >= sensitive_data.nkeys) \
1624 fatal_f("cert out of array bounds"); \
1625 check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), \
1626 &(sensitive_data.keys[o]), p, "cert"); \
1627 if (sensitive_data.keys[o] != NULL) { \
1628 debug2("hostbased key %d: %s cert from \"%s\"", o, \
1629 sshkey_ssh_name(sensitive_data.keys[o]), p); \
1634 if (options.hostbased_authentication == 1) {
1635 L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1636 L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1637 L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1638 L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1639 L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1640 L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1641 L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1642 L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1643 L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1644 L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1646 debug("HostbasedAuthentication enabled but no "
1647 "local public host keys could be loaded.");
1651 /* load options.identity_files */
1652 load_public_identity_files(cinfo);
1654 /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1655 if (options.identity_agent &&
1656 strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1657 if (strcmp(options.identity_agent, "none") == 0) {
1658 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1660 cp = options.identity_agent;
1661 /* legacy (limited) format */
1662 if (cp[0] == '$' && cp[1] != '{') {
1663 if (!valid_env_name(cp + 1)) {
1664 fatal("Invalid IdentityAgent "
1665 "environment variable name %s", cp);
1667 if ((p = getenv(cp + 1)) == NULL)
1668 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1670 setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1672 /* identity_agent specifies a path directly */
1673 setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1678 if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1679 cp = options.forward_agent_sock_path;
1681 if (!valid_env_name(cp + 1)) {
1682 fatal("Invalid ForwardAgent environment variable name %s", cp);
1684 if ((p = getenv(cp + 1)) != NULL)
1685 forward_agent_sock_path = xstrdup(p);
1687 options.forward_agent = 0;
1690 forward_agent_sock_path = cp;
1694 /* Expand ~ in known host file names. */
1695 tilde_expand_paths(options.system_hostfiles,
1696 options.num_system_hostfiles);
1697 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1699 ssh_signal(SIGCHLD, main_sigchld_handler);
1701 /* Log into the remote system. Never returns if the login fails. */
1702 ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1703 options.port, pw, timeout_ms, cinfo);
1705 /* We no longer need the private host keys. Clear them now. */
1706 if (sensitive_data.nkeys != 0) {
1707 for (i = 0; i < sensitive_data.nkeys; i++) {
1708 if (sensitive_data.keys[i] != NULL) {
1709 /* Destroys contents safely */
1710 debug3("clear hostkey %d", i);
1711 sshkey_free(sensitive_data.keys[i]);
1712 sensitive_data.keys[i] = NULL;
1715 free(sensitive_data.keys);
1717 for (i = 0; i < options.num_identity_files; i++) {
1718 free(options.identity_files[i]);
1719 options.identity_files[i] = NULL;
1720 if (options.identity_keys[i]) {
1721 sshkey_free(options.identity_keys[i]);
1722 options.identity_keys[i] = NULL;
1725 for (i = 0; i < options.num_certificate_files; i++) {
1726 free(options.certificate_files[i]);
1727 options.certificate_files[i] = NULL;
1730 #ifdef ENABLE_PKCS11
1731 (void)pkcs11_del_provider(options.pkcs11_provider);
1735 exit_status = ssh_session2(ssh, cinfo);
1736 ssh_conn_info_free(cinfo);
1737 ssh_packet_close(ssh);
1739 if (options.control_path != NULL && muxserver_sock != -1)
1740 unlink(options.control_path);
1742 /* Kill ProxyCommand if it is running. */
1743 ssh_kill_proxy_command();
1749 control_persist_detach(void)
1753 debug_f("backgrounding master process");
1756 * master (current process) into the background, and make the
1757 * foreground process a client of the backgrounded master.
1759 switch ((pid = fork())) {
1761 fatal_f("fork: %s", strerror(errno));
1763 /* Child: master process continues mainloop */
1766 /* Parent: set up mux client to connect to backgrounded master */
1767 debug2_f("background process is %ld", (long)pid);
1768 options.stdin_null = ostdin_null_flag;
1769 options.request_tty = orequest_tty;
1770 tty_flag = otty_flag;
1771 options.session_type = osession_type;
1772 close(muxserver_sock);
1773 muxserver_sock = -1;
1774 options.control_master = SSHCTL_MASTER_NO;
1775 muxclient(options.control_path);
1776 /* muxclient() doesn't return on success. */
1777 fatal("Failed to connect to new control master");
1779 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1780 error_f("stdfd_devnull failed");
1782 setproctitle("%s [mux]", options.control_path);
1785 /* Do fork() after authentication. Used by "ssh -f" */
1789 if (need_controlpersist_detach)
1790 control_persist_detach();
1791 debug("forking to background");
1792 options.fork_after_authentication = 0;
1793 if (daemon(1, 1) == -1)
1794 fatal("daemon() failed: %.200s", strerror(errno));
1795 if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1796 error_f("stdfd_devnull failed");
1800 forwarding_success(void)
1802 if (forward_confirms_pending == -1)
1804 if (--forward_confirms_pending == 0) {
1805 debug_f("all expected forwarding replies received");
1806 if (options.fork_after_authentication)
1809 debug2_f("%d expected forwarding replies remaining",
1810 forward_confirms_pending);
1814 /* Callback for remote forward global requests */
1816 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1818 struct Forward *rfwd = (struct Forward *)ctxt;
1822 /* XXX verbose() on failure? */
1823 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1824 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1825 rfwd->listen_path ? rfwd->listen_path :
1826 rfwd->listen_host ? rfwd->listen_host : "",
1827 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1828 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1829 rfwd->connect_host, rfwd->connect_port);
1830 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1831 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1832 if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1833 fatal_fr(r, "parse packet");
1835 error("Invalid allocated port %u for remote "
1836 "forward to %s:%d", port,
1837 rfwd->connect_host, rfwd->connect_port);
1838 /* Ensure failure processing runs below */
1839 type = SSH2_MSG_REQUEST_FAILURE;
1840 channel_update_permission(ssh,
1843 rfwd->allocated_port = (int)port;
1844 logit("Allocated port %u for remote "
1846 rfwd->allocated_port, rfwd->connect_path ?
1847 rfwd->connect_path : rfwd->connect_host,
1848 rfwd->connect_port);
1849 channel_update_permission(ssh,
1850 rfwd->handle, rfwd->allocated_port);
1853 channel_update_permission(ssh, rfwd->handle, -1);
1857 if (type == SSH2_MSG_REQUEST_FAILURE) {
1858 if (options.exit_on_forward_failure) {
1859 if (rfwd->listen_path != NULL)
1860 fatal("Error: remote port forwarding failed "
1861 "for listen path %s", rfwd->listen_path);
1863 fatal("Error: remote port forwarding failed "
1864 "for listen port %d", rfwd->listen_port);
1866 if (rfwd->listen_path != NULL)
1867 logit("Warning: remote port forwarding failed "
1868 "for listen path %s", rfwd->listen_path);
1870 logit("Warning: remote port forwarding failed "
1871 "for listen port %d", rfwd->listen_port);
1874 forwarding_success();
1878 client_cleanup_stdio_fwd(struct ssh *ssh, int id, int force, void *arg)
1880 debug("stdio forwarding: done");
1885 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1888 fatal("stdio forwarding failed");
1892 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1895 error("Tunnel forwarding failed");
1896 if (options.exit_on_forward_failure)
1900 debug_f("tunnel forward established, id=%d", id);
1901 forwarding_success();
1905 ssh_init_stdio_forwarding(struct ssh *ssh)
1910 if (options.stdio_forward_host == NULL)
1913 debug3_f("%s:%d", options.stdio_forward_host,
1914 options.stdio_forward_port);
1916 if ((in = dup(STDIN_FILENO)) == -1 ||
1917 (out = dup(STDOUT_FILENO)) == -1)
1918 fatal_f("dup() in/out failed");
1919 if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1920 options.stdio_forward_port, in, out,
1921 CHANNEL_NONBLOCK_STDIO)) == NULL)
1922 fatal_f("channel_connect_stdio_fwd failed");
1923 channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1924 channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1928 ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
1933 char *addr, *arg, *oarg;
1934 int where = FORWARD_LOCAL;
1936 channel_clear_permission(ssh, FORWARD_ADM, where);
1938 return; /* permit any */
1940 /* handle keywords: "any" / "none" */
1941 if (num_opens == 1 && strcmp(opens[0], "any") == 0)
1943 if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
1944 channel_disable_admin(ssh, where);
1947 /* Otherwise treat it as a list of permitted host:port */
1948 for (i = 0; i < num_opens; i++) {
1949 oarg = arg = xstrdup(opens[i]);
1950 addr = hpdelim(&arg);
1952 fatal_f("missing host in %s", what);
1953 addr = cleanhostname(addr);
1954 if (arg == NULL || ((port = permitopen_port(arg)) < 0))
1955 fatal_f("bad port number in %s", what);
1956 /* Send it to channels layer */
1957 channel_add_permission(ssh, FORWARD_ADM,
1964 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1969 ssh_init_forward_permissions(ssh, "permitremoteopen",
1970 options.permitted_remote_opens,
1971 options.num_permitted_remote_opens);
1973 if (options.exit_on_forward_failure)
1974 forward_confirms_pending = 0; /* track pending requests */
1975 /* Initiate local TCP/IP port forwardings. */
1976 for (i = 0; i < options.num_local_forwards; i++) {
1977 debug("Local connections to %.200s:%d forwarded to remote "
1978 "address %.200s:%d",
1979 (options.local_forwards[i].listen_path != NULL) ?
1980 options.local_forwards[i].listen_path :
1981 (options.local_forwards[i].listen_host == NULL) ?
1982 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1983 options.local_forwards[i].listen_host,
1984 options.local_forwards[i].listen_port,
1985 (options.local_forwards[i].connect_path != NULL) ?
1986 options.local_forwards[i].connect_path :
1987 options.local_forwards[i].connect_host,
1988 options.local_forwards[i].connect_port);
1989 success += channel_setup_local_fwd_listener(ssh,
1990 &options.local_forwards[i], &options.fwd_opts);
1992 if (i > 0 && success != i && options.exit_on_forward_failure)
1993 fatal("Could not request local forwarding.");
1994 if (i > 0 && success == 0)
1995 error("Could not request local forwarding.");
1997 /* Initiate remote TCP/IP port forwardings. */
1998 for (i = 0; i < options.num_remote_forwards; i++) {
1999 debug("Remote connections from %.200s:%d forwarded to "
2000 "local address %.200s:%d",
2001 (options.remote_forwards[i].listen_path != NULL) ?
2002 options.remote_forwards[i].listen_path :
2003 (options.remote_forwards[i].listen_host == NULL) ?
2004 "LOCALHOST" : options.remote_forwards[i].listen_host,
2005 options.remote_forwards[i].listen_port,
2006 (options.remote_forwards[i].connect_path != NULL) ?
2007 options.remote_forwards[i].connect_path :
2008 options.remote_forwards[i].connect_host,
2009 options.remote_forwards[i].connect_port);
2010 if ((options.remote_forwards[i].handle =
2011 channel_request_remote_forwarding(ssh,
2012 &options.remote_forwards[i])) >= 0) {
2013 client_register_global_confirm(
2014 ssh_confirm_remote_forward,
2015 &options.remote_forwards[i]);
2016 forward_confirms_pending++;
2017 } else if (options.exit_on_forward_failure)
2018 fatal("Could not request remote forwarding.");
2020 logit("Warning: Could not request remote forwarding.");
2023 /* Initiate tunnel forwarding. */
2024 if (options.tun_open != SSH_TUNMODE_NO) {
2025 if ((*ifname = client_request_tun_fwd(ssh,
2026 options.tun_open, options.tun_local,
2027 options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
2028 forward_confirms_pending++;
2029 else if (options.exit_on_forward_failure)
2030 fatal("Could not request tunnel forwarding.");
2032 error("Could not request tunnel forwarding.");
2034 if (forward_confirms_pending > 0) {
2035 debug_f("expecting replies for %d forwards",
2036 forward_confirms_pending);
2041 check_agent_present(void)
2045 if (options.forward_agent) {
2046 /* Clear agent forwarding if we don't have an agent. */
2047 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
2048 options.forward_agent = 0;
2049 if (r != SSH_ERR_AGENT_NOT_PRESENT)
2050 debug_r(r, "ssh_get_authentication_socket");
2056 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
2058 extern char **environ;
2059 const char *display, *term;
2060 int r, interactive = tty_flag;
2061 char *proto = NULL, *data = NULL;
2064 return; /* No need for error message, channels code sends one */
2066 display = getenv("DISPLAY");
2067 if (display == NULL && options.forward_x11)
2068 debug("X11 forwarding requested but DISPLAY not set");
2069 if (options.forward_x11 && client_x11_get_proto(ssh, display,
2070 options.xauth_location, options.forward_x11_trusted,
2071 options.forward_x11_timeout, &proto, &data) == 0) {
2072 /* Request forwarding with authentication spoofing. */
2073 debug("Requesting X11 forwarding with authentication "
2075 x11_request_forwarding_with_spoofing(ssh, id, display, proto,
2077 client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
2078 /* XXX exit_on_forward_failure */
2082 check_agent_present();
2083 if (options.forward_agent) {
2084 debug("Requesting authentication agent forwarding.");
2085 channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
2086 if ((r = sshpkt_send(ssh)) != 0)
2087 fatal_fr(r, "send packet");
2090 /* Tell the packet module whether this is an interactive session. */
2091 ssh_packet_set_interactive(ssh, interactive,
2092 options.ip_qos_interactive, options.ip_qos_bulk);
2094 if ((term = lookup_env_in_list("TERM", options.setenv,
2095 options.num_setenv)) == NULL || *term == '\0')
2096 term = getenv("TERM");
2097 client_session2_setup(ssh, id, tty_flag,
2098 options.session_type == SESSION_TYPE_SUBSYSTEM, term,
2099 NULL, fileno(stdin), command, environ);
2102 /* open new channel for a session */
2104 ssh_session2_open(struct ssh *ssh)
2107 int window, packetmax, in, out, err;
2109 if (options.stdin_null) {
2110 in = open(_PATH_DEVNULL, O_RDONLY);
2112 in = dup(STDIN_FILENO);
2114 out = dup(STDOUT_FILENO);
2115 err = dup(STDERR_FILENO);
2117 if (in == -1 || out == -1 || err == -1)
2118 fatal("dup() in/out/err failed");
2120 window = CHAN_SES_WINDOW_DEFAULT;
2121 packetmax = CHAN_SES_PACKET_DEFAULT;
2126 c = channel_new(ssh,
2127 "session", SSH_CHANNEL_OPENING, in, out, err,
2128 window, packetmax, CHAN_EXTENDED_WRITE,
2129 "client-session", CHANNEL_NONBLOCK_STDIO);
2131 debug3_f("channel_new: %d", c->self);
2133 channel_send_open(ssh, c->self);
2134 if (options.session_type != SESSION_TYPE_NONE)
2135 channel_register_open_confirm(ssh, c->self,
2136 ssh_session2_setup, NULL);
2142 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2145 char *cp, *tun_fwd_ifname = NULL;
2147 /* XXX should be pre-session */
2148 if (!options.control_persist)
2149 ssh_init_stdio_forwarding(ssh);
2151 ssh_init_forwarding(ssh, &tun_fwd_ifname);
2153 if (options.local_command != NULL) {
2154 debug3("expanding LocalCommand: %s", options.local_command);
2155 cp = options.local_command;
2156 options.local_command = percent_expand(cp,
2157 DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2158 "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2160 debug3("expanded LocalCommand: %s", options.local_command);
2164 /* Start listening for multiplex clients */
2165 if (!ssh_packet_get_mux(ssh))
2166 muxserver_listen(ssh);
2169 * If we are in control persist mode and have a working mux listen
2170 * socket, then prepare to background ourselves and have a foreground
2171 * client attach as a control client.
2172 * NB. we must save copies of the flags that we override for
2173 * the backgrounding, since we defer attachment of the client until
2174 * after the connection is fully established (in particular,
2175 * async rfwd replies have been received for ExitOnForwardFailure).
2177 if (options.control_persist && muxserver_sock != -1) {
2178 ostdin_null_flag = options.stdin_null;
2179 osession_type = options.session_type;
2180 orequest_tty = options.request_tty;
2181 otty_flag = tty_flag;
2182 options.stdin_null = 1;
2183 options.session_type = SESSION_TYPE_NONE;
2185 if (!options.fork_after_authentication &&
2186 (osession_type != SESSION_TYPE_NONE ||
2187 options.stdio_forward_host != NULL))
2188 need_controlpersist_detach = 1;
2189 options.fork_after_authentication = 1;
2192 * ControlPersist mux listen socket setup failed, attempt the
2193 * stdio forward setup that we skipped earlier.
2195 if (options.control_persist && muxserver_sock == -1)
2196 ssh_init_stdio_forwarding(ssh);
2198 if (options.session_type != SESSION_TYPE_NONE)
2199 id = ssh_session2_open(ssh);
2201 ssh_packet_set_interactive(ssh,
2202 options.control_master == SSHCTL_MASTER_NO,
2203 options.ip_qos_interactive, options.ip_qos_bulk);
2206 /* If we don't expect to open a new session, then disallow it */
2207 if (options.control_master == SSHCTL_MASTER_NO &&
2208 (ssh->compat & SSH_NEW_OPENSSH)) {
2209 debug("Requesting no-more-sessions@openssh.com");
2210 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2211 (r = sshpkt_put_cstring(ssh,
2212 "no-more-sessions@openssh.com")) != 0 ||
2213 (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2214 (r = sshpkt_send(ssh)) != 0)
2215 fatal_fr(r, "send packet");
2218 /* Execute a local command */
2219 if (options.local_command != NULL &&
2220 options.permit_local_command)
2221 ssh_local_cmd(options.local_command);
2224 * stdout is now owned by the session channel; clobber it here
2225 * so future channel closes are propagated to the local fd.
2226 * NB. this can only happen after LocalCommand has completed,
2227 * as it may want to write to stdout.
2229 if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2230 error_f("stdfd_devnull failed");
2233 * If requested and we are not interested in replies to remote
2234 * forwarding requests, then let ssh continue in the background.
2236 if (options.fork_after_authentication) {
2237 if (options.exit_on_forward_failure &&
2238 options.num_remote_forwards > 0) {
2239 debug("deferring postauth fork until remote forward "
2240 "confirmation received");
2245 return client_loop(ssh, tty_flag, tty_flag ?
2246 options.escape_char : SSH_ESCAPECHAR_NONE, id);
2249 /* Loads all IdentityFile and CertificateFile keys */
2251 load_public_identity_files(const struct ssh_conn_info *cinfo)
2253 char *filename, *cp;
2254 struct sshkey *public;
2256 u_int n_ids, n_certs;
2257 char *identity_files[SSH_MAX_IDENTITY_FILES];
2258 struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2259 int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2260 char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2261 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2262 int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2263 #ifdef ENABLE_PKCS11
2264 struct sshkey **keys = NULL;
2265 char **comments = NULL;
2269 n_ids = n_certs = 0;
2270 memset(identity_files, 0, sizeof(identity_files));
2271 memset(identity_keys, 0, sizeof(identity_keys));
2272 memset(identity_file_userprovided, 0,
2273 sizeof(identity_file_userprovided));
2274 memset(certificate_files, 0, sizeof(certificate_files));
2275 memset(certificates, 0, sizeof(certificates));
2276 memset(certificate_file_userprovided, 0,
2277 sizeof(certificate_file_userprovided));
2279 #ifdef ENABLE_PKCS11
2280 if (options.pkcs11_provider != NULL &&
2281 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2282 (pkcs11_init(!options.batch_mode) == 0) &&
2283 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2284 &keys, &comments)) > 0) {
2285 for (i = 0; i < nkeys; i++) {
2286 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2287 sshkey_free(keys[i]);
2291 identity_keys[n_ids] = keys[i];
2292 identity_files[n_ids] = comments[i]; /* transferred */
2298 #endif /* ENABLE_PKCS11 */
2299 for (i = 0; i < options.num_identity_files; i++) {
2300 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2301 strcasecmp(options.identity_files[i], "none") == 0) {
2302 free(options.identity_files[i]);
2303 options.identity_files[i] = NULL;
2306 cp = tilde_expand_filename(options.identity_files[i], getuid());
2307 filename = default_client_percent_dollar_expand(cp, cinfo);
2309 check_load(sshkey_load_public(filename, &public, NULL),
2310 &public, filename, "pubkey");
2311 debug("identity file %s type %d", filename,
2312 public ? public->type : -1);
2313 free(options.identity_files[i]);
2314 identity_files[n_ids] = filename;
2315 identity_keys[n_ids] = public;
2316 identity_file_userprovided[n_ids] =
2317 options.identity_file_userprovided[i];
2318 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2322 * If no certificates have been explicitly listed then try
2323 * to add the default certificate variant too.
2325 if (options.num_certificate_files != 0)
2327 xasprintf(&cp, "%s-cert", filename);
2328 check_load(sshkey_load_public(cp, &public, NULL),
2329 &public, filename, "pubkey");
2330 debug("identity file %s type %d", cp,
2331 public ? public->type : -1);
2332 if (public == NULL) {
2336 if (!sshkey_is_cert(public)) {
2337 debug_f("key %s type %s is not a certificate",
2338 cp, sshkey_type(public));
2339 sshkey_free(public);
2343 /* NB. leave filename pointing to private key */
2344 identity_files[n_ids] = xstrdup(filename);
2345 identity_keys[n_ids] = public;
2346 identity_file_userprovided[n_ids] =
2347 options.identity_file_userprovided[i];
2351 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2352 fatal_f("too many certificates");
2353 for (i = 0; i < options.num_certificate_files; i++) {
2354 cp = tilde_expand_filename(options.certificate_files[i],
2356 filename = default_client_percent_dollar_expand(cp, cinfo);
2359 check_load(sshkey_load_public(filename, &public, NULL),
2360 &public, filename, "certificate");
2361 debug("certificate file %s type %d", filename,
2362 public ? public->type : -1);
2363 free(options.certificate_files[i]);
2364 options.certificate_files[i] = NULL;
2365 if (public == NULL) {
2369 if (!sshkey_is_cert(public)) {
2370 debug_f("key %s type %s is not a certificate",
2371 filename, sshkey_type(public));
2372 sshkey_free(public);
2376 certificate_files[n_certs] = filename;
2377 certificates[n_certs] = public;
2378 certificate_file_userprovided[n_certs] =
2379 options.certificate_file_userprovided[i];
2383 options.num_identity_files = n_ids;
2384 memcpy(options.identity_files, identity_files, sizeof(identity_files));
2385 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2386 memcpy(options.identity_file_userprovided,
2387 identity_file_userprovided, sizeof(identity_file_userprovided));
2389 options.num_certificate_files = n_certs;
2390 memcpy(options.certificate_files,
2391 certificate_files, sizeof(certificate_files));
2392 memcpy(options.certificates, certificates, sizeof(certificates));
2393 memcpy(options.certificate_file_userprovided,
2394 certificate_file_userprovided,
2395 sizeof(certificate_file_userprovided));
2399 main_sigchld_handler(int sig)
2401 int save_errno = errno;
2405 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2406 (pid == -1 && errno == EINTR))