Exemple #1
0
 public static function verifyCrawlerPTR($hostPattern, $IP)
 {
     global $wpdb;
     $table = $wpdb->base_prefix . 'wfCrawlers';
     $db = new wfDB();
     $IPn = wfUtils::inet_pton($IP);
     $status = $db->querySingle("select status from {$table} where IP=%s and patternSig=UNHEX(MD5('%s')) and lastUpdate > unix_timestamp() - %d", $IPn, $hostPattern, WORDFENCE_CRAWLER_VERIFY_CACHE_TIME);
     if ($status) {
         if ($status == 'verified') {
             return true;
         } else {
             return false;
         }
     }
     $host = wfUtils::reverseLookup($IP);
     if (!$host) {
         $db->queryWrite("insert into {$table} (IP, patternSig, status, lastUpdate, PTR) values (%s, UNHEX(MD5('%s')), '%s', unix_timestamp(), '%s') ON DUPLICATE KEY UPDATE status='%s', lastUpdate=unix_timestamp(), PTR='%s'", $IPn, $hostPattern, 'noPTR', '', 'noPTR', '');
         return false;
     }
     if (preg_match($hostPattern, $host)) {
         $resultIPs = wfUtils::resolveDomainName($host);
         $addrsMatch = false;
         foreach ($resultIPs as $resultIP) {
             if ($resultIP == $IP) {
                 $addrsMatch = true;
                 break;
             }
         }
         if ($addrsMatch) {
             $db->queryWrite("insert into {$table} (IP, patternSig, status, lastUpdate, PTR) values (%s, UNHEX(MD5('%s')), '%s', unix_timestamp(), '%s') ON DUPLICATE KEY UPDATE status='%s', lastUpdate=unix_timestamp(), PTR='%s'", $IPn, $hostPattern, 'verified', $host, 'verified', $host);
             return true;
         } else {
             $db->queryWrite("insert into {$table} (IP, patternSig, status, lastUpdate, PTR) values (%s, UNHEX(MD5('%s')), '%s', unix_timestamp(), '%s') ON DUPLICATE KEY UPDATE status='%s', lastUpdate=unix_timestamp(), PTR='%s'", $IPn, $hostPattern, 'fwdFail', $host, 'fwdFail', $host);
             return false;
         }
     } else {
         $db->queryWrite("insert into {$table} (IP, patternSig, status, lastUpdate, PTR) values (%s, UNHEX(MD5('%s')), '%s', unix_timestamp(), '%s') ON DUPLICATE KEY UPDATE status='%s', lastUpdate=unix_timestamp(), PTR='%s'", $IPn, $hostPattern, 'badPTR', $host, 'badPTR', $host);
         return false;
     }
 }
Exemple #2
0
 public static function reverseLookup($IP)
 {
     $db = new wfDB();
     global $wpdb;
     $reverseTable = $wpdb->base_prefix . 'wfReverseCache';
     $IPn = wfUtils::inet_pton($IP);
     $host = $db->querySingle("select host from " . $reverseTable . " where IP=%s and unix_timestamp() - lastUpdate < %d", $IPn, WORDFENCE_REVERSE_LOOKUP_CACHE_TIME);
     if (!$host) {
         // This function works for IPv4 or IPv6
         if (function_exists('gethostbyaddr')) {
             $host = gethostbyaddr($IP);
         }
         if (!$host) {
             $ptr = false;
             if (filter_var($IP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
                 $ptr = implode(".", array_reverse(explode(".", $IP))) . ".in-addr.arpa";
             } else {
                 if (filter_var($IP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) {
                     $ptr = implode(".", array_reverse(str_split(bin2hex($IPn)))) . ".ip6.arpa";
                 }
             }
             if ($ptr && function_exists('dns_get_record')) {
                 $host = @dns_get_record($ptr, DNS_PTR);
                 if ($host) {
                     $host = $host[0]['target'];
                 }
             }
         }
         if (!$host) {
             $host = 'NONE';
         }
         $db->queryWrite("insert into " . $reverseTable . " (IP, host, lastUpdate) values (%s, '%s', unix_timestamp()) ON DUPLICATE KEY UPDATE host='%s', lastUpdate=unix_timestamp()", $IPn, $host, $host);
     }
     if ($host == 'NONE') {
         return '';
     } else {
         return $host;
     }
 }
    /**
     * @param mixed $ip_address
     * @param int|null $unixday
     */
    public static function logBlockedIP($ip_address, $unixday = null)
    {
        /** @var wpdb $wpdb */
        global $wpdb;
        if (wfUtils::isValidIP($ip_address)) {
            $ip_bin = wfUtils::inet_pton($ip_address);
        } else {
            $ip_bin = $ip_address;
            $ip_address = wfUtils::inet_ntop($ip_bin);
        }
        $blocked_table = "{$wpdb->base_prefix}wfBlockedIPLog";
        $unixday_insert = 'FLOOR(UNIX_TIMESTAMP() / 86400)';
        if (is_int($unixday)) {
            $unixday_insert = absint($unixday);
        }
        $country = wfUtils::IP2Country($ip_address);
        $wpdb->query($wpdb->prepare(<<<SQL
INSERT INTO {$blocked_table} (IP, countryCode, blockCount, unixday)
VALUES (%s, %s, 1, {$unixday_insert})
ON DUPLICATE KEY UPDATE blockCount = blockCount + 1
SQL
, $ip_bin, $country));
    }
Exemple #4
0
 public static function syncAttackData($exit = true)
 {
     global $wpdb;
     $waf = wfWAF::getInstance();
     $lastAttackMicroseconds = $wpdb->get_var("SELECT MAX(attackLogTime) FROM {$wpdb->base_prefix}wfHits");
     if ($waf->getStorageEngine()->hasNewerAttackData($lastAttackMicroseconds)) {
         $attackData = $waf->getStorageEngine()->getNewestAttackDataArray($lastAttackMicroseconds);
         if ($attackData) {
             foreach ($attackData as $request) {
                 if (count($request) !== 9) {
                     continue;
                 }
                 list($logTimeMicroseconds, $requestTime, $ip, $learningMode, $paramKey, $paramValue, $failedRules, $ssl, $requestString) = $request;
                 // Skip old entries and hits in learning mode, since they'll get picked up anyways.
                 if ($logTimeMicroseconds <= $lastAttackMicroseconds || $learningMode) {
                     continue;
                 }
                 $hit = new wfRequestModel();
                 $hit->attackLogTime = $logTimeMicroseconds;
                 $hit->statusCode = 403;
                 $hit->ctime = $requestTime;
                 $hit->IP = wfUtils::inet_pton($ip);
                 if (preg_match('/user\\-agent:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->UA = trim($matches[1]);
                     $hit->isGoogle = wfCrawl::isGoogleCrawler($hit->UA);
                 }
                 if (preg_match('/Referer:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->referer = trim($matches[1]);
                 }
                 if (preg_match('/^[a-z]+\\s+(.*?)\\s+/i', $requestString, $uriMatches) && preg_match('/Host:(.*?)\\n/i', $requestString, $hostMatches)) {
                     $hit->URL = 'http' . ($ssl ? 's' : '') . '://' . trim($hostMatches[1]) . trim($uriMatches[1]);
                 }
                 if (preg_match('/cookie:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->newVisit = strpos($matches[1], 'wfvt_' . crc32(site_url())) !== false ? 1 : 0;
                     $hasVerifiedHumanCookie = strpos($matches[1], 'wordfence_verifiedHuman') !== false;
                     if ($hasVerifiedHumanCookie && preg_match('/wordfence_verifiedHuman=(.*?);/', $matches[1], $cookieMatches)) {
                         $hit->jsRun = (int) wp_verify_nonce($cookieMatches[1], 'wordfence_verifiedHuman' . $hit->UA . $ip);
                     }
                     $hasLoginCookie = strpos($matches[1], $ssl ? SECURE_AUTH_COOKIE : AUTH_COOKIE) !== false;
                     if ($hasLoginCookie && preg_match('/' . ($ssl ? SECURE_AUTH_COOKIE : AUTH_COOKIE) . '=(.*?);/', $matches[1], $cookieMatches)) {
                         $authCookie = rawurldecode($cookieMatches[1]);
                         $authID = $ssl ? wp_validate_auth_cookie($authCookie, 'secure_auth') : wp_validate_auth_cookie($authCookie, 'auth');
                         if ($authID) {
                             $hit->userID = $authID;
                         }
                     }
                 }
                 $path = '/';
                 if (preg_match('/^[A-Z]+ (.*?) HTTP\\/1\\.1/', $requestString, $matches)) {
                     if (($pos = strpos($matches[1], '?')) !== false) {
                         $path = substr($matches[1], 0, $pos);
                     } else {
                         $path = $matches[1];
                     }
                 }
                 $hit->action = 'blocked:waf';
                 /** @var wfWAFRule $rule */
                 $ruleIDs = explode('|', $failedRules);
                 $actionData = array('learningMode' => $learningMode, 'failedRules' => $failedRules, 'paramKey' => $paramKey, 'paramValue' => $paramValue, 'path' => $path);
                 if ($ruleIDs && $ruleIDs[0]) {
                     $rule = $waf->getRule($ruleIDs[0]);
                     if ($rule) {
                         $hit->actionDescription = $rule->getDescription();
                         $actionData['category'] = $rule->getCategory();
                         $actionData['ssl'] = $ssl;
                         $actionData['fullRequest'] = base64_encode($requestString);
                     }
                 }
                 $hit->actionData = wfRequestModel::serializeActionData($actionData);
                 $hit->save();
                 self::scheduleSendAttackData();
             }
         }
         $waf->getStorageEngine()->truncateAttackData();
     }
     update_site_option('wordfence_syncingAttackData', 0);
     update_site_option('wordfence_syncAttackDataAttempts', 0);
     if ($exit) {
         exit;
     }
 }
 /**
  * Return a set of where clauses to use in MySQL.
  *
  * @param string $column
  * @return false|null|string
  */
 public function toSQL($column = 'ip')
 {
     /** @var wpdb $wpdb */
     global $wpdb;
     $ip_string = $this->getIPString();
     if (strpos($ip_string, '.') !== false && preg_match('/\\[\\d+\\-\\d+\\]/', $ip_string)) {
         $whiteParts = explode('.', $ip_string);
         $sql = "(SUBSTR({$column}, 1, 12) = LPAD(CHAR(0xff, 0xff), 12, CHAR(0)) AND ";
         for ($i = 0, $j = 24; $i <= 3; $i++, $j -= 8) {
             // MySQL can only perform bitwise operations on integers
             $conv = sprintf('CAST(CONV(HEX(SUBSTR(%s, 13, 8)), 16, 10) as UNSIGNED INTEGER)', $column);
             if (preg_match('/^\\[(\\d+)\\-(\\d+)\\]$/', $whiteParts[$i], $m)) {
                 $sql .= $wpdb->prepare("{$conv} >> {$j} & 0xFF BETWEEN %d AND %d", $m[1], $m[2]);
             } else {
                 $sql .= $wpdb->prepare("{$conv} >> {$j} & 0xFF = %d", $whiteParts[$i]);
             }
             $sql .= ' AND ';
         }
         $sql = substr($sql, 0, -5) . ')';
         return $sql;
     } else {
         if (strpos($ip_string, ':') !== false && preg_match('/\\[[a-f0-9]+\\-[a-f0-9]+\\]/', $ip_string)) {
             $whiteParts = explode(':', strtolower(self::expandIPv6Range($ip_string)));
             $sql = '(';
             for ($i = 0; $i <= 7; $i++) {
                 // MySQL can only perform bitwise operations on integers
                 $conv = sprintf('CAST(CONV(HEX(SUBSTR(%s, %d, 8)), 16, 10) as UNSIGNED INTEGER)', $column, $i < 4 ? 1 : 9);
                 $j = 16 * (3 - $i % 4);
                 if (preg_match('/^\\[([a-f0-9]+)\\-([a-f0-9]+)\\]$/', $whiteParts[$i], $m)) {
                     $sql .= $wpdb->prepare("{$conv} >> {$j} & 0xFFFF BETWEEN 0x%x AND 0x%x", hexdec($m[1]), hexdec($m[2]));
                 } else {
                     $sql .= $wpdb->prepare("{$conv} >> {$j} & 0xFFFF = 0x%x", hexdec($whiteParts[$i]));
                 }
                 $sql .= ' AND ';
             }
             $sql = substr($sql, 0, -5) . ')';
             return $sql;
         }
     }
     return $wpdb->prepare("({$column} = %s)", wfUtils::inet_pton($ip_string));
 }
 public static function syncAttackData($exit = true)
 {
     global $wpdb;
     $waf = wfWAF::getInstance();
     $lastAttackMicroseconds = $wpdb->get_var("SELECT MAX(attackLogTime) FROM {$wpdb->base_prefix}wfHits");
     if ($waf->getStorageEngine()->hasNewerAttackData($lastAttackMicroseconds)) {
         $attackData = $waf->getStorageEngine()->getNewestAttackDataArray($lastAttackMicroseconds);
         if ($attackData) {
             foreach ($attackData as $request) {
                 if (count($request) !== 9 && count($request) !== 10) {
                     continue;
                 }
                 list($logTimeMicroseconds, $requestTime, $ip, $learningMode, $paramKey, $paramValue, $failedRules, $ssl, $requestString, $metadata) = $request;
                 // Skip old entries and hits in learning mode, since they'll get picked up anyways.
                 if ($logTimeMicroseconds <= $lastAttackMicroseconds || $learningMode) {
                     continue;
                 }
                 $hit = new wfRequestModel();
                 $hit->attackLogTime = $logTimeMicroseconds;
                 $hit->statusCode = 403;
                 $hit->ctime = $requestTime;
                 $hit->IP = wfUtils::inet_pton($ip);
                 if (preg_match('/user\\-agent:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->UA = trim($matches[1]);
                     $hit->isGoogle = wfCrawl::isGoogleCrawler($hit->UA);
                 }
                 if (preg_match('/Referer:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->referer = trim($matches[1]);
                 }
                 if (preg_match('/^[a-z]+\\s+(.*?)\\s+/i', $requestString, $uriMatches) && preg_match('/Host:(.*?)\\n/i', $requestString, $hostMatches)) {
                     $hit->URL = 'http' . ($ssl ? 's' : '') . '://' . trim($hostMatches[1]) . trim($uriMatches[1]);
                 }
                 if (preg_match('/cookie:(.*?)\\n/i', $requestString, $matches)) {
                     $hit->newVisit = strpos($matches[1], 'wfvt_' . crc32(site_url())) !== false ? 1 : 0;
                     $hasVerifiedHumanCookie = strpos($matches[1], 'wordfence_verifiedHuman') !== false;
                     if ($hasVerifiedHumanCookie && preg_match('/wordfence_verifiedHuman=(.*?);/', $matches[1], $cookieMatches)) {
                         $hit->jsRun = (int) wp_verify_nonce($cookieMatches[1], 'wordfence_verifiedHuman' . $hit->UA . $ip);
                     }
                     $hasLoginCookie = strpos($matches[1], $ssl ? SECURE_AUTH_COOKIE : AUTH_COOKIE) !== false;
                     if ($hasLoginCookie && preg_match('/' . ($ssl ? SECURE_AUTH_COOKIE : AUTH_COOKIE) . '=(.*?);/', $matches[1], $cookieMatches)) {
                         $authCookie = rawurldecode($cookieMatches[1]);
                         $authID = $ssl ? wp_validate_auth_cookie($authCookie, 'secure_auth') : wp_validate_auth_cookie($authCookie, 'auth');
                         if ($authID) {
                             $hit->userID = $authID;
                         }
                     }
                 }
                 $path = '/';
                 if (preg_match('/^[A-Z]+ (.*?) HTTP\\/1\\.1/', $requestString, $matches)) {
                     if (($pos = strpos($matches[1], '?')) !== false) {
                         $path = substr($matches[1], 0, $pos);
                     } else {
                         $path = $matches[1];
                     }
                 }
                 $metadata = $metadata != null ? (array) $metadata : array();
                 if (isset($metadata['finalAction']) && $metadata['finalAction']) {
                     // The request was blocked/redirected because of its IP based on the plugin's blocking settings. WAF blocks should be reported but not shown in live traffic with that as a reason.
                     $action = $metadata['finalAction']['action'];
                     $actionDescription = $action;
                     if (class_exists('wfWAFIPBlocksController')) {
                         if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_UAREFIPRANGE) {
                             $id = $metadata['finalAction']['id'];
                             $wpdb->query($wpdb->prepare("UPDATE {$wpdb->base_prefix}wfBlocksAdv SET totalBlocked = totalBlocked + 1, lastBlocked = %d WHERE id = %d", $requestTime, $id));
                             wfActivityReport::logBlockedIP($ip);
                         } else {
                             if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_COUNTRY_REDIR) {
                                 $actionDescription .= ' (' . wfConfig::get('cbl_redirURL') . ')';
                                 wfConfig::inc('totalCountryBlocked');
                                 wfActivityReport::logBlockedIP($ip);
                             } else {
                                 if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_COUNTRY) {
                                     wfConfig::inc('totalCountryBlocked');
                                     wfActivityReport::logBlockedIP($ip);
                                 } else {
                                     if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_WFSN) {
                                         wordfence::wfsnReportBlockedAttempt($ip, 'login');
                                     }
                                 }
                             }
                         }
                     }
                     if (strlen($actionDescription) == 0) {
                         $actionDescription = 'Blocked by Wordfence';
                     }
                     if (empty($failedRules)) {
                         // Just a plugin block
                         $hit->action = 'blocked:wordfence';
                         if (class_exists('wfWAFIPBlocksController')) {
                             if ($action == wfWAFIPBlocksController::WFWAF_BLOCK_WFSN) {
                                 $hit->action = 'blocked:wfsnrepeat';
                             }
                         }
                         $hit->actionDescription = $actionDescription;
                     } else {
                         if ($failedRules == 'logged') {
                             $hit->action = 'logged:waf';
                         } else {
                             // Blocked by the WAF but would've been blocked anyway by the plugin settings so that message takes priority
                             $hit->action = 'blocked:waf-always';
                             $hit->actionDescription = $actionDescription;
                         }
                     }
                 } else {
                     if ($failedRules == 'logged') {
                         $hit->action = 'logged:waf';
                     } else {
                         $hit->action = 'blocked:waf';
                     }
                 }
                 /** @var wfWAFRule $rule */
                 $ruleIDs = explode('|', $failedRules);
                 $actionData = array('learningMode' => $learningMode, 'failedRules' => $failedRules, 'paramKey' => $paramKey, 'paramValue' => $paramValue, 'path' => $path);
                 if ($ruleIDs && $ruleIDs[0]) {
                     $rule = $waf->getRule($ruleIDs[0]);
                     if ($rule) {
                         if ($hit->action == 'logged:waf' || $hit->action == 'blocked:waf') {
                             $hit->actionDescription = $rule->getDescription();
                         }
                         $actionData['category'] = $rule->getCategory();
                         $actionData['ssl'] = $ssl;
                         $actionData['fullRequest'] = base64_encode($requestString);
                     } else {
                         if ($ruleIDs[0] == 'logged') {
                             if ($hit->action == 'logged:waf' || $hit->action == 'blocked:waf') {
                                 $hit->actionDescription = 'Watched IP Traffic: ' . $ip;
                             }
                             $actionData['category'] = 'logged';
                             $actionData['ssl'] = $ssl;
                             $actionData['fullRequest'] = base64_encode($requestString);
                         }
                     }
                 }
                 $hit->actionData = wfRequestModel::serializeActionData($actionData);
                 $hit->save();
                 self::scheduleSendAttackData();
             }
         }
         $waf->getStorageEngine()->truncateAttackData();
     }
     update_site_option('wordfence_syncingAttackData', 0);
     update_site_option('wordfence_syncAttackDataAttempts', 0);
     update_site_option('wordfence_lastSyncAttackData', time());
     if ($exit) {
         exit;
     }
 }
Exemple #7
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;
 }
 /**
  * @return array
  */
 public static function ajax_blockIPUARange_callback()
 {
     $ipRange = trim($_POST['ipRange']);
     $uaRange = trim($_POST['uaRange']);
     $referer = trim($_POST['referer']);
     $reason = trim($_POST['reason']);
     if (preg_match('/\\|+/', $ipRange . $uaRange . $referer)) {
         return array('err' => 1, 'errorMsg' => "You are not allowed to include a pipe character \"|\" in your IP range, browser pattern or referer");
     }
     if (!$ipRange && wfUtils::isUABlocked($uaRange)) {
         return array('err' => 1, 'errorMsg' => "The browser pattern you specified will block you from your own website. We have not accepted this pattern to protect you from being blocked.");
     }
     if (fnmatch($referer, site_url(), FNM_CASEFOLD)) {
         return array('err' => 1, 'errorMsg' => "The referer pattern you specified matches your own website and will block visitors as they surf from one page to another on your site. You can't enter this pattern.");
     }
     if ($ipRange) {
         list($start_range, $end_range) = explode('-', $ipRange);
         if (!wfUtils::isValidIP($start_range) || !wfUtils::isValidIP($end_range)) {
             return array('err' => 1, 'errorMsg' => "The IP range you specified is not valid. Please specify an IP range like the following example: \"1.2.3.4 - 1.2.3.8\" without quotes.");
         }
         $ip1 = wfUtils::inet_pton($start_range);
         $ip2 = wfUtils::inet_pton($end_range);
         if (strcmp($ip1, $ip2) >= 0) {
             return array('err' => 1, 'errorMsg' => "The first IP address in your range must be less than the second IP address in your range.");
         }
         $clientIP = wfUtils::inet_pton(wfUtils::getIP());
         if (strcmp($ip1, $clientIP) <= 0 && strcmp($ip2, $clientIP) >= 0) {
             return array('err' => 1, 'errorMsg' => "You are trying to block yourself. Your IP address is " . wp_kses(wfUtils::getIP(), array()) . " which falls into the range " . wp_kses($ipRange, array()) . ". This blocking action has been cancelled so that you don't block yourself from your website.");
         }
         $ipRange = wfUtils::inet_ntop($ip1) . '-' . wfUtils::inet_ntop($ip2);
     }
     $range = $ipRange . '|' . $uaRange . '|' . $referer;
     self::getLog()->blockRange('IU', $range, $reason);
     return array('ok' => 1);
 }
Exemple #9
0
 /**
  * @param string|null $ip
  * @return bool
  */
 public static function verifyGooglebotViaNOC1($ip = null)
 {
     global $wpdb;
     $table = $wpdb->base_prefix . 'wfCrawlers';
     if ($ip === null) {
         $ip = wfUtils::getIP();
     }
     $db = new wfDB();
     $IPn = wfUtils::inet_pton($ip);
     $patternSig = 'googlenoc1';
     $status = $db->querySingle("select status from {$table}\n\t\t\t\twhere IP=%s\n\t\t\t\tand patternSig=UNHEX(MD5('%s'))\n\t\t\t\tand lastUpdate > unix_timestamp() - %d", $IPn, $patternSig, WORDFENCE_CRAWLER_VERIFY_CACHE_TIME);
     if ($status === 'verified') {
         return true;
     } else {
         if ($status === 'fakeBot') {
             return false;
         }
     }
     $api = new wfAPI(wfConfig::get('apiKey'), wfUtils::getWPVersion());
     try {
         $data = $api->call('verify_googlebot', array('ip' => $ip));
         if (is_array($data) && !empty($data['verified'])) {
             // Cache results
             $db->queryWrite("insert into {$table} (IP, patternSig, status, lastUpdate)\nvalues (%s, UNHEX(MD5('%s')), '%s', unix_timestamp())\nON DUPLICATE KEY UPDATE status='%3\$s', lastUpdate=unix_timestamp()", $IPn, $patternSig, 'verified');
             return true;
         } else {
             $db->queryWrite("insert into {$table} (IP, patternSig, status, lastUpdate)\nvalues (%s, UNHEX(MD5('%s')), '%s', unix_timestamp())\nON DUPLICATE KEY UPDATE status='%3\$s', lastUpdate=unix_timestamp()", $IPn, $patternSig, 'fakeBot');
         }
     } catch (Exception $e) {
         // Do nothing, bail
     }
     return false;
 }
 function geoip_name_by_addr_v6($gi, $addr)
 {
     if ($addr == NULL) {
         return 0;
     }
     $ipnum = wfUtils::inet_pton($addr);
     return _get_org_v6($gi, $ipnum);
 }