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;
     }
 }
 function save_setting()
 {
     $settings = maybe_unserialize(base64_decode($_POST['settings']));
     if (is_array($settings) && count($settings) > 0) {
         $result = array();
         $reload = '';
         $opts = $settings;
         $validUsers = array();
         $invalidUsers = array();
         foreach (explode(',', $opts['liveTraf_ignoreUsers']) as $val) {
             $val = trim($val);
             if (strlen($val) > 0) {
                 if (get_user_by('login', $val)) {
                     $validUsers[] = $val;
                 } else {
                     $invalidUsers[] = $val;
                 }
             }
         }
         if (count($invalidUsers) > 0) {
             // return array('errorMsg' => "The following users you selected to ignore in live traffic reports are not valid on this system: " . htmlentities(implode(', ', $invalidUsers)) );
             $result['invalid_users'] = htmlentities(implode(', ', $invalidUsers));
         }
         if (count($validUsers) > 0) {
             $opts['liveTraf_ignoreUsers'] = implode(',', $validUsers);
         } else {
             $opts['liveTraf_ignoreUsers'] = '';
         }
         if (!$opts['other_WFNet']) {
             $wfdb = new wfDB();
             global $wpdb;
             $p = $wpdb->base_prefix;
             $wfdb->queryWrite("delete from {$p}" . 'wfBlocks where wfsn=1 and permanent=0');
         }
         $regenerateHtaccess = false;
         if (wfConfig::get('bannedURLs', false) !== $opts['bannedURLs']) {
             $regenerateHtaccess = true;
         }
         foreach ($opts as $key => $val) {
             if (in_array($key, self::$options_filter)) {
                 if ('apiKey' !== $key) {
                     //Don't save API key yet
                     wfConfig::set($key, $val);
                 }
             }
         }
         if ($regenerateHtaccess) {
             wfCache::addHtaccessCode('add');
         }
         if ('1' === $opts['autoUpdate']) {
             wfConfig::enableAutoUpdate();
         } else {
             if ('0' === $opts['autoUpdate']) {
                 wfConfig::disableAutoUpdate();
             }
         }
         if (isset($opts['disableCodeExecutionUploads'])) {
             try {
                 if ($opts['disableCodeExecutionUploads']) {
                     wfConfig::disableCodeExecutionForUploads();
                 } else {
                     wfConfig::removeCodeExecutionProtectionForUploads();
                 }
             } catch (wfConfigException $e) {
                 return array('error' => $e->getMessage());
             }
         }
         if (isset($opts['email_summary_enabled'])) {
             if (!empty($opts['email_summary_enabled'])) {
                 wfConfig::set('email_summary_enabled', 1);
                 wfConfig::set('email_summary_interval', $opts['email_summary_interval']);
                 wfConfig::set('email_summary_excluded_directories', $opts['email_summary_excluded_directories']);
                 wfActivityReport::scheduleCronJob();
             } else {
                 wfConfig::set('email_summary_enabled', 0);
                 wfActivityReport::disableCronJob();
             }
         }
         $sch = isset($opts['scheduleScan']) ? $opts['scheduleScan'] : '';
         if (get_option('mainwp_child_wordfence_cron_time') !== $sch) {
             update_option('mainwp_child_wordfence_cron_time', $sch);
             $sched = wp_next_scheduled('mainwp_child_wordfence_cron_scan');
             if (false !== $sched) {
                 wp_unschedule_event($sched, 'mainwp_child_wordfence_cron_scan');
             }
         }
         $result['cacheType'] = wfConfig::get('cacheType');
         $result['paidKeyMsg'] = false;
         $apiKey = trim($_POST['apiKey']);
         if (!$apiKey) {
             //Empty API key (after trim above), then try to get one.
             $api = new wfAPI('', wfUtils::getWPVersion());
             try {
                 $keyData = $api->call('get_anon_api_key');
                 if ($keyData['ok'] && $keyData['apiKey']) {
                     wfConfig::set('apiKey', $keyData['apiKey']);
                     wfConfig::set('isPaid', 0);
                     $result['apiKey'] = $keyData['apiKey'];
                     $result['isPaid'] = 0;
                     $reload = 'reload';
                 } else {
                     throw new Exception("We could not understand the Wordfence server's response because it did not contain an 'ok' and 'apiKey' element.");
                 }
             } catch (Exception $e) {
                 $result['error'] = 'Your options have been saved, but we encountered a problem. You left your API key blank, so we tried to get you a free API key from the Wordfence servers. However we encountered a problem fetching the free key: ' . htmlentities($e->getMessage());
                 return $result;
             }
         } else {
             if (wfConfig::get('apiKey') !== $apiKey) {
                 $api = new wfAPI($apiKey, wfUtils::getWPVersion());
                 try {
                     $res = $api->call('check_api_key', array(), array());
                     if ($res['ok'] && isset($res['isPaid'])) {
                         wfConfig::set('apiKey', $apiKey);
                         wfConfig::set('isPaid', $res['isPaid']);
                         //res['isPaid'] is boolean coming back as JSON and turned back into PHP struct. Assuming JSON to PHP handles bools.
                         $result['apiKey'] = $apiKey;
                         $result['isPaid'] = $res['isPaid'];
                         if ($res['isPaid']) {
                             $result['paidKeyMsg'] = true;
                         }
                         $reload = 'reload';
                     } else {
                         throw new Exception('We could not understand the Wordfence API server reply when updating your API key.');
                     }
                 } catch (Exception $e) {
                     $result['error'] = 'Your options have been saved. However we noticed you changed your API key and we tried to verify it with the Wordfence servers and received an error: ' . htmlentities($e->getMessage());
                     return $result;
                 }
             } else {
                 try {
                     $api = new wfAPI($apiKey, wfUtils::getWPVersion());
                     $res = $api->call('ping_api_key', array(), array());
                 } catch (Exception $e) {
                     $result['error'] = 'Your options have been saved. However we noticed you do not change your API key and we tried to verify it with the Wordfence servers and received an error: ' . htmlentities($e->getMessage());
                     return $result;
                 }
             }
         }
         $result['ok'] = 1;
         $result['reload'] = $reload;
         return $result;
     }
 }
Exemplo n.º 3
0
 public static function reverseLookup($IP)
 {
     $db = new wfDB();
     global $wpdb;
     $reverseTable = $wpdb->base_prefix . 'wfReverseCache';
     $IPn = wfUtils::inet_pton($IP);
     $host = $db->querySingle("select host from " . $reverseTable . " where IP=%s and unix_timestamp() - lastUpdate < %d", $IPn, WORDFENCE_REVERSE_LOOKUP_CACHE_TIME);
     if (!$host) {
         // This function works for IPv4 or IPv6
         if (function_exists('gethostbyaddr')) {
             $host = gethostbyaddr($IP);
         }
         if (!$host) {
             $ptr = false;
             if (filter_var($IP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
                 $ptr = implode(".", array_reverse(explode(".", $IP))) . ".in-addr.arpa";
             } else {
                 if (filter_var($IP, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) {
                     $ptr = implode(".", array_reverse(str_split(bin2hex($IPn)))) . ".ip6.arpa";
                 }
             }
             if ($ptr && function_exists('dns_get_record')) {
                 $host = @dns_get_record($ptr, DNS_PTR);
                 if ($host) {
                     $host = $host[0]['target'];
                 }
             }
         }
         if (!$host) {
             $host = 'NONE';
         }
         $db->queryWrite("insert into " . $reverseTable . " (IP, host, lastUpdate) values (%s, '%s', unix_timestamp()) ON DUPLICATE KEY UPDATE host='%s', lastUpdate=unix_timestamp()", $IPn, $host, $host);
     }
     if ($host == 'NONE') {
         return '';
     } else {
         return $host;
     }
 }
 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;
 }
Exemplo n.º 5
0
 public static function trimWfHits()
 {
     global $wpdb;
     $p = $wpdb->base_prefix;
     $wfdb = new wfDB();
     $count = $wfdb->querySingle("select count(*) as cnt from {$p}" . "wfHits");
     $liveTrafficMaxRows = absint(wfConfig::get('liveTraf_maxRows', 2000));
     if ($count > $liveTrafficMaxRows * 10) {
         $wfdb->truncate($p . "wfHits");
         //So we don't slow down sites that have very large wfHits tables
     } else {
         if ($count > $liveTrafficMaxRows) {
             $wfdb->queryWrite("delete from {$p}" . "wfHits order by id asc limit %d", $count - $liveTrafficMaxRows + $liveTrafficMaxRows * 0.2);
         }
     }
 }
Exemplo n.º 6
0
 public static function reverseLookup($IP)
 {
     $db = new wfDB();
     global $wpdb;
     $reverseTable = $wpdb->base_prefix . 'wfReverseCache';
     $IPn = wfUtils::inet_aton($IP);
     $host = $db->querySingle("select host from " . $reverseTable . " where IP=%s and unix_timestamp() - lastUpdate < %d", $IPn, WORDFENCE_REVERSE_LOOKUP_CACHE_TIME);
     if (!$host) {
         $ptr = implode(".", array_reverse(explode(".", $IP))) . ".in-addr.arpa";
         $host = @dns_get_record($ptr, DNS_PTR);
         if ($host == null) {
             $host = 'NONE';
         } else {
             $host = $host[0]['target'];
         }
         $db->queryWrite("insert into " . $reverseTable . " (IP, host, lastUpdate) values (%s, '%s', unix_timestamp()) ON DUPLICATE KEY UPDATE host='%s', lastUpdate=unix_timestamp()", $IPn, $host, $host);
     }
     if ($host == 'NONE') {
         return '';
     } else {
         return $host;
     }
 }
Exemplo n.º 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;
 }
Exemplo n.º 8
0
 public static function ajax_saveConfig_callback()
 {
     $reload = '';
     $opts = wfConfig::parseOptions();
     $emails = array();
     foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['alertEmails'])) as $email) {
         if (strlen($email) > 0) {
             $emails[] = $email;
         }
     }
     if (sizeof($emails) > 0) {
         $badEmails = array();
         foreach ($emails as $email) {
             if (!preg_match('/^[^@]+@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,11})$/i', $email)) {
                 $badEmails[] = $email;
             }
         }
         if (sizeof($badEmails) > 0) {
             return array('errorMsg' => "The following emails are invalid: " . wp_kses(implode(', ', $badEmails), array()));
         }
         $opts['alertEmails'] = implode(',', $emails);
     } else {
         $opts['alertEmails'] = '';
     }
     $opts['scan_exclude'] = preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['scan_exclude']);
     $whiteIPs = array();
     foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['whitelisted'])) as $whiteIP) {
         if (strlen($whiteIP) > 0) {
             $whiteIPs[] = $whiteIP;
         }
     }
     if (sizeof($whiteIPs) > 0) {
         $badWhiteIPs = array();
         $range = new wfUserIPRange();
         foreach ($whiteIPs as $whiteIP) {
             $range->setIPString($whiteIP);
             if (!$range->isValidRange()) {
                 $badWhiteIPs[] = $whiteIP;
             }
         }
         if (sizeof($badWhiteIPs) > 0) {
             return array('errorMsg' => "Please make sure you separate your IP addresses with commas. The following whitelisted IP addresses are invalid: " . wp_kses(implode(', ', $badWhiteIPs), array()));
         }
         $opts['whitelisted'] = implode(',', $whiteIPs);
     } else {
         $opts['whitelisted'] = '';
     }
     $validUsers = array();
     $invalidUsers = array();
     foreach (explode(',', $opts['liveTraf_ignoreUsers']) as $val) {
         $val = trim($val);
         if (strlen($val) > 0) {
             if (get_user_by('login', $val)) {
                 $validUsers[] = $val;
             } else {
                 $invalidUsers[] = $val;
             }
         }
     }
     $userBlacklist = array();
     foreach (explode(',', $opts['loginSec_userBlacklist']) as $user) {
         $user = trim($user);
         if (strlen($user) > 0) {
             $userBlacklist[] = $user;
         }
     }
     if (sizeof($userBlacklist) > 0) {
         $opts['loginSec_userBlacklist'] = implode(',', $userBlacklist);
     } else {
         $opts['loginSec_userBlacklist'] = '';
     }
     $opts['apiKey'] = trim($opts['apiKey']);
     if ($opts['apiKey'] && !preg_match('/^[a-fA-F0-9]+$/', $opts['apiKey'])) {
         //User entered something but it's garbage.
         return array('errorMsg' => "You entered an API key but it is not in a valid format. It must consist only of characters A to F and 0 to 9.");
     }
     if (sizeof($invalidUsers) > 0) {
         return array('errorMsg' => "The following users you selected to ignore in live traffic reports are not valid on this system: " . wp_kses(implode(', ', $invalidUsers), array()));
     }
     if (sizeof($validUsers) > 0) {
         $opts['liveTraf_ignoreUsers'] = implode(',', $validUsers);
     } else {
         $opts['liveTraf_ignoreUsers'] = '';
     }
     $validIPs = array();
     $invalidIPs = array();
     foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['liveTraf_ignoreIPs'])) as $val) {
         if (strlen($val) > 0) {
             if (wfUtils::isValidIP($val)) {
                 $validIPs[] = $val;
             } else {
                 $invalidIPs[] = $val;
             }
         }
     }
     if (sizeof($invalidIPs) > 0) {
         return array('errorMsg' => "The following IPs you selected to ignore in live traffic reports are not valid: " . wp_kses(implode(', ', $invalidIPs), array()));
     }
     if (sizeof($validIPs) > 0) {
         $opts['liveTraf_ignoreIPs'] = implode(',', $validIPs);
     }
     if (preg_match('/[a-zA-Z0-9\\d]+/', $opts['liveTraf_ignoreUA'])) {
         $opts['liveTraf_ignoreUA'] = trim($opts['liveTraf_ignoreUA']);
     } else {
         $opts['liveTraf_ignoreUA'] = '';
     }
     if (!$opts['other_WFNet']) {
         $wfdb = new wfDB();
         global $wpdb;
         $p = $wpdb->base_prefix;
         $wfdb->queryWrite("delete from {$p}" . "wfBlocks where wfsn=1 and permanent=0");
     }
     if ($opts['howGetIPs'] != wfConfig::get('howGetIPs', '')) {
         $reload = 'reload';
     }
     $regenerateHtaccess = false;
     if (wfConfig::get('bannedURLs', false) != $opts['bannedURLs']) {
         $regenerateHtaccess = true;
     }
     foreach ($opts as $key => $val) {
         if ($key != 'apiKey') {
             //Don't save API key yet
             wfConfig::set($key, $val);
         }
     }
     if ($regenerateHtaccess) {
         wfCache::addHtaccessCode('add');
     }
     if ($opts['autoUpdate'] == '1') {
         wfConfig::enableAutoUpdate();
     } else {
         if ($opts['autoUpdate'] == '0') {
             wfConfig::disableAutoUpdate();
         }
     }
     try {
         if ($opts['disableCodeExecutionUploads']) {
             wfConfig::disableCodeExecutionForUploads();
         } else {
             wfConfig::removeCodeExecutionProtectionForUploads();
         }
     } catch (wfConfigException $e) {
         return array('errorMsg' => $e->getMessage());
     }
     if (!empty($opts['email_summary_enabled'])) {
         wfConfig::set('email_summary_enabled', 1);
         wfConfig::set('email_summary_interval', $opts['email_summary_interval']);
         wfConfig::set('email_summary_excluded_directories', $opts['email_summary_excluded_directories']);
         wfActivityReport::scheduleCronJob();
     } else {
         wfConfig::set('email_summary_enabled', 0);
         wfActivityReport::disableCronJob();
     }
     $paidKeyMsg = false;
     if (!$opts['apiKey']) {
         //Empty API key (after trim above), then try to get one.
         $api = new wfAPI('', wfUtils::getWPVersion());
         try {
             $keyData = $api->call('get_anon_api_key');
             if ($keyData['ok'] && $keyData['apiKey']) {
                 wfConfig::set('apiKey', $keyData['apiKey']);
                 wfConfig::set('isPaid', 0);
                 $reload = 'reload';
             } else {
                 throw new Exception("We could not understand the Wordfence server's response because it did not contain an 'ok' and 'apiKey' element.");
             }
         } catch (Exception $e) {
             return array('errorMsg' => "Your options have been saved, but we encountered a problem. You left your API key blank, so we tried to get you a free API key from the Wordfence servers. However we encountered a problem fetching the free key: " . wp_kses($e->getMessage(), array()));
         }
     } else {
         if ($opts['apiKey'] != wfConfig::get('apiKey')) {
             $api = new wfAPI($opts['apiKey'], wfUtils::getWPVersion());
             try {
                 $res = $api->call('check_api_key', array(), array());
                 if ($res['ok'] && isset($res['isPaid'])) {
                     wfConfig::set('apiKey', $opts['apiKey']);
                     $reload = 'reload';
                     wfConfig::set('isPaid', $res['isPaid']);
                     //res['isPaid'] is boolean coming back as JSON and turned back into PHP struct. Assuming JSON to PHP handles bools.
                     if ($res['isPaid']) {
                         $paidKeyMsg = true;
                     }
                 } else {
                     throw new Exception("We could not understand the Wordfence API server reply when updating your API key.");
                 }
             } catch (Exception $e) {
                 return array('errorMsg' => "Your options have been saved. However we noticed you changed your API key and we tried to verify it with the Wordfence servers and received an error: " . wp_kses($e->getMessage(), array()));
             }
         } else {
             $api = new wfAPI($opts['apiKey'], wfUtils::getWPVersion());
             $api->call('ping_api_key', array(), array());
         }
     }
     return array('ok' => 1, 'reload' => $reload, 'paidKeyMsg' => $paidKeyMsg);
 }
Exemplo n.º 9
0
 /**
  * @param string|null $ip
  * @return bool
  */
 public static function verifyGooglebotViaNOC1($ip = null)
 {
     global $wpdb;
     $table = $wpdb->base_prefix . 'wfCrawlers';
     if ($ip === null) {
         $ip = wfUtils::getIP();
     }
     $db = new wfDB();
     $IPn = wfUtils::inet_pton($ip);
     $patternSig = 'googlenoc1';
     $status = $db->querySingle("select status from {$table}\n\t\t\t\twhere IP=%s\n\t\t\t\tand patternSig=UNHEX(MD5('%s'))\n\t\t\t\tand lastUpdate > unix_timestamp() - %d", $IPn, $patternSig, WORDFENCE_CRAWLER_VERIFY_CACHE_TIME);
     if ($status === 'verified') {
         return true;
     } else {
         if ($status === 'fakeBot') {
             return false;
         }
     }
     $api = new wfAPI(wfConfig::get('apiKey'), wfUtils::getWPVersion());
     try {
         $data = $api->call('verify_googlebot', array('ip' => $ip));
         if (is_array($data) && !empty($data['verified'])) {
             // Cache results
             $db->queryWrite("insert into {$table} (IP, patternSig, status, lastUpdate)\nvalues (%s, UNHEX(MD5('%s')), '%s', unix_timestamp())\nON DUPLICATE KEY UPDATE status='%3\$s', lastUpdate=unix_timestamp()", $IPn, $patternSig, 'verified');
             return true;
         } else {
             $db->queryWrite("insert into {$table} (IP, patternSig, status, lastUpdate)\nvalues (%s, UNHEX(MD5('%s')), '%s', unix_timestamp())\nON DUPLICATE KEY UPDATE status='%3\$s', lastUpdate=unix_timestamp()", $IPn, $patternSig, 'fakeBot');
         }
     } catch (Exception $e) {
         // Do nothing, bail
     }
     return false;
 }
Exemplo n.º 10
0
 public static function ajax_saveConfig_callback()
 {
     $reload = '';
     $opts = wfConfig::parseOptions();
     $emails = array();
     foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['alertEmails'])) as $email) {
         if (strlen($email) > 0) {
             array_push($emails, $email);
         }
     }
     if (sizeof($emails) > 0) {
         $badEmails = array();
         foreach ($emails as $email) {
             if (!preg_match('/^[^@]+@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,8})$/i', $email)) {
                 array_push($badEmails, $email);
             }
         }
         if (sizeof($badEmails) > 0) {
             return array('errorMsg' => "The following emails are invalid: " . htmlentities(implode(', ', $badEmails)));
         }
         $opts['alertEmails'] = implode(',', $emails);
     } else {
         $opts['alertEmails'] = '';
     }
     $whiteIPs = array();
     foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['whitelisted'])) as $whiteIP) {
         if (strlen($whiteIP) > 0) {
             array_push($whiteIPs, $whiteIP);
         }
     }
     if (sizeof($whiteIPs) > 0) {
         $badWhiteIPs = array();
         foreach ($whiteIPs as $whiteIP) {
             if (!preg_match('/^[\\[\\]\\-\\d]+\\.[\\[\\]\\-\\d]+\\.[\\[\\]\\-\\d]+\\.[\\[\\]\\-\\d]+$/', $whiteIP)) {
                 array_push($badWhiteIPs, $whiteIP);
             }
         }
         if (sizeof($badWhiteIPs) > 0) {
             return array('errorMsg' => "Please make sure you separate your IP addresses with commas. The following whitelisted IP addresses are invalid: " . htmlentities(implode(', ', $badWhiteIPs)));
         }
         $opts['whitelisted'] = implode(',', $whiteIPs);
     } else {
         $opts['whitelisted'] = '';
     }
     $validUsers = array();
     $invalidUsers = array();
     foreach (explode(',', $opts['liveTraf_ignoreUsers']) as $val) {
         $val = trim($val);
         if (strlen($val) > 0) {
             if (get_user_by('login', $val)) {
                 array_push($validUsers, $val);
             } else {
                 array_push($invalidUsers, $val);
             }
         }
     }
     $opts['apiKey'] = trim($opts['apiKey']);
     if ($opts['apiKey'] && !preg_match('/^[a-fA-F0-9]+$/', $opts['apiKey'])) {
         //User entered something but it's garbage.
         return array('errorMsg' => "You entered an API key but it is not in a valid format. It must consist only of characters A to F and 0 to 9.");
     }
     if (sizeof($invalidUsers) > 0) {
         return array('errorMsg' => "The following users you selected to ignore in live traffic reports are not valid on this system: " . htmlentities(implode(', ', $invalidUsers)));
     }
     if (sizeof($validUsers) > 0) {
         $opts['liveTraf_ignoreUsers'] = implode(',', $validUsers);
     } else {
         $opts['liveTraf_ignoreUsers'] = '';
     }
     $validIPs = array();
     $invalidIPs = array();
     foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['liveTraf_ignoreIPs'])) as $val) {
         if (strlen($val) > 0) {
             if (preg_match('/^\\d+\\.\\d+\\.\\d+\\.\\d+$/', $val)) {
                 array_push($validIPs, $val);
             } else {
                 array_push($invalidIPs, $val);
             }
         }
     }
     if (sizeof($invalidIPs) > 0) {
         return array('errorMsg' => "The following IPs you selected to ignore in live traffic reports are not valid: " . htmlentities(implode(', ', $invalidIPs)));
     }
     if (sizeof($validIPs) > 0) {
         $opts['liveTraf_ignoreIPs'] = implode(',', $validIPs);
     }
     if (preg_match('/[a-zA-Z0-9\\d]+/', $opts['liveTraf_ignoreUA'])) {
         $opts['liveTraf_ignoreUA'] = trim($opts['liveTraf_ignoreUA']);
     } else {
         $opts['liveTraf_ignoreUA'] = '';
     }
     if (!$opts['other_WFNet']) {
         $wfdb = new wfDB();
         global $wpdb;
         $p = $wpdb->base_prefix;
         $wfdb->queryWrite("delete from {$p}" . "wfBlocks where wfsn=1 and permanent=0");
     }
     if ($opts['howGetIPs'] != wfConfig::get('howGetIPs', '')) {
         $reload = 'reload';
     }
     foreach ($opts as $key => $val) {
         if ($key != 'apiKey') {
             //Don't save API key yet
             wfConfig::set($key, $val);
         }
     }
     $paidKeyMsg = false;
     if (!$opts['apiKey']) {
         //Empty API key (after trim above), then try to get one.
         $api = new wfAPI('', wfUtils::getWPVersion());
         try {
             $keyData = $api->call('get_anon_api_key');
             if ($keyData['ok'] && $keyData['apiKey']) {
                 wfConfig::set('apiKey', $keyData['apiKey']);
                 wfConfig::set('isPaid', 0);
                 $reload = 'reload';
             } else {
                 throw new Exception("We could not understand the Wordfence server's response because it did not contain an 'ok' and 'apiKey' element.");
             }
         } catch (Exception $e) {
             return array('errorMsg' => "Your options have been saved, but we encountered a problem. You left your API key blank, so we tried to get you a free API key from the Wordfence servers. However we encountered a problem fetching the free key: " . htmlentities($e->getMessage()));
         }
     } else {
         if ($opts['apiKey'] != wfConfig::get('apiKey')) {
             $api = new wfAPI($opts['apiKey'], wfUtils::getWPVersion());
             try {
                 $res = $api->call('check_api_key', array(), array());
                 if ($res['ok'] && isset($res['isPaid'])) {
                     wfConfig::set('apiKey', $opts['apiKey']);
                     $reload = 'reload';
                     wfConfig::set('isPaid', $res['isPaid']);
                     //res['isPaid'] is boolean coming back as JSON and turned back into PHP struct. Assuming JSON to PHP handles bools.
                     if ($res['isPaid']) {
                         $paidKeyMsg = true;
                     }
                 } else {
                     throw new Exception("We could not understand the Wordfence API server reply when updating your API key.");
                 }
             } catch (Exception $e) {
                 return array('errorMsg' => "Your options have been saved. However we noticed you changed your API key and we tried to verify it with the Wordfence servers and received an error: " . htmlentities($e->getMessage()));
             }
         }
     }
     return array('ok' => 1, 'reload' => $reload, 'paidKeyMsg' => $paidKeyMsg);
 }
Exemplo n.º 11
0
 public function scan($forkObj)
 {
     if (!$this->startTime) {
         $this->startTime = microtime(true);
     }
     if (!$this->lastStatusTime) {
         $this->lastStatusTime = microtime(true);
     }
     $db = new wfDB();
     $keepGoing = true;
     $limitOffset = 0;
     $queryChunkSize = 1000;
     while ($keepGoing) {
         $keepGoing = false;
         $res1 = $db->querySelect("select filename, filenameMD5, hex(newMD5) as newMD5 from " . $db->prefix() . "wfFileMods where oldMD5 != newMD5 and knownFile=0 limit {$limitOffset} , {$queryChunkSize}");
         if (sizeof($res1) > 0) {
             $keepGoing = true;
             $limitOffset += $queryChunkSize;
         }
         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'];
             $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;
             }
             if (preg_match('/^(?:jpg|jpeg|mp3|avi|m4v|gif|png)$/', $fileExt)) {
                 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) {
                     if (strpos($data, '$allowed' . 'Sites') !== false && strpos($data, "define ('VER" . "SION', '1.") !== false && strpos($data, "TimThum" . "b script created by") !== false) {
                         $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)) {
                             $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => $fileSum, 'shortMsg' => "This file appears to be an attack shell", 'longMsg' => "This file appears to be an executable shell that allows hackers entry to your site via a backdoor. 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;
                         }
                     }
                     /*
                     $longestNospace = wfUtils::longestNospace($data);
                     if($longestNospace > 1000 && (strpos($data, $this->patterns['pat1']) !== false || preg_match('/preg_replace\([^\(]+\/[a-z]*e/', $data)) ){
                     	$this->addResult(array(
                     		'type' => 'file',
                     		'severity' => 1,
                     		'ignoreP' => $this->path . $file,
                     		'ignoreC' => $fileSum,
                     		'shortMsg' => "This file may contain malicious executable code",
                     		'longMsg' => "This file is a PHP executable file and contains a line $longestNospace characters long without spaces that may be encoded data along with functions that may be used to execute that 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 (preg_match($this->patterns['pat2'], $data)) {
                         $this->addResult(array('type' => 'file', 'severity' => 1, 'ignoreP' => $this->path . $file, 'ignoreC' => $fileSum, 'shortMsg' => "This file may contain malicious executable code", '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;
                     }
                     $this->urlHoover->hoover($file, $data);
                 } else {
                     $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;
     }
     foreach ($hooverResults as $file => $hresults) {
         foreach ($hresults as $result) {
             if ($result['badList'] == 'goog-malware-shavar') {
                 $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') {
                     $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;
 }