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