Пример #1
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;
     }
 }
Пример #2
0
 private function googleSafetyCheckOK()
 {
     //returns true if OK to block. Returns false if we must not block.
     $cacheKey = md5((isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '') . ' ' . wfUtils::getIP());
     //Cache so we can call this multiple times in one request
     if (!isset(self::$gbSafeCache[$cacheKey])) {
         $nb = wfConfig::get('neverBlockBG');
         if ($nb == 'treatAsOtherCrawlers') {
             self::$gbSafeCache[$cacheKey] = true;
             //OK to block because we're treating google like everyone else
         } else {
             if ($nb == 'neverBlockUA' || $nb == 'neverBlockVerified') {
                 if (wfCrawl::isGoogleCrawler()) {
                     //Check the UA using regex
                     if ($nb == 'neverBlockVerified') {
                         if (wfCrawl::verifyCrawlerPTR($this->googlePattern, wfUtils::getIP())) {
                             //UA check passed, now verify using PTR if configured to
                             self::$gbSafeCache[$cacheKey] = false;
                             //This is a verified Google crawler, so no we can't block it
                         } else {
                             self::$gbSafeCache[$cacheKey] = true;
                             //This is a crawler claiming to be Google but it did not verify
                         }
                     } else {
                         //neverBlockUA
                         self::$gbSafeCache[$cacheKey] = false;
                         //User configured us to only do a UA check and this claims to be google so don't block
                     }
                 } else {
                     self::$gbSafeCache[$cacheKey] = true;
                     //This isn't a Google UA, so it's OK to block
                 }
             } else {
                 //error_log("Wordfence error: neverBlockBG option is not set.");
                 self::$gbSafeCache[$cacheKey] = false;
                 //Oops the config option is not set. This should never happen because it's set on install. So we return false to indicate it's not OK to block just for safety.
             }
         }
     }
     if (!isset(self::$gbSafeCache[$cacheKey])) {
         //error_log("Wordfence assertion fail in googleSafetyCheckOK: cached value is not set.");
         return false;
         //for safety
     }
     return self::$gbSafeCache[$cacheKey];
     //return cached value
 }
Пример #3
0
 public static function veryFirstAction()
 {
     $wfFunc = isset($_GET['_wfsf']) ? @$_GET['_wfsf'] : false;
     if ($wfFunc == 'unlockEmail') {
         if (!wp_verify_nonce(@$_POST['nonce'], 'wf-form')) {
             die("Sorry but your browser sent an invalid security token when trying to use this form.");
         }
         $numTries = get_transient('wordfenceUnlockTries');
         if ($numTries > 10) {
             echo "<html><body><h1>Please wait 3 minutes and try again</h1><p>You have used this form too much. Please wait 3 minutes and try again.</p></body></html>";
             exit;
         }
         if (!$numTries) {
             $numTries = 1;
         } else {
             $numTries = $numTries + 1;
         }
         set_transient('wordfenceUnlockTries', $numTries, 180);
         $email = trim($_POST['email']);
         global $wpdb;
         $ws = $wpdb->get_results($wpdb->prepare("SELECT ID, user_login FROM {$wpdb->users} WHERE user_email = %s", $email));
         foreach ($ws as $user) {
             $userDat = get_userdata($user->ID);
             if (wfUtils::isAdmin($userDat)) {
                 if ($email == $userDat->user_email) {
                     $found = true;
                     break;
                 }
             }
         }
         if (!$found) {
             foreach (wfConfig::getAlertEmails() as $alertEmail) {
                 if ($alertEmail == $email) {
                     $found = true;
                     break;
                 }
             }
         }
         if ($found) {
             $key = wfUtils::bigRandomHex();
             $IP = wfUtils::getIP();
             set_transient('wfunlock_' . $key, $IP, 1800);
             $content = wfUtils::tmpl('email_unlockRequest.php', array('siteName' => get_bloginfo('name', 'raw'), 'siteURL' => wfUtils::getSiteBaseURL(), 'unlockHref' => wfUtils::getSiteBaseURL() . '?_wfsf=unlockAccess&key=' . $key, 'key' => $key, 'IP' => $IP));
             wp_mail($email, "Unlock email requested", $content, "Content-Type: text/html");
         }
         echo "<html><body><h1>Your request was received</h1><p>We received a request to email \"" . wp_kses($email, array()) . "\" instructions to unlock their access. If that is the email address of a site administrator or someone on the Wordfence alert list, then they have been emailed instructions on how to regain access to this sytem. The instructions we sent will expire 30 minutes from now.</body></html>";
         exit;
     } else {
         if ($wfFunc == 'unlockAccess') {
             if (!preg_match('/^\\d+\\.\\d+\\.\\d+\\.\\d+$/', get_transient('wfunlock_' . $_GET['key']))) {
                 echo "Invalid key provided for authentication.";
                 exit;
             }
             /* You can enable this for paranoid security leve.
             			if(get_transient('wfunlock_' . $_GET['key']) != wfUtils::getIP()){
             				echo "You can only use this link from the IP address you used to generate the unlock email.";
             				exit();
             			}
             			*/
             $wfLog = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
             if ($_GET['func'] == 'unlockMyIP') {
                 $wfLog->unblockIP(wfUtils::getIP());
                 $wfLog->unlockOutIP(wfUtils::getIP());
                 delete_transient('wflginfl_' . bin2hex(wfUtils::inet_pton(wfUtils::getIP())));
                 //Reset login failure counter
                 header('Location: ' . wp_login_url());
                 exit;
             } else {
                 if ($_GET['func'] == 'unlockAllIPs') {
                     wordfence::status(1, 'info', "Request received via unlock email link to unblock all IP's.");
                     $wfLog->unblockAllIPs();
                     $wfLog->unlockAllIPs();
                     delete_transient('wflginfl_' . bin2hex(wfUtils::inet_pton(wfUtils::getIP())));
                     //Reset login failure counter
                     header('Location: ' . wp_login_url());
                     exit;
                 } else {
                     if ($_GET['func'] == 'disableRules') {
                         wfConfig::set('firewallEnabled', 0);
                         wfConfig::set('loginSecurityEnabled', 0);
                         wordfence::status(1, 'info', "Request received via unlock email link to unblock all IP's via disabling firewall rules.");
                         $wfLog->unblockAllIPs();
                         $wfLog->unlockAllIPs();
                         delete_transient('wflginfl_' . bin2hex(wfUtils::inet_pton(wfUtils::getIP())));
                         //Reset login failure counter
                         wfConfig::set('cbl_countries', '');
                         //unblock all countries
                         header('Location: ' . wp_login_url());
                         exit;
                     } else {
                         echo "Invalid function specified. Please check the link we emailed you and make sure it was not cut-off by your email reader.";
                         exit;
                     }
                 }
             }
         }
     }
     if (wfConfig::get('firewallEnabled')) {
         $wfLog = self::getLog();
         $wfLog->firewallBadIPs();
         $IP = wfUtils::getIP();
         if ($wfLog->isWhitelisted($IP)) {
             return;
         }
         if (wfConfig::get('neverBlockBG') == 'neverBlockUA' && wfCrawl::isGoogleCrawler()) {
             return;
         }
         if (wfConfig::get('neverBlockBG') == 'neverBlockVerified' && wfCrawl::isVerifiedGoogleCrawler()) {
             return;
         }
         if (wfConfig::get('blockFakeBots')) {
             if (wfCrawl::isGooglebot() && !wfCrawl::isVerifiedGoogleCrawler()) {
                 $wfLog->blockIP($IP, "Fake Google crawler automatically blocked");
                 wordfence::status(2, 'info', "Blocking fake Googlebot at IP {$IP}");
                 $wfLog->do503(3600, "Fake Google crawler automatically blocked.");
             }
         }
         if (wfConfig::get('bannedURLs', false)) {
             $URLs = explode(',', wfConfig::get('bannedURLs'));
             foreach ($URLs as $URL) {
                 if ($_SERVER['REQUEST_URI'] == trim($URL)) {
                     $wfLog->blockIP($IP, "Accessed a banned URL.");
                     $wfLog->do503(3600, "Accessed a banned URL.");
                     //exits
                 }
             }
         }
         if (wfConfig::get('other_blockBadPOST') == '1' && $_SERVER['REQUEST_METHOD'] == 'POST' && empty($_SERVER['HTTP_USER_AGENT']) && empty($_SERVER['HTTP_REFERER'])) {
             $wfLog->blockIP($IP, "POST received with blank user-agent and referer");
             $wfLog->do503(3600, "POST received with blank user-agent and referer");
             //exits
         }
     }
 }
Пример #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 && 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;
     }
 }
 public static function ajax_logHuman_callback()
 {
     $browscap = new wfBrowscap();
     $UA = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
     $isCrawler = false;
     if ($UA) {
         $b = $browscap->getBrowser($UA);
         if (!empty($b['Crawler']) || wfCrawl::isGoogleCrawler()) {
             $isCrawler = true;
         }
     }
     @ob_end_clean();
     if (!headers_sent()) {
         header('Content-type: text/javascript');
         header("Connection: close");
         header("Content-Length: 0");
         header("X-Robots-Tag: noindex");
         if (!$isCrawler) {
             setcookie('wordfence_verifiedHuman', wp_create_nonce('wordfence_verifiedHuman' . $UA . wfUtils::getIP()), time() + 86400, '/');
         }
     }
     flush();
     if (!$isCrawler) {
         $hid = $_GET['hid'];
         $hid = wfUtils::decrypt($hid);
         if (!preg_match('/^\\d+$/', $hid)) {
             exit;
         }
         $db = new wfDB();
         global $wpdb;
         $p = $wpdb->base_prefix;
         $db->queryWrite("update {$p}" . "wfHits set jsRun=1 where id=%d", $hid);
     }
     die("");
 }