Esempio n. 1
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;
 }
 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;
     }
 }
Esempio n. 3
0
?>
 />(Try
						this if your options aren't saving)
					</td>
				</tr>
				<tr>
					<th>Add a debugging comment to HTML source of cached pages.<a
							href="http://docs.wordfence.com/en/Wordfence_options#Add_a_debugging_comment_to_HTML_source_of_cached_pages"
							target="_blank" class="wfhelp"></a></th>
					<td><input type="checkbox" id="addCacheComment" class="wfConfigElem" name="addCacheComment"
					           value="1" <?php 
$w->cb('addCacheComment');
?>
 />
						<?php 
if ($w->get('allowHTTPSCaching')) {
    ?>
							<input type="hidden" name="allowHTTPSCaching" value="1"/>
						<?php 
}
?>
					</td>
				</tr>
				<tr>
					<th><label for="disableCodeExecutionUploads">Disable Code Execution for Uploads directory</label><a
							href="http://docs.wordfence.com/en/Wordfence_options#Disable_Code_Execution_for_Uploads_directory"
							target="_blank" class="wfhelp"></a></th>
					<td><input type="checkbox" id="disableCodeExecutionUploads" class="wfConfigElem"
					           name="disableCodeExecutionUploads"
					           value="1" <?php 
$w->cb('disableCodeExecutionUploads');
Esempio n. 4
0
if ($fileList) {
    ?>
<p style="width: 700px; margin-top: 20px;">
	<b>Please note:</b> To use this utility, you must enable scanning of Core, Theme and Plugin files on the Wordfence options page. 
	<?php 
    if (!wfConfig::get('scansEnabled_themes')) {
        echo '<span style="color: #F00;">Theme scanning is currently disabled.</span> ';
    }
    ?>
	<?php 
    if (!wfConfig::get('scansEnabled_plugins')) {
        echo '<span style="color: #F00;">Plugin scanning is currently disabled.</span> ';
    }
    ?>
	<?php 
    if (!wfConfig::get('scansEnabled_plugins') || !wfConfig::get('scansEnabled_themes')) {
        echo 'You can visit the Wordfence "options" page to enable theme or plugin scanning.';
    }
    ?>

	If you don't have core, theme and plugin scanning enabled, then the list below will not be very useful because Wordfence won't recognize known core, theme and plugin files. 
	If you have the option enabled to "Scan files outside your WordPress installation" enabled, then you may find that this list is very long because it will include files in all your directories.
	<br /><br />
	<b>What is in this list:</b>
	When Wordfence does a scan, it separates files on your system into two lists. The first list is files that belong to WordPress Core or a known theme or plugin. The second list is all other files. 
	<br /><br />
	If a <b>file belongs to WordPress Core or a known theme or plugin</b>, we do an integrity check and let you know if it has been modified.
	The integrity check we do on known Core, theme and plugin files is a very reliable way to detect compromised files. It is impossible as far as we know for a hacker to fool this scan
	because we are comparing your files to known originals on our secure scanning servers. If the file is modified, we let you know with a warning or critical alert in the scan results. 
	<br /><br />
	If the file <b>does not belong to WordPress Core or a known theme or plugin</b>, we scan it for security problems. 
Esempio n. 5
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. 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;
 }
				</tr>
				</tbody>
			<?php 
}
?>

			<tbody class="thead">
			<tr>
				<th>IPs</th>
				<th>Value</th>
				<th>Used</th>
			</tr>
			</tbody>
			<tbody>
			<?php 
$howGet = wfConfig::get('howGetIPs', false);
list($currentIP, $currentServerVarForIP) = wfUtils::getIPAndServerVarible();
foreach (array('REMOTE_ADDR' => 'REMOTE_ADDR', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For') as $variable => $label) {
    ?>
				<tr>
					<td><?php 
    echo $label;
    ?>
</td>
					<td><?php 
    echo esc_html(array_key_exists($variable, $_SERVER) ? $_SERVER[$variable] : '(not set)');
    ?>
</td>
					<?php 
    if ($currentServerVarForIP && $currentServerVarForIP === $variable) {
        ?>
				</tr>
				<tr>
					<td colspan="2">
						<div class="wfMarker" id="wfMarkerOtherOptions"></div>
						<h3 class="wfConfigHeading">Other Options<a
								href="http://docs.wordfence.com/en/Wordfence_options#Other_Options" target="_blank"
								class="wfhelp"></a></h3>
					</td>
				</tr>

				<tr>
					<th style="vertical-align: top;">Whitelisted IP addresses that bypass all rules:<a
							href="http://docs.wordfence.com/en/Wordfence_options#Whitelisted_IP_addresses_that_bypass_all_rules"
							target="_blank" class="wfhelp"></a></th>
					<td><textarea name="whitelisted" id="whitelisted" cols="40" rows="4"><?php 
echo esc_html(preg_replace('/,/', "\n", $w->get('whitelisted')));
?>
</textarea></td>
				</tr>
				<tr>
					<th colspan="2" style="color: #999;">Whitelisted IPs must be separated by commas or placed on separate lines. You can specify
						ranges using the following format: 123.23.34.[1-50]<br/>Wordfence automatically whitelists <a
							href="http://en.wikipedia.org/wiki/Private_network" target="_blank">private networks</a>
						because these are not routable on the public Internet.<br/><br/></th>
				</tr>

				<tr>
					<th style="vertical-align: top;">Immediately block IPs that access these URLs:<a
							href="http://docs.wordfence.com/en/Wordfence_options#Immediately_block_IP.27s_that_access_these_URLs"
							target="_blank" class="wfhelp"></a></th>
					<td><textarea type="text" name="bannedURLs" id="bannedURLs" cols="40" rows="4"><?php 
 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;
 }
Esempio n. 10
0
					<th>Amount of Live Traffic data to store (number of rows):</th>
					<td><input type="text" name="liveTraf_maxRows" id="liveTraf_maxRows"
					           value="<?php 
$w->f('liveTraf_maxRows');
?>
"/></td>
				</tr>
				<tr>
					<td colspan="2">
						<div class="wfMarker" id="wfMarkerScansToInclude"></div>
						<h3 class="wfConfigHeading">Scans to include<a
								href="http://docs.wordfence.com/en/Wordfence_options#Scans_to_Include" target="_blank"
								class="wfhelp"></a></h3></td>
				</tr>
				<?php 
if (wfConfig::get('isPaid')) {
    ?>
					<tr>
						<th>Scan public facing site for vulnerabilities?<a
								href="http://docs.wordfence.com/en/Wordfence_options#Scan_public_facing_site"
								target="_blank" class="wfhelp"></a></th>
						<td><input type="checkbox" id="scansEnabled_public" class="wfConfigElem"
						           name="scansEnabled_public" value="1" <?php 
    $w->cb('scansEnabled_public');
    ?>
 /></td>
					</tr>
				<?php 
} else {
    ?>
					<tr>
Esempio n. 11
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. 12
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;
 }
Esempio n. 13
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;
 }
<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. 15
0
 public function isEnabled()
 {
     $enabled = wfConfig::get('scansEnabled_suspiciousAdminUsers');
     if ($enabled && is_multisite()) {
         if (!function_exists('wp_is_large_network')) {
             require_once ABSPATH . WPINC . '/ms-functions.php';
         }
         $enabled = !wp_is_large_network('sites') && !wp_is_large_network('users');
     }
     return $enabled;
 }
Esempio n. 16
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 
}
<link rel='stylesheet' id='wordfence-main-style-css'  href='<?php 
echo wfUtils::getBaseURL();
?>
/css/fullLog.css?ver=<?php 
echo WORDFENCE_VERSION;
?>
' type='text/css' media='all' />
<style type="text/css">

</style>
<body>
<h1>Wordfence Full Activity Log</h1>
<?php 
$db = new wfDB();
global $wpdb;
$debugOn = wfConfig::get('debugOn', 0);
$table = $wpdb->base_prefix . 'wfStatus';
$offset = 0;
$timeOffset = 3600 * get_option('gmt_offset');
$q = $db->querySelect("SELECT ctime, level, type, msg FROM {$table} ORDER BY ctime DESC LIMIT %d, 100", $offset);
while (is_array($q) && count($q) > 0) {
    foreach ($q as $r) {
        if ($r['level'] < 4 || $debugOn) {
            echo '<div' . ($r['type'] == 'error' ? ' class="error"' : '') . '>[' . date('M d H:i:s', $r['ctime'] + $timeOffset) . ':' . $r['ctime'] . ':' . $r['level'] . ':' . $r['type'] . ']&nbsp;' . esc_html($r['msg']) . "</div>\n";
        }
    }
    $offset += count($q);
    $q = $db->querySelect("SELECT ctime, level, type, msg FROM {$table} ORDER BY ctime DESC LIMIT %d, 100", $offset);
}
?>
</body>
Esempio n. 18
0
 /**
  * @param $action
  * @return bool|string|void
  */
 public static function updateBlockedIPs($action)
 {
     //'add' or 'remove'
     if (wfConfig::get('cacheType') != 'falcon') {
         return;
     }
     $htaccessPath = self::getHtaccessPath();
     if (!$htaccessPath) {
         return "Wordfence could not find your .htaccess file.";
     }
     if ($action == 'remove') {
         $fh = @fopen($htaccessPath, 'r+');
         if (!$fh) {
             $err = error_get_last();
             return $err['message'];
         }
         flock($fh, LOCK_EX);
         fseek($fh, 0, SEEK_SET);
         //start of file
         clearstatcache();
         $contents = @fread($fh, filesize($htaccessPath));
         if (!$contents) {
             fclose($fh);
             return "Could not read from {$htaccessPath}";
         }
         $contents = preg_replace('/#WFIPBLOCKS.*WFIPBLOCKS[r\\s\\n\\t]*/s', '', $contents);
         ftruncate($fh, 0);
         fseek($fh, 0, SEEK_SET);
         @fwrite($fh, $contents);
         flock($fh, LOCK_UN);
         fclose($fh);
         return false;
     } else {
         if ($action == 'add') {
             $fh = @fopen($htaccessPath, 'r+');
             if (!$fh) {
                 $err = error_get_last();
                 return $err['message'];
             }
             $lines = array();
             $wfLog = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
             $IPs = $wfLog->getBlockedIPsAddrOnly();
             if (sizeof($IPs) > 0) {
                 foreach ($IPs as $IP) {
                     $lines[] = "Deny from {$IP}\n";
                 }
             }
             $ranges = $wfLog->getRangesBasic();
             $browserAdded = false;
             $browserLines = array();
             if ($ranges) {
                 foreach ($ranges as $r) {
                     $arr = explode('|', $r);
                     $range = isset($arr[0]) ? $arr[0] : false;
                     $browser = isset($arr[1]) ? $arr[1] : false;
                     $referer = isset($arr[2]) ? $arr[2] : false;
                     if ($range) {
                         if ($browser || $referer) {
                             continue;
                         }
                         //We don't allow combos in falcon
                         list($start_range, $end_range) = explode('-', $range);
                         if (preg_match('/[\\.:]/', $start_range)) {
                             $start_range = wfUtils::inet_pton($start_range);
                             $end_range = wfUtils::inet_pton($end_range);
                         } else {
                             $start_range = wfUtils::inet_pton(long2ip($start_range));
                             $end_range = wfUtils::inet_pton(long2ip($end_range));
                         }
                         $cidrs = wfUtils::rangeToCIDRs($start_range, $end_range);
                         $hIPs = wfUtils::inet_ntop($start_range) . ' - ' . wfUtils::inet_ntop($end_range);
                         if (sizeof($cidrs) > 0) {
                             $lines[] = '#Start of blocking code for IP range: ' . $hIPs . "\n";
                             foreach ($cidrs as $c) {
                                 $lines[] = "Deny from {$c}\n";
                             }
                             $lines[] = '#End of blocking code for IP range: ' . $hIPs . "\n";
                         }
                     } else {
                         if ($browser) {
                             if ($range || $referer) {
                                 continue;
                             }
                             $browserLines[] = "\t#Blocking code for browser pattern: {$browser}\n";
                             $browser = preg_replace('/([\\-\\_\\.\\+\\!\\@\\#\\$\\%\\^\\&\\(\\)\\[\\]\\{\\}\\/])/', "\\\\\$1", $browser);
                             $browser = preg_replace('/\\*/', '.*', $browser);
                             $browserLines[] = "\tSetEnvIf User-Agent " . $browser . " WordfenceBadBrowser=1\n";
                             $browserAdded = true;
                         } else {
                             if ($referer) {
                                 if ($browser || $range) {
                                     continue;
                                 }
                                 $browserLines[] = "\t#Blocking code for referer pattern: {$referer}\n";
                                 $referer = preg_replace('/([\\-\\_\\.\\+\\!\\@\\#\\$\\%\\^\\&\\(\\)\\[\\]\\{\\}\\/])/', "\\\\\$1", $referer);
                                 $referer = preg_replace('/\\*/', '.*', $referer);
                                 $browserLines[] = "\tSetEnvIf Referer " . $referer . " WordfenceBadBrowser=1\n";
                                 $browserAdded = true;
                             }
                         }
                     }
                 }
             }
             if ($browserAdded) {
                 $lines[] = "<IfModule mod_setenvif.c>\n";
                 foreach ($browserLines as $l) {
                     $lines[] = $l;
                 }
                 $lines[] = "\tDeny from env=WordfenceBadBrowser\n";
                 $lines[] = "</IfModule>\n";
             }
         }
     }
     $blockCode = "#WFIPBLOCKS - Do not remove this line. Disable Web Caching in Wordfence to remove this data.\nOrder Deny,Allow\n";
     $blockCode .= implode('', $lines);
     $blockCode .= "#Do not remove this line. Disable Web Caching in Wordfence to remove this data - WFIPBLOCKS\n";
     //Minimize time between lock/unlock
     flock($fh, LOCK_EX);
     fseek($fh, 0, SEEK_SET);
     //start of file
     clearstatcache();
     //Or we get the wrong size from a cached entry and corrupt the file
     $contents = @fread($fh, filesize($htaccessPath));
     if (!$contents) {
         fclose($fh);
         return "Could not read from {$htaccessPath}";
     }
     $contents = preg_replace('/#WFIPBLOCKS.*WFIPBLOCKS[r\\s\\n\\t]*/s', '', $contents);
     $contents = $blockCode . $contents;
     ftruncate($fh, 0);
     fseek($fh, 0, SEEK_SET);
     @fwrite($fh, $contents);
     flock($fh, LOCK_UN);
     fclose($fh);
     return false;
 }
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
		<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 
if (wfConfig::get('cacheType') == 'falcon') {
    echo 'checked="checked"';
}
?>
 /></td><td>30 to 50 Times speed increase</td></tr>
		</table>
		<br />
		<input type="button" id="button1" name="button1" class="button-primary" value="Save Changes to the type of caching enabled above" onclick="WFAD.saveCacheConfig();" />
		<h2>Cache Options</h2>
		<table border="0">
		<tr><td>Allow SSL (secure HTTPS pages) to be cached:</td><td><input type="checkbox" id="wfallowHTTPSCaching" value="1" <?php 
$w->cb('allowHTTPSCaching');
?>
 />We recommend you leave this disabled unless your<br />site uses HTTPS but does not receive/send sensitive user info.</td></tr>
		<tr><td>Add hidden debugging data to the bottom of the HTML source of cached pages:</td><td><input type="checkbox" id="wfaddCacheComment" value="1" <?php 
$w->cb('addCacheComment');
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");
     }
 }
 function block_ip()
 {
     $IP = trim($_POST['IP']);
     $perm = $_POST['perm'] == '1' ? true : false;
     if (!preg_match('/^\\d+\\.\\d+\\.\\d+\\.\\d+$/', $IP)) {
         return array('err' => 1, 'errorMsg' => 'Please enter a valid IP address to block.');
     }
     if (wfUtils::getIP() === $IP) {
         return array('err' => 1, 'errorMsg' => "You can't block your own IP address.");
     }
     if (self::getLog()->isWhitelisted($IP)) {
         return array('err' => 1, 'errorMsg' => 'The IP address ' . htmlentities($IP) . " is whitelisted and can't be blocked or it is in a range of internal IP addresses that Wordfence does not block. You can remove this IP from the whitelist on the Wordfence options page.");
     }
     if (wfConfig::get('neverBlockBG') !== 'treatAsOtherCrawlers') {
         //Either neverBlockVerified or neverBlockUA is selected which means the user doesn't want to block google
         if (wfCrawl::verifyCrawlerPTR('/googlebot\\.com$/i', $IP)) {
             return array('err' => 1, 'errorMsg' => "The IP address you're trying to block belongs to Google. Your options are currently set to not block these crawlers. Change this in Wordfence options if you want to manually block Google.");
         }
     }
     self::getLog()->blockIP($IP, $_POST['reason'], false, $perm);
     return array('ok' => 1);
 }
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
 }