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