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