1 /* $OpenBSD: ssh.c,v 1.401 2014/02/26 20:18:37 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
50 #include <sys/resource.h>
51 #include <sys/ioctl.h>
52 #include <sys/param.h>
53 #include <sys/socket.h>
72 #include <netinet/in.h>
73 #include <arpa/inet.h>
75 #include <openssl/evp.h>
76 #include <openssl/err.h>
77 #include "openbsd-compat/openssl-compat.h"
78 #include "openbsd-compat/sys-queue.h"
93 #include "pathnames.h"
95 #include "clientloop.h"
98 #include "sshconnect.h"
110 #include "ssh-pkcs11.h"
113 extern char *__progname;
115 /* Saves a copy of argv for setproctitle emulation */
116 #ifndef HAVE_SETPROCTITLE
117 static char **saved_av;
120 /* Flag indicating whether debug mode is on. May be set on the command line. */
123 /* Flag indicating whether a tty should be requested */
126 /* don't exec a shell */
127 int no_shell_flag = 0;
130 * Flag indicating that nothing should be read from stdin. This can be set
131 * on the command line.
133 int stdin_null_flag = 0;
136 * Flag indicating that the current process should be backgrounded and
137 * a new slave launched in the foreground for ControlPersist.
139 int need_controlpersist_detach = 0;
141 /* Copies of flags for ControlPersist foreground slave */
142 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
145 * Flag indicating that ssh should fork after authentication. This is useful
146 * so that the passphrase can be entered manually, and then ssh goes to the
149 int fork_after_authentication_flag = 0;
151 /* forward stdio to remote host and port */
152 char *stdio_forward_host = NULL;
153 int stdio_forward_port = 0;
156 * General data structure for command line options and options configurable
157 * in configuration files. See readconf.h.
161 /* optional user configfile */
165 * Name of the host we are connecting to. This is the name given on the
166 * command line, or the HostName specified for the user-supplied name in a
167 * configuration file.
171 /* socket address the host resolves to */
172 struct sockaddr_storage hostaddr;
174 /* Private host keys. */
175 Sensitive sensitive_data;
177 /* Original real UID. */
178 uid_t original_real_uid;
179 uid_t original_effective_uid;
181 /* command to be executed */
184 /* Should we execute a command or invoke a subsystem? */
185 int subsystem_flag = 0;
187 /* # of replies received for global requests */
188 static int remote_forward_confirms_received = 0;
191 extern int muxserver_sock;
192 extern u_int muxclient_command;
194 /* Prints a help message to the user. This function never returns. */
200 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
201 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
202 " [-F configfile] [-I pkcs11] [-i identity_file]\n"
203 " [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]\n"
204 " [-O ctl_cmd] [-o option] [-p port]\n"
205 " [-Q cipher | cipher-auth | mac | kex | key]\n"
206 " [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]\n"
207 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
212 static int ssh_session(void);
213 static int ssh_session2(void);
214 static void load_public_identity_files(void);
215 static void main_sigchld_handler(int);
217 /* from muxclient.c */
218 void muxclient(const char *);
219 void muxserver_listen(void);
221 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
223 tilde_expand_paths(char **paths, u_int num_paths)
228 for (i = 0; i < num_paths; i++) {
229 cp = tilde_expand_filename(paths[i], original_real_uid);
236 * Attempt to resolve a host name / port to a set of addresses and
237 * optionally return any CNAMEs encountered along the way.
238 * Returns NULL on failure.
239 * NB. this function must operate with a options having undefined members.
241 static struct addrinfo *
242 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
244 char strport[NI_MAXSERV];
245 struct addrinfo hints, *res;
246 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
249 port = default_ssh_port();
251 snprintf(strport, sizeof strport, "%u", port);
252 memset(&hints, 0, sizeof(hints));
253 hints.ai_family = options.address_family == -1 ?
254 AF_UNSPEC : options.address_family;
255 hints.ai_socktype = SOCK_STREAM;
257 hints.ai_flags = AI_CANONNAME;
258 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
259 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
260 loglevel = SYSLOG_LEVEL_ERROR;
261 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
262 __progname, name, ssh_gai_strerror(gaierr));
265 if (cname != NULL && res->ai_canonname != NULL) {
266 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
267 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
268 __func__, name, res->ai_canonname, (u_long)clen);
277 * Check whether the cname is a permitted replacement for the hostname
278 * and perform the replacement if it is.
279 * NB. this function must operate with a options having undefined members.
282 check_follow_cname(char **namep, const char *cname)
285 struct allowed_cname *rule;
287 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
288 strcmp(*namep, cname) == 0)
290 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
293 * Don't attempt to canonicalize names that will be interpreted by
294 * a proxy unless the user specifically requests so.
296 if (!option_clear_or_none(options.proxy_command) &&
297 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
299 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
300 for (i = 0; i < options.num_permitted_cnames; i++) {
301 rule = options.permitted_cnames + i;
302 if (match_pattern_list(*namep, rule->source_list,
303 strlen(rule->source_list), 1) != 1 ||
304 match_pattern_list(cname, rule->target_list,
305 strlen(rule->target_list), 1) != 1)
307 verbose("Canonicalized DNS aliased hostname "
308 "\"%s\" => \"%s\"", *namep, cname);
310 *namep = xstrdup(cname);
317 * Attempt to resolve the supplied hostname after applying the user's
318 * canonicalization rules. Returns the address list for the host or NULL
319 * if no name was found after canonicalization.
320 * NB. this function must operate with a options having undefined members.
322 static struct addrinfo *
323 resolve_canonicalize(char **hostp, int port)
326 char *cp, *fullhost, cname_target[NI_MAXHOST];
327 struct addrinfo *addrs;
329 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
333 * Don't attempt to canonicalize names that will be interpreted by
334 * a proxy unless the user specifically requests so.
336 if (!option_clear_or_none(options.proxy_command) &&
337 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
340 /* Don't apply canonicalization to sufficiently-qualified hostnames */
342 for (cp = *hostp; *cp != '\0'; cp++) {
346 if (ndots > options.canonicalize_max_dots) {
347 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
348 __func__, *hostp, options.canonicalize_max_dots);
351 /* Attempt each supplied suffix */
352 for (i = 0; i < options.num_canonical_domains; i++) {
353 *cname_target = '\0';
354 xasprintf(&fullhost, "%s.%s.", *hostp,
355 options.canonical_domains[i]);
356 debug3("%s: attempting \"%s\" => \"%s\"", __func__,
358 if ((addrs = resolve_host(fullhost, port, 0,
359 cname_target, sizeof(cname_target))) == NULL) {
363 /* Remove trailing '.' */
364 fullhost[strlen(fullhost) - 1] = '\0';
365 /* Follow CNAME if requested */
366 if (!check_follow_cname(&fullhost, cname_target)) {
367 debug("Canonicalized hostname \"%s\" => \"%s\"",
374 if (!options.canonicalize_fallback_local)
375 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
376 debug2("%s: host %s not found in any suffix", __func__, *hostp);
381 * Read per-user configuration file. Ignore the system wide config
382 * file if the user specifies a config file on the command line.
385 process_config_files(struct passwd *pw)
387 char buf[MAXPATHLEN];
390 if (config != NULL) {
391 if (strcasecmp(config, "none") != 0 &&
392 !read_config_file(config, pw, host, &options,
394 fatal("Can't open user config file %.100s: "
395 "%.100s", config, strerror(errno));
397 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
398 _PATH_SSH_USER_CONFFILE);
399 if (r > 0 && (size_t)r < sizeof(buf))
400 (void)read_config_file(buf, pw, host, &options,
401 SSHCONF_CHECKPERM|SSHCONF_USERCONF);
403 /* Read systemwide configuration file after user config. */
404 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host,
410 * Main program for the ssh client.
413 main(int ac, char **av)
415 int i, r, opt, exit_status, use_syslog;
416 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile;
417 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
418 char cname[NI_MAXHOST];
422 extern int optind, optreset;
425 struct addrinfo *addrs = NULL;
427 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
430 __progname = ssh_get_progname(av[0]);
432 #ifndef HAVE_SETPROCTITLE
433 /* Prepare for later setproctitle emulation */
434 /* Save argv so it isn't clobbered by setproctitle() emulation */
435 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
436 for (i = 0; i < ac; i++)
437 saved_av[i] = xstrdup(av[i]);
439 compat_init_setproctitle(ac, av);
444 * Discard other fds that are hanging around. These can cause problem
445 * with backgrounded ssh processes started by ControlPersist.
447 closefrom(STDERR_FILENO + 1);
450 * Save the original real uid. It will be needed later (uid-swapping
451 * may clobber the real uid).
453 original_real_uid = getuid();
454 original_effective_uid = geteuid();
457 * Use uid-swapping to give up root privileges for the duration of
458 * option processing. We will re-instantiate the rights when we are
459 * ready to create the privileged port, and will permanently drop
460 * them when the port has been created (actually, when the connection
461 * has been made, as we may need to create the port several times).
465 #ifdef HAVE_SETRLIMIT
466 /* If we are installed setuid root be careful to not drop core. */
467 if (original_real_uid != original_effective_uid) {
469 rlim.rlim_cur = rlim.rlim_max = 0;
470 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
471 fatal("setrlimit failed: %.100s", strerror(errno));
475 pw = getpwuid(original_real_uid);
477 logit("No user exists for uid %lu", (u_long)original_real_uid);
480 /* Take a copy of the returned structure. */
484 * Set our umask to something reasonable, as some files are created
485 * with the default umask. This will make them world-readable but
486 * writable only by the owner, which is ok for all files for which we
487 * don't set the modes explicitly.
492 * Initialize option structure to indicate that no values have been
495 initialize_options(&options);
497 /* Parse command-line arguments. */
504 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
505 "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
508 options.protocol = SSH_PROTO_1;
511 options.protocol = SSH_PROTO_2;
514 options.address_family = AF_INET;
517 options.address_family = AF_INET6;
523 fork_after_authentication_flag = 1;
527 options.forward_x11 = 0;
530 options.forward_x11 = 1;
536 logfile = xstrdup(optarg);
539 options.forward_x11 = 1;
540 options.forward_x11_trusted = 1;
543 options.gateway_ports = 1;
546 if (stdio_forward_host != NULL)
547 fatal("Cannot specify multiplexing "
549 else if (muxclient_command != 0)
550 fatal("Multiplexing command already specified");
551 if (strcmp(optarg, "check") == 0)
552 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
553 else if (strcmp(optarg, "forward") == 0)
554 muxclient_command = SSHMUX_COMMAND_FORWARD;
555 else if (strcmp(optarg, "exit") == 0)
556 muxclient_command = SSHMUX_COMMAND_TERMINATE;
557 else if (strcmp(optarg, "stop") == 0)
558 muxclient_command = SSHMUX_COMMAND_STOP;
559 else if (strcmp(optarg, "cancel") == 0)
560 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
562 fatal("Invalid multiplex command.");
564 case 'P': /* deprecated */
565 options.use_privileged_port = 0;
569 if (strcmp(optarg, "cipher") == 0)
570 cp = cipher_alg_list('\n', 0);
571 else if (strcmp(optarg, "cipher-auth") == 0)
572 cp = cipher_alg_list('\n', 1);
573 else if (strcmp(optarg, "mac") == 0)
574 cp = mac_alg_list('\n');
575 else if (strcmp(optarg, "kex") == 0)
576 cp = kex_alg_list('\n');
577 else if (strcmp(optarg, "key") == 0)
578 cp = key_alg_list(0, 0);
579 else if (strcmp(optarg, "key-cert") == 0)
580 cp = key_alg_list(1, 0);
581 else if (strcmp(optarg, "key-plain") == 0)
582 cp = key_alg_list(0, 1);
584 fatal("Unsupported query \"%s\"", optarg);
590 options.forward_agent = 0;
593 options.forward_agent = 1;
596 options.gss_deleg_creds = 0;
599 options.gss_authentication = 1;
600 options.gss_deleg_creds = 1;
603 if (stat(optarg, &st) < 0) {
604 fprintf(stderr, "Warning: Identity file %s "
605 "not accessible: %s.\n", optarg,
609 add_identity_file(&options, NULL, optarg, 1);
613 options.pkcs11_provider = xstrdup(optarg);
615 fprintf(stderr, "no support for PKCS#11.\n");
619 if (options.request_tty == REQUEST_TTY_YES)
620 options.request_tty = REQUEST_TTY_FORCE;
622 options.request_tty = REQUEST_TTY_YES;
625 if (debug_flag == 0) {
627 options.log_level = SYSLOG_LEVEL_DEBUG1;
629 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
634 if (options.version_addendum &&
635 *options.version_addendum != '\0')
636 fprintf(stderr, "%s%s %s, %s\n", SSH_RELEASE,
637 options.hpn_disabled ? "" : SSH_VERSION_HPN,
638 options.version_addendum,
639 SSLeay_version(SSLEAY_VERSION));
641 fprintf(stderr, "%s%s, %s\n", SSH_RELEASE,
642 options.hpn_disabled ? "" : SSH_VERSION_HPN,
643 SSLeay_version(SSLEAY_VERSION));
648 if (options.tun_open == -1)
649 options.tun_open = SSH_TUNMODE_DEFAULT;
650 options.tun_local = a2tun(optarg, &options.tun_remote);
651 if (options.tun_local == SSH_TUNID_ERR) {
653 "Bad tun device '%s'\n", optarg);
658 if (stdio_forward_host != NULL)
659 fatal("stdio forward already specified");
660 if (muxclient_command != 0)
661 fatal("Cannot specify stdio forward with -O");
662 if (parse_forward(&fwd, optarg, 1, 0)) {
663 stdio_forward_host = fwd.listen_host;
664 stdio_forward_port = fwd.listen_port;
665 free(fwd.connect_host);
668 "Bad stdio forwarding specification '%s'\n",
672 options.request_tty = REQUEST_TTY_NO;
674 options.clear_forwardings = 1;
675 options.exit_on_forward_failure = 1;
678 options.log_level = SYSLOG_LEVEL_QUIET;
681 if (optarg[0] == '^' && optarg[2] == 0 &&
682 (u_char) optarg[1] >= 64 &&
683 (u_char) optarg[1] < 128)
684 options.escape_char = (u_char) optarg[1] & 31;
685 else if (strlen(optarg) == 1)
686 options.escape_char = (u_char) optarg[0];
687 else if (strcmp(optarg, "none") == 0)
688 options.escape_char = SSH_ESCAPECHAR_NONE;
690 fprintf(stderr, "Bad escape character '%s'.\n",
696 if (ciphers_valid(optarg)) {
698 options.ciphers = xstrdup(optarg);
699 options.cipher = SSH_CIPHER_INVALID;
702 options.cipher = cipher_number(optarg);
703 if (options.cipher == -1) {
705 "Unknown cipher type '%s'\n",
709 if (options.cipher == SSH_CIPHER_3DES)
710 options.ciphers = "3des-cbc";
711 else if (options.cipher == SSH_CIPHER_BLOWFISH)
712 options.ciphers = "blowfish-cbc";
714 options.ciphers = (char *)-1;
718 if (mac_valid(optarg))
719 options.macs = xstrdup(optarg);
721 fprintf(stderr, "Unknown mac type '%s'\n",
727 if (options.control_master == SSHCTL_MASTER_YES)
728 options.control_master = SSHCTL_MASTER_ASK;
730 options.control_master = SSHCTL_MASTER_YES;
733 options.port = a2port(optarg);
734 if (options.port <= 0) {
735 fprintf(stderr, "Bad port '%s'\n", optarg);
740 options.user = optarg;
744 if (parse_forward(&fwd, optarg, 0, 0))
745 add_local_forward(&options, &fwd);
748 "Bad local forwarding specification '%s'\n",
755 if (parse_forward(&fwd, optarg, 0, 1)) {
756 add_remote_forward(&options, &fwd);
759 "Bad remote forwarding specification "
766 if (parse_forward(&fwd, optarg, 1, 0)) {
767 add_local_forward(&options, &fwd);
770 "Bad dynamic forwarding specification "
777 options.compression = 1;
781 options.request_tty = REQUEST_TTY_NO;
784 options.request_tty = REQUEST_TTY_NO;
785 #ifdef NONE_CIPHER_ENABLED
787 * Ensure that the user does not try to backdoor a
788 * NONE cipher switch on an interactive session by
789 * explicitly disabling it if the user asks for a
790 * session without a tty.
792 options.none_switch = 0;
796 line = xstrdup(optarg);
797 if (process_config_line(&options, pw, host ? host : "",
798 line, "command-line", 0, NULL, SSHCONF_USERCONF)
807 if (options.control_path != NULL)
808 free(options.control_path);
809 options.control_path = xstrdup(optarg);
812 options.bind_address = optarg;
825 if (ac > 0 && !host) {
826 if (strrchr(*av, '@')) {
828 cp = strrchr(p, '@');
829 if (cp == NULL || cp == p)
833 host = xstrdup(++cp);
837 optind = optreset = 1;
843 /* Check that we got a host name. */
847 host_arg = xstrdup(host);
849 OpenSSL_add_all_algorithms();
850 ERR_load_crypto_strings();
852 /* Initialize the command to execute on remote host. */
853 buffer_init(&command);
856 * Save the command to execute on the remote host in a buffer. There
857 * is no limit on the length of the command, except by the maximum
858 * packet size. Also sets the tty flag if there is no command.
861 /* No command specified - execute shell on a tty. */
862 if (subsystem_flag) {
864 "You must specify a subsystem to invoke.\n");
868 /* A command has been specified. Store it into the buffer. */
869 for (i = 0; i < ac; i++) {
871 buffer_append(&command, " ", 1);
872 buffer_append(&command, av[i], strlen(av[i]));
876 /* Cannot fork to background if no command. */
877 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
879 fatal("Cannot fork into background without a command "
883 * Initialize "log" output. Since we are the client all output
884 * goes to stderr unless otherwise specified by -y or -E.
886 if (use_syslog && logfile != NULL)
887 fatal("Can't specify both -y and -E");
888 if (logfile != NULL) {
889 log_redirect_stderr_to(logfile);
893 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
894 SYSLOG_FACILITY_USER, !use_syslog);
897 logit("%s, %s", SSH_RELEASE, SSLeay_version(SSLEAY_VERSION));
899 /* Parse the configuration files */
900 process_config_files(pw);
902 /* Hostname canonicalisation needs a few options filled. */
903 fill_default_options_for_canonicalization(&options);
905 /* If the user has replaced the hostname then take it into use now */
906 if (options.hostname != NULL) {
907 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
908 cp = percent_expand(options.hostname,
909 "h", host, (char *)NULL);
914 /* If canonicalization requested then try to apply it */
916 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
917 addrs = resolve_canonicalize(&host, options.port);
920 * If CanonicalizePermittedCNAMEs have been specified but
921 * other canonicalization did not happen (by not being requested
922 * or by failing with fallback) then the hostname may still be changed
923 * as a result of CNAME following.
925 * Try to resolve the bare hostname name using the system resolver's
926 * usual search rules and then apply the CNAME follow rules.
928 * Skip the lookup if a ProxyCommand is being used unless the user
929 * has specifically requested canonicalisation for this case via
930 * CanonicalizeHostname=always
932 if (addrs == NULL && options.num_permitted_cnames != 0 &&
933 (option_clear_or_none(options.proxy_command) ||
934 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
935 if ((addrs = resolve_host(host, options.port, 1,
936 cname, sizeof(cname))) == NULL)
937 cleanup_exit(255); /* resolve_host logs the error */
938 check_follow_cname(&host, cname);
942 * If the target hostname has changed as a result of canonicalisation
943 * then re-parse the configuration files as new stanzas may match.
945 if (strcasecmp(host_arg, host) != 0) {
946 debug("Hostname has changed; re-reading configuration");
947 process_config_files(pw);
950 /* Fill configuration defaults. */
951 fill_default_options(&options);
953 if (options.port == 0)
954 options.port = default_ssh_port();
955 channel_set_af(options.address_family);
957 /* Tidy and check options */
958 if (options.host_key_alias != NULL)
959 lowercase(options.host_key_alias);
960 if (options.proxy_command != NULL &&
961 strcmp(options.proxy_command, "-") == 0 &&
962 options.proxy_use_fdpass)
963 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
965 if (original_effective_uid != 0)
966 options.use_privileged_port = 0;
970 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
972 if (options.request_tty == REQUEST_TTY_YES ||
973 options.request_tty == REQUEST_TTY_FORCE)
976 /* Allocate a tty by default if no command specified. */
977 if (buffer_len(&command) == 0)
978 tty_flag = options.request_tty != REQUEST_TTY_NO;
981 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
983 /* Do not allocate a tty if stdin is not a tty. */
984 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
985 options.request_tty != REQUEST_TTY_FORCE) {
987 logit("Pseudo-terminal will not be allocated because "
988 "stdin is not a terminal.");
994 if (options.user == NULL)
995 options.user = xstrdup(pw->pw_name);
997 if (gethostname(thishost, sizeof(thishost)) == -1)
998 fatal("gethostname: %s", strerror(errno));
999 strlcpy(shorthost, thishost, sizeof(shorthost));
1000 shorthost[strcspn(thishost, ".")] = '\0';
1001 snprintf(portstr, sizeof(portstr), "%d", options.port);
1003 /* Find canonic host name. */
1004 if (strchr(host, '.') == 0) {
1005 struct addrinfo hints;
1006 struct addrinfo *ai = NULL;
1008 memset(&hints, 0, sizeof(hints));
1009 hints.ai_family = options.address_family;
1010 hints.ai_flags = AI_CANONNAME;
1011 hints.ai_socktype = SOCK_STREAM;
1012 errgai = getaddrinfo(host, NULL, &hints, &ai);
1014 if (ai->ai_canonname != NULL)
1015 host = xstrdup(ai->ai_canonname);
1020 if (options.local_command != NULL) {
1021 debug3("expanding LocalCommand: %s", options.local_command);
1022 cp = options.local_command;
1023 options.local_command = percent_expand(cp, "d", pw->pw_dir,
1024 "h", host, "l", thishost, "n", host_arg, "r", options.user,
1025 "p", portstr, "u", pw->pw_name, "L", shorthost,
1027 debug3("expanded LocalCommand: %s", options.local_command);
1031 if (options.control_path != NULL) {
1032 cp = tilde_expand_filename(options.control_path,
1034 free(options.control_path);
1035 options.control_path = percent_expand(cp, "h", host,
1036 "l", thishost, "n", host_arg, "r", options.user,
1037 "p", portstr, "u", pw->pw_name, "L", shorthost,
1041 if (muxclient_command != 0 && options.control_path == NULL)
1042 fatal("No ControlPath specified for \"-O\" command");
1043 if (options.control_path != NULL)
1044 muxclient(options.control_path);
1047 * If hostname canonicalisation was not enabled, then we may not
1048 * have yet resolved the hostname. Do so now.
1050 if (addrs == NULL && options.proxy_command == NULL) {
1051 if ((addrs = resolve_host(host, options.port, 1,
1052 cname, sizeof(cname))) == NULL)
1053 cleanup_exit(255); /* resolve_host logs the error */
1056 timeout_ms = options.connection_timeout * 1000;
1058 /* Open a connection to the remote host. */
1059 if (ssh_connect(host, addrs, &hostaddr, options.port,
1060 options.address_family, options.connection_attempts,
1061 &timeout_ms, options.tcp_keep_alive,
1062 options.use_privileged_port) != 0)
1066 freeaddrinfo(addrs);
1068 packet_set_timeout(options.server_alive_interval,
1069 options.server_alive_count_max);
1072 debug3("timeout: %d ms remain after connect", timeout_ms);
1075 * If we successfully made the connection, load the host private key
1076 * in case we will need it later for combined rsa-rhosts
1077 * authentication. This must be done before releasing extra
1078 * privileges, because the file is only readable by root.
1079 * If we cannot access the private keys, load the public keys
1080 * instead and try to execute the ssh-keysign helper instead.
1082 sensitive_data.nkeys = 0;
1083 sensitive_data.keys = NULL;
1084 sensitive_data.external_keysign = 0;
1085 if (options.rhosts_rsa_authentication ||
1086 options.hostbased_authentication) {
1087 sensitive_data.nkeys = 9;
1088 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1090 for (i = 0; i < sensitive_data.nkeys; i++)
1091 sensitive_data.keys[i] = NULL;
1094 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1095 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1096 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
1097 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1098 #ifdef OPENSSL_HAS_ECC
1099 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
1100 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1102 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1103 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1104 sensitive_data.keys[4] = key_load_private_cert(KEY_ED25519,
1105 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1106 sensitive_data.keys[5] = key_load_private_type(KEY_DSA,
1107 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1108 #ifdef OPENSSL_HAS_ECC
1109 sensitive_data.keys[6] = key_load_private_type(KEY_ECDSA,
1110 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1112 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1113 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1114 sensitive_data.keys[8] = key_load_private_type(KEY_ED25519,
1115 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1118 if (options.hostbased_authentication == 1 &&
1119 sensitive_data.keys[0] == NULL &&
1120 sensitive_data.keys[5] == NULL &&
1121 sensitive_data.keys[6] == NULL &&
1122 sensitive_data.keys[7] == NULL &&
1123 sensitive_data.keys[8] == NULL) {
1124 sensitive_data.keys[1] = key_load_cert(
1125 _PATH_HOST_DSA_KEY_FILE);
1126 #ifdef OPENSSL_HAS_ECC
1127 sensitive_data.keys[2] = key_load_cert(
1128 _PATH_HOST_ECDSA_KEY_FILE);
1130 sensitive_data.keys[3] = key_load_cert(
1131 _PATH_HOST_RSA_KEY_FILE);
1132 sensitive_data.keys[4] = key_load_cert(
1133 _PATH_HOST_ED25519_KEY_FILE);
1134 sensitive_data.keys[5] = key_load_public(
1135 _PATH_HOST_DSA_KEY_FILE, NULL);
1136 #ifdef OPENSSL_HAS_ECC
1137 sensitive_data.keys[6] = key_load_public(
1138 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1140 sensitive_data.keys[7] = key_load_public(
1141 _PATH_HOST_RSA_KEY_FILE, NULL);
1142 sensitive_data.keys[8] = key_load_public(
1143 _PATH_HOST_ED25519_KEY_FILE, NULL);
1144 sensitive_data.external_keysign = 1;
1148 * Get rid of any extra privileges that we may have. We will no
1149 * longer need them. Also, extra privileges could make it very hard
1150 * to read identity files and other non-world-readable files from the
1151 * user's home directory if it happens to be on a NFS volume where
1152 * root is mapped to nobody.
1154 if (original_effective_uid == 0) {
1156 permanently_set_uid(pw);
1160 * Now that we are back to our own permissions, create ~/.ssh
1161 * directory if it doesn't already exist.
1163 if (config == NULL) {
1164 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1165 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1166 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1168 ssh_selinux_setfscreatecon(buf);
1170 if (mkdir(buf, 0700) < 0)
1171 error("Could not create directory '%.200s'.",
1174 ssh_selinux_setfscreatecon(NULL);
1178 /* load options.identity_files */
1179 load_public_identity_files();
1181 /* Expand ~ in known host file names. */
1182 tilde_expand_paths(options.system_hostfiles,
1183 options.num_system_hostfiles);
1184 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1186 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1187 signal(SIGCHLD, main_sigchld_handler);
1189 /* Log into the remote system. Never returns if the login fails. */
1190 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1191 options.port, pw, timeout_ms);
1193 if (packet_connection_is_on_socket()) {
1194 verbose("Authenticated to %s ([%s]:%d).", host,
1195 get_remote_ipaddr(), get_remote_port());
1197 verbose("Authenticated to %s (via proxy).", host);
1200 /* We no longer need the private host keys. Clear them now. */
1201 if (sensitive_data.nkeys != 0) {
1202 for (i = 0; i < sensitive_data.nkeys; i++) {
1203 if (sensitive_data.keys[i] != NULL) {
1204 /* Destroys contents safely */
1205 debug3("clear hostkey %d", i);
1206 key_free(sensitive_data.keys[i]);
1207 sensitive_data.keys[i] = NULL;
1210 free(sensitive_data.keys);
1212 for (i = 0; i < options.num_identity_files; i++) {
1213 free(options.identity_files[i]);
1214 options.identity_files[i] = NULL;
1215 if (options.identity_keys[i]) {
1216 key_free(options.identity_keys[i]);
1217 options.identity_keys[i] = NULL;
1221 exit_status = compat20 ? ssh_session2() : ssh_session();
1224 if (options.control_path != NULL && muxserver_sock != -1)
1225 unlink(options.control_path);
1227 /* Kill ProxyCommand if it is running. */
1228 ssh_kill_proxy_command();
1234 control_persist_detach(void)
1239 debug("%s: backgrounding master process", __func__);
1242 * master (current process) into the background, and make the
1243 * foreground process a client of the backgrounded master.
1245 switch ((pid = fork())) {
1247 fatal("%s: fork: %s", __func__, strerror(errno));
1249 /* Child: master process continues mainloop */
1252 /* Parent: set up mux slave to connect to backgrounded master */
1253 debug2("%s: background process is %ld", __func__, (long)pid);
1254 stdin_null_flag = ostdin_null_flag;
1255 options.request_tty = orequest_tty;
1256 tty_flag = otty_flag;
1257 close(muxserver_sock);
1258 muxserver_sock = -1;
1259 options.control_master = SSHCTL_MASTER_NO;
1260 muxclient(options.control_path);
1261 /* muxclient() doesn't return on success. */
1262 fatal("Failed to connect to new control master");
1264 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1265 error("%s: open(\"/dev/null\"): %s", __func__,
1268 if (dup2(devnull, STDIN_FILENO) == -1 ||
1269 dup2(devnull, STDOUT_FILENO) == -1)
1270 error("%s: dup2: %s", __func__, strerror(errno));
1271 if (devnull > STDERR_FILENO)
1275 setproctitle("%s [mux]", options.control_path);
1278 /* Do fork() after authentication. Used by "ssh -f" */
1282 if (need_controlpersist_detach)
1283 control_persist_detach();
1284 debug("forking to background");
1285 fork_after_authentication_flag = 0;
1286 if (daemon(1, 1) < 0)
1287 fatal("daemon() failed: %.200s", strerror(errno));
1290 /* Callback for remote forward global requests */
1292 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1294 Forward *rfwd = (Forward *)ctxt;
1296 /* XXX verbose() on failure? */
1297 debug("remote forward %s for: listen %d, connect %s:%d",
1298 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1299 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1300 if (rfwd->listen_port == 0) {
1301 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1302 rfwd->allocated_port = packet_get_int();
1303 logit("Allocated port %u for remote forward to %s:%d",
1304 rfwd->allocated_port,
1305 rfwd->connect_host, rfwd->connect_port);
1306 channel_update_permitted_opens(rfwd->handle,
1307 rfwd->allocated_port);
1309 channel_update_permitted_opens(rfwd->handle, -1);
1313 if (type == SSH2_MSG_REQUEST_FAILURE) {
1314 if (options.exit_on_forward_failure)
1315 fatal("Error: remote port forwarding failed for "
1316 "listen port %d", rfwd->listen_port);
1318 logit("Warning: remote port forwarding failed for "
1319 "listen port %d", rfwd->listen_port);
1321 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1322 debug("All remote forwarding requests processed");
1323 if (fork_after_authentication_flag)
1329 client_cleanup_stdio_fwd(int id, void *arg)
1331 debug("stdio forwarding: done");
1336 ssh_init_stdio_forwarding(void)
1341 if (stdio_forward_host == NULL)
1344 fatal("stdio forwarding require Protocol 2");
1346 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1348 if ((in = dup(STDIN_FILENO)) < 0 ||
1349 (out = dup(STDOUT_FILENO)) < 0)
1350 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1351 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1352 stdio_forward_port, in, out)) == NULL)
1353 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1354 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1358 ssh_init_forwarding(void)
1363 /* Initiate local TCP/IP port forwardings. */
1364 for (i = 0; i < options.num_local_forwards; i++) {
1365 debug("Local connections to %.200s:%d forwarded to remote "
1366 "address %.200s:%d",
1367 (options.local_forwards[i].listen_host == NULL) ?
1368 (options.gateway_ports ? "*" : "LOCALHOST") :
1369 options.local_forwards[i].listen_host,
1370 options.local_forwards[i].listen_port,
1371 options.local_forwards[i].connect_host,
1372 options.local_forwards[i].connect_port);
1373 success += channel_setup_local_fwd_listener(
1374 options.local_forwards[i].listen_host,
1375 options.local_forwards[i].listen_port,
1376 options.local_forwards[i].connect_host,
1377 options.local_forwards[i].connect_port,
1378 options.gateway_ports);
1380 if (i > 0 && success != i && options.exit_on_forward_failure)
1381 fatal("Could not request local forwarding.");
1382 if (i > 0 && success == 0)
1383 error("Could not request local forwarding.");
1385 /* Initiate remote TCP/IP port forwardings. */
1386 for (i = 0; i < options.num_remote_forwards; i++) {
1387 debug("Remote connections from %.200s:%d forwarded to "
1388 "local address %.200s:%d",
1389 (options.remote_forwards[i].listen_host == NULL) ?
1390 "LOCALHOST" : options.remote_forwards[i].listen_host,
1391 options.remote_forwards[i].listen_port,
1392 options.remote_forwards[i].connect_host,
1393 options.remote_forwards[i].connect_port);
1394 options.remote_forwards[i].handle =
1395 channel_request_remote_forwarding(
1396 options.remote_forwards[i].listen_host,
1397 options.remote_forwards[i].listen_port,
1398 options.remote_forwards[i].connect_host,
1399 options.remote_forwards[i].connect_port);
1400 if (options.remote_forwards[i].handle < 0) {
1401 if (options.exit_on_forward_failure)
1402 fatal("Could not request remote forwarding.");
1404 logit("Warning: Could not request remote "
1407 client_register_global_confirm(ssh_confirm_remote_forward,
1408 &options.remote_forwards[i]);
1412 /* Initiate tunnel forwarding. */
1413 if (options.tun_open != SSH_TUNMODE_NO) {
1414 if (client_request_tun_fwd(options.tun_open,
1415 options.tun_local, options.tun_remote) == -1) {
1416 if (options.exit_on_forward_failure)
1417 fatal("Could not request tunnel forwarding.");
1419 error("Could not request tunnel forwarding.");
1425 check_agent_present(void)
1427 if (options.forward_agent) {
1428 /* Clear agent forwarding if we don't have an agent. */
1429 if (!ssh_agent_present())
1430 options.forward_agent = 0;
1438 int interactive = 0;
1442 const char *display;
1444 /* Enable compression if requested. */
1445 if (options.compression) {
1446 debug("Requesting compression at level %d.",
1447 options.compression_level);
1449 if (options.compression_level < 1 ||
1450 options.compression_level > 9)
1451 fatal("Compression level must be from 1 (fast) to "
1454 /* Send the request. */
1455 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1456 packet_put_int(options.compression_level);
1458 packet_write_wait();
1459 type = packet_read();
1460 if (type == SSH_SMSG_SUCCESS)
1461 packet_start_compression(options.compression_level);
1462 else if (type == SSH_SMSG_FAILURE)
1463 logit("Warning: Remote host refused compression.");
1465 packet_disconnect("Protocol error waiting for "
1466 "compression response.");
1468 /* Allocate a pseudo tty if appropriate. */
1470 debug("Requesting pty.");
1472 /* Start the packet. */
1473 packet_start(SSH_CMSG_REQUEST_PTY);
1475 /* Store TERM in the packet. There is no limit on the
1476 length of the string. */
1477 cp = getenv("TERM");
1480 packet_put_cstring(cp);
1482 /* Store window size in the packet. */
1483 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1484 memset(&ws, 0, sizeof(ws));
1485 packet_put_int((u_int)ws.ws_row);
1486 packet_put_int((u_int)ws.ws_col);
1487 packet_put_int((u_int)ws.ws_xpixel);
1488 packet_put_int((u_int)ws.ws_ypixel);
1490 /* Store tty modes in the packet. */
1491 tty_make_modes(fileno(stdin), NULL);
1493 /* Send the packet, and wait for it to leave. */
1495 packet_write_wait();
1497 /* Read response from the server. */
1498 type = packet_read();
1499 if (type == SSH_SMSG_SUCCESS) {
1502 } else if (type == SSH_SMSG_FAILURE)
1503 logit("Warning: Remote host failed or refused to "
1504 "allocate a pseudo tty.");
1506 packet_disconnect("Protocol error waiting for pty "
1507 "request response.");
1509 /* Request X11 forwarding if enabled and DISPLAY is set. */
1510 display = getenv("DISPLAY");
1511 if (options.forward_x11 && display != NULL) {
1513 /* Get reasonable local authentication information. */
1514 client_x11_get_proto(display, options.xauth_location,
1515 options.forward_x11_trusted,
1516 options.forward_x11_timeout,
1518 /* Request forwarding with authentication spoofing. */
1519 debug("Requesting X11 forwarding with authentication "
1521 x11_request_forwarding_with_spoofing(0, display, proto,
1523 /* Read response from the server. */
1524 type = packet_read();
1525 if (type == SSH_SMSG_SUCCESS) {
1527 } else if (type == SSH_SMSG_FAILURE) {
1528 logit("Warning: Remote host denied X11 forwarding.");
1530 packet_disconnect("Protocol error waiting for X11 "
1534 /* Tell the packet module whether this is an interactive session. */
1535 packet_set_interactive(interactive,
1536 options.ip_qos_interactive, options.ip_qos_bulk);
1538 /* Request authentication agent forwarding if appropriate. */
1539 check_agent_present();
1541 if (options.forward_agent) {
1542 debug("Requesting authentication agent forwarding.");
1543 auth_request_forwarding();
1545 /* Read response from the server. */
1546 type = packet_read();
1548 if (type != SSH_SMSG_SUCCESS)
1549 logit("Warning: Remote host denied authentication agent forwarding.");
1552 /* Initiate port forwardings. */
1553 ssh_init_stdio_forwarding();
1554 ssh_init_forwarding();
1556 /* Execute a local command */
1557 if (options.local_command != NULL &&
1558 options.permit_local_command)
1559 ssh_local_cmd(options.local_command);
1562 * If requested and we are not interested in replies to remote
1563 * forwarding requests, then let ssh continue in the background.
1565 if (fork_after_authentication_flag) {
1566 if (options.exit_on_forward_failure &&
1567 options.num_remote_forwards > 0) {
1568 debug("deferring postauth fork until remote forward "
1569 "confirmation received");
1575 * If a command was specified on the command line, execute the
1576 * command now. Otherwise request the server to start a shell.
1578 if (buffer_len(&command) > 0) {
1579 int len = buffer_len(&command);
1582 debug("Sending command: %.*s", len,
1583 (u_char *)buffer_ptr(&command));
1584 packet_start(SSH_CMSG_EXEC_CMD);
1585 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1587 packet_write_wait();
1589 debug("Requesting shell.");
1590 packet_start(SSH_CMSG_EXEC_SHELL);
1592 packet_write_wait();
1595 /* Enter the interactive session. */
1596 return client_loop(have_tty, tty_flag ?
1597 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1600 /* request pty/x11/agent/tcpfwd/shell for channel */
1602 ssh_session2_setup(int id, int success, void *arg)
1604 extern char **environ;
1605 const char *display;
1606 int interactive = tty_flag;
1609 return; /* No need for error message, channels code sens one */
1611 display = getenv("DISPLAY");
1612 if (options.forward_x11 && display != NULL) {
1614 /* Get reasonable local authentication information. */
1615 client_x11_get_proto(display, options.xauth_location,
1616 options.forward_x11_trusted,
1617 options.forward_x11_timeout, &proto, &data);
1618 /* Request forwarding with authentication spoofing. */
1619 debug("Requesting X11 forwarding with authentication "
1621 x11_request_forwarding_with_spoofing(id, display, proto,
1623 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1624 /* XXX exit_on_forward_failure */
1628 check_agent_present();
1629 if (options.forward_agent) {
1630 debug("Requesting authentication agent forwarding.");
1631 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1635 /* Tell the packet module whether this is an interactive session. */
1636 packet_set_interactive(interactive,
1637 options.ip_qos_interactive, options.ip_qos_bulk);
1639 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1640 NULL, fileno(stdin), &command, environ);
1643 /* open new channel for a session */
1645 ssh_session2_open(void)
1648 int window, packetmax, in, out, err;
1650 if (stdin_null_flag) {
1651 in = open(_PATH_DEVNULL, O_RDONLY);
1653 in = dup(STDIN_FILENO);
1655 out = dup(STDOUT_FILENO);
1656 err = dup(STDERR_FILENO);
1658 if (in < 0 || out < 0 || err < 0)
1659 fatal("dup() in/out/err failed");
1661 /* enable nonblocking unless tty */
1670 * We need to check to see what to do about buffer sizes here.
1671 * - In an HPN to non-HPN connection we want to limit the window size to
1672 * something reasonable in case the far side has the large window bug.
1673 * - In an HPN to HPN connection we want to use the max window size but
1674 * allow the user to override it.
1675 * - Lastly if HPN is disabled then use the ssh standard window size.
1677 * We cannot just do a getsockopt() here and set the ssh window to that
1678 * as in case of autotuning of socket buffers the window would get stuck
1679 * at the initial buffer size, generally less than 96k. Therefore we
1680 * need to set the maximum ssh window size to the maximum HPN buffer
1681 * size unless the user has set TcpRcvBufPoll to no. In that case we
1682 * can just set the window to the minimum of HPN buffer size and TCP
1683 * receive buffer size.
1686 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1688 options.hpn_buffer_size = CHAN_HPN_MIN_WINDOW_DEFAULT;
1690 if (datafellows & SSH_BUG_LARGEWINDOW) {
1691 debug("HPN to Non-HPN Connection");
1692 } else if (options.tcp_rcv_buf_poll <= 0) {
1693 sock_get_rcvbuf(&options.hpn_buffer_size, 0);
1694 debug("HPNBufferSize set to TCP RWIN: %d",
1695 options.hpn_buffer_size);
1696 } else if (options.tcp_rcv_buf > 0) {
1697 sock_get_rcvbuf(&options.hpn_buffer_size,
1698 options.tcp_rcv_buf);
1699 debug("HPNBufferSize set to user TCPRcvBuf: %d",
1700 options.hpn_buffer_size);
1702 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1703 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1704 window = options.hpn_buffer_size;
1706 packetmax = CHAN_SES_PACKET_DEFAULT;
1708 window = CHAN_SES_WINDOW_DEFAULT;
1713 "session", SSH_CHANNEL_OPENING, in, out, err,
1714 window, packetmax, CHAN_EXTENDED_WRITE,
1715 "client-session", /*nonblock*/0);
1716 if (!options.hpn_disabled && options.tcp_rcv_buf_poll > 0) {
1717 c->dynamic_window = 1;
1718 debug("Enabled Dynamic Window Scaling\n");
1721 debug3("ssh_session2_open: channel_new: %d", c->self);
1723 channel_send_open(c->self);
1725 channel_register_open_confirm(c->self,
1726 ssh_session2_setup, NULL);
1736 /* XXX should be pre-session */
1737 if (!options.control_persist)
1738 ssh_init_stdio_forwarding();
1739 ssh_init_forwarding();
1741 /* Start listening for multiplex clients */
1745 * If we are in control persist mode and have a working mux listen
1746 * socket, then prepare to background ourselves and have a foreground
1747 * client attach as a control slave.
1748 * NB. we must save copies of the flags that we override for
1749 * the backgrounding, since we defer attachment of the slave until
1750 * after the connection is fully established (in particular,
1751 * async rfwd replies have been received for ExitOnForwardFailure).
1753 if (options.control_persist && muxserver_sock != -1) {
1754 ostdin_null_flag = stdin_null_flag;
1755 ono_shell_flag = no_shell_flag;
1756 orequest_tty = options.request_tty;
1757 otty_flag = tty_flag;
1758 stdin_null_flag = 1;
1761 if (!fork_after_authentication_flag)
1762 need_controlpersist_detach = 1;
1763 fork_after_authentication_flag = 1;
1766 * ControlPersist mux listen socket setup failed, attempt the
1767 * stdio forward setup that we skipped earlier.
1769 if (options.control_persist && muxserver_sock == -1)
1770 ssh_init_stdio_forwarding();
1772 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1773 id = ssh_session2_open();
1775 packet_set_interactive(
1776 options.control_master == SSHCTL_MASTER_NO,
1777 options.ip_qos_interactive, options.ip_qos_bulk);
1780 /* If we don't expect to open a new session, then disallow it */
1781 if (options.control_master == SSHCTL_MASTER_NO &&
1782 (datafellows & SSH_NEW_OPENSSH)) {
1783 debug("Requesting no-more-sessions@openssh.com");
1784 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1785 packet_put_cstring("no-more-sessions@openssh.com");
1790 /* Execute a local command */
1791 if (options.local_command != NULL &&
1792 options.permit_local_command)
1793 ssh_local_cmd(options.local_command);
1796 * If requested and we are not interested in replies to remote
1797 * forwarding requests, then let ssh continue in the background.
1799 if (fork_after_authentication_flag) {
1800 if (options.exit_on_forward_failure &&
1801 options.num_remote_forwards > 0) {
1802 debug("deferring postauth fork until remote forward "
1803 "confirmation received");
1808 if (options.use_roaming)
1811 return client_loop(tty_flag, tty_flag ?
1812 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1816 load_public_identity_files(void)
1818 char *filename, *cp, thishost[NI_MAXHOST];
1819 char *pwdir = NULL, *pwname = NULL;
1824 char *identity_files[SSH_MAX_IDENTITY_FILES];
1825 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1826 #ifdef ENABLE_PKCS11
1832 memset(identity_files, 0, sizeof(identity_files));
1833 memset(identity_keys, 0, sizeof(identity_keys));
1835 #ifdef ENABLE_PKCS11
1836 if (options.pkcs11_provider != NULL &&
1837 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1838 (pkcs11_init(!options.batch_mode) == 0) &&
1839 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1841 for (i = 0; i < nkeys; i++) {
1842 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1846 identity_keys[n_ids] = keys[i];
1847 identity_files[n_ids] =
1848 xstrdup(options.pkcs11_provider); /* XXX */
1853 #endif /* ENABLE_PKCS11 */
1854 if ((pw = getpwuid(original_real_uid)) == NULL)
1855 fatal("load_public_identity_files: getpwuid failed");
1856 pwname = xstrdup(pw->pw_name);
1857 pwdir = xstrdup(pw->pw_dir);
1858 if (gethostname(thishost, sizeof(thishost)) == -1)
1859 fatal("load_public_identity_files: gethostname: %s",
1861 for (i = 0; i < options.num_identity_files; i++) {
1862 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
1863 strcasecmp(options.identity_files[i], "none") == 0) {
1864 free(options.identity_files[i]);
1867 cp = tilde_expand_filename(options.identity_files[i],
1869 filename = percent_expand(cp, "d", pwdir,
1870 "u", pwname, "l", thishost, "h", host,
1871 "r", options.user, (char *)NULL);
1873 public = key_load_public(filename, NULL);
1874 debug("identity file %s type %d", filename,
1875 public ? public->type : -1);
1876 free(options.identity_files[i]);
1877 identity_files[n_ids] = filename;
1878 identity_keys[n_ids] = public;
1880 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1883 /* Try to add the certificate variant too */
1884 xasprintf(&cp, "%s-cert", filename);
1885 public = key_load_public(cp, NULL);
1886 debug("identity file %s type %d", cp,
1887 public ? public->type : -1);
1888 if (public == NULL) {
1892 if (!key_is_cert(public)) {
1893 debug("%s: key %s type %s is not a certificate",
1894 __func__, cp, key_type(public));
1899 identity_keys[n_ids] = public;
1900 /* point to the original path, most likely the private key */
1901 identity_files[n_ids] = xstrdup(filename);
1904 options.num_identity_files = n_ids;
1905 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1906 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1908 explicit_bzero(pwname, strlen(pwname));
1910 explicit_bzero(pwdir, strlen(pwdir));
1915 main_sigchld_handler(int sig)
1917 int save_errno = errno;
1921 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1922 (pid < 0 && errno == EINTR))
1925 signal(sig, main_sigchld_handler);