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