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