1 /* $OpenBSD: ssh.c,v 1.420 2015/07/30 00:01:34 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * Ssh client program. This program can be used to log into a remote machine.
7 * The software supports strong authentication, encryption, and forwarding
8 * of X11, TCP/IP, and authentication connections.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Niels Provos. All rights reserved.
17 * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl. All rights reserved.
19 * Modified to work with SSL by Niels Provos <provos@citi.umich.edu>
20 * in Canada (German citizen).
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_STAT_H
48 # include <sys/stat.h>
50 #include <sys/resource.h>
51 #include <sys/ioctl.h>
52 #include <sys/socket.h>
72 #include <netinet/in.h>
73 #include <arpa/inet.h>
76 #include <openssl/evp.h>
77 #include <openssl/err.h>
79 #include "openbsd-compat/openssl-compat.h"
80 #include "openbsd-compat/sys-queue.h"
96 #include "pathnames.h"
98 #include "clientloop.h"
101 #include "readconf.h"
102 #include "sshconnect.h"
112 #include "myproposal.h"
115 #include "ssh-pkcs11.h"
118 extern char *__progname;
120 /* Saves a copy of argv for setproctitle emulation */
121 #ifndef HAVE_SETPROCTITLE
122 static char **saved_av;
125 /* Flag indicating whether debug mode is on. May be set on the command line. */
128 /* Flag indicating whether a tty should be requested */
131 /* don't exec a shell */
132 int no_shell_flag = 0;
135 * Flag indicating that nothing should be read from stdin. This can be set
136 * on the command line.
138 int stdin_null_flag = 0;
141 * Flag indicating that the current process should be backgrounded and
142 * a new slave launched in the foreground for ControlPersist.
144 int need_controlpersist_detach = 0;
146 /* Copies of flags for ControlPersist foreground slave */
147 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
150 * Flag indicating that ssh should fork after authentication. This is useful
151 * so that the passphrase can be entered manually, and then ssh goes to the
154 int fork_after_authentication_flag = 0;
156 /* forward stdio to remote host and port */
157 char *stdio_forward_host = NULL;
158 int stdio_forward_port = 0;
161 * General data structure for command line options and options configurable
162 * in configuration files. See readconf.h.
166 /* optional user configfile */
170 * Name of the host we are connecting to. This is the name given on the
171 * command line, or the HostName specified for the user-supplied name in a
172 * configuration file.
176 /* socket address the host resolves to */
177 struct sockaddr_storage hostaddr;
179 /* Private host keys. */
180 Sensitive sensitive_data;
182 /* Original real UID. */
183 uid_t original_real_uid;
184 uid_t original_effective_uid;
186 /* command to be executed */
189 /* Should we execute a command or invoke a subsystem? */
190 int subsystem_flag = 0;
192 /* # of replies received for global requests */
193 static int remote_forward_confirms_received = 0;
196 extern int muxserver_sock;
197 extern u_int muxclient_command;
199 /* Prints a help message to the user. This function never returns. */
205 "usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
206 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
207 " [-F configfile] [-I pkcs11] [-i identity_file]\n"
208 " [-L address] [-l login_name] [-m mac_spec]\n"
209 " [-O ctl_cmd] [-o option] [-p port]\n"
210 " [-Q cipher | cipher-auth | mac | kex | key]\n"
211 " [-R address] [-S ctl_path] [-W host:port]\n"
212 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
217 static int ssh_session(void);
218 static int ssh_session2(void);
219 static void load_public_identity_files(void);
220 static void main_sigchld_handler(int);
222 /* from muxclient.c */
223 void muxclient(const char *);
224 void muxserver_listen(void);
226 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
228 tilde_expand_paths(char **paths, u_int num_paths)
233 for (i = 0; i < num_paths; i++) {
234 cp = tilde_expand_filename(paths[i], original_real_uid);
241 * Attempt to resolve a host name / port to a set of addresses and
242 * optionally return any CNAMEs encountered along the way.
243 * Returns NULL on failure.
244 * NB. this function must operate with a options having undefined members.
246 static struct addrinfo *
247 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
249 char strport[NI_MAXSERV];
250 struct addrinfo hints, *res;
251 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
254 port = default_ssh_port();
256 snprintf(strport, sizeof strport, "%u", port);
257 memset(&hints, 0, sizeof(hints));
258 hints.ai_family = options.address_family == -1 ?
259 AF_UNSPEC : options.address_family;
260 hints.ai_socktype = SOCK_STREAM;
262 hints.ai_flags = AI_CANONNAME;
263 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
264 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
265 loglevel = SYSLOG_LEVEL_ERROR;
266 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
267 __progname, name, ssh_gai_strerror(gaierr));
270 if (cname != NULL && res->ai_canonname != NULL) {
271 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
272 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
273 __func__, name, res->ai_canonname, (u_long)clen);
282 * Attempt to resolve a numeric host address / port to a single address.
283 * Returns a canonical address string.
284 * Returns NULL on failure.
285 * NB. this function must operate with a options having undefined members.
287 static struct addrinfo *
288 resolve_addr(const char *name, int port, char *caddr, size_t clen)
290 char addr[NI_MAXHOST], strport[NI_MAXSERV];
291 struct addrinfo hints, *res;
295 port = default_ssh_port();
296 snprintf(strport, sizeof strport, "%u", port);
297 memset(&hints, 0, sizeof(hints));
298 hints.ai_family = options.address_family == -1 ?
299 AF_UNSPEC : options.address_family;
300 hints.ai_socktype = SOCK_STREAM;
301 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
302 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
303 debug2("%s: could not resolve name %.100s as address: %s",
304 __func__, name, ssh_gai_strerror(gaierr));
308 debug("%s: getaddrinfo %.100s returned no addresses",
312 if (res->ai_next != NULL) {
313 debug("%s: getaddrinfo %.100s returned multiple addresses",
317 if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
318 addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
319 debug("%s: Could not format address for name %.100s: %s",
320 __func__, name, ssh_gai_strerror(gaierr));
323 if (strlcpy(caddr, addr, clen) >= clen) {
324 error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
325 __func__, name, addr, (u_long)clen);
336 * Check whether the cname is a permitted replacement for the hostname
337 * and perform the replacement if it is.
338 * NB. this function must operate with a options having undefined members.
341 check_follow_cname(char **namep, const char *cname)
344 struct allowed_cname *rule;
346 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
347 strcmp(*namep, cname) == 0)
349 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
352 * Don't attempt to canonicalize names that will be interpreted by
353 * a proxy unless the user specifically requests so.
355 if (!option_clear_or_none(options.proxy_command) &&
356 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
358 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
359 for (i = 0; i < options.num_permitted_cnames; i++) {
360 rule = options.permitted_cnames + i;
361 if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
362 match_pattern_list(cname, rule->target_list, 1) != 1)
364 verbose("Canonicalized DNS aliased hostname "
365 "\"%s\" => \"%s\"", *namep, cname);
367 *namep = xstrdup(cname);
374 * Attempt to resolve the supplied hostname after applying the user's
375 * canonicalization rules. Returns the address list for the host or NULL
376 * if no name was found after canonicalization.
377 * NB. this function must operate with a options having undefined members.
379 static struct addrinfo *
380 resolve_canonicalize(char **hostp, int port)
383 char *cp, *fullhost, newname[NI_MAXHOST];
384 struct addrinfo *addrs;
386 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
390 * Don't attempt to canonicalize names that will be interpreted by
391 * a proxy unless the user specifically requests so.
393 if (!option_clear_or_none(options.proxy_command) &&
394 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
397 /* Try numeric hostnames first */
398 if ((addrs = resolve_addr(*hostp, port,
399 newname, sizeof(newname))) != NULL) {
400 debug2("%s: hostname %.100s is address", __func__, *hostp);
401 if (strcasecmp(*hostp, newname) != 0) {
402 debug2("%s: canonicalised address \"%s\" => \"%s\"",
403 __func__, *hostp, newname);
405 *hostp = xstrdup(newname);
410 /* Don't apply canonicalization to sufficiently-qualified hostnames */
412 for (cp = *hostp; *cp != '\0'; cp++) {
416 if (ndots > options.canonicalize_max_dots) {
417 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
418 __func__, *hostp, options.canonicalize_max_dots);
421 /* Attempt each supplied suffix */
422 for (i = 0; i < options.num_canonical_domains; i++) {
424 xasprintf(&fullhost, "%s.%s.", *hostp,
425 options.canonical_domains[i]);
426 debug3("%s: attempting \"%s\" => \"%s\"", __func__,
428 if ((addrs = resolve_host(fullhost, port, 0,
429 newname, sizeof(newname))) == NULL) {
433 /* Remove trailing '.' */
434 fullhost[strlen(fullhost) - 1] = '\0';
435 /* Follow CNAME if requested */
436 if (!check_follow_cname(&fullhost, newname)) {
437 debug("Canonicalized hostname \"%s\" => \"%s\"",
444 if (!options.canonicalize_fallback_local)
445 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
446 debug2("%s: host %s not found in any suffix", __func__, *hostp);
451 * Read per-user configuration file. Ignore the system wide config
452 * file if the user specifies a config file on the command line.
455 process_config_files(const char *host_arg, struct passwd *pw, int post_canon)
460 if (config != NULL) {
461 if (strcasecmp(config, "none") != 0 &&
462 !read_config_file(config, pw, host, host_arg, &options,
463 SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
464 fatal("Can't open user config file %.100s: "
465 "%.100s", config, strerror(errno));
467 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
468 _PATH_SSH_USER_CONFFILE);
469 if (r > 0 && (size_t)r < sizeof(buf))
470 (void)read_config_file(buf, pw, host, host_arg,
471 &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
472 (post_canon ? SSHCONF_POSTCANON : 0));
474 /* Read systemwide configuration file after user config. */
475 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
476 host, host_arg, &options,
477 post_canon ? SSHCONF_POSTCANON : 0);
481 /* Rewrite the port number in an addrinfo list of addresses */
483 set_addrinfo_port(struct addrinfo *addrs, int port)
485 struct addrinfo *addr;
487 for (addr = addrs; addr != NULL; addr = addr->ai_next) {
488 switch (addr->ai_family) {
490 ((struct sockaddr_in *)addr->ai_addr)->
491 sin_port = htons(port);
494 ((struct sockaddr_in6 *)addr->ai_addr)->
495 sin6_port = htons(port);
502 * Main program for the ssh client.
505 main(int ac, char **av)
507 int i, r, opt, exit_status, use_syslog, config_test = 0;
508 char *p, *cp, *line, *argv0, buf[PATH_MAX], *host_arg, *logfile;
509 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
510 char cname[NI_MAXHOST];
514 extern int optind, optreset;
517 struct addrinfo *addrs = NULL;
518 struct ssh_digest_ctx *md;
519 u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
522 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
525 __progname = ssh_get_progname(av[0]);
527 #ifndef HAVE_SETPROCTITLE
528 /* Prepare for later setproctitle emulation */
529 /* Save argv so it isn't clobbered by setproctitle() emulation */
530 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
531 for (i = 0; i < ac; i++)
532 saved_av[i] = xstrdup(av[i]);
534 compat_init_setproctitle(ac, av);
539 * Discard other fds that are hanging around. These can cause problem
540 * with backgrounded ssh processes started by ControlPersist.
542 closefrom(STDERR_FILENO + 1);
545 * Save the original real uid. It will be needed later (uid-swapping
546 * may clobber the real uid).
548 original_real_uid = getuid();
549 original_effective_uid = geteuid();
552 * Use uid-swapping to give up root privileges for the duration of
553 * option processing. We will re-instantiate the rights when we are
554 * ready to create the privileged port, and will permanently drop
555 * them when the port has been created (actually, when the connection
556 * has been made, as we may need to create the port several times).
560 #ifdef HAVE_SETRLIMIT
561 /* If we are installed setuid root be careful to not drop core. */
562 if (original_real_uid != original_effective_uid) {
564 rlim.rlim_cur = rlim.rlim_max = 0;
565 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
566 fatal("setrlimit failed: %.100s", strerror(errno));
570 pw = getpwuid(original_real_uid);
572 logit("No user exists for uid %lu", (u_long)original_real_uid);
575 /* Take a copy of the returned structure. */
579 * Set our umask to something reasonable, as some files are created
580 * with the default umask. This will make them world-readable but
581 * writable only by the owner, which is ok for all files for which we
582 * don't set the modes explicitly.
587 * Initialize option structure to indicate that no values have been
590 initialize_options(&options);
592 /* Parse command-line arguments. */
599 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
600 "ACD:E:F:GI:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
603 options.protocol = SSH_PROTO_1;
606 options.protocol = SSH_PROTO_2;
609 options.address_family = AF_INET;
612 options.address_family = AF_INET6;
618 fork_after_authentication_flag = 1;
622 options.forward_x11 = 0;
625 options.forward_x11 = 1;
631 logfile = xstrdup(optarg);
637 options.forward_x11 = 1;
638 options.forward_x11_trusted = 1;
641 options.fwd_opts.gateway_ports = 1;
644 if (stdio_forward_host != NULL)
645 fatal("Cannot specify multiplexing "
647 else if (muxclient_command != 0)
648 fatal("Multiplexing command already specified");
649 if (strcmp(optarg, "check") == 0)
650 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
651 else if (strcmp(optarg, "forward") == 0)
652 muxclient_command = SSHMUX_COMMAND_FORWARD;
653 else if (strcmp(optarg, "exit") == 0)
654 muxclient_command = SSHMUX_COMMAND_TERMINATE;
655 else if (strcmp(optarg, "stop") == 0)
656 muxclient_command = SSHMUX_COMMAND_STOP;
657 else if (strcmp(optarg, "cancel") == 0)
658 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
660 fatal("Invalid multiplex command.");
662 case 'P': /* deprecated */
663 options.use_privileged_port = 0;
667 if (strcmp(optarg, "cipher") == 0)
668 cp = cipher_alg_list('\n', 0);
669 else if (strcmp(optarg, "cipher-auth") == 0)
670 cp = cipher_alg_list('\n', 1);
671 else if (strcmp(optarg, "mac") == 0)
672 cp = mac_alg_list('\n');
673 else if (strcmp(optarg, "kex") == 0)
674 cp = kex_alg_list('\n');
675 else if (strcmp(optarg, "key") == 0)
676 cp = key_alg_list(0, 0);
677 else if (strcmp(optarg, "key-cert") == 0)
678 cp = key_alg_list(1, 0);
679 else if (strcmp(optarg, "key-plain") == 0)
680 cp = key_alg_list(0, 1);
681 else if (strcmp(optarg, "protocol-version") == 0) {
683 cp = xstrdup("1\n2");
689 fatal("Unsupported query \"%s\"", optarg);
695 options.forward_agent = 0;
698 options.forward_agent = 1;
701 options.gss_deleg_creds = 0;
704 options.gss_authentication = 1;
705 options.gss_deleg_creds = 1;
708 if (stat(optarg, &st) < 0) {
709 fprintf(stderr, "Warning: Identity file %s "
710 "not accessible: %s.\n", optarg,
714 add_identity_file(&options, NULL, optarg, 1);
718 options.pkcs11_provider = xstrdup(optarg);
720 fprintf(stderr, "no support for PKCS#11.\n");
724 if (options.request_tty == REQUEST_TTY_YES)
725 options.request_tty = REQUEST_TTY_FORCE;
727 options.request_tty = REQUEST_TTY_YES;
730 if (debug_flag == 0) {
732 options.log_level = SYSLOG_LEVEL_DEBUG1;
734 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
739 if (options.version_addendum &&
740 *options.version_addendum != '\0')
741 fprintf(stderr, "%s %s, %s\n", SSH_RELEASE,
742 options.version_addendum,
745 fprintf(stderr, "%s, %s\n", SSH_RELEASE,
751 if (options.tun_open == -1)
752 options.tun_open = SSH_TUNMODE_DEFAULT;
753 options.tun_local = a2tun(optarg, &options.tun_remote);
754 if (options.tun_local == SSH_TUNID_ERR) {
756 "Bad tun device '%s'\n", optarg);
761 if (stdio_forward_host != NULL)
762 fatal("stdio forward already specified");
763 if (muxclient_command != 0)
764 fatal("Cannot specify stdio forward with -O");
765 if (parse_forward(&fwd, optarg, 1, 0)) {
766 stdio_forward_host = fwd.listen_host;
767 stdio_forward_port = fwd.listen_port;
768 free(fwd.connect_host);
771 "Bad stdio forwarding specification '%s'\n",
775 options.request_tty = REQUEST_TTY_NO;
777 options.clear_forwardings = 1;
778 options.exit_on_forward_failure = 1;
781 options.log_level = SYSLOG_LEVEL_QUIET;
784 if (optarg[0] == '^' && optarg[2] == 0 &&
785 (u_char) optarg[1] >= 64 &&
786 (u_char) optarg[1] < 128)
787 options.escape_char = (u_char) optarg[1] & 31;
788 else if (strlen(optarg) == 1)
789 options.escape_char = (u_char) optarg[0];
790 else if (strcmp(optarg, "none") == 0)
791 options.escape_char = SSH_ESCAPECHAR_NONE;
793 fprintf(stderr, "Bad escape character '%s'.\n",
799 if (ciphers_valid(*optarg == '+' ?
800 optarg + 1 : optarg)) {
802 options.ciphers = xstrdup(optarg);
803 options.cipher = SSH_CIPHER_INVALID;
807 options.cipher = cipher_number(optarg);
808 if (options.cipher == -1) {
809 fprintf(stderr, "Unknown cipher type '%s'\n",
813 if (options.cipher == SSH_CIPHER_3DES)
814 options.ciphers = xstrdup("3des-cbc");
815 else if (options.cipher == SSH_CIPHER_BLOWFISH)
816 options.ciphers = xstrdup("blowfish-cbc");
818 options.ciphers = xstrdup(KEX_CLIENT_ENCRYPT);
821 if (mac_valid(optarg))
822 options.macs = xstrdup(optarg);
824 fprintf(stderr, "Unknown mac type '%s'\n",
830 if (options.control_master == SSHCTL_MASTER_YES)
831 options.control_master = SSHCTL_MASTER_ASK;
833 options.control_master = SSHCTL_MASTER_YES;
836 options.port = a2port(optarg);
837 if (options.port <= 0) {
838 fprintf(stderr, "Bad port '%s'\n", optarg);
843 options.user = optarg;
847 if (parse_forward(&fwd, optarg, 0, 0))
848 add_local_forward(&options, &fwd);
851 "Bad local forwarding specification '%s'\n",
858 if (parse_forward(&fwd, optarg, 0, 1)) {
859 add_remote_forward(&options, &fwd);
862 "Bad remote forwarding specification "
869 if (parse_forward(&fwd, optarg, 1, 0)) {
870 add_local_forward(&options, &fwd);
873 "Bad dynamic forwarding specification "
880 options.compression = 1;
884 options.request_tty = REQUEST_TTY_NO;
887 options.request_tty = REQUEST_TTY_NO;
890 line = xstrdup(optarg);
891 if (process_config_line(&options, pw,
892 host ? host : "", host ? host : "", line,
893 "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
901 if (options.control_path != NULL)
902 free(options.control_path);
903 options.control_path = xstrdup(optarg);
906 options.bind_address = optarg;
919 if (ac > 0 && !host) {
920 if (strrchr(*av, '@')) {
922 cp = strrchr(p, '@');
923 if (cp == NULL || cp == p)
927 host = xstrdup(++cp);
931 optind = optreset = 1;
937 /* Check that we got a host name. */
941 host_arg = xstrdup(host);
944 OpenSSL_add_all_algorithms();
945 ERR_load_crypto_strings();
948 /* Initialize the command to execute on remote host. */
949 buffer_init(&command);
952 * Save the command to execute on the remote host in a buffer. There
953 * is no limit on the length of the command, except by the maximum
954 * packet size. Also sets the tty flag if there is no command.
957 /* No command specified - execute shell on a tty. */
958 if (subsystem_flag) {
960 "You must specify a subsystem to invoke.\n");
964 /* A command has been specified. Store it into the buffer. */
965 for (i = 0; i < ac; i++) {
967 buffer_append(&command, " ", 1);
968 buffer_append(&command, av[i], strlen(av[i]));
972 /* Cannot fork to background if no command. */
973 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
975 fatal("Cannot fork into background without a command "
979 * Initialize "log" output. Since we are the client all output
980 * goes to stderr unless otherwise specified by -y or -E.
982 if (use_syslog && logfile != NULL)
983 fatal("Can't specify both -y and -E");
984 if (logfile != NULL) {
985 log_redirect_stderr_to(logfile);
989 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
990 SYSLOG_FACILITY_USER, !use_syslog);
993 /* version_addendum is always NULL at this point */
994 logit("%s, %s", SSH_RELEASE, OPENSSL_VERSION);
996 /* Parse the configuration files */
997 process_config_files(host_arg, pw, 0);
999 /* Hostname canonicalisation needs a few options filled. */
1000 fill_default_options_for_canonicalization(&options);
1002 /* If the user has replaced the hostname then take it into use now */
1003 if (options.hostname != NULL) {
1004 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1005 cp = percent_expand(options.hostname,
1006 "h", host, (char *)NULL);
1009 free(options.hostname);
1010 options.hostname = xstrdup(host);
1013 /* If canonicalization requested then try to apply it */
1015 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
1016 addrs = resolve_canonicalize(&host, options.port);
1019 * If CanonicalizePermittedCNAMEs have been specified but
1020 * other canonicalization did not happen (by not being requested
1021 * or by failing with fallback) then the hostname may still be changed
1022 * as a result of CNAME following.
1024 * Try to resolve the bare hostname name using the system resolver's
1025 * usual search rules and then apply the CNAME follow rules.
1027 * Skip the lookup if a ProxyCommand is being used unless the user
1028 * has specifically requested canonicalisation for this case via
1029 * CanonicalizeHostname=always
1031 if (addrs == NULL && options.num_permitted_cnames != 0 &&
1032 (option_clear_or_none(options.proxy_command) ||
1033 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1034 if ((addrs = resolve_host(host, options.port,
1035 option_clear_or_none(options.proxy_command),
1036 cname, sizeof(cname))) == NULL) {
1037 /* Don't fatal proxied host names not in the DNS */
1038 if (option_clear_or_none(options.proxy_command))
1039 cleanup_exit(255); /* logged in resolve_host */
1041 check_follow_cname(&host, cname);
1045 * If canonicalisation is enabled then re-parse the configuration
1046 * files as new stanzas may match.
1048 if (options.canonicalize_hostname != 0) {
1049 debug("Re-reading configuration after hostname "
1050 "canonicalisation");
1051 free(options.hostname);
1052 options.hostname = xstrdup(host);
1053 process_config_files(host_arg, pw, 1);
1055 * Address resolution happens early with canonicalisation
1056 * enabled and the port number may have changed since, so
1057 * reset it in address list
1059 if (addrs != NULL && options.port > 0)
1060 set_addrinfo_port(addrs, options.port);
1063 /* Fill configuration defaults. */
1064 fill_default_options(&options);
1066 if (options.port == 0)
1067 options.port = default_ssh_port();
1068 channel_set_af(options.address_family);
1070 /* Tidy and check options */
1071 if (options.host_key_alias != NULL)
1072 lowercase(options.host_key_alias);
1073 if (options.proxy_command != NULL &&
1074 strcmp(options.proxy_command, "-") == 0 &&
1075 options.proxy_use_fdpass)
1076 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1077 if (options.control_persist &&
1078 options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1079 debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1081 options.update_hostkeys = 0;
1084 if (original_effective_uid != 0)
1085 options.use_privileged_port = 0;
1089 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
1091 if (options.request_tty == REQUEST_TTY_YES ||
1092 options.request_tty == REQUEST_TTY_FORCE)
1095 /* Allocate a tty by default if no command specified. */
1096 if (buffer_len(&command) == 0)
1097 tty_flag = options.request_tty != REQUEST_TTY_NO;
1100 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
1102 /* Do not allocate a tty if stdin is not a tty. */
1103 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1104 options.request_tty != REQUEST_TTY_FORCE) {
1106 logit("Pseudo-terminal will not be allocated because "
1107 "stdin is not a terminal.");
1113 if (options.user == NULL)
1114 options.user = xstrdup(pw->pw_name);
1116 if (gethostname(thishost, sizeof(thishost)) == -1)
1117 fatal("gethostname: %s", strerror(errno));
1118 strlcpy(shorthost, thishost, sizeof(shorthost));
1119 shorthost[strcspn(thishost, ".")] = '\0';
1120 snprintf(portstr, sizeof(portstr), "%d", options.port);
1122 /* Find canonic host name. */
1123 if (strchr(host, '.') == 0) {
1124 struct addrinfo hints;
1125 struct addrinfo *ai = NULL;
1127 memset(&hints, 0, sizeof(hints));
1128 hints.ai_family = options.address_family;
1129 hints.ai_flags = AI_CANONNAME;
1130 hints.ai_socktype = SOCK_STREAM;
1131 errgai = getaddrinfo(host, NULL, &hints, &ai);
1133 if (ai->ai_canonname != NULL)
1134 host = xstrdup(ai->ai_canonname);
1139 if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1140 ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1141 ssh_digest_update(md, host, strlen(host)) < 0 ||
1142 ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1143 ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1144 ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1145 fatal("%s: mux digest failed", __func__);
1146 ssh_digest_free(md);
1147 conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1149 if (options.local_command != NULL) {
1150 debug3("expanding LocalCommand: %s", options.local_command);
1151 cp = options.local_command;
1152 options.local_command = percent_expand(cp,
1163 debug3("expanded LocalCommand: %s", options.local_command);
1167 if (options.control_path != NULL) {
1168 cp = tilde_expand_filename(options.control_path,
1170 free(options.control_path);
1171 options.control_path = percent_expand(cp,
1183 free(conn_hash_hex);
1186 dump_client_config(&options, host);
1190 if (muxclient_command != 0 && options.control_path == NULL)
1191 fatal("No ControlPath specified for \"-O\" command");
1192 if (options.control_path != NULL)
1193 muxclient(options.control_path);
1196 * If hostname canonicalisation was not enabled, then we may not
1197 * have yet resolved the hostname. Do so now.
1199 if (addrs == NULL && options.proxy_command == NULL) {
1200 if ((addrs = resolve_host(host, options.port, 1,
1201 cname, sizeof(cname))) == NULL)
1202 cleanup_exit(255); /* resolve_host logs the error */
1205 timeout_ms = options.connection_timeout * 1000;
1207 /* Open a connection to the remote host. */
1208 if (ssh_connect(host, addrs, &hostaddr, options.port,
1209 options.address_family, options.connection_attempts,
1210 &timeout_ms, options.tcp_keep_alive,
1211 options.use_privileged_port) != 0)
1215 freeaddrinfo(addrs);
1217 packet_set_timeout(options.server_alive_interval,
1218 options.server_alive_count_max);
1221 debug3("timeout: %d ms remain after connect", timeout_ms);
1224 * If we successfully made the connection, load the host private key
1225 * in case we will need it later for combined rsa-rhosts
1226 * authentication. This must be done before releasing extra
1227 * privileges, because the file is only readable by root.
1228 * If we cannot access the private keys, load the public keys
1229 * instead and try to execute the ssh-keysign helper instead.
1231 sensitive_data.nkeys = 0;
1232 sensitive_data.keys = NULL;
1233 sensitive_data.external_keysign = 0;
1234 if (options.rhosts_rsa_authentication ||
1235 options.hostbased_authentication) {
1236 sensitive_data.nkeys = 9;
1237 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1239 for (i = 0; i < sensitive_data.nkeys; i++)
1240 sensitive_data.keys[i] = NULL;
1243 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1244 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1245 #ifdef OPENSSL_HAS_ECC
1246 sensitive_data.keys[1] = key_load_private_cert(KEY_ECDSA,
1247 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1249 sensitive_data.keys[2] = key_load_private_cert(KEY_ED25519,
1250 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1251 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1252 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1253 sensitive_data.keys[4] = key_load_private_cert(KEY_DSA,
1254 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1255 #ifdef OPENSSL_HAS_ECC
1256 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
1257 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1259 sensitive_data.keys[6] = key_load_private_type(KEY_ED25519,
1260 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1261 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1262 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1263 sensitive_data.keys[8] = key_load_private_type(KEY_DSA,
1264 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1267 if (options.hostbased_authentication == 1 &&
1268 sensitive_data.keys[0] == NULL &&
1269 sensitive_data.keys[5] == NULL &&
1270 sensitive_data.keys[6] == NULL &&
1271 sensitive_data.keys[7] == NULL &&
1272 sensitive_data.keys[8] == NULL) {
1273 #ifdef OPENSSL_HAS_ECC
1274 sensitive_data.keys[1] = key_load_cert(
1275 _PATH_HOST_ECDSA_KEY_FILE);
1277 sensitive_data.keys[2] = key_load_cert(
1278 _PATH_HOST_ED25519_KEY_FILE);
1279 sensitive_data.keys[3] = key_load_cert(
1280 _PATH_HOST_RSA_KEY_FILE);
1281 sensitive_data.keys[4] = key_load_cert(
1282 _PATH_HOST_DSA_KEY_FILE);
1283 #ifdef OPENSSL_HAS_ECC
1284 sensitive_data.keys[5] = key_load_public(
1285 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1287 sensitive_data.keys[6] = key_load_public(
1288 _PATH_HOST_ED25519_KEY_FILE, NULL);
1289 sensitive_data.keys[7] = key_load_public(
1290 _PATH_HOST_RSA_KEY_FILE, NULL);
1291 sensitive_data.keys[8] = key_load_public(
1292 _PATH_HOST_DSA_KEY_FILE, NULL);
1293 sensitive_data.external_keysign = 1;
1297 * Get rid of any extra privileges that we may have. We will no
1298 * longer need them. Also, extra privileges could make it very hard
1299 * to read identity files and other non-world-readable files from the
1300 * user's home directory if it happens to be on a NFS volume where
1301 * root is mapped to nobody.
1303 if (original_effective_uid == 0) {
1305 permanently_set_uid(pw);
1309 * Now that we are back to our own permissions, create ~/.ssh
1310 * directory if it doesn't already exist.
1312 if (config == NULL) {
1313 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1314 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1315 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1317 ssh_selinux_setfscreatecon(buf);
1319 if (mkdir(buf, 0700) < 0)
1320 error("Could not create directory '%.200s'.",
1323 ssh_selinux_setfscreatecon(NULL);
1327 /* load options.identity_files */
1328 load_public_identity_files();
1330 /* Expand ~ in known host file names. */
1331 tilde_expand_paths(options.system_hostfiles,
1332 options.num_system_hostfiles);
1333 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1335 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1336 signal(SIGCHLD, main_sigchld_handler);
1338 /* Log into the remote system. Never returns if the login fails. */
1339 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1340 options.port, pw, timeout_ms);
1342 if (packet_connection_is_on_socket()) {
1343 verbose("Authenticated to %s ([%s]:%d).", host,
1344 get_remote_ipaddr(), get_remote_port());
1346 verbose("Authenticated to %s (via proxy).", host);
1349 /* We no longer need the private host keys. Clear them now. */
1350 if (sensitive_data.nkeys != 0) {
1351 for (i = 0; i < sensitive_data.nkeys; i++) {
1352 if (sensitive_data.keys[i] != NULL) {
1353 /* Destroys contents safely */
1354 debug3("clear hostkey %d", i);
1355 key_free(sensitive_data.keys[i]);
1356 sensitive_data.keys[i] = NULL;
1359 free(sensitive_data.keys);
1361 for (i = 0; i < options.num_identity_files; i++) {
1362 free(options.identity_files[i]);
1363 options.identity_files[i] = NULL;
1364 if (options.identity_keys[i]) {
1365 key_free(options.identity_keys[i]);
1366 options.identity_keys[i] = NULL;
1370 exit_status = compat20 ? ssh_session2() : ssh_session();
1373 if (options.control_path != NULL && muxserver_sock != -1)
1374 unlink(options.control_path);
1376 /* Kill ProxyCommand if it is running. */
1377 ssh_kill_proxy_command();
1383 control_persist_detach(void)
1388 debug("%s: backgrounding master process", __func__);
1391 * master (current process) into the background, and make the
1392 * foreground process a client of the backgrounded master.
1394 switch ((pid = fork())) {
1396 fatal("%s: fork: %s", __func__, strerror(errno));
1398 /* Child: master process continues mainloop */
1401 /* Parent: set up mux slave to connect to backgrounded master */
1402 debug2("%s: background process is %ld", __func__, (long)pid);
1403 stdin_null_flag = ostdin_null_flag;
1404 options.request_tty = orequest_tty;
1405 tty_flag = otty_flag;
1406 close(muxserver_sock);
1407 muxserver_sock = -1;
1408 options.control_master = SSHCTL_MASTER_NO;
1409 muxclient(options.control_path);
1410 /* muxclient() doesn't return on success. */
1411 fatal("Failed to connect to new control master");
1413 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1414 error("%s: open(\"/dev/null\"): %s", __func__,
1417 if (dup2(devnull, STDIN_FILENO) == -1 ||
1418 dup2(devnull, STDOUT_FILENO) == -1)
1419 error("%s: dup2: %s", __func__, strerror(errno));
1420 if (devnull > STDERR_FILENO)
1424 setproctitle("%s [mux]", options.control_path);
1427 /* Do fork() after authentication. Used by "ssh -f" */
1431 if (need_controlpersist_detach)
1432 control_persist_detach();
1433 debug("forking to background");
1434 fork_after_authentication_flag = 0;
1435 if (daemon(1, 1) < 0)
1436 fatal("daemon() failed: %.200s", strerror(errno));
1439 /* Callback for remote forward global requests */
1441 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1443 struct Forward *rfwd = (struct Forward *)ctxt;
1445 /* XXX verbose() on failure? */
1446 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1447 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1448 rfwd->listen_path ? rfwd->listen_path :
1449 rfwd->listen_host ? rfwd->listen_host : "",
1450 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1451 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1452 rfwd->connect_host, rfwd->connect_port);
1453 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1454 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1455 rfwd->allocated_port = packet_get_int();
1456 logit("Allocated port %u for remote forward to %s:%d",
1457 rfwd->allocated_port,
1458 rfwd->connect_host, rfwd->connect_port);
1459 channel_update_permitted_opens(rfwd->handle,
1460 rfwd->allocated_port);
1462 channel_update_permitted_opens(rfwd->handle, -1);
1466 if (type == SSH2_MSG_REQUEST_FAILURE) {
1467 if (options.exit_on_forward_failure) {
1468 if (rfwd->listen_path != NULL)
1469 fatal("Error: remote port forwarding failed "
1470 "for listen path %s", rfwd->listen_path);
1472 fatal("Error: remote port forwarding failed "
1473 "for listen port %d", rfwd->listen_port);
1475 if (rfwd->listen_path != NULL)
1476 logit("Warning: remote port forwarding failed "
1477 "for listen path %s", rfwd->listen_path);
1479 logit("Warning: remote port forwarding failed "
1480 "for listen port %d", rfwd->listen_port);
1483 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1484 debug("All remote forwarding requests processed");
1485 if (fork_after_authentication_flag)
1491 client_cleanup_stdio_fwd(int id, void *arg)
1493 debug("stdio forwarding: done");
1498 ssh_stdio_confirm(int id, int success, void *arg)
1501 fatal("stdio forwarding failed");
1505 ssh_init_stdio_forwarding(void)
1510 if (stdio_forward_host == NULL)
1513 fatal("stdio forwarding require Protocol 2");
1515 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1517 if ((in = dup(STDIN_FILENO)) < 0 ||
1518 (out = dup(STDOUT_FILENO)) < 0)
1519 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1520 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1521 stdio_forward_port, in, out)) == NULL)
1522 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1523 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1524 channel_register_open_confirm(c->self, ssh_stdio_confirm, NULL);
1528 ssh_init_forwarding(void)
1533 /* Initiate local TCP/IP port forwardings. */
1534 for (i = 0; i < options.num_local_forwards; i++) {
1535 debug("Local connections to %.200s:%d forwarded to remote "
1536 "address %.200s:%d",
1537 (options.local_forwards[i].listen_path != NULL) ?
1538 options.local_forwards[i].listen_path :
1539 (options.local_forwards[i].listen_host == NULL) ?
1540 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1541 options.local_forwards[i].listen_host,
1542 options.local_forwards[i].listen_port,
1543 (options.local_forwards[i].connect_path != NULL) ?
1544 options.local_forwards[i].connect_path :
1545 options.local_forwards[i].connect_host,
1546 options.local_forwards[i].connect_port);
1547 success += channel_setup_local_fwd_listener(
1548 &options.local_forwards[i], &options.fwd_opts);
1550 if (i > 0 && success != i && options.exit_on_forward_failure)
1551 fatal("Could not request local forwarding.");
1552 if (i > 0 && success == 0)
1553 error("Could not request local forwarding.");
1555 /* Initiate remote TCP/IP port forwardings. */
1556 for (i = 0; i < options.num_remote_forwards; i++) {
1557 debug("Remote connections from %.200s:%d forwarded to "
1558 "local address %.200s:%d",
1559 (options.remote_forwards[i].listen_path != NULL) ?
1560 options.remote_forwards[i].listen_path :
1561 (options.remote_forwards[i].listen_host == NULL) ?
1562 "LOCALHOST" : options.remote_forwards[i].listen_host,
1563 options.remote_forwards[i].listen_port,
1564 (options.remote_forwards[i].connect_path != NULL) ?
1565 options.remote_forwards[i].connect_path :
1566 options.remote_forwards[i].connect_host,
1567 options.remote_forwards[i].connect_port);
1568 options.remote_forwards[i].handle =
1569 channel_request_remote_forwarding(
1570 &options.remote_forwards[i]);
1571 if (options.remote_forwards[i].handle < 0) {
1572 if (options.exit_on_forward_failure)
1573 fatal("Could not request remote forwarding.");
1575 logit("Warning: Could not request remote "
1578 client_register_global_confirm(ssh_confirm_remote_forward,
1579 &options.remote_forwards[i]);
1583 /* Initiate tunnel forwarding. */
1584 if (options.tun_open != SSH_TUNMODE_NO) {
1585 if (client_request_tun_fwd(options.tun_open,
1586 options.tun_local, options.tun_remote) == -1) {
1587 if (options.exit_on_forward_failure)
1588 fatal("Could not request tunnel forwarding.");
1590 error("Could not request tunnel forwarding.");
1596 check_agent_present(void)
1600 if (options.forward_agent) {
1601 /* Clear agent forwarding if we don't have an agent. */
1602 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1603 options.forward_agent = 0;
1604 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1605 debug("ssh_get_authentication_socket: %s",
1615 int interactive = 0;
1619 const char *display;
1621 /* Enable compression if requested. */
1622 if (options.compression) {
1623 debug("Requesting compression at level %d.",
1624 options.compression_level);
1626 if (options.compression_level < 1 ||
1627 options.compression_level > 9)
1628 fatal("Compression level must be from 1 (fast) to "
1631 /* Send the request. */
1632 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1633 packet_put_int(options.compression_level);
1635 packet_write_wait();
1636 type = packet_read();
1637 if (type == SSH_SMSG_SUCCESS)
1638 packet_start_compression(options.compression_level);
1639 else if (type == SSH_SMSG_FAILURE)
1640 logit("Warning: Remote host refused compression.");
1642 packet_disconnect("Protocol error waiting for "
1643 "compression response.");
1645 /* Allocate a pseudo tty if appropriate. */
1647 debug("Requesting pty.");
1649 /* Start the packet. */
1650 packet_start(SSH_CMSG_REQUEST_PTY);
1652 /* Store TERM in the packet. There is no limit on the
1653 length of the string. */
1654 cp = getenv("TERM");
1657 packet_put_cstring(cp);
1659 /* Store window size in the packet. */
1660 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1661 memset(&ws, 0, sizeof(ws));
1662 packet_put_int((u_int)ws.ws_row);
1663 packet_put_int((u_int)ws.ws_col);
1664 packet_put_int((u_int)ws.ws_xpixel);
1665 packet_put_int((u_int)ws.ws_ypixel);
1667 /* Store tty modes in the packet. */
1668 tty_make_modes(fileno(stdin), NULL);
1670 /* Send the packet, and wait for it to leave. */
1672 packet_write_wait();
1674 /* Read response from the server. */
1675 type = packet_read();
1676 if (type == SSH_SMSG_SUCCESS) {
1679 } else if (type == SSH_SMSG_FAILURE)
1680 logit("Warning: Remote host failed or refused to "
1681 "allocate a pseudo tty.");
1683 packet_disconnect("Protocol error waiting for pty "
1684 "request response.");
1686 /* Request X11 forwarding if enabled and DISPLAY is set. */
1687 display = getenv("DISPLAY");
1688 if (display == NULL && options.forward_x11)
1689 debug("X11 forwarding requested but DISPLAY not set");
1690 if (options.forward_x11 && display != NULL) {
1692 /* Get reasonable local authentication information. */
1693 client_x11_get_proto(display, options.xauth_location,
1694 options.forward_x11_trusted,
1695 options.forward_x11_timeout,
1697 /* Request forwarding with authentication spoofing. */
1698 debug("Requesting X11 forwarding with authentication "
1700 x11_request_forwarding_with_spoofing(0, display, proto,
1702 /* Read response from the server. */
1703 type = packet_read();
1704 if (type == SSH_SMSG_SUCCESS) {
1706 } else if (type == SSH_SMSG_FAILURE) {
1707 logit("Warning: Remote host denied X11 forwarding.");
1709 packet_disconnect("Protocol error waiting for X11 "
1713 /* Tell the packet module whether this is an interactive session. */
1714 packet_set_interactive(interactive,
1715 options.ip_qos_interactive, options.ip_qos_bulk);
1717 /* Request authentication agent forwarding if appropriate. */
1718 check_agent_present();
1720 if (options.forward_agent) {
1721 debug("Requesting authentication agent forwarding.");
1722 auth_request_forwarding();
1724 /* Read response from the server. */
1725 type = packet_read();
1727 if (type != SSH_SMSG_SUCCESS)
1728 logit("Warning: Remote host denied authentication agent forwarding.");
1731 /* Initiate port forwardings. */
1732 ssh_init_stdio_forwarding();
1733 ssh_init_forwarding();
1735 /* Execute a local command */
1736 if (options.local_command != NULL &&
1737 options.permit_local_command)
1738 ssh_local_cmd(options.local_command);
1741 * If requested and we are not interested in replies to remote
1742 * forwarding requests, then let ssh continue in the background.
1744 if (fork_after_authentication_flag) {
1745 if (options.exit_on_forward_failure &&
1746 options.num_remote_forwards > 0) {
1747 debug("deferring postauth fork until remote forward "
1748 "confirmation received");
1754 * If a command was specified on the command line, execute the
1755 * command now. Otherwise request the server to start a shell.
1757 if (buffer_len(&command) > 0) {
1758 int len = buffer_len(&command);
1761 debug("Sending command: %.*s", len,
1762 (u_char *)buffer_ptr(&command));
1763 packet_start(SSH_CMSG_EXEC_CMD);
1764 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1766 packet_write_wait();
1768 debug("Requesting shell.");
1769 packet_start(SSH_CMSG_EXEC_SHELL);
1771 packet_write_wait();
1774 /* Enter the interactive session. */
1775 return client_loop(have_tty, tty_flag ?
1776 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1779 /* request pty/x11/agent/tcpfwd/shell for channel */
1781 ssh_session2_setup(int id, int success, void *arg)
1783 extern char **environ;
1784 const char *display;
1785 int interactive = tty_flag;
1788 return; /* No need for error message, channels code sens one */
1790 display = getenv("DISPLAY");
1791 if (display == NULL && options.forward_x11)
1792 debug("X11 forwarding requested but DISPLAY not set");
1793 if (options.forward_x11 && display != NULL) {
1795 /* Get reasonable local authentication information. */
1796 client_x11_get_proto(display, options.xauth_location,
1797 options.forward_x11_trusted,
1798 options.forward_x11_timeout, &proto, &data);
1799 /* Request forwarding with authentication spoofing. */
1800 debug("Requesting X11 forwarding with authentication "
1802 x11_request_forwarding_with_spoofing(id, display, proto,
1804 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1805 /* XXX exit_on_forward_failure */
1809 check_agent_present();
1810 if (options.forward_agent) {
1811 debug("Requesting authentication agent forwarding.");
1812 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1816 /* Tell the packet module whether this is an interactive session. */
1817 packet_set_interactive(interactive,
1818 options.ip_qos_interactive, options.ip_qos_bulk);
1820 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1821 NULL, fileno(stdin), &command, environ);
1824 /* open new channel for a session */
1826 ssh_session2_open(void)
1829 int window, packetmax, in, out, err;
1831 if (stdin_null_flag) {
1832 in = open(_PATH_DEVNULL, O_RDONLY);
1834 in = dup(STDIN_FILENO);
1836 out = dup(STDOUT_FILENO);
1837 err = dup(STDERR_FILENO);
1839 if (in < 0 || out < 0 || err < 0)
1840 fatal("dup() in/out/err failed");
1842 /* enable nonblocking unless tty */
1850 window = CHAN_SES_WINDOW_DEFAULT;
1851 packetmax = CHAN_SES_PACKET_DEFAULT;
1857 "session", SSH_CHANNEL_OPENING, in, out, err,
1858 window, packetmax, CHAN_EXTENDED_WRITE,
1859 "client-session", /*nonblock*/0);
1861 debug3("ssh_session2_open: channel_new: %d", c->self);
1863 channel_send_open(c->self);
1865 channel_register_open_confirm(c->self,
1866 ssh_session2_setup, NULL);
1876 /* XXX should be pre-session */
1877 if (!options.control_persist)
1878 ssh_init_stdio_forwarding();
1879 ssh_init_forwarding();
1881 /* Start listening for multiplex clients */
1885 * If we are in control persist mode and have a working mux listen
1886 * socket, then prepare to background ourselves and have a foreground
1887 * client attach as a control slave.
1888 * NB. we must save copies of the flags that we override for
1889 * the backgrounding, since we defer attachment of the slave until
1890 * after the connection is fully established (in particular,
1891 * async rfwd replies have been received for ExitOnForwardFailure).
1893 if (options.control_persist && muxserver_sock != -1) {
1894 ostdin_null_flag = stdin_null_flag;
1895 ono_shell_flag = no_shell_flag;
1896 orequest_tty = options.request_tty;
1897 otty_flag = tty_flag;
1898 stdin_null_flag = 1;
1901 if (!fork_after_authentication_flag)
1902 need_controlpersist_detach = 1;
1903 fork_after_authentication_flag = 1;
1906 * ControlPersist mux listen socket setup failed, attempt the
1907 * stdio forward setup that we skipped earlier.
1909 if (options.control_persist && muxserver_sock == -1)
1910 ssh_init_stdio_forwarding();
1912 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1913 id = ssh_session2_open();
1915 packet_set_interactive(
1916 options.control_master == SSHCTL_MASTER_NO,
1917 options.ip_qos_interactive, options.ip_qos_bulk);
1920 /* If we don't expect to open a new session, then disallow it */
1921 if (options.control_master == SSHCTL_MASTER_NO &&
1922 (datafellows & SSH_NEW_OPENSSH)) {
1923 debug("Requesting no-more-sessions@openssh.com");
1924 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1925 packet_put_cstring("no-more-sessions@openssh.com");
1930 /* Execute a local command */
1931 if (options.local_command != NULL &&
1932 options.permit_local_command)
1933 ssh_local_cmd(options.local_command);
1936 * If requested and we are not interested in replies to remote
1937 * forwarding requests, then let ssh continue in the background.
1939 if (fork_after_authentication_flag) {
1940 if (options.exit_on_forward_failure &&
1941 options.num_remote_forwards > 0) {
1942 debug("deferring postauth fork until remote forward "
1943 "confirmation received");
1948 return client_loop(tty_flag, tty_flag ?
1949 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1953 load_public_identity_files(void)
1955 char *filename, *cp, thishost[NI_MAXHOST];
1956 char *pwdir = NULL, *pwname = NULL;
1961 char *identity_files[SSH_MAX_IDENTITY_FILES];
1962 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1963 #ifdef ENABLE_PKCS11
1969 memset(identity_files, 0, sizeof(identity_files));
1970 memset(identity_keys, 0, sizeof(identity_keys));
1972 #ifdef ENABLE_PKCS11
1973 if (options.pkcs11_provider != NULL &&
1974 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1975 (pkcs11_init(!options.batch_mode) == 0) &&
1976 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
1978 for (i = 0; i < nkeys; i++) {
1979 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
1983 identity_keys[n_ids] = keys[i];
1984 identity_files[n_ids] =
1985 xstrdup(options.pkcs11_provider); /* XXX */
1990 #endif /* ENABLE_PKCS11 */
1991 if ((pw = getpwuid(original_real_uid)) == NULL)
1992 fatal("load_public_identity_files: getpwuid failed");
1993 pwname = xstrdup(pw->pw_name);
1994 pwdir = xstrdup(pw->pw_dir);
1995 if (gethostname(thishost, sizeof(thishost)) == -1)
1996 fatal("load_public_identity_files: gethostname: %s",
1998 for (i = 0; i < options.num_identity_files; i++) {
1999 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2000 strcasecmp(options.identity_files[i], "none") == 0) {
2001 free(options.identity_files[i]);
2004 cp = tilde_expand_filename(options.identity_files[i],
2006 filename = percent_expand(cp, "d", pwdir,
2007 "u", pwname, "l", thishost, "h", host,
2008 "r", options.user, (char *)NULL);
2010 public = key_load_public(filename, NULL);
2011 debug("identity file %s type %d", filename,
2012 public ? public->type : -1);
2013 free(options.identity_files[i]);
2014 identity_files[n_ids] = filename;
2015 identity_keys[n_ids] = public;
2017 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2020 /* Try to add the certificate variant too */
2021 xasprintf(&cp, "%s-cert", filename);
2022 public = key_load_public(cp, NULL);
2023 debug("identity file %s type %d", cp,
2024 public ? public->type : -1);
2025 if (public == NULL) {
2029 if (!key_is_cert(public)) {
2030 debug("%s: key %s type %s is not a certificate",
2031 __func__, cp, key_type(public));
2036 identity_keys[n_ids] = public;
2037 /* point to the original path, most likely the private key */
2038 identity_files[n_ids] = xstrdup(filename);
2041 options.num_identity_files = n_ids;
2042 memcpy(options.identity_files, identity_files, sizeof(identity_files));
2043 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2045 explicit_bzero(pwname, strlen(pwname));
2047 explicit_bzero(pwdir, strlen(pwdir));
2052 main_sigchld_handler(int sig)
2054 int save_errno = errno;
2058 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2059 (pid < 0 && errno == EINTR))
2062 signal(sig, main_sigchld_handler);