Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly into...
[dragonfly.git] / crypto / openssh-5 / servconf.c
1 /* $OpenBSD: servconf.c,v 1.186 2008/07/04 03:44:59 djm Exp $ */
2 /*
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  *
6  * As far as I am concerned, the code I have written for this software
7  * can be used freely for any purpose.  Any derived versions of this
8  * software must be clearly marked as such, and if the derived work is
9  * incompatible with the protocol description in the RFC file, it must be
10  * called by a name other than "ssh" or "Secure Shell".
11  */
12
13 #include "includes.h"
14
15 #include <sys/types.h>
16 #include <sys/socket.h>
17
18 #include <netdb.h>
19 #include <pwd.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <signal.h>
24 #include <unistd.h>
25 #include <stdarg.h>
26 #include <errno.h>
27
28 #include "openbsd-compat/sys-queue.h"
29 #include "xmalloc.h"
30 #include "ssh.h"
31 #include "log.h"
32 #include "buffer.h"
33 #include "servconf.h"
34 #include "compat.h"
35 #include "pathnames.h"
36 #include "misc.h"
37 #include "cipher.h"
38 #include "key.h"
39 #include "kex.h"
40 #include "mac.h"
41 #include "match.h"
42 #include "channels.h"
43 #include "groupaccess.h"
44
45 static void add_listen_addr(ServerOptions *, char *, u_short);
46 static void add_one_listen_addr(ServerOptions *, char *, u_short);
47
48 /* Use of privilege separation or not */
49 extern int use_privsep;
50 extern Buffer cfg;
51
52 /* Initializes the server options to their default values. */
53
54 void
55 initialize_server_options(ServerOptions *options)
56 {
57         memset(options, 0, sizeof(*options));
58
59         /* Portable-specific options */
60         options->use_pam = -1;
61
62         /* Standard Options */
63         options->num_ports = 0;
64         options->ports_from_cmdline = 0;
65         options->listen_addrs = NULL;
66         options->address_family = -1;
67         options->num_host_key_files = 0;
68         options->pid_file = NULL;
69         options->server_key_bits = -1;
70         options->login_grace_time = -1;
71         options->key_regeneration_time = -1;
72         options->permit_root_login = PERMIT_NOT_SET;
73         options->ignore_rhosts = -1;
74         options->ignore_user_known_hosts = -1;
75         options->print_motd = -1;
76         options->print_lastlog = -1;
77         options->x11_forwarding = -1;
78         options->x11_display_offset = -1;
79         options->x11_use_localhost = -1;
80         options->xauth_location = NULL;
81         options->strict_modes = -1;
82         options->tcp_keep_alive = -1;
83         options->log_facility = SYSLOG_FACILITY_NOT_SET;
84         options->log_level = SYSLOG_LEVEL_NOT_SET;
85         options->rhosts_rsa_authentication = -1;
86         options->hostbased_authentication = -1;
87         options->hostbased_uses_name_from_packet_only = -1;
88         options->rsa_authentication = -1;
89         options->pubkey_authentication = -1;
90         options->kerberos_authentication = -1;
91         options->kerberos_or_local_passwd = -1;
92         options->kerberos_ticket_cleanup = -1;
93         options->kerberos_get_afs_token = -1;
94         options->gss_authentication=-1;
95         options->gss_cleanup_creds = -1;
96         options->password_authentication = -1;
97         options->kbd_interactive_authentication = -1;
98         options->challenge_response_authentication = -1;
99         options->permit_blacklisted_keys = -1;
100         options->permit_empty_passwd = -1;
101         options->permit_user_env = -1;
102         options->use_login = -1;
103         options->compression = -1;
104         options->allow_tcp_forwarding = -1;
105         options->allow_agent_forwarding = -1;
106         options->num_allow_users = 0;
107         options->num_deny_users = 0;
108         options->num_allow_groups = 0;
109         options->num_deny_groups = 0;
110         options->ciphers = NULL;
111         options->macs = NULL;
112         options->protocol = SSH_PROTO_UNKNOWN;
113         options->gateway_ports = -1;
114         options->num_subsystems = 0;
115         options->max_startups_begin = -1;
116         options->max_startups_rate = -1;
117         options->max_startups = -1;
118         options->max_authtries = -1;
119         options->max_sessions = -1;
120         options->banner = NULL;
121         options->use_dns = -1;
122         options->client_alive_interval = -1;
123         options->client_alive_count_max = -1;
124         options->authorized_keys_file = NULL;
125         options->authorized_keys_file2 = NULL;
126         options->num_accept_env = 0;
127         options->permit_tun = -1;
128         options->num_permitted_opens = -1;
129         options->adm_forced_command = NULL;
130         options->chroot_directory = NULL;
131 }
132
133 void
134 fill_default_server_options(ServerOptions *options)
135 {
136         /* Portable-specific options */
137         if (options->use_pam == -1)
138                 options->use_pam = 0;
139
140         /* Standard Options */
141         if (options->protocol == SSH_PROTO_UNKNOWN)
142                 options->protocol = SSH_PROTO_2;
143         if (options->num_host_key_files == 0) {
144                 /* fill default hostkeys for protocols */
145                 if (options->protocol & SSH_PROTO_1)
146                         options->host_key_files[options->num_host_key_files++] =
147                             _PATH_HOST_KEY_FILE;
148                 if (options->protocol & SSH_PROTO_2) {
149                         options->host_key_files[options->num_host_key_files++] =
150                             _PATH_HOST_RSA_KEY_FILE;
151                         options->host_key_files[options->num_host_key_files++] =
152                             _PATH_HOST_DSA_KEY_FILE;
153                 }
154         }
155         if (options->num_ports == 0)
156                 options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
157         if (options->listen_addrs == NULL)
158                 add_listen_addr(options, NULL, 0);
159         if (options->pid_file == NULL)
160                 options->pid_file = _PATH_SSH_DAEMON_PID_FILE;
161         if (options->server_key_bits == -1)
162                 options->server_key_bits = 1024;
163         if (options->login_grace_time == -1)
164                 options->login_grace_time = 120;
165         if (options->key_regeneration_time == -1)
166                 options->key_regeneration_time = 3600;
167         if (options->permit_root_login == PERMIT_NOT_SET)
168                 options->permit_root_login = PERMIT_NO;
169         if (options->ignore_rhosts == -1)
170                 options->ignore_rhosts = 1;
171         if (options->ignore_user_known_hosts == -1)
172                 options->ignore_user_known_hosts = 0;
173         if (options->print_motd == -1)
174                 options->print_motd = 1;
175         if (options->print_lastlog == -1)
176                 options->print_lastlog = 1;
177         if (options->x11_forwarding == -1)
178                 options->x11_forwarding = 1;
179         if (options->x11_display_offset == -1)
180                 options->x11_display_offset = 10;
181         if (options->x11_use_localhost == -1)
182                 options->x11_use_localhost = 1;
183         if (options->xauth_location == NULL)
184                 options->xauth_location = _PATH_XAUTH;
185         if (options->strict_modes == -1)
186                 options->strict_modes = 1;
187         if (options->tcp_keep_alive == -1)
188                 options->tcp_keep_alive = 1;
189         if (options->log_facility == SYSLOG_FACILITY_NOT_SET)
190                 options->log_facility = SYSLOG_FACILITY_AUTH;
191         if (options->log_level == SYSLOG_LEVEL_NOT_SET)
192                 options->log_level = SYSLOG_LEVEL_INFO;
193         if (options->rhosts_rsa_authentication == -1)
194                 options->rhosts_rsa_authentication = 0;
195         if (options->hostbased_authentication == -1)
196                 options->hostbased_authentication = 0;
197         if (options->hostbased_uses_name_from_packet_only == -1)
198                 options->hostbased_uses_name_from_packet_only = 0;
199         if (options->rsa_authentication == -1)
200                 options->rsa_authentication = 1;
201         if (options->pubkey_authentication == -1)
202                 options->pubkey_authentication = 1;
203         if (options->kerberos_authentication == -1)
204                 options->kerberos_authentication = 0;
205         if (options->kerberos_or_local_passwd == -1)
206                 options->kerberos_or_local_passwd = 1;
207         if (options->kerberos_ticket_cleanup == -1)
208                 options->kerberos_ticket_cleanup = 1;
209         if (options->kerberos_get_afs_token == -1)
210                 options->kerberos_get_afs_token = 0;
211         if (options->gss_authentication == -1)
212                 options->gss_authentication = 0;
213         if (options->gss_cleanup_creds == -1)
214                 options->gss_cleanup_creds = 1;
215         if (options->password_authentication == -1)
216                 options->password_authentication = 1;
217         if (options->kbd_interactive_authentication == -1)
218                 options->kbd_interactive_authentication = 0;
219         if (options->challenge_response_authentication == -1)
220                 options->challenge_response_authentication = 1;
221         if (options->permit_blacklisted_keys == -1)
222                 options->permit_blacklisted_keys = 0;
223         if (options->permit_empty_passwd == -1)
224                 options->permit_empty_passwd = 0;
225         if (options->permit_user_env == -1)
226                 options->permit_user_env = 0;
227         if (options->use_login == -1)
228                 options->use_login = 0;
229         if (options->compression == -1)
230                 options->compression = COMP_DELAYED;
231         if (options->allow_tcp_forwarding == -1)
232                 options->allow_tcp_forwarding = 1;
233         if (options->allow_agent_forwarding == -1)
234                 options->allow_agent_forwarding = 1;
235         if (options->gateway_ports == -1)
236                 options->gateway_ports = 0;
237         if (options->max_startups == -1)
238                 options->max_startups = 10;
239         if (options->max_startups_rate == -1)
240                 options->max_startups_rate = 100;               /* 100% */
241         if (options->max_startups_begin == -1)
242                 options->max_startups_begin = options->max_startups;
243         if (options->max_authtries == -1)
244                 options->max_authtries = DEFAULT_AUTH_FAIL_MAX;
245         if (options->max_sessions == -1)
246                 options->max_sessions = DEFAULT_SESSIONS_MAX;
247         if (options->use_dns == -1)
248                 options->use_dns = 1;
249         if (options->client_alive_interval == -1)
250                 options->client_alive_interval = 0;
251         if (options->client_alive_count_max == -1)
252                 options->client_alive_count_max = 3;
253         if (options->authorized_keys_file2 == NULL) {
254                 /* authorized_keys_file2 falls back to authorized_keys_file */
255                 if (options->authorized_keys_file != NULL)
256                         options->authorized_keys_file2 = options->authorized_keys_file;
257                 else
258                         options->authorized_keys_file2 = _PATH_SSH_USER_PERMITTED_KEYS2;
259         }
260         if (options->authorized_keys_file == NULL)
261                 options->authorized_keys_file = _PATH_SSH_USER_PERMITTED_KEYS;
262         if (options->permit_tun == -1)
263                 options->permit_tun = SSH_TUNMODE_NO;
264
265         /* Turn privilege separation on by default */
266         if (use_privsep == -1)
267                 use_privsep = 1;
268
269 #ifndef HAVE_MMAP
270         if (use_privsep && options->compression == 1) {
271                 error("This platform does not support both privilege "
272                     "separation and compression");
273                 error("Compression disabled");
274                 options->compression = 0;
275         }
276 #endif
277
278 }
279
280 /* Keyword tokens. */
281 typedef enum {
282         sBadOption,             /* == unknown option */
283         /* Portable-specific options */
284         sUsePAM,
285         /* Standard Options */
286         sPort, sHostKeyFile, sServerKeyBits, sLoginGraceTime, sKeyRegenerationTime,
287         sPermitRootLogin, sLogFacility, sLogLevel,
288         sRhostsRSAAuthentication, sRSAAuthentication,
289         sKerberosAuthentication, sKerberosOrLocalPasswd, sKerberosTicketCleanup,
290         sKerberosGetAFSToken,
291         sKerberosTgtPassing, sChallengeResponseAuthentication,
292         sPasswordAuthentication, sKbdInteractiveAuthentication,
293         sListenAddress, sAddressFamily,
294         sPrintMotd, sPrintLastLog, sIgnoreRhosts,
295         sX11Forwarding, sX11DisplayOffset, sX11UseLocalhost,
296         sStrictModes, sPermitBlacklistedKeys, sEmptyPasswd, sTCPKeepAlive,
297         sPermitUserEnvironment, sUseLogin, sAllowTcpForwarding, sCompression,
298         sAllowUsers, sDenyUsers, sAllowGroups, sDenyGroups,
299         sIgnoreUserKnownHosts, sCiphers, sMacs, sProtocol, sPidFile,
300         sGatewayPorts, sPubkeyAuthentication, sXAuthLocation, sSubsystem,
301         sMaxStartups, sMaxAuthTries, sMaxSessions,
302         sBanner, sUseDNS, sHostbasedAuthentication,
303         sHostbasedUsesNameFromPacketOnly, sClientAliveInterval,
304         sClientAliveCountMax, sAuthorizedKeysFile, sAuthorizedKeysFile2,
305         sGssAuthentication, sGssCleanupCreds, sAcceptEnv, sPermitTunnel,
306         sMatch, sPermitOpen, sForceCommand, sChrootDirectory,
307         sUsePrivilegeSeparation, sAllowAgentForwarding,
308         sVersionAddendum,
309         sDeprecated, sUnsupported
310 } ServerOpCodes;
311
312 #define SSHCFG_GLOBAL   0x01    /* allowed in main section of sshd_config */
313 #define SSHCFG_MATCH    0x02    /* allowed inside a Match section */
314 #define SSHCFG_ALL      (SSHCFG_GLOBAL|SSHCFG_MATCH)
315
316 /* Textual representation of the tokens. */
317 static struct {
318         const char *name;
319         ServerOpCodes opcode;
320         u_int flags;
321 } keywords[] = {
322         /* Portable-specific options */
323 #ifdef USE_PAM
324         { "usepam", sUsePAM, SSHCFG_GLOBAL },
325 #else
326         { "usepam", sUnsupported, SSHCFG_GLOBAL },
327 #endif
328         { "pamauthenticationviakbdint", sDeprecated, SSHCFG_GLOBAL },
329         /* Standard Options */
330         { "port", sPort, SSHCFG_GLOBAL },
331         { "hostkey", sHostKeyFile, SSHCFG_GLOBAL },
332         { "hostdsakey", sHostKeyFile, SSHCFG_GLOBAL },          /* alias */
333         { "pidfile", sPidFile, SSHCFG_GLOBAL },
334         { "serverkeybits", sServerKeyBits, SSHCFG_GLOBAL },
335         { "logingracetime", sLoginGraceTime, SSHCFG_GLOBAL },
336         { "keyregenerationinterval", sKeyRegenerationTime, SSHCFG_GLOBAL },
337         { "permitrootlogin", sPermitRootLogin, SSHCFG_ALL },
338         { "syslogfacility", sLogFacility, SSHCFG_GLOBAL },
339         { "loglevel", sLogLevel, SSHCFG_GLOBAL },
340         { "rhostsauthentication", sDeprecated, SSHCFG_GLOBAL },
341         { "rhostsrsaauthentication", sRhostsRSAAuthentication, SSHCFG_ALL },
342         { "hostbasedauthentication", sHostbasedAuthentication, SSHCFG_ALL },
343         { "hostbasedusesnamefrompacketonly", sHostbasedUsesNameFromPacketOnly, SSHCFG_GLOBAL },
344         { "rsaauthentication", sRSAAuthentication, SSHCFG_ALL },
345         { "pubkeyauthentication", sPubkeyAuthentication, SSHCFG_ALL },
346         { "dsaauthentication", sPubkeyAuthentication, SSHCFG_GLOBAL },  /* alias */
347 #ifdef KRB5
348         { "kerberosauthentication", sKerberosAuthentication, SSHCFG_ALL },
349         { "kerberosorlocalpasswd", sKerberosOrLocalPasswd, SSHCFG_GLOBAL },
350         { "kerberosticketcleanup", sKerberosTicketCleanup, SSHCFG_GLOBAL },
351 #ifdef USE_AFS
352         { "kerberosgetafstoken", sKerberosGetAFSToken, SSHCFG_GLOBAL },
353 #else
354         { "kerberosgetafstoken", sUnsupported, SSHCFG_GLOBAL },
355 #endif
356 #else
357         { "kerberosauthentication", sUnsupported, SSHCFG_ALL },
358         { "kerberosorlocalpasswd", sUnsupported, SSHCFG_GLOBAL },
359         { "kerberosticketcleanup", sUnsupported, SSHCFG_GLOBAL },
360         { "kerberosgetafstoken", sUnsupported, SSHCFG_GLOBAL },
361 #endif
362         { "kerberostgtpassing", sUnsupported, SSHCFG_GLOBAL },
363         { "afstokenpassing", sUnsupported, SSHCFG_GLOBAL },
364 #ifdef GSSAPI
365         { "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
366         { "gssapicleanupcredentials", sGssCleanupCreds, SSHCFG_GLOBAL },
367 #else
368         { "gssapiauthentication", sUnsupported, SSHCFG_ALL },
369         { "gssapicleanupcredentials", sUnsupported, SSHCFG_GLOBAL },
370 #endif
371         { "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
372         { "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
373         { "challengeresponseauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL },
374         { "skeyauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL }, /* alias */
375         { "checkmail", sDeprecated, SSHCFG_GLOBAL },
376         { "listenaddress", sListenAddress, SSHCFG_GLOBAL },
377         { "addressfamily", sAddressFamily, SSHCFG_GLOBAL },
378         { "printmotd", sPrintMotd, SSHCFG_GLOBAL },
379         { "printlastlog", sPrintLastLog, SSHCFG_GLOBAL },
380         { "ignorerhosts", sIgnoreRhosts, SSHCFG_GLOBAL },
381         { "ignoreuserknownhosts", sIgnoreUserKnownHosts, SSHCFG_GLOBAL },
382         { "x11forwarding", sX11Forwarding, SSHCFG_ALL },
383         { "x11displayoffset", sX11DisplayOffset, SSHCFG_ALL },
384         { "x11uselocalhost", sX11UseLocalhost, SSHCFG_ALL },
385         { "xauthlocation", sXAuthLocation, SSHCFG_GLOBAL },
386         { "strictmodes", sStrictModes, SSHCFG_GLOBAL },
387         { "permitblacklistedkeys", sPermitBlacklistedKeys, SSHCFG_GLOBAL },
388         { "permitemptypasswords", sEmptyPasswd, SSHCFG_GLOBAL },
389         { "permituserenvironment", sPermitUserEnvironment, SSHCFG_GLOBAL },
390         { "uselogin", sUseLogin, SSHCFG_GLOBAL },
391         { "compression", sCompression, SSHCFG_GLOBAL },
392         { "tcpkeepalive", sTCPKeepAlive, SSHCFG_GLOBAL },
393         { "keepalive", sTCPKeepAlive, SSHCFG_GLOBAL },  /* obsolete alias */
394         { "allowtcpforwarding", sAllowTcpForwarding, SSHCFG_ALL },
395         { "allowagentforwarding", sAllowAgentForwarding, SSHCFG_ALL },
396         { "allowusers", sAllowUsers, SSHCFG_GLOBAL },
397         { "denyusers", sDenyUsers, SSHCFG_GLOBAL },
398         { "allowgroups", sAllowGroups, SSHCFG_GLOBAL },
399         { "denygroups", sDenyGroups, SSHCFG_GLOBAL },
400         { "ciphers", sCiphers, SSHCFG_GLOBAL },
401         { "macs", sMacs, SSHCFG_GLOBAL },
402         { "protocol", sProtocol, SSHCFG_GLOBAL },
403         { "gatewayports", sGatewayPorts, SSHCFG_ALL },
404         { "subsystem", sSubsystem, SSHCFG_GLOBAL },
405         { "maxstartups", sMaxStartups, SSHCFG_GLOBAL },
406         { "maxauthtries", sMaxAuthTries, SSHCFG_ALL },
407         { "maxsessions", sMaxSessions, SSHCFG_ALL },
408         { "banner", sBanner, SSHCFG_ALL },
409         { "usedns", sUseDNS, SSHCFG_GLOBAL },
410         { "verifyreversemapping", sDeprecated, SSHCFG_GLOBAL },
411         { "reversemappingcheck", sDeprecated, SSHCFG_GLOBAL },
412         { "clientaliveinterval", sClientAliveInterval, SSHCFG_GLOBAL },
413         { "clientalivecountmax", sClientAliveCountMax, SSHCFG_GLOBAL },
414         { "authorizedkeysfile", sAuthorizedKeysFile, SSHCFG_GLOBAL },
415         { "authorizedkeysfile2", sAuthorizedKeysFile2, SSHCFG_GLOBAL },
416         { "useprivilegeseparation", sUsePrivilegeSeparation, SSHCFG_GLOBAL },
417         { "versionaddendum", sVersionAddendum , SSHCFG_GLOBAL },
418         { "acceptenv", sAcceptEnv, SSHCFG_GLOBAL },
419         { "permittunnel", sPermitTunnel, SSHCFG_GLOBAL },
420         { "match", sMatch, SSHCFG_ALL },
421         { "permitopen", sPermitOpen, SSHCFG_ALL },
422         { "forcecommand", sForceCommand, SSHCFG_ALL },
423         { "chrootdirectory", sChrootDirectory, SSHCFG_ALL },
424         { NULL, sBadOption, 0 }
425 };
426
427 static struct {
428         int val;
429         char *text;
430 } tunmode_desc[] = {
431         { SSH_TUNMODE_NO, "no" },
432         { SSH_TUNMODE_POINTOPOINT, "point-to-point" },
433         { SSH_TUNMODE_ETHERNET, "ethernet" },
434         { SSH_TUNMODE_YES, "yes" },
435         { -1, NULL }
436 };
437
438 /*
439  * Returns the number of the token pointed to by cp or sBadOption.
440  */
441
442 static ServerOpCodes
443 parse_token(const char *cp, const char *filename,
444             int linenum, u_int *flags)
445 {
446         u_int i;
447
448         for (i = 0; keywords[i].name; i++)
449                 if (strcasecmp(cp, keywords[i].name) == 0) {
450                         *flags = keywords[i].flags;
451                         return keywords[i].opcode;
452                 }
453
454         error("%s: line %d: Bad configuration option: %s",
455             filename, linenum, cp);
456         return sBadOption;
457 }
458
459 static void
460 add_listen_addr(ServerOptions *options, char *addr, u_short port)
461 {
462         u_int i;
463
464         if (options->num_ports == 0)
465                 options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
466         if (options->address_family == -1)
467                 options->address_family = AF_UNSPEC;
468         if (port == 0)
469                 for (i = 0; i < options->num_ports; i++)
470                         add_one_listen_addr(options, addr, options->ports[i]);
471         else
472                 add_one_listen_addr(options, addr, port);
473 }
474
475 static void
476 add_one_listen_addr(ServerOptions *options, char *addr, u_short port)
477 {
478         struct addrinfo hints, *ai, *aitop;
479         char strport[NI_MAXSERV];
480         int gaierr;
481
482         memset(&hints, 0, sizeof(hints));
483         hints.ai_family = options->address_family;
484         hints.ai_socktype = SOCK_STREAM;
485         hints.ai_flags = (addr == NULL) ? AI_PASSIVE : 0;
486         snprintf(strport, sizeof strport, "%u", port);
487         if ((gaierr = getaddrinfo(addr, strport, &hints, &aitop)) != 0)
488                 fatal("bad addr or host: %s (%s)",
489                     addr ? addr : "<NULL>",
490                     ssh_gai_strerror(gaierr));
491         for (ai = aitop; ai->ai_next; ai = ai->ai_next)
492                 ;
493         ai->ai_next = options->listen_addrs;
494         options->listen_addrs = aitop;
495 }
496
497 /*
498  * The strategy for the Match blocks is that the config file is parsed twice.
499  *
500  * The first time is at startup.  activep is initialized to 1 and the
501  * directives in the global context are processed and acted on.  Hitting a
502  * Match directive unsets activep and the directives inside the block are
503  * checked for syntax only.
504  *
505  * The second time is after a connection has been established but before
506  * authentication.  activep is initialized to 2 and global config directives
507  * are ignored since they have already been processed.  If the criteria in a
508  * Match block is met, activep is set and the subsequent directives
509  * processed and actioned until EOF or another Match block unsets it.  Any
510  * options set are copied into the main server config.
511  *
512  * Potential additions/improvements:
513  *  - Add Match support for pre-kex directives, eg Protocol, Ciphers.
514  *
515  *  - Add a Tag directive (idea from David Leonard) ala pf, eg:
516  *      Match Address 192.168.0.*
517  *              Tag trusted
518  *      Match Group wheel
519  *              Tag trusted
520  *      Match Tag trusted
521  *              AllowTcpForwarding yes
522  *              GatewayPorts clientspecified
523  *              [...]
524  *
525  *  - Add a PermittedChannelRequests directive
526  *      Match Group shell
527  *              PermittedChannelRequests session,forwarded-tcpip
528  */
529
530 static int
531 match_cfg_line_group(const char *grps, int line, const char *user)
532 {
533         int result = 0;
534         struct passwd *pw;
535
536         if (user == NULL)
537                 goto out;
538
539         if ((pw = getpwnam(user)) == NULL) {
540                 debug("Can't match group at line %d because user %.100s does "
541                     "not exist", line, user);
542         } else if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
543                 debug("Can't Match group because user %.100s not in any group "
544                     "at line %d", user, line);
545         } else if (ga_match_pattern_list(grps) != 1) {
546                 debug("user %.100s does not match group list %.100s at line %d",
547                     user, grps, line);
548         } else {
549                 debug("user %.100s matched group list %.100s at line %d", user,
550                     grps, line);
551                 result = 1;
552         }
553 out:
554         ga_free();
555         return result;
556 }
557
558 static int
559 match_cfg_line(char **condition, int line, const char *user, const char *host,
560     const char *address)
561 {
562         int result = 1;
563         char *arg, *attrib, *cp = *condition;
564         size_t len;
565
566         if (user == NULL)
567                 debug3("checking syntax for 'Match %s'", cp);
568         else
569                 debug3("checking match for '%s' user %s host %s addr %s", cp,
570                     user ? user : "(null)", host ? host : "(null)",
571                     address ? address : "(null)");
572
573         while ((attrib = strdelim(&cp)) && *attrib != '\0') {
574                 if ((arg = strdelim(&cp)) == NULL || *arg == '\0') {
575                         error("Missing Match criteria for %s", attrib);
576                         return -1;
577                 }
578                 len = strlen(arg);
579                 if (strcasecmp(attrib, "user") == 0) {
580                         if (!user) {
581                                 result = 0;
582                                 continue;
583                         }
584                         if (match_pattern_list(user, arg, len, 0) != 1)
585                                 result = 0;
586                         else
587                                 debug("user %.100s matched 'User %.100s' at "
588                                     "line %d", user, arg, line);
589                 } else if (strcasecmp(attrib, "group") == 0) {
590                         switch (match_cfg_line_group(arg, line, user)) {
591                         case -1:
592                                 return -1;
593                         case 0:
594                                 result = 0;
595                         }
596                 } else if (strcasecmp(attrib, "host") == 0) {
597                         if (!host) {
598                                 result = 0;
599                                 continue;
600                         }
601                         if (match_hostname(host, arg, len) != 1)
602                                 result = 0;
603                         else
604                                 debug("connection from %.100s matched 'Host "
605                                     "%.100s' at line %d", host, arg, line);
606                 } else if (strcasecmp(attrib, "address") == 0) {
607                         switch (addr_match_list(address, arg)) {
608                         case 1:
609                                 debug("connection from %.100s matched 'Address "
610                                     "%.100s' at line %d", address, arg, line);
611                                 break;
612                         case 0:
613                         case -1:
614                                 result = 0;
615                                 break;
616                         case -2:
617                                 return -1;
618                         }
619                 } else {
620                         error("Unsupported Match attribute %s", attrib);
621                         return -1;
622                 }
623         }
624         if (user != NULL)
625                 debug3("match %sfound", result ? "" : "not ");
626         *condition = cp;
627         return result;
628 }
629
630 #define WHITESPACE " \t\r\n"
631
632 int
633 process_server_config_line(ServerOptions *options, char *line,
634     const char *filename, int linenum, int *activep, const char *user,
635     const char *host, const char *address)
636 {
637         char *cp, **charptr, *arg, *p;
638         int cmdline = 0, *intptr, value, n;
639         SyslogFacility *log_facility_ptr;
640         LogLevel *log_level_ptr;
641         ServerOpCodes opcode;
642         u_short port;
643         u_int i, flags = 0;
644         size_t len;
645
646         cp = line;
647         if ((arg = strdelim(&cp)) == NULL)
648                 return 0;
649         /* Ignore leading whitespace */
650         if (*arg == '\0')
651                 arg = strdelim(&cp);
652         if (!arg || !*arg || *arg == '#')
653                 return 0;
654         intptr = NULL;
655         charptr = NULL;
656         opcode = parse_token(arg, filename, linenum, &flags);
657
658         if (activep == NULL) { /* We are processing a command line directive */
659                 cmdline = 1;
660                 activep = &cmdline;
661         }
662         if (*activep && opcode != sMatch)
663                 debug3("%s:%d setting %s %s", filename, linenum, arg, cp);
664         if (*activep == 0 && !(flags & SSHCFG_MATCH)) {
665                 if (user == NULL) {
666                         fatal("%s line %d: Directive '%s' is not allowed "
667                             "within a Match block", filename, linenum, arg);
668                 } else { /* this is a directive we have already processed */
669                         while (arg)
670                                 arg = strdelim(&cp);
671                         return 0;
672                 }
673         }
674
675         switch (opcode) {
676         /* Portable-specific options */
677         case sUsePAM:
678                 intptr = &options->use_pam;
679                 goto parse_flag;
680
681         /* Standard Options */
682         case sBadOption:
683                 return -1;
684         case sPort:
685                 /* ignore ports from configfile if cmdline specifies ports */
686                 if (options->ports_from_cmdline)
687                         return 0;
688                 if (options->listen_addrs != NULL)
689                         fatal("%s line %d: ports must be specified before "
690                             "ListenAddress.", filename, linenum);
691                 if (options->num_ports >= MAX_PORTS)
692                         fatal("%s line %d: too many ports.",
693                             filename, linenum);
694                 arg = strdelim(&cp);
695                 if (!arg || *arg == '\0')
696                         fatal("%s line %d: missing port number.",
697                             filename, linenum);
698                 options->ports[options->num_ports++] = a2port(arg);
699                 if (options->ports[options->num_ports-1] == 0)
700                         fatal("%s line %d: Badly formatted port number.",
701                             filename, linenum);
702                 break;
703
704         case sServerKeyBits:
705                 intptr = &options->server_key_bits;
706  parse_int:
707                 arg = strdelim(&cp);
708                 if (!arg || *arg == '\0')
709                         fatal("%s line %d: missing integer value.",
710                             filename, linenum);
711                 value = atoi(arg);
712                 if (*activep && *intptr == -1)
713                         *intptr = value;
714                 break;
715
716         case sLoginGraceTime:
717                 intptr = &options->login_grace_time;
718  parse_time:
719                 arg = strdelim(&cp);
720                 if (!arg || *arg == '\0')
721                         fatal("%s line %d: missing time value.",
722                             filename, linenum);
723                 if ((value = convtime(arg)) == -1)
724                         fatal("%s line %d: invalid time value.",
725                             filename, linenum);
726                 if (*intptr == -1)
727                         *intptr = value;
728                 break;
729
730         case sKeyRegenerationTime:
731                 intptr = &options->key_regeneration_time;
732                 goto parse_time;
733
734         case sListenAddress:
735                 arg = strdelim(&cp);
736                 if (arg == NULL || *arg == '\0')
737                         fatal("%s line %d: missing address",
738                             filename, linenum);
739                 /* check for bare IPv6 address: no "[]" and 2 or more ":" */
740                 if (strchr(arg, '[') == NULL && (p = strchr(arg, ':')) != NULL
741                     && strchr(p+1, ':') != NULL) {
742                         add_listen_addr(options, arg, 0);
743                         break;
744                 }
745                 p = hpdelim(&arg);
746                 if (p == NULL)
747                         fatal("%s line %d: bad address:port usage",
748                             filename, linenum);
749                 p = cleanhostname(p);
750                 if (arg == NULL)
751                         port = 0;
752                 else if ((port = a2port(arg)) == 0)
753                         fatal("%s line %d: bad port number", filename, linenum);
754
755                 add_listen_addr(options, p, port);
756
757                 break;
758
759         case sAddressFamily:
760                 arg = strdelim(&cp);
761                 if (!arg || *arg == '\0')
762                         fatal("%s line %d: missing address family.",
763                             filename, linenum);
764                 intptr = &options->address_family;
765                 if (options->listen_addrs != NULL)
766                         fatal("%s line %d: address family must be specified before "
767                             "ListenAddress.", filename, linenum);
768                 if (strcasecmp(arg, "inet") == 0)
769                         value = AF_INET;
770                 else if (strcasecmp(arg, "inet6") == 0)
771                         value = AF_INET6;
772                 else if (strcasecmp(arg, "any") == 0)
773                         value = AF_UNSPEC;
774                 else
775                         fatal("%s line %d: unsupported address family \"%s\".",
776                             filename, linenum, arg);
777                 if (*intptr == -1)
778                         *intptr = value;
779                 break;
780
781         case sHostKeyFile:
782                 intptr = &options->num_host_key_files;
783                 if (*intptr >= MAX_HOSTKEYS)
784                         fatal("%s line %d: too many host keys specified (max %d).",
785                             filename, linenum, MAX_HOSTKEYS);
786                 charptr = &options->host_key_files[*intptr];
787  parse_filename:
788                 arg = strdelim(&cp);
789                 if (!arg || *arg == '\0')
790                         fatal("%s line %d: missing file name.",
791                             filename, linenum);
792                 if (*activep && *charptr == NULL) {
793                         *charptr = tilde_expand_filename(arg, getuid());
794                         /* increase optional counter */
795                         if (intptr != NULL)
796                                 *intptr = *intptr + 1;
797                 }
798                 break;
799
800         case sPidFile:
801                 charptr = &options->pid_file;
802                 goto parse_filename;
803
804         case sPermitRootLogin:
805                 intptr = &options->permit_root_login;
806                 arg = strdelim(&cp);
807                 if (!arg || *arg == '\0')
808                         fatal("%s line %d: missing yes/"
809                             "without-password/forced-commands-only/no "
810                             "argument.", filename, linenum);
811                 value = 0;      /* silence compiler */
812                 if (strcmp(arg, "without-password") == 0)
813                         value = PERMIT_NO_PASSWD;
814                 else if (strcmp(arg, "forced-commands-only") == 0)
815                         value = PERMIT_FORCED_ONLY;
816                 else if (strcmp(arg, "yes") == 0)
817                         value = PERMIT_YES;
818                 else if (strcmp(arg, "no") == 0)
819                         value = PERMIT_NO;
820                 else
821                         fatal("%s line %d: Bad yes/"
822                             "without-password/forced-commands-only/no "
823                             "argument: %s", filename, linenum, arg);
824                 if (*activep && *intptr == -1)
825                         *intptr = value;
826                 break;
827
828         case sIgnoreRhosts:
829                 intptr = &options->ignore_rhosts;
830  parse_flag:
831                 arg = strdelim(&cp);
832                 if (!arg || *arg == '\0')
833                         fatal("%s line %d: missing yes/no argument.",
834                             filename, linenum);
835                 value = 0;      /* silence compiler */
836                 if (strcmp(arg, "yes") == 0)
837                         value = 1;
838                 else if (strcmp(arg, "no") == 0)
839                         value = 0;
840                 else
841                         fatal("%s line %d: Bad yes/no argument: %s",
842                                 filename, linenum, arg);
843                 if (*activep && *intptr == -1)
844                         *intptr = value;
845                 break;
846
847         case sIgnoreUserKnownHosts:
848                 intptr = &options->ignore_user_known_hosts;
849                 goto parse_flag;
850
851         case sRhostsRSAAuthentication:
852                 intptr = &options->rhosts_rsa_authentication;
853                 goto parse_flag;
854
855         case sHostbasedAuthentication:
856                 intptr = &options->hostbased_authentication;
857                 goto parse_flag;
858
859         case sHostbasedUsesNameFromPacketOnly:
860                 intptr = &options->hostbased_uses_name_from_packet_only;
861                 goto parse_flag;
862
863         case sRSAAuthentication:
864                 intptr = &options->rsa_authentication;
865                 goto parse_flag;
866
867         case sPubkeyAuthentication:
868                 intptr = &options->pubkey_authentication;
869                 goto parse_flag;
870
871         case sKerberosAuthentication:
872                 intptr = &options->kerberos_authentication;
873                 goto parse_flag;
874
875         case sKerberosOrLocalPasswd:
876                 intptr = &options->kerberos_or_local_passwd;
877                 goto parse_flag;
878
879         case sKerberosTicketCleanup:
880                 intptr = &options->kerberos_ticket_cleanup;
881                 goto parse_flag;
882
883         case sKerberosGetAFSToken:
884                 intptr = &options->kerberos_get_afs_token;
885                 goto parse_flag;
886
887         case sGssAuthentication:
888                 intptr = &options->gss_authentication;
889                 goto parse_flag;
890
891         case sGssCleanupCreds:
892                 intptr = &options->gss_cleanup_creds;
893                 goto parse_flag;
894
895         case sPasswordAuthentication:
896                 intptr = &options->password_authentication;
897                 goto parse_flag;
898
899         case sKbdInteractiveAuthentication:
900                 intptr = &options->kbd_interactive_authentication;
901                 goto parse_flag;
902
903         case sChallengeResponseAuthentication:
904                 intptr = &options->challenge_response_authentication;
905                 goto parse_flag;
906
907         case sPrintMotd:
908                 intptr = &options->print_motd;
909                 goto parse_flag;
910
911         case sPrintLastLog:
912                 intptr = &options->print_lastlog;
913                 goto parse_flag;
914
915         case sX11Forwarding:
916                 intptr = &options->x11_forwarding;
917                 goto parse_flag;
918
919         case sX11DisplayOffset:
920                 intptr = &options->x11_display_offset;
921                 goto parse_int;
922
923         case sX11UseLocalhost:
924                 intptr = &options->x11_use_localhost;
925                 goto parse_flag;
926
927         case sXAuthLocation:
928                 charptr = &options->xauth_location;
929                 goto parse_filename;
930
931         case sStrictModes:
932                 intptr = &options->strict_modes;
933                 goto parse_flag;
934
935         case sTCPKeepAlive:
936                 intptr = &options->tcp_keep_alive;
937                 goto parse_flag;
938
939         case sPermitBlacklistedKeys:
940                 intptr = &options->permit_blacklisted_keys;
941                 goto parse_flag;
942
943         case sEmptyPasswd:
944                 intptr = &options->permit_empty_passwd;
945                 goto parse_flag;
946
947         case sPermitUserEnvironment:
948                 intptr = &options->permit_user_env;
949                 goto parse_flag;
950
951         case sUseLogin:
952                 intptr = &options->use_login;
953                 goto parse_flag;
954
955         case sCompression:
956                 intptr = &options->compression;
957                 arg = strdelim(&cp);
958                 if (!arg || *arg == '\0')
959                         fatal("%s line %d: missing yes/no/delayed "
960                             "argument.", filename, linenum);
961                 value = 0;      /* silence compiler */
962                 if (strcmp(arg, "delayed") == 0)
963                         value = COMP_DELAYED;
964                 else if (strcmp(arg, "yes") == 0)
965                         value = COMP_ZLIB;
966                 else if (strcmp(arg, "no") == 0)
967                         value = COMP_NONE;
968                 else
969                         fatal("%s line %d: Bad yes/no/delayed "
970                             "argument: %s", filename, linenum, arg);
971                 if (*intptr == -1)
972                         *intptr = value;
973                 break;
974
975         case sGatewayPorts:
976                 intptr = &options->gateway_ports;
977                 arg = strdelim(&cp);
978                 if (!arg || *arg == '\0')
979                         fatal("%s line %d: missing yes/no/clientspecified "
980                             "argument.", filename, linenum);
981                 value = 0;      /* silence compiler */
982                 if (strcmp(arg, "clientspecified") == 0)
983                         value = 2;
984                 else if (strcmp(arg, "yes") == 0)
985                         value = 1;
986                 else if (strcmp(arg, "no") == 0)
987                         value = 0;
988                 else
989                         fatal("%s line %d: Bad yes/no/clientspecified "
990                             "argument: %s", filename, linenum, arg);
991                 if (*activep && *intptr == -1)
992                         *intptr = value;
993                 break;
994
995         case sUseDNS:
996                 intptr = &options->use_dns;
997                 goto parse_flag;
998
999         case sLogFacility:
1000                 log_facility_ptr = &options->log_facility;
1001                 arg = strdelim(&cp);
1002                 value = log_facility_number(arg);
1003                 if (value == SYSLOG_FACILITY_NOT_SET)
1004                         fatal("%.200s line %d: unsupported log facility '%s'",
1005                             filename, linenum, arg ? arg : "<NONE>");
1006                 if (*log_facility_ptr == -1)
1007                         *log_facility_ptr = (SyslogFacility) value;
1008                 break;
1009
1010         case sLogLevel:
1011                 log_level_ptr = &options->log_level;
1012                 arg = strdelim(&cp);
1013                 value = log_level_number(arg);
1014                 if (value == SYSLOG_LEVEL_NOT_SET)
1015                         fatal("%.200s line %d: unsupported log level '%s'",
1016                             filename, linenum, arg ? arg : "<NONE>");
1017                 if (*log_level_ptr == -1)
1018                         *log_level_ptr = (LogLevel) value;
1019                 break;
1020
1021         case sAllowTcpForwarding:
1022                 intptr = &options->allow_tcp_forwarding;
1023                 goto parse_flag;
1024
1025         case sAllowAgentForwarding:
1026                 intptr = &options->allow_agent_forwarding;
1027                 goto parse_flag;
1028
1029         case sUsePrivilegeSeparation:
1030                 intptr = &use_privsep;
1031                 goto parse_flag;
1032
1033         case sAllowUsers:
1034                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1035                         if (options->num_allow_users >= MAX_ALLOW_USERS)
1036                                 fatal("%s line %d: too many allow users.",
1037                                     filename, linenum);
1038                         options->allow_users[options->num_allow_users++] =
1039                             xstrdup(arg);
1040                 }
1041                 break;
1042
1043         case sDenyUsers:
1044                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1045                         if (options->num_deny_users >= MAX_DENY_USERS)
1046                                 fatal("%s line %d: too many deny users.",
1047                                     filename, linenum);
1048                         options->deny_users[options->num_deny_users++] =
1049                             xstrdup(arg);
1050                 }
1051                 break;
1052
1053         case sAllowGroups:
1054                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1055                         if (options->num_allow_groups >= MAX_ALLOW_GROUPS)
1056                                 fatal("%s line %d: too many allow groups.",
1057                                     filename, linenum);
1058                         options->allow_groups[options->num_allow_groups++] =
1059                             xstrdup(arg);
1060                 }
1061                 break;
1062
1063         case sDenyGroups:
1064                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1065                         if (options->num_deny_groups >= MAX_DENY_GROUPS)
1066                                 fatal("%s line %d: too many deny groups.",
1067                                     filename, linenum);
1068                         options->deny_groups[options->num_deny_groups++] = xstrdup(arg);
1069                 }
1070                 break;
1071
1072         case sCiphers:
1073                 arg = strdelim(&cp);
1074                 if (!arg || *arg == '\0')
1075                         fatal("%s line %d: Missing argument.", filename, linenum);
1076                 if (!ciphers_valid(arg))
1077                         fatal("%s line %d: Bad SSH2 cipher spec '%s'.",
1078                             filename, linenum, arg ? arg : "<NONE>");
1079                 if (options->ciphers == NULL)
1080                         options->ciphers = xstrdup(arg);
1081                 break;
1082
1083         case sMacs:
1084                 arg = strdelim(&cp);
1085                 if (!arg || *arg == '\0')
1086                         fatal("%s line %d: Missing argument.", filename, linenum);
1087                 if (!mac_valid(arg))
1088                         fatal("%s line %d: Bad SSH2 mac spec '%s'.",
1089                             filename, linenum, arg ? arg : "<NONE>");
1090                 if (options->macs == NULL)
1091                         options->macs = xstrdup(arg);
1092                 break;
1093
1094         case sProtocol:
1095                 intptr = &options->protocol;
1096                 arg = strdelim(&cp);
1097                 if (!arg || *arg == '\0')
1098                         fatal("%s line %d: Missing argument.", filename, linenum);
1099                 value = proto_spec(arg);
1100                 if (value == SSH_PROTO_UNKNOWN)
1101                         fatal("%s line %d: Bad protocol spec '%s'.",
1102                             filename, linenum, arg ? arg : "<NONE>");
1103                 if (*intptr == SSH_PROTO_UNKNOWN)
1104                         *intptr = value;
1105                 break;
1106
1107         case sSubsystem:
1108                 if (options->num_subsystems >= MAX_SUBSYSTEMS) {
1109                         fatal("%s line %d: too many subsystems defined.",
1110                             filename, linenum);
1111                 }
1112                 arg = strdelim(&cp);
1113                 if (!arg || *arg == '\0')
1114                         fatal("%s line %d: Missing subsystem name.",
1115                             filename, linenum);
1116                 if (!*activep) {
1117                         arg = strdelim(&cp);
1118                         break;
1119                 }
1120                 for (i = 0; i < options->num_subsystems; i++)
1121                         if (strcmp(arg, options->subsystem_name[i]) == 0)
1122                                 fatal("%s line %d: Subsystem '%s' already defined.",
1123                                     filename, linenum, arg);
1124                 options->subsystem_name[options->num_subsystems] = xstrdup(arg);
1125                 arg = strdelim(&cp);
1126                 if (!arg || *arg == '\0')
1127                         fatal("%s line %d: Missing subsystem command.",
1128                             filename, linenum);
1129                 options->subsystem_command[options->num_subsystems] = xstrdup(arg);
1130
1131                 /* Collect arguments (separate to executable) */
1132                 p = xstrdup(arg);
1133                 len = strlen(p) + 1;
1134                 while ((arg = strdelim(&cp)) != NULL && *arg != '\0') {
1135                         len += 1 + strlen(arg);
1136                         p = xrealloc(p, 1, len);
1137                         strlcat(p, " ", len);
1138                         strlcat(p, arg, len);
1139                 }
1140                 options->subsystem_args[options->num_subsystems] = p;
1141                 options->num_subsystems++;
1142                 break;
1143
1144         case sMaxStartups:
1145                 arg = strdelim(&cp);
1146                 if (!arg || *arg == '\0')
1147                         fatal("%s line %d: Missing MaxStartups spec.",
1148                             filename, linenum);
1149                 if ((n = sscanf(arg, "%d:%d:%d",
1150                     &options->max_startups_begin,
1151                     &options->max_startups_rate,
1152                     &options->max_startups)) == 3) {
1153                         if (options->max_startups_begin >
1154                             options->max_startups ||
1155                             options->max_startups_rate > 100 ||
1156                             options->max_startups_rate < 1)
1157                                 fatal("%s line %d: Illegal MaxStartups spec.",
1158                                     filename, linenum);
1159                 } else if (n != 1)
1160                         fatal("%s line %d: Illegal MaxStartups spec.",
1161                             filename, linenum);
1162                 else
1163                         options->max_startups = options->max_startups_begin;
1164                 break;
1165
1166         case sMaxAuthTries:
1167                 intptr = &options->max_authtries;
1168                 goto parse_int;
1169
1170         case sMaxSessions:
1171                 intptr = &options->max_sessions;
1172                 goto parse_int;
1173
1174         case sBanner:
1175                 charptr = &options->banner;
1176                 goto parse_filename;
1177
1178         /*
1179          * These options can contain %X options expanded at
1180          * connect time, so that you can specify paths like:
1181          *
1182          * AuthorizedKeysFile   /etc/ssh_keys/%u
1183          */
1184         case sAuthorizedKeysFile:
1185         case sAuthorizedKeysFile2:
1186                 charptr = (opcode == sAuthorizedKeysFile) ?
1187                     &options->authorized_keys_file :
1188                     &options->authorized_keys_file2;
1189                 goto parse_filename;
1190
1191         case sClientAliveInterval:
1192                 intptr = &options->client_alive_interval;
1193                 goto parse_time;
1194
1195         case sClientAliveCountMax:
1196                 intptr = &options->client_alive_count_max;
1197                 goto parse_int;
1198
1199         case sAcceptEnv:
1200                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1201                         if (strchr(arg, '=') != NULL)
1202                                 fatal("%s line %d: Invalid environment name.",
1203                                     filename, linenum);
1204                         if (options->num_accept_env >= MAX_ACCEPT_ENV)
1205                                 fatal("%s line %d: too many allow env.",
1206                                     filename, linenum);
1207                         if (!*activep)
1208                                 break;
1209                         options->accept_env[options->num_accept_env++] =
1210                             xstrdup(arg);
1211                 }
1212                 break;
1213
1214         case sPermitTunnel:
1215                 intptr = &options->permit_tun;
1216                 arg = strdelim(&cp);
1217                 if (!arg || *arg == '\0')
1218                         fatal("%s line %d: Missing yes/point-to-point/"
1219                             "ethernet/no argument.", filename, linenum);
1220                 value = -1;
1221                 for (i = 0; tunmode_desc[i].val != -1; i++)
1222                         if (strcmp(tunmode_desc[i].text, arg) == 0) {
1223                                 value = tunmode_desc[i].val;
1224                                 break;
1225                         }
1226                 if (value == -1)
1227                         fatal("%s line %d: Bad yes/point-to-point/ethernet/"
1228                             "no argument: %s", filename, linenum, arg);
1229                 if (*intptr == -1)
1230                         *intptr = value;
1231                 break;
1232
1233         case sMatch:
1234                 if (cmdline)
1235                         fatal("Match directive not supported as a command-line "
1236                            "option");
1237                 value = match_cfg_line(&cp, linenum, user, host, address);
1238                 if (value < 0)
1239                         fatal("%s line %d: Bad Match condition", filename,
1240                             linenum);
1241                 *activep = value;
1242                 break;
1243
1244         case sPermitOpen:
1245                 arg = strdelim(&cp);
1246                 if (!arg || *arg == '\0')
1247                         fatal("%s line %d: missing PermitOpen specification",
1248                             filename, linenum);
1249                 n = options->num_permitted_opens;       /* modified later */
1250                 if (strcmp(arg, "any") == 0) {
1251                         if (*activep && n == -1) {
1252                                 channel_clear_adm_permitted_opens();
1253                                 options->num_permitted_opens = 0;
1254                         }
1255                         break;
1256                 }
1257                 if (*activep && n == -1)
1258                         channel_clear_adm_permitted_opens();
1259                 for (; arg != NULL && *arg != '\0'; arg = strdelim(&cp)) {
1260                         p = hpdelim(&arg);
1261                         if (p == NULL)
1262                                 fatal("%s line %d: missing host in PermitOpen",
1263                                     filename, linenum);
1264                         p = cleanhostname(p);
1265                         if (arg == NULL || (port = a2port(arg)) == 0)
1266                                 fatal("%s line %d: bad port number in "
1267                                     "PermitOpen", filename, linenum);
1268                         if (*activep && n == -1)
1269                                 options->num_permitted_opens =
1270                                     channel_add_adm_permitted_opens(p, port);
1271                 }
1272                 break;
1273
1274         case sForceCommand:
1275                 if (cp == NULL)
1276                         fatal("%.200s line %d: Missing argument.", filename,
1277                             linenum);
1278                 len = strspn(cp, WHITESPACE);
1279                 if (*activep && options->adm_forced_command == NULL)
1280                         options->adm_forced_command = xstrdup(cp + len);
1281                 return 0;
1282
1283         case sChrootDirectory:
1284                 charptr = &options->chroot_directory;
1285
1286                 arg = strdelim(&cp);
1287                 if (!arg || *arg == '\0')
1288                         fatal("%s line %d: missing file name.",
1289                             filename, linenum);
1290                 if (*activep && *charptr == NULL)
1291                         *charptr = xstrdup(arg);
1292                 break;
1293
1294         case sVersionAddendum:
1295                 ssh_version_set_addendum(strtok(cp, "\n"));
1296                 do {
1297                         arg = strdelim(&cp);
1298                 } while (arg != NULL && *arg != '\0');
1299                 break;
1300
1301         case sDeprecated:
1302                 logit("%s line %d: Deprecated option %s",
1303                     filename, linenum, arg);
1304                 while (arg)
1305                     arg = strdelim(&cp);
1306                 break;
1307
1308         case sUnsupported:
1309                 logit("%s line %d: Unsupported option %s",
1310                     filename, linenum, arg);
1311                 while (arg)
1312                     arg = strdelim(&cp);
1313                 break;
1314
1315         default:
1316                 fatal("%s line %d: Missing handler for opcode %s (%d)",
1317                     filename, linenum, arg, opcode);
1318         }
1319         if ((arg = strdelim(&cp)) != NULL && *arg != '\0')
1320                 fatal("%s line %d: garbage at end of line; \"%.200s\".",
1321                     filename, linenum, arg);
1322         return 0;
1323 }
1324
1325 /* Reads the server configuration file. */
1326
1327 void
1328 load_server_config(const char *filename, Buffer *conf)
1329 {
1330         char line[1024], *cp;
1331         FILE *f;
1332
1333         debug2("%s: filename %s", __func__, filename);
1334         if ((f = fopen(filename, "r")) == NULL) {
1335                 perror(filename);
1336                 exit(1);
1337         }
1338         buffer_clear(conf);
1339         while (fgets(line, sizeof(line), f)) {
1340                 /*
1341                  * Trim out comments and strip whitespace
1342                  * NB - preserve newlines, they are needed to reproduce
1343                  * line numbers later for error messages
1344                  */
1345                 if ((cp = strchr(line, '#')) != NULL)
1346                         memcpy(cp, "\n", 2);
1347                 cp = line + strspn(line, " \t\r");
1348
1349                 buffer_append(conf, cp, strlen(cp));
1350         }
1351         buffer_append(conf, "\0", 1);
1352         fclose(f);
1353         debug2("%s: done config len = %d", __func__, buffer_len(conf));
1354 }
1355
1356 void
1357 parse_server_match_config(ServerOptions *options, const char *user,
1358     const char *host, const char *address)
1359 {
1360         ServerOptions mo;
1361
1362         initialize_server_options(&mo);
1363         parse_server_config(&mo, "reprocess config", &cfg, user, host, address);
1364         copy_set_server_options(options, &mo, 0);
1365 }
1366
1367 /* Helper macros */
1368 #define M_CP_INTOPT(n) do {\
1369         if (src->n != -1) \
1370                 dst->n = src->n; \
1371 } while (0)
1372 #define M_CP_STROPT(n) do {\
1373         if (src->n != NULL) { \
1374                 if (dst->n != NULL) \
1375                         xfree(dst->n); \
1376                 dst->n = src->n; \
1377         } \
1378 } while(0)
1379
1380 /*
1381  * Copy any supported values that are set.
1382  *
1383  * If the preauth flag is set, we do not bother copying the the string or
1384  * array values that are not used pre-authentication, because any that we
1385  * do use must be explictly sent in mm_getpwnamallow().
1386  */
1387 void
1388 copy_set_server_options(ServerOptions *dst, ServerOptions *src, int preauth)
1389 {
1390         M_CP_INTOPT(password_authentication);
1391         M_CP_INTOPT(gss_authentication);
1392         M_CP_INTOPT(rsa_authentication);
1393         M_CP_INTOPT(pubkey_authentication);
1394         M_CP_INTOPT(kerberos_authentication);
1395         M_CP_INTOPT(hostbased_authentication);
1396         M_CP_INTOPT(kbd_interactive_authentication);
1397         M_CP_INTOPT(permit_root_login);
1398
1399         M_CP_INTOPT(allow_tcp_forwarding);
1400         M_CP_INTOPT(allow_agent_forwarding);
1401         M_CP_INTOPT(gateway_ports);
1402         M_CP_INTOPT(x11_display_offset);
1403         M_CP_INTOPT(x11_forwarding);
1404         M_CP_INTOPT(x11_use_localhost);
1405         M_CP_INTOPT(max_sessions);
1406         M_CP_INTOPT(max_authtries);
1407
1408         M_CP_STROPT(banner);
1409         if (preauth)
1410                 return;
1411         M_CP_STROPT(adm_forced_command);
1412         M_CP_STROPT(chroot_directory);
1413 }
1414
1415 #undef M_CP_INTOPT
1416 #undef M_CP_STROPT
1417
1418 void
1419 parse_server_config(ServerOptions *options, const char *filename, Buffer *conf,
1420     const char *user, const char *host, const char *address)
1421 {
1422         int active, linenum, bad_options = 0;
1423         char *cp, *obuf, *cbuf;
1424
1425         debug2("%s: config %s len %d", __func__, filename, buffer_len(conf));
1426
1427         obuf = cbuf = xstrdup(buffer_ptr(conf));
1428         active = user ? 0 : 1;
1429         linenum = 1;
1430         while ((cp = strsep(&cbuf, "\n")) != NULL) {
1431                 if (process_server_config_line(options, cp, filename,
1432                     linenum++, &active, user, host, address) != 0)
1433                         bad_options++;
1434         }
1435         xfree(obuf);
1436         if (bad_options > 0)
1437                 fatal("%s: terminating, %d bad configuration options",
1438                     filename, bad_options);
1439 }
1440
1441 static const char *
1442 fmt_intarg(ServerOpCodes code, int val)
1443 {
1444         if (code == sAddressFamily) {
1445                 switch (val) {
1446                 case AF_INET:
1447                         return "inet";
1448                 case AF_INET6:
1449                         return "inet6";
1450                 case AF_UNSPEC:
1451                         return "any";
1452                 default:
1453                         return "UNKNOWN";
1454                 }
1455         }
1456         if (code == sPermitRootLogin) {
1457                 switch (val) {
1458                 case PERMIT_NO_PASSWD:
1459                         return "without-passord";
1460                 case PERMIT_FORCED_ONLY:
1461                         return "forced-commands-only";
1462                 case PERMIT_YES:
1463                         return "yes";
1464                 }
1465         }
1466         if (code == sProtocol) {
1467                 switch (val) {
1468                 case SSH_PROTO_1:
1469                         return "1";
1470                 case SSH_PROTO_2:
1471                         return "2";
1472                 case (SSH_PROTO_1|SSH_PROTO_2):
1473                         return "2,1";
1474                 default:
1475                         return "UNKNOWN";
1476                 }
1477         }
1478         if (code == sGatewayPorts && val == 2)
1479                 return "clientspecified";
1480         if (code == sCompression && val == COMP_DELAYED)
1481                 return "delayed";
1482         switch (val) {
1483         case -1:
1484                 return "unset";
1485         case 0:
1486                 return "no";
1487         case 1:
1488                 return "yes";
1489         }
1490         return "UNKNOWN";
1491 }
1492
1493 static const char *
1494 lookup_opcode_name(ServerOpCodes code)
1495 {
1496         u_int i;
1497
1498         for (i = 0; keywords[i].name != NULL; i++)
1499                 if (keywords[i].opcode == code)
1500                         return(keywords[i].name);
1501         return "UNKNOWN";
1502 }
1503
1504 static void
1505 dump_cfg_int(ServerOpCodes code, int val)
1506 {
1507         printf("%s %d\n", lookup_opcode_name(code), val);
1508 }
1509
1510 static void
1511 dump_cfg_fmtint(ServerOpCodes code, int val)
1512 {
1513         printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
1514 }
1515
1516 static void
1517 dump_cfg_string(ServerOpCodes code, const char *val)
1518 {
1519         if (val == NULL)
1520                 return;
1521         printf("%s %s\n", lookup_opcode_name(code), val);
1522 }
1523
1524 static void
1525 dump_cfg_strarray(ServerOpCodes code, u_int count, char **vals)
1526 {
1527         u_int i;
1528
1529         for (i = 0; i < count; i++)
1530                 printf("%s %s\n", lookup_opcode_name(code),  vals[i]);
1531 }
1532
1533 void
1534 dump_config(ServerOptions *o)
1535 {
1536         u_int i;
1537         int ret;
1538         struct addrinfo *ai;
1539         char addr[NI_MAXHOST], port[NI_MAXSERV], *s = NULL;
1540
1541         /* these are usually at the top of the config */
1542         for (i = 0; i < o->num_ports; i++)
1543                 printf("port %d\n", o->ports[i]);
1544         dump_cfg_fmtint(sProtocol, o->protocol);
1545         dump_cfg_fmtint(sAddressFamily, o->address_family);
1546
1547         /* ListenAddress must be after Port */
1548         for (ai = o->listen_addrs; ai; ai = ai->ai_next) {
1549                 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1550                     sizeof(addr), port, sizeof(port),
1551                     NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1552                         error("getnameinfo failed: %.100s",
1553                             (ret != EAI_SYSTEM) ? gai_strerror(ret) :
1554                             strerror(errno));
1555                 } else {
1556                         if (ai->ai_family == AF_INET6)
1557                                 printf("listenaddress [%s]:%s\n", addr, port);
1558                         else
1559                                 printf("listenaddress %s:%s\n", addr, port);
1560                 }
1561         }
1562
1563         /* integer arguments */
1564         dump_cfg_int(sServerKeyBits, o->server_key_bits);
1565         dump_cfg_int(sLoginGraceTime, o->login_grace_time);
1566         dump_cfg_int(sKeyRegenerationTime, o->key_regeneration_time);
1567         dump_cfg_int(sX11DisplayOffset, o->x11_display_offset);
1568         dump_cfg_int(sMaxAuthTries, o->max_authtries);
1569         dump_cfg_int(sClientAliveInterval, o->client_alive_interval);
1570         dump_cfg_int(sClientAliveCountMax, o->client_alive_count_max);
1571
1572         /* formatted integer arguments */
1573         dump_cfg_fmtint(sPermitRootLogin, o->permit_root_login);
1574         dump_cfg_fmtint(sIgnoreRhosts, o->ignore_rhosts);
1575         dump_cfg_fmtint(sIgnoreUserKnownHosts, o->ignore_user_known_hosts);
1576         dump_cfg_fmtint(sRhostsRSAAuthentication, o->rhosts_rsa_authentication);
1577         dump_cfg_fmtint(sHostbasedAuthentication, o->hostbased_authentication);
1578         dump_cfg_fmtint(sHostbasedUsesNameFromPacketOnly,
1579             o->hostbased_uses_name_from_packet_only);
1580         dump_cfg_fmtint(sRSAAuthentication, o->rsa_authentication);
1581         dump_cfg_fmtint(sPubkeyAuthentication, o->pubkey_authentication);
1582         dump_cfg_fmtint(sKerberosAuthentication, o->kerberos_authentication);
1583         dump_cfg_fmtint(sKerberosOrLocalPasswd, o->kerberos_or_local_passwd);
1584         dump_cfg_fmtint(sKerberosTicketCleanup, o->kerberos_ticket_cleanup);
1585         dump_cfg_fmtint(sKerberosGetAFSToken, o->kerberos_get_afs_token);
1586         dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
1587         dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
1588         dump_cfg_fmtint(sPasswordAuthentication, o->password_authentication);
1589         dump_cfg_fmtint(sKbdInteractiveAuthentication,
1590             o->kbd_interactive_authentication);
1591         dump_cfg_fmtint(sChallengeResponseAuthentication,
1592             o->challenge_response_authentication);
1593         dump_cfg_fmtint(sPrintMotd, o->print_motd);
1594         dump_cfg_fmtint(sPrintLastLog, o->print_lastlog);
1595         dump_cfg_fmtint(sX11Forwarding, o->x11_forwarding);
1596         dump_cfg_fmtint(sX11UseLocalhost, o->x11_use_localhost);
1597         dump_cfg_fmtint(sStrictModes, o->strict_modes);
1598         dump_cfg_fmtint(sTCPKeepAlive, o->tcp_keep_alive);
1599         dump_cfg_fmtint(sEmptyPasswd, o->permit_empty_passwd);
1600         dump_cfg_fmtint(sPermitUserEnvironment, o->permit_user_env);
1601         dump_cfg_fmtint(sUseLogin, o->use_login);
1602         dump_cfg_fmtint(sCompression, o->compression);
1603         dump_cfg_fmtint(sGatewayPorts, o->gateway_ports);
1604         dump_cfg_fmtint(sUseDNS, o->use_dns);
1605         dump_cfg_fmtint(sAllowTcpForwarding, o->allow_tcp_forwarding);
1606         dump_cfg_fmtint(sUsePrivilegeSeparation, use_privsep);
1607
1608         /* string arguments */
1609         dump_cfg_string(sPidFile, o->pid_file);
1610         dump_cfg_string(sXAuthLocation, o->xauth_location);
1611         dump_cfg_string(sCiphers, o->ciphers);
1612         dump_cfg_string(sMacs, o->macs);
1613         dump_cfg_string(sBanner, o->banner);
1614         dump_cfg_string(sAuthorizedKeysFile, o->authorized_keys_file);
1615         dump_cfg_string(sAuthorizedKeysFile2, o->authorized_keys_file2);
1616         dump_cfg_string(sForceCommand, o->adm_forced_command);
1617
1618         /* string arguments requiring a lookup */
1619         dump_cfg_string(sLogLevel, log_level_name(o->log_level));
1620         dump_cfg_string(sLogFacility, log_facility_name(o->log_facility));
1621
1622         /* string array arguments */
1623         dump_cfg_strarray(sHostKeyFile, o->num_host_key_files,
1624              o->host_key_files);
1625         dump_cfg_strarray(sAllowUsers, o->num_allow_users, o->allow_users);
1626         dump_cfg_strarray(sDenyUsers, o->num_deny_users, o->deny_users);
1627         dump_cfg_strarray(sAllowGroups, o->num_allow_groups, o->allow_groups);
1628         dump_cfg_strarray(sDenyGroups, o->num_deny_groups, o->deny_groups);
1629         dump_cfg_strarray(sAcceptEnv, o->num_accept_env, o->accept_env);
1630
1631         /* other arguments */
1632         for (i = 0; i < o->num_subsystems; i++)
1633                 printf("subsystem %s %s\n", o->subsystem_name[i],
1634                     o->subsystem_args[i]);
1635
1636         printf("maxstartups %d:%d:%d\n", o->max_startups_begin,
1637             o->max_startups_rate, o->max_startups);
1638
1639         for (i = 0; tunmode_desc[i].val != -1; i++)
1640                 if (tunmode_desc[i].val == o->permit_tun) {
1641                         s = tunmode_desc[i].text;
1642                         break;
1643                 }
1644         dump_cfg_string(sPermitTunnel, s);
1645
1646         printf("permitopen");
1647         channel_print_adm_permitted_opens();
1648         printf("\n");
1649 }