]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - crypto/openssh/servconf.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.git] / crypto / openssh / servconf.c
1 /* $OpenBSD: servconf.c,v 1.204 2010/03/04 10:36:03 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;
478
479         expanded = tilde_expand_filename(path, getuid());
480         if (*expanded == '/')
481                 return expanded;
482         if ((cwd = getcwd(NULL, 0)) == NULL)
483                 fatal("%s: getcwd: %s", __func__, strerror(errno));
484         xasprintf(&ret, "%s/%s", cwd, expanded);
485         xfree(cwd);
486         xfree(expanded);
487         return ret;
488 }
489
490 static void
491 add_listen_addr(ServerOptions *options, char *addr, int port)
492 {
493         u_int i;
494
495         if (options->num_ports == 0)
496                 options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
497         if (options->address_family == -1)
498                 options->address_family = AF_UNSPEC;
499         if (port == 0)
500                 for (i = 0; i < options->num_ports; i++)
501                         add_one_listen_addr(options, addr, options->ports[i]);
502         else
503                 add_one_listen_addr(options, addr, port);
504 }
505
506 static void
507 add_one_listen_addr(ServerOptions *options, char *addr, int port)
508 {
509         struct addrinfo hints, *ai, *aitop;
510         char strport[NI_MAXSERV];
511         int gaierr;
512
513         memset(&hints, 0, sizeof(hints));
514         hints.ai_family = options->address_family;
515         hints.ai_socktype = SOCK_STREAM;
516         hints.ai_flags = (addr == NULL) ? AI_PASSIVE : 0;
517         snprintf(strport, sizeof strport, "%d", port);
518         if ((gaierr = getaddrinfo(addr, strport, &hints, &aitop)) != 0)
519                 fatal("bad addr or host: %s (%s)",
520                     addr ? addr : "<NULL>",
521                     ssh_gai_strerror(gaierr));
522         for (ai = aitop; ai->ai_next; ai = ai->ai_next)
523                 ;
524         ai->ai_next = options->listen_addrs;
525         options->listen_addrs = aitop;
526 }
527
528 /*
529  * The strategy for the Match blocks is that the config file is parsed twice.
530  *
531  * The first time is at startup.  activep is initialized to 1 and the
532  * directives in the global context are processed and acted on.  Hitting a
533  * Match directive unsets activep and the directives inside the block are
534  * checked for syntax only.
535  *
536  * The second time is after a connection has been established but before
537  * authentication.  activep is initialized to 2 and global config directives
538  * are ignored since they have already been processed.  If the criteria in a
539  * Match block is met, activep is set and the subsequent directives
540  * processed and actioned until EOF or another Match block unsets it.  Any
541  * options set are copied into the main server config.
542  *
543  * Potential additions/improvements:
544  *  - Add Match support for pre-kex directives, eg Protocol, Ciphers.
545  *
546  *  - Add a Tag directive (idea from David Leonard) ala pf, eg:
547  *      Match Address 192.168.0.*
548  *              Tag trusted
549  *      Match Group wheel
550  *              Tag trusted
551  *      Match Tag trusted
552  *              AllowTcpForwarding yes
553  *              GatewayPorts clientspecified
554  *              [...]
555  *
556  *  - Add a PermittedChannelRequests directive
557  *      Match Group shell
558  *              PermittedChannelRequests session,forwarded-tcpip
559  */
560
561 static int
562 match_cfg_line_group(const char *grps, int line, const char *user)
563 {
564         int result = 0;
565         struct passwd *pw;
566
567         if (user == NULL)
568                 goto out;
569
570         if ((pw = getpwnam(user)) == NULL) {
571                 debug("Can't match group at line %d because user %.100s does "
572                     "not exist", line, user);
573         } else if (ga_init(pw->pw_name, pw->pw_gid) == 0) {
574                 debug("Can't Match group because user %.100s not in any group "
575                     "at line %d", user, line);
576         } else if (ga_match_pattern_list(grps) != 1) {
577                 debug("user %.100s does not match group list %.100s at line %d",
578                     user, grps, line);
579         } else {
580                 debug("user %.100s matched group list %.100s at line %d", user,
581                     grps, line);
582                 result = 1;
583         }
584 out:
585         ga_free();
586         return result;
587 }
588
589 static int
590 match_cfg_line(char **condition, int line, const char *user, const char *host,
591     const char *address)
592 {
593         int result = 1;
594         char *arg, *attrib, *cp = *condition;
595         size_t len;
596
597         if (user == NULL)
598                 debug3("checking syntax for 'Match %s'", cp);
599         else
600                 debug3("checking match for '%s' user %s host %s addr %s", cp,
601                     user ? user : "(null)", host ? host : "(null)",
602                     address ? address : "(null)");
603
604         while ((attrib = strdelim(&cp)) && *attrib != '\0') {
605                 if ((arg = strdelim(&cp)) == NULL || *arg == '\0') {
606                         error("Missing Match criteria for %s", attrib);
607                         return -1;
608                 }
609                 len = strlen(arg);
610                 if (strcasecmp(attrib, "user") == 0) {
611                         if (!user) {
612                                 result = 0;
613                                 continue;
614                         }
615                         if (match_pattern_list(user, arg, len, 0) != 1)
616                                 result = 0;
617                         else
618                                 debug("user %.100s matched 'User %.100s' at "
619                                     "line %d", user, arg, line);
620                 } else if (strcasecmp(attrib, "group") == 0) {
621                         switch (match_cfg_line_group(arg, line, user)) {
622                         case -1:
623                                 return -1;
624                         case 0:
625                                 result = 0;
626                         }
627                 } else if (strcasecmp(attrib, "host") == 0) {
628                         if (!host) {
629                                 result = 0;
630                                 continue;
631                         }
632                         if (match_hostname(host, arg, len) != 1)
633                                 result = 0;
634                         else
635                                 debug("connection from %.100s matched 'Host "
636                                     "%.100s' at line %d", host, arg, line);
637                 } else if (strcasecmp(attrib, "address") == 0) {
638                         switch (addr_match_list(address, arg)) {
639                         case 1:
640                                 debug("connection from %.100s matched 'Address "
641                                     "%.100s' at line %d", address, arg, line);
642                                 break;
643                         case 0:
644                         case -1:
645                                 result = 0;
646                                 break;
647                         case -2:
648                                 return -1;
649                         }
650                 } else {
651                         error("Unsupported Match attribute %s", attrib);
652                         return -1;
653                 }
654         }
655         if (user != NULL)
656                 debug3("match %sfound", result ? "" : "not ");
657         *condition = cp;
658         return result;
659 }
660
661 #define WHITESPACE " \t\r\n"
662
663 int
664 process_server_config_line(ServerOptions *options, char *line,
665     const char *filename, int linenum, int *activep, const char *user,
666     const char *host, const char *address)
667 {
668         char *cp, **charptr, *arg, *p;
669         int cmdline = 0, *intptr, value, n;
670         SyslogFacility *log_facility_ptr;
671         LogLevel *log_level_ptr;
672         ServerOpCodes opcode;
673         int port;
674         u_int i, flags = 0;
675         size_t len;
676
677         cp = line;
678         if ((arg = strdelim(&cp)) == NULL)
679                 return 0;
680         /* Ignore leading whitespace */
681         if (*arg == '\0')
682                 arg = strdelim(&cp);
683         if (!arg || !*arg || *arg == '#')
684                 return 0;
685         intptr = NULL;
686         charptr = NULL;
687         opcode = parse_token(arg, filename, linenum, &flags);
688
689         if (activep == NULL) { /* We are processing a command line directive */
690                 cmdline = 1;
691                 activep = &cmdline;
692         }
693         if (*activep && opcode != sMatch)
694                 debug3("%s:%d setting %s %s", filename, linenum, arg, cp);
695         if (*activep == 0 && !(flags & SSHCFG_MATCH)) {
696                 if (user == NULL) {
697                         fatal("%s line %d: Directive '%s' is not allowed "
698                             "within a Match block", filename, linenum, arg);
699                 } else { /* this is a directive we have already processed */
700                         while (arg)
701                                 arg = strdelim(&cp);
702                         return 0;
703                 }
704         }
705
706         switch (opcode) {
707         /* Portable-specific options */
708         case sUsePAM:
709                 intptr = &options->use_pam;
710                 goto parse_flag;
711
712         /* Standard Options */
713         case sBadOption:
714                 return -1;
715         case sPort:
716                 /* ignore ports from configfile if cmdline specifies ports */
717                 if (options->ports_from_cmdline)
718                         return 0;
719                 if (options->listen_addrs != NULL)
720                         fatal("%s line %d: ports must be specified before "
721                             "ListenAddress.", filename, linenum);
722                 if (options->num_ports >= MAX_PORTS)
723                         fatal("%s line %d: too many ports.",
724                             filename, linenum);
725                 arg = strdelim(&cp);
726                 if (!arg || *arg == '\0')
727                         fatal("%s line %d: missing port number.",
728                             filename, linenum);
729                 options->ports[options->num_ports++] = a2port(arg);
730                 if (options->ports[options->num_ports-1] <= 0)
731                         fatal("%s line %d: Badly formatted port number.",
732                             filename, linenum);
733                 break;
734
735         case sServerKeyBits:
736                 intptr = &options->server_key_bits;
737  parse_int:
738                 arg = strdelim(&cp);
739                 if (!arg || *arg == '\0')
740                         fatal("%s line %d: missing integer value.",
741                             filename, linenum);
742                 value = atoi(arg);
743                 if (*activep && *intptr == -1)
744                         *intptr = value;
745                 break;
746
747         case sLoginGraceTime:
748                 intptr = &options->login_grace_time;
749  parse_time:
750                 arg = strdelim(&cp);
751                 if (!arg || *arg == '\0')
752                         fatal("%s line %d: missing time value.",
753                             filename, linenum);
754                 if ((value = convtime(arg)) == -1)
755                         fatal("%s line %d: invalid time value.",
756                             filename, linenum);
757                 if (*intptr == -1)
758                         *intptr = value;
759                 break;
760
761         case sKeyRegenerationTime:
762                 intptr = &options->key_regeneration_time;
763                 goto parse_time;
764
765         case sListenAddress:
766                 arg = strdelim(&cp);
767                 if (arg == NULL || *arg == '\0')
768                         fatal("%s line %d: missing address",
769                             filename, linenum);
770                 /* check for bare IPv6 address: no "[]" and 2 or more ":" */
771                 if (strchr(arg, '[') == NULL && (p = strchr(arg, ':')) != NULL
772                     && strchr(p+1, ':') != NULL) {
773                         add_listen_addr(options, arg, 0);
774                         break;
775                 }
776                 p = hpdelim(&arg);
777                 if (p == NULL)
778                         fatal("%s line %d: bad address:port usage",
779                             filename, linenum);
780                 p = cleanhostname(p);
781                 if (arg == NULL)
782                         port = 0;
783                 else if ((port = a2port(arg)) <= 0)
784                         fatal("%s line %d: bad port number", filename, linenum);
785
786                 add_listen_addr(options, p, port);
787
788                 break;
789
790         case sAddressFamily:
791                 arg = strdelim(&cp);
792                 if (!arg || *arg == '\0')
793                         fatal("%s line %d: missing address family.",
794                             filename, linenum);
795                 intptr = &options->address_family;
796                 if (options->listen_addrs != NULL)
797                         fatal("%s line %d: address family must be specified before "
798                             "ListenAddress.", filename, linenum);
799                 if (strcasecmp(arg, "inet") == 0)
800                         value = AF_INET;
801                 else if (strcasecmp(arg, "inet6") == 0)
802                         value = AF_INET6;
803                 else if (strcasecmp(arg, "any") == 0)
804                         value = AF_UNSPEC;
805                 else
806                         fatal("%s line %d: unsupported address family \"%s\".",
807                             filename, linenum, arg);
808                 if (*intptr == -1)
809                         *intptr = value;
810                 break;
811
812         case sHostKeyFile:
813                 intptr = &options->num_host_key_files;
814                 if (*intptr >= MAX_HOSTKEYS)
815                         fatal("%s line %d: too many host keys specified (max %d).",
816                             filename, linenum, MAX_HOSTKEYS);
817                 charptr = &options->host_key_files[*intptr];
818  parse_filename:
819                 arg = strdelim(&cp);
820                 if (!arg || *arg == '\0')
821                         fatal("%s line %d: missing file name.",
822                             filename, linenum);
823                 if (*activep && *charptr == NULL) {
824                         *charptr = derelativise_path(arg);
825                         /* increase optional counter */
826                         if (intptr != NULL)
827                                 *intptr = *intptr + 1;
828                 }
829                 break;
830
831         case sHostCertificate:
832                 intptr = &options->num_host_cert_files;
833                 if (*intptr >= MAX_HOSTKEYS)
834                         fatal("%s line %d: too many host certificates "
835                             "specified (max %d).", filename, linenum,
836                             MAX_HOSTCERTS);
837                 charptr = &options->host_cert_files[*intptr];
838                 goto parse_filename;
839                 break;
840
841         case sPidFile:
842                 charptr = &options->pid_file;
843                 goto parse_filename;
844
845         case sPermitRootLogin:
846                 intptr = &options->permit_root_login;
847                 arg = strdelim(&cp);
848                 if (!arg || *arg == '\0')
849                         fatal("%s line %d: missing yes/"
850                             "without-password/forced-commands-only/no "
851                             "argument.", filename, linenum);
852                 value = 0;      /* silence compiler */
853                 if (strcmp(arg, "without-password") == 0)
854                         value = PERMIT_NO_PASSWD;
855                 else if (strcmp(arg, "forced-commands-only") == 0)
856                         value = PERMIT_FORCED_ONLY;
857                 else if (strcmp(arg, "yes") == 0)
858                         value = PERMIT_YES;
859                 else if (strcmp(arg, "no") == 0)
860                         value = PERMIT_NO;
861                 else
862                         fatal("%s line %d: Bad yes/"
863                             "without-password/forced-commands-only/no "
864                             "argument: %s", filename, linenum, arg);
865                 if (*activep && *intptr == -1)
866                         *intptr = value;
867                 break;
868
869         case sIgnoreRhosts:
870                 intptr = &options->ignore_rhosts;
871  parse_flag:
872                 arg = strdelim(&cp);
873                 if (!arg || *arg == '\0')
874                         fatal("%s line %d: missing yes/no argument.",
875                             filename, linenum);
876                 value = 0;      /* silence compiler */
877                 if (strcmp(arg, "yes") == 0)
878                         value = 1;
879                 else if (strcmp(arg, "no") == 0)
880                         value = 0;
881                 else
882                         fatal("%s line %d: Bad yes/no argument: %s",
883                                 filename, linenum, arg);
884                 if (*activep && *intptr == -1)
885                         *intptr = value;
886                 break;
887
888         case sIgnoreUserKnownHosts:
889                 intptr = &options->ignore_user_known_hosts;
890                 goto parse_flag;
891
892         case sRhostsRSAAuthentication:
893                 intptr = &options->rhosts_rsa_authentication;
894                 goto parse_flag;
895
896         case sHostbasedAuthentication:
897                 intptr = &options->hostbased_authentication;
898                 goto parse_flag;
899
900         case sHostbasedUsesNameFromPacketOnly:
901                 intptr = &options->hostbased_uses_name_from_packet_only;
902                 goto parse_flag;
903
904         case sRSAAuthentication:
905                 intptr = &options->rsa_authentication;
906                 goto parse_flag;
907
908         case sPubkeyAuthentication:
909                 intptr = &options->pubkey_authentication;
910                 goto parse_flag;
911
912         case sKerberosAuthentication:
913                 intptr = &options->kerberos_authentication;
914                 goto parse_flag;
915
916         case sKerberosOrLocalPasswd:
917                 intptr = &options->kerberos_or_local_passwd;
918                 goto parse_flag;
919
920         case sKerberosTicketCleanup:
921                 intptr = &options->kerberos_ticket_cleanup;
922                 goto parse_flag;
923
924         case sKerberosGetAFSToken:
925                 intptr = &options->kerberos_get_afs_token;
926                 goto parse_flag;
927
928         case sGssAuthentication:
929                 intptr = &options->gss_authentication;
930                 goto parse_flag;
931
932         case sGssCleanupCreds:
933                 intptr = &options->gss_cleanup_creds;
934                 goto parse_flag;
935
936         case sPasswordAuthentication:
937                 intptr = &options->password_authentication;
938                 goto parse_flag;
939
940         case sZeroKnowledgePasswordAuthentication:
941                 intptr = &options->zero_knowledge_password_authentication;
942                 goto parse_flag;
943
944         case sKbdInteractiveAuthentication:
945                 intptr = &options->kbd_interactive_authentication;
946                 goto parse_flag;
947
948         case sChallengeResponseAuthentication:
949                 intptr = &options->challenge_response_authentication;
950                 goto parse_flag;
951
952         case sPrintMotd:
953                 intptr = &options->print_motd;
954                 goto parse_flag;
955
956         case sPrintLastLog:
957                 intptr = &options->print_lastlog;
958                 goto parse_flag;
959
960         case sX11Forwarding:
961                 intptr = &options->x11_forwarding;
962                 goto parse_flag;
963
964         case sX11DisplayOffset:
965                 intptr = &options->x11_display_offset;
966                 goto parse_int;
967
968         case sX11UseLocalhost:
969                 intptr = &options->x11_use_localhost;
970                 goto parse_flag;
971
972         case sXAuthLocation:
973                 charptr = &options->xauth_location;
974                 goto parse_filename;
975
976         case sStrictModes:
977                 intptr = &options->strict_modes;
978                 goto parse_flag;
979
980         case sTCPKeepAlive:
981                 intptr = &options->tcp_keep_alive;
982                 goto parse_flag;
983
984         case sEmptyPasswd:
985                 intptr = &options->permit_empty_passwd;
986                 goto parse_flag;
987
988         case sPermitUserEnvironment:
989                 intptr = &options->permit_user_env;
990                 goto parse_flag;
991
992         case sUseLogin:
993                 intptr = &options->use_login;
994                 goto parse_flag;
995
996         case sCompression:
997                 intptr = &options->compression;
998                 arg = strdelim(&cp);
999                 if (!arg || *arg == '\0')
1000                         fatal("%s line %d: missing yes/no/delayed "
1001                             "argument.", filename, linenum);
1002                 value = 0;      /* silence compiler */
1003                 if (strcmp(arg, "delayed") == 0)
1004                         value = COMP_DELAYED;
1005                 else if (strcmp(arg, "yes") == 0)
1006                         value = COMP_ZLIB;
1007                 else if (strcmp(arg, "no") == 0)
1008                         value = COMP_NONE;
1009                 else
1010                         fatal("%s line %d: Bad yes/no/delayed "
1011                             "argument: %s", filename, linenum, arg);
1012                 if (*intptr == -1)
1013                         *intptr = value;
1014                 break;
1015
1016         case sGatewayPorts:
1017                 intptr = &options->gateway_ports;
1018                 arg = strdelim(&cp);
1019                 if (!arg || *arg == '\0')
1020                         fatal("%s line %d: missing yes/no/clientspecified "
1021                             "argument.", filename, linenum);
1022                 value = 0;      /* silence compiler */
1023                 if (strcmp(arg, "clientspecified") == 0)
1024                         value = 2;
1025                 else if (strcmp(arg, "yes") == 0)
1026                         value = 1;
1027                 else if (strcmp(arg, "no") == 0)
1028                         value = 0;
1029                 else
1030                         fatal("%s line %d: Bad yes/no/clientspecified "
1031                             "argument: %s", filename, linenum, arg);
1032                 if (*activep && *intptr == -1)
1033                         *intptr = value;
1034                 break;
1035
1036         case sUseDNS:
1037                 intptr = &options->use_dns;
1038                 goto parse_flag;
1039
1040         case sLogFacility:
1041                 log_facility_ptr = &options->log_facility;
1042                 arg = strdelim(&cp);
1043                 value = log_facility_number(arg);
1044                 if (value == SYSLOG_FACILITY_NOT_SET)
1045                         fatal("%.200s line %d: unsupported log facility '%s'",
1046                             filename, linenum, arg ? arg : "<NONE>");
1047                 if (*log_facility_ptr == -1)
1048                         *log_facility_ptr = (SyslogFacility) value;
1049                 break;
1050
1051         case sLogLevel:
1052                 log_level_ptr = &options->log_level;
1053                 arg = strdelim(&cp);
1054                 value = log_level_number(arg);
1055                 if (value == SYSLOG_LEVEL_NOT_SET)
1056                         fatal("%.200s line %d: unsupported log level '%s'",
1057                             filename, linenum, arg ? arg : "<NONE>");
1058                 if (*log_level_ptr == -1)
1059                         *log_level_ptr = (LogLevel) value;
1060                 break;
1061
1062         case sAllowTcpForwarding:
1063                 intptr = &options->allow_tcp_forwarding;
1064                 goto parse_flag;
1065
1066         case sAllowAgentForwarding:
1067                 intptr = &options->allow_agent_forwarding;
1068                 goto parse_flag;
1069
1070         case sUsePrivilegeSeparation:
1071                 intptr = &use_privsep;
1072                 goto parse_flag;
1073
1074         case sAllowUsers:
1075                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1076                         if (options->num_allow_users >= MAX_ALLOW_USERS)
1077                                 fatal("%s line %d: too many allow users.",
1078                                     filename, linenum);
1079                         options->allow_users[options->num_allow_users++] =
1080                             xstrdup(arg);
1081                 }
1082                 break;
1083
1084         case sDenyUsers:
1085                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1086                         if (options->num_deny_users >= MAX_DENY_USERS)
1087                                 fatal("%s line %d: too many deny users.",
1088                                     filename, linenum);
1089                         options->deny_users[options->num_deny_users++] =
1090                             xstrdup(arg);
1091                 }
1092                 break;
1093
1094         case sAllowGroups:
1095                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1096                         if (options->num_allow_groups >= MAX_ALLOW_GROUPS)
1097                                 fatal("%s line %d: too many allow groups.",
1098                                     filename, linenum);
1099                         options->allow_groups[options->num_allow_groups++] =
1100                             xstrdup(arg);
1101                 }
1102                 break;
1103
1104         case sDenyGroups:
1105                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1106                         if (options->num_deny_groups >= MAX_DENY_GROUPS)
1107                                 fatal("%s line %d: too many deny groups.",
1108                                     filename, linenum);
1109                         options->deny_groups[options->num_deny_groups++] = xstrdup(arg);
1110                 }
1111                 break;
1112
1113         case sCiphers:
1114                 arg = strdelim(&cp);
1115                 if (!arg || *arg == '\0')
1116                         fatal("%s line %d: Missing argument.", filename, linenum);
1117                 if (!ciphers_valid(arg))
1118                         fatal("%s line %d: Bad SSH2 cipher spec '%s'.",
1119                             filename, linenum, arg ? arg : "<NONE>");
1120                 if (options->ciphers == NULL)
1121                         options->ciphers = xstrdup(arg);
1122                 break;
1123
1124         case sMacs:
1125                 arg = strdelim(&cp);
1126                 if (!arg || *arg == '\0')
1127                         fatal("%s line %d: Missing argument.", filename, linenum);
1128                 if (!mac_valid(arg))
1129                         fatal("%s line %d: Bad SSH2 mac spec '%s'.",
1130                             filename, linenum, arg ? arg : "<NONE>");
1131                 if (options->macs == NULL)
1132                         options->macs = xstrdup(arg);
1133                 break;
1134
1135         case sProtocol:
1136                 intptr = &options->protocol;
1137                 arg = strdelim(&cp);
1138                 if (!arg || *arg == '\0')
1139                         fatal("%s line %d: Missing argument.", filename, linenum);
1140                 value = proto_spec(arg);
1141                 if (value == SSH_PROTO_UNKNOWN)
1142                         fatal("%s line %d: Bad protocol spec '%s'.",
1143                             filename, linenum, arg ? arg : "<NONE>");
1144                 if (*intptr == SSH_PROTO_UNKNOWN)
1145                         *intptr = value;
1146                 break;
1147
1148         case sSubsystem:
1149                 if (options->num_subsystems >= MAX_SUBSYSTEMS) {
1150                         fatal("%s line %d: too many subsystems defined.",
1151                             filename, linenum);
1152                 }
1153                 arg = strdelim(&cp);
1154                 if (!arg || *arg == '\0')
1155                         fatal("%s line %d: Missing subsystem name.",
1156                             filename, linenum);
1157                 if (!*activep) {
1158                         arg = strdelim(&cp);
1159                         break;
1160                 }
1161                 for (i = 0; i < options->num_subsystems; i++)
1162                         if (strcmp(arg, options->subsystem_name[i]) == 0)
1163                                 fatal("%s line %d: Subsystem '%s' already defined.",
1164                                     filename, linenum, arg);
1165                 options->subsystem_name[options->num_subsystems] = xstrdup(arg);
1166                 arg = strdelim(&cp);
1167                 if (!arg || *arg == '\0')
1168                         fatal("%s line %d: Missing subsystem command.",
1169                             filename, linenum);
1170                 options->subsystem_command[options->num_subsystems] = xstrdup(arg);
1171
1172                 /* Collect arguments (separate to executable) */
1173                 p = xstrdup(arg);
1174                 len = strlen(p) + 1;
1175                 while ((arg = strdelim(&cp)) != NULL && *arg != '\0') {
1176                         len += 1 + strlen(arg);
1177                         p = xrealloc(p, 1, len);
1178                         strlcat(p, " ", len);
1179                         strlcat(p, arg, len);
1180                 }
1181                 options->subsystem_args[options->num_subsystems] = p;
1182                 options->num_subsystems++;
1183                 break;
1184
1185         case sMaxStartups:
1186                 arg = strdelim(&cp);
1187                 if (!arg || *arg == '\0')
1188                         fatal("%s line %d: Missing MaxStartups spec.",
1189                             filename, linenum);
1190                 if ((n = sscanf(arg, "%d:%d:%d",
1191                     &options->max_startups_begin,
1192                     &options->max_startups_rate,
1193                     &options->max_startups)) == 3) {
1194                         if (options->max_startups_begin >
1195                             options->max_startups ||
1196                             options->max_startups_rate > 100 ||
1197                             options->max_startups_rate < 1)
1198                                 fatal("%s line %d: Illegal MaxStartups spec.",
1199                                     filename, linenum);
1200                 } else if (n != 1)
1201                         fatal("%s line %d: Illegal MaxStartups spec.",
1202                             filename, linenum);
1203                 else
1204                         options->max_startups = options->max_startups_begin;
1205                 break;
1206
1207         case sMaxAuthTries:
1208                 intptr = &options->max_authtries;
1209                 goto parse_int;
1210
1211         case sMaxSessions:
1212                 intptr = &options->max_sessions;
1213                 goto parse_int;
1214
1215         case sBanner:
1216                 charptr = &options->banner;
1217                 goto parse_filename;
1218
1219         /*
1220          * These options can contain %X options expanded at
1221          * connect time, so that you can specify paths like:
1222          *
1223          * AuthorizedKeysFile   /etc/ssh_keys/%u
1224          */
1225         case sAuthorizedKeysFile:
1226         case sAuthorizedKeysFile2:
1227                 charptr = (opcode == sAuthorizedKeysFile) ?
1228                     &options->authorized_keys_file :
1229                     &options->authorized_keys_file2;
1230                 arg = strdelim(&cp);
1231                 if (!arg || *arg == '\0')
1232                         fatal("%s line %d: missing file name.",
1233                             filename, linenum);
1234                 if (*activep && *charptr == NULL) {
1235                         *charptr = tilde_expand_filename(arg, getuid());
1236                         /* increase optional counter */
1237                         if (intptr != NULL)
1238                                 *intptr = *intptr + 1;
1239                 }
1240                 break;
1241
1242         case sClientAliveInterval:
1243                 intptr = &options->client_alive_interval;
1244                 goto parse_time;
1245
1246         case sClientAliveCountMax:
1247                 intptr = &options->client_alive_count_max;
1248                 goto parse_int;
1249
1250         case sAcceptEnv:
1251                 while ((arg = strdelim(&cp)) && *arg != '\0') {
1252                         if (strchr(arg, '=') != NULL)
1253                                 fatal("%s line %d: Invalid environment name.",
1254                                     filename, linenum);
1255                         if (options->num_accept_env >= MAX_ACCEPT_ENV)
1256                                 fatal("%s line %d: too many allow env.",
1257                                     filename, linenum);
1258                         if (!*activep)
1259                                 break;
1260                         options->accept_env[options->num_accept_env++] =
1261                             xstrdup(arg);
1262                 }
1263                 break;
1264
1265         case sPermitTunnel:
1266                 intptr = &options->permit_tun;
1267                 arg = strdelim(&cp);
1268                 if (!arg || *arg == '\0')
1269                         fatal("%s line %d: Missing yes/point-to-point/"
1270                             "ethernet/no argument.", filename, linenum);
1271                 value = -1;
1272                 for (i = 0; tunmode_desc[i].val != -1; i++)
1273                         if (strcmp(tunmode_desc[i].text, arg) == 0) {
1274                                 value = tunmode_desc[i].val;
1275                                 break;
1276                         }
1277                 if (value == -1)
1278                         fatal("%s line %d: Bad yes/point-to-point/ethernet/"
1279                             "no argument: %s", filename, linenum, arg);
1280                 if (*intptr == -1)
1281                         *intptr = value;
1282                 break;
1283
1284         case sMatch:
1285                 if (cmdline)
1286                         fatal("Match directive not supported as a command-line "
1287                            "option");
1288                 value = match_cfg_line(&cp, linenum, user, host, address);
1289                 if (value < 0)
1290                         fatal("%s line %d: Bad Match condition", filename,
1291                             linenum);
1292                 *activep = value;
1293                 break;
1294
1295         case sPermitOpen:
1296                 arg = strdelim(&cp);
1297                 if (!arg || *arg == '\0')
1298                         fatal("%s line %d: missing PermitOpen specification",
1299                             filename, linenum);
1300                 n = options->num_permitted_opens;       /* modified later */
1301                 if (strcmp(arg, "any") == 0) {
1302                         if (*activep && n == -1) {
1303                                 channel_clear_adm_permitted_opens();
1304                                 options->num_permitted_opens = 0;
1305                         }
1306                         break;
1307                 }
1308                 if (*activep && n == -1)
1309                         channel_clear_adm_permitted_opens();
1310                 for (; arg != NULL && *arg != '\0'; arg = strdelim(&cp)) {
1311                         p = hpdelim(&arg);
1312                         if (p == NULL)
1313                                 fatal("%s line %d: missing host in PermitOpen",
1314                                     filename, linenum);
1315                         p = cleanhostname(p);
1316                         if (arg == NULL || (port = a2port(arg)) <= 0)
1317                                 fatal("%s line %d: bad port number in "
1318                                     "PermitOpen", filename, linenum);
1319                         if (*activep && n == -1)
1320                                 options->num_permitted_opens =
1321                                     channel_add_adm_permitted_opens(p, port);
1322                 }
1323                 break;
1324
1325         case sForceCommand:
1326                 if (cp == NULL)
1327                         fatal("%.200s line %d: Missing argument.", filename,
1328                             linenum);
1329                 len = strspn(cp, WHITESPACE);
1330                 if (*activep && options->adm_forced_command == NULL)
1331                         options->adm_forced_command = xstrdup(cp + len);
1332                 return 0;
1333
1334         case sChrootDirectory:
1335                 charptr = &options->chroot_directory;
1336
1337                 arg = strdelim(&cp);
1338                 if (!arg || *arg == '\0')
1339                         fatal("%s line %d: missing file name.",
1340                             filename, linenum);
1341                 if (*activep && *charptr == NULL)
1342                         *charptr = xstrdup(arg);
1343                 break;
1344
1345         case sTrustedUserCAKeys:
1346                 charptr = &options->trusted_user_ca_keys;
1347                 goto parse_filename;
1348
1349         case sRevokedKeys:
1350                 charptr = &options->revoked_keys_file;
1351                 goto parse_filename;
1352
1353         case sVersionAddendum:
1354                 ssh_version_set_addendum(strtok(cp, "\n"));
1355                 do {
1356                         arg = strdelim(&cp);
1357                 } while (arg != NULL && *arg != '\0');
1358                 break;
1359
1360         case sDeprecated:
1361                 logit("%s line %d: Deprecated option %s",
1362                     filename, linenum, arg);
1363                 while (arg)
1364                     arg = strdelim(&cp);
1365                 break;
1366
1367         case sUnsupported:
1368                 logit("%s line %d: Unsupported option %s",
1369                     filename, linenum, arg);
1370                 while (arg)
1371                     arg = strdelim(&cp);
1372                 break;
1373
1374         default:
1375                 fatal("%s line %d: Missing handler for opcode %s (%d)",
1376                     filename, linenum, arg, opcode);
1377         }
1378         if ((arg = strdelim(&cp)) != NULL && *arg != '\0')
1379                 fatal("%s line %d: garbage at end of line; \"%.200s\".",
1380                     filename, linenum, arg);
1381         return 0;
1382 }
1383
1384 /* Reads the server configuration file. */
1385
1386 void
1387 load_server_config(const char *filename, Buffer *conf)
1388 {
1389         char line[1024], *cp;
1390         FILE *f;
1391
1392         debug2("%s: filename %s", __func__, filename);
1393         if ((f = fopen(filename, "r")) == NULL) {
1394                 perror(filename);
1395                 exit(1);
1396         }
1397         buffer_clear(conf);
1398         while (fgets(line, sizeof(line), f)) {
1399                 /*
1400                  * Trim out comments and strip whitespace
1401                  * NB - preserve newlines, they are needed to reproduce
1402                  * line numbers later for error messages
1403                  */
1404                 if ((cp = strchr(line, '#')) != NULL)
1405                         memcpy(cp, "\n", 2);
1406                 cp = line + strspn(line, " \t\r");
1407
1408                 buffer_append(conf, cp, strlen(cp));
1409         }
1410         buffer_append(conf, "\0", 1);
1411         fclose(f);
1412         debug2("%s: done config len = %d", __func__, buffer_len(conf));
1413 }
1414
1415 void
1416 parse_server_match_config(ServerOptions *options, const char *user,
1417     const char *host, const char *address)
1418 {
1419         ServerOptions mo;
1420
1421         initialize_server_options(&mo);
1422         parse_server_config(&mo, "reprocess config", &cfg, user, host, address);
1423         copy_set_server_options(options, &mo, 0);
1424 }
1425
1426 /* Helper macros */
1427 #define M_CP_INTOPT(n) do {\
1428         if (src->n != -1) \
1429                 dst->n = src->n; \
1430 } while (0)
1431 #define M_CP_STROPT(n) do {\
1432         if (src->n != NULL) { \
1433                 if (dst->n != NULL) \
1434                         xfree(dst->n); \
1435                 dst->n = src->n; \
1436         } \
1437 } while(0)
1438
1439 /*
1440  * Copy any supported values that are set.
1441  *
1442  * If the preauth flag is set, we do not bother copying the string or
1443  * array values that are not used pre-authentication, because any that we
1444  * do use must be explictly sent in mm_getpwnamallow().
1445  */
1446 void
1447 copy_set_server_options(ServerOptions *dst, ServerOptions *src, int preauth)
1448 {
1449         M_CP_INTOPT(password_authentication);
1450         M_CP_INTOPT(gss_authentication);
1451         M_CP_INTOPT(rsa_authentication);
1452         M_CP_INTOPT(pubkey_authentication);
1453         M_CP_INTOPT(kerberos_authentication);
1454         M_CP_INTOPT(hostbased_authentication);
1455         M_CP_INTOPT(kbd_interactive_authentication);
1456         M_CP_INTOPT(zero_knowledge_password_authentication);
1457         M_CP_INTOPT(permit_root_login);
1458         M_CP_INTOPT(permit_empty_passwd);
1459
1460         M_CP_INTOPT(allow_tcp_forwarding);
1461         M_CP_INTOPT(allow_agent_forwarding);
1462         M_CP_INTOPT(gateway_ports);
1463         M_CP_INTOPT(x11_display_offset);
1464         M_CP_INTOPT(x11_forwarding);
1465         M_CP_INTOPT(x11_use_localhost);
1466         M_CP_INTOPT(max_sessions);
1467         M_CP_INTOPT(max_authtries);
1468
1469         M_CP_STROPT(banner);
1470         if (preauth)
1471                 return;
1472         M_CP_STROPT(adm_forced_command);
1473         M_CP_STROPT(chroot_directory);
1474         M_CP_STROPT(trusted_user_ca_keys);
1475         M_CP_STROPT(revoked_keys_file);
1476 }
1477
1478 #undef M_CP_INTOPT
1479 #undef M_CP_STROPT
1480
1481 void
1482 parse_server_config(ServerOptions *options, const char *filename, Buffer *conf,
1483     const char *user, const char *host, const char *address)
1484 {
1485         int active, linenum, bad_options = 0;
1486         char *cp, *obuf, *cbuf;
1487
1488         debug2("%s: config %s len %d", __func__, filename, buffer_len(conf));
1489
1490         obuf = cbuf = xstrdup(buffer_ptr(conf));
1491         active = user ? 0 : 1;
1492         linenum = 1;
1493         while ((cp = strsep(&cbuf, "\n")) != NULL) {
1494                 if (process_server_config_line(options, cp, filename,
1495                     linenum++, &active, user, host, address) != 0)
1496                         bad_options++;
1497         }
1498         xfree(obuf);
1499         if (bad_options > 0)
1500                 fatal("%s: terminating, %d bad configuration options",
1501                     filename, bad_options);
1502 }
1503
1504 static const char *
1505 fmt_intarg(ServerOpCodes code, int val)
1506 {
1507         if (code == sAddressFamily) {
1508                 switch (val) {
1509                 case AF_INET:
1510                         return "inet";
1511                 case AF_INET6:
1512                         return "inet6";
1513                 case AF_UNSPEC:
1514                         return "any";
1515                 default:
1516                         return "UNKNOWN";
1517                 }
1518         }
1519         if (code == sPermitRootLogin) {
1520                 switch (val) {
1521                 case PERMIT_NO_PASSWD:
1522                         return "without-password";
1523                 case PERMIT_FORCED_ONLY:
1524                         return "forced-commands-only";
1525                 case PERMIT_YES:
1526                         return "yes";
1527                 }
1528         }
1529         if (code == sProtocol) {
1530                 switch (val) {
1531                 case SSH_PROTO_1:
1532                         return "1";
1533                 case SSH_PROTO_2:
1534                         return "2";
1535                 case (SSH_PROTO_1|SSH_PROTO_2):
1536                         return "2,1";
1537                 default:
1538                         return "UNKNOWN";
1539                 }
1540         }
1541         if (code == sGatewayPorts && val == 2)
1542                 return "clientspecified";
1543         if (code == sCompression && val == COMP_DELAYED)
1544                 return "delayed";
1545         switch (val) {
1546         case -1:
1547                 return "unset";
1548         case 0:
1549                 return "no";
1550         case 1:
1551                 return "yes";
1552         }
1553         return "UNKNOWN";
1554 }
1555
1556 static const char *
1557 lookup_opcode_name(ServerOpCodes code)
1558 {
1559         u_int i;
1560
1561         for (i = 0; keywords[i].name != NULL; i++)
1562                 if (keywords[i].opcode == code)
1563                         return(keywords[i].name);
1564         return "UNKNOWN";
1565 }
1566
1567 static void
1568 dump_cfg_int(ServerOpCodes code, int val)
1569 {
1570         printf("%s %d\n", lookup_opcode_name(code), val);
1571 }
1572
1573 static void
1574 dump_cfg_fmtint(ServerOpCodes code, int val)
1575 {
1576         printf("%s %s\n", lookup_opcode_name(code), fmt_intarg(code, val));
1577 }
1578
1579 static void
1580 dump_cfg_string(ServerOpCodes code, const char *val)
1581 {
1582         if (val == NULL)
1583                 return;
1584         printf("%s %s\n", lookup_opcode_name(code), val);
1585 }
1586
1587 static void
1588 dump_cfg_strarray(ServerOpCodes code, u_int count, char **vals)
1589 {
1590         u_int i;
1591
1592         for (i = 0; i < count; i++)
1593                 printf("%s %s\n", lookup_opcode_name(code),  vals[i]);
1594 }
1595
1596 void
1597 dump_config(ServerOptions *o)
1598 {
1599         u_int i;
1600         int ret;
1601         struct addrinfo *ai;
1602         char addr[NI_MAXHOST], port[NI_MAXSERV], *s = NULL;
1603
1604         /* these are usually at the top of the config */
1605         for (i = 0; i < o->num_ports; i++)
1606                 printf("port %d\n", o->ports[i]);
1607         dump_cfg_fmtint(sProtocol, o->protocol);
1608         dump_cfg_fmtint(sAddressFamily, o->address_family);
1609
1610         /* ListenAddress must be after Port */
1611         for (ai = o->listen_addrs; ai; ai = ai->ai_next) {
1612                 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen, addr,
1613                     sizeof(addr), port, sizeof(port),
1614                     NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1615                         error("getnameinfo failed: %.100s",
1616                             (ret != EAI_SYSTEM) ? gai_strerror(ret) :
1617                             strerror(errno));
1618                 } else {
1619                         if (ai->ai_family == AF_INET6)
1620                                 printf("listenaddress [%s]:%s\n", addr, port);
1621                         else
1622                                 printf("listenaddress %s:%s\n", addr, port);
1623                 }
1624         }
1625
1626         /* integer arguments */
1627 #ifdef USE_PAM
1628         dump_cfg_int(sUsePAM, o->use_pam);
1629 #endif
1630         dump_cfg_int(sServerKeyBits, o->server_key_bits);
1631         dump_cfg_int(sLoginGraceTime, o->login_grace_time);
1632         dump_cfg_int(sKeyRegenerationTime, o->key_regeneration_time);
1633         dump_cfg_int(sX11DisplayOffset, o->x11_display_offset);
1634         dump_cfg_int(sMaxAuthTries, o->max_authtries);
1635         dump_cfg_int(sMaxSessions, o->max_sessions);
1636         dump_cfg_int(sClientAliveInterval, o->client_alive_interval);
1637         dump_cfg_int(sClientAliveCountMax, o->client_alive_count_max);
1638
1639         /* formatted integer arguments */
1640         dump_cfg_fmtint(sPermitRootLogin, o->permit_root_login);
1641         dump_cfg_fmtint(sIgnoreRhosts, o->ignore_rhosts);
1642         dump_cfg_fmtint(sIgnoreUserKnownHosts, o->ignore_user_known_hosts);
1643         dump_cfg_fmtint(sRhostsRSAAuthentication, o->rhosts_rsa_authentication);
1644         dump_cfg_fmtint(sHostbasedAuthentication, o->hostbased_authentication);
1645         dump_cfg_fmtint(sHostbasedUsesNameFromPacketOnly,
1646             o->hostbased_uses_name_from_packet_only);
1647         dump_cfg_fmtint(sRSAAuthentication, o->rsa_authentication);
1648         dump_cfg_fmtint(sPubkeyAuthentication, o->pubkey_authentication);
1649 #ifdef KRB5
1650         dump_cfg_fmtint(sKerberosAuthentication, o->kerberos_authentication);
1651         dump_cfg_fmtint(sKerberosOrLocalPasswd, o->kerberos_or_local_passwd);
1652         dump_cfg_fmtint(sKerberosTicketCleanup, o->kerberos_ticket_cleanup);
1653 # ifdef USE_AFS
1654         dump_cfg_fmtint(sKerberosGetAFSToken, o->kerberos_get_afs_token);
1655 # endif
1656 #endif
1657 #ifdef GSSAPI
1658         dump_cfg_fmtint(sGssAuthentication, o->gss_authentication);
1659         dump_cfg_fmtint(sGssCleanupCreds, o->gss_cleanup_creds);
1660 #endif
1661 #ifdef JPAKE
1662         dump_cfg_fmtint(sZeroKnowledgePasswordAuthentication,
1663             o->zero_knowledge_password_authentication);
1664 #endif
1665         dump_cfg_fmtint(sPasswordAuthentication, o->password_authentication);
1666         dump_cfg_fmtint(sKbdInteractiveAuthentication,
1667             o->kbd_interactive_authentication);
1668         dump_cfg_fmtint(sChallengeResponseAuthentication,
1669             o->challenge_response_authentication);
1670         dump_cfg_fmtint(sPrintMotd, o->print_motd);
1671         dump_cfg_fmtint(sPrintLastLog, o->print_lastlog);
1672         dump_cfg_fmtint(sX11Forwarding, o->x11_forwarding);
1673         dump_cfg_fmtint(sX11UseLocalhost, o->x11_use_localhost);
1674         dump_cfg_fmtint(sStrictModes, o->strict_modes);
1675         dump_cfg_fmtint(sTCPKeepAlive, o->tcp_keep_alive);
1676         dump_cfg_fmtint(sEmptyPasswd, o->permit_empty_passwd);
1677         dump_cfg_fmtint(sPermitUserEnvironment, o->permit_user_env);
1678         dump_cfg_fmtint(sUseLogin, o->use_login);
1679         dump_cfg_fmtint(sCompression, o->compression);
1680         dump_cfg_fmtint(sGatewayPorts, o->gateway_ports);
1681         dump_cfg_fmtint(sUseDNS, o->use_dns);
1682         dump_cfg_fmtint(sAllowTcpForwarding, o->allow_tcp_forwarding);
1683         dump_cfg_fmtint(sUsePrivilegeSeparation, use_privsep);
1684
1685         /* string arguments */
1686         dump_cfg_string(sPidFile, o->pid_file);
1687         dump_cfg_string(sXAuthLocation, o->xauth_location);
1688         dump_cfg_string(sCiphers, o->ciphers);
1689         dump_cfg_string(sMacs, o->macs);
1690         dump_cfg_string(sBanner, o->banner);
1691         dump_cfg_string(sAuthorizedKeysFile, o->authorized_keys_file);
1692         dump_cfg_string(sAuthorizedKeysFile2, o->authorized_keys_file2);
1693         dump_cfg_string(sForceCommand, o->adm_forced_command);
1694         dump_cfg_string(sChrootDirectory, o->chroot_directory);
1695         dump_cfg_string(sTrustedUserCAKeys, o->trusted_user_ca_keys);
1696         dump_cfg_string(sRevokedKeys, o->revoked_keys_file);
1697
1698         /* string arguments requiring a lookup */
1699         dump_cfg_string(sLogLevel, log_level_name(o->log_level));
1700         dump_cfg_string(sLogFacility, log_facility_name(o->log_facility));
1701
1702         /* string array arguments */
1703         dump_cfg_strarray(sHostKeyFile, o->num_host_key_files,
1704              o->host_key_files);
1705         dump_cfg_strarray(sHostKeyFile, o->num_host_cert_files,
1706              o->host_cert_files);
1707         dump_cfg_strarray(sAllowUsers, o->num_allow_users, o->allow_users);
1708         dump_cfg_strarray(sDenyUsers, o->num_deny_users, o->deny_users);
1709         dump_cfg_strarray(sAllowGroups, o->num_allow_groups, o->allow_groups);
1710         dump_cfg_strarray(sDenyGroups, o->num_deny_groups, o->deny_groups);
1711         dump_cfg_strarray(sAcceptEnv, o->num_accept_env, o->accept_env);
1712
1713         /* other arguments */
1714         for (i = 0; i < o->num_subsystems; i++)
1715                 printf("subsystem %s %s\n", o->subsystem_name[i],
1716                     o->subsystem_args[i]);
1717
1718         printf("maxstartups %d:%d:%d\n", o->max_startups_begin,
1719             o->max_startups_rate, o->max_startups);
1720
1721         for (i = 0; tunmode_desc[i].val != -1; i++)
1722                 if (tunmode_desc[i].val == o->permit_tun) {
1723                         s = tunmode_desc[i].text;
1724                         break;
1725                 }
1726         dump_cfg_string(sPermitTunnel, s);
1727
1728         channel_print_adm_permitted_opens();
1729 }