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