1 /* $OpenBSD: ssh.c,v 1.490 2018/07/27 05:34:42 dtucker 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/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"
96 #include "pathnames.h"
98 #include "clientloop.h"
101 #include "readconf.h"
102 #include "sshconnect.h"
110 #include "myproposal.h"
114 #include "ssh-pkcs11.h"
117 extern char *__progname;
119 /* Saves a copy of argv for setproctitle emulation */
120 #ifndef HAVE_SETPROCTITLE
121 static char **saved_av;
124 /* Flag indicating whether debug mode is on. May be set on the command line. */
127 /* Flag indicating whether a tty should be requested */
130 /* don't exec a shell */
131 int no_shell_flag = 0;
134 * Flag indicating that nothing should be read from stdin. This can be set
135 * on the command line.
137 int stdin_null_flag = 0;
140 * Flag indicating that the current process should be backgrounded and
141 * a new slave launched in the foreground for ControlPersist.
143 int need_controlpersist_detach = 0;
145 /* Copies of flags for ControlPersist foreground slave */
146 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
149 * Flag indicating that ssh should fork after authentication. This is useful
150 * so that the passphrase can be entered manually, and then ssh goes to the
153 int fork_after_authentication_flag = 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 /* Various strings used to to percent_expand() arguments */
172 static char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
173 static char uidstr[32], *host_arg, *conn_hash_hex;
175 /* socket address the host resolves to */
176 struct sockaddr_storage hostaddr;
178 /* Private host keys. */
179 Sensitive sensitive_data;
181 /* command to be executed */
182 struct sshbuf *command;
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 [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]\n"
201 " [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]\n"
202 " [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]\n"
203 " [-i identity_file] [-J [user@]host[:port]] [-L address]\n"
204 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
205 " [-Q query_option] [-R address] [-S ctl_path] [-W host:port]\n"
206 " [-w local_tun[:remote_tun]] destination [command]\n"
211 static int ssh_session2(struct ssh *, struct passwd *);
212 static void load_public_identity_files(struct passwd *);
213 static void main_sigchld_handler(int);
215 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
217 tilde_expand_paths(char **paths, u_int num_paths)
222 for (i = 0; i < num_paths; i++) {
223 cp = tilde_expand_filename(paths[i], getuid());
230 * Attempt to resolve a host name / port to a set of addresses and
231 * optionally return any CNAMEs encountered along the way.
232 * Returns NULL on failure.
233 * NB. this function must operate with a options having undefined members.
235 static struct addrinfo *
236 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
238 char strport[NI_MAXSERV];
239 struct addrinfo hints, *res;
240 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
243 port = default_ssh_port();
245 snprintf(strport, sizeof strport, "%d", port);
246 memset(&hints, 0, sizeof(hints));
247 hints.ai_family = options.address_family == -1 ?
248 AF_UNSPEC : options.address_family;
249 hints.ai_socktype = SOCK_STREAM;
251 hints.ai_flags = AI_CANONNAME;
252 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
253 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
254 loglevel = SYSLOG_LEVEL_ERROR;
255 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
256 __progname, name, ssh_gai_strerror(gaierr));
259 if (cname != NULL && res->ai_canonname != NULL) {
260 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
261 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
262 __func__, name, res->ai_canonname, (u_long)clen);
270 /* Returns non-zero if name can only be an address and not a hostname */
272 is_addr_fast(const char *name)
274 return (strchr(name, '%') != NULL || strchr(name, ':') != NULL ||
275 strspn(name, "0123456789.") == strlen(name));
278 /* Returns non-zero if name represents a valid, single address */
280 is_addr(const char *name)
282 char strport[NI_MAXSERV];
283 struct addrinfo hints, *res;
285 if (is_addr_fast(name))
288 snprintf(strport, sizeof strport, "%u", default_ssh_port());
289 memset(&hints, 0, sizeof(hints));
290 hints.ai_family = options.address_family == -1 ?
291 AF_UNSPEC : options.address_family;
292 hints.ai_socktype = SOCK_STREAM;
293 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
294 if (getaddrinfo(name, strport, &hints, &res) != 0)
296 if (res == NULL || res->ai_next != NULL) {
305 * Attempt to resolve a numeric host address / port to a single address.
306 * Returns a canonical address string.
307 * Returns NULL on failure.
308 * NB. this function must operate with a options having undefined members.
310 static struct addrinfo *
311 resolve_addr(const char *name, int port, char *caddr, size_t clen)
313 char addr[NI_MAXHOST], strport[NI_MAXSERV];
314 struct addrinfo hints, *res;
318 port = default_ssh_port();
319 snprintf(strport, sizeof strport, "%u", port);
320 memset(&hints, 0, sizeof(hints));
321 hints.ai_family = options.address_family == -1 ?
322 AF_UNSPEC : options.address_family;
323 hints.ai_socktype = SOCK_STREAM;
324 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
325 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
326 debug2("%s: could not resolve name %.100s as address: %s",
327 __func__, name, ssh_gai_strerror(gaierr));
331 debug("%s: getaddrinfo %.100s returned no addresses",
335 if (res->ai_next != NULL) {
336 debug("%s: getaddrinfo %.100s returned multiple addresses",
340 if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
341 addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
342 debug("%s: Could not format address for name %.100s: %s",
343 __func__, name, ssh_gai_strerror(gaierr));
346 if (strlcpy(caddr, addr, clen) >= clen) {
347 error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
348 __func__, name, addr, (u_long)clen);
359 * Check whether the cname is a permitted replacement for the hostname
360 * and perform the replacement if it is.
361 * NB. this function must operate with a options having undefined members.
364 check_follow_cname(int direct, char **namep, const char *cname)
367 struct allowed_cname *rule;
369 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
370 strcmp(*namep, cname) == 0)
372 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
375 * Don't attempt to canonicalize names that will be interpreted by
376 * a proxy or jump host unless the user specifically requests so.
379 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
381 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
382 for (i = 0; i < options.num_permitted_cnames; i++) {
383 rule = options.permitted_cnames + i;
384 if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
385 match_pattern_list(cname, rule->target_list, 1) != 1)
387 verbose("Canonicalized DNS aliased hostname "
388 "\"%s\" => \"%s\"", *namep, cname);
390 *namep = xstrdup(cname);
397 * Attempt to resolve the supplied hostname after applying the user's
398 * canonicalization rules. Returns the address list for the host or NULL
399 * if no name was found after canonicalization.
400 * NB. this function must operate with a options having undefined members.
402 static struct addrinfo *
403 resolve_canonicalize(char **hostp, int port)
405 int i, direct, ndots;
406 char *cp, *fullhost, newname[NI_MAXHOST];
407 struct addrinfo *addrs;
410 * Attempt to canonicalise addresses, regardless of
411 * whether hostname canonicalisation was requested
413 if ((addrs = resolve_addr(*hostp, port,
414 newname, sizeof(newname))) != NULL) {
415 debug2("%s: hostname %.100s is address", __func__, *hostp);
416 if (strcasecmp(*hostp, newname) != 0) {
417 debug2("%s: canonicalised address \"%s\" => \"%s\"",
418 __func__, *hostp, newname);
420 *hostp = xstrdup(newname);
426 * If this looks like an address but didn't parse as one, it might
427 * be an address with an invalid interface scope. Skip further
428 * attempts at canonicalisation.
430 if (is_addr_fast(*hostp)) {
431 debug("%s: hostname %.100s is an unrecognised address",
436 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
440 * Don't attempt to canonicalize names that will be interpreted by
441 * a proxy unless the user specifically requests so.
443 direct = option_clear_or_none(options.proxy_command) &&
444 options.jump_host == NULL;
446 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
449 /* If domain name is anchored, then resolve it now */
450 if ((*hostp)[strlen(*hostp) - 1] == '.') {
451 debug3("%s: name is fully qualified", __func__);
452 fullhost = xstrdup(*hostp);
453 if ((addrs = resolve_host(fullhost, port, 0,
454 newname, sizeof(newname))) != NULL)
460 /* Don't apply canonicalization to sufficiently-qualified hostnames */
462 for (cp = *hostp; *cp != '\0'; cp++) {
466 if (ndots > options.canonicalize_max_dots) {
467 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
468 __func__, *hostp, options.canonicalize_max_dots);
471 /* Attempt each supplied suffix */
472 for (i = 0; i < options.num_canonical_domains; i++) {
474 xasprintf(&fullhost, "%s.%s.", *hostp,
475 options.canonical_domains[i]);
476 debug3("%s: attempting \"%s\" => \"%s\"", __func__,
478 if ((addrs = resolve_host(fullhost, port, 0,
479 newname, sizeof(newname))) == NULL) {
484 /* Remove trailing '.' */
485 fullhost[strlen(fullhost) - 1] = '\0';
486 /* Follow CNAME if requested */
487 if (!check_follow_cname(direct, &fullhost, newname)) {
488 debug("Canonicalized hostname \"%s\" => \"%s\"",
496 if (!options.canonicalize_fallback_local)
497 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
498 debug2("%s: host %s not found in any suffix", __func__, *hostp);
503 * Check the result of hostkey loading, ignoring some errors and
504 * fatal()ing for others.
507 check_load(int r, const char *path, const char *message)
512 case SSH_ERR_INTERNAL_ERROR:
513 case SSH_ERR_ALLOC_FAIL:
514 fatal("load %s \"%s\": %s", message, path, ssh_err(r));
515 case SSH_ERR_SYSTEM_ERROR:
516 /* Ignore missing files */
521 error("load %s \"%s\": %s", message, path, ssh_err(r));
527 * Read per-user configuration file. Ignore the system wide config
528 * file if the user specifies a config file on the command line.
531 process_config_files(const char *host_name, struct passwd *pw, int post_canon)
536 if (config != NULL) {
537 if (strcasecmp(config, "none") != 0 &&
538 !read_config_file(config, pw, host, host_name, &options,
539 SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
540 fatal("Can't open user config file %.100s: "
541 "%.100s", config, strerror(errno));
543 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
544 _PATH_SSH_USER_CONFFILE);
545 if (r > 0 && (size_t)r < sizeof(buf))
546 (void)read_config_file(buf, pw, host, host_name,
547 &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
548 (post_canon ? SSHCONF_POSTCANON : 0));
550 /* Read systemwide configuration file after user config. */
551 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
552 host, host_name, &options,
553 post_canon ? SSHCONF_POSTCANON : 0);
557 /* Rewrite the port number in an addrinfo list of addresses */
559 set_addrinfo_port(struct addrinfo *addrs, int port)
561 struct addrinfo *addr;
563 for (addr = addrs; addr != NULL; addr = addr->ai_next) {
564 switch (addr->ai_family) {
566 ((struct sockaddr_in *)addr->ai_addr)->
567 sin_port = htons(port);
570 ((struct sockaddr_in6 *)addr->ai_addr)->
571 sin6_port = htons(port);
578 * Main program for the ssh client.
581 main(int ac, char **av)
583 struct ssh *ssh = NULL;
584 int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
585 int was_addr, config_test = 0, opt_terminated = 0;
586 char *p, *cp, *line, *argv0, buf[PATH_MAX], *logfile;
587 char cname[NI_MAXHOST];
590 extern int optind, optreset;
593 struct addrinfo *addrs = NULL;
594 struct ssh_digest_ctx *md;
595 u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
597 ssh_malloc_init(); /* must be called before any mallocs */
598 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
601 __progname = ssh_get_progname(av[0]);
603 #ifndef HAVE_SETPROCTITLE
604 /* Prepare for later setproctitle emulation */
605 /* Save argv so it isn't clobbered by setproctitle() emulation */
606 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
607 for (i = 0; i < ac; i++)
608 saved_av[i] = xstrdup(av[i]);
610 compat_init_setproctitle(ac, av);
615 * Discard other fds that are hanging around. These can cause problem
616 * with backgrounded ssh processes started by ControlPersist.
618 closefrom(STDERR_FILENO + 1);
621 pw = getpwuid(getuid());
623 logit("No user exists for uid %lu", (u_long)getuid());
626 /* Take a copy of the returned structure. */
630 * Set our umask to something reasonable, as some files are created
631 * with the default umask. This will make them world-readable but
632 * writable only by the owner, which is ok for all files for which we
633 * don't set the modes explicitly.
640 * Initialize option structure to indicate that no values have been
643 initialize_options(&options);
646 * Prepare main ssh transport/connection structures
648 if ((ssh = ssh_alloc_session_state()) == NULL)
649 fatal("Couldn't allocate session state");
650 channel_init_channels(ssh);
651 active_state = ssh; /* XXX legacy API compat */
653 /* Parse command-line arguments. */
660 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
661 "AB:CD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
664 fatal("SSH protocol v.1 is no longer supported");
670 options.address_family = AF_INET;
673 options.address_family = AF_INET6;
679 fork_after_authentication_flag = 1;
683 options.forward_x11 = 0;
686 options.forward_x11 = 1;
698 options.forward_x11 = 1;
699 options.forward_x11_trusted = 1;
702 options.fwd_opts.gateway_ports = 1;
705 if (options.stdio_forward_host != NULL)
706 fatal("Cannot specify multiplexing "
708 else if (muxclient_command != 0)
709 fatal("Multiplexing command already specified");
710 if (strcmp(optarg, "check") == 0)
711 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
712 else if (strcmp(optarg, "forward") == 0)
713 muxclient_command = SSHMUX_COMMAND_FORWARD;
714 else if (strcmp(optarg, "exit") == 0)
715 muxclient_command = SSHMUX_COMMAND_TERMINATE;
716 else if (strcmp(optarg, "stop") == 0)
717 muxclient_command = SSHMUX_COMMAND_STOP;
718 else if (strcmp(optarg, "cancel") == 0)
719 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
720 else if (strcmp(optarg, "proxy") == 0)
721 muxclient_command = SSHMUX_COMMAND_PROXY;
723 fatal("Invalid multiplex command.");
725 case 'P': /* deprecated */
729 if (strcmp(optarg, "cipher") == 0)
730 cp = cipher_alg_list('\n', 0);
731 else if (strcmp(optarg, "cipher-auth") == 0)
732 cp = cipher_alg_list('\n', 1);
733 else if (strcmp(optarg, "mac") == 0)
734 cp = mac_alg_list('\n');
735 else if (strcmp(optarg, "kex") == 0)
736 cp = kex_alg_list('\n');
737 else if (strcmp(optarg, "key") == 0)
738 cp = sshkey_alg_list(0, 0, 0, '\n');
739 else if (strcmp(optarg, "key-cert") == 0)
740 cp = sshkey_alg_list(1, 0, 0, '\n');
741 else if (strcmp(optarg, "key-plain") == 0)
742 cp = sshkey_alg_list(0, 1, 0, '\n');
743 else if (strcmp(optarg, "protocol-version") == 0) {
747 fatal("Unsupported query \"%s\"", optarg);
753 options.forward_agent = 0;
756 options.forward_agent = 1;
759 options.gss_deleg_creds = 0;
762 options.gss_authentication = 1;
763 options.gss_deleg_creds = 1;
766 p = tilde_expand_filename(optarg, getuid());
767 if (stat(p, &st) < 0)
768 fprintf(stderr, "Warning: Identity file %s "
769 "not accessible: %s.\n", p,
772 add_identity_file(&options, NULL, p, 1);
777 free(options.pkcs11_provider);
778 options.pkcs11_provider = xstrdup(optarg);
780 fprintf(stderr, "no support for PKCS#11.\n");
784 if (options.jump_host != NULL)
785 fatal("Only a single -J option permitted");
786 if (options.proxy_command != NULL)
787 fatal("Cannot specify -J with ProxyCommand");
788 if (parse_jump(optarg, &options, 1) == -1)
789 fatal("Invalid -J argument");
790 options.proxy_command = xstrdup("none");
793 if (options.request_tty == REQUEST_TTY_YES)
794 options.request_tty = REQUEST_TTY_FORCE;
796 options.request_tty = REQUEST_TTY_YES;
799 if (debug_flag == 0) {
801 options.log_level = SYSLOG_LEVEL_DEBUG1;
803 if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
810 if (options.version_addendum &&
811 *options.version_addendum != '\0')
812 fprintf(stderr, "%s %s, %s\n", SSH_RELEASE,
813 options.version_addendum,
814 OPENSSL_VERSION_STRING);
816 fprintf(stderr, "%s, %s\n", SSH_RELEASE,
817 OPENSSL_VERSION_STRING);
822 if (options.tun_open == -1)
823 options.tun_open = SSH_TUNMODE_DEFAULT;
824 options.tun_local = a2tun(optarg, &options.tun_remote);
825 if (options.tun_local == SSH_TUNID_ERR) {
827 "Bad tun device '%s'\n", optarg);
832 if (options.stdio_forward_host != NULL)
833 fatal("stdio forward already specified");
834 if (muxclient_command != 0)
835 fatal("Cannot specify stdio forward with -O");
836 if (parse_forward(&fwd, optarg, 1, 0)) {
837 options.stdio_forward_host = fwd.listen_host;
838 options.stdio_forward_port = fwd.listen_port;
839 free(fwd.connect_host);
842 "Bad stdio forwarding specification '%s'\n",
846 options.request_tty = REQUEST_TTY_NO;
850 options.log_level = SYSLOG_LEVEL_QUIET;
853 if (optarg[0] == '^' && optarg[2] == 0 &&
854 (u_char) optarg[1] >= 64 &&
855 (u_char) optarg[1] < 128)
856 options.escape_char = (u_char) optarg[1] & 31;
857 else if (strlen(optarg) == 1)
858 options.escape_char = (u_char) optarg[0];
859 else if (strcmp(optarg, "none") == 0)
860 options.escape_char = SSH_ESCAPECHAR_NONE;
862 fprintf(stderr, "Bad escape character '%s'.\n",
868 if (!ciphers_valid(*optarg == '+' ?
869 optarg + 1 : optarg)) {
870 fprintf(stderr, "Unknown cipher type '%s'\n",
874 free(options.ciphers);
875 options.ciphers = xstrdup(optarg);
878 if (mac_valid(optarg)) {
880 options.macs = xstrdup(optarg);
882 fprintf(stderr, "Unknown mac type '%s'\n",
888 if (options.control_master == SSHCTL_MASTER_YES)
889 options.control_master = SSHCTL_MASTER_ASK;
891 options.control_master = SSHCTL_MASTER_YES;
894 if (options.port == -1) {
895 options.port = a2port(optarg);
896 if (options.port <= 0) {
897 fprintf(stderr, "Bad port '%s'\n",
904 if (options.user == NULL)
905 options.user = optarg;
909 if (parse_forward(&fwd, optarg, 0, 0))
910 add_local_forward(&options, &fwd);
913 "Bad local forwarding specification '%s'\n",
920 if (parse_forward(&fwd, optarg, 0, 1) ||
921 parse_forward(&fwd, optarg, 1, 1)) {
922 add_remote_forward(&options, &fwd);
925 "Bad remote forwarding specification "
932 if (parse_forward(&fwd, optarg, 1, 0)) {
933 add_local_forward(&options, &fwd);
936 "Bad dynamic forwarding specification "
943 options.compression = 1;
947 options.request_tty = REQUEST_TTY_NO;
950 options.request_tty = REQUEST_TTY_NO;
953 line = xstrdup(optarg);
954 if (process_config_line(&options, pw,
955 host ? host : "", host ? host : "", line,
956 "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
964 free(options.control_path);
965 options.control_path = xstrdup(optarg);
968 options.bind_address = optarg;
971 options.bind_interface = optarg;
981 if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
987 if (ac > 0 && !host) {
990 switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
995 if (options.user == NULL) {
996 options.user = tuser;
1000 if (options.port == -1 && tport != -1)
1001 options.port = tport;
1005 cp = strrchr(p, '@');
1009 if (options.user == NULL) {
1020 if (ac > 1 && !opt_terminated) {
1021 optind = optreset = 1;
1027 /* Check that we got a host name. */
1031 host_arg = xstrdup(host);
1034 OpenSSL_add_all_algorithms();
1035 ERR_load_crypto_strings();
1038 /* Initialize the command to execute on remote host. */
1039 if ((command = sshbuf_new()) == NULL)
1040 fatal("sshbuf_new failed");
1043 * Save the command to execute on the remote host in a buffer. There
1044 * is no limit on the length of the command, except by the maximum
1045 * packet size. Also sets the tty flag if there is no command.
1048 /* No command specified - execute shell on a tty. */
1049 if (subsystem_flag) {
1051 "You must specify a subsystem to invoke.\n");
1055 /* A command has been specified. Store it into the buffer. */
1056 for (i = 0; i < ac; i++) {
1057 if ((r = sshbuf_putf(command, "%s%s",
1058 i ? " " : "", av[i])) != 0)
1059 fatal("%s: buffer error: %s",
1060 __func__, ssh_err(r));
1065 * Initialize "log" output. Since we are the client all output
1066 * goes to stderr unless otherwise specified by -y or -E.
1068 if (use_syslog && logfile != NULL)
1069 fatal("Can't specify both -y and -E");
1070 if (logfile != NULL)
1071 log_redirect_stderr_to(logfile);
1073 options.log_level == SYSLOG_LEVEL_NOT_SET ?
1074 SYSLOG_LEVEL_INFO : options.log_level,
1075 options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1076 SYSLOG_FACILITY_USER : options.log_facility,
1080 /* version_addendum is always NULL at this point */
1081 logit("%s, %s", SSH_RELEASE, OPENSSL_VERSION_STRING);
1083 /* Parse the configuration files */
1084 process_config_files(host_arg, pw, 0);
1086 /* Hostname canonicalisation needs a few options filled. */
1087 fill_default_options_for_canonicalization(&options);
1089 /* If the user has replaced the hostname then take it into use now */
1090 if (options.hostname != NULL) {
1091 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1092 cp = percent_expand(options.hostname,
1093 "h", host, (char *)NULL);
1096 free(options.hostname);
1097 options.hostname = xstrdup(host);
1100 /* Don't lowercase addresses, they will be explicitly canonicalised */
1101 if ((was_addr = is_addr(host)) == 0)
1105 * Try to canonicalize if requested by configuration or the
1106 * hostname is an address.
1108 if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1109 addrs = resolve_canonicalize(&host, options.port);
1112 * If CanonicalizePermittedCNAMEs have been specified but
1113 * other canonicalization did not happen (by not being requested
1114 * or by failing with fallback) then the hostname may still be changed
1115 * as a result of CNAME following.
1117 * Try to resolve the bare hostname name using the system resolver's
1118 * usual search rules and then apply the CNAME follow rules.
1120 * Skip the lookup if a ProxyCommand is being used unless the user
1121 * has specifically requested canonicalisation for this case via
1122 * CanonicalizeHostname=always
1124 direct = option_clear_or_none(options.proxy_command) &&
1125 options.jump_host == NULL;
1126 if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1127 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1128 if ((addrs = resolve_host(host, options.port,
1129 option_clear_or_none(options.proxy_command),
1130 cname, sizeof(cname))) == NULL) {
1131 /* Don't fatal proxied host names not in the DNS */
1132 if (option_clear_or_none(options.proxy_command))
1133 cleanup_exit(255); /* logged in resolve_host */
1135 check_follow_cname(direct, &host, cname);
1139 * If canonicalisation is enabled then re-parse the configuration
1140 * files as new stanzas may match.
1142 if (options.canonicalize_hostname != 0) {
1143 debug("Re-reading configuration after hostname "
1144 "canonicalisation");
1145 free(options.hostname);
1146 options.hostname = xstrdup(host);
1147 process_config_files(host_arg, pw, 1);
1149 * Address resolution happens early with canonicalisation
1150 * enabled and the port number may have changed since, so
1151 * reset it in address list
1153 if (addrs != NULL && options.port > 0)
1154 set_addrinfo_port(addrs, options.port);
1157 /* Fill configuration defaults. */
1158 fill_default_options(&options);
1161 * If ProxyJump option specified, then construct a ProxyCommand now.
1163 if (options.jump_host != NULL) {
1165 const char *sshbin = argv0;
1168 * Try to use SSH indicated by argv[0], but fall back to
1169 * "ssh" if it appears unavailable.
1171 if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1174 /* Consistency check */
1175 if (options.proxy_command != NULL)
1176 fatal("inconsistent options: ProxyCommand+ProxyJump");
1177 /* Never use FD passing for ProxyJump */
1178 options.proxy_use_fdpass = 0;
1179 snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1180 xasprintf(&options.proxy_command,
1181 "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1183 /* Optional "-l user" argument if jump_user set */
1184 options.jump_user == NULL ? "" : " -l ",
1185 options.jump_user == NULL ? "" : options.jump_user,
1186 /* Optional "-p port" argument if jump_port set */
1187 options.jump_port <= 0 ? "" : " -p ",
1188 options.jump_port <= 0 ? "" : port_s,
1189 /* Optional additional jump hosts ",..." */
1190 options.jump_extra == NULL ? "" : " -J ",
1191 options.jump_extra == NULL ? "" : options.jump_extra,
1192 /* Optional "-F" argumment if -F specified */
1193 config == NULL ? "" : " -F ",
1194 config == NULL ? "" : config,
1195 /* Optional "-v" arguments if -v set */
1196 debug_flag ? " -" : "",
1198 /* Mandatory hostname */
1200 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1201 options.proxy_command);
1204 if (options.port == 0)
1205 options.port = default_ssh_port();
1206 channel_set_af(ssh, options.address_family);
1208 /* Tidy and check options */
1209 if (options.host_key_alias != NULL)
1210 lowercase(options.host_key_alias);
1211 if (options.proxy_command != NULL &&
1212 strcmp(options.proxy_command, "-") == 0 &&
1213 options.proxy_use_fdpass)
1214 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1215 if (options.control_persist &&
1216 options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1217 debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1219 options.update_hostkeys = 0;
1221 if (options.connection_attempts <= 0)
1222 fatal("Invalid number of ConnectionAttempts");
1224 if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1225 fatal("Cannot execute command-line and remote command.");
1227 /* Cannot fork to background if no command. */
1228 if (fork_after_authentication_flag && sshbuf_len(command) == 0 &&
1229 options.remote_command == NULL && !no_shell_flag)
1230 fatal("Cannot fork into background without a command "
1234 log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1236 if (options.request_tty == REQUEST_TTY_YES ||
1237 options.request_tty == REQUEST_TTY_FORCE)
1240 /* Allocate a tty by default if no command specified. */
1241 if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1242 tty_flag = options.request_tty != REQUEST_TTY_NO;
1245 if (options.request_tty == REQUEST_TTY_NO ||
1246 (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1248 /* Do not allocate a tty if stdin is not a tty. */
1249 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1250 options.request_tty != REQUEST_TTY_FORCE) {
1252 logit("Pseudo-terminal will not be allocated because "
1253 "stdin is not a terminal.");
1259 if (options.user == NULL)
1260 options.user = xstrdup(pw->pw_name);
1262 /* Set up strings used to percent_expand() arguments */
1263 if (gethostname(thishost, sizeof(thishost)) == -1)
1264 fatal("gethostname: %s", strerror(errno));
1265 strlcpy(shorthost, thishost, sizeof(shorthost));
1266 shorthost[strcspn(thishost, ".")] = '\0';
1267 snprintf(portstr, sizeof(portstr), "%d", options.port);
1268 snprintf(uidstr, sizeof(uidstr), "%llu",
1269 (unsigned long long)pw->pw_uid);
1271 /* Find canonic host name. */
1272 if (strchr(host, '.') == 0) {
1273 struct addrinfo hints;
1274 struct addrinfo *ai = NULL;
1276 memset(&hints, 0, sizeof(hints));
1277 hints.ai_family = options.address_family;
1278 hints.ai_flags = AI_CANONNAME;
1279 hints.ai_socktype = SOCK_STREAM;
1280 errgai = getaddrinfo(host, NULL, &hints, &ai);
1282 if (ai->ai_canonname != NULL)
1283 host = xstrdup(ai->ai_canonname);
1288 if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1289 ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1290 ssh_digest_update(md, host, strlen(host)) < 0 ||
1291 ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1292 ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1293 ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1294 fatal("%s: mux digest failed", __func__);
1295 ssh_digest_free(md);
1296 conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1299 * Expand tokens in arguments. NB. LocalCommand is expanded later,
1300 * after port-forwarding is set up, so it may pick up any local
1301 * tunnel interface name allocated.
1303 if (options.remote_command != NULL) {
1304 debug3("expanding RemoteCommand: %s", options.remote_command);
1305 cp = options.remote_command;
1306 options.remote_command = percent_expand(cp,
1318 debug3("expanded RemoteCommand: %s", options.remote_command);
1320 if ((r = sshbuf_put(command, options.remote_command,
1321 strlen(options.remote_command))) != 0)
1322 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1325 if (options.control_path != NULL) {
1326 cp = tilde_expand_filename(options.control_path, getuid());
1327 free(options.control_path);
1328 options.control_path = percent_expand(cp,
1344 dump_client_config(&options, host);
1348 if (muxclient_command != 0 && options.control_path == NULL)
1349 fatal("No ControlPath specified for \"-O\" command");
1350 if (options.control_path != NULL) {
1352 if ((sock = muxclient(options.control_path)) >= 0) {
1353 ssh_packet_set_connection(ssh, sock, sock);
1360 * If hostname canonicalisation was not enabled, then we may not
1361 * have yet resolved the hostname. Do so now.
1363 if (addrs == NULL && options.proxy_command == NULL) {
1364 debug2("resolving \"%s\" port %d", host, options.port);
1365 if ((addrs = resolve_host(host, options.port, 1,
1366 cname, sizeof(cname))) == NULL)
1367 cleanup_exit(255); /* resolve_host logs the error */
1370 timeout_ms = options.connection_timeout * 1000;
1372 /* Open a connection to the remote host. */
1373 if (ssh_connect(ssh, host, addrs, &hostaddr, options.port,
1374 options.address_family, options.connection_attempts,
1375 &timeout_ms, options.tcp_keep_alive) != 0)
1379 freeaddrinfo(addrs);
1381 packet_set_timeout(options.server_alive_interval,
1382 options.server_alive_count_max);
1384 ssh = active_state; /* XXX */
1387 debug3("timeout: %d ms remain after connect", timeout_ms);
1390 * If we successfully made the connection and we have hostbased auth
1391 * enabled, load the public keys so we can later use the ssh-keysign
1392 * helper to sign challenges.
1394 sensitive_data.nkeys = 0;
1395 sensitive_data.keys = NULL;
1396 if (options.hostbased_authentication) {
1397 sensitive_data.nkeys = 10;
1398 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1399 sizeof(struct sshkey));
1401 /* XXX check errors? */
1402 #define L_PUBKEY(p,o) do { \
1403 if ((o) >= sensitive_data.nkeys) \
1404 fatal("%s pubkey out of array bounds", __func__); \
1405 check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1408 #define L_CERT(p,o) do { \
1409 if ((o) >= sensitive_data.nkeys) \
1410 fatal("%s cert out of array bounds", __func__); \
1411 check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), p, "cert"); \
1414 if (options.hostbased_authentication == 1) {
1415 L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1416 L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1417 L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1418 L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1419 L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1420 L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1421 L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1422 L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1423 L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1424 L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1428 /* Create ~/.ssh * directory if it doesn't already exist. */
1429 if (config == NULL) {
1430 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1431 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1432 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1434 ssh_selinux_setfscreatecon(buf);
1436 if (mkdir(buf, 0700) < 0)
1437 error("Could not create directory '%.200s'.",
1440 ssh_selinux_setfscreatecon(NULL);
1444 /* load options.identity_files */
1445 load_public_identity_files(pw);
1447 /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1448 if (options.identity_agent &&
1449 strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1450 if (strcmp(options.identity_agent, "none") == 0) {
1451 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1453 p = tilde_expand_filename(options.identity_agent,
1455 cp = percent_expand(p,
1463 setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1469 /* Expand ~ in known host file names. */
1470 tilde_expand_paths(options.system_hostfiles,
1471 options.num_system_hostfiles);
1472 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1474 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1475 signal(SIGCHLD, main_sigchld_handler);
1477 /* Log into the remote system. Never returns if the login fails. */
1478 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1479 options.port, pw, timeout_ms);
1481 if (packet_connection_is_on_socket()) {
1482 verbose("Authenticated to %s ([%s]:%d).", host,
1483 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1485 verbose("Authenticated to %s (via proxy).", host);
1488 /* We no longer need the private host keys. Clear them now. */
1489 if (sensitive_data.nkeys != 0) {
1490 for (i = 0; i < sensitive_data.nkeys; i++) {
1491 if (sensitive_data.keys[i] != NULL) {
1492 /* Destroys contents safely */
1493 debug3("clear hostkey %d", i);
1494 sshkey_free(sensitive_data.keys[i]);
1495 sensitive_data.keys[i] = NULL;
1498 free(sensitive_data.keys);
1500 for (i = 0; i < options.num_identity_files; i++) {
1501 free(options.identity_files[i]);
1502 options.identity_files[i] = NULL;
1503 if (options.identity_keys[i]) {
1504 sshkey_free(options.identity_keys[i]);
1505 options.identity_keys[i] = NULL;
1508 for (i = 0; i < options.num_certificate_files; i++) {
1509 free(options.certificate_files[i]);
1510 options.certificate_files[i] = NULL;
1514 exit_status = ssh_session2(ssh, pw);
1517 if (options.control_path != NULL && muxserver_sock != -1)
1518 unlink(options.control_path);
1520 /* Kill ProxyCommand if it is running. */
1521 ssh_kill_proxy_command();
1527 control_persist_detach(void)
1530 int devnull, keep_stderr;
1532 debug("%s: backgrounding master process", __func__);
1535 * master (current process) into the background, and make the
1536 * foreground process a client of the backgrounded master.
1538 switch ((pid = fork())) {
1540 fatal("%s: fork: %s", __func__, strerror(errno));
1542 /* Child: master process continues mainloop */
1545 /* Parent: set up mux slave to connect to backgrounded master */
1546 debug2("%s: background process is %ld", __func__, (long)pid);
1547 stdin_null_flag = ostdin_null_flag;
1548 options.request_tty = orequest_tty;
1549 tty_flag = otty_flag;
1550 close(muxserver_sock);
1551 muxserver_sock = -1;
1552 options.control_master = SSHCTL_MASTER_NO;
1553 muxclient(options.control_path);
1554 /* muxclient() doesn't return on success. */
1555 fatal("Failed to connect to new control master");
1557 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1558 error("%s: open(\"/dev/null\"): %s", __func__,
1561 keep_stderr = log_is_on_stderr() && debug_flag;
1562 if (dup2(devnull, STDIN_FILENO) == -1 ||
1563 dup2(devnull, STDOUT_FILENO) == -1 ||
1564 (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
1565 error("%s: dup2: %s", __func__, strerror(errno));
1566 if (devnull > STDERR_FILENO)
1570 setproctitle("%s [mux]", options.control_path);
1573 /* Do fork() after authentication. Used by "ssh -f" */
1577 if (need_controlpersist_detach)
1578 control_persist_detach();
1579 debug("forking to background");
1580 fork_after_authentication_flag = 0;
1581 if (daemon(1, 1) < 0)
1582 fatal("daemon() failed: %.200s", strerror(errno));
1585 /* Callback for remote forward global requests */
1587 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1589 struct Forward *rfwd = (struct Forward *)ctxt;
1591 /* XXX verbose() on failure? */
1592 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1593 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1594 rfwd->listen_path ? rfwd->listen_path :
1595 rfwd->listen_host ? rfwd->listen_host : "",
1596 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1597 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1598 rfwd->connect_host, rfwd->connect_port);
1599 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1600 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1601 rfwd->allocated_port = packet_get_int();
1602 logit("Allocated port %u for remote forward to %s:%d",
1603 rfwd->allocated_port,
1604 rfwd->connect_host, rfwd->connect_port);
1605 channel_update_permission(ssh,
1606 rfwd->handle, rfwd->allocated_port);
1608 channel_update_permission(ssh, rfwd->handle, -1);
1612 if (type == SSH2_MSG_REQUEST_FAILURE) {
1613 if (options.exit_on_forward_failure) {
1614 if (rfwd->listen_path != NULL)
1615 fatal("Error: remote port forwarding failed "
1616 "for listen path %s", rfwd->listen_path);
1618 fatal("Error: remote port forwarding failed "
1619 "for listen port %d", rfwd->listen_port);
1621 if (rfwd->listen_path != NULL)
1622 logit("Warning: remote port forwarding failed "
1623 "for listen path %s", rfwd->listen_path);
1625 logit("Warning: remote port forwarding failed "
1626 "for listen port %d", rfwd->listen_port);
1629 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1630 debug("All remote forwarding requests processed");
1631 if (fork_after_authentication_flag)
1637 client_cleanup_stdio_fwd(struct ssh *ssh, int id, void *arg)
1639 debug("stdio forwarding: done");
1644 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1647 fatal("stdio forwarding failed");
1651 ssh_init_stdio_forwarding(struct ssh *ssh)
1656 if (options.stdio_forward_host == NULL)
1659 debug3("%s: %s:%d", __func__, options.stdio_forward_host,
1660 options.stdio_forward_port);
1662 if ((in = dup(STDIN_FILENO)) < 0 ||
1663 (out = dup(STDOUT_FILENO)) < 0)
1664 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1665 if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1666 options.stdio_forward_port, in, out)) == NULL)
1667 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1668 channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1669 channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1673 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1678 /* Initiate local TCP/IP port forwardings. */
1679 for (i = 0; i < options.num_local_forwards; i++) {
1680 debug("Local connections to %.200s:%d forwarded to remote "
1681 "address %.200s:%d",
1682 (options.local_forwards[i].listen_path != NULL) ?
1683 options.local_forwards[i].listen_path :
1684 (options.local_forwards[i].listen_host == NULL) ?
1685 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1686 options.local_forwards[i].listen_host,
1687 options.local_forwards[i].listen_port,
1688 (options.local_forwards[i].connect_path != NULL) ?
1689 options.local_forwards[i].connect_path :
1690 options.local_forwards[i].connect_host,
1691 options.local_forwards[i].connect_port);
1692 success += channel_setup_local_fwd_listener(ssh,
1693 &options.local_forwards[i], &options.fwd_opts);
1695 if (i > 0 && success != i && options.exit_on_forward_failure)
1696 fatal("Could not request local forwarding.");
1697 if (i > 0 && success == 0)
1698 error("Could not request local forwarding.");
1700 /* Initiate remote TCP/IP port forwardings. */
1701 for (i = 0; i < options.num_remote_forwards; i++) {
1702 debug("Remote connections from %.200s:%d forwarded to "
1703 "local address %.200s:%d",
1704 (options.remote_forwards[i].listen_path != NULL) ?
1705 options.remote_forwards[i].listen_path :
1706 (options.remote_forwards[i].listen_host == NULL) ?
1707 "LOCALHOST" : options.remote_forwards[i].listen_host,
1708 options.remote_forwards[i].listen_port,
1709 (options.remote_forwards[i].connect_path != NULL) ?
1710 options.remote_forwards[i].connect_path :
1711 options.remote_forwards[i].connect_host,
1712 options.remote_forwards[i].connect_port);
1713 options.remote_forwards[i].handle =
1714 channel_request_remote_forwarding(ssh,
1715 &options.remote_forwards[i]);
1716 if (options.remote_forwards[i].handle < 0) {
1717 if (options.exit_on_forward_failure)
1718 fatal("Could not request remote forwarding.");
1720 logit("Warning: Could not request remote "
1723 client_register_global_confirm(
1724 ssh_confirm_remote_forward,
1725 &options.remote_forwards[i]);
1729 /* Initiate tunnel forwarding. */
1730 if (options.tun_open != SSH_TUNMODE_NO) {
1731 if ((*ifname = client_request_tun_fwd(ssh,
1732 options.tun_open, options.tun_local,
1733 options.tun_remote)) == NULL) {
1734 if (options.exit_on_forward_failure)
1735 fatal("Could not request tunnel forwarding.");
1737 error("Could not request tunnel forwarding.");
1743 check_agent_present(void)
1747 if (options.forward_agent) {
1748 /* Clear agent forwarding if we don't have an agent. */
1749 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1750 options.forward_agent = 0;
1751 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1752 debug("ssh_get_authentication_socket: %s",
1759 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
1761 extern char **environ;
1762 const char *display;
1763 int interactive = tty_flag;
1764 char *proto = NULL, *data = NULL;
1767 return; /* No need for error message, channels code sens one */
1769 display = getenv("DISPLAY");
1770 if (display == NULL && options.forward_x11)
1771 debug("X11 forwarding requested but DISPLAY not set");
1772 if (options.forward_x11 && client_x11_get_proto(ssh, display,
1773 options.xauth_location, options.forward_x11_trusted,
1774 options.forward_x11_timeout, &proto, &data) == 0) {
1775 /* Request forwarding with authentication spoofing. */
1776 debug("Requesting X11 forwarding with authentication "
1778 x11_request_forwarding_with_spoofing(ssh, id, display, proto,
1780 client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
1781 /* XXX exit_on_forward_failure */
1785 check_agent_present();
1786 if (options.forward_agent) {
1787 debug("Requesting authentication agent forwarding.");
1788 channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
1792 /* Tell the packet module whether this is an interactive session. */
1793 packet_set_interactive(interactive,
1794 options.ip_qos_interactive, options.ip_qos_bulk);
1796 client_session2_setup(ssh, id, tty_flag, subsystem_flag, getenv("TERM"),
1797 NULL, fileno(stdin), command, environ);
1800 /* open new channel for a session */
1802 ssh_session2_open(struct ssh *ssh)
1805 int window, packetmax, in, out, err;
1807 if (stdin_null_flag) {
1808 in = open(_PATH_DEVNULL, O_RDONLY);
1810 in = dup(STDIN_FILENO);
1812 out = dup(STDOUT_FILENO);
1813 err = dup(STDERR_FILENO);
1815 if (in < 0 || out < 0 || err < 0)
1816 fatal("dup() in/out/err failed");
1818 /* enable nonblocking unless tty */
1826 window = CHAN_SES_WINDOW_DEFAULT;
1827 packetmax = CHAN_SES_PACKET_DEFAULT;
1832 c = channel_new(ssh,
1833 "session", SSH_CHANNEL_OPENING, in, out, err,
1834 window, packetmax, CHAN_EXTENDED_WRITE,
1835 "client-session", /*nonblock*/0);
1837 debug3("%s: channel_new: %d", __func__, c->self);
1839 channel_send_open(ssh, c->self);
1841 channel_register_open_confirm(ssh, c->self,
1842 ssh_session2_setup, NULL);
1848 ssh_session2(struct ssh *ssh, struct passwd *pw)
1850 int devnull, id = -1;
1851 char *cp, *tun_fwd_ifname = NULL;
1853 /* XXX should be pre-session */
1854 if (!options.control_persist)
1855 ssh_init_stdio_forwarding(ssh);
1857 ssh_init_forwarding(ssh, &tun_fwd_ifname);
1859 if (options.local_command != NULL) {
1860 debug3("expanding LocalCommand: %s", options.local_command);
1861 cp = options.local_command;
1862 options.local_command = percent_expand(cp,
1873 "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
1875 debug3("expanded LocalCommand: %s", options.local_command);
1879 /* Start listening for multiplex clients */
1880 if (!packet_get_mux())
1881 muxserver_listen(ssh);
1884 * If we are in control persist mode and have a working mux listen
1885 * socket, then prepare to background ourselves and have a foreground
1886 * client attach as a control slave.
1887 * NB. we must save copies of the flags that we override for
1888 * the backgrounding, since we defer attachment of the slave until
1889 * after the connection is fully established (in particular,
1890 * async rfwd replies have been received for ExitOnForwardFailure).
1892 if (options.control_persist && muxserver_sock != -1) {
1893 ostdin_null_flag = stdin_null_flag;
1894 ono_shell_flag = no_shell_flag;
1895 orequest_tty = options.request_tty;
1896 otty_flag = tty_flag;
1897 stdin_null_flag = 1;
1900 if (!fork_after_authentication_flag)
1901 need_controlpersist_detach = 1;
1902 fork_after_authentication_flag = 1;
1905 * ControlPersist mux listen socket setup failed, attempt the
1906 * stdio forward setup that we skipped earlier.
1908 if (options.control_persist && muxserver_sock == -1)
1909 ssh_init_stdio_forwarding(ssh);
1912 id = ssh_session2_open(ssh);
1914 packet_set_interactive(
1915 options.control_master == SSHCTL_MASTER_NO,
1916 options.ip_qos_interactive, options.ip_qos_bulk);
1919 /* If we don't expect to open a new session, then disallow it */
1920 if (options.control_master == SSHCTL_MASTER_NO &&
1921 (datafellows & SSH_NEW_OPENSSH)) {
1922 debug("Requesting no-more-sessions@openssh.com");
1923 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1924 packet_put_cstring("no-more-sessions@openssh.com");
1929 /* Execute a local command */
1930 if (options.local_command != NULL &&
1931 options.permit_local_command)
1932 ssh_local_cmd(options.local_command);
1935 * stdout is now owned by the session channel; clobber it here
1936 * so future channel closes are propagated to the local fd.
1937 * NB. this can only happen after LocalCommand has completed,
1938 * as it may want to write to stdout.
1940 if (!need_controlpersist_detach) {
1941 if ((devnull = open(_PATH_DEVNULL, O_WRONLY)) == -1)
1942 error("%s: open %s: %s", __func__,
1943 _PATH_DEVNULL, strerror(errno));
1944 if (dup2(devnull, STDOUT_FILENO) < 0)
1945 fatal("%s: dup2() stdout failed", __func__);
1946 if (devnull > STDERR_FILENO)
1951 * If requested and we are not interested in replies to remote
1952 * forwarding requests, then let ssh continue in the background.
1954 if (fork_after_authentication_flag) {
1955 if (options.exit_on_forward_failure &&
1956 options.num_remote_forwards > 0) {
1957 debug("deferring postauth fork until remote forward "
1958 "confirmation received");
1963 return client_loop(ssh, tty_flag, tty_flag ?
1964 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1967 /* Loads all IdentityFile and CertificateFile keys */
1969 load_public_identity_files(struct passwd *pw)
1971 char *filename, *cp;
1972 struct sshkey *public;
1974 u_int n_ids, n_certs;
1975 char *identity_files[SSH_MAX_IDENTITY_FILES];
1976 struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
1977 int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
1978 char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
1979 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
1980 int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
1981 #ifdef ENABLE_PKCS11
1982 struct sshkey **keys;
1986 n_ids = n_certs = 0;
1987 memset(identity_files, 0, sizeof(identity_files));
1988 memset(identity_keys, 0, sizeof(identity_keys));
1989 memset(identity_file_userprovided, 0,
1990 sizeof(identity_file_userprovided));
1991 memset(certificate_files, 0, sizeof(certificate_files));
1992 memset(certificates, 0, sizeof(certificates));
1993 memset(certificate_file_userprovided, 0,
1994 sizeof(certificate_file_userprovided));
1996 #ifdef ENABLE_PKCS11
1997 if (options.pkcs11_provider != NULL &&
1998 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1999 (pkcs11_init(!options.batch_mode) == 0) &&
2000 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2002 for (i = 0; i < nkeys; i++) {
2003 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2004 sshkey_free(keys[i]);
2007 identity_keys[n_ids] = keys[i];
2008 identity_files[n_ids] =
2009 xstrdup(options.pkcs11_provider); /* XXX */
2014 #endif /* ENABLE_PKCS11 */
2015 for (i = 0; i < options.num_identity_files; i++) {
2016 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2017 strcasecmp(options.identity_files[i], "none") == 0) {
2018 free(options.identity_files[i]);
2019 options.identity_files[i] = NULL;
2022 cp = tilde_expand_filename(options.identity_files[i], getuid());
2023 filename = percent_expand(cp, "d", pw->pw_dir,
2024 "u", pw->pw_name, "l", thishost, "h", host,
2025 "r", options.user, (char *)NULL);
2027 check_load(sshkey_load_public(filename, &public, NULL),
2028 filename, "pubkey");
2029 debug("identity file %s type %d", filename,
2030 public ? public->type : -1);
2031 free(options.identity_files[i]);
2032 identity_files[n_ids] = filename;
2033 identity_keys[n_ids] = public;
2034 identity_file_userprovided[n_ids] =
2035 options.identity_file_userprovided[i];
2036 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2040 * If no certificates have been explicitly listed then try
2041 * to add the default certificate variant too.
2043 if (options.num_certificate_files != 0)
2045 xasprintf(&cp, "%s-cert", filename);
2046 check_load(sshkey_load_public(cp, &public, NULL),
2047 filename, "pubkey");
2048 debug("identity file %s type %d", cp,
2049 public ? public->type : -1);
2050 if (public == NULL) {
2054 if (!sshkey_is_cert(public)) {
2055 debug("%s: key %s type %s is not a certificate",
2056 __func__, cp, sshkey_type(public));
2057 sshkey_free(public);
2061 /* NB. leave filename pointing to private key */
2062 identity_files[n_ids] = xstrdup(filename);
2063 identity_keys[n_ids] = public;
2064 identity_file_userprovided[n_ids] =
2065 options.identity_file_userprovided[i];
2069 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2070 fatal("%s: too many certificates", __func__);
2071 for (i = 0; i < options.num_certificate_files; i++) {
2072 cp = tilde_expand_filename(options.certificate_files[i],
2074 filename = percent_expand(cp,
2084 check_load(sshkey_load_public(filename, &public, NULL),
2085 filename, "certificate");
2086 debug("certificate file %s type %d", filename,
2087 public ? public->type : -1);
2088 free(options.certificate_files[i]);
2089 options.certificate_files[i] = NULL;
2090 if (public == NULL) {
2094 if (!sshkey_is_cert(public)) {
2095 debug("%s: key %s type %s is not a certificate",
2096 __func__, filename, sshkey_type(public));
2097 sshkey_free(public);
2101 certificate_files[n_certs] = filename;
2102 certificates[n_certs] = public;
2103 certificate_file_userprovided[n_certs] =
2104 options.certificate_file_userprovided[i];
2108 options.num_identity_files = n_ids;
2109 memcpy(options.identity_files, identity_files, sizeof(identity_files));
2110 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2111 memcpy(options.identity_file_userprovided,
2112 identity_file_userprovided, sizeof(identity_file_userprovided));
2114 options.num_certificate_files = n_certs;
2115 memcpy(options.certificate_files,
2116 certificate_files, sizeof(certificate_files));
2117 memcpy(options.certificates, certificates, sizeof(certificates));
2118 memcpy(options.certificate_file_userprovided,
2119 certificate_file_userprovided,
2120 sizeof(certificate_file_userprovided));
2124 main_sigchld_handler(int sig)
2126 int save_errno = errno;
2130 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2131 (pid < 0 && errno == EINTR))