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