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