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