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