/** * Convert CIDR notation to a wfUserIPRange object * * @param string $cidr * @return wfUserIPRange */ public static function CIDR2wfUserIPRange($cidr) { list($network, $prefix) = array_pad(explode('/', $cidr, 2), 2, null); $ip_range = new wfUserIPRange(); if (filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { // If no prefix was supplied, 32 is implied for IPv4 if ($prefix === null) { $prefix = 32; } // Validate the IPv4 network prefix if ($prefix < 0 || $prefix > 32) { return $ip_range; } // Increase the IPv4 network prefix to work in the IPv6 address space $prefix += 96; } else { // If no prefix was supplied, 128 is implied for IPv6 if ($prefix === null) { $prefix = 128; } // Validate the IPv6 network prefix if ($prefix < 1 || $prefix > 128) { return $ip_range; } } // Convert human readable address to 128 bit (IPv6) binary string // Note: self::inet_pton converts IPv4 addresses to IPv6 compatible versions $binary_network = self::inet_pton($network); $binary_mask = wfHelperBin::str2bin(str_pad(str_repeat('1', $prefix), 128, '0', STR_PAD_RIGHT)); // Calculate first and last address $binary_first = $binary_network & $binary_mask; $binary_last = $binary_network | ~$binary_mask; // Convert binary addresses back to human readable strings $first = self::inet_ntop($binary_first); $last = self::inet_ntop($binary_last); if (filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { $first = self::expandIPv6Address($first); $last = self::expandIPv6Address($last); } // Split addresses into segments $first_array = preg_split('/[\\.\\:]/', $first); $last_array = preg_split('/[\\.\\:]/', $last); // Make sure arrays are the same size. IPv6 '::' could cause problems otherwise. // The strlen filter should leave zeros in place $first_array = array_pad(array_filter($first_array, 'strlen'), count($last_array), '0'); $range_segments = array(); foreach ($first_array as $index => $segment) { if ($segment === $last_array[$index]) { $range_segments[] = str_pad(ltrim($segment, '0'), 1, '0'); } else { if ($segment === '' || $last_array[$index] === '') { $range_segments[] = ''; } else { $range_segments[] = "[" . str_pad(ltrim($segment, '0'), 1, '0') . "-" . str_pad(ltrim($last_array[$index], '0'), 1, '0') . "]"; } } } $delimiter = filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ? '.' : ':'; $ip_range->setIPString(implode($delimiter, $range_segments)); return $ip_range; }
public static function ajax_saveConfig_callback() { $reload = ''; $opts = wfConfig::parseOptions(); // These are now on the Diagnostics page, so they aren't sent across. foreach (self::$diagnosticParams as $param) { $opts[$param] = wfConfig::get($param); } $emails = array(); foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['alertEmails'])) as $email) { if (strlen($email) > 0) { $emails[] = $email; } } if (sizeof($emails) > 0) { $badEmails = array(); foreach ($emails as $email) { if (!preg_match('/^[^@]+@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,11})$/i', $email)) { $badEmails[] = $email; } } if (sizeof($badEmails) > 0) { return array('errorMsg' => "The following emails are invalid: " . wp_kses(implode(', ', $badEmails), array())); } $opts['alertEmails'] = implode(',', $emails); } else { $opts['alertEmails'] = ''; } $opts['scan_exclude'] = wfUtils::cleanupOneEntryPerLine($opts['scan_exclude']); foreach (explode("\n", $opts['scan_include_extra']) as $regex) { if (@preg_match("/{$regex}/", "") === FALSE) { return array('errorMsg' => "\"" . esc_html($regex) . "\" is not a valid regular expression"); } } $whiteIPs = array(); foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['whitelisted'])) as $whiteIP) { if (strlen($whiteIP) > 0) { $whiteIPs[] = $whiteIP; } } if (sizeof($whiteIPs) > 0) { $badWhiteIPs = array(); $range = new wfUserIPRange(); foreach ($whiteIPs as $whiteIP) { $range->setIPString($whiteIP); if (!$range->isValidRange()) { $badWhiteIPs[] = $whiteIP; } } if (sizeof($badWhiteIPs) > 0) { return array('errorMsg' => "Please make sure you separate your IP addresses with commas. The following whitelisted IP addresses are invalid: " . wp_kses(implode(', ', $badWhiteIPs), array())); } $opts['whitelisted'] = implode(',', $whiteIPs); } else { $opts['whitelisted'] = ''; } $validUsers = array(); $invalidUsers = array(); foreach (explode(',', $opts['liveTraf_ignoreUsers']) as $val) { $val = trim($val); if (strlen($val) > 0) { if (get_user_by('login', $val)) { $validUsers[] = $val; } else { $invalidUsers[] = $val; } } } $opts['loginSec_userBlacklist'] = wfUtils::cleanupOneEntryPerLine($opts['loginSec_userBlacklist']); $opts['apiKey'] = trim($opts['apiKey']); if ($opts['apiKey'] && !preg_match('/^[a-fA-F0-9]+$/', $opts['apiKey'])) { //User entered something but it's garbage. return array('errorMsg' => "You entered an API key but it is not in a valid format. It must consist only of characters A to F and 0 to 9."); } if (sizeof($invalidUsers) > 0) { return array('errorMsg' => "The following users you selected to ignore in live traffic reports are not valid on this system: " . wp_kses(implode(', ', $invalidUsers), array())); } if (sizeof($validUsers) > 0) { $opts['liveTraf_ignoreUsers'] = implode(',', $validUsers); } else { $opts['liveTraf_ignoreUsers'] = ''; } $validIPs = array(); $invalidIPs = array(); foreach (explode(',', preg_replace('/[\\r\\n\\s\\t]+/', '', $opts['liveTraf_ignoreIPs'])) as $val) { if (strlen($val) > 0) { if (wfUtils::isValidIP($val)) { $validIPs[] = $val; } else { $invalidIPs[] = $val; } } } if (sizeof($invalidIPs) > 0) { return array('errorMsg' => "The following IPs you selected to ignore in live traffic reports are not valid: " . wp_kses(implode(', ', $invalidIPs), array())); } if (sizeof($validIPs) > 0) { $opts['liveTraf_ignoreIPs'] = implode(',', $validIPs); } if (preg_match('/[a-zA-Z0-9\\d]+/', $opts['liveTraf_ignoreUA'])) { $opts['liveTraf_ignoreUA'] = trim($opts['liveTraf_ignoreUA']); } else { $opts['liveTraf_ignoreUA'] = ''; } if (!$opts['other_WFNet']) { $wfdb = new wfDB(); global $wpdb; $p = $wpdb->base_prefix; $wfdb->queryWrite("delete from {$p}" . "wfBlocks where wfsn=1 and permanent=0"); } if ($opts['howGetIPs'] != wfConfig::get('howGetIPs', '')) { $reload = 'reload'; } $regenerateHtaccess = false; if (wfConfig::get('bannedURLs', false) != $opts['bannedURLs']) { $regenerateHtaccess = true; } if (!is_numeric($opts['liveTraf_maxRows'])) { return array('errorMsg' => 'Please enter a number for the amount of Live Traffic data to store.'); } foreach ($opts as $key => $val) { if ($key != 'apiKey') { //Don't save API key yet wfConfig::set($key, $val); } } if ($regenerateHtaccess && wfConfig::get('cacheType') == 'falcon') { wfCache::addHtaccessCode('add'); } if ($opts['autoUpdate'] == '1') { wfConfig::enableAutoUpdate(); } else { if ($opts['autoUpdate'] == '0') { wfConfig::disableAutoUpdate(); } } try { if ($opts['disableCodeExecutionUploads']) { wfConfig::disableCodeExecutionForUploads(); } else { wfConfig::removeCodeExecutionProtectionForUploads(); } } catch (wfConfigException $e) { return array('errorMsg' => $e->getMessage()); } if (!empty($opts['email_summary_enabled'])) { wfConfig::set('email_summary_enabled', 1); wfConfig::set('email_summary_interval', $opts['email_summary_interval']); wfConfig::set('email_summary_excluded_directories', $opts['email_summary_excluded_directories']); wfActivityReport::scheduleCronJob(); } else { wfConfig::set('email_summary_enabled', 0); wfActivityReport::disableCronJob(); } if (wfConfig::get('other_hideWPVersion')) { wfUtils::hideReadme(); } else { wfUtils::showReadme(); } $paidKeyMsg = false; if (!$opts['apiKey']) { //Empty API key (after trim above), then try to get one. $api = new wfAPI('', wfUtils::getWPVersion()); try { $keyData = $api->call('get_anon_api_key'); if ($keyData['ok'] && $keyData['apiKey']) { wfConfig::set('apiKey', $keyData['apiKey']); wfConfig::set('isPaid', 0); $reload = 'reload'; } else { throw new Exception("We could not understand the Wordfence server's response because it did not contain an 'ok' and 'apiKey' element."); } } catch (Exception $e) { return array('errorMsg' => "Your options have been saved, but we encountered a problem. You left your API key blank, so we tried to get you a free API key from the Wordfence servers. However we encountered a problem fetching the free key: " . wp_kses($e->getMessage(), array())); } } else { if ($opts['apiKey'] != wfConfig::get('apiKey')) { $api = new wfAPI($opts['apiKey'], wfUtils::getWPVersion()); try { $res = $api->call('check_api_key', array(), array()); if ($res['ok'] && isset($res['isPaid'])) { wfConfig::set('apiKey', $opts['apiKey']); $reload = 'reload'; wfConfig::set('isPaid', $res['isPaid']); //res['isPaid'] is boolean coming back as JSON and turned back into PHP struct. Assuming JSON to PHP handles bools. if ($res['isPaid']) { $paidKeyMsg = true; } } else { throw new Exception("We could not understand the Wordfence API server reply when updating your API key."); } } catch (Exception $e) { return array('errorMsg' => "Your options have been saved. However we noticed you changed your API key and we tried to verify it with the Wordfence servers and received an error: " . wp_kses($e->getMessage(), array())); } } else { $api = new wfAPI($opts['apiKey'], wfUtils::getWPVersion()); $api->call('ping_api_key', array(), array()); } } return array('ok' => 1, 'reload' => $reload, 'paidKeyMsg' => $paidKeyMsg); }