1 /* $OpenBSD: ssh.c,v 1.407 2014/07/17 07:22:19 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.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/param.h>
52 #include <sys/socket.h>
71 #include <netinet/in.h>
72 #include <arpa/inet.h>
75 #include <openssl/evp.h>
76 #include <openssl/err.h>
78 #include "openbsd-compat/openssl-compat.h"
79 #include "openbsd-compat/sys-queue.h"
95 #include "pathnames.h"
97 #include "clientloop.h"
100 #include "readconf.h"
101 #include "sshconnect.h"
112 #include "ssh-pkcs11.h"
115 extern char *__progname;
117 /* Saves a copy of argv for setproctitle emulation */
118 #ifndef HAVE_SETPROCTITLE
119 static char **saved_av;
122 /* Flag indicating whether debug mode is on. May be set on the command line. */
125 /* Flag indicating whether a tty should be requested */
128 /* don't exec a shell */
129 int no_shell_flag = 0;
132 * Flag indicating that nothing should be read from stdin. This can be set
133 * on the command line.
135 int stdin_null_flag = 0;
138 * Flag indicating that the current process should be backgrounded and
139 * a new slave launched in the foreground for ControlPersist.
141 int need_controlpersist_detach = 0;
143 /* Copies of flags for ControlPersist foreground slave */
144 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
147 * Flag indicating that ssh should fork after authentication. This is useful
148 * so that the passphrase can be entered manually, and then ssh goes to the
151 int fork_after_authentication_flag = 0;
153 /* forward stdio to remote host and port */
154 char *stdio_forward_host = NULL;
155 int stdio_forward_port = 0;
158 * General data structure for command line options and options configurable
159 * in configuration files. See readconf.h.
163 /* optional user configfile */
167 * Name of the host we are connecting to. This is the name given on the
168 * command line, or the HostName specified for the user-supplied name in a
169 * configuration file.
173 /* socket address the host resolves to */
174 struct sockaddr_storage hostaddr;
176 /* Private host keys. */
177 Sensitive sensitive_data;
179 /* Original real UID. */
180 uid_t original_real_uid;
181 uid_t original_effective_uid;
183 /* command to be executed */
186 /* Should we execute a command or invoke a subsystem? */
187 int subsystem_flag = 0;
189 /* # of replies received for global requests */
190 static int remote_forward_confirms_received = 0;
193 extern int muxserver_sock;
194 extern u_int muxclient_command;
196 /* Prints a help message to the user. This function never returns. */
202 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
203 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
204 " [-F configfile] [-I pkcs11] [-i identity_file]\n"
205 " [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]\n"
206 " [-O ctl_cmd] [-o option] [-p port]\n"
207 " [-Q cipher | cipher-auth | mac | kex | key]\n"
208 " [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]\n"
209 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
214 static int ssh_session(void);
215 static int ssh_session2(void);
216 static void load_public_identity_files(void);
217 static void main_sigchld_handler(int);
219 /* from muxclient.c */
220 void muxclient(const char *);
221 void muxserver_listen(void);
223 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
225 tilde_expand_paths(char **paths, u_int num_paths)
230 for (i = 0; i < num_paths; i++) {
231 cp = tilde_expand_filename(paths[i], original_real_uid);
238 * Attempt to resolve a host name / port to a set of addresses and
239 * optionally return any CNAMEs encountered along the way.
240 * Returns NULL on failure.
241 * NB. this function must operate with a options having undefined members.
243 static struct addrinfo *
244 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
246 char strport[NI_MAXSERV];
247 struct addrinfo hints, *res;
248 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
251 port = default_ssh_port();
253 snprintf(strport, sizeof strport, "%u", port);
254 memset(&hints, 0, sizeof(hints));
255 hints.ai_family = options.address_family == -1 ?
256 AF_UNSPEC : options.address_family;
257 hints.ai_socktype = SOCK_STREAM;
259 hints.ai_flags = AI_CANONNAME;
260 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
261 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
262 loglevel = SYSLOG_LEVEL_ERROR;
263 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
264 __progname, name, ssh_gai_strerror(gaierr));
267 if (cname != NULL && res->ai_canonname != NULL) {
268 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
269 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
270 __func__, name, res->ai_canonname, (u_long)clen);
279 * Check whether the cname is a permitted replacement for the hostname
280 * and perform the replacement if it is.
281 * NB. this function must operate with a options having undefined members.
284 check_follow_cname(char **namep, const char *cname)
287 struct allowed_cname *rule;
289 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
290 strcmp(*namep, cname) == 0)
292 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
295 * Don't attempt to canonicalize names that will be interpreted by
296 * a proxy unless the user specifically requests so.
298 if (!option_clear_or_none(options.proxy_command) &&
299 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
301 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
302 for (i = 0; i < options.num_permitted_cnames; i++) {
303 rule = options.permitted_cnames + i;
304 if (match_pattern_list(*namep, rule->source_list,
305 strlen(rule->source_list), 1) != 1 ||
306 match_pattern_list(cname, rule->target_list,
307 strlen(rule->target_list), 1) != 1)
309 verbose("Canonicalized DNS aliased hostname "
310 "\"%s\" => \"%s\"", *namep, cname);
312 *namep = xstrdup(cname);
319 * Attempt to resolve the supplied hostname after applying the user's
320 * canonicalization rules. Returns the address list for the host or NULL
321 * if no name was found after canonicalization.
322 * NB. this function must operate with a options having undefined members.
324 static struct addrinfo *
325 resolve_canonicalize(char **hostp, int port)
328 char *cp, *fullhost, cname_target[NI_MAXHOST];
329 struct addrinfo *addrs;
331 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
335 * Don't attempt to canonicalize names that will be interpreted by
336 * a proxy unless the user specifically requests so.
338 if (!option_clear_or_none(options.proxy_command) &&
339 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
342 /* Don't apply canonicalization to sufficiently-qualified hostnames */
344 for (cp = *hostp; *cp != '\0'; cp++) {
348 if (ndots > options.canonicalize_max_dots) {
349 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
350 __func__, *hostp, options.canonicalize_max_dots);
353 /* Attempt each supplied suffix */
354 for (i = 0; i < options.num_canonical_domains; i++) {
355 *cname_target = '\0';
356 xasprintf(&fullhost, "%s.%s.", *hostp,
357 options.canonical_domains[i]);
358 debug3("%s: attempting \"%s\" => \"%s\"", __func__,
360 if ((addrs = resolve_host(fullhost, port, 0,
361 cname_target, sizeof(cname_target))) == NULL) {
365 /* Remove trailing '.' */
366 fullhost[strlen(fullhost) - 1] = '\0';
367 /* Follow CNAME if requested */
368 if (!check_follow_cname(&fullhost, cname_target)) {
369 debug("Canonicalized hostname \"%s\" => \"%s\"",
376 if (!options.canonicalize_fallback_local)
377 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
378 debug2("%s: host %s not found in any suffix", __func__, *hostp);
383 * Read per-user configuration file. Ignore the system wide config
384 * file if the user specifies a config file on the command line.
387 process_config_files(struct passwd *pw)
389 char buf[MAXPATHLEN];
392 if (config != NULL) {
393 if (strcasecmp(config, "none") != 0 &&
394 !read_config_file(config, pw, host, &options,
396 fatal("Can't open user config file %.100s: "
397 "%.100s", config, strerror(errno));
399 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
400 _PATH_SSH_USER_CONFFILE);
401 if (r > 0 && (size_t)r < sizeof(buf))
402 (void)read_config_file(buf, pw, host, &options,
403 SSHCONF_CHECKPERM|SSHCONF_USERCONF);
405 /* Read systemwide configuration file after user config. */
406 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host,
412 * Main program for the ssh client.
415 main(int ac, char **av)
417 int i, r, opt, exit_status, use_syslog;
418 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile;
419 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
420 char cname[NI_MAXHOST];
424 extern int optind, optreset;
427 struct addrinfo *addrs = NULL;
428 struct ssh_digest_ctx *md;
429 u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
432 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
435 __progname = ssh_get_progname(av[0]);
437 #ifndef HAVE_SETPROCTITLE
438 /* Prepare for later setproctitle emulation */
439 /* Save argv so it isn't clobbered by setproctitle() emulation */
440 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
441 for (i = 0; i < ac; i++)
442 saved_av[i] = xstrdup(av[i]);
444 compat_init_setproctitle(ac, av);
449 * Discard other fds that are hanging around. These can cause problem
450 * with backgrounded ssh processes started by ControlPersist.
452 closefrom(STDERR_FILENO + 1);
455 * Save the original real uid. It will be needed later (uid-swapping
456 * may clobber the real uid).
458 original_real_uid = getuid();
459 original_effective_uid = geteuid();
462 * Use uid-swapping to give up root privileges for the duration of
463 * option processing. We will re-instantiate the rights when we are
464 * ready to create the privileged port, and will permanently drop
465 * them when the port has been created (actually, when the connection
466 * has been made, as we may need to create the port several times).
470 #ifdef HAVE_SETRLIMIT
471 /* If we are installed setuid root be careful to not drop core. */
472 if (original_real_uid != original_effective_uid) {
474 rlim.rlim_cur = rlim.rlim_max = 0;
475 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
476 fatal("setrlimit failed: %.100s", strerror(errno));
480 pw = getpwuid(original_real_uid);
482 logit("No user exists for uid %lu", (u_long)original_real_uid);
485 /* Take a copy of the returned structure. */
489 * Set our umask to something reasonable, as some files are created
490 * with the default umask. This will make them world-readable but
491 * writable only by the owner, which is ok for all files for which we
492 * don't set the modes explicitly.
497 * Initialize option structure to indicate that no values have been
500 initialize_options(&options);
502 /* Parse command-line arguments. */
509 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
510 "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
513 options.protocol = SSH_PROTO_1;
516 options.protocol = SSH_PROTO_2;
519 options.address_family = AF_INET;
522 options.address_family = AF_INET6;
528 fork_after_authentication_flag = 1;
532 options.forward_x11 = 0;
535 options.forward_x11 = 1;
541 logfile = xstrdup(optarg);
544 options.forward_x11 = 1;
545 options.forward_x11_trusted = 1;
548 options.fwd_opts.gateway_ports = 1;
551 if (stdio_forward_host != NULL)
552 fatal("Cannot specify multiplexing "
554 else if (muxclient_command != 0)
555 fatal("Multiplexing command already specified");
556 if (strcmp(optarg, "check") == 0)
557 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
558 else if (strcmp(optarg, "forward") == 0)
559 muxclient_command = SSHMUX_COMMAND_FORWARD;
560 else if (strcmp(optarg, "exit") == 0)
561 muxclient_command = SSHMUX_COMMAND_TERMINATE;
562 else if (strcmp(optarg, "stop") == 0)
563 muxclient_command = SSHMUX_COMMAND_STOP;
564 else if (strcmp(optarg, "cancel") == 0)
565 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
567 fatal("Invalid multiplex command.");
569 case 'P': /* deprecated */
570 options.use_privileged_port = 0;
574 if (strcmp(optarg, "cipher") == 0)
575 cp = cipher_alg_list('\n', 0);
576 else if (strcmp(optarg, "cipher-auth") == 0)
577 cp = cipher_alg_list('\n', 1);
578 else if (strcmp(optarg, "mac") == 0)
579 cp = mac_alg_list('\n');
580 else if (strcmp(optarg, "kex") == 0)
581 cp = kex_alg_list('\n');
582 else if (strcmp(optarg, "key") == 0)
583 cp = key_alg_list(0, 0);
584 else if (strcmp(optarg, "key-cert") == 0)
585 cp = key_alg_list(1, 0);
586 else if (strcmp(optarg, "key-plain") == 0)
587 cp = key_alg_list(0, 1);
589 fatal("Unsupported query \"%s\"", optarg);
595 options.forward_agent = 0;
598 options.forward_agent = 1;
601 options.gss_deleg_creds = 0;
604 options.gss_authentication = 1;
605 options.gss_deleg_creds = 1;
608 if (stat(optarg, &st) < 0) {
609 fprintf(stderr, "Warning: Identity file %s "
610 "not accessible: %s.\n", optarg,
614 add_identity_file(&options, NULL, optarg, 1);
618 options.pkcs11_provider = xstrdup(optarg);
620 fprintf(stderr, "no support for PKCS#11.\n");
624 if (options.request_tty == REQUEST_TTY_YES)
625 options.request_tty = REQUEST_TTY_FORCE;
627 options.request_tty = REQUEST_TTY_YES;
630 if (debug_flag == 0) {
632 options.log_level = SYSLOG_LEVEL_DEBUG1;
634 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
639 if (options.version_addendum &&
640 *options.version_addendum != '\0')
641 fprintf(stderr, "%s%s %s, %s\n", SSH_RELEASE,
642 options.hpn_disabled ? "" : SSH_VERSION_HPN,
643 options.version_addendum,
644 SSLeay_version(SSLEAY_VERSION));
646 fprintf(stderr, "%s%s, %s\n",
648 options.hpn_disabled ? "" : SSH_VERSION_HPN,
650 SSLeay_version(SSLEAY_VERSION)
659 if (options.tun_open == -1)
660 options.tun_open = SSH_TUNMODE_DEFAULT;
661 options.tun_local = a2tun(optarg, &options.tun_remote);
662 if (options.tun_local == SSH_TUNID_ERR) {
664 "Bad tun device '%s'\n", optarg);
669 if (stdio_forward_host != NULL)
670 fatal("stdio forward already specified");
671 if (muxclient_command != 0)
672 fatal("Cannot specify stdio forward with -O");
673 if (parse_forward(&fwd, optarg, 1, 0)) {
674 stdio_forward_host = fwd.listen_host;
675 stdio_forward_port = fwd.listen_port;
676 free(fwd.connect_host);
679 "Bad stdio forwarding specification '%s'\n",
683 options.request_tty = REQUEST_TTY_NO;
685 options.clear_forwardings = 1;
686 options.exit_on_forward_failure = 1;
689 options.log_level = SYSLOG_LEVEL_QUIET;
692 if (optarg[0] == '^' && optarg[2] == 0 &&
693 (u_char) optarg[1] >= 64 &&
694 (u_char) optarg[1] < 128)
695 options.escape_char = (u_char) optarg[1] & 31;
696 else if (strlen(optarg) == 1)
697 options.escape_char = (u_char) optarg[0];
698 else if (strcmp(optarg, "none") == 0)
699 options.escape_char = SSH_ESCAPECHAR_NONE;
701 fprintf(stderr, "Bad escape character '%s'.\n",
707 if (ciphers_valid(optarg)) {
709 options.ciphers = xstrdup(optarg);
710 options.cipher = SSH_CIPHER_INVALID;
713 options.cipher = cipher_number(optarg);
714 if (options.cipher == -1) {
716 "Unknown cipher type '%s'\n",
720 if (options.cipher == SSH_CIPHER_3DES)
721 options.ciphers = "3des-cbc";
722 else if (options.cipher == SSH_CIPHER_BLOWFISH)
723 options.ciphers = "blowfish-cbc";
725 options.ciphers = (char *)-1;
729 if (mac_valid(optarg))
730 options.macs = xstrdup(optarg);
732 fprintf(stderr, "Unknown mac type '%s'\n",
738 if (options.control_master == SSHCTL_MASTER_YES)
739 options.control_master = SSHCTL_MASTER_ASK;
741 options.control_master = SSHCTL_MASTER_YES;
744 options.port = a2port(optarg);
745 if (options.port <= 0) {
746 fprintf(stderr, "Bad port '%s'\n", optarg);
751 options.user = optarg;
755 if (parse_forward(&fwd, optarg, 0, 0))
756 add_local_forward(&options, &fwd);
759 "Bad local forwarding specification '%s'\n",
766 if (parse_forward(&fwd, optarg, 0, 1)) {
767 add_remote_forward(&options, &fwd);
770 "Bad remote forwarding specification "
777 if (parse_forward(&fwd, optarg, 1, 0)) {
778 add_local_forward(&options, &fwd);
781 "Bad dynamic forwarding specification "
788 options.compression = 1;
792 options.request_tty = REQUEST_TTY_NO;
795 options.request_tty = REQUEST_TTY_NO;
796 /* ensure that the user doesn't try to backdoor a */
797 /* null cipher switch on an interactive session */
798 /* so explicitly disable it no matter what */
799 options.none_switch=0;
802 line = xstrdup(optarg);
803 if (process_config_line(&options, pw, host ? host : "",
804 line, "command-line", 0, NULL, SSHCONF_USERCONF)
813 if (options.control_path != NULL)
814 free(options.control_path);
815 options.control_path = xstrdup(optarg);
818 options.bind_address = optarg;
831 if (ac > 0 && !host) {
832 if (strrchr(*av, '@')) {
834 cp = strrchr(p, '@');
835 if (cp == NULL || cp == p)
839 host = xstrdup(++cp);
843 optind = optreset = 1;
849 /* Check that we got a host name. */
853 host_arg = xstrdup(host);
856 OpenSSL_add_all_algorithms();
857 ERR_load_crypto_strings();
860 /* Initialize the command to execute on remote host. */
861 buffer_init(&command);
864 * Save the command to execute on the remote host in a buffer. There
865 * is no limit on the length of the command, except by the maximum
866 * packet size. Also sets the tty flag if there is no command.
869 /* No command specified - execute shell on a tty. */
870 if (subsystem_flag) {
872 "You must specify a subsystem to invoke.\n");
876 /* A command has been specified. Store it into the buffer. */
877 for (i = 0; i < ac; i++) {
879 buffer_append(&command, " ", 1);
880 buffer_append(&command, av[i], strlen(av[i]));
884 /* Cannot fork to background if no command. */
885 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
887 fatal("Cannot fork into background without a command "
891 * Initialize "log" output. Since we are the client all output
892 * goes to stderr unless otherwise specified by -y or -E.
894 if (use_syslog && logfile != NULL)
895 fatal("Can't specify both -y and -E");
896 if (logfile != NULL) {
897 log_redirect_stderr_to(logfile);
901 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
902 SYSLOG_FACILITY_USER, !use_syslog);
905 logit("%s, %s", SSH_RELEASE,
907 SSLeay_version(SSLEAY_VERSION)
913 /* Parse the configuration files */
914 process_config_files(pw);
916 /* Hostname canonicalisation needs a few options filled. */
917 fill_default_options_for_canonicalization(&options);
919 /* If the user has replaced the hostname then take it into use now */
920 if (options.hostname != NULL) {
921 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
922 cp = percent_expand(options.hostname,
923 "h", host, (char *)NULL);
928 /* If canonicalization requested then try to apply it */
930 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
931 addrs = resolve_canonicalize(&host, options.port);
934 * If CanonicalizePermittedCNAMEs have been specified but
935 * other canonicalization did not happen (by not being requested
936 * or by failing with fallback) then the hostname may still be changed
937 * as a result of CNAME following.
939 * Try to resolve the bare hostname name using the system resolver's
940 * usual search rules and then apply the CNAME follow rules.
942 * Skip the lookup if a ProxyCommand is being used unless the user
943 * has specifically requested canonicalisation for this case via
944 * CanonicalizeHostname=always
946 if (addrs == NULL && options.num_permitted_cnames != 0 &&
947 (option_clear_or_none(options.proxy_command) ||
948 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
949 if ((addrs = resolve_host(host, options.port,
950 option_clear_or_none(options.proxy_command),
951 cname, sizeof(cname))) == NULL) {
952 /* Don't fatal proxied host names not in the DNS */
953 if (option_clear_or_none(options.proxy_command))
954 cleanup_exit(255); /* logged in resolve_host */
956 check_follow_cname(&host, cname);
960 * If the target hostname has changed as a result of canonicalisation
961 * then re-parse the configuration files as new stanzas may match.
963 if (strcasecmp(host_arg, host) != 0) {
964 debug("Hostname has changed; re-reading configuration");
965 process_config_files(pw);
968 /* Fill configuration defaults. */
969 fill_default_options(&options);
971 if (options.port == 0)
972 options.port = default_ssh_port();
973 channel_set_af(options.address_family);
975 /* Tidy and check options */
976 if (options.host_key_alias != NULL)
977 lowercase(options.host_key_alias);
978 if (options.proxy_command != NULL &&
979 strcmp(options.proxy_command, "-") == 0 &&
980 options.proxy_use_fdpass)
981 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
983 if (original_effective_uid != 0)
984 options.use_privileged_port = 0;
988 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
990 if (options.request_tty == REQUEST_TTY_YES ||
991 options.request_tty == REQUEST_TTY_FORCE)
994 /* Allocate a tty by default if no command specified. */
995 if (buffer_len(&command) == 0)
996 tty_flag = options.request_tty != REQUEST_TTY_NO;
999 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
1001 /* Do not allocate a tty if stdin is not a tty. */
1002 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1003 options.request_tty != REQUEST_TTY_FORCE) {
1005 logit("Pseudo-terminal will not be allocated because "
1006 "stdin is not a terminal.");
1012 if (options.user == NULL)
1013 options.user = xstrdup(pw->pw_name);
1015 if (gethostname(thishost, sizeof(thishost)) == -1)
1016 fatal("gethostname: %s", strerror(errno));
1017 strlcpy(shorthost, thishost, sizeof(shorthost));
1018 shorthost[strcspn(thishost, ".")] = '\0';
1019 snprintf(portstr, sizeof(portstr), "%d", options.port);
1021 if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1022 ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1023 ssh_digest_update(md, host, strlen(host)) < 0 ||
1024 ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1025 ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1026 ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1027 fatal("%s: mux digest failed", __func__);
1028 ssh_digest_free(md);
1029 conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1031 if (options.local_command != NULL) {
1032 debug3("expanding LocalCommand: %s", options.local_command);
1033 cp = options.local_command;
1034 options.local_command = percent_expand(cp,
1045 debug3("expanded LocalCommand: %s", options.local_command);
1049 if (options.control_path != NULL) {
1050 cp = tilde_expand_filename(options.control_path,
1052 free(options.control_path);
1053 options.control_path = percent_expand(cp,
1065 free(conn_hash_hex);
1067 if (muxclient_command != 0 && options.control_path == NULL)
1068 fatal("No ControlPath specified for \"-O\" command");
1069 if (options.control_path != NULL)
1070 muxclient(options.control_path);
1073 * If hostname canonicalisation was not enabled, then we may not
1074 * have yet resolved the hostname. Do so now.
1076 if (addrs == NULL && options.proxy_command == NULL) {
1077 if ((addrs = resolve_host(host, options.port, 1,
1078 cname, sizeof(cname))) == NULL)
1079 cleanup_exit(255); /* resolve_host logs the error */
1082 timeout_ms = options.connection_timeout * 1000;
1084 /* Open a connection to the remote host. */
1085 if (ssh_connect(host, addrs, &hostaddr, options.port,
1086 options.address_family, options.connection_attempts,
1087 &timeout_ms, options.tcp_keep_alive,
1088 options.use_privileged_port) != 0)
1092 freeaddrinfo(addrs);
1094 packet_set_timeout(options.server_alive_interval,
1095 options.server_alive_count_max);
1098 debug3("timeout: %d ms remain after connect", timeout_ms);
1101 * If we successfully made the connection, load the host private key
1102 * in case we will need it later for combined rsa-rhosts
1103 * authentication. This must be done before releasing extra
1104 * privileges, because the file is only readable by root.
1105 * If we cannot access the private keys, load the public keys
1106 * instead and try to execute the ssh-keysign helper instead.
1108 sensitive_data.nkeys = 0;
1109 sensitive_data.keys = NULL;
1110 sensitive_data.external_keysign = 0;
1111 if (options.rhosts_rsa_authentication ||
1112 options.hostbased_authentication) {
1113 sensitive_data.nkeys = 9;
1114 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1116 for (i = 0; i < sensitive_data.nkeys; i++)
1117 sensitive_data.keys[i] = NULL;
1120 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1121 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1122 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
1123 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1124 #ifdef OPENSSL_HAS_ECC
1125 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
1126 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1128 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1129 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1130 sensitive_data.keys[4] = key_load_private_cert(KEY_ED25519,
1131 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1132 sensitive_data.keys[5] = key_load_private_type(KEY_DSA,
1133 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1134 #ifdef OPENSSL_HAS_ECC
1135 sensitive_data.keys[6] = key_load_private_type(KEY_ECDSA,
1136 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1138 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1139 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1140 sensitive_data.keys[8] = key_load_private_type(KEY_ED25519,
1141 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1144 if (options.hostbased_authentication == 1 &&
1145 sensitive_data.keys[0] == NULL &&
1146 sensitive_data.keys[5] == NULL &&
1147 sensitive_data.keys[6] == NULL &&
1148 sensitive_data.keys[7] == NULL &&
1149 sensitive_data.keys[8] == NULL) {
1150 sensitive_data.keys[1] = key_load_cert(
1151 _PATH_HOST_DSA_KEY_FILE);
1152 #ifdef OPENSSL_HAS_ECC
1153 sensitive_data.keys[2] = key_load_cert(
1154 _PATH_HOST_ECDSA_KEY_FILE);
1156 sensitive_data.keys[3] = key_load_cert(
1157 _PATH_HOST_RSA_KEY_FILE);
1158 sensitive_data.keys[4] = key_load_cert(
1159 _PATH_HOST_ED25519_KEY_FILE);
1160 sensitive_data.keys[5] = key_load_public(
1161 _PATH_HOST_DSA_KEY_FILE, NULL);
1162 #ifdef OPENSSL_HAS_ECC
1163 sensitive_data.keys[6] = key_load_public(
1164 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1166 sensitive_data.keys[7] = key_load_public(
1167 _PATH_HOST_RSA_KEY_FILE, NULL);
1168 sensitive_data.keys[8] = key_load_public(
1169 _PATH_HOST_ED25519_KEY_FILE, NULL);
1170 sensitive_data.external_keysign = 1;
1174 * Get rid of any extra privileges that we may have. We will no
1175 * longer need them. Also, extra privileges could make it very hard
1176 * to read identity files and other non-world-readable files from the
1177 * user's home directory if it happens to be on a NFS volume where
1178 * root is mapped to nobody.
1180 if (original_effective_uid == 0) {
1182 permanently_set_uid(pw);
1186 * Now that we are back to our own permissions, create ~/.ssh
1187 * directory if it doesn't already exist.
1189 if (config == NULL) {
1190 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1191 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1192 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1194 ssh_selinux_setfscreatecon(buf);
1196 if (mkdir(buf, 0700) < 0)
1197 error("Could not create directory '%.200s'.",
1200 ssh_selinux_setfscreatecon(NULL);
1204 /* load options.identity_files */
1205 load_public_identity_files();
1207 /* Expand ~ in known host file names. */
1208 tilde_expand_paths(options.system_hostfiles,
1209 options.num_system_hostfiles);
1210 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1212 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1213 signal(SIGCHLD, main_sigchld_handler);
1215 /* Log into the remote system. Never returns if the login fails. */
1216 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1217 options.port, pw, timeout_ms);
1219 if (packet_connection_is_on_socket()) {
1220 verbose("Authenticated to %s ([%s]:%d).", host,
1221 get_remote_ipaddr(), get_remote_port());
1223 verbose("Authenticated to %s (via proxy).", host);
1226 /* We no longer need the private host keys. Clear them now. */
1227 if (sensitive_data.nkeys != 0) {
1228 for (i = 0; i < sensitive_data.nkeys; i++) {
1229 if (sensitive_data.keys[i] != NULL) {
1230 /* Destroys contents safely */
1231 debug3("clear hostkey %d", i);
1232 key_free(sensitive_data.keys[i]);
1233 sensitive_data.keys[i] = NULL;
1236 free(sensitive_data.keys);
1238 for (i = 0; i < options.num_identity_files; i++) {
1239 free(options.identity_files[i]);
1240 options.identity_files[i] = NULL;
1241 if (options.identity_keys[i]) {
1242 key_free(options.identity_keys[i]);
1243 options.identity_keys[i] = NULL;
1247 exit_status = compat20 ? ssh_session2() : ssh_session();
1250 if (options.control_path != NULL && muxserver_sock != -1)
1251 unlink(options.control_path);
1253 /* Kill ProxyCommand if it is running. */
1254 ssh_kill_proxy_command();
1260 control_persist_detach(void)
1265 debug("%s: backgrounding master process", __func__);
1268 * master (current process) into the background, and make the
1269 * foreground process a client of the backgrounded master.
1271 switch ((pid = fork())) {
1273 fatal("%s: fork: %s", __func__, strerror(errno));
1275 /* Child: master process continues mainloop */
1278 /* Parent: set up mux slave to connect to backgrounded master */
1279 debug2("%s: background process is %ld", __func__, (long)pid);
1280 stdin_null_flag = ostdin_null_flag;
1281 options.request_tty = orequest_tty;
1282 tty_flag = otty_flag;
1283 close(muxserver_sock);
1284 muxserver_sock = -1;
1285 options.control_master = SSHCTL_MASTER_NO;
1286 muxclient(options.control_path);
1287 /* muxclient() doesn't return on success. */
1288 fatal("Failed to connect to new control master");
1290 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1291 error("%s: open(\"/dev/null\"): %s", __func__,
1294 if (dup2(devnull, STDIN_FILENO) == -1 ||
1295 dup2(devnull, STDOUT_FILENO) == -1)
1296 error("%s: dup2: %s", __func__, strerror(errno));
1297 if (devnull > STDERR_FILENO)
1301 setproctitle("%s [mux]", options.control_path);
1304 extern const EVP_CIPHER *evp_aes_ctr_mt(void);
1306 /* Do fork() after authentication. Used by "ssh -f" */
1310 if (need_controlpersist_detach)
1311 control_persist_detach();
1312 debug("forking to background");
1313 fork_after_authentication_flag = 0;
1314 if (daemon(1, 1) < 0)
1315 fatal("daemon() failed: %.200s", strerror(errno));
1318 /* Callback for remote forward global requests */
1320 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1322 struct Forward *rfwd = (struct Forward *)ctxt;
1324 /* XXX verbose() on failure? */
1325 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1326 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1327 rfwd->listen_path ? rfwd->listen_path :
1328 rfwd->listen_host ? rfwd->listen_host : "",
1329 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1330 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1331 rfwd->connect_host, rfwd->connect_port);
1332 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1333 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1334 rfwd->allocated_port = packet_get_int();
1335 logit("Allocated port %u for remote forward to %s:%d",
1336 rfwd->allocated_port,
1337 rfwd->connect_host, rfwd->connect_port);
1338 channel_update_permitted_opens(rfwd->handle,
1339 rfwd->allocated_port);
1341 channel_update_permitted_opens(rfwd->handle, -1);
1345 if (type == SSH2_MSG_REQUEST_FAILURE) {
1346 if (options.exit_on_forward_failure) {
1347 if (rfwd->listen_path != NULL)
1348 fatal("Error: remote port forwarding failed "
1349 "for listen path %s", rfwd->listen_path);
1351 fatal("Error: remote port forwarding failed "
1352 "for listen port %d", rfwd->listen_port);
1354 if (rfwd->listen_path != NULL)
1355 logit("Warning: remote port forwarding failed "
1356 "for listen path %s", rfwd->listen_path);
1358 logit("Warning: remote port forwarding failed "
1359 "for listen port %d", rfwd->listen_port);
1362 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1363 debug("All remote forwarding requests processed");
1364 if (fork_after_authentication_flag)
1370 client_cleanup_stdio_fwd(int id, void *arg)
1372 debug("stdio forwarding: done");
1377 ssh_stdio_confirm(int id, int success, void *arg)
1380 fatal("stdio forwarding failed");
1384 ssh_init_stdio_forwarding(void)
1389 if (stdio_forward_host == NULL)
1392 fatal("stdio forwarding require Protocol 2");
1394 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1396 if ((in = dup(STDIN_FILENO)) < 0 ||
1397 (out = dup(STDOUT_FILENO)) < 0)
1398 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1399 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1400 stdio_forward_port, in, out)) == NULL)
1401 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1402 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1403 channel_register_open_confirm(c->self, ssh_stdio_confirm, NULL);
1407 ssh_init_forwarding(void)
1412 /* Initiate local TCP/IP port forwardings. */
1413 for (i = 0; i < options.num_local_forwards; i++) {
1414 debug("Local connections to %.200s:%d forwarded to remote "
1415 "address %.200s:%d",
1416 (options.local_forwards[i].listen_path != NULL) ?
1417 options.local_forwards[i].listen_path :
1418 (options.local_forwards[i].listen_host == NULL) ?
1419 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1420 options.local_forwards[i].listen_host,
1421 options.local_forwards[i].listen_port,
1422 (options.local_forwards[i].connect_path != NULL) ?
1423 options.local_forwards[i].connect_path :
1424 options.local_forwards[i].connect_host,
1425 options.local_forwards[i].connect_port);
1426 success += channel_setup_local_fwd_listener(
1427 &options.local_forwards[i], &options.fwd_opts);
1429 if (i > 0 && success != i && options.exit_on_forward_failure)
1430 fatal("Could not request local forwarding.");
1431 if (i > 0 && success == 0)
1432 error("Could not request local forwarding.");
1434 /* Initiate remote TCP/IP port forwardings. */
1435 for (i = 0; i < options.num_remote_forwards; i++) {
1436 debug("Remote connections from %.200s:%d forwarded to "
1437 "local address %.200s:%d",
1438 (options.remote_forwards[i].listen_path != NULL) ?
1439 options.remote_forwards[i].listen_path :
1440 (options.remote_forwards[i].listen_host == NULL) ?
1441 "LOCALHOST" : options.remote_forwards[i].listen_host,
1442 options.remote_forwards[i].listen_port,
1443 (options.remote_forwards[i].connect_path != NULL) ?
1444 options.remote_forwards[i].connect_path :
1445 options.remote_forwards[i].connect_host,
1446 options.remote_forwards[i].connect_port);
1447 options.remote_forwards[i].handle =
1448 channel_request_remote_forwarding(
1449 &options.remote_forwards[i]);
1450 if (options.remote_forwards[i].handle < 0) {
1451 if (options.exit_on_forward_failure)
1452 fatal("Could not request remote forwarding.");
1454 logit("Warning: Could not request remote "
1457 client_register_global_confirm(ssh_confirm_remote_forward,
1458 &options.remote_forwards[i]);
1462 /* Initiate tunnel forwarding. */
1463 if (options.tun_open != SSH_TUNMODE_NO) {
1464 if (client_request_tun_fwd(options.tun_open,
1465 options.tun_local, options.tun_remote) == -1) {
1466 if (options.exit_on_forward_failure)
1467 fatal("Could not request tunnel forwarding.");
1469 error("Could not request tunnel forwarding.");
1475 check_agent_present(void)
1477 if (options.forward_agent) {
1478 /* Clear agent forwarding if we don't have an agent. */
1479 if (!ssh_agent_present())
1480 options.forward_agent = 0;
1488 int interactive = 0;
1492 const char *display;
1494 /* Enable compression if requested. */
1495 if (options.compression) {
1496 debug("Requesting compression at level %d.",
1497 options.compression_level);
1499 if (options.compression_level < 1 ||
1500 options.compression_level > 9)
1501 fatal("Compression level must be from 1 (fast) to "
1504 /* Send the request. */
1505 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1506 packet_put_int(options.compression_level);
1508 packet_write_wait();
1509 type = packet_read();
1510 if (type == SSH_SMSG_SUCCESS)
1511 packet_start_compression(options.compression_level);
1512 else if (type == SSH_SMSG_FAILURE)
1513 logit("Warning: Remote host refused compression.");
1515 packet_disconnect("Protocol error waiting for "
1516 "compression response.");
1518 /* Allocate a pseudo tty if appropriate. */
1520 debug("Requesting pty.");
1522 /* Start the packet. */
1523 packet_start(SSH_CMSG_REQUEST_PTY);
1525 /* Store TERM in the packet. There is no limit on the
1526 length of the string. */
1527 cp = getenv("TERM");
1530 packet_put_cstring(cp);
1532 /* Store window size in the packet. */
1533 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1534 memset(&ws, 0, sizeof(ws));
1535 packet_put_int((u_int)ws.ws_row);
1536 packet_put_int((u_int)ws.ws_col);
1537 packet_put_int((u_int)ws.ws_xpixel);
1538 packet_put_int((u_int)ws.ws_ypixel);
1540 /* Store tty modes in the packet. */
1541 tty_make_modes(fileno(stdin), NULL);
1543 /* Send the packet, and wait for it to leave. */
1545 packet_write_wait();
1547 /* Read response from the server. */
1548 type = packet_read();
1549 if (type == SSH_SMSG_SUCCESS) {
1552 } else if (type == SSH_SMSG_FAILURE)
1553 logit("Warning: Remote host failed or refused to "
1554 "allocate a pseudo tty.");
1556 packet_disconnect("Protocol error waiting for pty "
1557 "request response.");
1559 /* Request X11 forwarding if enabled and DISPLAY is set. */
1560 display = getenv("DISPLAY");
1561 if (options.forward_x11 && display != NULL) {
1563 /* Get reasonable local authentication information. */
1564 client_x11_get_proto(display, options.xauth_location,
1565 options.forward_x11_trusted,
1566 options.forward_x11_timeout,
1568 /* Request forwarding with authentication spoofing. */
1569 debug("Requesting X11 forwarding with authentication "
1571 x11_request_forwarding_with_spoofing(0, display, proto,
1573 /* Read response from the server. */
1574 type = packet_read();
1575 if (type == SSH_SMSG_SUCCESS) {
1577 } else if (type == SSH_SMSG_FAILURE) {
1578 logit("Warning: Remote host denied X11 forwarding.");
1580 packet_disconnect("Protocol error waiting for X11 "
1584 /* Tell the packet module whether this is an interactive session. */
1585 packet_set_interactive(interactive,
1586 options.ip_qos_interactive, options.ip_qos_bulk);
1588 /* Request authentication agent forwarding if appropriate. */
1589 check_agent_present();
1591 if (options.forward_agent) {
1592 debug("Requesting authentication agent forwarding.");
1593 auth_request_forwarding();
1595 /* Read response from the server. */
1596 type = packet_read();
1598 if (type != SSH_SMSG_SUCCESS)
1599 logit("Warning: Remote host denied authentication agent forwarding.");
1602 /* Initiate port forwardings. */
1603 ssh_init_stdio_forwarding();
1604 ssh_init_forwarding();
1606 /* Execute a local command */
1607 if (options.local_command != NULL &&
1608 options.permit_local_command)
1609 ssh_local_cmd(options.local_command);
1612 * If requested and we are not interested in replies to remote
1613 * forwarding requests, then let ssh continue in the background.
1615 if (fork_after_authentication_flag) {
1616 if (options.exit_on_forward_failure &&
1617 options.num_remote_forwards > 0) {
1618 debug("deferring postauth fork until remote forward "
1619 "confirmation received");
1625 * If a command was specified on the command line, execute the
1626 * command now. Otherwise request the server to start a shell.
1628 if (buffer_len(&command) > 0) {
1629 int len = buffer_len(&command);
1632 debug("Sending command: %.*s", len,
1633 (u_char *)buffer_ptr(&command));
1634 packet_start(SSH_CMSG_EXEC_CMD);
1635 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1637 packet_write_wait();
1639 debug("Requesting shell.");
1640 packet_start(SSH_CMSG_EXEC_SHELL);
1642 packet_write_wait();
1645 /* Enter the interactive session. */
1646 return client_loop(have_tty, tty_flag ?
1647 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1650 /* request pty/x11/agent/tcpfwd/shell for channel */
1652 ssh_session2_setup(int id, int success, void *arg)
1654 extern char **environ;
1655 const char *display;
1656 int interactive = tty_flag;
1659 return; /* No need for error message, channels code sens one */
1661 display = getenv("DISPLAY");
1662 if (options.forward_x11 && display != NULL) {
1664 /* Get reasonable local authentication information. */
1665 client_x11_get_proto(display, options.xauth_location,
1666 options.forward_x11_trusted,
1667 options.forward_x11_timeout, &proto, &data);
1668 /* Request forwarding with authentication spoofing. */
1669 debug("Requesting X11 forwarding with authentication "
1671 x11_request_forwarding_with_spoofing(id, display, proto,
1673 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1674 /* XXX exit_on_forward_failure */
1678 check_agent_present();
1679 if (options.forward_agent) {
1680 debug("Requesting authentication agent forwarding.");
1681 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1685 /* Tell the packet module whether this is an interactive session. */
1686 packet_set_interactive(interactive,
1687 options.ip_qos_interactive, options.ip_qos_bulk);
1689 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1690 NULL, fileno(stdin), &command, environ);
1693 /* open new channel for a session */
1695 ssh_session2_open(void)
1698 int window, packetmax, in, out, err;
1701 int socksizelen = sizeof(int);
1703 if (stdin_null_flag) {
1704 in = open(_PATH_DEVNULL, O_RDONLY);
1706 in = dup(STDIN_FILENO);
1708 out = dup(STDOUT_FILENO);
1709 err = dup(STDERR_FILENO);
1711 if (in < 0 || out < 0 || err < 0)
1712 fatal("dup() in/out/err failed");
1714 /* enable nonblocking unless tty */
1722 /* we need to check to see if what they want to do about buffer */
1723 /* sizes here. In a hpn to nonhpn connection we want to limit */
1724 /* the window size to something reasonable in case the far side */
1725 /* has the large window bug. In hpn to hpn connection we want to */
1726 /* use the max window size but allow the user to override it */
1727 /* lastly if they disabled hpn then use the ssh std window size */
1729 /* so why don't we just do a getsockopt() here and set the */
1730 /* ssh window to that? In the case of a autotuning receive */
1731 /* window the window would get stuck at the initial buffer */
1732 /* size generally less than 96k. Therefore we need to set the */
1733 /* maximum ssh window size to the maximum hpn buffer size */
1734 /* unless the user has specifically set the tcprcvbufpoll */
1735 /* to no. In which case we *can* just set the window to the */
1736 /* minimum of the hpn buffer size and tcp receive buffer size */
1739 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1741 options.hpn_buffer_size = 2*1024*1024;
1743 if (datafellows & SSH_BUG_LARGEWINDOW)
1745 debug("HPN to Non-HPN Connection");
1749 if (options.tcp_rcv_buf_poll <= 0)
1751 sock = socket(AF_INET, SOCK_STREAM, 0);
1752 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1753 &socksize, &socksizelen);
1755 debug("socksize %d", socksize);
1756 options.hpn_buffer_size = socksize;
1757 debug ("HPNBufferSize set to TCP RWIN: %d", options.hpn_buffer_size);
1761 if (options.tcp_rcv_buf > 0)
1763 /*create a socket but don't connect it */
1764 /* we use that the get the rcv socket size */
1765 sock = socket(AF_INET, SOCK_STREAM, 0);
1766 /* if they are using the tcp_rcv_buf option */
1767 /* attempt to set the buffer size to that */
1768 if (options.tcp_rcv_buf)
1769 setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (void *)&options.tcp_rcv_buf,
1770 sizeof(options.tcp_rcv_buf));
1771 getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1772 &socksize, &socksizelen);
1774 debug("socksize %d", socksize);
1775 options.hpn_buffer_size = socksize;
1776 debug ("HPNBufferSize set to user TCPRcvBuf: %d", options.hpn_buffer_size);
1781 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1783 window = options.hpn_buffer_size;
1785 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1787 packetmax = CHAN_SES_PACKET_DEFAULT;
1789 window = 4*CHAN_SES_PACKET_DEFAULT;
1794 "session", SSH_CHANNEL_OPENING, in, out, err,
1795 window, packetmax, CHAN_EXTENDED_WRITE,
1796 "client-session", /*nonblock*/0);
1798 if ((options.tcp_rcv_buf_poll > 0) && (!options.hpn_disabled)) {
1799 c->dynamic_window = 1;
1800 debug ("Enabled Dynamic Window Scaling");
1802 debug3("ssh_session2_open: channel_new: %d", c->self);
1804 channel_send_open(c->self);
1806 channel_register_open_confirm(c->self,
1807 ssh_session2_setup, NULL);
1817 /* XXX should be pre-session */
1818 if (!options.control_persist)
1819 ssh_init_stdio_forwarding();
1820 ssh_init_forwarding();
1822 /* Start listening for multiplex clients */
1826 * If we are in control persist mode and have a working mux listen
1827 * socket, then prepare to background ourselves and have a foreground
1828 * client attach as a control slave.
1829 * NB. we must save copies of the flags that we override for
1830 * the backgrounding, since we defer attachment of the slave until
1831 * after the connection is fully established (in particular,
1832 * async rfwd replies have been received for ExitOnForwardFailure).
1834 if (options.control_persist && muxserver_sock != -1) {
1835 ostdin_null_flag = stdin_null_flag;
1836 ono_shell_flag = no_shell_flag;
1837 orequest_tty = options.request_tty;
1838 otty_flag = tty_flag;
1839 stdin_null_flag = 1;
1842 if (!fork_after_authentication_flag)
1843 need_controlpersist_detach = 1;
1844 fork_after_authentication_flag = 1;
1847 * ControlPersist mux listen socket setup failed, attempt the
1848 * stdio forward setup that we skipped earlier.
1850 if (options.control_persist && muxserver_sock == -1)
1851 ssh_init_stdio_forwarding();
1853 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1854 id = ssh_session2_open();
1856 packet_set_interactive(
1857 options.control_master == SSHCTL_MASTER_NO,
1858 options.ip_qos_interactive, options.ip_qos_bulk);
1861 /* If we don't expect to open a new session, then disallow it */
1862 if (options.control_master == SSHCTL_MASTER_NO &&
1863 (datafellows & SSH_NEW_OPENSSH)) {
1864 debug("Requesting no-more-sessions@openssh.com");
1865 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1866 packet_put_cstring("no-more-sessions@openssh.com");
1871 /* Execute a local command */
1872 if (options.local_command != NULL &&
1873 options.permit_local_command)
1874 ssh_local_cmd(options.local_command);
1877 * If requested and we are not interested in replies to remote
1878 * forwarding requests, then let ssh continue in the background.
1880 if (fork_after_authentication_flag) {
1881 if (options.exit_on_forward_failure &&
1882 options.num_remote_forwards > 0) {
1883 debug("deferring postauth fork until remote forward "
1884 "confirmation received");
1889 if (options.use_roaming)
1892 return client_loop(tty_flag, tty_flag ?
1893 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1897 load_public_identity_files(void)
1899 char *filename, *cp, thishost[NI_MAXHOST];
1900 char *pwdir = NULL, *pwname = NULL;
1905 char *identity_files[SSH_MAX_IDENTITY_FILES];
1906 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1907 #ifdef ENABLE_PKCS11
1913 memset(identity_files, 0, sizeof(identity_files));
1914 memset(identity_keys, 0, sizeof(identity_keys));
1916 #ifdef ENABLE_PKCS11
1917 if (options.pkcs11_provider != NULL &&
1918 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1919 (pkcs11_init(!options.batch_mode) == 0) &&
1920 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1922 for (i = 0; i < nkeys; i++) {
1923 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1927 identity_keys[n_ids] = keys[i];
1928 identity_files[n_ids] =
1929 xstrdup(options.pkcs11_provider); /* XXX */
1934 #endif /* ENABLE_PKCS11 */
1935 if ((pw = getpwuid(original_real_uid)) == NULL)
1936 fatal("load_public_identity_files: getpwuid failed");
1937 pwname = xstrdup(pw->pw_name);
1938 pwdir = xstrdup(pw->pw_dir);
1939 if (gethostname(thishost, sizeof(thishost)) == -1)
1940 fatal("load_public_identity_files: gethostname: %s",
1942 for (i = 0; i < options.num_identity_files; i++) {
1943 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
1944 strcasecmp(options.identity_files[i], "none") == 0) {
1945 free(options.identity_files[i]);
1948 cp = tilde_expand_filename(options.identity_files[i],
1950 filename = percent_expand(cp, "d", pwdir,
1951 "u", pwname, "l", thishost, "h", host,
1952 "r", options.user, (char *)NULL);
1954 public = key_load_public(filename, NULL);
1955 debug("identity file %s type %d", filename,
1956 public ? public->type : -1);
1957 free(options.identity_files[i]);
1958 identity_files[n_ids] = filename;
1959 identity_keys[n_ids] = public;
1961 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1964 /* Try to add the certificate variant too */
1965 xasprintf(&cp, "%s-cert", filename);
1966 public = key_load_public(cp, NULL);
1967 debug("identity file %s type %d", cp,
1968 public ? public->type : -1);
1969 if (public == NULL) {
1973 if (!key_is_cert(public)) {
1974 debug("%s: key %s type %s is not a certificate",
1975 __func__, cp, key_type(public));
1980 identity_keys[n_ids] = public;
1981 /* point to the original path, most likely the private key */
1982 identity_files[n_ids] = xstrdup(filename);
1985 options.num_identity_files = n_ids;
1986 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1987 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1989 explicit_bzero(pwname, strlen(pwname));
1991 explicit_bzero(pwdir, strlen(pwdir));
1996 main_sigchld_handler(int sig)
1998 int save_errno = errno;
2002 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2003 (pid < 0 && errno == EINTR))
2006 signal(sig, main_sigchld_handler);