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