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