xref: /openssh-portable/servconf.c (revision e826bbca)
1 
2 /* $OpenBSD: servconf.c,v 1.351 2019/04/18 18:56:16 dtucker 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 + 1 : arg, 1))
1448 			fatal("%s line %d: Bad key types '%s'.",
1449 			    filename, linenum, arg ? arg : "<NONE>");
1450 		if (*activep && *charptr == NULL)
1451 			*charptr = xstrdup(arg);
1452 		break;
1453 
1454 	case sHostKeyAlgorithms:
1455 		charptr = &options->hostkeyalgorithms;
1456 		goto parse_keytypes;
1457 
1458 	case sCASignatureAlgorithms:
1459 		charptr = &options->ca_sign_algorithms;
1460 		goto parse_keytypes;
1461 
1462 	case sPubkeyAuthentication:
1463 		intptr = &options->pubkey_authentication;
1464 		goto parse_flag;
1465 
1466 	case sPubkeyAcceptedKeyTypes:
1467 		charptr = &options->pubkey_key_types;
1468 		goto parse_keytypes;
1469 
1470 	case sKerberosAuthentication:
1471 		intptr = &options->kerberos_authentication;
1472 		goto parse_flag;
1473 
1474 	case sKerberosOrLocalPasswd:
1475 		intptr = &options->kerberos_or_local_passwd;
1476 		goto parse_flag;
1477 
1478 	case sKerberosTicketCleanup:
1479 		intptr = &options->kerberos_ticket_cleanup;
1480 		goto parse_flag;
1481 
1482 	case sKerberosGetAFSToken:
1483 		intptr = &options->kerberos_get_afs_token;
1484 		goto parse_flag;
1485 
1486 	case sGssAuthentication:
1487 		intptr = &options->gss_authentication;
1488 		goto parse_flag;
1489 
1490 	case sGssCleanupCreds:
1491 		intptr = &options->gss_cleanup_creds;
1492 		goto parse_flag;
1493 
1494 	case sGssStrictAcceptor:
1495 		intptr = &options->gss_strict_acceptor;
1496 		goto parse_flag;
1497 
1498 	case sPasswordAuthentication:
1499 		intptr = &options->password_authentication;
1500 		goto parse_flag;
1501 
1502 	case sKbdInteractiveAuthentication:
1503 		intptr = &options->kbd_interactive_authentication;
1504 		goto parse_flag;
1505 
1506 	case sChallengeResponseAuthentication:
1507 		intptr = &options->challenge_response_authentication;
1508 		goto parse_flag;
1509 
1510 	case sPrintMotd:
1511 		intptr = &options->print_motd;
1512 		goto parse_flag;
1513 
1514 	case sPrintLastLog:
1515 		intptr = &options->print_lastlog;
1516 		goto parse_flag;
1517 
1518 	case sX11Forwarding:
1519 		intptr = &options->x11_forwarding;
1520 		goto parse_flag;
1521 
1522 	case sX11DisplayOffset:
1523 		intptr = &options->x11_display_offset;
1524  parse_int:
1525 		arg = strdelim(&cp);
1526 		if ((errstr = atoi_err(arg, &value)) != NULL)
1527 			fatal("%s line %d: integer value %s.",
1528 			    filename, linenum, errstr);
1529 		if (*activep && *intptr == -1)
1530 			*intptr = value;
1531 		break;
1532 
1533 	case sX11UseLocalhost:
1534 		intptr = &options->x11_use_localhost;
1535 		goto parse_flag;
1536 
1537 	case sXAuthLocation:
1538 		charptr = &options->xauth_location;
1539 		goto parse_filename;
1540 
1541 	case sPermitTTY:
1542 		intptr = &options->permit_tty;
1543 		goto parse_flag;
1544 
1545 	case sPermitUserRC:
1546 		intptr = &options->permit_user_rc;
1547 		goto parse_flag;
1548 
1549 	case sStrictModes:
1550 		intptr = &options->strict_modes;
1551 		goto parse_flag;
1552 
1553 	case sTCPKeepAlive:
1554 		intptr = &options->tcp_keep_alive;
1555 		goto parse_flag;
1556 
1557 	case sEmptyPasswd:
1558 		intptr = &options->permit_empty_passwd;
1559 		goto parse_flag;
1560 
1561 	case sPermitUserEnvironment:
1562 		intptr = &options->permit_user_env;
1563 		charptr = &options->permit_user_env_whitelist;
1564 		arg = strdelim(&cp);
1565 		if (!arg || *arg == '\0')
1566 			fatal("%s line %d: missing argument.",
1567 			    filename, linenum);
1568 		value = 0;
1569 		p = NULL;
1570 		if (strcmp(arg, "yes") == 0)
1571 			value = 1;
1572 		else if (strcmp(arg, "no") == 0)
1573 			value = 0;
1574 		else {
1575 			/* Pattern-list specified */
1576 			value = 1;
1577 			p = xstrdup(arg);
1578 		}
1579 		if (*activep && *intptr == -1) {
1580 			*intptr = value;
1581 			*charptr = p;
1582 			p = NULL;
1583 		}
1584 		free(p);
1585 		break;
1586 
1587 	case sCompression:
1588 		intptr = &options->compression;
1589 		multistate_ptr = multistate_compression;
1590 		goto parse_multistate;
1591 
1592 	case sRekeyLimit:
1593 		arg = strdelim(&cp);
1594 		if (!arg || *arg == '\0')
1595 			fatal("%.200s line %d: Missing argument.", filename,
1596 			    linenum);
1597 		if (strcmp(arg, "default") == 0) {
1598 			val64 = 0;
1599 		} else {
1600 			if (scan_scaled(arg, &val64) == -1)
1601 				fatal("%.200s line %d: Bad number '%s': %s",
1602 				    filename, linenum, arg, strerror(errno));
1603 			if (val64 != 0 && val64 < 16)
1604 				fatal("%.200s line %d: RekeyLimit too small",
1605 				    filename, linenum);
1606 		}
1607 		if (*activep && options->rekey_limit == -1)
1608 			options->rekey_limit = val64;
1609 		if (cp != NULL) { /* optional rekey interval present */
1610 			if (strcmp(cp, "none") == 0) {
1611 				(void)strdelim(&cp);	/* discard */
1612 				break;
1613 			}
1614 			intptr = &options->rekey_interval;
1615 			goto parse_time;
1616 		}
1617 		break;
1618 
1619 	case sGatewayPorts:
1620 		intptr = &options->fwd_opts.gateway_ports;
1621 		multistate_ptr = multistate_gatewayports;
1622 		goto parse_multistate;
1623 
1624 	case sUseDNS:
1625 		intptr = &options->use_dns;
1626 		goto parse_flag;
1627 
1628 	case sLogFacility:
1629 		log_facility_ptr = &options->log_facility;
1630 		arg = strdelim(&cp);
1631 		value = log_facility_number(arg);
1632 		if (value == SYSLOG_FACILITY_NOT_SET)
1633 			fatal("%.200s line %d: unsupported log facility '%s'",
1634 			    filename, linenum, arg ? arg : "<NONE>");
1635 		if (*log_facility_ptr == -1)
1636 			*log_facility_ptr = (SyslogFacility) value;
1637 		break;
1638 
1639 	case sLogLevel:
1640 		log_level_ptr = &options->log_level;
1641 		arg = strdelim(&cp);
1642 		value = log_level_number(arg);
1643 		if (value == SYSLOG_LEVEL_NOT_SET)
1644 			fatal("%.200s line %d: unsupported log level '%s'",
1645 			    filename, linenum, arg ? arg : "<NONE>");
1646 		if (*activep && *log_level_ptr == -1)
1647 			*log_level_ptr = (LogLevel) value;
1648 		break;
1649 
1650 	case sAllowTcpForwarding:
1651 		intptr = &options->allow_tcp_forwarding;
1652 		multistate_ptr = multistate_tcpfwd;
1653 		goto parse_multistate;
1654 
1655 	case sAllowStreamLocalForwarding:
1656 		intptr = &options->allow_streamlocal_forwarding;
1657 		multistate_ptr = multistate_tcpfwd;
1658 		goto parse_multistate;
1659 
1660 	case sAllowAgentForwarding:
1661 		intptr = &options->allow_agent_forwarding;
1662 		goto parse_flag;
1663 
1664 	case sDisableForwarding:
1665 		intptr = &options->disable_forwarding;
1666 		goto parse_flag;
1667 
1668 	case sAllowUsers:
1669 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1670 			if (match_user(NULL, NULL, NULL, arg) == -1)
1671 				fatal("%s line %d: invalid AllowUsers pattern: "
1672 				    "\"%.100s\"", filename, linenum, arg);
1673 			if (!*activep)
1674 				continue;
1675 			array_append(filename, linenum, "AllowUsers",
1676 			    &options->allow_users, &options->num_allow_users,
1677 			    arg);
1678 		}
1679 		break;
1680 
1681 	case sDenyUsers:
1682 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1683 			if (match_user(NULL, NULL, NULL, arg) == -1)
1684 				fatal("%s line %d: invalid DenyUsers pattern: "
1685 				    "\"%.100s\"", filename, linenum, arg);
1686 			if (!*activep)
1687 				continue;
1688 			array_append(filename, linenum, "DenyUsers",
1689 			    &options->deny_users, &options->num_deny_users,
1690 			    arg);
1691 		}
1692 		break;
1693 
1694 	case sAllowGroups:
1695 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1696 			if (!*activep)
1697 				continue;
1698 			array_append(filename, linenum, "AllowGroups",
1699 			    &options->allow_groups, &options->num_allow_groups,
1700 			    arg);
1701 		}
1702 		break;
1703 
1704 	case sDenyGroups:
1705 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1706 			if (!*activep)
1707 				continue;
1708 			array_append(filename, linenum, "DenyGroups",
1709 			    &options->deny_groups, &options->num_deny_groups,
1710 			    arg);
1711 		}
1712 		break;
1713 
1714 	case sCiphers:
1715 		arg = strdelim(&cp);
1716 		if (!arg || *arg == '\0')
1717 			fatal("%s line %d: Missing argument.", filename, linenum);
1718 		if (*arg != '-' && !ciphers_valid(*arg == '+' ? arg + 1 : arg))
1719 			fatal("%s line %d: Bad SSH2 cipher spec '%s'.",
1720 			    filename, linenum, arg ? arg : "<NONE>");
1721 		if (options->ciphers == NULL)
1722 			options->ciphers = xstrdup(arg);
1723 		break;
1724 
1725 	case sMacs:
1726 		arg = strdelim(&cp);
1727 		if (!arg || *arg == '\0')
1728 			fatal("%s line %d: Missing argument.", filename, linenum);
1729 		if (*arg != '-' && !mac_valid(*arg == '+' ? arg + 1 : arg))
1730 			fatal("%s line %d: Bad SSH2 mac spec '%s'.",
1731 			    filename, linenum, arg ? arg : "<NONE>");
1732 		if (options->macs == NULL)
1733 			options->macs = xstrdup(arg);
1734 		break;
1735 
1736 	case sKexAlgorithms:
1737 		arg = strdelim(&cp);
1738 		if (!arg || *arg == '\0')
1739 			fatal("%s line %d: Missing argument.",
1740 			    filename, linenum);
1741 		if (*arg != '-' &&
1742 		    !kex_names_valid(*arg == '+' ? arg + 1 : arg))
1743 			fatal("%s line %d: Bad SSH2 KexAlgorithms '%s'.",
1744 			    filename, linenum, arg ? arg : "<NONE>");
1745 		if (options->kex_algorithms == NULL)
1746 			options->kex_algorithms = xstrdup(arg);
1747 		break;
1748 
1749 	case sSubsystem:
1750 		if (options->num_subsystems >= MAX_SUBSYSTEMS) {
1751 			fatal("%s line %d: too many subsystems defined.",
1752 			    filename, linenum);
1753 		}
1754 		arg = strdelim(&cp);
1755 		if (!arg || *arg == '\0')
1756 			fatal("%s line %d: Missing subsystem name.",
1757 			    filename, linenum);
1758 		if (!*activep) {
1759 			arg = strdelim(&cp);
1760 			break;
1761 		}
1762 		for (i = 0; i < options->num_subsystems; i++)
1763 			if (strcmp(arg, options->subsystem_name[i]) == 0)
1764 				fatal("%s line %d: Subsystem '%s' already defined.",
1765 				    filename, linenum, arg);
1766 		options->subsystem_name[options->num_subsystems] = xstrdup(arg);
1767 		arg = strdelim(&cp);
1768 		if (!arg || *arg == '\0')
1769 			fatal("%s line %d: Missing subsystem command.",
1770 			    filename, linenum);
1771 		options->subsystem_command[options->num_subsystems] = xstrdup(arg);
1772 
1773 		/* Collect arguments (separate to executable) */
1774 		p = xstrdup(arg);
1775 		len = strlen(p) + 1;
1776 		while ((arg = strdelim(&cp)) != NULL && *arg != '\0') {
1777 			len += 1 + strlen(arg);
1778 			p = xreallocarray(p, 1, len);
1779 			strlcat(p, " ", len);
1780 			strlcat(p, arg, len);
1781 		}
1782 		options->subsystem_args[options->num_subsystems] = p;
1783 		options->num_subsystems++;
1784 		break;
1785 
1786 	case sMaxStartups:
1787 		arg = strdelim(&cp);
1788 		if (!arg || *arg == '\0')
1789 			fatal("%s line %d: Missing MaxStartups spec.",
1790 			    filename, linenum);
1791 		if ((n = sscanf(arg, "%d:%d:%d",
1792 		    &options->max_startups_begin,
1793 		    &options->max_startups_rate,
1794 		    &options->max_startups)) == 3) {
1795 			if (options->max_startups_begin >
1796 			    options->max_startups ||
1797 			    options->max_startups_rate > 100 ||
1798 			    options->max_startups_rate < 1)
1799 				fatal("%s line %d: Illegal MaxStartups spec.",
1800 				    filename, linenum);
1801 		} else if (n != 1)
1802 			fatal("%s line %d: Illegal MaxStartups spec.",
1803 			    filename, linenum);
1804 		else
1805 			options->max_startups = options->max_startups_begin;
1806 		break;
1807 
1808 	case sMaxAuthTries:
1809 		intptr = &options->max_authtries;
1810 		goto parse_int;
1811 
1812 	case sMaxSessions:
1813 		intptr = &options->max_sessions;
1814 		goto parse_int;
1815 
1816 	case sBanner:
1817 		charptr = &options->banner;
1818 		goto parse_filename;
1819 
1820 	/*
1821 	 * These options can contain %X options expanded at
1822 	 * connect time, so that you can specify paths like:
1823 	 *
1824 	 * AuthorizedKeysFile	/etc/ssh_keys/%u
1825 	 */
1826 	case sAuthorizedKeysFile:
1827 		if (*activep && options->num_authkeys_files == 0) {
1828 			while ((arg = strdelim(&cp)) && *arg != '\0') {
1829 				arg = tilde_expand_filename(arg, getuid());
1830 				array_append(filename, linenum,
1831 				    "AuthorizedKeysFile",
1832 				    &options->authorized_keys_files,
1833 				    &options->num_authkeys_files, arg);
1834 				free(arg);
1835 			}
1836 		}
1837 		return 0;
1838 
1839 	case sAuthorizedPrincipalsFile:
1840 		charptr = &options->authorized_principals_file;
1841 		arg = strdelim(&cp);
1842 		if (!arg || *arg == '\0')
1843 			fatal("%s line %d: missing file name.",
1844 			    filename, linenum);
1845 		if (*activep && *charptr == NULL) {
1846 			*charptr = tilde_expand_filename(arg, getuid());
1847 			/* increase optional counter */
1848 			if (intptr != NULL)
1849 				*intptr = *intptr + 1;
1850 		}
1851 		break;
1852 
1853 	case sClientAliveInterval:
1854 		intptr = &options->client_alive_interval;
1855 		goto parse_time;
1856 
1857 	case sClientAliveCountMax:
1858 		intptr = &options->client_alive_count_max;
1859 		goto parse_int;
1860 
1861 	case sAcceptEnv:
1862 		while ((arg = strdelim(&cp)) && *arg != '\0') {
1863 			if (strchr(arg, '=') != NULL)
1864 				fatal("%s line %d: Invalid environment name.",
1865 				    filename, linenum);
1866 			if (!*activep)
1867 				continue;
1868 			array_append(filename, linenum, "AcceptEnv",
1869 			    &options->accept_env, &options->num_accept_env,
1870 			    arg);
1871 		}
1872 		break;
1873 
1874 	case sSetEnv:
1875 		uvalue = options->num_setenv;
1876 		while ((arg = strdelimw(&cp)) && *arg != '\0') {
1877 			if (strchr(arg, '=') == NULL)
1878 				fatal("%s line %d: Invalid environment.",
1879 				    filename, linenum);
1880 			if (!*activep || uvalue != 0)
1881 				continue;
1882 			array_append(filename, linenum, "SetEnv",
1883 			    &options->setenv, &options->num_setenv, arg);
1884 		}
1885 		break;
1886 
1887 	case sPermitTunnel:
1888 		intptr = &options->permit_tun;
1889 		arg = strdelim(&cp);
1890 		if (!arg || *arg == '\0')
1891 			fatal("%s line %d: Missing yes/point-to-point/"
1892 			    "ethernet/no argument.", filename, linenum);
1893 		value = -1;
1894 		for (i = 0; tunmode_desc[i].val != -1; i++)
1895 			if (strcmp(tunmode_desc[i].text, arg) == 0) {
1896 				value = tunmode_desc[i].val;
1897 				break;
1898 			}
1899 		if (value == -1)
1900 			fatal("%s line %d: Bad yes/point-to-point/ethernet/"
1901 			    "no argument: %s", filename, linenum, arg);
1902 		if (*activep && *intptr == -1)
1903 			*intptr = value;
1904 		break;
1905 
1906 	case sMatch:
1907 		if (cmdline)
1908 			fatal("Match directive not supported as a command-line "
1909 			   "option");
1910 		value = match_cfg_line(&cp, linenum, connectinfo);
1911 		if (value < 0)
1912 			fatal("%s line %d: Bad Match condition", filename,
1913 			    linenum);
1914 		*activep = value;
1915 		break;
1916 
1917 	case sPermitListen:
1918 	case sPermitOpen:
1919 		if (opcode == sPermitListen) {
1920 			uintptr = &options->num_permitted_listens;
1921 			chararrayptr = &options->permitted_listens;
1922 		} else {
1923 			uintptr = &options->num_permitted_opens;
1924 			chararrayptr = &options->permitted_opens;
1925 		}
1926 		arg = strdelim(&cp);
1927 		if (!arg || *arg == '\0')
1928 			fatal("%s line %d: missing %s specification",
1929 			    filename, linenum, lookup_opcode_name(opcode));
1930 		uvalue = *uintptr;	/* modified later */
1931 		if (strcmp(arg, "any") == 0 || strcmp(arg, "none") == 0) {
1932 			if (*activep && uvalue == 0) {
1933 				*uintptr = 1;
1934 				*chararrayptr = xcalloc(1,
1935 				    sizeof(**chararrayptr));
1936 				(*chararrayptr)[0] = xstrdup(arg);
1937 			}
1938 			break;
1939 		}
1940 		for (; arg != NULL && *arg != '\0'; arg = strdelim(&cp)) {
1941 			if (opcode == sPermitListen &&
1942 			    strchr(arg, ':') == NULL) {
1943 				/*
1944 				 * Allow bare port number for PermitListen
1945 				 * to indicate a wildcard listen host.
1946 				 */
1947 				xasprintf(&arg2, "*:%s", arg);
1948 			} else {
1949 				arg2 = xstrdup(arg);
1950 				ch = '\0';
1951 				p = hpdelim2(&arg, &ch);
1952 				if (p == NULL || ch == '/') {
1953 					fatal("%s line %d: missing host in %s",
1954 					    filename, linenum,
1955 					    lookup_opcode_name(opcode));
1956 				}
1957 				p = cleanhostname(p);
1958 			}
1959 			if (arg == NULL ||
1960 			    ((port = permitopen_port(arg)) < 0)) {
1961 				fatal("%s line %d: bad port number in %s",
1962 				    filename, linenum,
1963 				    lookup_opcode_name(opcode));
1964 			}
1965 			if (*activep && uvalue == 0) {
1966 				array_append(filename, linenum,
1967 				    lookup_opcode_name(opcode),
1968 				    chararrayptr, uintptr, arg2);
1969 			}
1970 			free(arg2);
1971 		}
1972 		break;
1973 
1974 	case sForceCommand:
1975 		if (cp == NULL || *cp == '\0')
1976 			fatal("%.200s line %d: Missing argument.", filename,
1977 			    linenum);
1978 		len = strspn(cp, WHITESPACE);
1979 		if (*activep && options->adm_forced_command == NULL)
1980 			options->adm_forced_command = xstrdup(cp + len);
1981 		return 0;
1982 
1983 	case sChrootDirectory:
1984 		charptr = &options->chroot_directory;
1985 
1986 		arg = strdelim(&cp);
1987 		if (!arg || *arg == '\0')
1988 			fatal("%s line %d: missing file name.",
1989 			    filename, linenum);
1990 		if (*activep && *charptr == NULL)
1991 			*charptr = xstrdup(arg);
1992 		break;
1993 
1994 	case sTrustedUserCAKeys:
1995 		charptr = &options->trusted_user_ca_keys;
1996 		goto parse_filename;
1997 
1998 	case sRevokedKeys:
1999 		charptr = &options->revoked_keys_file;
2000 		goto parse_filename;
2001 
2002 	case sIPQoS:
2003 		arg = strdelim(&cp);
2004 		if ((value = parse_ipqos(arg)) == -1)
2005 			fatal("%s line %d: Bad IPQoS value: %s",
2006 			    filename, linenum, arg);
2007 		arg = strdelim(&cp);
2008 		if (arg == NULL)
2009 			value2 = value;
2010 		else if ((value2 = parse_ipqos(arg)) == -1)
2011 			fatal("%s line %d: Bad IPQoS value: %s",
2012 			    filename, linenum, arg);
2013 		if (*activep) {
2014 			options->ip_qos_interactive = value;
2015 			options->ip_qos_bulk = value2;
2016 		}
2017 		break;
2018 
2019 	case sVersionAddendum:
2020 		if (cp == NULL || *cp == '\0')
2021 			fatal("%.200s line %d: Missing argument.", filename,
2022 			    linenum);
2023 		len = strspn(cp, WHITESPACE);
2024 		if (*activep && options->version_addendum == NULL) {
2025 			if (strcasecmp(cp + len, "none") == 0)
2026 				options->version_addendum = xstrdup("");
2027 			else if (strchr(cp + len, '\r') != NULL)
2028 				fatal("%.200s line %d: Invalid argument",
2029 				    filename, linenum);
2030 			else
2031 				options->version_addendum = xstrdup(cp + len);
2032 		}
2033 		return 0;
2034 
2035 	case sAuthorizedKeysCommand:
2036 		if (cp == NULL)
2037 			fatal("%.200s line %d: Missing argument.", filename,
2038 			    linenum);
2039 		len = strspn(cp, WHITESPACE);
2040 		if (*activep && options->authorized_keys_command == NULL) {
2041 			if (cp[len] != '/' && strcasecmp(cp + len, "none") != 0)
2042 				fatal("%.200s line %d: AuthorizedKeysCommand "
2043 				    "must be an absolute path",
2044 				    filename, linenum);
2045 			options->authorized_keys_command = xstrdup(cp + len);
2046 		}
2047 		return 0;
2048 
2049 	case sAuthorizedKeysCommandUser:
2050 		charptr = &options->authorized_keys_command_user;
2051 
2052 		arg = strdelim(&cp);
2053 		if (!arg || *arg == '\0')
2054 			fatal("%s line %d: missing AuthorizedKeysCommandUser "
2055 			    "argument.", filename, linenum);
2056 		if (*activep && *charptr == NULL)
2057 			*charptr = xstrdup(arg);
2058 		break;
2059 
2060 	case sAuthorizedPrincipalsCommand:
2061 		if (cp == NULL)
2062 			fatal("%.200s line %d: Missing argument.", filename,
2063 			    linenum);
2064 		len = strspn(cp, WHITESPACE);
2065 		if (*activep &&
2066 		    options->authorized_principals_command == NULL) {
2067 			if (cp[len] != '/' && strcasecmp(cp + len, "none") != 0)
2068 				fatal("%.200s line %d: "
2069 				    "AuthorizedPrincipalsCommand must be "
2070 				    "an absolute path", filename, linenum);
2071 			options->authorized_principals_command =
2072 			    xstrdup(cp + len);
2073 		}
2074 		return 0;
2075 
2076 	case sAuthorizedPrincipalsCommandUser:
2077 		charptr = &options->authorized_principals_command_user;
2078 
2079 		arg = strdelim(&cp);
2080 		if (!arg || *arg == '\0')
2081 			fatal("%s line %d: missing "
2082 			    "AuthorizedPrincipalsCommandUser argument.",
2083 			    filename, linenum);
2084 		if (*activep && *charptr == NULL)
2085 			*charptr = xstrdup(arg);
2086 		break;
2087 
2088 	case sAuthenticationMethods:
2089 		if (options->num_auth_methods == 0) {
2090 			value = 0; /* seen "any" pseudo-method */
2091 			value2 = 0; /* successfully parsed any method */
2092 			while ((arg = strdelim(&cp)) && *arg != '\0') {
2093 				if (strcmp(arg, "any") == 0) {
2094 					if (options->num_auth_methods > 0) {
2095 						fatal("%s line %d: \"any\" "
2096 						    "must appear alone in "
2097 						    "AuthenticationMethods",
2098 						    filename, linenum);
2099 					}
2100 					value = 1;
2101 				} else if (value) {
2102 					fatal("%s line %d: \"any\" must appear "
2103 					    "alone in AuthenticationMethods",
2104 					    filename, linenum);
2105 				} else if (auth2_methods_valid(arg, 0) != 0) {
2106 					fatal("%s line %d: invalid "
2107 					    "authentication method list.",
2108 					    filename, linenum);
2109 				}
2110 				value2 = 1;
2111 				if (!*activep)
2112 					continue;
2113 				array_append(filename, linenum,
2114 				    "AuthenticationMethods",
2115 				    &options->auth_methods,
2116 				    &options->num_auth_methods, arg);
2117 			}
2118 			if (value2 == 0) {
2119 				fatal("%s line %d: no AuthenticationMethods "
2120 				    "specified", filename, linenum);
2121 			}
2122 		}
2123 		return 0;
2124 
2125 	case sStreamLocalBindMask:
2126 		arg = strdelim(&cp);
2127 		if (!arg || *arg == '\0')
2128 			fatal("%s line %d: missing StreamLocalBindMask "
2129 			    "argument.", filename, linenum);
2130 		/* Parse mode in octal format */
2131 		value = strtol(arg, &p, 8);
2132 		if (arg == p || value < 0 || value > 0777)
2133 			fatal("%s line %d: Bad mask.", filename, linenum);
2134 		if (*activep)
2135 			options->fwd_opts.streamlocal_bind_mask = (mode_t)value;
2136 		break;
2137 
2138 	case sStreamLocalBindUnlink:
2139 		intptr = &options->fwd_opts.streamlocal_bind_unlink;
2140 		goto parse_flag;
2141 
2142 	case sFingerprintHash:
2143 		arg = strdelim(&cp);
2144 		if (!arg || *arg == '\0')
2145 			fatal("%.200s line %d: Missing argument.",
2146 			    filename, linenum);
2147 		if ((value = ssh_digest_alg_by_name(arg)) == -1)
2148 			fatal("%.200s line %d: Invalid hash algorithm \"%s\".",
2149 			    filename, linenum, arg);
2150 		if (*activep)
2151 			options->fingerprint_hash = value;
2152 		break;
2153 
2154 	case sExposeAuthInfo:
2155 		intptr = &options->expose_userauth_info;
2156 		goto parse_flag;
2157 
2158 	case sRDomain:
2159 		charptr = &options->routing_domain;
2160 		arg = strdelim(&cp);
2161 		if (!arg || *arg == '\0')
2162 			fatal("%.200s line %d: Missing argument.",
2163 			    filename, linenum);
2164 		if (strcasecmp(arg, "none") != 0 && strcmp(arg, "%D") != 0 &&
2165 		    !valid_rdomain(arg))
2166 			fatal("%s line %d: bad routing domain",
2167 			    filename, linenum);
2168 		if (*activep && *charptr == NULL)
2169 			*charptr = xstrdup(arg);
2170 		break;
2171 
2172 	case sDeprecated:
2173 	case sIgnore:
2174 	case sUnsupported:
2175 		do_log2(opcode == sIgnore ?
2176 		    SYSLOG_LEVEL_DEBUG2 : SYSLOG_LEVEL_INFO,
2177 		    "%s line %d: %s option %s", filename, linenum,
2178 		    opcode == sUnsupported ? "Unsupported" : "Deprecated", arg);
2179 		while (arg)
2180 		    arg = strdelim(&cp);
2181 		break;
2182 
2183 	default:
2184 		fatal("%s line %d: Missing handler for opcode %s (%d)",
2185 		    filename, linenum, arg, opcode);
2186 	}
2187 	if ((arg = strdelim(&cp)) != NULL && *arg != '\0')
2188 		fatal("%s line %d: garbage at end of line; \"%.200s\".",
2189 		    filename, linenum, arg);
2190 	return 0;
2191 }
2192 
2193 /* Reads the server configuration file. */
2194 
2195 void
load_server_config(const char * filename,struct sshbuf * conf)2196 load_server_config(const char *filename, struct sshbuf *conf)
2197 {
2198 	char *line = NULL, *cp;
2199 	size_t linesize = 0;
2200 	FILE *f;
2201 	int r, lineno = 0;
2202 
2203 	debug2("%s: filename %s", __func__, filename);
2204 	if ((f = fopen(filename, "r")) == NULL) {
2205 		perror(filename);
2206 		exit(1);
2207 	}
2208 	sshbuf_reset(conf);
2209 	while (getline(&line, &linesize, f) != -1) {
2210 		lineno++;
2211 		/*
2212 		 * Trim out comments and strip whitespace
2213 		 * NB - preserve newlines, they are needed to reproduce
2214 		 * line numbers later for error messages
2215 		 */
2216 		if ((cp = strchr(line, '#')) != NULL)
2217 			memcpy(cp, "\n", 2);
2218 		cp = line + strspn(line, " \t\r");
2219 		if ((r = sshbuf_put(conf, cp, strlen(cp))) != 0)
2220 			fatal("%s: buffer error: %s", __func__, ssh_err(r));
2221 	}
2222 	free(line);
2223 	if ((r = sshbuf_put_u8(conf, 0)) != 0)
2224 		fatal("%s: buffer error: %s", __func__, ssh_err(r));
2225 	fclose(f);
2226 	debug2("%s: done config len = %zu", __func__, sshbuf_len(conf));
2227 }
2228 
2229 void
parse_server_match_config(ServerOptions * options,struct connection_info * connectinfo)2230 parse_server_match_config(ServerOptions *options,
2231    struct connection_info *connectinfo)
2232 {
2233 	ServerOptions mo;
2234 
2235 	initialize_server_options(&mo);
2236 	parse_server_config(&mo, "reprocess config", cfg, connectinfo);
2237 	copy_set_server_options(options, &mo, 0);
2238 }
2239 
parse_server_match_testspec(struct connection_info * ci,char * spec)2240 int parse_server_match_testspec(struct connection_info *ci, char *spec)
2241 {
2242 	char *p;
2243 
2244 	while ((p = strsep(&spec, ",")) && *p != '\0') {
2245 		if (strncmp(p, "addr=", 5) == 0) {
2246 			ci->address = xstrdup(p + 5);
2247 		} else if (strncmp(p, "host=", 5) == 0) {
2248 			ci->host = xstrdup(p + 5);
2249 		} else if (strncmp(p, "user=", 5) == 0) {
2250 			ci->user = xstrdup(p + 5);
2251 		} else if (strncmp(p, "laddr=", 6) == 0) {
2252 			ci->laddress = xstrdup(p + 6);
2253 		} else if (strncmp(p, "rdomain=", 8) == 0) {
2254 			ci->rdomain = xstrdup(p + 8);
2255 		} else if (strncmp(p, "lport=", 6) == 0) {
2256 			ci->lport = a2port(p + 6);
2257 			if (ci->lport == -1) {
2258 				fprintf(stderr, "Invalid port '%s' in test mode"
2259 				   " specification %s\n", p+6, p);
2260 				return -1;
2261 			}
2262 		} else {
2263 			fprintf(stderr, "Invalid test mode specification %s\n",
2264 			   p);
2265 			return -1;
2266 		}
2267 	}
2268 	return 0;
2269 }
2270 
2271 /*
2272  * Copy any supported values that are set.
2273  *
2274  * If the preauth flag is set, we do not bother copying the string or
2275  * array values that are not used pre-authentication, because any that we
2276  * do use must be explicitly sent in mm_getpwnamallow().
2277  */
2278 void
copy_set_server_options(ServerOptions * dst,ServerOptions * src,int preauth)2279 copy_set_server_options(ServerOptions *dst, ServerOptions *src, int preauth)
2280 {
2281 #define M_CP_INTOPT(n) do {\
2282 	if (src->n != -1) \
2283 		dst->n = src->n; \
2284 } while (0)
2285 
2286 	M_CP_INTOPT(password_authentication);
2287 	M_CP_INTOPT(gss_authentication);
2288 	M_CP_INTOPT(pubkey_authentication);
2289 	M_CP_INTOPT(kerberos_authentication);
2290 	M_CP_INTOPT(hostbased_authentication);
2291 	M_CP_INTOPT(hostbased_uses_name_from_packet_only);
2292 	M_CP_INTOPT(kbd_interactive_authentication);
2293 	M_CP_INTOPT(permit_root_login);
2294 	M_CP_INTOPT(permit_empty_passwd);
2295 
2296 	M_CP_INTOPT(allow_tcp_forwarding);
2297 	M_CP_INTOPT(allow_streamlocal_forwarding);
2298 	M_CP_INTOPT(allow_agent_forwarding);
2299 	M_CP_INTOPT(disable_forwarding);
2300 	M_CP_INTOPT(expose_userauth_info);
2301 	M_CP_INTOPT(permit_tun);
2302 	M_CP_INTOPT(fwd_opts.gateway_ports);
2303 	M_CP_INTOPT(fwd_opts.streamlocal_bind_unlink);
2304 	M_CP_INTOPT(x11_display_offset);
2305 	M_CP_INTOPT(x11_forwarding);
2306 	M_CP_INTOPT(x11_use_localhost);
2307 	M_CP_INTOPT(permit_tty);
2308 	M_CP_INTOPT(permit_user_rc);
2309 	M_CP_INTOPT(max_sessions);
2310 	M_CP_INTOPT(max_authtries);
2311 	M_CP_INTOPT(client_alive_count_max);
2312 	M_CP_INTOPT(client_alive_interval);
2313 	M_CP_INTOPT(ip_qos_interactive);
2314 	M_CP_INTOPT(ip_qos_bulk);
2315 	M_CP_INTOPT(rekey_limit);
2316 	M_CP_INTOPT(rekey_interval);
2317 	M_CP_INTOPT(log_level);
2318 
2319 	/*
2320 	 * The bind_mask is a mode_t that may be unsigned, so we can't use
2321 	 * M_CP_INTOPT - it does a signed comparison that causes compiler
2322 	 * warnings.
2323 	 */
2324 	if (src->fwd_opts.streamlocal_bind_mask != (mode_t)-1) {
2325 		dst->fwd_opts.streamlocal_bind_mask =
2326 		    src->fwd_opts.streamlocal_bind_mask;
2327 	}
2328 
2329 	/* M_CP_STROPT and M_CP_STRARRAYOPT should not appear before here */
2330 #define M_CP_STROPT(n) do {\
2331 	if (src->n != NULL && dst->n != src->n) { \
2332 		free(dst->n); \
2333 		dst->n = src->n; \
2334 	} \
2335 } while(0)
2336 #define M_CP_STRARRAYOPT(s, num_s) do {\
2337 	u_int i; \
2338 	if (src->num_s != 0) { \
2339 		for (i = 0; i < dst->num_s; i++) \
2340 			free(dst->s[i]); \
2341 		free(dst->s); \
2342 		dst->s = xcalloc(src->num_s, sizeof(*dst->s)); \
2343 		for (i = 0; i < src->num_s; i++) \
2344 			dst->s[i] = xstrdup(src->s[i]); \
2345 		dst->num_s = src->num_s; \
2346 	} \
2347 } while(0)
2348 
2349 	/* See comment in servconf.h */
2350 	COPY_MATCH_STRING_OPTS();
2351 
2352 	/* Arguments that accept '+...' need to be expanded */
2353 	assemble_algorithms(dst);
2354 
2355 	/*
2356 	 * The only things that should be below this point are string options
2357 	 * which are only used after authentication.
2358 	 */
2359 	if (preauth)
2360 		return;
2361 
2362 	/* These options may be "none" to clear a global setting */
2363 	M_CP_STROPT(adm_forced_command);
2364 	if (option_clear_or_none(dst->adm_forced_command)) {
2365 		free(dst->adm_forced_command);
2366 		dst->adm_forced_command = NULL;
2367 	}
2368 	M_CP_STROPT(chroot_directory);
2369 	if (option_clear_or_none(dst->chroot_directory)) {
2370 		free(dst->chroot_directory);
2371 		dst->chroot_directory = NULL;
2372 	}
2373 }
2374 
2375 #undef M_CP_INTOPT
2376 #undef M_CP_STROPT
2377 #undef M_CP_STRARRAYOPT
2378 
2379 void
parse_server_config(ServerOptions * options,const char * filename,struct sshbuf * conf,struct connection_info * connectinfo)2380 parse_server_config(ServerOptions *options, const char *filename,
2381     struct sshbuf *conf, struct connection_info *connectinfo)
2382 {
2383 	int active, linenum, bad_options = 0;
2384 	char *cp, *obuf, *cbuf;
2385 
2386 	debug2("%s: config %s len %zu", __func__, filename, sshbuf_len(conf));
2387 
2388 	if ((obuf = cbuf = sshbuf_dup_string(conf)) == NULL)
2389 		fatal("%s: sshbuf_dup_string failed", __func__);
2390 	active = connectinfo ? 0 : 1;
2391 	linenum = 1;
2392 	while ((cp = strsep(&cbuf, "\n")) != NULL) {
2393 		if (process_server_config_line(options, cp, filename,
2394 		    linenum++, &active, connectinfo) != 0)
2395 			bad_options++;
2396 	}
2397 	free(obuf);
2398 	if (bad_options > 0)
2399 		fatal("%s: terminating, %d bad configuration options",
2400 		    filename, bad_options);
2401 	process_queued_listen_addrs(options);
2402 }
2403 
2404 static const char *
fmt_multistate_int(int val,const struct multistate * m)2405 fmt_multistate_int(int val, const struct multistate *m)
2406 {
2407 	u_int i;
2408 
2409 	for (i = 0; m[i].key != NULL; i++) {
2410 		if (m[i].value == val)
2411 			return m[i].key;
2412 	}
2413 	return "UNKNOWN";
2414 }
2415 
2416 static const char *
fmt_intarg(ServerOpCodes code,int val)2417 fmt_intarg(ServerOpCodes code, int val)
2418 {
2419 	if (val == -1)
2420 		return "unset";
2421 	switch (code) {
2422 	case sAddressFamily:
2423 		return fmt_multistate_int(val, multistate_addressfamily);
2424 	case sPermitRootLogin:
2425 		return fmt_multistate_int(val, multistate_permitrootlogin);
2426 	case sGatewayPorts:
2427 		return fmt_multistate_int(val, multistate_gatewayports);
2428 	case sCompression:
2429 		return fmt_multistate_int(val, multistate_compression);
2430 	case sAllowTcpForwarding:
2431 		return fmt_multistate_int(val, multistate_tcpfwd);
2432 	case sAllowStreamLocalForwarding:
2433 		return fmt_multistate_int(val, multistate_tcpfwd);
2434 	case sFingerprintHash:
2435 		return ssh_digest_alg_name(val);
2436 	default:
2437 		switch (val) {
2438 		case 0:
2439 			return "no";
2440 		case 1:
2441 			return "yes";
2442 		default:
2443 			return "UNKNOWN";
2444 		}
2445 	}
2446 }
2447 
2448 static void
dump_cfg_int(ServerOpCodes code,int val)2449 dump_cfg_int(ServerOpCodes code, int val)
2450 {
2451 	printf("%s %d\n", lookup_opcode_name(code), val);
2452 }
2453 
2454 static void
dump_cfg_oct(ServerOpCodes code,int val)2455 dump_cfg_oct(ServerOpCodes code, int val)
2456 {
2457 	printf("%s 0%o\n", lookup_opcode_name(code), val);
2458 }
2459 
2460 static void
dump_cfg_fmtint(ServerOpCodes code,int val)2461 dump_cfg_fmtint(ServerOpCodes code, int val)
2462 {
2463 	printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
2464 }
2465 
2466 static void
dump_cfg_string(ServerOpCodes code,const char * val)2467 dump_cfg_string(ServerOpCodes code, const char *val)
2468 {
2469 	printf("%s %s\n", lookup_opcode_name(code),
2470 	    val == NULL ? "none" : val);
2471 }
2472 
2473 static void
dump_cfg_strarray(ServerOpCodes code,u_int count,char ** vals)2474 dump_cfg_strarray(ServerOpCodes code, u_int count, char **vals)
2475 {
2476 	u_int i;
2477 
2478 	for (i = 0; i < count; i++)
2479 		printf("%s %s\n", lookup_opcode_name(code), vals[i]);
2480 }
2481 
2482 static void
dump_cfg_strarray_oneline(ServerOpCodes code,u_int count,char ** vals)2483 dump_cfg_strarray_oneline(ServerOpCodes code, u_int count, char **vals)
2484 {
2485 	u_int i;
2486 
2487 	if (count <= 0 && code != sAuthenticationMethods)
2488 		return;
2489 	printf("%s", lookup_opcode_name(code));
2490 	for (i = 0; i < count; i++)
2491 		printf(" %s",  vals[i]);
2492 	if (code == sAuthenticationMethods && count == 0)
2493 		printf(" any");
2494 	printf("\n");
2495 }
2496 
2497 static char *
format_listen_addrs(struct listenaddr * la)2498 format_listen_addrs(struct listenaddr *la)
2499 {
2500 	int r;
2501 	struct addrinfo *ai;
2502 	char addr[NI_MAXHOST], port[NI_MAXSERV];
2503 	char *laddr1 = xstrdup(""), *laddr2 = NULL;
2504 
2505 	/*
2506 	 * ListenAddress must be after Port.  add_one_listen_addr pushes
2507 	 * addresses onto a stack, so to maintain ordering we need to
2508 	 * print these in reverse order.
2509 	 */
2510 	for (ai = la->addrs; ai; ai = ai->ai_next) {
2511 		if ((r = getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
2512 		    sizeof(addr), port, sizeof(port),
2513 		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
2514 			error("getnameinfo: %.100s", ssh_gai_strerror(r));
2515 			continue;
2516 		}
2517 		laddr2 = laddr1;
2518 		if (ai->ai_family == AF_INET6) {
2519 			xasprintf(&laddr1, "listenaddress [%s]:%s%s%s\n%s",
2520 			    addr, port,
2521 			    la->rdomain == NULL ? "" : " rdomain ",
2522 			    la->rdomain == NULL ? "" : la->rdomain,
2523 			    laddr2);
2524 		} else {
2525 			xasprintf(&laddr1, "listenaddress %s:%s%s%s\n%s",
2526 			    addr, port,
2527 			    la->rdomain == NULL ? "" : " rdomain ",
2528 			    la->rdomain == NULL ? "" : la->rdomain,
2529 			    laddr2);
2530 		}
2531 		free(laddr2);
2532 	}
2533 	return laddr1;
2534 }
2535 
2536 void
dump_config(ServerOptions * o)2537 dump_config(ServerOptions *o)
2538 {
2539 	char *s;
2540 	u_int i;
2541 
2542 	/* these are usually at the top of the config */
2543 	for (i = 0; i < o->num_ports; i++)
2544 		printf("port %d\n", o->ports[i]);
2545 	dump_cfg_fmtint(sAddressFamily, o->address_family);
2546 
2547 	for (i = 0; i < o->num_listen_addrs; i++) {
2548 		s = format_listen_addrs(&o->listen_addrs[i]);
2549 		printf("%s", s);
2550 		free(s);
2551 	}
2552 
2553 	/* integer arguments */
2554 #ifdef USE_PAM
2555 	dump_cfg_fmtint(sUsePAM, o->use_pam);
2556 #endif
2557 	dump_cfg_int(sLoginGraceTime, o->login_grace_time);
2558 	dump_cfg_int(sX11DisplayOffset, o->x11_display_offset);
2559 	dump_cfg_int(sMaxAuthTries, o->max_authtries);
2560 	dump_cfg_int(sMaxSessions, o->max_sessions);
2561 	dump_cfg_int(sClientAliveInterval, o->client_alive_interval);
2562 	dump_cfg_int(sClientAliveCountMax, o->client_alive_count_max);
2563 	dump_cfg_oct(sStreamLocalBindMask, o->fwd_opts.streamlocal_bind_mask);
2564 
2565 	/* formatted integer arguments */
2566 	dump_cfg_fmtint(sPermitRootLogin, o->permit_root_login);
2567 	dump_cfg_fmtint(sIgnoreRhosts, o->ignore_rhosts);
2568 	dump_cfg_fmtint(sIgnoreUserKnownHosts, o->ignore_user_known_hosts);
2569 	dump_cfg_fmtint(sHostbasedAuthentication, o->hostbased_authentication);
2570 	dump_cfg_fmtint(sHostbasedUsesNameFromPacketOnly,
2571 	    o->hostbased_uses_name_from_packet_only);
2572 	dump_cfg_fmtint(sPubkeyAuthentication, o->pubkey_authentication);
2573 #ifdef KRB5
2574 	dump_cfg_fmtint(sKerberosAuthentication, o->kerberos_authentication);
2575 	dump_cfg_fmtint(sKerberosOrLocalPasswd, o->kerberos_or_local_passwd);
2576 	dump_cfg_fmtint(sKerberosTicketCleanup, o->kerberos_ticket_cleanup);
2577 # ifdef USE_AFS
2578 	dump_cfg_fmtint(sKerberosGetAFSToken, o->kerberos_get_afs_token);
2579 # endif
2580 #endif
2581 #ifdef GSSAPI
2582 	dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
2583 	dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
2584 #endif
2585 	dump_cfg_fmtint(sPasswordAuthentication, o->password_authentication);
2586 	dump_cfg_fmtint(sKbdInteractiveAuthentication,
2587 	    o->kbd_interactive_authentication);
2588 	dump_cfg_fmtint(sChallengeResponseAuthentication,
2589 	    o->challenge_response_authentication);
2590 	dump_cfg_fmtint(sPrintMotd, o->print_motd);
2591 #ifndef DISABLE_LASTLOG
2592 	dump_cfg_fmtint(sPrintLastLog, o->print_lastlog);
2593 #endif
2594 	dump_cfg_fmtint(sX11Forwarding, o->x11_forwarding);
2595 	dump_cfg_fmtint(sX11UseLocalhost, o->x11_use_localhost);
2596 	dump_cfg_fmtint(sPermitTTY, o->permit_tty);
2597 	dump_cfg_fmtint(sPermitUserRC, o->permit_user_rc);
2598 	dump_cfg_fmtint(sStrictModes, o->strict_modes);
2599 	dump_cfg_fmtint(sTCPKeepAlive, o->tcp_keep_alive);
2600 	dump_cfg_fmtint(sEmptyPasswd, o->permit_empty_passwd);
2601 	dump_cfg_fmtint(sCompression, o->compression);
2602 	dump_cfg_fmtint(sGatewayPorts, o->fwd_opts.gateway_ports);
2603 	dump_cfg_fmtint(sUseDNS, o->use_dns);
2604 	dump_cfg_fmtint(sAllowTcpForwarding, o->allow_tcp_forwarding);
2605 	dump_cfg_fmtint(sAllowAgentForwarding, o->allow_agent_forwarding);
2606 	dump_cfg_fmtint(sDisableForwarding, o->disable_forwarding);
2607 	dump_cfg_fmtint(sAllowStreamLocalForwarding, o->allow_streamlocal_forwarding);
2608 	dump_cfg_fmtint(sStreamLocalBindUnlink, o->fwd_opts.streamlocal_bind_unlink);
2609 	dump_cfg_fmtint(sFingerprintHash, o->fingerprint_hash);
2610 	dump_cfg_fmtint(sExposeAuthInfo, o->expose_userauth_info);
2611 
2612 	/* string arguments */
2613 	dump_cfg_string(sPidFile, o->pid_file);
2614 	dump_cfg_string(sXAuthLocation, o->xauth_location);
2615 	dump_cfg_string(sCiphers, o->ciphers ? o->ciphers : KEX_SERVER_ENCRYPT);
2616 	dump_cfg_string(sMacs, o->macs ? o->macs : KEX_SERVER_MAC);
2617 	dump_cfg_string(sBanner, o->banner);
2618 	dump_cfg_string(sForceCommand, o->adm_forced_command);
2619 	dump_cfg_string(sChrootDirectory, o->chroot_directory);
2620 	dump_cfg_string(sTrustedUserCAKeys, o->trusted_user_ca_keys);
2621 	dump_cfg_string(sRevokedKeys, o->revoked_keys_file);
2622 	dump_cfg_string(sAuthorizedPrincipalsFile,
2623 	    o->authorized_principals_file);
2624 	dump_cfg_string(sVersionAddendum, *o->version_addendum == '\0'
2625 	    ? "none" : o->version_addendum);
2626 	dump_cfg_string(sAuthorizedKeysCommand, o->authorized_keys_command);
2627 	dump_cfg_string(sAuthorizedKeysCommandUser, o->authorized_keys_command_user);
2628 	dump_cfg_string(sAuthorizedPrincipalsCommand, o->authorized_principals_command);
2629 	dump_cfg_string(sAuthorizedPrincipalsCommandUser, o->authorized_principals_command_user);
2630 	dump_cfg_string(sHostKeyAgent, o->host_key_agent);
2631 	dump_cfg_string(sKexAlgorithms,
2632 	    o->kex_algorithms ? o->kex_algorithms : KEX_SERVER_KEX);
2633 	dump_cfg_string(sCASignatureAlgorithms, o->ca_sign_algorithms ?
2634 	    o->ca_sign_algorithms : SSH_ALLOWED_CA_SIGALGS);
2635 	dump_cfg_string(sHostbasedAcceptedKeyTypes, o->hostbased_key_types ?
2636 	    o->hostbased_key_types : KEX_DEFAULT_PK_ALG);
2637 	dump_cfg_string(sHostKeyAlgorithms, o->hostkeyalgorithms ?
2638 	    o->hostkeyalgorithms : KEX_DEFAULT_PK_ALG);
2639 	dump_cfg_string(sPubkeyAcceptedKeyTypes, o->pubkey_key_types ?
2640 	    o->pubkey_key_types : KEX_DEFAULT_PK_ALG);
2641 	dump_cfg_string(sRDomain, o->routing_domain);
2642 
2643 	/* string arguments requiring a lookup */
2644 	dump_cfg_string(sLogLevel, log_level_name(o->log_level));
2645 	dump_cfg_string(sLogFacility, log_facility_name(o->log_facility));
2646 
2647 	/* string array arguments */
2648 	dump_cfg_strarray_oneline(sAuthorizedKeysFile, o->num_authkeys_files,
2649 	    o->authorized_keys_files);
2650 	dump_cfg_strarray(sHostKeyFile, o->num_host_key_files,
2651 	     o->host_key_files);
2652 	dump_cfg_strarray(sHostCertificate, o->num_host_cert_files,
2653 	     o->host_cert_files);
2654 	dump_cfg_strarray(sAllowUsers, o->num_allow_users, o->allow_users);
2655 	dump_cfg_strarray(sDenyUsers, o->num_deny_users, o->deny_users);
2656 	dump_cfg_strarray(sAllowGroups, o->num_allow_groups, o->allow_groups);
2657 	dump_cfg_strarray(sDenyGroups, o->num_deny_groups, o->deny_groups);
2658 	dump_cfg_strarray(sAcceptEnv, o->num_accept_env, o->accept_env);
2659 	dump_cfg_strarray(sSetEnv, o->num_setenv, o->setenv);
2660 	dump_cfg_strarray_oneline(sAuthenticationMethods,
2661 	    o->num_auth_methods, o->auth_methods);
2662 
2663 	/* other arguments */
2664 	for (i = 0; i < o->num_subsystems; i++)
2665 		printf("subsystem %s %s\n", o->subsystem_name[i],
2666 		    o->subsystem_args[i]);
2667 
2668 	printf("maxstartups %d:%d:%d\n", o->max_startups_begin,
2669 	    o->max_startups_rate, o->max_startups);
2670 
2671 	s = NULL;
2672 	for (i = 0; tunmode_desc[i].val != -1; i++) {
2673 		if (tunmode_desc[i].val == o->permit_tun) {
2674 			s = tunmode_desc[i].text;
2675 			break;
2676 		}
2677 	}
2678 	dump_cfg_string(sPermitTunnel, s);
2679 
2680 	printf("ipqos %s ", iptos2str(o->ip_qos_interactive));
2681 	printf("%s\n", iptos2str(o->ip_qos_bulk));
2682 
2683 	printf("rekeylimit %llu %d\n", (unsigned long long)o->rekey_limit,
2684 	    o->rekey_interval);
2685 
2686 	printf("permitopen");
2687 	if (o->num_permitted_opens == 0)
2688 		printf(" any");
2689 	else {
2690 		for (i = 0; i < o->num_permitted_opens; i++)
2691 			printf(" %s", o->permitted_opens[i]);
2692 	}
2693 	printf("\n");
2694 	printf("permitlisten");
2695 	if (o->num_permitted_listens == 0)
2696 		printf(" any");
2697 	else {
2698 		for (i = 0; i < o->num_permitted_listens; i++)
2699 			printf(" %s", o->permitted_listens[i]);
2700 	}
2701 	printf("\n");
2702 
2703 	if (o->permit_user_env_whitelist == NULL) {
2704 		dump_cfg_fmtint(sPermitUserEnvironment, o->permit_user_env);
2705 	} else {
2706 		printf("permituserenvironment %s\n",
2707 		    o->permit_user_env_whitelist);
2708 	}
2709 
2710 }
2711