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