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