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