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