Пример #1
0
 public static function setDefaults()
 {
     foreach (self::$defaultConfig['checkboxes'] as $key => $val) {
         if (self::get($key) === false) {
             self::set($key, $val ? '1' : '0');
         }
     }
     foreach (self::$defaultConfig['otherParams'] as $key => $val) {
         if (self::get($key) === false) {
             self::set($key, $val);
         }
     }
     self::set('encKey', substr(wfUtils::bigRandomHex(), 0, 16));
     if (self::get('maxMem', false) === false) {
         self::set('maxMem', '256');
     }
     if (self::get('other_scanOutside', false) === false) {
         self::set('other_scanOutside', 0);
     }
     if (self::get('email_summary_enabled')) {
         wfActivityReport::scheduleCronJob();
     } else {
         wfActivityReport::disableCronJob();
     }
 }
Пример #2
0
 /**
  * Schedule the activity report cron job.
  */
 public static function scheduleCronJob()
 {
     self::clearCronJobs();
     if (!wfConfig::get('email_summary_enabled', 1)) {
         return;
     }
     if (is_main_site()) {
         list(, $end_time) = wfActivityReport::getReportDateRange();
         wp_schedule_single_event($end_time, 'wordfence_email_activity_report');
     }
 }
 function save_setting()
 {
     $settings = maybe_unserialize(base64_decode($_POST['settings']));
     if (is_array($settings) && count($settings) > 0) {
         $result = array();
         $reload = '';
         $opts = $settings;
         $validUsers = array();
         $invalidUsers = array();
         foreach (explode(',', $opts['liveTraf_ignoreUsers']) as $val) {
             $val = trim($val);
             if (strlen($val) > 0) {
                 if (get_user_by('login', $val)) {
                     $validUsers[] = $val;
                 } else {
                     $invalidUsers[] = $val;
                 }
             }
         }
         if (count($invalidUsers) > 0) {
             // return array('errorMsg' => "The following users you selected to ignore in live traffic reports are not valid on this system: " . htmlentities(implode(', ', $invalidUsers)) );
             $result['invalid_users'] = htmlentities(implode(', ', $invalidUsers));
         }
         if (count($validUsers) > 0) {
             $opts['liveTraf_ignoreUsers'] = implode(',', $validUsers);
         } else {
             $opts['liveTraf_ignoreUsers'] = '';
         }
         if (!$opts['other_WFNet']) {
             $wfdb = new wfDB();
             global $wpdb;
             $p = $wpdb->base_prefix;
             $wfdb->queryWrite("delete from {$p}" . 'wfBlocks where wfsn=1 and permanent=0');
         }
         $regenerateHtaccess = false;
         if (wfConfig::get('bannedURLs', false) !== $opts['bannedURLs']) {
             $regenerateHtaccess = true;
         }
         foreach ($opts as $key => $val) {
             if (in_array($key, self::$options_filter)) {
                 if ('apiKey' !== $key) {
                     //Don't save API key yet
                     wfConfig::set($key, $val);
                 }
             }
         }
         if ($regenerateHtaccess) {
             wfCache::addHtaccessCode('add');
         }
         if ('1' === $opts['autoUpdate']) {
             wfConfig::enableAutoUpdate();
         } else {
             if ('0' === $opts['autoUpdate']) {
                 wfConfig::disableAutoUpdate();
             }
         }
         if (isset($opts['disableCodeExecutionUploads'])) {
             try {
                 if ($opts['disableCodeExecutionUploads']) {
                     wfConfig::disableCodeExecutionForUploads();
                 } else {
                     wfConfig::removeCodeExecutionProtectionForUploads();
                 }
             } catch (wfConfigException $e) {
                 return array('error' => $e->getMessage());
             }
         }
         if (isset($opts['email_summary_enabled'])) {
             if (!empty($opts['email_summary_enabled'])) {
                 wfConfig::set('email_summary_enabled', 1);
                 wfConfig::set('email_summary_interval', $opts['email_summary_interval']);
                 wfConfig::set('email_summary_excluded_directories', $opts['email_summary_excluded_directories']);
                 wfActivityReport::scheduleCronJob();
             } else {
                 wfConfig::set('email_summary_enabled', 0);
                 wfActivityReport::disableCronJob();
             }
         }
         $sch = isset($opts['scheduleScan']) ? $opts['scheduleScan'] : '';
         if (get_option('mainwp_child_wordfence_cron_time') !== $sch) {
             update_option('mainwp_child_wordfence_cron_time', $sch);
             $sched = wp_next_scheduled('mainwp_child_wordfence_cron_scan');
             if (false !== $sched) {
                 wp_unschedule_event($sched, 'mainwp_child_wordfence_cron_scan');
             }
         }
         $result['cacheType'] = wfConfig::get('cacheType');
         $result['paidKeyMsg'] = false;
         $apiKey = trim($_POST['apiKey']);
         if (!$apiKey) {
             //Empty API key (after trim above), then try to get one.
             $api = new wfAPI('', wfUtils::getWPVersion());
             try {
                 $keyData = $api->call('get_anon_api_key');
                 if ($keyData['ok'] && $keyData['apiKey']) {
                     wfConfig::set('apiKey', $keyData['apiKey']);
                     wfConfig::set('isPaid', 0);
                     $result['apiKey'] = $keyData['apiKey'];
                     $result['isPaid'] = 0;
                     $reload = 'reload';
                 } else {
                     throw new Exception("We could not understand the Wordfence server's response because it did not contain an 'ok' and 'apiKey' element.");
                 }
             } catch (Exception $e) {
                 $result['error'] = 'Your options have been saved, but we encountered a problem. You left your API key blank, so we tried to get you a free API key from the Wordfence servers. However we encountered a problem fetching the free key: ' . htmlentities($e->getMessage());
                 return $result;
             }
         } else {
             if (wfConfig::get('apiKey') !== $apiKey) {
                 $api = new wfAPI($apiKey, wfUtils::getWPVersion());
                 try {
                     $res = $api->call('check_api_key', array(), array());
                     if ($res['ok'] && isset($res['isPaid'])) {
                         wfConfig::set('apiKey', $apiKey);
                         wfConfig::set('isPaid', $res['isPaid']);
                         //res['isPaid'] is boolean coming back as JSON and turned back into PHP struct. Assuming JSON to PHP handles bools.
                         $result['apiKey'] = $apiKey;
                         $result['isPaid'] = $res['isPaid'];
                         if ($res['isPaid']) {
                             $result['paidKeyMsg'] = true;
                         }
                         $reload = 'reload';
                     } else {
                         throw new Exception('We could not understand the Wordfence API server reply when updating your API key.');
                     }
                 } catch (Exception $e) {
                     $result['error'] = 'Your options have been saved. However we noticed you changed your API key and we tried to verify it with the Wordfence servers and received an error: ' . htmlentities($e->getMessage());
                     return $result;
                 }
             } else {
                 try {
                     $api = new wfAPI($apiKey, wfUtils::getWPVersion());
                     $res = $api->call('ping_api_key', array(), array());
                 } catch (Exception $e) {
                     $result['error'] = 'Your options have been saved. However we noticed you do not change your API key and we tried to verify it with the Wordfence servers and received an error: ' . htmlentities($e->getMessage());
                     return $result;
                 }
             }
         }
         $result['ok'] = 1;
         $result['reload'] = $reload;
         return $result;
     }
 }
Пример #4
0
 public static function ajax_email_summary_email_address_debug_callback()
 {
     $email = !empty($_REQUEST['email']) ? $_REQUEST['email'] : null;
     $report = new wfActivityReport();
     return $report->sendReportViaEmail($email) ? array('ok' => 1, 'result' => 'Test email sent successfully') : array('err' => "Test email failed to send.");
 }
Пример #5
0
 public function firewallBadIPs()
 {
     $IP = wfUtils::getIP();
     if ($this->isWhitelisted($IP)) {
         return;
     }
     $IPnum = wfUtils::inet_pton($IP);
     //New range and UA pattern blocking:
     $r1 = $this->getDB()->querySelect("select id, blockType, blockString from " . $this->ipRangesTable);
     foreach ($r1 as $blockRec) {
         if ($blockRec['blockType'] == 'IU') {
             $ipRangeBlocked = false;
             $uaPatternBlocked = false;
             $refBlocked = false;
             $bDat = explode('|', $blockRec['blockString']);
             $ipRange = $bDat[0];
             $uaPattern = $bDat[1];
             $refPattern = isset($bDat[2]) ? $bDat[2] : '';
             if ($ipRange) {
                 list($start_range, $end_range) = explode('-', $ipRange);
                 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));
                 }
                 if (strcmp($IPnum, $start_range) >= 0 && strcmp($IPnum, $end_range) <= 0) {
                     $ipRangeBlocked = true;
                 }
             }
             if ($uaPattern) {
                 if (wfUtils::isUABlocked($uaPattern)) {
                     $uaPatternBlocked = true;
                 }
             }
             if ($refPattern) {
                 if (wfUtils::isRefererBlocked($refPattern)) {
                     $refBlocked = true;
                 }
             }
             $doBlock = false;
             if ($uaPattern && $ipRange && $refPattern) {
                 if ($uaPatternBlocked && $ipRangeBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             }
             if ($uaPattern && $ipRange) {
                 if ($uaPatternBlocked && $ipRangeBlocked) {
                     $doBlock = true;
                 }
             }
             if ($uaPattern && $refPattern) {
                 if ($uaPatternBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             }
             if ($ipRange && $refPattern) {
                 if ($ipRangeBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             } else {
                 if ($uaPattern) {
                     if ($uaPatternBlocked) {
                         $doBlock = true;
                     }
                 } else {
                     if ($ipRange) {
                         if ($ipRangeBlocked) {
                             $doBlock = true;
                         }
                     } else {
                         if ($refPattern) {
                             if ($refBlocked) {
                                 $doBlock = true;
                             }
                         }
                     }
                 }
             }
             if ($doBlock) {
                 $this->getDB()->queryWrite("update " . $this->ipRangesTable . " set totalBlocked = totalBlocked + 1, lastBlocked = unix_timestamp() where id=%d", $blockRec['id']);
                 wfActivityReport::logBlockedIP($IP);
                 $this->do503(3600, "Advanced blocking in effect.");
             }
         }
     }
     //End range/UA blocking
     // Country blocking
     if (wfConfig::get('isPaid')) {
         $blockedCountries = wfConfig::get('cbl_countries', false);
         $bareRequestURI = wfUtils::extractBareURI($_SERVER['REQUEST_URI']);
         $bareBypassRedirURI = wfUtils::extractBareURI(wfConfig::get('cbl_bypassRedirURL', ''));
         $skipCountryBlocking = false;
         if ($bareBypassRedirURI && $bareRequestURI == $bareBypassRedirURI) {
             //Run this before country blocking because even if the user isn't blocked we need to set the bypass cookie so they can bypass future blocks.
             $bypassRedirDest = wfConfig::get('cbl_bypassRedirDest', '');
             if ($bypassRedirDest) {
                 self::setCBLCookieBypass();
                 $this->redirect($bypassRedirDest);
                 //exits
             }
         }
         $bareBypassViewURI = wfUtils::extractBareURI(wfConfig::get('cbl_bypassViewURL', ''));
         if ($bareBypassViewURI && $bareBypassViewURI == $bareRequestURI) {
             self::setCBLCookieBypass();
             $skipCountryBlocking = true;
         }
         if (!$skipCountryBlocking && $blockedCountries && !self::isCBLBypassCookieSet()) {
             if (is_user_logged_in() && !wfConfig::get('cbl_loggedInBlocked', false)) {
                 //User is logged in and we're allowing logins
                 //Do nothing
             } else {
                 if (strpos($_SERVER['REQUEST_URI'], '/wp-login.php') !== false && !wfConfig::get('cbl_loginFormBlocked', false)) {
                     //It's the login form and we're allowing that
                     //Do nothing
                 } else {
                     if (strpos($_SERVER['REQUEST_URI'], '/wp-login.php') === false && !wfConfig::get('cbl_restOfSiteBlocked', false)) {
                         //It's the rest of the site and we're allowing that
                         //Do nothing
                     } else {
                         if ($country = wfUtils::IP2Country($IP)) {
                             foreach (explode(',', $blockedCountries) as $blocked) {
                                 if (strtoupper($blocked) == strtoupper($country)) {
                                     //At this point we know the user has been blocked
                                     if (wfConfig::get('cbl_action') == 'redir') {
                                         $redirURL = wfConfig::get('cbl_redirURL');
                                         $eRedirHost = wfUtils::extractHostname($redirURL);
                                         $isExternalRedir = false;
                                         if ($eRedirHost && $eRedirHost != wfUtils::extractHostname(home_url())) {
                                             //It's an external redirect...
                                             $isExternalRedir = true;
                                         }
                                         if (!$isExternalRedir && wfUtils::extractBareURI($redirURL) == $bareRequestURI) {
                                             //Is this the URI we want to redirect to, then don't block it
                                             //Do nothing
                                             /* Uncomment the following if page components aren't loading for the page we redirect to.
                                             			   Uncommenting is not recommended because it means that anyone from a blocked country
                                             			   can crawl your site by sending the page blocked users are redirected to as the referer for every request.
                                             			   But it's your call.
                                             			} else if(wfUtils::extractBareURI($_SERVER['HTTP_REFERER']) == $redirURL){ //If the referer the page we want to redirect to? Then this might be loading as a component so don't block.
                                             				//Do nothing
                                             			*/
                                         } else {
                                             $this->redirect(wfConfig::get('cbl_redirURL'));
                                         }
                                     } else {
                                         $this->do503(3600, "Access from your area has been temporarily limited for security reasons");
                                         wfConfig::inc('totalCountryBlocked');
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($rec = $this->getDB()->querySingleRec("select blockedTime, reason from " . $this->blocksTable . " where IP=%s and (permanent=1 OR (blockedTime + %s > unix_timestamp()))", $IPnum, wfConfig::get('blockedTime'))) {
         $this->getDB()->queryWrite("update " . $this->blocksTable . " set lastAttempt=unix_timestamp(), blockedHits = blockedHits + 1 where IP=%s", $IPnum);
         $now = $this->getDB()->querySingle("select unix_timestamp()");
         $secsToGo = $rec['blockedTime'] + wfConfig::get('blockedTime') - $now;
         if (wfConfig::get('other_WFNet') && strpos($_SERVER['REQUEST_URI'], '/wp-login.php') !== false) {
             //We're on the login page and this IP has been blocked
             wordfence::wfsnReportBlockedAttempt($IP, 'login');
         }
         $this->do503($secsToGo, $rec['reason']);
     }
 }
 /**
  * Returns list of firewall activity up to $limit number of entries.
  * 
  * @param int $limit Max events to return in results
  * @return array
  */
 public function getRecentFirewallActivity($limit = 300, &$remainder)
 {
     $dateRange = wfActivityReport::getReportDateRange();
     $recent_firewall_activity = new wfRecentFirewallActivity(null, max(604800, $dateRange[1] - $dateRange[0]));
     $recent_firewall_activity->run();
     return $recent_firewall_activity->mostRecentActivity($limit, $remainder);
 }
Пример #7
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;
     }
 }
<?php

/**
 * @var wfActivityReportView $this
 */
$start_time = wfActivityReport::getReportDateFrom();
$end_time = time();
$report_start = date_i18n(get_option('date_format'), $start_time);
$report_end = date_i18n(get_option('date_format'), $end_time);
$title = sprintf('Wordfence activity from <br><strong>%s</strong> to <strong>%s</strong>', $report_start, $report_end);
$bg_colors = array('even' => 'background-color: #eeeeee;', 'odd' => '');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=<?php 
echo get_option('blog_charset');
?>
"/>
	<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
	<title><?php 
echo esc_html(strip_tags($title));
?>
</title>
	<!-- Targeting Windows Mobile -->
	<!--[if IEMobile 7]>
	<style type="text/css">

	</style>
	<![endif]-->
Пример #9
0
 public function checkForBlockedCountry()
 {
     static $hasRun;
     if (isset($hasRun)) {
         return;
     }
     $hasRun = true;
     $blockedCountries = wfConfig::get('cbl_countries', false);
     $bareRequestURI = untrailingslashit(wfUtils::extractBareURI($_SERVER['REQUEST_URI']));
     $IP = wfUtils::getIP();
     if ($country = wfUtils::IP2Country($IP)) {
         foreach (explode(',', $blockedCountries) as $blocked) {
             if (strtoupper($blocked) == strtoupper($country)) {
                 //At this point we know the user has been blocked
                 if (wfConfig::get('cbl_action') == 'redir') {
                     $redirURL = wfConfig::get('cbl_redirURL');
                     $eRedirHost = wfUtils::extractHostname($redirURL);
                     $isExternalRedir = false;
                     if ($eRedirHost && $eRedirHost != wfUtils::extractHostname(home_url())) {
                         //It's an external redirect...
                         $isExternalRedir = true;
                     }
                     if (!$isExternalRedir && untrailingslashit(wfUtils::extractBareURI($redirURL)) == $bareRequestURI) {
                         //Is this the URI we want to redirect to, then don't block it
                         //Do nothing
                         /* Uncomment the following if page components aren't loading for the page we redirect to.
                         			   Uncommenting is not recommended because it means that anyone from a blocked country
                         			   can crawl your site by sending the page blocked users are redirected to as the referer for every request.
                         			   But it's your call.
                         			} else if(wfUtils::extractBareURI($_SERVER['HTTP_REFERER']) == $redirURL){ //If the referer the page we want to redirect to? Then this might be loading as a component so don't block.
                         				//Do nothing
                         			*/
                     } else {
                         wfConfig::inc('totalCountryBlocked');
                         $this->initLogRequest();
                         $this->currentRequest->actionDescription = 'blocked access via country blocking and redirected to URL (' . wfConfig::get('cbl_redirURL') . ')';
                         $this->currentRequest->statusCode = 503;
                         if (!$this->currentRequest->action) {
                             $this->currentRequest->action = 'blocked:wordfence';
                         }
                         $this->logHit();
                         wfActivityReport::logBlockedIP($IP);
                         $this->redirect(wfConfig::get('cbl_redirURL'));
                     }
                 } else {
                     $this->currentRequest->actionDescription = 'blocked access via country blocking';
                     wfConfig::inc('totalCountryBlocked');
                     wfActivityReport::logBlockedIP($IP);
                     $this->do503(3600, "Access from your area has been temporarily limited for security reasons");
                 }
             }
         }
     }
 }
Пример #10
0
 public function firewallBadIPs()
 {
     $IP = wfUtils::getIP();
     if ($this->isWhitelisted($IP)) {
         return;
     }
     $IPnum = wfUtils::inet_pton($IP);
     $hostname = null;
     //New range and UA pattern blocking:
     $r1 = $this->getDB()->querySelect("select id, blockType, blockString from " . $this->ipRangesTable);
     foreach ($r1 as $blockRec) {
         if ($blockRec['blockType'] == 'IU') {
             $ipRangeBlocked = false;
             $uaPatternBlocked = false;
             $refBlocked = false;
             $bDat = explode('|', $blockRec['blockString']);
             $ipRange = $bDat[0];
             $uaPattern = $bDat[1];
             $refPattern = isset($bDat[2]) ? $bDat[2] : '';
             if ($ipRange) {
                 list($start_range, $end_range) = explode('-', $ipRange);
                 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));
                 }
                 if (strcmp($IPnum, $start_range) >= 0 && strcmp($IPnum, $end_range) <= 0) {
                     $ipRangeBlocked = true;
                 }
             }
             if (!empty($bDat[3])) {
                 $ipRange = true;
                 /* We reuse the ipRangeBlocked variable */
                 if ($hostname === null) {
                     $hostname = wfUtils::reverseLookup($IP);
                 }
                 if (preg_match(wfUtils::patternToRegex($bDat[3]), $hostname)) {
                     $ipRangeBlocked = true;
                 }
             }
             if ($uaPattern) {
                 if (wfUtils::isUABlocked($uaPattern)) {
                     $uaPatternBlocked = true;
                 }
             }
             if ($refPattern) {
                 if (wfUtils::isRefererBlocked($refPattern)) {
                     $refBlocked = true;
                 }
             }
             $doBlock = false;
             if ($uaPattern && $ipRange && $refPattern) {
                 if ($uaPatternBlocked && $ipRangeBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             }
             if ($uaPattern && $ipRange) {
                 if ($uaPatternBlocked && $ipRangeBlocked) {
                     $doBlock = true;
                 }
             }
             if ($uaPattern && $refPattern) {
                 if ($uaPatternBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             }
             if ($ipRange && $refPattern) {
                 if ($ipRangeBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             } else {
                 if ($uaPattern) {
                     if ($uaPatternBlocked) {
                         $doBlock = true;
                     }
                 } else {
                     if ($ipRange) {
                         if ($ipRangeBlocked) {
                             $doBlock = true;
                         }
                     } else {
                         if ($refPattern) {
                             if ($refBlocked) {
                                 $doBlock = true;
                             }
                         }
                     }
                 }
             }
             if ($doBlock) {
                 $this->getDB()->queryWrite("update " . $this->ipRangesTable . " set totalBlocked = totalBlocked + 1, lastBlocked = unix_timestamp() where id=%d", $blockRec['id']);
                 wfActivityReport::logBlockedIP($IP);
                 $this->currentRequest->actionDescription = 'UA/Referrer/IP Range not allowed';
                 $this->do503(3600, "Advanced blocking in effect.");
             }
         }
     }
     //End range/UA blocking
     // Country blocking
     if (wfConfig::get('isPaid')) {
         $blockedCountries = wfConfig::get('cbl_countries', false);
         $bareRequestURI = wfUtils::extractBareURI($_SERVER['REQUEST_URI']);
         $bareBypassRedirURI = wfUtils::extractBareURI(wfConfig::get('cbl_bypassRedirURL', ''));
         $skipCountryBlocking = false;
         if ($bareBypassRedirURI && $bareRequestURI == $bareBypassRedirURI) {
             //Run this before country blocking because even if the user isn't blocked we need to set the bypass cookie so they can bypass future blocks.
             $bypassRedirDest = wfConfig::get('cbl_bypassRedirDest', '');
             if ($bypassRedirDest) {
                 self::setCBLCookieBypass();
                 $this->redirect($bypassRedirDest);
                 //exits
             }
         }
         $bareBypassViewURI = wfUtils::extractBareURI(wfConfig::get('cbl_bypassViewURL', ''));
         if ($bareBypassViewURI && $bareBypassViewURI == $bareRequestURI) {
             self::setCBLCookieBypass();
             $skipCountryBlocking = true;
         }
         if (!$skipCountryBlocking && $blockedCountries && !self::isCBLBypassCookieSet()) {
             // If everything is checked, make sure this always runs.
             if (wfConfig::get('cbl_loggedInBlocked', false) && wfConfig::get('cbl_loginFormBlocked', false) && wfConfig::get('cbl_restOfSiteBlocked', false)) {
                 $this->checkForBlockedCountry();
             }
             // Block logged in users.
             if (wfConfig::get('cbl_loggedInBlocked', false) && is_user_logged_in()) {
                 $this->checkForBlockedCountry();
             }
             // Block the login form itself and any attempt to authenticate.
             if (wfConfig::get('cbl_loginFormBlocked', false)) {
                 if (self::isAuthRequest()) {
                     $this->checkForBlockedCountry();
                 }
                 add_filter('authenticate', array($this, 'checkForBlockedCountry'), 1, 0);
             }
             // Block requests that aren't to the login page, xmlrpc.php, or a user already logged in.
             if (wfConfig::get('cbl_restOfSiteBlocked', false) && !self::isAuthRequest() && !defined('XMLRPC_REQUEST') && !is_user_logged_in()) {
                 $this->checkForBlockedCountry();
             }
             // XMLRPC is inaccesible when public portion of the site and auth is disabled.
             if (wfConfig::get('cbl_loginFormBlocked', false) && wfConfig::get('cbl_restOfSiteBlocked', false) && defined('XMLRPC_REQUEST')) {
                 $this->checkForBlockedCountry();
             }
         }
     }
     if ($rec = $this->getDB()->querySingleRec("select blockedTime, reason from " . $this->blocksTable . " where IP=%s and (permanent=1 OR (blockedTime + %s > unix_timestamp()))", $IPnum, wfConfig::get('blockedTime'))) {
         $this->getDB()->queryWrite("update " . $this->blocksTable . " set lastAttempt=unix_timestamp(), blockedHits = blockedHits + 1 where IP=%s", $IPnum);
         $now = $this->getDB()->querySingle("select unix_timestamp()");
         $secsToGo = $rec['blockedTime'] + wfConfig::get('blockedTime') - $now;
         if (wfConfig::get('other_WFNet') && self::isAuthRequest()) {
             //It's an auth request and this IP has been blocked
             $this->getCurrentRequest()->action = 'blocked:wfsnrepeat';
             wordfence::wfsnReportBlockedAttempt($IP, 'login');
         }
         $this->do503($secsToGo, $rec['reason']);
     }
 }