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