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