Ejemplo n.º 1
0
 public function call($action, $getParams = array(), $postParams = array(), $forceSSL = false)
 {
     $apiURL = $this->getAPIURL();
     //Sanity check. Developer should call wfAPI::SSLEnabled() to check if SSL is enabled before forcing SSL and return a user friendly msg if it's not.
     if ($forceSSL && !preg_match('/^https:/i', $apiURL)) {
         //User's should never see this message unless we aren't calling SSLEnabled() to check if SSL is enabled before using call() with forceSSL
         throw new Exception("SSL is not supported by your web server and is required to use this function. Please ask your hosting provider or site admin to install cURL with openSSL to use this feature.");
     }
     $json = $this->getURL($apiURL . '/v' . WORDFENCE_API_VERSION . '/?' . $this->makeAPIQueryString() . '&' . self::buildQuery(array_merge(array('action' => $action), $getParams)), $postParams);
     if (!$json) {
         throw new Exception("We received an empty data response from the Wordfence scanning servers when calling the '{$action}' function.");
     }
     $dat = json_decode($json, true);
     if (isset($dat['_isPaidKey'])) {
         wfConfig::set('keyExpDays', $dat['_keyExpDays']);
         if ($dat['_keyExpDays'] > -1) {
             wfConfig::set('isPaid', 1);
         } else {
             if ($dat['_keyExpDays'] < 0) {
                 wfConfig::set('isPaid', '');
             }
         }
     }
     if (!is_array($dat)) {
         throw new Exception("We received a data structure that is not the expected array when contacting the Wordfence scanning servers and calling the '{$action}' function.");
     }
     if (is_array($dat) && isset($dat['errorMsg'])) {
         throw new Exception($dat['errorMsg']);
     }
     return $dat;
 }
Ejemplo n.º 2
0
 public function call($action, $getParams = array(), $postParams = array())
 {
     $json = $this->getURL($this->getAPIURL() . '/v' . WORDFENCE_API_VERSION . '/?' . $this->makeAPIQueryString() . '&' . self::buildQuery(array_merge(array('action' => $action), $getParams)), $postParams);
     if (!$json) {
         throw new Exception("We received an empty data response from the Wordfence scanning servers when calling the '{$action}' function.");
     }
     $dat = json_decode($json, true);
     if (isset($dat['_isPaidKey'])) {
         wfConfig::set('keyExpDays', $dat['_keyExpDays']);
         if ($dat['_keyExpDays'] > -1) {
             wfConfig::set('isPaid', 1);
         } else {
             if ($dat['_keyExpDays'] < 0) {
                 wfConfig::set('isPaid', '');
             }
         }
     }
     if (!is_array($dat)) {
         throw new Exception("We received a data structure that is not the expected array when contacting the Wordfence scanning servers and calling the '{$action}' function.");
     }
     if (is_array($dat) && isset($dat['errorMsg'])) {
         throw new Exception($dat['errorMsg']);
     }
     return $dat;
 }
Ejemplo n.º 3
0
 /**
  *
  */
 public static function processAttackData()
 {
     global $wpdb;
     $waf = wfWAF::getInstance();
     if ($waf->getStorageEngine()->getConfig('attackDataKey', false) === false) {
         $waf->getStorageEngine()->setConfig('attackDataKey', mt_rand(0, 0xfff));
     }
     $limit = 500;
     $lastSendTime = wfConfig::get('lastAttackDataSendTime');
     $attackData = $wpdb->get_results($wpdb->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM {$wpdb->base_prefix}wfHits\nWHERE action in ('blocked:waf', 'learned:waf')\nAND attackLogTime > %.6f\nLIMIT %d", $lastSendTime, $limit));
     $totalRows = $wpdb->get_var('SELECT FOUND_ROWS()');
     if ($attackData) {
         $response = wp_remote_get(sprintf(WFWAF_API_URL_SEC . "waf-rules/%d.txt", $waf->getStorageEngine()->getConfig('attackDataKey')));
         if (!is_wp_error($response)) {
             $okToSendBody = wp_remote_retrieve_body($response);
             if ($okToSendBody === 'ok') {
                 // Build JSON to send
                 $dataToSend = array();
                 $attackDataToUpdate = array();
                 foreach ($attackData as $attackDataRow) {
                     $actionData = (array) wfRequestModel::unserializeActionData($attackDataRow->actionData);
                     $dataToSend[] = array($attackDataRow->attackLogTime, $attackDataRow->ctime, wfUtils::inet_ntop($attackDataRow->IP), array_key_exists('learningMode', $actionData) ? $actionData['learningMode'] : 0, array_key_exists('paramKey', $actionData) ? base64_encode($actionData['paramKey']) : false, array_key_exists('paramValue', $actionData) ? base64_encode($actionData['paramValue']) : false, array_key_exists('failedRules', $actionData) ? $actionData['failedRules'] : '', strpos($attackDataRow->URL, 'https') === 0 ? 1 : 0, array_key_exists('fullRequest', $actionData) ? $actionData['fullRequest'] : '');
                     if (array_key_exists('fullRequest', $actionData)) {
                         unset($actionData['fullRequest']);
                         $attackDataToUpdate[$attackDataRow->id] = array('actionData' => wfRequestModel::serializeActionData($actionData));
                     }
                     if ($attackDataRow->attackLogTime > $lastSendTime) {
                         $lastSendTime = $attackDataRow->attackLogTime;
                     }
                 }
                 $response = wp_remote_post(WFWAF_API_URL_SEC . "?" . http_build_query(array('action' => 'send_waf_attack_data', 'k' => $waf->getStorageEngine()->getConfig('apiKey'), 's' => $waf->getStorageEngine()->getConfig('siteURL') ? $waf->getStorageEngine()->getConfig('siteURL') : sprintf('%s://%s/', $waf->getRequest()->getProtocol(), rawurlencode($waf->getRequest()->getHost())))), array('body' => json_encode($dataToSend), 'headers' => array('Content-Type' => 'application/json'), 'timeout' => 30));
                 if (!is_wp_error($response) && ($body = wp_remote_retrieve_body($response))) {
                     $jsonData = json_decode($body, true);
                     if (is_array($jsonData) && array_key_exists('success', $jsonData)) {
                         // Successfully sent data, remove the full request from the table to reduce storage size
                         foreach ($attackDataToUpdate as $hitID => $dataToUpdate) {
                             $wpdb->update($wpdb->base_prefix . 'wfHits', $dataToUpdate, array('id' => $hitID));
                         }
                         wfConfig::set('lastAttackDataSendTime', $lastSendTime);
                         if ($totalRows > $limit) {
                             self::scheduleSendAttackData();
                         }
                     }
                 }
             } else {
                 if (is_string($okToSendBody) && preg_match('/next check in: ([0-9]+)/', $okToSendBody, $matches)) {
                     self::scheduleSendAttackData(time() + $matches[1]);
                 }
             }
             // Could be that the server is down, so hold off on sending data for a little while.
         } else {
             self::scheduleSendAttackData(time() + 7200);
         }
     }
     self::trimWfHits();
 }
Ejemplo n.º 4
0
 public function getCBLCookieVal()
 {
     $val = wfConfig::get('cbl_cookieVal', false);
     if (!$val) {
         $val = uniqid();
         wfConfig::set('cbl_cookieVal', $val);
     }
     return $val;
 }
Ejemplo n.º 5
0
 public static function clearScanLock()
 {
     wfConfig::set('wf_scanRunning', '');
 }
Ejemplo n.º 6
0
    /**
     *
     */
    public static function processAttackData()
    {
        global $wpdb;
        $waf = wfWAF::getInstance();
        if ($waf->getStorageEngine()->getConfig('attackDataKey', false) === false) {
            $waf->getStorageEngine()->setConfig('attackDataKey', mt_rand(0, 0xfff));
        }
        //Send alert email if needed
        if (wfConfig::get('wafAlertOnAttacks')) {
            $alertInterval = wfConfig::get('wafAlertInterval', 0);
            $cutoffTime = max(time() - $alertInterval, wfConfig::get('wafAlertLastSendTime'));
            $wafAlertWhitelist = wfConfig::get('wafAlertWhitelist', '');
            $wafAlertWhitelist = preg_split("/[,\r\n]+/", $wafAlertWhitelist);
            foreach ($wafAlertWhitelist as $index => &$entry) {
                $entry = trim($entry);
                if (!preg_match('/^(?:\\d{1,3}(?:\\.|$)){4}/', $entry) && !preg_match('/^((?:[\\da-f]{1,4}(?::|)){0,8})(::)?((?:[\\da-f]{1,4}(?::|)){0,8})$/i', $entry)) {
                    unset($wafAlertWhitelist[$index]);
                    continue;
                }
                $packed = @wfUtils::inet_pton($entry);
                if ($packed === false) {
                    unset($wafAlertWhitelist[$index]);
                    continue;
                }
                $entry = bin2hex($packed);
            }
            $wafAlertWhitelist = array_filter($wafAlertWhitelist);
            $attackData = $wpdb->get_results($wpdb->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM {$wpdb->base_prefix}wfHits\n\tWHERE action = 'blocked:waf' " . (count($wafAlertWhitelist) ? "AND HEX(IP) NOT IN (" . implode(", ", array_fill(0, count($wafAlertWhitelist), '%s')) . ")" : "") . "AND attackLogTime > %.6f\n\tORDER BY attackLogTime DESC\n\tLIMIT 10", array_merge($wafAlertWhitelist, array($cutoffTime))));
            $attackCount = $wpdb->get_var('SELECT FOUND_ROWS()');
            if ($attackCount >= wfConfig::get('wafAlertThreshold')) {
                $durationMessage = wfUtils::makeDuration($alertInterval);
                $message = <<<ALERTMSG
The Wordfence Web Application Firewall has blocked {$attackCount} attacks over the last {$durationMessage}. Below is a sample of these recent attacks:


ALERTMSG;
                $attackTable = array();
                $dateMax = $ipMax = $countryMax = 0;
                foreach ($attackData as $row) {
                    $row->longDescription = "Blocked for " . $row->actionDescription;
                    $actionData = json_decode($row->actionData, true);
                    if (!is_array($actionData) || !isset($actionData['paramKey']) || !isset($actionData['paramValue'])) {
                        continue;
                    }
                    $paramKey = base64_decode($actionData['paramKey']);
                    $paramValue = base64_decode($actionData['paramValue']);
                    if (strlen($paramValue) > 100) {
                        $paramValue = substr($paramValue, 0, 100) . chr(2026);
                    }
                    if (preg_match('/([a-z0-9_]+\\.[a-z0-9_]+)(?:\\[(.+?)\\](.*))?/i', $paramKey, $matches)) {
                        switch ($matches[1]) {
                            case 'request.queryString':
                                $row->longDescription = "Blocked for " . $row->actionDescription . ' in query string: ' . $matches[2] . '=' . $paramValue;
                                break;
                            case 'request.body':
                                $row->longDescription = "Blocked for " . $row->actionDescription . ' in POST body: ' . $matches[2] . '=' . $paramValue;
                                break;
                            case 'request.cookie':
                                $row->longDescription = "Blocked for " . $row->actionDescription . ' in cookie: ' . $matches[2] . '=' . $paramValue;
                                break;
                            case 'request.fileNames':
                                $row->longDescription = "Blocked for a " . $row->actionDescription . ' in file: ' . $matches[2] . '=' . $paramValue;
                                break;
                        }
                    }
                    $date = date_i18n('F j, Y g:ia', floor($row->attackLogTime));
                    $dateMax = max(strlen($date), $dateMax);
                    $ip = wfUtils::inet_ntop($row->IP);
                    $ipMax = max(strlen($ip), $ipMax);
                    $country = wfUtils::countryCode2Name(wfUtils::IP2Country($ip));
                    $country = empty($country) ? 'Unknown' : $country;
                    $countryMax = max(strlen($country), $countryMax);
                    $attackTable[] = array('date' => $date, 'IP' => $ip, 'country' => $country, 'message' => $row->longDescription);
                }
                foreach ($attackTable as $row) {
                    $date = str_pad($row['date'], $dateMax + 2);
                    $ip = str_pad($row['IP'] . " ({$row['country']})", $ipMax + $countryMax + 8);
                    $attackMessage = $row['message'];
                    $message .= $date . $ip . $attackMessage . "\n";
                }
                self::alert('Increased Attack Rate', $message, false);
                wfConfig::set('wafAlertLastSendTime', time());
            }
        }
        //Send attack data
        $limit = 500;
        $lastSendTime = wfConfig::get('lastAttackDataSendTime');
        $attackData = $wpdb->get_results($wpdb->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM {$wpdb->base_prefix}wfHits\nWHERE action in ('blocked:waf', 'learned:waf', 'logged:waf', 'blocked:waf-always')\nAND attackLogTime > %.6f\nLIMIT %d", $lastSendTime, $limit));
        $totalRows = $wpdb->get_var('SELECT FOUND_ROWS()');
        if ($attackData && wfConfig::get('other_WFNet', true)) {
            $response = wp_remote_get(sprintf(WFWAF_API_URL_SEC . "waf-rules/%d.txt", $waf->getStorageEngine()->getConfig('attackDataKey')));
            if (!is_wp_error($response)) {
                $okToSendBody = wp_remote_retrieve_body($response);
                if ($okToSendBody === 'ok') {
                    // Build JSON to send
                    $dataToSend = array();
                    $attackDataToUpdate = array();
                    foreach ($attackData as $attackDataRow) {
                        $actionData = (array) wfRequestModel::unserializeActionData($attackDataRow->actionData);
                        $dataToSend[] = array($attackDataRow->attackLogTime, $attackDataRow->ctime, wfUtils::inet_ntop($attackDataRow->IP), array_key_exists('learningMode', $actionData) ? $actionData['learningMode'] : 0, array_key_exists('paramKey', $actionData) ? base64_encode($actionData['paramKey']) : false, array_key_exists('paramValue', $actionData) ? base64_encode($actionData['paramValue']) : false, array_key_exists('failedRules', $actionData) ? $actionData['failedRules'] : '', strpos($attackDataRow->URL, 'https') === 0 ? 1 : 0, array_key_exists('fullRequest', $actionData) ? $actionData['fullRequest'] : '');
                        if (array_key_exists('fullRequest', $actionData)) {
                            unset($actionData['fullRequest']);
                            $attackDataToUpdate[$attackDataRow->id] = array('actionData' => wfRequestModel::serializeActionData($actionData));
                        }
                        if ($attackDataRow->attackLogTime > $lastSendTime) {
                            $lastSendTime = $attackDataRow->attackLogTime;
                        }
                    }
                    $response = wp_remote_post(WFWAF_API_URL_SEC . "?" . http_build_query(array('action' => 'send_waf_attack_data', 'k' => $waf->getStorageEngine()->getConfig('apiKey'), 's' => $waf->getStorageEngine()->getConfig('siteURL') ? $waf->getStorageEngine()->getConfig('siteURL') : sprintf('%s://%s/', $waf->getRequest()->getProtocol(), rawurlencode($waf->getRequest()->getHost())), 't' => microtime(true)), null, '&'), array('body' => json_encode($dataToSend), 'headers' => array('Content-Type' => 'application/json'), 'timeout' => 30));
                    if (!is_wp_error($response) && ($body = wp_remote_retrieve_body($response))) {
                        $jsonData = json_decode($body, true);
                        if (is_array($jsonData) && array_key_exists('success', $jsonData)) {
                            // Successfully sent data, remove the full request from the table to reduce storage size
                            foreach ($attackDataToUpdate as $hitID => $dataToUpdate) {
                                $wpdb->update($wpdb->base_prefix . 'wfHits', $dataToUpdate, array('id' => $hitID));
                            }
                            wfConfig::set('lastAttackDataSendTime', $lastSendTime);
                            if ($totalRows > $limit) {
                                self::scheduleSendAttackData();
                            }
                            if (array_key_exists('data', $jsonData) && array_key_exists('watchedIPList', $jsonData['data'])) {
                                $waf->getStorageEngine()->setConfig('watchedIPs', $jsonData['data']['watchedIPList']);
                            }
                        }
                    }
                } else {
                    if (is_string($okToSendBody) && preg_match('/next check in: ([0-9]+)/', $okToSendBody, $matches)) {
                        self::scheduleSendAttackData(time() + $matches[1]);
                    }
                }
                // Could be that the server is down, so hold off on sending data for a little while.
            } else {
                self::scheduleSendAttackData(time() + 7200);
            }
        } else {
            if (!wfConfig::get('other_WFNet', true)) {
                wfConfig::set('lastAttackDataSendTime', time());
            }
        }
        self::trimWfHits();
    }
 public static function disableAutoUpdate()
 {
     wfConfig::set('autoUpdate', '0');
     wp_clear_scheduled_hook('wordfence_daily_autoUpdate');
 }
Ejemplo n.º 8
0
 public static function menu_options()
 {
     if (!wfConfig::get('alertEmails')) {
         foreach (array('alertOn_block', 'alertOn_loginLockout', 'alertOn_lostPasswdForm', 'alertOn_adminLogin') as $opt) {
             wfConfig::set($opt, '1');
         }
     }
     require 'menu_options.php';
 }
Ejemplo n.º 9
0
 public static function startScan($isFork = false)
 {
     if (!$isFork) {
         //beginning of scan
         wfConfig::inc('totalScansRun');
         wfConfig::set('wfKillRequested', 0);
         wordfence::status(4, 'info', "Entering start scan routine");
         if (wfUtils::isScanRunning()) {
             return "A scan is already running. Use the kill link if you would like to terminate the current scan.";
         }
     }
     $timeout = self::getMaxExecutionTime() - 2;
     //2 seconds shorter than max execution time which ensures that only 2 HTTP processes are ever occupied
     $testURL = admin_url('admin-ajax.php?action=wordfence_testAjax');
     if (!wfConfig::get('startScansRemotely', false)) {
         $testResult = wp_remote_post($testURL, array('timeout' => $timeout, 'blocking' => true, 'sslverify' => false, 'headers' => array()));
         wordfence::status(4, 'info', "Test result of scan start URL fetch: " . var_export($testResult, true));
     }
     $cronKey = wfUtils::bigRandomHex();
     wfConfig::set('currentCronKey', time() . ',' . $cronKey);
     if (!wfConfig::get('startScansRemotely', false) && !is_wp_error($testResult) && is_array($testResult) && strstr($testResult['body'], 'WFSCANTESTOK') !== false) {
         //ajax requests can be sent by the server to itself
         $cronURL = 'admin-ajax.php?action=wordfence_doScan&isFork=' . ($isFork ? '1' : '0') . '&cronKey=' . $cronKey;
         $cronURL = admin_url($cronURL);
         $headers = array();
         wordfence::status(4, 'info', "Starting cron with normal ajax at URL {$cronURL}");
         wp_remote_get($cronURL, array('timeout' => $timeout, 'blocking' => true, 'sslverify' => false, 'headers' => $headers));
         wordfence::status(4, 'info', "Scan process ended after forking.");
     } else {
         $cronURL = admin_url('admin-ajax.php');
         $cronURL = preg_replace('/^(https?:\\/\\/)/i', '$1noc1.wordfence.com/scanp/', $cronURL);
         $cronURL .= '?action=wordfence_doScan&isFork=' . ($isFork ? '1' : '0') . '&cronKey=' . $cronKey;
         $headers = array();
         wordfence::status(4, 'info', "Starting cron via proxy at URL {$cronURL}");
         wp_remote_get($cronURL, array('timeout' => $timeout, 'blocking' => true, 'sslverify' => false, 'headers' => $headers));
         wordfence::status(4, 'info', "Scan process ended after forking.");
     }
     return false;
     //No error
 }
Ejemplo n.º 10
0
 /**
  * @return bool Returns false if the payload is invalid, true if it processed the callback (even if the IP wasn't found).
  */
 public static function processDetectProxyCallback()
 {
     $nonce = wfConfig::get('detectProxyNonce', '');
     $testNonce = isset($_POST['nonce']) ? $_POST['nonce'] : '';
     if (empty($nonce) || empty($testNonce)) {
         return false;
     }
     if (!hash_equals($nonce, $testNonce)) {
         return false;
     }
     $ips = isset($_POST['ips']) ? $_POST['ips'] : array();
     if (empty($ips)) {
         return false;
     }
     $expandedIPs = array();
     foreach ($ips as $ip) {
         $expandedIPs[] = self::inet_pton($ip);
     }
     $checks = array('HTTP_CF_CONNECTING_IP', 'HTTP_X_REAL_IP', 'REMOTE_ADDR', 'HTTP_X_FORWARDED_FOR');
     foreach ($checks as $key) {
         if (!isset($_SERVER[$key])) {
             continue;
         }
         $testIP = self::getCleanIPAndServerVar(array(array($_SERVER[$key], $key)));
         if ($testIP === false) {
             continue;
         }
         $testIP = self::inet_pton($testIP[0]);
         if (in_array($testIP, $expandedIPs)) {
             wfConfig::set('detectProxyRecommendation', $key, wfConfig::DONT_AUTOLOAD);
             wfConfig::set('detectProxyNonce', '', wfConfig::DONT_AUTOLOAD);
             return true;
         }
     }
     wfConfig::set('detectProxyRecommendation', 'UNKNOWN', wfConfig::DONT_AUTOLOAD);
     wfConfig::set('detectProxyNonce', '', wfConfig::DONT_AUTOLOAD);
     return true;
 }
Ejemplo n.º 11
0
 public static function whitelistIP($IP)
 {
     //IP as a string in dotted quad notation e.g. '10.11.12.13'
     $IP = trim($IP);
     $user_range = new wfUserIPRange($IP);
     if (!$user_range->isValidRange()) {
         throw new Exception("The IP you provided must be in dotted quad notation or use ranges with square brackets. e.g. 10.11.12.13 or 10.11.12.[1-50]");
     }
     $whites = wfConfig::get('whitelisted', '');
     $arr = explode(',', $whites);
     $arr2 = array();
     foreach ($arr as $e) {
         if ($e == $IP) {
             return false;
         }
         $arr2[] = trim($e);
     }
     $arr2[] = $IP;
     wfConfig::set('whitelisted', implode(',', $arr2));
     return true;
 }
Ejemplo n.º 12
0
 public static function alert($subject, $alertMsg, $IP)
 {
     wfConfig::inc('totalAlertsSent');
     $emails = wfConfig::getAlertEmails();
     if (sizeof($emails) < 1) {
         return;
     }
     $IPMsg = "";
     if ($IP) {
         $IPMsg = "User IP: {$IP}\n";
         $reverse = wfUtils::reverseLookup($IP);
         if ($reverse) {
             $IPMsg .= "User hostname: " . $reverse . "\n";
         }
         $userLoc = wfUtils::getIPGeo($IP);
         if ($userLoc) {
             $IPMsg .= "User location: ";
             if ($userLoc['city']) {
                 $IPMsg .= $userLoc['city'] . ', ';
             }
             $IPMsg .= $userLoc['countryName'] . "\n";
         }
     }
     $content = wfUtils::tmpl('email_genericAlert.php', array('isPaid' => wfConfig::get('isPaid'), 'subject' => $subject, 'blogName' => get_bloginfo('name', 'raw'), 'adminURL' => get_admin_url(), 'alertMsg' => $alertMsg, 'IPMsg' => $IPMsg, 'date' => wfUtils::localHumanDate(), 'myHomeURL' => self::getMyHomeURL(), 'myOptionsURL' => self::getMyOptionsURL()));
     $shortSiteURL = preg_replace('/^https?:\\/\\//i', '', site_url());
     $subject = "[Wordfence Alert] {$shortSiteURL} " . $subject;
     $sendMax = wfConfig::get('alert_maxHourly', 0);
     if ($sendMax > 0) {
         $sendArr = wfConfig::get_ser('alertFreqTrack', array());
         if (!is_array($sendArr)) {
             $sendArr = array();
         }
         $minuteTime = floor(time() / 60);
         $totalSent = 0;
         for ($i = $minuteTime; $i > $minuteTime - 60; $i--) {
             $totalSent += isset($sendArr[$i]) ? $sendArr[$i] : 0;
         }
         if ($totalSent >= $sendMax) {
             return;
         }
         $sendArr[$minuteTime] = isset($sendArr[$minuteTime]) ? $sendArr[$minuteTime] + 1 : 1;
         wfConfig::set_ser('alertFreqTrack', $sendArr);
     }
     //Prevent duplicate emails within 1 hour:
     $hash = md5(implode(',', $emails) . ':' . $subject . ':' . $alertMsg . ':' . $IP);
     //Hex
     $lastHash = wfConfig::get('lastEmailHash', false);
     if ($lastHash) {
         $lastHashDat = explode(':', $lastHash);
         //[time, hash]
         if (time() - $lastHashDat[0] < 3600) {
             if ($lastHashDat[1] == $hash) {
                 return;
                 //Don't send because this email is identical to the previous email which was sent within the last hour.
             }
         }
     }
     wfConfig::set('lastEmailHash', time() . ':' . $hash);
     wp_mail(implode(',', $emails), $subject, $content);
 }
Ejemplo n.º 13
0
 private static function logPeakMemory()
 {
     $oldPeak = wfConfig::get('wfPeakMemory', 0);
     $peak = memory_get_peak_usage();
     if ($peak > $oldPeak) {
         wfConfig::set('wfPeakMemory', $peak);
     }
 }
Ejemplo n.º 14
0
 public static function clearScanLock()
 {
     global $wpdb;
     $wfdb = new wfDB();
     $wfdb->truncate($wpdb->base_prefix . 'wfHoover');
     wfConfig::set('wf_scanRunning', '');
 }
Ejemplo n.º 15
0
 /**
  * Get scan regexes from noc1 and add any user defined regexes, including descriptions, ID's and time added.
  * @todo add caching to this.
  * @throws Exception
  */
 protected function setupSigs()
 {
     $this->api = new wfAPI($this->apiKey, $this->wordpressVersion);
     $sigData = $this->api->call('get_patterns', array(), array());
     if (!(is_array($sigData) && isset($sigData['rules']))) {
         throw new Exception("Wordfence could not get the attack signature patterns from the scanning server.");
     }
     if (is_array($sigData['rules'])) {
         foreach ($sigData['rules'] as $key => $signatureRow) {
             list(, , $pattern) = $signatureRow;
             if (@preg_match('/' . $pattern . '/i', null) === false) {
                 wordfence::status(1, 'error', "A regex Wordfence received from it's servers is invalid. The pattern is: " . esc_html($pattern));
                 unset($sigData['rules'][$key]);
             }
         }
     }
     $extra = wfConfig::get('scan_include_extra');
     if (!empty($extra)) {
         $regexs = explode("\n", $extra);
         $id = 1000001;
         foreach ($regexs as $r) {
             $r = rtrim($r, "\r");
             try {
                 preg_match('/' . $r . '/i', "");
             } catch (Exception $e) {
                 throw new Exception("The following user defined scan pattern has an error: {$r}");
             }
             $sigData['rules'][] = array($id++, time(), $r, "User defined scan pattern");
         }
     }
     $this->patterns = $sigData;
     if (isset($this->patterns['signatureUpdateTime'])) {
         wfConfig::set('signatureUpdateTime', $this->patterns['signatureUpdateTime']);
     }
 }
 public function downgrade_license()
 {
     $api = new wfAPI('', wfUtils::getWPVersion());
     $return = array();
     try {
         $keyData = $api->call('get_anon_api_key');
         if ($keyData['ok'] && $keyData['apiKey']) {
             wfConfig::set('apiKey', $keyData['apiKey']);
             wfConfig::set('isPaid', 0);
             $return['apiKey'] = $keyData['apiKey'];
             $return['isPaid'] = 0;
             //When downgrading we must disable all two factor authentication because it can lock an admin out if we don't.
             wfConfig::set_ser('twoFactorUsers', array());
         } else {
             throw new Exception('Could not understand the response we received from the Wordfence servers when applying for a free API key.');
         }
     } catch (Exception $e) {
         $return['errorMsg'] = 'Could not fetch free API key from Wordfence: ' . htmlentities($e->getMessage());
         return $return;
     }
     $return['ok'] = 1;
     return $return;
 }
Ejemplo n.º 17
0
 public static function ajax_saveConfig_callback()
 {
     $reload = '';
     $opts = wfConfig::parseOptions();
     $emails = array();
     foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['alertEmails'])) as $email) {
         if (strlen($email) > 0) {
             array_push($emails, $email);
         }
     }
     if (sizeof($emails) > 0) {
         $badEmails = array();
         foreach ($emails as $email) {
             if (!preg_match('/^[^@]+@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,8})$/i', $email)) {
                 array_push($badEmails, $email);
             }
         }
         if (sizeof($badEmails) > 0) {
             return array('errorMsg' => "The following emails are invalid: " . implode(', ', $badEmails));
         }
         $opts['alertEmails'] = implode(',', $emails);
     } else {
         $opts['alertEmails'] = '';
     }
     $whiteIPs = array();
     foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['whitelisted'])) as $whiteIP) {
         if (strlen($whiteIP) > 0) {
             array_push($whiteIPs, $whiteIP);
         }
     }
     if (sizeof($whiteIPs) > 0) {
         $badWhiteIPs = array();
         foreach ($whiteIPs as $whiteIP) {
             if (!preg_match('/^[\\[\\]\\-\\d]+\\.[\\[\\]\\-\\d]+\\.[\\[\\]\\-\\d]+\\.[\\[\\]\\-\\d]+$/', $whiteIP)) {
                 array_push($badWhiteIPs, $whiteIP);
             }
         }
         if (sizeof($badWhiteIPs) > 0) {
             return array('errorMsg' => "Please make sure you separate your IP addresses with commas. The following whitelisted IP addresses are invalid: " . implode(', ', $badWhiteIPs));
         }
         $opts['whitelisted'] = implode(',', $whiteIPs);
     } else {
         $opts['whitelisted'] = '';
     }
     $validUsers = array();
     $invalidUsers = array();
     foreach (explode(',', $opts['liveTraf_ignoreUsers']) as $val) {
         $val = trim($val);
         if (strlen($val) > 0) {
             if (get_user_by('login', $val)) {
                 array_push($validUsers, $val);
             } else {
                 array_push($invalidUsers, $val);
             }
         }
     }
     $opts['apiKey'] = trim($opts['apiKey']);
     if ($opts['apiKey'] && !preg_match('/^[a-fA-F0-9]+$/', $opts['apiKey'])) {
         //User entered something but it's garbage.
         return array('errorMsg' => "You entered an API key but it is not in a valid format. It must consist only of characters A to F and 0 to 9.");
     }
     if (sizeof($invalidUsers) > 0) {
         return array('errorMsg' => "The following users you selected to ignore in live traffic reports are not valid on this system: " . implode(', ', $invalidUsers));
     }
     if (sizeof($validUsers) > 0) {
         $opts['liveTraf_ignoreUsers'] = implode(',', $validUsers);
     } else {
         $opts['liveTraf_ignoreUsers'] = '';
     }
     $validIPs = array();
     $invalidIPs = array();
     foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['liveTraf_ignoreIPs'])) as $val) {
         if (strlen($val) > 0) {
             if (preg_match('/^\\d+\\.\\d+\\.\\d+\\.\\d+$/', $val)) {
                 array_push($validIPs, $val);
             } else {
                 array_push($invalidIPs, $val);
             }
         }
     }
     if (sizeof($invalidIPs) > 0) {
         return array('errorMsg' => "The following IPs you selected to ignore in live traffic reports are not valid: " . implode(', ', $invalidIPs));
     }
     if (sizeof($validIPs) > 0) {
         $opts['liveTraf_ignoreIPs'] = implode(',', $validIPs);
     }
     if (preg_match('/[a-zA-Z0-9\\d]+/', $opts['liveTraf_ignoreUA'])) {
         $opts['liveTraf_ignoreUA'] = trim($opts['liveTraf_ignoreUA']);
     } else {
         $opts['liveTraf_ignoreUA'] = '';
     }
     if (!$opts['other_WFNet']) {
         $wfdb = new wfDB();
         global $wpdb;
         $p = $wpdb->base_prefix;
         $wfdb->queryWrite("delete from {$p}" . "wfBlocks where wfsn=1 and permanent=0");
     }
     if ($opts['howGetIPs'] != wfConfig::get('howGetIPs', '')) {
         $reload = 'reload';
     }
     foreach ($opts as $key => $val) {
         if ($key != 'apiKey') {
             //Don't save API key yet
             wfConfig::set($key, $val);
         }
     }
     $paidKeyMsg = false;
     if (!$opts['apiKey']) {
         //Empty API key (after trim above), then try to get one.
         $api = new wfAPI('', wfUtils::getWPVersion());
         try {
             $keyData = $api->call('get_anon_api_key');
             if ($keyData['ok'] && $keyData['apiKey']) {
                 wfConfig::set('apiKey', $keyData['apiKey']);
                 wfConfig::set('isPaid', 0);
                 $reload = 'reload';
             } else {
                 throw new Exception("We could not understand the Wordfence server's response because it did not contain an 'ok' and 'apiKey' element.");
             }
         } catch (Exception $e) {
             return array('errorMsg' => "Your options have been saved, but we encountered a problem. You left your API key blank, so we tried to get you a free API key from the Wordfence servers. However we encountered a problem fetching the free key: " . $e->getMessage());
         }
     } else {
         if ($opts['apiKey'] != wfConfig::get('apiKey')) {
             $api = new wfAPI($opts['apiKey'], wfUtils::getWPVersion());
             try {
                 $res = $api->call('check_api_key', array(), array());
                 if ($res['ok'] && isset($res['isPaid'])) {
                     wfConfig::set('apiKey', $opts['apiKey']);
                     $reload = 'reload';
                     wfConfig::set('isPaid', $res['isPaid']);
                     //res['isPaid'] is boolean coming back as JSON and turned back into PHP struct. Assuming JSON to PHP handles bools.
                     if ($res['isPaid']) {
                         $paidKeyMsg = true;
                     }
                 } else {
                     throw new Exception("We could not understand the Wordfence API server reply when updating your API key.");
                 }
             } catch (Exception $e) {
                 return array('errorMsg' => "Your options have been saved. However we noticed you changed your API key and we tried to verify it with the Wordfence servers and received an error: " . $e->getMessage());
             }
         }
     }
     //Clears next scan if scans are disabled. Schedules next scan if enabled.
     if ($err) {
         return array('errorMsg' => $err);
     } else {
         return array('ok' => 1, 'reload' => $reload, 'paidKeyMsg' => $paidKeyMsg);
     }
 }