1 /* $OpenBSD: ssh.c,v 1.451 2017/03/10 04:07:20 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
50 #include <sys/resource.h>
51 #include <sys/ioctl.h>
52 #include <sys/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"
97 #include "pathnames.h"
99 #include "clientloop.h"
102 #include "readconf.h"
103 #include "sshconnect.h"
112 #include "myproposal.h"
116 #include "ssh-pkcs11.h"
119 extern char *__progname;
121 /* Saves a copy of argv for setproctitle emulation */
122 #ifndef HAVE_SETPROCTITLE
123 static char **saved_av;
126 /* Flag indicating whether debug mode is on. May be set on the command line. */
129 /* Flag indicating whether a tty should be requested */
132 /* don't exec a shell */
133 int no_shell_flag = 0;
136 * Flag indicating that nothing should be read from stdin. This can be set
137 * on the command line.
139 int stdin_null_flag = 0;
142 * Flag indicating that the current process should be backgrounded and
143 * a new slave launched in the foreground for ControlPersist.
145 int need_controlpersist_detach = 0;
147 /* Copies of flags for ControlPersist foreground slave */
148 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
151 * Flag indicating that ssh should fork after authentication. This is useful
152 * so that the passphrase can be entered manually, and then ssh goes to the
155 int fork_after_authentication_flag = 0;
158 * General data structure for command line options and options configurable
159 * in configuration files. See readconf.h.
163 /* optional user configfile */
167 * Name of the host we are connecting to. This is the name given on the
168 * command line, or the HostName specified for the user-supplied name in a
169 * configuration file.
173 /* socket address the host resolves to */
174 struct sockaddr_storage hostaddr;
176 /* Private host keys. */
177 Sensitive sensitive_data;
179 /* Original real UID. */
180 uid_t original_real_uid;
181 uid_t original_effective_uid;
183 /* command to be executed */
186 /* Should we execute a command or invoke a subsystem? */
187 int subsystem_flag = 0;
189 /* # of replies received for global requests */
190 static int remote_forward_confirms_received = 0;
193 extern int muxserver_sock;
194 extern u_int muxclient_command;
196 /* Prints a help message to the user. This function never returns. */
202 "usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
203 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
204 " [-F configfile] [-I pkcs11] [-i identity_file]\n"
205 " [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]\n"
206 " [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]\n"
207 " [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
208 " [user@]hostname [command]\n"
213 static int ssh_session(void);
214 static int ssh_session2(void);
215 static void load_public_identity_files(void);
216 static void main_sigchld_handler(int);
218 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
220 tilde_expand_paths(char **paths, u_int num_paths)
225 for (i = 0; i < num_paths; i++) {
226 cp = tilde_expand_filename(paths[i], original_real_uid);
233 * Attempt to resolve a host name / port to a set of addresses and
234 * optionally return any CNAMEs encountered along the way.
235 * Returns NULL on failure.
236 * NB. this function must operate with a options having undefined members.
238 static struct addrinfo *
239 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
241 char strport[NI_MAXSERV];
242 struct addrinfo hints, *res;
243 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
246 port = default_ssh_port();
248 snprintf(strport, sizeof strport, "%d", port);
249 memset(&hints, 0, sizeof(hints));
250 hints.ai_family = options.address_family == -1 ?
251 AF_UNSPEC : options.address_family;
252 hints.ai_socktype = SOCK_STREAM;
254 hints.ai_flags = AI_CANONNAME;
255 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
256 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
257 loglevel = SYSLOG_LEVEL_ERROR;
258 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
259 __progname, name, ssh_gai_strerror(gaierr));
262 if (cname != NULL && res->ai_canonname != NULL) {
263 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
264 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
265 __func__, name, res->ai_canonname, (u_long)clen);
274 * Attempt to resolve a numeric host address / port to a single address.
275 * Returns a canonical address string.
276 * Returns NULL on failure.
277 * NB. this function must operate with a options having undefined members.
279 static struct addrinfo *
280 resolve_addr(const char *name, int port, char *caddr, size_t clen)
282 char addr[NI_MAXHOST], strport[NI_MAXSERV];
283 struct addrinfo hints, *res;
287 port = default_ssh_port();
288 snprintf(strport, sizeof strport, "%u", 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 ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
295 debug2("%s: could not resolve name %.100s as address: %s",
296 __func__, name, ssh_gai_strerror(gaierr));
300 debug("%s: getaddrinfo %.100s returned no addresses",
304 if (res->ai_next != NULL) {
305 debug("%s: getaddrinfo %.100s returned multiple addresses",
309 if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
310 addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
311 debug("%s: Could not format address for name %.100s: %s",
312 __func__, name, ssh_gai_strerror(gaierr));
315 if (strlcpy(caddr, addr, clen) >= clen) {
316 error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
317 __func__, name, addr, (u_long)clen);
328 * Check whether the cname is a permitted replacement for the hostname
329 * and perform the replacement if it is.
330 * NB. this function must operate with a options having undefined members.
333 check_follow_cname(int direct, char **namep, const char *cname)
336 struct allowed_cname *rule;
338 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
339 strcmp(*namep, cname) == 0)
341 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
344 * Don't attempt to canonicalize names that will be interpreted by
345 * a proxy or jump host unless the user specifically requests so.
348 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
350 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
351 for (i = 0; i < options.num_permitted_cnames; i++) {
352 rule = options.permitted_cnames + i;
353 if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
354 match_pattern_list(cname, rule->target_list, 1) != 1)
356 verbose("Canonicalized DNS aliased hostname "
357 "\"%s\" => \"%s\"", *namep, cname);
359 *namep = xstrdup(cname);
366 * Attempt to resolve the supplied hostname after applying the user's
367 * canonicalization rules. Returns the address list for the host or NULL
368 * if no name was found after canonicalization.
369 * NB. this function must operate with a options having undefined members.
371 static struct addrinfo *
372 resolve_canonicalize(char **hostp, int port)
374 int i, direct, ndots;
375 char *cp, *fullhost, newname[NI_MAXHOST];
376 struct addrinfo *addrs;
378 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
382 * Don't attempt to canonicalize names that will be interpreted by
383 * a proxy unless the user specifically requests so.
385 direct = option_clear_or_none(options.proxy_command) &&
386 options.jump_host == NULL;
388 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
391 /* Try numeric hostnames first */
392 if ((addrs = resolve_addr(*hostp, port,
393 newname, sizeof(newname))) != NULL) {
394 debug2("%s: hostname %.100s is address", __func__, *hostp);
395 if (strcasecmp(*hostp, newname) != 0) {
396 debug2("%s: canonicalised address \"%s\" => \"%s\"",
397 __func__, *hostp, newname);
399 *hostp = xstrdup(newname);
404 /* If domain name is anchored, then resolve it now */
405 if ((*hostp)[strlen(*hostp) - 1] == '.') {
406 debug3("%s: name is fully qualified", __func__);
407 fullhost = xstrdup(*hostp);
408 if ((addrs = resolve_host(fullhost, port, 0,
409 newname, sizeof(newname))) != NULL)
415 /* Don't apply canonicalization to sufficiently-qualified hostnames */
417 for (cp = *hostp; *cp != '\0'; cp++) {
421 if (ndots > options.canonicalize_max_dots) {
422 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
423 __func__, *hostp, options.canonicalize_max_dots);
426 /* Attempt each supplied suffix */
427 for (i = 0; i < options.num_canonical_domains; i++) {
429 xasprintf(&fullhost, "%s.%s.", *hostp,
430 options.canonical_domains[i]);
431 debug3("%s: attempting \"%s\" => \"%s\"", __func__,
433 if ((addrs = resolve_host(fullhost, port, 0,
434 newname, sizeof(newname))) == NULL) {
439 /* Remove trailing '.' */
440 fullhost[strlen(fullhost) - 1] = '\0';
441 /* Follow CNAME if requested */
442 if (!check_follow_cname(direct, &fullhost, newname)) {
443 debug("Canonicalized hostname \"%s\" => \"%s\"",
451 if (!options.canonicalize_fallback_local)
452 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
453 debug2("%s: host %s not found in any suffix", __func__, *hostp);
458 * Read per-user configuration file. Ignore the system wide config
459 * file if the user specifies a config file on the command line.
462 process_config_files(const char *host_arg, struct passwd *pw, int post_canon)
467 if (config != NULL) {
468 if (strcasecmp(config, "none") != 0 &&
469 !read_config_file(config, pw, host, host_arg, &options,
470 SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
471 fatal("Can't open user config file %.100s: "
472 "%.100s", config, strerror(errno));
474 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
475 _PATH_SSH_USER_CONFFILE);
476 if (r > 0 && (size_t)r < sizeof(buf))
477 (void)read_config_file(buf, pw, host, host_arg,
478 &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
479 (post_canon ? SSHCONF_POSTCANON : 0));
481 /* Read systemwide configuration file after user config. */
482 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
483 host, host_arg, &options,
484 post_canon ? SSHCONF_POSTCANON : 0);
488 /* Rewrite the port number in an addrinfo list of addresses */
490 set_addrinfo_port(struct addrinfo *addrs, int port)
492 struct addrinfo *addr;
494 for (addr = addrs; addr != NULL; addr = addr->ai_next) {
495 switch (addr->ai_family) {
497 ((struct sockaddr_in *)addr->ai_addr)->
498 sin_port = htons(port);
501 ((struct sockaddr_in6 *)addr->ai_addr)->
502 sin6_port = htons(port);
509 * Main program for the ssh client.
512 main(int ac, char **av)
514 struct ssh *ssh = NULL;
515 int i, r, opt, exit_status, use_syslog, direct, config_test = 0;
516 char *p, *cp, *line, *argv0, buf[PATH_MAX], *host_arg, *logfile;
517 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
518 char cname[NI_MAXHOST], uidstr[32], *conn_hash_hex;
522 extern int optind, optreset;
525 struct addrinfo *addrs = NULL;
526 struct ssh_digest_ctx *md;
527 u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
529 ssh_malloc_init(); /* must be called before any mallocs */
530 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
533 __progname = ssh_get_progname(av[0]);
535 #ifndef HAVE_SETPROCTITLE
536 /* Prepare for later setproctitle emulation */
537 /* Save argv so it isn't clobbered by setproctitle() emulation */
538 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
539 for (i = 0; i < ac; i++)
540 saved_av[i] = xstrdup(av[i]);
542 compat_init_setproctitle(ac, av);
547 * Discard other fds that are hanging around. These can cause problem
548 * with backgrounded ssh processes started by ControlPersist.
550 closefrom(STDERR_FILENO + 1);
553 * Save the original real uid. It will be needed later (uid-swapping
554 * may clobber the real uid).
556 original_real_uid = getuid();
557 original_effective_uid = geteuid();
560 * Use uid-swapping to give up root privileges for the duration of
561 * option processing. We will re-instantiate the rights when we are
562 * ready to create the privileged port, and will permanently drop
563 * them when the port has been created (actually, when the connection
564 * has been made, as we may need to create the port several times).
568 #ifdef HAVE_SETRLIMIT
569 /* If we are installed setuid root be careful to not drop core. */
570 if (original_real_uid != original_effective_uid) {
572 rlim.rlim_cur = rlim.rlim_max = 0;
573 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
574 fatal("setrlimit failed: %.100s", strerror(errno));
578 pw = getpwuid(original_real_uid);
580 logit("No user exists for uid %lu", (u_long)original_real_uid);
583 /* Take a copy of the returned structure. */
587 * Set our umask to something reasonable, as some files are created
588 * with the default umask. This will make them world-readable but
589 * writable only by the owner, which is ok for all files for which we
590 * don't set the modes explicitly.
597 * Initialize option structure to indicate that no values have been
600 initialize_options(&options);
602 /* Parse command-line arguments. */
609 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
610 "ACD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
613 options.protocol = SSH_PROTO_1;
616 options.protocol = SSH_PROTO_2;
619 options.address_family = AF_INET;
622 options.address_family = AF_INET6;
628 fork_after_authentication_flag = 1;
632 options.forward_x11 = 0;
635 options.forward_x11 = 1;
647 options.forward_x11 = 1;
648 options.forward_x11_trusted = 1;
651 options.fwd_opts.gateway_ports = 1;
654 if (options.stdio_forward_host != NULL)
655 fatal("Cannot specify multiplexing "
657 else if (muxclient_command != 0)
658 fatal("Multiplexing command already specified");
659 if (strcmp(optarg, "check") == 0)
660 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
661 else if (strcmp(optarg, "forward") == 0)
662 muxclient_command = SSHMUX_COMMAND_FORWARD;
663 else if (strcmp(optarg, "exit") == 0)
664 muxclient_command = SSHMUX_COMMAND_TERMINATE;
665 else if (strcmp(optarg, "stop") == 0)
666 muxclient_command = SSHMUX_COMMAND_STOP;
667 else if (strcmp(optarg, "cancel") == 0)
668 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
669 else if (strcmp(optarg, "proxy") == 0)
670 muxclient_command = SSHMUX_COMMAND_PROXY;
672 fatal("Invalid multiplex command.");
674 case 'P': /* deprecated */
675 options.use_privileged_port = 0;
679 if (strcmp(optarg, "cipher") == 0)
680 cp = cipher_alg_list('\n', 0);
681 else if (strcmp(optarg, "cipher-auth") == 0)
682 cp = cipher_alg_list('\n', 1);
683 else if (strcmp(optarg, "mac") == 0)
684 cp = mac_alg_list('\n');
685 else if (strcmp(optarg, "kex") == 0)
686 cp = kex_alg_list('\n');
687 else if (strcmp(optarg, "key") == 0)
688 cp = sshkey_alg_list(0, 0, 0, '\n');
689 else if (strcmp(optarg, "key-cert") == 0)
690 cp = sshkey_alg_list(1, 0, 0, '\n');
691 else if (strcmp(optarg, "key-plain") == 0)
692 cp = sshkey_alg_list(0, 1, 0, '\n');
693 else if (strcmp(optarg, "protocol-version") == 0) {
695 cp = xstrdup("1\n2");
701 fatal("Unsupported query \"%s\"", optarg);
707 options.forward_agent = 0;
710 options.forward_agent = 1;
713 options.gss_deleg_creds = 0;
716 options.gss_authentication = 1;
717 options.gss_deleg_creds = 1;
720 p = tilde_expand_filename(optarg, original_real_uid);
721 if (stat(p, &st) < 0)
722 fprintf(stderr, "Warning: Identity file %s "
723 "not accessible: %s.\n", p,
726 add_identity_file(&options, NULL, p, 1);
731 free(options.pkcs11_provider);
732 options.pkcs11_provider = xstrdup(optarg);
734 fprintf(stderr, "no support for PKCS#11.\n");
738 if (options.jump_host != NULL)
739 fatal("Only a single -J option permitted");
740 if (options.proxy_command != NULL)
741 fatal("Cannot specify -J with ProxyCommand");
742 if (parse_jump(optarg, &options, 1) == -1)
743 fatal("Invalid -J argument");
744 options.proxy_command = xstrdup("none");
747 if (options.request_tty == REQUEST_TTY_YES)
748 options.request_tty = REQUEST_TTY_FORCE;
750 options.request_tty = REQUEST_TTY_YES;
753 if (debug_flag == 0) {
755 options.log_level = SYSLOG_LEVEL_DEBUG1;
757 if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
764 if (options.version_addendum &&
765 *options.version_addendum != '\0')
766 fprintf(stderr, "%s %s, %s\n", SSH_RELEASE,
767 options.version_addendum,
768 OPENSSL_VERSION_STRING);
770 fprintf(stderr, "%s, %s\n", SSH_RELEASE,
771 OPENSSL_VERSION_STRING);
776 if (options.tun_open == -1)
777 options.tun_open = SSH_TUNMODE_DEFAULT;
778 options.tun_local = a2tun(optarg, &options.tun_remote);
779 if (options.tun_local == SSH_TUNID_ERR) {
781 "Bad tun device '%s'\n", optarg);
786 if (options.stdio_forward_host != NULL)
787 fatal("stdio forward already specified");
788 if (muxclient_command != 0)
789 fatal("Cannot specify stdio forward with -O");
790 if (parse_forward(&fwd, optarg, 1, 0)) {
791 options.stdio_forward_host = fwd.listen_host;
792 options.stdio_forward_port = fwd.listen_port;
793 free(fwd.connect_host);
796 "Bad stdio forwarding specification '%s'\n",
800 options.request_tty = REQUEST_TTY_NO;
804 options.log_level = SYSLOG_LEVEL_QUIET;
807 if (optarg[0] == '^' && optarg[2] == 0 &&
808 (u_char) optarg[1] >= 64 &&
809 (u_char) optarg[1] < 128)
810 options.escape_char = (u_char) optarg[1] & 31;
811 else if (strlen(optarg) == 1)
812 options.escape_char = (u_char) optarg[0];
813 else if (strcmp(optarg, "none") == 0)
814 options.escape_char = SSH_ESCAPECHAR_NONE;
816 fprintf(stderr, "Bad escape character '%s'.\n",
822 if (ciphers_valid(*optarg == '+' ?
823 optarg + 1 : optarg)) {
825 free(options.ciphers);
826 options.ciphers = xstrdup(optarg);
827 options.cipher = SSH_CIPHER_INVALID;
831 options.cipher = cipher_number(optarg);
832 if (options.cipher == -1) {
833 fprintf(stderr, "Unknown cipher type '%s'\n",
837 if (options.cipher == SSH_CIPHER_3DES)
838 options.ciphers = xstrdup("3des-cbc");
839 else if (options.cipher == SSH_CIPHER_BLOWFISH)
840 options.ciphers = xstrdup("blowfish-cbc");
842 options.ciphers = xstrdup(KEX_CLIENT_ENCRYPT);
845 if (mac_valid(optarg)) {
847 options.macs = xstrdup(optarg);
849 fprintf(stderr, "Unknown mac type '%s'\n",
855 if (options.control_master == SSHCTL_MASTER_YES)
856 options.control_master = SSHCTL_MASTER_ASK;
858 options.control_master = SSHCTL_MASTER_YES;
861 options.port = a2port(optarg);
862 if (options.port <= 0) {
863 fprintf(stderr, "Bad port '%s'\n", optarg);
868 options.user = optarg;
872 if (parse_forward(&fwd, optarg, 0, 0))
873 add_local_forward(&options, &fwd);
876 "Bad local forwarding specification '%s'\n",
883 if (parse_forward(&fwd, optarg, 0, 1)) {
884 add_remote_forward(&options, &fwd);
887 "Bad remote forwarding specification "
894 if (parse_forward(&fwd, optarg, 1, 0)) {
895 add_local_forward(&options, &fwd);
898 "Bad dynamic forwarding specification "
905 options.compression = 1;
909 options.request_tty = REQUEST_TTY_NO;
912 options.request_tty = REQUEST_TTY_NO;
915 line = xstrdup(optarg);
916 if (process_config_line(&options, pw,
917 host ? host : "", host ? host : "", line,
918 "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
926 free(options.control_path);
927 options.control_path = xstrdup(optarg);
930 options.bind_address = optarg;
943 if (ac > 0 && !host) {
944 if (strrchr(*av, '@')) {
946 cp = strrchr(p, '@');
947 if (cp == NULL || cp == p)
951 host = xstrdup(++cp);
955 optind = optreset = 1;
961 /* Check that we got a host name. */
965 host_arg = xstrdup(host);
968 OpenSSL_add_all_algorithms();
969 ERR_load_crypto_strings();
972 /* Initialize the command to execute on remote host. */
973 buffer_init(&command);
976 * Save the command to execute on the remote host in a buffer. There
977 * is no limit on the length of the command, except by the maximum
978 * packet size. Also sets the tty flag if there is no command.
981 /* No command specified - execute shell on a tty. */
982 if (subsystem_flag) {
984 "You must specify a subsystem to invoke.\n");
988 /* A command has been specified. Store it into the buffer. */
989 for (i = 0; i < ac; i++) {
991 buffer_append(&command, " ", 1);
992 buffer_append(&command, av[i], strlen(av[i]));
996 /* Cannot fork to background if no command. */
997 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
999 fatal("Cannot fork into background without a command "
1003 * Initialize "log" output. Since we are the client all output
1004 * goes to stderr unless otherwise specified by -y or -E.
1006 if (use_syslog && logfile != NULL)
1007 fatal("Can't specify both -y and -E");
1008 if (logfile != NULL)
1009 log_redirect_stderr_to(logfile);
1011 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
1012 SYSLOG_FACILITY_USER, !use_syslog);
1015 /* version_addendum is always NULL at this point */
1016 logit("%s, %s", SSH_RELEASE, OPENSSL_VERSION_STRING);
1018 /* Parse the configuration files */
1019 process_config_files(host_arg, pw, 0);
1021 /* Hostname canonicalisation needs a few options filled. */
1022 fill_default_options_for_canonicalization(&options);
1024 /* If the user has replaced the hostname then take it into use now */
1025 if (options.hostname != NULL) {
1026 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1027 cp = percent_expand(options.hostname,
1028 "h", host, (char *)NULL);
1031 free(options.hostname);
1032 options.hostname = xstrdup(host);
1035 /* If canonicalization requested then try to apply it */
1037 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
1038 addrs = resolve_canonicalize(&host, options.port);
1041 * If CanonicalizePermittedCNAMEs have been specified but
1042 * other canonicalization did not happen (by not being requested
1043 * or by failing with fallback) then the hostname may still be changed
1044 * as a result of CNAME following.
1046 * Try to resolve the bare hostname name using the system resolver's
1047 * usual search rules and then apply the CNAME follow rules.
1049 * Skip the lookup if a ProxyCommand is being used unless the user
1050 * has specifically requested canonicalisation for this case via
1051 * CanonicalizeHostname=always
1053 direct = option_clear_or_none(options.proxy_command) &&
1054 options.jump_host == NULL;
1055 if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1056 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1057 if ((addrs = resolve_host(host, options.port,
1058 option_clear_or_none(options.proxy_command),
1059 cname, sizeof(cname))) == NULL) {
1060 /* Don't fatal proxied host names not in the DNS */
1061 if (option_clear_or_none(options.proxy_command))
1062 cleanup_exit(255); /* logged in resolve_host */
1064 check_follow_cname(direct, &host, cname);
1068 * If canonicalisation is enabled then re-parse the configuration
1069 * files as new stanzas may match.
1071 if (options.canonicalize_hostname != 0) {
1072 debug("Re-reading configuration after hostname "
1073 "canonicalisation");
1074 free(options.hostname);
1075 options.hostname = xstrdup(host);
1076 process_config_files(host_arg, pw, 1);
1078 * Address resolution happens early with canonicalisation
1079 * enabled and the port number may have changed since, so
1080 * reset it in address list
1082 if (addrs != NULL && options.port > 0)
1083 set_addrinfo_port(addrs, options.port);
1086 /* Fill configuration defaults. */
1087 fill_default_options(&options);
1090 * If ProxyJump option specified, then construct a ProxyCommand now.
1092 if (options.jump_host != NULL) {
1095 /* Consistency check */
1096 if (options.proxy_command != NULL)
1097 fatal("inconsistent options: ProxyCommand+ProxyJump");
1098 /* Never use FD passing for ProxyJump */
1099 options.proxy_use_fdpass = 0;
1100 snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1101 xasprintf(&options.proxy_command,
1102 "ssh%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1103 /* Optional "-l user" argument if jump_user set */
1104 options.jump_user == NULL ? "" : " -l ",
1105 options.jump_user == NULL ? "" : options.jump_user,
1106 /* Optional "-p port" argument if jump_port set */
1107 options.jump_port <= 0 ? "" : " -p ",
1108 options.jump_port <= 0 ? "" : port_s,
1109 /* Optional additional jump hosts ",..." */
1110 options.jump_extra == NULL ? "" : " -J ",
1111 options.jump_extra == NULL ? "" : options.jump_extra,
1112 /* Optional "-F" argumment if -F specified */
1113 config == NULL ? "" : " -F ",
1114 config == NULL ? "" : config,
1115 /* Optional "-v" arguments if -v set */
1116 debug_flag ? " -" : "",
1118 /* Mandatory hostname */
1120 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1121 options.proxy_command);
1124 if (options.port == 0)
1125 options.port = default_ssh_port();
1126 channel_set_af(options.address_family);
1128 /* Tidy and check options */
1129 if (options.host_key_alias != NULL)
1130 lowercase(options.host_key_alias);
1131 if (options.proxy_command != NULL &&
1132 strcmp(options.proxy_command, "-") == 0 &&
1133 options.proxy_use_fdpass)
1134 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1135 if (options.control_persist &&
1136 options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1137 debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1139 options.update_hostkeys = 0;
1141 if (options.connection_attempts <= 0)
1142 fatal("Invalid number of ConnectionAttempts");
1144 if (original_effective_uid != 0)
1145 options.use_privileged_port = 0;
1149 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
1151 if (options.request_tty == REQUEST_TTY_YES ||
1152 options.request_tty == REQUEST_TTY_FORCE)
1155 /* Allocate a tty by default if no command specified. */
1156 if (buffer_len(&command) == 0)
1157 tty_flag = options.request_tty != REQUEST_TTY_NO;
1160 if (options.request_tty == REQUEST_TTY_NO ||
1161 (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY))
1163 /* Do not allocate a tty if stdin is not a tty. */
1164 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1165 options.request_tty != REQUEST_TTY_FORCE) {
1167 logit("Pseudo-terminal will not be allocated because "
1168 "stdin is not a terminal.");
1174 if (options.user == NULL)
1175 options.user = xstrdup(pw->pw_name);
1177 if (gethostname(thishost, sizeof(thishost)) == -1)
1178 fatal("gethostname: %s", strerror(errno));
1179 strlcpy(shorthost, thishost, sizeof(shorthost));
1180 shorthost[strcspn(thishost, ".")] = '\0';
1181 snprintf(portstr, sizeof(portstr), "%d", options.port);
1182 snprintf(uidstr, sizeof(uidstr), "%d", pw->pw_uid);
1184 /* Find canonic host name. */
1185 if (strchr(host, '.') == 0) {
1186 struct addrinfo hints;
1187 struct addrinfo *ai = NULL;
1189 memset(&hints, 0, sizeof(hints));
1190 hints.ai_family = options.address_family;
1191 hints.ai_flags = AI_CANONNAME;
1192 hints.ai_socktype = SOCK_STREAM;
1193 errgai = getaddrinfo(host, NULL, &hints, &ai);
1195 if (ai->ai_canonname != NULL)
1196 host = xstrdup(ai->ai_canonname);
1201 if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1202 ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1203 ssh_digest_update(md, host, strlen(host)) < 0 ||
1204 ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1205 ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1206 ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1207 fatal("%s: mux digest failed", __func__);
1208 ssh_digest_free(md);
1209 conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1211 if (options.local_command != NULL) {
1212 debug3("expanding LocalCommand: %s", options.local_command);
1213 cp = options.local_command;
1214 options.local_command = percent_expand(cp,
1225 debug3("expanded LocalCommand: %s", options.local_command);
1229 if (options.control_path != NULL) {
1230 cp = tilde_expand_filename(options.control_path,
1232 free(options.control_path);
1233 options.control_path = percent_expand(cp,
1246 free(conn_hash_hex);
1249 dump_client_config(&options, host);
1253 if (muxclient_command != 0 && options.control_path == NULL)
1254 fatal("No ControlPath specified for \"-O\" command");
1255 if (options.control_path != NULL) {
1257 if ((sock = muxclient(options.control_path)) >= 0) {
1258 packet_set_connection(sock, sock);
1259 ssh = active_state; /* XXX */
1260 enable_compat20(); /* XXX */
1267 * If hostname canonicalisation was not enabled, then we may not
1268 * have yet resolved the hostname. Do so now.
1270 if (addrs == NULL && options.proxy_command == NULL) {
1271 debug2("resolving \"%s\" port %d", host, options.port);
1272 if ((addrs = resolve_host(host, options.port, 1,
1273 cname, sizeof(cname))) == NULL)
1274 cleanup_exit(255); /* resolve_host logs the error */
1277 timeout_ms = options.connection_timeout * 1000;
1279 /* Open a connection to the remote host. */
1280 if (ssh_connect(host, addrs, &hostaddr, options.port,
1281 options.address_family, options.connection_attempts,
1282 &timeout_ms, options.tcp_keep_alive,
1283 options.use_privileged_port) != 0)
1287 freeaddrinfo(addrs);
1289 packet_set_timeout(options.server_alive_interval,
1290 options.server_alive_count_max);
1292 ssh = active_state; /* XXX */
1295 debug3("timeout: %d ms remain after connect", timeout_ms);
1298 * If we successfully made the connection, load the host private key
1299 * in case we will need it later for combined rsa-rhosts
1300 * authentication. This must be done before releasing extra
1301 * privileges, because the file is only readable by root.
1302 * If we cannot access the private keys, load the public keys
1303 * instead and try to execute the ssh-keysign helper instead.
1305 sensitive_data.nkeys = 0;
1306 sensitive_data.keys = NULL;
1307 sensitive_data.external_keysign = 0;
1308 if (options.rhosts_rsa_authentication ||
1309 options.hostbased_authentication) {
1310 sensitive_data.nkeys = 9;
1311 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1313 for (i = 0; i < sensitive_data.nkeys; i++)
1314 sensitive_data.keys[i] = NULL;
1318 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1319 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1321 #ifdef OPENSSL_HAS_ECC
1322 sensitive_data.keys[1] = key_load_private_cert(KEY_ECDSA,
1323 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1325 sensitive_data.keys[2] = key_load_private_cert(KEY_ED25519,
1326 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1327 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1328 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1329 sensitive_data.keys[4] = key_load_private_cert(KEY_DSA,
1330 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1331 #ifdef OPENSSL_HAS_ECC
1332 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
1333 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1335 sensitive_data.keys[6] = key_load_private_type(KEY_ED25519,
1336 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1337 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1338 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1339 sensitive_data.keys[8] = key_load_private_type(KEY_DSA,
1340 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1343 if (options.hostbased_authentication == 1 &&
1344 sensitive_data.keys[0] == NULL &&
1345 sensitive_data.keys[5] == NULL &&
1346 sensitive_data.keys[6] == NULL &&
1347 sensitive_data.keys[7] == NULL &&
1348 sensitive_data.keys[8] == NULL) {
1349 #ifdef OPENSSL_HAS_ECC
1350 sensitive_data.keys[1] = key_load_cert(
1351 _PATH_HOST_ECDSA_KEY_FILE);
1353 sensitive_data.keys[2] = key_load_cert(
1354 _PATH_HOST_ED25519_KEY_FILE);
1355 sensitive_data.keys[3] = key_load_cert(
1356 _PATH_HOST_RSA_KEY_FILE);
1357 sensitive_data.keys[4] = key_load_cert(
1358 _PATH_HOST_DSA_KEY_FILE);
1359 #ifdef OPENSSL_HAS_ECC
1360 sensitive_data.keys[5] = key_load_public(
1361 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1363 sensitive_data.keys[6] = key_load_public(
1364 _PATH_HOST_ED25519_KEY_FILE, NULL);
1365 sensitive_data.keys[7] = key_load_public(
1366 _PATH_HOST_RSA_KEY_FILE, NULL);
1367 sensitive_data.keys[8] = key_load_public(
1368 _PATH_HOST_DSA_KEY_FILE, NULL);
1369 sensitive_data.external_keysign = 1;
1373 * Get rid of any extra privileges that we may have. We will no
1374 * longer need them. Also, extra privileges could make it very hard
1375 * to read identity files and other non-world-readable files from the
1376 * user's home directory if it happens to be on a NFS volume where
1377 * root is mapped to nobody.
1379 if (original_effective_uid == 0) {
1381 permanently_set_uid(pw);
1385 * Now that we are back to our own permissions, create ~/.ssh
1386 * directory if it doesn't already exist.
1388 if (config == NULL) {
1389 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1390 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1391 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1393 ssh_selinux_setfscreatecon(buf);
1395 if (mkdir(buf, 0700) < 0)
1396 error("Could not create directory '%.200s'.",
1399 ssh_selinux_setfscreatecon(NULL);
1403 /* load options.identity_files */
1404 load_public_identity_files();
1406 /* optionally set the SSH_AUTHSOCKET_ENV_NAME varibale */
1407 if (options.identity_agent &&
1408 strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1409 if (strcmp(options.identity_agent, "none") == 0) {
1410 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1412 p = tilde_expand_filename(options.identity_agent,
1414 cp = percent_expand(p, "d", pw->pw_dir,
1415 "u", pw->pw_name, "l", thishost, "h", host,
1416 "r", options.user, (char *)NULL);
1417 setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1423 /* Expand ~ in known host file names. */
1424 tilde_expand_paths(options.system_hostfiles,
1425 options.num_system_hostfiles);
1426 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1428 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1429 signal(SIGCHLD, main_sigchld_handler);
1431 /* Log into the remote system. Never returns if the login fails. */
1432 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1433 options.port, pw, timeout_ms);
1435 if (packet_connection_is_on_socket()) {
1436 verbose("Authenticated to %s ([%s]:%d).", host,
1437 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1439 verbose("Authenticated to %s (via proxy).", host);
1442 /* We no longer need the private host keys. Clear them now. */
1443 if (sensitive_data.nkeys != 0) {
1444 for (i = 0; i < sensitive_data.nkeys; i++) {
1445 if (sensitive_data.keys[i] != NULL) {
1446 /* Destroys contents safely */
1447 debug3("clear hostkey %d", i);
1448 key_free(sensitive_data.keys[i]);
1449 sensitive_data.keys[i] = NULL;
1452 free(sensitive_data.keys);
1454 for (i = 0; i < options.num_identity_files; i++) {
1455 free(options.identity_files[i]);
1456 options.identity_files[i] = NULL;
1457 if (options.identity_keys[i]) {
1458 key_free(options.identity_keys[i]);
1459 options.identity_keys[i] = NULL;
1462 for (i = 0; i < options.num_certificate_files; i++) {
1463 free(options.certificate_files[i]);
1464 options.certificate_files[i] = NULL;
1468 exit_status = compat20 ? ssh_session2() : ssh_session();
1471 if (options.control_path != NULL && muxserver_sock != -1)
1472 unlink(options.control_path);
1474 /* Kill ProxyCommand if it is running. */
1475 ssh_kill_proxy_command();
1481 control_persist_detach(void)
1484 int devnull, keep_stderr;
1486 debug("%s: backgrounding master process", __func__);
1489 * master (current process) into the background, and make the
1490 * foreground process a client of the backgrounded master.
1492 switch ((pid = fork())) {
1494 fatal("%s: fork: %s", __func__, strerror(errno));
1496 /* Child: master process continues mainloop */
1499 /* Parent: set up mux slave to connect to backgrounded master */
1500 debug2("%s: background process is %ld", __func__, (long)pid);
1501 stdin_null_flag = ostdin_null_flag;
1502 options.request_tty = orequest_tty;
1503 tty_flag = otty_flag;
1504 close(muxserver_sock);
1505 muxserver_sock = -1;
1506 options.control_master = SSHCTL_MASTER_NO;
1507 muxclient(options.control_path);
1508 /* muxclient() doesn't return on success. */
1509 fatal("Failed to connect to new control master");
1511 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1512 error("%s: open(\"/dev/null\"): %s", __func__,
1515 keep_stderr = log_is_on_stderr() && debug_flag;
1516 if (dup2(devnull, STDIN_FILENO) == -1 ||
1517 dup2(devnull, STDOUT_FILENO) == -1 ||
1518 (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
1519 error("%s: dup2: %s", __func__, strerror(errno));
1520 if (devnull > STDERR_FILENO)
1524 setproctitle("%s [mux]", options.control_path);
1527 /* Do fork() after authentication. Used by "ssh -f" */
1531 if (need_controlpersist_detach)
1532 control_persist_detach();
1533 debug("forking to background");
1534 fork_after_authentication_flag = 0;
1535 if (daemon(1, 1) < 0)
1536 fatal("daemon() failed: %.200s", strerror(errno));
1539 /* Callback for remote forward global requests */
1541 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1543 struct Forward *rfwd = (struct Forward *)ctxt;
1545 /* XXX verbose() on failure? */
1546 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1547 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1548 rfwd->listen_path ? rfwd->listen_path :
1549 rfwd->listen_host ? rfwd->listen_host : "",
1550 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1551 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1552 rfwd->connect_host, rfwd->connect_port);
1553 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1554 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1555 rfwd->allocated_port = packet_get_int();
1556 logit("Allocated port %u for remote forward to %s:%d",
1557 rfwd->allocated_port,
1558 rfwd->connect_host, rfwd->connect_port);
1559 channel_update_permitted_opens(rfwd->handle,
1560 rfwd->allocated_port);
1562 channel_update_permitted_opens(rfwd->handle, -1);
1566 if (type == SSH2_MSG_REQUEST_FAILURE) {
1567 if (options.exit_on_forward_failure) {
1568 if (rfwd->listen_path != NULL)
1569 fatal("Error: remote port forwarding failed "
1570 "for listen path %s", rfwd->listen_path);
1572 fatal("Error: remote port forwarding failed "
1573 "for listen port %d", rfwd->listen_port);
1575 if (rfwd->listen_path != NULL)
1576 logit("Warning: remote port forwarding failed "
1577 "for listen path %s", rfwd->listen_path);
1579 logit("Warning: remote port forwarding failed "
1580 "for listen port %d", rfwd->listen_port);
1583 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1584 debug("All remote forwarding requests processed");
1585 if (fork_after_authentication_flag)
1591 client_cleanup_stdio_fwd(int id, void *arg)
1593 debug("stdio forwarding: done");
1598 ssh_stdio_confirm(int id, int success, void *arg)
1601 fatal("stdio forwarding failed");
1605 ssh_init_stdio_forwarding(void)
1610 if (options.stdio_forward_host == NULL)
1613 fatal("stdio forwarding require Protocol 2");
1615 debug3("%s: %s:%d", __func__, options.stdio_forward_host,
1616 options.stdio_forward_port);
1618 if ((in = dup(STDIN_FILENO)) < 0 ||
1619 (out = dup(STDOUT_FILENO)) < 0)
1620 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1621 if ((c = channel_connect_stdio_fwd(options.stdio_forward_host,
1622 options.stdio_forward_port, in, out)) == NULL)
1623 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1624 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1625 channel_register_open_confirm(c->self, ssh_stdio_confirm, NULL);
1629 ssh_init_forwarding(void)
1634 /* Initiate local TCP/IP port forwardings. */
1635 for (i = 0; i < options.num_local_forwards; i++) {
1636 debug("Local connections to %.200s:%d forwarded to remote "
1637 "address %.200s:%d",
1638 (options.local_forwards[i].listen_path != NULL) ?
1639 options.local_forwards[i].listen_path :
1640 (options.local_forwards[i].listen_host == NULL) ?
1641 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1642 options.local_forwards[i].listen_host,
1643 options.local_forwards[i].listen_port,
1644 (options.local_forwards[i].connect_path != NULL) ?
1645 options.local_forwards[i].connect_path :
1646 options.local_forwards[i].connect_host,
1647 options.local_forwards[i].connect_port);
1648 success += channel_setup_local_fwd_listener(
1649 &options.local_forwards[i], &options.fwd_opts);
1651 if (i > 0 && success != i && options.exit_on_forward_failure)
1652 fatal("Could not request local forwarding.");
1653 if (i > 0 && success == 0)
1654 error("Could not request local forwarding.");
1656 /* Initiate remote TCP/IP port forwardings. */
1657 for (i = 0; i < options.num_remote_forwards; i++) {
1658 debug("Remote connections from %.200s:%d forwarded to "
1659 "local address %.200s:%d",
1660 (options.remote_forwards[i].listen_path != NULL) ?
1661 options.remote_forwards[i].listen_path :
1662 (options.remote_forwards[i].listen_host == NULL) ?
1663 "LOCALHOST" : options.remote_forwards[i].listen_host,
1664 options.remote_forwards[i].listen_port,
1665 (options.remote_forwards[i].connect_path != NULL) ?
1666 options.remote_forwards[i].connect_path :
1667 options.remote_forwards[i].connect_host,
1668 options.remote_forwards[i].connect_port);
1669 options.remote_forwards[i].handle =
1670 channel_request_remote_forwarding(
1671 &options.remote_forwards[i]);
1672 if (options.remote_forwards[i].handle < 0) {
1673 if (options.exit_on_forward_failure)
1674 fatal("Could not request remote forwarding.");
1676 logit("Warning: Could not request remote "
1679 client_register_global_confirm(ssh_confirm_remote_forward,
1680 &options.remote_forwards[i]);
1684 /* Initiate tunnel forwarding. */
1685 if (options.tun_open != SSH_TUNMODE_NO) {
1686 if (client_request_tun_fwd(options.tun_open,
1687 options.tun_local, options.tun_remote) == -1) {
1688 if (options.exit_on_forward_failure)
1689 fatal("Could not request tunnel forwarding.");
1691 error("Could not request tunnel forwarding.");
1697 check_agent_present(void)
1701 if (options.forward_agent) {
1702 /* Clear agent forwarding if we don't have an agent. */
1703 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1704 options.forward_agent = 0;
1705 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1706 debug("ssh_get_authentication_socket: %s",
1716 int interactive = 0;
1720 const char *display;
1721 char *proto = NULL, *data = NULL;
1723 /* Enable compression if requested. */
1724 if (options.compression) {
1725 debug("Requesting compression at level %d.",
1726 options.compression_level);
1728 if (options.compression_level < 1 ||
1729 options.compression_level > 9)
1730 fatal("Compression level must be from 1 (fast) to "
1733 /* Send the request. */
1734 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1735 packet_put_int(options.compression_level);
1737 packet_write_wait();
1738 type = packet_read();
1739 if (type == SSH_SMSG_SUCCESS)
1740 packet_start_compression(options.compression_level);
1741 else if (type == SSH_SMSG_FAILURE)
1742 logit("Warning: Remote host refused compression.");
1744 packet_disconnect("Protocol error waiting for "
1745 "compression response.");
1747 /* Allocate a pseudo tty if appropriate. */
1749 debug("Requesting pty.");
1751 /* Start the packet. */
1752 packet_start(SSH_CMSG_REQUEST_PTY);
1754 /* Store TERM in the packet. There is no limit on the
1755 length of the string. */
1756 cp = getenv("TERM");
1759 packet_put_cstring(cp);
1761 /* Store window size in the packet. */
1762 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1763 memset(&ws, 0, sizeof(ws));
1764 packet_put_int((u_int)ws.ws_row);
1765 packet_put_int((u_int)ws.ws_col);
1766 packet_put_int((u_int)ws.ws_xpixel);
1767 packet_put_int((u_int)ws.ws_ypixel);
1769 /* Store tty modes in the packet. */
1770 tty_make_modes(fileno(stdin), NULL);
1772 /* Send the packet, and wait for it to leave. */
1774 packet_write_wait();
1776 /* Read response from the server. */
1777 type = packet_read();
1778 if (type == SSH_SMSG_SUCCESS) {
1781 } else if (type == SSH_SMSG_FAILURE)
1782 logit("Warning: Remote host failed or refused to "
1783 "allocate a pseudo tty.");
1785 packet_disconnect("Protocol error waiting for pty "
1786 "request response.");
1788 /* Request X11 forwarding if enabled and DISPLAY is set. */
1789 display = getenv("DISPLAY");
1790 if (display == NULL && options.forward_x11)
1791 debug("X11 forwarding requested but DISPLAY not set");
1792 if (options.forward_x11 && client_x11_get_proto(display,
1793 options.xauth_location, options.forward_x11_trusted,
1794 options.forward_x11_timeout, &proto, &data) == 0) {
1795 /* Request forwarding with authentication spoofing. */
1796 debug("Requesting X11 forwarding with authentication "
1798 x11_request_forwarding_with_spoofing(0, display, proto,
1800 /* Read response from the server. */
1801 type = packet_read();
1802 if (type == SSH_SMSG_SUCCESS) {
1804 } else if (type == SSH_SMSG_FAILURE) {
1805 logit("Warning: Remote host denied X11 forwarding.");
1807 packet_disconnect("Protocol error waiting for X11 "
1811 /* Tell the packet module whether this is an interactive session. */
1812 packet_set_interactive(interactive,
1813 options.ip_qos_interactive, options.ip_qos_bulk);
1815 /* Request authentication agent forwarding if appropriate. */
1816 check_agent_present();
1818 if (options.forward_agent) {
1819 debug("Requesting authentication agent forwarding.");
1820 auth_request_forwarding();
1822 /* Read response from the server. */
1823 type = packet_read();
1825 if (type != SSH_SMSG_SUCCESS)
1826 logit("Warning: Remote host denied authentication agent forwarding.");
1829 /* Initiate port forwardings. */
1830 ssh_init_stdio_forwarding();
1831 ssh_init_forwarding();
1833 /* Execute a local command */
1834 if (options.local_command != NULL &&
1835 options.permit_local_command)
1836 ssh_local_cmd(options.local_command);
1839 * If requested and we are not interested in replies to remote
1840 * forwarding requests, then let ssh continue in the background.
1842 if (fork_after_authentication_flag) {
1843 if (options.exit_on_forward_failure &&
1844 options.num_remote_forwards > 0) {
1845 debug("deferring postauth fork until remote forward "
1846 "confirmation received");
1852 * If a command was specified on the command line, execute the
1853 * command now. Otherwise request the server to start a shell.
1855 if (buffer_len(&command) > 0) {
1856 int len = buffer_len(&command);
1859 debug("Sending command: %.*s", len,
1860 (u_char *)buffer_ptr(&command));
1861 packet_start(SSH_CMSG_EXEC_CMD);
1862 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1864 packet_write_wait();
1866 debug("Requesting shell.");
1867 packet_start(SSH_CMSG_EXEC_SHELL);
1869 packet_write_wait();
1872 /* Enter the interactive session. */
1873 return client_loop(have_tty, tty_flag ?
1874 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1877 /* request pty/x11/agent/tcpfwd/shell for channel */
1879 ssh_session2_setup(int id, int success, void *arg)
1881 extern char **environ;
1882 const char *display;
1883 int interactive = tty_flag;
1884 char *proto = NULL, *data = NULL;
1887 return; /* No need for error message, channels code sens one */
1889 display = getenv("DISPLAY");
1890 if (display == NULL && options.forward_x11)
1891 debug("X11 forwarding requested but DISPLAY not set");
1892 if (options.forward_x11 && client_x11_get_proto(display,
1893 options.xauth_location, options.forward_x11_trusted,
1894 options.forward_x11_timeout, &proto, &data) == 0) {
1895 /* Request forwarding with authentication spoofing. */
1896 debug("Requesting X11 forwarding with authentication "
1898 x11_request_forwarding_with_spoofing(id, display, proto,
1900 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1901 /* XXX exit_on_forward_failure */
1905 check_agent_present();
1906 if (options.forward_agent) {
1907 debug("Requesting authentication agent forwarding.");
1908 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1912 /* Tell the packet module whether this is an interactive session. */
1913 packet_set_interactive(interactive,
1914 options.ip_qos_interactive, options.ip_qos_bulk);
1916 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1917 NULL, fileno(stdin), &command, environ);
1920 /* open new channel for a session */
1922 ssh_session2_open(void)
1925 int window, packetmax, in, out, err;
1927 if (stdin_null_flag) {
1928 in = open(_PATH_DEVNULL, O_RDONLY);
1930 in = dup(STDIN_FILENO);
1932 out = dup(STDOUT_FILENO);
1933 err = dup(STDERR_FILENO);
1935 if (in < 0 || out < 0 || err < 0)
1936 fatal("dup() in/out/err failed");
1938 /* enable nonblocking unless tty */
1946 window = CHAN_SES_WINDOW_DEFAULT;
1947 packetmax = CHAN_SES_PACKET_DEFAULT;
1953 "session", SSH_CHANNEL_OPENING, in, out, err,
1954 window, packetmax, CHAN_EXTENDED_WRITE,
1955 "client-session", /*nonblock*/0);
1957 debug3("ssh_session2_open: channel_new: %d", c->self);
1959 channel_send_open(c->self);
1961 channel_register_open_confirm(c->self,
1962 ssh_session2_setup, NULL);
1972 /* XXX should be pre-session */
1973 if (!options.control_persist)
1974 ssh_init_stdio_forwarding();
1975 ssh_init_forwarding();
1977 /* Start listening for multiplex clients */
1978 if (!packet_get_mux())
1982 * If we are in control persist mode and have a working mux listen
1983 * socket, then prepare to background ourselves and have a foreground
1984 * client attach as a control slave.
1985 * NB. we must save copies of the flags that we override for
1986 * the backgrounding, since we defer attachment of the slave until
1987 * after the connection is fully established (in particular,
1988 * async rfwd replies have been received for ExitOnForwardFailure).
1990 if (options.control_persist && muxserver_sock != -1) {
1991 ostdin_null_flag = stdin_null_flag;
1992 ono_shell_flag = no_shell_flag;
1993 orequest_tty = options.request_tty;
1994 otty_flag = tty_flag;
1995 stdin_null_flag = 1;
1998 if (!fork_after_authentication_flag)
1999 need_controlpersist_detach = 1;
2000 fork_after_authentication_flag = 1;
2003 * ControlPersist mux listen socket setup failed, attempt the
2004 * stdio forward setup that we skipped earlier.
2006 if (options.control_persist && muxserver_sock == -1)
2007 ssh_init_stdio_forwarding();
2009 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
2010 id = ssh_session2_open();
2012 packet_set_interactive(
2013 options.control_master == SSHCTL_MASTER_NO,
2014 options.ip_qos_interactive, options.ip_qos_bulk);
2017 /* If we don't expect to open a new session, then disallow it */
2018 if (options.control_master == SSHCTL_MASTER_NO &&
2019 (datafellows & SSH_NEW_OPENSSH)) {
2020 debug("Requesting no-more-sessions@openssh.com");
2021 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2022 packet_put_cstring("no-more-sessions@openssh.com");
2027 /* Execute a local command */
2028 if (options.local_command != NULL &&
2029 options.permit_local_command)
2030 ssh_local_cmd(options.local_command);
2033 * If requested and we are not interested in replies to remote
2034 * forwarding requests, then let ssh continue in the background.
2036 if (fork_after_authentication_flag) {
2037 if (options.exit_on_forward_failure &&
2038 options.num_remote_forwards > 0) {
2039 debug("deferring postauth fork until remote forward "
2040 "confirmation received");
2045 return client_loop(tty_flag, tty_flag ?
2046 options.escape_char : SSH_ESCAPECHAR_NONE, id);
2049 /* Loads all IdentityFile and CertificateFile keys */
2051 load_public_identity_files(void)
2053 char *filename, *cp, thishost[NI_MAXHOST];
2054 char *pwdir = NULL, *pwname = NULL;
2058 u_int n_ids, n_certs;
2059 char *identity_files[SSH_MAX_IDENTITY_FILES];
2060 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
2061 char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2062 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2063 #ifdef ENABLE_PKCS11
2068 n_ids = n_certs = 0;
2069 memset(identity_files, 0, sizeof(identity_files));
2070 memset(identity_keys, 0, sizeof(identity_keys));
2071 memset(certificate_files, 0, sizeof(certificate_files));
2072 memset(certificates, 0, sizeof(certificates));
2074 #ifdef ENABLE_PKCS11
2075 if (options.pkcs11_provider != NULL &&
2076 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2077 (pkcs11_init(!options.batch_mode) == 0) &&
2078 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2080 for (i = 0; i < nkeys; i++) {
2081 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2085 identity_keys[n_ids] = keys[i];
2086 identity_files[n_ids] =
2087 xstrdup(options.pkcs11_provider); /* XXX */
2092 #endif /* ENABLE_PKCS11 */
2093 if ((pw = getpwuid(original_real_uid)) == NULL)
2094 fatal("load_public_identity_files: getpwuid failed");
2095 pwname = xstrdup(pw->pw_name);
2096 pwdir = xstrdup(pw->pw_dir);
2097 if (gethostname(thishost, sizeof(thishost)) == -1)
2098 fatal("load_public_identity_files: gethostname: %s",
2100 for (i = 0; i < options.num_identity_files; i++) {
2101 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2102 strcasecmp(options.identity_files[i], "none") == 0) {
2103 free(options.identity_files[i]);
2104 options.identity_files[i] = NULL;
2107 cp = tilde_expand_filename(options.identity_files[i],
2109 filename = percent_expand(cp, "d", pwdir,
2110 "u", pwname, "l", thishost, "h", host,
2111 "r", options.user, (char *)NULL);
2113 public = key_load_public(filename, NULL);
2114 debug("identity file %s type %d", filename,
2115 public ? public->type : -1);
2116 free(options.identity_files[i]);
2117 identity_files[n_ids] = filename;
2118 identity_keys[n_ids] = public;
2120 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2124 * If no certificates have been explicitly listed then try
2125 * to add the default certificate variant too.
2127 if (options.num_certificate_files != 0)
2129 xasprintf(&cp, "%s-cert", filename);
2130 public = key_load_public(cp, NULL);
2131 debug("identity file %s type %d", cp,
2132 public ? public->type : -1);
2133 if (public == NULL) {
2137 if (!key_is_cert(public)) {
2138 debug("%s: key %s type %s is not a certificate",
2139 __func__, cp, key_type(public));
2144 /* NB. leave filename pointing to private key */
2145 identity_files[n_ids] = xstrdup(filename);
2146 identity_keys[n_ids] = public;
2150 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2151 fatal("%s: too many certificates", __func__);
2152 for (i = 0; i < options.num_certificate_files; i++) {
2153 cp = tilde_expand_filename(options.certificate_files[i],
2155 filename = percent_expand(cp, "d", pwdir,
2156 "u", pwname, "l", thishost, "h", host,
2157 "r", options.user, (char *)NULL);
2160 public = key_load_public(filename, NULL);
2161 debug("certificate file %s type %d", filename,
2162 public ? public->type : -1);
2163 free(options.certificate_files[i]);
2164 options.certificate_files[i] = NULL;
2165 if (public == NULL) {
2169 if (!key_is_cert(public)) {
2170 debug("%s: key %s type %s is not a certificate",
2171 __func__, filename, key_type(public));
2176 certificate_files[n_certs] = filename;
2177 certificates[n_certs] = public;
2181 options.num_identity_files = n_ids;
2182 memcpy(options.identity_files, identity_files, sizeof(identity_files));
2183 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2185 options.num_certificate_files = n_certs;
2186 memcpy(options.certificate_files,
2187 certificate_files, sizeof(certificate_files));
2188 memcpy(options.certificates, certificates, sizeof(certificates));
2190 explicit_bzero(pwname, strlen(pwname));
2192 explicit_bzero(pwdir, strlen(pwdir));
2197 main_sigchld_handler(int sig)
2199 int save_errno = errno;
2203 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2204 (pid < 0 && errno == EINTR))
2207 signal(sig, main_sigchld_handler);