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