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