예제 #1
0
 protected function getURL($url, $postParams = array())
 {
     wordfence::status(4, 'info', "Calling Wordfence API v" . WORDFENCE_API_VERSION . ":" . $url);
     if (!function_exists('wp_remote_post')) {
         require_once ABSPATH . WPINC . 'http.php';
     }
     $ssl_verify = (bool) wfConfig::get('ssl_verify');
     $args = array('timeout' => 900, 'user-agent' => "Wordfence.com UA " . (defined('WORDFENCE_VERSION') ? WORDFENCE_VERSION : '[Unknown version]'), 'body' => $postParams, 'sslverify' => $ssl_verify);
     if (!$ssl_verify) {
         // Some versions of cURL will complain that SSL verification is disabled but the CA bundle was supplied.
         $args['sslcertificates'] = false;
     }
     $response = wp_remote_post($url, $args);
     $this->lastHTTPStatus = (int) wp_remote_retrieve_response_code($response);
     if (is_wp_error($response)) {
         $error_message = $response->get_error_message();
         throw new Exception("There was an " . ($error_message ? '' : 'unknown ') . "error connecting to the the Wordfence scanning servers" . ($error_message ? ": {$error_message}" : '.'));
     }
     if (!empty($response['response']['code'])) {
         $this->lastHTTPStatus = (int) $response['response']['code'];
     }
     if (200 != $this->lastHTTPStatus) {
         throw new Exception("We received an error response when trying to contact the Wordfence scanning servers. The HTTP status code was [{$this->lastHTTPStatus}]");
     }
     $this->curlContent = wp_remote_retrieve_body($response);
     return $this->curlContent;
 }
예제 #2
0
 function scan()
 {
     if ($this->_checkWordFence()) {
         return wordfence::ajax_scan_callback();
     } else {
         return array('error' => "Word Fence plugin is not activated", 'error_code' => 'wordfence_plugin_is_not_activated');
     }
 }
예제 #3
0
	protected function getURL($url, $postParams = array()){
		if(function_exists('curl_init')){
			$this->curlDataWritten = 0;
			$this->curlContent = "";
			$curl = curl_init($url);
			if(defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT') && wfUtils::hostNotExcludedFromProxy($url) ){
				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, array($this, 'curlWrite'));
			curl_setopt($curl, CURLOPT_POST, true);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $postParams);
			wordfence::status(4, 'info', "CURL fetching URL: " . $url);
			curl_exec($curl);

			$httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
			$this->lastCurlErrorNo = curl_errno($curl);
			if($httpStatus == 200){
				curl_close($curl);
				return $this->curlContent;
			} else {
				$cerror = curl_error($curl);
				curl_close($curl);
				throw new Exception("We received an error response when trying to contact the Wordfence scanning servers. The HTTP status code was [$httpStatus] and the curl error number was [" . $this->lastCurlErrorNo . "] " . ($cerror ? (' and the error from CURL was: ' . $cerror) : ''));
			}
		} else {
			wordfence::status(4, 'info', "Fetching URL with file_get: " . $url);
			$data = $this->fileGet($url, $postParams);
			if($data === false){
				$err = error_get_last();
				if($err){
					throw new Exception("We received an error response when trying to contact the Wordfence scanning servers using PHP's file_get_contents function. The error was: " . var_export($err, true));
				} else {
					throw new Exception("We received an empty response when trying to contact the Wordfence scanning servers using PHP's file_get_contents function.");
				}
			}
			return $data;
		}

	}
예제 #4
0
 protected function getURL($url, $postParams = array())
 {
     wordfence::status(4, 'info', "Calling Wordfence API v" . WORDFENCE_API_VERSION . ":" . $url);
     if (!function_exists('wp_remote_post')) {
         require_once ABSPATH . WPINC . 'http.php';
     }
     $response = wp_remote_post($url, array('timeout' => 900, 'user-agent' => "Wordfence.com UA " . (defined('WORDFENCE_VERSION') ? WORDFENCE_VERSION : '[Unknown version]'), 'body' => $postParams));
     $this->lastHTTPStatus = (int) wp_remote_retrieve_response_code($response);
     if (is_wp_error($response)) {
         $error_message = $response->get_error_message();
         throw new Exception("There was an " . ($error_message ? '' : 'unknown ') . "error connecting to the the Wordfence scanning servers" . ($error_message ? ": {$error_message}" : '.'));
     }
     if (!empty($response['response']['code'])) {
         $this->lastHTTPStatus = (int) $response['response']['code'];
     }
     if (200 != $this->lastHTTPStatus) {
         throw new Exception("We received an error response when trying to contact the Wordfence scanning servers. The HTTP status code was [{$this->lastHTTPStatus}]");
     }
     $this->curlContent = wp_remote_retrieve_body($response);
     return $this->curlContent;
 }
예제 #5
0
 private function processFile($realFile)
 {
     $file = substr($realFile, $this->striplen);
     if (!$this->stoppedOnFile && microtime(true) - $this->startTime > $this->engine->maxExecTime) {
         //max X seconds but don't allow fork if we're looking for the file we stopped on. Search mode is VERY fast.
         $this->stoppedOnFile = $file;
         wordfence::status(4, 'info', "Calling fork() from wordfenceHash::processFile with maxExecTime: " . $this->engine->maxExecTime);
         $this->engine->fork();
         //exits
     }
     //Put this after the fork, that way we will at least scan one more file after we fork if it takes us more than 10 seconds to search for the stoppedOnFile
     if ($this->stoppedOnFile && $file != $this->stoppedOnFile) {
         return;
     } else {
         if ($this->stoppedOnFile && $file == $this->stoppedOnFile) {
             $this->stoppedOnFile = false;
             //Continue scanning
         }
     }
     if (wfUtils::fileTooBig($realFile)) {
         wordfence::status(4, 'info', "Skipping file larger than max size: {$realFile}");
         return;
     }
     if (function_exists('memory_get_usage')) {
         wordfence::status(4, 'info', "Scanning: {$realFile} (Mem:" . sprintf('%.1f', memory_get_usage(true) / (1024 * 1024)) . "M)");
     } else {
         wordfence::status(4, 'info', "Scanning: {$realFile}");
     }
     $wfHash = self::wfHash($realFile);
     if ($wfHash) {
         $md5 = strtoupper($wfHash[0]);
         $shac = strtoupper($wfHash[1]);
         $knownFile = 0;
         if ($this->malwareEnabled && $this->isMalwarePrefix($md5)) {
             $this->possibleMalware[] = array($file, $md5);
         }
         if (isset($this->knownFiles['core'][$file])) {
             if (strtoupper($this->knownFiles['core'][$file]) == $shac) {
                 $knownFile = 1;
             } else {
                 if ($this->coreEnabled) {
                     $localFile = ABSPATH . '/' . preg_replace('/^[\\.\\/]+/', '', $file);
                     $fileContents = @file_get_contents($localFile);
                     if ($fileContents && !preg_match('/<\\?' . 'php[\\r\\n\\s\\t]*\\/\\/[\\r\\n\\s\\t]*Silence is golden\\.[\\r\\n\\s\\t]*(?:\\?>)?[\\r\\n\\s\\t]*$/s', $fileContents)) {
                         //<?php
                         if (!$this->isSafeFile($shac)) {
                             $this->haveIssues['core'] = true;
                             $this->engine->addIssue('file', 1, 'coreModified' . $file . $md5, 'coreModified' . $file, 'WordPress core file modified: ' . $file, "This WordPress core file has been modified and differs from the original file distributed with this version of WordPress.", array('file' => $file, 'cType' => 'core', 'canDiff' => true, 'canFix' => true, 'canDelete' => false));
                         }
                     }
                 }
             }
         } else {
             if (isset($this->knownFiles['plugins'][$file])) {
                 if (in_array($shac, $this->knownFiles['plugins'][$file])) {
                     $knownFile = 1;
                 } else {
                     if ($this->pluginsEnabled) {
                         if (!$this->isSafeFile($shac)) {
                             $itemName = $this->knownFiles['plugins'][$file][0];
                             $itemVersion = $this->knownFiles['plugins'][$file][1];
                             $cKey = $this->knownFiles['plugins'][$file][2];
                             $this->haveIssues['plugins'] = true;
                             $this->engine->addIssue('file', 2, 'modifiedplugin' . $file . $md5, 'modifiedplugin' . $file, 'Modified plugin file: ' . $file, "This file belongs to plugin \"{$itemName}\" version \"{$itemVersion}\" and has been modified from the file that is distributed by WordPress.org for this version. Please use the link to see how the file has changed. If you have modified this file yourself, you can safely ignore this warning. If you see a lot of changed files in a plugin that have been made by the author, then try uninstalling and reinstalling the plugin to force an upgrade. Doing this is a workaround for plugin authors who don't manage their code correctly. [See our FAQ on www.wordfence.com for more info]", array('file' => $file, 'cType' => 'plugin', 'canDiff' => true, 'canFix' => true, 'canDelete' => false, 'cName' => $itemName, 'cVersion' => $itemVersion, 'cKey' => $cKey));
                         }
                     }
                 }
             } else {
                 if (isset($this->knownFiles['themes'][$file])) {
                     if (in_array($shac, $this->knownFiles['themes'][$file])) {
                         $knownFile = 1;
                     } else {
                         if ($this->themesEnabled) {
                             if (!$this->isSafeFile($shac)) {
                                 $itemName = $this->knownFiles['themes'][$file][0];
                                 $itemVersion = $this->knownFiles['themes'][$file][1];
                                 $cKey = $this->knownFiles['themes'][$file][2];
                                 $this->haveIssues['themes'] = true;
                                 $this->engine->addIssue('file', 2, 'modifiedtheme' . $file . $md5, 'modifiedtheme' . $file, 'Modified theme file: ' . $file, "This file belongs to theme \"{$itemName}\" version \"{$itemVersion}\" and has been modified from the original distribution. It is common for site owners to modify their theme files, so if you have modified this file yourself you can safely ignore this warning.", array('file' => $file, 'cType' => 'theme', 'canDiff' => true, 'canFix' => true, 'canDelete' => false, 'cName' => $itemName, 'cVersion' => $itemVersion, 'cKey' => $cKey));
                             }
                         }
                     }
                 }
             }
         }
         // knownFile means that the file is both part of core or a known plugin or theme AND that we recognize the file's hash.
         // we could split this into files who's path we recognize and file's who's path we recognize AND who have a valid sig.
         // But because we want to scan files who's sig we don't recognize, regardless of known path or not, we only need one "knownFile" field.
         $this->db->queryWrite("insert into " . $this->db->prefix() . "wfFileMods (filename, filenameMD5, knownFile, oldMD5, newMD5) values ('%s', unhex(md5('%s')), %d, '', unhex('%s')) ON DUPLICATE KEY UPDATE newMD5=unhex('%s'), knownFile=%d", $file, $file, $knownFile, $md5, $md5, $knownFile);
         //Now that we know we can open the file, lets update stats
         if (preg_match('/\\.(?:js|html|htm|css)$/i', $realFile)) {
             $this->linesOfJCH += sizeof(file($realFile));
         } else {
             if (preg_match('/\\.php$/i', $realFile)) {
                 $this->linesOfPHP += sizeof(file($realFile));
             }
         }
         $this->totalFiles++;
         $this->totalData += filesize($realFile);
         //We already checked if file overflows int in the fileTooBig routine above
         if ($this->totalFiles % 100 === 0) {
             wordfence::status(2, 'info', "Analyzed " . $this->totalFiles . " files containing " . wfUtils::formatBytes($this->totalData) . " of data so far");
         }
     } else {
         //wordfence::status(2, 'error', "Could not gen hash for file (probably because we don't have permission to access the file): $realFile");
     }
 }
 public static function autoUpdate()
 {
     try {
         if (getenv('noabort') != '1' && stristr($_SERVER['SERVER_SOFTWARE'], 'litespeed') !== false) {
             $lastEmail = self::get('lastLiteSpdEmail', false);
             if (!$lastEmail || time() - (int) $lastEmail > 86400 * 30) {
                 self::set('lastLiteSpdEmail', time());
                 wordfence::alert("Wordfence Upgrade not run. Please modify your .htaccess", "To preserve the integrity of your website we are not running Wordfence auto-update.\n" . "You are running the LiteSpeed web server which has been known to cause a problem with Wordfence auto-update.\n" . "Please go to your website now and make a minor change to your .htaccess to fix this.\n" . "You can find out how to make this change at:\n" . "https://support.wordfence.com/solution/articles/1000129050-running-wordfence-under-litespeed-web-server-and-preventing-process-killing-or\n" . "\nAlternatively you can disable auto-update on your website to stop receiving this message and upgrade Wordfence manually.\n", '127.0.0.1');
             }
             return;
         }
         require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
         require_once ABSPATH . 'wp-admin/includes/misc.php';
         /* We were creating show_message here so that WP did not write to STDOUT. This had the strange effect of throwing an error about redeclaring show_message function, but only when a crawler hit the site and triggered the cron job. Not a human. So we're now just require'ing misc.php which does generate output, but that's OK because it is a loopback cron request.  
         			if(! function_exists('show_message')){ 
         				function show_message($msg = 'null'){}
         			}
         			*/
         define('FS_METHOD', 'direct');
         require_once ABSPATH . 'wp-includes/update.php';
         require_once ABSPATH . 'wp-admin/includes/file.php';
         wp_update_plugins();
         ob_start();
         $upgrader = new Plugin_Upgrader();
         $upret = $upgrader->upgrade('wordfence/wordfence.php');
         if ($upret) {
             $cont = file_get_contents(WP_PLUGIN_DIR . '/wordfence/wordfence.php');
             if (wfConfig::get('alertOn_update') == '1' && preg_match('/Version: (\\d+\\.\\d+\\.\\d+)/', $cont, $matches)) {
                 wordfence::alert("Wordfence Upgraded to version " . $matches[1], "Your Wordfence installation has been upgraded to version " . $matches[1], '127.0.0.1');
             }
         }
         $output = @ob_get_contents();
         @ob_end_clean();
     } catch (Exception $e) {
     }
 }
예제 #7
0
 /**
  * @param string $file
  * @return array
  */
 private function dataForFile($file, $fullPath = null)
 {
     $loader = $this->scanEngine->getKnownFilesLoader();
     $data = array();
     if ($isKnownFile = $loader->isKnownFile($file)) {
         if ($loader->isKnownCoreFile($file)) {
             $data['cType'] = 'core';
         } else {
             if ($loader->isKnownPluginFile($file)) {
                 $data['cType'] = 'plugin';
                 list($itemName, $itemVersion, $cKey) = $loader->getKnownPluginData($file);
                 $data = array_merge($data, array('cName' => $itemName, 'cVersion' => $itemVersion, 'cKey' => $cKey));
             } else {
                 if ($loader->isKnownThemeFile($file)) {
                     $data['cType'] = 'theme';
                     list($itemName, $itemVersion, $cKey) = $loader->getKnownThemeData($file);
                     $data = array_merge($data, array('cName' => $itemName, 'cVersion' => $itemVersion, 'cKey' => $cKey));
                 }
             }
         }
     }
     $suppressDelete = false;
     $canRegenerate = false;
     if ($fullPath !== null) {
         $bootstrapPath = wordfence::getWAFBootstrapPath();
         $htaccessPath = get_home_path() . '.htaccess';
         $userIni = ini_get('user_ini.filename');
         $userIniPath = false;
         if ($userIni) {
             $userIniPath = get_home_path() . $userIni;
         }
         if ($fullPath == $htaccessPath) {
             $suppressDelete = true;
         } else {
             if ($userIniPath !== false && $fullPath == $userIniPath) {
                 $suppressDelete = true;
             } else {
                 if ($fullPath == $bootstrapPath) {
                     $suppressDelete = true;
                     $canRegenerate = true;
                 }
             }
         }
     }
     $data['canDiff'] = $isKnownFile;
     $data['canFix'] = $isKnownFile;
     $data['canDelete'] = !$isKnownFile && !$canRegenerate && !$suppressDelete;
     $data['canRegenerate'] = $canRegenerate;
     return $data;
 }
 function restore_file()
 {
     $issueID = $_POST['issueID'];
     $wfIssues = new wfIssues();
     $issue = $wfIssues->getIssueByID($issueID);
     if (!$issue) {
         return array('cerrorMsg' => "We could not find that issue in our database.");
     }
     $dat = $issue['data'];
     $result = wordfence::getWPFileContent($dat['file'], $dat['cType'], isset($dat['cName']) ? $dat['cName'] : '', isset($dat['cVersion']) ? $dat['cVersion'] : '');
     $file = $dat['file'];
     if (isset($result['cerrorMsg']) && $result['cerrorMsg']) {
         return $result;
     } else {
         if (!$result['fileContent']) {
             return array('cerrorMsg' => "We could not get the original file to do a repair.");
         }
     }
     if (preg_match('/\\.\\./', $file)) {
         return array('cerrorMsg' => "An invalid file was specified for repair.");
     }
     $localFile = ABSPATH . '/' . preg_replace('/^[\\.\\/]+/', '', $file);
     $fh = fopen($localFile, 'w');
     if (!$fh) {
         $err = error_get_last();
         if (preg_match('/Permission denied/i', $err['message'])) {
             $errMsg = "You don't have permission to repair that file. You need to either fix the file manually using FTP or change the file permissions and ownership so that your web server has write access to repair the file.";
         } else {
             $errMsg = "We could not write to that file. The error was: " . $err['message'];
         }
         return array('cerrorMsg' => $errMsg);
     }
     flock($fh, LOCK_EX);
     $bytes = fwrite($fh, $result['fileContent']);
     flock($fh, LOCK_UN);
     fclose($fh);
     if ($bytes < 1) {
         return array('cerrorMsg' => "We could not write to that file. ({$bytes} bytes written) You may not have permission to modify files on your WordPress server.");
     }
     $wfIssues->updateIssue($issueID, 'delete');
     return array('ok' => 1, 'file' => $localFile);
 }
예제 #9
0
 public static function getIPsGeo($IPs)
 {
     //works with int or dotted. Outputs same format it receives.
     $IPs = array_unique($IPs);
     $toResolve = array();
     $db = new wfDB();
     global $wpdb;
     $locsTable = $wpdb->base_prefix . 'wfLocs';
     $IPLocs = array();
     foreach ($IPs as $IP) {
         $isBinaryIP = !self::isValidIP($IP);
         if ($isBinaryIP) {
             $ip_printable = wfUtils::inet_ntop($IP);
             $ip_bin = $IP;
         } else {
             $ip_printable = $IP;
             $ip_bin = wfUtils::inet_pton($IP);
         }
         $row = $db->querySingleRec("select IP, ctime, failed, city, region, countryName, countryCode, lat, lon, unix_timestamp() - ctime as age from " . $locsTable . " where IP=%s", $ip_bin);
         if ($row) {
             if ($row['age'] > WORDFENCE_MAX_IPLOC_AGE) {
                 $db->queryWrite("delete from " . $locsTable . " where IP=%s", $row['IP']);
             } else {
                 if ($row['failed'] == 1) {
                     $IPLocs[$ip_printable] = false;
                 } else {
                     $row['IP'] = self::inet_ntop($row['IP']);
                     $IPLocs[$ip_printable] = $row;
                 }
             }
         }
         if (!isset($IPLocs[$ip_printable])) {
             $toResolve[] = $ip_printable;
         }
     }
     if (sizeof($toResolve) > 0) {
         $api = new wfAPI(wfConfig::get('apiKey'), wfUtils::getWPVersion());
         try {
             $freshIPs = $api->call('resolve_ips', array(), array('ips' => implode(',', $toResolve)));
             if (is_array($freshIPs)) {
                 foreach ($freshIPs as $IP => $value) {
                     $IP_bin = wfUtils::inet_pton($IP);
                     if ($value == 'failed') {
                         $db->queryWrite("insert IGNORE into " . $locsTable . " (IP, ctime, failed) values (%s, unix_timestamp(), 1)", $IP_bin);
                         $IPLocs[$IP] = false;
                     } else {
                         if (is_array($value)) {
                             for ($i = 0; $i <= 5; $i++) {
                                 //Prevent warnings in debug mode about uninitialized values
                                 if (!isset($value[$i])) {
                                     $value[$i] = '';
                                 }
                             }
                             $db->queryWrite("insert IGNORE into " . $locsTable . " (IP, ctime, failed, city, region, countryName, countryCode, lat, lon) values (%s, unix_timestamp(), 0, '%s', '%s', '%s', '%s', %s, %s)", $IP_bin, $value[3], $value[2], $value[1], $value[0], $value[4], $value[5]);
                             $IPLocs[$IP] = array('IP' => $IP, 'city' => $value[3], 'region' => $value[2], 'countryName' => $value[1], 'countryCode' => $value[0], 'lat' => $value[4], 'lon' => $value[5]);
                         }
                     }
                 }
             }
         } catch (Exception $e) {
             wordfence::status(2, 'error', "Call to Wordfence API to resolve IPs failed: " . $e->getMessage());
             return array();
         }
     }
     return $IPLocs;
 }
 private function writeScanningStatus()
 {
     wordfence::status(2, 'info', "Scanned contents of " . $this->totalFilesScanned . " additional files at " . sprintf('%.2f', $this->totalFilesScanned / (microtime(true) - $this->startTime)) . " per second");
 }
예제 #11
0
 public function uninstall()
 {
     /** @var WP_Filesystem_Base $wp_filesystem */
     global $wp_filesystem;
     $htaccessPath = $this->getHtaccessPath();
     $userIniPath = $this->getUserIniPath();
     $adminURL = admin_url('/');
     $allow_relaxed_file_ownership = true;
     $homePath = dirname($htaccessPath);
     ob_start();
     if (false === ($credentials = request_filesystem_credentials($adminURL, '', false, $homePath, array('version', 'locale'), $allow_relaxed_file_ownership))) {
         ob_end_clean();
         return false;
     }
     if (!WP_Filesystem($credentials, $homePath, $allow_relaxed_file_ownership)) {
         // Failed to connect, Error and request again
         request_filesystem_credentials($adminURL, '', true, ABSPATH, array('version', 'locale'), $allow_relaxed_file_ownership);
         ob_end_clean();
         return false;
     }
     if ($wp_filesystem->errors->get_error_code()) {
         ob_end_clean();
         return false;
     }
     ob_end_clean();
     if ($wp_filesystem->is_file($htaccessPath)) {
         $htaccessContent = $wp_filesystem->get_contents($htaccessPath);
         $regex = '/# Wordfence WAF.*?# END Wordfence WAF/is';
         if (preg_match($regex, $htaccessContent, $matches)) {
             $htaccessContent = preg_replace($regex, '', $htaccessContent);
             if (!$wp_filesystem->put_contents($htaccessPath, $htaccessContent)) {
                 return false;
             }
         }
     }
     if ($wp_filesystem->is_file($userIniPath)) {
         $userIniContent = $wp_filesystem->get_contents($userIniPath);
         $regex = '/; Wordfence WAF.*?; END Wordfence WAF/is';
         if (preg_match($regex, $userIniContent, $matches)) {
             $userIniContent = preg_replace($regex, '', $userIniContent);
             if (!$wp_filesystem->put_contents($userIniPath, $userIniContent)) {
                 return false;
             }
         }
     }
     $bootstrapPath = wordfence::getWAFBootstrapPath();
     if ($wp_filesystem->is_file($bootstrapPath)) {
         $wp_filesystem->delete($bootstrapPath);
     }
     return true;
 }
예제 #12
0
 private function processFile($realFile)
 {
     $file = substr($realFile, $this->striplen);
     if (wfUtils::fileTooBig($realFile)) {
         wordfence::status(4, 'info', "Skipping file larger than max size: {$realFile}");
         return;
     }
     if (function_exists('memory_get_usage')) {
         wordfence::status(4, 'info', "Scanning: {$realFile} (Mem:" . sprintf('%.1f', memory_get_usage(true) / (1024 * 1024)) . "M)");
     } else {
         wordfence::status(4, 'info', "Scanning: {$realFile}");
     }
     wfUtils::beginProcessingFile($file);
     $wfHash = self::wfHash($realFile);
     if ($wfHash) {
         $md5 = strtoupper($wfHash[0]);
         $shac = strtoupper($wfHash[1]);
         $knownFile = 0;
         if ($this->malwareEnabled && $this->isMalwarePrefix($md5)) {
             $this->possibleMalware[] = array($file, $md5);
         }
         $knownFileExclude = wordfenceScanner::getExcludeFilePattern(wordfenceScanner::EXCLUSION_PATTERNS_KNOWN_FILES);
         $allowKnownFileScan = true;
         if ($knownFileExclude) {
             $allowKnownFileScan = !preg_match($knownFileExclude, $realFile);
         }
         if ($allowKnownFileScan) {
             if ($this->coreUnknownEnabled && !$this->alertedOnUnknownWordPressVersion && empty($this->knownFiles['core'])) {
                 require ABSPATH . 'wp-includes/version.php';
                 //defines $wp_version
                 $this->alertedOnUnknownWordPressVersion = true;
                 $this->haveIssues['coreUnknown'] = true;
                 $this->engine->addIssue('coreUnknown', 2, 'coreUnknown' . $wp_version, 'coreUnknown' . $wp_version, 'Unknown WordPress core version: ' . $wp_version, "The core files scan will not be run because this version of WordPress is not currently indexed by Wordfence. This may be due to using a prerelease version or because the servers are still indexing a new release. If you are using an official WordPress release, this issue will automatically dismiss once the version is indexed and another scan is run.", array());
             }
             if (isset($this->knownFiles['core'][$file])) {
                 if (strtoupper($this->knownFiles['core'][$file]) == $shac) {
                     $knownFile = 1;
                 } else {
                     if ($this->coreEnabled) {
                         $localFile = ABSPATH . '/' . preg_replace('/^[\\.\\/]+/', '', $file);
                         $fileContents = @file_get_contents($localFile);
                         if ($fileContents && !preg_match('/<\\?' . 'php[\\r\\n\\s\\t]*\\/\\/[\\r\\n\\s\\t]*Silence is golden\\.[\\r\\n\\s\\t]*(?:\\?>)?[\\r\\n\\s\\t]*$/s', $fileContents)) {
                             //<?php
                             if (!$this->isSafeFile($shac)) {
                                 $this->haveIssues['core'] = true;
                                 $this->engine->addIssue('knownfile', 1, 'coreModified' . $file . $md5, 'coreModified' . $file, 'WordPress core file modified: ' . $file, "This WordPress core file has been modified and differs from the original file distributed with this version of WordPress.", array('file' => $file, 'cType' => 'core', 'canDiff' => true, 'canFix' => true, 'canDelete' => false));
                             }
                         }
                     }
                 }
             } else {
                 if (isset($this->knownFiles['plugins'][$file])) {
                     if (in_array($shac, $this->knownFiles['plugins'][$file])) {
                         $knownFile = 1;
                     } else {
                         if ($this->pluginsEnabled) {
                             if (!$this->isSafeFile($shac)) {
                                 $itemName = $this->knownFiles['plugins'][$file][0];
                                 $itemVersion = $this->knownFiles['plugins'][$file][1];
                                 $cKey = $this->knownFiles['plugins'][$file][2];
                                 $this->haveIssues['plugins'] = true;
                                 $this->engine->addIssue('knownfile', 2, 'modifiedplugin' . $file . $md5, 'modifiedplugin' . $file, 'Modified plugin file: ' . $file, "This file belongs to plugin \"{$itemName}\" version \"{$itemVersion}\" and has been modified from the file that is distributed by WordPress.org for this version. Please use the link to see how the file has changed. If you have modified this file yourself, you can safely ignore this warning. If you see a lot of changed files in a plugin that have been made by the author, then try uninstalling and reinstalling the plugin to force an upgrade. Doing this is a workaround for plugin authors who don't manage their code correctly. [See our FAQ on www.wordfence.com for more info]", array('file' => $file, 'cType' => 'plugin', 'canDiff' => true, 'canFix' => true, 'canDelete' => false, 'cName' => $itemName, 'cVersion' => $itemVersion, 'cKey' => $cKey));
                             }
                         }
                     }
                 } else {
                     if (isset($this->knownFiles['themes'][$file])) {
                         if (in_array($shac, $this->knownFiles['themes'][$file])) {
                             $knownFile = 1;
                         } else {
                             if ($this->themesEnabled) {
                                 if (!$this->isSafeFile($shac)) {
                                     $itemName = $this->knownFiles['themes'][$file][0];
                                     $itemVersion = $this->knownFiles['themes'][$file][1];
                                     $cKey = $this->knownFiles['themes'][$file][2];
                                     $this->haveIssues['themes'] = true;
                                     $this->engine->addIssue('knownfile', 2, 'modifiedtheme' . $file . $md5, 'modifiedtheme' . $file, 'Modified theme file: ' . $file, "This file belongs to theme \"{$itemName}\" version \"{$itemVersion}\" and has been modified from the original distribution. It is common for site owners to modify their theme files, so if you have modified this file yourself you can safely ignore this warning.", array('file' => $file, 'cType' => 'theme', 'canDiff' => true, 'canFix' => true, 'canDelete' => false, 'cName' => $itemName, 'cVersion' => $itemVersion, 'cKey' => $cKey));
                                 }
                             }
                         }
                     } else {
                         if ($this->coreUnknownEnabled && !$this->alertedOnUnknownWordPressVersion) {
                             //Check for unknown files in system directories
                             $restrictedWordPressFolders = array(ABSPATH . 'wp-admin/', ABSPATH . WPINC . '/');
                             foreach ($restrictedWordPressFolders as $path) {
                                 if (strpos($realFile, $path) === 0) {
                                     $this->haveIssues['coreUnknown'] = true;
                                     $this->engine->addIssue('knownfile', 2, 'coreUnknown' . $file . $md5, 'coreUnknown' . $file, 'Unknown file in WordPress core: ' . $file, "This file is in a WordPress core location but is not distributed with this version of WordPress. This is usually due to it being left over from a previous WordPress update, but it may also have been added by another plugin or a malicious file added by an attacker.", array('file' => $file, 'cType' => 'core', 'canDiff' => false, 'canFix' => false, 'canDelete' => true));
                                 }
                             }
                         }
                     }
                 }
             }
         }
         // knownFile means that the file is both part of core or a known plugin or theme AND that we recognize the file's hash.
         // we could split this into files who's path we recognize and file's who's path we recognize AND who have a valid sig.
         // But because we want to scan files who's sig we don't recognize, regardless of known path or not, we only need one "knownFile" field.
         $this->db->queryWrite("insert into " . $this->db->prefix() . "wfFileMods (filename, filenameMD5, knownFile, oldMD5, newMD5) values ('%s', unhex(md5('%s')), %d, '', unhex('%s')) ON DUPLICATE KEY UPDATE newMD5=unhex('%s'), knownFile=%d", $file, $file, $knownFile, $md5, $md5, $knownFile);
         $this->totalFiles++;
         $this->totalData += @filesize($realFile);
         //We already checked if file overflows int in the fileTooBig routine above
         if ($this->totalFiles % 100 === 0) {
             wordfence::status(2, 'info', "Analyzed " . $this->totalFiles . " files containing " . wfUtils::formatBytes($this->totalData) . " of data so far");
         }
     } else {
         //wordfence::status(2, 'error', "Could not gen hash for file (probably because we don't have permission to access the file): $realFile");
     }
     wfUtils::endProcessingFile();
 }
예제 #13
0
 public function getBaddies()
 {
     $allHostKeys = array();
     $stime = microtime(true);
     $allHostKeys = array();
     if ($this->useDB) {
         $q1 = $this->db->querySelect("select distinct hostKey as hostKey from {$this->table}");
         foreach ($q1 as $hRec) {
             $allHostKeys[] = $hRec['hostKey'];
         }
     } else {
         $allHostKeys = $this->hostKeys;
     }
     //Now call API and check if any hostkeys are bad.
     //This is a shortcut, because if no hostkeys are bad it saves us having to check URLs
     if (sizeof($allHostKeys) > 0) {
         //If we don't have any hostkeys, then we won't have any URL's to check either.
         //Hostkeys are 4 byte sha256 prefixes
         //Returned value is 2 byte shorts which are array indexes for bad keys that were passed in the original list
         $this->dbg("Checking " . sizeof($allHostKeys) . " hostkeys");
         if ($this->debug) {
             foreach ($allHostKeys as $key) {
                 $this->dbg("Checking hostkey: " . bin2hex($key));
             }
         }
         wordfence::status(2, 'info', "Checking " . sizeof($allHostKeys) . " host keys against Wordfence scanning servers.");
         $resp = $this->api->binCall('check_host_keys', implode('', $allHostKeys));
         wordfence::status(2, 'info', "Done host key check.");
         $this->dbg("Done hostkey check");
         $badHostKeys = array();
         if ($resp['code'] == 200) {
             if (strlen($resp['data']) > 0) {
                 $dataLen = strlen($resp['data']);
                 if ($dataLen % 2 != 0) {
                     $this->errorMsg = "Invalid data length received from Wordfence server: " . $dataLen;
                     return false;
                 }
                 for ($i = 0; $i < $dataLen; $i += 2) {
                     $idxArr = unpack('n', substr($resp['data'], $i, 2));
                     $idx = $idxArr[1];
                     if (isset($allHostKeys[$idx])) {
                         $badHostKeys[] = $allHostKeys[$idx];
                         $this->dbg("Got bad hostkey for record: " . var_export($allHostKeys[$idx], true));
                     } else {
                         $this->dbg("Bad allHostKeys index: {$idx}");
                         $this->errorMsg = "Bad allHostKeys index: {$idx}";
                         return false;
                     }
                 }
             }
         } else {
             $this->errorMsg = "Wordfence server responded with an error. HTTP code " . $resp['code'] . " and data: " . $resp['data'];
             return false;
         }
         if (sizeof($badHostKeys) > 0) {
             $urlsToCheck = array();
             $totalURLs = 0;
             //need to figure out which id's have bad hostkeys
             //need to feed in all URL's from those id's where the hostkey matches a URL
             foreach ($badHostKeys as $badHostKey) {
                 if ($this->useDB) {
                     //Putting a 10000 limit in here for sites that have a huge number of items with the same URL that repeats.
                     // This is an edge case. But if the URLs are malicious then presumably the admin will fix the malicious URLs
                     // and on subsequent scans the items (owners) that are above the 10000 limit will appear.
                     $q1 = $this->db->querySelect("select owner, host, path from {$this->table} where hostKey='%s' limit 10000", $badHostKey);
                     foreach ($q1 as $rec) {
                         $url = 'http://' . $rec['host'] . $rec['path'];
                         if (!isset($urlsToCheck[$rec['owner']])) {
                             $urlsToCheck[$rec['owner']] = array();
                         }
                         if (!in_array($url, $urlsToCheck[$rec['owner']])) {
                             $urlsToCheck[$rec['owner']][] = $url;
                             $totalURLs++;
                         }
                     }
                 } else {
                     foreach ($this->hostList as $rec) {
                         if ($rec['hostKey'] == $badHostKey) {
                             $url = 'http://' . $rec['host'] . $rec['path'];
                             if (!isset($urlsToCheck[$rec['owner']])) {
                                 $urlsToCheck[$rec['owner']] = array();
                             }
                             if (!in_array($url, $urlsToCheck[$rec['owner']])) {
                                 $urlsToCheck[$rec['owner']][] = $url;
                                 $totalURLs++;
                             }
                         }
                     }
                 }
             }
             if (sizeof($urlsToCheck) > 0) {
                 wordfence::status(2, 'info', "Checking " . $totalURLs . " URLs from " . sizeof($urlsToCheck) . " sources.");
                 $badURLs = $this->api->call('check_bad_urls', array(), array('toCheck' => json_encode($urlsToCheck)));
                 wordfence::status(2, 'info', "Done URL check.");
                 $this->dbg("Done URL check");
                 if (is_array($badURLs) && sizeof($badURLs) > 0) {
                     $finalResults = array();
                     foreach ($badURLs as $file => $badSiteList) {
                         if (!isset($finalResults[$file])) {
                             $finalResults[$file] = array();
                         }
                         foreach ($badSiteList as $badSite) {
                             $finalResults[$file][] = array('URL' => $badSite[0], 'badList' => $badSite[1]);
                         }
                     }
                     return $finalResults;
                 } else {
                     return array();
                 }
             } else {
                 return array();
             }
         } else {
             return array();
         }
     } else {
         return array();
     }
 }
예제 #14
0
 private static function status($level, $type, $msg)
 {
     wordfence::status($level, $type, $msg);
 }
예제 #15
0
 public static function set_ser($key, $val, $canUseDisk = false)
 {
     //We serialize some very big values so this is memory efficient. We don't make any copies of $val and don't use ON DUPLICATE KEY UPDATE
     // because we would have to concatenate $val twice into the query which could also exceed max packet for the mysql server
     $serialized = serialize($val);
     $val = '';
     $tempFilename = 'wordfence_tmpfile_' . $key . '.php';
     if (strlen($serialized) * 1.1 > self::getDB()->getMaxAllowedPacketBytes()) {
         //If it's greater than max_allowed_packet + 10% for escaping and SQL
         if ($canUseDisk) {
             $dir = self::getTempDir();
             if ($dir) {
                 $fh = false;
                 $fullFile = $dir . $tempFilename;
                 self::deleteOldTempFile($fullFile);
                 $fh = fopen($fullFile, 'w');
                 if ($fh) {
                     wordfence::status(4, 'info', "Serialized data for {$key} is " . strlen($serialized) . " bytes and is greater than max_allowed packet so writing it to disk file: " . $fullFile);
                 } else {
                     wordfence::status(1, 'error', "Your database doesn't allow big packets so we have to use files to store temporary data and Wordfence can't find a place to write them. Either ask your admin to increase max_allowed_packet on your MySQL database, or make one of the following directories writable by your web server: " . implode(', ', $dirs));
                     return false;
                 }
                 fwrite($fh, self::$tmpFileHeader);
                 fwrite($fh, $serialized);
                 fclose($fh);
                 return true;
             } else {
                 wordfence::status(1, 'error', "Wordfence tried to save a variable with name '{$key}' and your database max_allowed_packet is set to be too small. We then tried to save it to disk, but you don't have a temporary directory that is writable. You can fix this by making the /wp-content/plugins/wordfence/tmp/ directory writable by your web server. Or by increasing your max_allowed_packet configuration variable in your mysql database.");
                 return false;
             }
         } else {
             wordfence::status(1, 'error', "Wordfence tried to save a variable with name '{$key}' and your database max_allowed_packet is set to be too small. This particular variable can't be saved to disk. Please ask your administrator to increase max_allowed_packet and also report this in the Wordfence forums because it may be a bug. Thanks.");
             return false;
         }
     } else {
         //Delete temp files on disk or else the DB will be written to but get_ser will see files on disk and read them instead
         $tempDir = self::getTempDir();
         if ($tempDir) {
             self::deleteOldTempFile($tempDir . $tempFilename);
         }
         $exists = self::getDB()->querySingle("select name from " . self::table() . " where name='%s'", $key);
         if ($exists) {
             self::getDB()->queryWrite("update " . self::table() . " set val=%s where name=%s", $serialized, $key);
         } else {
             self::getDB()->queryWrite("insert IGNORE into " . self::table() . " (name, val) values (%s, %s)", $key, $serialized);
         }
     }
     self::getDB()->flush();
     return true;
 }
예제 #16
0
 public static function autoUpdate()
 {
     try {
         require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
         if (!function_exists('show_message')) {
             function show_message($msg = 'null')
             {
             }
         }
         define('FS_METHOD', 'direct');
         require_once ABSPATH . 'wp-includes/update.php';
         require_once ABSPATH . 'wp-admin/includes/file.php';
         wp_update_plugins();
         ob_start();
         $upgrader = new Plugin_Upgrader();
         $upret = $upgrader->upgrade('wordfence/wordfence.php');
         if ($upret) {
             $cont = file_get_contents(WP_PLUGIN_DIR . '/wordfence/wordfence.php');
             if (wfConfig::get('alertOn_update') == '1' && preg_match('/Version: (\\d+\\.\\d+\\.\\d+)/', $cont, $matches)) {
                 wordfence::alert("Wordfence Upgraded to version " . $matches[1], "Your Wordfence installation has been upgraded to version " . $matches[1], '127.0.0.1');
             }
         }
         $output = ob_get_contents();
         ob_end_clean();
     } catch (Exception $e) {
     }
 }
예제 #17
0
파일: wfCrawl.php 프로젝트: arobbins/davis
 /**
  * Has correct user agent and PTR record points to .googlebot.com domain.
  *
  * @param string|null $ip
  * @param string|null $ua
  * @return bool
  */
 public static function isVerifiedGoogleCrawler($ip = null, $ua = null)
 {
     static $verified;
     if (!isset($verified)) {
         $verified = array();
     }
     if ($ip === null) {
         $ip = wfUtils::getIP();
     }
     if (array_key_exists($ip, $verified)) {
         return $verified[$ip];
     }
     if (self::isGoogleCrawler($ua)) {
         if (self::verifyCrawlerPTR(wordfence::getLog()->getGooglePattern(), $ip)) {
             $verified[$ip] = true;
             return $verified[$ip];
         }
         if (self::verifyGooglebotViaNOC1($ip)) {
             $verified[$ip] = true;
             return $verified[$ip];
         }
     }
     $verified[$ip] = false;
     return $verified[$ip];
 }
예제 #18
0
 private function takeBlockingAction($configVar, $reason)
 {
     if ($this->googleSafetyCheckOK()) {
         $action = wfConfig::get($configVar . '_action');
         if (!$action) {
             //error_log("Wordfence action missing for configVar: $configVar");
             return;
         }
         $secsToGo = 0;
         if ($action == 'block') {
             $IP = wfUtils::getIP();
             $this->blockIP($IP, $reason);
             $secsToGo = wfConfig::get('blockedTime');
             //Moved the following code AFTER the block to prevent multiple emails.
             if (wfConfig::get('alertOn_block')) {
                 wordfence::alert("Blocking IP {$IP}", "Wordfence has blocked IP address {$IP}.\nThe reason is: \"{$reason}\".", $IP);
             }
             wordfence::status(2, 'info', "Blocking IP {$IP}. {$reason}");
         } else {
             if ($action == 'throttle') {
                 $IP = wfUtils::getIP();
                 $this->getDB()->queryWrite("insert into " . $this->throttleTable . " (IP, startTime, endTime, timesThrottled, lastReason) values (%s, unix_timestamp(), unix_timestamp(), 1, '%s') ON DUPLICATE KEY UPDATE endTime=unix_timestamp(), timesThrottled = timesThrottled + 1, lastReason='%s'", wfUtils::inet_pton($IP), $reason, $reason);
                 wordfence::status(2, 'info', "Throttling IP {$IP}. {$reason}");
                 wfConfig::inc('totalIPsThrottled');
                 $secsToGo = 60;
             }
         }
         $this->do503($secsToGo, $reason);
     } else {
         return;
     }
 }
예제 #19
0
    $newestItem = 0;
    $sumEvents = array();
    $timeOffset = 3600 * get_option('gmt_offset');
    foreach ($events as $e) {
        if (strpos($e['msg'], 'SUM_') !== 0) {
            if ($debugOn || $e['level'] < 4) {
                $typeClass = '';
                if ($debugOn) {
                    $typeClass = ' wf' . $e['type'];
                }
                echo '<div class="wfActivityLine' . $typeClass . '">[' . date('M d H:i:s', $e['ctime'] + $timeOffset) . ']&nbsp;' . $e['msg'] . '</div>';
            }
        }
        $newestItem = $e['ctime'];
    }
    echo '<script type="text/javascript">WFAD.lastALogCtime = ' . $newestItem . '; WFAD.processActArray(' . json_encode(wordfence::getLog()->getSummaryEvents()) . ');</script>';
} else {
    ?>
						A live stream of what Wordfence is busy with right now will appear in this box.

					<?php 
}
?>
			</div></div></div>
			<div style="position: relative; width: 803px;">
				&nbsp;
				<a href="#" target="_blank" class="wfALogViewLink" id="wfALogViewLink">View activity log</a>
			</div>
			<div style="margin: 0 0 20px 5px; width: 795px;">
				<strong>Docs:</strong> Our <a href="http://support.wordfence.com/" target="_blank">Support Site</a> can answer many common (and some less common) questions. It also includes our priority support ticketing system for Premium Wordfence users. 
				<?php 
예제 #20
0
 public static function autoUpdate()
 {
     try {
         require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
         require_once ABSPATH . 'wp-admin/includes/misc.php';
         /* We were creating show_message here so that WP did not write to STDOUT. This had the strange effect of throwing an error about redeclaring show_message function, but only when a crawler hit the site and triggered the cron job. Not a human. So we're now just require'ing misc.php which does generate output, but that's OK because it is a loopback cron request.  
         			if(! function_exists('show_message')){ 
         				function show_message($msg = 'null'){}
         			}
         			*/
         define('FS_METHOD', 'direct');
         require_once ABSPATH . 'wp-includes/update.php';
         require_once ABSPATH . 'wp-admin/includes/file.php';
         wp_update_plugins();
         ob_start();
         $upgrader = new Plugin_Upgrader();
         $upret = $upgrader->upgrade('wordfence/wordfence.php');
         if ($upret) {
             $cont = file_get_contents(WP_PLUGIN_DIR . '/wordfence/wordfence.php');
             if (wfConfig::get('alertOn_update') == '1' && preg_match('/Version: (\\d+\\.\\d+\\.\\d+)/', $cont, $matches)) {
                 wordfence::alert("Wordfence Upgraded to version " . $matches[1], "Your Wordfence installation has been upgraded to version " . $matches[1], '127.0.0.1');
             }
         }
         $output = @ob_get_contents();
         @ob_end_clean();
     } catch (Exception $e) {
     }
 }
예제 #21
0
 public static function isDebugOn()
 {
     if (is_null(self::$debugOn)) {
         if (wfConfig::get('debugOn')) {
             self::$debugOn = true;
         } else {
             self::$debugOn = false;
         }
     }
     return self::$debugOn;
 }
예제 #22
0
		<p class="center"><a class="button button-primary"
		                     href="https://www.wordfence.com/gnl1scanSched1/wordfence-signup/">Get Premium</a></p>
	</div>
<?php 
}
?>

	<div class="wordfenceWrap" style="margin: 20px 20px 20px 30px;">
		<p>
			<strong>Current time:</strong>&nbsp;<?php 
echo date('l jS \\of F Y H:i:s A', current_time('timestamp'));
?>
			<br /><strong>Next scan will start at:</strong>&nbsp;
			<span id="wfScanStartTime">
			<?php 
$nextTime = wordfence::getNextScanStartTime();
if ($nextTime) {
    echo $nextTime;
}
?>
			</span>
		</p>
		<p>
			<strong>Scan mode:</strong><select id="schedMode" onchange="WFAD.sched_modeChange();">
				<option value="auto"<?php 
echo wfConfig::get('schedMode') == 'auto' ? ' selected' : '';
?>
>Let Wordfence automatically schedule scans (recommended)</option>
				<option value="manual"<?php 
echo wfConfig::get('schedMode') == 'manual' ? ' selected' : '';
?>
/*
Plugin Name: Wordfence Security
Plugin URI: http://www.wordfence.com/
Description: Wordfence Security - Anti-virus, Firewall and High Speed Cache
Author: Wordfence
Version: 5.3.4
Author URI: http://www.wordfence.com/
*/
if (defined('WP_INSTALLING') && WP_INSTALLING) {
    return;
}
define('WORDFENCE_VERSION', '5.3.4');
if (get_option('wordfenceActivated') != 1) {
    add_action('activated_plugin', 'wordfence_save_activation_error');
    function wordfence_save_activation_error()
    {
        update_option('wf_plugin_act_error', ob_get_contents());
    }
}
if (!defined('WORDFENCE_VERSIONONLY_MODE')) {
    //Used to get version from file.
    if ((int) @ini_get('memory_limit') < 128) {
        if (strpos(ini_get('disable_functions'), 'ini_set') === false) {
            @ini_set('memory_limit', '128M');
            //Some hosts have ini set at as little as 32 megs. 64 is the min sane amount of memory.
        }
    }
    require_once 'lib/wordfenceConstants.php';
    require_once 'lib/wordfenceClass.php';
    wordfence::install_actions();
}
예제 #24
0
	<?php 
require 'menuHeader.php';
?>
	<?php 
$pageTitle = "Wordfence Web Application Firewall";
$helpLink = "http://docs.wordfence.com/en/WAF";
$helpLabel = "Learn more about the Wordfence Web Application Firewall";
include 'pageTitle.php';
?>
	<div class="wordfenceModeElem" id="wordfenceMode_waf"></div>

	<?php 
if (defined('WFWAF_ENABLED') && !WFWAF_ENABLED) {
    $message = 'To allow the firewall to re-enable, please remove this line from the appropriate file.';
    $pattern = '/define\\s*\\(\\s*(?:\'WFWAF_ENABLED\'|"WFWAF_ENABLED")\\s*,(.+?)\\)/x';
    $checkFiles = array(ABSPATH . 'wp-config.php', wordfence::getWAFBootstrapPath());
    foreach ($checkFiles as $path) {
        if (!file_exists($path)) {
            continue;
        }
        if (($contents = file_get_contents($path)) !== false) {
            if (preg_match($pattern, $contents, $matches) && (trim($matches[1]) == 'false' || trim($matches[1]) == '0')) {
                $message = "To allow the firewall to re-enable, please remove this line from the file '" . $path . "'.";
                break;
            }
        }
    }
    ?>
	<p class="wf-notice">The Wordfence Firewall is currently disabled because WFWAF_ENABLED is overridden and set to false. <?php 
    echo $message;
    ?>
예제 #25
0
 /**
  * Generate SQL from the whitelist.  Uses the return format from wfLog::getWhitelistedIPs
  *
  * @see wfLog::getWhitelistedIPs
  * @param array $whitelisted_ips
  * @return string
  */
 public function getBlockedIPWhitelistWhereClause($whitelisted_ips = null)
 {
     if ($whitelisted_ips === null) {
         $whitelisted_ips = wordfence::getLog()->getWhitelistedIPs();
     }
     if (!is_array($whitelisted_ips)) {
         return false;
     }
     $where = '';
     /** @var array|wfUserIPRange|string $ip_range */
     foreach ($whitelisted_ips as $ip_range) {
         if (is_array($ip_range) && count($ip_range) == 2) {
             $where .= $this->db->prepare('IP BETWEEN %s AND %s', $ip_range[0], $ip_range[1]) . ' OR ';
         } elseif (is_a($ip_range, 'wfUserIPRange')) {
             $where .= $ip_range->toSQL('IP') . ' OR ';
         } elseif (is_string($ip_range) || is_numeric($ip_range)) {
             $where .= $this->db->prepare('IP = %s', $ip_range) . ' OR ';
         }
     }
     if ($where) {
         // remove the extra ' OR '
         $where = substr($where, 0, -4);
     }
     return $where;
 }
예제 #26
0
 public static function getMaxExecutionTime()
 {
     $config = wfConfig::get('maxExecutionTime');
     wordfence::status(4, 'info', "Got value from wf config maxExecutionTime: {$config}");
     if (is_numeric($config) && $config >= 10) {
         wordfence::status(4, 'info', "getMaxExecutionTime() returning config value: {$config}");
         return $config;
     }
     $ini = @ini_get('max_execution_time');
     wordfence::status(4, 'info', "Got max_execution_time value from ini: {$ini}");
     if (is_numeric($ini) && $ini >= 10) {
         $ini = floor($ini / 2);
         wordfence::status(4, 'info', "getMaxExecutionTime() returning half ini value: {$ini}");
         return $ini;
     }
     wordfence::status(4, 'info', "getMaxExecutionTime() returning default of: 15");
     return 15;
 }
 public function import_settings()
 {
     $token = $_POST['token'];
     try {
         $totalSet = wordfence::importSettings($token);
         return array('ok' => 1, 'totalSet' => $totalSet, 'settings' => $this->get_settings());
     } catch (Exception $e) {
         return array('errorImport' => "An error occurred: " . $e->getMessage());
     }
 }
예제 #28
0
파일: wfCrawl.php 프로젝트: yszar/linuxwp
 /**
  * Has correct user agent and PTR record points to .googlebot.com domain.
  *
  * @return bool
  */
 public static function isVerifiedGoogleCrawler()
 {
     return self::isGoogleCrawler() && self::verifyCrawlerPTR(wordfence::getLog()->getGooglePattern(), wfUtils::getIP());
 }