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