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