Ejemplo n.º 1
0
 public static function isCrawler($UA)
 {
     $browscap = new wfBrowscap();
     $b = $browscap->getBrowser($UA);
     if (!$b || $b['Parent'] == 'DefaultProperties') {
         $log = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
         $IP = wfUtils::getIP();
         return !(isset($_COOKIE['wordfence_verifiedHuman']) && $log->validateVerifiedHumanCookie($_COOKIE['wordfence_verifiedHuman'], $UA, $IP));
     } else {
         if (isset($b['Crawler']) && $b['Crawler']) {
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 2
0
    /**
     * Permanently blocks all temporarily locked out IPs.
     */
    public static function ajax_permanentlyBlockAllIPs_callback()
    {
        /** @var wpdb $wpdb */
        global $wpdb;
        $IPs = array();
        $type = !empty($_REQUEST['type']) ? $_REQUEST['type'] : null;
        $reason = !empty($_REQUEST['reason']) ? $_REQUEST['reason'] : 'Manual block by administrator';
        switch ($type) {
            case 'throttled':
                $IPs = $wpdb->get_col('SELECT DISTINCT IP FROM ' . $wpdb->base_prefix . 'wfThrottleLog');
                break;
            case 'lockedOut':
                $lockoutSecs = wfConfig::get('loginSec_lockoutMins') * 60;
                $IPs = $wpdb->get_col($wpdb->prepare('SELECT DISTINCT IP FROM ' . $wpdb->base_prefix . 'wfLockedOut
				WHERE blockedTime + %d > UNIX_TIMESTAMP()', $lockoutSecs));
                break;
            case 'blocked':
                $blockedTime = wfConfig::get('blockedTime');
                $IPs = $wpdb->get_col($wpdb->prepare('SELECT DISTINCT IP FROM ' . $wpdb->base_prefix . 'wfBlocks
				WHERE wfsn = 0
				AND permanent = 0
				AND blockedTime + %d > UNIX_TIMESTAMP()', $blockedTime));
                break;
        }
        $log = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
        if ($IPs && is_array($IPs)) {
            foreach ($IPs as $IP) {
                $log->blockIP(wfUtils::inet_ntop($IP), $reason, false, true);
            }
        }
        switch ($type) {
            case 'lockedOut':
                if ($IPs) {
                    foreach ($IPs as &$IP) {
                        $IP = $wpdb->prepare('%s', $IP);
                    }
                    $wpdb->query('DELETE FROM ' . $wpdb->base_prefix . 'wfLockedOut WHERE IP IN (' . join(', ', $IPs) . ')');
                }
                break;
        }
        return array('ok' => 1);
    }
Ejemplo n.º 3
0
 /**
  * @param $action
  * @return bool|string|void
  */
 public static function updateBlockedIPs($action)
 {
     //'add' or 'remove'
     if (wfConfig::get('cacheType') != 'falcon') {
         return;
     }
     $htaccessPath = self::getHtaccessPath();
     if (!$htaccessPath) {
         return "Wordfence could not find your .htaccess file.";
     }
     if ($action == 'remove') {
         $fh = @fopen($htaccessPath, 'r+');
         if (!$fh) {
             $err = error_get_last();
             return $err['message'];
         }
         flock($fh, LOCK_EX);
         fseek($fh, 0, SEEK_SET);
         //start of file
         clearstatcache();
         $contents = @fread($fh, filesize($htaccessPath));
         if (!$contents) {
             fclose($fh);
             return "Could not read from {$htaccessPath}";
         }
         $contents = preg_replace('/#WFIPBLOCKS.*WFIPBLOCKS[r\\s\\n\\t]*/s', '', $contents);
         ftruncate($fh, 0);
         fseek($fh, 0, SEEK_SET);
         @fwrite($fh, $contents);
         flock($fh, LOCK_UN);
         fclose($fh);
         return false;
     } else {
         if ($action == 'add') {
             $fh = @fopen($htaccessPath, 'r+');
             if (!$fh) {
                 $err = error_get_last();
                 return $err['message'];
             }
             $lines = array();
             $wfLog = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
             $IPs = $wfLog->getBlockedIPsAddrOnly();
             if (sizeof($IPs) > 0) {
                 foreach ($IPs as $IP) {
                     $lines[] = "Deny from {$IP}\n";
                 }
             }
             $ranges = $wfLog->getRangesBasic();
             $browserAdded = false;
             $browserLines = array();
             if ($ranges) {
                 foreach ($ranges as $r) {
                     $arr = explode('|', $r);
                     $range = isset($arr[0]) ? $arr[0] : false;
                     $browser = isset($arr[1]) ? $arr[1] : false;
                     $referer = isset($arr[2]) ? $arr[2] : false;
                     if ($range) {
                         if ($browser || $referer) {
                             continue;
                         }
                         //We don't allow combos in falcon
                         list($start_range, $end_range) = explode('-', $range);
                         if (preg_match('/[\\.:]/', $start_range)) {
                             $start_range = wfUtils::inet_pton($start_range);
                             $end_range = wfUtils::inet_pton($end_range);
                         } else {
                             $start_range = wfUtils::inet_pton(long2ip($start_range));
                             $end_range = wfUtils::inet_pton(long2ip($end_range));
                         }
                         $cidrs = wfUtils::rangeToCIDRs($start_range, $end_range);
                         $hIPs = wfUtils::inet_ntop($start_range) . ' - ' . wfUtils::inet_ntop($end_range);
                         if (sizeof($cidrs) > 0) {
                             $lines[] = '#Start of blocking code for IP range: ' . $hIPs . "\n";
                             foreach ($cidrs as $c) {
                                 $lines[] = "Deny from {$c}\n";
                             }
                             $lines[] = '#End of blocking code for IP range: ' . $hIPs . "\n";
                         }
                     } else {
                         if ($browser) {
                             if ($range || $referer) {
                                 continue;
                             }
                             $browserLines[] = "\t#Blocking code for browser pattern: {$browser}\n";
                             $browser = preg_replace('/([\\-\\_\\.\\+\\!\\@\\#\\$\\%\\^\\&\\(\\)\\[\\]\\{\\}\\/])/', "\\\\\$1", $browser);
                             $browser = preg_replace('/\\*/', '.*', $browser);
                             $browserLines[] = "\tSetEnvIf User-Agent " . $browser . " WordfenceBadBrowser=1\n";
                             $browserAdded = true;
                         } else {
                             if ($referer) {
                                 if ($browser || $range) {
                                     continue;
                                 }
                                 $browserLines[] = "\t#Blocking code for referer pattern: {$referer}\n";
                                 $referer = preg_replace('/([\\-\\_\\.\\+\\!\\@\\#\\$\\%\\^\\&\\(\\)\\[\\]\\{\\}\\/])/', "\\\\\$1", $referer);
                                 $referer = preg_replace('/\\*/', '.*', $referer);
                                 $browserLines[] = "\tSetEnvIf Referer " . $referer . " WordfenceBadBrowser=1\n";
                                 $browserAdded = true;
                             }
                         }
                     }
                 }
             }
             if ($browserAdded) {
                 $lines[] = "<IfModule mod_setenvif.c>\n";
                 foreach ($browserLines as $l) {
                     $lines[] = $l;
                 }
                 $lines[] = "\tDeny from env=WordfenceBadBrowser\n";
                 $lines[] = "</IfModule>\n";
             }
         }
     }
     $blockCode = "#WFIPBLOCKS - Do not remove this line. Disable Web Caching in Wordfence to remove this data.\nOrder Deny,Allow\n";
     $blockCode .= implode('', $lines);
     $blockCode .= "#Do not remove this line. Disable Web Caching in Wordfence to remove this data - WFIPBLOCKS\n";
     //Minimize time between lock/unlock
     flock($fh, LOCK_EX);
     fseek($fh, 0, SEEK_SET);
     //start of file
     clearstatcache();
     //Or we get the wrong size from a cached entry and corrupt the file
     $contents = @fread($fh, filesize($htaccessPath));
     if (!$contents) {
         fclose($fh);
         return "Could not read from {$htaccessPath}";
     }
     $contents = preg_replace('/#WFIPBLOCKS.*WFIPBLOCKS[r\\s\\n\\t]*/s', '', $contents);
     $contents = $blockCode . $contents;
     ftruncate($fh, 0);
     fseek($fh, 0, SEEK_SET);
     @fwrite($fh, $contents);
     flock($fh, LOCK_UN);
     fclose($fh);
     return false;
 }
Ejemplo n.º 4
0
 public static function wfFunc_IPTraf()
 {
     $IP = $_GET['IP'];
     if (!wfUtils::isValidIP($IP)) {
         echo "An invalid IP address was specified.";
         exit(0);
     }
     $reverseLookup = wfUtils::reverseLookup($IP);
     $wfLog = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
     $results = array_merge($wfLog->getHits('hits', 'hit', 0, 10000, $IP), $wfLog->getHits('hits', '404', 0, 10000, $IP));
     usort($results, 'wordfence::iptrafsort');
     for ($i = 0; $i < sizeof($results); $i++) {
         if (array_key_exists($i + 1, $results)) {
             $results[$i]['timeSinceLastHit'] = sprintf('%.4f', $results[$i]['ctime'] - $results[$i + 1]['ctime']);
         } else {
             $results[$i]['timeSinceLastHit'] = '';
         }
     }
     require 'IPTraf.php';
     exit(0);
 }
Ejemplo n.º 5
0
 /**
  * @param string $type
  * @param array $results
  * @throws Exception
  */
 public function processGetHitsResults($type, &$results)
 {
     $serverTime = $this->getDB()->querySingle("select unix_timestamp()");
     $this->resolveIPs($results);
     $ourURL = parse_url(site_url());
     $ourHost = strtolower($ourURL['host']);
     $ourHost = preg_replace('/^www\\./i', '', $ourHost);
     $browscap = new wfBrowscap();
     $advanced_blocking_results = $this->getDB()->querySelect('SELECT * FROM ' . $this->ipRangesTable);
     $advanced_blocking = array();
     foreach ($advanced_blocking_results as $advanced_blocking_row) {
         list($blocked_range) = explode('|', $advanced_blocking_row['blockString']);
         $blocked_range = explode('-', $blocked_range);
         if (count($blocked_range) == 2) {
             // Still using v5 32 bit int style format.
             if (!preg_match('/[\\.:]/', $blocked_range[0])) {
                 $blocked_range[0] = long2ip($blocked_range[0]);
                 $blocked_range[1] = long2ip($blocked_range[1]);
             }
             $advanced_blocking[] = array(wfUtils::inet_pton($blocked_range[0]), wfUtils::inet_pton($blocked_range[1]), $advanced_blocking_row['id']);
         }
     }
     foreach ($results as &$res) {
         $res['type'] = $type;
         $res['timeAgo'] = wfUtils::makeTimeAgo($serverTime - $res['ctime']);
         $res['blocked'] = $this->getDB()->querySingle("select blockedTime from " . $this->blocksTable . " where IP=%s and (permanent = 1 OR (blockedTime + %s > unix_timestamp()))", $res['IP'], wfConfig::get('blockedTime'));
         $res['rangeBlocked'] = false;
         $res['ipRangeID'] = -1;
         foreach ($advanced_blocking as $advanced_blocking_row) {
             if (strcmp($res['IP'], $advanced_blocking_row[0]) >= 0 && strcmp($res['IP'], $advanced_blocking_row[1]) <= 0) {
                 $res['rangeBlocked'] = true;
                 $res['ipRangeID'] = $advanced_blocking_row[2];
                 break;
             }
         }
         $res['IP'] = wfUtils::inet_ntop($res['IP']);
         $res['extReferer'] = false;
         if (isset($res['referer']) && $res['referer']) {
             if (wfUtils::hasXSS($res['referer'])) {
                 //filtering out XSS
                 $res['referer'] = '';
             }
         }
         if (isset($res['referer']) && $res['referer']) {
             $refURL = parse_url($res['referer']);
             if (is_array($refURL) && isset($refURL['host']) && $refURL['host']) {
                 $refHost = strtolower(preg_replace('/^www\\./i', '', $refURL['host']));
                 if ($refHost != $ourHost) {
                     $res['extReferer'] = true;
                     //now extract search terms
                     $q = false;
                     if (preg_match('/(?:google|bing|alltheweb|aol|ask)\\./i', $refURL['host'])) {
                         $q = 'q';
                     } else {
                         if (stristr($refURL['host'], 'yahoo.')) {
                             $q = 'p';
                         } else {
                             if (stristr($refURL['host'], 'baidu.')) {
                                 $q = 'wd';
                             }
                         }
                     }
                     if ($q) {
                         $queryVars = array();
                         if (isset($refURL['query'])) {
                             parse_str($refURL['query'], $queryVars);
                             if (isset($queryVars[$q])) {
                                 $res['searchTerms'] = urlencode($queryVars[$q]);
                             }
                         }
                     }
                 }
             }
             if ($res['extReferer']) {
                 if (isset($referringPage) && stristr($referringPage['host'], 'google.')) {
                     parse_str($referringPage['query'], $queryVars);
                     // echo $queryVars['q']; // This is the search term used
                 }
             }
         }
         $res['browser'] = false;
         if ($res['UA']) {
             $b = $browscap->getBrowser($res['UA']);
             if ($b && $b['Parent'] != 'DefaultProperties') {
                 $res['browser'] = array('browser' => !empty($b['Browser']) ? $b['Browser'] : "", 'version' => !empty($b['Version']) ? $b['Version'] : "", 'platform' => !empty($b['Platform']) ? $b['Platform'] : "", 'isMobile' => !empty($b['isMobileDevice']) ? $b['isMobileDevice'] : "", 'isCrawler' => !empty($b['Crawler']) ? $b['Crawler'] : "");
             } else {
                 $log = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
                 $IP = wfUtils::getIP();
                 $res['browser'] = array('isCrawler' => !(isset($_COOKIE['wordfence_verifiedHuman']) && $log->validateVerifiedHumanCookie($_COOKIE['wordfence_verifiedHuman'], $res['UA'], $IP)) ? 'true' : '');
             }
         }
         if ($res['userID']) {
             $ud = get_userdata($res['userID']);
             if ($ud) {
                 $res['user'] = array('editLink' => wfUtils::editUserLink($res['userID']), 'display_name' => $res['display_name'], 'ID' => $res['userID']);
                 $res['user']['avatar'] = get_avatar($res['userID'], 16);
             }
         } else {
             $res['user'] = false;
         }
     }
 }
 public static function synchronizeConfigSettings()
 {
     if (!class_exists('wfConfig')) {
         // Ensure this is only called when WordPress and the plugin are fully loaded
         return;
     }
     static $isSynchronizing = false;
     if ($isSynchronizing) {
         return;
     }
     $isSynchronizing = true;
     global $wpdb;
     $db = new wfDB();
     // Pattern Blocks
     $r1 = $db->querySelect("SELECT id, blockType, blockString FROM {$wpdb->base_prefix}wfBlocksAdv");
     $patternBlocks = array();
     foreach ($r1 as $blockRec) {
         if ($blockRec['blockType'] == 'IU') {
             $bDat = explode('|', $blockRec['blockString']);
             $ipRange = isset($bDat[0]) ? $bDat[0] : '';
             $uaPattern = isset($bDat[1]) ? $bDat[1] : '';
             $refPattern = isset($bDat[2]) ? $bDat[2] : '';
             $hostnamePattern = isset($bDat[3]) ? $bDat[3] : '';
             $patternBlocks[] = array('id' => $blockRec['id'], 'ipRange' => $ipRange, 'hostnamePattern' => $hostnamePattern, 'uaPattern' => $uaPattern, 'refPattern' => $refPattern);
         }
     }
     // Country Blocks
     $wfLog = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
     $cblCookie = $wfLog->getCBLCookieVal();
     //Ensure we have the bypass cookie option set
     $countryBlocks = array();
     $countryBlocks['action'] = wfConfig::get('cbl_action', false);
     $countryBlocks['loggedInBlocked'] = wfConfig::get('cbl_loggedInBlocked', false);
     $countryBlocks['loginFormBlocked'] = wfConfig::get('cbl_loginFormBlocked', false);
     $countryBlocks['restOfSiteBlocked'] = wfConfig::get('cbl_restOfSiteBlocked', false);
     $countryBlocks['bypassRedirURL'] = wfConfig::get('cbl_bypassRedirURL', '');
     $countryBlocks['bypassRedirDest'] = wfConfig::get('cbl_bypassRedirDest', '');
     $countryBlocks['bypassViewURL'] = wfConfig::get('cbl_bypassViewURL', '');
     $countryBlocks['redirURL'] = wfConfig::get('cbl_redirURL', '');
     $countryBlocks['countries'] = explode(',', wfConfig::get('cbl_countries', ''));
     $countryBlocks['cookieVal'] = $cblCookie;
     //Other Blocks
     $otherBlocks = array('blockedTime' => wfConfig::get('blockedTime', 0));
     $otherBlockEntries = $db->querySelect("SELECT IP, blockedTime, reason, permanent, wfsn FROM {$wpdb->base_prefix}wfBlocks WHERE permanent = 1 OR (blockedTime + %d > unix_timestamp())", $otherBlocks['blockedTime']);
     $otherBlocks['blocks'] = is_array($otherBlockEntries) ? $otherBlockEntries : array();
     foreach ($otherBlocks['blocks'] as &$b) {
         $b['IP'] = base64_encode($b['IP']);
     }
     // Save it
     try {
         $patternBlocksJSON = wfWAFUtils::json_encode($patternBlocks);
         wfWAF::getInstance()->getStorageEngine()->setConfig('patternBlocks', $patternBlocksJSON);
         $countryBlocksJSON = wfWAFUtils::json_encode($countryBlocks);
         wfWAF::getInstance()->getStorageEngine()->setConfig('countryBlocks', $countryBlocksJSON);
         $otherBlocksJSON = wfWAFUtils::json_encode($otherBlocks);
         wfWAF::getInstance()->getStorageEngine()->setConfig('otherBlocks', $otherBlocksJSON);
         wfWAF::getInstance()->getStorageEngine()->setConfig('advancedBlockingEnabled', wfConfig::get('firewallEnabled'));
         wfWAF::getInstance()->getStorageEngine()->setConfig('disableWAFIPBlocking', wfConfig::get('disableWAFIPBlocking'));
     } catch (Exception $e) {
         // Do nothing
     }
     $isSynchronizing = false;
 }