/**
  * Check if any plugins need an update.
  *
  * @return $this
  */
 public function checkPluginUpdates()
 {
     $this->plugin_updates = array();
     if (!function_exists('wp_update_plugins')) {
         require_once ABSPATH . WPINC . '/update.php';
     }
     if (!function_exists('plugins_api')) {
         require_once ABSPATH . '/wp-admin/includes/plugin-install.php';
     }
     wp_update_plugins();
     // Check for Plugin updates
     $update_plugins = get_site_transient('update_plugins');
     if ($update_plugins && !empty($update_plugins->response)) {
         foreach ($update_plugins->response as $plugin => $vals) {
             if (!function_exists('get_plugin_data')) {
                 require_once ABSPATH . '/wp-admin/includes/plugin.php';
             }
             $pluginFile = wfUtils::getPluginBaseDir() . $plugin;
             $data = get_plugin_data($pluginFile);
             $data['pluginFile'] = $pluginFile;
             $data['newVersion'] = $vals->new_version;
             $data['slug'] = $vals->slug;
             $data['wpURL'] = rtrim($vals->url, '/');
             //Check the vulnerability database
             $result = $this->api->call('plugin_vulnerability_check', array(), array('slug' => $vals->slug, 'fromVersion' => $data['Version'], 'toVersion' => $vals->new_version));
             $data['vulnerabilityPatched'] = isset($result['vulnerable']) && $result['vulnerable'];
             $this->plugin_updates[] = $data;
         }
     }
     return $this;
 }
Пример #2
0
 public static function setDefaults()
 {
     foreach (self::$defaultConfig['checkboxes'] as $key => $config) {
         $val = $config['value'];
         $autoload = $config['autoload'];
         if (self::get($key) === false) {
             self::set($key, $val ? '1' : '0', $autoload);
         }
     }
     foreach (self::$defaultConfig['otherParams'] as $key => $val) {
         if (self::get($key) === false) {
             self::set($key, $val);
         }
     }
     self::set('encKey', substr(wfUtils::bigRandomHex(), 0, 16));
     if (self::get('maxMem', false) === false) {
         self::set('maxMem', '256');
     }
     if (self::get('other_scanOutside', false) === false) {
         self::set('other_scanOutside', 0);
     }
     if (self::get('email_summary_enabled')) {
         wfActivityReport::scheduleCronJob();
     } else {
         wfActivityReport::disableCronJob();
     }
 }
Пример #3
0
function doCurlTest($protocol)
{
    if (!function_exists('curl_init')) {
        echo "<br /><b style='color: #F00;'>CURL is not installed</b>. Asking your hosting provider to install and enable CURL may improve any connection problems.</b><br />\n";
        return;
    }
    echo "<br /><b>STARTING CURL {$protocol} CONNECTION TEST....</b><br />\n";
    global $curlContent;
    $curlContent = "";
    $curl = curl_init($protocol . '://noc1.wordfence.com/');
    if (defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT') && wfUtils::hostNotExcludedFromProxy('noc1.wordfence.com')) {
        curl_setopt($curl, CURLOPT_HTTPPROXYTUNNEL, 0);
        curl_setopt($curl, CURLOPT_PROXY, WP_PROXY_HOST . ':' . WP_PROXY_PORT);
        if (defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD')) {
            curl_setopt($curl, CURLOPT_PROXYUSERPWD, WP_PROXY_USERNAME . ':' . WP_PROXY_PASSWORD);
        }
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 900);
    curl_setopt($curl, CURLOPT_USERAGENT, "Wordfence.com UA " . (defined('WORDFENCE_VERSION') ? WORDFENCE_VERSION : '[Unknown version]'));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_WRITEFUNCTION, 'curlWrite');
    curl_exec($curl);
    $httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if (strpos($curlContent, 'Your site did not send an API key') !== false) {
        echo "Curl connectivity test passed.<br /><br />\n";
    } else {
        $curlErrorNo = curl_errno($curl);
        $curlError = curl_error($curl);
        echo "Curl connectivity test failed with response: <pre>{$curlContent}</pre>";
        echo "<br />Curl HTTP status: {$httpStatus}<br />Curl error code: {$curlErrorNo}<br />Curl Error: {$curlError}<br /><br />\n";
    }
}
Пример #4
0
 function load()
 {
     if ($this->_checkWordFence()) {
         if (wfUtils::isScanRunning()) {
             return array('scan' => 'yes');
         } else {
             return wordfence::ajax_loadIssues_callback();
         }
     } else {
         return array('warning' => "Word Fence plugin is not activated");
     }
 }
 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;
     }
 }
Пример #6
0
 /**
  * Check if any plugins need an update.
  *
  * @return $this
  */
 public function checkPluginUpdates()
 {
     $this->plugin_updates = array();
     if (!function_exists('wp_update_plugins')) {
         require_once ABSPATH . WPINC . '/update.php';
     }
     wp_update_plugins();
     // Check for Plugin updates
     $update_plugins = get_site_transient('update_plugins');
     if ($update_plugins && !empty($update_plugins->response)) {
         foreach ($update_plugins->response as $plugin => $vals) {
             if (!function_exists('get_plugin_data')) {
                 require_once ABSPATH . '/wp-admin/includes/plugin.php';
             }
             $pluginFile = wfUtils::getPluginBaseDir() . $plugin;
             $data = get_plugin_data($pluginFile);
             $data['newVersion'] = $vals->new_version;
             $this->plugin_updates[] = $data;
         }
     }
     return $this;
 }
Пример #7
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;
 }
Пример #8
0
<?php

if (!wfUtils::isAdmin()) {
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"  dir="ltr" lang="en-US">
<head>
<title>Wordfence System Info</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel='stylesheet' id='wordfence-main-style-css'  href='<?php 
echo wfUtils::getBaseURL();
?>
/css/phpinfo.css?ver=<?php 
echo WORDFENCE_VERSION;
?>
' type='text/css' media='all' />
<body>
<?php 
ob_start();
phpinfo(INFO_ALL);
$out = ob_get_clean();
$out = str_replace('width="600"', 'width="900"', $out);
$out = preg_replace('/<hr.*?PHP Credits.*?<\\/h1>/s', '', $out);
$out = preg_replace('/<a [^>]+>/', '', $out);
$out = preg_replace('/<\\/a>/', '', $out);
$out = preg_replace('/<title>[^<]*<\\/title>/', '', $out);
echo $out;
?>
<div class="diffFooter">&copy;&nbsp;2011 Wordfence &mdash; Visit <a href="http://wordfence.com/">Wordfence.com</a> for help, security updates and more.</a>
Пример #9
0
 /**
  * This is the only hook I see to tie into WP's core update process.
  * Since we hide the readme.html to prevent the WordPress version from being discovered, it breaks the upgrade
  * process because it cannot copy the previous readme.html.
  *
  * @param string $string
  * @return string
  */
 public static function restoreReadmeForUpgrade($string)
 {
     static $didRun;
     if (!isset($didRun)) {
         $didRun = true;
         wfUtils::showReadme();
         register_shutdown_function('wfUtils::hideReadme');
     }
     return $string;
 }
Пример #10
0
<?php

if (!wfUtils::isAdmin()) {
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"  dir="ltr" lang="en-US">
<head>
<title>Wordfence Connectivity Tester</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<body>
<h1>Wordfence connectivity tester</h1>
<br /><br />
DNS lookup for noc1.wordfence.com returns: <?php 
echo gethostbyname('noc1.wordfence.com');
?>
<br /><br />
<?php 
$curlContent = "";
function curlWrite($h, $d)
{
    global $curlContent;
    $curlContent .= $d;
    return strlen($d);
}
function doWPostTest($protocol)
{
    echo "<br /><b>Starting wp_remote_post() test</b><br />\n";
    $cronURL = admin_url('admin-ajax.php');
    $cronURL = preg_replace('/^(https?:\\/\\/)/i', '://noc1.wordfence.com/scanptest/', $cronURL);
Пример #11
0
 /**
  * Return a set of where clauses to use in MySQL.
  *
  * @param string $column
  * @return false|null|string
  */
 public function toSQL($column = 'ip')
 {
     /** @var wpdb $wpdb */
     global $wpdb;
     $ip_string = $this->getIPString();
     if (strpos($ip_string, '.') !== false && preg_match('/\\[\\d+\\-\\d+\\]/', $ip_string)) {
         $whiteParts = explode('.', $ip_string);
         $sql = "(SUBSTR({$column}, 1, 12) = LPAD(CHAR(0xff, 0xff), 12, CHAR(0)) AND ";
         for ($i = 0, $j = 24; $i <= 3; $i++, $j -= 8) {
             // MySQL can only perform bitwise operations on integers
             $conv = sprintf('CAST(CONV(HEX(SUBSTR(%s, 13, 8)), 16, 10) as UNSIGNED INTEGER)', $column);
             if (preg_match('/^\\[(\\d+)\\-(\\d+)\\]$/', $whiteParts[$i], $m)) {
                 $sql .= $wpdb->prepare("{$conv} >> {$j} & 0xFF BETWEEN %d AND %d", $m[1], $m[2]);
             } else {
                 $sql .= $wpdb->prepare("{$conv} >> {$j} & 0xFF = %d", $whiteParts[$i]);
             }
             $sql .= ' AND ';
         }
         $sql = substr($sql, 0, -5) . ')';
         return $sql;
     } else {
         if (strpos($ip_string, ':') !== false && preg_match('/\\[[a-f0-9]+\\-[a-f0-9]+\\]/', $ip_string)) {
             $whiteParts = explode(':', strtolower(self::expandIPv6Range($ip_string)));
             $sql = '(';
             for ($i = 0; $i <= 7; $i++) {
                 // MySQL can only perform bitwise operations on integers
                 $conv = sprintf('CAST(CONV(HEX(SUBSTR(%s, %d, 8)), 16, 10) as UNSIGNED INTEGER)', $column, $i < 4 ? 1 : 9);
                 $j = 16 * (3 - $i % 4);
                 if (preg_match('/^\\[([a-f0-9]+)\\-([a-f0-9]+)\\]$/', $whiteParts[$i], $m)) {
                     $sql .= $wpdb->prepare("{$conv} >> {$j} & 0xFFFF BETWEEN 0x%x AND 0x%x", hexdec($m[1]), hexdec($m[2]));
                 } else {
                     $sql .= $wpdb->prepare("{$conv} >> {$j} & 0xFFFF = 0x%x", hexdec($whiteParts[$i]));
                 }
                 $sql .= ' AND ';
             }
             $sql = substr($sql, 0, -5) . ')';
             return $sql;
         }
     }
     return $wpdb->prepare("({$column} = %s)", wfUtils::inet_pton($ip_string));
 }
Пример #12
0
    ?>
7&dir=<?php 
    echo $sortIDX == 7 && $sortDir == 'fwd' ? 'rev' : 'fwd';
    ?>
">Permissions</a></th>
	<th><a href="<?php 
    echo $sortLink;
    ?>
1&dir=<?php 
    echo $sortIDX == 1 && $sortDir == 'fwd' ? 'rev' : 'fwd';
    ?>
">Full file path</a></th>
</tr>
<?php 
    for ($i = 0; $i < sizeof($files); $i++) {
        echo '<tr><td>' . wfUtils::formatBytes($files[$i][2]) . '</td><td>' . wfUtils::makeTimeAgo(time() - $files[$i][3]) . ' ago.</td><td>' . $files[$i][5] . '</td><td>' . $files[$i][6] . '</td><td>' . $files[$i][7] . '</td><td><a href="' . $files[$i][4] . '" target="_blank">' . $files[$i][1] . '</a></td></tr>';
    }
    echo "</table>";
} else {
    ?>
<p style="margin: 40px; font-size: 20px;">
	You either have not completed a scan recently, or there were no files found on your system that are not in the WordPress official repository for Core files, themes and plugins.
</p>
<?php 
}
?>

<div class="diffFooter">&copy;&nbsp;2011 Wordfence &mdash; Visit <a href="http://wordfence.com/">Wordfence.com</a> for help, security updates and more.</a>
</body>
</html>
Пример #13
0
 public static function wfHash($file)
 {
     wfUtils::errorsOff();
     $md5 = @md5_file($file, false);
     wfUtils::errorsOn();
     if (!$md5) {
         return false;
     }
     $fp = @fopen($file, "rb");
     if (!$fp) {
         return false;
     }
     $ctx = hash_init('sha256');
     while (!feof($fp)) {
         hash_update($ctx, str_replace(array("\n", "\r", "\t", " "), "", fread($fp, 65536)));
     }
     $shac = hash_final($ctx, false);
     return array($md5, $shac);
 }
Пример #14
0
 public static function htaccess()
 {
     if (is_readable(ABSPATH . '/.htaccess') && !wfUtils::isNginx()) {
         return file_get_contents(ABSPATH . '/.htaccess');
     }
     return "";
 }
	<ul>
		<li>
			<a href="<?php 
    echo wfUtils::siteURLRelative();
    ?>
?_wfsf=sysinfo&nonce=<?php 
    echo wp_create_nonce('wp-ajax');
    ?>
"
			   target="_blank">Click to view your system's configuration in a new window</a>
			<a href="http://docs.wordfence.com/en/Wordfence_options#Click_to_view_your_system.27s_configuration_in_a_new_window"
			   target="_blank" class="wfhelp"></a></li>
		<li>
			<a href="<?php 
    echo wfUtils::siteURLRelative();
    ?>
?_wfsf=testmem&nonce=<?php 
    echo wp_create_nonce('wp-ajax');
    ?>
"
			   target="_blank">Test your WordPress host's available memory</a>
			<a href="http://docs.wordfence.com/en/Wordfence_options#Test_your_WordPress_host.27s_available_memory"
			   target="_blank" class="wfhelp"></a>
		</li>
		<li>
			Send a test email from this WordPress server to an email address:<a
				href="http://docs.wordfence.com/en/Wordfence_options#Send_a_test_email_from_this_WordPress_server_to_an_email_address"
				target="_blank" class="wfhelp"></a>
			<input type="text" id="testEmailDest" value="" size="20" maxlength="255" class="wfConfigElem"/>
			<input class="button" type="button" value="Send Test Email"
Пример #16
0
		<?php 
if (!wfUtils::isNginx()) {
    ?>
			<a href="#" onclick="WFAD.disableDirectoryListing('${id}'); return false;">Fix this issue</a>
		<?php 
}
?>
		<a href="#" onclick="WFAD.updateIssueStatus('${id}', 'delete'); return false;">I have fixed this issue</a>
		<a href="#" onclick="WFAD.updateIssueStatus('${id}', 'ignoreC'); return false;">Ignore this issue</a>
		{{/if}}
		{{if status == 'ignoreC' || status == 'ignoreP'}}
		<a href="#" onclick="WFAD.updateIssueStatus('${id}', 'delete'); return false;">Stop ignoring this issue</a>
		{{/if}}
	</div>
	<?php 
if (!wfUtils::isNginx()) {
    ?>
	{{if (status == 'new')}}
	<div class="wfIssueOptions">
		<strong style="width: auto;">Manual Fix:</strong>
		&nbsp;
		Add <code>Options -Indexes</code> to your .htaccess file.
	</div>
	{{/if}}
	<?php 
}
?>

</div>
</div>
</script>
 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;
 }
Пример #18
0
 public static function startScan($isFork = false)
 {
     if (!$isFork) {
         //beginning of scan
         wfConfig::inc('totalScansRun');
         wfConfig::set('wfKillRequested', 0);
         wordfence::status(4, 'info', "Entering start scan routine");
         if (wfUtils::isScanRunning()) {
             return "A scan is already running. Use the kill link if you would like to terminate the current scan.";
         }
     }
     $timeout = self::getMaxExecutionTime() - 2;
     //2 seconds shorter than max execution time which ensures that only 2 HTTP processes are ever occupied
     $testURL = admin_url('admin-ajax.php?action=wordfence_testAjax');
     if (!wfConfig::get('startScansRemotely', false)) {
         $testResult = wp_remote_post($testURL, array('timeout' => $timeout, 'blocking' => true, 'sslverify' => false, 'headers' => array()));
         wordfence::status(4, 'info', "Test result of scan start URL fetch: " . var_export($testResult, true));
     }
     $cronKey = wfUtils::bigRandomHex();
     wfConfig::set('currentCronKey', time() . ',' . $cronKey);
     if (!wfConfig::get('startScansRemotely', false) && !is_wp_error($testResult) && is_array($testResult) && strstr($testResult['body'], 'WFSCANTESTOK') !== false) {
         //ajax requests can be sent by the server to itself
         $cronURL = 'admin-ajax.php?action=wordfence_doScan&isFork=' . ($isFork ? '1' : '0') . '&cronKey=' . $cronKey;
         $cronURL = admin_url($cronURL);
         $headers = array();
         wordfence::status(4, 'info', "Starting cron with normal ajax at URL {$cronURL}");
         wp_remote_get($cronURL, array('timeout' => $timeout, 'blocking' => true, 'sslverify' => false, 'headers' => $headers));
         wordfence::status(4, 'info', "Scan process ended after forking.");
     } else {
         $cronURL = admin_url('admin-ajax.php');
         $cronURL = preg_replace('/^(https?:\\/\\/)/i', '$1noc1.wordfence.com/scanp/', $cronURL);
         $cronURL .= '?action=wordfence_doScan&isFork=' . ($isFork ? '1' : '0') . '&cronKey=' . $cronKey;
         $headers = array();
         wordfence::status(4, 'info', "Starting cron via proxy at URL {$cronURL}");
         wp_remote_get($cronURL, array('timeout' => $timeout, 'blocking' => true, 'sslverify' => false, 'headers' => $headers));
         wordfence::status(4, 'info', "Scan process ended after forking.");
     }
     return false;
     //No error
 }
				<div data-bind="if: !groupBy()">
					<div id="wf-lt-listings" data-bind="foreach: listings">
						<div data-bind="attr: { id: ('wfActEvent_' + id()), 'class': cssClasses }">
							<table border="0" cellpadding="1" cellspacing="0">
								<tr>
									<td>
										<span data-bind="if: action() != 'loginOK' && user()">
											<span data-bind="html: user.avatar" class="wfAvatar"></span>
											<a data-bind="attr: { href: user.editLink }, text: user().display_name"
											   target="_blank"></a>
										</span>
										<span data-bind="if: loc()">
											<span data-bind="if: action() != 'loginOK' && user()"> in</span>
											<img data-bind="attr: { src: '<?php 
echo wfUtils::getBaseURL() . 'images/flags/';
?>
' + loc().countryCode.toLowerCase() + '.png',
												alt: loc().countryName, title: loc().countryName }" width="16"
											     height="11"
											     class="wfFlag"/>
											<a data-bind="text: (loc().city ? loc().city + ', ' : '') + loc().countryName,
												attr: { href: 'http://maps.google.com/maps?q=' + loc().lat + ',' + loc().lon + '&z=6' }"
											   target="_blank"></a>
										</span>
										<span data-bind="if: !loc()">
											<span
												data-bind="text: action() != 'loginOK' && user() ? 'at an' : 'An'"></span> unknown location at IP <a
												data-bind="text: IP, attr: { href: WFAD.makeIPTrafLink(IP()) }"
												target="_blank"></a>
										</span>
Пример #20
0
			<th>Block Count</th>
		</tr>
	</thead>
	<tbody>
		<?php 
if ($top_ips_blocked) {
    ?>
			<?php 
    foreach ($top_ips_blocked as $row) {
        ?>
				<tr class="<?php 
        echo wfHelperString::cycle('odd', 'even');
        ?>
">
					<td><code><?php 
        echo wfUtils::inet_ntop($row->IP);
        ?>
</code></td>
					<td>
						<?php 
        if ($row->countryCode) {
            ?>
							<img src="//www.wordfence.com/images/flags/<?php 
            echo esc_attr(strtolower($row->countryCode));
            ?>
.png" class="wfFlag" height="11" width="16" alt="<?php 
            echo esc_attr($row->countryName);
            ?>
" title="<?php 
            echo esc_attr($row->countryName);
            ?>
Пример #21
0
$pageTitle = "Audit the Strength of your Passwords";
$helpLink = "http://docs.wordfence.com/en/Wordfence_Password_Auditing";
$helpLabel = "Learn more about Password Auditing";
include 'pageTitle.php';
?>
	<?php 
if (!wfConfig::get('isPaid')) {
    ?>
		<div class="wordfenceRightRail">
			<ul>
				<li><a href="https://www.wordfence.com/gnl1rightRailGetPremium/wordfence-signup/" target="_blank"><img src="<?php 
    echo wfUtils::getBaseURL() . 'images/rr_premium.png';
    ?>
" alt="Upgrade your protection - Get Wordfence Premium"></a></li>
				<li><a href="https://www.wordfence.com/gnl1rightRailSiteCleaning/wordfence-site-cleanings/" target="_blank"><img src="<?php 
    echo wfUtils::getBaseURL() . 'images/rr_sitecleaning.jpg';
    ?>
" alt="Have you been hacked? Get help from Wordfence"></a></li> 
				<li>
					<p class="center"><strong>Would you like to remove these ads?</strong><br><a href="https://www.wordfence.com/gnl1rightRailBottomUpgrade/wordfence-signup/" target="_blank">Get Premium</a></p>
				</li>
			</ul>
		</div>
	<?php 
}
?>
	<?php 
if (!wfConfig::get('isPaid')) {
    ?>
		<div class="wf-premium-callout" style="margin: 20px 0 20px 20px; width: 700px;">
			<h3>Password Auditing is only available to Premium Members</h3>
Пример #22
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;
 }
Пример #23
0
							href="http://docs.wordfence.com/en/Wordfence_options#Prevent_discovery_of_usernames_through_.27.3F.2Fauthor.3DN.27_scans"
							target="_blank" class="wfhelp"></a></th>
					<td><input type="checkbox" id="loginSec_disableAuthorScan" class="wfConfigElem"
					           name="loginSec_disableAuthorScan" <?php 
$w->cb('loginSec_disableAuthorScan');
?>
 />
					</td>
				</tr>
				<tr>
					<th style="vertical-align: top;">Immediately block the IP of users who try to sign in as these usernames<a
							href="http://docs.wordfence.com/en/Wordfence_options#Immediately_block_the_IP_of_users_who_try_to_sign_in_as_these_usernames"
							target="_blank" class="wfhelp"></a></th>
					<td>
						<textarea name="loginSec_userBlacklist" cols="40" rows="4" id="loginSec_userBlacklist"><?php 
echo wfUtils::cleanupOneEntryPerLine($w->getHTML('loginSec_userBlacklist'));
?>
</textarea><br/>
						(One per line. Existing users won't be blocked.)
					</td>
				</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>
 private static function getPotentialTempDirs()
 {
     return array(wfUtils::getPluginBaseDir() . 'wordfence/tmp/', sys_get_temp_dir(), ABSPATH . 'wp-content/uploads/');
 }
Пример #25
0
    /**
     * @param mixed $ip_address
     * @param int|null $unixday
     */
    public static function logBlockedIP($ip_address, $unixday = null)
    {
        /** @var wpdb $wpdb */
        global $wpdb;
        if (wfUtils::isValidIP($ip_address)) {
            $ip_bin = wfUtils::inet_pton($ip_address);
        } else {
            $ip_bin = $ip_address;
            $ip_address = wfUtils::inet_ntop($ip_bin);
        }
        $blocked_table = "{$wpdb->base_prefix}wfBlockedIPLog";
        $unixday_insert = 'FLOOR(UNIX_TIMESTAMP() / 86400)';
        if (is_int($unixday)) {
            $unixday_insert = absint($unixday);
        }
        $country = wfUtils::IP2Country($ip_address);
        $wpdb->query($wpdb->prepare(<<<SQL
INSERT INTO {$blocked_table} (IP, countryCode, blockCount, unixday)
VALUES (%s, %s, 1, {$unixday_insert})
ON DUPLICATE KEY UPDATE blockCount = blockCount + 1
SQL
, $ip_bin, $country));
    }
Пример #26
0
function rs_wpss_wf_geoiploc($ip = NULL, $disp = FALSE)
{
    /***
     * If WordFence installed, get GEO IP Location data
     * Added 1.9.5.2
     ***/
    global $wpss_geoiploc_data, $wpss_geolocation;
    if (class_exists('wfUtils') && rs_wpss_is_plugin_active('wordfence/wordfence.php')) {
        /* $start = microtime(TRUE); */
        if (empty($ip)) {
            $ip = rs_wpss_get_ip_addr();
        }
        if (empty($_SESSION['wpss_geoiploc_data_' . WPSS_HASH]) && empty($wpss_geoiploc_data) || (empty($_SESSION['wpss_geolocation_' . WPSS_HASH]) && empty($wpss_geolocation) || empty($_SESSION['wpss_geoiploc_ip_' . WPSS_HASH]) || $_SESSION['wpss_geoiploc_ip_' . WPSS_HASH] !== $ip)) {
            $wpss_geoiploc_data = wfUtils::getIPGeo($ip);
            /***
             * $wpss_geoiploc_data = array( 'IP' => $ip, 'city' => $city, 'region' => $region, 'countryName' => $countryName, 'countryCode' => $countryCode, 'lat' => $lat, 'lon' => $long );
             ***/
            if (empty($wpss_geoiploc_data) || !is_array($wpss_geoiploc_data)) {
                return '';
            }
            extract($wpss_geoiploc_data);
            $city_region = !empty($city) && !empty($region) ? ' - ' . $city . ', ' . $region : '';
            $_SESSION['wpss_geoiploc_ip_' . WPSS_HASH] = $ip;
            if (FALSE === $disp) {
                /* $rs_wpss_timer_bm( $start ); */
                return $wpss_geoiploc_data;
            }
        }
        if (TRUE === $disp) {
            if (!empty($_SESSION['wpss_geolocation_' . WPSS_HASH])) {
                $wpss_geolocation = $_SESSION['wpss_geolocation_' . WPSS_HASH];
                /* $rs_wpss_timer_bm( $start ); */
                return $wpss_geolocation;
            } elseif (!empty($wpss_geolocation)) {
                $_SESSION['wpss_geolocation_' . WPSS_HASH] = $wpss_geolocation;
                /* $rs_wpss_timer_bm( $start ); */
                return $wpss_geolocation;
            } else {
                $wpss_geolocation = $countryCode . ' - ' . $countryName . $city_region;
                $_SESSION['wpss_geolocation_' . WPSS_HASH] = $wpss_geolocation;
                /* $rs_wpss_timer_bm( $start ); */
                return $wpss_geolocation;
            }
        } else {
            if (!empty($_SESSION['wpss_geoiploc_data_' . WPSS_HASH])) {
                $wpss_geoiploc_data = $_SESSION['wpss_geoiploc_data_' . WPSS_HASH];
                /* $rs_wpss_timer_bm( $start ); */
                return $wpss_geoiploc_data;
            } elseif (!empty($wpss_geoiploc_data)) {
                $_SESSION['wpss_geoiploc_data_' . WPSS_HASH] = $wpss_geoiploc_data;
                /* $rs_wpss_timer_bm( $start ); */
                return $wpss_geoiploc_data;
            } else {
                $wpss_geoiploc_data = $countryCode . ' - ' . $countryName . $city_region;
                $_SESSION['wpss_geoiploc_data_' . WPSS_HASH] = $wpss_geoiploc_data;
                /* $rs_wpss_timer_bm( $start ); */
                return $wpss_geoiploc_data;
            }
        }
    }
    return '';
}
Пример #27
0
    $failedRules = $waf->getFailedRules();
} catch (wfWAFBlockXSSException $e) {
    $result = '<strong class="error">Blocked For XSS</strong>';
    $failedRules = $waf->getFailedRules();
}
?>
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title><?php 
echo esc_html($title);
?>
</title>
	<link rel="stylesheet" href="<?php 
echo wfUtils::getBaseURL() . 'css/main.css';
?>
">
	<style>
		html {
			font-family: "Open Sans", Helvetica, Arial, sans-serif;
		}
		h1, h2, h3, h4, h5 {
			margin: 20px 0px 8px;
		}
		pre, p {
			8px 0px 20px;
		}
		pre.request-debug {
			padding: 12px;
			background: #fafafa;
 public function displayIP($binaryIP)
 {
     $readableIP = wfUtils::inet_ntop($binaryIP);
     $country = wfUtils::countryCode2Name(wfUtils::IP2Country($readableIP));
     return "{$readableIP} (" . ($country ? $country : 'Unknown') . ")";
 }
 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;
 }
Пример #30
0
 public static function fileTooBig($file)
 {
     //Deals with files > 2 gigs on 32 bit systems which are reported with the wrong size due to integer overflow
     wfUtils::errorsOff();
     $fh = @fopen($file, 'r');
     wfUtils::errorsOn();
     if (!$fh) {
         return false;
     }
     $offset = WORDFENCE_MAX_FILE_SIZE_TO_PROCESS + 1;
     $tooBig = false;
     try {
         if (@fseek($fh, $offset, SEEK_SET) === 0) {
             if (strlen(fread($fh, 1)) === 1) {
                 $tooBig = true;
             }
         }
         //Otherwise we couldn't seek there so it must be smaller
         fclose($fh);
         return $tooBig;
     } catch (Exception $e) {
         return true;
     }
     //If we get an error don't scan this file, report it's too big.
 }