1 /* $OpenBSD: ssh.c,v 1.445 2016/07/17 04:20:16 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>
73 #include <netinet/in.h>
74 #include <arpa/inet.h>
77 #include <openssl/evp.h>
78 #include <openssl/err.h>
80 #include "openbsd-compat/openssl-compat.h"
81 #include "openbsd-compat/sys-queue.h"
97 #include "pathnames.h"
99 #include "clientloop.h"
102 #include "readconf.h"
103 #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;
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 [-1246AaCfGgKkMNnqsTtVvXxYy] [-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 " [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]\n"
205 " [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]\n"
206 " [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]\n"
207 " [user@]hostname [command]\n"
212 static int ssh_session(void);
213 static int ssh_session2(void);
214 static void load_public_identity_files(void);
215 static void main_sigchld_handler(int);
217 /* from muxclient.c */
218 void muxclient(const char *);
219 void muxserver_listen(void);
221 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
223 tilde_expand_paths(char **paths, u_int num_paths)
228 for (i = 0; i < num_paths; i++) {
229 cp = tilde_expand_filename(paths[i], original_real_uid);
236 * Attempt to resolve a host name / port to a set of addresses and
237 * optionally return any CNAMEs encountered along the way.
238 * Returns NULL on failure.
239 * NB. this function must operate with a options having undefined members.
241 static struct addrinfo *
242 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
244 char strport[NI_MAXSERV];
245 struct addrinfo hints, *res;
246 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
249 port = default_ssh_port();
251 snprintf(strport, sizeof strport, "%d", port);
252 memset(&hints, 0, sizeof(hints));
253 hints.ai_family = options.address_family == -1 ?
254 AF_UNSPEC : options.address_family;
255 hints.ai_socktype = SOCK_STREAM;
257 hints.ai_flags = AI_CANONNAME;
258 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
259 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
260 loglevel = SYSLOG_LEVEL_ERROR;
261 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
262 __progname, name, ssh_gai_strerror(gaierr));
265 if (cname != NULL && res->ai_canonname != NULL) {
266 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
267 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
268 __func__, name, res->ai_canonname, (u_long)clen);
277 * Attempt to resolve a numeric host address / port to a single address.
278 * Returns a canonical address string.
279 * Returns NULL on failure.
280 * NB. this function must operate with a options having undefined members.
282 static struct addrinfo *
283 resolve_addr(const char *name, int port, char *caddr, size_t clen)
285 char addr[NI_MAXHOST], strport[NI_MAXSERV];
286 struct addrinfo hints, *res;
290 port = default_ssh_port();
291 snprintf(strport, sizeof strport, "%u", port);
292 memset(&hints, 0, sizeof(hints));
293 hints.ai_family = options.address_family == -1 ?
294 AF_UNSPEC : options.address_family;
295 hints.ai_socktype = SOCK_STREAM;
296 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
297 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
298 debug2("%s: could not resolve name %.100s as address: %s",
299 __func__, name, ssh_gai_strerror(gaierr));
303 debug("%s: getaddrinfo %.100s returned no addresses",
307 if (res->ai_next != NULL) {
308 debug("%s: getaddrinfo %.100s returned multiple addresses",
312 if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
313 addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
314 debug("%s: Could not format address for name %.100s: %s",
315 __func__, name, ssh_gai_strerror(gaierr));
318 if (strlcpy(caddr, addr, clen) >= clen) {
319 error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
320 __func__, name, addr, (u_long)clen);
331 * Check whether the cname is a permitted replacement for the hostname
332 * and perform the replacement if it is.
333 * NB. this function must operate with a options having undefined members.
336 check_follow_cname(int direct, char **namep, const char *cname)
339 struct allowed_cname *rule;
341 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
342 strcmp(*namep, cname) == 0)
344 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
347 * Don't attempt to canonicalize names that will be interpreted by
348 * a proxy or jump host unless the user specifically requests so.
351 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
353 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
354 for (i = 0; i < options.num_permitted_cnames; i++) {
355 rule = options.permitted_cnames + i;
356 if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
357 match_pattern_list(cname, rule->target_list, 1) != 1)
359 verbose("Canonicalized DNS aliased hostname "
360 "\"%s\" => \"%s\"", *namep, cname);
362 *namep = xstrdup(cname);
369 * Attempt to resolve the supplied hostname after applying the user's
370 * canonicalization rules. Returns the address list for the host or NULL
371 * if no name was found after canonicalization.
372 * NB. this function must operate with a options having undefined members.
374 static struct addrinfo *
375 resolve_canonicalize(char **hostp, int port)
377 int i, direct, ndots;
378 char *cp, *fullhost, newname[NI_MAXHOST];
379 struct addrinfo *addrs;
381 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
385 * Don't attempt to canonicalize names that will be interpreted by
386 * a proxy unless the user specifically requests so.
388 direct = option_clear_or_none(options.proxy_command) &&
389 options.jump_host == NULL;
391 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
394 /* Try numeric hostnames first */
395 if ((addrs = resolve_addr(*hostp, port,
396 newname, sizeof(newname))) != NULL) {
397 debug2("%s: hostname %.100s is address", __func__, *hostp);
398 if (strcasecmp(*hostp, newname) != 0) {
399 debug2("%s: canonicalised address \"%s\" => \"%s\"",
400 __func__, *hostp, newname);
402 *hostp = xstrdup(newname);
407 /* If domain name is anchored, then resolve it now */
408 if ((*hostp)[strlen(*hostp) - 1] == '.') {
409 debug3("%s: name is fully qualified", __func__);
410 fullhost = xstrdup(*hostp);
411 if ((addrs = resolve_host(fullhost, port, 0,
412 newname, sizeof(newname))) != NULL)
418 /* Don't apply canonicalization to sufficiently-qualified hostnames */
420 for (cp = *hostp; *cp != '\0'; cp++) {
424 if (ndots > options.canonicalize_max_dots) {
425 debug3("%s: not canonicalizing hostname \"%s\" (max dots %d)",
426 __func__, *hostp, options.canonicalize_max_dots);
429 /* Attempt each supplied suffix */
430 for (i = 0; i < options.num_canonical_domains; i++) {
432 xasprintf(&fullhost, "%s.%s.", *hostp,
433 options.canonical_domains[i]);
434 debug3("%s: attempting \"%s\" => \"%s\"", __func__,
436 if ((addrs = resolve_host(fullhost, port, 0,
437 newname, sizeof(newname))) == NULL) {
442 /* Remove trailing '.' */
443 fullhost[strlen(fullhost) - 1] = '\0';
444 /* Follow CNAME if requested */
445 if (!check_follow_cname(direct, &fullhost, newname)) {
446 debug("Canonicalized hostname \"%s\" => \"%s\"",
454 if (!options.canonicalize_fallback_local)
455 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
456 debug2("%s: host %s not found in any suffix", __func__, *hostp);
461 * Read per-user configuration file. Ignore the system wide config
462 * file if the user specifies a config file on the command line.
465 process_config_files(const char *host_arg, struct passwd *pw, int post_canon)
470 if (config != NULL) {
471 if (strcasecmp(config, "none") != 0 &&
472 !read_config_file(config, pw, host, host_arg, &options,
473 SSHCONF_USERCONF | (post_canon ? SSHCONF_POSTCANON : 0)))
474 fatal("Can't open user config file %.100s: "
475 "%.100s", config, strerror(errno));
477 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
478 _PATH_SSH_USER_CONFFILE);
479 if (r > 0 && (size_t)r < sizeof(buf))
480 (void)read_config_file(buf, pw, host, host_arg,
481 &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
482 (post_canon ? SSHCONF_POSTCANON : 0));
484 /* Read systemwide configuration file after user config. */
485 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
486 host, host_arg, &options,
487 post_canon ? SSHCONF_POSTCANON : 0);
491 /* Rewrite the port number in an addrinfo list of addresses */
493 set_addrinfo_port(struct addrinfo *addrs, int port)
495 struct addrinfo *addr;
497 for (addr = addrs; addr != NULL; addr = addr->ai_next) {
498 switch (addr->ai_family) {
500 ((struct sockaddr_in *)addr->ai_addr)->
501 sin_port = htons(port);
504 ((struct sockaddr_in6 *)addr->ai_addr)->
505 sin6_port = htons(port);
512 * Main program for the ssh client.
515 main(int ac, char **av)
517 struct ssh *ssh = NULL;
518 int i, r, opt, exit_status, use_syslog, direct, config_test = 0;
519 char *p, *cp, *line, *argv0, buf[PATH_MAX], *host_arg, *logfile;
520 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
521 char cname[NI_MAXHOST], uidstr[32], *conn_hash_hex;
525 extern int optind, optreset;
528 struct addrinfo *addrs = NULL;
529 struct ssh_digest_ctx *md;
530 u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
532 ssh_malloc_init(); /* must be called before any mallocs */
533 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
536 __progname = ssh_get_progname(av[0]);
538 #ifndef HAVE_SETPROCTITLE
539 /* Prepare for later setproctitle emulation */
540 /* Save argv so it isn't clobbered by setproctitle() emulation */
541 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
542 for (i = 0; i < ac; i++)
543 saved_av[i] = xstrdup(av[i]);
545 compat_init_setproctitle(ac, av);
550 * Discard other fds that are hanging around. These can cause problem
551 * with backgrounded ssh processes started by ControlPersist.
553 closefrom(STDERR_FILENO + 1);
556 * Save the original real uid. It will be needed later (uid-swapping
557 * may clobber the real uid).
559 original_real_uid = getuid();
560 original_effective_uid = geteuid();
563 * Use uid-swapping to give up root privileges for the duration of
564 * option processing. We will re-instantiate the rights when we are
565 * ready to create the privileged port, and will permanently drop
566 * them when the port has been created (actually, when the connection
567 * has been made, as we may need to create the port several times).
571 #ifdef HAVE_SETRLIMIT
572 /* If we are installed setuid root be careful to not drop core. */
573 if (original_real_uid != original_effective_uid) {
575 rlim.rlim_cur = rlim.rlim_max = 0;
576 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
577 fatal("setrlimit failed: %.100s", strerror(errno));
581 pw = getpwuid(original_real_uid);
583 logit("No user exists for uid %lu", (u_long)original_real_uid);
586 /* Take a copy of the returned structure. */
590 * Set our umask to something reasonable, as some files are created
591 * with the default umask. This will make them world-readable but
592 * writable only by the owner, which is ok for all files for which we
593 * don't set the modes explicitly.
597 setlocale(LC_CTYPE, "");
600 * Initialize option structure to indicate that no values have been
603 initialize_options(&options);
605 /* Parse command-line arguments. */
612 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
613 "ACD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
616 options.protocol = SSH_PROTO_1;
619 options.protocol = SSH_PROTO_2;
622 options.address_family = AF_INET;
625 options.address_family = AF_INET6;
631 fork_after_authentication_flag = 1;
635 options.forward_x11 = 0;
638 options.forward_x11 = 1;
650 options.forward_x11 = 1;
651 options.forward_x11_trusted = 1;
654 options.fwd_opts.gateway_ports = 1;
657 if (options.stdio_forward_host != NULL)
658 fatal("Cannot specify multiplexing "
660 else if (muxclient_command != 0)
661 fatal("Multiplexing command already specified");
662 if (strcmp(optarg, "check") == 0)
663 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
664 else if (strcmp(optarg, "forward") == 0)
665 muxclient_command = SSHMUX_COMMAND_FORWARD;
666 else if (strcmp(optarg, "exit") == 0)
667 muxclient_command = SSHMUX_COMMAND_TERMINATE;
668 else if (strcmp(optarg, "stop") == 0)
669 muxclient_command = SSHMUX_COMMAND_STOP;
670 else if (strcmp(optarg, "cancel") == 0)
671 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
673 fatal("Invalid multiplex command.");
675 case 'P': /* deprecated */
676 options.use_privileged_port = 0;
680 if (strcmp(optarg, "cipher") == 0)
681 cp = cipher_alg_list('\n', 0);
682 else if (strcmp(optarg, "cipher-auth") == 0)
683 cp = cipher_alg_list('\n', 1);
684 else if (strcmp(optarg, "mac") == 0)
685 cp = mac_alg_list('\n');
686 else if (strcmp(optarg, "kex") == 0)
687 cp = kex_alg_list('\n');
688 else if (strcmp(optarg, "key") == 0)
689 cp = key_alg_list(0, 0);
690 else if (strcmp(optarg, "key-cert") == 0)
691 cp = key_alg_list(1, 0);
692 else if (strcmp(optarg, "key-plain") == 0)
693 cp = key_alg_list(0, 1);
694 else if (strcmp(optarg, "protocol-version") == 0) {
696 cp = xstrdup("1\n2");
702 fatal("Unsupported query \"%s\"", optarg);
708 options.forward_agent = 0;
711 options.forward_agent = 1;
714 options.gss_deleg_creds = 0;
717 options.gss_authentication = 1;
718 options.gss_deleg_creds = 1;
721 p = tilde_expand_filename(optarg, original_real_uid);
722 if (stat(p, &st) < 0)
723 fprintf(stderr, "Warning: Identity file %s "
724 "not accessible: %s.\n", p,
727 add_identity_file(&options, NULL, p, 1);
732 free(options.pkcs11_provider);
733 options.pkcs11_provider = xstrdup(optarg);
735 fprintf(stderr, "no support for PKCS#11.\n");
739 if (options.jump_host != NULL)
740 fatal("Only a single -J option permitted");
741 if (options.proxy_command != NULL)
742 fatal("Cannot specify -J with ProxyCommand");
743 if (parse_jump(optarg, &options, 1) == -1)
744 fatal("Invalid -J argument");
745 options.proxy_command = xstrdup("none");
748 if (options.request_tty == REQUEST_TTY_YES)
749 options.request_tty = REQUEST_TTY_FORCE;
751 options.request_tty = REQUEST_TTY_YES;
754 if (debug_flag == 0) {
756 options.log_level = SYSLOG_LEVEL_DEBUG1;
758 if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
765 if (options.version_addendum &&
766 *options.version_addendum != '\0')
767 fprintf(stderr, "%s %s, %s\n", SSH_RELEASE,
768 options.version_addendum,
771 fprintf(stderr, "%s, %s\n", SSH_RELEASE,
777 if (options.tun_open == -1)
778 options.tun_open = SSH_TUNMODE_DEFAULT;
779 options.tun_local = a2tun(optarg, &options.tun_remote);
780 if (options.tun_local == SSH_TUNID_ERR) {
782 "Bad tun device '%s'\n", optarg);
787 if (options.stdio_forward_host != NULL)
788 fatal("stdio forward already specified");
789 if (muxclient_command != 0)
790 fatal("Cannot specify stdio forward with -O");
791 if (parse_forward(&fwd, optarg, 1, 0)) {
792 options.stdio_forward_host = fwd.listen_host;
793 options.stdio_forward_port = fwd.listen_port;
794 free(fwd.connect_host);
797 "Bad stdio forwarding specification '%s'\n",
801 options.request_tty = REQUEST_TTY_NO;
805 options.log_level = SYSLOG_LEVEL_QUIET;
808 if (optarg[0] == '^' && optarg[2] == 0 &&
809 (u_char) optarg[1] >= 64 &&
810 (u_char) optarg[1] < 128)
811 options.escape_char = (u_char) optarg[1] & 31;
812 else if (strlen(optarg) == 1)
813 options.escape_char = (u_char) optarg[0];
814 else if (strcmp(optarg, "none") == 0)
815 options.escape_char = SSH_ESCAPECHAR_NONE;
817 fprintf(stderr, "Bad escape character '%s'.\n",
823 if (ciphers_valid(*optarg == '+' ?
824 optarg + 1 : optarg)) {
826 free(options.ciphers);
827 options.ciphers = xstrdup(optarg);
828 options.cipher = SSH_CIPHER_INVALID;
832 options.cipher = cipher_number(optarg);
833 if (options.cipher == -1) {
834 fprintf(stderr, "Unknown cipher type '%s'\n",
838 if (options.cipher == SSH_CIPHER_3DES)
839 options.ciphers = xstrdup("3des-cbc");
840 else if (options.cipher == SSH_CIPHER_BLOWFISH)
841 options.ciphers = xstrdup("blowfish-cbc");
843 options.ciphers = xstrdup(KEX_CLIENT_ENCRYPT);
846 if (mac_valid(optarg)) {
848 options.macs = xstrdup(optarg);
850 fprintf(stderr, "Unknown mac type '%s'\n",
856 if (options.control_master == SSHCTL_MASTER_YES)
857 options.control_master = SSHCTL_MASTER_ASK;
859 options.control_master = SSHCTL_MASTER_YES;
862 options.port = a2port(optarg);
863 if (options.port <= 0) {
864 fprintf(stderr, "Bad port '%s'\n", optarg);
869 options.user = optarg;
873 if (parse_forward(&fwd, optarg, 0, 0))
874 add_local_forward(&options, &fwd);
877 "Bad local forwarding specification '%s'\n",
884 if (parse_forward(&fwd, optarg, 0, 1)) {
885 add_remote_forward(&options, &fwd);
888 "Bad remote forwarding specification "
895 if (parse_forward(&fwd, optarg, 1, 0)) {
896 add_local_forward(&options, &fwd);
899 "Bad dynamic forwarding specification "
906 options.compression = 1;
910 options.request_tty = REQUEST_TTY_NO;
913 options.request_tty = REQUEST_TTY_NO;
916 line = xstrdup(optarg);
917 if (process_config_line(&options, pw,
918 host ? host : "", host ? host : "", line,
919 "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
927 free(options.control_path);
928 options.control_path = xstrdup(optarg);
931 options.bind_address = optarg;
944 if (ac > 0 && !host) {
945 if (strrchr(*av, '@')) {
947 cp = strrchr(p, '@');
948 if (cp == NULL || cp == p)
952 host = xstrdup(++cp);
956 optind = optreset = 1;
962 /* Check that we got a host name. */
966 host_arg = xstrdup(host);
969 OpenSSL_add_all_algorithms();
970 ERR_load_crypto_strings();
973 /* Initialize the command to execute on remote host. */
974 buffer_init(&command);
977 * Save the command to execute on the remote host in a buffer. There
978 * is no limit on the length of the command, except by the maximum
979 * packet size. Also sets the tty flag if there is no command.
982 /* No command specified - execute shell on a tty. */
983 if (subsystem_flag) {
985 "You must specify a subsystem to invoke.\n");
989 /* A command has been specified. Store it into the buffer. */
990 for (i = 0; i < ac; i++) {
992 buffer_append(&command, " ", 1);
993 buffer_append(&command, av[i], strlen(av[i]));
997 /* Cannot fork to background if no command. */
998 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
1000 fatal("Cannot fork into background without a command "
1004 * Initialize "log" output. Since we are the client all output
1005 * goes to stderr unless otherwise specified by -y or -E.
1007 if (use_syslog && logfile != NULL)
1008 fatal("Can't specify both -y and -E");
1009 if (logfile != NULL)
1010 log_redirect_stderr_to(logfile);
1012 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
1013 SYSLOG_FACILITY_USER, !use_syslog);
1016 /* version_addendum is always NULL at this point */
1017 logit("%s, %s", SSH_RELEASE, OPENSSL_VERSION);
1019 /* Parse the configuration files */
1020 process_config_files(host_arg, pw, 0);
1022 /* Hostname canonicalisation needs a few options filled. */
1023 fill_default_options_for_canonicalization(&options);
1025 /* If the user has replaced the hostname then take it into use now */
1026 if (options.hostname != NULL) {
1027 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1028 cp = percent_expand(options.hostname,
1029 "h", host, (char *)NULL);
1032 free(options.hostname);
1033 options.hostname = xstrdup(host);
1036 /* If canonicalization requested then try to apply it */
1038 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
1039 addrs = resolve_canonicalize(&host, options.port);
1042 * If CanonicalizePermittedCNAMEs have been specified but
1043 * other canonicalization did not happen (by not being requested
1044 * or by failing with fallback) then the hostname may still be changed
1045 * as a result of CNAME following.
1047 * Try to resolve the bare hostname name using the system resolver's
1048 * usual search rules and then apply the CNAME follow rules.
1050 * Skip the lookup if a ProxyCommand is being used unless the user
1051 * has specifically requested canonicalisation for this case via
1052 * CanonicalizeHostname=always
1054 direct = option_clear_or_none(options.proxy_command) &&
1055 options.jump_host == NULL;
1056 if (addrs == NULL && options.num_permitted_cnames != 0 && (direct ||
1057 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1058 if ((addrs = resolve_host(host, options.port,
1059 option_clear_or_none(options.proxy_command),
1060 cname, sizeof(cname))) == NULL) {
1061 /* Don't fatal proxied host names not in the DNS */
1062 if (option_clear_or_none(options.proxy_command))
1063 cleanup_exit(255); /* logged in resolve_host */
1065 check_follow_cname(direct, &host, cname);
1069 * If canonicalisation is enabled then re-parse the configuration
1070 * files as new stanzas may match.
1072 if (options.canonicalize_hostname != 0) {
1073 debug("Re-reading configuration after hostname "
1074 "canonicalisation");
1075 free(options.hostname);
1076 options.hostname = xstrdup(host);
1077 process_config_files(host_arg, pw, 1);
1079 * Address resolution happens early with canonicalisation
1080 * enabled and the port number may have changed since, so
1081 * reset it in address list
1083 if (addrs != NULL && options.port > 0)
1084 set_addrinfo_port(addrs, options.port);
1087 /* Fill configuration defaults. */
1088 fill_default_options(&options);
1091 * If ProxyJump option specified, then construct a ProxyCommand now.
1093 if (options.jump_host != NULL) {
1096 /* Consistency check */
1097 if (options.proxy_command != NULL)
1098 fatal("inconsistent options: ProxyCommand+ProxyJump");
1099 /* Never use FD passing for ProxyJump */
1100 options.proxy_use_fdpass = 0;
1101 snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1102 xasprintf(&options.proxy_command,
1103 "ssh%s%s%s%s%s%s%s%s%s%.*s -W %%h:%%p %s",
1104 /* Optional "-l user" argument if jump_user set */
1105 options.jump_user == NULL ? "" : " -l ",
1106 options.jump_user == NULL ? "" : options.jump_user,
1107 /* Optional "-p port" argument if jump_port set */
1108 options.jump_port <= 0 ? "" : " -p ",
1109 options.jump_port <= 0 ? "" : port_s,
1110 /* Optional additional jump hosts ",..." */
1111 options.jump_extra == NULL ? "" : " -J ",
1112 options.jump_extra == NULL ? "" : options.jump_extra,
1113 /* Optional "-F" argumment if -F specified */
1114 config == NULL ? "" : " -F ",
1115 config == NULL ? "" : config,
1116 /* Optional "-v" arguments if -v set */
1117 debug_flag ? " -" : "",
1119 /* Mandatory hostname */
1121 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1122 options.proxy_command);
1125 if (options.port == 0)
1126 options.port = default_ssh_port();
1127 channel_set_af(options.address_family);
1129 /* Tidy and check options */
1130 if (options.host_key_alias != NULL)
1131 lowercase(options.host_key_alias);
1132 if (options.proxy_command != NULL &&
1133 strcmp(options.proxy_command, "-") == 0 &&
1134 options.proxy_use_fdpass)
1135 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1136 if (options.control_persist &&
1137 options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1138 debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1140 options.update_hostkeys = 0;
1142 if (options.connection_attempts <= 0)
1143 fatal("Invalid number of ConnectionAttempts");
1145 if (original_effective_uid != 0)
1146 options.use_privileged_port = 0;
1150 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
1152 if (options.request_tty == REQUEST_TTY_YES ||
1153 options.request_tty == REQUEST_TTY_FORCE)
1156 /* Allocate a tty by default if no command specified. */
1157 if (buffer_len(&command) == 0)
1158 tty_flag = options.request_tty != REQUEST_TTY_NO;
1161 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
1163 /* Do not allocate a tty if stdin is not a tty. */
1164 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1165 options.request_tty != REQUEST_TTY_FORCE) {
1167 logit("Pseudo-terminal will not be allocated because "
1168 "stdin is not a terminal.");
1174 if (options.user == NULL)
1175 options.user = xstrdup(pw->pw_name);
1177 if (gethostname(thishost, sizeof(thishost)) == -1)
1178 fatal("gethostname: %s", strerror(errno));
1179 strlcpy(shorthost, thishost, sizeof(shorthost));
1180 shorthost[strcspn(thishost, ".")] = '\0';
1181 snprintf(portstr, sizeof(portstr), "%d", options.port);
1182 snprintf(uidstr, sizeof(uidstr), "%d", pw->pw_uid);
1184 /* Find canonic host name. */
1185 if (strchr(host, '.') == 0) {
1186 struct addrinfo hints;
1187 struct addrinfo *ai = NULL;
1189 memset(&hints, 0, sizeof(hints));
1190 hints.ai_family = options.address_family;
1191 hints.ai_flags = AI_CANONNAME;
1192 hints.ai_socktype = SOCK_STREAM;
1193 errgai = getaddrinfo(host, NULL, &hints, &ai);
1195 if (ai->ai_canonname != NULL)
1196 host = xstrdup(ai->ai_canonname);
1201 if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1202 ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1203 ssh_digest_update(md, host, strlen(host)) < 0 ||
1204 ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1205 ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1206 ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1207 fatal("%s: mux digest failed", __func__);
1208 ssh_digest_free(md);
1209 conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1211 if (options.local_command != NULL) {
1212 debug3("expanding LocalCommand: %s", options.local_command);
1213 cp = options.local_command;
1214 options.local_command = percent_expand(cp,
1225 debug3("expanded LocalCommand: %s", options.local_command);
1229 if (options.control_path != NULL) {
1230 cp = tilde_expand_filename(options.control_path,
1232 free(options.control_path);
1233 options.control_path = percent_expand(cp,
1246 free(conn_hash_hex);
1249 dump_client_config(&options, host);
1253 if (muxclient_command != 0 && options.control_path == NULL)
1254 fatal("No ControlPath specified for \"-O\" command");
1255 if (options.control_path != NULL)
1256 muxclient(options.control_path);
1259 * If hostname canonicalisation was not enabled, then we may not
1260 * have yet resolved the hostname. Do so now.
1262 if (addrs == NULL && options.proxy_command == NULL) {
1263 debug2("resolving \"%s\" port %d", host, options.port);
1264 if ((addrs = resolve_host(host, options.port, 1,
1265 cname, sizeof(cname))) == NULL)
1266 cleanup_exit(255); /* resolve_host logs the error */
1269 timeout_ms = options.connection_timeout * 1000;
1271 /* Open a connection to the remote host. */
1272 if (ssh_connect(host, addrs, &hostaddr, options.port,
1273 options.address_family, options.connection_attempts,
1274 &timeout_ms, options.tcp_keep_alive,
1275 options.use_privileged_port) != 0)
1279 freeaddrinfo(addrs);
1281 packet_set_timeout(options.server_alive_interval,
1282 options.server_alive_count_max);
1284 ssh = active_state; /* XXX */
1287 debug3("timeout: %d ms remain after connect", timeout_ms);
1290 * If we successfully made the connection, load the host private key
1291 * in case we will need it later for combined rsa-rhosts
1292 * authentication. This must be done before releasing extra
1293 * privileges, because the file is only readable by root.
1294 * If we cannot access the private keys, load the public keys
1295 * instead and try to execute the ssh-keysign helper instead.
1297 sensitive_data.nkeys = 0;
1298 sensitive_data.keys = NULL;
1299 sensitive_data.external_keysign = 0;
1300 if (options.rhosts_rsa_authentication ||
1301 options.hostbased_authentication) {
1302 sensitive_data.nkeys = 9;
1303 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1305 for (i = 0; i < sensitive_data.nkeys; i++)
1306 sensitive_data.keys[i] = NULL;
1310 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1311 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1313 #ifdef OPENSSL_HAS_ECC
1314 sensitive_data.keys[1] = key_load_private_cert(KEY_ECDSA,
1315 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1317 sensitive_data.keys[2] = key_load_private_cert(KEY_ED25519,
1318 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1319 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1320 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1321 sensitive_data.keys[4] = key_load_private_cert(KEY_DSA,
1322 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1323 #ifdef OPENSSL_HAS_ECC
1324 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
1325 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1327 sensitive_data.keys[6] = key_load_private_type(KEY_ED25519,
1328 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1329 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1330 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1331 sensitive_data.keys[8] = key_load_private_type(KEY_DSA,
1332 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1335 if (options.hostbased_authentication == 1 &&
1336 sensitive_data.keys[0] == NULL &&
1337 sensitive_data.keys[5] == NULL &&
1338 sensitive_data.keys[6] == NULL &&
1339 sensitive_data.keys[7] == NULL &&
1340 sensitive_data.keys[8] == NULL) {
1341 #ifdef OPENSSL_HAS_ECC
1342 sensitive_data.keys[1] = key_load_cert(
1343 _PATH_HOST_ECDSA_KEY_FILE);
1345 sensitive_data.keys[2] = key_load_cert(
1346 _PATH_HOST_ED25519_KEY_FILE);
1347 sensitive_data.keys[3] = key_load_cert(
1348 _PATH_HOST_RSA_KEY_FILE);
1349 sensitive_data.keys[4] = key_load_cert(
1350 _PATH_HOST_DSA_KEY_FILE);
1351 #ifdef OPENSSL_HAS_ECC
1352 sensitive_data.keys[5] = key_load_public(
1353 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1355 sensitive_data.keys[6] = key_load_public(
1356 _PATH_HOST_ED25519_KEY_FILE, NULL);
1357 sensitive_data.keys[7] = key_load_public(
1358 _PATH_HOST_RSA_KEY_FILE, NULL);
1359 sensitive_data.keys[8] = key_load_public(
1360 _PATH_HOST_DSA_KEY_FILE, NULL);
1361 sensitive_data.external_keysign = 1;
1365 * Get rid of any extra privileges that we may have. We will no
1366 * longer need them. Also, extra privileges could make it very hard
1367 * to read identity files and other non-world-readable files from the
1368 * user's home directory if it happens to be on a NFS volume where
1369 * root is mapped to nobody.
1371 if (original_effective_uid == 0) {
1373 permanently_set_uid(pw);
1377 * Now that we are back to our own permissions, create ~/.ssh
1378 * directory if it doesn't already exist.
1380 if (config == NULL) {
1381 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1382 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1383 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1385 ssh_selinux_setfscreatecon(buf);
1387 if (mkdir(buf, 0700) < 0)
1388 error("Could not create directory '%.200s'.",
1391 ssh_selinux_setfscreatecon(NULL);
1395 /* load options.identity_files */
1396 load_public_identity_files();
1398 /* optionally set the SSH_AUTHSOCKET_ENV_NAME varibale */
1399 if (options.identity_agent &&
1400 strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1401 if (strcmp(options.identity_agent, "none") == 0) {
1402 unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1404 p = tilde_expand_filename(options.identity_agent,
1406 cp = percent_expand(p, "d", pw->pw_dir,
1407 "u", pw->pw_name, "l", thishost, "h", host,
1408 "r", options.user, (char *)NULL);
1409 setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1415 /* Expand ~ in known host file names. */
1416 tilde_expand_paths(options.system_hostfiles,
1417 options.num_system_hostfiles);
1418 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1420 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1421 signal(SIGCHLD, main_sigchld_handler);
1423 /* Log into the remote system. Never returns if the login fails. */
1424 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1425 options.port, pw, timeout_ms);
1427 if (packet_connection_is_on_socket()) {
1428 verbose("Authenticated to %s ([%s]:%d).", host,
1429 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
1431 verbose("Authenticated to %s (via proxy).", host);
1434 /* We no longer need the private host keys. Clear them now. */
1435 if (sensitive_data.nkeys != 0) {
1436 for (i = 0; i < sensitive_data.nkeys; i++) {
1437 if (sensitive_data.keys[i] != NULL) {
1438 /* Destroys contents safely */
1439 debug3("clear hostkey %d", i);
1440 key_free(sensitive_data.keys[i]);
1441 sensitive_data.keys[i] = NULL;
1444 free(sensitive_data.keys);
1446 for (i = 0; i < options.num_identity_files; i++) {
1447 free(options.identity_files[i]);
1448 options.identity_files[i] = NULL;
1449 if (options.identity_keys[i]) {
1450 key_free(options.identity_keys[i]);
1451 options.identity_keys[i] = NULL;
1454 for (i = 0; i < options.num_certificate_files; i++) {
1455 free(options.certificate_files[i]);
1456 options.certificate_files[i] = NULL;
1459 exit_status = compat20 ? ssh_session2() : ssh_session();
1462 if (options.control_path != NULL && muxserver_sock != -1)
1463 unlink(options.control_path);
1465 /* Kill ProxyCommand if it is running. */
1466 ssh_kill_proxy_command();
1472 control_persist_detach(void)
1475 int devnull, keep_stderr;
1477 debug("%s: backgrounding master process", __func__);
1480 * master (current process) into the background, and make the
1481 * foreground process a client of the backgrounded master.
1483 switch ((pid = fork())) {
1485 fatal("%s: fork: %s", __func__, strerror(errno));
1487 /* Child: master process continues mainloop */
1490 /* Parent: set up mux slave to connect to backgrounded master */
1491 debug2("%s: background process is %ld", __func__, (long)pid);
1492 stdin_null_flag = ostdin_null_flag;
1493 options.request_tty = orequest_tty;
1494 tty_flag = otty_flag;
1495 close(muxserver_sock);
1496 muxserver_sock = -1;
1497 options.control_master = SSHCTL_MASTER_NO;
1498 muxclient(options.control_path);
1499 /* muxclient() doesn't return on success. */
1500 fatal("Failed to connect to new control master");
1502 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1503 error("%s: open(\"/dev/null\"): %s", __func__,
1506 keep_stderr = log_is_on_stderr() && debug_flag;
1507 if (dup2(devnull, STDIN_FILENO) == -1 ||
1508 dup2(devnull, STDOUT_FILENO) == -1 ||
1509 (!keep_stderr && dup2(devnull, STDERR_FILENO) == -1))
1510 error("%s: dup2: %s", __func__, strerror(errno));
1511 if (devnull > STDERR_FILENO)
1515 setproctitle("%s [mux]", options.control_path);
1518 /* Do fork() after authentication. Used by "ssh -f" */
1522 if (need_controlpersist_detach)
1523 control_persist_detach();
1524 debug("forking to background");
1525 fork_after_authentication_flag = 0;
1526 if (daemon(1, 1) < 0)
1527 fatal("daemon() failed: %.200s", strerror(errno));
1530 /* Callback for remote forward global requests */
1532 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1534 struct Forward *rfwd = (struct Forward *)ctxt;
1536 /* XXX verbose() on failure? */
1537 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1538 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1539 rfwd->listen_path ? rfwd->listen_path :
1540 rfwd->listen_host ? rfwd->listen_host : "",
1541 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1542 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1543 rfwd->connect_host, rfwd->connect_port);
1544 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1545 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1546 rfwd->allocated_port = packet_get_int();
1547 logit("Allocated port %u for remote forward to %s:%d",
1548 rfwd->allocated_port,
1549 rfwd->connect_host, rfwd->connect_port);
1550 channel_update_permitted_opens(rfwd->handle,
1551 rfwd->allocated_port);
1553 channel_update_permitted_opens(rfwd->handle, -1);
1557 if (type == SSH2_MSG_REQUEST_FAILURE) {
1558 if (options.exit_on_forward_failure) {
1559 if (rfwd->listen_path != NULL)
1560 fatal("Error: remote port forwarding failed "
1561 "for listen path %s", rfwd->listen_path);
1563 fatal("Error: remote port forwarding failed "
1564 "for listen port %d", rfwd->listen_port);
1566 if (rfwd->listen_path != NULL)
1567 logit("Warning: remote port forwarding failed "
1568 "for listen path %s", rfwd->listen_path);
1570 logit("Warning: remote port forwarding failed "
1571 "for listen port %d", rfwd->listen_port);
1574 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1575 debug("All remote forwarding requests processed");
1576 if (fork_after_authentication_flag)
1582 client_cleanup_stdio_fwd(int id, void *arg)
1584 debug("stdio forwarding: done");
1589 ssh_stdio_confirm(int id, int success, void *arg)
1592 fatal("stdio forwarding failed");
1596 ssh_init_stdio_forwarding(void)
1601 if (options.stdio_forward_host == NULL)
1604 fatal("stdio forwarding require Protocol 2");
1606 debug3("%s: %s:%d", __func__, options.stdio_forward_host,
1607 options.stdio_forward_port);
1609 if ((in = dup(STDIN_FILENO)) < 0 ||
1610 (out = dup(STDOUT_FILENO)) < 0)
1611 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1612 if ((c = channel_connect_stdio_fwd(options.stdio_forward_host,
1613 options.stdio_forward_port, in, out)) == NULL)
1614 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1615 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1616 channel_register_open_confirm(c->self, ssh_stdio_confirm, NULL);
1620 ssh_init_forwarding(void)
1625 /* Initiate local TCP/IP port forwardings. */
1626 for (i = 0; i < options.num_local_forwards; i++) {
1627 debug("Local connections to %.200s:%d forwarded to remote "
1628 "address %.200s:%d",
1629 (options.local_forwards[i].listen_path != NULL) ?
1630 options.local_forwards[i].listen_path :
1631 (options.local_forwards[i].listen_host == NULL) ?
1632 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1633 options.local_forwards[i].listen_host,
1634 options.local_forwards[i].listen_port,
1635 (options.local_forwards[i].connect_path != NULL) ?
1636 options.local_forwards[i].connect_path :
1637 options.local_forwards[i].connect_host,
1638 options.local_forwards[i].connect_port);
1639 success += channel_setup_local_fwd_listener(
1640 &options.local_forwards[i], &options.fwd_opts);
1642 if (i > 0 && success != i && options.exit_on_forward_failure)
1643 fatal("Could not request local forwarding.");
1644 if (i > 0 && success == 0)
1645 error("Could not request local forwarding.");
1647 /* Initiate remote TCP/IP port forwardings. */
1648 for (i = 0; i < options.num_remote_forwards; i++) {
1649 debug("Remote connections from %.200s:%d forwarded to "
1650 "local address %.200s:%d",
1651 (options.remote_forwards[i].listen_path != NULL) ?
1652 options.remote_forwards[i].listen_path :
1653 (options.remote_forwards[i].listen_host == NULL) ?
1654 "LOCALHOST" : options.remote_forwards[i].listen_host,
1655 options.remote_forwards[i].listen_port,
1656 (options.remote_forwards[i].connect_path != NULL) ?
1657 options.remote_forwards[i].connect_path :
1658 options.remote_forwards[i].connect_host,
1659 options.remote_forwards[i].connect_port);
1660 options.remote_forwards[i].handle =
1661 channel_request_remote_forwarding(
1662 &options.remote_forwards[i]);
1663 if (options.remote_forwards[i].handle < 0) {
1664 if (options.exit_on_forward_failure)
1665 fatal("Could not request remote forwarding.");
1667 logit("Warning: Could not request remote "
1670 client_register_global_confirm(ssh_confirm_remote_forward,
1671 &options.remote_forwards[i]);
1675 /* Initiate tunnel forwarding. */
1676 if (options.tun_open != SSH_TUNMODE_NO) {
1677 if (client_request_tun_fwd(options.tun_open,
1678 options.tun_local, options.tun_remote) == -1) {
1679 if (options.exit_on_forward_failure)
1680 fatal("Could not request tunnel forwarding.");
1682 error("Could not request tunnel forwarding.");
1688 check_agent_present(void)
1692 if (options.forward_agent) {
1693 /* Clear agent forwarding if we don't have an agent. */
1694 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1695 options.forward_agent = 0;
1696 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1697 debug("ssh_get_authentication_socket: %s",
1707 int interactive = 0;
1711 const char *display;
1712 char *proto = NULL, *data = NULL;
1714 /* Enable compression if requested. */
1715 if (options.compression) {
1716 debug("Requesting compression at level %d.",
1717 options.compression_level);
1719 if (options.compression_level < 1 ||
1720 options.compression_level > 9)
1721 fatal("Compression level must be from 1 (fast) to "
1724 /* Send the request. */
1725 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1726 packet_put_int(options.compression_level);
1728 packet_write_wait();
1729 type = packet_read();
1730 if (type == SSH_SMSG_SUCCESS)
1731 packet_start_compression(options.compression_level);
1732 else if (type == SSH_SMSG_FAILURE)
1733 logit("Warning: Remote host refused compression.");
1735 packet_disconnect("Protocol error waiting for "
1736 "compression response.");
1738 /* Allocate a pseudo tty if appropriate. */
1740 debug("Requesting pty.");
1742 /* Start the packet. */
1743 packet_start(SSH_CMSG_REQUEST_PTY);
1745 /* Store TERM in the packet. There is no limit on the
1746 length of the string. */
1747 cp = getenv("TERM");
1750 packet_put_cstring(cp);
1752 /* Store window size in the packet. */
1753 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1754 memset(&ws, 0, sizeof(ws));
1755 packet_put_int((u_int)ws.ws_row);
1756 packet_put_int((u_int)ws.ws_col);
1757 packet_put_int((u_int)ws.ws_xpixel);
1758 packet_put_int((u_int)ws.ws_ypixel);
1760 /* Store tty modes in the packet. */
1761 tty_make_modes(fileno(stdin), NULL);
1763 /* Send the packet, and wait for it to leave. */
1765 packet_write_wait();
1767 /* Read response from the server. */
1768 type = packet_read();
1769 if (type == SSH_SMSG_SUCCESS) {
1772 } else if (type == SSH_SMSG_FAILURE)
1773 logit("Warning: Remote host failed or refused to "
1774 "allocate a pseudo tty.");
1776 packet_disconnect("Protocol error waiting for pty "
1777 "request response.");
1779 /* Request X11 forwarding if enabled and DISPLAY is set. */
1780 display = getenv("DISPLAY");
1781 if (display == NULL && options.forward_x11)
1782 debug("X11 forwarding requested but DISPLAY not set");
1783 if (options.forward_x11 && client_x11_get_proto(display,
1784 options.xauth_location, options.forward_x11_trusted,
1785 options.forward_x11_timeout, &proto, &data) == 0) {
1786 /* Request forwarding with authentication spoofing. */
1787 debug("Requesting X11 forwarding with authentication "
1789 x11_request_forwarding_with_spoofing(0, display, proto,
1791 /* Read response from the server. */
1792 type = packet_read();
1793 if (type == SSH_SMSG_SUCCESS) {
1795 } else if (type == SSH_SMSG_FAILURE) {
1796 logit("Warning: Remote host denied X11 forwarding.");
1798 packet_disconnect("Protocol error waiting for X11 "
1802 /* Tell the packet module whether this is an interactive session. */
1803 packet_set_interactive(interactive,
1804 options.ip_qos_interactive, options.ip_qos_bulk);
1806 /* Request authentication agent forwarding if appropriate. */
1807 check_agent_present();
1809 if (options.forward_agent) {
1810 debug("Requesting authentication agent forwarding.");
1811 auth_request_forwarding();
1813 /* Read response from the server. */
1814 type = packet_read();
1816 if (type != SSH_SMSG_SUCCESS)
1817 logit("Warning: Remote host denied authentication agent forwarding.");
1820 /* Initiate port forwardings. */
1821 ssh_init_stdio_forwarding();
1822 ssh_init_forwarding();
1824 /* Execute a local command */
1825 if (options.local_command != NULL &&
1826 options.permit_local_command)
1827 ssh_local_cmd(options.local_command);
1830 * If requested and we are not interested in replies to remote
1831 * forwarding requests, then let ssh continue in the background.
1833 if (fork_after_authentication_flag) {
1834 if (options.exit_on_forward_failure &&
1835 options.num_remote_forwards > 0) {
1836 debug("deferring postauth fork until remote forward "
1837 "confirmation received");
1843 * If a command was specified on the command line, execute the
1844 * command now. Otherwise request the server to start a shell.
1846 if (buffer_len(&command) > 0) {
1847 int len = buffer_len(&command);
1850 debug("Sending command: %.*s", len,
1851 (u_char *)buffer_ptr(&command));
1852 packet_start(SSH_CMSG_EXEC_CMD);
1853 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1855 packet_write_wait();
1857 debug("Requesting shell.");
1858 packet_start(SSH_CMSG_EXEC_SHELL);
1860 packet_write_wait();
1863 /* Enter the interactive session. */
1864 return client_loop(have_tty, tty_flag ?
1865 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1868 /* request pty/x11/agent/tcpfwd/shell for channel */
1870 ssh_session2_setup(int id, int success, void *arg)
1872 extern char **environ;
1873 const char *display;
1874 int interactive = tty_flag;
1875 char *proto = NULL, *data = NULL;
1878 return; /* No need for error message, channels code sens one */
1880 display = getenv("DISPLAY");
1881 if (display == NULL && options.forward_x11)
1882 debug("X11 forwarding requested but DISPLAY not set");
1883 if (options.forward_x11 && client_x11_get_proto(display,
1884 options.xauth_location, options.forward_x11_trusted,
1885 options.forward_x11_timeout, &proto, &data) == 0) {
1886 /* Request forwarding with authentication spoofing. */
1887 debug("Requesting X11 forwarding with authentication "
1889 x11_request_forwarding_with_spoofing(id, display, proto,
1891 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1892 /* XXX exit_on_forward_failure */
1896 check_agent_present();
1897 if (options.forward_agent) {
1898 debug("Requesting authentication agent forwarding.");
1899 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1903 /* Tell the packet module whether this is an interactive session. */
1904 packet_set_interactive(interactive,
1905 options.ip_qos_interactive, options.ip_qos_bulk);
1907 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1908 NULL, fileno(stdin), &command, environ);
1911 /* open new channel for a session */
1913 ssh_session2_open(void)
1916 int window, packetmax, in, out, err;
1918 if (stdin_null_flag) {
1919 in = open(_PATH_DEVNULL, O_RDONLY);
1921 in = dup(STDIN_FILENO);
1923 out = dup(STDOUT_FILENO);
1924 err = dup(STDERR_FILENO);
1926 if (in < 0 || out < 0 || err < 0)
1927 fatal("dup() in/out/err failed");
1929 /* enable nonblocking unless tty */
1937 window = CHAN_SES_WINDOW_DEFAULT;
1938 packetmax = CHAN_SES_PACKET_DEFAULT;
1944 "session", SSH_CHANNEL_OPENING, in, out, err,
1945 window, packetmax, CHAN_EXTENDED_WRITE,
1946 "client-session", /*nonblock*/0);
1948 debug3("ssh_session2_open: channel_new: %d", c->self);
1950 channel_send_open(c->self);
1952 channel_register_open_confirm(c->self,
1953 ssh_session2_setup, NULL);
1963 /* XXX should be pre-session */
1964 if (!options.control_persist)
1965 ssh_init_stdio_forwarding();
1966 ssh_init_forwarding();
1968 /* Start listening for multiplex clients */
1972 * If we are in control persist mode and have a working mux listen
1973 * socket, then prepare to background ourselves and have a foreground
1974 * client attach as a control slave.
1975 * NB. we must save copies of the flags that we override for
1976 * the backgrounding, since we defer attachment of the slave until
1977 * after the connection is fully established (in particular,
1978 * async rfwd replies have been received for ExitOnForwardFailure).
1980 if (options.control_persist && muxserver_sock != -1) {
1981 ostdin_null_flag = stdin_null_flag;
1982 ono_shell_flag = no_shell_flag;
1983 orequest_tty = options.request_tty;
1984 otty_flag = tty_flag;
1985 stdin_null_flag = 1;
1988 if (!fork_after_authentication_flag)
1989 need_controlpersist_detach = 1;
1990 fork_after_authentication_flag = 1;
1993 * ControlPersist mux listen socket setup failed, attempt the
1994 * stdio forward setup that we skipped earlier.
1996 if (options.control_persist && muxserver_sock == -1)
1997 ssh_init_stdio_forwarding();
1999 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
2000 id = ssh_session2_open();
2002 packet_set_interactive(
2003 options.control_master == SSHCTL_MASTER_NO,
2004 options.ip_qos_interactive, options.ip_qos_bulk);
2007 /* If we don't expect to open a new session, then disallow it */
2008 if (options.control_master == SSHCTL_MASTER_NO &&
2009 (datafellows & SSH_NEW_OPENSSH)) {
2010 debug("Requesting no-more-sessions@openssh.com");
2011 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2012 packet_put_cstring("no-more-sessions@openssh.com");
2017 /* Execute a local command */
2018 if (options.local_command != NULL &&
2019 options.permit_local_command)
2020 ssh_local_cmd(options.local_command);
2023 * If requested and we are not interested in replies to remote
2024 * forwarding requests, then let ssh continue in the background.
2026 if (fork_after_authentication_flag) {
2027 if (options.exit_on_forward_failure &&
2028 options.num_remote_forwards > 0) {
2029 debug("deferring postauth fork until remote forward "
2030 "confirmation received");
2035 return client_loop(tty_flag, tty_flag ?
2036 options.escape_char : SSH_ESCAPECHAR_NONE, id);
2039 /* Loads all IdentityFile and CertificateFile keys */
2041 load_public_identity_files(void)
2043 char *filename, *cp, thishost[NI_MAXHOST];
2044 char *pwdir = NULL, *pwname = NULL;
2048 u_int n_ids, n_certs;
2049 char *identity_files[SSH_MAX_IDENTITY_FILES];
2050 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
2051 char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2052 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2053 #ifdef ENABLE_PKCS11
2058 n_ids = n_certs = 0;
2059 memset(identity_files, 0, sizeof(identity_files));
2060 memset(identity_keys, 0, sizeof(identity_keys));
2061 memset(certificate_files, 0, sizeof(certificate_files));
2062 memset(certificates, 0, sizeof(certificates));
2064 #ifdef ENABLE_PKCS11
2065 if (options.pkcs11_provider != NULL &&
2066 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2067 (pkcs11_init(!options.batch_mode) == 0) &&
2068 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2070 for (i = 0; i < nkeys; i++) {
2071 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2075 identity_keys[n_ids] = keys[i];
2076 identity_files[n_ids] =
2077 xstrdup(options.pkcs11_provider); /* XXX */
2082 #endif /* ENABLE_PKCS11 */
2083 if ((pw = getpwuid(original_real_uid)) == NULL)
2084 fatal("load_public_identity_files: getpwuid failed");
2085 pwname = xstrdup(pw->pw_name);
2086 pwdir = xstrdup(pw->pw_dir);
2087 if (gethostname(thishost, sizeof(thishost)) == -1)
2088 fatal("load_public_identity_files: gethostname: %s",
2090 for (i = 0; i < options.num_identity_files; i++) {
2091 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2092 strcasecmp(options.identity_files[i], "none") == 0) {
2093 free(options.identity_files[i]);
2094 options.identity_files[i] = NULL;
2097 cp = tilde_expand_filename(options.identity_files[i],
2099 filename = percent_expand(cp, "d", pwdir,
2100 "u", pwname, "l", thishost, "h", host,
2101 "r", options.user, (char *)NULL);
2103 public = key_load_public(filename, NULL);
2104 debug("identity file %s type %d", filename,
2105 public ? public->type : -1);
2106 free(options.identity_files[i]);
2107 identity_files[n_ids] = filename;
2108 identity_keys[n_ids] = public;
2110 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2114 * If no certificates have been explicitly listed then try
2115 * to add the default certificate variant too.
2117 if (options.num_certificate_files != 0)
2119 xasprintf(&cp, "%s-cert", filename);
2120 public = key_load_public(cp, NULL);
2121 debug("identity file %s type %d", cp,
2122 public ? public->type : -1);
2123 if (public == NULL) {
2127 if (!key_is_cert(public)) {
2128 debug("%s: key %s type %s is not a certificate",
2129 __func__, cp, key_type(public));
2134 identity_keys[n_ids] = public;
2135 identity_files[n_ids] = cp;
2139 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2140 fatal("%s: too many certificates", __func__);
2141 for (i = 0; i < options.num_certificate_files; i++) {
2142 cp = tilde_expand_filename(options.certificate_files[i],
2144 filename = percent_expand(cp, "d", pwdir,
2145 "u", pwname, "l", thishost, "h", host,
2146 "r", options.user, (char *)NULL);
2149 public = key_load_public(filename, NULL);
2150 debug("certificate file %s type %d", filename,
2151 public ? public->type : -1);
2152 free(options.certificate_files[i]);
2153 options.certificate_files[i] = NULL;
2154 if (public == NULL) {
2158 if (!key_is_cert(public)) {
2159 debug("%s: key %s type %s is not a certificate",
2160 __func__, filename, key_type(public));
2165 certificate_files[n_certs] = filename;
2166 certificates[n_certs] = public;
2170 options.num_identity_files = n_ids;
2171 memcpy(options.identity_files, identity_files, sizeof(identity_files));
2172 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2174 options.num_certificate_files = n_certs;
2175 memcpy(options.certificate_files,
2176 certificate_files, sizeof(certificate_files));
2177 memcpy(options.certificates, certificates, sizeof(certificates));
2179 explicit_bzero(pwname, strlen(pwname));
2181 explicit_bzero(pwdir, strlen(pwdir));
2186 main_sigchld_handler(int sig)
2188 int save_errno = errno;
2192 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2193 (pid < 0 && errno == EINTR))
2196 signal(sig, main_sigchld_handler);