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