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