]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/ssh.c
ssh: Update to OpenSSH 9.3p1
[FreeBSD/FreeBSD.git] / crypto / openssh / ssh.c
1 /* $OpenBSD: ssh.c,v 1.585 2023/02/10 04:40:28 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
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.
9  *
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".
15  *
16  * Copyright (c) 1999 Niels Provos.  All rights reserved.
17  * Copyright (c) 2000, 2001, 2002, 2003 Markus Friedl.  All rights reserved.
18  *
19  * Modified to work with SSLeay by Niels Provos <provos@citi.umich.edu>
20  * in Canada (German citizen).
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
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.
30  *
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.
41  */
42
43 #include "includes.h"
44
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #include <sys/resource.h>
50 #include <sys/ioctl.h>
51 #include <sys/socket.h>
52 #include <sys/wait.h>
53
54 #include <ctype.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <netdb.h>
58 #ifdef HAVE_PATHS_H
59 #include <paths.h>
60 #endif
61 #include <pwd.h>
62 #include <signal.h>
63 #include <stdarg.h>
64 #include <stddef.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <stdarg.h>
69 #include <unistd.h>
70 #include <limits.h>
71 #include <locale.h>
72
73 #include <netinet/in.h>
74 #include <arpa/inet.h>
75
76 #ifdef WITH_OPENSSL
77 #include <openssl/evp.h>
78 #include <openssl/err.h>
79 #endif
80 #include "openbsd-compat/openssl-compat.h"
81 #include "openbsd-compat/sys-queue.h"
82
83 #include "xmalloc.h"
84 #include "ssh.h"
85 #include "ssh2.h"
86 #include "canohost.h"
87 #include "compat.h"
88 #include "cipher.h"
89 #include "packet.h"
90 #include "sshbuf.h"
91 #include "channels.h"
92 #include "sshkey.h"
93 #include "authfd.h"
94 #include "authfile.h"
95 #include "pathnames.h"
96 #include "dispatch.h"
97 #include "clientloop.h"
98 #include "log.h"
99 #include "misc.h"
100 #include "readconf.h"
101 #include "sshconnect.h"
102 #include "kex.h"
103 #include "mac.h"
104 #include "sshpty.h"
105 #include "match.h"
106 #include "msg.h"
107 #include "version.h"
108 #include "ssherr.h"
109 #include "myproposal.h"
110 #include "utf8.h"
111
112 #ifdef ENABLE_PKCS11
113 #include "ssh-pkcs11.h"
114 #endif
115
116 extern char *__progname;
117
118 /* Saves a copy of argv for setproctitle emulation */
119 #ifndef HAVE_SETPROCTITLE
120 static char **saved_av;
121 #endif
122
123 /* Flag indicating whether debug mode is on.  May be set on the command line. */
124 int debug_flag = 0;
125
126 /* Flag indicating whether a tty should be requested */
127 int tty_flag = 0;
128
129 /*
130  * Flag indicating that the current process should be backgrounded and
131  * a new mux-client launched in the foreground for ControlPersist.
132  */
133 int need_controlpersist_detach = 0;
134
135 /* Copies of flags for ControlPersist foreground mux-client */
136 int ostdin_null_flag, osession_type, otty_flag, orequest_tty;
137
138 /*
139  * General data structure for command line options and options configurable
140  * in configuration files.  See readconf.h.
141  */
142 Options options;
143
144 /* optional user configfile */
145 char *config = NULL;
146
147 /*
148  * Name of the host we are connecting to.  This is the name given on the
149  * command line, or the Hostname specified for the user-supplied name in a
150  * configuration file.
151  */
152 char *host;
153
154 /*
155  * A config can specify a path to forward, overriding SSH_AUTH_SOCK. If this is
156  * not NULL, forward the socket at this path instead.
157  */
158 char *forward_agent_sock_path = NULL;
159
160 /* socket address the host resolves to */
161 struct sockaddr_storage hostaddr;
162
163 /* Private host keys. */
164 Sensitive sensitive_data;
165
166 /* command to be executed */
167 struct sshbuf *command;
168
169 /* # of replies received for global requests */
170 static int forward_confirms_pending = -1;
171
172 /* mux.c */
173 extern int muxserver_sock;
174 extern u_int muxclient_command;
175
176 /* Prints a help message to the user.  This function never returns. */
177
178 static void
179 usage(void)
180 {
181         fprintf(stderr,
182 "usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]\n"
183 "           [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]\n"
184 "           [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]\n"
185 "           [-i identity_file] [-J [user@]host[:port]] [-L address]\n"
186 "           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]\n"
187 "           [-Q query_option] [-R address] [-S ctl_path] [-W host:port]\n"
188 "           [-w local_tun[:remote_tun]] destination [command [argument ...]]\n"
189         );
190         exit(255);
191 }
192
193 static int ssh_session2(struct ssh *, const struct ssh_conn_info *);
194 static void load_public_identity_files(const struct ssh_conn_info *);
195 static void main_sigchld_handler(int);
196
197 /* ~/ expand a list of paths. NB. assumes path[n] is heap-allocated. */
198 static void
199 tilde_expand_paths(char **paths, u_int num_paths)
200 {
201         u_int i;
202         char *cp;
203
204         for (i = 0; i < num_paths; i++) {
205                 cp = tilde_expand_filename(paths[i], getuid());
206                 free(paths[i]);
207                 paths[i] = cp;
208         }
209 }
210
211 /*
212  * Expands the set of percent_expand options used by the majority of keywords
213  * in the client that support percent expansion.
214  * Caller must free returned string.
215  */
216 static char *
217 default_client_percent_expand(const char *str,
218     const struct ssh_conn_info *cinfo)
219 {
220         return percent_expand(str,
221             DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
222             (char *)NULL);
223 }
224
225 /*
226  * Expands the set of percent_expand options used by the majority of keywords
227  * AND perform environment variable substitution.
228  * Caller must free returned string.
229  */
230 static char *
231 default_client_percent_dollar_expand(const char *str,
232     const struct ssh_conn_info *cinfo)
233 {
234         char *ret;
235
236         ret = percent_dollar_expand(str,
237             DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
238             (char *)NULL);
239         if (ret == NULL)
240                 fatal("invalid environment variable expansion");
241         return ret;
242 }
243
244 /*
245  * Attempt to resolve a host name / port to a set of addresses and
246  * optionally return any CNAMEs encountered along the way.
247  * Returns NULL on failure.
248  * NB. this function must operate with a options having undefined members.
249  */
250 static struct addrinfo *
251 resolve_host(const char *name, int port, int logerr, char *cname, size_t clen)
252 {
253         char strport[NI_MAXSERV];
254         const char *errstr = NULL;
255         struct addrinfo hints, *res;
256         int gaierr;
257         LogLevel loglevel = SYSLOG_LEVEL_DEBUG1;
258
259         if (port <= 0)
260                 port = default_ssh_port();
261         if (cname != NULL)
262                 *cname = '\0';
263         debug3_f("lookup %s:%d", name, port);
264
265         snprintf(strport, sizeof strport, "%d", port);
266         memset(&hints, 0, sizeof(hints));
267         hints.ai_family = options.address_family == -1 ?
268             AF_UNSPEC : options.address_family;
269         hints.ai_socktype = SOCK_STREAM;
270         if (cname != NULL)
271                 hints.ai_flags = AI_CANONNAME;
272         if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
273                 if (logerr || (gaierr != EAI_NONAME && gaierr != EAI_NODATA))
274                         loglevel = SYSLOG_LEVEL_ERROR;
275                 do_log2(loglevel, "%s: Could not resolve hostname %.100s: %s",
276                     __progname, name, ssh_gai_strerror(gaierr));
277                 return NULL;
278         }
279         if (cname != NULL && res->ai_canonname != NULL) {
280                 if (!valid_domain(res->ai_canonname, 0, &errstr)) {
281                         error("ignoring bad CNAME \"%s\" for host \"%s\": %s",
282                             res->ai_canonname, name, errstr);
283                 } else if (strlcpy(cname, res->ai_canonname, clen) >= clen) {
284                         error_f("host \"%s\" cname \"%s\" too long (max %lu)",
285                             name,  res->ai_canonname, (u_long)clen);
286                         if (clen > 0)
287                                 *cname = '\0';
288                 }
289         }
290         return res;
291 }
292
293 /* Returns non-zero if name can only be an address and not a hostname */
294 static int
295 is_addr_fast(const char *name)
296 {
297         return (strchr(name, '%') != NULL || strchr(name, ':') != NULL ||
298             strspn(name, "0123456789.") == strlen(name));
299 }
300
301 /* Returns non-zero if name represents a valid, single address */
302 static int
303 is_addr(const char *name)
304 {
305         char strport[NI_MAXSERV];
306         struct addrinfo hints, *res;
307
308         if (is_addr_fast(name))
309                 return 1;
310
311         snprintf(strport, sizeof strport, "%u", default_ssh_port());
312         memset(&hints, 0, sizeof(hints));
313         hints.ai_family = options.address_family == -1 ?
314             AF_UNSPEC : options.address_family;
315         hints.ai_socktype = SOCK_STREAM;
316         hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
317         if (getaddrinfo(name, strport, &hints, &res) != 0)
318                 return 0;
319         if (res == NULL || res->ai_next != NULL) {
320                 freeaddrinfo(res);
321                 return 0;
322         }
323         freeaddrinfo(res);
324         return 1;
325 }
326
327 /*
328  * Attempt to resolve a numeric host address / port to a single address.
329  * Returns a canonical address string.
330  * Returns NULL on failure.
331  * NB. this function must operate with a options having undefined members.
332  */
333 static struct addrinfo *
334 resolve_addr(const char *name, int port, char *caddr, size_t clen)
335 {
336         char addr[NI_MAXHOST], strport[NI_MAXSERV];
337         struct addrinfo hints, *res;
338         int gaierr;
339
340         if (port <= 0)
341                 port = default_ssh_port();
342         snprintf(strport, sizeof strport, "%u", port);
343         memset(&hints, 0, sizeof(hints));
344         hints.ai_family = options.address_family == -1 ?
345             AF_UNSPEC : options.address_family;
346         hints.ai_socktype = SOCK_STREAM;
347         hints.ai_flags = AI_NUMERICHOST|AI_NUMERICSERV;
348         if ((gaierr = getaddrinfo(name, strport, &hints, &res)) != 0) {
349                 debug2_f("could not resolve name %.100s as address: %s",
350                     name, ssh_gai_strerror(gaierr));
351                 return NULL;
352         }
353         if (res == NULL) {
354                 debug_f("getaddrinfo %.100s returned no addresses", name);
355                 return NULL;
356         }
357         if (res->ai_next != NULL) {
358                 debug_f("getaddrinfo %.100s returned multiple addresses", name);
359                 goto fail;
360         }
361         if ((gaierr = getnameinfo(res->ai_addr, res->ai_addrlen,
362             addr, sizeof(addr), NULL, 0, NI_NUMERICHOST)) != 0) {
363                 debug_f("Could not format address for name %.100s: %s",
364                     name, ssh_gai_strerror(gaierr));
365                 goto fail;
366         }
367         if (strlcpy(caddr, addr, clen) >= clen) {
368                 error_f("host \"%s\" addr \"%s\" too long (max %lu)",
369                     name,  addr, (u_long)clen);
370                 if (clen > 0)
371                         *caddr = '\0';
372  fail:
373                 freeaddrinfo(res);
374                 return NULL;
375         }
376         return res;
377 }
378
379 /*
380  * Check whether the cname is a permitted replacement for the hostname
381  * and perform the replacement if it is.
382  * NB. this function must operate with a options having undefined members.
383  */
384 static int
385 check_follow_cname(int direct, char **namep, const char *cname)
386 {
387         int i;
388         struct allowed_cname *rule;
389
390         if (*cname == '\0' || !config_has_permitted_cnames(&options) ||
391             strcmp(*namep, cname) == 0)
392                 return 0;
393         if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
394                 return 0;
395         /*
396          * Don't attempt to canonicalize names that will be interpreted by
397          * a proxy or jump host unless the user specifically requests so.
398          */
399         if (!direct &&
400             options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
401                 return 0;
402         debug3_f("check \"%s\" CNAME \"%s\"", *namep, cname);
403         for (i = 0; i < options.num_permitted_cnames; i++) {
404                 rule = options.permitted_cnames + i;
405                 if (match_pattern_list(*namep, rule->source_list, 1) != 1 ||
406                     match_pattern_list(cname, rule->target_list, 1) != 1)
407                         continue;
408                 verbose("Canonicalized DNS aliased hostname "
409                     "\"%s\" => \"%s\"", *namep, cname);
410                 free(*namep);
411                 *namep = xstrdup(cname);
412                 return 1;
413         }
414         return 0;
415 }
416
417 /*
418  * Attempt to resolve the supplied hostname after applying the user's
419  * canonicalization rules. Returns the address list for the host or NULL
420  * if no name was found after canonicalization.
421  * NB. this function must operate with a options having undefined members.
422  */
423 static struct addrinfo *
424 resolve_canonicalize(char **hostp, int port)
425 {
426         int i, direct, ndots;
427         char *cp, *fullhost, newname[NI_MAXHOST];
428         struct addrinfo *addrs;
429
430         /*
431          * Attempt to canonicalise addresses, regardless of
432          * whether hostname canonicalisation was requested
433          */
434         if ((addrs = resolve_addr(*hostp, port,
435             newname, sizeof(newname))) != NULL) {
436                 debug2_f("hostname %.100s is address", *hostp);
437                 if (strcasecmp(*hostp, newname) != 0) {
438                         debug2_f("canonicalised address \"%s\" => \"%s\"",
439                             *hostp, newname);
440                         free(*hostp);
441                         *hostp = xstrdup(newname);
442                 }
443                 return addrs;
444         }
445
446         /*
447          * If this looks like an address but didn't parse as one, it might
448          * be an address with an invalid interface scope. Skip further
449          * attempts at canonicalisation.
450          */
451         if (is_addr_fast(*hostp)) {
452                 debug_f("hostname %.100s is an unrecognised address", *hostp);
453                 return NULL;
454         }
455
456         if (options.canonicalize_hostname == SSH_CANONICALISE_NO)
457                 return NULL;
458
459         /*
460          * Don't attempt to canonicalize names that will be interpreted by
461          * a proxy unless the user specifically requests so.
462          */
463         direct = option_clear_or_none(options.proxy_command) &&
464             options.jump_host == NULL;
465         if (!direct &&
466             options.canonicalize_hostname != SSH_CANONICALISE_ALWAYS)
467                 return NULL;
468
469         /* If domain name is anchored, then resolve it now */
470         if ((*hostp)[strlen(*hostp) - 1] == '.') {
471                 debug3_f("name is fully qualified");
472                 fullhost = xstrdup(*hostp);
473                 if ((addrs = resolve_host(fullhost, port, 0,
474                     newname, sizeof(newname))) != NULL)
475                         goto found;
476                 free(fullhost);
477                 goto notfound;
478         }
479
480         /* Don't apply canonicalization to sufficiently-qualified hostnames */
481         ndots = 0;
482         for (cp = *hostp; *cp != '\0'; cp++) {
483                 if (*cp == '.')
484                         ndots++;
485         }
486         if (ndots > options.canonicalize_max_dots) {
487                 debug3_f("not canonicalizing hostname \"%s\" (max dots %d)",
488                     *hostp, options.canonicalize_max_dots);
489                 return NULL;
490         }
491         /* Attempt each supplied suffix */
492         for (i = 0; i < options.num_canonical_domains; i++) {
493                 if (strcasecmp(options.canonical_domains[i], "none") == 0)
494                         break;
495                 xasprintf(&fullhost, "%s.%s.", *hostp,
496                     options.canonical_domains[i]);
497                 debug3_f("attempting \"%s\" => \"%s\"", *hostp, fullhost);
498                 if ((addrs = resolve_host(fullhost, port, 0,
499                     newname, sizeof(newname))) == NULL) {
500                         free(fullhost);
501                         continue;
502                 }
503  found:
504                 /* Remove trailing '.' */
505                 fullhost[strlen(fullhost) - 1] = '\0';
506                 /* Follow CNAME if requested */
507                 if (!check_follow_cname(direct, &fullhost, newname)) {
508                         debug("Canonicalized hostname \"%s\" => \"%s\"",
509                             *hostp, fullhost);
510                 }
511                 free(*hostp);
512                 *hostp = fullhost;
513                 return addrs;
514         }
515  notfound:
516         if (!options.canonicalize_fallback_local)
517                 fatal("%s: Could not resolve host \"%s\"", __progname, *hostp);
518         debug2_f("host %s not found in any suffix", *hostp);
519         return NULL;
520 }
521
522 /*
523  * Check the result of hostkey loading, ignoring some errors and either
524  * discarding the key or fatal()ing for others.
525  */
526 static void
527 check_load(int r, struct sshkey **k, const char *path, const char *message)
528 {
529         switch (r) {
530         case 0:
531                 /* Check RSA keys size and discard if undersized */
532                 if (k != NULL && *k != NULL &&
533                     (r = sshkey_check_rsa_length(*k,
534                     options.required_rsa_size)) != 0) {
535                         error_r(r, "load %s \"%s\"", message, path);
536                         free(*k);
537                         *k = NULL;
538                 }
539                 break;
540         case SSH_ERR_INTERNAL_ERROR:
541         case SSH_ERR_ALLOC_FAIL:
542                 fatal_r(r, "load %s \"%s\"", message, path);
543         case SSH_ERR_SYSTEM_ERROR:
544                 /* Ignore missing files */
545                 if (errno == ENOENT)
546                         break;
547                 /* FALLTHROUGH */
548         default:
549                 error_r(r, "load %s \"%s\"", message, path);
550                 break;
551         }
552 }
553
554 /*
555  * Read per-user configuration file.  Ignore the system wide config
556  * file if the user specifies a config file on the command line.
557  */
558 static void
559 process_config_files(const char *host_name, struct passwd *pw, int final_pass,
560     int *want_final_pass)
561 {
562         char buf[PATH_MAX];
563         int r;
564
565         if (config != NULL) {
566                 if (strcasecmp(config, "none") != 0 &&
567                     !read_config_file(config, pw, host, host_name, &options,
568                     SSHCONF_USERCONF | (final_pass ? SSHCONF_FINAL : 0),
569                     want_final_pass))
570                         fatal("Can't open user config file %.100s: "
571                             "%.100s", config, strerror(errno));
572         } else {
573                 r = snprintf(buf, sizeof buf, "%s/%s", pw->pw_dir,
574                     _PATH_SSH_USER_CONFFILE);
575                 if (r > 0 && (size_t)r < sizeof(buf))
576                         (void)read_config_file(buf, pw, host, host_name,
577                             &options, SSHCONF_CHECKPERM | SSHCONF_USERCONF |
578                             (final_pass ? SSHCONF_FINAL : 0), want_final_pass);
579
580                 /* Read systemwide configuration file after user config. */
581                 (void)read_config_file(_PATH_HOST_CONFIG_FILE, pw,
582                     host, host_name, &options,
583                     final_pass ? SSHCONF_FINAL : 0, want_final_pass);
584         }
585 }
586
587 /* Rewrite the port number in an addrinfo list of addresses */
588 static void
589 set_addrinfo_port(struct addrinfo *addrs, int port)
590 {
591         struct addrinfo *addr;
592
593         for (addr = addrs; addr != NULL; addr = addr->ai_next) {
594                 switch (addr->ai_family) {
595                 case AF_INET:
596                         ((struct sockaddr_in *)addr->ai_addr)->
597                             sin_port = htons(port);
598                         break;
599                 case AF_INET6:
600                         ((struct sockaddr_in6 *)addr->ai_addr)->
601                             sin6_port = htons(port);
602                         break;
603                 }
604         }
605 }
606
607 static void
608 ssh_conn_info_free(struct ssh_conn_info *cinfo)
609 {
610         if (cinfo == NULL)
611                 return;
612         free(cinfo->conn_hash_hex);
613         free(cinfo->shorthost);
614         free(cinfo->uidstr);
615         free(cinfo->keyalias);
616         free(cinfo->thishost);
617         free(cinfo->host_arg);
618         free(cinfo->portstr);
619         free(cinfo->remhost);
620         free(cinfo->remuser);
621         free(cinfo->homedir);
622         free(cinfo->locuser);
623         free(cinfo);
624 }
625
626 /*
627  * Main program for the ssh client.
628  */
629 int
630 main(int ac, char **av)
631 {
632         struct ssh *ssh = NULL;
633         int i, r, opt, exit_status, use_syslog, direct, timeout_ms;
634         int was_addr, config_test = 0, opt_terminated = 0, want_final_pass = 0;
635         char *p, *cp, *line, *argv0, *logfile;
636         char cname[NI_MAXHOST], thishost[NI_MAXHOST];
637         struct stat st;
638         struct passwd *pw;
639         extern int optind, optreset;
640         extern char *optarg;
641         struct Forward fwd;
642         struct addrinfo *addrs = NULL;
643         size_t n, len;
644         u_int j;
645         struct ssh_conn_info *cinfo = NULL;
646
647         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
648         sanitise_stdfd();
649
650         /*
651          * Discard other fds that are hanging around. These can cause problem
652          * with backgrounded ssh processes started by ControlPersist.
653          */
654         closefrom(STDERR_FILENO + 1);
655
656         __progname = ssh_get_progname(av[0]);
657
658 #ifndef HAVE_SETPROCTITLE
659         /* Prepare for later setproctitle emulation */
660         /* Save argv so it isn't clobbered by setproctitle() emulation */
661         saved_av = xcalloc(ac + 1, sizeof(*saved_av));
662         for (i = 0; i < ac; i++)
663                 saved_av[i] = xstrdup(av[i]);
664         saved_av[i] = NULL;
665         compat_init_setproctitle(ac, av);
666         av = saved_av;
667 #endif
668
669         seed_rng();
670
671         /* Get user data. */
672         pw = getpwuid(getuid());
673         if (!pw) {
674                 logit("No user exists for uid %lu", (u_long)getuid());
675                 exit(255);
676         }
677         /* Take a copy of the returned structure. */
678         pw = pwcopy(pw);
679
680         /*
681          * Set our umask to something reasonable, as some files are created
682          * with the default umask.  This will make them world-readable but
683          * writable only by the owner, which is ok for all files for which we
684          * don't set the modes explicitly.
685          */
686         umask(022 | umask(077));
687
688         msetlocale();
689
690         /*
691          * Initialize option structure to indicate that no values have been
692          * set.
693          */
694         initialize_options(&options);
695
696         /*
697          * Prepare main ssh transport/connection structures
698          */
699         if ((ssh = ssh_alloc_session_state()) == NULL)
700                 fatal("Couldn't allocate session state");
701         channel_init_channels(ssh);
702
703         /* Parse command-line arguments. */
704         host = NULL;
705         use_syslog = 0;
706         logfile = NULL;
707         argv0 = av[0];
708
709  again:
710         while ((opt = getopt(ac, av, "1246ab:c:e:fgi:kl:m:no:p:qstvx"
711             "AB:CD:E:F:GI:J:KL:MNO:PQ:R:S:TVw:W:XYy")) != -1) { /* HUZdhjruz */
712                 switch (opt) {
713                 case '1':
714                         fatal("SSH protocol v.1 is no longer supported");
715                         break;
716                 case '2':
717                         /* Ignored */
718                         break;
719                 case '4':
720                         options.address_family = AF_INET;
721                         break;
722                 case '6':
723                         options.address_family = AF_INET6;
724                         break;
725                 case 'n':
726                         options.stdin_null = 1;
727                         break;
728                 case 'f':
729                         options.fork_after_authentication = 1;
730                         options.stdin_null = 1;
731                         break;
732                 case 'x':
733                         options.forward_x11 = 0;
734                         break;
735                 case 'X':
736                         options.forward_x11 = 1;
737                         break;
738                 case 'y':
739                         use_syslog = 1;
740                         break;
741                 case 'E':
742                         logfile = optarg;
743                         break;
744                 case 'G':
745                         config_test = 1;
746                         break;
747                 case 'Y':
748                         options.forward_x11 = 1;
749                         options.forward_x11_trusted = 1;
750                         break;
751                 case 'g':
752                         options.fwd_opts.gateway_ports = 1;
753                         break;
754                 case 'O':
755                         if (options.stdio_forward_host != NULL)
756                                 fatal("Cannot specify multiplexing "
757                                     "command with -W");
758                         else if (muxclient_command != 0)
759                                 fatal("Multiplexing command already specified");
760                         if (strcmp(optarg, "check") == 0)
761                                 muxclient_command = SSHMUX_COMMAND_ALIVE_CHECK;
762                         else if (strcmp(optarg, "forward") == 0)
763                                 muxclient_command = SSHMUX_COMMAND_FORWARD;
764                         else if (strcmp(optarg, "exit") == 0)
765                                 muxclient_command = SSHMUX_COMMAND_TERMINATE;
766                         else if (strcmp(optarg, "stop") == 0)
767                                 muxclient_command = SSHMUX_COMMAND_STOP;
768                         else if (strcmp(optarg, "cancel") == 0)
769                                 muxclient_command = SSHMUX_COMMAND_CANCEL_FWD;
770                         else if (strcmp(optarg, "proxy") == 0)
771                                 muxclient_command = SSHMUX_COMMAND_PROXY;
772                         else
773                                 fatal("Invalid multiplex command.");
774                         break;
775                 case 'P':       /* deprecated */
776                         break;
777                 case 'Q':
778                         cp = NULL;
779                         if (strcmp(optarg, "cipher") == 0 ||
780                             strcasecmp(optarg, "Ciphers") == 0)
781                                 cp = cipher_alg_list('\n', 0);
782                         else if (strcmp(optarg, "cipher-auth") == 0)
783                                 cp = cipher_alg_list('\n', 1);
784                         else if (strcmp(optarg, "mac") == 0 ||
785                             strcasecmp(optarg, "MACs") == 0)
786                                 cp = mac_alg_list('\n');
787                         else if (strcmp(optarg, "kex") == 0 ||
788                             strcasecmp(optarg, "KexAlgorithms") == 0)
789                                 cp = kex_alg_list('\n');
790                         else if (strcmp(optarg, "key") == 0)
791                                 cp = sshkey_alg_list(0, 0, 0, '\n');
792                         else if (strcmp(optarg, "key-cert") == 0)
793                                 cp = sshkey_alg_list(1, 0, 0, '\n');
794                         else if (strcmp(optarg, "key-plain") == 0)
795                                 cp = sshkey_alg_list(0, 1, 0, '\n');
796                         else if (strcmp(optarg, "key-sig") == 0 ||
797                             strcasecmp(optarg, "CASignatureAlgorithms") == 0 ||
798                             strcasecmp(optarg, "PubkeyAcceptedKeyTypes") == 0 || /* deprecated name */
799                             strcasecmp(optarg, "PubkeyAcceptedAlgorithms") == 0 ||
800                             strcasecmp(optarg, "HostKeyAlgorithms") == 0 ||
801                             strcasecmp(optarg, "HostbasedKeyTypes") == 0 || /* deprecated name */
802                             strcasecmp(optarg, "HostbasedAcceptedKeyTypes") == 0 || /* deprecated name */
803                             strcasecmp(optarg, "HostbasedAcceptedAlgorithms") == 0)
804                                 cp = sshkey_alg_list(0, 0, 1, '\n');
805                         else if (strcmp(optarg, "sig") == 0)
806                                 cp = sshkey_alg_list(0, 1, 1, '\n');
807                         else if (strcmp(optarg, "protocol-version") == 0)
808                                 cp = xstrdup("2");
809                         else if (strcmp(optarg, "compression") == 0) {
810                                 cp = xstrdup(compression_alg_list(0));
811                                 len = strlen(cp);
812                                 for (n = 0; n < len; n++)
813                                         if (cp[n] == ',')
814                                                 cp[n] = '\n';
815                         } else if (strcmp(optarg, "help") == 0) {
816                                 cp = xstrdup(
817                                     "cipher\ncipher-auth\ncompression\nkex\n"
818                                     "key\nkey-cert\nkey-plain\nkey-sig\nmac\n"
819                                     "protocol-version\nsig");
820                         }
821                         if (cp == NULL)
822                                 fatal("Unsupported query \"%s\"", optarg);
823                         printf("%s\n", cp);
824                         free(cp);
825                         exit(0);
826                         break;
827                 case 'a':
828                         options.forward_agent = 0;
829                         break;
830                 case 'A':
831                         options.forward_agent = 1;
832                         break;
833                 case 'k':
834                         options.gss_deleg_creds = 0;
835                         break;
836                 case 'K':
837                         options.gss_authentication = 1;
838                         options.gss_deleg_creds = 1;
839                         break;
840                 case 'i':
841                         p = tilde_expand_filename(optarg, getuid());
842                         if (stat(p, &st) == -1)
843                                 fprintf(stderr, "Warning: Identity file %s "
844                                     "not accessible: %s.\n", p,
845                                     strerror(errno));
846                         else
847                                 add_identity_file(&options, NULL, p, 1);
848                         free(p);
849                         break;
850                 case 'I':
851 #ifdef ENABLE_PKCS11
852                         free(options.pkcs11_provider);
853                         options.pkcs11_provider = xstrdup(optarg);
854 #else
855                         fprintf(stderr, "no support for PKCS#11.\n");
856 #endif
857                         break;
858                 case 'J':
859                         if (options.jump_host != NULL) {
860                                 fatal("Only a single -J option is permitted "
861                                     "(use commas to separate multiple "
862                                     "jump hops)");
863                         }
864                         if (options.proxy_command != NULL)
865                                 fatal("Cannot specify -J with ProxyCommand");
866                         if (parse_jump(optarg, &options, 1) == -1)
867                                 fatal("Invalid -J argument");
868                         options.proxy_command = xstrdup("none");
869                         break;
870                 case 't':
871                         if (options.request_tty == REQUEST_TTY_YES)
872                                 options.request_tty = REQUEST_TTY_FORCE;
873                         else
874                                 options.request_tty = REQUEST_TTY_YES;
875                         break;
876                 case 'v':
877                         if (debug_flag == 0) {
878                                 debug_flag = 1;
879                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
880                         } else {
881                                 if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
882                                         debug_flag++;
883                                         options.log_level++;
884                                 }
885                         }
886                         break;
887                 case 'V':
888                         if (options.version_addendum != NULL &&
889                             *options.version_addendum != '\0')
890                                 fprintf(stderr, "%s %s, %s\n", SSH_RELEASE,
891                                     options.version_addendum,
892                                     SSH_OPENSSL_VERSION);
893                         else
894                                 fprintf(stderr, "%s, %s\n", SSH_RELEASE,
895                                     SSH_OPENSSL_VERSION);
896                         exit(0);
897                         break;
898                 case 'w':
899                         if (options.tun_open == -1)
900                                 options.tun_open = SSH_TUNMODE_DEFAULT;
901                         options.tun_local = a2tun(optarg, &options.tun_remote);
902                         if (options.tun_local == SSH_TUNID_ERR) {
903                                 fprintf(stderr,
904                                     "Bad tun device '%s'\n", optarg);
905                                 exit(255);
906                         }
907                         break;
908                 case 'W':
909                         if (options.stdio_forward_host != NULL)
910                                 fatal("stdio forward already specified");
911                         if (muxclient_command != 0)
912                                 fatal("Cannot specify stdio forward with -O");
913                         if (parse_forward(&fwd, optarg, 1, 0)) {
914                                 options.stdio_forward_host = fwd.listen_host;
915                                 options.stdio_forward_port = fwd.listen_port;
916                                 free(fwd.connect_host);
917                         } else {
918                                 fprintf(stderr,
919                                     "Bad stdio forwarding specification '%s'\n",
920                                     optarg);
921                                 exit(255);
922                         }
923                         options.request_tty = REQUEST_TTY_NO;
924                         options.session_type = SESSION_TYPE_NONE;
925                         break;
926                 case 'q':
927                         options.log_level = SYSLOG_LEVEL_QUIET;
928                         break;
929                 case 'e':
930                         if (optarg[0] == '^' && optarg[2] == 0 &&
931                             (u_char) optarg[1] >= 64 &&
932                             (u_char) optarg[1] < 128)
933                                 options.escape_char = (u_char) optarg[1] & 31;
934                         else if (strlen(optarg) == 1)
935                                 options.escape_char = (u_char) optarg[0];
936                         else if (strcmp(optarg, "none") == 0)
937                                 options.escape_char = SSH_ESCAPECHAR_NONE;
938                         else {
939                                 fprintf(stderr, "Bad escape character '%s'.\n",
940                                     optarg);
941                                 exit(255);
942                         }
943                         break;
944                 case 'c':
945                         if (!ciphers_valid(*optarg == '+' || *optarg == '^' ?
946                             optarg + 1 : optarg)) {
947                                 fprintf(stderr, "Unknown cipher type '%s'\n",
948                                     optarg);
949                                 exit(255);
950                         }
951                         free(options.ciphers);
952                         options.ciphers = xstrdup(optarg);
953                         break;
954                 case 'm':
955                         if (mac_valid(optarg)) {
956                                 free(options.macs);
957                                 options.macs = xstrdup(optarg);
958                         } else {
959                                 fprintf(stderr, "Unknown mac type '%s'\n",
960                                     optarg);
961                                 exit(255);
962                         }
963                         break;
964                 case 'M':
965                         if (options.control_master == SSHCTL_MASTER_YES)
966                                 options.control_master = SSHCTL_MASTER_ASK;
967                         else
968                                 options.control_master = SSHCTL_MASTER_YES;
969                         break;
970                 case 'p':
971                         if (options.port == -1) {
972                                 options.port = a2port(optarg);
973                                 if (options.port <= 0) {
974                                         fprintf(stderr, "Bad port '%s'\n",
975                                             optarg);
976                                         exit(255);
977                                 }
978                         }
979                         break;
980                 case 'l':
981                         if (options.user == NULL)
982                                 options.user = optarg;
983                         break;
984
985                 case 'L':
986                         if (parse_forward(&fwd, optarg, 0, 0))
987                                 add_local_forward(&options, &fwd);
988                         else {
989                                 fprintf(stderr,
990                                     "Bad local forwarding specification '%s'\n",
991                                     optarg);
992                                 exit(255);
993                         }
994                         break;
995
996                 case 'R':
997                         if (parse_forward(&fwd, optarg, 0, 1) ||
998                             parse_forward(&fwd, optarg, 1, 1)) {
999                                 add_remote_forward(&options, &fwd);
1000                         } else {
1001                                 fprintf(stderr,
1002                                     "Bad remote forwarding specification "
1003                                     "'%s'\n", optarg);
1004                                 exit(255);
1005                         }
1006                         break;
1007
1008                 case 'D':
1009                         if (parse_forward(&fwd, optarg, 1, 0)) {
1010                                 add_local_forward(&options, &fwd);
1011                         } else {
1012                                 fprintf(stderr,
1013                                     "Bad dynamic forwarding specification "
1014                                     "'%s'\n", optarg);
1015                                 exit(255);
1016                         }
1017                         break;
1018
1019                 case 'C':
1020 #ifdef WITH_ZLIB
1021                         options.compression = 1;
1022 #else
1023                         error("Compression not supported, disabling.");
1024 #endif
1025                         break;
1026                 case 'N':
1027                         if (options.session_type != -1 &&
1028                             options.session_type != SESSION_TYPE_NONE)
1029                                 fatal("Cannot specify -N with -s/SessionType");
1030                         options.session_type = SESSION_TYPE_NONE;
1031                         options.request_tty = REQUEST_TTY_NO;
1032                         break;
1033                 case 'T':
1034                         options.request_tty = REQUEST_TTY_NO;
1035                         break;
1036                 case 'o':
1037                         line = xstrdup(optarg);
1038                         if (process_config_line(&options, pw,
1039                             host ? host : "", host ? host : "", line,
1040                             "command-line", 0, NULL, SSHCONF_USERCONF) != 0)
1041                                 exit(255);
1042                         free(line);
1043                         break;
1044                 case 's':
1045                         if (options.session_type != -1 &&
1046                             options.session_type != SESSION_TYPE_SUBSYSTEM)
1047                                 fatal("Cannot specify -s with -N/SessionType");
1048                         options.session_type = SESSION_TYPE_SUBSYSTEM;
1049                         break;
1050                 case 'S':
1051                         free(options.control_path);
1052                         options.control_path = xstrdup(optarg);
1053                         break;
1054                 case 'b':
1055                         options.bind_address = optarg;
1056                         break;
1057                 case 'B':
1058                         options.bind_interface = optarg;
1059                         break;
1060                 case 'F':
1061                         config = optarg;
1062                         break;
1063                 default:
1064                         usage();
1065                 }
1066         }
1067
1068         if (optind > 1 && strcmp(av[optind - 1], "--") == 0)
1069                 opt_terminated = 1;
1070
1071         ac -= optind;
1072         av += optind;
1073
1074         if (ac > 0 && !host) {
1075                 int tport;
1076                 char *tuser;
1077                 switch (parse_ssh_uri(*av, &tuser, &host, &tport)) {
1078                 case -1:
1079                         usage();
1080                         break;
1081                 case 0:
1082                         if (options.user == NULL) {
1083                                 options.user = tuser;
1084                                 tuser = NULL;
1085                         }
1086                         free(tuser);
1087                         if (options.port == -1 && tport != -1)
1088                                 options.port = tport;
1089                         break;
1090                 default:
1091                         p = xstrdup(*av);
1092                         cp = strrchr(p, '@');
1093                         if (cp != NULL) {
1094                                 if (cp == p)
1095                                         usage();
1096                                 if (options.user == NULL) {
1097                                         options.user = p;
1098                                         p = NULL;
1099                                 }
1100                                 *cp++ = '\0';
1101                                 host = xstrdup(cp);
1102                                 free(p);
1103                         } else
1104                                 host = p;
1105                         break;
1106                 }
1107                 if (ac > 1 && !opt_terminated) {
1108                         optind = optreset = 1;
1109                         goto again;
1110                 }
1111                 ac--, av++;
1112         }
1113
1114         /* Check that we got a host name. */
1115         if (!host)
1116                 usage();
1117
1118         options.host_arg = xstrdup(host);
1119
1120         /* Initialize the command to execute on remote host. */
1121         if ((command = sshbuf_new()) == NULL)
1122                 fatal("sshbuf_new failed");
1123
1124         /*
1125          * Save the command to execute on the remote host in a buffer. There
1126          * is no limit on the length of the command, except by the maximum
1127          * packet size.  Also sets the tty flag if there is no command.
1128          */
1129         if (!ac) {
1130                 /* No command specified - execute shell on a tty. */
1131                 if (options.session_type == SESSION_TYPE_SUBSYSTEM) {
1132                         fprintf(stderr,
1133                             "You must specify a subsystem to invoke.\n");
1134                         usage();
1135                 }
1136         } else {
1137                 /* A command has been specified.  Store it into the buffer. */
1138                 for (i = 0; i < ac; i++) {
1139                         if ((r = sshbuf_putf(command, "%s%s",
1140                             i ? " " : "", av[i])) != 0)
1141                                 fatal_fr(r, "buffer error");
1142                 }
1143         }
1144
1145         ssh_signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE early */
1146
1147         /*
1148          * Initialize "log" output.  Since we are the client all output
1149          * goes to stderr unless otherwise specified by -y or -E.
1150          */
1151         if (use_syslog && logfile != NULL)
1152                 fatal("Can't specify both -y and -E");
1153         if (logfile != NULL)
1154                 log_redirect_stderr_to(logfile);
1155         log_init(argv0,
1156             options.log_level == SYSLOG_LEVEL_NOT_SET ?
1157             SYSLOG_LEVEL_INFO : options.log_level,
1158             options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1159             SYSLOG_FACILITY_USER : options.log_facility,
1160             !use_syslog);
1161
1162         if (debug_flag)
1163                 /* version_addendum is always NULL at this point */
1164                 logit("%s, %s", SSH_RELEASE, SSH_OPENSSL_VERSION);
1165
1166         /* Parse the configuration files */
1167         process_config_files(options.host_arg, pw, 0, &want_final_pass);
1168         if (want_final_pass)
1169                 debug("configuration requests final Match pass");
1170
1171         /* Hostname canonicalisation needs a few options filled. */
1172         fill_default_options_for_canonicalization(&options);
1173
1174         /* If the user has replaced the hostname then take it into use now */
1175         if (options.hostname != NULL) {
1176                 /* NB. Please keep in sync with readconf.c:match_cfg_line() */
1177                 cp = percent_expand(options.hostname,
1178                     "h", host, (char *)NULL);
1179                 free(host);
1180                 host = cp;
1181                 free(options.hostname);
1182                 options.hostname = xstrdup(host);
1183         }
1184
1185         /* Don't lowercase addresses, they will be explicitly canonicalised */
1186         if ((was_addr = is_addr(host)) == 0)
1187                 lowercase(host);
1188
1189         /*
1190          * Try to canonicalize if requested by configuration or the
1191          * hostname is an address.
1192          */
1193         if (options.canonicalize_hostname != SSH_CANONICALISE_NO || was_addr)
1194                 addrs = resolve_canonicalize(&host, options.port);
1195
1196         /*
1197          * If CanonicalizePermittedCNAMEs have been specified but
1198          * other canonicalization did not happen (by not being requested
1199          * or by failing with fallback) then the hostname may still be changed
1200          * as a result of CNAME following.
1201          *
1202          * Try to resolve the bare hostname name using the system resolver's
1203          * usual search rules and then apply the CNAME follow rules.
1204          *
1205          * Skip the lookup if a ProxyCommand is being used unless the user
1206          * has specifically requested canonicalisation for this case via
1207          * CanonicalizeHostname=always
1208          */
1209         direct = option_clear_or_none(options.proxy_command) &&
1210             options.jump_host == NULL;
1211         if (addrs == NULL && config_has_permitted_cnames(&options) && (direct ||
1212             options.canonicalize_hostname == SSH_CANONICALISE_ALWAYS)) {
1213                 if ((addrs = resolve_host(host, options.port,
1214                     direct, cname, sizeof(cname))) == NULL) {
1215                         /* Don't fatal proxied host names not in the DNS */
1216                         if (direct)
1217                                 cleanup_exit(255); /* logged in resolve_host */
1218                 } else
1219                         check_follow_cname(direct, &host, cname);
1220         }
1221
1222         /*
1223          * If canonicalisation is enabled then re-parse the configuration
1224          * files as new stanzas may match.
1225          */
1226         if (options.canonicalize_hostname != 0 && !want_final_pass) {
1227                 debug("hostname canonicalisation enabled, "
1228                     "will re-parse configuration");
1229                 want_final_pass = 1;
1230         }
1231
1232         if (want_final_pass) {
1233                 debug("re-parsing configuration");
1234                 free(options.hostname);
1235                 options.hostname = xstrdup(host);
1236                 process_config_files(options.host_arg, pw, 1, NULL);
1237                 /*
1238                  * Address resolution happens early with canonicalisation
1239                  * enabled and the port number may have changed since, so
1240                  * reset it in address list
1241                  */
1242                 if (addrs != NULL && options.port > 0)
1243                         set_addrinfo_port(addrs, options.port);
1244         }
1245
1246         /* Fill configuration defaults. */
1247         if (fill_default_options(&options) != 0)
1248                 cleanup_exit(255);
1249
1250         if (options.user == NULL)
1251                 options.user = xstrdup(pw->pw_name);
1252
1253         /*
1254          * If ProxyJump option specified, then construct a ProxyCommand now.
1255          */
1256         if (options.jump_host != NULL) {
1257                 char port_s[8];
1258                 const char *jumpuser = options.jump_user, *sshbin = argv0;
1259                 int port = options.port, jumpport = options.jump_port;
1260
1261                 if (port <= 0)
1262                         port = default_ssh_port();
1263                 if (jumpport <= 0)
1264                         jumpport = default_ssh_port();
1265                 if (jumpuser == NULL)
1266                         jumpuser = options.user;
1267                 if (strcmp(options.jump_host, host) == 0 && port == jumpport &&
1268                     strcmp(options.user, jumpuser) == 0)
1269                         fatal("jumphost loop via %s", options.jump_host);
1270
1271                 /*
1272                  * Try to use SSH indicated by argv[0], but fall back to
1273                  * "ssh" if it appears unavailable.
1274                  */
1275                 if (strchr(argv0, '/') != NULL && access(argv0, X_OK) != 0)
1276                         sshbin = "ssh";
1277
1278                 /* Consistency check */
1279                 if (options.proxy_command != NULL)
1280                         fatal("inconsistent options: ProxyCommand+ProxyJump");
1281                 /* Never use FD passing for ProxyJump */
1282                 options.proxy_use_fdpass = 0;
1283                 snprintf(port_s, sizeof(port_s), "%d", options.jump_port);
1284                 xasprintf(&options.proxy_command,
1285                     "%s%s%s%s%s%s%s%s%s%s%.*s -W '[%%h]:%%p' %s",
1286                     sshbin,
1287                     /* Optional "-l user" argument if jump_user set */
1288                     options.jump_user == NULL ? "" : " -l ",
1289                     options.jump_user == NULL ? "" : options.jump_user,
1290                     /* Optional "-p port" argument if jump_port set */
1291                     options.jump_port <= 0 ? "" : " -p ",
1292                     options.jump_port <= 0 ? "" : port_s,
1293                     /* Optional additional jump hosts ",..." */
1294                     options.jump_extra == NULL ? "" : " -J ",
1295                     options.jump_extra == NULL ? "" : options.jump_extra,
1296                     /* Optional "-F" argument if -F specified */
1297                     config == NULL ? "" : " -F ",
1298                     config == NULL ? "" : config,
1299                     /* Optional "-v" arguments if -v set */
1300                     debug_flag ? " -" : "",
1301                     debug_flag, "vvv",
1302                     /* Mandatory hostname */
1303                     options.jump_host);
1304                 debug("Setting implicit ProxyCommand from ProxyJump: %s",
1305                     options.proxy_command);
1306         }
1307
1308         if (options.port == 0)
1309                 options.port = default_ssh_port();
1310         channel_set_af(ssh, options.address_family);
1311
1312         /* Tidy and check options */
1313         if (options.host_key_alias != NULL)
1314                 lowercase(options.host_key_alias);
1315         if (options.proxy_command != NULL &&
1316             strcmp(options.proxy_command, "-") == 0 &&
1317             options.proxy_use_fdpass)
1318                 fatal("ProxyCommand=- and ProxyUseFDPass are incompatible");
1319         if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1320                 if (options.control_persist && options.control_path != NULL) {
1321                         debug("UpdateHostKeys=ask is incompatible with "
1322                             "ControlPersist; disabling");
1323                         options.update_hostkeys = 0;
1324                 } else if (sshbuf_len(command) != 0 ||
1325                     options.remote_command != NULL ||
1326                     options.request_tty == REQUEST_TTY_NO) {
1327                         debug("UpdateHostKeys=ask is incompatible with "
1328                             "remote command execution; disabling");
1329                         options.update_hostkeys = 0;
1330                 } else if (options.log_level < SYSLOG_LEVEL_INFO) {
1331                         /* no point logging anything; user won't see it */
1332                         options.update_hostkeys = 0;
1333                 }
1334         }
1335         if (options.connection_attempts <= 0)
1336                 fatal("Invalid number of ConnectionAttempts");
1337
1338         if (sshbuf_len(command) != 0 && options.remote_command != NULL)
1339                 fatal("Cannot execute command-line and remote command.");
1340
1341         /* Cannot fork to background if no command. */
1342         if (options.fork_after_authentication && sshbuf_len(command) == 0 &&
1343             options.remote_command == NULL &&
1344             options.session_type != SESSION_TYPE_NONE)
1345                 fatal("Cannot fork into background without a command "
1346                     "to execute.");
1347
1348         /* reinit */
1349         log_init(argv0, options.log_level, options.log_facility, !use_syslog);
1350         for (j = 0; j < options.num_log_verbose; j++) {
1351                 if (strcasecmp(options.log_verbose[j], "none") == 0)
1352                         break;
1353                 log_verbose_add(options.log_verbose[j]);
1354         }
1355
1356         if (options.request_tty == REQUEST_TTY_YES ||
1357             options.request_tty == REQUEST_TTY_FORCE)
1358                 tty_flag = 1;
1359
1360         /* Allocate a tty by default if no command specified. */
1361         if (sshbuf_len(command) == 0 && options.remote_command == NULL)
1362                 tty_flag = options.request_tty != REQUEST_TTY_NO;
1363
1364         /* Force no tty */
1365         if (options.request_tty == REQUEST_TTY_NO ||
1366             (muxclient_command && muxclient_command != SSHMUX_COMMAND_PROXY) ||
1367             options.session_type == SESSION_TYPE_NONE)
1368                 tty_flag = 0;
1369         /* Do not allocate a tty if stdin is not a tty. */
1370         if ((!isatty(fileno(stdin)) || options.stdin_null) &&
1371             options.request_tty != REQUEST_TTY_FORCE) {
1372                 if (tty_flag)
1373                         logit("Pseudo-terminal will not be allocated because "
1374                             "stdin is not a terminal.");
1375                 tty_flag = 0;
1376         }
1377
1378         /* Set up strings used to percent_expand() arguments */
1379         cinfo = xcalloc(1, sizeof(*cinfo));
1380         if (gethostname(thishost, sizeof(thishost)) == -1)
1381                 fatal("gethostname: %s", strerror(errno));
1382         cinfo->thishost = xstrdup(thishost);
1383         thishost[strcspn(thishost, ".")] = '\0';
1384         cinfo->shorthost = xstrdup(thishost);
1385         xasprintf(&cinfo->portstr, "%d", options.port);
1386         xasprintf(&cinfo->uidstr, "%llu",
1387             (unsigned long long)pw->pw_uid);
1388         cinfo->keyalias = xstrdup(options.host_key_alias ?
1389             options.host_key_alias : options.host_arg);
1390         cinfo->conn_hash_hex = ssh_connection_hash(cinfo->thishost, host,
1391             cinfo->portstr, options.user);
1392         cinfo->host_arg = xstrdup(options.host_arg);
1393         cinfo->remhost = xstrdup(host);
1394         cinfo->remuser = xstrdup(options.user);
1395         cinfo->homedir = xstrdup(pw->pw_dir);
1396         cinfo->locuser = xstrdup(pw->pw_name);
1397
1398         /* Find canonic host name. */
1399         if (strchr(host, '.') == 0) {
1400                 struct addrinfo hints;
1401                 struct addrinfo *ai = NULL;
1402                 int errgai;
1403                 memset(&hints, 0, sizeof(hints));
1404                 hints.ai_family = options.address_family;
1405                 hints.ai_flags = AI_CANONNAME;
1406                 hints.ai_socktype = SOCK_STREAM;
1407                 errgai = getaddrinfo(host, NULL, &hints, &ai);
1408                 if (errgai == 0) {
1409                         if (ai->ai_canonname != NULL)
1410                                 host = xstrdup(ai->ai_canonname);
1411                         freeaddrinfo(ai);
1412                 }
1413         }
1414
1415         /*
1416          * Expand tokens in arguments. NB. LocalCommand is expanded later,
1417          * after port-forwarding is set up, so it may pick up any local
1418          * tunnel interface name allocated.
1419          */
1420         if (options.remote_command != NULL) {
1421                 debug3("expanding RemoteCommand: %s", options.remote_command);
1422                 cp = options.remote_command;
1423                 options.remote_command = default_client_percent_expand(cp,
1424                     cinfo);
1425                 debug3("expanded RemoteCommand: %s", options.remote_command);
1426                 free(cp);
1427                 if ((r = sshbuf_put(command, options.remote_command,
1428                     strlen(options.remote_command))) != 0)
1429                         fatal_fr(r, "buffer error");
1430         }
1431
1432         if (options.control_path != NULL) {
1433                 cp = tilde_expand_filename(options.control_path, getuid());
1434                 free(options.control_path);
1435                 options.control_path = default_client_percent_dollar_expand(cp,
1436                     cinfo);
1437                 free(cp);
1438         }
1439
1440         if (options.identity_agent != NULL) {
1441                 p = tilde_expand_filename(options.identity_agent, getuid());
1442                 cp = default_client_percent_dollar_expand(p, cinfo);
1443                 free(p);
1444                 free(options.identity_agent);
1445                 options.identity_agent = cp;
1446         }
1447
1448         if (options.forward_agent_sock_path != NULL) {
1449                 p = tilde_expand_filename(options.forward_agent_sock_path,
1450                     getuid());
1451                 cp = default_client_percent_dollar_expand(p, cinfo);
1452                 free(p);
1453                 free(options.forward_agent_sock_path);
1454                 options.forward_agent_sock_path = cp;
1455                 if (stat(options.forward_agent_sock_path, &st) != 0) {
1456                         error("Cannot forward agent socket path \"%s\": %s",
1457                             options.forward_agent_sock_path, strerror(errno));
1458                         if (options.exit_on_forward_failure)
1459                                 cleanup_exit(255);
1460                 }
1461         }
1462
1463         if (options.num_system_hostfiles > 0 &&
1464             strcasecmp(options.system_hostfiles[0], "none") == 0) {
1465                 if (options.num_system_hostfiles > 1)
1466                         fatal("Invalid GlobalKnownHostsFiles: \"none\" "
1467                             "appears with other entries");
1468                 free(options.system_hostfiles[0]);
1469                 options.system_hostfiles[0] = NULL;
1470                 options.num_system_hostfiles = 0;
1471         }
1472
1473         if (options.num_user_hostfiles > 0 &&
1474             strcasecmp(options.user_hostfiles[0], "none") == 0) {
1475                 if (options.num_user_hostfiles > 1)
1476                         fatal("Invalid UserKnownHostsFiles: \"none\" "
1477                             "appears with other entries");
1478                 free(options.user_hostfiles[0]);
1479                 options.user_hostfiles[0] = NULL;
1480                 options.num_user_hostfiles = 0;
1481         }
1482         for (j = 0; j < options.num_user_hostfiles; j++) {
1483                 if (options.user_hostfiles[j] == NULL)
1484                         continue;
1485                 cp = tilde_expand_filename(options.user_hostfiles[j], getuid());
1486                 p = default_client_percent_dollar_expand(cp, cinfo);
1487                 if (strcmp(options.user_hostfiles[j], p) != 0)
1488                         debug3("expanded UserKnownHostsFile '%s' -> "
1489                             "'%s'", options.user_hostfiles[j], p);
1490                 free(options.user_hostfiles[j]);
1491                 free(cp);
1492                 options.user_hostfiles[j] = p;
1493         }
1494
1495         for (i = 0; i < options.num_local_forwards; i++) {
1496                 if (options.local_forwards[i].listen_path != NULL) {
1497                         cp = options.local_forwards[i].listen_path;
1498                         p = options.local_forwards[i].listen_path =
1499                             default_client_percent_expand(cp, cinfo);
1500                         if (strcmp(cp, p) != 0)
1501                                 debug3("expanded LocalForward listen path "
1502                                     "'%s' -> '%s'", cp, p);
1503                         free(cp);
1504                 }
1505                 if (options.local_forwards[i].connect_path != NULL) {
1506                         cp = options.local_forwards[i].connect_path;
1507                         p = options.local_forwards[i].connect_path =
1508                             default_client_percent_expand(cp, cinfo);
1509                         if (strcmp(cp, p) != 0)
1510                                 debug3("expanded LocalForward connect path "
1511                                     "'%s' -> '%s'", cp, p);
1512                         free(cp);
1513                 }
1514         }
1515
1516         for (i = 0; i < options.num_remote_forwards; i++) {
1517                 if (options.remote_forwards[i].listen_path != NULL) {
1518                         cp = options.remote_forwards[i].listen_path;
1519                         p = options.remote_forwards[i].listen_path =
1520                             default_client_percent_expand(cp, cinfo);
1521                         if (strcmp(cp, p) != 0)
1522                                 debug3("expanded RemoteForward listen path "
1523                                     "'%s' -> '%s'", cp, p);
1524                         free(cp);
1525                 }
1526                 if (options.remote_forwards[i].connect_path != NULL) {
1527                         cp = options.remote_forwards[i].connect_path;
1528                         p = options.remote_forwards[i].connect_path =
1529                             default_client_percent_expand(cp, cinfo);
1530                         if (strcmp(cp, p) != 0)
1531                                 debug3("expanded RemoteForward connect path "
1532                                     "'%s' -> '%s'", cp, p);
1533                         free(cp);
1534                 }
1535         }
1536
1537         if (config_test) {
1538                 dump_client_config(&options, host);
1539                 exit(0);
1540         }
1541
1542         /* Expand SecurityKeyProvider if it refers to an environment variable */
1543         if (options.sk_provider != NULL && *options.sk_provider == '$' &&
1544             strlen(options.sk_provider) > 1) {
1545                 if ((cp = getenv(options.sk_provider + 1)) == NULL) {
1546                         debug("Authenticator provider %s did not resolve; "
1547                             "disabling", options.sk_provider);
1548                         free(options.sk_provider);
1549                         options.sk_provider = NULL;
1550                 } else {
1551                         debug2("resolved SecurityKeyProvider %s => %s",
1552                             options.sk_provider, cp);
1553                         free(options.sk_provider);
1554                         options.sk_provider = xstrdup(cp);
1555                 }
1556         }
1557
1558         if (muxclient_command != 0 && options.control_path == NULL)
1559                 fatal("No ControlPath specified for \"-O\" command");
1560         if (options.control_path != NULL) {
1561                 int sock;
1562                 if ((sock = muxclient(options.control_path)) >= 0) {
1563                         ssh_packet_set_connection(ssh, sock, sock);
1564                         ssh_packet_set_mux(ssh);
1565                         goto skip_connect;
1566                 }
1567         }
1568
1569         /*
1570          * If hostname canonicalisation was not enabled, then we may not
1571          * have yet resolved the hostname. Do so now.
1572          */
1573         if (addrs == NULL && options.proxy_command == NULL) {
1574                 debug2("resolving \"%s\" port %d", host, options.port);
1575                 if ((addrs = resolve_host(host, options.port, 1,
1576                     cname, sizeof(cname))) == NULL)
1577                         cleanup_exit(255); /* resolve_host logs the error */
1578         }
1579
1580         if (options.connection_timeout >= INT_MAX/1000)
1581                 timeout_ms = INT_MAX;
1582         else
1583                 timeout_ms = options.connection_timeout * 1000;
1584
1585         /* Open a connection to the remote host. */
1586         if (ssh_connect(ssh, host, options.host_arg, addrs, &hostaddr,
1587             options.port, options.connection_attempts,
1588             &timeout_ms, options.tcp_keep_alive) != 0)
1589                 exit(255);
1590
1591         if (addrs != NULL)
1592                 freeaddrinfo(addrs);
1593
1594         ssh_packet_set_timeout(ssh, options.server_alive_interval,
1595             options.server_alive_count_max);
1596
1597         if (timeout_ms > 0)
1598                 debug3("timeout: %d ms remain after connect", timeout_ms);
1599
1600         /*
1601          * If we successfully made the connection and we have hostbased auth
1602          * enabled, load the public keys so we can later use the ssh-keysign
1603          * helper to sign challenges.
1604          */
1605         sensitive_data.nkeys = 0;
1606         sensitive_data.keys = NULL;
1607         if (options.hostbased_authentication) {
1608                 int loaded = 0;
1609
1610                 sensitive_data.nkeys = 10;
1611                 sensitive_data.keys = xcalloc(sensitive_data.nkeys,
1612                     sizeof(*sensitive_data.keys));
1613
1614                 /* XXX check errors? */
1615 #define L_PUBKEY(p,o) do { \
1616         if ((o) >= sensitive_data.nkeys) \
1617                 fatal_f("pubkey out of array bounds"); \
1618         check_load(sshkey_load_public(p, &(sensitive_data.keys[o]), NULL), \
1619             &(sensitive_data.keys[o]), p, "pubkey"); \
1620         if (sensitive_data.keys[o] != NULL) { \
1621                 debug2("hostbased key %d: %s key from \"%s\"", o, \
1622                     sshkey_ssh_name(sensitive_data.keys[o]), p); \
1623                 loaded++; \
1624         } \
1625 } while (0)
1626 #define L_CERT(p,o) do { \
1627         if ((o) >= sensitive_data.nkeys) \
1628                 fatal_f("cert out of array bounds"); \
1629         check_load(sshkey_load_cert(p, &(sensitive_data.keys[o])), \
1630             &(sensitive_data.keys[o]), p, "cert"); \
1631         if (sensitive_data.keys[o] != NULL) { \
1632                 debug2("hostbased key %d: %s cert from \"%s\"", o, \
1633                     sshkey_ssh_name(sensitive_data.keys[o]), p); \
1634                 loaded++; \
1635         } \
1636 } while (0)
1637
1638                 if (options.hostbased_authentication == 1) {
1639                         L_CERT(_PATH_HOST_ECDSA_KEY_FILE, 0);
1640                         L_CERT(_PATH_HOST_ED25519_KEY_FILE, 1);
1641                         L_CERT(_PATH_HOST_RSA_KEY_FILE, 2);
1642                         L_CERT(_PATH_HOST_DSA_KEY_FILE, 3);
1643                         L_PUBKEY(_PATH_HOST_ECDSA_KEY_FILE, 4);
1644                         L_PUBKEY(_PATH_HOST_ED25519_KEY_FILE, 5);
1645                         L_PUBKEY(_PATH_HOST_RSA_KEY_FILE, 6);
1646                         L_PUBKEY(_PATH_HOST_DSA_KEY_FILE, 7);
1647                         L_CERT(_PATH_HOST_XMSS_KEY_FILE, 8);
1648                         L_PUBKEY(_PATH_HOST_XMSS_KEY_FILE, 9);
1649                         if (loaded == 0)
1650                                 debug("HostbasedAuthentication enabled but no "
1651                                    "local public host keys could be loaded.");
1652                 }
1653         }
1654
1655         /* load options.identity_files */
1656         load_public_identity_files(cinfo);
1657
1658         /* optionally set the SSH_AUTHSOCKET_ENV_NAME variable */
1659         if (options.identity_agent &&
1660             strcmp(options.identity_agent, SSH_AUTHSOCKET_ENV_NAME) != 0) {
1661                 if (strcmp(options.identity_agent, "none") == 0) {
1662                         unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1663                 } else {
1664                         cp = options.identity_agent;
1665                         /* legacy (limited) format */
1666                         if (cp[0] == '$' && cp[1] != '{') {
1667                                 if (!valid_env_name(cp + 1)) {
1668                                         fatal("Invalid IdentityAgent "
1669                                             "environment variable name %s", cp);
1670                                 }
1671                                 if ((p = getenv(cp + 1)) == NULL)
1672                                         unsetenv(SSH_AUTHSOCKET_ENV_NAME);
1673                                 else
1674                                         setenv(SSH_AUTHSOCKET_ENV_NAME, p, 1);
1675                         } else {
1676                                 /* identity_agent specifies a path directly */
1677                                 setenv(SSH_AUTHSOCKET_ENV_NAME, cp, 1);
1678                         }
1679                 }
1680         }
1681
1682         if (options.forward_agent && options.forward_agent_sock_path != NULL) {
1683                 cp = options.forward_agent_sock_path;
1684                 if (cp[0] == '$') {
1685                         if (!valid_env_name(cp + 1)) {
1686                                 fatal("Invalid ForwardAgent environment variable name %s", cp);
1687                         }
1688                         if ((p = getenv(cp + 1)) != NULL)
1689                                 forward_agent_sock_path = xstrdup(p);
1690                         else
1691                                 options.forward_agent = 0;
1692                         free(cp);
1693                 } else {
1694                         forward_agent_sock_path = cp;
1695                 }
1696         }
1697
1698         /* Expand ~ in known host file names. */
1699         tilde_expand_paths(options.system_hostfiles,
1700             options.num_system_hostfiles);
1701         tilde_expand_paths(options.user_hostfiles, options.num_user_hostfiles);
1702
1703         ssh_signal(SIGCHLD, main_sigchld_handler);
1704
1705         /* Log into the remote system.  Never returns if the login fails. */
1706         ssh_login(ssh, &sensitive_data, host, (struct sockaddr *)&hostaddr,
1707             options.port, pw, timeout_ms, cinfo);
1708
1709         /* We no longer need the private host keys.  Clear them now. */
1710         if (sensitive_data.nkeys != 0) {
1711                 for (i = 0; i < sensitive_data.nkeys; i++) {
1712                         if (sensitive_data.keys[i] != NULL) {
1713                                 /* Destroys contents safely */
1714                                 debug3("clear hostkey %d", i);
1715                                 sshkey_free(sensitive_data.keys[i]);
1716                                 sensitive_data.keys[i] = NULL;
1717                         }
1718                 }
1719                 free(sensitive_data.keys);
1720         }
1721         for (i = 0; i < options.num_identity_files; i++) {
1722                 free(options.identity_files[i]);
1723                 options.identity_files[i] = NULL;
1724                 if (options.identity_keys[i]) {
1725                         sshkey_free(options.identity_keys[i]);
1726                         options.identity_keys[i] = NULL;
1727                 }
1728         }
1729         for (i = 0; i < options.num_certificate_files; i++) {
1730                 free(options.certificate_files[i]);
1731                 options.certificate_files[i] = NULL;
1732         }
1733
1734 #ifdef ENABLE_PKCS11
1735         (void)pkcs11_del_provider(options.pkcs11_provider);
1736 #endif
1737
1738  skip_connect:
1739         exit_status = ssh_session2(ssh, cinfo);
1740         ssh_conn_info_free(cinfo);
1741         ssh_packet_close(ssh);
1742
1743         if (options.control_path != NULL && muxserver_sock != -1)
1744                 unlink(options.control_path);
1745
1746         /* Kill ProxyCommand if it is running. */
1747         ssh_kill_proxy_command();
1748
1749         return exit_status;
1750 }
1751
1752 static void
1753 control_persist_detach(void)
1754 {
1755         pid_t pid;
1756
1757         debug_f("backgrounding master process");
1758
1759         /*
1760          * master (current process) into the background, and make the
1761          * foreground process a client of the backgrounded master.
1762          */
1763         switch ((pid = fork())) {
1764         case -1:
1765                 fatal_f("fork: %s", strerror(errno));
1766         case 0:
1767                 /* Child: master process continues mainloop */
1768                 break;
1769         default:
1770                 /* Parent: set up mux client to connect to backgrounded master */
1771                 debug2_f("background process is %ld", (long)pid);
1772                 options.stdin_null = ostdin_null_flag;
1773                 options.request_tty = orequest_tty;
1774                 tty_flag = otty_flag;
1775                 options.session_type = osession_type;
1776                 close(muxserver_sock);
1777                 muxserver_sock = -1;
1778                 options.control_master = SSHCTL_MASTER_NO;
1779                 muxclient(options.control_path);
1780                 /* muxclient() doesn't return on success. */
1781                 fatal("Failed to connect to new control master");
1782         }
1783         if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1784                 error_f("stdfd_devnull failed");
1785         daemon(1, 1);
1786         setproctitle("%s [mux]", options.control_path);
1787 }
1788
1789 /* Do fork() after authentication. Used by "ssh -f" */
1790 static void
1791 fork_postauth(void)
1792 {
1793         if (need_controlpersist_detach)
1794                 control_persist_detach();
1795         debug("forking to background");
1796         options.fork_after_authentication = 0;
1797         if (daemon(1, 1) == -1)
1798                 fatal("daemon() failed: %.200s", strerror(errno));
1799         if (stdfd_devnull(1, 1, !(log_is_on_stderr() && debug_flag)) == -1)
1800                 error_f("stdfd_devnull failed");
1801 }
1802
1803 static void
1804 forwarding_success(void)
1805 {
1806         if (forward_confirms_pending == -1)
1807                 return;
1808         if (--forward_confirms_pending == 0) {
1809                 debug_f("all expected forwarding replies received");
1810                 if (options.fork_after_authentication)
1811                         fork_postauth();
1812         } else {
1813                 debug2_f("%d expected forwarding replies remaining",
1814                     forward_confirms_pending);
1815         }
1816 }
1817
1818 /* Callback for remote forward global requests */
1819 static void
1820 ssh_confirm_remote_forward(struct ssh *ssh, int type, u_int32_t seq, void *ctxt)
1821 {
1822         struct Forward *rfwd = (struct Forward *)ctxt;
1823         u_int port;
1824         int r;
1825
1826         /* XXX verbose() on failure? */
1827         debug("remote forward %s for: listen %s%s%d, connect %s:%d",
1828             type == SSH2_MSG_REQUEST_SUCCESS ? "success" : "failure",
1829             rfwd->listen_path ? rfwd->listen_path :
1830             rfwd->listen_host ? rfwd->listen_host : "",
1831             (rfwd->listen_path || rfwd->listen_host) ? ":" : "",
1832             rfwd->listen_port, rfwd->connect_path ? rfwd->connect_path :
1833             rfwd->connect_host, rfwd->connect_port);
1834         if (rfwd->listen_path == NULL && rfwd->listen_port == 0) {
1835                 if (type == SSH2_MSG_REQUEST_SUCCESS) {
1836                         if ((r = sshpkt_get_u32(ssh, &port)) != 0)
1837                                 fatal_fr(r, "parse packet");
1838                         if (port > 65535) {
1839                                 error("Invalid allocated port %u for remote "
1840                                     "forward to %s:%d", port,
1841                                     rfwd->connect_host, rfwd->connect_port);
1842                                 /* Ensure failure processing runs below */
1843                                 type = SSH2_MSG_REQUEST_FAILURE;
1844                                 channel_update_permission(ssh,
1845                                     rfwd->handle, -1);
1846                         } else {
1847                                 rfwd->allocated_port = (int)port;
1848                                 logit("Allocated port %u for remote "
1849                                     "forward to %s:%d",
1850                                     rfwd->allocated_port, rfwd->connect_path ?
1851                                     rfwd->connect_path : rfwd->connect_host,
1852                                     rfwd->connect_port);
1853                                 channel_update_permission(ssh,
1854                                     rfwd->handle, rfwd->allocated_port);
1855                         }
1856                 } else {
1857                         channel_update_permission(ssh, rfwd->handle, -1);
1858                 }
1859         }
1860
1861         if (type == SSH2_MSG_REQUEST_FAILURE) {
1862                 if (options.exit_on_forward_failure) {
1863                         if (rfwd->listen_path != NULL)
1864                                 fatal("Error: remote port forwarding failed "
1865                                     "for listen path %s", rfwd->listen_path);
1866                         else
1867                                 fatal("Error: remote port forwarding failed "
1868                                     "for listen port %d", rfwd->listen_port);
1869                 } else {
1870                         if (rfwd->listen_path != NULL)
1871                                 logit("Warning: remote port forwarding failed "
1872                                     "for listen path %s", rfwd->listen_path);
1873                         else
1874                                 logit("Warning: remote port forwarding failed "
1875                                     "for listen port %d", rfwd->listen_port);
1876                 }
1877         }
1878         forwarding_success();
1879 }
1880
1881 static void
1882 client_cleanup_stdio_fwd(struct ssh *ssh, int id, int force, void *arg)
1883 {
1884         debug("stdio forwarding: done");
1885         cleanup_exit(0);
1886 }
1887
1888 static void
1889 ssh_stdio_confirm(struct ssh *ssh, int id, int success, void *arg)
1890 {
1891         if (!success)
1892                 fatal("stdio forwarding failed");
1893 }
1894
1895 static void
1896 ssh_tun_confirm(struct ssh *ssh, int id, int success, void *arg)
1897 {
1898         if (!success) {
1899                 error("Tunnel forwarding failed");
1900                 if (options.exit_on_forward_failure)
1901                         cleanup_exit(255);
1902         }
1903
1904         debug_f("tunnel forward established, id=%d", id);
1905         forwarding_success();
1906 }
1907
1908 static void
1909 ssh_init_stdio_forwarding(struct ssh *ssh)
1910 {
1911         Channel *c;
1912         int in, out;
1913
1914         if (options.stdio_forward_host == NULL)
1915                 return;
1916
1917         debug3_f("%s:%d", options.stdio_forward_host,
1918             options.stdio_forward_port);
1919
1920         if ((in = dup(STDIN_FILENO)) == -1 ||
1921             (out = dup(STDOUT_FILENO)) == -1)
1922                 fatal_f("dup() in/out failed");
1923         if ((c = channel_connect_stdio_fwd(ssh, options.stdio_forward_host,
1924             options.stdio_forward_port, in, out,
1925             CHANNEL_NONBLOCK_STDIO)) == NULL)
1926                 fatal_f("channel_connect_stdio_fwd failed");
1927         channel_register_cleanup(ssh, c->self, client_cleanup_stdio_fwd, 0);
1928         channel_register_open_confirm(ssh, c->self, ssh_stdio_confirm, NULL);
1929 }
1930
1931 static void
1932 ssh_init_forward_permissions(struct ssh *ssh, const char *what, char **opens,
1933     u_int num_opens)
1934 {
1935         u_int i;
1936         int port;
1937         char *addr, *arg, *oarg;
1938         int where = FORWARD_LOCAL;
1939
1940         channel_clear_permission(ssh, FORWARD_ADM, where);
1941         if (num_opens == 0)
1942                 return; /* permit any */
1943
1944         /* handle keywords: "any" / "none" */
1945         if (num_opens == 1 && strcmp(opens[0], "any") == 0)
1946                 return;
1947         if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
1948                 channel_disable_admin(ssh, where);
1949                 return;
1950         }
1951         /* Otherwise treat it as a list of permitted host:port */
1952         for (i = 0; i < num_opens; i++) {
1953                 oarg = arg = xstrdup(opens[i]);
1954                 addr = hpdelim(&arg);
1955                 if (addr == NULL)
1956                         fatal_f("missing host in %s", what);
1957                 addr = cleanhostname(addr);
1958                 if (arg == NULL || ((port = permitopen_port(arg)) < 0))
1959                         fatal_f("bad port number in %s", what);
1960                 /* Send it to channels layer */
1961                 channel_add_permission(ssh, FORWARD_ADM,
1962                     where, addr, port);
1963                 free(oarg);
1964         }
1965 }
1966
1967 static void
1968 ssh_init_forwarding(struct ssh *ssh, char **ifname)
1969 {
1970         int success = 0;
1971         int i;
1972
1973         ssh_init_forward_permissions(ssh, "permitremoteopen",
1974             options.permitted_remote_opens,
1975             options.num_permitted_remote_opens);
1976
1977         if (options.exit_on_forward_failure)
1978                 forward_confirms_pending = 0; /* track pending requests */
1979         /* Initiate local TCP/IP port forwardings. */
1980         for (i = 0; i < options.num_local_forwards; i++) {
1981                 debug("Local connections to %.200s:%d forwarded to remote "
1982                     "address %.200s:%d",
1983                     (options.local_forwards[i].listen_path != NULL) ?
1984                     options.local_forwards[i].listen_path :
1985                     (options.local_forwards[i].listen_host == NULL) ?
1986                     (options.fwd_opts.gateway_ports ? "*" : "LOCALHOST") :
1987                     options.local_forwards[i].listen_host,
1988                     options.local_forwards[i].listen_port,
1989                     (options.local_forwards[i].connect_path != NULL) ?
1990                     options.local_forwards[i].connect_path :
1991                     options.local_forwards[i].connect_host,
1992                     options.local_forwards[i].connect_port);
1993                 success += channel_setup_local_fwd_listener(ssh,
1994                     &options.local_forwards[i], &options.fwd_opts);
1995         }
1996         if (i > 0 && success != i && options.exit_on_forward_failure)
1997                 fatal("Could not request local forwarding.");
1998         if (i > 0 && success == 0)
1999                 error("Could not request local forwarding.");
2000
2001         /* Initiate remote TCP/IP port forwardings. */
2002         for (i = 0; i < options.num_remote_forwards; i++) {
2003                 debug("Remote connections from %.200s:%d forwarded to "
2004                     "local address %.200s:%d",
2005                     (options.remote_forwards[i].listen_path != NULL) ?
2006                     options.remote_forwards[i].listen_path :
2007                     (options.remote_forwards[i].listen_host == NULL) ?
2008                     "LOCALHOST" : options.remote_forwards[i].listen_host,
2009                     options.remote_forwards[i].listen_port,
2010                     (options.remote_forwards[i].connect_path != NULL) ?
2011                     options.remote_forwards[i].connect_path :
2012                     options.remote_forwards[i].connect_host,
2013                     options.remote_forwards[i].connect_port);
2014                 if ((options.remote_forwards[i].handle =
2015                     channel_request_remote_forwarding(ssh,
2016                     &options.remote_forwards[i])) >= 0) {
2017                         client_register_global_confirm(
2018                             ssh_confirm_remote_forward,
2019                             &options.remote_forwards[i]);
2020                         forward_confirms_pending++;
2021                 } else if (options.exit_on_forward_failure)
2022                         fatal("Could not request remote forwarding.");
2023                 else
2024                         logit("Warning: Could not request remote forwarding.");
2025         }
2026
2027         /* Initiate tunnel forwarding. */
2028         if (options.tun_open != SSH_TUNMODE_NO) {
2029                 if ((*ifname = client_request_tun_fwd(ssh,
2030                     options.tun_open, options.tun_local,
2031                     options.tun_remote, ssh_tun_confirm, NULL)) != NULL)
2032                         forward_confirms_pending++;
2033                 else if (options.exit_on_forward_failure)
2034                         fatal("Could not request tunnel forwarding.");
2035                 else
2036                         error("Could not request tunnel forwarding.");
2037         }
2038         if (forward_confirms_pending > 0) {
2039                 debug_f("expecting replies for %d forwards",
2040                     forward_confirms_pending);
2041         }
2042 }
2043
2044 static void
2045 check_agent_present(void)
2046 {
2047         int r;
2048
2049         if (options.forward_agent) {
2050                 /* Clear agent forwarding if we don't have an agent. */
2051                 if ((r = ssh_get_authentication_socket(NULL)) != 0) {
2052                         options.forward_agent = 0;
2053                         if (r != SSH_ERR_AGENT_NOT_PRESENT)
2054                                 debug_r(r, "ssh_get_authentication_socket");
2055                 }
2056         }
2057 }
2058
2059 static void
2060 ssh_session2_setup(struct ssh *ssh, int id, int success, void *arg)
2061 {
2062         extern char **environ;
2063         const char *display, *term;
2064         int r, interactive = tty_flag;
2065         char *proto = NULL, *data = NULL;
2066
2067         if (!success)
2068                 return; /* No need for error message, channels code sends one */
2069
2070         display = getenv("DISPLAY");
2071         if (display == NULL && options.forward_x11)
2072                 debug("X11 forwarding requested but DISPLAY not set");
2073         if (options.forward_x11 && client_x11_get_proto(ssh, display,
2074             options.xauth_location, options.forward_x11_trusted,
2075             options.forward_x11_timeout, &proto, &data) == 0) {
2076                 /* Request forwarding with authentication spoofing. */
2077                 debug("Requesting X11 forwarding with authentication "
2078                     "spoofing.");
2079                 x11_request_forwarding_with_spoofing(ssh, id, display, proto,
2080                     data, 1);
2081                 client_expect_confirm(ssh, id, "X11 forwarding", CONFIRM_WARN);
2082                 /* XXX exit_on_forward_failure */
2083                 interactive = 1;
2084         }
2085
2086         check_agent_present();
2087         if (options.forward_agent) {
2088                 debug("Requesting authentication agent forwarding.");
2089                 channel_request_start(ssh, id, "auth-agent-req@openssh.com", 0);
2090                 if ((r = sshpkt_send(ssh)) != 0)
2091                         fatal_fr(r, "send packet");
2092         }
2093
2094         /* Tell the packet module whether this is an interactive session. */
2095         ssh_packet_set_interactive(ssh, interactive,
2096             options.ip_qos_interactive, options.ip_qos_bulk);
2097
2098         if ((term = lookup_env_in_list("TERM", options.setenv,
2099             options.num_setenv)) == NULL || *term == '\0')
2100                 term = getenv("TERM");
2101         client_session2_setup(ssh, id, tty_flag,
2102             options.session_type == SESSION_TYPE_SUBSYSTEM, term,
2103             NULL, fileno(stdin), command, environ);
2104 }
2105
2106 /* open new channel for a session */
2107 static int
2108 ssh_session2_open(struct ssh *ssh)
2109 {
2110         Channel *c;
2111         int window, packetmax, in, out, err;
2112
2113         if (options.stdin_null) {
2114                 in = open(_PATH_DEVNULL, O_RDONLY);
2115         } else {
2116                 in = dup(STDIN_FILENO);
2117         }
2118         out = dup(STDOUT_FILENO);
2119         err = dup(STDERR_FILENO);
2120
2121         if (in == -1 || out == -1 || err == -1)
2122                 fatal("dup() in/out/err failed");
2123
2124         window = CHAN_SES_WINDOW_DEFAULT;
2125         packetmax = CHAN_SES_PACKET_DEFAULT;
2126         if (tty_flag) {
2127                 window >>= 1;
2128                 packetmax >>= 1;
2129         }
2130         c = channel_new(ssh,
2131             "session", SSH_CHANNEL_OPENING, in, out, err,
2132             window, packetmax, CHAN_EXTENDED_WRITE,
2133             "client-session", CHANNEL_NONBLOCK_STDIO);
2134
2135         debug3_f("channel_new: %d", c->self);
2136
2137         channel_send_open(ssh, c->self);
2138         if (options.session_type != SESSION_TYPE_NONE)
2139                 channel_register_open_confirm(ssh, c->self,
2140                     ssh_session2_setup, NULL);
2141
2142         return c->self;
2143 }
2144
2145 static int
2146 ssh_session2(struct ssh *ssh, const struct ssh_conn_info *cinfo)
2147 {
2148         int r, id = -1;
2149         char *cp, *tun_fwd_ifname = NULL;
2150
2151         /* XXX should be pre-session */
2152         if (!options.control_persist)
2153                 ssh_init_stdio_forwarding(ssh);
2154
2155         ssh_init_forwarding(ssh, &tun_fwd_ifname);
2156
2157         if (options.local_command != NULL) {
2158                 debug3("expanding LocalCommand: %s", options.local_command);
2159                 cp = options.local_command;
2160                 options.local_command = percent_expand(cp,
2161                     DEFAULT_CLIENT_PERCENT_EXPAND_ARGS(cinfo),
2162                     "T", tun_fwd_ifname == NULL ? "NONE" : tun_fwd_ifname,
2163                     (char *)NULL);
2164                 debug3("expanded LocalCommand: %s", options.local_command);
2165                 free(cp);
2166         }
2167
2168         /* Start listening for multiplex clients */
2169         if (!ssh_packet_get_mux(ssh))
2170                 muxserver_listen(ssh);
2171
2172         /*
2173          * If we are in control persist mode and have a working mux listen
2174          * socket, then prepare to background ourselves and have a foreground
2175          * client attach as a control client.
2176          * NB. we must save copies of the flags that we override for
2177          * the backgrounding, since we defer attachment of the client until
2178          * after the connection is fully established (in particular,
2179          * async rfwd replies have been received for ExitOnForwardFailure).
2180          */
2181         if (options.control_persist && muxserver_sock != -1) {
2182                 ostdin_null_flag = options.stdin_null;
2183                 osession_type = options.session_type;
2184                 orequest_tty = options.request_tty;
2185                 otty_flag = tty_flag;
2186                 options.stdin_null = 1;
2187                 options.session_type = SESSION_TYPE_NONE;
2188                 tty_flag = 0;
2189                 if (!options.fork_after_authentication &&
2190                     (osession_type != SESSION_TYPE_NONE ||
2191                     options.stdio_forward_host != NULL))
2192                         need_controlpersist_detach = 1;
2193                 options.fork_after_authentication = 1;
2194         }
2195         /*
2196          * ControlPersist mux listen socket setup failed, attempt the
2197          * stdio forward setup that we skipped earlier.
2198          */
2199         if (options.control_persist && muxserver_sock == -1)
2200                 ssh_init_stdio_forwarding(ssh);
2201
2202         if (options.session_type != SESSION_TYPE_NONE)
2203                 id = ssh_session2_open(ssh);
2204         else {
2205                 ssh_packet_set_interactive(ssh,
2206                     options.control_master == SSHCTL_MASTER_NO,
2207                     options.ip_qos_interactive, options.ip_qos_bulk);
2208         }
2209
2210         /* If we don't expect to open a new session, then disallow it */
2211         if (options.control_master == SSHCTL_MASTER_NO &&
2212             (ssh->compat & SSH_NEW_OPENSSH)) {
2213                 debug("Requesting no-more-sessions@openssh.com");
2214                 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2215                     (r = sshpkt_put_cstring(ssh,
2216                     "no-more-sessions@openssh.com")) != 0 ||
2217                     (r = sshpkt_put_u8(ssh, 0)) != 0 ||
2218                     (r = sshpkt_send(ssh)) != 0)
2219                         fatal_fr(r, "send packet");
2220         }
2221
2222         /* Execute a local command */
2223         if (options.local_command != NULL &&
2224             options.permit_local_command)
2225                 ssh_local_cmd(options.local_command);
2226
2227         /*
2228          * stdout is now owned by the session channel; clobber it here
2229          * so future channel closes are propagated to the local fd.
2230          * NB. this can only happen after LocalCommand has completed,
2231          * as it may want to write to stdout.
2232          */
2233         if (!need_controlpersist_detach && stdfd_devnull(0, 1, 0) == -1)
2234                 error_f("stdfd_devnull failed");
2235
2236         /*
2237          * If requested and we are not interested in replies to remote
2238          * forwarding requests, then let ssh continue in the background.
2239          */
2240         if (options.fork_after_authentication) {
2241                 if (options.exit_on_forward_failure &&
2242                     options.num_remote_forwards > 0) {
2243                         debug("deferring postauth fork until remote forward "
2244                             "confirmation received");
2245                 } else
2246                         fork_postauth();
2247         }
2248
2249         return client_loop(ssh, tty_flag, tty_flag ?
2250             options.escape_char : SSH_ESCAPECHAR_NONE, id);
2251 }
2252
2253 /* Loads all IdentityFile and CertificateFile keys */
2254 static void
2255 load_public_identity_files(const struct ssh_conn_info *cinfo)
2256 {
2257         char *filename, *cp;
2258         struct sshkey *public;
2259         int i;
2260         u_int n_ids, n_certs;
2261         char *identity_files[SSH_MAX_IDENTITY_FILES];
2262         struct sshkey *identity_keys[SSH_MAX_IDENTITY_FILES];
2263         int identity_file_userprovided[SSH_MAX_IDENTITY_FILES];
2264         char *certificate_files[SSH_MAX_CERTIFICATE_FILES];
2265         struct sshkey *certificates[SSH_MAX_CERTIFICATE_FILES];
2266         int certificate_file_userprovided[SSH_MAX_CERTIFICATE_FILES];
2267 #ifdef ENABLE_PKCS11
2268         struct sshkey **keys = NULL;
2269         char **comments = NULL;
2270         int nkeys;
2271 #endif /* PKCS11 */
2272
2273         n_ids = n_certs = 0;
2274         memset(identity_files, 0, sizeof(identity_files));
2275         memset(identity_keys, 0, sizeof(identity_keys));
2276         memset(identity_file_userprovided, 0,
2277             sizeof(identity_file_userprovided));
2278         memset(certificate_files, 0, sizeof(certificate_files));
2279         memset(certificates, 0, sizeof(certificates));
2280         memset(certificate_file_userprovided, 0,
2281             sizeof(certificate_file_userprovided));
2282
2283 #ifdef ENABLE_PKCS11
2284         if (options.pkcs11_provider != NULL &&
2285             options.num_identity_files < SSH_MAX_IDENTITY_FILES &&
2286             (pkcs11_init(!options.batch_mode) == 0) &&
2287             (nkeys = pkcs11_add_provider(options.pkcs11_provider, NULL,
2288             &keys, &comments)) > 0) {
2289                 for (i = 0; i < nkeys; i++) {
2290                         if (n_ids >= SSH_MAX_IDENTITY_FILES) {
2291                                 sshkey_free(keys[i]);
2292                                 free(comments[i]);
2293                                 continue;
2294                         }
2295                         identity_keys[n_ids] = keys[i];
2296                         identity_files[n_ids] = comments[i]; /* transferred */
2297                         n_ids++;
2298                 }
2299                 free(keys);
2300                 free(comments);
2301         }
2302 #endif /* ENABLE_PKCS11 */
2303         for (i = 0; i < options.num_identity_files; i++) {
2304                 if (n_ids >= SSH_MAX_IDENTITY_FILES ||
2305                     strcasecmp(options.identity_files[i], "none") == 0) {
2306                         free(options.identity_files[i]);
2307                         options.identity_files[i] = NULL;
2308                         continue;
2309                 }
2310                 cp = tilde_expand_filename(options.identity_files[i], getuid());
2311                 filename = default_client_percent_dollar_expand(cp, cinfo);
2312                 free(cp);
2313                 check_load(sshkey_load_public(filename, &public, NULL),
2314                     &public, filename, "pubkey");
2315                 debug("identity file %s type %d", filename,
2316                     public ? public->type : -1);
2317                 free(options.identity_files[i]);
2318                 identity_files[n_ids] = filename;
2319                 identity_keys[n_ids] = public;
2320                 identity_file_userprovided[n_ids] =
2321                     options.identity_file_userprovided[i];
2322                 if (++n_ids >= SSH_MAX_IDENTITY_FILES)
2323                         continue;
2324
2325                 /*
2326                  * If no certificates have been explicitly listed then try
2327                  * to add the default certificate variant too.
2328                  */
2329                 if (options.num_certificate_files != 0)
2330                         continue;
2331                 xasprintf(&cp, "%s-cert", filename);
2332                 check_load(sshkey_load_public(cp, &public, NULL),
2333                     &public, filename, "pubkey");
2334                 debug("identity file %s type %d", cp,
2335                     public ? public->type : -1);
2336                 if (public == NULL) {
2337                         free(cp);
2338                         continue;
2339                 }
2340                 if (!sshkey_is_cert(public)) {
2341                         debug_f("key %s type %s is not a certificate",
2342                             cp, sshkey_type(public));
2343                         sshkey_free(public);
2344                         free(cp);
2345                         continue;
2346                 }
2347                 /* NB. leave filename pointing to private key */
2348                 identity_files[n_ids] = xstrdup(filename);
2349                 identity_keys[n_ids] = public;
2350                 identity_file_userprovided[n_ids] =
2351                     options.identity_file_userprovided[i];
2352                 n_ids++;
2353         }
2354
2355         if (options.num_certificate_files > SSH_MAX_CERTIFICATE_FILES)
2356                 fatal_f("too many certificates");
2357         for (i = 0; i < options.num_certificate_files; i++) {
2358                 cp = tilde_expand_filename(options.certificate_files[i],
2359                     getuid());
2360                 filename = default_client_percent_dollar_expand(cp, cinfo);
2361                 free(cp);
2362
2363                 check_load(sshkey_load_public(filename, &public, NULL),
2364                     &public, filename, "certificate");
2365                 debug("certificate file %s type %d", filename,
2366                     public ? public->type : -1);
2367                 free(options.certificate_files[i]);
2368                 options.certificate_files[i] = NULL;
2369                 if (public == NULL) {
2370                         free(filename);
2371                         continue;
2372                 }
2373                 if (!sshkey_is_cert(public)) {
2374                         debug_f("key %s type %s is not a certificate",
2375                             filename, sshkey_type(public));
2376                         sshkey_free(public);
2377                         free(filename);
2378                         continue;
2379                 }
2380                 certificate_files[n_certs] = filename;
2381                 certificates[n_certs] = public;
2382                 certificate_file_userprovided[n_certs] =
2383                     options.certificate_file_userprovided[i];
2384                 ++n_certs;
2385         }
2386
2387         options.num_identity_files = n_ids;
2388         memcpy(options.identity_files, identity_files, sizeof(identity_files));
2389         memcpy(options.identity_keys, identity_keys, sizeof(identity_keys));
2390         memcpy(options.identity_file_userprovided,
2391             identity_file_userprovided, sizeof(identity_file_userprovided));
2392
2393         options.num_certificate_files = n_certs;
2394         memcpy(options.certificate_files,
2395             certificate_files, sizeof(certificate_files));
2396         memcpy(options.certificates, certificates, sizeof(certificates));
2397         memcpy(options.certificate_file_userprovided,
2398             certificate_file_userprovided,
2399             sizeof(certificate_file_userprovided));
2400 }
2401
2402 static void
2403 main_sigchld_handler(int sig)
2404 {
2405         int save_errno = errno;
2406         pid_t pid;
2407         int status;
2408
2409         while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
2410             (pid == -1 && errno == EINTR))
2411                 ;
2412         errno = save_errno;
2413 }