1 /* $OpenBSD: ssh.c,v 1.436 2016/02/15 09:47:49 dtucker 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"
111 #include "myproposal.h"
114 #include "ssh-pkcs11.h"
117 extern char *__progname;
119 /* Saves a copy of argv for setproctitle emulation */
120 #ifndef HAVE_SETPROCTITLE
121 static char **saved_av;
124 /* Flag indicating whether debug mode is on. May be set on the command line. */
127 /* Flag indicating whether a tty should be requested */
130 /* don't exec a shell */
131 int no_shell_flag = 0;
134 * Flag indicating that nothing should be read from stdin. This can be set
135 * on the command line.
137 int stdin_null_flag = 0;
140 * Flag indicating that the current process should be backgrounded and
141 * a new slave launched in the foreground for ControlPersist.
143 int need_controlpersist_detach = 0;
145 /* Copies of flags for ControlPersist foreground slave */
146 int ostdin_null_flag, ono_shell_flag, otty_flag, orequest_tty;
149 * Flag indicating that ssh should fork after authentication. This is useful
150 * so that the passphrase can be entered manually, and then ssh goes to the
153 int fork_after_authentication_flag = 0;
155 /* forward stdio to remote host and port */
156 char *stdio_forward_host = NULL;
157 int stdio_forward_port = 0;
160 * General data structure for command line options and options configurable
161 * in configuration files. See readconf.h.
165 /* optional user configfile */
169 * Name of the host we are connecting to. This is the name given on the
170 * command line, or the HostName specified for the user-supplied name in a
171 * configuration file.
175 /* socket address the host resolves to */
176 struct sockaddr_storage hostaddr;
178 /* Private host keys. */
179 Sensitive sensitive_data;
181 /* Original real UID. */
182 uid_t original_real_uid;
183 uid_t original_effective_uid;
185 /* command to be executed */
188 /* Should we execute a command or invoke a subsystem? */
189 int subsystem_flag = 0;
191 /* # of replies received for global requests */
192 static int remote_forward_confirms_received = 0;
195 extern int muxserver_sock;
196 extern u_int muxclient_command;
198 /* Prints a help message to the user. This function never returns. */
204 "usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]\n"
205 " [-D [bind_address:]port] [-E log_file] [-e escape_char]\n"
206 " [-F configfile] [-I pkcs11] [-i identity_file] [-L address]\n"
207 " [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
208 " [-Q query_option] [-R address] [-S ctl_path] [-W host:port]\n"
209 " [-w local_tun[:remote_tun]] [user@]hostname [command]\n"
214 static int ssh_session(void);
215 static int ssh_session2(void);
216 static void load_public_identity_files(void);
217 static void main_sigchld_handler(int);
219 /* from muxclient.c */
220 void muxclient(const char *);
221 void muxserver_listen(void);
223 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
225 tilde_expand_paths(char **paths, u_int num_paths)
230 for (i = 0; i < num_paths; i++) {
231 cp = tilde_expand_filename(paths[i], original_real_uid);
238 * Attempt to resolve a host name / port to a set of addresses and
239 * optionally return any CNAMEs encountered along the way.
240 * Returns NULL on failure.
241 * NB. this function must operate with a options having undefined members.
243 static struct addrinfo *
244 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
246 char strport[NI_MAXSERV];
247 struct addrinfo hints, *res;
248 int gaierr, loglevel = SYSLOG_LEVEL_DEBUG1;
251 port = default_ssh_port();
253 snprintf(strport, sizeof strport, "%d", port);
254 memset(&hints, 0, sizeof(hints));
255 hints.ai_family = options.address_family == -1 ?
256 AF_UNSPEC : options.address_family;
257 hints.ai_socktype = SOCK_STREAM;
259 hints.ai_flags = AI_CANONNAME;
260 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
261 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
262 loglevel = SYSLOG_LEVEL_ERROR;
263 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
264 __progname, name, ssh_gai_strerror(gaierr));
267 if (cname != NULL && res->ai_canonname != NULL) {
268 if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
269 error("%s: host \"%s\" cname \"%s\" too long (max %lu)",
270 __func__, name, res->ai_canonname, (u_long)clen);
279 * Attempt to resolve a numeric host address / port to a single address.
280 * Returns a canonical address string.
281 * Returns NULL on failure.
282 * NB. this function must operate with a options having undefined members.
284 static struct addrinfo *
285 resolve_addr(const char *name, int port, char *caddr, size_t clen)
287 char addr[NI_MAXHOST], strport[NI_MAXSERV];
288 struct addrinfo hints, *res;
292 port = default_ssh_port();
293 snprintf(strport, sizeof strport, "%u", port);
294 memset(&hints, 0, sizeof(hints));
295 hints.ai_family = options.address_family == -1 ?
296 AF_UNSPEC : options.address_family;
297 hints.ai_socktype = SOCK_STREAM;
298 hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
299 if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
300 debug2("%s: could not resolve name %.100s as address: %s",
301 __func__, name, ssh_gai_strerror(gaierr));
305 debug("%s: getaddrinfo %.100s returned no addresses",
309 if (res->ai_next != NULL) {
310 debug("%s: getaddrinfo %.100s returned multiple addresses",
314 if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
315 addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
316 debug("%s: Could not format address for name %.100s: %s",
317 __func__, name, ssh_gai_strerror(gaierr));
320 if (strlcpy(caddr, addr, clen) >= clen) {
321 error("%s: host \"%s\" addr \"%s\" too long (max %lu)",
322 __func__, name, addr, (u_long)clen);
333 * Check whether the cname is a permitted replacement for the hostname
334 * and perform the replacement if it is.
335 * NB. this function must operate with a options having undefined members.
338 check_follow_cname(char **namep, const char *cname)
341 struct allowed_cname *rule;
343 if (*cname == '\0' || options.num_permitted_cnames == 0 ||
344 strcmp(*namep, cname) == 0)
346 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
349 * Don't attempt to canonicalize names that will be interpreted by
350 * a proxy unless the user specifically requests so.
352 if (!option_clear_or_none(options.proxy_command) &&
353 options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
355 debug3("%s: check \"%s\" CNAME \"%s\"", __func__, *namep, cname);
356 for (i = 0; i < options.num_permitted_cnames; i++) {
357 rule = options.permitted_cnames + i;
358 if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
359 match_pattern_list(cname, rule->target_list, 1) != 1)
361 verbose("Canonicalized DNS aliased hostname "
362 "\"%s\" => \"%s\"", *namep, cname);
364 *namep = xstrdup(cname);
371 * Attempt to resolve the supplied hostname after applying the user's
372 * canonicalization rules. Returns the address list for the host or NULL
373 * if no name was found after canonicalization.
374 * NB. this function must operate with a options having undefined members.
376 static struct addrinfo *
377 resolve_canonicalize(char **hostp, int port)
380 char *cp, *fullhost, newname[NI_MAXHOST];
381 struct addrinfo *addrs;
383 if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
387 * Don't attempt to canonicalize names that will be interpreted by
388 * a proxy unless the user specifically requests so.
390 if (!option_clear_or_none(options.proxy_command) &&
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(&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 int i, r, opt, exit_status, use_syslog, config_test = 0;
518 char *p, *cp, *line, *argv0, buf[PATH_MAX], *host_arg, *logfile;
519 char thishost[NI_MAXHOST], shorthost[NI_MAXHOST], portstr[NI_MAXSERV];
520 char cname[NI_MAXHOST], uidstr[32], *conn_hash_hex;
524 extern int optind, optreset;
527 struct addrinfo *addrs = NULL;
528 struct ssh_digest_ctx *md;
529 u_char conn_hash[SSH_DIGEST_MAX_LENGTH];
531 ssh_malloc_init(); /* must be called before any mallocs */
532 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
535 __progname = ssh_get_progname(av[0]);
537 #ifndef HAVE_SETPROCTITLE
538 /* Prepare for later setproctitle emulation */
539 /* Save argv so it isn't clobbered by setproctitle() emulation */
540 saved_av = xcalloc(ac + 1, sizeof(*saved_av));
541 for (i = 0; i < ac; i++)
542 saved_av[i] = xstrdup(av[i]);
544 compat_init_setproctitle(ac, av);
549 * Discard other fds that are hanging around. These can cause problem
550 * with backgrounded ssh processes started by ControlPersist.
552 closefrom(STDERR_FILENO + 1);
555 * Save the original real uid. It will be needed later (uid-swapping
556 * may clobber the real uid).
558 original_real_uid = getuid();
559 original_effective_uid = geteuid();
562 * Use uid-swapping to give up root privileges for the duration of
563 * option processing. We will re-instantiate the rights when we are
564 * ready to create the privileged port, and will permanently drop
565 * them when the port has been created (actually, when the connection
566 * has been made, as we may need to create the port several times).
570 #ifdef HAVE_SETRLIMIT
571 /* If we are installed setuid root be careful to not drop core. */
572 if (original_real_uid != original_effective_uid) {
574 rlim.rlim_cur = rlim.rlim_max = 0;
575 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
576 fatal("setrlimit failed: %.100s", strerror(errno));
580 pw = getpwuid(original_real_uid);
582 logit("No user exists for uid %lu", (u_long)original_real_uid);
585 /* Take a copy of the returned structure. */
589 * Set our umask to something reasonable, as some files are created
590 * with the default umask. This will make them world-readable but
591 * writable only by the owner, which is ok for all files for which we
592 * don't set the modes explicitly.
597 * Initialize option structure to indicate that no values have been
600 initialize_options(&options);
602 /* Parse command-line arguments. */
609 while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
610 "ACD:E:F:GI:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) {
613 options.protocol = SSH_PROTO_1;
616 options.protocol = SSH_PROTO_2;
619 options.address_family = AF_INET;
622 options.address_family = AF_INET6;
628 fork_after_authentication_flag = 1;
632 options.forward_x11 = 0;
635 options.forward_x11 = 1;
647 options.forward_x11 = 1;
648 options.forward_x11_trusted = 1;
651 options.fwd_opts.gateway_ports = 1;
654 if (stdio_forward_host != NULL)
655 fatal("Cannot specify multiplexing "
657 else if (muxclient_command != 0)
658 fatal("Multiplexing command already specified");
659 if (strcmp(optarg, "check") == 0)
660 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
661 else if (strcmp(optarg, "forward") == 0)
662 muxclient_command = SSHMUX_COMMAND_FORWARD;
663 else if (strcmp(optarg, "exit") == 0)
664 muxclient_command = SSHMUX_COMMAND_TERMINATE;
665 else if (strcmp(optarg, "stop") == 0)
666 muxclient_command = SSHMUX_COMMAND_STOP;
667 else if (strcmp(optarg, "cancel") == 0)
668 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
670 fatal("Invalid multiplex command.");
672 case 'P': /* deprecated */
673 options.use_privileged_port = 0;
677 if (strcmp(optarg, "cipher") == 0)
678 cp = cipher_alg_list('\n', 0);
679 else if (strcmp(optarg, "cipher-auth") == 0)
680 cp = cipher_alg_list('\n', 1);
681 else if (strcmp(optarg, "mac") == 0)
682 cp = mac_alg_list('\n');
683 else if (strcmp(optarg, "kex") == 0)
684 cp = kex_alg_list('\n');
685 else if (strcmp(optarg, "key") == 0)
686 cp = key_alg_list(0, 0);
687 else if (strcmp(optarg, "key-cert") == 0)
688 cp = key_alg_list(1, 0);
689 else if (strcmp(optarg, "key-plain") == 0)
690 cp = key_alg_list(0, 1);
691 else if (strcmp(optarg, "protocol-version") == 0) {
693 cp = xstrdup("1\n2");
699 fatal("Unsupported query \"%s\"", optarg);
705 options.forward_agent = 0;
708 options.forward_agent = 1;
711 options.gss_deleg_creds = 0;
714 options.gss_authentication = 1;
715 options.gss_deleg_creds = 1;
718 p = tilde_expand_filename(optarg, original_real_uid);
719 if (stat(p, &st) < 0)
720 fprintf(stderr, "Warning: Identity file %s "
721 "not accessible: %s.\n", p,
724 add_identity_file(&options, NULL, p, 1);
729 free(options.pkcs11_provider);
730 options.pkcs11_provider = xstrdup(optarg);
732 fprintf(stderr, "no support for PKCS#11.\n");
736 if (options.request_tty == REQUEST_TTY_YES)
737 options.request_tty = REQUEST_TTY_FORCE;
739 options.request_tty = REQUEST_TTY_YES;
742 if (debug_flag == 0) {
744 options.log_level = SYSLOG_LEVEL_DEBUG1;
746 if (options.log_level < SYSLOG_LEVEL_DEBUG3)
751 if (options.version_addendum &&
752 *options.version_addendum != '\0')
753 fprintf(stderr, "%s %s, %s\n", SSH_RELEASE,
754 options.version_addendum,
757 fprintf(stderr, "%s, %s\n", SSH_RELEASE,
763 if (options.tun_open == -1)
764 options.tun_open = SSH_TUNMODE_DEFAULT;
765 options.tun_local = a2tun(optarg, &options.tun_remote);
766 if (options.tun_local == SSH_TUNID_ERR) {
768 "Bad tun device '%s'\n", optarg);
773 if (stdio_forward_host != NULL)
774 fatal("stdio forward already specified");
775 if (muxclient_command != 0)
776 fatal("Cannot specify stdio forward with -O");
777 if (parse_forward(&fwd, optarg, 1, 0)) {
778 stdio_forward_host = fwd.listen_host;
779 stdio_forward_port = fwd.listen_port;
780 free(fwd.connect_host);
783 "Bad stdio forwarding specification '%s'\n",
787 options.request_tty = REQUEST_TTY_NO;
789 options.clear_forwardings = 1;
790 options.exit_on_forward_failure = 1;
793 options.log_level = SYSLOG_LEVEL_QUIET;
796 if (optarg[0] == '^' && optarg[2] == 0 &&
797 (u_char) optarg[1] >= 64 &&
798 (u_char) optarg[1] < 128)
799 options.escape_char = (u_char) optarg[1] & 31;
800 else if (strlen(optarg) == 1)
801 options.escape_char = (u_char) optarg[0];
802 else if (strcmp(optarg, "none") == 0)
803 options.escape_char = SSH_ESCAPECHAR_NONE;
805 fprintf(stderr, "Bad escape character '%s'.\n",
811 if (ciphers_valid(*optarg == '+' ?
812 optarg + 1 : optarg)) {
814 free(options.ciphers);
815 options.ciphers = xstrdup(optarg);
816 options.cipher = SSH_CIPHER_INVALID;
820 options.cipher = cipher_number(optarg);
821 if (options.cipher == -1) {
822 fprintf(stderr, "Unknown cipher type '%s'\n",
826 if (options.cipher == SSH_CIPHER_3DES)
827 options.ciphers = xstrdup("3des-cbc");
828 else if (options.cipher == SSH_CIPHER_BLOWFISH)
829 options.ciphers = xstrdup("blowfish-cbc");
831 options.ciphers = xstrdup(KEX_CLIENT_ENCRYPT);
834 if (mac_valid(optarg)) {
836 options.macs = xstrdup(optarg);
838 fprintf(stderr, "Unknown mac type '%s'\n",
844 if (options.control_master == SSHCTL_MASTER_YES)
845 options.control_master = SSHCTL_MASTER_ASK;
847 options.control_master = SSHCTL_MASTER_YES;
850 options.port = a2port(optarg);
851 if (options.port <= 0) {
852 fprintf(stderr, "Bad port '%s'\n", optarg);
857 options.user = optarg;
861 if (parse_forward(&fwd, optarg, 0, 0))
862 add_local_forward(&options, &fwd);
865 "Bad local forwarding specification '%s'\n",
872 if (parse_forward(&fwd, optarg, 0, 1)) {
873 add_remote_forward(&options, &fwd);
876 "Bad remote forwarding specification "
883 if (parse_forward(&fwd, optarg, 1, 0)) {
884 add_local_forward(&options, &fwd);
887 "Bad dynamic forwarding specification "
894 options.compression = 1;
898 options.request_tty = REQUEST_TTY_NO;
901 options.request_tty = REQUEST_TTY_NO;
904 line = xstrdup(optarg);
905 if (process_config_line(&options, pw,
906 host ? host : "", host ? host : "", line,
907 "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
915 free(options.control_path);
916 options.control_path = xstrdup(optarg);
919 options.bind_address = optarg;
932 if (ac > 0 && !host) {
933 if (strrchr(*av, '@')) {
935 cp = strrchr(p, '@');
936 if (cp == NULL || cp == p)
940 host = xstrdup(++cp);
944 optind = optreset = 1;
950 /* Check that we got a host name. */
954 host_arg = xstrdup(host);
957 OpenSSL_add_all_algorithms();
958 ERR_load_crypto_strings();
961 /* Initialize the command to execute on remote host. */
962 buffer_init(&command);
965 * Save the command to execute on the remote host in a buffer. There
966 * is no limit on the length of the command, except by the maximum
967 * packet size. Also sets the tty flag if there is no command.
970 /* No command specified - execute shell on a tty. */
971 if (subsystem_flag) {
973 "You must specify a subsystem to invoke.\n");
977 /* A command has been specified. Store it into the buffer. */
978 for (i = 0; i < ac; i++) {
980 buffer_append(&command, " ", 1);
981 buffer_append(&command, av[i], strlen(av[i]));
985 /* Cannot fork to background if no command. */
986 if (fork_after_authentication_flag && buffer_len(&command) == 0 &&
988 fatal("Cannot fork into background without a command "
992 * Initialize "log" output. Since we are the client all output
993 * goes to stderr unless otherwise specified by -y or -E.
995 if (use_syslog && logfile != NULL)
996 fatal("Can't specify both -y and -E");
998 log_redirect_stderr_to(logfile);
1000 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
1001 SYSLOG_FACILITY_USER, !use_syslog);
1004 /* version_addendum is always NULL at this point */
1005 logit("%s, %s", SSH_RELEASE, OPENSSL_VERSION);
1007 /* Parse the configuration files */
1008 process_config_files(host_arg, pw, 0);
1010 /* Hostname canonicalisation needs a few options filled. */
1011 fill_default_options_for_canonicalization(&options);
1013 /* If the user has replaced the hostname then take it into use now */
1014 if (options.hostname != NULL) {
1015 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1016 cp = percent_expand(options.hostname,
1017 "h", host, (char *)NULL);
1020 free(options.hostname);
1021 options.hostname = xstrdup(host);
1024 /* If canonicalization requested then try to apply it */
1026 if (options.canonicalize_hostname != SSH_CANONICALISE_NO)
1027 addrs = resolve_canonicalize(&host, options.port);
1030 * If CanonicalizePermittedCNAMEs have been specified but
1031 * other canonicalization did not happen (by not being requested
1032 * or by failing with fallback) then the hostname may still be changed
1033 * as a result of CNAME following.
1035 * Try to resolve the bare hostname name using the system resolver's
1036 * usual search rules and then apply the CNAME follow rules.
1038 * Skip the lookup if a ProxyCommand is being used unless the user
1039 * has specifically requested canonicalisation for this case via
1040 * CanonicalizeHostname=always
1042 if (addrs == NULL && options.num_permitted_cnames != 0 &&
1043 (option_clear_or_none(options.proxy_command) ||
1044 options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1045 if ((addrs = resolve_host(host, options.port,
1046 option_clear_or_none(options.proxy_command),
1047 cname, sizeof(cname))) == NULL) {
1048 /* Don't fatal proxied host names not in the DNS */
1049 if (option_clear_or_none(options.proxy_command))
1050 cleanup_exit(255); /* logged in resolve_host */
1052 check_follow_cname(&host, cname);
1056 * If canonicalisation is enabled then re-parse the configuration
1057 * files as new stanzas may match.
1059 if (options.canonicalize_hostname != 0) {
1060 debug("Re-reading configuration after hostname "
1061 "canonicalisation");
1062 free(options.hostname);
1063 options.hostname = xstrdup(host);
1064 process_config_files(host_arg, pw, 1);
1066 * Address resolution happens early with canonicalisation
1067 * enabled and the port number may have changed since, so
1068 * reset it in address list
1070 if (addrs != NULL && options.port > 0)
1071 set_addrinfo_port(addrs, options.port);
1074 /* Fill configuration defaults. */
1075 fill_default_options(&options);
1077 if (options.port == 0)
1078 options.port = default_ssh_port();
1079 channel_set_af(options.address_family);
1081 /* Tidy and check options */
1082 if (options.host_key_alias != NULL)
1083 lowercase(options.host_key_alias);
1084 if (options.proxy_command != NULL &&
1085 strcmp(options.proxy_command, "-") == 0 &&
1086 options.proxy_use_fdpass)
1087 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1088 if (options.control_persist &&
1089 options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1090 debug("UpdateHostKeys=ask is incompatible with ControlPersist; "
1092 options.update_hostkeys = 0;
1094 if (options.connection_attempts <= 0)
1095 fatal("Invalid number of ConnectionAttempts");
1097 if (original_effective_uid != 0)
1098 options.use_privileged_port = 0;
1102 log_init(argv0, options.log_level, SYSLOG_FACILITY_USER, !use_syslog);
1104 if (options.request_tty == REQUEST_TTY_YES ||
1105 options.request_tty == REQUEST_TTY_FORCE)
1108 /* Allocate a tty by default if no command specified. */
1109 if (buffer_len(&command) == 0)
1110 tty_flag = options.request_tty != REQUEST_TTY_NO;
1113 if (options.request_tty == REQUEST_TTY_NO || muxclient_command != 0)
1115 /* Do not allocate a tty if stdin is not a tty. */
1116 if ((!isatty(fileno(stdin)) || stdin_null_flag) &&
1117 options.request_tty != REQUEST_TTY_FORCE) {
1119 logit("Pseudo-terminal will not be allocated because "
1120 "stdin is not a terminal.");
1126 if (options.user == NULL)
1127 options.user = xstrdup(pw->pw_name);
1129 if (gethostname(thishost, sizeof(thishost)) == -1)
1130 fatal("gethostname: %s", strerror(errno));
1131 strlcpy(shorthost, thishost, sizeof(shorthost));
1132 shorthost[strcspn(thishost, ".")] = '\0';
1133 snprintf(portstr, sizeof(portstr), "%d", options.port);
1134 snprintf(uidstr, sizeof(uidstr), "%d", pw->pw_uid);
1136 /* Find canonic host name. */
1137 if (strchr(host, '.') == 0) {
1138 struct addrinfo hints;
1139 struct addrinfo *ai = NULL;
1141 memset(&hints, 0, sizeof(hints));
1142 hints.ai_family = options.address_family;
1143 hints.ai_flags = AI_CANONNAME;
1144 hints.ai_socktype = SOCK_STREAM;
1145 errgai = getaddrinfo(host, NULL, &hints, &ai);
1147 if (ai->ai_canonname != NULL)
1148 host = xstrdup(ai->ai_canonname);
1153 if ((md = ssh_digest_start(SSH_DIGEST_SHA1)) == NULL ||
1154 ssh_digest_update(md, thishost, strlen(thishost)) < 0 ||
1155 ssh_digest_update(md, host, strlen(host)) < 0 ||
1156 ssh_digest_update(md, portstr, strlen(portstr)) < 0 ||
1157 ssh_digest_update(md, options.user, strlen(options.user)) < 0 ||
1158 ssh_digest_final(md, conn_hash, sizeof(conn_hash)) < 0)
1159 fatal("%s: mux digest failed", __func__);
1160 ssh_digest_free(md);
1161 conn_hash_hex = tohex(conn_hash, ssh_digest_bytes(SSH_DIGEST_SHA1));
1163 if (options.local_command != NULL) {
1164 debug3("expanding LocalCommand: %s", options.local_command);
1165 cp = options.local_command;
1166 options.local_command = percent_expand(cp,
1177 debug3("expanded LocalCommand: %s", options.local_command);
1181 if (options.control_path != NULL) {
1182 cp = tilde_expand_filename(options.control_path,
1184 free(options.control_path);
1185 options.control_path = percent_expand(cp,
1198 free(conn_hash_hex);
1201 dump_client_config(&options, host);
1205 if (muxclient_command != 0 && options.control_path == NULL)
1206 fatal("No ControlPath specified for \"-O\" command");
1207 if (options.control_path != NULL)
1208 muxclient(options.control_path);
1211 * If hostname canonicalisation was not enabled, then we may not
1212 * have yet resolved the hostname. Do so now.
1214 if (addrs == NULL && options.proxy_command == NULL) {
1215 debug2("resolving \"%s\" port %d", host, options.port);
1216 if ((addrs = resolve_host(host, options.port, 1,
1217 cname, sizeof(cname))) == NULL)
1218 cleanup_exit(255); /* resolve_host logs the error */
1221 timeout_ms = options.connection_timeout * 1000;
1223 /* Open a connection to the remote host. */
1224 if (ssh_connect(host, addrs, &hostaddr, options.port,
1225 options.address_family, options.connection_attempts,
1226 &timeout_ms, options.tcp_keep_alive,
1227 options.use_privileged_port) != 0)
1231 freeaddrinfo(addrs);
1233 packet_set_timeout(options.server_alive_interval,
1234 options.server_alive_count_max);
1237 debug3("timeout: %d ms remain after connect", timeout_ms);
1240 * If we successfully made the connection, load the host private key
1241 * in case we will need it later for combined rsa-rhosts
1242 * authentication. This must be done before releasing extra
1243 * privileges, because the file is only readable by root.
1244 * If we cannot access the private keys, load the public keys
1245 * instead and try to execute the ssh-keysign helper instead.
1247 sensitive_data.nkeys = 0;
1248 sensitive_data.keys = NULL;
1249 sensitive_data.external_keysign = 0;
1250 if (options.rhosts_rsa_authentication ||
1251 options.hostbased_authentication) {
1252 sensitive_data.nkeys = 9;
1253 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1255 for (i = 0; i < sensitive_data.nkeys; i++)
1256 sensitive_data.keys[i] = NULL;
1260 sensitive_data.keys[0] = key_load_private_type(KEY_RSA1,
1261 _PATH_HOST_KEY_FILE, "", NULL, NULL);
1263 #ifdef OPENSSL_HAS_ECC
1264 sensitive_data.keys[1] = key_load_private_cert(KEY_ECDSA,
1265 _PATH_HOST_ECDSA_KEY_FILE, "", NULL);
1267 sensitive_data.keys[2] = key_load_private_cert(KEY_ED25519,
1268 _PATH_HOST_ED25519_KEY_FILE, "", NULL);
1269 sensitive_data.keys[3] = key_load_private_cert(KEY_RSA,
1270 _PATH_HOST_RSA_KEY_FILE, "", NULL);
1271 sensitive_data.keys[4] = key_load_private_cert(KEY_DSA,
1272 _PATH_HOST_DSA_KEY_FILE, "", NULL);
1273 #ifdef OPENSSL_HAS_ECC
1274 sensitive_data.keys[5] = key_load_private_type(KEY_ECDSA,
1275 _PATH_HOST_ECDSA_KEY_FILE, "", NULL, NULL);
1277 sensitive_data.keys[6] = key_load_private_type(KEY_ED25519,
1278 _PATH_HOST_ED25519_KEY_FILE, "", NULL, NULL);
1279 sensitive_data.keys[7] = key_load_private_type(KEY_RSA,
1280 _PATH_HOST_RSA_KEY_FILE, "", NULL, NULL);
1281 sensitive_data.keys[8] = key_load_private_type(KEY_DSA,
1282 _PATH_HOST_DSA_KEY_FILE, "", NULL, NULL);
1285 if (options.hostbased_authentication == 1 &&
1286 sensitive_data.keys[0] == NULL &&
1287 sensitive_data.keys[5] == NULL &&
1288 sensitive_data.keys[6] == NULL &&
1289 sensitive_data.keys[7] == NULL &&
1290 sensitive_data.keys[8] == NULL) {
1291 #ifdef OPENSSL_HAS_ECC
1292 sensitive_data.keys[1] = key_load_cert(
1293 _PATH_HOST_ECDSA_KEY_FILE);
1295 sensitive_data.keys[2] = key_load_cert(
1296 _PATH_HOST_ED25519_KEY_FILE);
1297 sensitive_data.keys[3] = key_load_cert(
1298 _PATH_HOST_RSA_KEY_FILE);
1299 sensitive_data.keys[4] = key_load_cert(
1300 _PATH_HOST_DSA_KEY_FILE);
1301 #ifdef OPENSSL_HAS_ECC
1302 sensitive_data.keys[5] = key_load_public(
1303 _PATH_HOST_ECDSA_KEY_FILE, NULL);
1305 sensitive_data.keys[6] = key_load_public(
1306 _PATH_HOST_ED25519_KEY_FILE, NULL);
1307 sensitive_data.keys[7] = key_load_public(
1308 _PATH_HOST_RSA_KEY_FILE, NULL);
1309 sensitive_data.keys[8] = key_load_public(
1310 _PATH_HOST_DSA_KEY_FILE, NULL);
1311 sensitive_data.external_keysign = 1;
1315 * Get rid of any extra privileges that we may have. We will no
1316 * longer need them. Also, extra privileges could make it very hard
1317 * to read identity files and other non-world-readable files from the
1318 * user's home directory if it happens to be on a NFS volume where
1319 * root is mapped to nobody.
1321 if (original_effective_uid == 0) {
1323 permanently_set_uid(pw);
1327 * Now that we are back to our own permissions, create ~/.ssh
1328 * directory if it doesn't already exist.
1330 if (config == NULL) {
1331 r = snprintf(buf, sizeof buf, "%s%s%s", pw->pw_dir,
1332 strcmp(pw->pw_dir, "/") ? "/" : "", _PATH_SSH_USER_DIR);
1333 if (r > 0 && (size_t)r < sizeof(buf) && stat(buf, &st) < 0) {
1335 ssh_selinux_setfscreatecon(buf);
1337 if (mkdir(buf, 0700) < 0)
1338 error("Could not create directory '%.200s'.",
1341 ssh_selinux_setfscreatecon(NULL);
1345 /* load options.identity_files */
1346 load_public_identity_files();
1348 /* Expand ~ in known host file names. */
1349 tilde_expand_paths(options.system_hostfiles,
1350 options.num_system_hostfiles);
1351 tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1353 signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1354 signal(SIGCHLD, main_sigchld_handler);
1356 /* Log into the remote system. Never returns if the login fails. */
1357 ssh_login(&sensitive_data, host, (struct sockaddr *)&hostaddr,
1358 options.port, pw, timeout_ms);
1360 if (packet_connection_is_on_socket()) {
1361 verbose("Authenticated to %s ([%s]:%d).", host,
1362 get_remote_ipaddr(), get_remote_port());
1364 verbose("Authenticated to %s (via proxy).", host);
1367 /* We no longer need the private host keys. Clear them now. */
1368 if (sensitive_data.nkeys != 0) {
1369 for (i = 0; i < sensitive_data.nkeys; i++) {
1370 if (sensitive_data.keys[i] != NULL) {
1371 /* Destroys contents safely */
1372 debug3("clear hostkey %d", i);
1373 key_free(sensitive_data.keys[i]);
1374 sensitive_data.keys[i] = NULL;
1377 free(sensitive_data.keys);
1379 for (i = 0; i < options.num_identity_files; i++) {
1380 free(options.identity_files[i]);
1381 options.identity_files[i] = NULL;
1382 if (options.identity_keys[i]) {
1383 key_free(options.identity_keys[i]);
1384 options.identity_keys[i] = NULL;
1387 for (i = 0; i < options.num_certificate_files; i++) {
1388 free(options.certificate_files[i]);
1389 options.certificate_files[i] = NULL;
1392 exit_status = compat20 ? ssh_session2() : ssh_session();
1395 if (options.control_path != NULL && muxserver_sock != -1)
1396 unlink(options.control_path);
1398 /* Kill ProxyCommand if it is running. */
1399 ssh_kill_proxy_command();
1405 control_persist_detach(void)
1410 debug("%s: backgrounding master process", __func__);
1413 * master (current process) into the background, and make the
1414 * foreground process a client of the backgrounded master.
1416 switch ((pid = fork())) {
1418 fatal("%s: fork: %s", __func__, strerror(errno));
1420 /* Child: master process continues mainloop */
1423 /* Parent: set up mux slave to connect to backgrounded master */
1424 debug2("%s: background process is %ld", __func__, (long)pid);
1425 stdin_null_flag = ostdin_null_flag;
1426 options.request_tty = orequest_tty;
1427 tty_flag = otty_flag;
1428 close(muxserver_sock);
1429 muxserver_sock = -1;
1430 options.control_master = SSHCTL_MASTER_NO;
1431 muxclient(options.control_path);
1432 /* muxclient() doesn't return on success. */
1433 fatal("Failed to connect to new control master");
1435 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
1436 error("%s: open(\"/dev/null\"): %s", __func__,
1439 if (dup2(devnull, STDIN_FILENO) == -1 ||
1440 dup2(devnull, STDOUT_FILENO) == -1)
1441 error("%s: dup2: %s", __func__, strerror(errno));
1442 if (devnull > STDERR_FILENO)
1446 setproctitle("%s [mux]", options.control_path);
1449 /* Do fork() after authentication. Used by "ssh -f" */
1453 if (need_controlpersist_detach)
1454 control_persist_detach();
1455 debug("forking to background");
1456 fork_after_authentication_flag = 0;
1457 if (daemon(1, 1) < 0)
1458 fatal("daemon() failed: %.200s", strerror(errno));
1461 /* Callback for remote forward global requests */
1463 ssh_confirm_remote_forward(int type, u_int32_t seq, void *ctxt)
1465 struct Forward *rfwd = (struct Forward *)ctxt;
1467 /* XXX verbose() on failure? */
1468 debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1469 type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1470 rfwd->listen_path ? rfwd->listen_path :
1471 rfwd->listen_host ? rfwd->listen_host : "",
1472 (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1473 rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1474 rfwd->connect_host, rfwd->connect_port);
1475 if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1476 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1477 rfwd->allocated_port = packet_get_int();
1478 logit("Allocated port %u for remote forward to %s:%d",
1479 rfwd->allocated_port,
1480 rfwd->connect_host, rfwd->connect_port);
1481 channel_update_permitted_opens(rfwd->handle,
1482 rfwd->allocated_port);
1484 channel_update_permitted_opens(rfwd->handle, -1);
1488 if (type == SSH2_MSG_REQUEST_FAILURE) {
1489 if (options.exit_on_forward_failure) {
1490 if (rfwd->listen_path != NULL)
1491 fatal("Error: remote port forwarding failed "
1492 "for listen path %s", rfwd->listen_path);
1494 fatal("Error: remote port forwarding failed "
1495 "for listen port %d", rfwd->listen_port);
1497 if (rfwd->listen_path != NULL)
1498 logit("Warning: remote port forwarding failed "
1499 "for listen path %s", rfwd->listen_path);
1501 logit("Warning: remote port forwarding failed "
1502 "for listen port %d", rfwd->listen_port);
1505 if (++remote_forward_confirms_received == options.num_remote_forwards) {
1506 debug("All remote forwarding requests processed");
1507 if (fork_after_authentication_flag)
1513 client_cleanup_stdio_fwd(int id, void *arg)
1515 debug("stdio forwarding: done");
1520 ssh_stdio_confirm(int id, int success, void *arg)
1523 fatal("stdio forwarding failed");
1527 ssh_init_stdio_forwarding(void)
1532 if (stdio_forward_host == NULL)
1535 fatal("stdio forwarding require Protocol 2");
1537 debug3("%s: %s:%d", __func__, stdio_forward_host, stdio_forward_port);
1539 if ((in = dup(STDIN_FILENO)) < 0 ||
1540 (out = dup(STDOUT_FILENO)) < 0)
1541 fatal("channel_connect_stdio_fwd: dup() in/out failed");
1542 if ((c = channel_connect_stdio_fwd(stdio_forward_host,
1543 stdio_forward_port, in, out)) == NULL)
1544 fatal("%s: channel_connect_stdio_fwd failed", __func__);
1545 channel_register_cleanup(c->self, client_cleanup_stdio_fwd, 0);
1546 channel_register_open_confirm(c->self, ssh_stdio_confirm, NULL);
1550 ssh_init_forwarding(void)
1555 /* Initiate local TCP/IP port forwardings. */
1556 for (i = 0; i < options.num_local_forwards; i++) {
1557 debug("Local connections to %.200s:%d forwarded to remote "
1558 "address %.200s:%d",
1559 (options.local_forwards[i].listen_path != NULL) ?
1560 options.local_forwards[i].listen_path :
1561 (options.local_forwards[i].listen_host == NULL) ?
1562 (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1563 options.local_forwards[i].listen_host,
1564 options.local_forwards[i].listen_port,
1565 (options.local_forwards[i].connect_path != NULL) ?
1566 options.local_forwards[i].connect_path :
1567 options.local_forwards[i].connect_host,
1568 options.local_forwards[i].connect_port);
1569 success += channel_setup_local_fwd_listener(
1570 &options.local_forwards[i], &options.fwd_opts);
1572 if (i > 0 && success != i && options.exit_on_forward_failure)
1573 fatal("Could not request local forwarding.");
1574 if (i > 0 && success == 0)
1575 error("Could not request local forwarding.");
1577 /* Initiate remote TCP/IP port forwardings. */
1578 for (i = 0; i < options.num_remote_forwards; i++) {
1579 debug("Remote connections from %.200s:%d forwarded to "
1580 "local address %.200s:%d",
1581 (options.remote_forwards[i].listen_path != NULL) ?
1582 options.remote_forwards[i].listen_path :
1583 (options.remote_forwards[i].listen_host == NULL) ?
1584 "LOCALHOST" : options.remote_forwards[i].listen_host,
1585 options.remote_forwards[i].listen_port,
1586 (options.remote_forwards[i].connect_path != NULL) ?
1587 options.remote_forwards[i].connect_path :
1588 options.remote_forwards[i].connect_host,
1589 options.remote_forwards[i].connect_port);
1590 options.remote_forwards[i].handle =
1591 channel_request_remote_forwarding(
1592 &options.remote_forwards[i]);
1593 if (options.remote_forwards[i].handle < 0) {
1594 if (options.exit_on_forward_failure)
1595 fatal("Could not request remote forwarding.");
1597 logit("Warning: Could not request remote "
1600 client_register_global_confirm(ssh_confirm_remote_forward,
1601 &options.remote_forwards[i]);
1605 /* Initiate tunnel forwarding. */
1606 if (options.tun_open != SSH_TUNMODE_NO) {
1607 if (client_request_tun_fwd(options.tun_open,
1608 options.tun_local, options.tun_remote) == -1) {
1609 if (options.exit_on_forward_failure)
1610 fatal("Could not request tunnel forwarding.");
1612 error("Could not request tunnel forwarding.");
1618 check_agent_present(void)
1622 if (options.forward_agent) {
1623 /* Clear agent forwarding if we don't have an agent. */
1624 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
1625 options.forward_agent = 0;
1626 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1627 debug("ssh_get_authentication_socket: %s",
1637 int interactive = 0;
1641 const char *display;
1642 char *proto = NULL, *data = NULL;
1644 /* Enable compression if requested. */
1645 if (options.compression) {
1646 debug("Requesting compression at level %d.",
1647 options.compression_level);
1649 if (options.compression_level < 1 ||
1650 options.compression_level > 9)
1651 fatal("Compression level must be from 1 (fast) to "
1654 /* Send the request. */
1655 packet_start(SSH_CMSG_REQUEST_COMPRESSION);
1656 packet_put_int(options.compression_level);
1658 packet_write_wait();
1659 type = packet_read();
1660 if (type == SSH_SMSG_SUCCESS)
1661 packet_start_compression(options.compression_level);
1662 else if (type == SSH_SMSG_FAILURE)
1663 logit("Warning: Remote host refused compression.");
1665 packet_disconnect("Protocol error waiting for "
1666 "compression response.");
1668 /* Allocate a pseudo tty if appropriate. */
1670 debug("Requesting pty.");
1672 /* Start the packet. */
1673 packet_start(SSH_CMSG_REQUEST_PTY);
1675 /* Store TERM in the packet. There is no limit on the
1676 length of the string. */
1677 cp = getenv("TERM");
1680 packet_put_cstring(cp);
1682 /* Store window size in the packet. */
1683 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
1684 memset(&ws, 0, sizeof(ws));
1685 packet_put_int((u_int)ws.ws_row);
1686 packet_put_int((u_int)ws.ws_col);
1687 packet_put_int((u_int)ws.ws_xpixel);
1688 packet_put_int((u_int)ws.ws_ypixel);
1690 /* Store tty modes in the packet. */
1691 tty_make_modes(fileno(stdin), NULL);
1693 /* Send the packet, and wait for it to leave. */
1695 packet_write_wait();
1697 /* Read response from the server. */
1698 type = packet_read();
1699 if (type == SSH_SMSG_SUCCESS) {
1702 } else if (type == SSH_SMSG_FAILURE)
1703 logit("Warning: Remote host failed or refused to "
1704 "allocate a pseudo tty.");
1706 packet_disconnect("Protocol error waiting for pty "
1707 "request response.");
1709 /* Request X11 forwarding if enabled and DISPLAY is set. */
1710 display = getenv("DISPLAY");
1711 if (display == NULL && options.forward_x11)
1712 debug("X11 forwarding requested but DISPLAY not set");
1713 if (options.forward_x11 && client_x11_get_proto(display,
1714 options.xauth_location, options.forward_x11_trusted,
1715 options.forward_x11_timeout, &proto, &data) == 0) {
1716 /* Request forwarding with authentication spoofing. */
1717 debug("Requesting X11 forwarding with authentication "
1719 x11_request_forwarding_with_spoofing(0, display, proto,
1721 /* Read response from the server. */
1722 type = packet_read();
1723 if (type == SSH_SMSG_SUCCESS) {
1725 } else if (type == SSH_SMSG_FAILURE) {
1726 logit("Warning: Remote host denied X11 forwarding.");
1728 packet_disconnect("Protocol error waiting for X11 "
1732 /* Tell the packet module whether this is an interactive session. */
1733 packet_set_interactive(interactive,
1734 options.ip_qos_interactive, options.ip_qos_bulk);
1736 /* Request authentication agent forwarding if appropriate. */
1737 check_agent_present();
1739 if (options.forward_agent) {
1740 debug("Requesting authentication agent forwarding.");
1741 auth_request_forwarding();
1743 /* Read response from the server. */
1744 type = packet_read();
1746 if (type != SSH_SMSG_SUCCESS)
1747 logit("Warning: Remote host denied authentication agent forwarding.");
1750 /* Initiate port forwardings. */
1751 ssh_init_stdio_forwarding();
1752 ssh_init_forwarding();
1754 /* Execute a local command */
1755 if (options.local_command != NULL &&
1756 options.permit_local_command)
1757 ssh_local_cmd(options.local_command);
1760 * If requested and we are not interested in replies to remote
1761 * forwarding requests, then let ssh continue in the background.
1763 if (fork_after_authentication_flag) {
1764 if (options.exit_on_forward_failure &&
1765 options.num_remote_forwards > 0) {
1766 debug("deferring postauth fork until remote forward "
1767 "confirmation received");
1773 * If a command was specified on the command line, execute the
1774 * command now. Otherwise request the server to start a shell.
1776 if (buffer_len(&command) > 0) {
1777 int len = buffer_len(&command);
1780 debug("Sending command: %.*s", len,
1781 (u_char *)buffer_ptr(&command));
1782 packet_start(SSH_CMSG_EXEC_CMD);
1783 packet_put_string(buffer_ptr(&command), buffer_len(&command));
1785 packet_write_wait();
1787 debug("Requesting shell.");
1788 packet_start(SSH_CMSG_EXEC_SHELL);
1790 packet_write_wait();
1793 /* Enter the interactive session. */
1794 return client_loop(have_tty, tty_flag ?
1795 options.escape_char : SSH_ESCAPECHAR_NONE, 0);
1798 /* request pty/x11/agent/tcpfwd/shell for channel */
1800 ssh_session2_setup(int id, int success, void *arg)
1802 extern char **environ;
1803 const char *display;
1804 int interactive = tty_flag;
1805 char *proto = NULL, *data = NULL;
1808 return; /* No need for error message, channels code sens one */
1810 display = getenv("DISPLAY");
1811 if (display == NULL && options.forward_x11)
1812 debug("X11 forwarding requested but DISPLAY not set");
1813 if (options.forward_x11 && client_x11_get_proto(display,
1814 options.xauth_location, options.forward_x11_trusted,
1815 options.forward_x11_timeout, &proto, &data) == 0) {
1816 /* Request forwarding with authentication spoofing. */
1817 debug("Requesting X11 forwarding with authentication "
1819 x11_request_forwarding_with_spoofing(id, display, proto,
1821 client_expect_confirm(id, "X11 forwarding", CONFIRM_WARN);
1822 /* XXX exit_on_forward_failure */
1826 check_agent_present();
1827 if (options.forward_agent) {
1828 debug("Requesting authentication agent forwarding.");
1829 channel_request_start(id, "auth-agent-req@openssh.com", 0);
1833 /* Tell the packet module whether this is an interactive session. */
1834 packet_set_interactive(interactive,
1835 options.ip_qos_interactive, options.ip_qos_bulk);
1837 client_session2_setup(id, tty_flag, subsystem_flag, getenv("TERM"),
1838 NULL, fileno(stdin), &command, environ);
1841 /* open new channel for a session */
1843 ssh_session2_open(void)
1846 int window, packetmax, in, out, err;
1848 if (stdin_null_flag) {
1849 in = open(_PATH_DEVNULL, O_RDONLY);
1851 in = dup(STDIN_FILENO);
1853 out = dup(STDOUT_FILENO);
1854 err = dup(STDERR_FILENO);
1856 if (in < 0 || out < 0 || err < 0)
1857 fatal("dup() in/out/err failed");
1859 /* enable nonblocking unless tty */
1867 window = CHAN_SES_WINDOW_DEFAULT;
1868 packetmax = CHAN_SES_PACKET_DEFAULT;
1874 "session", SSH_CHANNEL_OPENING, in, out, err,
1875 window, packetmax, CHAN_EXTENDED_WRITE,
1876 "client-session", /*nonblock*/0);
1878 debug3("ssh_session2_open: channel_new: %d", c->self);
1880 channel_send_open(c->self);
1882 channel_register_open_confirm(c->self,
1883 ssh_session2_setup, NULL);
1893 /* XXX should be pre-session */
1894 if (!options.control_persist)
1895 ssh_init_stdio_forwarding();
1896 ssh_init_forwarding();
1898 /* Start listening for multiplex clients */
1902 * If we are in control persist mode and have a working mux listen
1903 * socket, then prepare to background ourselves and have a foreground
1904 * client attach as a control slave.
1905 * NB. we must save copies of the flags that we override for
1906 * the backgrounding, since we defer attachment of the slave until
1907 * after the connection is fully established (in particular,
1908 * async rfwd replies have been received for ExitOnForwardFailure).
1910 if (options.control_persist && muxserver_sock != -1) {
1911 ostdin_null_flag = stdin_null_flag;
1912 ono_shell_flag = no_shell_flag;
1913 orequest_tty = options.request_tty;
1914 otty_flag = tty_flag;
1915 stdin_null_flag = 1;
1918 if (!fork_after_authentication_flag)
1919 need_controlpersist_detach = 1;
1920 fork_after_authentication_flag = 1;
1923 * ControlPersist mux listen socket setup failed, attempt the
1924 * stdio forward setup that we skipped earlier.
1926 if (options.control_persist && muxserver_sock == -1)
1927 ssh_init_stdio_forwarding();
1929 if (!no_shell_flag || (datafellows & SSH_BUG_DUMMYCHAN))
1930 id = ssh_session2_open();
1932 packet_set_interactive(
1933 options.control_master == SSHCTL_MASTER_NO,
1934 options.ip_qos_interactive, options.ip_qos_bulk);
1937 /* If we don't expect to open a new session, then disallow it */
1938 if (options.control_master == SSHCTL_MASTER_NO &&
1939 (datafellows & SSH_NEW_OPENSSH)) {
1940 debug("Requesting no-more-sessions@openssh.com");
1941 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1942 packet_put_cstring("no-more-sessions@openssh.com");
1947 /* Execute a local command */
1948 if (options.local_command != NULL &&
1949 options.permit_local_command)
1950 ssh_local_cmd(options.local_command);
1953 * If requested and we are not interested in replies to remote
1954 * forwarding requests, then let ssh continue in the background.
1956 if (fork_after_authentication_flag) {
1957 if (options.exit_on_forward_failure &&
1958 options.num_remote_forwards > 0) {
1959 debug("deferring postauth fork until remote forward "
1960 "confirmation received");
1965 return client_loop(tty_flag, tty_flag ?
1966 options.escape_char : SSH_ESCAPECHAR_NONE, id);
1969 /* Loads all IdentityFile and CertificateFile keys */
1971 load_public_identity_files(void)
1973 char *filename, *cp, thishost[NI_MAXHOST];
1974 char *pwdir = NULL, *pwname = NULL;
1978 u_int n_ids, n_certs;
1979 char *identity_files[SSH_MAX_IDENTITY_FILES];
1980 Key *identity_keys[SSH_MAX_IDENTITY_FILES];
1981 char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
1982 struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
1983 #ifdef ENABLE_PKCS11
1988 n_ids = n_certs = 0;
1989 memset(identity_files, 0, sizeof(identity_files));
1990 memset(identity_keys, 0, sizeof(identity_keys));
1991 memset(certificate_files, 0, sizeof(certificate_files));
1992 memset(certificates, 0, sizeof(certificates));
1994 #ifdef ENABLE_PKCS11
1995 if (options.pkcs11_provider != NULL &&
1996 options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
1997 (pkcs11_init(!options.batch_mode) == 0) &&
1998 (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2000 for (i = 0; i < nkeys; i++) {
2001 if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2005 identity_keys[n_ids] = keys[i];
2006 identity_files[n_ids] =
2007 xstrdup(options.pkcs11_provider); /* XXX */
2012 #endif /* ENABLE_PKCS11 */
2013 if ((pw = getpwuid(original_real_uid)) == NULL)
2014 fatal("load_public_identity_files: getpwuid failed");
2015 pwname = xstrdup(pw->pw_name);
2016 pwdir = xstrdup(pw->pw_dir);
2017 if (gethostname(thishost, sizeof(thishost)) == -1)
2018 fatal("load_public_identity_files: gethostname: %s",
2020 for (i = 0; i < options.num_identity_files; i++) {
2021 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2022 strcasecmp(options.identity_files[i], "none") == 0) {
2023 free(options.identity_files[i]);
2024 options.identity_files[i] = NULL;
2027 cp = tilde_expand_filename(options.identity_files[i],
2029 filename = percent_expand(cp, "d", pwdir,
2030 "u", pwname, "l", thishost, "h", host,
2031 "r", options.user, (char *)NULL);
2033 public = key_load_public(filename, NULL);
2034 debug("identity file %s type %d", filename,
2035 public ? public->type : -1);
2036 free(options.identity_files[i]);
2037 identity_files[n_ids] = filename;
2038 identity_keys[n_ids] = public;
2040 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2044 * If no certificates have been explicitly listed then try
2045 * to add the default certificate variant too.
2047 if (options.num_certificate_files != 0)
2049 xasprintf(&cp, "%s-cert", filename);
2050 public = key_load_public(cp, NULL);
2051 debug("identity file %s type %d", cp,
2052 public ? public->type : -1);
2053 if (public == NULL) {
2057 if (!key_is_cert(public)) {
2058 debug("%s: key %s type %s is not a certificate",
2059 __func__, cp, key_type(public));
2064 identity_keys[n_ids] = public;
2065 identity_files[n_ids] = cp;
2069 if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2070 fatal("%s: too many certificates", __func__);
2071 for (i = 0; i < options.num_certificate_files; i++) {
2072 cp = tilde_expand_filename(options.certificate_files[i],
2074 filename = percent_expand(cp, "d", pwdir,
2075 "u", pwname, "l", thishost, "h", host,
2076 "r", options.user, (char *)NULL);
2079 public = key_load_public(filename, NULL);
2080 debug("certificate file %s type %d", filename,
2081 public ? public->type : -1);
2082 free(options.certificate_files[i]);
2083 options.certificate_files[i] = NULL;
2084 if (public == NULL) {
2088 if (!key_is_cert(public)) {
2089 debug("%s: key %s type %s is not a certificate",
2090 __func__, filename, key_type(public));
2095 certificate_files[n_certs] = filename;
2096 certificates[n_certs] = public;
2100 options.num_identity_files = n_ids;
2101 memcpy(options.identity_files, identity_files, sizeof(identity_files));
2102 memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2104 options.num_certificate_files = n_certs;
2105 memcpy(options.certificate_files,
2106 certificate_files, sizeof(certificate_files));
2107 memcpy(options.certificates, certificates, sizeof(certificates));
2109 explicit_bzero(pwname, strlen(pwname));
2111 explicit_bzero(pwdir, strlen(pwdir));
2116 main_sigchld_handler(int sig)
2118 int save_errno = errno;
2122 while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2123 (pid < 0 && errno == EINTR))
2126 signal(sig, main_sigchld_handler);