xref: /dragonfly/crypto/openssh/servconf.c (revision 73e0051e)
1 /* $OpenBSD: servconf.c,v 1.194 2009/01/22 10:02:34 djm Exp $ */
2 /*
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  *
6  * As far as I am concerned, the code I have written for this software
7  * can be used freely for any purpose.  Any derived versions of this
8  * software must be clearly marked as such, and if the derived work is
9  * incompatible with the protocol description in the RFC file, it must be
10  * called by a name other than "ssh" or "Secure Shell".
11  */
12 
13 #include "includes.h"
14 
15 #include <sys/types.h>
16 #include <sys/socket.h>
17 
18 #include <netdb.h>
19 #include <pwd.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <signal.h>
24 #include <unistd.h>
25 #include <stdarg.h>
26 #include <errno.h>
27 
28 #include "openbsd-compat/sys-queue.h"
29 #include "xmalloc.h"
30 #include "ssh.h"
31 #include "log.h"
32 #include "buffer.h"
33 #include "servconf.h"
34 #include "compat.h"
35 #include "pathnames.h"
36 #include "misc.h"
37 #include "cipher.h"
38 #include "key.h"
39 #include "kex.h"
40 #include "mac.h"
41 #include "match.h"
42 #include "channels.h"
43 #include "groupaccess.h"
44 
45 static void add_listen_addr(ServerOptions *, char *, int);
46 static void add_one_listen_addr(ServerOptions *, char *, int);
47 
48 /* Use of privilege separation or not */
49 extern int use_privsep;
50 extern Buffer cfg;
51 
52 /* Initializes the server options to their default values. */
53 
54 void
55 initialize_server_options(ServerOptions *options)
56 {
57 	memset(options, 0, sizeof(*options));
58 
59 	/* Portable-specific options */
60 	options->use_pam = -1;
61 
62 	/* Standard Options */
63 	options->num_ports = 0;
64 	options->ports_from_cmdline = 0;
65 	options->listen_addrs = NULL;
66 	options->address_family = -1;
67 	options->num_host_key_files = 0;
68 	options->pid_file = NULL;
69 	options->server_key_bits = -1;
70 	options->login_grace_time = -1;
71 	options->key_regeneration_time = -1;
72 	options->permit_root_login = PERMIT_NOT_SET;
73 	options->ignore_rhosts = -1;
74 	options->ignore_user_known_hosts = -1;
75 	options->print_motd = -1;
76 	options->print_lastlog = -1;
77 	options->x11_forwarding = -1;
78 	options->x11_display_offset = -1;
79 	options->x11_use_localhost = -1;
80 	options->xauth_location = NULL;
81 	options->strict_modes = -1;
82 	options->tcp_keep_alive = -1;
83 	options->log_facility = SYSLOG_FACILITY_NOT_SET;
84 	options->log_level = SYSLOG_LEVEL_NOT_SET;
85 	options->rhosts_rsa_authentication = -1;
86 	options->hostbased_authentication = -1;
87 	options->hostbased_uses_name_from_packet_only = -1;
88 	options->rsa_authentication = -1;
89 	options->pubkey_authentication = -1;
90 	options->kerberos_authentication = -1;
91 	options->kerberos_or_local_passwd = -1;
92 	options->kerberos_ticket_cleanup = -1;
93 	options->kerberos_get_afs_token = -1;
94 	options->gss_authentication=-1;
95 	options->gss_cleanup_creds = -1;
96 	options->password_authentication = -1;
97 	options->kbd_interactive_authentication = -1;
98 	options->challenge_response_authentication = -1;
99 	options->permit_blacklisted_keys = -1;
100 	options->permit_empty_passwd = -1;
101 	options->permit_user_env = -1;
102 	options->use_login = -1;
103 	options->compression = -1;
104 	options->allow_tcp_forwarding = -1;
105 	options->allow_agent_forwarding = -1;
106 	options->num_allow_users = 0;
107 	options->num_deny_users = 0;
108 	options->num_allow_groups = 0;
109 	options->num_deny_groups = 0;
110 	options->ciphers = NULL;
111 	options->macs = NULL;
112 	options->protocol = SSH_PROTO_UNKNOWN;
113 	options->gateway_ports = -1;
114 	options->num_subsystems = 0;
115 	options->max_startups_begin = -1;
116 	options->max_startups_rate = -1;
117 	options->max_startups = -1;
118 	options->max_authtries = -1;
119 	options->max_sessions = -1;
120 	options->banner = NULL;
121 	options->use_dns = -1;
122 	options->client_alive_interval = -1;
123 	options->client_alive_count_max = -1;
124 	options->authorized_keys_file = NULL;
125 	options->authorized_keys_file2 = NULL;
126 	options->num_accept_env = 0;
127 	options->permit_tun = -1;
128 	options->num_permitted_opens = -1;
129 	options->adm_forced_command = NULL;
130 	options->chroot_directory = NULL;
131 	options->zero_knowledge_password_authentication = -1;
132 }
133 
134 void
135 fill_default_server_options(ServerOptions *options)
136 {
137 	/* Portable-specific options */
138 	if (options->use_pam == -1)
139 		options->use_pam = 0;
140 
141 	/* Standard Options */
142 	if (options->protocol == SSH_PROTO_UNKNOWN)
143 		options->protocol = SSH_PROTO_2;
144 	if (options->num_host_key_files == 0) {
145 		/* fill default hostkeys for protocols */
146 		if (options->protocol & SSH_PROTO_1)
147 			options->host_key_files[options->num_host_key_files++] =
148 			    _PATH_HOST_KEY_FILE;
149 		if (options->protocol & SSH_PROTO_2) {
150 			options->host_key_files[options->num_host_key_files++] =
151 			    _PATH_HOST_RSA_KEY_FILE;
152 			options->host_key_files[options->num_host_key_files++] =
153 			    _PATH_HOST_DSA_KEY_FILE;
154 		}
155 	}
156 	if (options->num_ports == 0)
157 		options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
158 	if (options->listen_addrs == NULL)
159 		add_listen_addr(options, NULL, 0);
160 	if (options->pid_file == NULL)
161 		options->pid_file = _PATH_SSH_DAEMON_PID_FILE;
162 	if (options->server_key_bits == -1)
163 		options->server_key_bits = 1024;
164 	if (options->login_grace_time == -1)
165 		options->login_grace_time = 120;
166 	if (options->key_regeneration_time == -1)
167 		options->key_regeneration_time = 3600;
168 	if (options->permit_root_login == PERMIT_NOT_SET)
169 		options->permit_root_login = PERMIT_NO;
170 	if (options->ignore_rhosts == -1)
171 		options->ignore_rhosts = 1;
172 	if (options->ignore_user_known_hosts == -1)
173 		options->ignore_user_known_hosts = 0;
174 	if (options->print_motd == -1)
175 		options->print_motd = 1;
176 	if (options->print_lastlog == -1)
177 		options->print_lastlog = 1;
178 	if (options->x11_forwarding == -1)
179 		options->x11_forwarding = 1;
180 	if (options->x11_display_offset == -1)
181 		options->x11_display_offset = 10;
182 	if (options->x11_use_localhost == -1)
183 		options->x11_use_localhost = 1;
184 	if (options->xauth_location == NULL)
185 		options->xauth_location = _PATH_XAUTH;
186 	if (options->strict_modes == -1)
187 		options->strict_modes = 1;
188 	if (options->tcp_keep_alive == -1)
189 		options->tcp_keep_alive = 1;
190 	if (options->log_facility == SYSLOG_FACILITY_NOT_SET)
191 		options->log_facility = SYSLOG_FACILITY_AUTH;
192 	if (options->log_level == SYSLOG_LEVEL_NOT_SET)
193 		options->log_level = SYSLOG_LEVEL_INFO;
194 	if (options->rhosts_rsa_authentication == -1)
195 		options->rhosts_rsa_authentication = 0;
196 	if (options->hostbased_authentication == -1)
197 		options->hostbased_authentication = 0;
198 	if (options->hostbased_uses_name_from_packet_only == -1)
199 		options->hostbased_uses_name_from_packet_only = 0;
200 	if (options->rsa_authentication == -1)
201 		options->rsa_authentication = 1;
202 	if (options->pubkey_authentication == -1)
203 		options->pubkey_authentication = 1;
204 	if (options->kerberos_authentication == -1)
205 		options->kerberos_authentication = 0;
206 	if (options->kerberos_or_local_passwd == -1)
207 		options->kerberos_or_local_passwd = 1;
208 	if (options->kerberos_ticket_cleanup == -1)
209 		options->kerberos_ticket_cleanup = 1;
210 	if (options->kerberos_get_afs_token == -1)
211 		options->kerberos_get_afs_token = 0;
212 	if (options->gss_authentication == -1)
213 		options->gss_authentication = 0;
214 	if (options->gss_cleanup_creds == -1)
215 		options->gss_cleanup_creds = 1;
216 	if (options->password_authentication == -1)
217 		options->password_authentication = 1;
218 	if (options->kbd_interactive_authentication == -1)
219 		options->kbd_interactive_authentication = 0;
220 	if (options->challenge_response_authentication == -1)
221 		options->challenge_response_authentication = 1;
222 	if (options->permit_blacklisted_keys == -1)
223 		options->permit_blacklisted_keys = 0;
224 	if (options->permit_empty_passwd == -1)
225 		options->permit_empty_passwd = 0;
226 	if (options->permit_user_env == -1)
227 		options->permit_user_env = 0;
228 	if (options->use_login == -1)
229 		options->use_login = 0;
230 	if (options->compression == -1)
231 		options->compression = COMP_DELAYED;
232 	if (options->allow_tcp_forwarding == -1)
233 		options->allow_tcp_forwarding = 1;
234 	if (options->allow_agent_forwarding == -1)
235 		options->allow_agent_forwarding = 1;
236 	if (options->gateway_ports == -1)
237 		options->gateway_ports = 0;
238 	if (options->max_startups == -1)
239 		options->max_startups = 10;
240 	if (options->max_startups_rate == -1)
241 		options->max_startups_rate = 100;		/* 100% */
242 	if (options->max_startups_begin == -1)
243 		options->max_startups_begin = options->max_startups;
244 	if (options->max_authtries == -1)
245 		options->max_authtries = DEFAULT_AUTH_FAIL_MAX;
246 	if (options->max_sessions == -1)
247 		options->max_sessions = DEFAULT_SESSIONS_MAX;
248 	if (options->use_dns == -1)
249 		options->use_dns = 1;
250 	if (options->client_alive_interval == -1)
251 		options->client_alive_interval = 0;
252 	if (options->client_alive_count_max == -1)
253 		options->client_alive_count_max = 3;
254 	if (options->authorized_keys_file2 == NULL) {
255 		/* authorized_keys_file2 falls back to authorized_keys_file */
256 		if (options->authorized_keys_file != NULL)
257 			options->authorized_keys_file2 = options->authorized_keys_file;
258 		else
259 			options->authorized_keys_file2 = _PATH_SSH_USER_PERMITTED_KEYS2;
260 	}
261 	if (options->authorized_keys_file == NULL)
262 		options->authorized_keys_file = _PATH_SSH_USER_PERMITTED_KEYS;
263 	if (options->permit_tun == -1)
264 		options->permit_tun = SSH_TUNMODE_NO;
265 	if (options->zero_knowledge_password_authentication == -1)
266 		options->zero_knowledge_password_authentication = 0;
267 
268 	/* Turn privilege separation on by default */
269 	if (use_privsep == -1)
270 		use_privsep = 1;
271 
272 #ifndef HAVE_MMAP
273 	if (use_privsep && options->compression == 1) {
274 		error("This platform does not support both privilege "
275 		    "separation and compression");
276 		error("Compression disabled");
277 		options->compression = 0;
278 	}
279 #endif
280 
281 }
282 
283 /* Keyword tokens. */
284 typedef enum {
285 	sBadOption,		/* == unknown option */
286 	/* Portable-specific options */
287 	sUsePAM,
288 	/* Standard Options */
289 	sPort, sHostKeyFile, sServerKeyBits, sLoginGraceTime, sKeyRegenerationTime,
290 	sPermitRootLogin, sLogFacility, sLogLevel,
291 	sRhostsRSAAuthentication, sRSAAuthentication,
292 	sKerberosAuthentication, sKerberosOrLocalPasswd, sKerberosTicketCleanup,
293 	sKerberosGetAFSToken,
294 	sKerberosTgtPassing, sChallengeResponseAuthentication,
295 	sPasswordAuthentication, sKbdInteractiveAuthentication,
296 	sListenAddress, sAddressFamily,
297 	sPrintMotd, sPrintLastLog, sIgnoreRhosts,
298 	sX11Forwarding, sX11DisplayOffset, sX11UseLocalhost,
299 	sStrictModes, sPermitBlacklistedKeys, sEmptyPasswd, sTCPKeepAlive,
300 	sPermitUserEnvironment, sUseLogin, sAllowTcpForwarding, sCompression,
301 	sAllowUsers, sDenyUsers, sAllowGroups, sDenyGroups,
302 	sIgnoreUserKnownHosts, sCiphers, sMacs, sProtocol, sPidFile,
303 	sGatewayPorts, sPubkeyAuthentication, sXAuthLocation, sSubsystem,
304 	sMaxStartups, sMaxAuthTries, sMaxSessions,
305 	sBanner, sUseDNS, sHostbasedAuthentication,
306 	sHostbasedUsesNameFromPacketOnly, sClientAliveInterval,
307 	sClientAliveCountMax, sAuthorizedKeysFile, sAuthorizedKeysFile2,
308 	sGssAuthentication, sGssCleanupCreds, sAcceptEnv, sPermitTunnel,
309 	sMatch, sPermitOpen, sForceCommand, sChrootDirectory,
310 	sUsePrivilegeSeparation, sAllowAgentForwarding,
311 	sZeroKnowledgePasswordAuthentication,
312 	sVersionAddendum,
313 	sDeprecated, sUnsupported
314 } ServerOpCodes;
315 
316 #define SSHCFG_GLOBAL	0x01	/* allowed in main section of sshd_config */
317 #define SSHCFG_MATCH	0x02	/* allowed inside a Match section */
318 #define SSHCFG_ALL	(SSHCFG_GLOBAL|SSHCFG_MATCH)
319 
320 /* Textual representation of the tokens. */
321 static struct {
322 	const char *name;
323 	ServerOpCodes opcode;
324 	u_int flags;
325 } keywords[] = {
326 	/* Portable-specific options */
327 #ifdef USE_PAM
328 	{ "usepam", sUsePAM, SSHCFG_GLOBAL },
329 #else
330 	{ "usepam", sUnsupported, SSHCFG_GLOBAL },
331 #endif
332 	{ "pamauthenticationviakbdint", sDeprecated, SSHCFG_GLOBAL },
333 	/* Standard Options */
334 	{ "port", sPort, SSHCFG_GLOBAL },
335 	{ "hostkey", sHostKeyFile, SSHCFG_GLOBAL },
336 	{ "hostdsakey", sHostKeyFile, SSHCFG_GLOBAL },		/* alias */
337 	{ "pidfile", sPidFile, SSHCFG_GLOBAL },
338 	{ "serverkeybits", sServerKeyBits, SSHCFG_GLOBAL },
339 	{ "logingracetime", sLoginGraceTime, SSHCFG_GLOBAL },
340 	{ "keyregenerationinterval", sKeyRegenerationTime, SSHCFG_GLOBAL },
341 	{ "permitrootlogin", sPermitRootLogin, SSHCFG_ALL },
342 	{ "syslogfacility", sLogFacility, SSHCFG_GLOBAL },
343 	{ "loglevel", sLogLevel, SSHCFG_GLOBAL },
344 	{ "rhostsauthentication", sDeprecated, SSHCFG_GLOBAL },
345 	{ "rhostsrsaauthentication", sRhostsRSAAuthentication, SSHCFG_ALL },
346 	{ "hostbasedauthentication", sHostbasedAuthentication, SSHCFG_ALL },
347 	{ "hostbasedusesnamefrompacketonly", sHostbasedUsesNameFromPacketOnly, SSHCFG_GLOBAL },
348 	{ "rsaauthentication", sRSAAuthentication, SSHCFG_ALL },
349 	{ "pubkeyauthentication", sPubkeyAuthentication, SSHCFG_ALL },
350 	{ "dsaauthentication", sPubkeyAuthentication, SSHCFG_GLOBAL },	/* alias */
351 #ifdef KRB5
352 	{ "kerberosauthentication", sKerberosAuthentication, SSHCFG_ALL },
353 	{ "kerberosorlocalpasswd", sKerberosOrLocalPasswd, SSHCFG_GLOBAL },
354 	{ "kerberosticketcleanup", sKerberosTicketCleanup, SSHCFG_GLOBAL },
355 #ifdef USE_AFS
356 	{ "kerberosgetafstoken", sKerberosGetAFSToken, SSHCFG_GLOBAL },
357 #else
358 	{ "kerberosgetafstoken", sUnsupported, SSHCFG_GLOBAL },
359 #endif
360 #else
361 	{ "kerberosauthentication", sUnsupported, SSHCFG_ALL },
362 	{ "kerberosorlocalpasswd", sUnsupported, SSHCFG_GLOBAL },
363 	{ "kerberosticketcleanup", sUnsupported, SSHCFG_GLOBAL },
364 	{ "kerberosgetafstoken", sUnsupported, SSHCFG_GLOBAL },
365 #endif
366 	{ "kerberostgtpassing", sUnsupported, SSHCFG_GLOBAL },
367 	{ "afstokenpassing", sUnsupported, SSHCFG_GLOBAL },
368 #ifdef GSSAPI
369 	{ "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
370 	{ "gssapicleanupcredentials", sGssCleanupCreds, SSHCFG_GLOBAL },
371 #else
372 	{ "gssapiauthentication", sUnsupported, SSHCFG_ALL },
373 	{ "gssapicleanupcredentials", sUnsupported, SSHCFG_GLOBAL },
374 #endif
375 	{ "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
376 	{ "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
377 	{ "challengeresponseauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL },
378 	{ "skeyauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL }, /* alias */
379 #ifdef JPAKE
380 	{ "zeroknowledgepasswordauthentication", sZeroKnowledgePasswordAuthentication, SSHCFG_ALL },
381 #else
382 	{ "zeroknowledgepasswordauthentication", sUnsupported, SSHCFG_ALL },
383 #endif
384 	{ "checkmail", sDeprecated, SSHCFG_GLOBAL },
385 	{ "listenaddress", sListenAddress, SSHCFG_GLOBAL },
386 	{ "addressfamily", sAddressFamily, SSHCFG_GLOBAL },
387 	{ "printmotd", sPrintMotd, SSHCFG_GLOBAL },
388 	{ "printlastlog", sPrintLastLog, SSHCFG_GLOBAL },
389 	{ "ignorerhosts", sIgnoreRhosts, SSHCFG_GLOBAL },
390 	{ "ignoreuserknownhosts", sIgnoreUserKnownHosts, SSHCFG_GLOBAL },
391 	{ "x11forwarding", sX11Forwarding, SSHCFG_ALL },
392 	{ "x11displayoffset", sX11DisplayOffset, SSHCFG_ALL },
393 	{ "x11uselocalhost", sX11UseLocalhost, SSHCFG_ALL },
394 	{ "xauthlocation", sXAuthLocation, SSHCFG_GLOBAL },
395 	{ "strictmodes", sStrictModes, SSHCFG_GLOBAL },
396 	{ "permitblacklistedkeys", sPermitBlacklistedKeys, SSHCFG_GLOBAL },
397 	{ "permitemptypasswords", sEmptyPasswd, SSHCFG_ALL },
398 	{ "permituserenvironment", sPermitUserEnvironment, SSHCFG_GLOBAL },
399 	{ "uselogin", sUseLogin, SSHCFG_GLOBAL },
400 	{ "compression", sCompression, SSHCFG_GLOBAL },
401 	{ "tcpkeepalive", sTCPKeepAlive, SSHCFG_GLOBAL },
402 	{ "keepalive", sTCPKeepAlive, SSHCFG_GLOBAL },	/* obsolete alias */
403 	{ "allowtcpforwarding", sAllowTcpForwarding, SSHCFG_ALL },
404 	{ "allowagentforwarding", sAllowAgentForwarding, SSHCFG_ALL },
405 	{ "allowusers", sAllowUsers, SSHCFG_GLOBAL },
406 	{ "denyusers", sDenyUsers, SSHCFG_GLOBAL },
407 	{ "allowgroups", sAllowGroups, SSHCFG_GLOBAL },
408 	{ "denygroups", sDenyGroups, SSHCFG_GLOBAL },
409 	{ "ciphers", sCiphers, SSHCFG_GLOBAL },
410 	{ "macs", sMacs, SSHCFG_GLOBAL },
411 	{ "protocol", sProtocol, SSHCFG_GLOBAL },
412 	{ "gatewayports", sGatewayPorts, SSHCFG_ALL },
413 	{ "subsystem", sSubsystem, SSHCFG_GLOBAL },
414 	{ "maxstartups", sMaxStartups, SSHCFG_GLOBAL },
415 	{ "maxauthtries", sMaxAuthTries, SSHCFG_ALL },
416 	{ "maxsessions", sMaxSessions, SSHCFG_ALL },
417 	{ "banner", sBanner, SSHCFG_ALL },
418 	{ "usedns", sUseDNS, SSHCFG_GLOBAL },
419 	{ "verifyreversemapping", sDeprecated, SSHCFG_GLOBAL },
420 	{ "reversemappingcheck", sDeprecated, SSHCFG_GLOBAL },
421 	{ "clientaliveinterval", sClientAliveInterval, SSHCFG_GLOBAL },
422 	{ "clientalivecountmax", sClientAliveCountMax, SSHCFG_GLOBAL },
423 	{ "authorizedkeysfile", sAuthorizedKeysFile, SSHCFG_GLOBAL },
424 	{ "authorizedkeysfile2", sAuthorizedKeysFile2, SSHCFG_GLOBAL },
425 	{ "useprivilegeseparation", sUsePrivilegeSeparation, SSHCFG_GLOBAL },
426 	{ "versionaddendum", sVersionAddendum , SSHCFG_GLOBAL },
427 	{ "acceptenv", sAcceptEnv, SSHCFG_GLOBAL },
428 	{ "permittunnel", sPermitTunnel, SSHCFG_GLOBAL },
429  	{ "match", sMatch, SSHCFG_ALL },
430 	{ "permitopen", sPermitOpen, SSHCFG_ALL },
431 	{ "forcecommand", sForceCommand, SSHCFG_ALL },
432 	{ "chrootdirectory", sChrootDirectory, SSHCFG_ALL },
433 	{ NULL, sBadOption, 0 }
434 };
435 
436 static struct {
437 	int val;
438 	char *text;
439 } tunmode_desc[] = {
440 	{ SSH_TUNMODE_NO, "no" },
441 	{ SSH_TUNMODE_POINTOPOINT, "point-to-point" },
442 	{ SSH_TUNMODE_ETHERNET, "ethernet" },
443 	{ SSH_TUNMODE_YES, "yes" },
444 	{ -1, NULL }
445 };
446 
447 /*
448  * Returns the number of the token pointed to by cp or sBadOption.
449  */
450 
451 static ServerOpCodes
452 parse_token(const char *cp, const char *filename,
453 	    int linenum, u_int *flags)
454 {
455 	u_int i;
456 
457 	for (i = 0; keywords[i].name; i++)
458 		if (strcasecmp(cp, keywords[i].name) == 0) {
459 			*flags = keywords[i].flags;
460 			return keywords[i].opcode;
461 		}
462 
463 	error("%s: line %d: Bad configuration option: %s",
464 	    filename, linenum, cp);
465 	return sBadOption;
466 }
467 
468 static void
469 add_listen_addr(ServerOptions *options, char *addr, int port)
470 {
471 	u_int i;
472 
473 	if (options->num_ports == 0)
474 		options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
475 	if (options->address_family == -1)
476 		options->address_family = AF_UNSPEC;
477 	if (port == 0)
478 		for (i = 0; i < options->num_ports; i++)
479 			add_one_listen_addr(options, addr, options->ports[i]);
480 	else
481 		add_one_listen_addr(options, addr, port);
482 }
483 
484 static void
485 add_one_listen_addr(ServerOptions *options, char *addr, int port)
486 {
487 	struct addrinfo hints, *ai, *aitop;
488 	char strport[NI_MAXSERV];
489 	int gaierr;
490 
491 	memset(&hints, 0, sizeof(hints));
492 	hints.ai_family = options->address_family;
493 	hints.ai_socktype = SOCK_STREAM;
494 	hints.ai_flags = (addr == NULL) ? AI_PASSIVE : 0;
495 	snprintf(strport, sizeof strport, "%d", port);
496 	if ((gaierr = getaddrinfo(addr, strport, &hints, &aitop)) != 0)
497 		fatal("bad addr or host: %s (%s)",
498 		    addr ? addr : "<NULL>",
499 		    ssh_gai_strerror(gaierr));
500 	for (ai = aitop; ai->ai_next; ai = ai->ai_next)
501 		;
502 	ai->ai_next = options->listen_addrs;
503 	options->listen_addrs = aitop;
504 }
505 
506 /*
507  * The strategy for the Match blocks is that the config file is parsed twice.
508  *
509  * The first time is at startup.  activep is initialized to 1 and the
510  * directives in the global context are processed and acted on.  Hitting a
511  * Match directive unsets activep and the directives inside the block are
512  * checked for syntax only.
513  *
514  * The second time is after a connection has been established but before
515  * authentication.  activep is initialized to 2 and global config directives
516  * are ignored since they have already been processed.  If the criteria in a
517  * Match block is met, activep is set and the subsequent directives
518  * processed and actioned until EOF or another Match block unsets it.  Any
519  * options set are copied into the main server config.
520  *
521  * Potential additions/improvements:
522  *  - Add Match support for pre-kex directives, eg Protocol, Ciphers.
523  *
524  *  - Add a Tag directive (idea from David Leonard) ala pf, eg:
525  *	Match Address 192.168.0.*
526  *		Tag trusted
527  *	Match Group wheel
528  *		Tag trusted
529  *	Match Tag trusted
530  *		AllowTcpForwarding yes
531  *		GatewayPorts clientspecified
532  *		[...]
533  *
534  *  - Add a PermittedChannelRequests directive
535  *	Match Group shell
536  *		PermittedChannelRequests session,forwarded-tcpip
537  */
538 
539 static int
540 match_cfg_line_group(const char *grps, int line, const char *user)
541 {
542 	int result = 0;
543 	struct passwd *pw;
544 
545 	if (user == NULL)
546 		goto out;
547 
548 	if ((pw = getpwnam(user)) == NULL) {
549 		debug("Can't match group at line %d because user %.100s does "
550 		    "not exist", line, user);
551 	} else if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
552 		debug("Can't Match group because user %.100s not in any group "
553 		    "at line %d", user, line);
554 	} else if (ga_match_pattern_list(grps) != 1) {
555 		debug("user %.100s does not match group list %.100s at line %d",
556 		    user, grps, line);
557 	} else {
558 		debug("user %.100s matched group list %.100s at line %d", user,
559 		    grps, line);
560 		result = 1;
561 	}
562 out:
563 	ga_free();
564 	return result;
565 }
566 
567 static int
568 match_cfg_line(char **condition, int line, const char *user, const char *host,
569     const char *address)
570 {
571 	int result = 1;
572 	char *arg, *attrib, *cp = *condition;
573 	size_t len;
574 
575 	if (user == NULL)
576 		debug3("checking syntax for 'Match %s'", cp);
577 	else
578 		debug3("checking match for '%s' user %s host %s addr %s", cp,
579 		    user ? user : "(null)", host ? host : "(null)",
580 		    address ? address : "(null)");
581 
582 	while ((attrib = strdelim(&cp)) && *attrib != '\0') {
583 		if ((arg = strdelim(&cp)) == NULL || *arg == '\0') {
584 			error("Missing Match criteria for %s", attrib);
585 			return -1;
586 		}
587 		len = strlen(arg);
588 		if (strcasecmp(attrib, "user") == 0) {
589 			if (!user) {
590 				result = 0;
591 				continue;
592 			}
593 			if (match_pattern_list(user, arg, len, 0) != 1)
594 				result = 0;
595 			else
596 				debug("user %.100s matched 'User %.100s' at "
597 				    "line %d", user, arg, line);
598 		} else if (strcasecmp(attrib, "group") == 0) {
599 			switch (match_cfg_line_group(arg, line, user)) {
600 			case -1:
601 				return -1;
602 			case 0:
603 				result = 0;
604 			}
605 		} else if (strcasecmp(attrib, "host") == 0) {
606 			if (!host) {
607 				result = 0;
608 				continue;
609 			}
610 			if (match_hostname(host, arg, len) != 1)
611 				result = 0;
612 			else
613 				debug("connection from %.100s matched 'Host "
614 				    "%.100s' at line %d", host, arg, line);
615 		} else if (strcasecmp(attrib, "address") == 0) {
616 			switch (addr_match_list(address, arg)) {
617 			case 1:
618 				debug("connection from %.100s matched 'Address "
619 				    "%.100s' at line %d", address, arg, line);
620 				break;
621 			case 0:
622 			case -1:
623 				result = 0;
624 				break;
625 			case -2:
626 				return -1;
627 			}
628 		} else {
629 			error("Unsupported Match attribute %s", attrib);
630 			return -1;
631 		}
632 	}
633 	if (user != NULL)
634 		debug3("match %sfound", result ? "" : "not ");
635 	*condition = cp;
636 	return result;
637 }
638 
639 #define WHITESPACE " \t\r\n"
640 
641 int
642 process_server_config_line(ServerOptions *options, char *line,
643     const char *filename, int linenum, int *activep, const char *user,
644     const char *host, const char *address)
645 {
646 	char *cp, **charptr, *arg, *p;
647 	int cmdline = 0, *intptr, value, n;
648 	SyslogFacility *log_facility_ptr;
649 	LogLevel *log_level_ptr;
650 	ServerOpCodes opcode;
651 	int port;
652 	u_int i, flags = 0;
653 	size_t len;
654 
655 	cp = line;
656 	if ((arg = strdelim(&cp)) == NULL)
657 		return 0;
658 	/* Ignore leading whitespace */
659 	if (*arg == '\0')
660 		arg = strdelim(&cp);
661 	if (!arg || !*arg || *arg == '#')
662 		return 0;
663 	intptr = NULL;
664 	charptr = NULL;
665 	opcode = parse_token(arg, filename, linenum, &flags);
666 
667 	if (activep == NULL) { /* We are processing a command line directive */
668 		cmdline = 1;
669 		activep = &cmdline;
670 	}
671 	if (*activep && opcode != sMatch)
672 		debug3("%s:%d setting %s %s", filename, linenum, arg, cp);
673 	if (*activep == 0 && !(flags & SSHCFG_MATCH)) {
674 		if (user == NULL) {
675 			fatal("%s line %d: Directive '%s' is not allowed "
676 			    "within a Match block", filename, linenum, arg);
677 		} else { /* this is a directive we have already processed */
678 			while (arg)
679 				arg = strdelim(&cp);
680 			return 0;
681 		}
682 	}
683 
684 	switch (opcode) {
685 	/* Portable-specific options */
686 	case sUsePAM:
687 		intptr = &options->use_pam;
688 		goto parse_flag;
689 
690 	/* Standard Options */
691 	case sBadOption:
692 		return -1;
693 	case sPort:
694 		/* ignore ports from configfile if cmdline specifies ports */
695 		if (options->ports_from_cmdline)
696 			return 0;
697 		if (options->listen_addrs != NULL)
698 			fatal("%s line %d: ports must be specified before "
699 			    "ListenAddress.", filename, linenum);
700 		if (options->num_ports >= MAX_PORTS)
701 			fatal("%s line %d: too many ports.",
702 			    filename, linenum);
703 		arg = strdelim(&cp);
704 		if (!arg || *arg == '\0')
705 			fatal("%s line %d: missing port number.",
706 			    filename, linenum);
707 		options->ports[options->num_ports++] = a2port(arg);
708 		if (options->ports[options->num_ports-1] <= 0)
709 			fatal("%s line %d: Badly formatted port number.",
710 			    filename, linenum);
711 		break;
712 
713 	case sServerKeyBits:
714 		intptr = &options->server_key_bits;
715  parse_int:
716 		arg = strdelim(&cp);
717 		if (!arg || *arg == '\0')
718 			fatal("%s line %d: missing integer value.",
719 			    filename, linenum);
720 		value = atoi(arg);
721 		if (*activep && *intptr == -1)
722 			*intptr = value;
723 		break;
724 
725 	case sLoginGraceTime:
726 		intptr = &options->login_grace_time;
727  parse_time:
728 		arg = strdelim(&cp);
729 		if (!arg || *arg == '\0')
730 			fatal("%s line %d: missing time value.",
731 			    filename, linenum);
732 		if ((value = convtime(arg)) == -1)
733 			fatal("%s line %d: invalid time value.",
734 			    filename, linenum);
735 		if (*intptr == -1)
736 			*intptr = value;
737 		break;
738 
739 	case sKeyRegenerationTime:
740 		intptr = &options->key_regeneration_time;
741 		goto parse_time;
742 
743 	case sListenAddress:
744 		arg = strdelim(&cp);
745 		if (arg == NULL || *arg == '\0')
746 			fatal("%s line %d: missing address",
747 			    filename, linenum);
748 		/* check for bare IPv6 address: no "[]" and 2 or more ":" */
749 		if (strchr(arg, '[') == NULL && (p = strchr(arg, ':')) != NULL
750 		    && strchr(p+1, ':') != NULL) {
751 			add_listen_addr(options, arg, 0);
752 			break;
753 		}
754 		p = hpdelim(&arg);
755 		if (p == NULL)
756 			fatal("%s line %d: bad address:port usage",
757 			    filename, linenum);
758 		p = cleanhostname(p);
759 		if (arg == NULL)
760 			port = 0;
761 		else if ((port = a2port(arg)) <= 0)
762 			fatal("%s line %d: bad port number", filename, linenum);
763 
764 		add_listen_addr(options, p, port);
765 
766 		break;
767 
768 	case sAddressFamily:
769 		arg = strdelim(&cp);
770 		if (!arg || *arg == '\0')
771 			fatal("%s line %d: missing address family.",
772 			    filename, linenum);
773 		intptr = &options->address_family;
774 		if (options->listen_addrs != NULL)
775 			fatal("%s line %d: address family must be specified before "
776 			    "ListenAddress.", filename, linenum);
777 		if (strcasecmp(arg, "inet") == 0)
778 			value = AF_INET;
779 		else if (strcasecmp(arg, "inet6") == 0)
780 			value = AF_INET6;
781 		else if (strcasecmp(arg, "any") == 0)
782 			value = AF_UNSPEC;
783 		else
784 			fatal("%s line %d: unsupported address family \"%s\".",
785 			    filename, linenum, arg);
786 		if (*intptr == -1)
787 			*intptr = value;
788 		break;
789 
790 	case sHostKeyFile:
791 		intptr = &options->num_host_key_files;
792 		if (*intptr >= MAX_HOSTKEYS)
793 			fatal("%s line %d: too many host keys specified (max %d).",
794 			    filename, linenum, MAX_HOSTKEYS);
795 		charptr = &options->host_key_files[*intptr];
796  parse_filename:
797 		arg = strdelim(&cp);
798 		if (!arg || *arg == '\0')
799 			fatal("%s line %d: missing file name.",
800 			    filename, linenum);
801 		if (*activep && *charptr == NULL) {
802 			*charptr = tilde_expand_filename(arg, getuid());
803 			/* increase optional counter */
804 			if (intptr != NULL)
805 				*intptr = *intptr + 1;
806 		}
807 		break;
808 
809 	case sPidFile:
810 		charptr = &options->pid_file;
811 		goto parse_filename;
812 
813 	case sPermitRootLogin:
814 		intptr = &options->permit_root_login;
815 		arg = strdelim(&cp);
816 		if (!arg || *arg == '\0')
817 			fatal("%s line %d: missing yes/"
818 			    "without-password/forced-commands-only/no "
819 			    "argument.", filename, linenum);
820 		value = 0;	/* silence compiler */
821 		if (strcmp(arg, "without-password") == 0)
822 			value = PERMIT_NO_PASSWD;
823 		else if (strcmp(arg, "forced-commands-only") == 0)
824 			value = PERMIT_FORCED_ONLY;
825 		else if (strcmp(arg, "yes") == 0)
826 			value = PERMIT_YES;
827 		else if (strcmp(arg, "no") == 0)
828 			value = PERMIT_NO;
829 		else
830 			fatal("%s line %d: Bad yes/"
831 			    "without-password/forced-commands-only/no "
832 			    "argument: %s", filename, linenum, arg);
833 		if (*activep && *intptr == -1)
834 			*intptr = value;
835 		break;
836 
837 	case sIgnoreRhosts:
838 		intptr = &options->ignore_rhosts;
839  parse_flag:
840 		arg = strdelim(&cp);
841 		if (!arg || *arg == '\0')
842 			fatal("%s line %d: missing yes/no argument.",
843 			    filename, linenum);
844 		value = 0;	/* silence compiler */
845 		if (strcmp(arg, "yes") == 0)
846 			value = 1;
847 		else if (strcmp(arg, "no") == 0)
848 			value = 0;
849 		else
850 			fatal("%s line %d: Bad yes/no argument: %s",
851 				filename, linenum, arg);
852 		if (*activep && *intptr == -1)
853 			*intptr = value;
854 		break;
855 
856 	case sIgnoreUserKnownHosts:
857 		intptr = &options->ignore_user_known_hosts;
858 		goto parse_flag;
859 
860 	case sRhostsRSAAuthentication:
861 		intptr = &options->rhosts_rsa_authentication;
862 		goto parse_flag;
863 
864 	case sHostbasedAuthentication:
865 		intptr = &options->hostbased_authentication;
866 		goto parse_flag;
867 
868 	case sHostbasedUsesNameFromPacketOnly:
869 		intptr = &options->hostbased_uses_name_from_packet_only;
870 		goto parse_flag;
871 
872 	case sRSAAuthentication:
873 		intptr = &options->rsa_authentication;
874 		goto parse_flag;
875 
876 	case sPubkeyAuthentication:
877 		intptr = &options->pubkey_authentication;
878 		goto parse_flag;
879 
880 	case sKerberosAuthentication:
881 		intptr = &options->kerberos_authentication;
882 		goto parse_flag;
883 
884 	case sKerberosOrLocalPasswd:
885 		intptr = &options->kerberos_or_local_passwd;
886 		goto parse_flag;
887 
888 	case sKerberosTicketCleanup:
889 		intptr = &options->kerberos_ticket_cleanup;
890 		goto parse_flag;
891 
892 	case sKerberosGetAFSToken:
893 		intptr = &options->kerberos_get_afs_token;
894 		goto parse_flag;
895 
896 	case sGssAuthentication:
897 		intptr = &options->gss_authentication;
898 		goto parse_flag;
899 
900 	case sGssCleanupCreds:
901 		intptr = &options->gss_cleanup_creds;
902 		goto parse_flag;
903 
904 	case sPasswordAuthentication:
905 		intptr = &options->password_authentication;
906 		goto parse_flag;
907 
908 	case sZeroKnowledgePasswordAuthentication:
909 		intptr = &options->zero_knowledge_password_authentication;
910 		goto parse_flag;
911 
912 	case sKbdInteractiveAuthentication:
913 		intptr = &options->kbd_interactive_authentication;
914 		goto parse_flag;
915 
916 	case sChallengeResponseAuthentication:
917 		intptr = &options->challenge_response_authentication;
918 		goto parse_flag;
919 
920 	case sPrintMotd:
921 		intptr = &options->print_motd;
922 		goto parse_flag;
923 
924 	case sPrintLastLog:
925 		intptr = &options->print_lastlog;
926 		goto parse_flag;
927 
928 	case sX11Forwarding:
929 		intptr = &options->x11_forwarding;
930 		goto parse_flag;
931 
932 	case sX11DisplayOffset:
933 		intptr = &options->x11_display_offset;
934 		goto parse_int;
935 
936 	case sX11UseLocalhost:
937 		intptr = &options->x11_use_localhost;
938 		goto parse_flag;
939 
940 	case sXAuthLocation:
941 		charptr = &options->xauth_location;
942 		goto parse_filename;
943 
944 	case sStrictModes:
945 		intptr = &options->strict_modes;
946 		goto parse_flag;
947 
948 	case sTCPKeepAlive:
949 		intptr = &options->tcp_keep_alive;
950 		goto parse_flag;
951 
952 	case sPermitBlacklistedKeys:
953 		intptr = &options->permit_blacklisted_keys;
954 		goto parse_flag;
955 
956 	case sEmptyPasswd:
957 		intptr = &options->permit_empty_passwd;
958 		goto parse_flag;
959 
960 	case sPermitUserEnvironment:
961 		intptr = &options->permit_user_env;
962 		goto parse_flag;
963 
964 	case sUseLogin:
965 		intptr = &options->use_login;
966 		goto parse_flag;
967 
968 	case sCompression:
969 		intptr = &options->compression;
970 		arg = strdelim(&cp);
971 		if (!arg || *arg == '\0')
972 			fatal("%s line %d: missing yes/no/delayed "
973 			    "argument.", filename, linenum);
974 		value = 0;	/* silence compiler */
975 		if (strcmp(arg, "delayed") == 0)
976 			value = COMP_DELAYED;
977 		else if (strcmp(arg, "yes") == 0)
978 			value = COMP_ZLIB;
979 		else if (strcmp(arg, "no") == 0)
980 			value = COMP_NONE;
981 		else
982 			fatal("%s line %d: Bad yes/no/delayed "
983 			    "argument: %s", filename, linenum, arg);
984 		if (*intptr == -1)
985 			*intptr = value;
986 		break;
987 
988 	case sGatewayPorts:
989 		intptr = &options->gateway_ports;
990 		arg = strdelim(&cp);
991 		if (!arg || *arg == '\0')
992 			fatal("%s line %d: missing yes/no/clientspecified "
993 			    "argument.", filename, linenum);
994 		value = 0;	/* silence compiler */
995 		if (strcmp(arg, "clientspecified") == 0)
996 			value = 2;
997 		else if (strcmp(arg, "yes") == 0)
998 			value = 1;
999 		else if (strcmp(arg, "no") == 0)
1000 			value = 0;
1001 		else
1002 			fatal("%s line %d: Bad yes/no/clientspecified "
1003 			    "argument: %s", filename, linenum, arg);
1004 		if (*activep && *intptr == -1)
1005 			*intptr = value;
1006 		break;
1007 
1008 	case sUseDNS:
1009 		intptr = &options->use_dns;
1010 		goto parse_flag;
1011 
1012 	case sLogFacility:
1013 		log_facility_ptr = &options->log_facility;
1014 		arg = strdelim(&cp);
1015 		value = log_facility_number(arg);
1016 		if (value == SYSLOG_FACILITY_NOT_SET)
1017 			fatal("%.200s line %d: unsupported log facility '%s'",
1018 			    filename, linenum, arg ? arg : "<NONE>");
1019 		if (*log_facility_ptr == -1)
1020 			*log_facility_ptr = (SyslogFacility) value;
1021 		break;
1022 
1023 	case sLogLevel:
1024 		log_level_ptr = &options->log_level;
1025 		arg = strdelim(&cp);
1026 		value = log_level_number(arg);
1027 		if (value == SYSLOG_LEVEL_NOT_SET)
1028 			fatal("%.200s line %d: unsupported log level '%s'",
1029 			    filename, linenum, arg ? arg : "<NONE>");
1030 		if (*log_level_ptr == -1)
1031 			*log_level_ptr = (LogLevel) value;
1032 		break;
1033 
1034 	case sAllowTcpForwarding:
1035 		intptr = &options->allow_tcp_forwarding;
1036 		goto parse_flag;
1037 
1038 	case sAllowAgentForwarding:
1039 		intptr = &options->allow_agent_forwarding;
1040 		goto parse_flag;
1041 
1042 	case sUsePrivilegeSeparation:
1043 		intptr = &use_privsep;
1044 		goto parse_flag;
1045 
1046 	case sAllowUsers:
1047 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1048 			if (options->num_allow_users >= MAX_ALLOW_USERS)
1049 				fatal("%s line %d: too many allow users.",
1050 				    filename, linenum);
1051 			options->allow_users[options->num_allow_users++] =
1052 			    xstrdup(arg);
1053 		}
1054 		break;
1055 
1056 	case sDenyUsers:
1057 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1058 			if (options->num_deny_users >= MAX_DENY_USERS)
1059 				fatal("%s line %d: too many deny users.",
1060 				    filename, linenum);
1061 			options->deny_users[options->num_deny_users++] =
1062 			    xstrdup(arg);
1063 		}
1064 		break;
1065 
1066 	case sAllowGroups:
1067 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1068 			if (options->num_allow_groups >= MAX_ALLOW_GROUPS)
1069 				fatal("%s line %d: too many allow groups.",
1070 				    filename, linenum);
1071 			options->allow_groups[options->num_allow_groups++] =
1072 			    xstrdup(arg);
1073 		}
1074 		break;
1075 
1076 	case sDenyGroups:
1077 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1078 			if (options->num_deny_groups >= MAX_DENY_GROUPS)
1079 				fatal("%s line %d: too many deny groups.",
1080 				    filename, linenum);
1081 			options->deny_groups[options->num_deny_groups++] = xstrdup(arg);
1082 		}
1083 		break;
1084 
1085 	case sCiphers:
1086 		arg = strdelim(&cp);
1087 		if (!arg || *arg == '\0')
1088 			fatal("%s line %d: Missing argument.", filename, linenum);
1089 		if (!ciphers_valid(arg))
1090 			fatal("%s line %d: Bad SSH2 cipher spec '%s'.",
1091 			    filename, linenum, arg ? arg : "<NONE>");
1092 		if (options->ciphers == NULL)
1093 			options->ciphers = xstrdup(arg);
1094 		break;
1095 
1096 	case sMacs:
1097 		arg = strdelim(&cp);
1098 		if (!arg || *arg == '\0')
1099 			fatal("%s line %d: Missing argument.", filename, linenum);
1100 		if (!mac_valid(arg))
1101 			fatal("%s line %d: Bad SSH2 mac spec '%s'.",
1102 			    filename, linenum, arg ? arg : "<NONE>");
1103 		if (options->macs == NULL)
1104 			options->macs = xstrdup(arg);
1105 		break;
1106 
1107 	case sProtocol:
1108 		intptr = &options->protocol;
1109 		arg = strdelim(&cp);
1110 		if (!arg || *arg == '\0')
1111 			fatal("%s line %d: Missing argument.", filename, linenum);
1112 		value = proto_spec(arg);
1113 		if (value == SSH_PROTO_UNKNOWN)
1114 			fatal("%s line %d: Bad protocol spec '%s'.",
1115 			    filename, linenum, arg ? arg : "<NONE>");
1116 		if (*intptr == SSH_PROTO_UNKNOWN)
1117 			*intptr = value;
1118 		break;
1119 
1120 	case sSubsystem:
1121 		if (options->num_subsystems >= MAX_SUBSYSTEMS) {
1122 			fatal("%s line %d: too many subsystems defined.",
1123 			    filename, linenum);
1124 		}
1125 		arg = strdelim(&cp);
1126 		if (!arg || *arg == '\0')
1127 			fatal("%s line %d: Missing subsystem name.",
1128 			    filename, linenum);
1129 		if (!*activep) {
1130 			arg = strdelim(&cp);
1131 			break;
1132 		}
1133 		for (i = 0; i < options->num_subsystems; i++)
1134 			if (strcmp(arg, options->subsystem_name[i]) == 0)
1135 				fatal("%s line %d: Subsystem '%s' already defined.",
1136 				    filename, linenum, arg);
1137 		options->subsystem_name[options->num_subsystems] = xstrdup(arg);
1138 		arg = strdelim(&cp);
1139 		if (!arg || *arg == '\0')
1140 			fatal("%s line %d: Missing subsystem command.",
1141 			    filename, linenum);
1142 		options->subsystem_command[options->num_subsystems] = xstrdup(arg);
1143 
1144 		/* Collect arguments (separate to executable) */
1145 		p = xstrdup(arg);
1146 		len = strlen(p) + 1;
1147 		while ((arg = strdelim(&cp)) != NULL && *arg != '\0') {
1148 			len += 1 + strlen(arg);
1149 			p = xrealloc(p, 1, len);
1150 			strlcat(p, " ", len);
1151 			strlcat(p, arg, len);
1152 		}
1153 		options->subsystem_args[options->num_subsystems] = p;
1154 		options->num_subsystems++;
1155 		break;
1156 
1157 	case sMaxStartups:
1158 		arg = strdelim(&cp);
1159 		if (!arg || *arg == '\0')
1160 			fatal("%s line %d: Missing MaxStartups spec.",
1161 			    filename, linenum);
1162 		if ((n = sscanf(arg, "%d:%d:%d",
1163 		    &options->max_startups_begin,
1164 		    &options->max_startups_rate,
1165 		    &options->max_startups)) == 3) {
1166 			if (options->max_startups_begin >
1167 			    options->max_startups ||
1168 			    options->max_startups_rate > 100 ||
1169 			    options->max_startups_rate < 1)
1170 				fatal("%s line %d: Illegal MaxStartups spec.",
1171 				    filename, linenum);
1172 		} else if (n != 1)
1173 			fatal("%s line %d: Illegal MaxStartups spec.",
1174 			    filename, linenum);
1175 		else
1176 			options->max_startups = options->max_startups_begin;
1177 		break;
1178 
1179 	case sMaxAuthTries:
1180 		intptr = &options->max_authtries;
1181 		goto parse_int;
1182 
1183 	case sMaxSessions:
1184 		intptr = &options->max_sessions;
1185 		goto parse_int;
1186 
1187 	case sBanner:
1188 		charptr = &options->banner;
1189 		goto parse_filename;
1190 
1191 	/*
1192 	 * These options can contain %X options expanded at
1193 	 * connect time, so that you can specify paths like:
1194 	 *
1195 	 * AuthorizedKeysFile	/etc/ssh_keys/%u
1196 	 */
1197 	case sAuthorizedKeysFile:
1198 	case sAuthorizedKeysFile2:
1199 		charptr = (opcode == sAuthorizedKeysFile) ?
1200 		    &options->authorized_keys_file :
1201 		    &options->authorized_keys_file2;
1202 		goto parse_filename;
1203 
1204 	case sClientAliveInterval:
1205 		intptr = &options->client_alive_interval;
1206 		goto parse_time;
1207 
1208 	case sClientAliveCountMax:
1209 		intptr = &options->client_alive_count_max;
1210 		goto parse_int;
1211 
1212 	case sAcceptEnv:
1213 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1214 			if (strchr(arg, '=') != NULL)
1215 				fatal("%s line %d: Invalid environment name.",
1216 				    filename, linenum);
1217 			if (options->num_accept_env >= MAX_ACCEPT_ENV)
1218 				fatal("%s line %d: too many allow env.",
1219 				    filename, linenum);
1220 			if (!*activep)
1221 				break;
1222 			options->accept_env[options->num_accept_env++] =
1223 			    xstrdup(arg);
1224 		}
1225 		break;
1226 
1227 	case sPermitTunnel:
1228 		intptr = &options->permit_tun;
1229 		arg = strdelim(&cp);
1230 		if (!arg || *arg == '\0')
1231 			fatal("%s line %d: Missing yes/point-to-point/"
1232 			    "ethernet/no argument.", filename, linenum);
1233 		value = -1;
1234 		for (i = 0; tunmode_desc[i].val != -1; i++)
1235 			if (strcmp(tunmode_desc[i].text, arg) == 0) {
1236 				value = tunmode_desc[i].val;
1237 				break;
1238 			}
1239 		if (value == -1)
1240 			fatal("%s line %d: Bad yes/point-to-point/ethernet/"
1241 			    "no argument: %s", filename, linenum, arg);
1242 		if (*intptr == -1)
1243 			*intptr = value;
1244 		break;
1245 
1246 	case sMatch:
1247 		if (cmdline)
1248 			fatal("Match directive not supported as a command-line "
1249 			   "option");
1250 		value = match_cfg_line(&cp, linenum, user, host, address);
1251 		if (value < 0)
1252 			fatal("%s line %d: Bad Match condition", filename,
1253 			    linenum);
1254 		*activep = value;
1255 		break;
1256 
1257 	case sPermitOpen:
1258 		arg = strdelim(&cp);
1259 		if (!arg || *arg == '\0')
1260 			fatal("%s line %d: missing PermitOpen specification",
1261 			    filename, linenum);
1262 		n = options->num_permitted_opens;	/* modified later */
1263 		if (strcmp(arg, "any") == 0) {
1264 			if (*activep && n == -1) {
1265 				channel_clear_adm_permitted_opens();
1266 				options->num_permitted_opens = 0;
1267 			}
1268 			break;
1269 		}
1270 		if (*activep && n == -1)
1271 			channel_clear_adm_permitted_opens();
1272 		for (; arg != NULL && *arg != '\0'; arg = strdelim(&cp)) {
1273 			p = hpdelim(&arg);
1274 			if (p == NULL)
1275 				fatal("%s line %d: missing host in PermitOpen",
1276 				    filename, linenum);
1277 			p = cleanhostname(p);
1278 			if (arg == NULL || (port = a2port(arg)) <= 0)
1279 				fatal("%s line %d: bad port number in "
1280 				    "PermitOpen", filename, linenum);
1281 			if (*activep && n == -1)
1282 				options->num_permitted_opens =
1283 				    channel_add_adm_permitted_opens(p, port);
1284 		}
1285 		break;
1286 
1287 	case sForceCommand:
1288 		if (cp == NULL)
1289 			fatal("%.200s line %d: Missing argument.", filename,
1290 			    linenum);
1291 		len = strspn(cp, WHITESPACE);
1292 		if (*activep && options->adm_forced_command == NULL)
1293 			options->adm_forced_command = xstrdup(cp + len);
1294 		return 0;
1295 
1296 	case sChrootDirectory:
1297 		charptr = &options->chroot_directory;
1298 
1299 		arg = strdelim(&cp);
1300 		if (!arg || *arg == '\0')
1301 			fatal("%s line %d: missing file name.",
1302 			    filename, linenum);
1303 		if (*activep && *charptr == NULL)
1304 			*charptr = xstrdup(arg);
1305 		break;
1306 
1307 	case sVersionAddendum:
1308                 ssh_version_set_addendum(strtok(cp, "\n"));
1309                 do {
1310                         arg = strdelim(&cp);
1311                 } while (arg != NULL && *arg != '\0');
1312 		break;
1313 
1314 	case sDeprecated:
1315 		logit("%s line %d: Deprecated option %s",
1316 		    filename, linenum, arg);
1317 		while (arg)
1318 		    arg = strdelim(&cp);
1319 		break;
1320 
1321 	case sUnsupported:
1322 		logit("%s line %d: Unsupported option %s",
1323 		    filename, linenum, arg);
1324 		while (arg)
1325 		    arg = strdelim(&cp);
1326 		break;
1327 
1328 	default:
1329 		fatal("%s line %d: Missing handler for opcode %s (%d)",
1330 		    filename, linenum, arg, opcode);
1331 	}
1332 	if ((arg = strdelim(&cp)) != NULL && *arg != '\0')
1333 		fatal("%s line %d: garbage at end of line; \"%.200s\".",
1334 		    filename, linenum, arg);
1335 	return 0;
1336 }
1337 
1338 /* Reads the server configuration file. */
1339 
1340 void
1341 load_server_config(const char *filename, Buffer *conf)
1342 {
1343 	char line[1024], *cp;
1344 	FILE *f;
1345 
1346 	debug2("%s: filename %s", __func__, filename);
1347 	if ((f = fopen(filename, "r")) == NULL) {
1348 		perror(filename);
1349 		exit(1);
1350 	}
1351 	buffer_clear(conf);
1352 	while (fgets(line, sizeof(line), f)) {
1353 		/*
1354 		 * Trim out comments and strip whitespace
1355 		 * NB - preserve newlines, they are needed to reproduce
1356 		 * line numbers later for error messages
1357 		 */
1358 		if ((cp = strchr(line, '#')) != NULL)
1359 			memcpy(cp, "\n", 2);
1360 		cp = line + strspn(line, " \t\r");
1361 
1362 		buffer_append(conf, cp, strlen(cp));
1363 	}
1364 	buffer_append(conf, "\0", 1);
1365 	fclose(f);
1366 	debug2("%s: done config len = %d", __func__, buffer_len(conf));
1367 }
1368 
1369 void
1370 parse_server_match_config(ServerOptions *options, const char *user,
1371     const char *host, const char *address)
1372 {
1373 	ServerOptions mo;
1374 
1375 	initialize_server_options(&mo);
1376 	parse_server_config(&mo, "reprocess config", &cfg, user, host, address);
1377 	copy_set_server_options(options, &mo, 0);
1378 }
1379 
1380 /* Helper macros */
1381 #define M_CP_INTOPT(n) do {\
1382 	if (src->n != -1) \
1383 		dst->n = src->n; \
1384 } while (0)
1385 #define M_CP_STROPT(n) do {\
1386 	if (src->n != NULL) { \
1387 		if (dst->n != NULL) \
1388 			xfree(dst->n); \
1389 		dst->n = src->n; \
1390 	} \
1391 } while(0)
1392 
1393 /*
1394  * Copy any supported values that are set.
1395  *
1396  * If the preauth flag is set, we do not bother copying the the string or
1397  * array values that are not used pre-authentication, because any that we
1398  * do use must be explictly sent in mm_getpwnamallow().
1399  */
1400 void
1401 copy_set_server_options(ServerOptions *dst, ServerOptions *src, int preauth)
1402 {
1403 	M_CP_INTOPT(password_authentication);
1404 	M_CP_INTOPT(gss_authentication);
1405 	M_CP_INTOPT(rsa_authentication);
1406 	M_CP_INTOPT(pubkey_authentication);
1407 	M_CP_INTOPT(kerberos_authentication);
1408 	M_CP_INTOPT(hostbased_authentication);
1409 	M_CP_INTOPT(kbd_interactive_authentication);
1410 	M_CP_INTOPT(zero_knowledge_password_authentication);
1411 	M_CP_INTOPT(permit_root_login);
1412 	M_CP_INTOPT(permit_empty_passwd);
1413 
1414 	M_CP_INTOPT(allow_tcp_forwarding);
1415 	M_CP_INTOPT(allow_agent_forwarding);
1416 	M_CP_INTOPT(gateway_ports);
1417 	M_CP_INTOPT(x11_display_offset);
1418 	M_CP_INTOPT(x11_forwarding);
1419 	M_CP_INTOPT(x11_use_localhost);
1420 	M_CP_INTOPT(max_sessions);
1421 	M_CP_INTOPT(max_authtries);
1422 
1423 	M_CP_STROPT(banner);
1424 	if (preauth)
1425 		return;
1426 	M_CP_STROPT(adm_forced_command);
1427 	M_CP_STROPT(chroot_directory);
1428 }
1429 
1430 #undef M_CP_INTOPT
1431 #undef M_CP_STROPT
1432 
1433 void
1434 parse_server_config(ServerOptions *options, const char *filename, Buffer *conf,
1435     const char *user, const char *host, const char *address)
1436 {
1437 	int active, linenum, bad_options = 0;
1438 	char *cp, *obuf, *cbuf;
1439 
1440 	debug2("%s: config %s len %d", __func__, filename, buffer_len(conf));
1441 
1442 	obuf = cbuf = xstrdup(buffer_ptr(conf));
1443 	active = user ? 0 : 1;
1444 	linenum = 1;
1445 	while ((cp = strsep(&cbuf, "\n")) != NULL) {
1446 		if (process_server_config_line(options, cp, filename,
1447 		    linenum++, &active, user, host, address) != 0)
1448 			bad_options++;
1449 	}
1450 	xfree(obuf);
1451 	if (bad_options > 0)
1452 		fatal("%s: terminating, %d bad configuration options",
1453 		    filename, bad_options);
1454 }
1455 
1456 static const char *
1457 fmt_intarg(ServerOpCodes code, int val)
1458 {
1459 	if (code == sAddressFamily) {
1460 		switch (val) {
1461 		case AF_INET:
1462 			return "inet";
1463 		case AF_INET6:
1464 			return "inet6";
1465 		case AF_UNSPEC:
1466 			return "any";
1467 		default:
1468 			return "UNKNOWN";
1469 		}
1470 	}
1471 	if (code == sPermitRootLogin) {
1472 		switch (val) {
1473 		case PERMIT_NO_PASSWD:
1474 			return "without-password";
1475 		case PERMIT_FORCED_ONLY:
1476 			return "forced-commands-only";
1477 		case PERMIT_YES:
1478 			return "yes";
1479 		}
1480 	}
1481 	if (code == sProtocol) {
1482 		switch (val) {
1483 		case SSH_PROTO_1:
1484 			return "1";
1485 		case SSH_PROTO_2:
1486 			return "2";
1487 		case (SSH_PROTO_1|SSH_PROTO_2):
1488 			return "2,1";
1489 		default:
1490 			return "UNKNOWN";
1491 		}
1492 	}
1493 	if (code == sGatewayPorts && val == 2)
1494 		return "clientspecified";
1495 	if (code == sCompression && val == COMP_DELAYED)
1496 		return "delayed";
1497 	switch (val) {
1498 	case -1:
1499 		return "unset";
1500 	case 0:
1501 		return "no";
1502 	case 1:
1503 		return "yes";
1504 	}
1505 	return "UNKNOWN";
1506 }
1507 
1508 static const char *
1509 lookup_opcode_name(ServerOpCodes code)
1510 {
1511 	u_int i;
1512 
1513 	for (i = 0; keywords[i].name != NULL; i++)
1514 		if (keywords[i].opcode == code)
1515 			return(keywords[i].name);
1516 	return "UNKNOWN";
1517 }
1518 
1519 static void
1520 dump_cfg_int(ServerOpCodes code, int val)
1521 {
1522 	printf("%s %d\n", lookup_opcode_name(code), val);
1523 }
1524 
1525 static void
1526 dump_cfg_fmtint(ServerOpCodes code, int val)
1527 {
1528 	printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
1529 }
1530 
1531 static void
1532 dump_cfg_string(ServerOpCodes code, const char *val)
1533 {
1534 	if (val == NULL)
1535 		return;
1536 	printf("%s %s\n", lookup_opcode_name(code), val);
1537 }
1538 
1539 static void
1540 dump_cfg_strarray(ServerOpCodes code, u_int count, char **vals)
1541 {
1542 	u_int i;
1543 
1544 	for (i = 0; i < count; i++)
1545 		printf("%s %s\n", lookup_opcode_name(code),  vals[i]);
1546 }
1547 
1548 void
1549 dump_config(ServerOptions *o)
1550 {
1551 	u_int i;
1552 	int ret;
1553 	struct addrinfo *ai;
1554 	char addr[NI_MAXHOST], port[NI_MAXSERV], *s = NULL;
1555 
1556 	/* these are usually at the top of the config */
1557 	for (i = 0; i < o->num_ports; i++)
1558 		printf("port %d\n", o->ports[i]);
1559 	dump_cfg_fmtint(sProtocol, o->protocol);
1560 	dump_cfg_fmtint(sAddressFamily, o->address_family);
1561 
1562 	/* ListenAddress must be after Port */
1563 	for (ai = o->listen_addrs; ai; ai = ai->ai_next) {
1564 		if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1565 		    sizeof(addr), port, sizeof(port),
1566 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1567 			error("getnameinfo failed: %.100s",
1568 			    (ret != EAI_SYSTEM) ? gai_strerror(ret) :
1569 			    strerror(errno));
1570 		} else {
1571 			if (ai->ai_family == AF_INET6)
1572 				printf("listenaddress [%s]:%s\n", addr, port);
1573 			else
1574 				printf("listenaddress %s:%s\n", addr, port);
1575 		}
1576 	}
1577 
1578 	/* integer arguments */
1579 #ifdef USE_PAM
1580 	dump_cfg_int(sUsePAM, o->use_pam);
1581 #endif
1582 	dump_cfg_int(sServerKeyBits, o->server_key_bits);
1583 	dump_cfg_int(sLoginGraceTime, o->login_grace_time);
1584 	dump_cfg_int(sKeyRegenerationTime, o->key_regeneration_time);
1585 	dump_cfg_int(sX11DisplayOffset, o->x11_display_offset);
1586 	dump_cfg_int(sMaxAuthTries, o->max_authtries);
1587 	dump_cfg_int(sMaxSessions, o->max_sessions);
1588 	dump_cfg_int(sClientAliveInterval, o->client_alive_interval);
1589 	dump_cfg_int(sClientAliveCountMax, o->client_alive_count_max);
1590 
1591 	/* formatted integer arguments */
1592 	dump_cfg_fmtint(sPermitRootLogin, o->permit_root_login);
1593 	dump_cfg_fmtint(sIgnoreRhosts, o->ignore_rhosts);
1594 	dump_cfg_fmtint(sIgnoreUserKnownHosts, o->ignore_user_known_hosts);
1595 	dump_cfg_fmtint(sRhostsRSAAuthentication, o->rhosts_rsa_authentication);
1596 	dump_cfg_fmtint(sHostbasedAuthentication, o->hostbased_authentication);
1597 	dump_cfg_fmtint(sHostbasedUsesNameFromPacketOnly,
1598 	    o->hostbased_uses_name_from_packet_only);
1599 	dump_cfg_fmtint(sRSAAuthentication, o->rsa_authentication);
1600 	dump_cfg_fmtint(sPubkeyAuthentication, o->pubkey_authentication);
1601 #ifdef KRB5
1602 	dump_cfg_fmtint(sKerberosAuthentication, o->kerberos_authentication);
1603 	dump_cfg_fmtint(sKerberosOrLocalPasswd, o->kerberos_or_local_passwd);
1604 	dump_cfg_fmtint(sKerberosTicketCleanup, o->kerberos_ticket_cleanup);
1605 # ifdef USE_AFS
1606 	dump_cfg_fmtint(sKerberosGetAFSToken, o->kerberos_get_afs_token);
1607 # endif
1608 #endif
1609 #ifdef GSSAPI
1610 	dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
1611 	dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
1612 #endif
1613 #ifdef JPAKE
1614 	dump_cfg_fmtint(sZeroKnowledgePasswordAuthentication,
1615 	    o->zero_knowledge_password_authentication);
1616 #endif
1617 	dump_cfg_fmtint(sPasswordAuthentication, o->password_authentication);
1618 	dump_cfg_fmtint(sKbdInteractiveAuthentication,
1619 	    o->kbd_interactive_authentication);
1620 	dump_cfg_fmtint(sChallengeResponseAuthentication,
1621 	    o->challenge_response_authentication);
1622 	dump_cfg_fmtint(sPrintMotd, o->print_motd);
1623 	dump_cfg_fmtint(sPrintLastLog, o->print_lastlog);
1624 	dump_cfg_fmtint(sX11Forwarding, o->x11_forwarding);
1625 	dump_cfg_fmtint(sX11UseLocalhost, o->x11_use_localhost);
1626 	dump_cfg_fmtint(sStrictModes, o->strict_modes);
1627 	dump_cfg_fmtint(sTCPKeepAlive, o->tcp_keep_alive);
1628 	dump_cfg_fmtint(sEmptyPasswd, o->permit_empty_passwd);
1629 	dump_cfg_fmtint(sPermitUserEnvironment, o->permit_user_env);
1630 	dump_cfg_fmtint(sUseLogin, o->use_login);
1631 	dump_cfg_fmtint(sCompression, o->compression);
1632 	dump_cfg_fmtint(sGatewayPorts, o->gateway_ports);
1633 	dump_cfg_fmtint(sUseDNS, o->use_dns);
1634 	dump_cfg_fmtint(sAllowTcpForwarding, o->allow_tcp_forwarding);
1635 	dump_cfg_fmtint(sUsePrivilegeSeparation, use_privsep);
1636 
1637 	/* string arguments */
1638 	dump_cfg_string(sPidFile, o->pid_file);
1639 	dump_cfg_string(sXAuthLocation, o->xauth_location);
1640 	dump_cfg_string(sCiphers, o->ciphers);
1641 	dump_cfg_string(sMacs, o->macs);
1642 	dump_cfg_string(sBanner, o->banner);
1643 	dump_cfg_string(sAuthorizedKeysFile, o->authorized_keys_file);
1644 	dump_cfg_string(sAuthorizedKeysFile2, o->authorized_keys_file2);
1645 	dump_cfg_string(sForceCommand, o->adm_forced_command);
1646 
1647 	/* string arguments requiring a lookup */
1648 	dump_cfg_string(sLogLevel, log_level_name(o->log_level));
1649 	dump_cfg_string(sLogFacility, log_facility_name(o->log_facility));
1650 
1651 	/* string array arguments */
1652 	dump_cfg_strarray(sHostKeyFile, o->num_host_key_files,
1653 	     o->host_key_files);
1654 	dump_cfg_strarray(sAllowUsers, o->num_allow_users, o->allow_users);
1655 	dump_cfg_strarray(sDenyUsers, o->num_deny_users, o->deny_users);
1656 	dump_cfg_strarray(sAllowGroups, o->num_allow_groups, o->allow_groups);
1657 	dump_cfg_strarray(sDenyGroups, o->num_deny_groups, o->deny_groups);
1658 	dump_cfg_strarray(sAcceptEnv, o->num_accept_env, o->accept_env);
1659 
1660 	/* other arguments */
1661 	for (i = 0; i < o->num_subsystems; i++)
1662 		printf("subsystem %s %s\n", o->subsystem_name[i],
1663 		    o->subsystem_args[i]);
1664 
1665 	printf("maxstartups %d:%d:%d\n", o->max_startups_begin,
1666 	    o->max_startups_rate, o->max_startups);
1667 
1668 	for (i = 0; tunmode_desc[i].val != -1; i++)
1669 		if (tunmode_desc[i].val == o->permit_tun) {
1670 			s = tunmode_desc[i].text;
1671 			break;
1672 		}
1673 	dump_cfg_string(sPermitTunnel, s);
1674 
1675 	channel_print_adm_permitted_opens();
1676 }
1677