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