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