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