1/*	$NetBSD: servconf.c,v 1.44 2023/12/20 17:15:21 christos Exp $	*/
2/* $OpenBSD: servconf.c,v 1.403 2023/10/11 22:42:26 djm Exp $ */
3
4/*
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 *                    All rights reserved
7 *
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose.  Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
13 */
14
15#include "includes.h"
16__RCSID("$NetBSD: servconf.c,v 1.44 2023/12/20 17:15:21 christos Exp $");
17#include <sys/types.h>
18#include <sys/socket.h>
19#include <sys/queue.h>
20#include <sys/param.h>
21#include <sys/sysctl.h>
22#include <sys/stat.h>
23
24#include <netinet/in.h>
25#include <netinet/ip.h>
26#include <net/route.h>
27
28#include <ctype.h>
29#include <glob.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#include <util.h>
41#include <time.h>
42
43#ifdef KRB4
44#include <krb.h>
45#ifdef AFS
46#include <kafs.h>
47#endif /* AFS */
48#endif /* KRB4 */
49
50#include "xmalloc.h"
51#include "ssh.h"
52#include "log.h"
53#include "sshbuf.h"
54#include "misc.h"
55#include "servconf.h"
56#include "pathnames.h"
57#include "cipher.h"
58#include "sshkey.h"
59#include "kex.h"
60#include "mac.h"
61#include "match.h"
62#include "channels.h"
63#include "groupaccess.h"
64#include "canohost.h"
65#include "packet.h"
66#include "ssherr.h"
67#include "hostfile.h"
68#include "auth.h"
69#include "fmt_scaled.h"
70
71#ifdef WITH_LDAP_PUBKEY
72#include "ldapauth.h"
73#endif
74#include "myproposal.h"
75#include "digest.h"
76
77static void add_listen_addr(ServerOptions *, const char *,
78    const char *, int);
79static void add_one_listen_addr(ServerOptions *, const char *,
80    const char *, int);
81static void parse_server_config_depth(ServerOptions *options,
82    const char *filename, struct sshbuf *conf, struct include_list *includes,
83    struct connection_info *connectinfo, int flags, int *activep, int depth);
84
85/* Use of privilege separation or not */
86extern int use_privsep;
87extern struct sshbuf *cfg;
88
89/* Initializes the server options to their default values. */
90
91void
92initialize_server_options(ServerOptions *options)
93{
94	memset(options, 0, sizeof(*options));
95
96	/* Portable-specific options */
97	options->use_pam = -1;
98
99	/* Standard Options */
100	options->num_ports = 0;
101	options->ports_from_cmdline = 0;
102	options->queued_listen_addrs = NULL;
103	options->num_queued_listens = 0;
104	options->listen_addrs = NULL;
105	options->num_listen_addrs = 0;
106	options->address_family = -1;
107	options->routing_domain = NULL;
108	options->num_host_key_files = 0;
109	options->num_host_cert_files = 0;
110	options->host_key_agent = NULL;
111	options->pid_file = NULL;
112	options->login_grace_time = -1;
113	options->permit_root_login = PERMIT_NOT_SET;
114	options->ignore_rhosts = -1;
115	options->ignore_root_rhosts = -1;
116	options->ignore_user_known_hosts = -1;
117	options->print_motd = -1;
118	options->print_lastlog = -1;
119	options->x11_forwarding = -1;
120	options->x11_display_offset = -1;
121	options->x11_use_localhost = -1;
122	options->permit_tty = -1;
123	options->permit_user_rc = -1;
124	options->xauth_location = NULL;
125	options->strict_modes = -1;
126	options->tcp_keep_alive = -1;
127	options->log_facility = SYSLOG_FACILITY_NOT_SET;
128	options->log_level = SYSLOG_LEVEL_NOT_SET;
129	options->num_log_verbose = 0;
130	options->log_verbose = NULL;
131	options->hostbased_authentication = -1;
132	options->hostbased_uses_name_from_packet_only = -1;
133	options->hostbased_accepted_algos = NULL;
134	options->hostkeyalgorithms = NULL;
135	options->pubkey_authentication = -1;
136	options->pubkey_auth_options = -1;
137	options->pubkey_accepted_algos = NULL;
138	options->kerberos_authentication = -1;
139	options->kerberos_or_local_passwd = -1;
140	options->kerberos_ticket_cleanup = -1;
141#if defined(AFS) || defined(KRB5)
142	options->kerberos_tgt_passing = -1;
143#endif
144#ifdef AFS
145	options->afs_token_passing = -1;
146#endif
147	options->kerberos_get_afs_token = -1;
148	options->gss_authentication=-1;
149	options->gss_cleanup_creds = -1;
150	options->gss_strict_acceptor = -1;
151	options->password_authentication = -1;
152	options->kbd_interactive_authentication = -1;
153	options->permit_empty_passwd = -1;
154	options->permit_user_env = -1;
155	options->permit_user_env_allowlist = NULL;
156	options->compression = -1;
157	options->rekey_limit = -1;
158	options->rekey_interval = -1;
159	options->allow_tcp_forwarding = -1;
160	options->allow_streamlocal_forwarding = -1;
161	options->allow_agent_forwarding = -1;
162	options->num_allow_users = 0;
163	options->num_deny_users = 0;
164	options->num_allow_groups = 0;
165	options->num_deny_groups = 0;
166	options->ciphers = NULL;
167#ifdef WITH_LDAP_PUBKEY
168	/* XXX dirty */
169	options->lpk.ld = NULL;
170	options->lpk.on = -1;
171	options->lpk.servers = NULL;
172	options->lpk.u_basedn = NULL;
173	options->lpk.g_basedn = NULL;
174	options->lpk.binddn = NULL;
175	options->lpk.bindpw = NULL;
176	options->lpk.sgroup = NULL;
177	options->lpk.filter = NULL;
178	options->lpk.fgroup = NULL;
179	options->lpk.l_conf = NULL;
180	options->lpk.tls = -1;
181	options->lpk.b_timeout.tv_sec = -1;
182	options->lpk.s_timeout.tv_sec = -1;
183	options->lpk.flags = FLAG_EMPTY;
184	options->lpk.pub_key_attr = NULL;
185#endif
186	options->macs = NULL;
187	options->kex_algorithms = NULL;
188	options->ca_sign_algorithms = NULL;
189	options->fwd_opts.gateway_ports = -1;
190	options->fwd_opts.streamlocal_bind_mask = (mode_t)-1;
191	options->fwd_opts.streamlocal_bind_unlink = -1;
192	options->num_subsystems = 0;
193	options->max_startups_begin = -1;
194	options->max_startups_rate = -1;
195	options->max_startups = -1;
196	options->per_source_max_startups = -1;
197	options->per_source_masklen_ipv4 = -1;
198	options->per_source_masklen_ipv6 = -1;
199	options->max_authtries = -1;
200	options->max_sessions = -1;
201	options->banner = NULL;
202	options->use_dns = -1;
203	options->client_alive_interval = -1;
204	options->client_alive_count_max = -1;
205	options->num_authkeys_files = 0;
206	options->num_accept_env = 0;
207	options->num_setenv = 0;
208	options->permit_tun = -1;
209	options->permitted_opens = NULL;
210	options->permitted_listens = NULL;
211	options->adm_forced_command = NULL;
212	options->chroot_directory = NULL;
213	options->authorized_keys_command = NULL;
214	options->authorized_keys_command_user = NULL;
215	options->revoked_keys_file = NULL;
216	options->sk_provider = NULL;
217	options->trusted_user_ca_keys = NULL;
218	options->authorized_principals_file = NULL;
219	options->authorized_principals_command = NULL;
220	options->authorized_principals_command_user = NULL;
221	options->ip_qos_interactive = -1;
222	options->ip_qos_bulk = -1;
223	options->version_addendum = NULL;
224	options->fingerprint_hash = -1;
225	options->disable_forwarding = -1;
226	options->expose_userauth_info = -1;
227	options->required_rsa_size = -1;
228	options->channel_timeouts = NULL;
229	options->num_channel_timeouts = 0;
230	options->unused_connection_timeout = -1;
231	options->none_enabled = -1;
232	options->tcp_rcv_buf_poll = -1;
233	options->hpn_disabled = -1;
234	options->hpn_buffer_size = -1;
235}
236
237/* Returns 1 if a string option is unset or set to "none" or 0 otherwise. */
238static int
239option_clear_or_none(const char *o)
240{
241	return o == NULL || strcasecmp(o, "none") == 0;
242}
243
244static void
245assemble_algorithms(ServerOptions *o)
246{
247	char *all_cipher, *all_mac, *all_kex, *all_key, *all_sig;
248	char *def_cipher, *def_mac, *def_kex, *def_key, *def_sig;
249	int r;
250
251	all_cipher = cipher_alg_list(',', 0);
252	all_mac = mac_alg_list(',');
253	all_kex = kex_alg_list(',');
254	all_key = sshkey_alg_list(0, 0, 1, ',');
255	all_sig = sshkey_alg_list(0, 1, 1, ',');
256	/* remove unsupported algos from default lists */
257	def_cipher = match_filter_allowlist(KEX_SERVER_ENCRYPT, all_cipher);
258	def_mac = match_filter_allowlist(KEX_SERVER_MAC, all_mac);
259	def_kex = match_filter_allowlist(KEX_SERVER_KEX, all_kex);
260	def_key = match_filter_allowlist(KEX_DEFAULT_PK_ALG, all_key);
261	def_sig = match_filter_allowlist(SSH_ALLOWED_CA_SIGALGS, all_sig);
262#define ASSEMBLE(what, defaults, all) \
263	do { \
264		if ((r = kex_assemble_names(&o->what, defaults, all)) != 0) \
265			fatal_fr(r, "%s", #what); \
266	} while (0)
267	ASSEMBLE(ciphers, def_cipher, all_cipher);
268	ASSEMBLE(macs, def_mac, all_mac);
269	ASSEMBLE(kex_algorithms, def_kex, all_kex);
270	ASSEMBLE(hostkeyalgorithms, def_key, all_key);
271	ASSEMBLE(hostbased_accepted_algos, def_key, all_key);
272	ASSEMBLE(pubkey_accepted_algos, def_key, all_key);
273	ASSEMBLE(ca_sign_algorithms, def_sig, all_sig);
274#undef ASSEMBLE
275	free(all_cipher);
276	free(all_mac);
277	free(all_kex);
278	free(all_key);
279	free(all_sig);
280	free(def_cipher);
281	free(def_mac);
282	free(def_kex);
283	free(def_key);
284	free(def_sig);
285}
286
287void
288servconf_add_hostkey(const char *file, const int line,
289    ServerOptions *options, const char *path, int userprovided)
290{
291	char *apath = derelativise_path(path);
292
293	opt_array_append2(file, line, "HostKey",
294	    &options->host_key_files, &options->host_key_file_userprovided,
295	    &options->num_host_key_files, apath, userprovided);
296	free(apath);
297}
298
299void
300servconf_add_hostcert(const char *file, const int line,
301    ServerOptions *options, const char *path)
302{
303	char *apath = derelativise_path(path);
304
305	opt_array_append(file, line, "HostCertificate",
306	    &options->host_cert_files, &options->num_host_cert_files, apath);
307	free(apath);
308}
309
310void
311fill_default_server_options(ServerOptions *options)
312{
313	/* needed for hpn socket tests */
314	int sock;
315	int socksize;
316	socklen_t socksizelen = sizeof(int);
317
318	/* Portable-specific options */
319	if (options->use_pam == -1)
320		options->use_pam = 0;
321
322	/* Standard Options */
323	u_int i;
324
325	if (options->num_host_key_files == 0) {
326		/* fill default hostkeys */
327		servconf_add_hostkey("[default]", 0, options,
328		    _PATH_HOST_RSA_KEY_FILE, 0);
329		servconf_add_hostkey("[default]", 0, options,
330		    _PATH_HOST_ECDSA_KEY_FILE, 0);
331		servconf_add_hostkey("[default]", 0, options,
332		    _PATH_HOST_ED25519_KEY_FILE, 0);
333#ifdef WITH_XMSS
334		servconf_add_hostkey("[default]", 0, options,
335		    _PATH_HOST_XMSS_KEY_FILE, 0);
336#endif /* WITH_XMSS */
337	}
338	/* No certificates by default */
339	if (options->num_ports == 0)
340		options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
341	if (options->address_family == -1)
342		options->address_family = AF_UNSPEC;
343	if (options->listen_addrs == NULL)
344		add_listen_addr(options, NULL, NULL, 0);
345	if (options->pid_file == NULL)
346		options->pid_file = xstrdup(_PATH_SSH_DAEMON_PID_FILE);
347	if (options->moduli_file == NULL)
348		options->moduli_file = xstrdup(_PATH_DH_MODULI);
349	if (options->login_grace_time == -1)
350		options->login_grace_time = 120;
351	if (options->permit_root_login == PERMIT_NOT_SET)
352		options->permit_root_login = PERMIT_NO_PASSWD;
353	if (options->ignore_rhosts == -1)
354		options->ignore_rhosts = 1;
355	if (options->ignore_root_rhosts == -1)
356		options->ignore_root_rhosts = options->ignore_rhosts;
357	if (options->ignore_user_known_hosts == -1)
358		options->ignore_user_known_hosts = 0;
359	if (options->print_motd == -1)
360		options->print_motd = 1;
361	if (options->print_lastlog == -1)
362		options->print_lastlog = 1;
363	if (options->x11_forwarding == -1)
364		options->x11_forwarding = 0;
365	if (options->x11_display_offset == -1)
366		options->x11_display_offset = 10;
367	if (options->x11_use_localhost == -1)
368		options->x11_use_localhost = 1;
369	if (options->xauth_location == NULL)
370		options->xauth_location = xstrdup(_PATH_XAUTH);
371	if (options->permit_tty == -1)
372		options->permit_tty = 1;
373	if (options->permit_user_rc == -1)
374		options->permit_user_rc = 1;
375	if (options->strict_modes == -1)
376		options->strict_modes = 1;
377	if (options->tcp_keep_alive == -1)
378		options->tcp_keep_alive = 1;
379	if (options->log_facility == SYSLOG_FACILITY_NOT_SET)
380		options->log_facility = SYSLOG_FACILITY_AUTH;
381	if (options->log_level == SYSLOG_LEVEL_NOT_SET)
382		options->log_level = SYSLOG_LEVEL_INFO;
383	if (options->hostbased_authentication == -1)
384		options->hostbased_authentication = 0;
385	if (options->hostbased_uses_name_from_packet_only == -1)
386		options->hostbased_uses_name_from_packet_only = 0;
387	if (options->pubkey_authentication == -1)
388		options->pubkey_authentication = 1;
389	if (options->pubkey_auth_options == -1)
390		options->pubkey_auth_options = 0;
391	if (options->kerberos_authentication == -1)
392		options->kerberos_authentication = 0;
393	if (options->kerberos_or_local_passwd == -1)
394		options->kerberos_or_local_passwd = 1;
395	if (options->kerberos_ticket_cleanup == -1)
396		options->kerberos_ticket_cleanup = 1;
397#if defined(AFS) || defined(KRB5)
398	if (options->kerberos_tgt_passing == -1)
399		options->kerberos_tgt_passing = 0;
400#endif
401#ifdef AFS
402	if (options->afs_token_passing == -1)
403		options->afs_token_passing = 0;
404#endif
405	if (options->kerberos_get_afs_token == -1)
406		options->kerberos_get_afs_token = 0;
407	if (options->gss_authentication == -1)
408		options->gss_authentication = 0;
409	if (options->gss_cleanup_creds == -1)
410		options->gss_cleanup_creds = 1;
411	if (options->gss_strict_acceptor == -1)
412		options->gss_strict_acceptor = 1;
413	if (options->password_authentication == -1)
414		options->password_authentication = 1;
415	if (options->kbd_interactive_authentication == -1)
416		options->kbd_interactive_authentication = 1;
417	if (options->permit_empty_passwd == -1)
418		options->permit_empty_passwd = 0;
419	if (options->permit_user_env == -1) {
420		options->permit_user_env = 0;
421		options->permit_user_env_allowlist = NULL;
422	}
423	if (options->compression == -1)
424#ifdef WITH_ZLIB
425		options->compression = COMP_DELAYED;
426#else
427		options->compression = COMP_NONE;
428#endif
429
430	if (options->rekey_limit == -1)
431		options->rekey_limit = 0;
432	if (options->rekey_interval == -1)
433		options->rekey_interval = 0;
434	if (options->allow_tcp_forwarding == -1)
435		options->allow_tcp_forwarding = FORWARD_ALLOW;
436	if (options->allow_streamlocal_forwarding == -1)
437		options->allow_streamlocal_forwarding = FORWARD_ALLOW;
438	if (options->allow_agent_forwarding == -1)
439		options->allow_agent_forwarding = 1;
440	if (options->fwd_opts.gateway_ports == -1)
441		options->fwd_opts.gateway_ports = 0;
442	if (options->max_startups == -1)
443		options->max_startups = 100;
444	if (options->max_startups_rate == -1)
445		options->max_startups_rate = 30;		/* 30% */
446	if (options->max_startups_begin == -1)
447		options->max_startups_begin = 10;
448	if (options->per_source_max_startups == -1)
449		options->per_source_max_startups = INT_MAX;
450	if (options->per_source_masklen_ipv4 == -1)
451		options->per_source_masklen_ipv4 = 32;
452	if (options->per_source_masklen_ipv6 == -1)
453		options->per_source_masklen_ipv6 = 128;
454	if (options->max_authtries == -1)
455		options->max_authtries = DEFAULT_AUTH_FAIL_MAX;
456	if (options->max_sessions == -1)
457		options->max_sessions = DEFAULT_SESSIONS_MAX;
458	if (options->use_dns == -1)
459		options->use_dns = 0;
460	if (options->client_alive_interval == -1)
461		options->client_alive_interval = 0;
462	if (options->client_alive_count_max == -1)
463		options->client_alive_count_max = 3;
464	if (options->num_authkeys_files == 0) {
465		opt_array_append("[default]", 0, "AuthorizedKeysFiles",
466		    &options->authorized_keys_files,
467		    &options->num_authkeys_files,
468		    _PATH_SSH_USER_PERMITTED_KEYS);
469		opt_array_append("[default]", 0, "AuthorizedKeysFiles",
470		    &options->authorized_keys_files,
471		    &options->num_authkeys_files,
472		    _PATH_SSH_USER_PERMITTED_KEYS2);
473	}
474	if (options->permit_tun == -1)
475		options->permit_tun = SSH_TUNMODE_NO;
476	if (options->ip_qos_interactive == -1)
477		options->ip_qos_interactive = IPTOS_DSCP_AF21;
478	if (options->ip_qos_bulk == -1)
479		options->ip_qos_bulk = IPTOS_DSCP_CS1;
480	if (options->version_addendum == NULL)
481		options->version_addendum = xstrdup("");
482
483	if (options->hpn_disabled == -1)
484		options->hpn_disabled = 0;
485
486	if (options->hpn_buffer_size == -1) {
487		/* option not explicitly set. Now we have to figure out */
488		/* what value to use */
489		if (options->hpn_disabled == 1) {
490			options->hpn_buffer_size = CHAN_SES_WINDOW_DEFAULT;
491		} else {
492			/* get the current RCV size and set it to that */
493			/*create a socket but don't connect it */
494			/* we use that the get the rcv socket size */
495			sock = socket(AF_INET, SOCK_STREAM, 0);
496			getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
497				   &socksize, &socksizelen);
498			close(sock);
499			options->hpn_buffer_size = socksize;
500			debug ("HPN Buffer Size: %d", options->hpn_buffer_size);
501
502		}
503	} else {
504		/* we have to do this incase the user sets both values in a contradictory */
505		/* manner. hpn_disabled overrrides hpn_buffer_size*/
506		if (options->hpn_disabled <= 0) {
507			if (options->hpn_buffer_size == 0)
508				options->hpn_buffer_size = 1;
509			/* limit the maximum buffer to 64MB */
510			if (options->hpn_buffer_size > 64*1024) {
511				options->hpn_buffer_size = 64*1024*1024;
512			} else {
513				options->hpn_buffer_size *= 1024;
514			}
515		} else
516			options->hpn_buffer_size = CHAN_TCP_WINDOW_DEFAULT;
517	}
518
519#ifdef WITH_LDAP_PUBKEY
520	if (options->lpk.on == -1)
521	    options->lpk.on = _DEFAULT_LPK_ON;
522	if (options->lpk.servers == NULL)
523	    options->lpk.servers = _DEFAULT_LPK_SERVERS;
524	if (options->lpk.u_basedn == NULL)
525	    options->lpk.u_basedn = _DEFAULT_LPK_UDN;
526	if (options->lpk.g_basedn == NULL)
527	    options->lpk.g_basedn = _DEFAULT_LPK_GDN;
528	if (options->lpk.binddn == NULL)
529	    options->lpk.binddn = _DEFAULT_LPK_BINDDN;
530	if (options->lpk.bindpw == NULL)
531	    options->lpk.bindpw = _DEFAULT_LPK_BINDPW;
532	if (options->lpk.sgroup == NULL)
533	    options->lpk.sgroup = _DEFAULT_LPK_SGROUP;
534	if (options->lpk.filter == NULL)
535	    options->lpk.filter = _DEFAULT_LPK_FILTER;
536	if (options->lpk.tls == -1)
537	    options->lpk.tls = _DEFAULT_LPK_TLS;
538	if (options->lpk.b_timeout.tv_sec == -1)
539	    options->lpk.b_timeout.tv_sec = _DEFAULT_LPK_BTIMEOUT;
540	if (options->lpk.s_timeout.tv_sec == -1)
541	    options->lpk.s_timeout.tv_sec = _DEFAULT_LPK_STIMEOUT;
542	if (options->lpk.l_conf == NULL)
543	    options->lpk.l_conf = _DEFAULT_LPK_LDP;
544	if (options->lpk.pub_key_attr == NULL)
545	    options->lpk.pub_key_attr = __UNCONST(_DEFAULT_LPK_PUB);
546#endif
547
548	if (options->fwd_opts.streamlocal_bind_mask == (mode_t)-1)
549		options->fwd_opts.streamlocal_bind_mask = 0177;
550	if (options->fwd_opts.streamlocal_bind_unlink == -1)
551		options->fwd_opts.streamlocal_bind_unlink = 0;
552	if (options->fingerprint_hash == -1)
553		options->fingerprint_hash = SSH_FP_HASH_DEFAULT;
554	if (options->disable_forwarding == -1)
555		options->disable_forwarding = 0;
556	if (options->expose_userauth_info == -1)
557		options->expose_userauth_info = 0;
558	if (options->sk_provider == NULL)
559		options->sk_provider = xstrdup("internal");
560	if (options->required_rsa_size == -1)
561		options->required_rsa_size = SSH_RSA_MINIMUM_MODULUS_SIZE;
562	if (options->unused_connection_timeout == -1)
563		options->unused_connection_timeout = 0;
564
565	assemble_algorithms(options);
566
567	/* Turn privilege separation and sandboxing on by default */
568	if (use_privsep == -1)
569		use_privsep = PRIVSEP_ON;
570
571#define CLEAR_ON_NONE(v) \
572	do { \
573		if (option_clear_or_none(v)) { \
574			free(v); \
575			v = NULL; \
576		} \
577	} while(0)
578#define CLEAR_ON_NONE_ARRAY(v, nv, none) \
579	do { \
580		if (options->nv == 1 && \
581		    strcasecmp(options->v[0], none) == 0) { \
582			free(options->v[0]); \
583			free(options->v); \
584			options->v = NULL; \
585			options->nv = 0; \
586		} \
587	} while (0)
588	CLEAR_ON_NONE(options->pid_file);
589	CLEAR_ON_NONE(options->xauth_location);
590	CLEAR_ON_NONE(options->banner);
591	CLEAR_ON_NONE(options->trusted_user_ca_keys);
592	CLEAR_ON_NONE(options->revoked_keys_file);
593	CLEAR_ON_NONE(options->sk_provider);
594	CLEAR_ON_NONE(options->authorized_principals_file);
595	CLEAR_ON_NONE(options->adm_forced_command);
596	CLEAR_ON_NONE(options->chroot_directory);
597	CLEAR_ON_NONE(options->routing_domain);
598	CLEAR_ON_NONE(options->host_key_agent);
599
600	for (i = 0; i < options->num_host_key_files; i++)
601		CLEAR_ON_NONE(options->host_key_files[i]);
602	for (i = 0; i < options->num_host_cert_files; i++)
603		CLEAR_ON_NONE(options->host_cert_files[i]);
604
605	CLEAR_ON_NONE_ARRAY(channel_timeouts, num_channel_timeouts, "none");
606	CLEAR_ON_NONE_ARRAY(auth_methods, num_auth_methods, "any");
607#undef CLEAR_ON_NONE
608#undef CLEAR_ON_NONE_ARRAY
609}
610
611/* Keyword tokens. */
612typedef enum {
613	sBadOption,		/* == unknown option */
614	sUsePAM,
615	sPort, sHostKeyFile, sLoginGraceTime,
616	sPermitRootLogin, sLogFacility, sLogLevel, sLogVerbose,
617	sKerberosAuthentication, sKerberosOrLocalPasswd, sKerberosTicketCleanup,
618	sKerberosGetAFSToken,
619	sKerberosTgtPassing,
620	sPasswordAuthentication,
621	sKbdInteractiveAuthentication, sListenAddress, sAddressFamily,
622	sPrintMotd, sPrintLastLog, sIgnoreRhosts,
623	sX11Forwarding, sX11DisplayOffset, sX11UseLocalhost,
624	sPermitTTY, sStrictModes, sEmptyPasswd, sTCPKeepAlive,
625	sPermitUserEnvironment, sAllowTcpForwarding, sCompression,
626	sRekeyLimit, sAllowUsers, sDenyUsers, sAllowGroups, sDenyGroups,
627	sIgnoreUserKnownHosts, sCiphers, sMacs, sPidFile, sModuliFile,
628	sGatewayPorts, sPubkeyAuthentication, sPubkeyAcceptedAlgorithms,
629	sXAuthLocation, sSubsystem, sMaxStartups, sMaxAuthTries, sMaxSessions,
630	sBanner, sUseDNS, sHostbasedAuthentication,
631	sHostbasedUsesNameFromPacketOnly, sHostbasedAcceptedAlgorithms,
632	sHostKeyAlgorithms, sPerSourceMaxStartups, sPerSourceNetBlockSize,
633	sClientAliveInterval, sClientAliveCountMax, sAuthorizedKeysFile,
634	sGssAuthentication, sGssCleanupCreds, sGssStrictAcceptor,
635	sAcceptEnv, sSetEnv, sPermitTunnel,
636	sMatch, sPermitOpen, sPermitListen, sForceCommand, sChrootDirectory,
637	sUsePrivilegeSeparation, sAllowAgentForwarding,
638	sHostCertificate, sInclude,
639	sRevokedKeys, sTrustedUserCAKeys, sAuthorizedPrincipalsFile,
640	sAuthorizedPrincipalsCommand, sAuthorizedPrincipalsCommandUser,
641	sKexAlgorithms, sCASignatureAlgorithms, sIPQoS, sVersionAddendum,
642	sIgnoreRootRhosts,
643	sNoneEnabled, sTcpRcvBufPoll,sHPNDisabled, sHPNBufferSize,
644	sAuthorizedKeysCommand, sAuthorizedKeysCommandUser,
645	sAuthenticationMethods, sHostKeyAgent, sPermitUserRC,
646	sStreamLocalBindMask, sStreamLocalBindUnlink,
647	sAllowStreamLocalForwarding, sFingerprintHash, sDisableForwarding,
648	sExposeAuthInfo, sRDomain, sPubkeyAuthOptions, sSecurityKeyProvider,
649	sRequiredRSASize, sChannelTimeout, sUnusedConnectionTimeout,
650	sDeprecated, sIgnore, sUnsupported
651#ifdef WITH_LDAP_PUBKEY
652	,sLdapPublickey, sLdapServers, sLdapUserDN
653	,sLdapGroupDN, sBindDN, sBindPw, sMyGroup
654	,sLdapFilter, sForceTLS, sBindTimeout
655	,sSearchTimeout, sLdapConf ,sLpkPubKeyAttr
656#endif
657} ServerOpCodes;
658
659#define SSHCFG_GLOBAL		0x01	/* allowed in main section of config */
660#define SSHCFG_MATCH		0x02	/* allowed inside a Match section */
661#define SSHCFG_ALL		(SSHCFG_GLOBAL|SSHCFG_MATCH)
662#define SSHCFG_NEVERMATCH	0x04  /* Match never matches; internal only */
663#define SSHCFG_MATCH_ONLY	0x08  /* Match only in conditional blocks; internal only */
664
665/* Textual representation of the tokens. */
666static struct {
667	const char *name;
668	ServerOpCodes opcode;
669	u_int flags;
670} keywords[] = {
671#ifdef USE_PAM
672	{ "usepam", sUsePAM, SSHCFG_GLOBAL },
673#else
674	{ "usepam", sUnsupported, SSHCFG_GLOBAL },
675#endif
676	{ "port", sPort, SSHCFG_GLOBAL },
677	{ "hostkey", sHostKeyFile, SSHCFG_GLOBAL },
678	{ "hostdsakey", sHostKeyFile, SSHCFG_GLOBAL },		/* alias */
679	{ "hostkeyagent", sHostKeyAgent, SSHCFG_GLOBAL },
680	{ "pidfile", sPidFile, SSHCFG_GLOBAL },
681	{ "modulifile", sModuliFile, SSHCFG_GLOBAL },
682	{ "serverkeybits", sDeprecated, SSHCFG_GLOBAL },
683	{ "logingracetime", sLoginGraceTime, SSHCFG_GLOBAL },
684	{ "keyregenerationinterval", sDeprecated, SSHCFG_GLOBAL },
685	{ "permitrootlogin", sPermitRootLogin, SSHCFG_ALL },
686	{ "syslogfacility", sLogFacility, SSHCFG_GLOBAL },
687	{ "loglevel", sLogLevel, SSHCFG_ALL },
688	{ "logverbose", sLogVerbose, SSHCFG_ALL },
689	{ "rhostsauthentication", sDeprecated, SSHCFG_GLOBAL },
690	{ "rhostsrsaauthentication", sDeprecated, SSHCFG_ALL },
691	{ "hostbasedauthentication", sHostbasedAuthentication, SSHCFG_ALL },
692	{ "hostbasedusesnamefrompacketonly", sHostbasedUsesNameFromPacketOnly, SSHCFG_ALL },
693	{ "hostbasedacceptedalgorithms", sHostbasedAcceptedAlgorithms, SSHCFG_ALL },
694	{ "hostbasedacceptedkeytypes", sHostbasedAcceptedAlgorithms, SSHCFG_ALL }, /* obsolete */
695	{ "hostkeyalgorithms", sHostKeyAlgorithms, SSHCFG_GLOBAL },
696	{ "rsaauthentication", sDeprecated, SSHCFG_ALL },
697	{ "pubkeyauthentication", sPubkeyAuthentication, SSHCFG_ALL },
698	{ "pubkeyacceptedalgorithms", sPubkeyAcceptedAlgorithms, SSHCFG_ALL },
699	{ "pubkeyacceptedkeytypes", sPubkeyAcceptedAlgorithms, SSHCFG_ALL }, /* obsolete */
700	{ "pubkeyauthoptions", sPubkeyAuthOptions, SSHCFG_ALL },
701	{ "dsaauthentication", sPubkeyAuthentication, SSHCFG_GLOBAL }, /* alias */
702#ifdef KRB5
703	{ "kerberosauthentication", sKerberosAuthentication, SSHCFG_ALL },
704	{ "kerberosorlocalpasswd", sKerberosOrLocalPasswd, SSHCFG_GLOBAL },
705	{ "kerberosticketcleanup", sKerberosTicketCleanup, SSHCFG_GLOBAL },
706	{ "kerberosgetafstoken", sKerberosGetAFSToken, SSHCFG_GLOBAL },
707#else
708	{ "kerberosauthentication", sUnsupported, SSHCFG_ALL },
709	{ "kerberosorlocalpasswd", sUnsupported, SSHCFG_GLOBAL },
710	{ "kerberosticketcleanup", sUnsupported, SSHCFG_GLOBAL },
711	{ "kerberosgetafstoken", sUnsupported, SSHCFG_GLOBAL },
712#endif
713#if defined(AFS) || defined(KRB5)
714	{ "kerberostgtpassing", sKerberosTgtPassing, SSHCFG_GLOBAL },
715#else
716	{ "kerberostgtpassing", sUnsupported, SSHCFG_GLOBAL },
717#endif
718	{ "afstokenpassing", sUnsupported, SSHCFG_GLOBAL },
719#ifdef GSSAPI
720	{ "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
721	{ "gssapicleanupcredentials", sGssCleanupCreds, SSHCFG_GLOBAL },
722	{ "gssapistrictacceptorcheck", sGssStrictAcceptor, SSHCFG_GLOBAL },
723#else
724	{ "gssapiauthentication", sUnsupported, SSHCFG_ALL },
725	{ "gssapicleanupcredentials", sUnsupported, SSHCFG_GLOBAL },
726	{ "gssapistrictacceptorcheck", sUnsupported, SSHCFG_GLOBAL },
727#endif
728	{ "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
729	{ "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
730	{ "challengeresponseauthentication", sKbdInteractiveAuthentication, SSHCFG_GLOBAL },
731	{ "skeyauthentication", sKbdInteractiveAuthentication, SSHCFG_GLOBAL }, /* alias */
732	{ "checkmail", sDeprecated, SSHCFG_GLOBAL },
733	{ "listenaddress", sListenAddress, SSHCFG_GLOBAL },
734	{ "addressfamily", sAddressFamily, SSHCFG_GLOBAL },
735	{ "printmotd", sPrintMotd, SSHCFG_GLOBAL },
736	{ "printlastlog", sPrintLastLog, SSHCFG_GLOBAL },
737	{ "ignorerhosts", sIgnoreRhosts, SSHCFG_ALL },
738	{ "ignoreuserknownhosts", sIgnoreUserKnownHosts, SSHCFG_GLOBAL },
739	{ "x11forwarding", sX11Forwarding, SSHCFG_ALL },
740	{ "x11displayoffset", sX11DisplayOffset, SSHCFG_ALL },
741	{ "x11uselocalhost", sX11UseLocalhost, SSHCFG_ALL },
742	{ "xauthlocation", sXAuthLocation, SSHCFG_GLOBAL },
743	{ "strictmodes", sStrictModes, SSHCFG_GLOBAL },
744	{ "permitemptypasswords", sEmptyPasswd, SSHCFG_ALL },
745	{ "permituserenvironment", sPermitUserEnvironment, SSHCFG_GLOBAL },
746	{ "uselogin", sDeprecated, SSHCFG_GLOBAL },
747	{ "compression", sCompression, SSHCFG_GLOBAL },
748	{ "rekeylimit", sRekeyLimit, SSHCFG_ALL },
749	{ "tcpkeepalive", sTCPKeepAlive, SSHCFG_GLOBAL },
750	{ "keepalive", sTCPKeepAlive, SSHCFG_GLOBAL },	/* obsolete alias */
751	{ "allowtcpforwarding", sAllowTcpForwarding, SSHCFG_ALL },
752	{ "allowagentforwarding", sAllowAgentForwarding, SSHCFG_ALL },
753	{ "allowusers", sAllowUsers, SSHCFG_ALL },
754	{ "denyusers", sDenyUsers, SSHCFG_ALL },
755	{ "allowgroups", sAllowGroups, SSHCFG_ALL },
756	{ "denygroups", sDenyGroups, SSHCFG_ALL },
757	{ "ciphers", sCiphers, SSHCFG_GLOBAL },
758	{ "macs", sMacs, SSHCFG_GLOBAL },
759	{ "protocol", sIgnore, SSHCFG_GLOBAL },
760	{ "gatewayports", sGatewayPorts, SSHCFG_ALL },
761	{ "subsystem", sSubsystem, SSHCFG_ALL },
762	{ "maxstartups", sMaxStartups, SSHCFG_GLOBAL },
763	{ "persourcemaxstartups", sPerSourceMaxStartups, SSHCFG_GLOBAL },
764	{ "persourcenetblocksize", sPerSourceNetBlockSize, SSHCFG_GLOBAL },
765	{ "maxauthtries", sMaxAuthTries, SSHCFG_ALL },
766	{ "maxsessions", sMaxSessions, SSHCFG_ALL },
767	{ "banner", sBanner, SSHCFG_ALL },
768	{ "usedns", sUseDNS, SSHCFG_GLOBAL },
769	{ "verifyreversemapping", sDeprecated, SSHCFG_GLOBAL },
770	{ "reversemappingcheck", sDeprecated, SSHCFG_GLOBAL },
771	{ "clientaliveinterval", sClientAliveInterval, SSHCFG_ALL },
772	{ "clientalivecountmax", sClientAliveCountMax, SSHCFG_ALL },
773	{ "authorizedkeysfile", sAuthorizedKeysFile, SSHCFG_ALL },
774	{ "authorizedkeysfile2", sDeprecated, SSHCFG_ALL },
775#ifdef WITH_LDAP_PUBKEY
776	{ _DEFAULT_LPK_TOKEN, sLdapPublickey, SSHCFG_GLOBAL },
777	{ _DEFAULT_SRV_TOKEN, sLdapServers, SSHCFG_GLOBAL },
778	{ _DEFAULT_USR_TOKEN, sLdapUserDN, SSHCFG_GLOBAL },
779	{ _DEFAULT_GRP_TOKEN, sLdapGroupDN, SSHCFG_GLOBAL },
780	{ _DEFAULT_BDN_TOKEN, sBindDN, SSHCFG_GLOBAL },
781	{ _DEFAULT_BPW_TOKEN, sBindPw, SSHCFG_GLOBAL },
782	{ _DEFAULT_MYG_TOKEN, sMyGroup, SSHCFG_GLOBAL },
783	{ _DEFAULT_FIL_TOKEN, sLdapFilter, SSHCFG_GLOBAL },
784	{ _DEFAULT_TLS_TOKEN, sForceTLS, SSHCFG_GLOBAL },
785	{ _DEFAULT_BTI_TOKEN, sBindTimeout, SSHCFG_GLOBAL },
786	{ _DEFAULT_STI_TOKEN, sSearchTimeout, SSHCFG_GLOBAL },
787	{ _DEFAULT_LDP_TOKEN, sLdapConf, SSHCFG_GLOBAL },
788	{ "LpkPubKeyAttr", sLpkPubKeyAttr, SSHCFG_GLOBAL },
789#endif
790	{ "useprivilegeseparation", sDeprecated, SSHCFG_GLOBAL},
791	{ "acceptenv", sAcceptEnv, SSHCFG_ALL },
792	{ "setenv", sSetEnv, SSHCFG_ALL },
793	{ "permittunnel", sPermitTunnel, SSHCFG_ALL },
794	{ "permittty", sPermitTTY, SSHCFG_ALL },
795	{ "permituserrc", sPermitUserRC, SSHCFG_ALL },
796	{ "match", sMatch, SSHCFG_ALL },
797	{ "permitopen", sPermitOpen, SSHCFG_ALL },
798	{ "permitlisten", sPermitListen, SSHCFG_ALL },
799	{ "forcecommand", sForceCommand, SSHCFG_ALL },
800	{ "chrootdirectory", sChrootDirectory, SSHCFG_ALL },
801	{ "hostcertificate", sHostCertificate, SSHCFG_GLOBAL },
802	{ "revokedkeys", sRevokedKeys, SSHCFG_ALL },
803	{ "trustedusercakeys", sTrustedUserCAKeys, SSHCFG_ALL },
804	{ "authorizedprincipalsfile", sAuthorizedPrincipalsFile, SSHCFG_ALL },
805	{ "kexalgorithms", sKexAlgorithms, SSHCFG_GLOBAL },
806	{ "include", sInclude, SSHCFG_ALL },
807	{ "ipqos", sIPQoS, SSHCFG_ALL },
808	{ "authorizedkeyscommand", sAuthorizedKeysCommand, SSHCFG_ALL },
809	{ "authorizedkeyscommanduser", sAuthorizedKeysCommandUser, SSHCFG_ALL },
810	{ "authorizedprincipalscommand", sAuthorizedPrincipalsCommand, SSHCFG_ALL },
811	{ "authorizedprincipalscommanduser", sAuthorizedPrincipalsCommandUser, SSHCFG_ALL },
812	{ "versionaddendum", sVersionAddendum, SSHCFG_GLOBAL },
813	{ "noneenabled", sNoneEnabled, SSHCFG_ALL },
814	{ "hpndisabled", sHPNDisabled, SSHCFG_ALL },
815	{ "hpnbuffersize", sHPNBufferSize, SSHCFG_ALL },
816	{ "tcprcvbufpoll", sTcpRcvBufPoll, SSHCFG_ALL },
817	{ "authenticationmethods", sAuthenticationMethods, SSHCFG_ALL },
818	{ "streamlocalbindmask", sStreamLocalBindMask, SSHCFG_ALL },
819	{ "streamlocalbindunlink", sStreamLocalBindUnlink, SSHCFG_ALL },
820	{ "allowstreamlocalforwarding", sAllowStreamLocalForwarding, SSHCFG_ALL },
821	{ "fingerprinthash", sFingerprintHash, SSHCFG_GLOBAL },
822	{ "disableforwarding", sDisableForwarding, SSHCFG_ALL },
823	{ "exposeauthinfo", sExposeAuthInfo, SSHCFG_ALL },
824	{ "rdomain", sRDomain, SSHCFG_ALL },
825	{ "casignaturealgorithms", sCASignatureAlgorithms, SSHCFG_ALL },
826	{ "securitykeyprovider", sSecurityKeyProvider, SSHCFG_GLOBAL },
827	{ "requiredrsasize", sRequiredRSASize, SSHCFG_ALL },
828	{ "channeltimeout", sChannelTimeout, SSHCFG_ALL },
829	{ "unusedconnectiontimeout", sUnusedConnectionTimeout, SSHCFG_ALL },
830	{ NULL, sBadOption, 0 }
831};
832
833static struct {
834	int val;
835	const char *text;
836} tunmode_desc[] = {
837	{ SSH_TUNMODE_NO, "no" },
838	{ SSH_TUNMODE_POINTOPOINT, "point-to-point" },
839	{ SSH_TUNMODE_ETHERNET, "ethernet" },
840	{ SSH_TUNMODE_YES, "yes" },
841	{ -1, NULL }
842};
843
844/* Returns an opcode name from its number */
845
846static const char *
847lookup_opcode_name(ServerOpCodes code)
848{
849	u_int i;
850
851	for (i = 0; keywords[i].name != NULL; i++)
852		if (keywords[i].opcode == code)
853			return(keywords[i].name);
854	return "UNKNOWN";
855}
856
857
858/*
859 * Returns the number of the token pointed to by cp or sBadOption.
860 */
861
862static ServerOpCodes
863parse_token(const char *cp, const char *filename,
864	    int linenum, u_int *flags)
865{
866	u_int i;
867
868	for (i = 0; keywords[i].name; i++)
869		if (strcasecmp(cp, keywords[i].name) == 0) {
870		        debug ("Config token is %s", keywords[i].name);
871			*flags = keywords[i].flags;
872			return keywords[i].opcode;
873		}
874
875	error("%s: line %d: Bad configuration option: %s",
876	    filename, linenum, cp);
877	return sBadOption;
878}
879
880char *
881derelativise_path(const char *path)
882{
883	char *expanded, *ret, cwd[PATH_MAX];
884
885	if (strcasecmp(path, "none") == 0)
886		return xstrdup("none");
887	expanded = tilde_expand_filename(path, getuid());
888	if (path_absolute(expanded))
889		return expanded;
890	if (getcwd(cwd, sizeof(cwd)) == NULL)
891		fatal_f("getcwd: %s", strerror(errno));
892	xasprintf(&ret, "%s/%s", cwd, expanded);
893	free(expanded);
894	return ret;
895}
896
897static void
898add_listen_addr(ServerOptions *options, const char *addr,
899    const char *rdomain, int port)
900{
901	u_int i;
902
903	if (port > 0)
904		add_one_listen_addr(options, addr, rdomain, port);
905	else {
906		for (i = 0; i < options->num_ports; i++) {
907			add_one_listen_addr(options, addr, rdomain,
908			    options->ports[i]);
909		}
910	}
911}
912
913static void
914add_one_listen_addr(ServerOptions *options, const char *addr,
915    const char *rdomain, int port)
916{
917	struct addrinfo hints, *ai, *aitop;
918	char strport[NI_MAXSERV];
919	int gaierr;
920	u_int i;
921
922	/* Find listen_addrs entry for this rdomain */
923	for (i = 0; i < options->num_listen_addrs; i++) {
924		if (rdomain == NULL && options->listen_addrs[i].rdomain == NULL)
925			break;
926		if (rdomain == NULL || options->listen_addrs[i].rdomain == NULL)
927			continue;
928		if (strcmp(rdomain, options->listen_addrs[i].rdomain) == 0)
929			break;
930	}
931	if (i >= options->num_listen_addrs) {
932		/* No entry for this rdomain; allocate one */
933		if (i >= INT_MAX)
934			fatal_f("too many listen addresses");
935		options->listen_addrs = xrecallocarray(options->listen_addrs,
936		    options->num_listen_addrs, options->num_listen_addrs + 1,
937		    sizeof(*options->listen_addrs));
938		i = options->num_listen_addrs++;
939		if (rdomain != NULL)
940			options->listen_addrs[i].rdomain = xstrdup(rdomain);
941	}
942	/* options->listen_addrs[i] points to the addresses for this rdomain */
943
944	memset(&hints, 0, sizeof(hints));
945	hints.ai_family = options->address_family;
946	hints.ai_socktype = SOCK_STREAM;
947	hints.ai_flags = (addr == NULL) ? AI_PASSIVE : 0;
948	snprintf(strport, sizeof strport, "%d", port);
949	if ((gaierr = getaddrinfo(addr, strport, &hints, &aitop)) != 0)
950		fatal("bad addr or host: %s (%s)",
951		    addr ? addr : "<NULL>",
952		    ssh_gai_strerror(gaierr));
953	for (ai = aitop; ai->ai_next; ai = ai->ai_next)
954		;
955	ai->ai_next = options->listen_addrs[i].addrs;
956	options->listen_addrs[i].addrs = aitop;
957}
958
959/* Returns nonzero if the routing domain name is valid */
960static int
961valid_rdomain(const char *name)
962{
963#ifdef NET_RT_TABLE
964	const char *errstr;
965	long long num;
966	struct rt_tableinfo info;
967	int mib[6];
968	size_t miblen = sizeof(mib);
969
970	if (name == NULL)
971		return 1;
972
973	num = strtonum(name, 0, 255, &errstr);
974	if (errstr != NULL)
975		return 0;
976
977	/* Check whether the table actually exists */
978	memset(mib, 0, sizeof(mib));
979	mib[0] = CTL_NET;
980	mib[1] = PF_ROUTE;
981	mib[4] = NET_RT_TABLE;
982	mib[5] = (int)num;
983	if (sysctl(mib, 6, &info, &miblen, NULL, 0) == -1)
984		return 0;
985
986	return 1;
987#else
988	return 0;
989#endif
990}
991
992/*
993 * Queue a ListenAddress to be processed once we have all of the Ports
994 * and AddressFamily options.
995 */
996static void
997queue_listen_addr(ServerOptions *options, const char *addr,
998    const char *rdomain, int port)
999{
1000	struct queued_listenaddr *qla;
1001
1002	options->queued_listen_addrs = xrecallocarray(
1003	    options->queued_listen_addrs,
1004	    options->num_queued_listens, options->num_queued_listens + 1,
1005	    sizeof(*options->queued_listen_addrs));
1006	qla = &options->queued_listen_addrs[options->num_queued_listens++];
1007	qla->addr = xstrdup(addr);
1008	qla->port = port;
1009	qla->rdomain = rdomain == NULL ? NULL : xstrdup(rdomain);
1010}
1011
1012/*
1013 * Process queued (text) ListenAddress entries.
1014 */
1015static void
1016process_queued_listen_addrs(ServerOptions *options)
1017{
1018	u_int i;
1019	struct queued_listenaddr *qla;
1020
1021	if (options->num_ports == 0)
1022		options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
1023	if (options->address_family == -1)
1024		options->address_family = AF_UNSPEC;
1025
1026	for (i = 0; i < options->num_queued_listens; i++) {
1027		qla = &options->queued_listen_addrs[i];
1028		add_listen_addr(options, qla->addr, qla->rdomain, qla->port);
1029		free(qla->addr);
1030		free(qla->rdomain);
1031	}
1032	free(options->queued_listen_addrs);
1033	options->queued_listen_addrs = NULL;
1034	options->num_queued_listens = 0;
1035}
1036
1037/*
1038 * Inform channels layer of permitopen options for a single forwarding
1039 * direction (local/remote).
1040 */
1041static void
1042process_permitopen_list(struct ssh *ssh, ServerOpCodes opcode,
1043    char **opens, u_int num_opens)
1044{
1045	u_int i;
1046	int port;
1047	char *host, *arg, *oarg;
1048	int where = opcode == sPermitOpen ? FORWARD_LOCAL : FORWARD_REMOTE;
1049	const char *what = lookup_opcode_name(opcode);
1050
1051	channel_clear_permission(ssh, FORWARD_ADM, where);
1052	if (num_opens == 0)
1053		return; /* permit any */
1054
1055	/* handle keywords: "any" / "none" */
1056	if (num_opens == 1 && strcmp(opens[0], "any") == 0)
1057		return;
1058	if (num_opens == 1 && strcmp(opens[0], "none") == 0) {
1059		channel_disable_admin(ssh, where);
1060		return;
1061	}
1062	/* Otherwise treat it as a list of permitted host:port */
1063	for (i = 0; i < num_opens; i++) {
1064		oarg = arg = xstrdup(opens[i]);
1065		host = hpdelim(&arg);
1066		if (host == NULL)
1067			fatal_f("missing host in %s", what);
1068		host = cleanhostname(host);
1069		if (arg == NULL || ((port = permitopen_port(arg)) < 0))
1070			fatal_f("bad port number in %s", what);
1071		/* Send it to channels layer */
1072		channel_add_permission(ssh, FORWARD_ADM,
1073		    where, host, port);
1074		free(oarg);
1075	}
1076}
1077
1078/*
1079 * Inform channels layer of permitopen options from configuration.
1080 */
1081void
1082process_permitopen(struct ssh *ssh, ServerOptions *options)
1083{
1084	process_permitopen_list(ssh, sPermitOpen,
1085	    options->permitted_opens, options->num_permitted_opens);
1086	process_permitopen_list(ssh, sPermitListen,
1087	    options->permitted_listens,
1088	    options->num_permitted_listens);
1089}
1090
1091void
1092process_channel_timeouts(struct ssh *ssh, ServerOptions *options)
1093{
1094	int secs;
1095	u_int i;
1096	char *type;
1097
1098	debug3_f("setting %u timeouts", options->num_channel_timeouts);
1099	channel_clear_timeouts(ssh);
1100	for (i = 0; i < options->num_channel_timeouts; i++) {
1101		if (parse_pattern_interval(options->channel_timeouts[i],
1102		    &type, &secs) != 0) {
1103			fatal_f("internal error: bad timeout %s",
1104			    options->channel_timeouts[i]);
1105		}
1106		channel_add_timeout(ssh, type, secs);
1107		free(type);
1108	}
1109}
1110
1111struct connection_info *
1112get_connection_info(struct ssh *ssh, int populate, int use_dns)
1113{
1114	static struct connection_info ci;
1115
1116	if (ssh == NULL || !populate)
1117		return &ci;
1118	ci.host = auth_get_canonical_hostname(ssh, use_dns);
1119	ci.address = ssh_remote_ipaddr(ssh);
1120	ci.laddress = ssh_local_ipaddr(ssh);
1121	ci.lport = ssh_local_port(ssh);
1122	ci.rdomain = ssh_packet_rdomain_in(ssh);
1123	return &ci;
1124}
1125
1126/*
1127 * The strategy for the Match blocks is that the config file is parsed twice.
1128 *
1129 * The first time is at startup.  activep is initialized to 1 and the
1130 * directives in the global context are processed and acted on.  Hitting a
1131 * Match directive unsets activep and the directives inside the block are
1132 * checked for syntax only.
1133 *
1134 * The second time is after a connection has been established but before
1135 * authentication.  activep is initialized to 2 and global config directives
1136 * are ignored since they have already been processed.  If the criteria in a
1137 * Match block is met, activep is set and the subsequent directives
1138 * processed and actioned until EOF or another Match block unsets it.  Any
1139 * options set are copied into the main server config.
1140 *
1141 * Potential additions/improvements:
1142 *  - Add Match support for pre-kex directives, eg. Ciphers.
1143 *
1144 *  - Add a Tag directive (idea from David Leonard) ala pf, eg:
1145 *	Match Address 192.168.0.*
1146 *		Tag trusted
1147 *	Match Group wheel
1148 *		Tag trusted
1149 *	Match Tag trusted
1150 *		AllowTcpForwarding yes
1151 *		GatewayPorts clientspecified
1152 *		[...]
1153 *
1154 *  - Add a PermittedChannelRequests directive
1155 *	Match Group shell
1156 *		PermittedChannelRequests session,forwarded-tcpip
1157 */
1158
1159static int
1160match_cfg_line_group(const char *grps, int line, const char *user)
1161{
1162	int result = 0;
1163	struct passwd *pw;
1164
1165	if (user == NULL)
1166		goto out;
1167
1168	if ((pw = getpwnam(user)) == NULL) {
1169		debug("Can't match group at line %d because user %.100s does "
1170		    "not exist", line, user);
1171	} else if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
1172		debug("Can't Match group because user %.100s not in any group "
1173		    "at line %d", user, line);
1174	} else if (ga_match_pattern_list(grps) != 1) {
1175		debug("user %.100s does not match group list %.100s at line %d",
1176		    user, grps, line);
1177	} else {
1178		debug("user %.100s matched group list %.100s at line %d", user,
1179		    grps, line);
1180		result = 1;
1181	}
1182out:
1183	ga_free();
1184	return result;
1185}
1186
1187__dead static void
1188match_test_missing_fatal(const char *criteria, const char *attrib)
1189{
1190	fatal("'Match %s' in configuration but '%s' not in connection "
1191	    "test specification.", criteria, attrib);
1192}
1193
1194/*
1195 * All of the attributes on a single Match line are ANDed together, so we need
1196 * to check every attribute and set the result to zero if any attribute does
1197 * not match.
1198 */
1199static int
1200match_cfg_line(char **condition, int line, struct connection_info *ci)
1201{
1202	int result = 1, attributes = 0, port;
1203	char *arg, *attrib, *cp = *condition;
1204
1205	if (ci == NULL)
1206		debug3("checking syntax for 'Match %s'", cp);
1207	else
1208		debug3("checking match for '%s' user %s host %s addr %s "
1209		    "laddr %s lport %d", cp, ci->user ? ci->user : "(null)",
1210		    ci->host ? ci->host : "(null)",
1211		    ci->address ? ci->address : "(null)",
1212		    ci->laddress ? ci->laddress : "(null)", ci->lport);
1213
1214	while ((attrib = strdelim(&cp)) && *attrib != '\0') {
1215		/* Terminate on comment */
1216		if (*attrib == '#') {
1217			cp = NULL; /* mark all arguments consumed */
1218			break;
1219		}
1220		arg = NULL;
1221		attributes++;
1222		/* Criterion "all" has no argument and must appear alone */
1223		if (strcasecmp(attrib, "all") == 0) {
1224			if (attributes > 1 || ((arg = strdelim(&cp)) != NULL &&
1225			    *arg != '\0' && *arg != '#')) {
1226				error("'all' cannot be combined with other "
1227				    "Match attributes");
1228				return -1;
1229			}
1230			if (arg != NULL && *arg == '#')
1231				cp = NULL; /* mark all arguments consumed */
1232			*condition = cp;
1233			return 1;
1234		}
1235		/* All other criteria require an argument */
1236		if ((arg = strdelim(&cp)) == NULL ||
1237		    *arg == '\0' || *arg == '#') {
1238			error("Missing Match criteria for %s", attrib);
1239			return -1;
1240		}
1241		if (strcasecmp(attrib, "user") == 0) {
1242			if (ci == NULL || (ci->test && ci->user == NULL)) {
1243				result = 0;
1244				continue;
1245			}
1246			if (ci->user == NULL)
1247				match_test_missing_fatal("User", "user");
1248			if (match_usergroup_pattern_list(ci->user, arg) != 1)
1249				result = 0;
1250			else
1251				debug("user %.100s matched 'User %.100s' at "
1252				    "line %d", ci->user, arg, line);
1253		} else if (strcasecmp(attrib, "group") == 0) {
1254			if (ci == NULL || (ci->test && ci->user == NULL)) {
1255				result = 0;
1256				continue;
1257			}
1258			if (ci->user == NULL)
1259				match_test_missing_fatal("Group", "user");
1260			switch (match_cfg_line_group(arg, line, ci->user)) {
1261			case -1:
1262				return -1;
1263			case 0:
1264				result = 0;
1265			}
1266		} else if (strcasecmp(attrib, "host") == 0) {
1267			if (ci == NULL || (ci->test && ci->host == NULL)) {
1268				result = 0;
1269				continue;
1270			}
1271			if (ci->host == NULL)
1272				match_test_missing_fatal("Host", "host");
1273			if (match_hostname(ci->host, arg) != 1)
1274				result = 0;
1275			else
1276				debug("connection from %.100s matched 'Host "
1277				    "%.100s' at line %d", ci->host, arg, line);
1278		} else if (strcasecmp(attrib, "address") == 0) {
1279			if (ci == NULL || (ci->test && ci->address == NULL)) {
1280				if (addr_match_list(NULL, arg) != 0)
1281					fatal("Invalid Match address argument "
1282					    "'%s' at line %d", arg, line);
1283				result = 0;
1284				continue;
1285			}
1286			if (ci->address == NULL)
1287				match_test_missing_fatal("Address", "addr");
1288			switch (addr_match_list(ci->address, arg)) {
1289			case 1:
1290				debug("connection from %.100s matched 'Address "
1291				    "%.100s' at line %d", ci->address, arg, line);
1292				break;
1293			case 0:
1294			case -1:
1295				result = 0;
1296				break;
1297			case -2:
1298				return -1;
1299			}
1300		} else if (strcasecmp(attrib, "localaddress") == 0){
1301			if (ci == NULL || (ci->test && ci->laddress == NULL)) {
1302				if (addr_match_list(NULL, arg) != 0)
1303					fatal("Invalid Match localaddress "
1304					    "argument '%s' at line %d", arg,
1305					    line);
1306				result = 0;
1307				continue;
1308			}
1309			if (ci->laddress == NULL)
1310				match_test_missing_fatal("LocalAddress",
1311				    "laddr");
1312			switch (addr_match_list(ci->laddress, arg)) {
1313			case 1:
1314				debug("connection from %.100s matched "
1315				    "'LocalAddress %.100s' at line %d",
1316				    ci->laddress, arg, line);
1317				break;
1318			case 0:
1319			case -1:
1320				result = 0;
1321				break;
1322			case -2:
1323				return -1;
1324			}
1325		} else if (strcasecmp(attrib, "localport") == 0) {
1326			if ((port = a2port(arg)) == -1) {
1327				error("Invalid LocalPort '%s' on Match line",
1328				    arg);
1329				return -1;
1330			}
1331			if (ci == NULL || (ci->test && ci->lport == -1)) {
1332				result = 0;
1333				continue;
1334			}
1335			if (ci->lport == 0)
1336				match_test_missing_fatal("LocalPort", "lport");
1337			/* TODO support port lists */
1338			if (port == ci->lport)
1339				debug("connection from %.100s matched "
1340				    "'LocalPort %d' at line %d",
1341				    ci->laddress, port, line);
1342			else
1343				result = 0;
1344		} else if (strcasecmp(attrib, "rdomain") == 0) {
1345			if (ci == NULL || (ci->test && ci->rdomain == NULL)) {
1346				result = 0;
1347				continue;
1348			}
1349			if (ci->rdomain == NULL)
1350				match_test_missing_fatal("RDomain", "rdomain");
1351			if (match_pattern_list(ci->rdomain, arg, 0) != 1)
1352				result = 0;
1353			else
1354				debug("user %.100s matched 'RDomain %.100s' at "
1355				    "line %d", ci->rdomain, arg, line);
1356		} else {
1357			error("Unsupported Match attribute %s", attrib);
1358			return -1;
1359		}
1360	}
1361	if (attributes == 0) {
1362		error("One or more attributes required for Match");
1363		return -1;
1364	}
1365	if (ci != NULL)
1366		debug3("match %sfound", result ? "" : "not ");
1367	*condition = cp;
1368	return result;
1369}
1370
1371#define WHITESPACE " \t\r\n"
1372
1373/* Multistate option parsing */
1374struct multistate {
1375	const char *key;
1376	int value;
1377};
1378static const struct multistate multistate_flag[] = {
1379	{ "yes",			1 },
1380	{ "no",				0 },
1381	{ NULL, -1 }
1382};
1383static const struct multistate multistate_ignore_rhosts[] = {
1384	{ "yes",			IGNORE_RHOSTS_YES },
1385	{ "no",				IGNORE_RHOSTS_NO },
1386	{ "shosts-only",		IGNORE_RHOSTS_SHOSTS },
1387	{ NULL, -1 }
1388};
1389static const struct multistate multistate_addressfamily[] = {
1390	{ "inet",			AF_INET },
1391	{ "inet6",			AF_INET6 },
1392	{ "any",			AF_UNSPEC },
1393	{ NULL, -1 }
1394};
1395static const struct multistate multistate_permitrootlogin[] = {
1396	{ "without-password",		PERMIT_NO_PASSWD },
1397	{ "prohibit-password",		PERMIT_NO_PASSWD },
1398	{ "forced-commands-only",	PERMIT_FORCED_ONLY },
1399	{ "yes",			PERMIT_YES },
1400	{ "no",				PERMIT_NO },
1401	{ NULL, -1 }
1402};
1403static const struct multistate multistate_compression[] = {
1404#ifdef WITH_ZLIB
1405	{ "yes",			COMP_DELAYED },
1406	{ "delayed",			COMP_DELAYED },
1407#endif
1408	{ "no",				COMP_NONE },
1409	{ NULL, -1 }
1410};
1411static const struct multistate multistate_gatewayports[] = {
1412	{ "clientspecified",		2 },
1413	{ "yes",			1 },
1414	{ "no",				0 },
1415	{ NULL, -1 }
1416};
1417static const struct multistate multistate_tcpfwd[] = {
1418	{ "yes",			FORWARD_ALLOW },
1419	{ "all",			FORWARD_ALLOW },
1420	{ "no",				FORWARD_DENY },
1421	{ "remote",			FORWARD_REMOTE },
1422	{ "local",			FORWARD_LOCAL },
1423	{ NULL, -1 }
1424};
1425
1426static int
1427process_server_config_line_depth(ServerOptions *options, char *line,
1428    const char *filename, int linenum, int *activep,
1429    struct connection_info *connectinfo, int *inc_flags, int depth,
1430    struct include_list *includes)
1431{
1432	char *str, ***chararrayptr, **charptr, *arg, *arg2, *p, *keyword;
1433	int cmdline = 0, *intptr, value, value2, n, port, oactive, r, found;
1434	int ca_only = 0;
1435	SyslogFacility *log_facility_ptr;
1436	LogLevel *log_level_ptr;
1437#ifdef WITH_LDAP_PUBKEY
1438 	unsigned long lvalue;
1439#endif
1440	time_t *timetptr __unused;
1441	ServerOpCodes opcode;
1442	u_int i, *uintptr, uvalue, flags = 0;
1443	size_t len;
1444	long long val64;
1445	const struct multistate *multistate_ptr;
1446	const char *errstr;
1447	struct include_item *item;
1448	glob_t gbuf;
1449	char **oav = NULL, **av;
1450	int oac = 0, ac;
1451	int ret = -1;
1452
1453	/* Strip trailing whitespace. Allow \f (form feed) at EOL only */
1454	if ((len = strlen(line)) == 0)
1455		return 0;
1456	for (len--; len > 0; len--) {
1457		if (strchr(WHITESPACE "\f", line[len]) == NULL)
1458			break;
1459		line[len] = '\0';
1460	}
1461
1462	str = line;
1463	if ((keyword = strdelim(&str)) == NULL)
1464		return 0;
1465	/* Ignore leading whitespace */
1466	if (*keyword == '\0')
1467		keyword = strdelim(&str);
1468	if (!keyword || !*keyword || *keyword == '#')
1469		return 0;
1470	if (str == NULL || *str == '\0') {
1471		error("%s line %d: no argument after keyword \"%s\"",
1472		    filename, linenum, keyword);
1473		return -1;
1474	}
1475	intptr = NULL;
1476	timetptr = NULL;
1477	charptr = NULL;
1478	opcode = parse_token(keyword, filename, linenum, &flags);
1479
1480	if (argv_split(str, &oac, &oav, 1) != 0) {
1481		error("%s line %d: invalid quotes", filename, linenum);
1482		return -1;
1483	}
1484	ac = oac;
1485	av = oav;
1486
1487	if (activep == NULL) { /* We are processing a command line directive */
1488		cmdline = 1;
1489		activep = &cmdline;
1490	}
1491	if (*activep && opcode != sMatch && opcode != sInclude)
1492		debug3("%s:%d setting %s %s", filename, linenum, keyword, str);
1493	if (*activep == 0 && !(flags & SSHCFG_MATCH)) {
1494		if (connectinfo == NULL) {
1495			fatal("%s line %d: Directive '%s' is not allowed "
1496			    "within a Match block", filename, linenum, keyword);
1497		} else { /* this is a directive we have already processed */
1498			ret = 0;
1499			goto out;
1500		}
1501	}
1502
1503	switch (opcode) {
1504	/* Portable-specific options */
1505	case sUsePAM:
1506		intptr = &options->use_pam;
1507		goto parse_flag;
1508
1509	/* Standard Options */
1510	case sBadOption:
1511		goto out;
1512	case sPort:
1513		/* ignore ports from configfile if cmdline specifies ports */
1514		if (options->ports_from_cmdline) {
1515			argv_consume(&ac);
1516			break;
1517		}
1518		if (options->num_ports >= MAX_PORTS)
1519			fatal("%s line %d: too many ports.",
1520			    filename, linenum);
1521		arg = argv_next(&ac, &av);
1522		if (!arg || *arg == '\0')
1523			fatal("%s line %d: missing port number.",
1524			    filename, linenum);
1525		options->ports[options->num_ports++] = a2port(arg);
1526		if (options->ports[options->num_ports-1] <= 0)
1527			fatal("%s line %d: Badly formatted port number.",
1528			    filename, linenum);
1529		break;
1530
1531	case sLoginGraceTime:
1532		intptr = &options->login_grace_time;
1533 parse_time:
1534		arg = argv_next(&ac, &av);
1535		if (!arg || *arg == '\0')
1536			fatal("%s line %d: missing time value.",
1537			    filename, linenum);
1538		if ((value = convtime(arg)) == -1)
1539			fatal("%s line %d: invalid time value.",
1540			    filename, linenum);
1541		if (*activep && *intptr == -1)
1542			*intptr = value;
1543		break;
1544
1545	case sListenAddress:
1546		arg = argv_next(&ac, &av);
1547		if (arg == NULL || *arg == '\0')
1548			fatal("%s line %d: missing address",
1549			    filename, linenum);
1550		/* check for bare IPv6 address: no "[]" and 2 or more ":" */
1551		if (strchr(arg, '[') == NULL && (p = strchr(arg, ':')) != NULL
1552		    && strchr(p+1, ':') != NULL) {
1553			port = 0;
1554			p = arg;
1555		} else {
1556			arg2 = NULL;
1557			p = hpdelim(&arg);
1558			if (p == NULL)
1559				fatal("%s line %d: bad address:port usage",
1560				    filename, linenum);
1561			p = cleanhostname(p);
1562			if (arg == NULL)
1563				port = 0;
1564			else if ((port = a2port(arg)) <= 0)
1565				fatal("%s line %d: bad port number",
1566				    filename, linenum);
1567		}
1568		/* Optional routing table */
1569		arg2 = NULL;
1570		if ((arg = argv_next(&ac, &av)) != NULL) {
1571			if (strcmp(arg, "rdomain") != 0 ||
1572			    (arg2 = argv_next(&ac, &av)) == NULL)
1573				fatal("%s line %d: bad ListenAddress syntax",
1574				    filename, linenum);
1575			if (!valid_rdomain(arg2))
1576				fatal("%s line %d: bad routing domain",
1577				    filename, linenum);
1578		}
1579		queue_listen_addr(options, p, arg2, port);
1580
1581		break;
1582
1583	case sAddressFamily:
1584		intptr = &options->address_family;
1585		multistate_ptr = multistate_addressfamily;
1586 parse_multistate:
1587		arg = argv_next(&ac, &av);
1588		if (!arg || *arg == '\0')
1589			fatal("%s line %d: missing argument.",
1590			    filename, linenum);
1591		value = -1;
1592		for (i = 0; multistate_ptr[i].key != NULL; i++) {
1593			if (strcasecmp(arg, multistate_ptr[i].key) == 0) {
1594				value = multistate_ptr[i].value;
1595				break;
1596			}
1597		}
1598		if (value == -1)
1599			fatal("%s line %d: unsupported option \"%s\".",
1600			    filename, linenum, arg);
1601		if (*activep && *intptr == -1)
1602			*intptr = value;
1603		break;
1604
1605	case sHostKeyFile:
1606		arg = argv_next(&ac, &av);
1607		if (!arg || *arg == '\0')
1608			fatal("%s line %d: missing file name.",
1609			    filename, linenum);
1610		if (*activep) {
1611			servconf_add_hostkey(filename, linenum,
1612			    options, arg, 1);
1613		}
1614		break;
1615
1616	case sHostKeyAgent:
1617		charptr = &options->host_key_agent;
1618		arg = argv_next(&ac, &av);
1619		if (!arg || *arg == '\0')
1620			fatal("%s line %d: missing socket name.",
1621			    filename, linenum);
1622		if (*activep && *charptr == NULL)
1623			*charptr = !strcmp(arg, SSH_AUTHSOCKET_ENV_NAME) ?
1624			    xstrdup(arg) : derelativise_path(arg);
1625		break;
1626
1627	case sHostCertificate:
1628		arg = argv_next(&ac, &av);
1629		if (!arg || *arg == '\0')
1630			fatal("%s line %d: missing file name.",
1631			    filename, linenum);
1632		if (*activep)
1633			servconf_add_hostcert(filename, linenum, options, arg);
1634		break;
1635
1636	case sPidFile:
1637		charptr = &options->pid_file;
1638 parse_filename:
1639		arg = argv_next(&ac, &av);
1640		if (!arg || *arg == '\0')
1641			fatal("%s line %d: missing file name.",
1642			    filename, linenum);
1643		if (*activep && *charptr == NULL) {
1644			*charptr = derelativise_path(arg);
1645			/* increase optional counter */
1646			if (intptr != NULL)
1647				*intptr = *intptr + 1;
1648		}
1649		break;
1650
1651	case sModuliFile:
1652		charptr = &options->moduli_file;
1653		goto parse_filename;
1654
1655	case sPermitRootLogin:
1656		intptr = &options->permit_root_login;
1657		multistate_ptr = multistate_permitrootlogin;
1658		goto parse_multistate;
1659
1660	case sIgnoreRhosts:
1661		intptr = &options->ignore_rhosts;
1662		multistate_ptr = multistate_ignore_rhosts;
1663		goto parse_multistate;
1664
1665	case sIgnoreRootRhosts:
1666		intptr = &options->ignore_root_rhosts;
1667		goto parse_flag;
1668
1669	case sNoneEnabled:
1670		intptr = &options->none_enabled;
1671		goto parse_flag;
1672
1673	case sTcpRcvBufPoll:
1674		intptr = &options->tcp_rcv_buf_poll;
1675		goto parse_flag;
1676
1677	case sHPNDisabled:
1678		intptr = &options->hpn_disabled;
1679		goto parse_flag;
1680
1681	case sHPNBufferSize:
1682		intptr = &options->hpn_buffer_size;
1683		goto parse_int;
1684
1685	case sIgnoreUserKnownHosts:
1686		intptr = &options->ignore_user_known_hosts;
1687 parse_flag:
1688		multistate_ptr = multistate_flag;
1689		goto parse_multistate;
1690
1691	case sHostbasedAuthentication:
1692		intptr = &options->hostbased_authentication;
1693		goto parse_flag;
1694
1695	case sHostbasedUsesNameFromPacketOnly:
1696		intptr = &options->hostbased_uses_name_from_packet_only;
1697		goto parse_flag;
1698
1699	case sHostbasedAcceptedAlgorithms:
1700		charptr = &options->hostbased_accepted_algos;
1701		ca_only = 0;
1702 parse_pubkey_algos:
1703		arg = argv_next(&ac, &av);
1704		if (!arg || *arg == '\0')
1705			fatal("%s line %d: Missing argument.",
1706			    filename, linenum);
1707		if (*arg != '-' &&
1708		    !sshkey_names_valid2(*arg == '+' || *arg == '^' ?
1709		    arg + 1 : arg, 1, ca_only))
1710			fatal("%s line %d: Bad key types '%s'.",
1711			    filename, linenum, arg ? arg : "<NONE>");
1712		if (*activep && *charptr == NULL)
1713			*charptr = xstrdup(arg);
1714		break;
1715
1716	case sHostKeyAlgorithms:
1717		charptr = &options->hostkeyalgorithms;
1718		ca_only = 0;
1719		goto parse_pubkey_algos;
1720
1721	case sCASignatureAlgorithms:
1722		charptr = &options->ca_sign_algorithms;
1723		ca_only = 1;
1724		goto parse_pubkey_algos;
1725
1726	case sPubkeyAuthentication:
1727		intptr = &options->pubkey_authentication;
1728		ca_only = 0;
1729		goto parse_flag;
1730
1731	case sPubkeyAcceptedAlgorithms:
1732		charptr = &options->pubkey_accepted_algos;
1733		ca_only = 0;
1734		goto parse_pubkey_algos;
1735
1736	case sPubkeyAuthOptions:
1737		intptr = &options->pubkey_auth_options;
1738		value = 0;
1739		while ((arg = argv_next(&ac, &av)) != NULL) {
1740			if (strcasecmp(arg, "none") == 0)
1741				continue;
1742			if (strcasecmp(arg, "touch-required") == 0)
1743				value |= PUBKEYAUTH_TOUCH_REQUIRED;
1744			else if (strcasecmp(arg, "verify-required") == 0)
1745				value |= PUBKEYAUTH_VERIFY_REQUIRED;
1746			else {
1747				error("%s line %d: unsupported %s option %s",
1748				    filename, linenum, keyword, arg);
1749				goto out;
1750			}
1751		}
1752		if (*activep && *intptr == -1)
1753			*intptr = value;
1754		break;
1755
1756	case sKerberosAuthentication:
1757		intptr = &options->kerberos_authentication;
1758		goto parse_flag;
1759
1760	case sKerberosOrLocalPasswd:
1761		intptr = &options->kerberos_or_local_passwd;
1762		goto parse_flag;
1763
1764	case sKerberosTicketCleanup:
1765		intptr = &options->kerberos_ticket_cleanup;
1766		goto parse_flag;
1767
1768	case sKerberosTgtPassing:
1769		intptr = &options->kerberos_tgt_passing;
1770		goto parse_flag;
1771
1772	case sKerberosGetAFSToken:
1773		intptr = &options->kerberos_get_afs_token;
1774		goto parse_flag;
1775
1776	case sGssAuthentication:
1777		intptr = &options->gss_authentication;
1778		goto parse_flag;
1779
1780	case sGssCleanupCreds:
1781		intptr = &options->gss_cleanup_creds;
1782		goto parse_flag;
1783
1784	case sGssStrictAcceptor:
1785		intptr = &options->gss_strict_acceptor;
1786		goto parse_flag;
1787
1788	case sPasswordAuthentication:
1789		intptr = &options->password_authentication;
1790		goto parse_flag;
1791
1792	case sKbdInteractiveAuthentication:
1793		intptr = &options->kbd_interactive_authentication;
1794		goto parse_flag;
1795
1796	case sPrintMotd:
1797		intptr = &options->print_motd;
1798		goto parse_flag;
1799
1800	case sPrintLastLog:
1801		intptr = &options->print_lastlog;
1802		goto parse_flag;
1803
1804	case sX11Forwarding:
1805		intptr = &options->x11_forwarding;
1806		goto parse_flag;
1807
1808	case sX11DisplayOffset:
1809		intptr = &options->x11_display_offset;
1810 parse_int:
1811		arg = argv_next(&ac, &av);
1812		if ((errstr = atoi_err(arg, &value)) != NULL)
1813			fatal("%s line %d: %s integer value %s.",
1814			    filename, linenum, keyword, errstr);
1815		if (*activep && *intptr == -1)
1816			*intptr = value;
1817		break;
1818
1819	case sX11UseLocalhost:
1820		intptr = &options->x11_use_localhost;
1821		goto parse_flag;
1822
1823	case sXAuthLocation:
1824		charptr = &options->xauth_location;
1825		goto parse_filename;
1826
1827	case sPermitTTY:
1828		intptr = &options->permit_tty;
1829		goto parse_flag;
1830
1831	case sPermitUserRC:
1832		intptr = &options->permit_user_rc;
1833		goto parse_flag;
1834
1835	case sStrictModes:
1836		intptr = &options->strict_modes;
1837		goto parse_flag;
1838
1839	case sTCPKeepAlive:
1840		intptr = &options->tcp_keep_alive;
1841		goto parse_flag;
1842
1843	case sEmptyPasswd:
1844		intptr = &options->permit_empty_passwd;
1845		goto parse_flag;
1846
1847	case sPermitUserEnvironment:
1848		intptr = &options->permit_user_env;
1849		charptr = &options->permit_user_env_allowlist;
1850		arg = argv_next(&ac, &av);
1851		if (!arg || *arg == '\0')
1852			fatal("%s line %d: %s missing argument.",
1853			    filename, linenum, keyword);
1854		value = 0;
1855		p = NULL;
1856		if (strcmp(arg, "yes") == 0)
1857			value = 1;
1858		else if (strcmp(arg, "no") == 0)
1859			value = 0;
1860		else {
1861			/* Pattern-list specified */
1862			value = 1;
1863			p = xstrdup(arg);
1864		}
1865		if (*activep && *intptr == -1) {
1866			*intptr = value;
1867			*charptr = p;
1868			p = NULL;
1869		}
1870		free(p);
1871		break;
1872
1873	case sCompression:
1874		intptr = &options->compression;
1875		multistate_ptr = multistate_compression;
1876		goto parse_multistate;
1877
1878	case sRekeyLimit:
1879		arg = argv_next(&ac, &av);
1880		if (!arg || *arg == '\0')
1881			fatal("%s line %d: %s missing argument.",
1882			    filename, linenum, keyword);
1883		if (strcmp(arg, "default") == 0) {
1884			val64 = 0;
1885		} else {
1886			if (scan_scaled(arg, &val64) == -1)
1887				fatal("%.200s line %d: Bad %s number '%s': %s",
1888				    filename, linenum, keyword,
1889				    arg, strerror(errno));
1890			if (val64 != 0 && val64 < 16)
1891				fatal("%.200s line %d: %s too small",
1892				    filename, linenum, keyword);
1893		}
1894		if (*activep && options->rekey_limit == -1)
1895			options->rekey_limit = val64;
1896		if (ac != 0) { /* optional rekey interval present */
1897			if (strcmp(av[0], "none") == 0) {
1898				(void)argv_next(&ac, &av);	/* discard */
1899				break;
1900			}
1901			intptr = &options->rekey_interval;
1902			goto parse_time;
1903		}
1904		break;
1905
1906	case sGatewayPorts:
1907		intptr = &options->fwd_opts.gateway_ports;
1908		multistate_ptr = multistate_gatewayports;
1909		goto parse_multistate;
1910
1911	case sUseDNS:
1912		intptr = &options->use_dns;
1913		goto parse_flag;
1914
1915	case sLogFacility:
1916		log_facility_ptr = &options->log_facility;
1917		arg = argv_next(&ac, &av);
1918		value = log_facility_number(arg);
1919		if (value == SYSLOG_FACILITY_NOT_SET)
1920			fatal("%.200s line %d: unsupported log facility '%s'",
1921			    filename, linenum, arg ? arg : "<NONE>");
1922		if (*log_facility_ptr == -1)
1923			*log_facility_ptr = (SyslogFacility) value;
1924		break;
1925
1926	case sLogLevel:
1927		log_level_ptr = &options->log_level;
1928		arg = argv_next(&ac, &av);
1929		value = log_level_number(arg);
1930		if (value == SYSLOG_LEVEL_NOT_SET)
1931			fatal("%.200s line %d: unsupported log level '%s'",
1932			    filename, linenum, arg ? arg : "<NONE>");
1933		if (*activep && *log_level_ptr == -1)
1934			*log_level_ptr = (LogLevel) value;
1935		break;
1936
1937	case sLogVerbose:
1938		found = options->num_log_verbose == 0;
1939		i = 0;
1940		while ((arg = argv_next(&ac, &av)) != NULL) {
1941			if (*arg == '\0') {
1942				error("%s line %d: keyword %s empty argument",
1943				    filename, linenum, keyword);
1944				goto out;
1945			}
1946			/* Allow "none" only in first position */
1947			if (strcasecmp(arg, "none") == 0) {
1948				if (i > 0 || ac > 0) {
1949					error("%s line %d: keyword %s \"none\" "
1950					    "argument must appear alone.",
1951					    filename, linenum, keyword);
1952					goto out;
1953				}
1954			}
1955			i++;
1956			if (!found || !*activep)
1957				continue;
1958			opt_array_append(filename, linenum, keyword,
1959			    &options->log_verbose, &options->num_log_verbose,
1960			    arg);
1961		}
1962		break;
1963
1964	case sAllowTcpForwarding:
1965		intptr = &options->allow_tcp_forwarding;
1966		multistate_ptr = multistate_tcpfwd;
1967		goto parse_multistate;
1968
1969	case sAllowStreamLocalForwarding:
1970		intptr = &options->allow_streamlocal_forwarding;
1971		multistate_ptr = multistate_tcpfwd;
1972		goto parse_multistate;
1973
1974	case sAllowAgentForwarding:
1975		intptr = &options->allow_agent_forwarding;
1976		goto parse_flag;
1977
1978	case sDisableForwarding:
1979		intptr = &options->disable_forwarding;
1980		goto parse_flag;
1981
1982	case sAllowUsers:
1983		chararrayptr = &options->allow_users;
1984		uintptr = &options->num_allow_users;
1985 parse_allowdenyusers:
1986		while ((arg = argv_next(&ac, &av)) != NULL) {
1987			if (*arg == '\0' ||
1988			    match_user(NULL, NULL, NULL, arg) == -1)
1989				fatal("%s line %d: invalid %s pattern: \"%s\"",
1990				    filename, linenum, keyword, arg);
1991			if (!*activep)
1992				continue;
1993			opt_array_append(filename, linenum, keyword,
1994			    chararrayptr, uintptr, arg);
1995		}
1996		break;
1997
1998	case sDenyUsers:
1999		chararrayptr = &options->deny_users;
2000		uintptr = &options->num_deny_users;
2001		goto parse_allowdenyusers;
2002
2003	case sAllowGroups:
2004		chararrayptr = &options->allow_groups;
2005		uintptr = &options->num_allow_groups;
2006 parse_allowdenygroups:
2007		while ((arg = argv_next(&ac, &av)) != NULL) {
2008			if (*arg == '\0')
2009				fatal("%s line %d: empty %s pattern",
2010				    filename, linenum, keyword);
2011			if (!*activep)
2012				continue;
2013			opt_array_append(filename, linenum, keyword,
2014			    chararrayptr, uintptr, arg);
2015		}
2016		break;
2017
2018	case sDenyGroups:
2019		chararrayptr = &options->deny_groups;
2020		uintptr = &options->num_deny_groups;
2021		goto parse_allowdenygroups;
2022
2023	case sCiphers:
2024		arg = argv_next(&ac, &av);
2025		if (!arg || *arg == '\0')
2026			fatal("%s line %d: %s missing argument.",
2027			    filename, linenum, keyword);
2028		if (*arg != '-' &&
2029		    !ciphers_valid(*arg == '+' || *arg == '^' ? arg + 1 : arg))
2030			fatal("%s line %d: Bad SSH2 cipher spec '%s'.",
2031			    filename, linenum, arg ? arg : "<NONE>");
2032		if (options->ciphers == NULL)
2033			options->ciphers = xstrdup(arg);
2034		break;
2035
2036	case sMacs:
2037		arg = argv_next(&ac, &av);
2038		if (!arg || *arg == '\0')
2039			fatal("%s line %d: %s missing argument.",
2040			    filename, linenum, keyword);
2041		if (*arg != '-' &&
2042		    !mac_valid(*arg == '+' || *arg == '^' ? arg + 1 : arg))
2043			fatal("%s line %d: Bad SSH2 mac spec '%s'.",
2044			    filename, linenum, arg ? arg : "<NONE>");
2045		if (options->macs == NULL)
2046			options->macs = xstrdup(arg);
2047		break;
2048
2049	case sKexAlgorithms:
2050		arg = argv_next(&ac, &av);
2051		if (!arg || *arg == '\0')
2052			fatal("%s line %d: %s missing argument.",
2053			    filename, linenum, keyword);
2054		if (*arg != '-' &&
2055		    !kex_names_valid(*arg == '+' || *arg == '^' ?
2056		    arg + 1 : arg))
2057			fatal("%s line %d: Bad SSH2 KexAlgorithms '%s'.",
2058			    filename, linenum, arg ? arg : "<NONE>");
2059		if (options->kex_algorithms == NULL)
2060			options->kex_algorithms = xstrdup(arg);
2061		break;
2062
2063	case sSubsystem:
2064		arg = argv_next(&ac, &av);
2065		if (!arg || *arg == '\0')
2066			fatal("%s line %d: %s missing argument.",
2067			    filename, linenum, keyword);
2068		if (!*activep) {
2069			argv_consume(&ac);
2070			break;
2071		}
2072		found = 0;
2073		for (i = 0; i < options->num_subsystems; i++) {
2074			if (strcmp(arg, options->subsystem_name[i]) == 0) {
2075				found = 1;
2076				break;
2077			}
2078		}
2079		if (found) {
2080			debug("%s line %d: Subsystem '%s' already defined.",
2081			    filename, linenum, arg);
2082			argv_consume(&ac);
2083			break;
2084		}
2085		options->subsystem_name = xrecallocarray(
2086		    options->subsystem_name, options->num_subsystems,
2087		    options->num_subsystems + 1,
2088		    sizeof(*options->subsystem_name));
2089		options->subsystem_command = xrecallocarray(
2090		    options->subsystem_command, options->num_subsystems,
2091		    options->num_subsystems + 1,
2092		    sizeof(*options->subsystem_command));
2093		options->subsystem_args = xrecallocarray(
2094		    options->subsystem_args, options->num_subsystems,
2095		    options->num_subsystems + 1,
2096		    sizeof(*options->subsystem_args));
2097		options->subsystem_name[options->num_subsystems] = xstrdup(arg);
2098		arg = argv_next(&ac, &av);
2099		if (!arg || *arg == '\0') {
2100			fatal("%s line %d: Missing subsystem command.",
2101			    filename, linenum);
2102		}
2103		options->subsystem_command[options->num_subsystems] =
2104		    xstrdup(arg);
2105		/* Collect arguments (separate to executable) */
2106		arg = argv_assemble(1, &arg); /* quote command correctly */
2107		arg2 = argv_assemble(ac, av); /* rest of command */
2108		xasprintf(&options->subsystem_args[options->num_subsystems],
2109		    "%s %s", arg, arg2);
2110		free(arg2);
2111		argv_consume(&ac);
2112		options->num_subsystems++;
2113		break;
2114
2115	case sMaxStartups:
2116		arg = argv_next(&ac, &av);
2117		if (!arg || *arg == '\0')
2118			fatal("%s line %d: %s missing argument.",
2119			    filename, linenum, keyword);
2120		if ((n = sscanf(arg, "%d:%d:%d",
2121		    &options->max_startups_begin,
2122		    &options->max_startups_rate,
2123		    &options->max_startups)) == 3) {
2124			if (options->max_startups_begin >
2125			    options->max_startups ||
2126			    options->max_startups_rate > 100 ||
2127			    options->max_startups_rate < 1)
2128				fatal("%s line %d: Invalid %s spec.",
2129				    filename, linenum, keyword);
2130		} else if (n != 1)
2131			fatal("%s line %d: Invalid %s spec.",
2132			    filename, linenum, keyword);
2133		else
2134			options->max_startups = options->max_startups_begin;
2135		if (options->max_startups <= 0 ||
2136		    options->max_startups_begin <= 0)
2137			fatal("%s line %d: Invalid %s spec.",
2138			    filename, linenum, keyword);
2139		break;
2140
2141	case sPerSourceNetBlockSize:
2142		arg = argv_next(&ac, &av);
2143		if (!arg || *arg == '\0')
2144			fatal("%s line %d: %s missing argument.",
2145			    filename, linenum, keyword);
2146		switch (n = sscanf(arg, "%d:%d", &value, &value2)) {
2147		case 2:
2148			if (value2 < 0 || value2 > 128)
2149				n = -1;
2150			/* FALLTHROUGH */
2151		case 1:
2152			if (value < 0 || value > 32)
2153				n = -1;
2154		}
2155		if (n != 1 && n != 2)
2156			fatal("%s line %d: Invalid %s spec.",
2157			    filename, linenum, keyword);
2158		if (*activep) {
2159			options->per_source_masklen_ipv4 = value;
2160			options->per_source_masklen_ipv6 = value2;
2161		}
2162		break;
2163
2164	case sPerSourceMaxStartups:
2165		arg = argv_next(&ac, &av);
2166		if (!arg || *arg == '\0')
2167			fatal("%s line %d: %s missing argument.",
2168			    filename, linenum, keyword);
2169		if (strcmp(arg, "none") == 0) { /* no limit */
2170			value = INT_MAX;
2171		} else {
2172			if ((errstr = atoi_err(arg, &value)) != NULL)
2173				fatal("%s line %d: %s integer value %s.",
2174				    filename, linenum, keyword, errstr);
2175		}
2176		if (*activep && options->per_source_max_startups == -1)
2177			options->per_source_max_startups = value;
2178		break;
2179
2180	case sMaxAuthTries:
2181		intptr = &options->max_authtries;
2182		goto parse_int;
2183
2184	case sMaxSessions:
2185		intptr = &options->max_sessions;
2186		goto parse_int;
2187
2188	case sBanner:
2189		charptr = &options->banner;
2190		goto parse_filename;
2191
2192	/*
2193	 * These options can contain %X options expanded at
2194	 * connect time, so that you can specify paths like:
2195	 *
2196	 * AuthorizedKeysFile	/etc/ssh_keys/%u
2197	 */
2198	case sAuthorizedKeysFile:
2199		uvalue = options->num_authkeys_files;
2200		while ((arg = argv_next(&ac, &av)) != NULL) {
2201			if (*arg == '\0') {
2202				error("%s line %d: keyword %s empty argument",
2203				    filename, linenum, keyword);
2204				goto out;
2205			}
2206			arg2 = tilde_expand_filename(arg, getuid());
2207			if (*activep && uvalue == 0) {
2208				opt_array_append(filename, linenum, keyword,
2209				    &options->authorized_keys_files,
2210				    &options->num_authkeys_files, arg2);
2211			}
2212			free(arg2);
2213		}
2214		break;
2215
2216	case sAuthorizedPrincipalsFile:
2217		charptr = &options->authorized_principals_file;
2218		arg = argv_next(&ac, &av);
2219		if (!arg || *arg == '\0')
2220			fatal("%s line %d: %s missing argument.",
2221			    filename, linenum, keyword);
2222		if (*activep && *charptr == NULL) {
2223			*charptr = tilde_expand_filename(arg, getuid());
2224			/* increase optional counter */
2225			if (intptr != NULL)
2226				*intptr = *intptr + 1;
2227		}
2228		break;
2229
2230	case sClientAliveInterval:
2231		intptr = &options->client_alive_interval;
2232		goto parse_time;
2233
2234	case sClientAliveCountMax:
2235		intptr = &options->client_alive_count_max;
2236		goto parse_int;
2237
2238	case sAcceptEnv:
2239		while ((arg = argv_next(&ac, &av)) != NULL) {
2240			if (*arg == '\0' || strchr(arg, '=') != NULL)
2241				fatal("%s line %d: Invalid environment name.",
2242				    filename, linenum);
2243			if (!*activep)
2244				continue;
2245			opt_array_append(filename, linenum, keyword,
2246			    &options->accept_env, &options->num_accept_env,
2247			    arg);
2248		}
2249		break;
2250
2251	case sSetEnv:
2252		uvalue = options->num_setenv;
2253		while ((arg = argv_next(&ac, &av)) != NULL) {
2254			if (*arg == '\0' || strchr(arg, '=') == NULL)
2255				fatal("%s line %d: Invalid environment.",
2256				    filename, linenum);
2257			if (!*activep || uvalue != 0)
2258				continue;
2259			if (lookup_setenv_in_list(arg, options->setenv,
2260			    options->num_setenv) != NULL) {
2261				debug2("%s line %d: ignoring duplicate env "
2262				    "name \"%.64s\"", filename, linenum, arg);
2263				continue;
2264			}
2265			opt_array_append(filename, linenum, keyword,
2266			    &options->setenv, &options->num_setenv, arg);
2267		}
2268		break;
2269
2270	case sPermitTunnel:
2271		intptr = &options->permit_tun;
2272		arg = argv_next(&ac, &av);
2273		if (!arg || *arg == '\0')
2274			fatal("%s line %d: %s missing argument.",
2275			    filename, linenum, keyword);
2276		value = -1;
2277		for (i = 0; tunmode_desc[i].val != -1; i++)
2278			if (strcmp(tunmode_desc[i].text, arg) == 0) {
2279				value = tunmode_desc[i].val;
2280				break;
2281			}
2282		if (value == -1)
2283			fatal("%s line %d: bad %s argument %s",
2284			    filename, linenum, keyword, arg);
2285		if (*activep && *intptr == -1)
2286			*intptr = value;
2287		break;
2288
2289	case sInclude:
2290		if (cmdline) {
2291			fatal("Include directive not supported as a "
2292			    "command-line option");
2293		}
2294		value = 0;
2295		while ((arg2 = argv_next(&ac, &av)) != NULL) {
2296			if (*arg2 == '\0') {
2297				error("%s line %d: keyword %s empty argument",
2298				    filename, linenum, keyword);
2299				goto out;
2300			}
2301			value++;
2302			found = 0;
2303			if (*arg2 != '/' && *arg2 != '~') {
2304				xasprintf(&arg, "%s/%s", SSHDIR, arg2);
2305			} else
2306				arg = xstrdup(arg2);
2307
2308			/*
2309			 * Don't let included files clobber the containing
2310			 * file's Match state.
2311			 */
2312			oactive = *activep;
2313
2314			/* consult cache of include files */
2315			TAILQ_FOREACH(item, includes, entry) {
2316				if (strcmp(item->selector, arg) != 0)
2317					continue;
2318				if (item->filename != NULL) {
2319					parse_server_config_depth(options,
2320					    item->filename, item->contents,
2321					    includes, connectinfo,
2322					    (*inc_flags & SSHCFG_MATCH_ONLY
2323					        ? SSHCFG_MATCH_ONLY : (oactive
2324					            ? 0 : SSHCFG_NEVERMATCH)),
2325					    activep, depth + 1);
2326				}
2327				found = 1;
2328				*activep = oactive;
2329			}
2330			if (found != 0) {
2331				free(arg);
2332				continue;
2333			}
2334
2335			/* requested glob was not in cache */
2336			debug2("%s line %d: new include %s",
2337			    filename, linenum, arg);
2338			if ((r = glob(arg, 0, NULL, &gbuf)) != 0) {
2339				if (r != GLOB_NOMATCH) {
2340					fatal("%s line %d: include \"%s\" glob "
2341					    "failed", filename, linenum, arg);
2342				}
2343				/*
2344				 * If no entry matched then record a
2345				 * placeholder to skip later glob calls.
2346				 */
2347				debug2("%s line %d: no match for %s",
2348				    filename, linenum, arg);
2349				item = xcalloc(1, sizeof(*item));
2350				item->selector = strdup(arg);
2351				TAILQ_INSERT_TAIL(includes,
2352				    item, entry);
2353			}
2354			if (gbuf.gl_pathc > INT_MAX)
2355				fatal_f("too many glob results");
2356			for (n = 0; n < (int)gbuf.gl_pathc; n++) {
2357				debug2("%s line %d: including %s",
2358				    filename, linenum, gbuf.gl_pathv[n]);
2359				item = xcalloc(1, sizeof(*item));
2360				item->selector = strdup(arg);
2361				item->filename = strdup(gbuf.gl_pathv[n]);
2362				if ((item->contents = sshbuf_new()) == NULL)
2363					fatal_f("sshbuf_new failed");
2364				load_server_config(item->filename,
2365				    item->contents);
2366				parse_server_config_depth(options,
2367				    item->filename, item->contents,
2368				    includes, connectinfo,
2369				    (*inc_flags & SSHCFG_MATCH_ONLY
2370				        ? SSHCFG_MATCH_ONLY : (oactive
2371				            ? 0 : SSHCFG_NEVERMATCH)),
2372				    activep, depth + 1);
2373				*activep = oactive;
2374				TAILQ_INSERT_TAIL(includes, item, entry);
2375			}
2376			globfree(&gbuf);
2377			free(arg);
2378		}
2379		if (value == 0) {
2380			fatal("%s line %d: %s missing filename argument",
2381			    filename, linenum, keyword);
2382		}
2383		break;
2384
2385	case sMatch:
2386		if (cmdline)
2387			fatal("Match directive not supported as a command-line "
2388			    "option");
2389		value = match_cfg_line(&str, linenum,
2390		    (*inc_flags & SSHCFG_NEVERMATCH ? NULL : connectinfo));
2391		if (value < 0)
2392			fatal("%s line %d: Bad Match condition", filename,
2393			    linenum);
2394		*activep = (*inc_flags & SSHCFG_NEVERMATCH) ? 0 : value;
2395		/*
2396		 * The MATCH_ONLY flag is applicable only until the first
2397		 * match block.
2398		 */
2399		*inc_flags &= ~SSHCFG_MATCH_ONLY;
2400		/*
2401		 * If match_cfg_line() didn't consume all its arguments then
2402		 * arrange for the extra arguments check below to fail.
2403		 */
2404		if (str == NULL || *str == '\0')
2405			argv_consume(&ac);
2406		break;
2407
2408	case sPermitListen:
2409	case sPermitOpen:
2410		if (opcode == sPermitListen) {
2411			uintptr = &options->num_permitted_listens;
2412			chararrayptr = &options->permitted_listens;
2413		} else {
2414			uintptr = &options->num_permitted_opens;
2415			chararrayptr = &options->permitted_opens;
2416		}
2417		arg = argv_next(&ac, &av);
2418		if (!arg || *arg == '\0')
2419			fatal("%s line %d: %s missing argument.",
2420			    filename, linenum, keyword);
2421		uvalue = *uintptr;	/* modified later */
2422		if (strcmp(arg, "any") == 0 || strcmp(arg, "none") == 0) {
2423			if (*activep && uvalue == 0) {
2424				*uintptr = 1;
2425				*chararrayptr = xcalloc(1,
2426				    sizeof(**chararrayptr));
2427				(*chararrayptr)[0] = xstrdup(arg);
2428			}
2429			break;
2430		}
2431		for (; arg != NULL && *arg != '\0'; arg = argv_next(&ac, &av)) {
2432			if (opcode == sPermitListen &&
2433			    strchr(arg, ':') == NULL) {
2434				/*
2435				 * Allow bare port number for PermitListen
2436				 * to indicate a wildcard listen host.
2437				 */
2438				xasprintf(&arg2, "*:%s", arg);
2439			} else {
2440				arg2 = xstrdup(arg);
2441				p = hpdelim(&arg);
2442				if (p == NULL) {
2443					fatal("%s line %d: %s missing host",
2444					    filename, linenum, keyword);
2445				}
2446				p = cleanhostname(p);
2447			}
2448			if (arg == NULL ||
2449			    ((port = permitopen_port(arg)) < 0)) {
2450				fatal("%s line %d: %s bad port number",
2451				    filename, linenum, keyword);
2452			}
2453			if (*activep && uvalue == 0) {
2454				opt_array_append(filename, linenum, keyword,
2455				    chararrayptr, uintptr, arg2);
2456			}
2457			free(arg2);
2458		}
2459		break;
2460
2461	case sForceCommand:
2462		if (str == NULL || *str == '\0')
2463			fatal("%s line %d: %s missing argument.",
2464			    filename, linenum, keyword);
2465		len = strspn(str, WHITESPACE);
2466		if (*activep && options->adm_forced_command == NULL)
2467			options->adm_forced_command = xstrdup(str + len);
2468		argv_consume(&ac);
2469		break;
2470
2471	case sChrootDirectory:
2472		charptr = &options->chroot_directory;
2473
2474		arg = argv_next(&ac, &av);
2475		if (!arg || *arg == '\0')
2476			fatal("%s line %d: %s missing argument.",
2477			    filename, linenum, keyword);
2478		if (*activep && *charptr == NULL)
2479			*charptr = xstrdup(arg);
2480		break;
2481
2482	case sTrustedUserCAKeys:
2483		charptr = &options->trusted_user_ca_keys;
2484		goto parse_filename;
2485
2486	case sRevokedKeys:
2487		charptr = &options->revoked_keys_file;
2488		goto parse_filename;
2489
2490	case sSecurityKeyProvider:
2491		charptr = &options->sk_provider;
2492		arg = argv_next(&ac, &av);
2493		if (!arg || *arg == '\0')
2494			fatal("%s line %d: %s missing argument.",
2495			    filename, linenum, keyword);
2496		if (*activep && *charptr == NULL) {
2497			*charptr = strcasecmp(arg, "internal") == 0 ?
2498			    xstrdup(arg) : derelativise_path(arg);
2499			/* increase optional counter */
2500			if (intptr != NULL)
2501				*intptr = *intptr + 1;
2502		}
2503		break;
2504
2505	case sIPQoS:
2506		arg = argv_next(&ac, &av);
2507		if (!arg || *arg == '\0')
2508			fatal("%s line %d: %s missing argument.",
2509			    filename, linenum, keyword);
2510		if ((value = parse_ipqos(arg)) == -1)
2511			fatal("%s line %d: Bad %s value: %s",
2512			    filename, linenum, keyword, arg);
2513		arg = argv_next(&ac, &av);
2514		if (arg == NULL)
2515			value2 = value;
2516		else if ((value2 = parse_ipqos(arg)) == -1)
2517			fatal("%s line %d: Bad %s value: %s",
2518			    filename, linenum, keyword, arg);
2519		if (*activep) {
2520			options->ip_qos_interactive = value;
2521			options->ip_qos_bulk = value2;
2522		}
2523		break;
2524
2525	case sVersionAddendum:
2526		if (str == NULL || *str == '\0')
2527			fatal("%s line %d: %s missing argument.",
2528			    filename, linenum, keyword);
2529		len = strspn(str, WHITESPACE);
2530		if (strchr(str + len, '\r') != NULL) {
2531			fatal("%.200s line %d: Invalid %s argument",
2532			    filename, linenum, keyword);
2533		}
2534		if ((arg = strchr(line, '#')) != NULL) {
2535			*arg = '\0';
2536			rtrim(line);
2537		}
2538		if (*activep && options->version_addendum == NULL) {
2539			if (strcasecmp(str + len, "none") == 0)
2540				options->version_addendum = xstrdup("");
2541			else
2542				options->version_addendum = xstrdup(str + len);
2543		}
2544		argv_consume(&ac);
2545		break;
2546
2547	case sAuthorizedKeysCommand:
2548		charptr = &options->authorized_keys_command;
2549 parse_command:
2550		len = strspn(str, WHITESPACE);
2551		if (str[len] != '/' && strcasecmp(str + len, "none") != 0) {
2552			fatal("%.200s line %d: %s must be an absolute path",
2553			    filename, linenum, keyword);
2554		}
2555		if (*activep && *charptr == NULL)
2556			*charptr = xstrdup(str + len);
2557		argv_consume(&ac);
2558		break;
2559
2560	case sAuthorizedKeysCommandUser:
2561		charptr = &options->authorized_keys_command_user;
2562 parse_localuser:
2563		arg = argv_next(&ac, &av);
2564		if (!arg || *arg == '\0') {
2565			fatal("%s line %d: missing %s argument.",
2566			    filename, linenum, keyword);
2567		}
2568		if (*activep && *charptr == NULL)
2569			*charptr = xstrdup(arg);
2570		break;
2571
2572	case sAuthorizedPrincipalsCommand:
2573		charptr = &options->authorized_principals_command;
2574		goto parse_command;
2575
2576	case sAuthorizedPrincipalsCommandUser:
2577		charptr = &options->authorized_principals_command_user;
2578		goto parse_localuser;
2579
2580	case sAuthenticationMethods:
2581		found = options->num_auth_methods == 0;
2582		value = 0; /* seen "any" pseudo-method */
2583		value2 = 0; /* successfully parsed any method */
2584		while ((arg = argv_next(&ac, &av)) != NULL) {
2585			if (strcmp(arg, "any") == 0) {
2586				if (options->num_auth_methods > 0) {
2587					fatal("%s line %d: \"any\" must "
2588					    "appear alone in %s",
2589					    filename, linenum, keyword);
2590				}
2591				value = 1;
2592			} else if (value) {
2593				fatal("%s line %d: \"any\" must appear "
2594				    "alone in %s", filename, linenum, keyword);
2595			} else if (auth2_methods_valid(arg, 0) != 0) {
2596				fatal("%s line %d: invalid %s method list.",
2597				    filename, linenum, keyword);
2598			}
2599			value2 = 1;
2600			if (!found || !*activep)
2601				continue;
2602			opt_array_append(filename, linenum, keyword,
2603			    &options->auth_methods,
2604			    &options->num_auth_methods, arg);
2605		}
2606		if (value2 == 0) {
2607			fatal("%s line %d: no %s specified",
2608			    filename, linenum, keyword);
2609		}
2610		break;
2611
2612	case sStreamLocalBindMask:
2613		arg = argv_next(&ac, &av);
2614		if (!arg || *arg == '\0')
2615			fatal("%s line %d: %s missing argument.",
2616			    filename, linenum, keyword);
2617		/* Parse mode in octal format */
2618		value = strtol(arg, &p, 8);
2619		if (arg == p || value < 0 || value > 0777)
2620			fatal("%s line %d: Invalid %s.",
2621			    filename, linenum, keyword);
2622		if (*activep)
2623			options->fwd_opts.streamlocal_bind_mask = (mode_t)value;
2624		break;
2625
2626	case sStreamLocalBindUnlink:
2627		intptr = &options->fwd_opts.streamlocal_bind_unlink;
2628		goto parse_flag;
2629
2630	case sFingerprintHash:
2631		arg = argv_next(&ac, &av);
2632		if (!arg || *arg == '\0')
2633			fatal("%s line %d: %s missing argument.",
2634			    filename, linenum, keyword);
2635		if ((value = ssh_digest_alg_by_name(arg)) == -1)
2636			fatal("%.200s line %d: Invalid %s algorithm \"%s\".",
2637			    filename, linenum, keyword, arg);
2638		if (*activep)
2639			options->fingerprint_hash = value;
2640		break;
2641
2642	case sExposeAuthInfo:
2643		intptr = &options->expose_userauth_info;
2644		goto parse_flag;
2645
2646	case sRDomain:
2647		charptr = &options->routing_domain;
2648		arg = argv_next(&ac, &av);
2649		if (!arg || *arg == '\0')
2650			fatal("%s line %d: %s missing argument.",
2651			    filename, linenum, keyword);
2652		if (strcasecmp(arg, "none") != 0 && strcmp(arg, "%D") != 0 &&
2653		    !valid_rdomain(arg))
2654			fatal("%s line %d: invalid routing domain",
2655			    filename, linenum);
2656		if (*activep && *charptr == NULL)
2657			*charptr = xstrdup(arg);
2658		break;
2659
2660	case sRequiredRSASize:
2661		intptr = &options->required_rsa_size;
2662		goto parse_int;
2663
2664	case sChannelTimeout:
2665		uvalue = options->num_channel_timeouts;
2666		i = 0;
2667		while ((arg = argv_next(&ac, &av)) != NULL) {
2668			/* Allow "none" only in first position */
2669			if (strcasecmp(arg, "none") == 0) {
2670				if (i > 0 || ac > 0) {
2671					error("%s line %d: keyword %s \"none\" "
2672					    "argument must appear alone.",
2673					    filename, linenum, keyword);
2674					goto out;
2675				}
2676			} else if (parse_pattern_interval(arg,
2677			    NULL, NULL) != 0) {
2678				fatal("%s line %d: invalid channel timeout %s",
2679				    filename, linenum, arg);
2680			}
2681			if (!*activep || uvalue != 0)
2682				continue;
2683			opt_array_append(filename, linenum, keyword,
2684			    &options->channel_timeouts,
2685			    &options->num_channel_timeouts, arg);
2686		}
2687		break;
2688
2689	case sUnusedConnectionTimeout:
2690		intptr = &options->unused_connection_timeout;
2691		/* peek at first arg for "none" so we can reuse parse_time */
2692		if (av[0] != NULL && strcasecmp(av[0], "none") == 0) {
2693			(void)argv_next(&ac, &av); /* consume arg */
2694			if (*activep)
2695				*intptr = 0;
2696			break;
2697		}
2698		goto parse_time;
2699
2700	case sDeprecated:
2701	case sIgnore:
2702	case sUnsupported:
2703		do_log2(opcode == sIgnore ?
2704		    SYSLOG_LEVEL_DEBUG2 : SYSLOG_LEVEL_INFO,
2705		    "%s line %d: %s option %s", filename, linenum,
2706		    opcode == sUnsupported ? "Unsupported" : "Deprecated",
2707		    keyword);
2708		argv_consume(&ac);
2709		break;
2710
2711#ifdef WITH_LDAP_PUBKEY
2712	case sLdapPublickey:
2713		intptr = &options->lpk.on;
2714		goto parse_flag;
2715	case sLdapServers:
2716		/* arg = strdelim(&cp); */
2717		p = line;
2718		while(*p++);
2719		arg = p;
2720		if (!arg || *arg == '\0')
2721		    fatal("%s line %d: missing ldap server",filename,linenum);
2722		arg[strlen(arg)] = '\0';
2723		if ((options->lpk.servers = ldap_parse_servers(arg)) == NULL)
2724		    fatal("%s line %d: error in ldap servers", filename, linenum);
2725		memset(arg,0,strlen(arg));
2726		break;
2727	case sLdapUserDN:
2728		arg = argv_next(&ac, &av);
2729		if (!arg || *arg == '\0')
2730		    fatal("%s line %d: missing ldap server",filename,linenum);
2731		arg[strlen(arg)] = '\0';
2732		options->lpk.u_basedn = xstrdup(arg);
2733		memset(arg,0,strlen(arg));
2734		break;
2735	case sLdapGroupDN:
2736		arg = argv_next(&ac, &av);
2737		if (!arg || *arg == '\0')
2738		    fatal("%s line %d: missing ldap server",filename,linenum);
2739		arg[strlen(arg)] = '\0';
2740		options->lpk.g_basedn = xstrdup(arg);
2741		memset(arg,0,strlen(arg));
2742		break;
2743	case sBindDN:
2744		arg = argv_next(&ac, &av);
2745		if (!arg || *arg == '\0')
2746		    fatal("%s line %d: missing binddn",filename,linenum);
2747		arg[strlen(arg)] = '\0';
2748		options->lpk.binddn = xstrdup(arg);
2749		memset(arg,0,strlen(arg));
2750		break;
2751	case sBindPw:
2752		arg = argv_next(&ac, &av);
2753		if (!arg || *arg == '\0')
2754		    fatal("%s line %d: missing bindpw",filename,linenum);
2755		arg[strlen(arg)] = '\0';
2756		options->lpk.bindpw = xstrdup(arg);
2757		memset(arg,0,strlen(arg));
2758		break;
2759	case sMyGroup:
2760		arg = argv_next(&ac, &av);
2761		if (!arg || *arg == '\0')
2762		    fatal("%s line %d: missing groupname",filename, linenum);
2763		arg[strlen(arg)] = '\0';
2764		options->lpk.sgroup = xstrdup(arg);
2765		if (options->lpk.sgroup)
2766		    options->lpk.fgroup = ldap_parse_groups(options->lpk.sgroup);
2767		memset(arg,0,strlen(arg));
2768		break;
2769	case sLdapFilter:
2770		arg = argv_next(&ac, &av);
2771		if (!arg || *arg == '\0')
2772		    fatal("%s line %d: missing filter",filename, linenum);
2773		arg[strlen(arg)] = '\0';
2774		options->lpk.filter = xstrdup(arg);
2775		memset(arg,0,strlen(arg));
2776		break;
2777	case sForceTLS:
2778		intptr = &options->lpk.tls;
2779		arg = argv_next(&ac, &av);
2780		if (!arg || *arg == '\0')
2781			fatal("%s line %d: missing yes/no argument.",
2782			    filename, linenum);
2783		value = 0;	/* silence compiler */
2784		if (strcmp(arg, "yes") == 0)
2785			value = 1;
2786		else if (strcmp(arg, "no") == 0)
2787			value = 0;
2788		else if (strcmp(arg, "try") == 0)
2789			value = -1;
2790		else
2791			fatal("%s line %d: Bad yes/no argument: %s",
2792				filename, linenum, arg);
2793		if (*intptr == -1)
2794			*intptr = value;
2795		break;
2796	case sBindTimeout:
2797		timetptr = &options->lpk.b_timeout.tv_sec;
2798parse_ulong:
2799		arg = argv_next(&ac, &av);
2800		if (!arg || *arg == '\0')
2801			fatal("%s line %d: missing integer value.",
2802			    filename, linenum);
2803		lvalue = atol(arg);
2804		if (*activep && *timetptr == -1)
2805			*timetptr = lvalue;
2806		break;
2807
2808	case sSearchTimeout:
2809		timetptr = &options->lpk.s_timeout.tv_sec;
2810		goto parse_ulong;
2811		break;
2812	case sLdapConf:
2813		arg = argv_next(&ac, &av);
2814		if (!arg || *arg == '\0')
2815		    fatal("%s line %d: missing LpkLdapConf", filename, linenum);
2816		arg[strlen(arg)] = '\0';
2817		options->lpk.l_conf = xstrdup(arg);
2818		memset(arg, 0, strlen(arg));
2819		break;
2820	case sLpkPubKeyAttr:
2821		arg = argv_next(&ac, &av);
2822                if (!arg || *arg == '\0')
2823                    fatal("%s line %d: missing pubkeyattr",filename,linenum);
2824                arg[strlen(arg)] = '\0';
2825                options->lpk.pub_key_attr = xstrdup(arg);
2826                memset(arg,0,strlen(arg));
2827                break;
2828
2829#endif
2830
2831	default:
2832		fatal("%s line %d: Missing handler for opcode %s (%d)",
2833		    filename, linenum, keyword, opcode);
2834	}
2835	/* Check that there is no garbage at end of line. */
2836	if (ac > 0) {
2837		error("%.200s line %d: keyword %s extra arguments "
2838		    "at end of line", filename, linenum, keyword);
2839		goto out;
2840	}
2841
2842	/* success */
2843	ret = 0;
2844 out:
2845	argv_free(oav, oac);
2846	return ret;
2847}
2848
2849int
2850process_server_config_line(ServerOptions *options, char *line,
2851    const char *filename, int linenum, int *activep,
2852    struct connection_info *connectinfo, struct include_list *includes)
2853{
2854	int inc_flags = 0;
2855
2856	return process_server_config_line_depth(options, line, filename,
2857	    linenum, activep, connectinfo, &inc_flags, 0, includes);
2858}
2859
2860
2861/* Reads the server configuration file. */
2862
2863void
2864load_server_config(const char *filename, struct sshbuf *conf)
2865{
2866	struct stat st;
2867	char *line = NULL, *cp;
2868	size_t linesize = 0;
2869	FILE *f;
2870	int r;
2871
2872	debug2_f("filename %s", filename);
2873	if ((f = fopen(filename, "r")) == NULL) {
2874		perror(filename);
2875		exit(1);
2876	}
2877	sshbuf_reset(conf);
2878	/* grow buffer, so realloc is avoided for large config files */
2879	if (fstat(fileno(f), &st) == 0 && st.st_size > 0 &&
2880	    (r = sshbuf_allocate(conf, st.st_size)) != 0)
2881		fatal_fr(r, "allocate");
2882	while (getline(&line, &linesize, f) != -1) {
2883		/*
2884		 * Strip whitespace
2885		 * NB - preserve newlines, they are needed to reproduce
2886		 * line numbers later for error messages
2887		 */
2888		cp = line + strspn(line, " \t\r");
2889		if ((r = sshbuf_put(conf, cp, strlen(cp))) != 0)
2890			fatal_fr(r, "sshbuf_put");
2891	}
2892	free(line);
2893	if ((r = sshbuf_put_u8(conf, 0)) != 0)
2894		fatal_fr(r, "sshbuf_put_u8");
2895	fclose(f);
2896	debug2_f("done config len = %zu", sshbuf_len(conf));
2897}
2898
2899void
2900parse_server_match_config(ServerOptions *options,
2901   struct include_list *includes, struct connection_info *connectinfo)
2902{
2903	ServerOptions mo;
2904
2905	initialize_server_options(&mo);
2906	parse_server_config(&mo, "reprocess config", cfg, includes,
2907	    connectinfo, 0);
2908	copy_set_server_options(options, &mo, 0);
2909}
2910
2911int parse_server_match_testspec(struct connection_info *ci, char *spec)
2912{
2913	char *p;
2914
2915	while ((p = strsep(&spec, ",")) && *p != '\0') {
2916		if (strncmp(p, "addr=", 5) == 0) {
2917			ci->address = xstrdup(p + 5);
2918		} else if (strncmp(p, "host=", 5) == 0) {
2919			ci->host = xstrdup(p + 5);
2920		} else if (strncmp(p, "user=", 5) == 0) {
2921			ci->user = xstrdup(p + 5);
2922		} else if (strncmp(p, "laddr=", 6) == 0) {
2923			ci->laddress = xstrdup(p + 6);
2924		} else if (strncmp(p, "rdomain=", 8) == 0) {
2925			ci->rdomain = xstrdup(p + 8);
2926		} else if (strncmp(p, "lport=", 6) == 0) {
2927			ci->lport = a2port(p + 6);
2928			if (ci->lport == -1) {
2929				fprintf(stderr, "Invalid port '%s' in test mode"
2930				    " specification %s\n", p+6, p);
2931				return -1;
2932			}
2933		} else {
2934			fprintf(stderr, "Invalid test mode specification %s\n",
2935			    p);
2936			return -1;
2937		}
2938	}
2939	return 0;
2940}
2941
2942void
2943servconf_merge_subsystems(ServerOptions *dst, ServerOptions *src)
2944{
2945	u_int i, j, found;
2946
2947	for (i = 0; i < src->num_subsystems; i++) {
2948		found = 0;
2949		for (j = 0; j < dst->num_subsystems; j++) {
2950			if (strcmp(src->subsystem_name[i],
2951			    dst->subsystem_name[j]) == 0) {
2952				found = 1;
2953				break;
2954			}
2955		}
2956		if (found) {
2957			debug_f("override \"%s\"", dst->subsystem_name[j]);
2958			free(dst->subsystem_command[j]);
2959			free(dst->subsystem_args[j]);
2960			dst->subsystem_command[j] =
2961			    xstrdup(src->subsystem_command[i]);
2962			dst->subsystem_args[j] =
2963			    xstrdup(src->subsystem_args[i]);
2964			continue;
2965		}
2966		debug_f("add \"%s\"", src->subsystem_name[i]);
2967		dst->subsystem_name = xrecallocarray(
2968		    dst->subsystem_name, dst->num_subsystems,
2969		    dst->num_subsystems + 1, sizeof(*dst->subsystem_name));
2970		dst->subsystem_command = xrecallocarray(
2971		    dst->subsystem_command, dst->num_subsystems,
2972		    dst->num_subsystems + 1, sizeof(*dst->subsystem_command));
2973		dst->subsystem_args = xrecallocarray(
2974		    dst->subsystem_args, dst->num_subsystems,
2975		    dst->num_subsystems + 1, sizeof(*dst->subsystem_args));
2976		j = dst->num_subsystems++;
2977		dst->subsystem_name[j] = xstrdup(src->subsystem_name[i]);
2978		dst->subsystem_command[j] = xstrdup(src->subsystem_command[i]);
2979		dst->subsystem_args[j] = xstrdup(src->subsystem_args[i]);
2980	}
2981}
2982
2983/*
2984 * Copy any supported values that are set.
2985 *
2986 * If the preauth flag is set, we do not bother copying the string or
2987 * array values that are not used pre-authentication, because any that we
2988 * do use must be explicitly sent in mm_getpwnamallow().
2989 */
2990void
2991copy_set_server_options(ServerOptions *dst, ServerOptions *src, int preauth)
2992{
2993#define M_CP_INTOPT(n) do {\
2994	if (src->n != -1) \
2995		dst->n = src->n; \
2996} while (0)
2997
2998	M_CP_INTOPT(password_authentication);
2999	M_CP_INTOPT(gss_authentication);
3000	M_CP_INTOPT(pubkey_authentication);
3001	M_CP_INTOPT(pubkey_auth_options);
3002	M_CP_INTOPT(kerberos_authentication);
3003	M_CP_INTOPT(hostbased_authentication);
3004	M_CP_INTOPT(hostbased_uses_name_from_packet_only);
3005	M_CP_INTOPT(kbd_interactive_authentication);
3006	M_CP_INTOPT(permit_root_login);
3007	M_CP_INTOPT(permit_empty_passwd);
3008	M_CP_INTOPT(ignore_rhosts);
3009
3010	M_CP_INTOPT(allow_tcp_forwarding);
3011	M_CP_INTOPT(allow_streamlocal_forwarding);
3012	M_CP_INTOPT(allow_agent_forwarding);
3013	M_CP_INTOPT(disable_forwarding);
3014	M_CP_INTOPT(expose_userauth_info);
3015	M_CP_INTOPT(permit_tun);
3016	M_CP_INTOPT(fwd_opts.gateway_ports);
3017	M_CP_INTOPT(fwd_opts.streamlocal_bind_unlink);
3018	M_CP_INTOPT(x11_display_offset);
3019	M_CP_INTOPT(x11_forwarding);
3020	M_CP_INTOPT(x11_use_localhost);
3021	M_CP_INTOPT(permit_tty);
3022	M_CP_INTOPT(permit_user_rc);
3023	M_CP_INTOPT(max_sessions);
3024	M_CP_INTOPT(max_authtries);
3025	M_CP_INTOPT(client_alive_count_max);
3026	M_CP_INTOPT(client_alive_interval);
3027	M_CP_INTOPT(ip_qos_interactive);
3028	M_CP_INTOPT(ip_qos_bulk);
3029	M_CP_INTOPT(rekey_limit);
3030	M_CP_INTOPT(rekey_interval);
3031	M_CP_INTOPT(log_level);
3032	M_CP_INTOPT(required_rsa_size);
3033	M_CP_INTOPT(unused_connection_timeout);
3034
3035	/*
3036	 * The bind_mask is a mode_t that may be unsigned, so we can't use
3037	 * M_CP_INTOPT - it does a signed comparison that causes compiler
3038	 * warnings.
3039	 */
3040	if (src->fwd_opts.streamlocal_bind_mask != (mode_t)-1) {
3041		dst->fwd_opts.streamlocal_bind_mask =
3042		    src->fwd_opts.streamlocal_bind_mask;
3043	}
3044
3045	/* M_CP_STROPT and M_CP_STRARRAYOPT should not appear before here */
3046#define M_CP_STROPT(n) do {\
3047	if (src->n != NULL && dst->n != src->n) { \
3048		free(dst->n); \
3049		dst->n = src->n; \
3050	} \
3051} while(0)
3052#define M_CP_STRARRAYOPT(s, num_s) do {\
3053	u_int i; \
3054	if (src->num_s != 0) { \
3055		for (i = 0; i < dst->num_s; i++) \
3056			free(dst->s[i]); \
3057		free(dst->s); \
3058		dst->s = xcalloc(src->num_s, sizeof(*dst->s)); \
3059		for (i = 0; i < src->num_s; i++) \
3060			dst->s[i] = xstrdup(src->s[i]); \
3061		dst->num_s = src->num_s; \
3062	} \
3063} while(0)
3064
3065	/* See comment in servconf.h */
3066	COPY_MATCH_STRING_OPTS();
3067
3068	/* Arguments that accept '+...' need to be expanded */
3069	assemble_algorithms(dst);
3070
3071	/*
3072	 * The only things that should be below this point are string options
3073	 * which are only used after authentication.
3074	 */
3075	if (preauth)
3076		return;
3077
3078	/* These options may be "none" to clear a global setting */
3079	M_CP_STROPT(adm_forced_command);
3080	if (option_clear_or_none(dst->adm_forced_command)) {
3081		free(dst->adm_forced_command);
3082		dst->adm_forced_command = NULL;
3083	}
3084	M_CP_STROPT(chroot_directory);
3085	if (option_clear_or_none(dst->chroot_directory)) {
3086		free(dst->chroot_directory);
3087		dst->chroot_directory = NULL;
3088	}
3089
3090	/* Subsystems require merging. */
3091	servconf_merge_subsystems(dst, src);
3092}
3093
3094#undef M_CP_INTOPT
3095#undef M_CP_STROPT
3096#undef M_CP_STRARRAYOPT
3097
3098#define SERVCONF_MAX_DEPTH	16
3099static void
3100parse_server_config_depth(ServerOptions *options, const char *filename,
3101    struct sshbuf *conf, struct include_list *includes,
3102    struct connection_info *connectinfo, int flags, int *activep, int depth)
3103{
3104	int linenum, bad_options = 0;
3105	char *cp, *obuf, *cbuf;
3106
3107	if (depth < 0 || depth > SERVCONF_MAX_DEPTH)
3108		fatal("Too many recursive configuration includes");
3109
3110	debug2_f("config %s len %zu%s", filename, sshbuf_len(conf),
3111	    (flags & SSHCFG_NEVERMATCH ? " [checking syntax only]" : ""));
3112
3113	if ((obuf = cbuf = sshbuf_dup_string(conf)) == NULL)
3114		fatal_f("sshbuf_dup_string failed");
3115	linenum = 1;
3116	while ((cp = strsep(&cbuf, "\n")) != NULL) {
3117		if (process_server_config_line_depth(options, cp,
3118		    filename, linenum++, activep, connectinfo, &flags,
3119		    depth, includes) != 0)
3120			bad_options++;
3121	}
3122	free(obuf);
3123	if (bad_options > 0)
3124		fatal("%s: terminating, %d bad configuration options",
3125		    filename, bad_options);
3126}
3127
3128void
3129parse_server_config(ServerOptions *options, const char *filename,
3130    struct sshbuf *conf, struct include_list *includes,
3131    struct connection_info *connectinfo, int reexec)
3132{
3133	int active = connectinfo ? 0 : 1;
3134	parse_server_config_depth(options, filename, conf, includes,
3135	    connectinfo, (connectinfo ? SSHCFG_MATCH_ONLY : 0), &active, 0);
3136	if (!reexec)
3137		process_queued_listen_addrs(options);
3138}
3139
3140static const char *
3141fmt_multistate_int(int val, const struct multistate *m)
3142{
3143	u_int i;
3144
3145	for (i = 0; m[i].key != NULL; i++) {
3146		if (m[i].value == val)
3147			return m[i].key;
3148	}
3149	return "UNKNOWN";
3150}
3151
3152static const char *
3153fmt_intarg(ServerOpCodes code, int val)
3154{
3155	if (val == -1)
3156		return "unset";
3157	switch (code) {
3158	case sAddressFamily:
3159		return fmt_multistate_int(val, multistate_addressfamily);
3160	case sPermitRootLogin:
3161		return fmt_multistate_int(val, multistate_permitrootlogin);
3162	case sGatewayPorts:
3163		return fmt_multistate_int(val, multistate_gatewayports);
3164	case sCompression:
3165		return fmt_multistate_int(val, multistate_compression);
3166	case sAllowTcpForwarding:
3167		return fmt_multistate_int(val, multistate_tcpfwd);
3168	case sAllowStreamLocalForwarding:
3169		return fmt_multistate_int(val, multistate_tcpfwd);
3170	case sIgnoreRhosts:
3171		return fmt_multistate_int(val, multistate_ignore_rhosts);
3172	case sFingerprintHash:
3173		return ssh_digest_alg_name(val);
3174	default:
3175		switch (val) {
3176		case 0:
3177			return "no";
3178		case 1:
3179			return "yes";
3180		default:
3181			return "UNKNOWN";
3182		}
3183	}
3184}
3185
3186static void
3187dump_cfg_int(ServerOpCodes code, int val)
3188{
3189	if (code == sUnusedConnectionTimeout && val == 0) {
3190		printf("%s none\n", lookup_opcode_name(code));
3191		return;
3192	}
3193	printf("%s %d\n", lookup_opcode_name(code), val);
3194}
3195
3196static void
3197dump_cfg_oct(ServerOpCodes code, int val)
3198{
3199	printf("%s 0%o\n", lookup_opcode_name(code), val);
3200}
3201
3202static void
3203dump_cfg_fmtint(ServerOpCodes code, int val)
3204{
3205	printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
3206}
3207
3208static void
3209dump_cfg_string(ServerOpCodes code, const char *val)
3210{
3211	printf("%s %s\n", lookup_opcode_name(code),
3212	    val == NULL ? "none" : val);
3213}
3214
3215static void
3216dump_cfg_strarray(ServerOpCodes code, u_int count, char **vals)
3217{
3218	u_int i;
3219
3220	for (i = 0; i < count; i++)
3221		printf("%s %s\n", lookup_opcode_name(code), vals[i]);
3222}
3223
3224static void
3225dump_cfg_strarray_oneline(ServerOpCodes code, u_int count, char **vals)
3226{
3227	u_int i;
3228
3229	switch (code) {
3230	case sAuthenticationMethods:
3231	case sChannelTimeout:
3232		break;
3233	default:
3234		if (count <= 0)
3235			return;
3236		break;
3237	}
3238
3239	printf("%s", lookup_opcode_name(code));
3240	for (i = 0; i < count; i++)
3241		printf(" %s",  vals[i]);
3242	if (code == sAuthenticationMethods && count == 0)
3243		printf(" any");
3244	else if (code == sChannelTimeout && count == 0)
3245		printf(" none");
3246	printf("\n");
3247}
3248
3249static char *
3250format_listen_addrs(struct listenaddr *la)
3251{
3252	int r;
3253	struct addrinfo *ai;
3254	char addr[NI_MAXHOST], port[NI_MAXSERV];
3255	char *laddr1 = xstrdup(""), *laddr2 = NULL;
3256
3257	/*
3258	 * ListenAddress must be after Port.  add_one_listen_addr pushes
3259	 * addresses onto a stack, so to maintain ordering we need to
3260	 * print these in reverse order.
3261	 */
3262	for (ai = la->addrs; ai; ai = ai->ai_next) {
3263		if ((r = getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
3264		    sizeof(addr), port, sizeof(port),
3265		    NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
3266			error("getnameinfo: %.100s", ssh_gai_strerror(r));
3267			continue;
3268		}
3269		laddr2 = laddr1;
3270		if (ai->ai_family == AF_INET6) {
3271			xasprintf(&laddr1, "listenaddress [%s]:%s%s%s\n%s",
3272			    addr, port,
3273			    la->rdomain == NULL ? "" : " rdomain ",
3274			    la->rdomain == NULL ? "" : la->rdomain,
3275			    laddr2);
3276		} else {
3277			xasprintf(&laddr1, "listenaddress %s:%s%s%s\n%s",
3278			    addr, port,
3279			    la->rdomain == NULL ? "" : " rdomain ",
3280			    la->rdomain == NULL ? "" : la->rdomain,
3281			    laddr2);
3282		}
3283		free(laddr2);
3284	}
3285	return laddr1;
3286}
3287
3288void
3289dump_config(ServerOptions *o)
3290{
3291	const char *s;
3292	u_int i;
3293
3294	/* these are usually at the top of the config */
3295	for (i = 0; i < o->num_ports; i++)
3296		printf("port %d\n", o->ports[i]);
3297	dump_cfg_fmtint(sAddressFamily, o->address_family);
3298
3299	for (i = 0; i < o->num_listen_addrs; i++) {
3300		char *ss = format_listen_addrs(&o->listen_addrs[i]);
3301		printf("%s", ss);
3302		free(ss);
3303	}
3304
3305	/* integer arguments */
3306	dump_cfg_int(sLoginGraceTime, o->login_grace_time);
3307	dump_cfg_int(sX11DisplayOffset, o->x11_display_offset);
3308	dump_cfg_int(sMaxAuthTries, o->max_authtries);
3309	dump_cfg_int(sMaxSessions, o->max_sessions);
3310	dump_cfg_int(sClientAliveInterval, o->client_alive_interval);
3311	dump_cfg_int(sClientAliveCountMax, o->client_alive_count_max);
3312	dump_cfg_int(sRequiredRSASize, o->required_rsa_size);
3313	dump_cfg_oct(sStreamLocalBindMask, o->fwd_opts.streamlocal_bind_mask);
3314	dump_cfg_int(sUnusedConnectionTimeout, o->unused_connection_timeout);
3315
3316	/* formatted integer arguments */
3317	dump_cfg_fmtint(sPermitRootLogin, o->permit_root_login);
3318	dump_cfg_fmtint(sIgnoreRhosts, o->ignore_rhosts);
3319	dump_cfg_fmtint(sIgnoreUserKnownHosts, o->ignore_user_known_hosts);
3320	dump_cfg_fmtint(sHostbasedAuthentication, o->hostbased_authentication);
3321	dump_cfg_fmtint(sHostbasedUsesNameFromPacketOnly,
3322	    o->hostbased_uses_name_from_packet_only);
3323	dump_cfg_fmtint(sPubkeyAuthentication, o->pubkey_authentication);
3324#ifdef KRB5
3325	dump_cfg_fmtint(sKerberosAuthentication, o->kerberos_authentication);
3326	dump_cfg_fmtint(sKerberosOrLocalPasswd, o->kerberos_or_local_passwd);
3327	dump_cfg_fmtint(sKerberosTicketCleanup, o->kerberos_ticket_cleanup);
3328	dump_cfg_fmtint(sKerberosGetAFSToken, o->kerberos_get_afs_token);
3329#endif
3330#ifdef GSSAPI
3331	dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
3332	dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
3333#endif
3334	dump_cfg_fmtint(sPasswordAuthentication, o->password_authentication);
3335	dump_cfg_fmtint(sKbdInteractiveAuthentication,
3336	    o->kbd_interactive_authentication);
3337	dump_cfg_fmtint(sPrintMotd, o->print_motd);
3338	dump_cfg_fmtint(sPrintLastLog, o->print_lastlog);
3339	dump_cfg_fmtint(sX11Forwarding, o->x11_forwarding);
3340	dump_cfg_fmtint(sX11UseLocalhost, o->x11_use_localhost);
3341	dump_cfg_fmtint(sPermitTTY, o->permit_tty);
3342	dump_cfg_fmtint(sPermitUserRC, o->permit_user_rc);
3343	dump_cfg_fmtint(sStrictModes, o->strict_modes);
3344	dump_cfg_fmtint(sTCPKeepAlive, o->tcp_keep_alive);
3345	dump_cfg_fmtint(sEmptyPasswd, o->permit_empty_passwd);
3346	dump_cfg_fmtint(sCompression, o->compression);
3347	dump_cfg_fmtint(sGatewayPorts, o->fwd_opts.gateway_ports);
3348	dump_cfg_fmtint(sUseDNS, o->use_dns);
3349	dump_cfg_fmtint(sAllowTcpForwarding, o->allow_tcp_forwarding);
3350	dump_cfg_fmtint(sAllowAgentForwarding, o->allow_agent_forwarding);
3351	dump_cfg_fmtint(sDisableForwarding, o->disable_forwarding);
3352	dump_cfg_fmtint(sAllowStreamLocalForwarding, o->allow_streamlocal_forwarding);
3353	dump_cfg_fmtint(sStreamLocalBindUnlink, o->fwd_opts.streamlocal_bind_unlink);
3354	dump_cfg_fmtint(sFingerprintHash, o->fingerprint_hash);
3355	dump_cfg_fmtint(sExposeAuthInfo, o->expose_userauth_info);
3356
3357	/* string arguments */
3358	dump_cfg_string(sPidFile, o->pid_file);
3359	dump_cfg_string(sModuliFile, o->moduli_file);
3360	dump_cfg_string(sXAuthLocation, o->xauth_location);
3361	dump_cfg_string(sCiphers, o->ciphers);
3362	dump_cfg_string(sMacs, o->macs);
3363	dump_cfg_string(sBanner, o->banner);
3364	dump_cfg_string(sForceCommand, o->adm_forced_command);
3365	dump_cfg_string(sChrootDirectory, o->chroot_directory);
3366	dump_cfg_string(sTrustedUserCAKeys, o->trusted_user_ca_keys);
3367	dump_cfg_string(sRevokedKeys, o->revoked_keys_file);
3368	dump_cfg_string(sSecurityKeyProvider, o->sk_provider);
3369	dump_cfg_string(sAuthorizedPrincipalsFile,
3370	    o->authorized_principals_file);
3371	dump_cfg_string(sVersionAddendum, *o->version_addendum == '\0'
3372	    ? "none" : o->version_addendum);
3373	dump_cfg_string(sAuthorizedKeysCommand, o->authorized_keys_command);
3374	dump_cfg_string(sAuthorizedKeysCommandUser, o->authorized_keys_command_user);
3375	dump_cfg_string(sAuthorizedPrincipalsCommand, o->authorized_principals_command);
3376	dump_cfg_string(sAuthorizedPrincipalsCommandUser, o->authorized_principals_command_user);
3377	dump_cfg_string(sHostKeyAgent, o->host_key_agent);
3378	dump_cfg_string(sKexAlgorithms, o->kex_algorithms);
3379	dump_cfg_string(sCASignatureAlgorithms, o->ca_sign_algorithms);
3380	dump_cfg_string(sHostbasedAcceptedAlgorithms, o->hostbased_accepted_algos);
3381	dump_cfg_string(sHostKeyAlgorithms, o->hostkeyalgorithms);
3382	dump_cfg_string(sPubkeyAcceptedAlgorithms, o->pubkey_accepted_algos);
3383	dump_cfg_string(sRDomain, o->routing_domain);
3384
3385	/* string arguments requiring a lookup */
3386	dump_cfg_string(sLogLevel, log_level_name(o->log_level));
3387	dump_cfg_string(sLogFacility, log_facility_name(o->log_facility));
3388
3389	/* string array arguments */
3390	dump_cfg_strarray_oneline(sAuthorizedKeysFile, o->num_authkeys_files,
3391	    o->authorized_keys_files);
3392	dump_cfg_strarray(sHostKeyFile, o->num_host_key_files,
3393	    o->host_key_files);
3394	dump_cfg_strarray(sHostCertificate, o->num_host_cert_files,
3395	    o->host_cert_files);
3396	dump_cfg_strarray(sAllowUsers, o->num_allow_users, o->allow_users);
3397	dump_cfg_strarray(sDenyUsers, o->num_deny_users, o->deny_users);
3398	dump_cfg_strarray(sAllowGroups, o->num_allow_groups, o->allow_groups);
3399	dump_cfg_strarray(sDenyGroups, o->num_deny_groups, o->deny_groups);
3400	dump_cfg_strarray(sAcceptEnv, o->num_accept_env, o->accept_env);
3401	dump_cfg_strarray(sSetEnv, o->num_setenv, o->setenv);
3402	dump_cfg_strarray_oneline(sAuthenticationMethods,
3403	    o->num_auth_methods, o->auth_methods);
3404	dump_cfg_strarray_oneline(sLogVerbose,
3405	    o->num_log_verbose, o->log_verbose);
3406	dump_cfg_strarray_oneline(sChannelTimeout,
3407	    o->num_channel_timeouts, o->channel_timeouts);
3408
3409	/* other arguments */
3410	for (i = 0; i < o->num_subsystems; i++)
3411		printf("subsystem %s %s\n", o->subsystem_name[i],
3412		    o->subsystem_args[i]);
3413
3414	printf("maxstartups %d:%d:%d\n", o->max_startups_begin,
3415	    o->max_startups_rate, o->max_startups);
3416	printf("persourcemaxstartups ");
3417	if (o->per_source_max_startups == INT_MAX)
3418		printf("none\n");
3419	else
3420		printf("%d\n", o->per_source_max_startups);
3421	printf("persourcenetblocksize %d:%d\n", o->per_source_masklen_ipv4,
3422	    o->per_source_masklen_ipv6);
3423
3424	s = NULL;
3425	for (i = 0; tunmode_desc[i].val != -1; i++) {
3426		if (tunmode_desc[i].val == o->permit_tun) {
3427			s = tunmode_desc[i].text;
3428			break;
3429		}
3430	}
3431	dump_cfg_string(sPermitTunnel, s);
3432
3433	printf("ipqos %s ", iptos2str(o->ip_qos_interactive));
3434	printf("%s\n", iptos2str(o->ip_qos_bulk));
3435
3436	printf("rekeylimit %llu %d\n", (unsigned long long)o->rekey_limit,
3437	    o->rekey_interval);
3438
3439	printf("permitopen");
3440	if (o->num_permitted_opens == 0)
3441		printf(" any");
3442	else {
3443		for (i = 0; i < o->num_permitted_opens; i++)
3444			printf(" %s", o->permitted_opens[i]);
3445	}
3446	printf("\n");
3447	printf("permitlisten");
3448	if (o->num_permitted_listens == 0)
3449		printf(" any");
3450	else {
3451		for (i = 0; i < o->num_permitted_listens; i++)
3452			printf(" %s", o->permitted_listens[i]);
3453	}
3454	printf("\n");
3455
3456	if (o->permit_user_env_allowlist == NULL) {
3457		dump_cfg_fmtint(sPermitUserEnvironment, o->permit_user_env);
3458	} else {
3459		printf("permituserenvironment %s\n",
3460		    o->permit_user_env_allowlist);
3461	}
3462
3463	printf("pubkeyauthoptions");
3464	if (o->pubkey_auth_options == 0)
3465		printf(" none");
3466	if (o->pubkey_auth_options & PUBKEYAUTH_TOUCH_REQUIRED)
3467		printf(" touch-required");
3468	if (o->pubkey_auth_options & PUBKEYAUTH_VERIFY_REQUIRED)
3469		printf(" verify-required");
3470	printf("\n");
3471}
3472