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