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