1 /*
   2  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
   3  *                    All rights reserved
   4  *
   5  * As far as I am concerned, the code I have written for this software
   6  * can be used freely for any purpose.  Any derived versions of this
   7  * software must be clearly marked as such, and if the derived work is
   8  * incompatible with the protocol description in the RFC file, it must be
   9  * called by a name other than "ssh" or "Secure Shell".
  10  */
  11 /*
  12  * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
  13  */
  14 
  15 #include "includes.h"
  16 RCSID("$OpenBSD: servconf.c,v 1.115 2002/09/04 18:52:42 stevesk Exp $");
  17 
  18 #ifdef HAVE_DEFOPEN
  19 #include <deflt.h>
  20 #endif /* HAVE_DEFOPEN */
  21 
  22 #if defined(KRB4)
  23 #include <krb.h>
  24 #endif
  25 #if defined(KRB5)
  26 #ifdef HEIMDAL
  27 #include <krb.h>
  28 #else
  29 /* Bodge - but then, so is using the kerberos IV KEYFILE to get a Kerberos V
  30  * keytab */
  31 #define KEYFILE "/etc/krb5.keytab"
  32 #endif
  33 #endif
  34 #ifdef AFS
  35 #include <kafs.h>
  36 #endif
  37 
  38 #include "ssh.h"
  39 #include "log.h"
  40 #include "buffer.h"
  41 #include "servconf.h"
  42 #include "xmalloc.h"
  43 #include "compat.h"
  44 #include "pathnames.h"
  45 #include "tildexpand.h"
  46 #include "misc.h"
  47 #include "cipher.h"
  48 #include "kex.h"
  49 #include "mac.h"
  50 #include "auth.h"
  51 #include "match.h"
  52 #include "groupaccess.h"
  53 
  54 static void add_listen_addr(ServerOptions *, char *, u_short);
  55 static void add_one_listen_addr(ServerOptions *, char *, u_short);
  56 
  57 extern Buffer cfg;
  58 
  59 /* AF_UNSPEC or AF_INET or AF_INET6 */
  60 extern int IPv4or6;
  61 
  62 /*
  63  * Initializes the server options to their initial (unset) values. Some of those
  64  * that stay unset after the command line options and configuration files are
  65  * read are set to their default values in fill_default_server_options().
  66  */
  67 void
  68 initialize_server_options(ServerOptions *options)
  69 {
  70         (void) memset(options, 0, sizeof(*options));
  71 
  72         /* Standard Options */
  73         options->num_ports = 0;
  74         options->ports_from_cmdline = 0;
  75         options->listen_addrs = NULL;
  76         options->num_host_key_files = 0;
  77         options->pid_file = NULL;
  78         options->server_key_bits = -1;
  79         options->login_grace_time = -1;
  80         options->key_regeneration_time = -1;
  81         options->permit_root_login = PERMIT_NOT_SET;
  82         options->ignore_rhosts = -1;
  83         options->ignore_user_known_hosts = -1;
  84         options->print_motd = -1;
  85         options->print_lastlog = -1;
  86         options->x11_forwarding = -1;
  87         options->x11_display_offset = -1;
  88         options->x11_use_localhost = -1;
  89         options->xauth_location = NULL;
  90         options->strict_modes = -1;
  91         options->keepalives = -1;
  92         options->log_facility = SYSLOG_FACILITY_NOT_SET;
  93         options->log_level = SYSLOG_LEVEL_NOT_SET;
  94         options->rhosts_authentication = -1;
  95         options->rhosts_rsa_authentication = -1;
  96         options->hostbased_authentication = -1;
  97         options->hostbased_uses_name_from_packet_only = -1;
  98         options->rsa_authentication = -1;
  99         options->pubkey_authentication = -1;
 100 #ifdef GSSAPI
 101         options->gss_authentication = -1;
 102         options->gss_keyex = -1;
 103         options->gss_store_creds = -1;
 104         options->gss_use_session_ccache = -1;
 105         options->gss_cleanup_creds = -1;
 106 #endif
 107 #if defined(KRB4) || defined(KRB5)
 108         options->kerberos_authentication = -1;
 109         options->kerberos_or_local_passwd = -1;
 110         options->kerberos_ticket_cleanup = -1;
 111 #endif
 112 #if defined(AFS) || defined(KRB5)
 113         options->kerberos_tgt_passing = -1;
 114 #endif
 115 #ifdef AFS
 116         options->afs_token_passing = -1;
 117 #endif
 118         options->password_authentication = -1;
 119         options->kbd_interactive_authentication = -1;
 120         options->challenge_response_authentication = -1;
 121         options->pam_authentication_via_kbd_int = -1;
 122         options->permit_empty_passwd = -1;
 123         options->permit_user_env = -1;
 124         options->compression = -1;
 125         options->allow_tcp_forwarding = -1;
 126         options->num_allow_users = 0;
 127         options->num_deny_users = 0;
 128         options->num_allow_groups = 0;
 129         options->num_deny_groups = 0;
 130         options->ciphers = NULL;
 131         options->macs = NULL;
 132         options->protocol = SSH_PROTO_UNKNOWN;
 133         options->gateway_ports = -1;
 134         options->num_subsystems = 0;
 135         options->max_startups_begin = -1;
 136         options->max_startups_rate = -1;
 137         options->max_startups = -1;
 138         options->banner = NULL;
 139         options->verify_reverse_mapping = -1;
 140         options->client_alive_interval = -1;
 141         options->client_alive_count_max = -1;
 142         options->authorized_keys_file = NULL;
 143         options->authorized_keys_file2 = NULL;
 144 
 145         options->max_auth_tries = -1;
 146         options->max_auth_tries_log = -1;
 147 
 148         options->max_init_auth_tries = -1;
 149         options->max_init_auth_tries_log = -1;
 150 
 151         options->lookup_client_hostnames = -1;
 152         options->use_openssl_engine = -1;
 153         options->chroot_directory = NULL;
 154         options->pre_userauth_hook = NULL;
 155         options->pam_service_name = NULL;
 156         options->pam_service_prefix = NULL;
 157         options->pubkey_plugin = NULL;
 158 }
 159 
 160 #ifdef HAVE_DEFOPEN
 161 /*
 162  * Reads /etc/default/login and defaults several ServerOptions:
 163  *
 164  * PermitRootLogin
 165  * PermitEmptyPasswords
 166  * LoginGraceTime
 167  *
 168  * CONSOLE=*      -> PermitRootLogin=without-password
 169  * #CONSOLE=*     -> PermitRootLogin=yes
 170  *
 171  * PASSREQ=YES    -> PermitEmptyPasswords=no
 172  * PASSREQ=NO     -> PermitEmptyPasswords=yes
 173  * #PASSREQ=*     -> PermitEmptyPasswords=no
 174  *
 175  * TIMEOUT=<secs> -> LoginGraceTime=<secs>
 176  * #TIMEOUT=<secs> -> LoginGraceTime=300
 177  */
 178 static
 179 void
 180 deflt_fill_default_server_options(ServerOptions *options)
 181 {
 182         int     flags;
 183         char    *ptr;
 184 
 185         if (defopen(_PATH_DEFAULT_LOGIN))
 186                 return;
 187 
 188         /* Ignore case */
 189         flags = defcntl(DC_GETFLAGS, 0);
 190         TURNOFF(flags, DC_CASE);
 191         (void) defcntl(DC_SETFLAGS, flags);
 192 
 193         if (options->permit_root_login == PERMIT_NOT_SET &&
 194             (ptr = defread("CONSOLE=")) != NULL)
 195                 options->permit_root_login = PERMIT_NO_PASSWD;
 196 
 197         if (options->permit_empty_passwd == -1 &&
 198             (ptr = defread("PASSREQ=")) != NULL) {
 199                 if (strcasecmp("YES", ptr) == 0)
 200                         options->permit_empty_passwd = 0;
 201                 else if (strcasecmp("NO", ptr) == 0)
 202                         options->permit_empty_passwd = 1;
 203         }
 204 
 205         if (options->max_init_auth_tries == -1 &&
 206             (ptr = defread("RETRIES=")) != NULL) {
 207                 options->max_init_auth_tries = atoi(ptr);
 208         }
 209 
 210         if (options->max_init_auth_tries_log == -1 &&
 211             (ptr = defread("SYSLOG_FAILED_LOGINS=")) != NULL) {
 212                 options->max_init_auth_tries_log = atoi(ptr);
 213         }
 214 
 215         if (options->login_grace_time == -1) {
 216                 if ((ptr = defread("TIMEOUT=")) != NULL)
 217                         options->login_grace_time = (unsigned)atoi(ptr);
 218                 else
 219                         options->login_grace_time = 300;
 220         }
 221 
 222         (void) defopen((char *)NULL);
 223 }
 224 #endif /* HAVE_DEFOPEN */
 225 
 226 void
 227 fill_default_server_options(ServerOptions *options)
 228 {
 229 
 230 #ifdef HAVE_DEFOPEN
 231         deflt_fill_default_server_options(options);
 232 #endif /* HAVE_DEFOPEN */
 233 
 234         /* Standard Options */
 235         if (options->protocol == SSH_PROTO_UNKNOWN)
 236                 options->protocol = SSH_PROTO_1|SSH_PROTO_2;
 237         if (options->num_host_key_files == 0) {
 238                 /* fill default hostkeys for protocols */
 239                 if (options->protocol & SSH_PROTO_1)
 240                         options->host_key_files[options->num_host_key_files++] =
 241                             _PATH_HOST_KEY_FILE;
 242 #ifndef GSSAPI
 243                 /* With GSS keyex we can run v2 w/ no host keys */
 244                 if (options->protocol & SSH_PROTO_2) {
 245                         options->host_key_files[options->num_host_key_files++] =
 246                             _PATH_HOST_RSA_KEY_FILE;
 247                         options->host_key_files[options->num_host_key_files++] =
 248                             _PATH_HOST_DSA_KEY_FILE;
 249                 }
 250 #endif /* GSSAPI */
 251         }
 252         if (options->num_ports == 0)
 253                 options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
 254         if (options->listen_addrs == NULL)
 255                 add_listen_addr(options, NULL, 0);
 256         if (options->pid_file == NULL)
 257                 options->pid_file = _PATH_SSH_DAEMON_PID_FILE;
 258         if (options->server_key_bits == -1)
 259                 options->server_key_bits = 768;
 260         if (options->login_grace_time == -1)
 261                 options->login_grace_time = 120;
 262         if (options->key_regeneration_time == -1)
 263                 options->key_regeneration_time = 3600;
 264         if (options->permit_root_login == PERMIT_NOT_SET)
 265                 options->permit_root_login = PERMIT_YES;
 266         if (options->ignore_rhosts == -1)
 267                 options->ignore_rhosts = 1;
 268         if (options->ignore_user_known_hosts == -1)
 269                 options->ignore_user_known_hosts = 0;
 270         if (options->print_motd == -1)
 271                 options->print_motd = 1;
 272         if (options->print_lastlog == -1)
 273                 options->print_lastlog = 1;
 274         if (options->x11_forwarding == -1)
 275                 options->x11_forwarding = 1;
 276         if (options->x11_display_offset == -1)
 277                 options->x11_display_offset = 10;
 278         if (options->x11_use_localhost == -1)
 279                 options->x11_use_localhost = 1;
 280         if (options->xauth_location == NULL)
 281                 options->xauth_location = _PATH_XAUTH;
 282         if (options->strict_modes == -1)
 283                 options->strict_modes = 1;
 284         if (options->keepalives == -1)
 285                 options->keepalives = 1;
 286         if (options->log_facility == SYSLOG_FACILITY_NOT_SET)
 287                 options->log_facility = SYSLOG_FACILITY_AUTH;
 288         if (options->log_level == SYSLOG_LEVEL_NOT_SET)
 289                 options->log_level = SYSLOG_LEVEL_INFO;
 290         if (options->rhosts_authentication == -1)
 291                 options->rhosts_authentication = 0;
 292         if (options->rhosts_rsa_authentication == -1)
 293                 options->rhosts_rsa_authentication = 0;
 294         if (options->hostbased_authentication == -1)
 295                 options->hostbased_authentication = 0;
 296         if (options->hostbased_uses_name_from_packet_only == -1)
 297                 options->hostbased_uses_name_from_packet_only = 0;
 298         if (options->rsa_authentication == -1)
 299                 options->rsa_authentication = 1;
 300         if (options->pubkey_authentication == -1)
 301                 options->pubkey_authentication = 1;
 302 #ifdef GSSAPI
 303         if (options->gss_authentication == -1)
 304                 options->gss_authentication = 1;
 305         if (options->gss_keyex == -1)
 306                 options->gss_keyex = 1;
 307         if (options->gss_store_creds == -1)
 308                 options->gss_store_creds = 1;
 309         if (options->gss_use_session_ccache == -1)
 310                 options->gss_use_session_ccache = 1;
 311         if (options->gss_cleanup_creds == -1)
 312                 options->gss_cleanup_creds = 1;
 313 #endif
 314 #if defined(KRB4) || defined(KRB5)
 315         if (options->kerberos_authentication == -1)
 316                 options->kerberos_authentication = 0;
 317         if (options->kerberos_or_local_passwd == -1)
 318                 options->kerberos_or_local_passwd = 1;
 319         if (options->kerberos_ticket_cleanup == -1)
 320                 options->kerberos_ticket_cleanup = 1;
 321 #endif
 322 #if defined(AFS) || defined(KRB5)
 323         if (options->kerberos_tgt_passing == -1)
 324                 options->kerberos_tgt_passing = 0;
 325 #endif
 326 #ifdef AFS
 327         if (options->afs_token_passing == -1)
 328                 options->afs_token_passing = 0;
 329 #endif
 330         if (options->password_authentication == -1)
 331                 options->password_authentication = 1;
 332         /*
 333          * options->pam_authentication_via_kbd_int has intentionally no default
 334          * value since we do not need it.
 335          */
 336         if (options->kbd_interactive_authentication == -1)
 337                 options->kbd_interactive_authentication = 1;
 338         if (options->challenge_response_authentication == -1)
 339                 options->challenge_response_authentication = 1;
 340         if (options->permit_empty_passwd == -1)
 341                 options->permit_empty_passwd = 0;
 342         if (options->permit_user_env == -1)
 343                 options->permit_user_env = 0;
 344         if (options->compression == -1)
 345                 options->compression = 1;
 346         if (options->allow_tcp_forwarding == -1)
 347                 options->allow_tcp_forwarding = 1;
 348         if (options->gateway_ports == -1)
 349                 options->gateway_ports = 0;
 350         if (options->max_startups == -1)
 351                 options->max_startups = 10;
 352         if (options->max_startups_rate == -1)
 353                 options->max_startups_rate = 100;            /* 100% */
 354         if (options->max_startups_begin == -1)
 355                 options->max_startups_begin = options->max_startups;
 356         if (options->verify_reverse_mapping == -1)
 357                 options->verify_reverse_mapping = 0;
 358         if (options->client_alive_interval == -1)
 359                 options->client_alive_interval = 0;
 360         if (options->client_alive_count_max == -1)
 361                 options->client_alive_count_max = 3;
 362         if (options->authorized_keys_file2 == NULL) {
 363                 /* authorized_keys_file2 falls back to authorized_keys_file */
 364                 if (options->authorized_keys_file != NULL)
 365                         options->authorized_keys_file2 = options->authorized_keys_file;
 366                 else
 367                         options->authorized_keys_file2 = _PATH_SSH_USER_PERMITTED_KEYS2;
 368         }
 369         if (options->authorized_keys_file == NULL)
 370                 options->authorized_keys_file = _PATH_SSH_USER_PERMITTED_KEYS;
 371 
 372         if (options->max_auth_tries == -1)
 373                 options->max_auth_tries = AUTH_FAIL_MAX;
 374         if (options->max_auth_tries_log == -1)
 375                 options->max_auth_tries_log = options->max_auth_tries / 2;
 376 
 377         if (options->max_init_auth_tries == -1)
 378                 options->max_init_auth_tries = AUTH_FAIL_MAX;
 379         if (options->max_init_auth_tries_log == -1)
 380                 options->max_init_auth_tries_log = options->max_init_auth_tries / 2;
 381 
 382         if (options->lookup_client_hostnames == -1)
 383                 options->lookup_client_hostnames = 1;
 384         if (options->use_openssl_engine == -1)
 385                 options->use_openssl_engine = 1;
 386         if (options->pam_service_prefix == NULL)
 387                 options->pam_service_prefix = _SSH_PAM_SERVICE_PREFIX;
 388         if (options->pam_service_name == NULL)
 389                 options->pam_service_name = NULL;
 390 }
 391 
 392 /* Keyword tokens. */
 393 typedef enum {
 394         sBadOption,             /* == unknown option */
 395         /* Portable-specific options */
 396         sPAMAuthenticationViaKbdInt,
 397         /* Standard Options */
 398         sPort, sHostKeyFile, sServerKeyBits, sLoginGraceTime, sKeyRegenerationTime,
 399         sPermitRootLogin, sLogFacility, sLogLevel,
 400         sRhostsAuthentication, sRhostsRSAAuthentication, sRSAAuthentication,
 401 #ifdef GSSAPI
 402         sGssAuthentication, sGssKeyEx, sGssStoreDelegCreds,
 403         sGssUseSessionCredCache, sGssCleanupCreds,
 404 #endif /* GSSAPI */
 405 #if defined(KRB4) || defined(KRB5)
 406         sKerberosAuthentication, sKerberosOrLocalPasswd, sKerberosTicketCleanup,
 407 #endif
 408 #if defined(AFS) || defined(KRB5)
 409         sKerberosTgtPassing,
 410 #endif
 411 #ifdef AFS
 412         sAFSTokenPassing,
 413 #endif
 414         sChallengeResponseAuthentication,
 415         sPasswordAuthentication, sKbdInteractiveAuthentication, sListenAddress,
 416         sPrintMotd, sPrintLastLog, sIgnoreRhosts,
 417         sX11Forwarding, sX11DisplayOffset, sX11UseLocalhost,
 418         sStrictModes, sEmptyPasswd, sKeepAlives,
 419         sPermitUserEnvironment, sUseLogin, sAllowTcpForwarding, sCompression,
 420         sAllowUsers, sDenyUsers, sAllowGroups, sDenyGroups,
 421         sIgnoreUserKnownHosts, sCiphers, sMacs, sProtocol, sPidFile,
 422         sGatewayPorts, sPubkeyAuthentication, sXAuthLocation, sSubsystem, 
 423         sBanner, sVerifyReverseMapping, sHostbasedAuthentication,
 424         sHostbasedUsesNameFromPacketOnly, sClientAliveInterval,
 425         sClientAliveCountMax, sAuthorizedKeysFile, sAuthorizedKeysFile2,
 426         sMaxAuthTries, sMaxAuthTriesLog, sUsePrivilegeSeparation,
 427         sLookupClientHostnames, sUseOpenSSLEngine, sChrootDirectory,
 428         sPreUserauthHook, sMatch, sPAMServicePrefix, sPAMServiceName,
 429         sMaxStartups, sPubKeyPlugin,
 430         sDeprecated
 431 } ServerOpCodes;
 432 
 433 #define SSHCFG_GLOBAL   0x01    /* allowed in main section of sshd_config */
 434 #define SSHCFG_MATCH    0x02    /* allowed inside a Match section */
 435 #define SSHCFG_ALL      (SSHCFG_GLOBAL|SSHCFG_MATCH)
 436 
 437 /* Textual representation of the tokens. */
 438 static struct {
 439         const char *name;
 440         ServerOpCodes opcode;
 441         u_int flags;
 442 } keywords[] = {
 443         /* Portable-specific options */
 444         { "PAMAuthenticationViaKbdInt", sPAMAuthenticationViaKbdInt, SSHCFG_GLOBAL },
 445         /* Standard Options */
 446         { "port", sPort, SSHCFG_GLOBAL },
 447         { "hostkey", sHostKeyFile, SSHCFG_GLOBAL },
 448         { "hostdsakey", sHostKeyFile, SSHCFG_GLOBAL },                  /* alias */
 449         { "pidfile", sPidFile, SSHCFG_GLOBAL },
 450         { "serverkeybits", sServerKeyBits, SSHCFG_GLOBAL },
 451         { "logingracetime", sLoginGraceTime, SSHCFG_GLOBAL },
 452         { "keyregenerationinterval", sKeyRegenerationTime, SSHCFG_GLOBAL },
 453         { "permitrootlogin", sPermitRootLogin, SSHCFG_ALL },
 454         { "syslogfacility", sLogFacility, SSHCFG_GLOBAL },
 455         { "loglevel", sLogLevel, SSHCFG_GLOBAL },
 456         { "rhostsauthentication", sRhostsAuthentication, SSHCFG_GLOBAL },
 457         { "rhostsrsaauthentication", sRhostsRSAAuthentication, SSHCFG_ALL },
 458         { "hostbasedauthentication", sHostbasedAuthentication, SSHCFG_ALL },
 459         { "hostbasedusesnamefrompacketonly", sHostbasedUsesNameFromPacketOnly },
 460         { "rsaauthentication", sRSAAuthentication, SSHCFG_ALL },
 461         { "pubkeyauthentication", sPubkeyAuthentication, SSHCFG_ALL },
 462         { "dsaauthentication", sPubkeyAuthentication, SSHCFG_GLOBAL },  /* alias */
 463 #ifdef GSSAPI
 464         { "gssapiauthentication", sGssAuthentication, SSHCFG_ALL },
 465         { "gssapikeyexchange", sGssKeyEx,   SSHCFG_GLOBAL },
 466         { "gssapistoredelegatedcredentials", sGssStoreDelegCreds, SSHCFG_GLOBAL },
 467         { "gssauthentication", sGssAuthentication, SSHCFG_GLOBAL },     /* alias */
 468         { "gsskeyex", sGssKeyEx, SSHCFG_GLOBAL },       /* alias */
 469         { "gssstoredelegcreds", sGssStoreDelegCreds, SSHCFG_GLOBAL },   /* alias */
 470 #ifndef SUNW_GSSAPI
 471         { "gssusesessionccache", sGssUseSessionCredCache, SSHCFG_GLOBAL },
 472         { "gssusesessioncredcache", sGssUseSessionCredCache, SSHCFG_GLOBAL },
 473         { "gsscleanupcreds", sGssCleanupCreds, SSHCFG_GLOBAL },
 474 #endif /* SUNW_GSSAPI */
 475 #endif
 476 #if defined(KRB4) || defined(KRB5)
 477         { "kerberosauthentication", sKerberosAuthentication, SSHCFG_ALL },
 478         { "kerberosorlocalpasswd", sKerberosOrLocalPasswd, SSHCFG_GLOBAL },
 479         { "kerberosticketcleanup", sKerberosTicketCleanup, SSHCFG_GLOBAL },
 480 #endif
 481 #if defined(AFS) || defined(KRB5)
 482         { "kerberostgtpassing", sKerberosTgtPassing, SSHCFG_GLOBAL },
 483 #endif
 484 #ifdef AFS
 485         { "afstokenpassing", sAFSTokenPassing, SSHCFG_GLOBAL },
 486 #endif
 487         { "passwordauthentication", sPasswordAuthentication, SSHCFG_ALL },
 488         { "kbdinteractiveauthentication", sKbdInteractiveAuthentication, SSHCFG_ALL },
 489         { "challengeresponseauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL },
 490         { "skeyauthentication", sChallengeResponseAuthentication, SSHCFG_GLOBAL }, /* alias */
 491         { "checkmail", sDeprecated, SSHCFG_GLOBAL },
 492         { "listenaddress", sListenAddress, SSHCFG_GLOBAL },
 493         { "printmotd", sPrintMotd, SSHCFG_GLOBAL },
 494         { "printlastlog", sPrintLastLog, SSHCFG_GLOBAL },
 495         { "ignorerhosts", sIgnoreRhosts, SSHCFG_GLOBAL },
 496         { "ignoreuserknownhosts", sIgnoreUserKnownHosts, SSHCFG_GLOBAL },
 497         { "x11forwarding", sX11Forwarding, SSHCFG_ALL },
 498         { "x11displayoffset", sX11DisplayOffset, SSHCFG_ALL },
 499         { "x11uselocalhost", sX11UseLocalhost, SSHCFG_ALL },
 500         { "xauthlocation", sXAuthLocation, SSHCFG_GLOBAL },
 501         { "strictmodes", sStrictModes, SSHCFG_GLOBAL },
 502         { "permitemptypasswords", sEmptyPasswd, SSHCFG_ALL },
 503         { "permituserenvironment", sPermitUserEnvironment, SSHCFG_GLOBAL },
 504         { "uselogin", sUseLogin, SSHCFG_GLOBAL },
 505         { "compression", sCompression, SSHCFG_GLOBAL },
 506         { "keepalive", sKeepAlives, SSHCFG_GLOBAL },
 507         { "allowtcpforwarding", sAllowTcpForwarding, SSHCFG_ALL },
 508         { "allowusers", sAllowUsers, SSHCFG_GLOBAL },
 509         { "denyusers", sDenyUsers, SSHCFG_GLOBAL },
 510         { "allowgroups", sAllowGroups, SSHCFG_GLOBAL },
 511         { "denygroups", sDenyGroups, SSHCFG_GLOBAL },
 512         { "ciphers", sCiphers, SSHCFG_GLOBAL },
 513         { "macs", sMacs, SSHCFG_GLOBAL},
 514         { "protocol", sProtocol,SSHCFG_GLOBAL },
 515         { "gatewayports", sGatewayPorts, SSHCFG_ALL },
 516         { "subsystem", sSubsystem, SSHCFG_GLOBAL},
 517         { "maxstartups", sMaxStartups, SSHCFG_GLOBAL },
 518         { "banner", sBanner, SSHCFG_ALL },
 519         { "verifyreversemapping", sVerifyReverseMapping, SSHCFG_GLOBAL },
 520         { "reversemappingcheck", sVerifyReverseMapping,SSHCFG_GLOBAL },
 521         { "clientaliveinterval", sClientAliveInterval, SSHCFG_GLOBAL },
 522         { "clientalivecountmax", sClientAliveCountMax, SSHCFG_GLOBAL },
 523         { "authorizedkeysfile", sAuthorizedKeysFile, SSHCFG_GLOBAL },
 524         { "authorizedkeysfile2", sAuthorizedKeysFile2, SSHCFG_GLOBAL },
 525         { "maxauthtries", sMaxAuthTries, SSHCFG_ALL },
 526         { "maxauthtrieslog", sMaxAuthTriesLog, SSHCFG_GLOBAL },
 527         { "useprivilegeseparation", sUsePrivilegeSeparation, SSHCFG_GLOBAL },
 528         { "lookupclienthostnames", sLookupClientHostnames, SSHCFG_GLOBAL },
 529         { "useopensslengine", sUseOpenSSLEngine, SSHCFG_GLOBAL },
 530         { "chrootdirectory", sChrootDirectory, SSHCFG_ALL },
 531         { "preuserauthhook", sPreUserauthHook, SSHCFG_ALL},
 532         { "match", sMatch, SSHCFG_ALL },
 533         { "pamserviceprefix", sPAMServicePrefix, SSHCFG_GLOBAL },
 534         { "pamservicename", sPAMServiceName, SSHCFG_GLOBAL },
 535         { "pubkeyplugin", sPubKeyPlugin, SSHCFG_ALL },
 536 
 537         { NULL, sBadOption, 0 }
 538 };
 539 
 540 /*
 541  * Returns the number of the token pointed to by cp or sBadOption.
 542  */
 543 
 544 static ServerOpCodes
 545 parse_token(const char *cp, const char *filename,
 546             int linenum, u_int *flags)
 547 {
 548         u_int i;
 549 
 550         for (i = 0; keywords[i].name; i++)
 551                 if (strcasecmp(cp, keywords[i].name) == 0) {
 552                         *flags = keywords[i].flags;
 553                         return keywords[i].opcode;
 554                 }
 555 
 556         error("%s: line %d: Bad configuration option: %s",
 557             filename, linenum, cp);
 558         return sBadOption;
 559 }
 560 
 561 static void
 562 add_listen_addr(ServerOptions *options, char *addr, u_short port)
 563 {
 564         int i;
 565 
 566         if (options->num_ports == 0)
 567                 options->ports[options->num_ports++] = SSH_DEFAULT_PORT;
 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);
 573 }
 574 
 575 static void
 576 add_one_listen_addr(ServerOptions *options, char *addr, u_short port)
 577 {
 578         struct addrinfo hints, *ai, *aitop;
 579         char strport[NI_MAXSERV];
 580         int gaierr;
 581 
 582         (void) memset(&hints, 0, sizeof(hints));
 583         hints.ai_family = IPv4or6;
 584         hints.ai_socktype = SOCK_STREAM;
 585         hints.ai_flags = (addr == NULL) ? AI_PASSIVE : 0;
 586         (void) snprintf(strport, sizeof strport, "%u", port);
 587         if ((gaierr = getaddrinfo(addr, strport, &hints, &aitop)) != 0)
 588                 fatal("bad addr or host: %s (%s)",
 589                     addr ? addr : "<NULL>",
 590                     gai_strerror(gaierr));
 591         for (ai = aitop; ai->ai_next; ai = ai->ai_next)
 592                 ;
 593         ai->ai_next = options->listen_addrs;
 594         options->listen_addrs = aitop;
 595 }
 596 
 597 /*
 598  * The strategy for the Match blocks is that the config file is parsed twice.
 599  *
 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.
 604  *
 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.
 611  *
 612  * Potential additions/improvements:
 613  *  - Add Match support for pre-kex directives, eg Protocol, Ciphers.
 614  *
 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  *              [...]
 624  *
 625  *  - Add a PermittedChannelRequests directive
 626  *      Match Group shell
 627  *              PermittedChannelRequests session,forwarded-tcpip
 628  */
 629 
 630 static int
 631 match_cfg_line_group(const char *grps, int line, const char *user)
 632 {
 633         int result = 0;
 634         struct passwd *pw;
 635 
 636         if (user == NULL)
 637                 goto out;
 638 
 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;
 652         }
 653 out:
 654         ga_free();
 655         return result;
 656 }
 657 
 658 static int
 659 match_cfg_line(char **condition, int line, const char *user, const char *host,
 660     const char *address)
 661 {
 662         int result = 1;
 663         char *arg, *attrib, *cp = *condition;
 664         size_t len;
 665 
 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)");
 672 
 673         while ((attrib = strdelim(&cp)) != NULL && *attrib != '\0') {
 674                 if ((arg = strdelim(&cp)) == NULL || *arg == '\0') {
 675                         error("Missing Match criteria for %s", attrib);
 676                         return -1;
 677                 }
 678                 len = strlen(arg);
 679                 if (strcasecmp(attrib, "user") == 0) {
 680                         if (!user) {
 681                                 result = 0;
 682                                 continue;
 683                         }
 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;
 695                         }
 696                 } else if (strcasecmp(attrib, "host") == 0) {
 697                         if (!host) {
 698                                 result = 0;
 699                                 continue;
 700                         }
 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;
 718                         }
 719                 } else {
 720                         error("Unsupported Match attribute %s", attrib);
 721                         return -1;
 722                 }
 723         }
 724         if (user != NULL)
 725                 debug3("match %sfound", result ? "" : "not ");
 726         *condition = cp;
 727         return result;
 728 }
 729 
 730 #define WHITESPACE " \t\r\n"
 731 
 732 int
 733 process_server_config_line(ServerOptions *options, char *line,
 734     const char *filename, int linenum, int *activep, const char *user,
 735     const char *host, const char *address)
 736 {
 737         char *cp, **charptr, *arg, *p;
 738         int cmdline = 0, *intptr, value, n;
 739         ServerOpCodes opcode;
 740         u_int i, flags = 0;
 741         size_t len;
 742 
 743         cp = line;
 744         arg = strdelim(&cp);
 745         /* Ignore leading whitespace */
 746         if (*arg == '\0')
 747                 arg = strdelim(&cp);
 748         if (!arg || !*arg || *arg == '#')
 749                 return 0;
 750         intptr = NULL;
 751         charptr = NULL;
 752         opcode = parse_token(arg, filename, linenum, &flags);
 753 
 754         if (activep == NULL) { /* We are processing a command line directive */
 755                 cmdline = 1;
 756                 activep = &cmdline;
 757         }
 758         if (*activep && opcode != sMatch)
 759                 debug3("%s:%d setting %s %s", filename, linenum, arg, cp);
 760         if (*activep == 0 && !(flags & SSHCFG_MATCH)) {
 761                 if (user == NULL) {
 762                         fatal("%s line %d: Directive '%s' is not allowed "
 763                             "within a Match block", filename, linenum, arg);
 764                 } else { /* this is a directive we have already processed */
 765                         while (arg)
 766                                 arg = strdelim(&cp);
 767                         return 0;
 768                 }
 769         }
 770 
 771         switch (opcode) {
 772         /* Portable-specific options */
 773         case sPAMAuthenticationViaKbdInt:
 774                 log("%s line %d: PAMAuthenticationViaKbdInt has been "
 775                     "deprecated. You should use KbdInteractiveAuthentication "
 776                     "instead (which defaults to \"yes\").", filename, linenum);
 777                 intptr = &options->pam_authentication_via_kbd_int;
 778                 goto parse_flag;
 779 
 780         /* Standard Options */
 781         case sBadOption:
 782                 return -1;
 783         case sPort:
 784                 /* ignore ports from configfile if cmdline specifies ports */
 785                 if (options->ports_from_cmdline)
 786                         return 0;
 787                 if (options->listen_addrs != NULL)
 788                         fatal("%s line %d: ports must be specified before "
 789                             "ListenAddress.", filename, linenum);
 790                 if (options->num_ports >= MAX_PORTS)
 791                         fatal("%s line %d: too many ports.",
 792                             filename, linenum);
 793                 arg = strdelim(&cp);
 794                 if (!arg || *arg == '\0')
 795                         fatal("%s line %d: missing port number.",
 796                             filename, linenum);
 797                 options->ports[options->num_ports++] = a2port(arg);
 798                 if (options->ports[options->num_ports-1] == 0)
 799                         fatal("%s line %d: Badly formatted port number.",
 800                             filename, linenum);
 801                 break;
 802 
 803         case sServerKeyBits:
 804                 intptr = &options->server_key_bits;
 805 parse_int:
 806                 arg = strdelim(&cp);
 807                 if (!arg || *arg == '\0')
 808                         fatal("%s line %d: missing integer value.",
 809                             filename, linenum);
 810                 value = atoi(arg);
 811                 if (*activep && *intptr == -1)
 812                         *intptr = value;
 813                 break;
 814 
 815         case sLoginGraceTime:
 816                 intptr = &options->login_grace_time;
 817 parse_time:
 818                 arg = strdelim(&cp);
 819                 if (!arg || *arg == '\0')
 820                         fatal("%s line %d: missing time value.",
 821                             filename, linenum);
 822                 if ((value = convtime(arg)) == -1)
 823                         fatal("%s line %d: invalid time value.",
 824                             filename, linenum);
 825                 if (*intptr == -1)
 826                         *intptr = value;
 827                 break;
 828 
 829         case sKeyRegenerationTime:
 830                 intptr = &options->key_regeneration_time;
 831                 goto parse_time;
 832 
 833         case sListenAddress:
 834                 arg = strdelim(&cp);
 835                 if (!arg || *arg == '\0' || strncmp(arg, "[]", 2) == 0)
 836                         fatal("%s line %d: missing inet addr.",
 837                             filename, linenum);
 838                 if (*arg == '[') {
 839                         if ((p = strchr(arg, ']')) == NULL)
 840                                 fatal("%s line %d: bad ipv6 inet addr usage.",
 841                                     filename, linenum);
 842                         arg++;
 843                         (void) memmove(p, p+1, strlen(p+1)+1);
 844                 } else if (((p = strchr(arg, ':')) == NULL) ||
 845                             (strchr(p+1, ':') != NULL)) {
 846                         add_listen_addr(options, arg, 0);
 847                         break;
 848                 }
 849                 if (*p == ':') {
 850                         u_short port;
 851 
 852                         p++;
 853                         if (*p == '\0')
 854                                 fatal("%s line %d: bad inet addr:port usage.",
 855                                     filename, linenum);
 856                         else {
 857                                 *(p-1) = '\0';
 858                                 if ((port = a2port(p)) == 0)
 859                                         fatal("%s line %d: bad port number.",
 860                                             filename, linenum);
 861                                 add_listen_addr(options, arg, port);
 862                         }
 863                 } else if (*p == '\0')
 864                         add_listen_addr(options, arg, 0);
 865                 else
 866                         fatal("%s line %d: bad inet addr usage.",
 867                             filename, linenum);
 868                 break;
 869 
 870         case sHostKeyFile:
 871                 intptr = &options->num_host_key_files;
 872                 if (*intptr >= MAX_HOSTKEYS)
 873                         fatal("%s line %d: too many host keys specified (max %d).",
 874                             filename, linenum, MAX_HOSTKEYS);
 875                 charptr = &options->host_key_files[*intptr];
 876 parse_filename:
 877                 arg = strdelim(&cp);
 878                 if (!arg || *arg == '\0')
 879                         fatal("%s line %d: missing file name.",
 880                             filename, linenum);
 881                 if (*activep && *charptr == NULL) {
 882                         *charptr = tilde_expand_filename(arg, getuid());
 883                         /* increase optional counter */
 884                         if (intptr != NULL)
 885                                 *intptr = *intptr + 1;
 886                 }
 887                 break;
 888 
 889         case sPidFile:
 890                 charptr = &options->pid_file;
 891                 goto parse_filename;
 892 
 893         case sPermitRootLogin:
 894                 intptr = &options->permit_root_login;
 895                 arg = strdelim(&cp);
 896                 if (!arg || *arg == '\0')
 897                         fatal("%s line %d: missing yes/"
 898                             "without-password/forced-commands-only/no "
 899                             "argument.", filename, linenum);
 900                 value = 0;      /* silence compiler */
 901                 if (strcmp(arg, "without-password") == 0)
 902                         value = PERMIT_NO_PASSWD;
 903                 else if (strcmp(arg, "forced-commands-only") == 0)
 904                         value = PERMIT_FORCED_ONLY;
 905                 else if (strcmp(arg, "yes") == 0)
 906                         value = PERMIT_YES;
 907                 else if (strcmp(arg, "no") == 0)
 908                         value = PERMIT_NO;
 909                 else
 910                         fatal("%s line %d: Bad yes/"
 911                             "without-password/forced-commands-only/no "
 912                             "argument: %s", filename, linenum, arg);
 913                 if (*activep && *intptr == -1)
 914                         *intptr = value;
 915                 break;
 916 
 917         case sIgnoreRhosts:
 918                 intptr = &options->ignore_rhosts;
 919 parse_flag:
 920                 arg = strdelim(&cp);
 921                 if (!arg || *arg == '\0')
 922                         fatal("%s line %d: missing yes/no argument.",
 923                             filename, linenum);
 924                 value = 0;      /* silence compiler */
 925                 if (strcmp(arg, "yes") == 0)
 926                         value = 1;
 927                 else if (strcmp(arg, "no") == 0)
 928                         value = 0;
 929                 else
 930                         fatal("%s line %d: Bad yes/no argument: %s",
 931                                 filename, linenum, arg);
 932                 if (*activep && *intptr == -1)
 933                         *intptr = value;
 934                 break;
 935 
 936         case sIgnoreUserKnownHosts:
 937                 intptr = &options->ignore_user_known_hosts;
 938                 goto parse_flag;
 939 
 940         case sRhostsAuthentication:
 941                 intptr = &options->rhosts_authentication;
 942                 goto parse_flag;
 943 
 944         case sRhostsRSAAuthentication:
 945                 intptr = &options->rhosts_rsa_authentication;
 946                 goto parse_flag;
 947 
 948         case sHostbasedAuthentication:
 949                 intptr = &options->hostbased_authentication;
 950                 goto parse_flag;
 951 
 952         case sHostbasedUsesNameFromPacketOnly:
 953                 intptr = &options->hostbased_uses_name_from_packet_only;
 954                 goto parse_flag;
 955 
 956         case sRSAAuthentication:
 957                 intptr = &options->rsa_authentication;
 958                 goto parse_flag;
 959 
 960         case sPubkeyAuthentication:
 961                 intptr = &options->pubkey_authentication;
 962                 goto parse_flag;
 963 #ifdef GSSAPI
 964         case sGssAuthentication:
 965                 intptr = &options->gss_authentication;
 966                 goto parse_flag;
 967         case sGssKeyEx:
 968                 intptr = &options->gss_keyex;
 969                 goto parse_flag;
 970         case sGssStoreDelegCreds:
 971                 intptr = &options->gss_keyex;
 972                 goto parse_flag;
 973 #ifndef SUNW_GSSAPI
 974         case sGssUseSessionCredCache:
 975                 intptr = &options->gss_use_session_ccache;
 976                 goto parse_flag;
 977         case sGssCleanupCreds:
 978                 intptr = &options->gss_cleanup_creds;
 979                 goto parse_flag;
 980 #endif /* SUNW_GSSAPI */
 981 #endif /* GSSAPI */
 982 #if defined(KRB4) || defined(KRB5)
 983         case sKerberosAuthentication:
 984                 intptr = &options->kerberos_authentication;
 985                 goto parse_flag;
 986 
 987         case sKerberosOrLocalPasswd:
 988                 intptr = &options->kerberos_or_local_passwd;
 989                 goto parse_flag;
 990 
 991         case sKerberosTicketCleanup:
 992                 intptr = &options->kerberos_ticket_cleanup;
 993                 goto parse_flag;
 994 #endif
 995 #if defined(AFS) || defined(KRB5)
 996         case sKerberosTgtPassing:
 997                 intptr = &options->kerberos_tgt_passing;
 998                 goto parse_flag;
 999 #endif
1000 #ifdef AFS
1001         case sAFSTokenPassing:
1002                 intptr = &options->afs_token_passing;
1003                 goto parse_flag;
1004 #endif
1005 
1006         case sPasswordAuthentication:
1007                 intptr = &options->password_authentication;
1008                 goto parse_flag;
1009 
1010         case sKbdInteractiveAuthentication:
1011                 intptr = &options->kbd_interactive_authentication;
1012                 goto parse_flag;
1013 
1014         case sChallengeResponseAuthentication:
1015                 intptr = &options->challenge_response_authentication;
1016                 goto parse_flag;
1017 
1018         case sPrintMotd:
1019                 intptr = &options->print_motd;
1020                 goto parse_flag;
1021 
1022         case sPrintLastLog:
1023                 intptr = &options->print_lastlog;
1024                 goto parse_flag;
1025 
1026         case sX11Forwarding:
1027                 intptr = &options->x11_forwarding;
1028                 goto parse_flag;
1029 
1030         case sX11DisplayOffset:
1031                 intptr = &options->x11_display_offset;
1032                 goto parse_int;
1033 
1034         case sX11UseLocalhost:
1035                 intptr = &options->x11_use_localhost;
1036                 goto parse_flag;
1037 
1038         case sXAuthLocation:
1039                 charptr = &options->xauth_location;
1040                 goto parse_filename;
1041 
1042         case sStrictModes:
1043                 intptr = &options->strict_modes;
1044                 goto parse_flag;
1045 
1046         case sKeepAlives:
1047                 intptr = &options->keepalives;
1048                 goto parse_flag;
1049 
1050         case sEmptyPasswd:
1051                 intptr = &options->permit_empty_passwd;
1052                 goto parse_flag;
1053 
1054         case sPermitUserEnvironment:
1055                 intptr = &options->permit_user_env;
1056                 goto parse_flag;
1057 
1058         case sUseLogin:
1059                 log("%s line %d: ignoring UseLogin option value."
1060                     " This option is always off.", filename, linenum);
1061                 while (arg)
1062                         arg = strdelim(&cp);
1063                 break;
1064 
1065         case sCompression:
1066                 intptr = &options->compression;
1067                 goto parse_flag;
1068 
1069         case sGatewayPorts:
1070                 intptr = &options->gateway_ports;
1071                 arg = strdelim(&cp);
1072                 if (!arg || *arg == '\0')
1073                         fatal("%s line %d: missing yes/no/clientspecified "
1074                             "argument.", filename, linenum);
1075                 value = 0;      /* silence compiler */
1076                 if (strcmp(arg, "clientspecified") == 0)
1077                         value = 2;
1078                 else if (strcmp(arg, "yes") == 0)
1079                         value = 1;
1080                 else if (strcmp(arg, "no") == 0)
1081                         value = 0;
1082                 else
1083                         fatal("%s line %d: Bad yes/no/clientspecified "
1084                             "argument: %s", filename, linenum, arg);
1085                 if (*activep && *intptr == -1)
1086                         *intptr = value;
1087                 break;
1088 
1089         case sVerifyReverseMapping:
1090                 intptr = &options->verify_reverse_mapping;
1091                 goto parse_flag;
1092 
1093         case sLogFacility:
1094                 intptr = (int *) &options->log_facility;
1095                 arg = strdelim(&cp);
1096                 value = log_facility_number(arg);
1097                 if (value == SYSLOG_FACILITY_NOT_SET)
1098                         fatal("%.200s line %d: unsupported log facility '%s'",
1099                             filename, linenum, arg ? arg : "<NONE>");
1100                 if (*intptr == -1)
1101                         *intptr = (SyslogFacility) value;
1102                 break;
1103 
1104         case sLogLevel:
1105                 intptr = (int *) &options->log_level;
1106                 arg = strdelim(&cp);
1107                 value = log_level_number(arg);
1108                 if (value == SYSLOG_LEVEL_NOT_SET)
1109                         fatal("%.200s line %d: unsupported log level '%s'",
1110                             filename, linenum, arg ? arg : "<NONE>");
1111                 if (*intptr == -1)
1112                         *intptr = (LogLevel) value;
1113                 break;
1114 
1115         case sAllowTcpForwarding:
1116                 intptr = &options->allow_tcp_forwarding;
1117                 goto parse_flag;
1118 
1119         case sUsePrivilegeSeparation:
1120                 log("%s line %d: ignoring UsePrivilegeSeparation option value."
1121                     " This option is always on.", filename, linenum);
1122                 while (arg)
1123                         arg = strdelim(&cp);
1124                 break;
1125 
1126         case sAllowUsers:
1127                 while (((arg = strdelim(&cp)) != NULL) && *arg != '\0') {
1128                         if (options->num_allow_users >= MAX_ALLOW_USERS)
1129                                 fatal("%s line %d: too many allow users.",
1130                                     filename, linenum);
1131                         options->allow_users[options->num_allow_users++] =
1132                             xstrdup(arg);
1133                 }
1134                 break;
1135 
1136         case sDenyUsers:
1137                 while (((arg = strdelim(&cp)) != NULL) && *arg != '\0') {
1138                         if (options->num_deny_users >= MAX_DENY_USERS)
1139                                 fatal( "%s line %d: too many deny users.",
1140                                     filename, linenum);
1141                         options->deny_users[options->num_deny_users++] =
1142                             xstrdup(arg);
1143                 }
1144                 break;
1145 
1146         case sAllowGroups:
1147                 while (((arg = strdelim(&cp)) != NULL) && *arg != '\0') {
1148                         if (options->num_allow_groups >= MAX_ALLOW_GROUPS)
1149                                 fatal("%s line %d: too many allow groups.",
1150                                     filename, linenum);
1151                         options->allow_groups[options->num_allow_groups++] =
1152                             xstrdup(arg);
1153                 }
1154                 break;
1155 
1156         case sDenyGroups:
1157                 while (((arg = strdelim(&cp)) != NULL) && *arg != '\0') {
1158                         if (options->num_deny_groups >= MAX_DENY_GROUPS)
1159                                 fatal("%s line %d: too many deny groups.",
1160                                     filename, linenum);
1161                         options->deny_groups[options->num_deny_groups++] = xstrdup(arg);
1162                 }
1163                 break;
1164 
1165         case sCiphers:
1166                 arg = strdelim(&cp);
1167                 if (!arg || *arg == '\0')
1168                         fatal("%s line %d: Missing argument.", filename, linenum);
1169                 if (!ciphers_valid(arg))
1170                         fatal("%s line %d: Bad SSH2 cipher spec '%s'.",
1171                             filename, linenum, arg ? arg : "<NONE>");
1172                 if (options->ciphers == NULL)
1173                         options->ciphers = xstrdup(arg);
1174                 break;
1175 
1176         case sMacs:
1177                 arg = strdelim(&cp);
1178                 if (!arg || *arg == '\0')
1179                         fatal("%s line %d: Missing argument.", filename, linenum);
1180                 if (!mac_valid(arg))
1181                         fatal("%s line %d: Bad SSH2 mac spec '%s'.",
1182                             filename, linenum, arg ? arg : "<NONE>");
1183                 if (options->macs == NULL)
1184                         options->macs = xstrdup(arg);
1185                 break;
1186 
1187         case sProtocol:
1188                 intptr = &options->protocol;
1189                 arg = strdelim(&cp);
1190                 if (!arg || *arg == '\0')
1191                         fatal("%s line %d: Missing argument.", filename, linenum);
1192                 value = proto_spec(arg);
1193                 if (value == SSH_PROTO_UNKNOWN)
1194                         fatal("%s line %d: Bad protocol spec '%s'.",
1195                             filename, linenum, arg ? arg : "<NONE>");
1196                 if (*intptr == SSH_PROTO_UNKNOWN)
1197                         *intptr = value;
1198                 break;
1199 
1200         case sSubsystem:
1201                 if (options->num_subsystems >= MAX_SUBSYSTEMS) {
1202                         fatal("%s line %d: too many subsystems defined.",
1203                             filename, linenum);
1204                 }
1205                 arg = strdelim(&cp);
1206                 if (!arg || *arg == '\0')
1207                         fatal("%s line %d: Missing subsystem name.",
1208                             filename, linenum);
1209                 if (!*activep) {
1210                         arg = strdelim(&cp);
1211                         break;
1212                 }
1213                 for (i = 0; i < options->num_subsystems; i++)
1214                         if (strcmp(arg, options->subsystem_name[i]) == 0)
1215                                 fatal("%s line %d: Subsystem '%s' already defined.",
1216                                     filename, linenum, arg);
1217                 options->subsystem_name[options->num_subsystems] = xstrdup(arg);
1218                 arg = strdelim(&cp);
1219                 if (!arg || *arg == '\0')
1220                         fatal("%s line %d: Missing subsystem command.",
1221                             filename, linenum);
1222                 options->subsystem_command[options->num_subsystems] = xstrdup(arg);
1223 
1224                 /*
1225                  * Collect arguments (separate to executable), including the
1226                  * name of the executable, in a way that is easier to parse
1227                  * later.
1228                  */
1229                 p = xstrdup(arg);
1230                 len = strlen(p) + 1;
1231                 while ((arg = strdelim(&cp)) != NULL && *arg != '\0') {
1232                         len += 1 + strlen(arg);
1233                         p = xrealloc(p, len);
1234                         strlcat(p, " ", len);
1235                         strlcat(p, arg, len);
1236                 }
1237                 options->subsystem_args[options->num_subsystems] = p;
1238                 options->num_subsystems++;
1239                 break;
1240 
1241         case sMaxStartups:
1242                 arg = strdelim(&cp);
1243                 if (!arg || *arg == '\0')
1244                         fatal("%s line %d: Missing MaxStartups spec.",
1245                             filename, linenum);
1246                 if ((n = sscanf(arg, "%d:%d:%d",
1247                     &options->max_startups_begin,
1248                     &options->max_startups_rate,
1249                     &options->max_startups)) == 3) {
1250                         if (options->max_startups_begin >
1251                             options->max_startups ||
1252                             options->max_startups_rate > 100 ||
1253                             options->max_startups_rate < 1)
1254                                 fatal("%s line %d: Illegal MaxStartups spec.",
1255                                     filename, linenum);
1256                 } else if (n != 1)
1257                         fatal("%s line %d: Illegal MaxStartups spec.",
1258                             filename, linenum);
1259                 else
1260                         options->max_startups = options->max_startups_begin;
1261                 break;
1262 
1263         case sBanner:
1264                 charptr = &options->banner;
1265                 goto parse_filename;
1266         /*
1267          * These options can contain %X options expanded at
1268          * connect time, so that you can specify paths like:
1269          *
1270          * AuthorizedKeysFile   /etc/ssh_keys/%u
1271          */
1272         case sAuthorizedKeysFile:
1273         case sAuthorizedKeysFile2:
1274                 charptr = (opcode == sAuthorizedKeysFile) ?
1275                     &options->authorized_keys_file :
1276                     &options->authorized_keys_file2;
1277                 goto parse_filename;
1278 
1279         case sClientAliveInterval:
1280                 intptr = &options->client_alive_interval;
1281                 goto parse_time;
1282 
1283         case sClientAliveCountMax:
1284                 intptr = &options->client_alive_count_max;
1285                 goto parse_int;
1286 
1287         case sMaxAuthTries:
1288                 intptr = &options->max_auth_tries;
1289                 goto parse_int;
1290 
1291         case sMaxAuthTriesLog:
1292                 intptr = &options->max_auth_tries_log;
1293                 goto parse_int;
1294 
1295         case sLookupClientHostnames:
1296                 intptr = &options->lookup_client_hostnames;
1297                 goto parse_flag;
1298 
1299         case sUseOpenSSLEngine:
1300                 intptr = &options->use_openssl_engine;
1301                 goto parse_flag;
1302 
1303         case sChrootDirectory:
1304                 charptr = &options->chroot_directory;
1305 
1306                 arg = strdelim(&cp);
1307                 if (arg == NULL || *arg == '\0')
1308                         fatal("%s line %d: missing directory name for "
1309                             "ChrootDirectory.", filename, linenum);
1310                 if (*activep && *charptr == NULL)
1311                         *charptr = xstrdup(arg);
1312                 break;
1313 
1314         case sPreUserauthHook:
1315                 charptr = &options->pre_userauth_hook;
1316                 goto parse_filename;
1317 
1318         case sMatch:
1319                 if (cmdline)
1320                         fatal("Match directive not supported as a command-line "
1321                            "option");
1322                 value = match_cfg_line(&cp, linenum, user, host, address);
1323                 if (value < 0)
1324                         fatal("%s line %d: Bad Match condition", filename,
1325                             linenum);
1326                 *activep = value;
1327                 break;
1328 
1329         case sDeprecated:
1330                 log("%s line %d: Deprecated option %s",
1331                     filename, linenum, arg);
1332                 while (arg)
1333                     arg = strdelim(&cp);
1334                 break;
1335 
1336         case sPAMServicePrefix:
1337                 arg = strdelim(&cp);
1338                 if (!arg || *arg == '\0')
1339                         fatal("%s line %d: Missing argument.",
1340                             filename, linenum);
1341                 if (options->pam_service_name != NULL)
1342                         fatal("%s line %d: PAMServiceName and PAMServicePrefix "
1343                             "are mutually exclusive.", filename, linenum);
1344                 if (options->pam_service_prefix == NULL)
1345                         options->pam_service_prefix = xstrdup(arg);
1346                 break;
1347 
1348         case sPAMServiceName:
1349                 arg = strdelim(&cp);
1350                 if (!arg || *arg == '\0')
1351                         fatal("%s line %d: Missing argument.",
1352                             filename, linenum);
1353                 if (options->pam_service_prefix != NULL)
1354                         fatal("%s line %d: PAMServiceName and PAMServicePrefix "
1355                             "are mutually exclusive.", filename, linenum);
1356                 if (options->pam_service_name == NULL)
1357                         options->pam_service_name = xstrdup(arg);
1358                 break;
1359 
1360         case sPubKeyPlugin:
1361                 charptr = &options->pubkey_plugin;
1362                 goto parse_filename;
1363 
1364         default:
1365                 fatal("%s line %d: Missing handler for opcode %s (%d)",
1366                     filename, linenum, arg, opcode);
1367         }
1368         if ((arg = strdelim(&cp)) != NULL && *arg != '\0')
1369                 fatal("%s line %d: garbage at end of line; \"%.200s\".",
1370                     filename, linenum, arg);
1371         return 0;
1372 }
1373 
1374 
1375 /* Reads the server configuration file. */
1376 
1377 void
1378 load_server_config(const char *filename, Buffer *conf)
1379 {
1380         char line[1024], *cp;
1381         FILE *f;
1382 
1383         debug2("%s: filename %s", __func__, filename);
1384         if ((f = fopen(filename, "r")) == NULL) {
1385                 perror(filename);
1386                 exit(1);
1387         }
1388         buffer_clear(conf);
1389         while (fgets(line, sizeof(line), f)) {
1390                 /*
1391                  * Trim out comments and strip whitespace
1392                  * NB - preserve newlines, they are needed to reproduce
1393                  * line numbers later for error messages
1394                  */
1395                 if ((cp = strchr(line, '#')) != NULL)
1396                         memcpy(cp, "\n", 2);
1397                 cp = line + strspn(line, " \t\r");
1398 
1399                 buffer_append(conf, cp, strlen(cp));
1400         }
1401         buffer_append(conf, "\0", 1);
1402         fclose(f);
1403         debug2("%s: done config len = %d", __func__, buffer_len(conf));
1404 }
1405 
1406 void
1407 parse_server_match_config(ServerOptions *options, const char *user,
1408     const char *host, const char *address)
1409 {
1410         ServerOptions mo;
1411 
1412         initialize_server_options(&mo);
1413         parse_server_config(&mo, "reprocess config", &cfg, user, host, address);
1414         copy_set_server_options(options, &mo, 0);
1415 }
1416 
1417 
1418 
1419 /* Helper macros */
1420 #define M_CP_INTOPT(n) do {\
1421         if (src->n != -1) \
1422                 dst->n = src->n; \
1423 } while (0)
1424 #define M_CP_STROPT(n) do {\
1425         if (src->n != NULL) { \
1426                 if (dst->n != NULL) \
1427                         xfree(dst->n); \
1428                 dst->n = src->n; \
1429         } \
1430 } while(0)
1431 
1432 /*
1433  * Copy any supported values that are set.
1434  *
1435  * If the preauth flag is set, we do not bother copying the the string or
1436  * array values that are not used pre-authentication, because any that we
1437  * do use must be explictly sent in mm_getpwnamallow().
1438  */
1439 void
1440 copy_set_server_options(ServerOptions *dst, ServerOptions *src, int preauth)
1441 {
1442         M_CP_INTOPT(password_authentication);
1443         M_CP_INTOPT(gss_authentication);
1444         M_CP_INTOPT(rsa_authentication);
1445         M_CP_INTOPT(pubkey_authentication);
1446         M_CP_INTOPT(hostbased_authentication);
1447         M_CP_INTOPT(kbd_interactive_authentication);
1448         M_CP_INTOPT(permit_root_login);
1449         M_CP_INTOPT(permit_empty_passwd);
1450         M_CP_INTOPT(allow_tcp_forwarding);
1451         M_CP_INTOPT(gateway_ports);
1452         M_CP_INTOPT(x11_display_offset);
1453         M_CP_INTOPT(x11_forwarding);
1454         M_CP_INTOPT(x11_use_localhost);
1455         M_CP_INTOPT(max_auth_tries);
1456         M_CP_STROPT(banner);
1457 
1458         if (preauth)
1459                 return;
1460         M_CP_STROPT(chroot_directory);
1461 }
1462 
1463 #undef M_CP_INTOPT
1464 #undef M_CP_STROPT
1465 
1466 void
1467 parse_server_config(ServerOptions *options, const char *filename, Buffer *conf,
1468     const char *user, const char *host, const char *address)
1469 {
1470         int active, linenum, bad_options = 0;
1471         char *cp, *obuf, *cbuf;
1472 
1473         debug2("%s: config %s len %d", __func__, filename, buffer_len(conf));
1474 
1475         obuf = cbuf = xstrdup(buffer_ptr(conf));
1476         active = user ? 0 : 1;
1477         linenum = 1;
1478         while ((cp = strsep(&cbuf, "\n")) != NULL) {
1479                 if (process_server_config_line(options, cp, filename,
1480                     linenum++, &active, user, host, address) != 0)
1481                         bad_options++;
1482         }
1483         xfree(obuf);
1484         if (bad_options > 0)
1485                 fatal("%s: terminating, %d bad configuration options",
1486                     filename, bad_options);
1487 }
1488 
1489 
1490 /*
1491  * Note that "none" is a special path having the same affect on sshd
1492  * configuration as not specifying ChrootDirectory at all.
1493  */
1494 int
1495 chroot_requested(char *chroot_directory)
1496 {
1497         return (chroot_directory != NULL &&
1498             strcasecmp(chroot_directory, "none") != 0);
1499 }