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