1 /* $OpenBSD: ssh.c,v 1.397 2013/12/29 05:42:16 djm Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * Ssh client program. This program can be used to log into a remote machine.
8 * The software supports strong authentication, encryption, and forwarding
9 * of X11, TCP/IP, and authentication connections.
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
17 * Copyright (c) 1999 Niels Provos. All rights reserved.
18 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
20 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
21 * in Canada (German citizen).
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 #include <sys/types.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h>
51 #include <sys/resource.h>
52 #include <sys/ioctl.h>
53 #include <sys/param.h>
54 #include <sys/socket.h>
73 #include <netinet/in.h>
74 #include <arpa/inet.h>
76 #include <openssl/evp.h>
77 #include <openssl/err.h>
78 #include "openbsd-compat/openssl-compat.h"
79 #include "openbsd-compat/sys-queue.h"
94 #include "pathnames.h"
96 #include "clientloop.h"
99 #include "sshconnect.h"
111 #include "ssh-pkcs11.h"
114 extern char *__progname;
116 /* Saves a copy of argv for setproctitle emulation */
117 #ifndef HAVE_SETPROCTITLE
118 static char **saved_av;
121 /* Flag indicating whether debug mode is on. May be set on the command line. */
124 /* Flag indicating whether a tty should be requested */
127 /* don't exec a shell */
128 int no_shell_flag = 0;
131 * Flag indicating that nothing should be read from stdin. This can be set
132 * on the command line.
134 int stdin_null_flag = 0;
137 * Flag indicating that the current process should be backgrounded and
138 * a new slave launched in the foreground for ControlPersist.
140 int need_controlpersist_detach = 0;
142 /* Copies of flags for ControlPersist foreground slave */
143 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
146 * Flag indicating that ssh should fork after authentication. This is useful
147 * so that the passphrase can be entered manually, and then ssh goes to the
150 int fork_after_authentication_flag = 0;
152 /* forward stdio to remote host and port */
153 char *stdio_forward_host = NULL;
154 int stdio_forward_port = 0;
157 * General data structure for command line options and options configurable
158 * in configuration files. See readconf.h.
162 /* optional user configfile */
166 * Name of the host we are connecting to. This is the name given on the
167 * command line, or the HostName specified for the user-supplied name in a
168 * configuration file.
172 /* socket address the host resolves to */
173 struct sockaddr_storage hostaddr;
175 /* Private host keys. */
176 Sensitive sensitive_data;
178 /* Original real UID. */
179 uid_t original_real_uid;
180 uid_t original_effective_uid;
182 /* command to be executed */
185 /* Should we execute a command or invoke a subsystem? */
186 int subsystem_flag = 0;
188 /* # of replies received for global requests */
189 static int remote_forward_confirms_received = 0;
192 extern int muxserver_sock;
193 extern u_int muxclient_command;
195 /* Prints a help message to the user. This function never returns. */
201 "usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
202 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
203 " [-F configfile] [-I pkcs11] [-i identity_file]\n"
204 " [-L [bind_address:]port:host:hostport] [-l login_name] [-m mac_spec]\n"
205 " [-O ctl_cmd] [-o option] [-p port]\n"
206 " [-Q cipher | cipher-auth | mac | kex | key]\n"
207 " [-R [bind_address:]port:host:hostport] [-S ctl_path] [-W host:port]\n"
208 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
213 static int ssh_session(void);
214 static int ssh_session2(void);
215 static void load_public_identity_files(void);
216 static void main_sigchld_handler(int);
218 /* from muxclient.c */
219 void muxclient(const char *);
220 void muxserver_listen(void);
222 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
224 tilde_expand_paths(char **paths, u_int num_paths)
229 for (i = 0; i < num_paths; i++) {
230 cp = tilde_expand_filename(paths[i], original_real_uid);
236 static struct addrinfo *
237 resolve_host(const char *name, u_int port, int logerr, char *cname, size_t clen)
239 char strport[NI_MAXSERV];
240 struct addrinfo hints, *res;
241 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
243 snprintf(strport, sizeof strport, "%u", port);
244 bzero(&hints, sizeof(hints));
245 hints.ai_family = options.address_family;
246 hints.ai_socktype = SOCK_STREAM;
248 hints.ai_flags = AI_CANONNAME;
249 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
250 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
251 loglevel = SYSLOG_LEVEL_ERROR;
252 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
253 __progname, name, ssh_gai_strerror(gaierr));
256 if (cname != NULL && res->ai_canonname != NULL) {
257 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
258 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
259 __func__, name, res->ai_canonname, (u_long)clen);
268 * Check whether the cname is a permitted replacement for the hostname
269 * and perform the replacement if it is.
272 check_follow_cname(char **namep, const char *cname)
275 struct allowed_cname *rule;
277 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
278 strcmp(*namep, cname) == 0)
280 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
283 * Don't attempt to canonicalize names that will be interpreted by
284 * a proxy unless the user specifically requests so.
286 if (options.proxy_command != NULL &&
287 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
289 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
290 for (i = 0; i < options.num_permitted_cnames; i++) {
291 rule = options.permitted_cnames + i;
292 if (match_pattern_list(*namep, rule->source_list,
293 strlen(rule->source_list), 1) != 1 ||
294 match_pattern_list(cname, rule->target_list,
295 strlen(rule->target_list), 1) != 1)
297 verbose("Canonicalized DNS aliased hostname "
298 "\"%s\" => \"%s\"", *namep, cname);
300 *namep = xstrdup(cname);
307 * Attempt to resolve the supplied hostname after applying the user's
308 * canonicalization rules. Returns the address list for the host or NULL
309 * if no name was found after canonicalization.
311 static struct addrinfo *
312 resolve_canonicalize(char **hostp, u_int port)
315 char *cp, *fullhost, cname_target[NI_MAXHOST];
316 struct addrinfo *addrs;
318 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
321 * Don't attempt to canonicalize names that will be interpreted by
322 * a proxy unless the user specifically requests so.
324 if (options.proxy_command != NULL &&
325 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
327 /* Don't apply canonicalization to sufficiently-qualified hostnames */
329 for (cp = *hostp; *cp != '\0'; cp++) {
333 if (ndots > options.canonicalize_max_dots) {
334 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
335 __func__, *hostp, options.canonicalize_max_dots);
338 /* Attempt each supplied suffix */
339 for (i = 0; i < options.num_canonical_domains; i++) {
340 *cname_target = '\0';
341 xasprintf(&fullhost, "%s.%s.", *hostp,
342 options.canonical_domains[i]);
343 if ((addrs = resolve_host(fullhost, options.port, 0,
344 cname_target, sizeof(cname_target))) == NULL) {
348 /* Remove trailing '.' */
349 fullhost[strlen(fullhost) - 1] = '\0';
350 /* Follow CNAME if requested */
351 if (!check_follow_cname(&fullhost, cname_target)) {
352 debug("Canonicalized hostname \"%s\" => \"%s\"",
359 if (!options.canonicalize_fallback_local)
360 fatal("%s: Could not resolve host \"%s\"", __progname, host);
365 * Main program for the ssh client.
368 main(int ac, char **av)
370 int i, r, opt, exit_status, use_syslog;
371 char *p, *cp, *line, *argv0, buf[MAXPATHLEN], *host_arg, *logfile;
372 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
373 char cname[NI_MAXHOST];
377 extern int optind, optreset;
380 struct addrinfo *addrs = NULL;
382 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
385 __progname = ssh_get_progname(av[0]);
387 #ifndef HAVE_SETPROCTITLE
388 /* Prepare for later setproctitle emulation */
389 /* Save argv so it isn't clobbered by setproctitle() emulation */
390 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
391 for (i = 0; i < ac; i++)
392 saved_av[i] = xstrdup(av[i]);
394 compat_init_setproctitle(ac, av);
399 * Discard other fds that are hanging around. These can cause problem
400 * with backgrounded ssh processes started by ControlPersist.
402 closefrom(STDERR_FILENO + 1);
405 * Save the original real uid. It will be needed later (uid-swapping
406 * may clobber the real uid).
408 original_real_uid = getuid();
409 original_effective_uid = geteuid();
412 * Use uid-swapping to give up root privileges for the duration of
413 * option processing. We will re-instantiate the rights when we are
414 * ready to create the privileged port, and will permanently drop
415 * them when the port has been created (actually, when the connection
416 * has been made, as we may need to create the port several times).
420 #ifdef HAVE_SETRLIMIT
421 /* If we are installed setuid root be careful to not drop core. */
422 if (original_real_uid != original_effective_uid) {
424 rlim.rlim_cur = rlim.rlim_max = 0;
425 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
426 fatal("setrlimit failed: %.100s", strerror(errno));
430 pw = getpwuid(original_real_uid);
432 logit("No user exists for uid %lu", (u_long)original_real_uid);
435 /* Take a copy of the returned structure. */
439 * Set our umask to something reasonable, as some files are created
440 * with the default umask. This will make them world-readable but
441 * writable only by the owner, which is ok for all files for which we
442 * don't set the modes explicitly.
447 * Initialize option structure to indicate that no values have been
450 initialize_options(&options);
452 /* Parse command-line arguments. */
459 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
460 "ACD:E:F:I:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
463 options.protocol = SSH_PROTO_1;
466 options.protocol = SSH_PROTO_2;
469 options.address_family = AF_INET;
472 options.address_family = AF_INET6;
478 fork_after_authentication_flag = 1;
482 options.forward_x11 = 0;
485 options.forward_x11 = 1;
491 logfile = xstrdup(optarg);
494 options.forward_x11 = 1;
495 options.forward_x11_trusted = 1;
498 options.gateway_ports = 1;
501 if (stdio_forward_host != NULL)
502 fatal("Cannot specify multiplexing "
504 else if (muxclient_command != 0)
505 fatal("Multiplexing command already specified");
506 if (strcmp(optarg, "check") == 0)
507 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
508 else if (strcmp(optarg, "forward") == 0)
509 muxclient_command = SSHMUX_COMMAND_FORWARD;
510 else if (strcmp(optarg, "exit") == 0)
511 muxclient_command = SSHMUX_COMMAND_TERMINATE;
512 else if (strcmp(optarg, "stop") == 0)
513 muxclient_command = SSHMUX_COMMAND_STOP;
514 else if (strcmp(optarg, "cancel") == 0)
515 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
517 fatal("Invalid multiplex command.");
519 case 'P': /* deprecated */
520 options.use_privileged_port = 0;
524 if (strcmp(optarg, "cipher") == 0)
525 cp = cipher_alg_list('\n', 0);
526 else if (strcmp(optarg, "cipher-auth") == 0)
527 cp = cipher_alg_list('\n', 1);
528 else if (strcmp(optarg, "mac") == 0)
529 cp = mac_alg_list('\n');
530 else if (strcmp(optarg, "kex") == 0)
531 cp = kex_alg_list('\n');
532 else if (strcmp(optarg, "key") == 0)
533 cp = key_alg_list(0, 0);
534 else if (strcmp(optarg, "key-cert") == 0)
535 cp = key_alg_list(1, 0);
536 else if (strcmp(optarg, "key-plain") == 0)
537 cp = key_alg_list(0, 1);
539 fatal("Unsupported query \"%s\"", optarg);
545 options.forward_agent = 0;
548 options.forward_agent = 1;
551 options.gss_deleg_creds = 0;
554 options.gss_authentication = 1;
555 options.gss_deleg_creds = 1;
558 if (stat(optarg, &st) < 0) {
559 fprintf(stderr, "Warning: Identity file %s "
560 "not accessible: %s.\n", optarg,
564 add_identity_file(&options, NULL, optarg, 1);
568 options.pkcs11_provider = xstrdup(optarg);
570 fprintf(stderr, "no support for PKCS#11.\n");
574 if (options.request_tty == REQUEST_TTY_YES)
575 options.request_tty = REQUEST_TTY_FORCE;
577 options.request_tty = REQUEST_TTY_YES;
580 if (debug_flag == 0) {
582 options.log_level = SYSLOG_LEVEL_DEBUG1;
584 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
589 if (options.version_addendum &&
590 *options.version_addendum != '\0')
591 fprintf(stderr, "%s%s %s, %s\n", SSH_RELEASE,
592 options.hpn_disabled ? "" : SSH_VERSION_HPN,
593 options.version_addendum,
594 SSLeay_version(SSLEAY_VERSION));
596 fprintf(stderr, "%s%s, %s\n", SSH_RELEASE,
597 options.hpn_disabled ? "" : SSH_VERSION_HPN,
598 SSLeay_version(SSLEAY_VERSION));
603 if (options.tun_open == -1)
604 options.tun_open = SSH_TUNMODE_DEFAULT;
605 options.tun_local = a2tun(optarg, &options.tun_remote);
606 if (options.tun_local == SSH_TUNID_ERR) {
608 "Bad tun device '%s'\n", optarg);
613 if (stdio_forward_host != NULL)
614 fatal("stdio forward already specified");
615 if (muxclient_command != 0)
616 fatal("Cannot specify stdio forward with -O");
617 if (parse_forward(&fwd, optarg, 1, 0)) {
618 stdio_forward_host = fwd.listen_host;
619 stdio_forward_port = fwd.listen_port;
620 free(fwd.connect_host);
623 "Bad stdio forwarding specification '%s'\n",
627 options.request_tty = REQUEST_TTY_NO;
629 options.clear_forwardings = 1;
630 options.exit_on_forward_failure = 1;
633 options.log_level = SYSLOG_LEVEL_QUIET;
636 if (optarg[0] == '^' && optarg[2] == 0 &&
637 (u_char) optarg[1] >= 64 &&
638 (u_char) optarg[1] < 128)
639 options.escape_char = (u_char) optarg[1] & 31;
640 else if (strlen(optarg) == 1)
641 options.escape_char = (u_char) optarg[0];
642 else if (strcmp(optarg, "none") == 0)
643 options.escape_char = SSH_ESCAPECHAR_NONE;
645 fprintf(stderr, "Bad escape character '%s'.\n",
651 if (ciphers_valid(optarg)) {
653 options.ciphers = xstrdup(optarg);
654 options.cipher = SSH_CIPHER_INVALID;
657 options.cipher = cipher_number(optarg);
658 if (options.cipher == -1) {
660 "Unknown cipher type '%s'\n",
664 if (options.cipher == SSH_CIPHER_3DES)
665 options.ciphers = "3des-cbc";
666 else if (options.cipher == SSH_CIPHER_BLOWFISH)
667 options.ciphers = "blowfish-cbc";
669 options.ciphers = (char *)-1;
673 if (mac_valid(optarg))
674 options.macs = xstrdup(optarg);
676 fprintf(stderr, "Unknown mac type '%s'\n",
682 if (options.control_master == SSHCTL_MASTER_YES)
683 options.control_master = SSHCTL_MASTER_ASK;
685 options.control_master = SSHCTL_MASTER_YES;
688 options.port = a2port(optarg);
689 if (options.port <= 0) {
690 fprintf(stderr, "Bad port '%s'\n", optarg);
695 options.user = optarg;
699 if (parse_forward(&fwd, optarg, 0, 0))
700 add_local_forward(&options, &fwd);
703 "Bad local forwarding specification '%s'\n",
710 if (parse_forward(&fwd, optarg, 0, 1)) {
711 add_remote_forward(&options, &fwd);
714 "Bad remote forwarding specification "
721 if (parse_forward(&fwd, optarg, 1, 0)) {
722 add_local_forward(&options, &fwd);
725 "Bad dynamic forwarding specification "
732 options.compression = 1;
736 options.request_tty = REQUEST_TTY_NO;
739 options.request_tty = REQUEST_TTY_NO;
740 #ifdef NONE_CIPHER_ENABLED
742 * Ensure that the user does not try to backdoor a
743 * NONE cipher switch on an interactive session by
744 * explicitly disabling it if the user asks for a
745 * session without a tty.
747 options.none_switch = 0;
751 line = xstrdup(optarg);
752 if (process_config_line(&options, pw, host ? host : "",
753 line, "command-line", 0, NULL, SSHCONF_USERCONF)
762 if (options.control_path != NULL)
763 free(options.control_path);
764 options.control_path = xstrdup(optarg);
767 options.bind_address = optarg;
780 if (ac > 0 && !host) {
781 if (strrchr(*av, '@')) {
783 cp = strrchr(p, '@');
784 if (cp == NULL || cp == p)
788 host = xstrdup(++cp);
792 optind = optreset = 1;
798 /* Check that we got a host name. */
803 host_arg = xstrdup(host);
805 OpenSSL_add_all_algorithms();
806 ERR_load_crypto_strings();
808 /* Initialize the command to execute on remote host. */
809 buffer_init(&command);
812 * Save the command to execute on the remote host in a buffer. There
813 * is no limit on the length of the command, except by the maximum
814 * packet size. Also sets the tty flag if there is no command.
817 /* No command specified - execute shell on a tty. */
818 if (subsystem_flag) {
820 "You must specify a subsystem to invoke.\n");
824 /* A command has been specified. Store it into the buffer. */
825 for (i = 0; i < ac; i++) {
827 buffer_append(&command, " ", 1);
828 buffer_append(&command, av[i], strlen(av[i]));
832 /* Cannot fork to background if no command. */
833 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
835 fatal("Cannot fork into background without a command "
839 * Initialize "log" output. Since we are the client all output
840 * goes to stderr unless otherwise specified by -y or -E.
842 if (use_syslog && logfile != NULL)
843 fatal("Can't specify both -y and -E");
844 if (logfile != NULL) {
845 log_redirect_stderr_to(logfile);
849 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
850 SYSLOG_FACILITY_USER, !use_syslog);
853 logit("%s, %s", SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
856 * Read per-user configuration file. Ignore the system wide config
857 * file if the user specifies a config file on the command line.
859 if (config != NULL) {
860 if (strcasecmp(config, "none") != 0 &&
861 !read_config_file(config, pw, host, &options,
863 fatal("Can't open user config file %.100s: "
864 "%.100s", config, strerror(errno));
866 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
867 _PATH_SSH_USER_CONFFILE);
868 if (r > 0 && (size_t)r < sizeof(buf))
869 (void)read_config_file(buf, pw, host, &options,
870 SSHCONF_CHECKPERM|SSHCONF_USERCONF);
872 /* Read systemwide configuration file after user config. */
873 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, host,
877 /* Fill configuration defaults. */
878 fill_default_options(&options);
880 channel_set_af(options.address_family);
882 /* Tidy and check options */
883 if (options.host_key_alias != NULL)
884 lowercase(options.host_key_alias);
885 if (options.proxy_command != NULL &&
886 strcmp(options.proxy_command, "-") == 0 &&
887 options.proxy_use_fdpass)
888 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
890 if (original_effective_uid != 0)
891 options.use_privileged_port = 0;
895 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
897 if (options.request_tty == REQUEST_TTY_YES ||
898 options.request_tty == REQUEST_TTY_FORCE)
901 /* Allocate a tty by default if no command specified. */
902 if (buffer_len(&command) == 0)
903 tty_flag = options.request_tty != REQUEST_TTY_NO;
906 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
908 /* Do not allocate a tty if stdin is not a tty. */
909 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
910 options.request_tty != REQUEST_TTY_FORCE) {
912 logit("Pseudo-terminal will not be allocated because "
913 "stdin is not a terminal.");
919 if (options.user == NULL)
920 options.user = xstrdup(pw->pw_name);
922 /* Get default port if port has not been set. */
923 if (options.port == 0)
924 options.port = default_ssh_port();
926 /* preserve host name given on command line for %n expansion */
927 if (options.hostname != NULL) {
928 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
929 cp = percent_expand(options.hostname,
930 "h", host, (char *)NULL);
935 /* If canonicalization requested then try to apply it */
936 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
937 addrs = resolve_canonicalize(&host, options.port);
939 * If canonicalization not requested, or if it failed then try to
940 * resolve the bare hostname name using the system resolver's usual
941 * search rules. Skip the lookup if a ProxyCommand is being used
942 * unless the user has specifically requested canonicalisation.
944 if (addrs == NULL && (options.proxy_command == NULL ||
945 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
946 if ((addrs = resolve_host(host, options.port, 1,
947 cname, sizeof(cname))) == NULL)
948 cleanup_exit(255); /* resolve_host logs the error */
949 check_follow_cname(&host, cname);
952 if (gethostname(thishost, sizeof(thishost)) == -1)
953 fatal("gethostname: %s", strerror(errno));
954 strlcpy(shorthost, thishost, sizeof(shorthost));
955 shorthost[strcspn(thishost, ".")] = '\0';
956 snprintf(portstr, sizeof(portstr), "%d", options.port);
958 if (options.local_command != NULL) {
959 debug3("expanding LocalCommand: %s", options.local_command);
960 cp = options.local_command;
961 options.local_command = percent_expand(cp, "d", pw->pw_dir,
962 "h", host, "l", thishost, "n", host_arg, "r", options.user,
963 "p", portstr, "u", pw->pw_name, "L", shorthost,
965 debug3("expanded LocalCommand: %s", options.local_command);
969 if (options.control_path != NULL) {
970 cp = tilde_expand_filename(options.control_path,
972 free(options.control_path);
973 options.control_path = percent_expand(cp, "h", host,
974 "l", thishost, "n", host_arg, "r", options.user,
975 "p", portstr, "u", pw->pw_name, "L", shorthost,
979 if (muxclient_command != 0 && options.control_path == NULL)
980 fatal("No ControlPath specified for \"-O\" command");
981 if (options.control_path != NULL)
982 muxclient(options.control_path);
984 timeout_ms = options.connection_timeout * 1000;
986 /* Open a connection to the remote host. */
987 if (ssh_connect(host, addrs, &hostaddr, options.port,
988 options.address_family, options.connection_attempts,
989 &timeout_ms, options.tcp_keep_alive,
990 options.use_privileged_port) != 0)
996 packet_set_timeout(options.server_alive_interval,
997 options.server_alive_count_max);
1000 debug3("timeout: %d ms remain after connect", timeout_ms);
1003 * If we successfully made the connection, load the host private key
1004 * in case we will need it later for combined rsa-rhosts
1005 * authentication. This must be done before releasing extra
1006 * privileges, because the file is only readable by root.
1007 * If we cannot access the private keys, load the public keys
1008 * instead and try to execute the ssh-keysign helper instead.
1010 sensitive_data.nkeys = 0;
1011 sensitive_data.keys = NULL;
1012 sensitive_data.external_keysign = 0;
1013 if (options.rhosts_rsa_authentication ||
1014 options.hostbased_authentication) {
1015 sensitive_data.nkeys = 9;
1016 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1018 for (i = 0; i < sensitive_data.nkeys; i++)
1019 sensitive_data.keys[i] = NULL;
1022 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1023 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1024 sensitive_data.keys[1] = key_load_private_cert(KEY_DSA,
1025 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1026 #ifdef OPENSSL_HAS_ECC
1027 sensitive_data.keys[2] = key_load_private_cert(KEY_ECDSA,
1028 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1030 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1031 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1032 sensitive_data.keys[4] = key_load_private_cert(KEY_ED25519,
1033 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1034 sensitive_data.keys[5] = key_load_private_type(KEY_DSA,
1035 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1036 #ifdef OPENSSL_HAS_ECC
1037 sensitive_data.keys[6] = key_load_private_type(KEY_ECDSA,
1038 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1040 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1041 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1042 sensitive_data.keys[8] = key_load_private_type(KEY_ED25519,
1043 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1046 if (options.hostbased_authentication == 1 &&
1047 sensitive_data.keys[0] == NULL &&
1048 sensitive_data.keys[5] == NULL &&
1049 sensitive_data.keys[6] == NULL &&
1050 sensitive_data.keys[7] == NULL &&
1051 sensitive_data.keys[8] == NULL) {
1052 sensitive_data.keys[1] = key_load_cert(
1053 _PATH_HOST_DSA_KEY_FILE);
1054 #ifdef OPENSSL_HAS_ECC
1055 sensitive_data.keys[2] = key_load_cert(
1056 _PATH_HOST_ECDSA_KEY_FILE);
1058 sensitive_data.keys[3] = key_load_cert(
1059 _PATH_HOST_RSA_KEY_FILE);
1060 sensitive_data.keys[4] = key_load_cert(
1061 _PATH_HOST_ED25519_KEY_FILE);
1062 sensitive_data.keys[5] = key_load_public(
1063 _PATH_HOST_DSA_KEY_FILE, NULL);
1064 #ifdef OPENSSL_HAS_ECC
1065 sensitive_data.keys[6] = key_load_public(
1066 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1068 sensitive_data.keys[7] = key_load_public(
1069 _PATH_HOST_RSA_KEY_FILE, NULL);
1070 sensitive_data.keys[8] = key_load_public(
1071 _PATH_HOST_ED25519_KEY_FILE, NULL);
1072 sensitive_data.external_keysign = 1;
1076 * Get rid of any extra privileges that we may have. We will no
1077 * longer need them. Also, extra privileges could make it very hard
1078 * to read identity files and other non-world-readable files from the
1079 * user's home directory if it happens to be on a NFS volume where
1080 * root is mapped to nobody.
1082 if (original_effective_uid == 0) {
1084 permanently_set_uid(pw);
1088 * Now that we are back to our own permissions, create ~/.ssh
1089 * directory if it doesn't already exist.
1091 if (config == NULL) {
1092 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1093 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1094 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1096 ssh_selinux_setfscreatecon(buf);
1098 if (mkdir(buf, 0700) < 0)
1099 error("Could not create directory '%.200s'.",
1102 ssh_selinux_setfscreatecon(NULL);
1106 /* load options.identity_files */
1107 load_public_identity_files();
1109 /* Expand ~ in known host file names. */
1110 tilde_expand_paths(options.system_hostfiles,
1111 options.num_system_hostfiles);
1112 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1114 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1115 signal(SIGCHLD, main_sigchld_handler);
1117 /* Log into the remote system. Never returns if the login fails. */
1118 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1119 options.port, pw, timeout_ms);
1121 if (packet_connection_is_on_socket()) {
1122 verbose("Authenticated to %s ([%s]:%d).", host,
1123 get_remote_ipaddr(), get_remote_port());
1125 verbose("Authenticated to %s (via proxy).", host);
1128 /* We no longer need the private host keys. Clear them now. */
1129 if (sensitive_data.nkeys != 0) {
1130 for (i = 0; i < sensitive_data.nkeys; i++) {
1131 if (sensitive_data.keys[i] != NULL) {
1132 /* Destroys contents safely */
1133 debug3("clear hostkey %d", i);
1134 key_free(sensitive_data.keys[i]);
1135 sensitive_data.keys[i] = NULL;
1138 free(sensitive_data.keys);
1140 for (i = 0; i < options.num_identity_files; i++) {
1141 free(options.identity_files[i]);
1142 options.identity_files[i] = NULL;
1143 if (options.identity_keys[i]) {
1144 key_free(options.identity_keys[i]);
1145 options.identity_keys[i] = NULL;
1149 exit_status = compat20 ? ssh_session2() : ssh_session();
1152 if (options.control_path != NULL && muxserver_sock != -1)
1153 unlink(options.control_path);
1155 /* Kill ProxyCommand if it is running. */
1156 ssh_kill_proxy_command();
1162 control_persist_detach(void)
1167 debug("%s: backgrounding master process", __func__);
1170 * master (current process) into the background, and make the
1171 * foreground process a client of the backgrounded master.
1173 switch ((pid = fork())) {
1175 fatal("%s: fork: %s", __func__, strerror(errno));
1177 /* Child: master process continues mainloop */
1180 /* Parent: set up mux slave to connect to backgrounded master */
1181 debug2("%s: background process is %ld", __func__, (long)pid);
1182 stdin_null_flag = ostdin_null_flag;
1183 options.request_tty = orequest_tty;
1184 tty_flag = otty_flag;
1185 close(muxserver_sock);
1186 muxserver_sock = -1;
1187 options.control_master = SSHCTL_MASTER_NO;
1188 muxclient(options.control_path);
1189 /* muxclient() doesn't return on success. */
1190 fatal("Failed to connect to new control master");
1192 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1193 error("%s: open(\"/dev/null\"): %s", __func__,
1196 if (dup2(devnull, STDIN_FILENO) == -1 ||
1197 dup2(devnull, STDOUT_FILENO) == -1)
1198 error("%s: dup2: %s", __func__, strerror(errno));
1199 if (devnull > STDERR_FILENO)
1203 setproctitle("%s [mux]", options.control_path);
1206 /* Do fork() after authentication. Used by "ssh -f" */
1210 if (need_controlpersist_detach)
1211 control_persist_detach();
1212 debug("forking to background");
1213 fork_after_authentication_flag = 0;
1214 if (daemon(1, 1) < 0)
1215 fatal("daemon() failed: %.200s", strerror(errno));
1218 /* Callback for remote forward global requests */
1220 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1222 Forward *rfwd = (Forward *)ctxt;
1224 /* XXX verbose() on failure? */
1225 debug("remote forward %s for: listen %d, connect %s:%d",
1226 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1227 rfwd->listen_port, rfwd->connect_host, rfwd->connect_port);
1228 if (rfwd->listen_port == 0) {
1229 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1230 rfwd->allocated_port = packet_get_int();
1231 logit("Allocated port %u for remote forward to %s:%d",
1232 rfwd->allocated_port,
1233 rfwd->connect_host, rfwd->connect_port);
1234 channel_update_permitted_opens(rfwd->handle,
1235 rfwd->allocated_port);
1237 channel_update_permitted_opens(rfwd->handle, -1);
1241 if (type == SSH2_MSG_REQUEST_FAILURE) {
1242 if (options.exit_on_forward_failure)
1243 fatal("Error: remote port forwarding failed for "
1244 "listen port %d", rfwd->listen_port);
1246 logit("Warning: remote port forwarding failed for "
1247 "listen port %d", rfwd->listen_port);
1249 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1250 debug("All remote forwarding requests processed");
1251 if (fork_after_authentication_flag)
1257 client_cleanup_stdio_fwd(int id, void *arg)
1259 debug("stdio forwarding: done");
1264 ssh_init_stdio_forwarding(void)
1269 if (stdio_forward_host == NULL)
1272 fatal("stdio forwarding require Protocol 2");
1274 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1276 if ((in = dup(STDIN_FILENO)) < 0 ||
1277 (out = dup(STDOUT_FILENO)) < 0)
1278 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1279 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1280 stdio_forward_port, in, out)) == NULL)
1281 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1282 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1286 ssh_init_forwarding(void)
1291 /* Initiate local TCP/IP port forwardings. */
1292 for (i = 0; i < options.num_local_forwards; i++) {
1293 debug("Local connections to %.200s:%d forwarded to remote "
1294 "address %.200s:%d",
1295 (options.local_forwards[i].listen_host == NULL) ?
1296 (options.gateway_ports ? "*" : "LOCALHOST") :
1297 options.local_forwards[i].listen_host,
1298 options.local_forwards[i].listen_port,
1299 options.local_forwards[i].connect_host,
1300 options.local_forwards[i].connect_port);
1301 success += channel_setup_local_fwd_listener(
1302 options.local_forwards[i].listen_host,
1303 options.local_forwards[i].listen_port,
1304 options.local_forwards[i].connect_host,
1305 options.local_forwards[i].connect_port,
1306 options.gateway_ports);
1308 if (i > 0 && success != i && options.exit_on_forward_failure)
1309 fatal("Could not request local forwarding.");
1310 if (i > 0 && success == 0)
1311 error("Could not request local forwarding.");
1313 /* Initiate remote TCP/IP port forwardings. */
1314 for (i = 0; i < options.num_remote_forwards; i++) {
1315 debug("Remote connections from %.200s:%d forwarded to "
1316 "local address %.200s:%d",
1317 (options.remote_forwards[i].listen_host == NULL) ?
1318 "LOCALHOST" : options.remote_forwards[i].listen_host,
1319 options.remote_forwards[i].listen_port,
1320 options.remote_forwards[i].connect_host,
1321 options.remote_forwards[i].connect_port);
1322 options.remote_forwards[i].handle =
1323 channel_request_remote_forwarding(
1324 options.remote_forwards[i].listen_host,
1325 options.remote_forwards[i].listen_port,
1326 options.remote_forwards[i].connect_host,
1327 options.remote_forwards[i].connect_port);
1328 if (options.remote_forwards[i].handle < 0) {
1329 if (options.exit_on_forward_failure)
1330 fatal("Could not request remote forwarding.");
1332 logit("Warning: Could not request remote "
1335 client_register_global_confirm(ssh_confirm_remote_forward,
1336 &options.remote_forwards[i]);
1340 /* Initiate tunnel forwarding. */
1341 if (options.tun_open != SSH_TUNMODE_NO) {
1342 if (client_request_tun_fwd(options.tun_open,
1343 options.tun_local, options.tun_remote) == -1) {
1344 if (options.exit_on_forward_failure)
1345 fatal("Could not request tunnel forwarding.");
1347 error("Could not request tunnel forwarding.");
1353 check_agent_present(void)
1355 if (options.forward_agent) {
1356 /* Clear agent forwarding if we don't have an agent. */
1357 if (!ssh_agent_present())
1358 options.forward_agent = 0;
1366 int interactive = 0;
1370 const char *display;
1372 /* Enable compression if requested. */
1373 if (options.compression) {
1374 debug("Requesting compression at level %d.",
1375 options.compression_level);
1377 if (options.compression_level < 1 ||
1378 options.compression_level > 9)
1379 fatal("Compression level must be from 1 (fast) to "
1382 /* Send the request. */
1383 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1384 packet_put_int(options.compression_level);
1386 packet_write_wait();
1387 type = packet_read();
1388 if (type == SSH_SMSG_SUCCESS)
1389 packet_start_compression(options.compression_level);
1390 else if (type == SSH_SMSG_FAILURE)
1391 logit("Warning: Remote host refused compression.");
1393 packet_disconnect("Protocol error waiting for "
1394 "compression response.");
1396 /* Allocate a pseudo tty if appropriate. */
1398 debug("Requesting pty.");
1400 /* Start the packet. */
1401 packet_start(SSH_CMSG_REQUEST_PTY);
1403 /* Store TERM in the packet. There is no limit on the
1404 length of the string. */
1405 cp = getenv("TERM");
1408 packet_put_cstring(cp);
1410 /* Store window size in the packet. */
1411 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1412 memset(&ws, 0, sizeof(ws));
1413 packet_put_int((u_int)ws.ws_row);
1414 packet_put_int((u_int)ws.ws_col);
1415 packet_put_int((u_int)ws.ws_xpixel);
1416 packet_put_int((u_int)ws.ws_ypixel);
1418 /* Store tty modes in the packet. */
1419 tty_make_modes(fileno(stdin), NULL);
1421 /* Send the packet, and wait for it to leave. */
1423 packet_write_wait();
1425 /* Read response from the server. */
1426 type = packet_read();
1427 if (type == SSH_SMSG_SUCCESS) {
1430 } else if (type == SSH_SMSG_FAILURE)
1431 logit("Warning: Remote host failed or refused to "
1432 "allocate a pseudo tty.");
1434 packet_disconnect("Protocol error waiting for pty "
1435 "request response.");
1437 /* Request X11 forwarding if enabled and DISPLAY is set. */
1438 display = getenv("DISPLAY");
1439 if (options.forward_x11 && display != NULL) {
1441 /* Get reasonable local authentication information. */
1442 client_x11_get_proto(display, options.xauth_location,
1443 options.forward_x11_trusted,
1444 options.forward_x11_timeout,
1446 /* Request forwarding with authentication spoofing. */
1447 debug("Requesting X11 forwarding with authentication "
1449 x11_request_forwarding_with_spoofing(0, display, proto,
1451 /* Read response from the server. */
1452 type = packet_read();
1453 if (type == SSH_SMSG_SUCCESS) {
1455 } else if (type == SSH_SMSG_FAILURE) {
1456 logit("Warning: Remote host denied X11 forwarding.");
1458 packet_disconnect("Protocol error waiting for X11 "
1462 /* Tell the packet module whether this is an interactive session. */
1463 packet_set_interactive(interactive,
1464 options.ip_qos_interactive, options.ip_qos_bulk);
1466 /* Request authentication agent forwarding if appropriate. */
1467 check_agent_present();
1469 if (options.forward_agent) {
1470 debug("Requesting authentication agent forwarding.");
1471 auth_request_forwarding();
1473 /* Read response from the server. */
1474 type = packet_read();
1476 if (type != SSH_SMSG_SUCCESS)
1477 logit("Warning: Remote host denied authentication agent forwarding.");
1480 /* Initiate port forwardings. */
1481 ssh_init_stdio_forwarding();
1482 ssh_init_forwarding();
1484 /* Execute a local command */
1485 if (options.local_command != NULL &&
1486 options.permit_local_command)
1487 ssh_local_cmd(options.local_command);
1490 * If requested and we are not interested in replies to remote
1491 * forwarding requests, then let ssh continue in the background.
1493 if (fork_after_authentication_flag) {
1494 if (options.exit_on_forward_failure &&
1495 options.num_remote_forwards > 0) {
1496 debug("deferring postauth fork until remote forward "
1497 "confirmation received");
1503 * If a command was specified on the command line, execute the
1504 * command now. Otherwise request the server to start a shell.
1506 if (buffer_len(&command) > 0) {
1507 int len = buffer_len(&command);
1510 debug("Sending command: %.*s", len,
1511 (u_char *)buffer_ptr(&command));
1512 packet_start(SSH_CMSG_EXEC_CMD);
1513 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1515 packet_write_wait();
1517 debug("Requesting shell.");
1518 packet_start(SSH_CMSG_EXEC_SHELL);
1520 packet_write_wait();
1523 /* Enter the interactive session. */
1524 return client_loop(have_tty, tty_flag ?
1525 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1528 /* request pty/x11/agent/tcpfwd/shell for channel */
1530 ssh_session2_setup(int id, int success, void *arg)
1532 extern char **environ;
1533 const char *display;
1534 int interactive = tty_flag;
1537 return; /* No need for error message, channels code sens one */
1539 display = getenv("DISPLAY");
1540 if (options.forward_x11 && display != NULL) {
1542 /* Get reasonable local authentication information. */
1543 client_x11_get_proto(display, options.xauth_location,
1544 options.forward_x11_trusted,
1545 options.forward_x11_timeout, &proto, &data);
1546 /* Request forwarding with authentication spoofing. */
1547 debug("Requesting X11 forwarding with authentication "
1549 x11_request_forwarding_with_spoofing(id, display, proto,
1551 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1552 /* XXX exit_on_forward_failure */
1556 check_agent_present();
1557 if (options.forward_agent) {
1558 debug("Requesting authentication agent forwarding.");
1559 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1563 /* Tell the packet module whether this is an interactive session. */
1564 packet_set_interactive(interactive,
1565 options.ip_qos_interactive, options.ip_qos_bulk);
1567 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1568 NULL, fileno(stdin), &command, environ);
1571 /* open new channel for a session */
1573 ssh_session2_open(void)
1576 int window, packetmax, in, out, err;
1578 if (stdin_null_flag) {
1579 in = open(_PATH_DEVNULL, O_RDONLY);
1581 in = dup(STDIN_FILENO);
1583 out = dup(STDOUT_FILENO);
1584 err = dup(STDERR_FILENO);
1586 if (in < 0 || out < 0 || err < 0)
1587 fatal("dup() in/out/err failed");
1589 /* enable nonblocking unless tty */
1598 * We need to check to see what to do about buffer sizes here.
1599 * - In an HPN to non-HPN connection we want to limit the window size to
1600 * something reasonable in case the far side has the large window bug.
1601 * - In an HPN to HPN connection we want to use the max window size but
1602 * allow the user to override it.
1603 * - Lastly if HPN is disabled then use the ssh standard window size.
1605 * We cannot just do a getsockopt() here and set the ssh window to that
1606 * as in case of autotuning of socket buffers the window would get stuck
1607 * at the initial buffer size, generally less than 96k. Therefore we
1608 * need to set the maximum ssh window size to the maximum HPN buffer
1609 * size unless the user has set TcpRcvBufPoll to no. In that case we
1610 * can just set the window to the minimum of HPN buffer size and TCP
1611 * receive buffer size.
1614 options.hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
1616 options.hpn_buffer_size = CHAN_HPN_MIN_WINDOW_DEFAULT;
1618 if (datafellows & SSH_BUG_LARGEWINDOW) {
1619 debug("HPN to Non-HPN Connection");
1620 } else if (options.tcp_rcv_buf_poll <= 0) {
1621 sock_get_rcvbuf(&options.hpn_buffer_size, 0);
1622 debug("HPNBufferSize set to TCP RWIN: %d",
1623 options.hpn_buffer_size);
1624 } else if (options.tcp_rcv_buf > 0) {
1625 sock_get_rcvbuf(&options.hpn_buffer_size,
1626 options.tcp_rcv_buf);
1627 debug("HPNBufferSize set to user TCPRcvBuf: %d",
1628 options.hpn_buffer_size);
1630 debug("Final hpn_buffer_size = %d", options.hpn_buffer_size);
1631 channel_set_hpn(options.hpn_disabled, options.hpn_buffer_size);
1632 window = options.hpn_buffer_size;
1634 packetmax = CHAN_SES_PACKET_DEFAULT;
1636 window = CHAN_SES_WINDOW_DEFAULT;
1641 "session", SSH_CHANNEL_OPENING, in, out, err,
1642 window, packetmax, CHAN_EXTENDED_WRITE,
1643 "client-session", /*nonblock*/0);
1644 if (!options.hpn_disabled && options.tcp_rcv_buf_poll > 0) {
1645 c->dynamic_window = 1;
1646 debug("Enabled Dynamic Window Scaling\n");
1649 debug3("ssh_session2_open: channel_new: %d", c->self);
1651 channel_send_open(c->self);
1653 channel_register_open_confirm(c->self,
1654 ssh_session2_setup, NULL);
1664 /* XXX should be pre-session */
1665 if (!options.control_persist)
1666 ssh_init_stdio_forwarding();
1667 ssh_init_forwarding();
1669 /* Start listening for multiplex clients */
1673 * If we are in control persist mode and have a working mux listen
1674 * socket, then prepare to background ourselves and have a foreground
1675 * client attach as a control slave.
1676 * NB. we must save copies of the flags that we override for
1677 * the backgrounding, since we defer attachment of the slave until
1678 * after the connection is fully established (in particular,
1679 * async rfwd replies have been received for ExitOnForwardFailure).
1681 if (options.control_persist && muxserver_sock != -1) {
1682 ostdin_null_flag = stdin_null_flag;
1683 ono_shell_flag = no_shell_flag;
1684 orequest_tty = options.request_tty;
1685 otty_flag = tty_flag;
1686 stdin_null_flag = 1;
1689 if (!fork_after_authentication_flag)
1690 need_controlpersist_detach = 1;
1691 fork_after_authentication_flag = 1;
1694 * ControlPersist mux listen socket setup failed, attempt the
1695 * stdio forward setup that we skipped earlier.
1697 if (options.control_persist && muxserver_sock == -1)
1698 ssh_init_stdio_forwarding();
1700 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1701 id = ssh_session2_open();
1703 packet_set_interactive(
1704 options.control_master == SSHCTL_MASTER_NO,
1705 options.ip_qos_interactive, options.ip_qos_bulk);
1708 /* If we don't expect to open a new session, then disallow it */
1709 if (options.control_master == SSHCTL_MASTER_NO &&
1710 (datafellows & SSH_NEW_OPENSSH)) {
1711 debug("Requesting no-more-sessions@openssh.com");
1712 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1713 packet_put_cstring("no-more-sessions@openssh.com");
1718 /* Execute a local command */
1719 if (options.local_command != NULL &&
1720 options.permit_local_command)
1721 ssh_local_cmd(options.local_command);
1724 * If requested and we are not interested in replies to remote
1725 * forwarding requests, then let ssh continue in the background.
1727 if (fork_after_authentication_flag) {
1728 if (options.exit_on_forward_failure &&
1729 options.num_remote_forwards > 0) {
1730 debug("deferring postauth fork until remote forward "
1731 "confirmation received");
1736 if (options.use_roaming)
1739 return client_loop(tty_flag, tty_flag ?
1740 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1744 load_public_identity_files(void)
1746 char *filename, *cp, thishost[NI_MAXHOST];
1747 char *pwdir = NULL, *pwname = NULL;
1752 char *identity_files[SSH_MAX_IDENTITY_FILES];
1753 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1754 #ifdef ENABLE_PKCS11
1760 bzero(identity_files, sizeof(identity_files));
1761 bzero(identity_keys, sizeof(identity_keys));
1763 #ifdef ENABLE_PKCS11
1764 if (options.pkcs11_provider != NULL &&
1765 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1766 (pkcs11_init(!options.batch_mode) == 0) &&
1767 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1769 for (i = 0; i < nkeys; i++) {
1770 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1774 identity_keys[n_ids] = keys[i];
1775 identity_files[n_ids] =
1776 xstrdup(options.pkcs11_provider); /* XXX */
1781 #endif /* ENABLE_PKCS11 */
1782 if ((pw = getpwuid(original_real_uid)) == NULL)
1783 fatal("load_public_identity_files: getpwuid failed");
1784 pwname = xstrdup(pw->pw_name);
1785 pwdir = xstrdup(pw->pw_dir);
1786 if (gethostname(thishost, sizeof(thishost)) == -1)
1787 fatal("load_public_identity_files: gethostname: %s",
1789 for (i = 0; i < options.num_identity_files; i++) {
1790 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
1791 strcasecmp(options.identity_files[i], "none") == 0) {
1792 free(options.identity_files[i]);
1795 cp = tilde_expand_filename(options.identity_files[i],
1797 filename = percent_expand(cp, "d", pwdir,
1798 "u", pwname, "l", thishost, "h", host,
1799 "r", options.user, (char *)NULL);
1801 public = key_load_public(filename, NULL);
1802 debug("identity file %s type %d", filename,
1803 public ? public->type : -1);
1804 free(options.identity_files[i]);
1805 identity_files[n_ids] = filename;
1806 identity_keys[n_ids] = public;
1808 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
1811 /* Try to add the certificate variant too */
1812 xasprintf(&cp, "%s-cert", filename);
1813 public = key_load_public(cp, NULL);
1814 debug("identity file %s type %d", cp,
1815 public ? public->type : -1);
1816 if (public == NULL) {
1820 if (!key_is_cert(public)) {
1821 debug("%s: key %s type %s is not a certificate",
1822 __func__, cp, key_type(public));
1827 identity_keys[n_ids] = public;
1828 /* point to the original path, most likely the private key */
1829 identity_files[n_ids] = xstrdup(filename);
1832 options.num_identity_files = n_ids;
1833 memcpy(options.identity_files, identity_files, sizeof(identity_files));
1834 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
1836 bzero(pwname, strlen(pwname));
1838 bzero(pwdir, strlen(pwdir));
1843 main_sigchld_handler(int sig)
1845 int save_errno = errno;
1849 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
1850 (pid < 0 && errno == EINTR))
1853 signal(sig, main_sigchld_handler);