Esempio n. 1
0
 public function call($action, $getParams = array(), $postParams = array(), $forceSSL = false)
 {
     $apiURL = $this->getAPIURL();
     //Sanity check. Developer should call wfAPI::SSLEnabled() to check if SSL is enabled before forcing SSL and return a user friendly msg if it's not.
     if ($forceSSL && !preg_match('/^https:/i', $apiURL)) {
         //User's should never see this message unless we aren't calling SSLEnabled() to check if SSL is enabled before using call() with forceSSL
         throw new Exception("SSL is not supported by your web server and is required to use this function. Please ask your hosting provider or site admin to install cURL with openSSL to use this feature.");
     }
     $json = $this->getURL($apiURL . '/v' . WORDFENCE_API_VERSION . '/?' . $this->makeAPIQueryString() . '&' . self::buildQuery(array_merge(array('action' => $action), $getParams)), $postParams);
     if (!$json) {
         throw new Exception("We received an empty data response from the Wordfence scanning servers when calling the '{$action}' function.");
     }
     $dat = json_decode($json, true);
     if (isset($dat['_isPaidKey'])) {
         wfConfig::set('keyExpDays', $dat['_keyExpDays']);
         if ($dat['_keyExpDays'] > -1) {
             wfConfig::set('isPaid', 1);
         } else {
             if ($dat['_keyExpDays'] < 0) {
                 wfConfig::set('isPaid', '');
             }
         }
     }
     if (!is_array($dat)) {
         throw new Exception("We received a data structure that is not the expected array when contacting the Wordfence scanning servers and calling the '{$action}' function.");
     }
     if (is_array($dat) && isset($dat['errorMsg'])) {
         throw new Exception($dat['errorMsg']);
     }
     return $dat;
 }
Esempio n. 2
0
 protected function getURL($url, $postParams = array())
 {
     wordfence::status(4, 'info', "Calling Wordfence API v" . WORDFENCE_API_VERSION . ":" . $url);
     if (!function_exists('wp_remote_post')) {
         require_once ABSPATH . WPINC . 'http.php';
     }
     $ssl_verify = (bool) wfConfig::get('ssl_verify');
     $args = array('timeout' => 900, 'user-agent' => "Wordfence.com UA " . (defined('WORDFENCE_VERSION') ? WORDFENCE_VERSION : '[Unknown version]'), 'body' => $postParams, 'sslverify' => $ssl_verify);
     if (!$ssl_verify) {
         // Some versions of cURL will complain that SSL verification is disabled but the CA bundle was supplied.
         $args['sslcertificates'] = false;
     }
     $response = wp_remote_post($url, $args);
     $this->lastHTTPStatus = (int) wp_remote_retrieve_response_code($response);
     if (is_wp_error($response)) {
         $error_message = $response->get_error_message();
         throw new Exception("There was an " . ($error_message ? '' : 'unknown ') . "error connecting to the the Wordfence scanning servers" . ($error_message ? ": {$error_message}" : '.'));
     }
     if (!empty($response['response']['code'])) {
         $this->lastHTTPStatus = (int) $response['response']['code'];
     }
     if (200 != $this->lastHTTPStatus) {
         throw new Exception("We received an error response when trying to contact the Wordfence scanning servers. The HTTP status code was [{$this->lastHTTPStatus}]");
     }
     $this->curlContent = wp_remote_retrieve_body($response);
     return $this->curlContent;
 }
Esempio n. 3
0
 public function call($action, $getParams = array(), $postParams = array())
 {
     $json = $this->getURL($this->getAPIURL() . '/v' . WORDFENCE_API_VERSION . '/?' . $this->makeAPIQueryString() . '&' . self::buildQuery(array_merge(array('action' => $action), $getParams)), $postParams);
     if (!$json) {
         throw new Exception("We received an empty data response from the Wordfence scanning servers when calling the '{$action}' function.");
     }
     $dat = json_decode($json, true);
     if (isset($dat['_isPaidKey'])) {
         wfConfig::set('keyExpDays', $dat['_keyExpDays']);
         if ($dat['_keyExpDays'] > -1) {
             wfConfig::set('isPaid', 1);
         } else {
             if ($dat['_keyExpDays'] < 0) {
                 wfConfig::set('isPaid', '');
             }
         }
     }
     if (!is_array($dat)) {
         throw new Exception("We received a data structure that is not the expected array when contacting the Wordfence scanning servers and calling the '{$action}' function.");
     }
     if (is_array($dat) && isset($dat['errorMsg'])) {
         throw new Exception($dat['errorMsg']);
     }
     return $dat;
 }
 public static function verifyCrawlerPTR($hostPattern, $IP)
 {
     global $wpdb;
     $table = $wpdb->base_prefix . 'wfCrawlers';
     $db = new wfDB();
     $IPn = wfUtils::inet_aton($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;
         }
     }
     $wfLog = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
     $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 = gethostbynamel($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;
     }
 }
<?php

$diagnostic = new wfDiagnostic();
$plugins = get_plugins();
$activePlugins = array_flip(get_option('active_plugins'));
$activeNetworkPlugins = is_multisite() ? array_flip(wp_get_active_network_plugins()) : array();
$muPlugins = get_mu_plugins();
$themes = wp_get_themes();
$currentTheme = wp_get_theme();
$cols = 3;
$w = new wfConfig();
?>

<div class="wrap wordfence">
	<?php 
require 'menuHeader.php';
?>
	<h2 id="wfHeading">
		Diagnostics
	</h2>
	<br clear="both"/>
	
	<?php 
$rightRail = new wfView('marketing/rightrail', array('additionalClasses' => 'wordfenceRightRailDiagnostics'));
echo $rightRail;
?>

	<form id="wfConfigForm">
		<table class="wf-table"<?php 
echo !empty($inEmail) ? ' border=1' : '';
?>
Esempio n. 6
0
 public static function getIPsGeo($IPs)
 {
     //works with int or dotted. Outputs same format it receives.
     $IPs = array_unique($IPs);
     $toResolve = array();
     $db = new wfDB();
     global $wpdb;
     $locsTable = $wpdb->base_prefix . 'wfLocs';
     $IPLocs = array();
     foreach ($IPs as $IP) {
         $isBinaryIP = !self::isValidIP($IP);
         if ($isBinaryIP) {
             $ip_printable = wfUtils::inet_ntop($IP);
             $ip_bin = $IP;
         } else {
             $ip_printable = $IP;
             $ip_bin = wfUtils::inet_pton($IP);
         }
         $row = $db->querySingleRec("select IP, ctime, failed, city, region, countryName, countryCode, lat, lon, unix_timestamp() - ctime as age from " . $locsTable . " where IP=%s", $ip_bin);
         if ($row) {
             if ($row['age'] > WORDFENCE_MAX_IPLOC_AGE) {
                 $db->queryWrite("delete from " . $locsTable . " where IP=%s", $row['IP']);
             } else {
                 if ($row['failed'] == 1) {
                     $IPLocs[$ip_printable] = false;
                 } else {
                     $row['IP'] = self::inet_ntop($row['IP']);
                     $IPLocs[$ip_printable] = $row;
                 }
             }
         }
         if (!isset($IPLocs[$ip_printable])) {
             $toResolve[] = $ip_printable;
         }
     }
     if (sizeof($toResolve) > 0) {
         $api = new wfAPI(wfConfig::get('apiKey'), wfUtils::getWPVersion());
         try {
             $freshIPs = $api->call('resolve_ips', array(), array('ips' => implode(',', $toResolve)));
             if (is_array($freshIPs)) {
                 foreach ($freshIPs as $IP => $value) {
                     $IP_bin = wfUtils::inet_pton($IP);
                     if ($value == 'failed') {
                         $db->queryWrite("insert IGNORE into " . $locsTable . " (IP, ctime, failed) values (%s, unix_timestamp(), 1)", $IP_bin);
                         $IPLocs[$IP] = false;
                     } else {
                         if (is_array($value)) {
                             for ($i = 0; $i <= 5; $i++) {
                                 //Prevent warnings in debug mode about uninitialized values
                                 if (!isset($value[$i])) {
                                     $value[$i] = '';
                                 }
                             }
                             $db->queryWrite("insert IGNORE into " . $locsTable . " (IP, ctime, failed, city, region, countryName, countryCode, lat, lon) values (%s, unix_timestamp(), 0, '%s', '%s', '%s', '%s', %s, %s)", $IP_bin, $value[3], $value[2], $value[1], $value[0], $value[4], $value[5]);
                             $IPLocs[$IP] = array('IP' => $IP, 'city' => $value[3], 'region' => $value[2], 'countryName' => $value[1], 'countryCode' => $value[0], 'lat' => $value[4], 'lon' => $value[5]);
                         }
                     }
                 }
             }
         } catch (Exception $e) {
             wordfence::status(2, 'error', "Call to Wordfence API to resolve IPs failed: " . $e->getMessage());
             return array();
         }
     }
     return $IPLocs;
 }
 public function scan($forkObj)
 {
     if (!$this->startTime) {
         $this->startTime = microtime(true);
     }
     if (!$this->lastStatusTime) {
         $this->lastStatusTime = microtime(true);
     }
     $db = new wfDB();
     $lastCount = 'whatever';
     $excludePattern = false;
     if (wfConfig::get('scan_exclude', false)) {
         $exParts = explode(',', wfConfig::get('scan_exclude'));
         foreach ($exParts as &$exPart) {
             $exPart = preg_quote($exPart);
             $exPart = preg_replace('/\\\\\\*/', '.*', $exPart);
         }
         $excludePattern = '/^(?:' . implode('|', $exParts) . ')$/i';
     }
     while (true) {
         $thisCount = $db->querySingle("select count(*) from " . $db->prefix() . "wfFileMods where oldMD5 != newMD5 and knownFile=0");
         if ($thisCount == $lastCount) {
             //count should always be decreasing. If not, we're in an infinite loop so lets catch it early
             break;
         }
         $lastCount = $thisCount;
         $res1 = $db->querySelect("select filename, filenameMD5, hex(newMD5) as newMD5 from " . $db->prefix() . "wfFileMods where oldMD5 != newMD5 and knownFile=0 limit 500");
         if (sizeof($res1) < 1) {
             break;
         }
         foreach ($res1 as $rec1) {
             $db->queryWrite("update " . $db->prefix() . "wfFileMods set oldMD5 = newMD5 where filenameMD5='%s'", $rec1['filenameMD5']);
             //A way to mark as scanned so that if we come back from a sleep we don't rescan this one.
             $file = $rec1['filename'];
             if ($excludePattern && preg_match($excludePattern, $file)) {
                 continue;
             }
             $fileSum = $rec1['newMD5'];
             if (!file_exists($this->path . $file)) {
                 continue;
             }
             $fileExt = '';
             if (preg_match('/\\.([a-zA-Z\\d\\-]{1,7})$/', $file, $matches)) {
                 $fileExt = strtolower($matches[1]);
             }
             $isPHP = false;
             if (preg_match('/^(?:php|phtml|php\\d+)$/', $fileExt)) {
                 $isPHP = true;
             }
             $dontScanForURLs = false;
             if (!wfConfig::get('scansEnabled_highSense') && (preg_match('/^(?:\\.htaccess|wp\\-config\\.php)$/', $file) || preg_match('/^(?:sql|tbz|tgz|gz|tar|log|err\\d+)$/', $fileExt))) {
                 $dontScanForURLs = true;
             }
             if (preg_match('/^(?:jpg|jpeg|mp3|avi|m4v|gif|png)$/', $fileExt) && !wfConfig::get('scansEnabled_scanImages')) {
                 continue;
             }
             if (!wfConfig::get('scansEnabled_highSense') && strtolower($fileExt) == 'sql') {
                 //
                 continue;
             }
             if (wfUtils::fileTooBig($this->path . $file)) {
                 //We can't use filesize on 32 bit systems for files > 2 gigs
                 //We should not need this check because files > 2 gigs are not hashed and therefore won't be received back as unknowns from the API server
                 //But we do it anyway to be safe.
                 wordfence::status(2, 'error', "Encountered file that is too large: {$file} - Skipping.");
                 continue;
             }
             $fsize = filesize($this->path . $file);
             //Checked if too big above
             if ($fsize > 1000000) {
                 $fsize = sprintf('%.2f', $fsize / 1000000) . "M";
             } else {
                 $fsize = $fsize . "B";
             }
             if (function_exists('memory_get_usage')) {
                 wordfence::status(4, 'info', "Scanning contents: {$file} (Size:{$fsize} Mem:" . sprintf('%.1f', memory_get_usage(true) / (1024 * 1024)) . "M)");
             } else {
                 wordfence::status(4, 'info', "Scanning contents: {$file} (Size: {$fsize})");
             }
             $stime = microtime(true);
             $fh = @fopen($this->path . $file, 'r');
             if (!$fh) {
                 continue;
             }
             $totalRead = 0;
             while (!feof($fh)) {
                 $data = fread($fh, 1 * 1024 * 1024);
                 //read 1 megs max per chunk
                 $totalRead += strlen($data);
                 if ($totalRead < 1) {
                     break;
                 }
                 if ($isPHP || wfConfig::get('scansEnabled_scanImages')) {
                     if (strpos($data, '$allowed' . 'Sites') !== false && strpos($data, "define ('VER" . "SION', '1.") !== false && strpos($data, "TimThum" . "b script created by") !== false) {
                         if (!$this->isSafeFile($this->path . $file)) {
                             $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => $fileSum, 'shortMsg' => "File is an old version of TimThumb which is vulnerable.", 'longMsg' => "This file appears to be an old version of the TimThumb script which makes your system vulnerable to attackers. Please upgrade the theme or plugin that uses this or remove it.", 'data' => array('file' => $file, 'canDiff' => false, 'canFix' => false, 'canDelete' => true)));
                             break;
                         }
                     } else {
                         if (strpos($file, 'lib/wordfenceScanner.php') === false && preg_match($this->patterns['sigPattern'], $data, $matches)) {
                             if (!$this->isSafeFile($this->path . $file)) {
                                 $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => $fileSum, 'shortMsg' => "This file appears to be malicious", 'longMsg' => "This file appears to be installed by a hacker to perform malicious activity. If you know about this file you can choose to ignore it to exclude it from future scans. The text we found in this file that matches a known malicious file is: <strong style=\"color: #F00;\">\"" . $matches[1] . "\"</strong>.", 'data' => array('file' => $file, 'canDiff' => false, 'canFix' => false, 'canDelete' => true)));
                                 break;
                             }
                         }
                     }
                     if (preg_match($this->patterns['pat2'], $data)) {
                         if (!$this->isSafeFile($this->path . $file)) {
                             $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => $fileSum, 'shortMsg' => "This file may contain malicious executable code: " . $this->path . $file, 'longMsg' => "This file is a PHP executable file and contains an " . $this->patterns['word1'] . " function and " . $this->patterns['word2'] . " decoding function on the same line. This is a common technique used by hackers to hide and execute code. If you know about this file you can choose to ignore it to exclude it from future scans.", 'data' => array('file' => $file, 'canDiff' => false, 'canFix' => false, 'canDelete' => true)));
                             break;
                         }
                     }
                     if (wfConfig::get('scansEnabled_highSense')) {
                         $badStringFound = false;
                         if (strpos($data, $this->patterns['badstrings'][0]) !== false) {
                             for ($i = 1; $i < sizeof($this->patterns['badstrings']); $i++) {
                                 if (strpos($data, $this->patterns['badstrings'][$i]) !== false) {
                                     $badStringFound = $this->patterns['badstrings'][$i];
                                     break;
                                 }
                             }
                         }
                         if ($badStringFound) {
                             if (!$this->isSafeFile($this->path . $file)) {
                                 $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => $fileSum, 'shortMsg' => "This file may contain malicious executable code" . $this->path . $file, 'longMsg' => "This file is a PHP executable file and contains the word 'eval' (without quotes) and the word '" . $badStringFound . "' (without quotes). The eval() function along with an encoding function like the one mentioned are commonly used by hackers to hide their code. If you know about this file you can choose to ignore it to exclude it from future scans.", 'data' => array('file' => $file, 'canDiff' => false, 'canFix' => false, 'canDelete' => true)));
                                 break;
                             }
                         }
                     }
                     if (!$dontScanForURLs) {
                         $this->urlHoover->hoover($file, $data);
                     }
                 } else {
                     if (!$dontScanForURLs) {
                         $this->urlHoover->hoover($file, $data);
                     }
                 }
                 if ($totalRead > 2 * 1024 * 1024) {
                     break;
                 }
             }
             fclose($fh);
             $mtime = sprintf("%.5f", microtime(true) - $stime);
             $this->totalFilesScanned++;
             if (microtime(true) - $this->lastStatusTime > 1) {
                 $this->lastStatusTime = microtime(true);
                 $this->writeScanningStatus();
             }
             $forkObj->forkIfNeeded();
         }
     }
     $this->writeScanningStatus();
     wordfence::status(2, 'info', "Asking Wordfence to check URL's against malware list.");
     $hooverResults = $this->urlHoover->getBaddies();
     if ($this->urlHoover->errorMsg) {
         $this->errorMsg = $this->urlHoover->errorMsg;
         return false;
     }
     $this->urlHoover->cleanup();
     foreach ($hooverResults as $file => $hresults) {
         foreach ($hresults as $result) {
             if (preg_match('/wfBrowscapCache\\.php$/', $file)) {
                 continue;
             }
             if ($result['badList'] == 'goog-malware-shavar') {
                 if (!$this->isSafeFile($this->path . $file)) {
                     $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => md5_file($this->path . $file), 'shortMsg' => "File contains suspected malware URL: " . $this->path . $file, 'longMsg' => "This file contains a suspected malware URL listed on Google's list of malware sites. Wordfence decodes " . $this->patterns['word3'] . " when scanning files so the URL may not be visible if you view this file. The URL is: " . $result['URL'] . " - More info available at <a href=\"http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=" . urlencode($result['URL']) . "&client=googlechrome&hl=en-US\" target=\"_blank\">Google Safe Browsing diagnostic page</a>.", 'data' => array('file' => $file, 'badURL' => $result['URL'], 'canDiff' => false, 'canFix' => false, 'canDelete' => true, 'gsb' => 'goog-malware-shavar')));
                 }
             } else {
                 if ($result['badList'] == 'googpub-phish-shavar') {
                     if (!$this->isSafeFile($this->path . $file)) {
                         $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => md5_file($this->path . $file), 'shortMsg' => "File contains suspected phishing URL: " . $this->path . $file, 'longMsg' => "This file contains a URL that is a suspected phishing site that is currently listed on Google's list of known phishing sites. The URL is: " . $result['URL'], 'data' => array('file' => $file, 'badURL' => $result['URL'], 'canDiff' => false, 'canFix' => false, 'canDelete' => true, 'gsb' => 'googpub-phish-shavar')));
                     }
                 }
             }
         }
     }
     return $this->results;
 }
<?php

$w = new wfConfig();
?>
<div class="wordfenceModeElem" id="wordfenceMode_options"></div>
<div class="wrap">
	<?php 
require 'menuHeader.php';
?>
	<?php 
$helpLink = "http://docs.wordfence.com/en/Wordfence_options";
$helpLabel = "Learn more about Wordfence Options";
$pageTitle = "Wordfence Options";
include 'pageTitle.php';
?>
	<div class="wordfenceLive">
		<table border="0" cellpadding="0" cellspacing="0">
			<tr>
				<td><h2>Wordfence Live Activity:</h2></td>
				<td id="wfLiveStatus"></td>
			</tr>
		</table>
	</div>
	<?php 
$rightRail = new wfView('marketing/rightrail', array('additionalClasses' => 'wordfenceRightRailOptions'));
echo $rightRail;
?>
	<form id="wfConfigForm">
		<table class="wfConfigForm">
			<tr>
				<td colspan="2"><h2>License</h2></td>
Esempio n. 9
0
				                     href="https://www.wordfence.com/gnl1scanGetHelp/wordfence-site-cleanings/">
						Get Help</a></p>
			</div>


		</div>
		<div style="margin-top: 20px;">
			<div id="wfTabs">
				<a href="#" id="wfNewIssuesTab" class="wfTab2 wfTabSwitch selected" onclick="wordfenceAdmin.switchIssuesTab(this, 'new'); return false;">New Issues</a>
				<a href="#" class="wfTab2 wfTabSwitch"          onclick="wordfenceAdmin.switchIssuesTab(this, 'ignored'); return false;">Ignored Issues</a>
			</div>
			<div class="wfTabsContainer">
				<div id="wfIssues_new" class="wfIssuesContainer">
					<h2>New Issues</h2>
					<?php 
if (wfConfig::get('scansEnabled_highSense')) {
    ?>
					<div class="wf-notice">
						<em>HIGH SENSITIVITY scanning is enabled, it may produce false positives</em>
					</div>
					<?php 
}
?>
					<p>
						The list below shows new problems or warnings that Wordfence found with your site.
						If you have fixed all the issues below, you can <a href="#" onclick="WFAD.updateAllIssues('deleteNew'); return false;">click here to mark all new issues as fixed</a>.
						You can also <a href="#" onclick="WFAD.updateAllIssues('ignoreAllNew'); return false;">ignore all new issues</a> which will exclude all issues listed below from future scans.
					</p>
					<p>
						<a href="#" onclick="jQuery('#wfBulkOps').toggle(); return false;">Bulk operation&raquo;&raquo;</a>
						<div id="wfBulkOps" style="display: none;">
Esempio n. 10
0
 /**
  * @param wfScanEngine $forkObj
  * @return array
  */
 public function scan($forkObj)
 {
     $this->scanEngine = $forkObj;
     $loader = $this->scanEngine->getKnownFilesLoader();
     if (!$this->startTime) {
         $this->startTime = microtime(true);
     }
     if (!$this->lastStatusTime) {
         $this->lastStatusTime = microtime(true);
     }
     $db = new wfDB();
     $lastCount = 'whatever';
     $excludePattern = self::getExcludeFilePattern(self::EXCLUSION_PATTERNS_USER & self::EXCLUSION_PATTERNS_MALWARE);
     while (true) {
         $thisCount = $db->querySingle("select count(*) from " . $db->prefix() . "wfFileMods where oldMD5 != newMD5 and knownFile=0");
         if ($thisCount == $lastCount) {
             //count should always be decreasing. If not, we're in an infinite loop so lets catch it early
             break;
         }
         $lastCount = $thisCount;
         $res1 = $db->querySelect("select filename, filenameMD5, hex(newMD5) as newMD5 from " . $db->prefix() . "wfFileMods where oldMD5 != newMD5 and knownFile=0 limit 500");
         if (sizeof($res1) < 1) {
             break;
         }
         foreach ($res1 as $rec1) {
             $db->queryWrite("update " . $db->prefix() . "wfFileMods set oldMD5 = newMD5 where filenameMD5='%s'", $rec1['filenameMD5']);
             //A way to mark as scanned so that if we come back from a sleep we don't rescan this one.
             $file = $rec1['filename'];
             if ($excludePattern && preg_match($excludePattern, $file)) {
                 continue;
             }
             $fileSum = $rec1['newMD5'];
             if (!file_exists($this->path . $file)) {
                 continue;
             }
             $fileExt = '';
             if (preg_match('/\\.([a-zA-Z\\d\\-]{1,7})$/', $file, $matches)) {
                 $fileExt = strtolower($matches[1]);
             }
             $isPHP = false;
             if (preg_match('/\\.(?:php(?:\\d+)?|phtml)(\\.|$)/i', $file)) {
                 $isPHP = true;
             }
             $dontScanForURLs = false;
             if (!wfConfig::get('scansEnabled_highSense') && (preg_match('/^(?:\\.htaccess|wp\\-config\\.php)$/', $file) || $file === ini_get('user_ini.filename'))) {
                 $dontScanForURLs = true;
             }
             $isScanImagesFile = false;
             if (!$isPHP && preg_match('/^(?:jpg|jpeg|mp3|avi|m4v|gif|png|sql|js|tbz2?|bz2?|xz|zip|tgz|gz|tar|log|err\\d+)$/', $fileExt)) {
                 if (wfConfig::get('scansEnabled_scanImages')) {
                     $isScanImagesFile = true;
                 } else {
                     continue;
                 }
             }
             $isHighSensitivityFile = false;
             if (strtolower($fileExt) == 'sql') {
                 if (wfConfig::get('scansEnabled_highSense')) {
                     $isHighSensitivityFile = true;
                 } else {
                     continue;
                 }
             }
             if (wfUtils::fileTooBig($this->path . $file)) {
                 //We can't use filesize on 32 bit systems for files > 2 gigs
                 //We should not need this check because files > 2 gigs are not hashed and therefore won't be received back as unknowns from the API server
                 //But we do it anyway to be safe.
                 wordfence::status(2, 'error', "Encountered file that is too large: {$file} - Skipping.");
                 continue;
             }
             wfUtils::beginProcessingFile($file);
             $fsize = filesize($this->path . $file);
             //Checked if too big above
             if ($fsize > 1000000) {
                 $fsize = sprintf('%.2f', $fsize / 1000000) . "M";
             } else {
                 $fsize = $fsize . "B";
             }
             if (function_exists('memory_get_usage')) {
                 wordfence::status(4, 'info', "Scanning contents: {$file} (Size:{$fsize} Mem:" . sprintf('%.1f', memory_get_usage(true) / (1024 * 1024)) . "M)");
             } else {
                 wordfence::status(4, 'info', "Scanning contents: {$file} (Size: {$fsize})");
             }
             $stime = microtime(true);
             $fh = @fopen($this->path . $file, 'r');
             if (!$fh) {
                 continue;
             }
             $totalRead = 0;
             $dataForFile = $this->dataForFile($file);
             while (!feof($fh)) {
                 $data = fread($fh, 1 * 1024 * 1024);
                 //read 1 megs max per chunk
                 $totalRead += strlen($data);
                 if ($totalRead < 1) {
                     break;
                 }
                 $extraMsg = '';
                 if ($isScanImagesFile) {
                     $extraMsg = ' This file was detected because you have enabled "Scan images, binary, and other files as if they were executable", which treats non-PHP files as if they were PHP code. This option is more aggressive than the usual scans, and may cause false positives.';
                 } else {
                     if ($isHighSensitivityFile) {
                         $extraMsg = ' This file was detected because you have enabled HIGH SENSITIVITY scanning. This option is more aggressive than the usual scans, and may cause false positives.';
                     }
                 }
                 if ($isPHP || wfConfig::get('scansEnabled_scanImages')) {
                     if (strpos($data, '$allowed' . 'Sites') !== false && strpos($data, "define ('VER" . "SION', '1.") !== false && strpos($data, "TimThum" . "b script created by") !== false) {
                         if (!$this->isSafeFile($this->path . $file)) {
                             $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => $fileSum, 'shortMsg' => "File is an old version of TimThumb which is vulnerable.", 'longMsg' => "This file appears to be an old version of the TimThumb script which makes your system vulnerable to attackers. Please upgrade the theme or plugin that uses this or remove it." . $extraMsg, 'data' => array_merge(array('file' => $file), $dataForFile)));
                             break;
                         }
                     } else {
                         if (strpos($file, 'lib/wordfenceScanner.php') === false) {
                             // && preg_match($this->patterns['sigPattern'], $data, $matches)){
                             $regexMatched = false;
                             foreach ($this->patterns['rules'] as $rule) {
                                 if (preg_match('/(' . $rule[2] . ')/i', $data, $matches)) {
                                     if (!$this->isSafeFile($this->path . $file)) {
                                         $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => $fileSum, 'shortMsg' => "File appears to be malicious: " . esc_html($file), 'longMsg' => "This file appears to be installed by a hacker to perform malicious activity. If you know about this file you can choose to ignore it to exclude it from future scans. The text we found in this file that matches a known malicious file is: <strong style=\"color: #F00;\">\"" . esc_html(strlen($matches[1]) > 200 ? substr($matches[1], 0, 200) . '...' : $matches[1]) . "\"</strong>. The infection type is: <strong>" . esc_html($rule[3]) . '</strong>' . $extraMsg, 'data' => array_merge(array('file' => $file), $dataForFile)));
                                         $regexMatched = true;
                                         break;
                                     }
                                 }
                             }
                             if ($regexMatched) {
                                 break;
                             }
                         }
                     }
                     if (wfConfig::get('scansEnabled_highSense')) {
                         $badStringFound = false;
                         if (strpos($data, $this->patterns['badstrings'][0]) !== false) {
                             for ($i = 1; $i < sizeof($this->patterns['badstrings']); $i++) {
                                 if (strpos($data, $this->patterns['badstrings'][$i]) !== false) {
                                     $badStringFound = $this->patterns['badstrings'][$i];
                                     break;
                                 }
                             }
                         }
                         if ($badStringFound) {
                             if (!$this->isSafeFile($this->path . $file)) {
                                 $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => $fileSum, 'shortMsg' => "This file may contain malicious executable code: " . esc_html($this->path . $file), 'longMsg' => "This file is a PHP executable file and contains the word 'eval' (without quotes) and the word '" . esc_html($badStringFound) . "' (without quotes). The eval() function along with an encoding function like the one mentioned are commonly used by hackers to hide their code. If you know about this file you can choose to ignore it to exclude it from future scans. This file was detected because you have enabled HIGH SENSITIVITY scanning. This option is more aggressive than the usual scans, and may cause false positives.", 'data' => array_merge(array('file' => $file), $dataForFile)));
                                 break;
                             }
                         }
                     }
                     if (!$dontScanForURLs) {
                         $this->urlHoover->hoover($file, $data);
                     }
                 } else {
                     if (!$dontScanForURLs) {
                         $this->urlHoover->hoover($file, $data);
                     }
                 }
                 if ($totalRead > 2 * 1024 * 1024) {
                     break;
                 }
             }
             fclose($fh);
             $this->totalFilesScanned++;
             if (microtime(true) - $this->lastStatusTime > 1) {
                 $this->lastStatusTime = microtime(true);
                 $this->writeScanningStatus();
             }
             $forkObj->forkIfNeeded();
         }
     }
     $this->writeScanningStatus();
     wordfence::status(2, 'info', "Asking Wordfence to check URL's against malware list.");
     $hooverResults = $this->urlHoover->getBaddies();
     if ($this->urlHoover->errorMsg) {
         $this->errorMsg = $this->urlHoover->errorMsg;
         return false;
     }
     $this->urlHoover->cleanup();
     $siteURL = get_site_url();
     $siteHost = parse_url($siteURL, PHP_URL_HOST);
     foreach ($hooverResults as $file => $hresults) {
         $dataForFile = $this->dataForFile($file, $this->path . $file);
         foreach ($hresults as $result) {
             if (preg_match('/wfBrowscapCache\\.php$/', $file)) {
                 continue;
             }
             if (empty($result['URL'])) {
                 continue;
             }
             $url = $result['URL'];
             $urlHost = parse_url($url, PHP_URL_HOST);
             if (strcasecmp($siteHost, $urlHost) === 0) {
                 continue;
             }
             if ($result['badList'] == 'goog-malware-shavar') {
                 if (!$this->isSafeFile($this->path . $file)) {
                     $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => md5_file($this->path . $file), 'shortMsg' => "File contains suspected malware URL: " . esc_html($this->path . $file), 'longMsg' => "This file contains a suspected malware URL listed on Google's list of malware sites. Wordfence decodes " . esc_html($this->patterns['word3']) . " when scanning files so the URL may not be visible if you view this file. The URL is: " . esc_html($result['URL']) . " - More info available at <a href=\"http://safebrowsing.clients.google.com/safebrowsing/diagnostic?site=" . urlencode($result['URL']) . "&client=googlechrome&hl=en-US\" target=\"_blank\">Google Safe Browsing diagnostic page</a>.", 'data' => array_merge(array('file' => $file, 'badURL' => $result['URL'], 'gsb' => 'goog-malware-shavar'), $dataForFile)));
                 }
             } else {
                 if ($result['badList'] == 'googpub-phish-shavar') {
                     if (!$this->isSafeFile($this->path . $file)) {
                         $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => md5_file($this->path . $file), 'shortMsg' => "File contains suspected phishing URL: " . esc_html($this->path . $file), 'longMsg' => "This file contains a URL that is a suspected phishing site that is currently listed on Google's list of known phishing sites. The URL is: " . esc_html($result['URL']), 'data' => array_merge(array('file' => $file, 'badURL' => $result['URL'], 'gsb' => 'googpub-phish-shavar'), $dataForFile)));
                     }
                 }
             }
         }
     }
     wfUtils::endProcessingFile();
     return $this->results;
 }
Esempio n. 11
0
 public static function getMaxExecutionTime()
 {
     $config = wfConfig::get('maxExecutionTime');
     wordfence::status(4, 'info', "Got value from wf config maxExecutionTime: {$config}");
     if (is_numeric($config) && $config >= 10) {
         wordfence::status(4, 'info', "getMaxExecutionTime() returning config value: {$config}");
         return $config;
     }
     $ini = @ini_get('max_execution_time');
     wordfence::status(4, 'info', "Got max_execution_time value from ini: {$ini}");
     if (is_numeric($ini) && $ini >= 10) {
         $ini = floor($ini / 2);
         wordfence::status(4, 'info', "getMaxExecutionTime() returning half ini value: {$ini}");
         return $ini;
     }
     wordfence::status(4, 'info', "getMaxExecutionTime() returning default of: 15");
     return 15;
 }
	</div>
	<div class="wordfenceWrap<?php 
if (!wfConfig::get('isPaid')) {
    echo " wordfence-community";
}
?>
">
		<?php 
$rightRail = new wfView('marketing/rightrail', array('additionalClasses' => 'wordfenceRightRailLiveTraffic'));
echo $rightRail;
?>
		<?php 
if (!wfConfig::liveTrafficEnabled()) {
    ?>
			<div id="wordfenceLiveActivityDisabled"><p><strong>Live activity is disabled.</strong> <?php 
    if (wfConfig::get('cacheType') == 'falcon') {
        ?>
This is done to improve performance because you have Wordfence Falcon Engine enabled.<?php 
    }
    ?>
 Login and firewall activity will still appear below.</p></div>
		<?php 
}
?>
		
		<div id="wf-live-traffic" class="wfTabsContainer">

				<div id="wf-live-traffic-legend">
					<ul>
						<li class="wfHuman">Human</li>
						<li class="wfBot">Bot</li>
<div class="wordfenceModeElem" id="wordfenceMode_rangeBlocking"></div>
<div class="wrap" id="paidWrap">
	<?php 
require 'menuHeader.php';
?>
	<?php 
$helpLink = "http://docs.wordfence.com/en/Advanced_Blocking";
$helpLabel = "Learn more about Advanced Blocking";
$pageTitle = "Advanced Blocking";
include 'pageTitle.php';
?>
	<div class="wordfenceWrap" style="margin: 20px 20px 20px 30px;">
		<p>
			<?php 
if (!wfConfig::get('firewallEnabled')) {
    ?>
<div style="color: #F00; font-weight: bold;">Firewall is disabled. You can enable it on the <a href="admin.php?page=WordfenceSecOpt">Wordfence Options page</a> at the top.</div><br /><?php 
}
?>
			<table class="wfConfigForm">
				<tr><th>IP address range:</th><td><input id="ipRange" type="text" size="30" maxlength="255" value="<?php 
if (isset($_GET['wfBlockRange']) && preg_match('/^[\\da-f\\.\\s\\t\\-:]+$/i', $_GET['wfBlockRange'])) {
    echo wp_kses($_GET['wfBlockRange'], array());
}
?>
" onkeyup="WFAD.calcRangeTotal();">&nbsp;<span id="wfShowRangeTotal"></span></td></tr>
				<tr><td></td><td style="padding-bottom: 15px;"><strong>Examples:</strong> 192.168.200.200 - 192.168.200.220</td></tr>
				<tr><th>User-Agent (browser) that matches:</th><td><input id="uaRange" type="text" size="30" maxlength="255" >&nbsp;(Case insensitive)</td></tr>
				<tr><td></td><td style="padding-bottom: 15px;"><strong>Examples:</strong> *badRobot*, AnotherBadRobot*, *someBrowserSuffix</td></tr>
				<tr><th>Referer (website visitor arrived from) that matches:</th><td><input id="wfreferer" type="text" size="30" maxlength="255" >&nbsp;(Case insensitive)</td></tr>
				<tr><td></td><td style="padding-bottom: 15px;"><strong>Examples:</strong> *badWebsite*, AnotherBadWebsite*, *someWebsiteSuffix</td></tr>
Esempio n. 14
0
 /**
  * @param int $userID
  */
 public function removeAdmin($userID)
 {
     $loggedAdmins = $this->getLoggedAdmins();
     if (array_key_exists($userID, $loggedAdmins) && !array_key_exists($userID, $this->getCurrentAdmins())) {
         unset($loggedAdmins[$userID]);
         wfConfig::set_ser('adminUserList', $loggedAdmins);
     }
 }
Esempio n. 15
0
" is available.
			</li>
		<?php 
    }
    ?>
	</ul>
<?php 
}
?>

<?php 
if ($updates_needed['core'] || $updates_needed['plugins'] || $updates_needed['themes']) {
    ?>
	<p><a class="button button-primary" href="<?php 
    echo esc_attr(network_admin_url('update-core.php'));
    ?>
">Update Now</a></p>
<?php 
} else {
    ?>
	<p>No updates are available at this time.</p>
<?php 
}
if (defined('WP_DEBUG') && WP_DEBUG || wfConfig::get('debugOn')) {
    ?>
	<p>Generated in <?php 
    printf('%.4f seconds', $microseconds);
    ?>
</p>
<?php 
}
Esempio n. 16
0
 public function makeAPIQueryString()
 {
     $siteurl = '';
     if (function_exists('get_bloginfo')) {
         if (is_multisite()) {
             $siteurl = network_home_url();
             $siteurl = rtrim($siteurl, '/');
             //Because previously we used get_bloginfo and it returns http://example.com without a '/' char.
         } else {
             $siteurl = home_url();
         }
     }
     return self::buildQuery(array('v' => $this->wordpressVersion, 's' => $siteurl, 'k' => $this->APIKey, 'openssl' => function_exists('openssl_verify') && defined('OPENSSL_VERSION_NUMBER') ? OPENSSL_VERSION_NUMBER : '0.0.0', 'phpv' => phpversion(), 'betaFeed' => (int) wfConfig::get('betaThreatDefenseFeed')));
 }
Esempio n. 17
0
<script type="text/x-jquery-template" id="wfWelcomePasswd">
<div>
	<h3>Premium Feature: Audit your Password Strength</h3>
	<strong><p>Want to know how easily a hacker can crack your passwords?</p></strong>

	<p>
		Wordfence Premium includes password auditing. Using this feature
		we securely test your passwords against a cracking program that hackers use.
		The difference is that we use extremely fast servers in our data center which
		allow us to quickly simulate a complex password cracking attack. We then tell
		you which passwords on your system are weak and help you easily fix the problem.
	</p>

	<p>
		<?php 
if (wfConfig::get('isPaid')) {
    ?>
			You have upgraded to the premium version of Wordfence and have full access
			to this feature along with our other premium features and priority support.
		<?php 
} else {
    ?>
		If you would like access to this premium feature, please
		<a href="https://www.wordfence.com/gnl1pwAuditUp2/wordfence-signup/" target="_blank">upgrade to our premium version</a>.
	</p>
	<?php 
}
?>
</div>
</script>
Esempio n. 18
0
<?php

$w = new wfConfig();
?>
<script type="text/javascript">
	var WFSLevels = <?php 
echo json_encode(wfConfig::$securityLevels);
?>
;
</script>
<div class="wordfenceModeElem" id="wordfenceMode_options"></div>
<div class="wrap">
	<?php 
require 'menuHeader.php';
?>
	<?php 
$helpLink = "http://docs.wordfence.com/en/Wordfence_options";
$helpLabel = "Learn more about Wordfence Options";
$pageTitle = "Wordfence Options";
include 'pageTitle.php';
?>
	<div class="wordfenceLive">
		<table border="0" cellpadding="0" cellspacing="0">
			<tr>
				<td><h2>Wordfence Live Activity:</h2></td>
				<td id="wfLiveStatus"></td>
			</tr>
		</table>
	</div>

	<form id="wfConfigForm">
Esempio n. 19
0
 /**
  *
  */
 public static function processAttackData()
 {
     global $wpdb;
     $waf = wfWAF::getInstance();
     if ($waf->getStorageEngine()->getConfig('attackDataKey', false) === false) {
         $waf->getStorageEngine()->setConfig('attackDataKey', mt_rand(0, 0xfff));
     }
     $limit = 500;
     $lastSendTime = wfConfig::get('lastAttackDataSendTime');
     $attackData = $wpdb->get_results($wpdb->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM {$wpdb->base_prefix}wfHits\nWHERE action in ('blocked:waf', 'learned:waf')\nAND attackLogTime > %.6f\nLIMIT %d", $lastSendTime, $limit));
     $totalRows = $wpdb->get_var('SELECT FOUND_ROWS()');
     if ($attackData) {
         $response = wp_remote_get(sprintf(WFWAF_API_URL_SEC . "waf-rules/%d.txt", $waf->getStorageEngine()->getConfig('attackDataKey')));
         if (!is_wp_error($response)) {
             $okToSendBody = wp_remote_retrieve_body($response);
             if ($okToSendBody === 'ok') {
                 // Build JSON to send
                 $dataToSend = array();
                 $attackDataToUpdate = array();
                 foreach ($attackData as $attackDataRow) {
                     $actionData = (array) wfRequestModel::unserializeActionData($attackDataRow->actionData);
                     $dataToSend[] = array($attackDataRow->attackLogTime, $attackDataRow->ctime, wfUtils::inet_ntop($attackDataRow->IP), array_key_exists('learningMode', $actionData) ? $actionData['learningMode'] : 0, array_key_exists('paramKey', $actionData) ? base64_encode($actionData['paramKey']) : false, array_key_exists('paramValue', $actionData) ? base64_encode($actionData['paramValue']) : false, array_key_exists('failedRules', $actionData) ? $actionData['failedRules'] : '', strpos($attackDataRow->URL, 'https') === 0 ? 1 : 0, array_key_exists('fullRequest', $actionData) ? $actionData['fullRequest'] : '');
                     if (array_key_exists('fullRequest', $actionData)) {
                         unset($actionData['fullRequest']);
                         $attackDataToUpdate[$attackDataRow->id] = array('actionData' => wfRequestModel::serializeActionData($actionData));
                     }
                     if ($attackDataRow->attackLogTime > $lastSendTime) {
                         $lastSendTime = $attackDataRow->attackLogTime;
                     }
                 }
                 $response = wp_remote_post(WFWAF_API_URL_SEC . "?" . http_build_query(array('action' => 'send_waf_attack_data', 'k' => $waf->getStorageEngine()->getConfig('apiKey'), 's' => $waf->getStorageEngine()->getConfig('siteURL') ? $waf->getStorageEngine()->getConfig('siteURL') : sprintf('%s://%s/', $waf->getRequest()->getProtocol(), rawurlencode($waf->getRequest()->getHost())))), array('body' => json_encode($dataToSend), 'headers' => array('Content-Type' => 'application/json'), 'timeout' => 30));
                 if (!is_wp_error($response) && ($body = wp_remote_retrieve_body($response))) {
                     $jsonData = json_decode($body, true);
                     if (is_array($jsonData) && array_key_exists('success', $jsonData)) {
                         // Successfully sent data, remove the full request from the table to reduce storage size
                         foreach ($attackDataToUpdate as $hitID => $dataToUpdate) {
                             $wpdb->update($wpdb->base_prefix . 'wfHits', $dataToUpdate, array('id' => $hitID));
                         }
                         wfConfig::set('lastAttackDataSendTime', $lastSendTime);
                         if ($totalRows > $limit) {
                             self::scheduleSendAttackData();
                         }
                     }
                 }
             } else {
                 if (is_string($okToSendBody) && preg_match('/next check in: ([0-9]+)/', $okToSendBody, $matches)) {
                     self::scheduleSendAttackData(time() + $matches[1]);
                 }
             }
             // Could be that the server is down, so hold off on sending data for a little while.
         } else {
             self::scheduleSendAttackData(time() + 7200);
         }
     }
     self::trimWfHits();
 }
Esempio n. 20
0
 public function __construct()
 {
     $this->api = new wfAPI(wfConfig::get('apiKey'), wfUtils::getWPVersion());
 }
Esempio n. 21
0
}
</style>

<div class="wrap">
	<?php 
require 'menuHeader.php';
?>
	<div class="wordfence-lock-icon wordfence-icon32"><br /></div>
	<h2 id="wfHeading">
		<div style="float: left;">
			Your Site Performance in Real-Time
		</div>
		<div class="wordfenceWrap" style="margin: 5px 0 0 15px; float: left;">
			<div class="wfOnOffSwitch" id="wfOnOffSwitchID">
				<input type="checkbox" name="wfOnOffSwitch" class="wfOnOffSwitch-checkbox" id="wfPerfOnOff" <?php 
if (wfConfig::get('perfLoggingEnabled')) {
    echo ' checked ';
}
?>
>
				<label class="wfOnOffSwitch-label" for="wfPerfOnOff">
					<div class="wfOnOffSwitch-inner"></div>
					<div class="wfOnOffSwitch-switch"></div>
				</label>
			</div>
		</div>
	</h2>
	<br clear="left" />
	<div style="margin: 20px; width: 1100px;">
		<div class="wfPerfItem wfPerfKey wfPerfKeyHead">Network &amp; Server Performance Key:</div>
		<div class="wfPerfItem wfPerfKey" style="background-color: #fdff47;">Time taken for DNS lookup</div>
 public static function autoUpdate()
 {
     try {
         if (getenv('noabort') != '1' && stristr($_SERVER['SERVER_SOFTWARE'], 'litespeed') !== false) {
             $lastEmail = self::get('lastLiteSpdEmail', false);
             if (!$lastEmail || time() - (int) $lastEmail > 86400 * 30) {
                 self::set('lastLiteSpdEmail', time());
                 wordfence::alert("Wordfence Upgrade not run. Please modify your .htaccess", "To preserve the integrity of your website we are not running Wordfence auto-update.\n" . "You are running the LiteSpeed web server which has been known to cause a problem with Wordfence auto-update.\n" . "Please go to your website now and make a minor change to your .htaccess to fix this.\n" . "You can find out how to make this change at:\n" . "https://support.wordfence.com/solution/articles/1000129050-running-wordfence-under-litespeed-web-server-and-preventing-process-killing-or\n" . "\nAlternatively you can disable auto-update on your website to stop receiving this message and upgrade Wordfence manually.\n", '127.0.0.1');
             }
             return;
         }
         require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
         require_once ABSPATH . 'wp-admin/includes/misc.php';
         /* We were creating show_message here so that WP did not write to STDOUT. This had the strange effect of throwing an error about redeclaring show_message function, but only when a crawler hit the site and triggered the cron job. Not a human. So we're now just require'ing misc.php which does generate output, but that's OK because it is a loopback cron request.  
         			if(! function_exists('show_message')){ 
         				function show_message($msg = 'null'){}
         			}
         			*/
         define('FS_METHOD', 'direct');
         require_once ABSPATH . 'wp-includes/update.php';
         require_once ABSPATH . 'wp-admin/includes/file.php';
         wp_update_plugins();
         ob_start();
         $upgrader = new Plugin_Upgrader();
         $upret = $upgrader->upgrade('wordfence/wordfence.php');
         if ($upret) {
             $cont = file_get_contents(WP_PLUGIN_DIR . '/wordfence/wordfence.php');
             if (wfConfig::get('alertOn_update') == '1' && preg_match('/Version: (\\d+\\.\\d+\\.\\d+)/', $cont, $matches)) {
                 wordfence::alert("Wordfence Upgraded to version " . $matches[1], "Your Wordfence installation has been upgraded to version " . $matches[1], '127.0.0.1');
             }
         }
         $output = @ob_get_contents();
         @ob_end_clean();
     } catch (Exception $e) {
     }
 }
    if (wfConfig::get('scansEnabled_highSense')) {
        ?>
<tr><td style="padding-right: 20px;">High sensitivity scans enabled:</td><td style="color: #0F0;">&#10004;</td></tr> <?php 
    }
    if (wfConfig::get('scansEnabled_scanImages')) {
        ?>
<tr><td style="padding-right: 20px;">Scan image files for executable code:</td><td style="color: #0F0;">&#10004;</td></tr> <?php 
    }
    if (wfConfig::get('other_scanOutside')) {
        ?>
<tr><td style="padding-right: 20px;">Scan files outside WordPress install:</td><td style="color: #0F0;">&#10004;</td></tr> <?php 
    }
    if (wfConfig::get('scansEnabled_dns')) {
        ?>
<tr><td style="padding-right: 20px;">Scan for DNS changes:</td><td style="color: #0F0;">&#10004;</td></tr> <?php 
    }
    if (wfConfig::get('scansEnabled_diskSpace')) {
        ?>
<tr><td style="padding-right: 20px;">Monitor disk space:</td><td style="color: #0F0;">&#10004;</td></tr> <?php 
    }
}
if (wfConfig::get('debugOn')) {
    ?>
<tr><td style="padding-right: 20px;">Wordfence DEBUG mode enabled:</td><td style="color: #F00;">DEBUG ENABLED</td></tr> <?php 
}
?>


</table>

 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;
     }
 }
Esempio n. 25
0
 /**
  * @param string $directory
  * @param int    $max_files_per_directory
  * @param int    $max_iterations
  * @param int    $time_range
  */
 public function __construct($directory = ABSPATH, $max_files_per_directory = 20000, $max_iterations = 250000, $time_range = 604800)
 {
     parent::__construct($directory, $max_files_per_directory, $max_iterations);
     $this->time_range = $time_range;
     $excluded_directories = explode(',', (string) wfConfig::get('email_summary_excluded_directories'));
     $this->excluded_directories = array();
     foreach ($excluded_directories as $index => $path) {
         if (($dir = realpath(ABSPATH . $path)) !== false) {
             $this->excluded_directories[$dir] = 1;
         }
     }
 }
Esempio n. 26
0
<?php

$w = new wfConfig();
?>
<div class="wordfenceModeElem" id="wordfenceMode_caching"></div>
<div class="wrap">
	<?php 
require 'menuHeader.php';
?>
	<?php 
$pageTitle = "Your Site Performance";
$helpLink = "http://docs.wordfence.com/en/Falcon_Cache";
$helpLabel = "Learn more about Wordfence Caching";
include 'pageTitle.php';
?>
	<div class="wordfenceWrap" style="margin: 20px 20px 20px 30px;">
		<h2>Caching</h2>
		<table border="0">
		<tr><td>Disable all performance enhancements:</td><td><input type="radio" name="cacheType" id="cacheType_disable" value="disable" <?php 
if (!wfConfig::get('cacheType')) {
    echo 'checked="checked"';
}
?>
 /></td><td>No performance improvement</td></tr>
		<tr><td>Enable Basic Caching:</td><td><input type="radio" name="cacheType" id="cacheType_php" value="php" <?php 
if (wfConfig::get('cacheType') == 'php') {
    echo 'checked="checked"';
}
?>
 /></td><td>2 to 3 Times speed increase</td></tr>
		<tr><td>Enable Wordfence Falcon Engine:<div class="wfSmallFalcon"></div></td><td><input type="radio" name="cacheType" id="cacheType_falcon" value="falcon" <?php 
Esempio n. 27
0
 /**
  * Checks if WordFence protects the site against 'fake' Google crawlers.
  *
  * @return boolean
  */
 private function wordfence_protection_enabled()
 {
     if (!class_exists('wfConfig')) {
         return false;
     }
     if (!method_exists('wfConfig', 'get')) {
         return false;
     }
     return (bool) wfConfig::get('blockFakeBots');
 }
Esempio n. 28
0
 /**
  * @param string $striplen
  * @param string $path
  * @param array $only
  * @param array $themes
  * @param array $plugins
  * @param wfScanEngine $engine
  * @throws Exception
  */
 public function __construct($striplen, $path, $only, $themes, $plugins, $engine)
 {
     $this->striplen = $striplen;
     $this->path = $path;
     $this->only = $only;
     $this->startTime = microtime(true);
     if (wfConfig::get('scansEnabled_core')) {
         $this->coreEnabled = true;
     }
     if (wfConfig::get('scansEnabled_plugins')) {
         $this->pluginsEnabled = true;
     }
     if (wfConfig::get('scansEnabled_themes')) {
         $this->themesEnabled = true;
     }
     if (wfConfig::get('scansEnabled_malware')) {
         $this->malwareEnabled = true;
     }
     $this->db = new wfDB();
     //Doing a delete for now. Later we can optimize this to only scan modified files.
     //$this->db->queryWrite("update " . $this->db->prefix() . "wfFileMods set oldMD5 = newMD5");
     $this->db->queryWrite("delete from " . $this->db->prefix() . "wfFileMods");
     $fetchCoreHashesStatus = wordfence::statusStart("Fetching core, theme and plugin file signatures from Wordfence");
     $dataArr = $engine->api->binCall('get_known_files', json_encode(array('plugins' => $plugins, 'themes' => $themes)));
     if ($dataArr['code'] != 200) {
         wordfence::statusEndErr();
         throw new Exception("Got error response from Wordfence servers: " . $dataArr['code']);
     }
     $this->knownFiles = @json_decode($dataArr['data'], true);
     if (!is_array($this->knownFiles)) {
         wordfence::statusEndErr();
         throw new Exception("Invalid response from Wordfence servers.");
     }
     wordfence::statusEnd($fetchCoreHashesStatus, false, true);
     if ($this->malwareEnabled) {
         $malwarePrefixStatus = wordfence::statusStart("Fetching list of known malware files from Wordfence");
         $malwareData = $engine->api->getStaticURL('/malwarePrefixes.bin');
         if (!$malwareData) {
             wordfence::statusEndErr();
             throw new Exception("Could not fetch malware signatures from Wordfence servers.");
         }
         if (strlen($malwareData) % 4 != 0) {
             wordfence::statusEndErr();
             throw new Exception("Malware data received from Wordfence servers was not valid.");
         }
         $this->malwareData = array();
         for ($i = 0; $i < strlen($malwareData); $i += 4) {
             $this->malwareData[substr($malwareData, $i, 4)] = '1';
         }
         wordfence::statusEnd($malwarePrefixStatus, false, true);
     }
     if ($this->path[strlen($this->path) - 1] != '/') {
         $this->path .= '/';
     }
     if (!is_readable($path)) {
         throw new Exception("Could not read directory " . $this->path . " to do scan.");
     }
     $this->haveIssues = array('core' => false, 'themes' => false, 'plugins' => false, 'malware' => false);
     if ($this->coreEnabled) {
         $this->status['core'] = wordfence::statusStart("Comparing core WordPress files against originals in repository");
     } else {
         wordfence::statusDisabled("Skipping core scan");
     }
     if ($this->themesEnabled) {
         $this->status['themes'] = wordfence::statusStart("Comparing open source themes against WordPress.org originals");
     } else {
         wordfence::statusDisabled("Skipping theme scan");
     }
     if ($this->pluginsEnabled) {
         $this->status['plugins'] = wordfence::statusStart("Comparing plugins against WordPress.org originals");
     } else {
         wordfence::statusDisabled("Skipping plugin scan");
     }
     if ($this->malwareEnabled) {
         $this->status['malware'] = wordfence::statusStart("Scanning for known malware files");
     } else {
         wordfence::statusDisabled("Skipping malware scan");
     }
 }
 public function downgrade_license()
 {
     $api = new wfAPI('', wfUtils::getWPVersion());
     $return = array();
     try {
         $keyData = $api->call('get_anon_api_key');
         if ($keyData['ok'] && $keyData['apiKey']) {
             wfConfig::set('apiKey', $keyData['apiKey']);
             wfConfig::set('isPaid', 0);
             $return['apiKey'] = $keyData['apiKey'];
             $return['isPaid'] = 0;
             //When downgrading we must disable all two factor authentication because it can lock an admin out if we don't.
             wfConfig::set_ser('twoFactorUsers', array());
         } else {
             throw new Exception('Could not understand the response we received from the Wordfence servers when applying for a free API key.');
         }
     } catch (Exception $e) {
         $return['errorMsg'] = 'Could not fetch free API key from Wordfence: ' . htmlentities($e->getMessage());
         return $return;
     }
     $return['ok'] = 1;
     return $return;
 }
Esempio n. 30
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
 }