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