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