public static function doNotCache() { header("Cache-Control: no-cache, must-revalidate"); header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); //In the past if (!defined('DONOTCACHEPAGE')) { define('DONOTCACHEPAGE', true); } if (!defined('DONOTCACHEDB')) { define('DONOTCACHEDB', true); } if (!defined('DONOTCDN')) { define('DONOTCDN', true); } if (!defined('DONOTCACHEOBJECT')) { define('DONOTCACHEOBJECT', true); } wfCache::doNotCache(); }
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; } }
public function blockIP($IP, $reason, $wfsn = false, $permanent = false, $maxTimeBlocked = false) { //wfsn indicates it comes from Wordfence secure network if ($this->isWhitelisted($IP)) { return false; } $wfsn = $wfsn ? 1 : 0; $timeBlockOccurred = $this->getDB()->querySingle("select unix_timestamp() as ctime"); $durationOfBlocks = wfConfig::get('blockedTime'); if ($maxTimeBlocked && $durationOfBlocks > $maxTimeBlocked) { $timeBlockOccurred -= $durationOfBlocks - $maxTimeBlocked; } if ($permanent) { //Insert permanent=1 or update existing perm or non-per block to be permanent $this->getDB()->queryWrite("insert into " . $this->blocksTable . " (IP, blockedTime, reason, wfsn, permanent) values (%s, %d, '%s', %d, %d) ON DUPLICATE KEY update blockedTime=%d, reason='%s', wfsn=%d, permanent=%d", wfUtils::inet_pton($IP), $timeBlockOccurred, $reason, $wfsn, 1, $timeBlockOccurred, $reason, $wfsn, 1); } else { //insert perm=0 but don't update and make perm blocks non-perm. $this->getDB()->queryWrite("insert into " . $this->blocksTable . " (IP, blockedTime, reason, wfsn, permanent) values (%s, %d, '%s', %d, %d) ON DUPLICATE KEY update blockedTime=%d, reason='%s', wfsn=%d", wfUtils::inet_pton($IP), $timeBlockOccurred, $reason, $wfsn, 0, $timeBlockOccurred, $reason, $wfsn); } wfActivityReport::logBlockedIP($IP); wfCache::updateBlockedIPs('add'); wfConfig::inc('totalIPsBlocked'); return true; }
/** * */ public static function ajax_disableDirectoryListing_callback() { $issueID = absint($_POST['issueID']); $wfIssues = new wfIssues(); $issue = $wfIssues->getIssueByID($issueID); if (!$issue) { return array('err' => 1, 'errorMsg' => "We could not find that issue in our database."); } $wfIssues->deleteIssue($issueID); $htaccessPath = wfCache::getHtaccessPath(); if (!$htaccessPath) { return array('err' => 1, 'errorMsg' => "Wordfence could not find your .htaccess file."); } $fileContents = file_get_contents($htaccessPath); if (file_put_contents($htaccessPath, "# Added by Wordfence " . date('r') . "\nOptions -Indexes\n\n" . $fileContents, LOCK_EX)) { $uploadPaths = wp_upload_dir(); if (!wfScanEngine::isDirectoryListingEnabled($uploadPaths['baseurl'])) { return array('ok' => 1); } else { // Revert any changes done to .htaccess file_put_contents($htaccessPath, $fileContents, LOCK_EX); return array('err' => 1, 'errorMsg' => "Updating the .htaccess did not fix the issue. You may need to add <code>Options -Indexes</code>\nto your httpd.conf if using Apache, or find documentation on how to disable directory listing for your web server."); } } return array('err' => 1, 'errorMsg' => "There was an error writing to your .htaccess file."); }
public static function clearPageCache() { //If a clear is in progress this does nothing. self::$cacheStats = array('dirsDeleted' => 0, 'filesDeleted' => 0, 'totalData' => 0, 'totalErrors' => 0); $cacheClearLock = WP_CONTENT_DIR . '/wfcache/clear.lock'; if (!is_file($cacheClearLock)) { touch($cacheClearLock); } $fp = fopen($cacheClearLock, 'w'); if (!$fp) { return; } if (flock($fp, LOCK_EX | LOCK_NB)) { //non blocking exclusive flock attempt. If we get a lock then it continues and returns true. If we don't lock, then return false, don't block and don't clear the cache. // This logic means that if a cache clear is currently in progress we don't try to clear the cache. // This prevents web server children from being queued up waiting to be able to also clear the cache. self::recursiveDelete(WP_CONTENT_DIR . '/wfcache/'); flock($fp, LOCK_UN); } fclose($fp); return self::$cacheStats; }
public static function recursiveDelete($dir) { $files = array_diff(scandir($dir), array('.', '..')); foreach ($files as $file) { if (is_dir($dir . '/' . $file)) { if (!self::recursiveDelete($dir . '/' . $file)) { return false; } } else { if ($file == 'clear.lock') { continue; } //Don't delete our lock file $size = filesize($dir . '/' . $file); if ($size) { self::$cacheStats['totalData'] += round($size / 1024); } if (strpos($dir, 'wfcache/') === false) { self::$lastRecursiveDeleteError = "Not deleting file in directory {$dir} because it appears to be in the wrong path."; self::$cacheStats['totalErrors']++; return false; //Safety check that we're in a subdir of the cache } if (@unlink($dir . '/' . $file)) { self::$cacheStats['filesDeleted']++; } else { self::$lastRecursiveDeleteError = "Could not delete file " . $dir . "/" . $file . " : " . wfUtils::getLastError(); self::$cacheStats['totalErrors']++; return false; } } } if ($dir != WP_CONTENT_DIR . '/wfcache/') { if (strpos($dir, 'wfcache/') === false) { self::$lastRecursiveDeleteError = "Not deleting directory {$dir} because it appears to be in the wrong path."; self::$cacheStats['totalErrors']++; return false; //Safety check that we're in a subdir of the cache } if (@rmdir($dir)) { self::$cacheStats['dirsDeleted']++; } else { self::$lastRecursiveDeleteError = "Could not delete directory {$dir} : " . wfUtils::getLastError(); self::$cacheStats['totalErrors']++; return false; } return true; } else { return true; } }
public static function doNotCache() { //Call this to prevent Wordfence from caching the current page. wfCache::doNotCache(); return true; }
public static function htaccess() { $htaccess = wfCache::getHtaccessPath(); if (is_readable($htaccess) && !wfUtils::isNginx()) { return file_get_contents($htaccess); } return ""; }
public function blockIP($IP, $reason, $wfsn = false, $permanent = false, $maxTimeBlocked = false) { //wfsn indicates it comes from Wordfence secure network if ($this->isWhitelisted($IP)) { return false; } $wfsn = $wfsn ? 1 : 0; $timeBlockOccurred = $this->getDB()->querySingle("select unix_timestamp() as ctime"); $durationOfBlocks = wfConfig::get('blockedTime'); if ($maxTimeBlocked && $durationOfBlocks > $maxTimeBlocked) { $timeBlockOccurred -= $durationOfBlocks - $maxTimeBlocked; } if ($permanent) { //Insert permanent=1 or update existing perm or non-per block to be permanent $this->getDB()->queryWrite("insert into " . $this->blocksTable . " (IP, blockedTime, reason, wfsn, permanent) values (%s, %d, '%s', %d, %d) ON DUPLICATE KEY update blockedTime=%d, reason='%s', wfsn=%d, permanent=%d", wfUtils::inet_pton($IP), $timeBlockOccurred, $reason, $wfsn, 1, $timeBlockOccurred, $reason, $wfsn, 1); } else { //insert perm=0 but don't update and make perm blocks non-perm. $this->getDB()->queryWrite("insert into " . $this->blocksTable . " (IP, blockedTime, reason, wfsn, permanent) values (%s, %d, '%s', %d, %d) ON DUPLICATE KEY update blockedTime=%d, reason='%s', wfsn=%d", wfUtils::inet_pton($IP), $timeBlockOccurred, $reason, $wfsn, 0, $timeBlockOccurred, $reason, $wfsn); } wfActivityReport::logBlockedIP($IP); if ($this->currentRequest !== null) { $this->currentRequest->statusCode = 403; $this->currentRequest->action = 'blocked:' . ($wfsn ? 'wfsn' : 'wordfence'); $this->currentRequest->actionDescription = $reason; } wfCache::updateBlockedIPs('add'); wfConfig::inc('totalIPsBlocked'); if (!WFWAF_SUBDIRECTORY_INSTALL && class_exists('wfWAFIPBlocksController')) { wfWAFIPBlocksController::synchronizeConfigSettings(); } return true; }
function wordfence_clean_falcon_cache() { if (class_exists('wfCache') && method_exists('wfCache', 'clearPageCache') && is_callable(array('wfCache', 'clearPageCache'))) { wfCache::clearPageCache(); } }
public static function ajax_addCacheExclusion_callback() { $ex = wfConfig::get('cacheExclusions', false); if ($ex) { $ex = unserialize($ex); } else { $ex = array(); } $ex[] = array('pt' => $_POST['patternType'], 'p' => $_POST['pattern'], 'id' => microtime(true)); wfConfig::set('cacheExclusions', serialize($ex)); wfCache::scheduleCacheClear(); return array('ok' => 1); }
public function testWfCache() { $result = wfCache::cacheDirectoryTest(); return array('test' => $result === false, 'message' => is_string($result) ? $result : 'OK'); }
public static function ajax_removeCacheExclusion_callback() { $id = $_POST['id']; $ex = wfConfig::get('cacheExclusions', false); if (!$ex) { return array('ok' => 1); } $ex = unserialize($ex); $rewriteHtaccess = false; for ($i = 0; $i < sizeof($ex); $i++) { if ((string) $ex[$i]['id'] == (string) $id) { if (wfConfig::get('cacheType', false) == 'falcon' && preg_match('/^(?:uac|uaeq|cc)$/', $ex[$i]['pt'])) { $rewriteHtaccess = true; } array_splice($ex, $i, 1); //Dont break in case of dups } } wfConfig::set('cacheExclusions', serialize($ex)); if ($rewriteHtaccess && wfCache::addHtaccessCode('add')) { //rewrites htaccess rules return array('errorMsg', "We removed that rule but could not rewrite your .htaccess file. You're going to have to manually remove this rule from your .htaccess file. Please reload this page now."); } return array('ok' => 1); }