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