コード例 #1
0
ファイル: wordfenceClass.php プロジェクト: ashenkar/sanga
 public static function veryFirstAction()
 {
     /** @var wpdb $wpdb ; */
     global $wpdb;
     $wfFunc = isset($_GET['_wfsf']) ? @$_GET['_wfsf'] : false;
     if ($wfFunc == 'unlockEmail') {
         if (!wp_verify_nonce(@$_POST['nonce'], 'wf-form')) {
             die("Sorry but your browser sent an invalid security token when trying to use this form.");
         }
         $numTries = get_transient('wordfenceUnlockTries');
         if ($numTries > 10) {
             echo "<html><body><h1>Please wait 3 minutes and try again</h1><p>You have used this form too much. Please wait 3 minutes and try again.</p></body></html>";
             exit;
         }
         if (!$numTries) {
             $numTries = 1;
         } else {
             $numTries = $numTries + 1;
         }
         set_transient('wordfenceUnlockTries', $numTries, 180);
         $email = trim($_POST['email']);
         global $wpdb;
         $ws = $wpdb->get_results($wpdb->prepare("SELECT ID, user_login FROM {$wpdb->users} WHERE user_email = %s", $email));
         foreach ($ws as $user) {
             $userDat = get_userdata($user->ID);
             if (wfUtils::isAdmin($userDat)) {
                 if ($email == $userDat->user_email) {
                     $found = true;
                     break;
                 }
             }
         }
         if (!$found) {
             foreach (wfConfig::getAlertEmails() as $alertEmail) {
                 if ($alertEmail == $email) {
                     $found = true;
                     break;
                 }
             }
         }
         if ($found) {
             $key = wfUtils::bigRandomHex();
             $IP = wfUtils::getIP();
             set_transient('wfunlock_' . $key, $IP, 1800);
             $content = wfUtils::tmpl('email_unlockRequest.php', array('siteName' => get_bloginfo('name', 'raw'), 'siteURL' => wfUtils::getSiteBaseURL(), 'unlockHref' => wfUtils::getSiteBaseURL() . '?_wfsf=unlockAccess&key=' . $key, 'key' => $key, 'IP' => $IP));
             wp_mail($email, "Unlock email requested", $content, "Content-Type: text/html");
         }
         echo "<html><body><h1>Your request was received</h1><p>We received a request to email \"" . wp_kses($email, array()) . "\" instructions to unlock their access. If that is the email address of a site administrator or someone on the Wordfence alert list, then they have been emailed instructions on how to regain access to this sytem. The instructions we sent will expire 30 minutes from now.</body></html>";
         exit;
     } else {
         if ($wfFunc == 'unlockAccess') {
             if (!preg_match('/^\\d+\\.\\d+\\.\\d+\\.\\d+$/', get_transient('wfunlock_' . $_GET['key']))) {
                 echo "Invalid key provided for authentication.";
                 exit;
             }
             /* You can enable this for paranoid security leve.
             			if(get_transient('wfunlock_' . $_GET['key']) != wfUtils::getIP()){
             				echo "You can only use this link from the IP address you used to generate the unlock email.";
             				exit();
             			}
             			*/
             $wfLog = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
             if ($_GET['func'] == 'unlockMyIP') {
                 $wfLog->unblockIP(wfUtils::getIP());
                 $wfLog->unlockOutIP(wfUtils::getIP());
                 delete_transient('wflginfl_' . bin2hex(wfUtils::inet_pton(wfUtils::getIP())));
                 //Reset login failure counter
                 header('Location: ' . wp_login_url());
                 exit;
             } else {
                 if ($_GET['func'] == 'unlockAllIPs') {
                     wordfence::status(1, 'info', "Request received via unlock email link to unblock all IP's.");
                     $wfLog->unblockAllIPs();
                     $wfLog->unlockAllIPs();
                     delete_transient('wflginfl_' . bin2hex(wfUtils::inet_pton(wfUtils::getIP())));
                     //Reset login failure counter
                     header('Location: ' . wp_login_url());
                     exit;
                 } else {
                     if ($_GET['func'] == 'disableRules') {
                         wfConfig::set('firewallEnabled', 0);
                         wfConfig::set('loginSecurityEnabled', 0);
                         wordfence::status(1, 'info', "Request received via unlock email link to unblock all IP's via disabling firewall rules.");
                         $wfLog->unblockAllIPs();
                         $wfLog->unlockAllIPs();
                         delete_transient('wflginfl_' . bin2hex(wfUtils::inet_pton(wfUtils::getIP())));
                         //Reset login failure counter
                         wfConfig::set('cbl_countries', '');
                         //unblock all countries
                         header('Location: ' . wp_login_url());
                         exit;
                     } else {
                         echo "Invalid function specified. Please check the link we emailed you and make sure it was not cut-off by your email reader.";
                         exit;
                     }
                 }
             }
         }
     }
     // Sync the WAF data with the database.
     if (!WFWAF_SUBDIRECTORY_INSTALL && ($waf = wfWAF::getInstance())) {
         try {
             $configDefaults = array('apiKey' => wfConfig::get('apiKey'), 'isPaid' => wfConfig::get('isPaid'), 'siteURL' => site_url(), 'homeURL' => home_url(), 'whitelistedIPs' => (string) wfConfig::get('whitelisted'), 'howGetIPs' => (string) wfConfig::get('howGetIPs'));
             foreach ($configDefaults as $key => $value) {
                 $waf->getStorageEngine()->setConfig($key, $value);
             }
             if (empty($_GET['wordfence_syncAttackData'])) {
                 $lastAttackMicroseconds = $wpdb->get_var("SELECT MAX(attackLogTime) FROM {$wpdb->base_prefix}wfHits");
                 if ($waf->getStorageEngine()->hasNewerAttackData($lastAttackMicroseconds)) {
                     if (get_site_option('wordfence_syncingAttackData') <= time() - 60) {
                         // Could be the request to itself is not completing, add ajax to the head as a workaround
                         $attempts = get_site_option('wordfence_syncAttackDataAttempts', 0);
                         if ($attempts > 10) {
                             add_action('wp_head', 'wordfence::addSyncAttackDataAjax');
                             add_action('login_head', 'wordfence::addSyncAttackDataAjax');
                             add_action('admin_head', 'wordfence::addSyncAttackDataAjax');
                         } else {
                             update_site_option('wordfence_syncAttackDataAttempts', ++$attempts);
                             wp_remote_post(add_query_arg('wordfence_syncAttackData', microtime(true), home_url('/')), array('timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters('https_local_ssl_verify', false)));
                         }
                     }
                 }
             }
             if ($waf instanceof wfWAFWordPress && ($learningModeAttackException = $waf->getLearningModeAttackException())) {
                 $log = self::getLog();
                 $log->initLogRequest();
                 $request = $log->getCurrentRequest();
                 $request->action = 'learned:waf';
                 $request->attackLogTime = microtime(true);
                 $ruleIDs = array();
                 /** @var wfWAFRule $failedRule */
                 foreach ($learningModeAttackException->getFailedRules() as $failedRule) {
                     $ruleIDs[] = $failedRule->getRuleID();
                 }
                 $actionData = array('learningMode' => 1, 'failedRules' => $ruleIDs, 'paramKey' => $learningModeAttackException->getParamKey(), 'paramValue' => $learningModeAttackException->getParamValue());
                 if ($ruleIDs && $ruleIDs[0]) {
                     $rule = $waf->getRule($ruleIDs[0]);
                     if ($rule) {
                         $request->actionDescription = $rule->getDescription();
                         $actionData['category'] = $rule->getCategory();
                         $actionData['ssl'] = $waf->getRequest()->getProtocol() === 'https';
                         $actionData['fullRequest'] = base64_encode($waf->getRequest());
                     }
                 }
                 $request->actionData = wfRequestModel::serializeActionData($actionData);
                 register_shutdown_function(array($request, 'save'));
                 self::scheduleSendAttackData();
             }
         } catch (wfWAFStorageFileException $e) {
             // We don't have anywhere to write files in this scenario.
         }
     }
     if (wfConfig::get('firewallEnabled')) {
         $wfLog = self::getLog();
         $wfLog->firewallBadIPs();
         $IP = wfUtils::getIP();
         if ($wfLog->isWhitelisted($IP)) {
             return;
         }
         if (wfConfig::get('neverBlockBG') == 'neverBlockUA' && wfCrawl::isGoogleCrawler()) {
             return;
         }
         if (wfConfig::get('neverBlockBG') == 'neverBlockVerified' && wfCrawl::isVerifiedGoogleCrawler()) {
             return;
         }
         if (wfConfig::get('blockFakeBots')) {
             if (wfCrawl::isGooglebot() && !wfCrawl::isVerifiedGoogleCrawler()) {
                 $wfLog->blockIP($IP, "Fake Google crawler automatically blocked");
                 wordfence::status(2, 'info', "Blocking fake Googlebot at IP {$IP}");
                 $wfLog->do503(3600, "Fake Google crawler automatically blocked.");
             }
         }
         if (wfConfig::get('bannedURLs', false)) {
             $URLs = explode(',', wfConfig::get('bannedURLs'));
             foreach ($URLs as $URL) {
                 if (preg_match(wfUtils::patternToRegex($URL, ''), $_SERVER['REQUEST_URI'])) {
                     $wfLog->blockIP($IP, "Accessed a banned URL.");
                     $wfLog->do503(3600, "Accessed a banned URL.");
                     //exits
                 }
             }
         }
         if (wfConfig::get('other_blockBadPOST') == '1' && $_SERVER['REQUEST_METHOD'] == 'POST' && empty($_SERVER['HTTP_USER_AGENT']) && empty($_SERVER['HTTP_REFERER'])) {
             $wfLog->blockIP($IP, "POST received with blank user-agent and referer");
             $wfLog->do503(3600, "POST received with blank user-agent and referer");
             //exits
         }
     }
 }
コード例 #2
0
 public function firewallBadIPs()
 {
     $IP = wfUtils::getIP();
     if ($this->isWhitelisted($IP)) {
         return;
     }
     $IPnum = wfUtils::inet_pton($IP);
     $hostname = null;
     //New range and UA pattern blocking:
     $r1 = $this->getDB()->querySelect("select id, blockType, blockString from " . $this->ipRangesTable);
     foreach ($r1 as $blockRec) {
         if ($blockRec['blockType'] == 'IU') {
             $ipRangeBlocked = false;
             $uaPatternBlocked = false;
             $refBlocked = false;
             $bDat = explode('|', $blockRec['blockString']);
             $ipRange = $bDat[0];
             $uaPattern = $bDat[1];
             $refPattern = isset($bDat[2]) ? $bDat[2] : '';
             if ($ipRange) {
                 list($start_range, $end_range) = explode('-', $ipRange);
                 if (preg_match('/[\\.:]/', $start_range)) {
                     $start_range = wfUtils::inet_pton($start_range);
                     $end_range = wfUtils::inet_pton($end_range);
                 } else {
                     $start_range = wfUtils::inet_pton(long2ip($start_range));
                     $end_range = wfUtils::inet_pton(long2ip($end_range));
                 }
                 if (strcmp($IPnum, $start_range) >= 0 && strcmp($IPnum, $end_range) <= 0) {
                     $ipRangeBlocked = true;
                 }
             }
             if (!empty($bDat[3])) {
                 $ipRange = true;
                 /* We reuse the ipRangeBlocked variable */
                 if ($hostname === null) {
                     $hostname = wfUtils::reverseLookup($IP);
                 }
                 if (preg_match(wfUtils::patternToRegex($bDat[3]), $hostname)) {
                     $ipRangeBlocked = true;
                 }
             }
             if ($uaPattern) {
                 if (wfUtils::isUABlocked($uaPattern)) {
                     $uaPatternBlocked = true;
                 }
             }
             if ($refPattern) {
                 if (wfUtils::isRefererBlocked($refPattern)) {
                     $refBlocked = true;
                 }
             }
             $doBlock = false;
             if ($uaPattern && $ipRange && $refPattern) {
                 if ($uaPatternBlocked && $ipRangeBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             }
             if ($uaPattern && $ipRange) {
                 if ($uaPatternBlocked && $ipRangeBlocked) {
                     $doBlock = true;
                 }
             }
             if ($uaPattern && $refPattern) {
                 if ($uaPatternBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             }
             if ($ipRange && $refPattern) {
                 if ($ipRangeBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             } else {
                 if ($uaPattern) {
                     if ($uaPatternBlocked) {
                         $doBlock = true;
                     }
                 } else {
                     if ($ipRange) {
                         if ($ipRangeBlocked) {
                             $doBlock = true;
                         }
                     } else {
                         if ($refPattern) {
                             if ($refBlocked) {
                                 $doBlock = true;
                             }
                         }
                     }
                 }
             }
             if ($doBlock) {
                 $this->getDB()->queryWrite("update " . $this->ipRangesTable . " set totalBlocked = totalBlocked + 1, lastBlocked = unix_timestamp() where id=%d", $blockRec['id']);
                 wfActivityReport::logBlockedIP($IP);
                 $this->currentRequest->actionDescription = 'UA/Referrer/IP Range not allowed';
                 $this->do503(3600, "Advanced blocking in effect.");
             }
         }
     }
     //End range/UA blocking
     // Country blocking
     if (wfConfig::get('isPaid')) {
         $blockedCountries = wfConfig::get('cbl_countries', false);
         $bareRequestURI = wfUtils::extractBareURI($_SERVER['REQUEST_URI']);
         $bareBypassRedirURI = wfUtils::extractBareURI(wfConfig::get('cbl_bypassRedirURL', ''));
         $skipCountryBlocking = false;
         if ($bareBypassRedirURI && $bareRequestURI == $bareBypassRedirURI) {
             //Run this before country blocking because even if the user isn't blocked we need to set the bypass cookie so they can bypass future blocks.
             $bypassRedirDest = wfConfig::get('cbl_bypassRedirDest', '');
             if ($bypassRedirDest) {
                 self::setCBLCookieBypass();
                 $this->redirect($bypassRedirDest);
                 //exits
             }
         }
         $bareBypassViewURI = wfUtils::extractBareURI(wfConfig::get('cbl_bypassViewURL', ''));
         if ($bareBypassViewURI && $bareBypassViewURI == $bareRequestURI) {
             self::setCBLCookieBypass();
             $skipCountryBlocking = true;
         }
         if (!$skipCountryBlocking && $blockedCountries && !self::isCBLBypassCookieSet()) {
             // If everything is checked, make sure this always runs.
             if (wfConfig::get('cbl_loggedInBlocked', false) && wfConfig::get('cbl_loginFormBlocked', false) && wfConfig::get('cbl_restOfSiteBlocked', false)) {
                 $this->checkForBlockedCountry();
             }
             // Block logged in users.
             if (wfConfig::get('cbl_loggedInBlocked', false) && is_user_logged_in()) {
                 $this->checkForBlockedCountry();
             }
             // Block the login form itself and any attempt to authenticate.
             if (wfConfig::get('cbl_loginFormBlocked', false)) {
                 if (self::isAuthRequest()) {
                     $this->checkForBlockedCountry();
                 }
                 add_filter('authenticate', array($this, 'checkForBlockedCountry'), 1, 0);
             }
             // Block requests that aren't to the login page, xmlrpc.php, or a user already logged in.
             if (wfConfig::get('cbl_restOfSiteBlocked', false) && !self::isAuthRequest() && !defined('XMLRPC_REQUEST') && !is_user_logged_in()) {
                 $this->checkForBlockedCountry();
             }
             // XMLRPC is inaccesible when public portion of the site and auth is disabled.
             if (wfConfig::get('cbl_loginFormBlocked', false) && wfConfig::get('cbl_restOfSiteBlocked', false) && defined('XMLRPC_REQUEST')) {
                 $this->checkForBlockedCountry();
             }
         }
     }
     if ($rec = $this->getDB()->querySingleRec("select blockedTime, reason from " . $this->blocksTable . " where IP=%s and (permanent=1 OR (blockedTime + %s > unix_timestamp()))", $IPnum, wfConfig::get('blockedTime'))) {
         $this->getDB()->queryWrite("update " . $this->blocksTable . " set lastAttempt=unix_timestamp(), blockedHits = blockedHits + 1 where IP=%s", $IPnum);
         $now = $this->getDB()->querySingle("select unix_timestamp()");
         $secsToGo = $rec['blockedTime'] + wfConfig::get('blockedTime') - $now;
         if (wfConfig::get('other_WFNet') && self::isAuthRequest()) {
             //It's an auth request and this IP has been blocked
             $this->getCurrentRequest()->action = 'blocked:wfsnrepeat';
             wordfence::wfsnReportBlockedAttempt($IP, 'login');
         }
         $this->do503($secsToGo, $rec['reason']);
     }
 }
コード例 #3
0
ファイル: wfLog.php プロジェクト: ashenkar/sanga
 public function firewallBadIPs()
 {
     $IP = wfUtils::getIP();
     if ($this->isWhitelisted($IP)) {
         return;
     }
     $IPnum = wfUtils::inet_pton($IP);
     $hostname = null;
     //New range and UA pattern blocking:
     $r1 = $this->getDB()->querySelect("select id, blockType, blockString from " . $this->ipRangesTable);
     foreach ($r1 as $blockRec) {
         if ($blockRec['blockType'] == 'IU') {
             $ipRangeBlocked = false;
             $uaPatternBlocked = false;
             $refBlocked = false;
             $bDat = explode('|', $blockRec['blockString']);
             $ipRange = $bDat[0];
             $uaPattern = $bDat[1];
             $refPattern = isset($bDat[2]) ? $bDat[2] : '';
             if ($ipRange) {
                 list($start_range, $end_range) = explode('-', $ipRange);
                 if (preg_match('/[\\.:]/', $start_range)) {
                     $start_range = wfUtils::inet_pton($start_range);
                     $end_range = wfUtils::inet_pton($end_range);
                 } else {
                     $start_range = wfUtils::inet_pton(long2ip($start_range));
                     $end_range = wfUtils::inet_pton(long2ip($end_range));
                 }
                 if (strcmp($IPnum, $start_range) >= 0 && strcmp($IPnum, $end_range) <= 0) {
                     $ipRangeBlocked = true;
                 }
             }
             if (!empty($bDat[3])) {
                 $ipRange = true;
                 /* We reuse the ipRangeBlocked variable */
                 if ($hostname === null) {
                     $hostname = wfUtils::reverseLookup($IP);
                 }
                 if (preg_match(wfUtils::patternToRegex($bDat[3]), $hostname)) {
                     $ipRangeBlocked = true;
                 }
             }
             if ($uaPattern) {
                 if (wfUtils::isUABlocked($uaPattern)) {
                     $uaPatternBlocked = true;
                 }
             }
             if ($refPattern) {
                 if (wfUtils::isRefererBlocked($refPattern)) {
                     $refBlocked = true;
                 }
             }
             $doBlock = false;
             if ($uaPattern && $ipRange && $refPattern) {
                 if ($uaPatternBlocked && $ipRangeBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             }
             if ($uaPattern && $ipRange) {
                 if ($uaPatternBlocked && $ipRangeBlocked) {
                     $doBlock = true;
                 }
             }
             if ($uaPattern && $refPattern) {
                 if ($uaPatternBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             }
             if ($ipRange && $refPattern) {
                 if ($ipRangeBlocked && $refBlocked) {
                     $doBlock = true;
                 }
             } else {
                 if ($uaPattern) {
                     if ($uaPatternBlocked) {
                         $doBlock = true;
                     }
                 } else {
                     if ($ipRange) {
                         if ($ipRangeBlocked) {
                             $doBlock = true;
                         }
                     } else {
                         if ($refPattern) {
                             if ($refBlocked) {
                                 $doBlock = true;
                             }
                         }
                     }
                 }
             }
             if ($doBlock) {
                 $this->getDB()->queryWrite("update " . $this->ipRangesTable . " set totalBlocked = totalBlocked + 1, lastBlocked = unix_timestamp() where id=%d", $blockRec['id']);
                 wfActivityReport::logBlockedIP($IP);
                 $this->currentRequest->actionDescription = 'UA/Referrer/IP Range not allowed';
                 $this->do503(3600, "Advanced blocking in effect.");
             }
         }
     }
     //End range/UA blocking
     // Country blocking
     if (wfConfig::get('isPaid')) {
         $blockedCountries = wfConfig::get('cbl_countries', false);
         $bareRequestURI = wfUtils::extractBareURI($_SERVER['REQUEST_URI']);
         $bareBypassRedirURI = wfUtils::extractBareURI(wfConfig::get('cbl_bypassRedirURL', ''));
         $skipCountryBlocking = false;
         if ($bareBypassRedirURI && $bareRequestURI == $bareBypassRedirURI) {
             //Run this before country blocking because even if the user isn't blocked we need to set the bypass cookie so they can bypass future blocks.
             $bypassRedirDest = wfConfig::get('cbl_bypassRedirDest', '');
             if ($bypassRedirDest) {
                 self::setCBLCookieBypass();
                 $this->redirect($bypassRedirDest);
                 //exits
             }
         }
         $bareBypassViewURI = wfUtils::extractBareURI(wfConfig::get('cbl_bypassViewURL', ''));
         if ($bareBypassViewURI && $bareBypassViewURI == $bareRequestURI) {
             self::setCBLCookieBypass();
             $skipCountryBlocking = true;
         }
         if (!$skipCountryBlocking && $blockedCountries && !self::isCBLBypassCookieSet()) {
             if (is_user_logged_in() && !wfConfig::get('cbl_loggedInBlocked', false)) {
                 //User is logged in and we're allowing logins
                 //Do nothing
             } else {
                 if (strpos($_SERVER['REQUEST_URI'], '/wp-login.php') !== false && !wfConfig::get('cbl_loginFormBlocked', false)) {
                     //It's the login form and we're allowing that
                     //Do nothing
                 } else {
                     if (strpos($_SERVER['REQUEST_URI'], '/wp-login.php') === false && !wfConfig::get('cbl_restOfSiteBlocked', false)) {
                         //It's the rest of the site and we're allowing that
                         //Do nothing
                     } else {
                         if ($country = wfUtils::IP2Country($IP)) {
                             foreach (explode(',', $blockedCountries) as $blocked) {
                                 if (strtoupper($blocked) == strtoupper($country)) {
                                     //At this point we know the user has been blocked
                                     if (wfConfig::get('cbl_action') == 'redir') {
                                         $redirURL = wfConfig::get('cbl_redirURL');
                                         $eRedirHost = wfUtils::extractHostname($redirURL);
                                         $isExternalRedir = false;
                                         if ($eRedirHost && $eRedirHost != wfUtils::extractHostname(home_url())) {
                                             //It's an external redirect...
                                             $isExternalRedir = true;
                                         }
                                         if (!$isExternalRedir && wfUtils::extractBareURI($redirURL) == $bareRequestURI) {
                                             //Is this the URI we want to redirect to, then don't block it
                                             //Do nothing
                                             /* Uncomment the following if page components aren't loading for the page we redirect to.
                                             			   Uncommenting is not recommended because it means that anyone from a blocked country
                                             			   can crawl your site by sending the page blocked users are redirected to as the referer for every request.
                                             			   But it's your call.
                                             			} else if(wfUtils::extractBareURI($_SERVER['HTTP_REFERER']) == $redirURL){ //If the referer the page we want to redirect to? Then this might be loading as a component so don't block.
                                             				//Do nothing
                                             			*/
                                         } else {
                                             $this->redirect(wfConfig::get('cbl_redirURL'));
                                         }
                                     } else {
                                         $this->currentRequest->actionDescription = 'blocked access via country blocking';
                                         $this->do503(3600, "Access from your area has been temporarily limited for security reasons");
                                         wfConfig::inc('totalCountryBlocked');
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     if ($rec = $this->getDB()->querySingleRec("select blockedTime, reason from " . $this->blocksTable . " where IP=%s and (permanent=1 OR (blockedTime + %s > unix_timestamp()))", $IPnum, wfConfig::get('blockedTime'))) {
         $this->getDB()->queryWrite("update " . $this->blocksTable . " set lastAttempt=unix_timestamp(), blockedHits = blockedHits + 1 where IP=%s", $IPnum);
         $now = $this->getDB()->querySingle("select unix_timestamp()");
         $secsToGo = $rec['blockedTime'] + wfConfig::get('blockedTime') - $now;
         if (wfConfig::get('other_WFNet') && strpos($_SERVER['REQUEST_URI'], '/wp-login.php') !== false) {
             //We're on the login page and this IP has been blocked
             wordfence::wfsnReportBlockedAttempt($IP, 'login');
         }
         $this->do503($secsToGo, $rec['reason']);
     }
 }
コード例 #4
0
ファイル: wfCache.php プロジェクト: ashenkar/sanga
    public static function getHtaccessCode()
    {
        $siteURL = site_url();
        $homeURL = home_url();
        $pathPrefix = "";
        if (preg_match('/^https?:\\/\\/[^\\/]+\\/(.+)$/i', $siteURL, $matches)) {
            $path = $matches[1];
            $path = preg_replace('/^\\//', '', $path);
            $path = preg_replace('/\\/$/', '', $path);
            $pathPrefix = '/' . $path;
            // Which is: /my/path
        }
        $matchCaps = '$1/$2~$3~$4~$5~$6';
        if (preg_match('/^https?:\\/\\/[^\\/]+\\/(.+)$/i', $homeURL, $matches)) {
            $path = $matches[1];
            $path = preg_replace('/^\\//', '', $path);
            $path = preg_replace('/\\/$/', '', $path);
            $pieces = explode('/', $path);
            if (count($pieces) == 1) {
                # No path:       "/wp-content/wfcache/%{HTTP_HOST}_$1/$2~$3~$4~$5~$6_wfcache%{ENV:WRDFNC_HTTPS}.html%{ENV:WRDFNC_ENC}" [L]
                # One path:  "/mdm/wp-content/wfcache/%{HTTP_HOST}_mdm/$1~$2~$3~$4~$5_wfcache%{ENV:WRDFNC_HTTPS}.html%{ENV:WRDFNC_ENC}" [L]
                $matchCaps = $pieces[0] . '/$1~$2~$3~$4~$5';
            } else {
                if (count($pieces) == 2) {
                    $matchCaps = $pieces[0] . '/' . $pieces[1] . '/$1~$2~$3~$4';
                } else {
                    $matchCaps = '$1/$2~$3~$4~$5~$6';
                    #defaults to the regular setting but this won't work. However user should already have gotten a warning that we don't support sites more than 2 dirs deep with falcon.
                }
            }
        }
        $sslString = "RewriteCond %{HTTPS} off";
        if (wfConfig::get('allowHTTPSCaching')) {
            $sslString = "";
        }
        $otherRewriteConds = "";
        $ex = wfConfig::get('cacheExclusions', false);
        if ($ex) {
            $ex = unserialize($ex);
            foreach ($ex as $v) {
                if ($v['pt'] == 'uac') {
                    $otherRewriteConds .= "\n\tRewriteCond %{HTTP_USER_AGENT} !" . self::regexSpaceFix(preg_quote($v['p'])) . " [NC]";
                }
                if ($v['pt'] == 'uaeq') {
                    $otherRewriteConds .= "\n\tRewriteCond %{HTTP_USER_AGENT} !^" . self::regexSpaceFix(preg_quote($v['p'])) . "\$ [NC]";
                }
                if ($v['pt'] == 'cc') {
                    $otherRewriteConds .= "\n\tRewriteCond %{HTTP_COOKIE} !" . self::regexSpaceFix(preg_quote($v['p'])) . " [NC]";
                }
            }
        }
        //We exclude URLs that are banned so that Wordfence PHP code can catch the IP address, then ban that IP and the ban is added to .htaccess.
        $excludedURLs = "";
        if (wfConfig::get('bannedURLs', false)) {
            foreach (explode(',', wfConfig::get('bannedURLs', false)) as $URL) {
                $excludedURLs .= "RewriteCond %{REQUEST_URI} !" . wfUtils::patternToRegex($URL, '', '') . "\n\t";
            }
        }
        $code = <<<EOT
#WFCACHECODE - Do not remove this line. Disable Web Caching in Wordfence to remove this data.
<IfModule mod_deflate.c>
\tAddOutputFilterByType DEFLATE text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon application/json
\t<IfModule mod_headers.c>
\t\tHeader append Vary User-Agent env=!dont-vary
\t</IfModule>
\t<IfModule mod_mime.c>
\t\tAddOutputFilter DEFLATE js css htm html xml
\t</IfModule>
</IfModule>
<IfModule mod_mime.c>
\tAddType text/html .html_gzip
\tAddEncoding gzip .html_gzip
\tAddType text/xml .xml_gzip
\tAddEncoding gzip .xml_gzip
</IfModule>
<IfModule mod_setenvif.c>
\tSetEnvIfNoCase Request_URI \\.html_gzip\$ no-gzip
\tSetEnvIfNoCase Request_URI \\.xml_gzip\$ no-gzip
</IfModule>
<IfModule mod_headers.c>
\tHeader set Vary "Accept-Encoding, Cookie"
</IfModule>
<IfModule mod_rewrite.c>
\t#Prevents garbled chars in cached files if there is no default charset.
\tAddDefaultCharset utf-8

\t#Cache rules:
\tRewriteEngine On
\tRewriteBase /
\tRewriteCond %{HTTPS} on
\tRewriteRule .* - [E=WRDFNC_HTTPS:_https]
\tRewriteCond %{HTTP:Accept-Encoding} gzip
\tRewriteRule .* - [E=WRDFNC_ENC:_gzip]
\tRewriteCond %{REQUEST_METHOD} !=POST
\t{$sslString}
\tRewriteCond %{QUERY_STRING} ^(?:\\d+=\\d+)?\$
\tRewriteCond %{REQUEST_URI} (?:\\/|\\.html)\$ [NC]
\t{$excludedURLs}
\tRewriteCond %{HTTP_COOKIE} !(comment_author|wp\\-postpass|wf_logout|wordpress_logged_in|wptouch_switch_toggle|wpmp_switcher) [NC]
\t{$otherRewriteConds}
\tRewriteCond %{REQUEST_URI} \\/*([^\\/]*)\\/*([^\\/]*)\\/*([^\\/]*)\\/*([^\\/]*)\\/*([^\\/]*)(.*)\$
\tRewriteCond "%{DOCUMENT_ROOT}{$pathPrefix}/wp-content/wfcache/%{HTTP_HOST}_%1/%2~%3~%4~%5~%6_wfcache%{ENV:WRDFNC_HTTPS}.html%{ENV:WRDFNC_ENC}" -f
\tRewriteRule \\/*([^\\/]*)\\/*([^\\/]*)\\/*([^\\/]*)\\/*([^\\/]*)\\/*([^\\/]*)(.*)\$ "{$pathPrefix}/wp-content/wfcache/%{HTTP_HOST}_{$matchCaps}_wfcache%{ENV:WRDFNC_HTTPS}.html%{ENV:WRDFNC_ENC}" [L]
</IfModule>
#Do not remove this line. Disable Web caching in Wordfence to remove this data - WFCACHECODE
EOT;
        return $code;
    }