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