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