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