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