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