1 /* $OpenBSD: ssh.c,v 1.401 2014/02/26 20:18:37 djm Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * Ssh client program. This program can be used to log into a remote machine.
8 * The software supports strong authentication, encryption, and forwarding
9 * of X11, TCP/IP, and authentication connections.
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
17 * Copyright (c) 1999 Niels Provos. All rights reserved.
18 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
20 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
21 * in Canada (German citizen).
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 #include <sys/types.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h>
51 #include <sys/resource.h>
52 #include <sys/ioctl.h>
53 #include <sys/param.h>
54 #include <sys/socket.h>
73 #include <netinet/in.h>
74 #include <arpa/inet.h>
76 #include <openssl/evp.h>
77 #include <openssl/err.h>
78 #include "openbsd-compat/openssl-compat.h"
79 #include "openbsd-compat/sys-queue.h"
94 #include "pathnames.h"
96 #include "clientloop.h"
99 #include "sshconnect.h"
111 #include "ssh-pkcs11.h"
114 extern char *__progname;
116 /* Saves a copy of argv for setproctitle emulation */
117 #ifndef HAVE_SETPROCTITLE
118 static char **saved_av;
121 /* Flag indicating whether debug mode is on. May be set on the command line. */
124 /* Flag indicating whether a tty should be requested */
127 /* don't exec a shell */
128 int no_shell_flag = 0;
131 * Flag indicating that nothing should be read from stdin. This can be set
132 * on the command line.
134 int stdin_null_flag = 0;
137 * Flag indicating that the current process should be backgrounded and
138 * a new slave launched in the foreground for ControlPersist.
140 int need_controlpersist_detach = 0;
142 /* Copies of flags for ControlPersist foreground slave */
143 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
146 * Flag indicating that ssh should fork after authentication. This is useful
147 * so that the passphrase can be entered manually, and then ssh goes to the
150 int fork_after_authentication_flag = 0;
152 /* forward stdio to remote host and port */
153 char *stdio_forward_host = NULL;
154 int stdio_forward_port = 0;
157 * General data structure for command line options and options configurable
158 * in configuration files. See readconf.h.
162 /* optional user configfile */
166 * Name of the host we are connecting to. This is the name given on the
167 * command line, or the HostName specified for the user-supplied name in a
168 * configuration file.
172 /* socket address the host resolves to */
173 struct sockaddr_storage hostaddr;
175 /* Private host keys. */
176 Sensitive sensitive_data;
178 /* Original real UID. */
179 uid_t original_real_uid;
180 uid_t original_effective_uid;
182 /* command to be executed */
185 /* Should we execute a command or invoke a subsystem? */
186 int subsystem_flag = 0;
188 /* # of replies received for global requests */
189 static int remote_forward_confirms_received = 0;
192 extern int muxserver_sock;
193 extern u_int muxclient_command;
195 /* Prints a help message to the user. This function never returns. */
201 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
202 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
203 " [-F configfile] [-I pkcs11] [-i identity_file]\n"
204 " [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]\n"
205 " [-O ctl_cmd] [-o option] [-p port]\n"
206 " [-Q cipher | cipher-auth | mac | kex | key]\n"
207 " [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]\n"
208 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
213 static int ssh_session(void);
214 static int ssh_session2(void);
215 static void load_public_identity_files(void);
216 static void main_sigchld_handler(int);
218 /* from muxclient.c */
219 void muxclient(const char *);
220 void muxserver_listen(void);
222 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
224 tilde_expand_paths(char **paths, u_int num_paths)
229 for (i = 0; i < num_paths; i++) {
230 cp = tilde_expand_filename(paths[i], original_real_uid);
237 * Attempt to resolve a host name / port to a set of addresses and
238 * optionally return any CNAMEs encountered along the way.
239 * Returns NULL on failure.
240 * NB. this function must operate with a options having undefined members.
242 static struct addrinfo *
243 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
245 char strport[NI_MAXSERV];
246 struct addrinfo hints, *res;
247 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
250 port = default_ssh_port();
252 snprintf(strport, sizeof strport, "%u", port);
253 memset(&hints, 0, sizeof(hints));
254 hints.ai_family = options.address_family == -1 ?
255 AF_UNSPEC : options.address_family;
256 hints.ai_socktype = SOCK_STREAM;
258 hints.ai_flags = AI_CANONNAME;
259 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
260 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
261 loglevel = SYSLOG_LEVEL_ERROR;
262 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
263 __progname, name, ssh_gai_strerror(gaierr));
266 if (cname != NULL && res->ai_canonname != NULL) {
267 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
268 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
269 __func__, name, res->ai_canonname, (u_long)clen);
278 * Check whether the cname is a permitted replacement for the hostname
279 * and perform the replacement if it is.
280 * NB. this function must operate with a options having undefined members.
283 check_follow_cname(char **namep, const char *cname)
286 struct allowed_cname *rule;
288 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
289 strcmp(*namep, cname) == 0)
291 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
294 * Don't attempt to canonicalize names that will be interpreted by
295 * a proxy unless the user specifically requests so.
297 if (!option_clear_or_none(options.proxy_command) &&
298 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
300 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
301 for (i = 0; i < options.num_permitted_cnames; i++) {
302 rule = options.permitted_cnames + i;
303 if (match_pattern_list(*namep, rule->source_list,
304 strlen(rule->source_list), 1) != 1 ||
305 match_pattern_list(cname, rule->target_list,
306 strlen(rule->target_list), 1) != 1)
308 verbose("Canonicalized DNS aliased hostname "
309 "\"%s\" => \"%s\"", *namep, cname);
311 *namep = xstrdup(cname);
318 * Attempt to resolve the supplied hostname after applying the user's
319 * canonicalization rules. Returns the address list for the host or NULL
320 * if no name was found after canonicalization.
321 * NB. this function must operate with a options having undefined members.
323 static struct addrinfo *
324 resolve_canonicalize(char **hostp, int port)
327 char *cp, *fullhost, cname_target[NI_MAXHOST];
328 struct addrinfo *addrs;
330 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
334 * Don't attempt to canonicalize names that will be interpreted by
335 * a proxy unless the user specifically requests so.
337 if (!option_clear_or_none(options.proxy_command) &&
338 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
341 /* Don't apply canonicalization to sufficiently-qualified hostnames */
343 for (cp = *hostp; *cp != '\0'; cp++) {
347 if (ndots > options.canonicalize_max_dots) {
348 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
349 __func__, *hostp, options.canonicalize_max_dots);
352 /* Attempt each supplied suffix */
353 for (i = 0; i < options.num_canonical_domains; i++) {
354 *cname_target = '\0';
355 xasprintf(&fullhost, "%s.%s.", *hostp,
356 options.canonical_domains[i]);
357 debug3("%s: attempting \"%s\" => \"%s\"", __func__,
359 if ((addrs = resolve_host(fullhost, port, 0,
360 cname_target, sizeof(cname_target))) == NULL) {
364 /* Remove trailing '.' */
365 fullhost[strlen(fullhost) - 1] = '\0';
366 /* Follow CNAME if requested */
367 if (!check_follow_cname(&fullhost, cname_target)) {
368 debug("Canonicalized hostname \"%s\" => \"%s\"",
375 if (!options.canonicalize_fallback_local)
376 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
377 debug2("%s: host %s not found in any suffix", __func__, *hostp);
382 * Read per-user configuration file. Ignore the system wide config
383 * file if the user specifies a config file on the command line.
386 process_config_files(struct passwd *pw)
388 char buf[MAXPATHLEN];
391 if (config != NULL) {
392 if (strcasecmp(config, "none") != 0 &&
393 !read_config_file(config, pw, host, &options,
395 fatal("Can't open user config file %.100s: "
396 "%.100s", config, strerror(errno));
398 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
399 _PATH_SSH_USER_CONFFILE);
400 if (r > 0 && (size_t)r < sizeof(buf))
401 (void)read_config_file(buf, pw, host, &options,
402 SSHCONF_CHECKPERM|SSHCONF_USERCONF);
404 /* Read systemwide configuration file after user config. */
405 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host,
411 * Main program for the ssh client.
414 main(int ac, char **av)
416 int i, r, opt, exit_status, use_syslog;
417 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile;
418 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
419 char cname[NI_MAXHOST];
423 extern int optind, optreset;
426 struct addrinfo *addrs = NULL;
428 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
431 __progname = ssh_get_progname(av[0]);
433 #ifndef HAVE_SETPROCTITLE
434 /* Prepare for later setproctitle emulation */
435 /* Save argv so it isn't clobbered by setproctitle() emulation */
436 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
437 for (i = 0; i < ac; i++)
438 saved_av[i] = xstrdup(av[i]);
440 compat_init_setproctitle(ac, av);
445 * Discard other fds that are hanging around. These can cause problem
446 * with backgrounded ssh processes started by ControlPersist.
448 closefrom(STDERR_FILENO + 1);
451 * Save the original real uid. It will be needed later (uid-swapping
452 * may clobber the real uid).
454 original_real_uid = getuid();
455 original_effective_uid = geteuid();
458 * Use uid-swapping to give up root privileges for the duration of
459 * option processing. We will re-instantiate the rights when we are
460 * ready to create the privileged port, and will permanently drop
461 * them when the port has been created (actually, when the connection
462 * has been made, as we may need to create the port several times).
466 #ifdef HAVE_SETRLIMIT
467 /* If we are installed setuid root be careful to not drop core. */
468 if (original_real_uid != original_effective_uid) {
470 rlim.rlim_cur = rlim.rlim_max = 0;
471 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
472 fatal("setrlimit failed: %.100s", strerror(errno));
476 pw = getpwuid(original_real_uid);
478 logit("No user exists for uid %lu", (u_long)original_real_uid);
481 /* Take a copy of the returned structure. */
485 * Set our umask to something reasonable, as some files are created
486 * with the default umask. This will make them world-readable but
487 * writable only by the owner, which is ok for all files for which we
488 * don't set the modes explicitly.
493 * Initialize option structure to indicate that no values have been
496 initialize_options(&options);
498 /* Parse command-line arguments. */
505 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
506 "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
509 options.protocol = SSH_PROTO_1;
512 options.protocol = SSH_PROTO_2;
515 options.address_family = AF_INET;
518 options.address_family = AF_INET6;
524 fork_after_authentication_flag = 1;
528 options.forward_x11 = 0;
531 options.forward_x11 = 1;
537 logfile = xstrdup(optarg);
540 options.forward_x11 = 1;
541 options.forward_x11_trusted = 1;
544 options.gateway_ports = 1;
547 if (stdio_forward_host != NULL)
548 fatal("Cannot specify multiplexing "
550 else if (muxclient_command != 0)
551 fatal("Multiplexing command already specified");
552 if (strcmp(optarg, "check") == 0)
553 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
554 else if (strcmp(optarg, "forward") == 0)
555 muxclient_command = SSHMUX_COMMAND_FORWARD;
556 else if (strcmp(optarg, "exit") == 0)
557 muxclient_command = SSHMUX_COMMAND_TERMINATE;
558 else if (strcmp(optarg, "stop") == 0)
559 muxclient_command = SSHMUX_COMMAND_STOP;
560 else if (strcmp(optarg, "cancel") == 0)
561 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
563 fatal("Invalid multiplex command.");
565 case 'P': /* deprecated */
566 options.use_privileged_port = 0;
570 if (strcmp(optarg, "cipher") == 0)
571 cp = cipher_alg_list('\n', 0);
572 else if (strcmp(optarg, "cipher-auth") == 0)
573 cp = cipher_alg_list('\n', 1);
574 else if (strcmp(optarg, "mac") == 0)
575 cp = mac_alg_list('\n');
576 else if (strcmp(optarg, "kex") == 0)
577 cp = kex_alg_list('\n');
578 else if (strcmp(optarg, "key") == 0)
579 cp = key_alg_list(0, 0);
580 else if (strcmp(optarg, "key-cert") == 0)
581 cp = key_alg_list(1, 0);
582 else if (strcmp(optarg, "key-plain") == 0)
583 cp = key_alg_list(0, 1);
585 fatal("Unsupported query \"%s\"", optarg);
591 options.forward_agent = 0;
594 options.forward_agent = 1;
597 options.gss_deleg_creds = 0;
600 options.gss_authentication = 1;
601 options.gss_deleg_creds = 1;
604 if (stat(optarg, &st) < 0) {
605 fprintf(stderr, "Warning: Identity file %s "
606 "not accessible: %s.\n", optarg,
610 add_identity_file(&options, NULL, optarg, 1);
614 options.pkcs11_provider = xstrdup(optarg);
616 fprintf(stderr, "no support for PKCS#11.\n");
620 if (options.request_tty == REQUEST_TTY_YES)
621 options.request_tty = REQUEST_TTY_FORCE;
623 options.request_tty = REQUEST_TTY_YES;
626 if (debug_flag == 0) {
628 options.log_level = SYSLOG_LEVEL_DEBUG1;
630 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
635 if (options.version_addendum &&
636 *options.version_addendum != '\0')
637 fprintf(stderr, "%s%s %s, %s\n", SSH_RELEASE,
638 options.hpn_disabled ? "" : SSH_VERSION_HPN,
639 options.version_addendum,
640 SSLeay_version(SSLEAY_VERSION));
642 fprintf(stderr, "%s%s, %s\n", SSH_RELEASE,
643 options.hpn_disabled ? "" : SSH_VERSION_HPN,
644 SSLeay_version(SSLEAY_VERSION));
649 if (options.tun_open == -1)
650 options.tun_open = SSH_TUNMODE_DEFAULT;
651 options.tun_local = a2tun(optarg, &options.tun_remote);
652 if (options.tun_local == SSH_TUNID_ERR) {
654 "Bad tun device '%s'\n", optarg);
659 if (stdio_forward_host != NULL)
660 fatal("stdio forward already specified");
661 if (muxclient_command != 0)
662 fatal("Cannot specify stdio forward with -O");
663 if (parse_forward(&fwd, optarg, 1, 0)) {
664 stdio_forward_host = fwd.listen_host;
665 stdio_forward_port = fwd.listen_port;
666 free(fwd.connect_host);
669 "Bad stdio forwarding specification '%s'\n",
673 options.request_tty = REQUEST_TTY_NO;
675 options.clear_forwardings = 1;
676 options.exit_on_forward_failure = 1;
679 options.log_level = SYSLOG_LEVEL_QUIET;
682 if (optarg[0] == '^' && optarg[2] == 0 &&
683 (u_char) optarg[1] >= 64 &&
684 (u_char) optarg[1] < 128)
685 options.escape_char = (u_char) optarg[1] & 31;
686 else if (strlen(optarg) == 1)
687 options.escape_char = (u_char) optarg[0];
688 else if (strcmp(optarg, "none") == 0)
689 options.escape_char = SSH_ESCAPECHAR_NONE;
691 fprintf(stderr, "Bad escape character '%s'.\n",
697 if (ciphers_valid(optarg)) {
699 options.ciphers = xstrdup(optarg);
700 options.cipher = SSH_CIPHER_INVALID;
703 options.cipher = cipher_number(optarg);
704 if (options.cipher == -1) {
706 "Unknown cipher type '%s'\n",
710 if (options.cipher == SSH_CIPHER_3DES)
711 options.ciphers = "3des-cbc";
712 else if (options.cipher == SSH_CIPHER_BLOWFISH)
713 options.ciphers = "blowfish-cbc";
715 options.ciphers = (char *)-1;
719 if (mac_valid(optarg))
720 options.macs = xstrdup(optarg);
722 fprintf(stderr, "Unknown mac type '%s'\n",
728 if (options.control_master == SSHCTL_MASTER_YES)
729 options.control_master = SSHCTL_MASTER_ASK;
731 options.control_master = SSHCTL_MASTER_YES;
734 options.port = a2port(optarg);
735 if (options.port <= 0) {
736 fprintf(stderr, "Bad port '%s'\n", optarg);
741 options.user = optarg;
745 if (parse_forward(&fwd, optarg, 0, 0))
746 add_local_forward(&options, &fwd);
749 "Bad local forwarding specification '%s'\n",
756 if (parse_forward(&fwd, optarg, 0, 1)) {
757 add_remote_forward(&options, &fwd);
760 "Bad remote forwarding specification "
767 if (parse_forward(&fwd, optarg, 1, 0)) {
768 add_local_forward(&options, &fwd);
771 "Bad dynamic forwarding specification "
778 options.compression = 1;
782 options.request_tty = REQUEST_TTY_NO;
785 options.request_tty = REQUEST_TTY_NO;
786 #ifdef NONE_CIPHER_ENABLED
788 * Ensure that the user does not try to backdoor a
789 * NONE cipher switch on an interactive session by
790 * explicitly disabling it if the user asks for a
791 * session without a tty.
793 options.none_switch = 0;
797 line = xstrdup(optarg);
798 if (process_config_line(&options, pw, host ? host : "",
799 line, "command-line", 0, NULL, SSHCONF_USERCONF)
808 if (options.control_path != NULL)
809 free(options.control_path);
810 options.control_path = xstrdup(optarg);
813 options.bind_address = optarg;
826 if (ac > 0 && !host) {
827 if (strrchr(*av, '@')) {
829 cp = strrchr(p, '@');
830 if (cp == NULL || cp == p)
834 host = xstrdup(++cp);
838 optind = optreset = 1;
844 /* Check that we got a host name. */
848 host_arg = xstrdup(host);
850 OpenSSL_add_all_algorithms();
851 ERR_load_crypto_strings();
853 /* Initialize the command to execute on remote host. */
854 buffer_init(&command);
857 * Save the command to execute on the remote host in a buffer. There
858 * is no limit on the length of the command, except by the maximum
859 * packet size. Also sets the tty flag if there is no command.
862 /* No command specified - execute shell on a tty. */
863 if (subsystem_flag) {
865 "You must specify a subsystem to invoke.\n");
869 /* A command has been specified. Store it into the buffer. */
870 for (i = 0; i < ac; i++) {
872 buffer_append(&command, " ", 1);
873 buffer_append(&command, av[i], strlen(av[i]));
877 /* Cannot fork to background if no command. */
878 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
880 fatal("Cannot fork into background without a command "
884 * Initialize "log" output. Since we are the client all output
885 * goes to stderr unless otherwise specified by -y or -E.
887 if (use_syslog && logfile != NULL)
888 fatal("Can't specify both -y and -E");
889 if (logfile != NULL) {
890 log_redirect_stderr_to(logfile);
894 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
895 SYSLOG_FACILITY_USER, !use_syslog);
898 logit("%s, %s", SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
900 /* Parse the configuration files */
901 process_config_files(pw);
903 /* Hostname canonicalisation needs a few options filled. */
904 fill_default_options_for_canonicalization(&options);
906 /* If the user has replaced the hostname then take it into use now */
907 if (options.hostname != NULL) {
908 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
909 cp = percent_expand(options.hostname,
910 "h", host, (char *)NULL);
915 /* If canonicalization requested then try to apply it */
917 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
918 addrs = resolve_canonicalize(&host, options.port);
921 * If CanonicalizePermittedCNAMEs have been specified but
922 * other canonicalization did not happen (by not being requested
923 * or by failing with fallback) then the hostname may still be changed
924 * as a result of CNAME following.
926 * Try to resolve the bare hostname name using the system resolver's
927 * usual search rules and then apply the CNAME follow rules.
929 * Skip the lookup if a ProxyCommand is being used unless the user
930 * has specifically requested canonicalisation for this case via
931 * CanonicalizeHostname=always
933 if (addrs == NULL && options.num_permitted_cnames != 0 &&
934 (option_clear_or_none(options.proxy_command) ||
935 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
936 if ((addrs = resolve_host(host, options.port, 1,
937 cname, sizeof(cname))) == NULL)
938 cleanup_exit(255); /* resolve_host logs the error */
939 check_follow_cname(&host, cname);
943 * If the target hostname has changed as a result of canonicalisation
944 * then re-parse the configuration files as new stanzas may match.
946 if (strcasecmp(host_arg, host) != 0) {
947 debug("Hostname has changed; re-reading configuration");
948 process_config_files(pw);
951 /* Fill configuration defaults. */
952 fill_default_options(&options);
954 if (options.port == 0)
955 options.port = default_ssh_port();
956 channel_set_af(options.address_family);
958 /* Tidy and check options */
959 if (options.host_key_alias != NULL)
960 lowercase(options.host_key_alias);
961 if (options.proxy_command != NULL &&
962 strcmp(options.proxy_command, "-") == 0 &&
963 options.proxy_use_fdpass)
964 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
966 if (original_effective_uid != 0)
967 options.use_privileged_port = 0;
971 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
973 if (options.request_tty == REQUEST_TTY_YES ||
974 options.request_tty == REQUEST_TTY_FORCE)
977 /* Allocate a tty by default if no command specified. */
978 if (buffer_len(&command) == 0)
979 tty_flag = options.request_tty != REQUEST_TTY_NO;
982 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
984 /* Do not allocate a tty if stdin is not a tty. */
985 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
986 options.request_tty != REQUEST_TTY_FORCE) {
988 logit("Pseudo-terminal will not be allocated because "
989 "stdin is not a terminal.");
995 if (options.user == NULL)
996 options.user = xstrdup(pw->pw_name);
998 if (gethostname(thishost, sizeof(thishost)) == -1)
999 fatal("gethostname: %s", strerror(errno));
1000 strlcpy(shorthost, thishost, sizeof(shorthost));
1001 shorthost[strcspn(thishost, ".")] = '\0';
1002 snprintf(portstr, sizeof(portstr), "%d", options.port);
1004 if (options.local_command != NULL) {
1005 debug3("expanding LocalCommand: %s", options.local_command);
1006 cp = options.local_command;
1007 options.local_command = percent_expand(cp, "d", pw->pw_dir,
1008 "h", host, "l", thishost, "n", host_arg, "r", options.user,
1009 "p", portstr, "u", pw->pw_name, "L", shorthost,
1011 debug3("expanded LocalCommand: %s", options.local_command);
1015 if (options.control_path != NULL) {
1016 cp = tilde_expand_filename(options.control_path,
1018 free(options.control_path);
1019 options.control_path = percent_expand(cp, "h", host,
1020 "l", thishost, "n", host_arg, "r", options.user,
1021 "p", portstr, "u", pw->pw_name, "L", shorthost,
1025 if (muxclient_command != 0 && options.control_path == NULL)
1026 fatal("No ControlPath specified for \"-O\" command");
1027 if (options.control_path != NULL)
1028 muxclient(options.control_path);
1031 * If hostname canonicalisation was not enabled, then we may not
1032 * have yet resolved the hostname. Do so now.
1034 if (addrs == NULL && options.proxy_command == NULL) {
1035 if ((addrs = resolve_host(host, options.port, 1,
1036 cname, sizeof(cname))) == NULL)
1037 cleanup_exit(255); /* resolve_host logs the error */
1040 timeout_ms = options.connection_timeout * 1000;
1042 /* Open a connection to the remote host. */
1043 if (ssh_connect(host, addrs, &hostaddr, options.port,
1044 options.address_family, options.connection_attempts,
1045 &timeout_ms, options.tcp_keep_alive,
1046 options.use_privileged_port) != 0)
1050 freeaddrinfo(addrs);
1052 packet_set_timeout(options.server_alive_interval,
1053 options.server_alive_count_max);
1056 debug3("timeout: %d ms remain after connect", timeout_ms);
1059 * If we successfully made the connection, load the host private key
1060 * in case we will need it later for combined rsa-rhosts
1061 * authentication. This must be done before releasing extra
1062 * privileges, because the file is only readable by root.
1063 * If we cannot access the private keys, load the public keys
1064 * instead and try to execute the ssh-keysign helper instead.
1066 sensitive_data.nkeys = 0;
1067 sensitive_data.keys = NULL;
1068 sensitive_data.external_keysign = 0;
1069 if (options.rhosts_rsa_authentication ||
1070 options.hostbased_authentication) {
1071 sensitive_data.nkeys = 9;
1072 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1074 for (i = 0; i < sensitive_data.nkeys; i++)
1075 sensitive_data.keys[i] = NULL;
1078 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1079 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1080 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
1081 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1082 #ifdef OPENSSL_HAS_ECC
1083 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
1084 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1086 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1087 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1088 sensitive_data.keys[4] = key_load_private_cert(KEY_ED25519,
1089 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1090 sensitive_data.keys[5] = key_load_private_type(KEY_DSA,
1091 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1092 #ifdef OPENSSL_HAS_ECC
1093 sensitive_data.keys[6] = key_load_private_type(KEY_ECDSA,
1094 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1096 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1097 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1098 sensitive_data.keys[8] = key_load_private_type(KEY_ED25519,
1099 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1102 if (options.hostbased_authentication == 1 &&
1103 sensitive_data.keys[0] == NULL &&
1104 sensitive_data.keys[5] == NULL &&
1105 sensitive_data.keys[6] == NULL &&
1106 sensitive_data.keys[7] == NULL &&
1107 sensitive_data.keys[8] == NULL) {
1108 sensitive_data.keys[1] = key_load_cert(
1109 _PATH_HOST_DSA_KEY_FILE);
1110 #ifdef OPENSSL_HAS_ECC
1111 sensitive_data.keys[2] = key_load_cert(
1112 _PATH_HOST_ECDSA_KEY_FILE);
1114 sensitive_data.keys[3] = key_load_cert(
1115 _PATH_HOST_RSA_KEY_FILE);
1116 sensitive_data.keys[4] = key_load_cert(
1117 _PATH_HOST_ED25519_KEY_FILE);
1118 sensitive_data.keys[5] = key_load_public(
1119 _PATH_HOST_DSA_KEY_FILE, NULL);
1120 #ifdef OPENSSL_HAS_ECC
1121 sensitive_data.keys[6] = key_load_public(
1122 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1124 sensitive_data.keys[7] = key_load_public(
1125 _PATH_HOST_RSA_KEY_FILE, NULL);
1126 sensitive_data.keys[8] = key_load_public(
1127 _PATH_HOST_ED25519_KEY_FILE, NULL);
1128 sensitive_data.external_keysign = 1;
1132 * Get rid of any extra privileges that we may have. We will no
1133 * longer need them. Also, extra privileges could make it very hard
1134 * to read identity files and other non-world-readable files from the
1135 * user's home directory if it happens to be on a NFS volume where
1136 * root is mapped to nobody.
1138 if (original_effective_uid == 0) {
1140 permanently_set_uid(pw);
1144 * Now that we are back to our own permissions, create ~/.ssh
1145 * directory if it doesn't already exist.
1147 if (config == NULL) {
1148 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1149 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1150 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1152 ssh_selinux_setfscreatecon(buf);
1154 if (mkdir(buf, 0700) < 0)
1155 error("Could not create directory '%.200s'.",
1158 ssh_selinux_setfscreatecon(NULL);
1162 /* load options.identity_files */
1163 load_public_identity_files();
1165 /* Expand ~ in known host file names. */
1166 tilde_expand_paths(options.system_hostfiles,
1167 options.num_system_hostfiles);
1168 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1170 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1171 signal(SIGCHLD, main_sigchld_handler);
1173 /* Log into the remote system. Never returns if the login fails. */
1174 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1175 options.port, pw, timeout_ms);
1177 if (packet_connection_is_on_socket()) {
1178 verbose("Authenticated to %s ([%s]:%d).", host,
1179 get_remote_ipaddr(), get_remote_port());
1181 verbose("Authenticated to %s (via proxy).", host);
1184 /* We no longer need the private host keys. Clear them now. */
1185 if (sensitive_data.nkeys != 0) {
1186 for (i = 0; i < sensitive_data.nkeys; i++) {
1187 if (sensitive_data.keys[i] != NULL) {
1188 /* Destroys contents safely */
1189 debug3("clear hostkey %d", i);
1190 key_free(sensitive_data.keys[i]);
1191 sensitive_data.keys[i] = NULL;
1194 free(sensitive_data.keys);
1196 for (i = 0; i < options.num_identity_files; i++) {
1197 free(options.identity_files[i]);
1198 options.identity_files[i] = NULL;
1199 if (options.identity_keys[i]) {
1200 key_free(options.identity_keys[i]);
1201 options.identity_keys[i] = NULL;
1205 exit_status = compat20 ? ssh_session2() : ssh_session();
1208 if (options.control_path != NULL && muxserver_sock != -1)
1209 unlink(options.control_path);
1211 /* Kill ProxyCommand if it is running. */
1212 ssh_kill_proxy_command();
1218 control_persist_detach(void)
1223 debug("%s: backgrounding master process", __func__);
1226 * master (current process) into the background, and make the
1227 * foreground process a client of the backgrounded master.
1229 switch ((pid = fork())) {
1231 fatal("%s: fork: %s", __func__, strerror(errno));
1233 /* Child: master process continues mainloop */
1236 /* Parent: set up mux slave to connect to backgrounded master */
1237 debug2("%s: background process is %ld", __func__, (long)pid);
1238 stdin_null_flag = ostdin_null_flag;
1239 options.request_tty = orequest_tty;
1240 tty_flag = otty_flag;
1241 close(muxserver_sock);
1242 muxserver_sock = -1;
1243 options.control_master = SSHCTL_MASTER_NO;
1244 muxclient(options.control_path);
1245 /* muxclient() doesn't return on success. */
1246 fatal("Failed to connect to new control master");
1248 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1249 error("%s: open(\"/dev/null\"): %s", __func__,
1252 if (dup2(devnull, STDIN_FILENO) == -1 ||
1253 dup2(devnull, STDOUT_FILENO) == -1)
1254 error("%s: dup2: %s", __func__, strerror(errno));
1255 if (devnull > STDERR_FILENO)
1259 setproctitle("%s [mux]", options.control_path);
1262 /* Do fork() after authentication. Used by "ssh -f" */
1266 if (need_controlpersist_detach)
1267 control_persist_detach();
1268 debug("forking to background");
1269 fork_after_authentication_flag = 0;
1270 if (daemon(1, 1) < 0)
1271 fatal("daemon() failed: %.200s", strerror(errno));
1274 /* Callback for remote forward global requests */
1276 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1278 Forward *rfwd = (Forward *)ctxt;
1280 /* XXX verbose() on failure? */
1281 debug("remote forward %s for: listen %d, connect %s:%d",
1282 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1283 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1284 if (rfwd->listen_port == 0) {
1285 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1286 rfwd->allocated_port = packet_get_int();
1287 logit("Allocated port %u for remote forward to %s:%d",
1288 rfwd->allocated_port,
1289 rfwd->connect_host, rfwd->connect_port);
1290 channel_update_permitted_opens(rfwd->handle,
1291 rfwd->allocated_port);
1293 channel_update_permitted_opens(rfwd->handle, -1);
1297 if (type == SSH2_MSG_REQUEST_FAILURE) {
1298 if (options.exit_on_forward_failure)
1299 fatal("Error: remote port forwarding failed for "
1300 "listen port %d", rfwd->listen_port);
1302 logit("Warning: remote port forwarding failed for "
1303 "listen port %d", rfwd->listen_port);
1305 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1306 debug("All remote forwarding requests processed");
1307 if (fork_after_authentication_flag)
1313 client_cleanup_stdio_fwd(int id, void *arg)
1315 debug("stdio forwarding: done");
1320 ssh_init_stdio_forwarding(void)
1325 if (stdio_forward_host == NULL)
1328 fatal("stdio forwarding require Protocol 2");
1330 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1332 if ((in = dup(STDIN_FILENO)) < 0 ||
1333 (out = dup(STDOUT_FILENO)) < 0)
1334 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1335 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1336 stdio_forward_port, in, out)) == NULL)
1337 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1338 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1342 ssh_init_forwarding(void)
1347 /* Initiate local TCP/IP port forwardings. */
1348 for (i = 0; i < options.num_local_forwards; i++) {
1349 debug("Local connections to %.200s:%d forwarded to remote "
1350 "address %.200s:%d",
1351 (options.local_forwards[i].listen_host == NULL) ?
1352 (options.gateway_ports ? "*" : "LOCALHOST") :
1353 options.local_forwards[i].listen_host,
1354 options.local_forwards[i].listen_port,
1355 options.local_forwards[i].connect_host,
1356 options.local_forwards[i].connect_port);
1357 success += channel_setup_local_fwd_listener(
1358 options.local_forwards[i].listen_host,
1359 options.local_forwards[i].listen_port,
1360 options.local_forwards[i].connect_host,
1361 options.local_forwards[i].connect_port,
1362 options.gateway_ports);
1364 if (i > 0 && success != i && options.exit_on_forward_failure)
1365 fatal("Could not request local forwarding.");
1366 if (i > 0 && success == 0)
1367 error("Could not request local forwarding.");
1369 /* Initiate remote TCP/IP port forwardings. */
1370 for (i = 0; i < options.num_remote_forwards; i++) {
1371 debug("Remote connections from %.200s:%d forwarded to "
1372 "local address %.200s:%d",
1373 (options.remote_forwards[i].listen_host == NULL) ?
1374 "LOCALHOST" : options.remote_forwards[i].listen_host,
1375 options.remote_forwards[i].listen_port,
1376 options.remote_forwards[i].connect_host,
1377 options.remote_forwards[i].connect_port);
1378 options.remote_forwards[i].handle =
1379 channel_request_remote_forwarding(
1380 options.remote_forwards[i].listen_host,
1381 options.remote_forwards[i].listen_port,
1382 options.remote_forwards[i].connect_host,
1383 options.remote_forwards[i].connect_port);
1384 if (options.remote_forwards[i].handle < 0) {
1385 if (options.exit_on_forward_failure)
1386 fatal("Could not request remote forwarding.");
1388 logit("Warning: Could not request remote "
1391 client_register_global_confirm(ssh_confirm_remote_forward,
1392 &options.remote_forwards[i]);
1396 /* Initiate tunnel forwarding. */
1397 if (options.tun_open != SSH_TUNMODE_NO) {
1398 if (client_request_tun_fwd(options.tun_open,
1399 options.tun_local, options.tun_remote) == -1) {
1400 if (options.exit_on_forward_failure)
1401 fatal("Could not request tunnel forwarding.");
1403 error("Could not request tunnel forwarding.");
1409 check_agent_present(void)
1411 if (options.forward_agent) {
1412 /* Clear agent forwarding if we don't have an agent. */
1413 if (!ssh_agent_present())
1414 options.forward_agent = 0;
1422 int interactive = 0;
1426 const char *display;
1428 /* Enable compression if requested. */
1429 if (options.compression) {
1430 debug("Requesting compression at level %d.",
1431 options.compression_level);
1433 if (options.compression_level < 1 ||
1434 options.compression_level > 9)
1435 fatal("Compression level must be from 1 (fast) to "
1438 /* Send the request. */
1439 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1440 packet_put_int(options.compression_level);
1442 packet_write_wait();
1443 type = packet_read();
1444 if (type == SSH_SMSG_SUCCESS)
1445 packet_start_compression(options.compression_level);
1446 else if (type == SSH_SMSG_FAILURE)
1447 logit("Warning: Remote host refused compression.");
1449 packet_disconnect("Protocol error waiting for "
1450 "compression response.");
1452 /* Allocate a pseudo tty if appropriate. */
1454 debug("Requesting pty.");
1456 /* Start the packet. */
1457 packet_start(SSH_CMSG_REQUEST_PTY);
1459 /* Store TERM in the packet. There is no limit on the
1460 length of the string. */
1461 cp = getenv("TERM");
1464 packet_put_cstring(cp);
1466 /* Store window size in the packet. */
1467 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1468 memset(&ws, 0, sizeof(ws));
1469 packet_put_int((u_int)ws.ws_row);
1470 packet_put_int((u_int)ws.ws_col);
1471 packet_put_int((u_int)ws.ws_xpixel);
1472 packet_put_int((u_int)ws.ws_ypixel);
1474 /* Store tty modes in the packet. */
1475 tty_make_modes(fileno(stdin), NULL);
1477 /* Send the packet, and wait for it to leave. */
1479 packet_write_wait();
1481 /* Read response from the server. */
1482 type = packet_read();
1483 if (type == SSH_SMSG_SUCCESS) {
1486 } else if (type == SSH_SMSG_FAILURE)
1487 logit("Warning: Remote host failed or refused to "
1488 "allocate a pseudo tty.");
1490 packet_disconnect("Protocol error waiting for pty "
1491 "request response.");
1493 /* Request X11 forwarding if enabled and DISPLAY is set. */
1494 display = getenv("DISPLAY");
1495 if (options.forward_x11 && display != NULL) {
1497 /* Get reasonable local authentication information. */
1498 client_x11_get_proto(display, options.xauth_location,
1499 options.forward_x11_trusted,
1500 options.forward_x11_timeout,
1502 /* Request forwarding with authentication spoofing. */
1503 debug("Requesting X11 forwarding with authentication "
1505 x11_request_forwarding_with_spoofing(0, display, proto,
1507 /* Read response from the server. */
1508 type = packet_read();
1509 if (type == SSH_SMSG_SUCCESS) {
1511 } else if (type == SSH_SMSG_FAILURE) {
1512 logit("Warning: Remote host denied X11 forwarding.");
1514 packet_disconnect("Protocol error waiting for X11 "
1518 /* Tell the packet module whether this is an interactive session. */
1519 packet_set_interactive(interactive,
1520 options.ip_qos_interactive, options.ip_qos_bulk);
1522 /* Request authentication agent forwarding if appropriate. */
1523 check_agent_present();
1525 if (options.forward_agent) {
1526 debug("Requesting authentication agent forwarding.");
1527 auth_request_forwarding();
1529 /* Read response from the server. */
1530 type = packet_read();
1532 if (type != SSH_SMSG_SUCCESS)
1533 logit("Warning: Remote host denied authentication agent forwarding.");
1536 /* Initiate port forwardings. */
1537 ssh_init_stdio_forwarding();
1538 ssh_init_forwarding();
1540 /* Execute a local command */
1541 if (options.local_command != NULL &&
1542 options.permit_local_command)
1543 ssh_local_cmd(options.local_command);
1546 * If requested and we are not interested in replies to remote
1547 * forwarding requests, then let ssh continue in the background.
1549 if (fork_after_authentication_flag) {
1550 if (options.exit_on_forward_failure &&
1551 options.num_remote_forwards > 0) {
1552 debug("deferring postauth fork until remote forward "
1553 "confirmation received");
1559 * If a command was specified on the command line, execute the
1560 * command now. Otherwise request the server to start a shell.
1562 if (buffer_len(&command) > 0) {
1563 int len = buffer_len(&command);
1566 debug("Sending command: %.*s", len,
1567 (u_char *)buffer_ptr(&command));
1568 packet_start(SSH_CMSG_EXEC_CMD);
1569 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1571 packet_write_wait();
1573 debug("Requesting shell.");
1574 packet_start(SSH_CMSG_EXEC_SHELL);
1576 packet_write_wait();
1579 /* Enter the interactive session. */
1580 return client_loop(have_tty, tty_flag ?
1581 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1584 /* request pty/x11/agent/tcpfwd/shell for channel */
1586 ssh_session2_setup(int id, int success, void *arg)
1588 extern char **environ;
1589 const char *display;
1590 int interactive = tty_flag;
1593 return; /* No need for error message, channels code sens one */
1595 display = getenv("DISPLAY");
1596 if (options.forward_x11 && display != NULL) {
1598 /* Get reasonable local authentication information. */
1599 client_x11_get_proto(display, options.xauth_location,
1600 options.forward_x11_trusted,
1601 options.forward_x11_timeout, &proto, &data);
1602 /* Request forwarding with authentication spoofing. */
1603 debug("Requesting X11 forwarding with authentication "
1605 x11_request_forwarding_with_spoofing(id, display, proto,
1607 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1608 /* XXX exit_on_forward_failure */
1612 check_agent_present();
1613 if (options.forward_agent) {
1614 debug("Requesting authentication agent forwarding.");
1615 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1619 /* Tell the packet module whether this is an interactive session. */
1620 packet_set_interactive(interactive,
1621 options.ip_qos_interactive, options.ip_qos_bulk);
1623 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1624 NULL, fileno(stdin), &command, environ);
1627 /* open new channel for a session */
1629 ssh_session2_open(void)
1632 int window, packetmax, in, out, err;
1634 if (stdin_null_flag) {
1635 in = open(_PATH_DEVNULL, O_RDONLY);
1637 in = dup(STDIN_FILENO);
1639 out = dup(STDOUT_FILENO);
1640 err = dup(STDERR_FILENO);
1642 if (in < 0 || out < 0 || err < 0)
1643 fatal("dup() in/out/err failed");
1645 /* enable nonblocking unless tty */
1654 * We need to check to see what to do about buffer sizes here.
1655 * - In an HPN to non-HPN connection we want to limit the window size to
1656 * something reasonable in case the far side has the large window bug.
1657 * - In an HPN to HPN connection we want to use the max window size but
1658 * allow the user to override it.
1659 * - Lastly if HPN is disabled then use the ssh standard window size.
1661 * We cannot just do a getsockopt() here and set the ssh window to that
1662 * as in case of autotuning of socket buffers the window would get stuck
1663 * at the initial buffer size, generally less than 96k. Therefore we
1664 * need to set the maximum ssh window size to the maximum HPN buffer
1665 * size unless the user has set TcpRcvBufPoll to no. In that case we
1666 * can just set the window to the minimum of HPN buffer size and TCP
1667 * receive buffer size.
1670 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1672 options.hpn_buffer_size = CHAN_HPN_MIN_WINDOW_DEFAULT;
1674 if (datafellows & SSH_BUG_LARGEWINDOW) {
1675 debug("HPN to Non-HPN Connection");
1676 } else if (options.tcp_rcv_buf_poll <= 0) {
1677 sock_get_rcvbuf(&options.hpn_buffer_size, 0);
1678 debug("HPNBufferSize set to TCP RWIN: %d",
1679 options.hpn_buffer_size);
1680 } else if (options.tcp_rcv_buf > 0) {
1681 sock_get_rcvbuf(&options.hpn_buffer_size,
1682 options.tcp_rcv_buf);
1683 debug("HPNBufferSize set to user TCPRcvBuf: %d",
1684 options.hpn_buffer_size);
1686 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1687 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1688 window = options.hpn_buffer_size;
1690 packetmax = CHAN_SES_PACKET_DEFAULT;
1692 window = CHAN_SES_WINDOW_DEFAULT;
1697 "session", SSH_CHANNEL_OPENING, in, out, err,
1698 window, packetmax, CHAN_EXTENDED_WRITE,
1699 "client-session", /*nonblock*/0);
1700 if (!options.hpn_disabled && options.tcp_rcv_buf_poll > 0) {
1701 c->dynamic_window = 1;
1702 debug("Enabled Dynamic Window Scaling\n");
1705 debug3("ssh_session2_open: channel_new: %d", c->self);
1707 channel_send_open(c->self);
1709 channel_register_open_confirm(c->self,
1710 ssh_session2_setup, NULL);
1720 /* XXX should be pre-session */
1721 if (!options.control_persist)
1722 ssh_init_stdio_forwarding();
1723 ssh_init_forwarding();
1725 /* Start listening for multiplex clients */
1729 * If we are in control persist mode and have a working mux listen
1730 * socket, then prepare to background ourselves and have a foreground
1731 * client attach as a control slave.
1732 * NB. we must save copies of the flags that we override for
1733 * the backgrounding, since we defer attachment of the slave until
1734 * after the connection is fully established (in particular,
1735 * async rfwd replies have been received for ExitOnForwardFailure).
1737 if (options.control_persist && muxserver_sock != -1) {
1738 ostdin_null_flag = stdin_null_flag;
1739 ono_shell_flag = no_shell_flag;
1740 orequest_tty = options.request_tty;
1741 otty_flag = tty_flag;
1742 stdin_null_flag = 1;
1745 if (!fork_after_authentication_flag)
1746 need_controlpersist_detach = 1;
1747 fork_after_authentication_flag = 1;
1750 * ControlPersist mux listen socket setup failed, attempt the
1751 * stdio forward setup that we skipped earlier.
1753 if (options.control_persist && muxserver_sock == -1)
1754 ssh_init_stdio_forwarding();
1756 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1757 id = ssh_session2_open();
1759 packet_set_interactive(
1760 options.control_master == SSHCTL_MASTER_NO,
1761 options.ip_qos_interactive, options.ip_qos_bulk);
1764 /* If we don't expect to open a new session, then disallow it */
1765 if (options.control_master == SSHCTL_MASTER_NO &&
1766 (datafellows & SSH_NEW_OPENSSH)) {
1767 debug("Requesting no-more-sessions@openssh.com");
1768 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1769 packet_put_cstring("no-more-sessions@openssh.com");
1774 /* Execute a local command */
1775 if (options.local_command != NULL &&
1776 options.permit_local_command)
1777 ssh_local_cmd(options.local_command);
1780 * If requested and we are not interested in replies to remote
1781 * forwarding requests, then let ssh continue in the background.
1783 if (fork_after_authentication_flag) {
1784 if (options.exit_on_forward_failure &&
1785 options.num_remote_forwards > 0) {
1786 debug("deferring postauth fork until remote forward "
1787 "confirmation received");
1792 if (options.use_roaming)
1795 return client_loop(tty_flag, tty_flag ?
1796 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1800 load_public_identity_files(void)
1802 char *filename, *cp, thishost[NI_MAXHOST];
1803 char *pwdir = NULL, *pwname = NULL;
1808 char *identity_files[SSH_MAX_IDENTITY_FILES];
1809 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1810 #ifdef ENABLE_PKCS11
1816 memset(identity_files, 0, sizeof(identity_files));
1817 memset(identity_keys, 0, sizeof(identity_keys));
1819 #ifdef ENABLE_PKCS11
1820 if (options.pkcs11_provider != NULL &&
1821 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1822 (pkcs11_init(!options.batch_mode) == 0) &&
1823 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1825 for (i = 0; i < nkeys; i++) {
1826 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1830 identity_keys[n_ids] = keys[i];
1831 identity_files[n_ids] =
1832 xstrdup(options.pkcs11_provider); /* XXX */
1837 #endif /* ENABLE_PKCS11 */
1838 if ((pw = getpwuid(original_real_uid)) == NULL)
1839 fatal("load_public_identity_files: getpwuid failed");
1840 pwname = xstrdup(pw->pw_name);
1841 pwdir = xstrdup(pw->pw_dir);
1842 if (gethostname(thishost, sizeof(thishost)) == -1)
1843 fatal("load_public_identity_files: gethostname: %s",
1845 for (i = 0; i < options.num_identity_files; i++) {
1846 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
1847 strcasecmp(options.identity_files[i], "none") == 0) {
1848 free(options.identity_files[i]);
1851 cp = tilde_expand_filename(options.identity_files[i],
1853 filename = percent_expand(cp, "d", pwdir,
1854 "u", pwname, "l", thishost, "h", host,
1855 "r", options.user, (char *)NULL);
1857 public = key_load_public(filename, NULL);
1858 debug("identity file %s type %d", filename,
1859 public ? public->type : -1);
1860 free(options.identity_files[i]);
1861 identity_files[n_ids] = filename;
1862 identity_keys[n_ids] = public;
1864 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1867 /* Try to add the certificate variant too */
1868 xasprintf(&cp, "%s-cert", filename);
1869 public = key_load_public(cp, NULL);
1870 debug("identity file %s type %d", cp,
1871 public ? public->type : -1);
1872 if (public == NULL) {
1876 if (!key_is_cert(public)) {
1877 debug("%s: key %s type %s is not a certificate",
1878 __func__, cp, key_type(public));
1883 identity_keys[n_ids] = public;
1884 /* point to the original path, most likely the private key */
1885 identity_files[n_ids] = xstrdup(filename);
1888 options.num_identity_files = n_ids;
1889 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1890 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1892 explicit_bzero(pwname, strlen(pwname));
1894 explicit_bzero(pwdir, strlen(pwdir));
1899 main_sigchld_handler(int sig)
1901 int save_errno = errno;
1905 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1906 (pid < 0 && errno == EINTR))
1909 signal(sig, main_sigchld_handler);