xref: /netbsd-src/crypto/external/bsd/openssh/dist/servconf.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: servconf.c,v 1.28 2018/06/07 15:26:09 riastradh Exp $	*/
2 
3 /* $OpenBSD: servconf.c,v 1.326 2018/03/01 20:32:16 markus Exp $ */
4 /*
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  *
8  * As far as I am concerned, the code I have written for this software
9  * can be used freely for any purpose.  Any derived versions of this
10  * software must be clearly marked as such, and if the derived work is
11  * incompatible with the protocol description in the RFC file, it must be
12  * called by a name other than "ssh" or "Secure Shell".
13  */
14 
15 #include "includes.h"
16 __RCSID("$NetBSD: servconf.c,v 1.28 2018/06/07 15:26:09 riastradh Exp $");
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <sys/queue.h>
20 #include <sys/param.h>
21 #include <sys/sysctl.h>
22 
23 #include <netinet/in.h>
24 #include <netinet/ip.h>
25 #include <net/route.h>
26 
27 #include <ctype.h>
28 #include <netdb.h>
29 #include <pwd.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <signal.h>
34 #include <unistd.h>
35 #include <limits.h>
36 #include <stdarg.h>
37 #include <errno.h>
38 #include <util.h>
39 #include <time.h>
40 
41 #ifdef KRB4
42 #include <krb.h>
43 #ifdef AFS
44 #include <kafs.h>
45 #endif /* AFS */
46 #endif /* KRB4 */
47 
48 #include "xmalloc.h"
49 #include "ssh.h"
50 #include "log.h"
51 #include "buffer.h"
52 #include "misc.h"
53 #include "servconf.h"
54 #include "compat.h"
55 #include "pathnames.h"
56 #include "cipher.h"
57 #include "key.h"
58 #include "kex.h"
59 #include "mac.h"
60 #include "match.h"
61 #include "channels.h"
62 #include "groupaccess.h"
63 #include "canohost.h"
64 #include "packet.h"
65 #include "hostfile.h"
66 #include "auth.h"
67 #include "fmt_scaled.h"
68 
69 #ifdef WITH_LDAP_PUBKEY
70 #include "ldapauth.h"
71 #endif
72 #include "myproposal.h"
73 #include "digest.h"
74 
75 static void add_listen_addr(ServerOptions *, const char *,
76     const char *, int);
77 static void add_one_listen_addr(ServerOptions *, const char *,
78     const char *, int);
79 
80 /* Use of privilege separation or not */
81 extern int use_privsep;
82 extern Buffer cfg;
83 
84 /* Initializes the server options to their default values. */
85 
86 void
87 initialize_server_options(ServerOptions *options)
88 {
89 	memset(options, 0, sizeof(*options));
90 
91 	/* Portable-specific options */
92 	options->use_pam = -1;
93 
94 	/* Standard Options */
95 	options->num_ports = 0;
96 	options->ports_from_cmdline = 0;
97 	options->queued_listen_addrs = NULL;
98 	options->num_queued_listens = 0;
99 	options->listen_addrs = NULL;
100 	options->num_listen_addrs = 0;
101 	options->address_family = -1;
102 	options->routing_domain = NULL;
103 	options->num_host_key_files = 0;
104 	options->num_host_cert_files = 0;
105 	options->host_key_agent = NULL;
106 	options->pid_file = NULL;
107 	options->login_grace_time = -1;
108 	options->permit_root_login = PERMIT_NOT_SET;
109 	options->ignore_rhosts = -1;
110 	options->ignore_root_rhosts = -1;
111 	options->ignore_user_known_hosts = -1;
112 	options->print_motd = -1;
113 	options->print_lastlog = -1;
114 	options->x11_forwarding = -1;
115 	options->x11_display_offset = -1;
116 	options->x11_use_localhost = -1;
117 	options->permit_tty = -1;
118 	options->permit_user_rc = -1;
119 	options->xauth_location = NULL;
120 	options->strict_modes = -1;
121 	options->tcp_keep_alive = -1;
122 	options->log_facility = SYSLOG_FACILITY_NOT_SET;
123 	options->log_level = SYSLOG_LEVEL_NOT_SET;
124 	options->hostbased_authentication = -1;
125 	options->hostbased_uses_name_from_packet_only = -1;
126 	options->hostbased_key_types = NULL;
127 	options->hostkeyalgorithms = NULL;
128 	options->pubkey_authentication = -1;
129 	options->pubkey_key_types = NULL;
130 	options->kerberos_authentication = -1;
131 	options->kerberos_or_local_passwd = -1;
132 	options->kerberos_ticket_cleanup = -1;
133 #if defined(AFS) || defined(KRB5)
134 	options->kerberos_tgt_passing = -1;
135 #endif
136 #ifdef AFS
137 	options->afs_token_passing = -1;
138 #endif
139 	options->kerberos_get_afs_token = -1;
140 	options->gss_authentication=-1;
141 	options->gss_cleanup_creds = -1;
142 	options->gss_strict_acceptor = -1;
143 	options->password_authentication = -1;
144 	options->kbd_interactive_authentication = -1;
145 	options->challenge_response_authentication = -1;
146 	options->permit_empty_passwd = -1;
147 	options->permit_user_env = -1;
148 	options->compression = -1;
149 	options->rekey_limit = -1;
150 	options->rekey_interval = -1;
151 	options->allow_tcp_forwarding = -1;
152 	options->allow_streamlocal_forwarding = -1;
153 	options->allow_agent_forwarding = -1;
154 	options->num_allow_users = 0;
155 	options->num_deny_users = 0;
156 	options->num_allow_groups = 0;
157 	options->num_deny_groups = 0;
158 	options->ciphers = NULL;
159 #ifdef WITH_LDAP_PUBKEY
160 	/* XXX dirty */
161 	options->lpk.ld = NULL;
162 	options->lpk.on = -1;
163 	options->lpk.servers = NULL;
164 	options->lpk.u_basedn = NULL;
165 	options->lpk.g_basedn = NULL;
166 	options->lpk.binddn = NULL;
167 	options->lpk.bindpw = NULL;
168 	options->lpk.sgroup = NULL;
169 	options->lpk.filter = NULL;
170 	options->lpk.fgroup = NULL;
171 	options->lpk.l_conf = NULL;
172 	options->lpk.tls = -1;
173 	options->lpk.b_timeout.tv_sec = -1;
174 	options->lpk.s_timeout.tv_sec = -1;
175 	options->lpk.flags = FLAG_EMPTY;
176 	options->lpk.pub_key_attr = NULL;
177 #endif
178 	options->macs = NULL;
179 	options->kex_algorithms = NULL;
180 	options->fwd_opts.gateway_ports = -1;
181 	options->fwd_opts.streamlocal_bind_mask = (mode_t)-1;
182 	options->fwd_opts.streamlocal_bind_unlink = -1;
183 	options->num_subsystems = 0;
184 	options->max_startups_begin = -1;
185 	options->max_startups_rate = -1;
186 	options->max_startups = -1;
187 	options->max_authtries = -1;
188 	options->max_sessions = -1;
189 	options->banner = NULL;
190 	options->use_dns = -1;
191 	options->client_alive_interval = -1;
192 	options->client_alive_count_max = -1;
193 	options->num_authkeys_files = 0;
194 	options->num_accept_env = 0;
195 	options->permit_tun = -1;
196 	options->permitted_opens = NULL;
197 	options->adm_forced_command = NULL;
198 	options->chroot_directory = NULL;
199 	options->authorized_keys_command = NULL;
200 	options->authorized_keys_command_user = NULL;
201 	options->revoked_keys_file = NULL;
202 	options->trusted_user_ca_keys = NULL;
203 	options->authorized_principals_file = NULL;
204 	options->authorized_principals_command = NULL;
205 	options->authorized_principals_command_user = NULL;
206 	options->ip_qos_interactive = -1;
207 	options->ip_qos_bulk = -1;
208 	options->version_addendum = NULL;
209 	options->fingerprint_hash = -1;
210 	options->disable_forwarding = -1;
211 	options->expose_userauth_info = -1;
212 	options->none_enabled = -1;
213 	options->tcp_rcv_buf_poll = -1;
214 	options->hpn_disabled = -1;
215 	options->hpn_buffer_size = -1;
216 }
217 
218 /* Returns 1 if a string option is unset or set to "none" or 0 otherwise. */
219 static int
220 option_clear_or_none(const char *o)
221 {
222 	return o == NULL || strcasecmp(o, "none") == 0;
223 }
224 
225 static void
226 assemble_algorithms(ServerOptions *o)
227 {
228 	if (kex_assemble_names(KEX_SERVER_ENCRYPT, &o->ciphers) != 0 ||
229 	    kex_assemble_names(KEX_SERVER_MAC, &o->macs) != 0 ||
230 	    kex_assemble_names(KEX_SERVER_KEX, &o->kex_algorithms) != 0 ||
231 	    kex_assemble_names(KEX_DEFAULT_PK_ALG,
232 	    &o->hostkeyalgorithms) != 0 ||
233 	    kex_assemble_names(KEX_DEFAULT_PK_ALG,
234 	    &o->hostbased_key_types) != 0 ||
235 	    kex_assemble_names(KEX_DEFAULT_PK_ALG, &o->pubkey_key_types) != 0)
236 		fatal("kex_assemble_names failed");
237 }
238 
239 static void
240 array_append(const char *file, const int line, const char *directive,
241     char ***array, u_int *lp, const char *s)
242 {
243 
244 	if (*lp >= INT_MAX)
245 		fatal("%s line %d: Too many %s entries", file, line, directive);
246 
247 	*array = xrecallocarray(*array, *lp, *lp + 1, sizeof(**array));
248 	(*array)[*lp] = xstrdup(s);
249 	(*lp)++;
250 }
251 
252 void
253 servconf_add_hostkey(const char *file, const int line,
254     ServerOptions *options, const char *path)
255 {
256 	char *apath = derelativise_path(path);
257 
258 	array_append(file, line, "HostKey",
259 	    &options->host_key_files, &options->num_host_key_files, apath);
260 	free(apath);
261 }
262 
263 void
264 servconf_add_hostcert(const char *file, const int line,
265     ServerOptions *options, const char *path)
266 {
267 	char *apath = derelativise_path(path);
268 
269 	array_append(file, line, "HostCertificate",
270 	    &options->host_cert_files, &options->num_host_cert_files, apath);
271 	free(apath);
272 }
273 
274 void
275 fill_default_server_options(ServerOptions *options)
276 {
277 	/* needed for hpn socket tests */
278 	int sock;
279 	int socksize;
280 	socklen_t socksizelen = sizeof(int);
281 
282 	/* Portable-specific options */
283 	if (options->use_pam == -1)
284 		options->use_pam = 0;
285 
286 	/* Standard Options */
287 	u_int i;
288 
289 	if (options->num_host_key_files == 0) {
290 		/* fill default hostkeys */
291 		servconf_add_hostkey("[default]", 0, options,
292 		    _PATH_HOST_RSA_KEY_FILE);
293 		servconf_add_hostkey("[default]", 0, options,
294 		    _PATH_HOST_ECDSA_KEY_FILE);
295 		servconf_add_hostkey("[default]", 0, options,
296 		    _PATH_HOST_ED25519_KEY_FILE);
297 	}
298 	/* No certificates by default */
299 	if (options->num_ports == 0)
300 		options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
301 	if (options->address_family == -1)
302 		options->address_family = AF_UNSPEC;
303 	if (options->listen_addrs == NULL)
304 		add_listen_addr(options, NULL, NULL, 0);
305 	if (options->pid_file == NULL)
306 		options->pid_file = xstrdup(_PATH_SSH_DAEMON_PID_FILE);
307 	if (options->login_grace_time == -1)
308 		options->login_grace_time = 120;
309 	if (options->permit_root_login == PERMIT_NOT_SET)
310 		options->permit_root_login = PERMIT_NO_PASSWD;
311 	if (options->ignore_rhosts == -1)
312 		options->ignore_rhosts = 1;
313 	if (options->ignore_root_rhosts == -1)
314 		options->ignore_root_rhosts = options->ignore_rhosts;
315 	if (options->ignore_user_known_hosts == -1)
316 		options->ignore_user_known_hosts = 0;
317 	if (options->print_motd == -1)
318 		options->print_motd = 1;
319 	if (options->print_lastlog == -1)
320 		options->print_lastlog = 1;
321 	if (options->x11_forwarding == -1)
322 		options->x11_forwarding = 0;
323 	if (options->x11_display_offset == -1)
324 		options->x11_display_offset = 10;
325 	if (options->x11_use_localhost == -1)
326 		options->x11_use_localhost = 1;
327 	if (options->xauth_location == NULL)
328 		options->xauth_location = xstrdup(_PATH_XAUTH);
329 	if (options->permit_tty == -1)
330 		options->permit_tty = 1;
331 	if (options->permit_user_rc == -1)
332 		options->permit_user_rc = 1;
333 	if (options->strict_modes == -1)
334 		options->strict_modes = 1;
335 	if (options->tcp_keep_alive == -1)
336 		options->tcp_keep_alive = 1;
337 	if (options->log_facility == SYSLOG_FACILITY_NOT_SET)
338 		options->log_facility = SYSLOG_FACILITY_AUTH;
339 	if (options->log_level == SYSLOG_LEVEL_NOT_SET)
340 		options->log_level = SYSLOG_LEVEL_INFO;
341 	if (options->hostbased_authentication == -1)
342 		options->hostbased_authentication = 0;
343 	if (options->hostbased_uses_name_from_packet_only == -1)
344 		options->hostbased_uses_name_from_packet_only = 0;
345 	if (options->pubkey_authentication == -1)
346 		options->pubkey_authentication = 1;
347 	if (options->kerberos_authentication == -1)
348 		options->kerberos_authentication = 0;
349 	if (options->kerberos_or_local_passwd == -1)
350 		options->kerberos_or_local_passwd = 1;
351 	if (options->kerberos_ticket_cleanup == -1)
352 		options->kerberos_ticket_cleanup = 1;
353 #if defined(AFS) || defined(KRB5)
354 	if (options->kerberos_tgt_passing == -1)
355 		options->kerberos_tgt_passing = 0;
356 #endif
357 #ifdef AFS
358 	if (options->afs_token_passing == -1)
359 		options->afs_token_passing = 0;
360 #endif
361 	if (options->kerberos_get_afs_token == -1)
362 		options->kerberos_get_afs_token = 0;
363 	if (options->gss_authentication == -1)
364 		options->gss_authentication = 0;
365 	if (options->gss_cleanup_creds == -1)
366 		options->gss_cleanup_creds = 1;
367 	if (options->gss_strict_acceptor == -1)
368 		options->gss_strict_acceptor = 1;
369 	if (options->password_authentication == -1)
370 		options->password_authentication = 1;
371 	if (options->kbd_interactive_authentication == -1)
372 		options->kbd_interactive_authentication = 0;
373 	if (options->challenge_response_authentication == -1)
374 		options->challenge_response_authentication = 1;
375 	if (options->permit_empty_passwd == -1)
376 		options->permit_empty_passwd = 0;
377 	if (options->permit_user_env == -1)
378 		options->permit_user_env = 0;
379 	if (options->compression == -1)
380 		options->compression = COMP_DELAYED;
381 	if (options->rekey_limit == -1)
382 		options->rekey_limit = 0;
383 	if (options->rekey_interval == -1)
384 		options->rekey_interval = 0;
385 	if (options->allow_tcp_forwarding == -1)
386 		options->allow_tcp_forwarding = FORWARD_ALLOW;
387 	if (options->allow_streamlocal_forwarding == -1)
388 		options->allow_streamlocal_forwarding = FORWARD_ALLOW;
389 	if (options->allow_agent_forwarding == -1)
390 		options->allow_agent_forwarding = 1;
391 	if (options->fwd_opts.gateway_ports == -1)
392 		options->fwd_opts.gateway_ports = 0;
393 	if (options->max_startups == -1)
394 		options->max_startups = 100;
395 	if (options->max_startups_rate == -1)
396 		options->max_startups_rate = 30;		/* 30% */
397 	if (options->max_startups_begin == -1)
398 		options->max_startups_begin = 10;
399 	if (options->max_authtries == -1)
400 		options->max_authtries = DEFAULT_AUTH_FAIL_MAX;
401 	if (options->max_sessions == -1)
402 		options->max_sessions = DEFAULT_SESSIONS_MAX;
403 	if (options->use_dns == -1)
404 		options->use_dns = 0;
405 	if (options->client_alive_interval == -1)
406 		options->client_alive_interval = 0;
407 	if (options->client_alive_count_max == -1)
408 		options->client_alive_count_max = 3;
409 	if (options->num_authkeys_files == 0) {
410 		array_append("[default]", 0, "AuthorizedKeysFiles",
411 		    &options->authorized_keys_files,
412 		    &options->num_authkeys_files,
413 		    _PATH_SSH_USER_PERMITTED_KEYS);
414 		array_append("[default]", 0, "AuthorizedKeysFiles",
415 		    &options->authorized_keys_files,
416 		    &options->num_authkeys_files,
417 		    _PATH_SSH_USER_PERMITTED_KEYS2);
418 	}
419 	if (options->permit_tun == -1)
420 		options->permit_tun = SSH_TUNMODE_NO;
421 	if (options->ip_qos_interactive == -1)
422 		options->ip_qos_interactive = IPTOS_LOWDELAY;
423 	if (options->ip_qos_bulk == -1)
424 		options->ip_qos_bulk = IPTOS_THROUGHPUT;
425 	if (options->version_addendum == NULL)
426 		options->version_addendum = xstrdup("");
427 
428 	if (options->hpn_disabled == -1)
429 		options->hpn_disabled = 0;
430 
431 	if (options->hpn_buffer_size == -1) {
432 		/* option not explicitly set. Now we have to figure out */
433 		/* what value to use */
434 		if (options->hpn_disabled == 1) {
435 			options->hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
436 		} else {
437 			/* get the current RCV size and set it to that */
438 			/*create a socket but don't connect it */
439 			/* we use that the get the rcv socket size */
440 			sock = socket(AF_INET, SOCK_STREAM, 0);
441 			getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
442 				   &socksize, &socksizelen);
443 			close(sock);
444 			options->hpn_buffer_size = socksize;
445 			debug ("HPN Buffer Size: %d", options->hpn_buffer_size);
446 
447 		}
448 	} else {
449 		/* we have to do this incase the user sets both values in a contradictory */
450 		/* manner. hpn_disabled overrrides hpn_buffer_size*/
451 		if (options->hpn_disabled <= 0) {
452 			if (options->hpn_buffer_size == 0)
453 				options->hpn_buffer_size = 1;
454 			/* limit the maximum buffer to 64MB */
455 			if (options->hpn_buffer_size > 64*1024) {
456 				options->hpn_buffer_size = 64*1024*1024;
457 			} else {
458 				options->hpn_buffer_size *= 1024;
459 			}
460 		} else
461 			options->hpn_buffer_size = CHAN_TCP_WINDOW_DEFAULT;
462 	}
463 
464 #ifdef WITH_LDAP_PUBKEY
465 	if (options->lpk.on == -1)
466 	    options->lpk.on = _DEFAULT_LPK_ON;
467 	if (options->lpk.servers == NULL)
468 	    options->lpk.servers = _DEFAULT_LPK_SERVERS;
469 	if (options->lpk.u_basedn == NULL)
470 	    options->lpk.u_basedn = _DEFAULT_LPK_UDN;
471 	if (options->lpk.g_basedn == NULL)
472 	    options->lpk.g_basedn = _DEFAULT_LPK_GDN;
473 	if (options->lpk.binddn == NULL)
474 	    options->lpk.binddn = _DEFAULT_LPK_BINDDN;
475 	if (options->lpk.bindpw == NULL)
476 	    options->lpk.bindpw = _DEFAULT_LPK_BINDPW;
477 	if (options->lpk.sgroup == NULL)
478 	    options->lpk.sgroup = _DEFAULT_LPK_SGROUP;
479 	if (options->lpk.filter == NULL)
480 	    options->lpk.filter = _DEFAULT_LPK_FILTER;
481 	if (options->lpk.tls == -1)
482 	    options->lpk.tls = _DEFAULT_LPK_TLS;
483 	if (options->lpk.b_timeout.tv_sec == -1)
484 	    options->lpk.b_timeout.tv_sec = _DEFAULT_LPK_BTIMEOUT;
485 	if (options->lpk.s_timeout.tv_sec == -1)
486 	    options->lpk.s_timeout.tv_sec = _DEFAULT_LPK_STIMEOUT;
487 	if (options->lpk.l_conf == NULL)
488 	    options->lpk.l_conf = _DEFAULT_LPK_LDP;
489 	if (options->lpk.pub_key_attr == NULL)
490 	    options->lpk.pub_key_attr = __UNCONST(_DEFAULT_LPK_PUB);
491 #endif
492 
493 	if (options->fwd_opts.streamlocal_bind_mask == (mode_t)-1)
494 		options->fwd_opts.streamlocal_bind_mask = 0177;
495 	if (options->fwd_opts.streamlocal_bind_unlink == -1)
496 		options->fwd_opts.streamlocal_bind_unlink = 0;
497 	if (options->fingerprint_hash == -1)
498 		options->fingerprint_hash = SSH_FP_HASH_DEFAULT;
499 	if (options->disable_forwarding == -1)
500 		options->disable_forwarding = 0;
501 	if (options->expose_userauth_info == -1)
502 		options->expose_userauth_info = 0;
503 
504 	assemble_algorithms(options);
505 
506 	/* Turn privilege separation and sandboxing on by default */
507 	if (use_privsep == -1)
508 		use_privsep = PRIVSEP_ON;
509 
510 #define CLEAR_ON_NONE(v) \
511 	do { \
512 		if (option_clear_or_none(v)) { \
513 			free(v); \
514 			v = NULL; \
515 		} \
516 	} while(0)
517 	CLEAR_ON_NONE(options->pid_file);
518 	CLEAR_ON_NONE(options->xauth_location);
519 	CLEAR_ON_NONE(options->banner);
520 	CLEAR_ON_NONE(options->trusted_user_ca_keys);
521 	CLEAR_ON_NONE(options->revoked_keys_file);
522 	CLEAR_ON_NONE(options->authorized_principals_file);
523 	CLEAR_ON_NONE(options->adm_forced_command);
524 	CLEAR_ON_NONE(options->chroot_directory);
525 	CLEAR_ON_NONE(options->routing_domain);
526 	for (i = 0; i < options->num_host_key_files; i++)
527 		CLEAR_ON_NONE(options->host_key_files[i]);
528 	for (i = 0; i < options->num_host_cert_files; i++)
529 		CLEAR_ON_NONE(options->host_cert_files[i]);
530 #undef CLEAR_ON_NONE
531 
532 	/* Similar handling for AuthenticationMethods=any */
533 	if (options->num_auth_methods == 1 &&
534 	    strcmp(options->auth_methods[0], "any") == 0) {
535 		free(options->auth_methods[0]);
536 		options->auth_methods[0] = NULL;
537 		options->num_auth_methods = 0;
538 	}
539 
540 }
541 
542 /* Keyword tokens. */
543 typedef enum {
544 	sBadOption,		/* == unknown option */
545 	sUsePAM,
546 	sPort, sHostKeyFile, sLoginGraceTime,
547 	sPermitRootLogin, sLogFacility, sLogLevel,
548 	sKerberosAuthentication, sKerberosOrLocalPasswd, sKerberosTicketCleanup,
549 	sKerberosGetAFSToken,
550 	sKerberosTgtPassing, sChallengeResponseAuthentication,
551 	sPasswordAuthentication, sKbdInteractiveAuthentication,
552 	sListenAddress, sAddressFamily,
553 	sPrintMotd, sPrintLastLog, sIgnoreRhosts,
554 	sX11Forwarding, sX11DisplayOffset, sX11UseLocalhost,
555 	sPermitTTY, sStrictModes, sEmptyPasswd, sTCPKeepAlive,
556 	sPermitUserEnvironment, sAllowTcpForwarding, sCompression,
557 	sRekeyLimit, sAllowUsers, sDenyUsers, sAllowGroups, sDenyGroups,
558 	sIgnoreUserKnownHosts, sCiphers, sMacs, sPidFile,
559 	sGatewayPorts, sPubkeyAuthentication, sPubkeyAcceptedKeyTypes,
560 	sXAuthLocation, sSubsystem, sMaxStartups, sMaxAuthTries, sMaxSessions,
561 	sBanner, sUseDNS, sHostbasedAuthentication,
562 	sHostbasedUsesNameFromPacketOnly, sHostbasedAcceptedKeyTypes,
563 	sHostKeyAlgorithms,
564 	sClientAliveInterval, sClientAliveCountMax, sAuthorizedKeysFile,
565 	sGssAuthentication, sGssCleanupCreds, sGssStrictAcceptor,
566 	sAcceptEnv, sPermitTunnel,
567 	sMatch, sPermitOpen, sForceCommand, sChrootDirectory,
568 	sUsePrivilegeSeparation, sAllowAgentForwarding,
569 	sHostCertificate,
570 	sRevokedKeys, sTrustedUserCAKeys, sAuthorizedPrincipalsFile,
571 	sAuthorizedPrincipalsCommand, sAuthorizedPrincipalsCommandUser,
572 	sKexAlgorithms, sIPQoS, sVersionAddendum,
573 	sIgnoreRootRhosts,
574 	sNoneEnabled, sTcpRcvBufPoll,sHPNDisabled, sHPNBufferSize,
575 	sAuthorizedKeysCommand, sAuthorizedKeysCommandUser,
576 	sAuthenticationMethods, sHostKeyAgent, sPermitUserRC,
577 	sStreamLocalBindMask, sStreamLocalBindUnlink,
578 	sAllowStreamLocalForwarding, sFingerprintHash, sDisableForwarding,
579 	sExposeAuthInfo, sRDomain,
580 	sDeprecated, sIgnore, sUnsupported
581 #ifdef WITH_LDAP_PUBKEY
582 	,sLdapPublickey, sLdapServers, sLdapUserDN
583 	,sLdapGroupDN, sBindDN, sBindPw, sMyGroup
584 	,sLdapFilter, sForceTLS, sBindTimeout
585 	,sSearchTimeout, sLdapConf ,sLpkPubKeyAttr
586 #endif
587 } ServerOpCodes;
588 
589 #define SSHCFG_GLOBAL	0x01	/* allowed in main section of sshd_config */
590 #define SSHCFG_MATCH	0x02	/* allowed inside a Match section */
591 #define SSHCFG_ALL	(SSHCFG_GLOBAL|SSHCFG_MATCH)
592 
593 /* Textual representation of the tokens. */
594 static struct {
595 	const char *name;
596 	ServerOpCodes opcode;
597 	u_int flags;
598 } keywords[] = {
599 #ifdef USE_PAM
600 	{ "usepam", sUsePAM, SSHCFG_GLOBAL },
601 #else
602 	{ "usepam", sUnsupported, SSHCFG_GLOBAL },
603 #endif
604 	{ "port", sPort, SSHCFG_GLOBAL },
605 	{ "hostkey", sHostKeyFile, SSHCFG_GLOBAL },
606 	{ "hostdsakey", sHostKeyFile, SSHCFG_GLOBAL },		/* alias */
607 	{ "hostkeyagent", sHostKeyAgent, SSHCFG_GLOBAL },
608 	{ "pidfile", sPidFile, SSHCFG_GLOBAL },
609 	{ "serverkeybits", sDeprecated, SSHCFG_GLOBAL },
610 	{ "logingracetime", sLoginGraceTime, SSHCFG_GLOBAL },
611 	{ "keyregenerationinterval", sDeprecated, SSHCFG_GLOBAL },
612 	{ "permitrootlogin", sPermitRootLogin, SSHCFG_ALL },
613 	{ "syslogfacility", sLogFacility, SSHCFG_GLOBAL },
614 	{ "loglevel", sLogLevel, SSHCFG_ALL },
615 	{ "rhostsauthentication", sDeprecated, SSHCFG_GLOBAL },
616 	{ "rhostsrsaauthentication", sDeprecated, SSHCFG_ALL },
617 	{ "hostbasedauthentication", sHostbasedAuthentication, SSHCFG_ALL },
618 	{ "hostbasedusesnamefrompacketonly", sHostbasedUsesNameFromPacketOnly, SSHCFG_ALL },
619 	{ "hostbasedacceptedkeytypes", sHostbasedAcceptedKeyTypes, SSHCFG_ALL },
620 	{ "hostkeyalgorithms", sHostKeyAlgorithms, SSHCFG_GLOBAL },
621 	{ "rsaauthentication", sDeprecated, SSHCFG_ALL },
622 	{ "pubkeyauthentication", sPubkeyAuthentication, SSHCFG_ALL },
623 	{ "pubkeyacceptedkeytypes", sPubkeyAcceptedKeyTypes, SSHCFG_ALL },
624 	{ "dsaauthentication", sPubkeyAuthentication, SSHCFG_GLOBAL }, /* alias */
625 #ifdef KRB5
626 	{ "kerberosauthentication", sKerberosAuthentication, SSHCFG_ALL },
627 	{ "kerberosorlocalpasswd", sKerberosOrLocalPasswd, SSHCFG_GLOBAL },
628 	{ "kerberosticketcleanup", sKerberosTicketCleanup, SSHCFG_GLOBAL },
629 	{ "kerberosgetafstoken", sKerberosGetAFSToken, SSHCFG_GLOBAL },
630 #else
631 	{ "kerberosauthentication", sUnsupported, SSHCFG_ALL },
632 	{ "kerberosorlocalpasswd", sUnsupported, SSHCFG_GLOBAL },
633 	{ "kerberosticketcleanup", sUnsupported, SSHCFG_GLOBAL },
634 	{ "kerberosgetafstoken", sUnsupported, SSHCFG_GLOBAL },
635 #endif
636 #if defined(AFS) || defined(KRB5)
637 	{ "kerberostgtpassing", sKerberosTgtPassing, SSHCFG_GLOBAL },
638 #else
639 	{ "kerberostgtpassing", sUnsupported, SSHCFG_GLOBAL },
640 #endif
641 	{ "afstokenpassing", sUnsupported, SSHCFG_GLOBAL },
642 #ifdef GSSAPI
643 	{ "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
644 	{ "gssapicleanupcredentials", sGssCleanupCreds, SSHCFG_GLOBAL },
645 	{ "gssapistrictacceptorcheck", sGssStrictAcceptor, SSHCFG_GLOBAL },
646 #else
647 	{ "gssapiauthentication", sUnsupported, SSHCFG_ALL },
648 	{ "gssapicleanupcredentials", sUnsupported, SSHCFG_GLOBAL },
649 	{ "gssapistrictacceptorcheck", sUnsupported, SSHCFG_GLOBAL },
650 #endif
651 	{ "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
652 	{ "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
653 	{ "challengeresponseauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL },
654 	{ "skeyauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL }, /* alias */
655 	{ "checkmail", sDeprecated, SSHCFG_GLOBAL },
656 	{ "listenaddress", sListenAddress, SSHCFG_GLOBAL },
657 	{ "addressfamily", sAddressFamily, SSHCFG_GLOBAL },
658 	{ "printmotd", sPrintMotd, SSHCFG_GLOBAL },
659 	{ "printlastlog", sPrintLastLog, SSHCFG_GLOBAL },
660 	{ "ignorerhosts", sIgnoreRhosts, SSHCFG_GLOBAL },
661 	{ "ignorerootrhosts", sIgnoreRootRhosts, SSHCFG_GLOBAL },
662 	{ "ignoreuserknownhosts", sIgnoreUserKnownHosts, SSHCFG_GLOBAL },
663 	{ "x11forwarding", sX11Forwarding, SSHCFG_ALL },
664 	{ "x11displayoffset", sX11DisplayOffset, SSHCFG_ALL },
665 	{ "x11uselocalhost", sX11UseLocalhost, SSHCFG_ALL },
666 	{ "xauthlocation", sXAuthLocation, SSHCFG_GLOBAL },
667 	{ "strictmodes", sStrictModes, SSHCFG_GLOBAL },
668 	{ "permitemptypasswords", sEmptyPasswd, SSHCFG_ALL },
669 	{ "permituserenvironment", sPermitUserEnvironment, SSHCFG_GLOBAL },
670 	{ "uselogin", sDeprecated, SSHCFG_GLOBAL },
671 	{ "compression", sCompression, SSHCFG_GLOBAL },
672 	{ "rekeylimit", sRekeyLimit, SSHCFG_ALL },
673 	{ "tcpkeepalive", sTCPKeepAlive, SSHCFG_GLOBAL },
674 	{ "keepalive", sTCPKeepAlive, SSHCFG_GLOBAL },	/* obsolete alias */
675 	{ "allowtcpforwarding", sAllowTcpForwarding, SSHCFG_ALL },
676 	{ "allowagentforwarding", sAllowAgentForwarding, SSHCFG_ALL },
677 	{ "allowusers", sAllowUsers, SSHCFG_ALL },
678 	{ "denyusers", sDenyUsers, SSHCFG_ALL },
679 	{ "allowgroups", sAllowGroups, SSHCFG_ALL },
680 	{ "denygroups", sDenyGroups, SSHCFG_ALL },
681 	{ "ciphers", sCiphers, SSHCFG_GLOBAL },
682 	{ "macs", sMacs, SSHCFG_GLOBAL },
683 	{ "protocol", sIgnore, SSHCFG_GLOBAL },
684 	{ "gatewayports", sGatewayPorts, SSHCFG_ALL },
685 	{ "subsystem", sSubsystem, SSHCFG_GLOBAL },
686 	{ "maxstartups", sMaxStartups, SSHCFG_GLOBAL },
687 	{ "maxauthtries", sMaxAuthTries, SSHCFG_ALL },
688 	{ "maxsessions", sMaxSessions, SSHCFG_ALL },
689 	{ "banner", sBanner, SSHCFG_ALL },
690 	{ "usedns", sUseDNS, SSHCFG_GLOBAL },
691 	{ "verifyreversemapping", sDeprecated, SSHCFG_GLOBAL },
692 	{ "reversemappingcheck", sDeprecated, SSHCFG_GLOBAL },
693 	{ "clientaliveinterval", sClientAliveInterval, SSHCFG_ALL },
694 	{ "clientalivecountmax", sClientAliveCountMax, SSHCFG_ALL },
695 	{ "authorizedkeysfile", sAuthorizedKeysFile, SSHCFG_ALL },
696 	{ "authorizedkeysfile2", sDeprecated, SSHCFG_ALL },
697 #ifdef WITH_LDAP_PUBKEY
698 	{ _DEFAULT_LPK_TOKEN, sLdapPublickey, SSHCFG_GLOBAL },
699 	{ _DEFAULT_SRV_TOKEN, sLdapServers, SSHCFG_GLOBAL },
700 	{ _DEFAULT_USR_TOKEN, sLdapUserDN, SSHCFG_GLOBAL },
701 	{ _DEFAULT_GRP_TOKEN, sLdapGroupDN, SSHCFG_GLOBAL },
702 	{ _DEFAULT_BDN_TOKEN, sBindDN, SSHCFG_GLOBAL },
703 	{ _DEFAULT_BPW_TOKEN, sBindPw, SSHCFG_GLOBAL },
704 	{ _DEFAULT_MYG_TOKEN, sMyGroup, SSHCFG_GLOBAL },
705 	{ _DEFAULT_FIL_TOKEN, sLdapFilter, SSHCFG_GLOBAL },
706 	{ _DEFAULT_TLS_TOKEN, sForceTLS, SSHCFG_GLOBAL },
707 	{ _DEFAULT_BTI_TOKEN, sBindTimeout, SSHCFG_GLOBAL },
708 	{ _DEFAULT_STI_TOKEN, sSearchTimeout, SSHCFG_GLOBAL },
709 	{ _DEFAULT_LDP_TOKEN, sLdapConf, SSHCFG_GLOBAL },
710 	{ "LpkPubKeyAttr", sLpkPubKeyAttr, SSHCFG_GLOBAL },
711 #endif
712 	{ "useprivilegeseparation", sDeprecated, SSHCFG_GLOBAL},
713 	{ "acceptenv", sAcceptEnv, SSHCFG_ALL },
714 	{ "permittunnel", sPermitTunnel, SSHCFG_ALL },
715 	{ "permittty", sPermitTTY, SSHCFG_ALL },
716 	{ "permituserrc", sPermitUserRC, SSHCFG_ALL },
717 	{ "match", sMatch, SSHCFG_ALL },
718 	{ "permitopen", sPermitOpen, SSHCFG_ALL },
719 	{ "forcecommand", sForceCommand, SSHCFG_ALL },
720 	{ "chrootdirectory", sChrootDirectory, SSHCFG_ALL },
721 	{ "hostcertificate", sHostCertificate, SSHCFG_GLOBAL },
722 	{ "revokedkeys", sRevokedKeys, SSHCFG_ALL },
723 	{ "trustedusercakeys", sTrustedUserCAKeys, SSHCFG_ALL },
724 	{ "authorizedprincipalsfile", sAuthorizedPrincipalsFile, SSHCFG_ALL },
725 	{ "kexalgorithms", sKexAlgorithms, SSHCFG_GLOBAL },
726 	{ "ipqos", sIPQoS, SSHCFG_ALL },
727 	{ "authorizedkeyscommand", sAuthorizedKeysCommand, SSHCFG_ALL },
728 	{ "authorizedkeyscommanduser", sAuthorizedKeysCommandUser, SSHCFG_ALL },
729 	{ "authorizedprincipalscommand", sAuthorizedPrincipalsCommand, SSHCFG_ALL },
730 	{ "authorizedprincipalscommanduser", sAuthorizedPrincipalsCommandUser, SSHCFG_ALL },
731 	{ "versionaddendum", sVersionAddendum, SSHCFG_GLOBAL },
732 	{ "noneenabled", sNoneEnabled, SSHCFG_ALL },
733 	{ "hpndisabled", sHPNDisabled, SSHCFG_ALL },
734 	{ "hpnbuffersize", sHPNBufferSize, SSHCFG_ALL },
735 	{ "tcprcvbufpoll", sTcpRcvBufPoll, SSHCFG_ALL },
736 	{ "authenticationmethods", sAuthenticationMethods, SSHCFG_ALL },
737 	{ "streamlocalbindmask", sStreamLocalBindMask, SSHCFG_ALL },
738 	{ "streamlocalbindunlink", sStreamLocalBindUnlink, SSHCFG_ALL },
739 	{ "allowstreamlocalforwarding", sAllowStreamLocalForwarding, SSHCFG_ALL },
740 	{ "fingerprinthash", sFingerprintHash, SSHCFG_GLOBAL },
741 	{ "disableforwarding", sDisableForwarding, SSHCFG_ALL },
742 	{ "exposeauthinfo", sExposeAuthInfo, SSHCFG_ALL },
743 	{ "rdomain", sRDomain, SSHCFG_ALL },
744 	{ NULL, sBadOption, 0 }
745 };
746 
747 static struct {
748 	int val;
749 	const char *text;
750 } tunmode_desc[] = {
751 	{ SSH_TUNMODE_NO, "no" },
752 	{ SSH_TUNMODE_POINTOPOINT, "point-to-point" },
753 	{ SSH_TUNMODE_ETHERNET, "ethernet" },
754 	{ SSH_TUNMODE_YES, "yes" },
755 	{ -1, NULL }
756 };
757 
758 /*
759  * Returns the number of the token pointed to by cp or sBadOption.
760  */
761 
762 static ServerOpCodes
763 parse_token(const char *cp, const char *filename,
764 	    int linenum, u_int *flags)
765 {
766 	u_int i;
767 
768 	for (i = 0; keywords[i].name; i++)
769 		if (strcasecmp(cp, keywords[i].name) == 0) {
770 		        debug ("Config token is %s", keywords[i].name);
771 			*flags = keywords[i].flags;
772 			return keywords[i].opcode;
773 		}
774 
775 	error("%s: line %d: Bad configuration option: %s",
776 	    filename, linenum, cp);
777 	return sBadOption;
778 }
779 
780 char *
781 derelativise_path(const char *path)
782 {
783 	char *expanded, *ret, cwd[PATH_MAX];
784 
785 	if (strcasecmp(path, "none") == 0)
786 		return xstrdup("none");
787 	expanded = tilde_expand_filename(path, getuid());
788 	if (*expanded == '/')
789 		return expanded;
790 	if (getcwd(cwd, sizeof(cwd)) == NULL)
791 		fatal("%s: getcwd: %s", __func__, strerror(errno));
792 	xasprintf(&ret, "%s/%s", cwd, expanded);
793 	free(expanded);
794 	return ret;
795 }
796 
797 static void
798 add_listen_addr(ServerOptions *options, const char *addr,
799     const char *rdomain, int port)
800 {
801 	u_int i;
802 
803 	if (port > 0)
804 		add_one_listen_addr(options, addr, rdomain, port);
805 	else {
806 		for (i = 0; i < options->num_ports; i++) {
807 			add_one_listen_addr(options, addr, rdomain,
808 			    options->ports[i]);
809 		}
810 	}
811 }
812 
813 static void
814 add_one_listen_addr(ServerOptions *options, const char *addr,
815     const char *rdomain, int port)
816 {
817 	struct addrinfo hints, *ai, *aitop;
818 	char strport[NI_MAXSERV];
819 	int gaierr;
820 	u_int i;
821 
822 	/* Find listen_addrs entry for this rdomain */
823 	for (i = 0; i < options->num_listen_addrs; i++) {
824 		if (rdomain == NULL && options->listen_addrs[i].rdomain == NULL)
825 			break;
826 		if (rdomain == NULL || options->listen_addrs[i].rdomain == NULL)
827 			continue;
828 		if (strcmp(rdomain, options->listen_addrs[i].rdomain) == 0)
829 			break;
830 	}
831 	if (i >= options->num_listen_addrs) {
832 		/* No entry for this rdomain; allocate one */
833 		if (i >= INT_MAX)
834 			fatal("%s: too many listen addresses", __func__);
835 		options->listen_addrs = xrecallocarray(options->listen_addrs,
836 		    options->num_listen_addrs, options->num_listen_addrs + 1,
837 		    sizeof(*options->listen_addrs));
838 		i = options->num_listen_addrs++;
839 		if (rdomain != NULL)
840 			options->listen_addrs[i].rdomain = xstrdup(rdomain);
841 	}
842 	/* options->listen_addrs[i] points to the addresses for this rdomain */
843 
844 	memset(&hints, 0, sizeof(hints));
845 	hints.ai_family = options->address_family;
846 	hints.ai_socktype = SOCK_STREAM;
847 	hints.ai_flags = (addr == NULL) ? AI_PASSIVE : 0;
848 	snprintf(strport, sizeof strport, "%d", port);
849 	if ((gaierr = getaddrinfo(addr, strport, &hints, &aitop)) != 0)
850 		fatal("bad addr or host: %s (%s)",
851 		    addr ? addr : "<NULL>",
852 		    ssh_gai_strerror(gaierr));
853 	for (ai = aitop; ai->ai_next; ai = ai->ai_next)
854 		;
855 	ai->ai_next = options->listen_addrs[i].addrs;
856 	options->listen_addrs[i].addrs = aitop;
857 }
858 
859 /* Returns nonzero if the routing domain name is valid */
860 static int
861 valid_rdomain(const char *name)
862 {
863 #ifdef NET_RT_TABLE
864 	const char *errstr;
865 	long long num;
866 	struct rt_tableinfo info;
867 	int mib[6];
868 	size_t miblen = sizeof(mib);
869 
870 	if (name == NULL)
871 		return 1;
872 
873 	num = strtonum(name, 0, 255, &errstr);
874 	if (errstr != NULL)
875 		return 0;
876 
877 	/* Check whether the table actually exists */
878 	memset(mib, 0, sizeof(mib));
879 	mib[0] = CTL_NET;
880 	mib[1] = PF_ROUTE;
881 	mib[4] = NET_RT_TABLE;
882 	mib[5] = (int)num;
883 	if (sysctl(mib, 6, &info, &miblen, NULL, 0) == -1)
884 		return 0;
885 
886 	return 1;
887 #else
888 	return 0;
889 #endif
890 }
891 
892 /*
893  * Queue a ListenAddress to be processed once we have all of the Ports
894  * and AddressFamily options.
895  */
896 static void
897 queue_listen_addr(ServerOptions *options, const char *addr,
898     const char *rdomain, int port)
899 {
900 	struct queued_listenaddr *qla;
901 
902 	options->queued_listen_addrs = xrecallocarray(
903 	    options->queued_listen_addrs,
904 	    options->num_queued_listens, options->num_queued_listens + 1,
905 	    sizeof(*options->queued_listen_addrs));
906 	qla = &options->queued_listen_addrs[options->num_queued_listens++];
907 	qla->addr = xstrdup(addr);
908 	qla->port = port;
909 	qla->rdomain = rdomain == NULL ? NULL : xstrdup(rdomain);
910 }
911 
912 /*
913  * Process queued (text) ListenAddress entries.
914  */
915 static void
916 process_queued_listen_addrs(ServerOptions *options)
917 {
918 	u_int i;
919 	struct queued_listenaddr *qla;
920 
921 	if (options->num_ports == 0)
922 		options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
923 	if (options->address_family == -1)
924 		options->address_family = AF_UNSPEC;
925 
926 	for (i = 0; i < options->num_queued_listens; i++) {
927 		qla = &options->queued_listen_addrs[i];
928 		add_listen_addr(options, qla->addr, qla->rdomain, qla->port);
929 		free(qla->addr);
930 		free(qla->rdomain);
931 	}
932 	free(options->queued_listen_addrs);
933 	options->queued_listen_addrs = NULL;
934 	options->num_queued_listens = 0;
935 }
936 
937 /*
938  * Inform channels layer of permitopen options from configuration.
939  */
940 void
941 process_permitopen(struct ssh *ssh, ServerOptions *options)
942 {
943 	u_int i;
944 	int port;
945 	char *host, *arg, *oarg;
946 
947 	channel_clear_adm_permitted_opens(ssh);
948 	if (options->num_permitted_opens == 0)
949 		return; /* permit any */
950 
951 	/* handle keywords: "any" / "none" */
952 	if (options->num_permitted_opens == 1 &&
953 	    strcmp(options->permitted_opens[0], "any") == 0)
954 		return;
955 	if (options->num_permitted_opens == 1 &&
956 	    strcmp(options->permitted_opens[0], "none") == 0) {
957 		channel_disable_adm_local_opens(ssh);
958 		return;
959 	}
960 	/* Otherwise treat it as a list of permitted host:port */
961 	for (i = 0; i < options->num_permitted_opens; i++) {
962 		oarg = arg = xstrdup(options->permitted_opens[i]);
963 		host = hpdelim(&arg);
964 		if (host == NULL)
965 			fatal("%s: missing host in PermitOpen", __func__);
966 		host = cleanhostname(host);
967 		if (arg == NULL || ((port = permitopen_port(arg)) < 0))
968 			fatal("%s: bad port number in PermitOpen", __func__);
969 		/* Send it to channels layer */
970 		channel_add_adm_permitted_opens(ssh, host, port);
971 		free(oarg);
972 	}
973 }
974 
975 struct connection_info *
976 get_connection_info(int populate, int use_dns)
977 {
978 	struct ssh *ssh = active_state; /* XXX */
979 	static struct connection_info ci;
980 
981 	if (!populate)
982 		return &ci;
983 	ci.host = auth_get_canonical_hostname(ssh, use_dns);
984 	ci.address = ssh_remote_ipaddr(ssh);
985 	ci.laddress = ssh_local_ipaddr(ssh);
986 	ci.lport = ssh_local_port(ssh);
987 	ci.rdomain = ssh_packet_rdomain_in(ssh);
988 	return &ci;
989 }
990 
991 /*
992  * The strategy for the Match blocks is that the config file is parsed twice.
993  *
994  * The first time is at startup.  activep is initialized to 1 and the
995  * directives in the global context are processed and acted on.  Hitting a
996  * Match directive unsets activep and the directives inside the block are
997  * checked for syntax only.
998  *
999  * The second time is after a connection has been established but before
1000  * authentication.  activep is initialized to 2 and global config directives
1001  * are ignored since they have already been processed.  If the criteria in a
1002  * Match block is met, activep is set and the subsequent directives
1003  * processed and actioned until EOF or another Match block unsets it.  Any
1004  * options set are copied into the main server config.
1005  *
1006  * Potential additions/improvements:
1007  *  - Add Match support for pre-kex directives, eg. Ciphers.
1008  *
1009  *  - Add a Tag directive (idea from David Leonard) ala pf, eg:
1010  *	Match Address 192.168.0.*
1011  *		Tag trusted
1012  *	Match Group wheel
1013  *		Tag trusted
1014  *	Match Tag trusted
1015  *		AllowTcpForwarding yes
1016  *		GatewayPorts clientspecified
1017  *		[...]
1018  *
1019  *  - Add a PermittedChannelRequests directive
1020  *	Match Group shell
1021  *		PermittedChannelRequests session,forwarded-tcpip
1022  */
1023 
1024 static int
1025 match_cfg_line_group(const char *grps, int line, const char *user)
1026 {
1027 	int result = 0;
1028 	struct passwd *pw;
1029 
1030 	if (user == NULL)
1031 		goto out;
1032 
1033 	if ((pw = getpwnam(user)) == NULL) {
1034 		debug("Can't match group at line %d because user %.100s does "
1035 		    "not exist", line, user);
1036 	} else if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
1037 		debug("Can't Match group because user %.100s not in any group "
1038 		    "at line %d", user, line);
1039 	} else if (ga_match_pattern_list(grps) != 1) {
1040 		debug("user %.100s does not match group list %.100s at line %d",
1041 		    user, grps, line);
1042 	} else {
1043 		debug("user %.100s matched group list %.100s at line %d", user,
1044 		    grps, line);
1045 		result = 1;
1046 	}
1047 out:
1048 	ga_free();
1049 	return result;
1050 }
1051 
1052 __dead static void
1053 match_test_missing_fatal(const char *criteria, const char *attrib)
1054 {
1055 	fatal("'Match %s' in configuration but '%s' not in connection "
1056 	    "test specification.", criteria, attrib);
1057 }
1058 
1059 /*
1060  * All of the attributes on a single Match line are ANDed together, so we need
1061  * to check every attribute and set the result to zero if any attribute does
1062  * not match.
1063  */
1064 static int
1065 match_cfg_line(char **condition, int line, struct connection_info *ci)
1066 {
1067 	int result = 1, attributes = 0, port;
1068 	char *arg, *attrib, *cp = *condition;
1069 
1070 	if (ci == NULL)
1071 		debug3("checking syntax for 'Match %s'", cp);
1072 	else
1073 		debug3("checking match for '%s' user %s host %s addr %s "
1074 		    "laddr %s lport %d", cp, ci->user ? ci->user : "(null)",
1075 		    ci->host ? ci->host : "(null)",
1076 		    ci->address ? ci->address : "(null)",
1077 		    ci->laddress ? ci->laddress : "(null)", ci->lport);
1078 
1079 	while ((attrib = strdelim(&cp)) && *attrib != '\0') {
1080 		attributes++;
1081 		if (strcasecmp(attrib, "all") == 0) {
1082 			if (attributes != 1 ||
1083 			    ((arg = strdelim(&cp)) != NULL && *arg != '\0')) {
1084 				error("'all' cannot be combined with other "
1085 				    "Match attributes");
1086 				return -1;
1087 			}
1088 			*condition = cp;
1089 			return 1;
1090 		}
1091 		if ((arg = strdelim(&cp)) == NULL || *arg == '\0') {
1092 			error("Missing Match criteria for %s", attrib);
1093 			return -1;
1094 		}
1095 		if (strcasecmp(attrib, "user") == 0) {
1096 			if (ci == NULL) {
1097 				result = 0;
1098 				continue;
1099 			}
1100 			if (ci->user == NULL)
1101 				match_test_missing_fatal("User", "user");
1102 			if (match_pattern_list(ci->user, arg, 0) != 1)
1103 				result = 0;
1104 			else
1105 				debug("user %.100s matched 'User %.100s' at "
1106 				    "line %d", ci->user, arg, line);
1107 		} else if (strcasecmp(attrib, "group") == 0) {
1108 			if (ci == NULL) {
1109 				result = 0;
1110 				continue;
1111 			}
1112 			if (ci->user == NULL)
1113 				match_test_missing_fatal("Group", "user");
1114 			switch (match_cfg_line_group(arg, line, ci->user)) {
1115 			case -1:
1116 				return -1;
1117 			case 0:
1118 				result = 0;
1119 			}
1120 		} else if (strcasecmp(attrib, "host") == 0) {
1121 			if (ci == NULL) {
1122 				result = 0;
1123 				continue;
1124 			}
1125 			if (ci->host == NULL)
1126 				match_test_missing_fatal("Host", "host");
1127 			if (match_hostname(ci->host, arg) != 1)
1128 				result = 0;
1129 			else
1130 				debug("connection from %.100s matched 'Host "
1131 				    "%.100s' at line %d", ci->host, arg, line);
1132 		} else if (strcasecmp(attrib, "address") == 0) {
1133 			if (ci == NULL) {
1134 				result = 0;
1135 				continue;
1136 			}
1137 			if (ci->address == NULL)
1138 				match_test_missing_fatal("Address", "addr");
1139 			switch (addr_match_list(ci->address, arg)) {
1140 			case 1:
1141 				debug("connection from %.100s matched 'Address "
1142 				    "%.100s' at line %d", ci->address, arg, line);
1143 				break;
1144 			case 0:
1145 			case -1:
1146 				result = 0;
1147 				break;
1148 			case -2:
1149 				return -1;
1150 			}
1151 		} else if (strcasecmp(attrib, "localaddress") == 0){
1152 			if (ci == NULL) {
1153 				result = 0;
1154 				continue;
1155 			}
1156 			if (ci->laddress == NULL)
1157 				match_test_missing_fatal("LocalAddress",
1158 				    "laddr");
1159 			switch (addr_match_list(ci->laddress, arg)) {
1160 			case 1:
1161 				debug("connection from %.100s matched "
1162 				    "'LocalAddress %.100s' at line %d",
1163 				    ci->laddress, arg, line);
1164 				break;
1165 			case 0:
1166 			case -1:
1167 				result = 0;
1168 				break;
1169 			case -2:
1170 				return -1;
1171 			}
1172 		} else if (strcasecmp(attrib, "localport") == 0) {
1173 			if ((port = a2port(arg)) == -1) {
1174 				error("Invalid LocalPort '%s' on Match line",
1175 				    arg);
1176 				return -1;
1177 			}
1178 			if (ci == NULL) {
1179 				result = 0;
1180 				continue;
1181 			}
1182 			if (ci->lport == 0)
1183 				match_test_missing_fatal("LocalPort", "lport");
1184 			/* TODO support port lists */
1185 			if (port == ci->lport)
1186 				debug("connection from %.100s matched "
1187 				    "'LocalPort %d' at line %d",
1188 				    ci->laddress, port, line);
1189 			else
1190 				result = 0;
1191 		} else if (strcasecmp(attrib, "rdomain") == 0) {
1192 			if (ci == NULL || ci->rdomain == NULL) {
1193 				result = 0;
1194 				continue;
1195 			}
1196 			if (match_pattern_list(ci->rdomain, arg, 0) != 1)
1197 				result = 0;
1198 			else
1199 				debug("user %.100s matched 'RDomain %.100s' at "
1200 				    "line %d", ci->rdomain, arg, line);
1201 		} else {
1202 			error("Unsupported Match attribute %s", attrib);
1203 			return -1;
1204 		}
1205 	}
1206 	if (attributes == 0) {
1207 		error("One or more attributes required for Match");
1208 		return -1;
1209 	}
1210 	if (ci != NULL)
1211 		debug3("match %sfound", result ? "" : "not ");
1212 	*condition = cp;
1213 	return result;
1214 }
1215 
1216 #define WHITESPACE " \t\r\n"
1217 
1218 /* Multistate option parsing */
1219 struct multistate {
1220 	const char *key;
1221 	int value;
1222 };
1223 static const struct multistate multistate_flag[] = {
1224 	{ "yes",			1 },
1225 	{ "no",				0 },
1226 	{ NULL, -1 }
1227 };
1228 static const struct multistate multistate_addressfamily[] = {
1229 	{ "inet",			AF_INET },
1230 	{ "inet6",			AF_INET6 },
1231 	{ "any",			AF_UNSPEC },
1232 	{ NULL, -1 }
1233 };
1234 static const struct multistate multistate_permitrootlogin[] = {
1235 	{ "without-password",		PERMIT_NO_PASSWD },
1236 	{ "prohibit-password",		PERMIT_NO_PASSWD },
1237 	{ "forced-commands-only",	PERMIT_FORCED_ONLY },
1238 	{ "yes",			PERMIT_YES },
1239 	{ "no",				PERMIT_NO },
1240 	{ NULL, -1 }
1241 };
1242 static const struct multistate multistate_compression[] = {
1243 	{ "yes",			COMP_DELAYED },
1244 	{ "delayed",			COMP_DELAYED },
1245 	{ "no",				COMP_NONE },
1246 	{ NULL, -1 }
1247 };
1248 static const struct multistate multistate_gatewayports[] = {
1249 	{ "clientspecified",		2 },
1250 	{ "yes",			1 },
1251 	{ "no",				0 },
1252 	{ NULL, -1 }
1253 };
1254 static const struct multistate multistate_tcpfwd[] = {
1255 	{ "yes",			FORWARD_ALLOW },
1256 	{ "all",			FORWARD_ALLOW },
1257 	{ "no",				FORWARD_DENY },
1258 	{ "remote",			FORWARD_REMOTE },
1259 	{ "local",			FORWARD_LOCAL },
1260 	{ NULL, -1 }
1261 };
1262 
1263 int
1264 process_server_config_line(ServerOptions *options, char *line,
1265     const char *filename, int linenum, int *activep,
1266     struct connection_info *connectinfo)
1267 {
1268 	char *cp, **charptr, *arg, *arg2, *p;
1269 	int cmdline = 0, *intptr, value, value2, n, port;
1270 	SyslogFacility *log_facility_ptr;
1271 	LogLevel *log_level_ptr;
1272 #ifdef WITH_LDAP_PUBKEY
1273  	unsigned long lvalue;
1274 #endif
1275 	time_t *timetptr __unused;
1276 	ServerOpCodes opcode;
1277 	u_int i, flags = 0;
1278 	size_t len;
1279 	long long val64;
1280 	const struct multistate *multistate_ptr;
1281 	const char *errstr;
1282 
1283 	/* Strip trailing whitespace. Allow \f (form feed) at EOL only */
1284 	if ((len = strlen(line)) == 0)
1285 		return 0;
1286 	for (len--; len > 0; len--) {
1287 		if (strchr(WHITESPACE "\f", line[len]) == NULL)
1288 			break;
1289 		line[len] = '\0';
1290 	}
1291 
1292 	cp = line;
1293 	if ((arg = strdelim(&cp)) == NULL)
1294 		return 0;
1295 	/* Ignore leading whitespace */
1296 	if (*arg == '\0')
1297 		arg = strdelim(&cp);
1298 	if (!arg || !*arg || *arg == '#')
1299 		return 0;
1300 	intptr = NULL;
1301 	timetptr = NULL;
1302 	charptr = NULL;
1303 	opcode = parse_token(arg, filename, linenum, &flags);
1304 
1305 	if (activep == NULL) { /* We are processing a command line directive */
1306 		cmdline = 1;
1307 		activep = &cmdline;
1308 	}
1309 	if (*activep && opcode != sMatch)
1310 		debug3("%s:%d setting %s %s", filename, linenum, arg, cp);
1311 	if (*activep == 0 && !(flags & SSHCFG_MATCH)) {
1312 		if (connectinfo == NULL) {
1313 			fatal("%s line %d: Directive '%s' is not allowed "
1314 			    "within a Match block", filename, linenum, arg);
1315 		} else { /* this is a directive we have already processed */
1316 			while (arg)
1317 				arg = strdelim(&cp);
1318 			return 0;
1319 		}
1320 	}
1321 
1322 	switch (opcode) {
1323 	/* Portable-specific options */
1324 	case sUsePAM:
1325 		intptr = &options->use_pam;
1326 		goto parse_flag;
1327 
1328 	/* Standard Options */
1329 	case sBadOption:
1330 		return -1;
1331 	case sPort:
1332 		/* ignore ports from configfile if cmdline specifies ports */
1333 		if (options->ports_from_cmdline)
1334 			return 0;
1335 		if (options->num_ports >= MAX_PORTS)
1336 			fatal("%s line %d: too many ports.",
1337 			    filename, linenum);
1338 		arg = strdelim(&cp);
1339 		if (!arg || *arg == '\0')
1340 			fatal("%s line %d: missing port number.",
1341 			    filename, linenum);
1342 		options->ports[options->num_ports++] = a2port(arg);
1343 		if (options->ports[options->num_ports-1] <= 0)
1344 			fatal("%s line %d: Badly formatted port number.",
1345 			    filename, linenum);
1346 		break;
1347 
1348 	case sLoginGraceTime:
1349 		intptr = &options->login_grace_time;
1350  parse_time:
1351 		arg = strdelim(&cp);
1352 		if (!arg || *arg == '\0')
1353 			fatal("%s line %d: missing time value.",
1354 			    filename, linenum);
1355 		if ((value = convtime(arg)) == -1)
1356 			fatal("%s line %d: invalid time value.",
1357 			    filename, linenum);
1358 		if (*activep && *intptr == -1)
1359 			*intptr = value;
1360 		break;
1361 
1362 	case sListenAddress:
1363 		arg = strdelim(&cp);
1364 		if (arg == NULL || *arg == '\0')
1365 			fatal("%s line %d: missing address",
1366 			    filename, linenum);
1367 		/* check for bare IPv6 address: no "[]" and 2 or more ":" */
1368 		if (strchr(arg, '[') == NULL && (p = strchr(arg, ':')) != NULL
1369 		    && strchr(p+1, ':') != NULL) {
1370 			port = 0;
1371 			p = arg;
1372 		} else {
1373 			p = hpdelim(&arg);
1374 			if (p == NULL)
1375 				fatal("%s line %d: bad address:port usage",
1376 				    filename, linenum);
1377 			p = cleanhostname(p);
1378 			if (arg == NULL)
1379 				port = 0;
1380 			else if ((port = a2port(arg)) <= 0)
1381 				fatal("%s line %d: bad port number",
1382 				    filename, linenum);
1383 		}
1384 		/* Optional routing table */
1385 		arg2 = NULL;
1386 		if ((arg = strdelim(&cp)) != NULL) {
1387 			if (strcmp(arg, "rdomain") != 0 ||
1388 			    (arg2 = strdelim(&cp)) == NULL)
1389 				fatal("%s line %d: bad ListenAddress syntax",
1390 				    filename, linenum);
1391 			if (!valid_rdomain(arg2))
1392 				fatal("%s line %d: bad routing domain",
1393 				    filename, linenum);
1394 		}
1395 
1396 		queue_listen_addr(options, p, arg2, port);
1397 
1398 		break;
1399 
1400 	case sAddressFamily:
1401 		intptr = &options->address_family;
1402 		multistate_ptr = multistate_addressfamily;
1403  parse_multistate:
1404 		arg = strdelim(&cp);
1405 		if (!arg || *arg == '\0')
1406 			fatal("%s line %d: missing argument.",
1407 			    filename, linenum);
1408 		value = -1;
1409 		for (i = 0; multistate_ptr[i].key != NULL; i++) {
1410 			if (strcasecmp(arg, multistate_ptr[i].key) == 0) {
1411 				value = multistate_ptr[i].value;
1412 				break;
1413 			}
1414 		}
1415 		if (value == -1)
1416 			fatal("%s line %d: unsupported option \"%s\".",
1417 			    filename, linenum, arg);
1418 		if (*activep && *intptr == -1)
1419 			*intptr = value;
1420 		break;
1421 
1422 	case sHostKeyFile:
1423 		arg = strdelim(&cp);
1424 		if (!arg || *arg == '\0')
1425 			fatal("%s line %d: missing file name.",
1426 			    filename, linenum);
1427 		if (*activep)
1428 			servconf_add_hostkey(filename, linenum, options, arg);
1429 		break;
1430 
1431 	case sHostKeyAgent:
1432 		charptr = &options->host_key_agent;
1433 		arg = strdelim(&cp);
1434 		if (!arg || *arg == '\0')
1435 			fatal("%s line %d: missing socket name.",
1436 			    filename, linenum);
1437 		if (*activep && *charptr == NULL)
1438 			*charptr = !strcmp(arg, SSH_AUTHSOCKET_ENV_NAME) ?
1439 			    xstrdup(arg) : derelativise_path(arg);
1440 		break;
1441 
1442 	case sHostCertificate:
1443 		arg = strdelim(&cp);
1444 		if (!arg || *arg == '\0')
1445 			fatal("%s line %d: missing file name.",
1446 			    filename, linenum);
1447 		if (*activep)
1448 			servconf_add_hostcert(filename, linenum, options, arg);
1449 		break;
1450 
1451 	case sPidFile:
1452 		charptr = &options->pid_file;
1453  parse_filename:
1454 		arg = strdelim(&cp);
1455 		if (!arg || *arg == '\0')
1456 			fatal("%s line %d: missing file name.",
1457 			    filename, linenum);
1458 		if (*activep && *charptr == NULL) {
1459 			*charptr = derelativise_path(arg);
1460 			/* increase optional counter */
1461 			if (intptr != NULL)
1462 				*intptr = *intptr + 1;
1463 		}
1464 		break;
1465 
1466 	case sPermitRootLogin:
1467 		intptr = &options->permit_root_login;
1468 		multistate_ptr = multistate_permitrootlogin;
1469 		goto parse_multistate;
1470 
1471 	case sIgnoreRhosts:
1472 		intptr = &options->ignore_rhosts;
1473  parse_flag:
1474 		multistate_ptr = multistate_flag;
1475 		goto parse_multistate;
1476 
1477 	case sIgnoreRootRhosts:
1478 		intptr = &options->ignore_root_rhosts;
1479 		goto parse_flag;
1480 
1481 	case sNoneEnabled:
1482 		intptr = &options->none_enabled;
1483 		goto parse_flag;
1484 
1485 	case sTcpRcvBufPoll:
1486 		intptr = &options->tcp_rcv_buf_poll;
1487 		goto parse_flag;
1488 
1489 	case sHPNDisabled:
1490 		intptr = &options->hpn_disabled;
1491 		goto parse_flag;
1492 
1493 	case sHPNBufferSize:
1494 		intptr = &options->hpn_buffer_size;
1495 		goto parse_int;
1496 
1497 	case sIgnoreUserKnownHosts:
1498 		intptr = &options->ignore_user_known_hosts;
1499 		goto parse_flag;
1500 
1501 	case sHostbasedAuthentication:
1502 		intptr = &options->hostbased_authentication;
1503 		goto parse_flag;
1504 
1505 	case sHostbasedUsesNameFromPacketOnly:
1506 		intptr = &options->hostbased_uses_name_from_packet_only;
1507 		goto parse_flag;
1508 
1509 	case sHostbasedAcceptedKeyTypes:
1510 		charptr = &options->hostbased_key_types;
1511  parse_keytypes:
1512 		arg = strdelim(&cp);
1513 		if (!arg || *arg == '\0')
1514 			fatal("%s line %d: Missing argument.",
1515 			    filename, linenum);
1516 		if (*arg != '-' &&
1517 		    !sshkey_names_valid2(*arg == '+' ? arg + 1 : arg, 1))
1518 			fatal("%s line %d: Bad key types '%s'.",
1519 			    filename, linenum, arg ? arg : "<NONE>");
1520 		if (*activep && *charptr == NULL)
1521 			*charptr = xstrdup(arg);
1522 		break;
1523 
1524 	case sHostKeyAlgorithms:
1525 		charptr = &options->hostkeyalgorithms;
1526 		goto parse_keytypes;
1527 
1528 	case sPubkeyAuthentication:
1529 		intptr = &options->pubkey_authentication;
1530 		goto parse_flag;
1531 
1532 	case sPubkeyAcceptedKeyTypes:
1533 		charptr = &options->pubkey_key_types;
1534 		goto parse_keytypes;
1535 
1536 	case sKerberosAuthentication:
1537 		intptr = &options->kerberos_authentication;
1538 		goto parse_flag;
1539 
1540 	case sKerberosOrLocalPasswd:
1541 		intptr = &options->kerberos_or_local_passwd;
1542 		goto parse_flag;
1543 
1544 	case sKerberosTicketCleanup:
1545 		intptr = &options->kerberos_ticket_cleanup;
1546 		goto parse_flag;
1547 
1548 	case sKerberosTgtPassing:
1549 		intptr = &options->kerberos_tgt_passing;
1550 		goto parse_flag;
1551 
1552 	case sKerberosGetAFSToken:
1553 		intptr = &options->kerberos_get_afs_token;
1554 		goto parse_flag;
1555 
1556 	case sGssAuthentication:
1557 		intptr = &options->gss_authentication;
1558 		goto parse_flag;
1559 
1560 	case sGssCleanupCreds:
1561 		intptr = &options->gss_cleanup_creds;
1562 		goto parse_flag;
1563 
1564 	case sGssStrictAcceptor:
1565 		intptr = &options->gss_strict_acceptor;
1566 		goto parse_flag;
1567 
1568 	case sPasswordAuthentication:
1569 		intptr = &options->password_authentication;
1570 		goto parse_flag;
1571 
1572 	case sKbdInteractiveAuthentication:
1573 		intptr = &options->kbd_interactive_authentication;
1574 		goto parse_flag;
1575 
1576 	case sChallengeResponseAuthentication:
1577 		intptr = &options->challenge_response_authentication;
1578 		goto parse_flag;
1579 
1580 	case sPrintMotd:
1581 		intptr = &options->print_motd;
1582 		goto parse_flag;
1583 
1584 	case sPrintLastLog:
1585 		intptr = &options->print_lastlog;
1586 		goto parse_flag;
1587 
1588 	case sX11Forwarding:
1589 		intptr = &options->x11_forwarding;
1590 		goto parse_flag;
1591 
1592 	case sX11DisplayOffset:
1593 		intptr = &options->x11_display_offset;
1594  parse_int:
1595 		arg = strdelim(&cp);
1596 		if ((errstr = atoi_err(arg, &value)) != NULL)
1597 			fatal("%s line %d: integer value %s.",
1598 			    filename, linenum, errstr);
1599 		if (*activep && *intptr == -1)
1600 			*intptr = value;
1601 		break;
1602 
1603 	case sX11UseLocalhost:
1604 		intptr = &options->x11_use_localhost;
1605 		goto parse_flag;
1606 
1607 	case sXAuthLocation:
1608 		charptr = &options->xauth_location;
1609 		goto parse_filename;
1610 
1611 	case sPermitTTY:
1612 		intptr = &options->permit_tty;
1613 		goto parse_flag;
1614 
1615 	case sPermitUserRC:
1616 		intptr = &options->permit_user_rc;
1617 		goto parse_flag;
1618 
1619 	case sStrictModes:
1620 		intptr = &options->strict_modes;
1621 		goto parse_flag;
1622 
1623 	case sTCPKeepAlive:
1624 		intptr = &options->tcp_keep_alive;
1625 		goto parse_flag;
1626 
1627 	case sEmptyPasswd:
1628 		intptr = &options->permit_empty_passwd;
1629 		goto parse_flag;
1630 
1631 	case sPermitUserEnvironment:
1632 		intptr = &options->permit_user_env;
1633 		goto parse_flag;
1634 
1635 	case sCompression:
1636 		intptr = &options->compression;
1637 		multistate_ptr = multistate_compression;
1638 		goto parse_multistate;
1639 
1640 	case sRekeyLimit:
1641 		arg = strdelim(&cp);
1642 		if (!arg || *arg == '\0')
1643 			fatal("%.200s line %d: Missing argument.", filename,
1644 			    linenum);
1645 		if (strcmp(arg, "default") == 0) {
1646 			val64 = 0;
1647 		} else {
1648 			if (scan_scaled(arg, &val64) == -1)
1649 				fatal("%.200s line %d: Bad number '%s': %s",
1650 				    filename, linenum, arg, strerror(errno));
1651 			if (val64 != 0 && val64 < 16)
1652 				fatal("%.200s line %d: RekeyLimit too small",
1653 				    filename, linenum);
1654 		}
1655 		if (*activep && options->rekey_limit == -1)
1656 			options->rekey_limit = val64;
1657 		if (cp != NULL) { /* optional rekey interval present */
1658 			if (strcmp(cp, "none") == 0) {
1659 				(void)strdelim(&cp);	/* discard */
1660 				break;
1661 			}
1662 			intptr = &options->rekey_interval;
1663 			goto parse_time;
1664 		}
1665 		break;
1666 
1667 	case sGatewayPorts:
1668 		intptr = &options->fwd_opts.gateway_ports;
1669 		multistate_ptr = multistate_gatewayports;
1670 		goto parse_multistate;
1671 
1672 	case sUseDNS:
1673 		intptr = &options->use_dns;
1674 		goto parse_flag;
1675 
1676 	case sLogFacility:
1677 		log_facility_ptr = &options->log_facility;
1678 		arg = strdelim(&cp);
1679 		value = log_facility_number(arg);
1680 		if (value == SYSLOG_FACILITY_NOT_SET)
1681 			fatal("%.200s line %d: unsupported log facility '%s'",
1682 			    filename, linenum, arg ? arg : "<NONE>");
1683 		if (*log_facility_ptr == -1)
1684 			*log_facility_ptr = (SyslogFacility) value;
1685 		break;
1686 
1687 	case sLogLevel:
1688 		log_level_ptr = &options->log_level;
1689 		arg = strdelim(&cp);
1690 		value = log_level_number(arg);
1691 		if (value == SYSLOG_LEVEL_NOT_SET)
1692 			fatal("%.200s line %d: unsupported log level '%s'",
1693 			    filename, linenum, arg ? arg : "<NONE>");
1694 		if (*activep && *log_level_ptr == -1)
1695 			*log_level_ptr = (LogLevel) value;
1696 		break;
1697 
1698 	case sAllowTcpForwarding:
1699 		intptr = &options->allow_tcp_forwarding;
1700 		multistate_ptr = multistate_tcpfwd;
1701 		goto parse_multistate;
1702 
1703 	case sAllowStreamLocalForwarding:
1704 		intptr = &options->allow_streamlocal_forwarding;
1705 		multistate_ptr = multistate_tcpfwd;
1706 		goto parse_multistate;
1707 
1708 	case sAllowAgentForwarding:
1709 		intptr = &options->allow_agent_forwarding;
1710 		goto parse_flag;
1711 
1712 	case sDisableForwarding:
1713 		intptr = &options->disable_forwarding;
1714 		goto parse_flag;
1715 
1716 	case sAllowUsers:
1717 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1718 			if (match_user(NULL, NULL, NULL, arg) == -1)
1719 				fatal("%s line %d: invalid AllowUsers pattern: "
1720 				    "\"%.100s\"", filename, linenum, arg);
1721 			if (!*activep)
1722 				continue;
1723 			array_append(filename, linenum, "AllowUsers",
1724 			    &options->allow_users, &options->num_allow_users,
1725 			    arg);
1726 		}
1727 		break;
1728 
1729 	case sDenyUsers:
1730 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1731 			if (match_user(NULL, NULL, NULL, arg) == -1)
1732 				fatal("%s line %d: invalid DenyUsers pattern: "
1733 				    "\"%.100s\"", filename, linenum, arg);
1734 			if (!*activep)
1735 				continue;
1736 			array_append(filename, linenum, "DenyUsers",
1737 			    &options->deny_users, &options->num_deny_users,
1738 			    arg);
1739 		}
1740 		break;
1741 
1742 	case sAllowGroups:
1743 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1744 			if (!*activep)
1745 				continue;
1746 			array_append(filename, linenum, "AllowGroups",
1747 			    &options->allow_groups, &options->num_allow_groups,
1748 			    arg);
1749 		}
1750 		break;
1751 
1752 	case sDenyGroups:
1753 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1754 			if (!*activep)
1755 				continue;
1756 			array_append(filename, linenum, "DenyGroups",
1757 			    &options->deny_groups, &options->num_deny_groups,
1758 			    arg);
1759 		}
1760 		break;
1761 
1762 	case sCiphers:
1763 		arg = strdelim(&cp);
1764 		if (!arg || *arg == '\0')
1765 			fatal("%s line %d: Missing argument.", filename, linenum);
1766 		if (*arg != '-' && !ciphers_valid(*arg == '+' ? arg + 1 : arg))
1767 			fatal("%s line %d: Bad SSH2 cipher spec '%s'.",
1768 			    filename, linenum, arg ? arg : "<NONE>");
1769 		if (options->ciphers == NULL)
1770 			options->ciphers = xstrdup(arg);
1771 		break;
1772 
1773 	case sMacs:
1774 		arg = strdelim(&cp);
1775 		if (!arg || *arg == '\0')
1776 			fatal("%s line %d: Missing argument.", filename, linenum);
1777 		if (*arg != '-' && !mac_valid(*arg == '+' ? arg + 1 : arg))
1778 			fatal("%s line %d: Bad SSH2 mac spec '%s'.",
1779 			    filename, linenum, arg ? arg : "<NONE>");
1780 		if (options->macs == NULL)
1781 			options->macs = xstrdup(arg);
1782 		break;
1783 
1784 	case sKexAlgorithms:
1785 		arg = strdelim(&cp);
1786 		if (!arg || *arg == '\0')
1787 			fatal("%s line %d: Missing argument.",
1788 			    filename, linenum);
1789 		if (*arg != '-' &&
1790 		    !kex_names_valid(*arg == '+' ? arg + 1 : arg))
1791 			fatal("%s line %d: Bad SSH2 KexAlgorithms '%s'.",
1792 			    filename, linenum, arg ? arg : "<NONE>");
1793 		if (options->kex_algorithms == NULL)
1794 			options->kex_algorithms = xstrdup(arg);
1795 		break;
1796 
1797 	case sSubsystem:
1798 		if (options->num_subsystems >= MAX_SUBSYSTEMS) {
1799 			fatal("%s line %d: too many subsystems defined.",
1800 			    filename, linenum);
1801 		}
1802 		arg = strdelim(&cp);
1803 		if (!arg || *arg == '\0')
1804 			fatal("%s line %d: Missing subsystem name.",
1805 			    filename, linenum);
1806 		if (!*activep) {
1807 			arg = strdelim(&cp);
1808 			break;
1809 		}
1810 		for (i = 0; i < options->num_subsystems; i++)
1811 			if (strcmp(arg, options->subsystem_name[i]) == 0)
1812 				fatal("%s line %d: Subsystem '%s' already defined.",
1813 				    filename, linenum, arg);
1814 		options->subsystem_name[options->num_subsystems] = xstrdup(arg);
1815 		arg = strdelim(&cp);
1816 		if (!arg || *arg == '\0')
1817 			fatal("%s line %d: Missing subsystem command.",
1818 			    filename, linenum);
1819 		options->subsystem_command[options->num_subsystems] = xstrdup(arg);
1820 
1821 		/* Collect arguments (separate to executable) */
1822 		p = xstrdup(arg);
1823 		len = strlen(p) + 1;
1824 		while ((arg = strdelim(&cp)) != NULL && *arg != '\0') {
1825 			len += 1 + strlen(arg);
1826 			p = xreallocarray(p, 1, len);
1827 			strlcat(p, " ", len);
1828 			strlcat(p, arg, len);
1829 		}
1830 		options->subsystem_args[options->num_subsystems] = p;
1831 		options->num_subsystems++;
1832 		break;
1833 
1834 	case sMaxStartups:
1835 		arg = strdelim(&cp);
1836 		if (!arg || *arg == '\0')
1837 			fatal("%s line %d: Missing MaxStartups spec.",
1838 			    filename, linenum);
1839 		if ((n = sscanf(arg, "%d:%d:%d",
1840 		    &options->max_startups_begin,
1841 		    &options->max_startups_rate,
1842 		    &options->max_startups)) == 3) {
1843 			if (options->max_startups_begin >
1844 			    options->max_startups ||
1845 			    options->max_startups_rate > 100 ||
1846 			    options->max_startups_rate < 1)
1847 				fatal("%s line %d: Illegal MaxStartups spec.",
1848 				    filename, linenum);
1849 		} else if (n != 1)
1850 			fatal("%s line %d: Illegal MaxStartups spec.",
1851 			    filename, linenum);
1852 		else
1853 			options->max_startups = options->max_startups_begin;
1854 		break;
1855 
1856 	case sMaxAuthTries:
1857 		intptr = &options->max_authtries;
1858 		goto parse_int;
1859 
1860 	case sMaxSessions:
1861 		intptr = &options->max_sessions;
1862 		goto parse_int;
1863 
1864 	case sBanner:
1865 		charptr = &options->banner;
1866 		goto parse_filename;
1867 
1868 	/*
1869 	 * These options can contain %X options expanded at
1870 	 * connect time, so that you can specify paths like:
1871 	 *
1872 	 * AuthorizedKeysFile	/etc/ssh_keys/%u
1873 	 */
1874 	case sAuthorizedKeysFile:
1875 		if (*activep && options->num_authkeys_files == 0) {
1876 			while ((arg = strdelim(&cp)) && *arg != '\0') {
1877 				arg = tilde_expand_filename(arg, getuid());
1878 				array_append(filename, linenum,
1879 				    "AuthorizedKeysFile",
1880 				    &options->authorized_keys_files,
1881 				    &options->num_authkeys_files, arg);
1882 				free(arg);
1883 			}
1884 		}
1885 		return 0;
1886 
1887 	case sAuthorizedPrincipalsFile:
1888 		charptr = &options->authorized_principals_file;
1889 		arg = strdelim(&cp);
1890 		if (!arg || *arg == '\0')
1891 			fatal("%s line %d: missing file name.",
1892 			    filename, linenum);
1893 		if (*activep && *charptr == NULL) {
1894 			*charptr = tilde_expand_filename(arg, getuid());
1895 			/* increase optional counter */
1896 			if (intptr != NULL)
1897 				*intptr = *intptr + 1;
1898 		}
1899 		break;
1900 
1901 	case sClientAliveInterval:
1902 		intptr = &options->client_alive_interval;
1903 		goto parse_time;
1904 
1905 	case sClientAliveCountMax:
1906 		intptr = &options->client_alive_count_max;
1907 		goto parse_int;
1908 
1909 	case sAcceptEnv:
1910 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1911 			if (strchr(arg, '=') != NULL)
1912 				fatal("%s line %d: Invalid environment name.",
1913 				    filename, linenum);
1914 			if (!*activep)
1915 				continue;
1916 			array_append(filename, linenum, "AcceptEnv",
1917 			    &options->accept_env, &options->num_accept_env,
1918 			    arg);
1919 		}
1920 		break;
1921 
1922 	case sPermitTunnel:
1923 		intptr = &options->permit_tun;
1924 		arg = strdelim(&cp);
1925 		if (!arg || *arg == '\0')
1926 			fatal("%s line %d: Missing yes/point-to-point/"
1927 			    "ethernet/no argument.", filename, linenum);
1928 		value = -1;
1929 		for (i = 0; tunmode_desc[i].val != -1; i++)
1930 			if (strcmp(tunmode_desc[i].text, arg) == 0) {
1931 				value = tunmode_desc[i].val;
1932 				break;
1933 			}
1934 		if (value == -1)
1935 			fatal("%s line %d: Bad yes/point-to-point/ethernet/"
1936 			    "no argument: %s", filename, linenum, arg);
1937 		if (*activep && *intptr == -1)
1938 			*intptr = value;
1939 		break;
1940 
1941 	case sMatch:
1942 		if (cmdline)
1943 			fatal("Match directive not supported as a command-line "
1944 			   "option");
1945 		value = match_cfg_line(&cp, linenum, connectinfo);
1946 		if (value < 0)
1947 			fatal("%s line %d: Bad Match condition", filename,
1948 			    linenum);
1949 		*activep = value;
1950 		break;
1951 
1952 	case sPermitOpen:
1953 		arg = strdelim(&cp);
1954 		if (!arg || *arg == '\0')
1955 			fatal("%s line %d: missing PermitOpen specification",
1956 			    filename, linenum);
1957 		value = options->num_permitted_opens;	/* modified later */
1958 		if (strcmp(arg, "any") == 0 || strcmp(arg, "none") == 0) {
1959 			if (*activep && value == 0) {
1960 				options->num_permitted_opens = 1;
1961 				options->permitted_opens = xcalloc(1,
1962 				    sizeof(*options->permitted_opens));
1963 				options->permitted_opens[0] = xstrdup(arg);
1964 			}
1965 			break;
1966 		}
1967 		for (; arg != NULL && *arg != '\0'; arg = strdelim(&cp)) {
1968 			arg2 = xstrdup(arg);
1969 			p = hpdelim(&arg);
1970 			if (p == NULL)
1971 				fatal("%s line %d: missing host in PermitOpen",
1972 				    filename, linenum);
1973 			p = cleanhostname(p);
1974 			if (arg == NULL || ((port = permitopen_port(arg)) < 0))
1975 				fatal("%s line %d: bad port number in "
1976 				    "PermitOpen", filename, linenum);
1977 			if (*activep && value == 0) {
1978 				array_append(filename, linenum,
1979 				    "PermitOpen",
1980 				    &options->permitted_opens,
1981 				    &options->num_permitted_opens, arg2);
1982 			}
1983 			free(arg2);
1984 		}
1985 		break;
1986 
1987 	case sForceCommand:
1988 		if (cp == NULL || *cp == '\0')
1989 			fatal("%.200s line %d: Missing argument.", filename,
1990 			    linenum);
1991 		len = strspn(cp, WHITESPACE);
1992 		if (*activep && options->adm_forced_command == NULL)
1993 			options->adm_forced_command = xstrdup(cp + len);
1994 		return 0;
1995 
1996 	case sChrootDirectory:
1997 		charptr = &options->chroot_directory;
1998 
1999 		arg = strdelim(&cp);
2000 		if (!arg || *arg == '\0')
2001 			fatal("%s line %d: missing file name.",
2002 			    filename, linenum);
2003 		if (*activep && *charptr == NULL)
2004 			*charptr = xstrdup(arg);
2005 		break;
2006 
2007 	case sTrustedUserCAKeys:
2008 		charptr = &options->trusted_user_ca_keys;
2009 		goto parse_filename;
2010 
2011 	case sRevokedKeys:
2012 		charptr = &options->revoked_keys_file;
2013 		goto parse_filename;
2014 
2015 	case sIPQoS:
2016 		arg = strdelim(&cp);
2017 		if ((value = parse_ipqos(arg)) == -1)
2018 			fatal("%s line %d: Bad IPQoS value: %s",
2019 			    filename, linenum, arg);
2020 		arg = strdelim(&cp);
2021 		if (arg == NULL)
2022 			value2 = value;
2023 		else if ((value2 = parse_ipqos(arg)) == -1)
2024 			fatal("%s line %d: Bad IPQoS value: %s",
2025 			    filename, linenum, arg);
2026 		if (*activep) {
2027 			options->ip_qos_interactive = value;
2028 			options->ip_qos_bulk = value2;
2029 		}
2030 		break;
2031 
2032 	case sVersionAddendum:
2033 		if (cp == NULL || *cp == '\0')
2034 			fatal("%.200s line %d: Missing argument.", filename,
2035 			    linenum);
2036 		len = strspn(cp, WHITESPACE);
2037 		if (*activep && options->version_addendum == NULL) {
2038 			if (strcasecmp(cp + len, "none") == 0)
2039 				options->version_addendum = xstrdup("");
2040 			else if (strchr(cp + len, '\r') != NULL)
2041 				fatal("%.200s line %d: Invalid argument",
2042 				    filename, linenum);
2043 			else
2044 				options->version_addendum = xstrdup(cp + len);
2045 		}
2046 		return 0;
2047 
2048 	case sAuthorizedKeysCommand:
2049 		if (cp == NULL)
2050 			fatal("%.200s line %d: Missing argument.", filename,
2051 			    linenum);
2052 		len = strspn(cp, WHITESPACE);
2053 		if (*activep && options->authorized_keys_command == NULL) {
2054 			if (cp[len] != '/' && strcasecmp(cp + len, "none") != 0)
2055 				fatal("%.200s line %d: AuthorizedKeysCommand "
2056 				    "must be an absolute path",
2057 				    filename, linenum);
2058 			options->authorized_keys_command = xstrdup(cp + len);
2059 		}
2060 		return 0;
2061 
2062 	case sAuthorizedKeysCommandUser:
2063 		charptr = &options->authorized_keys_command_user;
2064 
2065 		arg = strdelim(&cp);
2066 		if (!arg || *arg == '\0')
2067 			fatal("%s line %d: missing AuthorizedKeysCommandUser "
2068 			    "argument.", filename, linenum);
2069 		if (*activep && *charptr == NULL)
2070 			*charptr = xstrdup(arg);
2071 		break;
2072 
2073 	case sAuthorizedPrincipalsCommand:
2074 		if (cp == NULL)
2075 			fatal("%.200s line %d: Missing argument.", filename,
2076 			    linenum);
2077 		len = strspn(cp, WHITESPACE);
2078 		if (*activep &&
2079 		    options->authorized_principals_command == NULL) {
2080 			if (cp[len] != '/' && strcasecmp(cp + len, "none") != 0)
2081 				fatal("%.200s line %d: "
2082 				    "AuthorizedPrincipalsCommand must be "
2083 				    "an absolute path", filename, linenum);
2084 			options->authorized_principals_command =
2085 			    xstrdup(cp + len);
2086 		}
2087 		return 0;
2088 
2089 	case sAuthorizedPrincipalsCommandUser:
2090 		charptr = &options->authorized_principals_command_user;
2091 
2092 		arg = strdelim(&cp);
2093 		if (!arg || *arg == '\0')
2094 			fatal("%s line %d: missing "
2095 			    "AuthorizedPrincipalsCommandUser argument.",
2096 			    filename, linenum);
2097 		if (*activep && *charptr == NULL)
2098 			*charptr = xstrdup(arg);
2099 		break;
2100 
2101 	case sAuthenticationMethods:
2102 		if (options->num_auth_methods == 0) {
2103 			value = 0; /* seen "any" pseudo-method */
2104 			value2 = 0; /* sucessfully parsed any method */
2105 			while ((arg = strdelim(&cp)) && *arg != '\0') {
2106 				if (strcmp(arg, "any") == 0) {
2107 					if (options->num_auth_methods > 0) {
2108 						fatal("%s line %d: \"any\" "
2109 						    "must appear alone in "
2110 						    "AuthenticationMethods",
2111 						    filename, linenum);
2112 					}
2113 					value = 1;
2114 				} else if (value) {
2115 					fatal("%s line %d: \"any\" must appear "
2116 					    "alone in AuthenticationMethods",
2117 					    filename, linenum);
2118 				} else if (auth2_methods_valid(arg, 0) != 0) {
2119 					fatal("%s line %d: invalid "
2120 					    "authentication method list.",
2121 					    filename, linenum);
2122 				}
2123 				value2 = 1;
2124 				if (!*activep)
2125 					continue;
2126 				array_append(filename, linenum,
2127 				    "AuthenticationMethods",
2128 				    &options->auth_methods,
2129 				    &options->num_auth_methods, arg);
2130 			}
2131 			if (value2 == 0) {
2132 				fatal("%s line %d: no AuthenticationMethods "
2133 				    "specified", filename, linenum);
2134 			}
2135 		}
2136 		return 0;
2137 
2138 	case sStreamLocalBindMask:
2139 		arg = strdelim(&cp);
2140 		if (!arg || *arg == '\0')
2141 			fatal("%s line %d: missing StreamLocalBindMask "
2142 			    "argument.", filename, linenum);
2143 		/* Parse mode in octal format */
2144 		value = strtol(arg, &p, 8);
2145 		if (arg == p || value < 0 || value > 0777)
2146 			fatal("%s line %d: Bad mask.", filename, linenum);
2147 		if (*activep)
2148 			options->fwd_opts.streamlocal_bind_mask = (mode_t)value;
2149 		break;
2150 
2151 	case sStreamLocalBindUnlink:
2152 		intptr = &options->fwd_opts.streamlocal_bind_unlink;
2153 		goto parse_flag;
2154 
2155 	case sFingerprintHash:
2156 		arg = strdelim(&cp);
2157 		if (!arg || *arg == '\0')
2158 			fatal("%.200s line %d: Missing argument.",
2159 			    filename, linenum);
2160 		if ((value = ssh_digest_alg_by_name(arg)) == -1)
2161 			fatal("%.200s line %d: Invalid hash algorithm \"%s\".",
2162 			    filename, linenum, arg);
2163 		if (*activep)
2164 			options->fingerprint_hash = value;
2165 		break;
2166 
2167 	case sExposeAuthInfo:
2168 		intptr = &options->expose_userauth_info;
2169 		goto parse_flag;
2170 
2171 	case sRDomain:
2172 		charptr = &options->routing_domain;
2173 		arg = strdelim(&cp);
2174 		if (!arg || *arg == '\0')
2175 			fatal("%.200s line %d: Missing argument.",
2176 			    filename, linenum);
2177 		if (strcasecmp(arg, "none") != 0 && strcmp(arg, "%D") != 0 &&
2178 		    !valid_rdomain(arg))
2179 			fatal("%s line %d: bad routing domain",
2180 			    filename, linenum);
2181 		if (*activep && *charptr == NULL)
2182 			*charptr = xstrdup(arg);
2183 		break;
2184 
2185 	case sDeprecated:
2186 	case sIgnore:
2187 	case sUnsupported:
2188 		do_log2(opcode == sIgnore ?
2189 		    SYSLOG_LEVEL_DEBUG2 : SYSLOG_LEVEL_INFO,
2190 		    "%s line %d: %s option %s", filename, linenum,
2191 		    opcode == sUnsupported ? "Unsupported" : "Deprecated", arg);
2192 		while (arg)
2193 		    arg = strdelim(&cp);
2194 		break;
2195 
2196 #ifdef WITH_LDAP_PUBKEY
2197 	case sLdapPublickey:
2198 		intptr = &options->lpk.on;
2199 		goto parse_flag;
2200 	case sLdapServers:
2201 		/* arg = strdelim(&cp); */
2202 		p = line;
2203 		while(*p++);
2204 		arg = p;
2205 		if (!arg || *arg == '\0')
2206 		    fatal("%s line %d: missing ldap server",filename,linenum);
2207 		arg[strlen(arg)] = '\0';
2208 		if ((options->lpk.servers = ldap_parse_servers(arg)) == NULL)
2209 		    fatal("%s line %d: error in ldap servers", filename, linenum);
2210 		memset(arg,0,strlen(arg));
2211 		break;
2212 	case sLdapUserDN:
2213 		arg = cp;
2214 		if (!arg || *arg == '\0')
2215 		    fatal("%s line %d: missing ldap server",filename,linenum);
2216 		arg[strlen(arg)] = '\0';
2217 		options->lpk.u_basedn = xstrdup(arg);
2218 		memset(arg,0,strlen(arg));
2219 		break;
2220 	case sLdapGroupDN:
2221 		arg = cp;
2222 		if (!arg || *arg == '\0')
2223 		    fatal("%s line %d: missing ldap server",filename,linenum);
2224 		arg[strlen(arg)] = '\0';
2225 		options->lpk.g_basedn = xstrdup(arg);
2226 		memset(arg,0,strlen(arg));
2227 		break;
2228 	case sBindDN:
2229 		arg = cp;
2230 		if (!arg || *arg == '\0')
2231 		    fatal("%s line %d: missing binddn",filename,linenum);
2232 		arg[strlen(arg)] = '\0';
2233 		options->lpk.binddn = xstrdup(arg);
2234 		memset(arg,0,strlen(arg));
2235 		break;
2236 	case sBindPw:
2237 		arg = cp;
2238 		if (!arg || *arg == '\0')
2239 		    fatal("%s line %d: missing bindpw",filename,linenum);
2240 		arg[strlen(arg)] = '\0';
2241 		options->lpk.bindpw = xstrdup(arg);
2242 		memset(arg,0,strlen(arg));
2243 		break;
2244 	case sMyGroup:
2245 		arg = cp;
2246 		if (!arg || *arg == '\0')
2247 		    fatal("%s line %d: missing groupname",filename, linenum);
2248 		arg[strlen(arg)] = '\0';
2249 		options->lpk.sgroup = xstrdup(arg);
2250 		if (options->lpk.sgroup)
2251 		    options->lpk.fgroup = ldap_parse_groups(options->lpk.sgroup);
2252 		memset(arg,0,strlen(arg));
2253 		break;
2254 	case sLdapFilter:
2255 		arg = cp;
2256 		if (!arg || *arg == '\0')
2257 		    fatal("%s line %d: missing filter",filename, linenum);
2258 		arg[strlen(arg)] = '\0';
2259 		options->lpk.filter = xstrdup(arg);
2260 		memset(arg,0,strlen(arg));
2261 		break;
2262 	case sForceTLS:
2263 		intptr = &options->lpk.tls;
2264 		arg = strdelim(&cp);
2265 		if (!arg || *arg == '\0')
2266 			fatal("%s line %d: missing yes/no argument.",
2267 			    filename, linenum);
2268 		value = 0;	/* silence compiler */
2269 		if (strcmp(arg, "yes") == 0)
2270 			value = 1;
2271 		else if (strcmp(arg, "no") == 0)
2272 			value = 0;
2273 		else if (strcmp(arg, "try") == 0)
2274 			value = -1;
2275 		else
2276 			fatal("%s line %d: Bad yes/no argument: %s",
2277 				filename, linenum, arg);
2278 		if (*intptr == -1)
2279 			*intptr = value;
2280 		break;
2281 	case sBindTimeout:
2282 		timetptr = &options->lpk.b_timeout.tv_sec;
2283 parse_ulong:
2284 		arg = strdelim(&cp);
2285 		if (!arg || *arg == '\0')
2286 			fatal("%s line %d: missing integer value.",
2287 			    filename, linenum);
2288 		lvalue = atol(arg);
2289 		if (*activep && *timetptr == -1)
2290 			*timetptr = lvalue;
2291 		break;
2292 
2293 	case sSearchTimeout:
2294 		timetptr = &options->lpk.s_timeout.tv_sec;
2295 		goto parse_ulong;
2296 		break;
2297 	case sLdapConf:
2298 		arg = cp;
2299 		if (!arg || *arg == '\0')
2300 		    fatal("%s line %d: missing LpkLdapConf", filename, linenum);
2301 		arg[strlen(arg)] = '\0';
2302 		options->lpk.l_conf = xstrdup(arg);
2303 		memset(arg, 0, strlen(arg));
2304 		break;
2305 	case sLpkPubKeyAttr:
2306 		arg = cp;
2307                 if (!arg || *arg == '\0')
2308                     fatal("%s line %d: missing pubkeyattr",filename,linenum);
2309                 arg[strlen(arg)] = '\0';
2310                 options->lpk.pub_key_attr = xstrdup(arg);
2311                 memset(arg,0,strlen(arg));
2312                 break;
2313 
2314 #endif
2315 
2316 	default:
2317 		fatal("%s line %d: Missing handler for opcode %s (%d)",
2318 		    filename, linenum, arg, opcode);
2319 	}
2320 	if ((arg = strdelim(&cp)) != NULL && *arg != '\0')
2321 		fatal("%s line %d: garbage at end of line; \"%.200s\".",
2322 		    filename, linenum, arg);
2323 	return 0;
2324 }
2325 
2326 /* Reads the server configuration file. */
2327 
2328 void
2329 load_server_config(const char *filename, Buffer *conf)
2330 {
2331 	char line[4096], *cp;
2332 	FILE *f;
2333 	int lineno = 0;
2334 
2335 	debug2("%s: filename %s", __func__, filename);
2336 	if ((f = fopen(filename, "r")) == NULL) {
2337 		perror(filename);
2338 		exit(1);
2339 	}
2340 	buffer_clear(conf);
2341 	while (fgets(line, sizeof(line), f)) {
2342 		lineno++;
2343 		if (strlen(line) == sizeof(line) - 1)
2344 			fatal("%s line %d too long", filename, lineno);
2345 		/*
2346 		 * Trim out comments and strip whitespace
2347 		 * NB - preserve newlines, they are needed to reproduce
2348 		 * line numbers later for error messages
2349 		 */
2350 		if ((cp = strchr(line, '#')) != NULL)
2351 			memcpy(cp, "\n", 2);
2352 		cp = line + strspn(line, " \t\r");
2353 
2354 		buffer_append(conf, cp, strlen(cp));
2355 	}
2356 	buffer_append(conf, "\0", 1);
2357 	fclose(f);
2358 	debug2("%s: done config len = %d", __func__, buffer_len(conf));
2359 }
2360 
2361 void
2362 parse_server_match_config(ServerOptions *options,
2363    struct connection_info *connectinfo)
2364 {
2365 	ServerOptions mo;
2366 
2367 	initialize_server_options(&mo);
2368 	parse_server_config(&mo, "reprocess config", &cfg, connectinfo);
2369 	copy_set_server_options(options, &mo, 0);
2370 }
2371 
2372 int parse_server_match_testspec(struct connection_info *ci, char *spec)
2373 {
2374 	char *p;
2375 
2376 	while ((p = strsep(&spec, ",")) && *p != '\0') {
2377 		if (strncmp(p, "addr=", 5) == 0) {
2378 			ci->address = xstrdup(p + 5);
2379 		} else if (strncmp(p, "host=", 5) == 0) {
2380 			ci->host = xstrdup(p + 5);
2381 		} else if (strncmp(p, "user=", 5) == 0) {
2382 			ci->user = xstrdup(p + 5);
2383 		} else if (strncmp(p, "laddr=", 6) == 0) {
2384 			ci->laddress = xstrdup(p + 6);
2385 		} else if (strncmp(p, "rdomain=", 8) == 0) {
2386 			ci->rdomain = xstrdup(p + 8);
2387 		} else if (strncmp(p, "lport=", 6) == 0) {
2388 			ci->lport = a2port(p + 6);
2389 			if (ci->lport == -1) {
2390 				fprintf(stderr, "Invalid port '%s' in test mode"
2391 				   " specification %s\n", p+6, p);
2392 				return -1;
2393 			}
2394 		} else {
2395 			fprintf(stderr, "Invalid test mode specification %s\n",
2396 			   p);
2397 			return -1;
2398 		}
2399 	}
2400 	return 0;
2401 }
2402 
2403 /*
2404  * Copy any supported values that are set.
2405  *
2406  * If the preauth flag is set, we do not bother copying the string or
2407  * array values that are not used pre-authentication, because any that we
2408  * do use must be explictly sent in mm_getpwnamallow().
2409  */
2410 void
2411 copy_set_server_options(ServerOptions *dst, ServerOptions *src, int preauth)
2412 {
2413 #define M_CP_INTOPT(n) do {\
2414 	if (src->n != -1) \
2415 		dst->n = src->n; \
2416 } while (0)
2417 
2418 	M_CP_INTOPT(password_authentication);
2419 	M_CP_INTOPT(gss_authentication);
2420 	M_CP_INTOPT(pubkey_authentication);
2421 	M_CP_INTOPT(kerberos_authentication);
2422 	M_CP_INTOPT(hostbased_authentication);
2423 	M_CP_INTOPT(hostbased_uses_name_from_packet_only);
2424 	M_CP_INTOPT(kbd_interactive_authentication);
2425 	M_CP_INTOPT(permit_root_login);
2426 	M_CP_INTOPT(permit_empty_passwd);
2427 
2428 	M_CP_INTOPT(allow_tcp_forwarding);
2429 	M_CP_INTOPT(allow_streamlocal_forwarding);
2430 	M_CP_INTOPT(allow_agent_forwarding);
2431 	M_CP_INTOPT(disable_forwarding);
2432 	M_CP_INTOPT(expose_userauth_info);
2433 	M_CP_INTOPT(permit_tun);
2434 	M_CP_INTOPT(fwd_opts.gateway_ports);
2435 	M_CP_INTOPT(fwd_opts.streamlocal_bind_unlink);
2436 	M_CP_INTOPT(x11_display_offset);
2437 	M_CP_INTOPT(x11_forwarding);
2438 	M_CP_INTOPT(x11_use_localhost);
2439 	M_CP_INTOPT(permit_tty);
2440 	M_CP_INTOPT(permit_user_rc);
2441 	M_CP_INTOPT(max_sessions);
2442 	M_CP_INTOPT(max_authtries);
2443 	M_CP_INTOPT(client_alive_count_max);
2444 	M_CP_INTOPT(client_alive_interval);
2445 	M_CP_INTOPT(ip_qos_interactive);
2446 	M_CP_INTOPT(ip_qos_bulk);
2447 	M_CP_INTOPT(rekey_limit);
2448 	M_CP_INTOPT(rekey_interval);
2449 	M_CP_INTOPT(log_level);
2450 
2451 	/*
2452 	 * The bind_mask is a mode_t that may be unsigned, so we can't use
2453 	 * M_CP_INTOPT - it does a signed comparison that causes compiler
2454 	 * warnings.
2455 	 */
2456 	if (src->fwd_opts.streamlocal_bind_mask != (mode_t)-1) {
2457 		dst->fwd_opts.streamlocal_bind_mask =
2458 		    src->fwd_opts.streamlocal_bind_mask;
2459 	}
2460 
2461 	/* M_CP_STROPT and M_CP_STRARRAYOPT should not appear before here */
2462 #define M_CP_STROPT(n) do {\
2463 	if (src->n != NULL && dst->n != src->n) { \
2464 		free(dst->n); \
2465 		dst->n = src->n; \
2466 	} \
2467 } while(0)
2468 #define M_CP_STRARRAYOPT(s, num_s) do {\
2469 	u_int i; \
2470 	if (src->num_s != 0) { \
2471 		for (i = 0; i < dst->num_s; i++) \
2472 			free(dst->s[i]); \
2473 		free(dst->s); \
2474 		dst->s = xcalloc(src->num_s, sizeof(*dst->s)); \
2475 		for (i = 0; i < src->num_s; i++) \
2476 			dst->s[i] = xstrdup(src->s[i]); \
2477 		dst->num_s = src->num_s; \
2478 	} \
2479 } while(0)
2480 
2481 	/* See comment in servconf.h */
2482 	COPY_MATCH_STRING_OPTS();
2483 
2484 	/* Arguments that accept '+...' need to be expanded */
2485 	assemble_algorithms(dst);
2486 
2487 	/*
2488 	 * The only things that should be below this point are string options
2489 	 * which are only used after authentication.
2490 	 */
2491 	if (preauth)
2492 		return;
2493 
2494 	/* These options may be "none" to clear a global setting */
2495 	M_CP_STROPT(adm_forced_command);
2496 	if (option_clear_or_none(dst->adm_forced_command)) {
2497 		free(dst->adm_forced_command);
2498 		dst->adm_forced_command = NULL;
2499 	}
2500 	M_CP_STROPT(chroot_directory);
2501 	if (option_clear_or_none(dst->chroot_directory)) {
2502 		free(dst->chroot_directory);
2503 		dst->chroot_directory = NULL;
2504 	}
2505 }
2506 
2507 #undef M_CP_INTOPT
2508 #undef M_CP_STROPT
2509 #undef M_CP_STRARRAYOPT
2510 
2511 void
2512 parse_server_config(ServerOptions *options, const char *filename, Buffer *conf,
2513     struct connection_info *connectinfo)
2514 {
2515 	int active, linenum, bad_options = 0;
2516 	char *cp, *obuf, *cbuf;
2517 
2518 	debug2("%s: config %s len %d", __func__, filename, buffer_len(conf));
2519 
2520 	if ((obuf = cbuf = sshbuf_dup_string(conf)) == NULL)
2521 		fatal("%s: sshbuf_dup_string failed", __func__);
2522 	active = connectinfo ? 0 : 1;
2523 	linenum = 1;
2524 	while ((cp = strsep(&cbuf, "\n")) != NULL) {
2525 		if (process_server_config_line(options, cp, filename,
2526 		    linenum++, &active, connectinfo) != 0)
2527 			bad_options++;
2528 	}
2529 	free(obuf);
2530 	if (bad_options > 0)
2531 		fatal("%s: terminating, %d bad configuration options",
2532 		    filename, bad_options);
2533 	process_queued_listen_addrs(options);
2534 }
2535 
2536 static const char *
2537 fmt_multistate_int(int val, const struct multistate *m)
2538 {
2539 	u_int i;
2540 
2541 	for (i = 0; m[i].key != NULL; i++) {
2542 		if (m[i].value == val)
2543 			return m[i].key;
2544 	}
2545 	return "UNKNOWN";
2546 }
2547 
2548 static const char *
2549 fmt_intarg(ServerOpCodes code, int val)
2550 {
2551 	if (val == -1)
2552 		return "unset";
2553 	switch (code) {
2554 	case sAddressFamily:
2555 		return fmt_multistate_int(val, multistate_addressfamily);
2556 	case sPermitRootLogin:
2557 		return fmt_multistate_int(val, multistate_permitrootlogin);
2558 	case sGatewayPorts:
2559 		return fmt_multistate_int(val, multistate_gatewayports);
2560 	case sCompression:
2561 		return fmt_multistate_int(val, multistate_compression);
2562 	case sAllowTcpForwarding:
2563 		return fmt_multistate_int(val, multistate_tcpfwd);
2564 	case sAllowStreamLocalForwarding:
2565 		return fmt_multistate_int(val, multistate_tcpfwd);
2566 	case sFingerprintHash:
2567 		return ssh_digest_alg_name(val);
2568 	default:
2569 		switch (val) {
2570 		case 0:
2571 			return "no";
2572 		case 1:
2573 			return "yes";
2574 		default:
2575 			return "UNKNOWN";
2576 		}
2577 	}
2578 }
2579 
2580 static const char *
2581 lookup_opcode_name(ServerOpCodes code)
2582 {
2583 	u_int i;
2584 
2585 	for (i = 0; keywords[i].name != NULL; i++)
2586 		if (keywords[i].opcode == code)
2587 			return(keywords[i].name);
2588 	return "UNKNOWN";
2589 }
2590 
2591 static void
2592 dump_cfg_int(ServerOpCodes code, int val)
2593 {
2594 	printf("%s %d\n", lookup_opcode_name(code), val);
2595 }
2596 
2597 static void
2598 dump_cfg_oct(ServerOpCodes code, int val)
2599 {
2600 	printf("%s 0%o\n", lookup_opcode_name(code), val);
2601 }
2602 
2603 static void
2604 dump_cfg_fmtint(ServerOpCodes code, int val)
2605 {
2606 	printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
2607 }
2608 
2609 static void
2610 dump_cfg_string(ServerOpCodes code, const char *val)
2611 {
2612 	printf("%s %s\n", lookup_opcode_name(code),
2613 	    val == NULL ? "none" : val);
2614 }
2615 
2616 static void
2617 dump_cfg_strarray(ServerOpCodes code, u_int count, char **vals)
2618 {
2619 	u_int i;
2620 
2621 	for (i = 0; i < count; i++)
2622 		printf("%s %s\n", lookup_opcode_name(code), vals[i]);
2623 }
2624 
2625 static void
2626 dump_cfg_strarray_oneline(ServerOpCodes code, u_int count, char **vals)
2627 {
2628 	u_int i;
2629 
2630 	if (count <= 0 && code != sAuthenticationMethods)
2631 		return;
2632 	printf("%s", lookup_opcode_name(code));
2633 	for (i = 0; i < count; i++)
2634 		printf(" %s",  vals[i]);
2635 	if (code == sAuthenticationMethods && count == 0)
2636 		printf(" any");
2637 	printf("\n");
2638 }
2639 
2640 static char *
2641 format_listen_addrs(struct listenaddr *la)
2642 {
2643 	int r;
2644 	struct addrinfo *ai;
2645 	char addr[NI_MAXHOST], port[NI_MAXSERV];
2646 	char *laddr1 = xstrdup(""), *laddr2 = NULL;
2647 
2648 	/*
2649 	 * ListenAddress must be after Port.  add_one_listen_addr pushes
2650 	 * addresses onto a stack, so to maintain ordering we need to
2651 	 * print these in reverse order.
2652 	 */
2653 	for (ai = la->addrs; ai; ai = ai->ai_next) {
2654 		if ((r = getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
2655 		    sizeof(addr), port, sizeof(port),
2656 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
2657 			error("getnameinfo: %.100s", ssh_gai_strerror(r));
2658 			continue;
2659 		}
2660 		laddr2 = laddr1;
2661 		if (ai->ai_family == AF_INET6) {
2662 			xasprintf(&laddr1, "listenaddress [%s]:%s%s%s\n%s",
2663 			    addr, port,
2664 			    la->rdomain == NULL ? "" : " rdomain ",
2665 			    la->rdomain == NULL ? "" : la->rdomain,
2666 			    laddr2);
2667 		} else {
2668 			xasprintf(&laddr1, "listenaddress %s:%s%s%s\n%s",
2669 			    addr, port,
2670 			    la->rdomain == NULL ? "" : " rdomain ",
2671 			    la->rdomain == NULL ? "" : la->rdomain,
2672 			    laddr2);
2673 		}
2674 		free(laddr2);
2675 	}
2676 	return laddr1;
2677 }
2678 
2679 void
2680 dump_config(ServerOptions *o)
2681 {
2682 	const char *s;
2683 	u_int i;
2684 
2685 	/* these are usually at the top of the config */
2686 	for (i = 0; i < o->num_ports; i++)
2687 		printf("port %d\n", o->ports[i]);
2688 	dump_cfg_fmtint(sAddressFamily, o->address_family);
2689 
2690 	for (i = 0; i < o->num_listen_addrs; i++) {
2691 		char *ss = format_listen_addrs(&o->listen_addrs[i]);
2692 		printf("%s", ss);
2693 		free(ss);
2694 	}
2695 
2696 	/* integer arguments */
2697 	dump_cfg_int(sLoginGraceTime, o->login_grace_time);
2698 	dump_cfg_int(sX11DisplayOffset, o->x11_display_offset);
2699 	dump_cfg_int(sMaxAuthTries, o->max_authtries);
2700 	dump_cfg_int(sMaxSessions, o->max_sessions);
2701 	dump_cfg_int(sClientAliveInterval, o->client_alive_interval);
2702 	dump_cfg_int(sClientAliveCountMax, o->client_alive_count_max);
2703 	dump_cfg_oct(sStreamLocalBindMask, o->fwd_opts.streamlocal_bind_mask);
2704 
2705 	/* formatted integer arguments */
2706 	dump_cfg_fmtint(sPermitRootLogin, o->permit_root_login);
2707 	dump_cfg_fmtint(sIgnoreRhosts, o->ignore_rhosts);
2708 	dump_cfg_fmtint(sIgnoreUserKnownHosts, o->ignore_user_known_hosts);
2709 	dump_cfg_fmtint(sHostbasedAuthentication, o->hostbased_authentication);
2710 	dump_cfg_fmtint(sHostbasedUsesNameFromPacketOnly,
2711 	    o->hostbased_uses_name_from_packet_only);
2712 	dump_cfg_fmtint(sPubkeyAuthentication, o->pubkey_authentication);
2713 #ifdef KRB5
2714 	dump_cfg_fmtint(sKerberosAuthentication, o->kerberos_authentication);
2715 	dump_cfg_fmtint(sKerberosOrLocalPasswd, o->kerberos_or_local_passwd);
2716 	dump_cfg_fmtint(sKerberosTicketCleanup, o->kerberos_ticket_cleanup);
2717 	dump_cfg_fmtint(sKerberosGetAFSToken, o->kerberos_get_afs_token);
2718 #endif
2719 #ifdef GSSAPI
2720 	dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
2721 	dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
2722 #endif
2723 	dump_cfg_fmtint(sPasswordAuthentication, o->password_authentication);
2724 	dump_cfg_fmtint(sKbdInteractiveAuthentication,
2725 	    o->kbd_interactive_authentication);
2726 	dump_cfg_fmtint(sChallengeResponseAuthentication,
2727 	    o->challenge_response_authentication);
2728 	dump_cfg_fmtint(sPrintMotd, o->print_motd);
2729 	dump_cfg_fmtint(sPrintLastLog, o->print_lastlog);
2730 	dump_cfg_fmtint(sX11Forwarding, o->x11_forwarding);
2731 	dump_cfg_fmtint(sX11UseLocalhost, o->x11_use_localhost);
2732 	dump_cfg_fmtint(sPermitTTY, o->permit_tty);
2733 	dump_cfg_fmtint(sPermitUserRC, o->permit_user_rc);
2734 	dump_cfg_fmtint(sStrictModes, o->strict_modes);
2735 	dump_cfg_fmtint(sTCPKeepAlive, o->tcp_keep_alive);
2736 	dump_cfg_fmtint(sEmptyPasswd, o->permit_empty_passwd);
2737 	dump_cfg_fmtint(sPermitUserEnvironment, o->permit_user_env);
2738 	dump_cfg_fmtint(sCompression, o->compression);
2739 	dump_cfg_fmtint(sGatewayPorts, o->fwd_opts.gateway_ports);
2740 	dump_cfg_fmtint(sUseDNS, o->use_dns);
2741 	dump_cfg_fmtint(sAllowTcpForwarding, o->allow_tcp_forwarding);
2742 	dump_cfg_fmtint(sAllowAgentForwarding, o->allow_agent_forwarding);
2743 	dump_cfg_fmtint(sDisableForwarding, o->disable_forwarding);
2744 	dump_cfg_fmtint(sAllowStreamLocalForwarding, o->allow_streamlocal_forwarding);
2745 	dump_cfg_fmtint(sStreamLocalBindUnlink, o->fwd_opts.streamlocal_bind_unlink);
2746 	dump_cfg_fmtint(sFingerprintHash, o->fingerprint_hash);
2747 	dump_cfg_fmtint(sExposeAuthInfo, o->expose_userauth_info);
2748 
2749 	/* string arguments */
2750 	dump_cfg_string(sPidFile, o->pid_file);
2751 	dump_cfg_string(sXAuthLocation, o->xauth_location);
2752 	dump_cfg_string(sCiphers, o->ciphers ? o->ciphers : KEX_SERVER_ENCRYPT);
2753 	dump_cfg_string(sMacs, o->macs ? o->macs : KEX_SERVER_MAC);
2754 	dump_cfg_string(sBanner, o->banner);
2755 	dump_cfg_string(sForceCommand, o->adm_forced_command);
2756 	dump_cfg_string(sChrootDirectory, o->chroot_directory);
2757 	dump_cfg_string(sTrustedUserCAKeys, o->trusted_user_ca_keys);
2758 	dump_cfg_string(sRevokedKeys, o->revoked_keys_file);
2759 	dump_cfg_string(sAuthorizedPrincipalsFile,
2760 	    o->authorized_principals_file);
2761 	dump_cfg_string(sVersionAddendum, *o->version_addendum == '\0'
2762 	    ? "none" : o->version_addendum);
2763 	dump_cfg_string(sAuthorizedKeysCommand, o->authorized_keys_command);
2764 	dump_cfg_string(sAuthorizedKeysCommandUser, o->authorized_keys_command_user);
2765 	dump_cfg_string(sAuthorizedPrincipalsCommand, o->authorized_principals_command);
2766 	dump_cfg_string(sAuthorizedPrincipalsCommandUser, o->authorized_principals_command_user);
2767 	dump_cfg_string(sHostKeyAgent, o->host_key_agent);
2768 	dump_cfg_string(sKexAlgorithms,
2769 	    o->kex_algorithms ? o->kex_algorithms : KEX_SERVER_KEX);
2770 	dump_cfg_string(sHostbasedAcceptedKeyTypes, o->hostbased_key_types ?
2771 	    o->hostbased_key_types : KEX_DEFAULT_PK_ALG);
2772 	dump_cfg_string(sHostKeyAlgorithms, o->hostkeyalgorithms ?
2773 	    o->hostkeyalgorithms : KEX_DEFAULT_PK_ALG);
2774 	dump_cfg_string(sPubkeyAcceptedKeyTypes, o->pubkey_key_types ?
2775 	    o->pubkey_key_types : KEX_DEFAULT_PK_ALG);
2776 	dump_cfg_string(sRDomain, o->routing_domain);
2777 
2778 	/* string arguments requiring a lookup */
2779 	dump_cfg_string(sLogLevel, log_level_name(o->log_level));
2780 	dump_cfg_string(sLogFacility, log_facility_name(o->log_facility));
2781 
2782 	/* string array arguments */
2783 	dump_cfg_strarray_oneline(sAuthorizedKeysFile, o->num_authkeys_files,
2784 	    o->authorized_keys_files);
2785 	dump_cfg_strarray(sHostKeyFile, o->num_host_key_files,
2786 	     o->host_key_files);
2787 	dump_cfg_strarray(sHostCertificate, o->num_host_cert_files,
2788 	     o->host_cert_files);
2789 	dump_cfg_strarray(sAllowUsers, o->num_allow_users, o->allow_users);
2790 	dump_cfg_strarray(sDenyUsers, o->num_deny_users, o->deny_users);
2791 	dump_cfg_strarray(sAllowGroups, o->num_allow_groups, o->allow_groups);
2792 	dump_cfg_strarray(sDenyGroups, o->num_deny_groups, o->deny_groups);
2793 	dump_cfg_strarray(sAcceptEnv, o->num_accept_env, o->accept_env);
2794 	dump_cfg_strarray_oneline(sAuthenticationMethods,
2795 	    o->num_auth_methods, o->auth_methods);
2796 
2797 	/* other arguments */
2798 	for (i = 0; i < o->num_subsystems; i++)
2799 		printf("subsystem %s %s\n", o->subsystem_name[i],
2800 		    o->subsystem_args[i]);
2801 
2802 	printf("maxstartups %d:%d:%d\n", o->max_startups_begin,
2803 	    o->max_startups_rate, o->max_startups);
2804 
2805 	s = NULL;
2806 	for (i = 0; tunmode_desc[i].val != -1; i++) {
2807 		if (tunmode_desc[i].val == o->permit_tun) {
2808 			s = tunmode_desc[i].text;
2809 			break;
2810 		}
2811 	}
2812 	dump_cfg_string(sPermitTunnel, s);
2813 
2814 	printf("ipqos %s ", iptos2str(o->ip_qos_interactive));
2815 	printf("%s\n", iptos2str(o->ip_qos_bulk));
2816 
2817 	printf("rekeylimit %llu %d\n", (unsigned long long)o->rekey_limit,
2818 	    o->rekey_interval);
2819 
2820 	printf("permitopen");
2821 	if (o->num_permitted_opens == 0)
2822 		printf(" any");
2823 	else {
2824 		for (i = 0; i < o->num_permitted_opens; i++)
2825 			printf(" %s", o->permitted_opens[i]);
2826 	}
2827 	printf("\n");
2828 }
2829