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