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