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