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