xref: /netbsd-src/crypto/external/bsd/openssh/dist/servconf.c (revision 9fb66d812c00ebfb445c0b47dea128f32aa6fe96)
1 /*	$NetBSD: servconf.c,v 1.35 2021/03/05 17:47:16 christos Exp $	*/
2 
3 /* $OpenBSD: servconf.c,v 1.377 2021/02/24 01:18:08 dtucker Exp $ */
4 /*
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  */
14 
15 #include "includes.h"
16 __RCSID("$NetBSD: servconf.c,v 1.35 2021/03/05 17:47:16 christos Exp $");
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <sys/queue.h>
20 #include <sys/param.h>
21 #include <sys/sysctl.h>
22 #include <sys/stat.h>
23 
24 #include <netinet/in.h>
25 #include <netinet/ip.h>
26 #include <net/route.h>
27 
28 #include <ctype.h>
29 #include <glob.h>
30 #include <netdb.h>
31 #include <pwd.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <signal.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <stdarg.h>
39 #include <errno.h>
40 #include <util.h>
41 #include <time.h>
42 
43 #ifdef KRB4
44 #include <krb.h>
45 #ifdef AFS
46 #include <kafs.h>
47 #endif /* AFS */
48 #endif /* KRB4 */
49 
50 #include "xmalloc.h"
51 #include "ssh.h"
52 #include "log.h"
53 #include "sshbuf.h"
54 #include "misc.h"
55 #include "servconf.h"
56 #include "compat.h"
57 #include "pathnames.h"
58 #include "cipher.h"
59 #include "sshkey.h"
60 #include "kex.h"
61 #include "mac.h"
62 #include "match.h"
63 #include "channels.h"
64 #include "groupaccess.h"
65 #include "canohost.h"
66 #include "packet.h"
67 #include "ssherr.h"
68 #include "hostfile.h"
69 #include "auth.h"
70 #include "fmt_scaled.h"
71 
72 #ifdef WITH_LDAP_PUBKEY
73 #include "ldapauth.h"
74 #endif
75 #include "myproposal.h"
76 #include "digest.h"
77 
78 static void add_listen_addr(ServerOptions *, const char *,
79     const char *, int);
80 static void add_one_listen_addr(ServerOptions *, const char *,
81     const char *, int);
82 static void parse_server_config_depth(ServerOptions *options,
83     const char *filename, struct sshbuf *conf, struct include_list *includes,
84     struct connection_info *connectinfo, int flags, int *activep, int depth);
85 
86 /* Use of privilege separation or not */
87 extern int use_privsep;
88 extern struct sshbuf *cfg;
89 
90 /* Initializes the server options to their default values. */
91 
92 void
93 initialize_server_options(ServerOptions *options)
94 {
95 	memset(options, 0, sizeof(*options));
96 
97 	/* Portable-specific options */
98 	options->use_pam = -1;
99 
100 	/* Standard Options */
101 	options->num_ports = 0;
102 	options->ports_from_cmdline = 0;
103 	options->queued_listen_addrs = NULL;
104 	options->num_queued_listens = 0;
105 	options->listen_addrs = NULL;
106 	options->num_listen_addrs = 0;
107 	options->address_family = -1;
108 	options->routing_domain = NULL;
109 	options->num_host_key_files = 0;
110 	options->num_host_cert_files = 0;
111 	options->host_key_agent = NULL;
112 	options->pid_file = NULL;
113 	options->login_grace_time = -1;
114 	options->permit_root_login = PERMIT_NOT_SET;
115 	options->ignore_rhosts = -1;
116 	options->ignore_root_rhosts = -1;
117 	options->ignore_user_known_hosts = -1;
118 	options->print_motd = -1;
119 	options->print_lastlog = -1;
120 	options->x11_forwarding = -1;
121 	options->x11_display_offset = -1;
122 	options->x11_use_localhost = -1;
123 	options->permit_tty = -1;
124 	options->permit_user_rc = -1;
125 	options->xauth_location = NULL;
126 	options->strict_modes = -1;
127 	options->tcp_keep_alive = -1;
128 	options->log_facility = SYSLOG_FACILITY_NOT_SET;
129 	options->log_level = SYSLOG_LEVEL_NOT_SET;
130 	options->num_log_verbose = 0;
131 	options->log_verbose = NULL;
132 	options->hostbased_authentication = -1;
133 	options->hostbased_uses_name_from_packet_only = -1;
134 	options->hostbased_accepted_algos = NULL;
135 	options->hostkeyalgorithms = NULL;
136 	options->pubkey_authentication = -1;
137 	options->pubkey_auth_options = -1;
138 	options->pubkey_accepted_algos = NULL;
139 	options->kerberos_authentication = -1;
140 	options->kerberos_or_local_passwd = -1;
141 	options->kerberos_ticket_cleanup = -1;
142 #if defined(AFS) || defined(KRB5)
143 	options->kerberos_tgt_passing = -1;
144 #endif
145 #ifdef AFS
146 	options->afs_token_passing = -1;
147 #endif
148 	options->kerberos_get_afs_token = -1;
149 	options->gss_authentication=-1;
150 	options->gss_cleanup_creds = -1;
151 	options->gss_strict_acceptor = -1;
152 	options->password_authentication = -1;
153 	options->kbd_interactive_authentication = -1;
154 	options->challenge_response_authentication = -1;
155 	options->permit_empty_passwd = -1;
156 	options->permit_user_env = -1;
157 	options->permit_user_env_allowlist = NULL;
158 	options->compression = -1;
159 	options->rekey_limit = -1;
160 	options->rekey_interval = -1;
161 	options->allow_tcp_forwarding = -1;
162 	options->allow_streamlocal_forwarding = -1;
163 	options->allow_agent_forwarding = -1;
164 	options->num_allow_users = 0;
165 	options->num_deny_users = 0;
166 	options->num_allow_groups = 0;
167 	options->num_deny_groups = 0;
168 	options->ciphers = NULL;
169 #ifdef WITH_LDAP_PUBKEY
170 	/* XXX dirty */
171 	options->lpk.ld = NULL;
172 	options->lpk.on = -1;
173 	options->lpk.servers = NULL;
174 	options->lpk.u_basedn = NULL;
175 	options->lpk.g_basedn = NULL;
176 	options->lpk.binddn = NULL;
177 	options->lpk.bindpw = NULL;
178 	options->lpk.sgroup = NULL;
179 	options->lpk.filter = NULL;
180 	options->lpk.fgroup = NULL;
181 	options->lpk.l_conf = NULL;
182 	options->lpk.tls = -1;
183 	options->lpk.b_timeout.tv_sec = -1;
184 	options->lpk.s_timeout.tv_sec = -1;
185 	options->lpk.flags = FLAG_EMPTY;
186 	options->lpk.pub_key_attr = NULL;
187 #endif
188 	options->macs = NULL;
189 	options->kex_algorithms = NULL;
190 	options->ca_sign_algorithms = NULL;
191 	options->fwd_opts.gateway_ports = -1;
192 	options->fwd_opts.streamlocal_bind_mask = (mode_t)-1;
193 	options->fwd_opts.streamlocal_bind_unlink = -1;
194 	options->num_subsystems = 0;
195 	options->max_startups_begin = -1;
196 	options->max_startups_rate = -1;
197 	options->max_startups = -1;
198 	options->per_source_max_startups = -1;
199 	options->per_source_masklen_ipv4 = -1;
200 	options->per_source_masklen_ipv6 = -1;
201 	options->max_authtries = -1;
202 	options->max_sessions = -1;
203 	options->banner = NULL;
204 	options->use_dns = -1;
205 	options->client_alive_interval = -1;
206 	options->client_alive_count_max = -1;
207 	options->num_authkeys_files = 0;
208 	options->num_accept_env = 0;
209 	options->num_setenv = 0;
210 	options->permit_tun = -1;
211 	options->permitted_opens = NULL;
212 	options->permitted_listens = NULL;
213 	options->adm_forced_command = NULL;
214 	options->chroot_directory = NULL;
215 	options->authorized_keys_command = NULL;
216 	options->authorized_keys_command_user = NULL;
217 	options->revoked_keys_file = NULL;
218 	options->sk_provider = NULL;
219 	options->trusted_user_ca_keys = NULL;
220 	options->authorized_principals_file = NULL;
221 	options->authorized_principals_command = NULL;
222 	options->authorized_principals_command_user = NULL;
223 	options->ip_qos_interactive = -1;
224 	options->ip_qos_bulk = -1;
225 	options->version_addendum = NULL;
226 	options->fingerprint_hash = -1;
227 	options->disable_forwarding = -1;
228 	options->expose_userauth_info = -1;
229 	options->none_enabled = -1;
230 	options->tcp_rcv_buf_poll = -1;
231 	options->hpn_disabled = -1;
232 	options->hpn_buffer_size = -1;
233 }
234 
235 /* Returns 1 if a string option is unset or set to "none" or 0 otherwise. */
236 static int
237 option_clear_or_none(const char *o)
238 {
239 	return o == NULL || strcasecmp(o, "none") == 0;
240 }
241 
242 static void
243 assemble_algorithms(ServerOptions *o)
244 {
245 	char *all_cipher, *all_mac, *all_kex, *all_key, *all_sig;
246 	char *def_cipher, *def_mac, *def_kex, *def_key, *def_sig;
247 	int r;
248 
249 	all_cipher = cipher_alg_list(',', 0);
250 	all_mac = mac_alg_list(',');
251 	all_kex = kex_alg_list(',');
252 	all_key = sshkey_alg_list(0, 0, 1, ',');
253 	all_sig = sshkey_alg_list(0, 1, 1, ',');
254 	/* remove unsupported algos from default lists */
255 	def_cipher = match_filter_allowlist(KEX_SERVER_ENCRYPT, all_cipher);
256 	def_mac = match_filter_allowlist(KEX_SERVER_MAC, all_mac);
257 	def_kex = match_filter_allowlist(KEX_SERVER_KEX, all_kex);
258 	def_key = match_filter_allowlist(KEX_DEFAULT_PK_ALG, all_key);
259 	def_sig = match_filter_allowlist(SSH_ALLOWED_CA_SIGALGS, all_sig);
260 #define ASSEMBLE(what, defaults, all) \
261 	do { \
262 		if ((r = kex_assemble_names(&o->what, defaults, all)) != 0) \
263 			fatal_fr(r, "%s", #what); \
264 	} while (0)
265 	ASSEMBLE(ciphers, def_cipher, all_cipher);
266 	ASSEMBLE(macs, def_mac, all_mac);
267 	ASSEMBLE(kex_algorithms, def_kex, all_kex);
268 	ASSEMBLE(hostkeyalgorithms, def_key, all_key);
269 	ASSEMBLE(hostbased_accepted_algos, def_key, all_key);
270 	ASSEMBLE(pubkey_accepted_algos, def_key, all_key);
271 	ASSEMBLE(ca_sign_algorithms, def_sig, all_sig);
272 #undef ASSEMBLE
273 	free(all_cipher);
274 	free(all_mac);
275 	free(all_kex);
276 	free(all_key);
277 	free(all_sig);
278 	free(def_cipher);
279 	free(def_mac);
280 	free(def_kex);
281 	free(def_key);
282 	free(def_sig);
283 }
284 
285 void
286 servconf_add_hostkey(const char *file, const int line,
287     ServerOptions *options, const char *path, int userprovided)
288 {
289 	char *apath = derelativise_path(path);
290 
291 	opt_array_append2(file, line, "HostKey",
292 	    &options->host_key_files, &options->host_key_file_userprovided,
293 	    &options->num_host_key_files, apath, userprovided);
294 	free(apath);
295 }
296 
297 void
298 servconf_add_hostcert(const char *file, const int line,
299     ServerOptions *options, const char *path)
300 {
301 	char *apath = derelativise_path(path);
302 
303 	opt_array_append(file, line, "HostCertificate",
304 	    &options->host_cert_files, &options->num_host_cert_files, apath);
305 	free(apath);
306 }
307 
308 void
309 fill_default_server_options(ServerOptions *options)
310 {
311 	/* needed for hpn socket tests */
312 	int sock;
313 	int socksize;
314 	socklen_t socksizelen = sizeof(int);
315 
316 	/* Portable-specific options */
317 	if (options->use_pam == -1)
318 		options->use_pam = 0;
319 
320 	/* Standard Options */
321 	u_int i;
322 
323 	if (options->num_host_key_files == 0) {
324 		/* fill default hostkeys */
325 		servconf_add_hostkey("[default]", 0, options,
326 		    _PATH_HOST_RSA_KEY_FILE, 0);
327 		servconf_add_hostkey("[default]", 0, options,
328 		    _PATH_HOST_ECDSA_KEY_FILE, 0);
329 		servconf_add_hostkey("[default]", 0, options,
330 		    _PATH_HOST_ED25519_KEY_FILE, 0);
331 #ifdef WITH_XMSS
332 		servconf_add_hostkey("[default]", 0, options,
333 		    _PATH_HOST_XMSS_KEY_FILE, 0);
334 #endif /* WITH_XMSS */
335 	}
336 	/* No certificates by default */
337 	if (options->num_ports == 0)
338 		options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
339 	if (options->address_family == -1)
340 		options->address_family = AF_UNSPEC;
341 	if (options->listen_addrs == NULL)
342 		add_listen_addr(options, NULL, NULL, 0);
343 	if (options->pid_file == NULL)
344 		options->pid_file = xstrdup(_PATH_SSH_DAEMON_PID_FILE);
345 	if (options->login_grace_time == -1)
346 		options->login_grace_time = 120;
347 	if (options->permit_root_login == PERMIT_NOT_SET)
348 		options->permit_root_login = PERMIT_NO_PASSWD;
349 	if (options->ignore_rhosts == -1)
350 		options->ignore_rhosts = 1;
351 	if (options->ignore_root_rhosts == -1)
352 		options->ignore_root_rhosts = options->ignore_rhosts;
353 	if (options->ignore_user_known_hosts == -1)
354 		options->ignore_user_known_hosts = 0;
355 	if (options->print_motd == -1)
356 		options->print_motd = 1;
357 	if (options->print_lastlog == -1)
358 		options->print_lastlog = 1;
359 	if (options->x11_forwarding == -1)
360 		options->x11_forwarding = 0;
361 	if (options->x11_display_offset == -1)
362 		options->x11_display_offset = 10;
363 	if (options->x11_use_localhost == -1)
364 		options->x11_use_localhost = 1;
365 	if (options->xauth_location == NULL)
366 		options->xauth_location = xstrdup(_PATH_XAUTH);
367 	if (options->permit_tty == -1)
368 		options->permit_tty = 1;
369 	if (options->permit_user_rc == -1)
370 		options->permit_user_rc = 1;
371 	if (options->strict_modes == -1)
372 		options->strict_modes = 1;
373 	if (options->tcp_keep_alive == -1)
374 		options->tcp_keep_alive = 1;
375 	if (options->log_facility == SYSLOG_FACILITY_NOT_SET)
376 		options->log_facility = SYSLOG_FACILITY_AUTH;
377 	if (options->log_level == SYSLOG_LEVEL_NOT_SET)
378 		options->log_level = SYSLOG_LEVEL_INFO;
379 	if (options->hostbased_authentication == -1)
380 		options->hostbased_authentication = 0;
381 	if (options->hostbased_uses_name_from_packet_only == -1)
382 		options->hostbased_uses_name_from_packet_only = 0;
383 	if (options->pubkey_authentication == -1)
384 		options->pubkey_authentication = 1;
385 	if (options->pubkey_auth_options == -1)
386 		options->pubkey_auth_options = 0;
387 	if (options->kerberos_authentication == -1)
388 		options->kerberos_authentication = 0;
389 	if (options->kerberos_or_local_passwd == -1)
390 		options->kerberos_or_local_passwd = 1;
391 	if (options->kerberos_ticket_cleanup == -1)
392 		options->kerberos_ticket_cleanup = 1;
393 #if defined(AFS) || defined(KRB5)
394 	if (options->kerberos_tgt_passing == -1)
395 		options->kerberos_tgt_passing = 0;
396 #endif
397 #ifdef AFS
398 	if (options->afs_token_passing == -1)
399 		options->afs_token_passing = 0;
400 #endif
401 	if (options->kerberos_get_afs_token == -1)
402 		options->kerberos_get_afs_token = 0;
403 	if (options->gss_authentication == -1)
404 		options->gss_authentication = 0;
405 	if (options->gss_cleanup_creds == -1)
406 		options->gss_cleanup_creds = 1;
407 	if (options->gss_strict_acceptor == -1)
408 		options->gss_strict_acceptor = 1;
409 	if (options->password_authentication == -1)
410 		options->password_authentication = 1;
411 	if (options->kbd_interactive_authentication == -1)
412 		options->kbd_interactive_authentication = 0;
413 	if (options->challenge_response_authentication == -1)
414 		options->challenge_response_authentication = 1;
415 	if (options->permit_empty_passwd == -1)
416 		options->permit_empty_passwd = 0;
417 	if (options->permit_user_env == -1) {
418 		options->permit_user_env = 0;
419 		options->permit_user_env_allowlist = NULL;
420 	}
421 	if (options->compression == -1)
422 #ifdef WITH_ZLIB
423 		options->compression = COMP_DELAYED;
424 #else
425 		options->compression = COMP_NONE;
426 #endif
427 
428 	if (options->rekey_limit == -1)
429 		options->rekey_limit = 0;
430 	if (options->rekey_interval == -1)
431 		options->rekey_interval = 0;
432 	if (options->allow_tcp_forwarding == -1)
433 		options->allow_tcp_forwarding = FORWARD_ALLOW;
434 	if (options->allow_streamlocal_forwarding == -1)
435 		options->allow_streamlocal_forwarding = FORWARD_ALLOW;
436 	if (options->allow_agent_forwarding == -1)
437 		options->allow_agent_forwarding = 1;
438 	if (options->fwd_opts.gateway_ports == -1)
439 		options->fwd_opts.gateway_ports = 0;
440 	if (options->max_startups == -1)
441 		options->max_startups = 100;
442 	if (options->max_startups_rate == -1)
443 		options->max_startups_rate = 30;		/* 30% */
444 	if (options->max_startups_begin == -1)
445 		options->max_startups_begin = 10;
446 	if (options->per_source_max_startups == -1)
447 		options->per_source_max_startups = INT_MAX;
448 	if (options->per_source_masklen_ipv4 == -1)
449 		options->per_source_masklen_ipv4 = 32;
450 	if (options->per_source_masklen_ipv6 == -1)
451 		options->per_source_masklen_ipv6 = 128;
452 	if (options->max_authtries == -1)
453 		options->max_authtries = DEFAULT_AUTH_FAIL_MAX;
454 	if (options->max_sessions == -1)
455 		options->max_sessions = DEFAULT_SESSIONS_MAX;
456 	if (options->use_dns == -1)
457 		options->use_dns = 0;
458 	if (options->client_alive_interval == -1)
459 		options->client_alive_interval = 0;
460 	if (options->client_alive_count_max == -1)
461 		options->client_alive_count_max = 3;
462 	if (options->num_authkeys_files == 0) {
463 		opt_array_append("[default]", 0, "AuthorizedKeysFiles",
464 		    &options->authorized_keys_files,
465 		    &options->num_authkeys_files,
466 		    _PATH_SSH_USER_PERMITTED_KEYS);
467 		opt_array_append("[default]", 0, "AuthorizedKeysFiles",
468 		    &options->authorized_keys_files,
469 		    &options->num_authkeys_files,
470 		    _PATH_SSH_USER_PERMITTED_KEYS2);
471 	}
472 	if (options->permit_tun == -1)
473 		options->permit_tun = SSH_TUNMODE_NO;
474 	if (options->ip_qos_interactive == -1)
475 		options->ip_qos_interactive = IPTOS_DSCP_AF21;
476 	if (options->ip_qos_bulk == -1)
477 		options->ip_qos_bulk = IPTOS_DSCP_CS1;
478 	if (options->version_addendum == NULL)
479 		options->version_addendum = xstrdup("");
480 
481 	if (options->hpn_disabled == -1)
482 		options->hpn_disabled = 0;
483 
484 	if (options->hpn_buffer_size == -1) {
485 		/* option not explicitly set. Now we have to figure out */
486 		/* what value to use */
487 		if (options->hpn_disabled == 1) {
488 			options->hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
489 		} else {
490 			/* get the current RCV size and set it to that */
491 			/*create a socket but don't connect it */
492 			/* we use that the get the rcv socket size */
493 			sock = socket(AF_INET, SOCK_STREAM, 0);
494 			getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
495 				   &socksize, &socksizelen);
496 			close(sock);
497 			options->hpn_buffer_size = socksize;
498 			debug ("HPN Buffer Size: %d", options->hpn_buffer_size);
499 
500 		}
501 	} else {
502 		/* we have to do this incase the user sets both values in a contradictory */
503 		/* manner. hpn_disabled overrrides hpn_buffer_size*/
504 		if (options->hpn_disabled <= 0) {
505 			if (options->hpn_buffer_size == 0)
506 				options->hpn_buffer_size = 1;
507 			/* limit the maximum buffer to 64MB */
508 			if (options->hpn_buffer_size > 64*1024) {
509 				options->hpn_buffer_size = 64*1024*1024;
510 			} else {
511 				options->hpn_buffer_size *= 1024;
512 			}
513 		} else
514 			options->hpn_buffer_size = CHAN_TCP_WINDOW_DEFAULT;
515 	}
516 
517 #ifdef WITH_LDAP_PUBKEY
518 	if (options->lpk.on == -1)
519 	    options->lpk.on = _DEFAULT_LPK_ON;
520 	if (options->lpk.servers == NULL)
521 	    options->lpk.servers = _DEFAULT_LPK_SERVERS;
522 	if (options->lpk.u_basedn == NULL)
523 	    options->lpk.u_basedn = _DEFAULT_LPK_UDN;
524 	if (options->lpk.g_basedn == NULL)
525 	    options->lpk.g_basedn = _DEFAULT_LPK_GDN;
526 	if (options->lpk.binddn == NULL)
527 	    options->lpk.binddn = _DEFAULT_LPK_BINDDN;
528 	if (options->lpk.bindpw == NULL)
529 	    options->lpk.bindpw = _DEFAULT_LPK_BINDPW;
530 	if (options->lpk.sgroup == NULL)
531 	    options->lpk.sgroup = _DEFAULT_LPK_SGROUP;
532 	if (options->lpk.filter == NULL)
533 	    options->lpk.filter = _DEFAULT_LPK_FILTER;
534 	if (options->lpk.tls == -1)
535 	    options->lpk.tls = _DEFAULT_LPK_TLS;
536 	if (options->lpk.b_timeout.tv_sec == -1)
537 	    options->lpk.b_timeout.tv_sec = _DEFAULT_LPK_BTIMEOUT;
538 	if (options->lpk.s_timeout.tv_sec == -1)
539 	    options->lpk.s_timeout.tv_sec = _DEFAULT_LPK_STIMEOUT;
540 	if (options->lpk.l_conf == NULL)
541 	    options->lpk.l_conf = _DEFAULT_LPK_LDP;
542 	if (options->lpk.pub_key_attr == NULL)
543 	    options->lpk.pub_key_attr = __UNCONST(_DEFAULT_LPK_PUB);
544 #endif
545 
546 	if (options->fwd_opts.streamlocal_bind_mask == (mode_t)-1)
547 		options->fwd_opts.streamlocal_bind_mask = 0177;
548 	if (options->fwd_opts.streamlocal_bind_unlink == -1)
549 		options->fwd_opts.streamlocal_bind_unlink = 0;
550 	if (options->fingerprint_hash == -1)
551 		options->fingerprint_hash = SSH_FP_HASH_DEFAULT;
552 	if (options->disable_forwarding == -1)
553 		options->disable_forwarding = 0;
554 	if (options->expose_userauth_info == -1)
555 		options->expose_userauth_info = 0;
556 	if (options->sk_provider == NULL)
557 		options->sk_provider = xstrdup("internal");
558 
559 	assemble_algorithms(options);
560 
561 	/* Turn privilege separation and sandboxing on by default */
562 	if (use_privsep == -1)
563 		use_privsep = PRIVSEP_ON;
564 
565 #define CLEAR_ON_NONE(v) \
566 	do { \
567 		if (option_clear_or_none(v)) { \
568 			free(v); \
569 			v = NULL; \
570 		} \
571 	} while(0)
572 	CLEAR_ON_NONE(options->pid_file);
573 	CLEAR_ON_NONE(options->xauth_location);
574 	CLEAR_ON_NONE(options->banner);
575 	CLEAR_ON_NONE(options->trusted_user_ca_keys);
576 	CLEAR_ON_NONE(options->revoked_keys_file);
577 	CLEAR_ON_NONE(options->sk_provider);
578 	CLEAR_ON_NONE(options->authorized_principals_file);
579 	CLEAR_ON_NONE(options->adm_forced_command);
580 	CLEAR_ON_NONE(options->chroot_directory);
581 	CLEAR_ON_NONE(options->routing_domain);
582 	CLEAR_ON_NONE(options->host_key_agent);
583 	for (i = 0; i < options->num_host_key_files; i++)
584 		CLEAR_ON_NONE(options->host_key_files[i]);
585 	for (i = 0; i < options->num_host_cert_files; i++)
586 		CLEAR_ON_NONE(options->host_cert_files[i]);
587 #undef CLEAR_ON_NONE
588 
589 	/* Similar handling for AuthenticationMethods=any */
590 	if (options->num_auth_methods == 1 &&
591 	    strcmp(options->auth_methods[0], "any") == 0) {
592 		free(options->auth_methods[0]);
593 		options->auth_methods[0] = NULL;
594 		options->num_auth_methods = 0;
595 	}
596 }
597 
598 /* Keyword tokens. */
599 typedef enum {
600 	sBadOption,		/* == unknown option */
601 	sUsePAM,
602 	sPort, sHostKeyFile, sLoginGraceTime,
603 	sPermitRootLogin, sLogFacility, sLogLevel, sLogVerbose,
604 	sKerberosAuthentication, sKerberosOrLocalPasswd, sKerberosTicketCleanup,
605 	sKerberosGetAFSToken,
606 	sKerberosTgtPassing, sChallengeResponseAuthentication,
607 	sPasswordAuthentication, sKbdInteractiveAuthentication,
608 	sListenAddress, sAddressFamily,
609 	sPrintMotd, sPrintLastLog, sIgnoreRhosts,
610 	sX11Forwarding, sX11DisplayOffset, sX11UseLocalhost,
611 	sPermitTTY, sStrictModes, sEmptyPasswd, sTCPKeepAlive,
612 	sPermitUserEnvironment, sAllowTcpForwarding, sCompression,
613 	sRekeyLimit, sAllowUsers, sDenyUsers, sAllowGroups, sDenyGroups,
614 	sIgnoreUserKnownHosts, sCiphers, sMacs, sPidFile,
615 	sGatewayPorts, sPubkeyAuthentication, sPubkeyAcceptedAlgorithms,
616 	sXAuthLocation, sSubsystem, sMaxStartups, sMaxAuthTries, sMaxSessions,
617 	sBanner, sUseDNS, sHostbasedAuthentication,
618 	sHostbasedUsesNameFromPacketOnly, sHostbasedAcceptedAlgorithms,
619 	sHostKeyAlgorithms, sPerSourceMaxStartups, sPerSourceNetBlockSize,
620 	sClientAliveInterval, sClientAliveCountMax, sAuthorizedKeysFile,
621 	sGssAuthentication, sGssCleanupCreds, sGssStrictAcceptor,
622 	sAcceptEnv, sSetEnv, sPermitTunnel,
623 	sMatch, sPermitOpen, sPermitListen, sForceCommand, sChrootDirectory,
624 	sUsePrivilegeSeparation, sAllowAgentForwarding,
625 	sHostCertificate, sInclude,
626 	sRevokedKeys, sTrustedUserCAKeys, sAuthorizedPrincipalsFile,
627 	sAuthorizedPrincipalsCommand, sAuthorizedPrincipalsCommandUser,
628 	sKexAlgorithms, sCASignatureAlgorithms, sIPQoS, sVersionAddendum,
629 	sIgnoreRootRhosts,
630 	sNoneEnabled, sTcpRcvBufPoll,sHPNDisabled, sHPNBufferSize,
631 	sAuthorizedKeysCommand, sAuthorizedKeysCommandUser,
632 	sAuthenticationMethods, sHostKeyAgent, sPermitUserRC,
633 	sStreamLocalBindMask, sStreamLocalBindUnlink,
634 	sAllowStreamLocalForwarding, sFingerprintHash, sDisableForwarding,
635 	sExposeAuthInfo, sRDomain, sPubkeyAuthOptions, sSecurityKeyProvider,
636 	sDeprecated, sIgnore, sUnsupported
637 #ifdef WITH_LDAP_PUBKEY
638 	,sLdapPublickey, sLdapServers, sLdapUserDN
639 	,sLdapGroupDN, sBindDN, sBindPw, sMyGroup
640 	,sLdapFilter, sForceTLS, sBindTimeout
641 	,sSearchTimeout, sLdapConf ,sLpkPubKeyAttr
642 #endif
643 } ServerOpCodes;
644 
645 #define SSHCFG_GLOBAL		0x01	/* allowed in main section of config */
646 #define SSHCFG_MATCH		0x02	/* allowed inside a Match section */
647 #define SSHCFG_ALL		(SSHCFG_GLOBAL|SSHCFG_MATCH)
648 #define SSHCFG_NEVERMATCH	0x04  /* Match never matches; internal only */
649 #define SSHCFG_MATCH_ONLY	0x08  /* Match only in conditional blocks; internal only */
650 
651 /* Textual representation of the tokens. */
652 static struct {
653 	const char *name;
654 	ServerOpCodes opcode;
655 	u_int flags;
656 } keywords[] = {
657 #ifdef USE_PAM
658 	{ "usepam", sUsePAM, SSHCFG_GLOBAL },
659 #else
660 	{ "usepam", sUnsupported, SSHCFG_GLOBAL },
661 #endif
662 	{ "port", sPort, SSHCFG_GLOBAL },
663 	{ "hostkey", sHostKeyFile, SSHCFG_GLOBAL },
664 	{ "hostdsakey", sHostKeyFile, SSHCFG_GLOBAL },		/* alias */
665 	{ "hostkeyagent", sHostKeyAgent, SSHCFG_GLOBAL },
666 	{ "pidfile", sPidFile, SSHCFG_GLOBAL },
667 	{ "serverkeybits", sDeprecated, SSHCFG_GLOBAL },
668 	{ "logingracetime", sLoginGraceTime, SSHCFG_GLOBAL },
669 	{ "keyregenerationinterval", sDeprecated, SSHCFG_GLOBAL },
670 	{ "permitrootlogin", sPermitRootLogin, SSHCFG_ALL },
671 	{ "syslogfacility", sLogFacility, SSHCFG_GLOBAL },
672 	{ "loglevel", sLogLevel, SSHCFG_ALL },
673 	{ "logverbose", sLogVerbose, SSHCFG_ALL },
674 	{ "rhostsauthentication", sDeprecated, SSHCFG_GLOBAL },
675 	{ "rhostsrsaauthentication", sDeprecated, SSHCFG_ALL },
676 	{ "hostbasedauthentication", sHostbasedAuthentication, SSHCFG_ALL },
677 	{ "hostbasedusesnamefrompacketonly", sHostbasedUsesNameFromPacketOnly, SSHCFG_ALL },
678 	{ "hostbasedacceptedalgorithms", sHostbasedAcceptedAlgorithms, SSHCFG_ALL },
679 	{ "hostbasedacceptedkeytypes", sHostbasedAcceptedAlgorithms, SSHCFG_ALL }, /* obsolete */
680 	{ "hostkeyalgorithms", sHostKeyAlgorithms, SSHCFG_GLOBAL },
681 	{ "rsaauthentication", sDeprecated, SSHCFG_ALL },
682 	{ "pubkeyauthentication", sPubkeyAuthentication, SSHCFG_ALL },
683 	{ "pubkeyacceptedalgorithms", sPubkeyAcceptedAlgorithms, SSHCFG_ALL },
684 	{ "pubkeyacceptedkeytypes", sPubkeyAcceptedAlgorithms, SSHCFG_ALL }, /* obsolete */
685 	{ "pubkeyauthoptions", sPubkeyAuthOptions, SSHCFG_ALL },
686 	{ "dsaauthentication", sPubkeyAuthentication, SSHCFG_GLOBAL }, /* alias */
687 #ifdef KRB5
688 	{ "kerberosauthentication", sKerberosAuthentication, SSHCFG_ALL },
689 	{ "kerberosorlocalpasswd", sKerberosOrLocalPasswd, SSHCFG_GLOBAL },
690 	{ "kerberosticketcleanup", sKerberosTicketCleanup, SSHCFG_GLOBAL },
691 	{ "kerberosgetafstoken", sKerberosGetAFSToken, SSHCFG_GLOBAL },
692 #else
693 	{ "kerberosauthentication", sUnsupported, SSHCFG_ALL },
694 	{ "kerberosorlocalpasswd", sUnsupported, SSHCFG_GLOBAL },
695 	{ "kerberosticketcleanup", sUnsupported, SSHCFG_GLOBAL },
696 	{ "kerberosgetafstoken", sUnsupported, SSHCFG_GLOBAL },
697 #endif
698 #if defined(AFS) || defined(KRB5)
699 	{ "kerberostgtpassing", sKerberosTgtPassing, SSHCFG_GLOBAL },
700 #else
701 	{ "kerberostgtpassing", sUnsupported, SSHCFG_GLOBAL },
702 #endif
703 	{ "afstokenpassing", sUnsupported, SSHCFG_GLOBAL },
704 #ifdef GSSAPI
705 	{ "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
706 	{ "gssapicleanupcredentials", sGssCleanupCreds, SSHCFG_GLOBAL },
707 	{ "gssapistrictacceptorcheck", sGssStrictAcceptor, SSHCFG_GLOBAL },
708 #else
709 	{ "gssapiauthentication", sUnsupported, SSHCFG_ALL },
710 	{ "gssapicleanupcredentials", sUnsupported, SSHCFG_GLOBAL },
711 	{ "gssapistrictacceptorcheck", sUnsupported, SSHCFG_GLOBAL },
712 #endif
713 	{ "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
714 	{ "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
715 	{ "challengeresponseauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL },
716 	{ "skeyauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL }, /* alias */
717 	{ "checkmail", sDeprecated, SSHCFG_GLOBAL },
718 	{ "listenaddress", sListenAddress, SSHCFG_GLOBAL },
719 	{ "addressfamily", sAddressFamily, SSHCFG_GLOBAL },
720 	{ "printmotd", sPrintMotd, SSHCFG_GLOBAL },
721 	{ "printlastlog", sPrintLastLog, SSHCFG_GLOBAL },
722 	{ "ignorerhosts", sIgnoreRhosts, SSHCFG_ALL },
723 	{ "ignoreuserknownhosts", sIgnoreUserKnownHosts, SSHCFG_GLOBAL },
724 	{ "x11forwarding", sX11Forwarding, SSHCFG_ALL },
725 	{ "x11displayoffset", sX11DisplayOffset, SSHCFG_ALL },
726 	{ "x11uselocalhost", sX11UseLocalhost, SSHCFG_ALL },
727 	{ "xauthlocation", sXAuthLocation, SSHCFG_GLOBAL },
728 	{ "strictmodes", sStrictModes, SSHCFG_GLOBAL },
729 	{ "permitemptypasswords", sEmptyPasswd, SSHCFG_ALL },
730 	{ "permituserenvironment", sPermitUserEnvironment, SSHCFG_GLOBAL },
731 	{ "uselogin", sDeprecated, SSHCFG_GLOBAL },
732 	{ "compression", sCompression, SSHCFG_GLOBAL },
733 	{ "rekeylimit", sRekeyLimit, SSHCFG_ALL },
734 	{ "tcpkeepalive", sTCPKeepAlive, SSHCFG_GLOBAL },
735 	{ "keepalive", sTCPKeepAlive, SSHCFG_GLOBAL },	/* obsolete alias */
736 	{ "allowtcpforwarding", sAllowTcpForwarding, SSHCFG_ALL },
737 	{ "allowagentforwarding", sAllowAgentForwarding, SSHCFG_ALL },
738 	{ "allowusers", sAllowUsers, SSHCFG_ALL },
739 	{ "denyusers", sDenyUsers, SSHCFG_ALL },
740 	{ "allowgroups", sAllowGroups, SSHCFG_ALL },
741 	{ "denygroups", sDenyGroups, SSHCFG_ALL },
742 	{ "ciphers", sCiphers, SSHCFG_GLOBAL },
743 	{ "macs", sMacs, SSHCFG_GLOBAL },
744 	{ "protocol", sIgnore, SSHCFG_GLOBAL },
745 	{ "gatewayports", sGatewayPorts, SSHCFG_ALL },
746 	{ "subsystem", sSubsystem, SSHCFG_GLOBAL },
747 	{ "maxstartups", sMaxStartups, SSHCFG_GLOBAL },
748 	{ "persourcemaxstartups", sPerSourceMaxStartups, SSHCFG_GLOBAL },
749 	{ "persourcenetblocksize", sPerSourceNetBlockSize, SSHCFG_GLOBAL },
750 	{ "maxauthtries", sMaxAuthTries, SSHCFG_ALL },
751 	{ "maxsessions", sMaxSessions, SSHCFG_ALL },
752 	{ "banner", sBanner, SSHCFG_ALL },
753 	{ "usedns", sUseDNS, SSHCFG_GLOBAL },
754 	{ "verifyreversemapping", sDeprecated, SSHCFG_GLOBAL },
755 	{ "reversemappingcheck", sDeprecated, SSHCFG_GLOBAL },
756 	{ "clientaliveinterval", sClientAliveInterval, SSHCFG_ALL },
757 	{ "clientalivecountmax", sClientAliveCountMax, SSHCFG_ALL },
758 	{ "authorizedkeysfile", sAuthorizedKeysFile, SSHCFG_ALL },
759 	{ "authorizedkeysfile2", sDeprecated, SSHCFG_ALL },
760 #ifdef WITH_LDAP_PUBKEY
761 	{ _DEFAULT_LPK_TOKEN, sLdapPublickey, SSHCFG_GLOBAL },
762 	{ _DEFAULT_SRV_TOKEN, sLdapServers, SSHCFG_GLOBAL },
763 	{ _DEFAULT_USR_TOKEN, sLdapUserDN, SSHCFG_GLOBAL },
764 	{ _DEFAULT_GRP_TOKEN, sLdapGroupDN, SSHCFG_GLOBAL },
765 	{ _DEFAULT_BDN_TOKEN, sBindDN, SSHCFG_GLOBAL },
766 	{ _DEFAULT_BPW_TOKEN, sBindPw, SSHCFG_GLOBAL },
767 	{ _DEFAULT_MYG_TOKEN, sMyGroup, SSHCFG_GLOBAL },
768 	{ _DEFAULT_FIL_TOKEN, sLdapFilter, SSHCFG_GLOBAL },
769 	{ _DEFAULT_TLS_TOKEN, sForceTLS, SSHCFG_GLOBAL },
770 	{ _DEFAULT_BTI_TOKEN, sBindTimeout, SSHCFG_GLOBAL },
771 	{ _DEFAULT_STI_TOKEN, sSearchTimeout, SSHCFG_GLOBAL },
772 	{ _DEFAULT_LDP_TOKEN, sLdapConf, SSHCFG_GLOBAL },
773 	{ "LpkPubKeyAttr", sLpkPubKeyAttr, SSHCFG_GLOBAL },
774 #endif
775 	{ "useprivilegeseparation", sDeprecated, SSHCFG_GLOBAL},
776 	{ "acceptenv", sAcceptEnv, SSHCFG_ALL },
777 	{ "setenv", sSetEnv, SSHCFG_ALL },
778 	{ "permittunnel", sPermitTunnel, SSHCFG_ALL },
779 	{ "permittty", sPermitTTY, SSHCFG_ALL },
780 	{ "permituserrc", sPermitUserRC, SSHCFG_ALL },
781 	{ "match", sMatch, SSHCFG_ALL },
782 	{ "permitopen", sPermitOpen, SSHCFG_ALL },
783 	{ "permitlisten", sPermitListen, SSHCFG_ALL },
784 	{ "forcecommand", sForceCommand, SSHCFG_ALL },
785 	{ "chrootdirectory", sChrootDirectory, SSHCFG_ALL },
786 	{ "hostcertificate", sHostCertificate, SSHCFG_GLOBAL },
787 	{ "revokedkeys", sRevokedKeys, SSHCFG_ALL },
788 	{ "trustedusercakeys", sTrustedUserCAKeys, SSHCFG_ALL },
789 	{ "authorizedprincipalsfile", sAuthorizedPrincipalsFile, SSHCFG_ALL },
790 	{ "kexalgorithms", sKexAlgorithms, SSHCFG_GLOBAL },
791 	{ "include", sInclude, SSHCFG_ALL },
792 	{ "ipqos", sIPQoS, SSHCFG_ALL },
793 	{ "authorizedkeyscommand", sAuthorizedKeysCommand, SSHCFG_ALL },
794 	{ "authorizedkeyscommanduser", sAuthorizedKeysCommandUser, SSHCFG_ALL },
795 	{ "authorizedprincipalscommand", sAuthorizedPrincipalsCommand, SSHCFG_ALL },
796 	{ "authorizedprincipalscommanduser", sAuthorizedPrincipalsCommandUser, SSHCFG_ALL },
797 	{ "versionaddendum", sVersionAddendum, SSHCFG_GLOBAL },
798 	{ "noneenabled", sNoneEnabled, SSHCFG_ALL },
799 	{ "hpndisabled", sHPNDisabled, SSHCFG_ALL },
800 	{ "hpnbuffersize", sHPNBufferSize, SSHCFG_ALL },
801 	{ "tcprcvbufpoll", sTcpRcvBufPoll, SSHCFG_ALL },
802 	{ "authenticationmethods", sAuthenticationMethods, SSHCFG_ALL },
803 	{ "streamlocalbindmask", sStreamLocalBindMask, SSHCFG_ALL },
804 	{ "streamlocalbindunlink", sStreamLocalBindUnlink, SSHCFG_ALL },
805 	{ "allowstreamlocalforwarding", sAllowStreamLocalForwarding, SSHCFG_ALL },
806 	{ "fingerprinthash", sFingerprintHash, SSHCFG_GLOBAL },
807 	{ "disableforwarding", sDisableForwarding, SSHCFG_ALL },
808 	{ "exposeauthinfo", sExposeAuthInfo, SSHCFG_ALL },
809 	{ "rdomain", sRDomain, SSHCFG_ALL },
810 	{ "casignaturealgorithms", sCASignatureAlgorithms, SSHCFG_ALL },
811 	{ "securitykeyprovider", sSecurityKeyProvider, SSHCFG_GLOBAL },
812 	{ NULL, sBadOption, 0 }
813 };
814 
815 static struct {
816 	int val;
817 	const char *text;
818 } tunmode_desc[] = {
819 	{ SSH_TUNMODE_NO, "no" },
820 	{ SSH_TUNMODE_POINTOPOINT, "point-to-point" },
821 	{ SSH_TUNMODE_ETHERNET, "ethernet" },
822 	{ SSH_TUNMODE_YES, "yes" },
823 	{ -1, NULL }
824 };
825 
826 /* Returns an opcode name from its number */
827 
828 static const char *
829 lookup_opcode_name(ServerOpCodes code)
830 {
831 	u_int i;
832 
833 	for (i = 0; keywords[i].name != NULL; i++)
834 		if (keywords[i].opcode == code)
835 			return(keywords[i].name);
836 	return "UNKNOWN";
837 }
838 
839 
840 /*
841  * Returns the number of the token pointed to by cp or sBadOption.
842  */
843 
844 static ServerOpCodes
845 parse_token(const char *cp, const char *filename,
846 	    int linenum, u_int *flags)
847 {
848 	u_int i;
849 
850 	for (i = 0; keywords[i].name; i++)
851 		if (strcasecmp(cp, keywords[i].name) == 0) {
852 		        debug ("Config token is %s", keywords[i].name);
853 			*flags = keywords[i].flags;
854 			return keywords[i].opcode;
855 		}
856 
857 	error("%s: line %d: Bad configuration option: %s",
858 	    filename, linenum, cp);
859 	return sBadOption;
860 }
861 
862 char *
863 derelativise_path(const char *path)
864 {
865 	char *expanded, *ret, cwd[PATH_MAX];
866 
867 	if (strcasecmp(path, "none") == 0)
868 		return xstrdup("none");
869 	expanded = tilde_expand_filename(path, getuid());
870 	if (path_absolute(expanded))
871 		return expanded;
872 	if (getcwd(cwd, sizeof(cwd)) == NULL)
873 		fatal_f("getcwd: %s", strerror(errno));
874 	xasprintf(&ret, "%s/%s", cwd, expanded);
875 	free(expanded);
876 	return ret;
877 }
878 
879 static void
880 add_listen_addr(ServerOptions *options, const char *addr,
881     const char *rdomain, int port)
882 {
883 	u_int i;
884 
885 	if (port > 0)
886 		add_one_listen_addr(options, addr, rdomain, port);
887 	else {
888 		for (i = 0; i < options->num_ports; i++) {
889 			add_one_listen_addr(options, addr, rdomain,
890 			    options->ports[i]);
891 		}
892 	}
893 }
894 
895 static void
896 add_one_listen_addr(ServerOptions *options, const char *addr,
897     const char *rdomain, int port)
898 {
899 	struct addrinfo hints, *ai, *aitop;
900 	char strport[NI_MAXSERV];
901 	int gaierr;
902 	u_int i;
903 
904 	/* Find listen_addrs entry for this rdomain */
905 	for (i = 0; i < options->num_listen_addrs; i++) {
906 		if (rdomain == NULL && options->listen_addrs[i].rdomain == NULL)
907 			break;
908 		if (rdomain == NULL || options->listen_addrs[i].rdomain == NULL)
909 			continue;
910 		if (strcmp(rdomain, options->listen_addrs[i].rdomain) == 0)
911 			break;
912 	}
913 	if (i >= options->num_listen_addrs) {
914 		/* No entry for this rdomain; allocate one */
915 		if (i >= INT_MAX)
916 			fatal_f("too many listen addresses");
917 		options->listen_addrs = xrecallocarray(options->listen_addrs,
918 		    options->num_listen_addrs, options->num_listen_addrs + 1,
919 		    sizeof(*options->listen_addrs));
920 		i = options->num_listen_addrs++;
921 		if (rdomain != NULL)
922 			options->listen_addrs[i].rdomain = xstrdup(rdomain);
923 	}
924 	/* options->listen_addrs[i] points to the addresses for this rdomain */
925 
926 	memset(&hints, 0, sizeof(hints));
927 	hints.ai_family = options->address_family;
928 	hints.ai_socktype = SOCK_STREAM;
929 	hints.ai_flags = (addr == NULL) ? AI_PASSIVE : 0;
930 	snprintf(strport, sizeof strport, "%d", port);
931 	if ((gaierr = getaddrinfo(addr, strport, &hints, &aitop)) != 0)
932 		fatal("bad addr or host: %s (%s)",
933 		    addr ? addr : "<NULL>",
934 		    ssh_gai_strerror(gaierr));
935 	for (ai = aitop; ai->ai_next; ai = ai->ai_next)
936 		;
937 	ai->ai_next = options->listen_addrs[i].addrs;
938 	options->listen_addrs[i].addrs = aitop;
939 }
940 
941 /* Returns nonzero if the routing domain name is valid */
942 static int
943 valid_rdomain(const char *name)
944 {
945 #ifdef NET_RT_TABLE
946 	const char *errstr;
947 	long long num;
948 	struct rt_tableinfo info;
949 	int mib[6];
950 	size_t miblen = sizeof(mib);
951 
952 	if (name == NULL)
953 		return 1;
954 
955 	num = strtonum(name, 0, 255, &errstr);
956 	if (errstr != NULL)
957 		return 0;
958 
959 	/* Check whether the table actually exists */
960 	memset(mib, 0, sizeof(mib));
961 	mib[0] = CTL_NET;
962 	mib[1] = PF_ROUTE;
963 	mib[4] = NET_RT_TABLE;
964 	mib[5] = (int)num;
965 	if (sysctl(mib, 6, &info, &miblen, NULL, 0) == -1)
966 		return 0;
967 
968 	return 1;
969 #else
970 	return 0;
971 #endif
972 }
973 
974 /*
975  * Queue a ListenAddress to be processed once we have all of the Ports
976  * and AddressFamily options.
977  */
978 static void
979 queue_listen_addr(ServerOptions *options, const char *addr,
980     const char *rdomain, int port)
981 {
982 	struct queued_listenaddr *qla;
983 
984 	options->queued_listen_addrs = xrecallocarray(
985 	    options->queued_listen_addrs,
986 	    options->num_queued_listens, options->num_queued_listens + 1,
987 	    sizeof(*options->queued_listen_addrs));
988 	qla = &options->queued_listen_addrs[options->num_queued_listens++];
989 	qla->addr = xstrdup(addr);
990 	qla->port = port;
991 	qla->rdomain = rdomain == NULL ? NULL : xstrdup(rdomain);
992 }
993 
994 /*
995  * Process queued (text) ListenAddress entries.
996  */
997 static void
998 process_queued_listen_addrs(ServerOptions *options)
999 {
1000 	u_int i;
1001 	struct queued_listenaddr *qla;
1002 
1003 	if (options->num_ports == 0)
1004 		options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
1005 	if (options->address_family == -1)
1006 		options->address_family = AF_UNSPEC;
1007 
1008 	for (i = 0; i < options->num_queued_listens; i++) {
1009 		qla = &options->queued_listen_addrs[i];
1010 		add_listen_addr(options, qla->addr, qla->rdomain, qla->port);
1011 		free(qla->addr);
1012 		free(qla->rdomain);
1013 	}
1014 	free(options->queued_listen_addrs);
1015 	options->queued_listen_addrs = NULL;
1016 	options->num_queued_listens = 0;
1017 }
1018 
1019 /*
1020  * Inform channels layer of permitopen options for a single forwarding
1021  * direction (local/remote).
1022  */
1023 static void
1024 process_permitopen_list(struct ssh *ssh, ServerOpCodes opcode,
1025     char **opens, u_int num_opens)
1026 {
1027 	u_int i;
1028 	int port;
1029 	char *host, *arg, *oarg, ch;
1030 	int where = opcode == sPermitOpen ? FORWARD_LOCAL : FORWARD_REMOTE;
1031 	const char *what = lookup_opcode_name(opcode);
1032 
1033 	channel_clear_permission(ssh, FORWARD_ADM, where);
1034 	if (num_opens == 0)
1035 		return; /* permit any */
1036 
1037 	/* handle keywords: "any" / "none" */
1038 	if (num_opens == 1 && strcmp(opens[0], "any") == 0)
1039 		return;
1040 	if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
1041 		channel_disable_admin(ssh, where);
1042 		return;
1043 	}
1044 	/* Otherwise treat it as a list of permitted host:port */
1045 	for (i = 0; i < num_opens; i++) {
1046 		oarg = arg = xstrdup(opens[i]);
1047 		ch = '\0';
1048 		host = hpdelim2(&arg, &ch);
1049 		if (host == NULL || ch == '/')
1050 			fatal_f("missing host in %s", what);
1051 		host = cleanhostname(host);
1052 		if (arg == NULL || ((port = permitopen_port(arg)) < 0))
1053 			fatal_f("bad port number in %s", what);
1054 		/* Send it to channels layer */
1055 		channel_add_permission(ssh, FORWARD_ADM,
1056 		    where, host, port);
1057 		free(oarg);
1058 	}
1059 }
1060 
1061 /*
1062  * Inform channels layer of permitopen options from configuration.
1063  */
1064 void
1065 process_permitopen(struct ssh *ssh, ServerOptions *options)
1066 {
1067 	process_permitopen_list(ssh, sPermitOpen,
1068 	    options->permitted_opens, options->num_permitted_opens);
1069 	process_permitopen_list(ssh, sPermitListen,
1070 	    options->permitted_listens,
1071 	    options->num_permitted_listens);
1072 }
1073 
1074 struct connection_info *
1075 get_connection_info(struct ssh *ssh, int populate, int use_dns)
1076 {
1077 	static struct connection_info ci;
1078 
1079 	if (ssh == NULL || !populate)
1080 		return &ci;
1081 	ci.host = auth_get_canonical_hostname(ssh, use_dns);
1082 	ci.address = ssh_remote_ipaddr(ssh);
1083 	ci.laddress = ssh_local_ipaddr(ssh);
1084 	ci.lport = ssh_local_port(ssh);
1085 	ci.rdomain = ssh_packet_rdomain_in(ssh);
1086 	return &ci;
1087 }
1088 
1089 /*
1090  * The strategy for the Match blocks is that the config file is parsed twice.
1091  *
1092  * The first time is at startup.  activep is initialized to 1 and the
1093  * directives in the global context are processed and acted on.  Hitting a
1094  * Match directive unsets activep and the directives inside the block are
1095  * checked for syntax only.
1096  *
1097  * The second time is after a connection has been established but before
1098  * authentication.  activep is initialized to 2 and global config directives
1099  * are ignored since they have already been processed.  If the criteria in a
1100  * Match block is met, activep is set and the subsequent directives
1101  * processed and actioned until EOF or another Match block unsets it.  Any
1102  * options set are copied into the main server config.
1103  *
1104  * Potential additions/improvements:
1105  *  - Add Match support for pre-kex directives, eg. Ciphers.
1106  *
1107  *  - Add a Tag directive (idea from David Leonard) ala pf, eg:
1108  *	Match Address 192.168.0.*
1109  *		Tag trusted
1110  *	Match Group wheel
1111  *		Tag trusted
1112  *	Match Tag trusted
1113  *		AllowTcpForwarding yes
1114  *		GatewayPorts clientspecified
1115  *		[...]
1116  *
1117  *  - Add a PermittedChannelRequests directive
1118  *	Match Group shell
1119  *		PermittedChannelRequests session,forwarded-tcpip
1120  */
1121 
1122 static int
1123 match_cfg_line_group(const char *grps, int line, const char *user)
1124 {
1125 	int result = 0;
1126 	struct passwd *pw;
1127 
1128 	if (user == NULL)
1129 		goto out;
1130 
1131 	if ((pw = getpwnam(user)) == NULL) {
1132 		debug("Can't match group at line %d because user %.100s does "
1133 		    "not exist", line, user);
1134 	} else if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
1135 		debug("Can't Match group because user %.100s not in any group "
1136 		    "at line %d", user, line);
1137 	} else if (ga_match_pattern_list(grps) != 1) {
1138 		debug("user %.100s does not match group list %.100s at line %d",
1139 		    user, grps, line);
1140 	} else {
1141 		debug("user %.100s matched group list %.100s at line %d", user,
1142 		    grps, line);
1143 		result = 1;
1144 	}
1145 out:
1146 	ga_free();
1147 	return result;
1148 }
1149 
1150 __dead static void
1151 match_test_missing_fatal(const char *criteria, const char *attrib)
1152 {
1153 	fatal("'Match %s' in configuration but '%s' not in connection "
1154 	    "test specification.", criteria, attrib);
1155 }
1156 
1157 /*
1158  * All of the attributes on a single Match line are ANDed together, so we need
1159  * to check every attribute and set the result to zero if any attribute does
1160  * not match.
1161  */
1162 static int
1163 match_cfg_line(char **condition, int line, struct connection_info *ci)
1164 {
1165 	int result = 1, attributes = 0, port;
1166 	char *arg, *attrib, *cp = *condition;
1167 
1168 	if (ci == NULL)
1169 		debug3("checking syntax for 'Match %s'", cp);
1170 	else
1171 		debug3("checking match for '%s' user %s host %s addr %s "
1172 		    "laddr %s lport %d", cp, ci->user ? ci->user : "(null)",
1173 		    ci->host ? ci->host : "(null)",
1174 		    ci->address ? ci->address : "(null)",
1175 		    ci->laddress ? ci->laddress : "(null)", ci->lport);
1176 
1177 	while ((attrib = strdelim(&cp)) && *attrib != '\0') {
1178 		attributes++;
1179 		if (strcasecmp(attrib, "all") == 0) {
1180 			if (attributes != 1 ||
1181 			    ((arg = strdelim(&cp)) != NULL && *arg != '\0')) {
1182 				error("'all' cannot be combined with other "
1183 				    "Match attributes");
1184 				return -1;
1185 			}
1186 			*condition = cp;
1187 			return 1;
1188 		}
1189 		if ((arg = strdelim(&cp)) == NULL || *arg == '\0') {
1190 			error("Missing Match criteria for %s", attrib);
1191 			return -1;
1192 		}
1193 		if (strcasecmp(attrib, "user") == 0) {
1194 			if (ci == NULL || (ci->test && ci->user == NULL)) {
1195 				result = 0;
1196 				continue;
1197 			}
1198 			if (ci->user == NULL)
1199 				match_test_missing_fatal("User", "user");
1200 			if (match_usergroup_pattern_list(ci->user, arg) != 1)
1201 				result = 0;
1202 			else
1203 				debug("user %.100s matched 'User %.100s' at "
1204 				    "line %d", ci->user, arg, line);
1205 		} else if (strcasecmp(attrib, "group") == 0) {
1206 			if (ci == NULL || (ci->test && ci->user == NULL)) {
1207 				result = 0;
1208 				continue;
1209 			}
1210 			if (ci->user == NULL)
1211 				match_test_missing_fatal("Group", "user");
1212 			switch (match_cfg_line_group(arg, line, ci->user)) {
1213 			case -1:
1214 				return -1;
1215 			case 0:
1216 				result = 0;
1217 			}
1218 		} else if (strcasecmp(attrib, "host") == 0) {
1219 			if (ci == NULL || (ci->test && ci->host == NULL)) {
1220 				result = 0;
1221 				continue;
1222 			}
1223 			if (ci->host == NULL)
1224 				match_test_missing_fatal("Host", "host");
1225 			if (match_hostname(ci->host, arg) != 1)
1226 				result = 0;
1227 			else
1228 				debug("connection from %.100s matched 'Host "
1229 				    "%.100s' at line %d", ci->host, arg, line);
1230 		} else if (strcasecmp(attrib, "address") == 0) {
1231 			if (ci == NULL || (ci->test && ci->address == NULL)) {
1232 				if (addr_match_list(NULL, arg) != 0)
1233 					fatal("Invalid Match address argument "
1234 					    "'%s' at line %d", arg, line);
1235 				result = 0;
1236 				continue;
1237 			}
1238 			if (ci->address == NULL)
1239 				match_test_missing_fatal("Address", "addr");
1240 			switch (addr_match_list(ci->address, arg)) {
1241 			case 1:
1242 				debug("connection from %.100s matched 'Address "
1243 				    "%.100s' at line %d", ci->address, arg, line);
1244 				break;
1245 			case 0:
1246 			case -1:
1247 				result = 0;
1248 				break;
1249 			case -2:
1250 				return -1;
1251 			}
1252 		} else if (strcasecmp(attrib, "localaddress") == 0){
1253 			if (ci == NULL || (ci->test && ci->laddress == NULL)) {
1254 				if (addr_match_list(NULL, arg) != 0)
1255 					fatal("Invalid Match localaddress "
1256 					    "argument '%s' at line %d", arg,
1257 					    line);
1258 				result = 0;
1259 				continue;
1260 			}
1261 			if (ci->laddress == NULL)
1262 				match_test_missing_fatal("LocalAddress",
1263 				    "laddr");
1264 			switch (addr_match_list(ci->laddress, arg)) {
1265 			case 1:
1266 				debug("connection from %.100s matched "
1267 				    "'LocalAddress %.100s' at line %d",
1268 				    ci->laddress, arg, line);
1269 				break;
1270 			case 0:
1271 			case -1:
1272 				result = 0;
1273 				break;
1274 			case -2:
1275 				return -1;
1276 			}
1277 		} else if (strcasecmp(attrib, "localport") == 0) {
1278 			if ((port = a2port(arg)) == -1) {
1279 				error("Invalid LocalPort '%s' on Match line",
1280 				    arg);
1281 				return -1;
1282 			}
1283 			if (ci == NULL || (ci->test && ci->lport == -1)) {
1284 				result = 0;
1285 				continue;
1286 			}
1287 			if (ci->lport == 0)
1288 				match_test_missing_fatal("LocalPort", "lport");
1289 			/* TODO support port lists */
1290 			if (port == ci->lport)
1291 				debug("connection from %.100s matched "
1292 				    "'LocalPort %d' at line %d",
1293 				    ci->laddress, port, line);
1294 			else
1295 				result = 0;
1296 		} else if (strcasecmp(attrib, "rdomain") == 0) {
1297 			if (ci == NULL || (ci->test && ci->rdomain == NULL)) {
1298 				result = 0;
1299 				continue;
1300 			}
1301 			if (ci->rdomain == NULL)
1302 				match_test_missing_fatal("RDomain", "rdomain");
1303 			if (match_pattern_list(ci->rdomain, arg, 0) != 1)
1304 				result = 0;
1305 			else
1306 				debug("user %.100s matched 'RDomain %.100s' at "
1307 				    "line %d", ci->rdomain, arg, line);
1308 		} else {
1309 			error("Unsupported Match attribute %s", attrib);
1310 			return -1;
1311 		}
1312 	}
1313 	if (attributes == 0) {
1314 		error("One or more attributes required for Match");
1315 		return -1;
1316 	}
1317 	if (ci != NULL)
1318 		debug3("match %sfound", result ? "" : "not ");
1319 	*condition = cp;
1320 	return result;
1321 }
1322 
1323 #define WHITESPACE " \t\r\n"
1324 
1325 /* Multistate option parsing */
1326 struct multistate {
1327 	const char *key;
1328 	int value;
1329 };
1330 static const struct multistate multistate_flag[] = {
1331 	{ "yes",			1 },
1332 	{ "no",				0 },
1333 	{ NULL, -1 }
1334 };
1335 static const struct multistate multistate_ignore_rhosts[] = {
1336 	{ "yes",			IGNORE_RHOSTS_YES },
1337 	{ "no",				IGNORE_RHOSTS_NO },
1338 	{ "shosts-only",		IGNORE_RHOSTS_SHOSTS },
1339 	{ NULL, -1 }
1340 };
1341 static const struct multistate multistate_addressfamily[] = {
1342 	{ "inet",			AF_INET },
1343 	{ "inet6",			AF_INET6 },
1344 	{ "any",			AF_UNSPEC },
1345 	{ NULL, -1 }
1346 };
1347 static const struct multistate multistate_permitrootlogin[] = {
1348 	{ "without-password",		PERMIT_NO_PASSWD },
1349 	{ "prohibit-password",		PERMIT_NO_PASSWD },
1350 	{ "forced-commands-only",	PERMIT_FORCED_ONLY },
1351 	{ "yes",			PERMIT_YES },
1352 	{ "no",				PERMIT_NO },
1353 	{ NULL, -1 }
1354 };
1355 static const struct multistate multistate_compression[] = {
1356 #ifdef WITH_ZLIB
1357 	{ "yes",			COMP_DELAYED },
1358 	{ "delayed",			COMP_DELAYED },
1359 #endif
1360 	{ "no",				COMP_NONE },
1361 	{ NULL, -1 }
1362 };
1363 static const struct multistate multistate_gatewayports[] = {
1364 	{ "clientspecified",		2 },
1365 	{ "yes",			1 },
1366 	{ "no",				0 },
1367 	{ NULL, -1 }
1368 };
1369 static const struct multistate multistate_tcpfwd[] = {
1370 	{ "yes",			FORWARD_ALLOW },
1371 	{ "all",			FORWARD_ALLOW },
1372 	{ "no",				FORWARD_DENY },
1373 	{ "remote",			FORWARD_REMOTE },
1374 	{ "local",			FORWARD_LOCAL },
1375 	{ NULL, -1 }
1376 };
1377 
1378 static int
1379 process_server_config_line_depth(ServerOptions *options, char *line,
1380     const char *filename, int linenum, int *activep,
1381     struct connection_info *connectinfo, int *inc_flags, int depth,
1382     struct include_list *includes)
1383 {
1384 	char ch, *cp, ***chararrayptr, **charptr, *arg, *arg2, *p;
1385 	int cmdline = 0, *intptr, value, value2, n, port, oactive, r, found;
1386 	SyslogFacility *log_facility_ptr;
1387 	LogLevel *log_level_ptr;
1388 #ifdef WITH_LDAP_PUBKEY
1389  	unsigned long lvalue;
1390 #endif
1391 	time_t *timetptr __unused;
1392 	ServerOpCodes opcode;
1393 	u_int i, *uintptr, uvalue, flags = 0;
1394 	size_t len;
1395 	long long val64;
1396 	const struct multistate *multistate_ptr;
1397 	const char *errstr;
1398 	struct include_item *item;
1399 	glob_t gbuf;
1400 
1401 	/* Strip trailing whitespace. Allow \f (form feed) at EOL only */
1402 	if ((len = strlen(line)) == 0)
1403 		return 0;
1404 	for (len--; len > 0; len--) {
1405 		if (strchr(WHITESPACE "\f", line[len]) == NULL)
1406 			break;
1407 		line[len] = '\0';
1408 	}
1409 
1410 	cp = line;
1411 	if ((arg = strdelim(&cp)) == NULL)
1412 		return 0;
1413 	/* Ignore leading whitespace */
1414 	if (*arg == '\0')
1415 		arg = strdelim(&cp);
1416 	if (!arg || !*arg || *arg == '#')
1417 		return 0;
1418 	intptr = NULL;
1419 	timetptr = NULL;
1420 	charptr = NULL;
1421 	opcode = parse_token(arg, filename, linenum, &flags);
1422 
1423 	if (activep == NULL) { /* We are processing a command line directive */
1424 		cmdline = 1;
1425 		activep = &cmdline;
1426 	}
1427 	if (*activep && opcode != sMatch && opcode != sInclude)
1428 		debug3("%s:%d setting %s %s", filename, linenum, arg, cp);
1429 	if (*activep == 0 && !(flags & SSHCFG_MATCH)) {
1430 		if (connectinfo == NULL) {
1431 			fatal("%s line %d: Directive '%s' is not allowed "
1432 			    "within a Match block", filename, linenum, arg);
1433 		} else { /* this is a directive we have already processed */
1434 			while (arg)
1435 				arg = strdelim(&cp);
1436 			return 0;
1437 		}
1438 	}
1439 
1440 	switch (opcode) {
1441 	/* Portable-specific options */
1442 	case sUsePAM:
1443 		intptr = &options->use_pam;
1444 		goto parse_flag;
1445 
1446 	/* Standard Options */
1447 	case sBadOption:
1448 		return -1;
1449 	case sPort:
1450 		/* ignore ports from configfile if cmdline specifies ports */
1451 		if (options->ports_from_cmdline)
1452 			return 0;
1453 		if (options->num_ports >= MAX_PORTS)
1454 			fatal("%s line %d: too many ports.",
1455 			    filename, linenum);
1456 		arg = strdelim(&cp);
1457 		if (!arg || *arg == '\0')
1458 			fatal("%s line %d: missing port number.",
1459 			    filename, linenum);
1460 		options->ports[options->num_ports++] = a2port(arg);
1461 		if (options->ports[options->num_ports-1] <= 0)
1462 			fatal("%s line %d: Badly formatted port number.",
1463 			    filename, linenum);
1464 		break;
1465 
1466 	case sLoginGraceTime:
1467 		intptr = &options->login_grace_time;
1468  parse_time:
1469 		arg = strdelim(&cp);
1470 		if (!arg || *arg == '\0')
1471 			fatal("%s line %d: missing time value.",
1472 			    filename, linenum);
1473 		if ((value = convtime(arg)) == -1)
1474 			fatal("%s line %d: invalid time value.",
1475 			    filename, linenum);
1476 		if (*activep && *intptr == -1)
1477 			*intptr = value;
1478 		break;
1479 
1480 	case sListenAddress:
1481 		arg = strdelim(&cp);
1482 		if (arg == NULL || *arg == '\0')
1483 			fatal("%s line %d: missing address",
1484 			    filename, linenum);
1485 		/* check for bare IPv6 address: no "[]" and 2 or more ":" */
1486 		if (strchr(arg, '[') == NULL && (p = strchr(arg, ':')) != NULL
1487 		    && strchr(p+1, ':') != NULL) {
1488 			port = 0;
1489 			p = arg;
1490 		} else {
1491 			arg2 = NULL;
1492 			ch = '\0';
1493 			p = hpdelim2(&arg, &ch);
1494 			if (p == NULL || ch == '/')
1495 				fatal("%s line %d: bad address:port usage",
1496 				    filename, linenum);
1497 			p = cleanhostname(p);
1498 			if (arg == NULL)
1499 				port = 0;
1500 			else if ((port = a2port(arg)) <= 0)
1501 				fatal("%s line %d: bad port number",
1502 				    filename, linenum);
1503 		}
1504 		/* Optional routing table */
1505 		arg2 = NULL;
1506 		if ((arg = strdelim(&cp)) != NULL) {
1507 			if (strcmp(arg, "rdomain") != 0 ||
1508 			    (arg2 = strdelim(&cp)) == NULL)
1509 				fatal("%s line %d: bad ListenAddress syntax",
1510 				    filename, linenum);
1511 			if (!valid_rdomain(arg2))
1512 				fatal("%s line %d: bad routing domain",
1513 				    filename, linenum);
1514 		}
1515 
1516 		queue_listen_addr(options, p, arg2, port);
1517 
1518 		break;
1519 
1520 	case sAddressFamily:
1521 		intptr = &options->address_family;
1522 		multistate_ptr = multistate_addressfamily;
1523  parse_multistate:
1524 		arg = strdelim(&cp);
1525 		if (!arg || *arg == '\0')
1526 			fatal("%s line %d: missing argument.",
1527 			    filename, linenum);
1528 		value = -1;
1529 		for (i = 0; multistate_ptr[i].key != NULL; i++) {
1530 			if (strcasecmp(arg, multistate_ptr[i].key) == 0) {
1531 				value = multistate_ptr[i].value;
1532 				break;
1533 			}
1534 		}
1535 		if (value == -1)
1536 			fatal("%s line %d: unsupported option \"%s\".",
1537 			    filename, linenum, arg);
1538 		if (*activep && *intptr == -1)
1539 			*intptr = value;
1540 		break;
1541 
1542 	case sHostKeyFile:
1543 		arg = strdelim(&cp);
1544 		if (!arg || *arg == '\0')
1545 			fatal("%s line %d: missing file name.",
1546 			    filename, linenum);
1547 		if (*activep) {
1548 			servconf_add_hostkey(filename, linenum,
1549 			    options, arg, 1);
1550 		}
1551 		break;
1552 
1553 	case sHostKeyAgent:
1554 		charptr = &options->host_key_agent;
1555 		arg = strdelim(&cp);
1556 		if (!arg || *arg == '\0')
1557 			fatal("%s line %d: missing socket name.",
1558 			    filename, linenum);
1559 		if (*activep && *charptr == NULL)
1560 			*charptr = !strcmp(arg, SSH_AUTHSOCKET_ENV_NAME) ?
1561 			    xstrdup(arg) : derelativise_path(arg);
1562 		break;
1563 
1564 	case sHostCertificate:
1565 		arg = strdelim(&cp);
1566 		if (!arg || *arg == '\0')
1567 			fatal("%s line %d: missing file name.",
1568 			    filename, linenum);
1569 		if (*activep)
1570 			servconf_add_hostcert(filename, linenum, options, arg);
1571 		break;
1572 
1573 	case sPidFile:
1574 		charptr = &options->pid_file;
1575  parse_filename:
1576 		arg = strdelim(&cp);
1577 		if (!arg || *arg == '\0')
1578 			fatal("%s line %d: missing file name.",
1579 			    filename, linenum);
1580 		if (*activep && *charptr == NULL) {
1581 			*charptr = derelativise_path(arg);
1582 			/* increase optional counter */
1583 			if (intptr != NULL)
1584 				*intptr = *intptr + 1;
1585 		}
1586 		break;
1587 
1588 	case sPermitRootLogin:
1589 		intptr = &options->permit_root_login;
1590 		multistate_ptr = multistate_permitrootlogin;
1591 		goto parse_multistate;
1592 
1593 	case sIgnoreRhosts:
1594 		intptr = &options->ignore_rhosts;
1595 		multistate_ptr = multistate_ignore_rhosts;
1596 		goto parse_multistate;
1597 
1598 	case sIgnoreRootRhosts:
1599 		intptr = &options->ignore_root_rhosts;
1600 		goto parse_flag;
1601 
1602 	case sNoneEnabled:
1603 		intptr = &options->none_enabled;
1604 		goto parse_flag;
1605 
1606 	case sTcpRcvBufPoll:
1607 		intptr = &options->tcp_rcv_buf_poll;
1608 		goto parse_flag;
1609 
1610 	case sHPNDisabled:
1611 		intptr = &options->hpn_disabled;
1612 		goto parse_flag;
1613 
1614 	case sHPNBufferSize:
1615 		intptr = &options->hpn_buffer_size;
1616 		goto parse_int;
1617 
1618 	case sIgnoreUserKnownHosts:
1619 		intptr = &options->ignore_user_known_hosts;
1620  parse_flag:
1621 		multistate_ptr = multistate_flag;
1622 		goto parse_multistate;
1623 
1624 	case sHostbasedAuthentication:
1625 		intptr = &options->hostbased_authentication;
1626 		goto parse_flag;
1627 
1628 	case sHostbasedUsesNameFromPacketOnly:
1629 		intptr = &options->hostbased_uses_name_from_packet_only;
1630 		goto parse_flag;
1631 
1632 	case sHostbasedAcceptedAlgorithms:
1633 		charptr = &options->hostbased_accepted_algos;
1634  parse_pubkey_algos:
1635 		arg = strdelim(&cp);
1636 		if (!arg || *arg == '\0')
1637 			fatal("%s line %d: Missing argument.",
1638 			    filename, linenum);
1639 		if (*arg != '-' &&
1640 		    !sshkey_names_valid2(*arg == '+' || *arg == '^' ?
1641 		    arg + 1 : arg, 1))
1642 			fatal("%s line %d: Bad key types '%s'.",
1643 			    filename, linenum, arg ? arg : "<NONE>");
1644 		if (*activep && *charptr == NULL)
1645 			*charptr = xstrdup(arg);
1646 		break;
1647 
1648 	case sHostKeyAlgorithms:
1649 		charptr = &options->hostkeyalgorithms;
1650 		goto parse_pubkey_algos;
1651 
1652 	case sCASignatureAlgorithms:
1653 		charptr = &options->ca_sign_algorithms;
1654 		goto parse_pubkey_algos;
1655 
1656 	case sPubkeyAuthentication:
1657 		intptr = &options->pubkey_authentication;
1658 		goto parse_flag;
1659 
1660 	case sPubkeyAcceptedAlgorithms:
1661 		charptr = &options->pubkey_accepted_algos;
1662 		goto parse_pubkey_algos;
1663 
1664 	case sPubkeyAuthOptions:
1665 		intptr = &options->pubkey_auth_options;
1666 		value = 0;
1667 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1668 			if (strcasecmp(arg, "none") == 0)
1669 				continue;
1670 			if (strcasecmp(arg, "touch-required") == 0)
1671 				value |= PUBKEYAUTH_TOUCH_REQUIRED;
1672 			else if (strcasecmp(arg, "verify-required") == 0)
1673 				value |= PUBKEYAUTH_VERIFY_REQUIRED;
1674 			else {
1675 				fatal("%s line %d: unsupported "
1676 				    "PubkeyAuthOptions option %s",
1677 				    filename, linenum, arg);
1678 			}
1679 		}
1680 		if (*activep && *intptr == -1)
1681 			*intptr = value;
1682 		break;
1683 
1684 	case sKerberosAuthentication:
1685 		intptr = &options->kerberos_authentication;
1686 		goto parse_flag;
1687 
1688 	case sKerberosOrLocalPasswd:
1689 		intptr = &options->kerberos_or_local_passwd;
1690 		goto parse_flag;
1691 
1692 	case sKerberosTicketCleanup:
1693 		intptr = &options->kerberos_ticket_cleanup;
1694 		goto parse_flag;
1695 
1696 	case sKerberosTgtPassing:
1697 		intptr = &options->kerberos_tgt_passing;
1698 		goto parse_flag;
1699 
1700 	case sKerberosGetAFSToken:
1701 		intptr = &options->kerberos_get_afs_token;
1702 		goto parse_flag;
1703 
1704 	case sGssAuthentication:
1705 		intptr = &options->gss_authentication;
1706 		goto parse_flag;
1707 
1708 	case sGssCleanupCreds:
1709 		intptr = &options->gss_cleanup_creds;
1710 		goto parse_flag;
1711 
1712 	case sGssStrictAcceptor:
1713 		intptr = &options->gss_strict_acceptor;
1714 		goto parse_flag;
1715 
1716 	case sPasswordAuthentication:
1717 		intptr = &options->password_authentication;
1718 		goto parse_flag;
1719 
1720 	case sKbdInteractiveAuthentication:
1721 		intptr = &options->kbd_interactive_authentication;
1722 		goto parse_flag;
1723 
1724 	case sChallengeResponseAuthentication:
1725 		intptr = &options->challenge_response_authentication;
1726 		goto parse_flag;
1727 
1728 	case sPrintMotd:
1729 		intptr = &options->print_motd;
1730 		goto parse_flag;
1731 
1732 	case sPrintLastLog:
1733 		intptr = &options->print_lastlog;
1734 		goto parse_flag;
1735 
1736 	case sX11Forwarding:
1737 		intptr = &options->x11_forwarding;
1738 		goto parse_flag;
1739 
1740 	case sX11DisplayOffset:
1741 		intptr = &options->x11_display_offset;
1742  parse_int:
1743 		arg = strdelim(&cp);
1744 		if ((errstr = atoi_err(arg, &value)) != NULL)
1745 			fatal("%s line %d: integer value %s.",
1746 			    filename, linenum, errstr);
1747 		if (*activep && *intptr == -1)
1748 			*intptr = value;
1749 		break;
1750 
1751 	case sX11UseLocalhost:
1752 		intptr = &options->x11_use_localhost;
1753 		goto parse_flag;
1754 
1755 	case sXAuthLocation:
1756 		charptr = &options->xauth_location;
1757 		goto parse_filename;
1758 
1759 	case sPermitTTY:
1760 		intptr = &options->permit_tty;
1761 		goto parse_flag;
1762 
1763 	case sPermitUserRC:
1764 		intptr = &options->permit_user_rc;
1765 		goto parse_flag;
1766 
1767 	case sStrictModes:
1768 		intptr = &options->strict_modes;
1769 		goto parse_flag;
1770 
1771 	case sTCPKeepAlive:
1772 		intptr = &options->tcp_keep_alive;
1773 		goto parse_flag;
1774 
1775 	case sEmptyPasswd:
1776 		intptr = &options->permit_empty_passwd;
1777 		goto parse_flag;
1778 
1779 	case sPermitUserEnvironment:
1780 		intptr = &options->permit_user_env;
1781 		charptr = &options->permit_user_env_allowlist;
1782 		arg = strdelim(&cp);
1783 		if (!arg || *arg == '\0')
1784 			fatal("%s line %d: missing argument.",
1785 			    filename, linenum);
1786 		value = 0;
1787 		p = NULL;
1788 		if (strcmp(arg, "yes") == 0)
1789 			value = 1;
1790 		else if (strcmp(arg, "no") == 0)
1791 			value = 0;
1792 		else {
1793 			/* Pattern-list specified */
1794 			value = 1;
1795 			p = xstrdup(arg);
1796 		}
1797 		if (*activep && *intptr == -1) {
1798 			*intptr = value;
1799 			*charptr = p;
1800 			p = NULL;
1801 		}
1802 		free(p);
1803 		break;
1804 
1805 	case sCompression:
1806 		intptr = &options->compression;
1807 		multistate_ptr = multistate_compression;
1808 		goto parse_multistate;
1809 
1810 	case sRekeyLimit:
1811 		arg = strdelim(&cp);
1812 		if (!arg || *arg == '\0')
1813 			fatal("%.200s line %d: Missing argument.", filename,
1814 			    linenum);
1815 		if (strcmp(arg, "default") == 0) {
1816 			val64 = 0;
1817 		} else {
1818 			if (scan_scaled(arg, &val64) == -1)
1819 				fatal("%.200s line %d: Bad number '%s': %s",
1820 				    filename, linenum, arg, strerror(errno));
1821 			if (val64 != 0 && val64 < 16)
1822 				fatal("%.200s line %d: RekeyLimit too small",
1823 				    filename, linenum);
1824 		}
1825 		if (*activep && options->rekey_limit == -1)
1826 			options->rekey_limit = val64;
1827 		if (cp != NULL) { /* optional rekey interval present */
1828 			if (strcmp(cp, "none") == 0) {
1829 				(void)strdelim(&cp);	/* discard */
1830 				break;
1831 			}
1832 			intptr = &options->rekey_interval;
1833 			goto parse_time;
1834 		}
1835 		break;
1836 
1837 	case sGatewayPorts:
1838 		intptr = &options->fwd_opts.gateway_ports;
1839 		multistate_ptr = multistate_gatewayports;
1840 		goto parse_multistate;
1841 
1842 	case sUseDNS:
1843 		intptr = &options->use_dns;
1844 		goto parse_flag;
1845 
1846 	case sLogFacility:
1847 		log_facility_ptr = &options->log_facility;
1848 		arg = strdelim(&cp);
1849 		value = log_facility_number(arg);
1850 		if (value == SYSLOG_FACILITY_NOT_SET)
1851 			fatal("%.200s line %d: unsupported log facility '%s'",
1852 			    filename, linenum, arg ? arg : "<NONE>");
1853 		if (*log_facility_ptr == -1)
1854 			*log_facility_ptr = (SyslogFacility) value;
1855 		break;
1856 
1857 	case sLogLevel:
1858 		log_level_ptr = &options->log_level;
1859 		arg = strdelim(&cp);
1860 		value = log_level_number(arg);
1861 		if (value == SYSLOG_LEVEL_NOT_SET)
1862 			fatal("%.200s line %d: unsupported log level '%s'",
1863 			    filename, linenum, arg ? arg : "<NONE>");
1864 		if (*activep && *log_level_ptr == -1)
1865 			*log_level_ptr = (LogLevel) value;
1866 		break;
1867 
1868 	case sLogVerbose:
1869 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1870 			if (!*activep)
1871 				continue;
1872 			opt_array_append(filename, linenum, "oLogVerbose",
1873 			    &options->log_verbose, &options->num_log_verbose,
1874 			    arg);
1875 		}
1876 		break;
1877 
1878 	case sAllowTcpForwarding:
1879 		intptr = &options->allow_tcp_forwarding;
1880 		multistate_ptr = multistate_tcpfwd;
1881 		goto parse_multistate;
1882 
1883 	case sAllowStreamLocalForwarding:
1884 		intptr = &options->allow_streamlocal_forwarding;
1885 		multistate_ptr = multistate_tcpfwd;
1886 		goto parse_multistate;
1887 
1888 	case sAllowAgentForwarding:
1889 		intptr = &options->allow_agent_forwarding;
1890 		goto parse_flag;
1891 
1892 	case sDisableForwarding:
1893 		intptr = &options->disable_forwarding;
1894 		goto parse_flag;
1895 
1896 	case sAllowUsers:
1897 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1898 			if (match_user(NULL, NULL, NULL, arg) == -1)
1899 				fatal("%s line %d: invalid AllowUsers pattern: "
1900 				    "\"%.100s\"", filename, linenum, arg);
1901 			if (!*activep)
1902 				continue;
1903 			opt_array_append(filename, linenum, "AllowUsers",
1904 			    &options->allow_users, &options->num_allow_users,
1905 			    arg);
1906 		}
1907 		break;
1908 
1909 	case sDenyUsers:
1910 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1911 			if (match_user(NULL, NULL, NULL, arg) == -1)
1912 				fatal("%s line %d: invalid DenyUsers pattern: "
1913 				    "\"%.100s\"", filename, linenum, arg);
1914 			if (!*activep)
1915 				continue;
1916 			opt_array_append(filename, linenum, "DenyUsers",
1917 			    &options->deny_users, &options->num_deny_users,
1918 			    arg);
1919 		}
1920 		break;
1921 
1922 	case sAllowGroups:
1923 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1924 			if (!*activep)
1925 				continue;
1926 			opt_array_append(filename, linenum, "AllowGroups",
1927 			    &options->allow_groups, &options->num_allow_groups,
1928 			    arg);
1929 		}
1930 		break;
1931 
1932 	case sDenyGroups:
1933 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1934 			if (!*activep)
1935 				continue;
1936 			opt_array_append(filename, linenum, "DenyGroups",
1937 			    &options->deny_groups, &options->num_deny_groups,
1938 			    arg);
1939 		}
1940 		break;
1941 
1942 	case sCiphers:
1943 		arg = strdelim(&cp);
1944 		if (!arg || *arg == '\0')
1945 			fatal("%s line %d: Missing argument.", filename, linenum);
1946 		if (*arg != '-' &&
1947 		    !ciphers_valid(*arg == '+' || *arg == '^' ? arg + 1 : arg))
1948 			fatal("%s line %d: Bad SSH2 cipher spec '%s'.",
1949 			    filename, linenum, arg ? arg : "<NONE>");
1950 		if (options->ciphers == NULL)
1951 			options->ciphers = xstrdup(arg);
1952 		break;
1953 
1954 	case sMacs:
1955 		arg = strdelim(&cp);
1956 		if (!arg || *arg == '\0')
1957 			fatal("%s line %d: Missing argument.", filename, linenum);
1958 		if (*arg != '-' &&
1959 		    !mac_valid(*arg == '+' || *arg == '^' ? arg + 1 : arg))
1960 			fatal("%s line %d: Bad SSH2 mac spec '%s'.",
1961 			    filename, linenum, arg ? arg : "<NONE>");
1962 		if (options->macs == NULL)
1963 			options->macs = xstrdup(arg);
1964 		break;
1965 
1966 	case sKexAlgorithms:
1967 		arg = strdelim(&cp);
1968 		if (!arg || *arg == '\0')
1969 			fatal("%s line %d: Missing argument.",
1970 			    filename, linenum);
1971 		if (*arg != '-' &&
1972 		    !kex_names_valid(*arg == '+' || *arg == '^' ?
1973 		    arg + 1 : arg))
1974 			fatal("%s line %d: Bad SSH2 KexAlgorithms '%s'.",
1975 			    filename, linenum, arg ? arg : "<NONE>");
1976 		if (options->kex_algorithms == NULL)
1977 			options->kex_algorithms = xstrdup(arg);
1978 		break;
1979 
1980 	case sSubsystem:
1981 		if (options->num_subsystems >= MAX_SUBSYSTEMS) {
1982 			fatal("%s line %d: too many subsystems defined.",
1983 			    filename, linenum);
1984 		}
1985 		arg = strdelim(&cp);
1986 		if (!arg || *arg == '\0')
1987 			fatal("%s line %d: Missing subsystem name.",
1988 			    filename, linenum);
1989 		if (!*activep) {
1990 			arg = strdelim(&cp);
1991 			break;
1992 		}
1993 		for (i = 0; i < options->num_subsystems; i++)
1994 			if (strcmp(arg, options->subsystem_name[i]) == 0)
1995 				fatal("%s line %d: Subsystem '%s' already defined.",
1996 				    filename, linenum, arg);
1997 		options->subsystem_name[options->num_subsystems] = xstrdup(arg);
1998 		arg = strdelim(&cp);
1999 		if (!arg || *arg == '\0')
2000 			fatal("%s line %d: Missing subsystem command.",
2001 			    filename, linenum);
2002 		options->subsystem_command[options->num_subsystems] = xstrdup(arg);
2003 
2004 		/* Collect arguments (separate to executable) */
2005 		p = xstrdup(arg);
2006 		len = strlen(p) + 1;
2007 		while ((arg = strdelim(&cp)) != NULL && *arg != '\0') {
2008 			len += 1 + strlen(arg);
2009 			p = xreallocarray(p, 1, len);
2010 			strlcat(p, " ", len);
2011 			strlcat(p, arg, len);
2012 		}
2013 		options->subsystem_args[options->num_subsystems] = p;
2014 		options->num_subsystems++;
2015 		break;
2016 
2017 	case sMaxStartups:
2018 		arg = strdelim(&cp);
2019 		if (!arg || *arg == '\0')
2020 			fatal("%s line %d: Missing MaxStartups spec.",
2021 			    filename, linenum);
2022 		if ((n = sscanf(arg, "%d:%d:%d",
2023 		    &options->max_startups_begin,
2024 		    &options->max_startups_rate,
2025 		    &options->max_startups)) == 3) {
2026 			if (options->max_startups_begin >
2027 			    options->max_startups ||
2028 			    options->max_startups_rate > 100 ||
2029 			    options->max_startups_rate < 1)
2030 				fatal("%s line %d: Illegal MaxStartups spec.",
2031 				    filename, linenum);
2032 		} else if (n != 1)
2033 			fatal("%s line %d: Illegal MaxStartups spec.",
2034 			    filename, linenum);
2035 		else
2036 			options->max_startups = options->max_startups_begin;
2037 		break;
2038 
2039 	case sPerSourceNetBlockSize:
2040 		arg = strdelim(&cp);
2041 		if (!arg || *arg == '\0')
2042 			fatal("%s line %d: Missing PerSourceNetBlockSize spec.",
2043 			    filename, linenum);
2044 		switch (n = sscanf(arg, "%d:%d", &value, &value2)) {
2045 		case 2:
2046 			if (value2 < 0 || value2 > 128)
2047 				n = -1;
2048 			/* FALLTHROUGH */
2049 		case 1:
2050 			if (value < 0 || value > 32)
2051 				n = -1;
2052 		}
2053 		if (n != 1 && n != 2)
2054 			fatal("%s line %d: Invalid PerSourceNetBlockSize"
2055 			    " spec.", filename, linenum);
2056 		if (*activep) {
2057 			options->per_source_masklen_ipv4 = value;
2058 			options->per_source_masklen_ipv6 = value2;
2059 		}
2060 		break;
2061 
2062 	case sPerSourceMaxStartups:
2063 		arg = strdelim(&cp);
2064 		if (!arg || *arg == '\0')
2065 			fatal("%s line %d: Missing PerSourceMaxStartups spec.",
2066 			    filename, linenum);
2067 		if (strcmp(arg, "none") == 0) { /* no limit */
2068 			value = INT_MAX;
2069 		} else {
2070 			if ((errstr = atoi_err(arg, &value)) != NULL)
2071 				fatal("%s line %d: integer value %s.",
2072 				    filename, linenum, errstr);
2073 		}
2074 		if (*activep)
2075 			options->per_source_max_startups = value;
2076 		break;
2077 
2078 	case sMaxAuthTries:
2079 		intptr = &options->max_authtries;
2080 		goto parse_int;
2081 
2082 	case sMaxSessions:
2083 		intptr = &options->max_sessions;
2084 		goto parse_int;
2085 
2086 	case sBanner:
2087 		charptr = &options->banner;
2088 		goto parse_filename;
2089 
2090 	/*
2091 	 * These options can contain %X options expanded at
2092 	 * connect time, so that you can specify paths like:
2093 	 *
2094 	 * AuthorizedKeysFile	/etc/ssh_keys/%u
2095 	 */
2096 	case sAuthorizedKeysFile:
2097 		if (*activep && options->num_authkeys_files == 0) {
2098 			while ((arg = strdelim(&cp)) && *arg != '\0') {
2099 				arg = tilde_expand_filename(arg, getuid());
2100 				opt_array_append(filename, linenum,
2101 				    "AuthorizedKeysFile",
2102 				    &options->authorized_keys_files,
2103 				    &options->num_authkeys_files, arg);
2104 				free(arg);
2105 			}
2106 		}
2107 		return 0;
2108 
2109 	case sAuthorizedPrincipalsFile:
2110 		charptr = &options->authorized_principals_file;
2111 		arg = strdelim(&cp);
2112 		if (!arg || *arg == '\0')
2113 			fatal("%s line %d: missing file name.",
2114 			    filename, linenum);
2115 		if (*activep && *charptr == NULL) {
2116 			*charptr = tilde_expand_filename(arg, getuid());
2117 			/* increase optional counter */
2118 			if (intptr != NULL)
2119 				*intptr = *intptr + 1;
2120 		}
2121 		break;
2122 
2123 	case sClientAliveInterval:
2124 		intptr = &options->client_alive_interval;
2125 		goto parse_time;
2126 
2127 	case sClientAliveCountMax:
2128 		intptr = &options->client_alive_count_max;
2129 		goto parse_int;
2130 
2131 	case sAcceptEnv:
2132 		while ((arg = strdelim(&cp)) && *arg != '\0') {
2133 			if (strchr(arg, '=') != NULL)
2134 				fatal("%s line %d: Invalid environment name.",
2135 				    filename, linenum);
2136 			if (!*activep)
2137 				continue;
2138 			opt_array_append(filename, linenum, "AcceptEnv",
2139 			    &options->accept_env, &options->num_accept_env,
2140 			    arg);
2141 		}
2142 		break;
2143 
2144 	case sSetEnv:
2145 		uvalue = options->num_setenv;
2146 		while ((arg = strdelimw(&cp)) && *arg != '\0') {
2147 			if (strchr(arg, '=') == NULL)
2148 				fatal("%s line %d: Invalid environment.",
2149 				    filename, linenum);
2150 			if (!*activep || uvalue != 0)
2151 				continue;
2152 			opt_array_append(filename, linenum, "SetEnv",
2153 			    &options->setenv, &options->num_setenv, arg);
2154 		}
2155 		break;
2156 
2157 	case sPermitTunnel:
2158 		intptr = &options->permit_tun;
2159 		arg = strdelim(&cp);
2160 		if (!arg || *arg == '\0')
2161 			fatal("%s line %d: Missing yes/point-to-point/"
2162 			    "ethernet/no argument.", filename, linenum);
2163 		value = -1;
2164 		for (i = 0; tunmode_desc[i].val != -1; i++)
2165 			if (strcmp(tunmode_desc[i].text, arg) == 0) {
2166 				value = tunmode_desc[i].val;
2167 				break;
2168 			}
2169 		if (value == -1)
2170 			fatal("%s line %d: Bad yes/point-to-point/ethernet/"
2171 			    "no argument: %s", filename, linenum, arg);
2172 		if (*activep && *intptr == -1)
2173 			*intptr = value;
2174 		break;
2175 
2176 	case sInclude:
2177 		if (cmdline) {
2178 			fatal("Include directive not supported as a "
2179 			    "command-line option");
2180 		}
2181 		value = 0;
2182 		while ((arg2 = strdelim(&cp)) != NULL && *arg2 != '\0') {
2183 			value++;
2184 			found = 0;
2185 			if (*arg2 != '/' && *arg2 != '~') {
2186 				xasprintf(&arg, "%s/%s", SSHDIR, arg2);
2187 			} else
2188 				arg = xstrdup(arg2);
2189 
2190 			/*
2191 			 * Don't let included files clobber the containing
2192 			 * file's Match state.
2193 			 */
2194 			oactive = *activep;
2195 
2196 			/* consult cache of include files */
2197 			TAILQ_FOREACH(item, includes, entry) {
2198 				if (strcmp(item->selector, arg) != 0)
2199 					continue;
2200 				if (item->filename != NULL) {
2201 					parse_server_config_depth(options,
2202 					    item->filename, item->contents,
2203 					    includes, connectinfo,
2204 					    (*inc_flags & SSHCFG_MATCH_ONLY
2205 					        ? SSHCFG_MATCH_ONLY : (oactive
2206 					            ? 0 : SSHCFG_NEVERMATCH)),
2207 					    activep, depth + 1);
2208 				}
2209 				found = 1;
2210 				*activep = oactive;
2211 			}
2212 			if (found != 0) {
2213 				free(arg);
2214 				continue;
2215 			}
2216 
2217 			/* requested glob was not in cache */
2218 			debug2("%s line %d: new include %s",
2219 			    filename, linenum, arg);
2220 			if ((r = glob(arg, 0, NULL, &gbuf)) != 0) {
2221 				if (r != GLOB_NOMATCH) {
2222 					fatal("%s line %d: include \"%s\" "
2223 					    "glob failed", filename,
2224 					    linenum, arg);
2225 				}
2226 				/*
2227 				 * If no entry matched then record a
2228 				 * placeholder to skip later glob calls.
2229 				 */
2230 				debug2("%s line %d: no match for %s",
2231 				    filename, linenum, arg);
2232 				item = xcalloc(1, sizeof(*item));
2233 				item->selector = strdup(arg);
2234 				TAILQ_INSERT_TAIL(includes,
2235 				    item, entry);
2236 			}
2237 			if (gbuf.gl_pathc > INT_MAX)
2238 				fatal_f("too many glob results");
2239 			for (n = 0; n < (int)gbuf.gl_pathc; n++) {
2240 				debug2("%s line %d: including %s",
2241 				    filename, linenum, gbuf.gl_pathv[n]);
2242 				item = xcalloc(1, sizeof(*item));
2243 				item->selector = strdup(arg);
2244 				item->filename = strdup(gbuf.gl_pathv[n]);
2245 				if ((item->contents = sshbuf_new()) == NULL)
2246 					fatal_f("sshbuf_new failed");
2247 				load_server_config(item->filename,
2248 				    item->contents);
2249 				parse_server_config_depth(options,
2250 				    item->filename, item->contents,
2251 				    includes, connectinfo,
2252 				    (*inc_flags & SSHCFG_MATCH_ONLY
2253 				        ? SSHCFG_MATCH_ONLY : (oactive
2254 				            ? 0 : SSHCFG_NEVERMATCH)),
2255 				    activep, depth + 1);
2256 				*activep = oactive;
2257 				TAILQ_INSERT_TAIL(includes, item, entry);
2258 			}
2259 			globfree(&gbuf);
2260 			free(arg);
2261 		}
2262 		if (value == 0) {
2263 			fatal("%s line %d: Include missing filename argument",
2264 			    filename, linenum);
2265 		}
2266 		break;
2267 
2268 	case sMatch:
2269 		if (cmdline)
2270 			fatal("Match directive not supported as a command-line "
2271 			   "option");
2272 		value = match_cfg_line(&cp, linenum,
2273 		    (*inc_flags & SSHCFG_NEVERMATCH ? NULL : connectinfo));
2274 		if (value < 0)
2275 			fatal("%s line %d: Bad Match condition", filename,
2276 			    linenum);
2277 		*activep = (*inc_flags & SSHCFG_NEVERMATCH) ? 0 : value;
2278 		/* The MATCH_ONLY is applicable only until the first match block */
2279 		*inc_flags &= ~SSHCFG_MATCH_ONLY;
2280 		break;
2281 
2282 	case sPermitListen:
2283 	case sPermitOpen:
2284 		if (opcode == sPermitListen) {
2285 			uintptr = &options->num_permitted_listens;
2286 			chararrayptr = &options->permitted_listens;
2287 		} else {
2288 			uintptr = &options->num_permitted_opens;
2289 			chararrayptr = &options->permitted_opens;
2290 		}
2291 		arg = strdelim(&cp);
2292 		if (!arg || *arg == '\0')
2293 			fatal("%s line %d: missing %s specification",
2294 			    filename, linenum, lookup_opcode_name(opcode));
2295 		uvalue = *uintptr;	/* modified later */
2296 		if (strcmp(arg, "any") == 0 || strcmp(arg, "none") == 0) {
2297 			if (*activep && uvalue == 0) {
2298 				*uintptr = 1;
2299 				*chararrayptr = xcalloc(1,
2300 				    sizeof(**chararrayptr));
2301 				(*chararrayptr)[0] = xstrdup(arg);
2302 			}
2303 			break;
2304 		}
2305 		for (; arg != NULL && *arg != '\0'; arg = strdelim(&cp)) {
2306 			if (opcode == sPermitListen &&
2307 			    strchr(arg, ':') == NULL) {
2308 				/*
2309 				 * Allow bare port number for PermitListen
2310 				 * to indicate a wildcard listen host.
2311 				 */
2312 				xasprintf(&arg2, "*:%s", arg);
2313 			} else {
2314 				arg2 = xstrdup(arg);
2315 				ch = '\0';
2316 				p = hpdelim2(&arg, &ch);
2317 				if (p == NULL || ch == '/') {
2318 					fatal("%s line %d: missing host in %s",
2319 					    filename, linenum,
2320 					    lookup_opcode_name(opcode));
2321 				}
2322 				p = cleanhostname(p);
2323 			}
2324 			if (arg == NULL ||
2325 			    ((port = permitopen_port(arg)) < 0)) {
2326 				fatal("%s line %d: bad port number in %s",
2327 				    filename, linenum,
2328 				    lookup_opcode_name(opcode));
2329 			}
2330 			if (*activep && uvalue == 0) {
2331 				opt_array_append(filename, linenum,
2332 				    lookup_opcode_name(opcode),
2333 				    chararrayptr, uintptr, arg2);
2334 			}
2335 			free(arg2);
2336 		}
2337 		break;
2338 
2339 	case sForceCommand:
2340 		if (cp == NULL || *cp == '\0')
2341 			fatal("%.200s line %d: Missing argument.", filename,
2342 			    linenum);
2343 		len = strspn(cp, WHITESPACE);
2344 		if (*activep && options->adm_forced_command == NULL)
2345 			options->adm_forced_command = xstrdup(cp + len);
2346 		return 0;
2347 
2348 	case sChrootDirectory:
2349 		charptr = &options->chroot_directory;
2350 
2351 		arg = strdelim(&cp);
2352 		if (!arg || *arg == '\0')
2353 			fatal("%s line %d: missing file name.",
2354 			    filename, linenum);
2355 		if (*activep && *charptr == NULL)
2356 			*charptr = xstrdup(arg);
2357 		break;
2358 
2359 	case sTrustedUserCAKeys:
2360 		charptr = &options->trusted_user_ca_keys;
2361 		goto parse_filename;
2362 
2363 	case sRevokedKeys:
2364 		charptr = &options->revoked_keys_file;
2365 		goto parse_filename;
2366 
2367 	case sSecurityKeyProvider:
2368 		charptr = &options->sk_provider;
2369 		arg = strdelim(&cp);
2370 		if (!arg || *arg == '\0')
2371 			fatal("%s line %d: missing file name.",
2372 			    filename, linenum);
2373 		if (*activep && *charptr == NULL) {
2374 			*charptr = strcasecmp(arg, "internal") == 0 ?
2375 			    xstrdup(arg) : derelativise_path(arg);
2376 			/* increase optional counter */
2377 			if (intptr != NULL)
2378 				*intptr = *intptr + 1;
2379 		}
2380 		break;
2381 
2382 	case sIPQoS:
2383 		arg = strdelim(&cp);
2384 		if ((value = parse_ipqos(arg)) == -1)
2385 			fatal("%s line %d: Bad IPQoS value: %s",
2386 			    filename, linenum, arg);
2387 		arg = strdelim(&cp);
2388 		if (arg == NULL)
2389 			value2 = value;
2390 		else if ((value2 = parse_ipqos(arg)) == -1)
2391 			fatal("%s line %d: Bad IPQoS value: %s",
2392 			    filename, linenum, arg);
2393 		if (*activep) {
2394 			options->ip_qos_interactive = value;
2395 			options->ip_qos_bulk = value2;
2396 		}
2397 		break;
2398 
2399 	case sVersionAddendum:
2400 		if (cp == NULL || *cp == '\0')
2401 			fatal("%.200s line %d: Missing argument.", filename,
2402 			    linenum);
2403 		len = strspn(cp, WHITESPACE);
2404 		if (*activep && options->version_addendum == NULL) {
2405 			if (strcasecmp(cp + len, "none") == 0)
2406 				options->version_addendum = xstrdup("");
2407 			else if (strchr(cp + len, '\r') != NULL)
2408 				fatal("%.200s line %d: Invalid argument",
2409 				    filename, linenum);
2410 			else
2411 				options->version_addendum = xstrdup(cp + len);
2412 		}
2413 		return 0;
2414 
2415 	case sAuthorizedKeysCommand:
2416 		if (cp == NULL)
2417 			fatal("%.200s line %d: Missing argument.", filename,
2418 			    linenum);
2419 		len = strspn(cp, WHITESPACE);
2420 		if (*activep && options->authorized_keys_command == NULL) {
2421 			if (cp[len] != '/' && strcasecmp(cp + len, "none") != 0)
2422 				fatal("%.200s line %d: AuthorizedKeysCommand "
2423 				    "must be an absolute path",
2424 				    filename, linenum);
2425 			options->authorized_keys_command = xstrdup(cp + len);
2426 		}
2427 		return 0;
2428 
2429 	case sAuthorizedKeysCommandUser:
2430 		charptr = &options->authorized_keys_command_user;
2431 
2432 		arg = strdelim(&cp);
2433 		if (!arg || *arg == '\0')
2434 			fatal("%s line %d: missing AuthorizedKeysCommandUser "
2435 			    "argument.", filename, linenum);
2436 		if (*activep && *charptr == NULL)
2437 			*charptr = xstrdup(arg);
2438 		break;
2439 
2440 	case sAuthorizedPrincipalsCommand:
2441 		if (cp == NULL)
2442 			fatal("%.200s line %d: Missing argument.", filename,
2443 			    linenum);
2444 		len = strspn(cp, WHITESPACE);
2445 		if (*activep &&
2446 		    options->authorized_principals_command == NULL) {
2447 			if (cp[len] != '/' && strcasecmp(cp + len, "none") != 0)
2448 				fatal("%.200s line %d: "
2449 				    "AuthorizedPrincipalsCommand must be "
2450 				    "an absolute path", filename, linenum);
2451 			options->authorized_principals_command =
2452 			    xstrdup(cp + len);
2453 		}
2454 		return 0;
2455 
2456 	case sAuthorizedPrincipalsCommandUser:
2457 		charptr = &options->authorized_principals_command_user;
2458 
2459 		arg = strdelim(&cp);
2460 		if (!arg || *arg == '\0')
2461 			fatal("%s line %d: missing "
2462 			    "AuthorizedPrincipalsCommandUser argument.",
2463 			    filename, linenum);
2464 		if (*activep && *charptr == NULL)
2465 			*charptr = xstrdup(arg);
2466 		break;
2467 
2468 	case sAuthenticationMethods:
2469 		if (options->num_auth_methods == 0) {
2470 			value = 0; /* seen "any" pseudo-method */
2471 			value2 = 0; /* successfully parsed any method */
2472 			while ((arg = strdelim(&cp)) && *arg != '\0') {
2473 				if (strcmp(arg, "any") == 0) {
2474 					if (options->num_auth_methods > 0) {
2475 						fatal("%s line %d: \"any\" "
2476 						    "must appear alone in "
2477 						    "AuthenticationMethods",
2478 						    filename, linenum);
2479 					}
2480 					value = 1;
2481 				} else if (value) {
2482 					fatal("%s line %d: \"any\" must appear "
2483 					    "alone in AuthenticationMethods",
2484 					    filename, linenum);
2485 				} else if (auth2_methods_valid(arg, 0) != 0) {
2486 					fatal("%s line %d: invalid "
2487 					    "authentication method list.",
2488 					    filename, linenum);
2489 				}
2490 				value2 = 1;
2491 				if (!*activep)
2492 					continue;
2493 				opt_array_append(filename, linenum,
2494 				    "AuthenticationMethods",
2495 				    &options->auth_methods,
2496 				    &options->num_auth_methods, arg);
2497 			}
2498 			if (value2 == 0) {
2499 				fatal("%s line %d: no AuthenticationMethods "
2500 				    "specified", filename, linenum);
2501 			}
2502 		}
2503 		return 0;
2504 
2505 	case sStreamLocalBindMask:
2506 		arg = strdelim(&cp);
2507 		if (!arg || *arg == '\0')
2508 			fatal("%s line %d: missing StreamLocalBindMask "
2509 			    "argument.", filename, linenum);
2510 		/* Parse mode in octal format */
2511 		value = strtol(arg, &p, 8);
2512 		if (arg == p || value < 0 || value > 0777)
2513 			fatal("%s line %d: Bad mask.", filename, linenum);
2514 		if (*activep)
2515 			options->fwd_opts.streamlocal_bind_mask = (mode_t)value;
2516 		break;
2517 
2518 	case sStreamLocalBindUnlink:
2519 		intptr = &options->fwd_opts.streamlocal_bind_unlink;
2520 		goto parse_flag;
2521 
2522 	case sFingerprintHash:
2523 		arg = strdelim(&cp);
2524 		if (!arg || *arg == '\0')
2525 			fatal("%.200s line %d: Missing argument.",
2526 			    filename, linenum);
2527 		if ((value = ssh_digest_alg_by_name(arg)) == -1)
2528 			fatal("%.200s line %d: Invalid hash algorithm \"%s\".",
2529 			    filename, linenum, arg);
2530 		if (*activep)
2531 			options->fingerprint_hash = value;
2532 		break;
2533 
2534 	case sExposeAuthInfo:
2535 		intptr = &options->expose_userauth_info;
2536 		goto parse_flag;
2537 
2538 	case sRDomain:
2539 		charptr = &options->routing_domain;
2540 		arg = strdelim(&cp);
2541 		if (!arg || *arg == '\0')
2542 			fatal("%.200s line %d: Missing argument.",
2543 			    filename, linenum);
2544 		if (strcasecmp(arg, "none") != 0 && strcmp(arg, "%D") != 0 &&
2545 		    !valid_rdomain(arg))
2546 			fatal("%s line %d: bad routing domain",
2547 			    filename, linenum);
2548 		if (*activep && *charptr == NULL)
2549 			*charptr = xstrdup(arg);
2550 		break;
2551 
2552 	case sDeprecated:
2553 	case sIgnore:
2554 	case sUnsupported:
2555 		do_log2(opcode == sIgnore ?
2556 		    SYSLOG_LEVEL_DEBUG2 : SYSLOG_LEVEL_INFO,
2557 		    "%s line %d: %s option %s", filename, linenum,
2558 		    opcode == sUnsupported ? "Unsupported" : "Deprecated", arg);
2559 		while (arg)
2560 		    arg = strdelim(&cp);
2561 		break;
2562 
2563 #ifdef WITH_LDAP_PUBKEY
2564 	case sLdapPublickey:
2565 		intptr = &options->lpk.on;
2566 		goto parse_flag;
2567 	case sLdapServers:
2568 		/* arg = strdelim(&cp); */
2569 		p = line;
2570 		while(*p++);
2571 		arg = p;
2572 		if (!arg || *arg == '\0')
2573 		    fatal("%s line %d: missing ldap server",filename,linenum);
2574 		arg[strlen(arg)] = '\0';
2575 		if ((options->lpk.servers = ldap_parse_servers(arg)) == NULL)
2576 		    fatal("%s line %d: error in ldap servers", filename, linenum);
2577 		memset(arg,0,strlen(arg));
2578 		break;
2579 	case sLdapUserDN:
2580 		arg = cp;
2581 		if (!arg || *arg == '\0')
2582 		    fatal("%s line %d: missing ldap server",filename,linenum);
2583 		arg[strlen(arg)] = '\0';
2584 		options->lpk.u_basedn = xstrdup(arg);
2585 		memset(arg,0,strlen(arg));
2586 		break;
2587 	case sLdapGroupDN:
2588 		arg = cp;
2589 		if (!arg || *arg == '\0')
2590 		    fatal("%s line %d: missing ldap server",filename,linenum);
2591 		arg[strlen(arg)] = '\0';
2592 		options->lpk.g_basedn = xstrdup(arg);
2593 		memset(arg,0,strlen(arg));
2594 		break;
2595 	case sBindDN:
2596 		arg = cp;
2597 		if (!arg || *arg == '\0')
2598 		    fatal("%s line %d: missing binddn",filename,linenum);
2599 		arg[strlen(arg)] = '\0';
2600 		options->lpk.binddn = xstrdup(arg);
2601 		memset(arg,0,strlen(arg));
2602 		break;
2603 	case sBindPw:
2604 		arg = cp;
2605 		if (!arg || *arg == '\0')
2606 		    fatal("%s line %d: missing bindpw",filename,linenum);
2607 		arg[strlen(arg)] = '\0';
2608 		options->lpk.bindpw = xstrdup(arg);
2609 		memset(arg,0,strlen(arg));
2610 		break;
2611 	case sMyGroup:
2612 		arg = cp;
2613 		if (!arg || *arg == '\0')
2614 		    fatal("%s line %d: missing groupname",filename, linenum);
2615 		arg[strlen(arg)] = '\0';
2616 		options->lpk.sgroup = xstrdup(arg);
2617 		if (options->lpk.sgroup)
2618 		    options->lpk.fgroup = ldap_parse_groups(options->lpk.sgroup);
2619 		memset(arg,0,strlen(arg));
2620 		break;
2621 	case sLdapFilter:
2622 		arg = cp;
2623 		if (!arg || *arg == '\0')
2624 		    fatal("%s line %d: missing filter",filename, linenum);
2625 		arg[strlen(arg)] = '\0';
2626 		options->lpk.filter = xstrdup(arg);
2627 		memset(arg,0,strlen(arg));
2628 		break;
2629 	case sForceTLS:
2630 		intptr = &options->lpk.tls;
2631 		arg = strdelim(&cp);
2632 		if (!arg || *arg == '\0')
2633 			fatal("%s line %d: missing yes/no argument.",
2634 			    filename, linenum);
2635 		value = 0;	/* silence compiler */
2636 		if (strcmp(arg, "yes") == 0)
2637 			value = 1;
2638 		else if (strcmp(arg, "no") == 0)
2639 			value = 0;
2640 		else if (strcmp(arg, "try") == 0)
2641 			value = -1;
2642 		else
2643 			fatal("%s line %d: Bad yes/no argument: %s",
2644 				filename, linenum, arg);
2645 		if (*intptr == -1)
2646 			*intptr = value;
2647 		break;
2648 	case sBindTimeout:
2649 		timetptr = &options->lpk.b_timeout.tv_sec;
2650 parse_ulong:
2651 		arg = strdelim(&cp);
2652 		if (!arg || *arg == '\0')
2653 			fatal("%s line %d: missing integer value.",
2654 			    filename, linenum);
2655 		lvalue = atol(arg);
2656 		if (*activep && *timetptr == -1)
2657 			*timetptr = lvalue;
2658 		break;
2659 
2660 	case sSearchTimeout:
2661 		timetptr = &options->lpk.s_timeout.tv_sec;
2662 		goto parse_ulong;
2663 		break;
2664 	case sLdapConf:
2665 		arg = cp;
2666 		if (!arg || *arg == '\0')
2667 		    fatal("%s line %d: missing LpkLdapConf", filename, linenum);
2668 		arg[strlen(arg)] = '\0';
2669 		options->lpk.l_conf = xstrdup(arg);
2670 		memset(arg, 0, strlen(arg));
2671 		break;
2672 	case sLpkPubKeyAttr:
2673 		arg = cp;
2674                 if (!arg || *arg == '\0')
2675                     fatal("%s line %d: missing pubkeyattr",filename,linenum);
2676                 arg[strlen(arg)] = '\0';
2677                 options->lpk.pub_key_attr = xstrdup(arg);
2678                 memset(arg,0,strlen(arg));
2679                 break;
2680 
2681 #endif
2682 
2683 	default:
2684 		fatal("%s line %d: Missing handler for opcode %s (%d)",
2685 		    filename, linenum, arg, opcode);
2686 	}
2687 	if ((arg = strdelim(&cp)) != NULL && *arg != '\0')
2688 		fatal("%s line %d: garbage at end of line; \"%.200s\".",
2689 		    filename, linenum, arg);
2690 	return 0;
2691 }
2692 
2693 int
2694 process_server_config_line(ServerOptions *options, char *line,
2695     const char *filename, int linenum, int *activep,
2696     struct connection_info *connectinfo, struct include_list *includes)
2697 {
2698 	int inc_flags = 0;
2699 
2700 	return process_server_config_line_depth(options, line, filename,
2701 	    linenum, activep, connectinfo, &inc_flags, 0, includes);
2702 }
2703 
2704 
2705 /* Reads the server configuration file. */
2706 
2707 void
2708 load_server_config(const char *filename, struct sshbuf *conf)
2709 {
2710 	struct stat st;
2711 	char *line = NULL, *cp;
2712 	size_t linesize = 0;
2713 	FILE *f;
2714 	int r, lineno = 0;
2715 
2716 	debug2_f("filename %s", filename);
2717 	if ((f = fopen(filename, "r")) == NULL) {
2718 		perror(filename);
2719 		exit(1);
2720 	}
2721 	sshbuf_reset(conf);
2722 	/* grow buffer, so realloc is avoided for large config files */
2723 	if (fstat(fileno(f), &st) == 0 && st.st_size > 0 &&
2724             (r = sshbuf_allocate(conf, st.st_size)) != 0)
2725 		fatal_fr(r, "allocate");
2726 	while (getline(&line, &linesize, f) != -1) {
2727 		lineno++;
2728 		/*
2729 		 * Trim out comments and strip whitespace
2730 		 * NB - preserve newlines, they are needed to reproduce
2731 		 * line numbers later for error messages
2732 		 */
2733 		if ((cp = strchr(line, '#')) != NULL)
2734 			memcpy(cp, "\n", 2);
2735 		cp = line + strspn(line, " \t\r");
2736 		if ((r = sshbuf_put(conf, cp, strlen(cp))) != 0)
2737 			fatal_fr(r, "sshbuf_put");
2738 	}
2739 	free(line);
2740 	if ((r = sshbuf_put_u8(conf, 0)) != 0)
2741 		fatal_fr(r, "sshbuf_put_u8");
2742 	fclose(f);
2743 	debug2_f("done config len = %zu", sshbuf_len(conf));
2744 }
2745 
2746 void
2747 parse_server_match_config(ServerOptions *options,
2748    struct include_list *includes, struct connection_info *connectinfo)
2749 {
2750 	ServerOptions mo;
2751 
2752 	initialize_server_options(&mo);
2753 	parse_server_config(&mo, "reprocess config", cfg, includes,
2754 	    connectinfo);
2755 	copy_set_server_options(options, &mo, 0);
2756 }
2757 
2758 int parse_server_match_testspec(struct connection_info *ci, char *spec)
2759 {
2760 	char *p;
2761 
2762 	while ((p = strsep(&spec, ",")) && *p != '\0') {
2763 		if (strncmp(p, "addr=", 5) == 0) {
2764 			ci->address = xstrdup(p + 5);
2765 		} else if (strncmp(p, "host=", 5) == 0) {
2766 			ci->host = xstrdup(p + 5);
2767 		} else if (strncmp(p, "user=", 5) == 0) {
2768 			ci->user = xstrdup(p + 5);
2769 		} else if (strncmp(p, "laddr=", 6) == 0) {
2770 			ci->laddress = xstrdup(p + 6);
2771 		} else if (strncmp(p, "rdomain=", 8) == 0) {
2772 			ci->rdomain = xstrdup(p + 8);
2773 		} else if (strncmp(p, "lport=", 6) == 0) {
2774 			ci->lport = a2port(p + 6);
2775 			if (ci->lport == -1) {
2776 				fprintf(stderr, "Invalid port '%s' in test mode"
2777 				   " specification %s\n", p+6, p);
2778 				return -1;
2779 			}
2780 		} else {
2781 			fprintf(stderr, "Invalid test mode specification %s\n",
2782 			   p);
2783 			return -1;
2784 		}
2785 	}
2786 	return 0;
2787 }
2788 
2789 /*
2790  * Copy any supported values that are set.
2791  *
2792  * If the preauth flag is set, we do not bother copying the string or
2793  * array values that are not used pre-authentication, because any that we
2794  * do use must be explicitly sent in mm_getpwnamallow().
2795  */
2796 void
2797 copy_set_server_options(ServerOptions *dst, ServerOptions *src, int preauth)
2798 {
2799 #define M_CP_INTOPT(n) do {\
2800 	if (src->n != -1) \
2801 		dst->n = src->n; \
2802 } while (0)
2803 
2804 	M_CP_INTOPT(password_authentication);
2805 	M_CP_INTOPT(gss_authentication);
2806 	M_CP_INTOPT(pubkey_authentication);
2807 	M_CP_INTOPT(pubkey_auth_options);
2808 	M_CP_INTOPT(kerberos_authentication);
2809 	M_CP_INTOPT(hostbased_authentication);
2810 	M_CP_INTOPT(hostbased_uses_name_from_packet_only);
2811 	M_CP_INTOPT(kbd_interactive_authentication);
2812 	M_CP_INTOPT(permit_root_login);
2813 	M_CP_INTOPT(permit_empty_passwd);
2814 	M_CP_INTOPT(ignore_rhosts);
2815 
2816 	M_CP_INTOPT(allow_tcp_forwarding);
2817 	M_CP_INTOPT(allow_streamlocal_forwarding);
2818 	M_CP_INTOPT(allow_agent_forwarding);
2819 	M_CP_INTOPT(disable_forwarding);
2820 	M_CP_INTOPT(expose_userauth_info);
2821 	M_CP_INTOPT(permit_tun);
2822 	M_CP_INTOPT(fwd_opts.gateway_ports);
2823 	M_CP_INTOPT(fwd_opts.streamlocal_bind_unlink);
2824 	M_CP_INTOPT(x11_display_offset);
2825 	M_CP_INTOPT(x11_forwarding);
2826 	M_CP_INTOPT(x11_use_localhost);
2827 	M_CP_INTOPT(permit_tty);
2828 	M_CP_INTOPT(permit_user_rc);
2829 	M_CP_INTOPT(max_sessions);
2830 	M_CP_INTOPT(max_authtries);
2831 	M_CP_INTOPT(client_alive_count_max);
2832 	M_CP_INTOPT(client_alive_interval);
2833 	M_CP_INTOPT(ip_qos_interactive);
2834 	M_CP_INTOPT(ip_qos_bulk);
2835 	M_CP_INTOPT(rekey_limit);
2836 	M_CP_INTOPT(rekey_interval);
2837 	M_CP_INTOPT(log_level);
2838 
2839 	/*
2840 	 * The bind_mask is a mode_t that may be unsigned, so we can't use
2841 	 * M_CP_INTOPT - it does a signed comparison that causes compiler
2842 	 * warnings.
2843 	 */
2844 	if (src->fwd_opts.streamlocal_bind_mask != (mode_t)-1) {
2845 		dst->fwd_opts.streamlocal_bind_mask =
2846 		    src->fwd_opts.streamlocal_bind_mask;
2847 	}
2848 
2849 	/* M_CP_STROPT and M_CP_STRARRAYOPT should not appear before here */
2850 #define M_CP_STROPT(n) do {\
2851 	if (src->n != NULL && dst->n != src->n) { \
2852 		free(dst->n); \
2853 		dst->n = src->n; \
2854 	} \
2855 } while(0)
2856 #define M_CP_STRARRAYOPT(s, num_s) do {\
2857 	u_int i; \
2858 	if (src->num_s != 0) { \
2859 		for (i = 0; i < dst->num_s; i++) \
2860 			free(dst->s[i]); \
2861 		free(dst->s); \
2862 		dst->s = xcalloc(src->num_s, sizeof(*dst->s)); \
2863 		for (i = 0; i < src->num_s; i++) \
2864 			dst->s[i] = xstrdup(src->s[i]); \
2865 		dst->num_s = src->num_s; \
2866 	} \
2867 } while(0)
2868 
2869 	/* See comment in servconf.h */
2870 	COPY_MATCH_STRING_OPTS();
2871 
2872 	/* Arguments that accept '+...' need to be expanded */
2873 	assemble_algorithms(dst);
2874 
2875 	/*
2876 	 * The only things that should be below this point are string options
2877 	 * which are only used after authentication.
2878 	 */
2879 	if (preauth)
2880 		return;
2881 
2882 	/* These options may be "none" to clear a global setting */
2883 	M_CP_STROPT(adm_forced_command);
2884 	if (option_clear_or_none(dst->adm_forced_command)) {
2885 		free(dst->adm_forced_command);
2886 		dst->adm_forced_command = NULL;
2887 	}
2888 	M_CP_STROPT(chroot_directory);
2889 	if (option_clear_or_none(dst->chroot_directory)) {
2890 		free(dst->chroot_directory);
2891 		dst->chroot_directory = NULL;
2892 	}
2893 }
2894 
2895 #undef M_CP_INTOPT
2896 #undef M_CP_STROPT
2897 #undef M_CP_STRARRAYOPT
2898 
2899 #define SERVCONF_MAX_DEPTH	16
2900 static void
2901 parse_server_config_depth(ServerOptions *options, const char *filename,
2902     struct sshbuf *conf, struct include_list *includes,
2903     struct connection_info *connectinfo, int flags, int *activep, int depth)
2904 {
2905 	int linenum, bad_options = 0;
2906 	char *cp, *obuf, *cbuf;
2907 
2908 	if (depth < 0 || depth > SERVCONF_MAX_DEPTH)
2909 		fatal("Too many recursive configuration includes");
2910 
2911 	debug2_f("config %s len %zu%s", filename, sshbuf_len(conf),
2912 	    (flags & SSHCFG_NEVERMATCH ? " [checking syntax only]" : ""));
2913 
2914 	if ((obuf = cbuf = sshbuf_dup_string(conf)) == NULL)
2915 		fatal_f("sshbuf_dup_string failed");
2916 	linenum = 1;
2917 	while ((cp = strsep(&cbuf, "\n")) != NULL) {
2918 		if (process_server_config_line_depth(options, cp,
2919 		    filename, linenum++, activep, connectinfo, &flags,
2920 		    depth, includes) != 0)
2921 			bad_options++;
2922 	}
2923 	free(obuf);
2924 	if (bad_options > 0)
2925 		fatal("%s: terminating, %d bad configuration options",
2926 		    filename, bad_options);
2927 }
2928 
2929 void
2930 parse_server_config(ServerOptions *options, const char *filename,
2931     struct sshbuf *conf, struct include_list *includes,
2932     struct connection_info *connectinfo)
2933 {
2934 	int active = connectinfo ? 0 : 1;
2935 	parse_server_config_depth(options, filename, conf, includes,
2936 	    connectinfo, (connectinfo ? SSHCFG_MATCH_ONLY : 0), &active, 0);
2937 	process_queued_listen_addrs(options);
2938 }
2939 
2940 static const char *
2941 fmt_multistate_int(int val, const struct multistate *m)
2942 {
2943 	u_int i;
2944 
2945 	for (i = 0; m[i].key != NULL; i++) {
2946 		if (m[i].value == val)
2947 			return m[i].key;
2948 	}
2949 	return "UNKNOWN";
2950 }
2951 
2952 static const char *
2953 fmt_intarg(ServerOpCodes code, int val)
2954 {
2955 	if (val == -1)
2956 		return "unset";
2957 	switch (code) {
2958 	case sAddressFamily:
2959 		return fmt_multistate_int(val, multistate_addressfamily);
2960 	case sPermitRootLogin:
2961 		return fmt_multistate_int(val, multistate_permitrootlogin);
2962 	case sGatewayPorts:
2963 		return fmt_multistate_int(val, multistate_gatewayports);
2964 	case sCompression:
2965 		return fmt_multistate_int(val, multistate_compression);
2966 	case sAllowTcpForwarding:
2967 		return fmt_multistate_int(val, multistate_tcpfwd);
2968 	case sAllowStreamLocalForwarding:
2969 		return fmt_multistate_int(val, multistate_tcpfwd);
2970 	case sIgnoreRhosts:
2971 		return fmt_multistate_int(val, multistate_ignore_rhosts);
2972 	case sFingerprintHash:
2973 		return ssh_digest_alg_name(val);
2974 	default:
2975 		switch (val) {
2976 		case 0:
2977 			return "no";
2978 		case 1:
2979 			return "yes";
2980 		default:
2981 			return "UNKNOWN";
2982 		}
2983 	}
2984 }
2985 
2986 static void
2987 dump_cfg_int(ServerOpCodes code, int val)
2988 {
2989 	printf("%s %d\n", lookup_opcode_name(code), val);
2990 }
2991 
2992 static void
2993 dump_cfg_oct(ServerOpCodes code, int val)
2994 {
2995 	printf("%s 0%o\n", lookup_opcode_name(code), val);
2996 }
2997 
2998 static void
2999 dump_cfg_fmtint(ServerOpCodes code, int val)
3000 {
3001 	printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
3002 }
3003 
3004 static void
3005 dump_cfg_string(ServerOpCodes code, const char *val)
3006 {
3007 	printf("%s %s\n", lookup_opcode_name(code),
3008 	    val == NULL ? "none" : val);
3009 }
3010 
3011 static void
3012 dump_cfg_strarray(ServerOpCodes code, u_int count, char **vals)
3013 {
3014 	u_int i;
3015 
3016 	for (i = 0; i < count; i++)
3017 		printf("%s %s\n", lookup_opcode_name(code), vals[i]);
3018 }
3019 
3020 static void
3021 dump_cfg_strarray_oneline(ServerOpCodes code, u_int count, char **vals)
3022 {
3023 	u_int i;
3024 
3025 	if (count <= 0 && code != sAuthenticationMethods)
3026 		return;
3027 	printf("%s", lookup_opcode_name(code));
3028 	for (i = 0; i < count; i++)
3029 		printf(" %s",  vals[i]);
3030 	if (code == sAuthenticationMethods && count == 0)
3031 		printf(" any");
3032 	printf("\n");
3033 }
3034 
3035 static char *
3036 format_listen_addrs(struct listenaddr *la)
3037 {
3038 	int r;
3039 	struct addrinfo *ai;
3040 	char addr[NI_MAXHOST], port[NI_MAXSERV];
3041 	char *laddr1 = xstrdup(""), *laddr2 = NULL;
3042 
3043 	/*
3044 	 * ListenAddress must be after Port.  add_one_listen_addr pushes
3045 	 * addresses onto a stack, so to maintain ordering we need to
3046 	 * print these in reverse order.
3047 	 */
3048 	for (ai = la->addrs; ai; ai = ai->ai_next) {
3049 		if ((r = getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
3050 		    sizeof(addr), port, sizeof(port),
3051 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
3052 			error("getnameinfo: %.100s", ssh_gai_strerror(r));
3053 			continue;
3054 		}
3055 		laddr2 = laddr1;
3056 		if (ai->ai_family == AF_INET6) {
3057 			xasprintf(&laddr1, "listenaddress [%s]:%s%s%s\n%s",
3058 			    addr, port,
3059 			    la->rdomain == NULL ? "" : " rdomain ",
3060 			    la->rdomain == NULL ? "" : la->rdomain,
3061 			    laddr2);
3062 		} else {
3063 			xasprintf(&laddr1, "listenaddress %s:%s%s%s\n%s",
3064 			    addr, port,
3065 			    la->rdomain == NULL ? "" : " rdomain ",
3066 			    la->rdomain == NULL ? "" : la->rdomain,
3067 			    laddr2);
3068 		}
3069 		free(laddr2);
3070 	}
3071 	return laddr1;
3072 }
3073 
3074 void
3075 dump_config(ServerOptions *o)
3076 {
3077 	const char *s;
3078 	u_int i;
3079 
3080 	/* these are usually at the top of the config */
3081 	for (i = 0; i < o->num_ports; i++)
3082 		printf("port %d\n", o->ports[i]);
3083 	dump_cfg_fmtint(sAddressFamily, o->address_family);
3084 
3085 	for (i = 0; i < o->num_listen_addrs; i++) {
3086 		char *ss = format_listen_addrs(&o->listen_addrs[i]);
3087 		printf("%s", ss);
3088 		free(ss);
3089 	}
3090 
3091 	/* integer arguments */
3092 	dump_cfg_int(sLoginGraceTime, o->login_grace_time);
3093 	dump_cfg_int(sX11DisplayOffset, o->x11_display_offset);
3094 	dump_cfg_int(sMaxAuthTries, o->max_authtries);
3095 	dump_cfg_int(sMaxSessions, o->max_sessions);
3096 	dump_cfg_int(sClientAliveInterval, o->client_alive_interval);
3097 	dump_cfg_int(sClientAliveCountMax, o->client_alive_count_max);
3098 	dump_cfg_oct(sStreamLocalBindMask, o->fwd_opts.streamlocal_bind_mask);
3099 
3100 	/* formatted integer arguments */
3101 	dump_cfg_fmtint(sPermitRootLogin, o->permit_root_login);
3102 	dump_cfg_fmtint(sIgnoreRhosts, o->ignore_rhosts);
3103 	dump_cfg_fmtint(sIgnoreUserKnownHosts, o->ignore_user_known_hosts);
3104 	dump_cfg_fmtint(sHostbasedAuthentication, o->hostbased_authentication);
3105 	dump_cfg_fmtint(sHostbasedUsesNameFromPacketOnly,
3106 	    o->hostbased_uses_name_from_packet_only);
3107 	dump_cfg_fmtint(sPubkeyAuthentication, o->pubkey_authentication);
3108 #ifdef KRB5
3109 	dump_cfg_fmtint(sKerberosAuthentication, o->kerberos_authentication);
3110 	dump_cfg_fmtint(sKerberosOrLocalPasswd, o->kerberos_or_local_passwd);
3111 	dump_cfg_fmtint(sKerberosTicketCleanup, o->kerberos_ticket_cleanup);
3112 	dump_cfg_fmtint(sKerberosGetAFSToken, o->kerberos_get_afs_token);
3113 #endif
3114 #ifdef GSSAPI
3115 	dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
3116 	dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
3117 #endif
3118 	dump_cfg_fmtint(sPasswordAuthentication, o->password_authentication);
3119 	dump_cfg_fmtint(sKbdInteractiveAuthentication,
3120 	    o->kbd_interactive_authentication);
3121 	dump_cfg_fmtint(sChallengeResponseAuthentication,
3122 	    o->challenge_response_authentication);
3123 	dump_cfg_fmtint(sPrintMotd, o->print_motd);
3124 	dump_cfg_fmtint(sPrintLastLog, o->print_lastlog);
3125 	dump_cfg_fmtint(sX11Forwarding, o->x11_forwarding);
3126 	dump_cfg_fmtint(sX11UseLocalhost, o->x11_use_localhost);
3127 	dump_cfg_fmtint(sPermitTTY, o->permit_tty);
3128 	dump_cfg_fmtint(sPermitUserRC, o->permit_user_rc);
3129 	dump_cfg_fmtint(sStrictModes, o->strict_modes);
3130 	dump_cfg_fmtint(sTCPKeepAlive, o->tcp_keep_alive);
3131 	dump_cfg_fmtint(sEmptyPasswd, o->permit_empty_passwd);
3132 	dump_cfg_fmtint(sCompression, o->compression);
3133 	dump_cfg_fmtint(sGatewayPorts, o->fwd_opts.gateway_ports);
3134 	dump_cfg_fmtint(sUseDNS, o->use_dns);
3135 	dump_cfg_fmtint(sAllowTcpForwarding, o->allow_tcp_forwarding);
3136 	dump_cfg_fmtint(sAllowAgentForwarding, o->allow_agent_forwarding);
3137 	dump_cfg_fmtint(sDisableForwarding, o->disable_forwarding);
3138 	dump_cfg_fmtint(sAllowStreamLocalForwarding, o->allow_streamlocal_forwarding);
3139 	dump_cfg_fmtint(sStreamLocalBindUnlink, o->fwd_opts.streamlocal_bind_unlink);
3140 	dump_cfg_fmtint(sFingerprintHash, o->fingerprint_hash);
3141 	dump_cfg_fmtint(sExposeAuthInfo, o->expose_userauth_info);
3142 
3143 	/* string arguments */
3144 	dump_cfg_string(sPidFile, o->pid_file);
3145 	dump_cfg_string(sXAuthLocation, o->xauth_location);
3146 	dump_cfg_string(sCiphers, o->ciphers);
3147 	dump_cfg_string(sMacs, o->macs);
3148 	dump_cfg_string(sBanner, o->banner);
3149 	dump_cfg_string(sForceCommand, o->adm_forced_command);
3150 	dump_cfg_string(sChrootDirectory, o->chroot_directory);
3151 	dump_cfg_string(sTrustedUserCAKeys, o->trusted_user_ca_keys);
3152 	dump_cfg_string(sRevokedKeys, o->revoked_keys_file);
3153 	dump_cfg_string(sSecurityKeyProvider, o->sk_provider);
3154 	dump_cfg_string(sAuthorizedPrincipalsFile,
3155 	    o->authorized_principals_file);
3156 	dump_cfg_string(sVersionAddendum, *o->version_addendum == '\0'
3157 	    ? "none" : o->version_addendum);
3158 	dump_cfg_string(sAuthorizedKeysCommand, o->authorized_keys_command);
3159 	dump_cfg_string(sAuthorizedKeysCommandUser, o->authorized_keys_command_user);
3160 	dump_cfg_string(sAuthorizedPrincipalsCommand, o->authorized_principals_command);
3161 	dump_cfg_string(sAuthorizedPrincipalsCommandUser, o->authorized_principals_command_user);
3162 	dump_cfg_string(sHostKeyAgent, o->host_key_agent);
3163 	dump_cfg_string(sKexAlgorithms, o->kex_algorithms);
3164 	dump_cfg_string(sCASignatureAlgorithms, o->ca_sign_algorithms);
3165 	dump_cfg_string(sHostbasedAcceptedAlgorithms, o->hostbased_accepted_algos);
3166 	dump_cfg_string(sHostKeyAlgorithms, o->hostkeyalgorithms);
3167 	dump_cfg_string(sPubkeyAcceptedAlgorithms, o->pubkey_accepted_algos);
3168 	dump_cfg_string(sRDomain, o->routing_domain);
3169 
3170 	/* string arguments requiring a lookup */
3171 	dump_cfg_string(sLogLevel, log_level_name(o->log_level));
3172 	dump_cfg_string(sLogFacility, log_facility_name(o->log_facility));
3173 
3174 	/* string array arguments */
3175 	dump_cfg_strarray_oneline(sAuthorizedKeysFile, o->num_authkeys_files,
3176 	    o->authorized_keys_files);
3177 	dump_cfg_strarray(sHostKeyFile, o->num_host_key_files,
3178 	     o->host_key_files);
3179 	dump_cfg_strarray(sHostCertificate, o->num_host_cert_files,
3180 	     o->host_cert_files);
3181 	dump_cfg_strarray(sAllowUsers, o->num_allow_users, o->allow_users);
3182 	dump_cfg_strarray(sDenyUsers, o->num_deny_users, o->deny_users);
3183 	dump_cfg_strarray(sAllowGroups, o->num_allow_groups, o->allow_groups);
3184 	dump_cfg_strarray(sDenyGroups, o->num_deny_groups, o->deny_groups);
3185 	dump_cfg_strarray(sAcceptEnv, o->num_accept_env, o->accept_env);
3186 	dump_cfg_strarray(sSetEnv, o->num_setenv, o->setenv);
3187 	dump_cfg_strarray_oneline(sAuthenticationMethods,
3188 	    o->num_auth_methods, o->auth_methods);
3189 	dump_cfg_strarray_oneline(sLogVerbose,
3190 	    o->num_log_verbose, o->log_verbose);
3191 
3192 	/* other arguments */
3193 	for (i = 0; i < o->num_subsystems; i++)
3194 		printf("subsystem %s %s\n", o->subsystem_name[i],
3195 		    o->subsystem_args[i]);
3196 
3197 	printf("maxstartups %d:%d:%d\n", o->max_startups_begin,
3198 	    o->max_startups_rate, o->max_startups);
3199 	printf("persourcemaxstartups ");
3200 	if (o->per_source_max_startups == INT_MAX)
3201 		printf("none\n");
3202 	else
3203 		printf("%d\n", o->per_source_max_startups);
3204 	printf("persourcenetblocksize %d:%d\n", o->per_source_masklen_ipv4,
3205 	    o->per_source_masklen_ipv6);
3206 
3207 	s = NULL;
3208 	for (i = 0; tunmode_desc[i].val != -1; i++) {
3209 		if (tunmode_desc[i].val == o->permit_tun) {
3210 			s = tunmode_desc[i].text;
3211 			break;
3212 		}
3213 	}
3214 	dump_cfg_string(sPermitTunnel, s);
3215 
3216 	printf("ipqos %s ", iptos2str(o->ip_qos_interactive));
3217 	printf("%s\n", iptos2str(o->ip_qos_bulk));
3218 
3219 	printf("rekeylimit %llu %d\n", (unsigned long long)o->rekey_limit,
3220 	    o->rekey_interval);
3221 
3222 	printf("permitopen");
3223 	if (o->num_permitted_opens == 0)
3224 		printf(" any");
3225 	else {
3226 		for (i = 0; i < o->num_permitted_opens; i++)
3227 			printf(" %s", o->permitted_opens[i]);
3228 	}
3229 	printf("\n");
3230 	printf("permitlisten");
3231 	if (o->num_permitted_listens == 0)
3232 		printf(" any");
3233 	else {
3234 		for (i = 0; i < o->num_permitted_listens; i++)
3235 			printf(" %s", o->permitted_listens[i]);
3236 	}
3237 	printf("\n");
3238 
3239 	if (o->permit_user_env_allowlist == NULL) {
3240 		dump_cfg_fmtint(sPermitUserEnvironment, o->permit_user_env);
3241 	} else {
3242 		printf("permituserenvironment %s\n",
3243 		    o->permit_user_env_allowlist);
3244 	}
3245 
3246 	printf("pubkeyauthoptions");
3247 	if (o->pubkey_auth_options == 0)
3248 		printf(" none");
3249 	if (o->pubkey_auth_options & PUBKEYAUTH_TOUCH_REQUIRED)
3250 		printf(" touch-required");
3251 	if (o->pubkey_auth_options & PUBKEYAUTH_VERIFY_REQUIRED)
3252 		printf(" verify-required");
3253 	printf("\n");
3254 }
3255