1:   2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16:  17:  18:  19:  20:  21:  22:  23:  24:  25:  26:  27:  28:  29:  30:  31:  32:  33:  34:  35:  36:  37:  38:  39:  40:  41:  42:  43:  44:  45:  46:  47:  48:  49:  50:  51:  52:  53:  54:  55:  56:  57:  58:  59:  60:  61:  62:  63:  64:  65:  66:  67:  68:  69:  70:  71:  72:  73:  74:  75:  76:  77:  78:  79:  80:  81:  82:  83:  84:  85:  86:  87:  88:  89:  90:  91:  92:  93:  94:  95:  96:  97:  98:  99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 388: 389: 390: 391: 392: 393: 394: 395: 396: 397: 398: 399: 400: 401: 402: 403: 404: 405: 406: 407: 408: 409: 410: 411: 412: 413: 414: 415: 416: 417: 418: 419: 420: 421: 422: 423: 424: 425: 426: 427: 428: 429: 430: 431: 432: 433: 434: 435: 436: 437: 438: 439: 440: 441: 442: 443: 444: 445: 446: 447: 448: 449: 450: 451: 452: 453: 454: 455: 456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470: 471: 472: 473: 474: 475: 476: 477: 478: 479: 480: 481: 482: 483: 484: 485: 486: 487: 488: 489: 490: 491: 492: 493: 494: 495: 496: 497: 498: 499: 500: 501: 502: 503: 504: 505: 506: 507: 508: 509: 510: 511: 512: 513: 514: 515: 516: 517: 518: 519: 520: 521: 522: 523: 524: 525: 526: 527: 528: 529: 530: 531: 532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542: 543: 544: 545: 546: 547: 548: 549: 550: 551: 552: 553: 554: 555: 556: 557: 558: 559: 560: 561: 562: 563: 564: 565: 566: 567: 568: 569: 570: 571: 572: 573: 574: 575: 576: 577: 578: 579: 580: 581: 582: 583: 584: 585: 586: 587: 588: 589: 590: 591: 592: 593: 594: 595: 596: 597: 598: 599: 600: 601: 602: 603: 604: 605: 606: 607: 608: 609: 610: 611: 612: 613: 614: 615: 616: 617: 618: 619: 620: 621: 622: 623: 624: 625: 626: 627: 628: 629: 630: 631: 632: 633: 634: 635: 636: 637: 638: 639: 640: 641: 642: 643: 644: 645: 646: 647: 648: 649: 650: 651: 652: 653: 654: 655: 656: 657: 658: 659: 
<?php declare(strict_types=1);
    /**
     * Copyright (C) Apis Networks, Inc - All Rights Reserved.
     *
     * Unauthorized copying of this file, via any medium, is
     * strictly prohibited without consent. Any dissemination of
     * material herein is prohibited.
     *
     * For licensing inquiries email <licensing@apisnetworks.com>
     *
     * Written by Matt Saladna <matt@apisnetworks.com>, April 2018
     */

    use Opcenter\Net\Fail2ban;
    use Opcenter\Net\Firewall;
    use Opcenter\Net\Firewall\Delegated;
    use Opcenter\Net\Firewall\Ipset;
    use Opcenter\Net\Ip6;
    use Opcenter\Net\IpCommon;
    use Opcenter\Service\Contracts\DefaultNullable;

    /**
     * Class Rampart_Module
     *
     * Integrates into fail2ban. Provides short-term and long-term blocks
     */
    class Rampart_Module extends Module_Skeleton
    {
        public const FAIL2BAN_IPT_PREFIX = RAMPART_PREFIX;
        public const FAIL2BAN_DRIVER = RAMPART_DRIVER;
        public const FAIL2BAN_CACHE_KEY = 'f2b';
        // @var array list of permanent lists
        public const PLIST_NAMES = ['whitelist', 'blacklist', 'whitelist6', 'blacklist6'];
        protected $confMapping;

        protected $exportedFunctions = [
            '*'                  => PRIVILEGE_ADMIN | PRIVILEGE_SITE,
            'ban'                => PRIVILEGE_ADMIN,
            'blacklist'          => PRIVILEGE_ADMIN,
            'whitelist'          => PRIVILEGE_ADMIN,
            'get_plist'          => PRIVILEGE_ADMIN,
            'get_jail_entries'   => PRIVILEGE_ADMIN,
            'flush'              => PRIVILEGE_ADMIN,
            'get_delegated_list' => PRIVILEGE_SITE,
            'can_delegate'       => PRIVILEGE_SITE,
            'max_delegations'    => PRIVILEGE_SITE,
            'temp'               => PRIVILEGE_SITE
        ];

        public function __construct()
        {
            parent::__construct();
            if (static::FAIL2BAN_DRIVER !== 'ipset') {
                $this->exportedFunctions = [
                    'whitelist' => PRIVILEGE_NONE,
                    'blacklist' => PRIVILEGE_NONE
                ] + $this->exportedFunctions;
            } else if (version_compare(APNSCP_VERSION, '3.1', '>=')) {
                $this->exportedFunctions['whitelist'] |= PRIVILEGE_SITE;
            }
        }

        /**
         * Authenticated client IP or $ip is banned
         *
         * @param string|null $ip
         * @param string|null $jail optional jail to check
         * @return bool
         */
        public function is_banned(string $ip = null, string $jail = null): bool
        {
            if (!IS_CLI) {
                return $this->query('rampart_is_banned', $ip, $jail);
            }
            if (false === ($ip = $this->checkInput($ip, $jail))) {
                return false;
            }

            return count($this->getMatches($ip, $jail)) > 0;
        }

        /**
         * Get services for which IP is banned
         *
         * @param string $ip
         * @return array
         */
        public function banned_services(string $ip = null): array
        {
            if (!IS_CLI) {
                return $this->query('rampart_banned_services', $ip);
            }
            if (false === ($ip = $this->checkInput($ip))) {
                return false;
            }

            return $this->getMatches($ip);
        }

        /**
         * Get reason for ban
         *
         * @param string|null $ip
         * @param string|null $jail
         * @return string|null
         */
        public function get_reason(string $ip = null, string $jail = null): ?string
        {
            if (!IS_CLI) {
                return $this->query('rampart_get_reason', $ip, $jail);
            }
            if (!RAMPART_SHOW_REASON && !($this->permission_level & PRIVILEGE_ADMIN)) {
                return null;
            }

            if (false === ($ip = $this->checkInput($ip))) {
                return null;
            }

            $matches = $this->getMatches($ip);

            $db = Fail2ban::getDatabaseHandler();
            $fragment = "ip = '$ip'";
            if ($jail) {
                $fragment .= ' AND jail = ' . $db->quote($jail) . '';
            }

            $query = "SELECT data FROM bans WHERE $fragment ORDER BY timeofban DESC LIMIT 1";
            $rs = $db->query($query);
            if (!$rs) {
                return null;
            }
            $data = json_decode(array_get($rs->fetch(\PDO::FETCH_ASSOC), 'data', 'null'), true);
            $last = array_get($data, 'matches', []);
            return  $data ? array_pop($last) : null;
        }

        /**
         * Perform permission validation and IP transformation
         *
         * @param string|null $ip
         * @param string|null $jail
         * @return false|string
         */
        protected function checkInput(string $ip = null, string $jail = null)
        {
            if ($this->permission_level & PRIVILEGE_SITE) {
                if ($ip) {
                    return error('IP address may not be specified if site admin');
                }
                if ($jail) {
                    return error('jail may not be specified if site admin');
                }
                if (!$this->enabled()) {
                    return error('user may not remove block');
                }
            }
            if (!$ip) {
                $ip = \Auth::client_ip();
            }
            if (!$ip) {
                report('Odd?' . var_export($_ENV, true));
            }
            if (false === inet_pton($ip)) {
                return error("invalid IP address `%s'", $ip);
            }

            return $ip;
        }

        /**
         * Get matching rules where IP is banned
         *
         * @param string      $ip
         * @param string|null $jail optional jail to restrict check
         * @return array jails banned
         */
        private function getMatches(string $ip, string $jail = null): array
        {
            $banned = [];
            if ($jail) {
                $jail = static::FAIL2BAN_IPT_PREFIX . $jail;
            }
            $matches = (new Firewall)->getEntriesFromChain($jail);
            if ($jail) {
                $matches = [$jail => $matches];
            }

            foreach ($matches as $chain => $records) {
                foreach ($records as $record) {
                    if ($record->getHost() === $ip && $record->isBlocked()) {
                        $banned[$chain] = 1;
                    }
                }
            }

            return array_keys($banned);
        }

        /**
         * Disallow an IP address from service
         *
         * @param string $ip
         * @param string $jail
         * @return bool
         */
        public function ban(string $ip, string $jail): bool
        {
            if (!IS_CLI) {
                return $this->query('rampart_ban', $ip, $jail);
            }
            if (!in_array($jail, $this->get_jails(), true)) {
                return error("Unknown jail `%s'", $jail);
            }
            if (false === $this->checkInput($ip, $jail)) {
                return false;
            }
            $ret = \Util_Process_Safe::exec('fail2ban-client set %s banip %s', $jail, $ip);

            return $ret['success'];
        }

        /**
         * Temporarily whitelist an IP
         *
         * @param string $ip
         * @param int    $duration
         * @return bool
         */
        public function temp(string $ip = null, int $duration = 7200): bool
        {
            if ($duration < 1) {
                return error('Non-sensical usage of %s: %s', 'duration', $duration);
            }
            $ip = $ip ?? \Auth::client_ip();
            // fetch whitelist
            if (\in_array($ip, $this->get_delegated_list(), true)) {
                return true;
            }

            if (!$this->whitelist($ip, 'add')) {
                return false;
            }

            return $this->pman_schedule_api_cmd('rampart_whitelist', [$ip, 'remove'], "now + ${duration} seconds");
        }

        /**
         * Whitelist IP acccess
         *
         * @param string|null $ip whitelist named or present IP
         * @param string $mode
         * @return bool
         */
        public function whitelist(string $ip = null, string $mode = 'add'): bool
        {
            if (!IS_CLI) {
                if (!$this->query('rampart_whitelist', $ip, $mode)) {
                    return false;
                }
                $this->getAuthContext()->reset();
                return true;
            }

            if (!$ip) {
                $ip = \Auth::client_ip();
            }

            if ($mode !== 'add' && $mode !== 'remove' && $mode !== 'delete') {
                return error('Unknown whitelist operation %s', $mode);
            }
            $fn = $mode === 'add' ? 'add' : 'remove';

            if ( !($this->permission_level & PRIVILEGE_SITE) ) {
                if (!$this->ipsetWrapper('whitelist', $ip, $mode)) {
                    return false;
                }
                // use "site0" for admin
                return $fn === 'add' ? Delegated::markDelegated($ip, 'site0') :
                    Delegated::releaseDelegation($ip, 'site0');
            }

            if ($this->auth_is_demo()) {
                return error('Demo accounts cannot alter whitelist');
            } else if (!version_compare(APNSCP_VERSION, '3.1', '>=')) {
                return error('Delegated whitelisting supported on v8+ platforms');
            } else if (false !== strpos($ip, '/')) {
                return error('Delegated whitelisting cannot accept ranges');
            } else if (!$this->addressValid($ip)) {
                return false;
            }

            return Delegated::instantiateContexted($this->getAuthContext())->$fn($ip);

        }

        /**
         * Account supports delegation abilities
         *
         * @return bool
         */
        public function can_delegate(): bool
        {
            return Delegated::instantiateContexted($this->getAuthContext())->permitted();
        }

        /**
         * Get maximum number of delegated entries
         *
         * @return int|null
         */
        public function max_delegations(): ?int
        {
            if (!$this->can_delegate()) {
                return 0;
            }
            $val = $this->getServiceValue('rampart', 'max', RAMPART_DELEGATED_WHITELIST);
            if ($val === DefaultNullable::NULLABLE_MARKER) {
                /**
                 * (new ConfigurationContext('rampart', new SiteConfiguration('')))->getValidatorClass('max')->getDefault()
                 * is a little slow, let's bypass this logic and just pull from config.ini
                 */
                $val = RAMPART_DELEGATED_WHITELIST;
            }
            return $val;
        }

        /**
         * Rampart service enabled
         *
         * @return bool
         */
        public function enabled(): bool
        {
            return (bool)$this->getConfig('rampart', 'enabled', true);
        }

        /**
         * Return a list of delegated whitelist entries
         *
         * @return array
         */
        public function get_delegated_list(): array
        {
            if (!version_compare(APNSCP_VERSION, '3.1', '>=')) {
                return [];
            }
            // wrapper for get_plist
            return Delegated::instantiateContexted($this->getAuthContext())->get();
        }

        /**
         * ipset wrapper
         *
         * @param string $set set name
         * @param string $address ip address or CIDR
         * @param string $mode
         * @return bool
         */
        private function ipsetWrapper(string $set, string $address, string $mode): bool {
            if (!$this->addressValid($address)) {
                return false;
            } else if (static::FAIL2BAN_DRIVER !== 'ipset') {
                return error('ipset is not configured as Rampart driver');
            }

            if (($set === 'whitelist' || $set === 'blacklist') && Ip6::valid($address)) {
                $set .= '6';
            }
            if ($mode === 'delete') {
                $mode = 'remove';
            }

            if ($mode !== 'add' && $mode !== 'remove') {
                return error("Unknown ipset wrapper mode `%s'", $mode);
            }

            return Ipset::$mode($set, $address);
        }

        /**
         * Get permanent list entries
         *
         * @param string $list "blacklist" or "whitelist"
         * @return array|bool
         */
        public function get_plist(string $list)
        {
            if (!IS_CLI) {
                return $this->query('rampart_get_plist', $list);
            }
            if (!\in_array($list, static::PLIST_NAMES, true)) {
                return error("Unknown permanent list `%s'", $list);
            }
            return array_column(Ipset::getSetMembers($list), 'host');
        }

        /**
         * Get jail entries
         *
         * @param string $jail
         * @return array|bool array or false on failure
         */
        public function get_jail_entries(?string $jail)
        {
            if (!IS_CLI) {
                return $this->query('rampart_get_jail_entries', $jail);
            }
            $list = static::FAIL2BAN_IPT_PREFIX . $jail;
            if (!$jail) {
                $items = (array)(new Firewall())->getEntriesFromChain();
                return json_decode(json_encode($items), true);
            }
            if (!\in_array($jail, $this->get_jails(), true)) {
                return error("Unknown jail `%s'", $jail);
            }

            return array_column((array)(new Firewall())->getEntriesFromChain($list), 'host');
        }

        /**
         * Flush jails
         *
         * @param string|null $jail
         * @return bool
         */
        public function flush(string $jail = null): bool
        {
            if (!IS_CLI) {
                return $this->query('rampart_flush', $jail);
            }

            if ($jail && !\in_array($jail, $this->get_jails(), true)) {
                return error("Unknown jail `%s'", $jail);
            } else if (!$jail) {
                $ret = \Util_Process::exec('fail2ban-client unban --all');
                return $ret['success'];
            }

            foreach ((array)$jail as $j) {
                $ret = \Util_Process::exec('fail2ban-client reload --unban %s', $j);
                if (!$ret['success']) {
                    warn("Failed to empty jail `%s'", $jail);
                }
            }
            return true;
        }

        /**
         * Permanently block access
         *
         * @param string $ip
         * @param string $mode add, remove, or set
         * @return bool
         */
        public function blacklist(string $ip, string $mode = 'add'): bool
        {
            if (!IS_CLI) {
                return $this->query('rampart_blacklist', $ip, $mode);
            }

            return $this->ipsetWrapper('blacklist', $ip, $mode);

        }

        /**
         * Specified address is valid address or range
         *
         * @param string $address
         * @return bool
         */
        private function addressValid(string $address): bool
        {
            $class = '';
            if (!IpCommon::supported($address, $class)) {
                return error('Requested address family %s disabled on server', $class);
            }
            if (!IpCommon::valid($address)) {
                return error("Address `%s' is invalid %s",
                    $address, $class
                );
            }

            return true;
        }

        /**
         * Get active jails
         *
         * @return array
         */
        public function get_jails(): array
        {
            static $jails;
            if ($jails === null) {
                $cache = \Cache_Global::spawn($this->getAuthContext());
                if (false === ($jails = $cache->get('rampart.jails'))) {
                    if (!IS_CLI) {
                        return $this->query('rampart_get_jails');
                    }
                    $jails = Fail2ban::getJails();
                    $cache->set('rampart.jails', $jails, 1800);
                }
            }

            return $jails ?? [];
        }

        /**
         * Unban an IP address
         *
         * @param string|null $ip
         * @param string|null $jail optional jail to remove
         * @return bool
         */
        public function unban(string $ip = null, string $jail = null): bool
        {
            if (!IS_CLI) {
                return $this->query('rampart_unban', $ip, $jail);
            }
            if ($this->auth_is_demo()) {
                return error('cannot unban IP address in demo mode');
            }
            if (false === ($ip = $this->checkInput($ip, $jail))) {
                return false;
            }
            foreach ($this->getMatches($ip, $jail) as $chain) {
                if (!$jail = $this->chain2Jail($chain)) {
                    warn("Address blocked in `%s' but not recognized Rampart jail - cannot unban %s", $chain, $ip);
                    continue;
                }

                $ret = \Util_Process_Safe::exec('fail2ban-client set %s unbanip %s', $jail, $ip);
                if ($ret['success']) {
                    info("Unbanned `%s' from jail `%s'", $ip, $jail);
                } else {
                    warn("Failed to unban `%s' from jail `%s'", $ip, $jail);
                }
            }

            return true;
        }

        /**
         * Get ban counts for each jail
         *
         * @param int        $begin begin ts inclusive
         * @param int|null   $end   end ts exclusive
         * @param array|null $jails restrict to jails
         * @return array
         */
        public function bans_since(int $begin, int $end = null, array $jails = null): array
        {
            if (!IS_CLI) {
                return $this->query('rampart_bans_since', $begin, $end, $jails);
            }
            if ($begin < 0 || $end && $end < 0) {
                error('Invalid timestamp');
                return [];
            } else if ($end && $begin > $end) {
                return error('Begin TS may not be newer than end TS');
            }
            $fragment = "timeofban >= $begin";
            if ($end) {
                $fragment .= " AND timeofban < $end";
            }
            if ($jails) {
                $diff = array_diff($jails, $this->get_jails());
                if ($diff) {
                    error('Invalid jails specified: %s', implode(',', $diff));
                    return [];
                }
                $fragment .= " AND jail IN ('" . implode("','", $jails) . "')";
            }
            $query = "SELECT count(*) AS count, jail FROM bans WHERE $fragment GROUP BY (jail)";
            $db = Fail2ban::getDatabaseHandler();
            $built = [];
            foreach ($db->query($query)->fetchAll(\PDO::FETCH_ASSOC) as $rec) {
                $built[$rec['jail']] = (int)$rec['count'];
            }

            return $built;
        }

        /**
         * Convert an iptables rule into a fail2ban jail
         *
         * @param string $chain iptables chain
         * @return null|string
         */
        protected function chain2Jail(string $chain): ?string
        {
            if (isset($this->confMapping[$chain])) {
                return $this->confMapping[$chain];
            }
            $jails = $this->getJailConfig();
            $chain = ' ' . $chain . ' ';
            foreach ($jails as $jail => $actions) {
                foreach ($actions as $action) {
                    if (false !== strpos($action, $chain)) {
                        $this->confMapping[$chain] = $jail;

                        return $jail;
                    }
                }
            }

            return null;
        }

        protected function getJailConfig(): ?array
        {
            $cache = \Cache_Global::spawn();
            $key = static::FAIL2BAN_CACHE_KEY . '.jail-config';
            if (false === ($jails = $cache->get($key))) {
                if (null === ($jails = Fail2ban::map())) {
                    warn('error retrieving fail2ban jail configuration');

                    return [];
                }
                $cache->set($key, $jails, 86400);
            }

            if (is_string($jails)) {
                report($jails);
            }

            return $jails;
        }

        public function _cron(Cronus $cron)
        {
            if (!TELEMETRY_ENABLED) {
                return;
            }

            $rampartMetric = new \Daphnie\Metrics\Rampart();
            $lastRun = 0;
            $attrCheck = $rampartMetric->mutate('recidive')->metricAsAttribute();
            if ($this->telemetry_has($attrCheck)) {
                $lastRun = array_get($this->telemetry_get($attrCheck, null), 'ts', 0);
            }

            $attrs = \Daphnie\Metrics\Rampart::getAttributeMap();
            $jails = array_keys($attrs);
            $bans = $this->bans_since($lastRun, time(), $jails);

            $collector = new \Daphnie\Collector(PostgreSQL::pdo());
            foreach ($jails as $jail) {
                $name = $rampartMetric->mutate($jail);
                $collector->add($name->metricAsAttribute(), null, array_get($bans, $jail, 0));
            }
        }

        public function _housekeeping()
        {
            $this->getJailConfig();
        }
    }