wfWAFIPBlocksController.php
16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
<?php
class wfWAFIPBlocksController
{
const WFWAF_BLOCK_UAREFIPRANGE = 'UA/Referrer/IP Range not allowed';
const WFWAF_BLOCK_COUNTRY = 'blocked access via country blocking';
const WFWAF_BLOCK_COUNTRY_REDIR = 'blocked access via country blocking and redirected to URL';
const WFWAF_BLOCK_COUNTRY_BYPASS_REDIR = 'redirected to bypass URL';
const WFWAF_BLOCK_WFSN = 'Blocked by Wordfence Security Network';
protected static $_currentController = null;
public static function currentController() {
if (self::$_currentController === null) {
self::$_currentController = new wfWAFIPBlocksController();
}
return self::$_currentController;
}
public static function setCurrentController($currentController) {
self::$_currentController = $currentController;
}
public static function synchronizeConfigSettings() {
if (!class_exists('wfConfig')) { // Ensure this is only called when WordPress and the plugin are fully loaded
return;
}
static $isSynchronizing = false;
if ($isSynchronizing) {
return;
}
$isSynchronizing = true;
global $wpdb;
$db = new wfDB();
// Pattern Blocks
$r1 = $db->querySelect("SELECT id, blockType, blockString FROM {$wpdb->base_prefix}wfBlocksAdv");
$patternBlocks = array();
foreach ($r1 as $blockRec) {
if ($blockRec['blockType'] == 'IU') {
$bDat = explode('|', $blockRec['blockString']);
$ipRange = isset($bDat[0]) ? $bDat[0] : '';
$uaPattern = isset($bDat[1]) ? $bDat[1] : '';
$refPattern = isset($bDat[2]) ? $bDat[2] : '';
$hostnamePattern = isset($bDat[3]) ? $bDat[3] : '';
$patternBlocks[] = array('id' => $blockRec['id'], 'ipRange' => $ipRange, 'hostnamePattern' => $hostnamePattern, 'uaPattern' => $uaPattern, 'refPattern' => $refPattern);
}
}
// Country Blocks
$wfLog = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
$cblCookie = $wfLog->getCBLCookieVal(); //Ensure we have the bypass cookie option set
$countryBlocks = array();
$countryBlocks['action'] = wfConfig::get('cbl_action', false);
$countryBlocks['loggedInBlocked'] = wfConfig::get('cbl_loggedInBlocked', false);
$countryBlocks['loginFormBlocked'] = wfConfig::get('cbl_loginFormBlocked', false);
$countryBlocks['restOfSiteBlocked'] = wfConfig::get('cbl_restOfSiteBlocked', false);
$countryBlocks['bypassRedirURL'] = wfConfig::get('cbl_bypassRedirURL', '');
$countryBlocks['bypassRedirDest'] = wfConfig::get('cbl_bypassRedirDest', '');
$countryBlocks['bypassViewURL'] = wfConfig::get('cbl_bypassViewURL', '');
$countryBlocks['redirURL'] = wfConfig::get('cbl_redirURL', '');
$countryBlocks['countries'] = explode(',', wfConfig::get('cbl_countries', ''));
$countryBlocks['cookieVal'] = $cblCookie;
//Other Blocks
$otherBlocks = array('blockedTime' => wfConfig::get('blockedTime', 0));
$otherBlockEntries = $db->querySelect("SELECT IP, blockedTime, reason, permanent, wfsn FROM {$wpdb->base_prefix}wfBlocks WHERE permanent = 1 OR (blockedTime + %d > unix_timestamp())", $otherBlocks['blockedTime']);
$otherBlocks['blocks'] = (is_array($otherBlockEntries) ? $otherBlockEntries : array());
foreach ($otherBlocks['blocks'] as &$b) {
$b['IP'] = base64_encode($b['IP']);
}
//Lockouts
$lockoutSecs = wfConfig::get('loginSec_lockoutMins') * 60;
$lockouts = array('lockedOutTime' => $lockoutSecs);
$lockoutEntries = $db->querySelect("SELECT IP, blockedTime, reason FROM {$wpdb->base_prefix}wfLockedOut WHERE (blockedTime + %d) > UNIX_TIMESTAMP() ORDER BY blockedTime DESC, IP DESC", $lockoutSecs);
$lockouts['lockouts'] = (is_array($lockoutEntries) ? $lockoutEntries : array());
foreach ($lockouts['lockouts'] as &$l) {
$l['IP'] = base64_encode($l['IP']);
}
// Save it
try {
$patternBlocksJSON = wfWAFUtils::json_encode($patternBlocks);
wfWAF::getInstance()->getStorageEngine()->setConfig('patternBlocks', $patternBlocksJSON);
$countryBlocksJSON = wfWAFUtils::json_encode($countryBlocks);
wfWAF::getInstance()->getStorageEngine()->setConfig('countryBlocks', $countryBlocksJSON);
$otherBlocksJSON = wfWAFUtils::json_encode($otherBlocks);
wfWAF::getInstance()->getStorageEngine()->setConfig('otherBlocks', $otherBlocksJSON);
$lockoutsJSON = wfWAFUtils::json_encode($lockouts);
wfWAF::getInstance()->getStorageEngine()->setConfig('lockouts', $lockoutsJSON);
wfWAF::getInstance()->getStorageEngine()->setConfig('advancedBlockingEnabled', wfConfig::get('firewallEnabled'));
wfWAF::getInstance()->getStorageEngine()->setConfig('disableWAFIPBlocking', wfConfig::get('disableWAFIPBlocking'));
}
catch (Exception $e) {
// Do nothing
}
$isSynchronizing = false;
}
/**
* @param wfWAFRequest $request
* @return bool|string If not blocked, returns false. Otherwise a string of the reason it was blocked or true.
*/
public function shouldBlockRequest($request) {
// Checking the user whitelist is done before reaching this call
$ip = $request->getIP();
//Check the system whitelist
if ($this->checkForWhitelisted($ip)) {
return false;
}
//Let the plugin handle these
$wfFunc = $request->getQueryString('_wfsf');
if ($wfFunc == 'unlockEmail' || $wfFunc == 'unlockAccess') { // Can't check validity here, let it pass through to plugin level where it can
return false;
}
$logHuman = $request->getQueryString('wordfence_logHuman');
if ($logHuman !== null) {
return false;
}
//Start block checks
$ipNum = wfWAFUtils::inet_pton($ip);
$hostname = null;
$ua = $request->getHeaders('User-Agent'); if ($ua === null) { $ua = ''; }
$referer = $request->getHeaders('Referer'); if ($referer === null) { $referer = ''; }
$isPaid = false;
try {
$isPaid = wfWAF::getInstance()->getStorageEngine()->getConfig('isPaid');
$pluginABSPATH = wfWAF::getInstance()->getStorageEngine()->getConfig('pluginABSPATH');
$patternBlocksJSON = wfWAF::getInstance()->getStorageEngine()->getConfig('patternBlocks');
$countryBlocksJSON = wfWAF::getInstance()->getStorageEngine()->getConfig('countryBlocks');
$otherBlocksJSON = wfWAF::getInstance()->getStorageEngine()->getConfig('otherBlocks');
$lockoutsJSON = wfWAF::getInstance()->getStorageEngine()->getConfig('lockouts');
}
catch (Exception $e) {
// Do nothing
}
if (isset($_SERVER['SCRIPT_FILENAME']) && (strpos($_SERVER['SCRIPT_FILENAME'], $pluginABSPATH . "wp-admin/") === 0 || strpos($_SERVER['SCRIPT_FILENAME'], $pluginABSPATH . "wp-content/") === 0 || strpos($_SERVER['SCRIPT_FILENAME'], $pluginABSPATH . "wp-includes/") === 0)) {
return false; //Rely on WordPress's own access control and blocking at the plugin level
}
// Pattern Blocks from the Advanced Blocking page (IP Range, UA, Referer)
$patternBlocks = @wfWAFUtils::json_decode($patternBlocksJSON, true);
if (is_array($patternBlocks)) {
// Instead of a long block of if/else statements, using bitshifting to generate an expected value and a found value
$ipRangeOffset = 1;
$uaPatternOffset = 2;
$refPatternOffset = 3;
foreach ($patternBlocks as $b) {
$expectedBits = 0;
$foundBits = 0;
if (!empty($b['ipRange'])) {
$expectedBits |= (1 << $ipRangeOffset);
list($start_range, $end_range) = explode('-', $b['ipRange']);
if (preg_match('/[\.:]/', $start_range)) {
$start_range = wfWAFUtils::inet_pton($start_range);
$end_range = wfWAFUtils::inet_pton($end_range);
} else {
$start_range = wfWAFUtils::inet_pton(long2ip($start_range));
$end_range = wfWAFUtils::inet_pton(long2ip($end_range));
}
if (strcmp($ipNum, $start_range) >= 0 && strcmp($ipNum, $end_range) <= 0) {
$foundBits |= (1 << $ipRangeOffset);
}
}
if (!empty($b['hostnamePattern'])) {
$expectedBits |= (1 << $ipRangeOffset);
if ($hostname === null) {
$hostname = wfWAFUtils::reverseLookup($ip);
}
if (preg_match(wfWAFUtils::patternToRegex($b['hostnamePattern']), $hostname)) {
$foundBits |= (1 << $ipRangeOffset);
}
}
if (!empty($b['uaPattern'])) {
$expectedBits |= (1 << $uaPatternOffset);
if (wfWAFUtils::isUABlocked($b['uaPattern'], $ua)) {
$foundBits |= (1 << $uaPatternOffset);
}
}
if (!empty($b['refPattern'])) {
$expectedBits |= (1 << $refPatternOffset);
if (wfWAFUtils::isRefererBlocked($b['refPattern'], $referer)) {
$foundBits |= (1 << $refPatternOffset);
}
}
if ($foundBits === $expectedBits && $expectedBits > 0) {
return array('action' => self::WFWAF_BLOCK_UAREFIPRANGE, 'id' => $b['id']);
}
}
}
// End Pattern Blocks
// Country Blocking
if ($isPaid) {
$countryBlocks = @wfWAFUtils::json_decode($countryBlocksJSON, true);
if (is_array($countryBlocks)) {
$blockedCountries = $countryBlocks['countries'];
$bareRequestURI = wfWAFUtils::extractBareURI($request->getURI());
$bareBypassRedirURI = wfWAFUtils::extractBareURI($countryBlocks['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.
if ($countryBlocks['bypassRedirDest']) {
setcookie('wfCBLBypass', $countryBlocks['cookieVal'], time() + (86400 * 365), '/', null, null, true);
return array('action' => self::WFWAF_BLOCK_COUNTRY_BYPASS_REDIR);
}
}
$bareBypassViewURI = wfWAFUtils::extractBareURI($countryBlocks['bypassViewURL']);
if ($bareBypassViewURI && $bareBypassViewURI == $bareRequestURI) {
setcookie('wfCBLBypass', $countryBlocks['cookieVal'], time() + (86400 * 365), '/', null, null, true);
$skipCountryBlocking = true;
}
$bypassCookieSet = false;
$bypassCookie = $request->getCookies('wfCBLBypass');
if (isset($bypassCookie) && $bypassCookie == $countryBlocks['cookieVal']) {
$bypassCookieSet = true;
}
if (!$skipCountryBlocking && $blockedCountries && !$bypassCookieSet) {
$isAuthRequest = (strpos($bareRequestURI, '/wp-login.php') !== false);
$isXMLRPC = (strpos($bareRequestURI, '/xmlrpc.php') !== false);
$isUserLoggedIn = wfWAF::getInstance()->parseAuthCookie() !== false;
// If everything is checked, make sure this always runs.
if ($countryBlocks['loggedInBlocked'] && $countryBlocks['loginFormBlocked'] && $countryBlocks['restOfSiteBlocked']) {
if ($blocked = $this->checkForBlockedCountry($countryBlocks, $ip, $bareRequestURI)) { return $blocked; }
}
// Block logged in users.
if ($countryBlocks['loggedInBlocked'] && $isUserLoggedIn) {
if ($blocked = $this->checkForBlockedCountry($countryBlocks, $ip, $bareRequestURI)) { return $blocked; }
}
// Block the login form itself and any attempt to authenticate.
if ($countryBlocks['loginFormBlocked'] && $isAuthRequest) {
if ($blocked = $this->checkForBlockedCountry($countryBlocks, $ip, $bareRequestURI)) { return $blocked; }
}
// Block requests that aren't to the login page, xmlrpc.php, or a user already logged in.
if ($countryBlocks['restOfSiteBlocked'] && !$isAuthRequest && !$isXMLRPC && !$isUserLoggedIn) {
if ($blocked = $this->checkForBlockedCountry($countryBlocks, $ip, $bareRequestURI)) { return $blocked; }
}
// XMLRPC is inaccesible when public portion of the site and auth is disabled.
if ($countryBlocks['loginFormBlocked'] && $countryBlocks['restOfSiteBlocked'] && $isXMLRPC) {
if ($blocked = $this->checkForBlockedCountry($countryBlocks, $ip, $bareRequestURI)) { return $blocked; }
}
// Any bypasses and other block possibilities will be checked at the plugin level once WordPress loads
}
}
}
// End Country Blocking
// Other Blocks
$otherBlocks = @wfWAFUtils::json_decode($otherBlocksJSON, true);
if (is_array($otherBlocks)) {
$blockedTime = $otherBlocks['blockedTime'];
$blocks = $otherBlocks['blocks'];
$bareRequestURI = wfWAFUtils::extractBareURI($request->getURI());
$isAuthRequest = (stripos($bareRequestURI, '/wp-login.php') !== false);
foreach ($blocks as $b) {
if (!$b['permanent'] && ($b['blockedTime'] + $blockedTime) < time()) {
continue;
}
if (base64_decode($b['IP']) != $ipNum) {
continue;
}
if ($isAuthRequest && isset($b['wfsn']) && $b['wfsn']) {
return array('action' => self::WFWAF_BLOCK_WFSN);
}
return array('action' => (empty($b['reason']) ? '' : $b['reason']), 'block' => true);
}
}
// End Other Blocks
// Lockouts
$lockouts = @wfWAFUtils::json_decode($lockoutsJSON, true);
if (is_array($lockouts)) {
$lockedOutTime = $lockouts['lockedOutTime'];
$lockouts = $lockouts['lockouts'];
foreach ($lockouts as $l) {
if ($l['blockedTime'] + $lockedOutTime < time()) {
continue;
}
if (base64_decode($l['IP']) != $ipNum) {
continue;
}
$isAuthRequest = (stripos($bareRequestURI, '/wp-login.php') !== false) || (stripos($bareRequestURI, '/xmlrpc.php') !== false);
if (!$isAuthRequest) {
continue;
}
return array('action' => (empty($l['reason']) ? '' : $l['reason']), 'lockout' => true);
}
}
// End Lockouts
return false;
}
public function countryRedirURL($countryBlocks = null) {
if (!isset($countryBlocks)) {
try {
$countryBlocksJSON = wfWAF::getInstance()->getStorageEngine()->getConfig('countryBlocks');
}
catch (Exception $e) {
return false;
}
}
$countryBlocks = @wfWAFUtils::json_decode($countryBlocksJSON, true);
if (is_array($countryBlocks)) {
if ($countryBlocks['action'] == 'redir') {
return $countryBlocks['redirURL'];
}
}
return false;
}
public function countryBypassRedirURL($countryBlocks = null) {
if (!isset($countryBlocks)) {
try {
$countryBlocksJSON = wfWAF::getInstance()->getStorageEngine()->getConfig('countryBlocks');
}
catch (Exception $e) {
return false;
}
}
$countryBlocks = @wfWAFUtils::json_decode($countryBlocksJSON, true);
if (is_array($countryBlocks)) {
return $countryBlocks['bypassRedirDest'];
}
return false;
}
protected function checkForBlockedCountry($countryBlock, $ip, $bareRequestURI) {
try {
$homeURL = wfWAF::getInstance()->getStorageEngine()->getConfig('homeURL');
}
catch (Exception $e) {
//Do nothing
}
$bareRequestURI = rtrim($bareRequestURI, '/\\');
if ($country = $this->ip2Country($ip)) {
foreach ($countryBlock['countries'] as $blocked) {
if (strtoupper($blocked) == strtoupper($country)) {
if ($countryBlock['action'] == 'redir') {
$redirURL = $countryBlock['redirURL'];
$eRedirHost = wfWAFUtils::extractHostname($redirURL);
$isExternalRedir = false;
if ($eRedirHost && $homeURL && $eRedirHost != wfWAFUtils::extractHostname($homeURL)) {
$isExternalRedir = true;
}
if ((!$isExternalRedir) && rtrim(wfWAFUtils::extractBareURI($redirURL), '/\\') == $bareRequestURI){ //Is this the URI we want to redirect to, then don't block it
//Do nothing
}
else {
return array('action' => self::WFWAF_BLOCK_COUNTRY_REDIR);
}
}
else {
return array('action' => self::WFWAF_BLOCK_COUNTRY);
}
}
}
}
return false;
}
protected function checkForWhitelisted($ip) {
$wordfenceLib = realpath(dirname(__FILE__) . '/../lib');
include($wordfenceLib . '/wfIPWhitelist.php'); // defines $wfIPWhitelist
foreach ($wfIPWhitelist as $group) {
foreach ($group as $subnet) {
if ($subnet instanceof wfWAFUserIPRange) { //Not currently reached
if ($subnet->isIPInRange($ip)) {
return true;
}
} elseif (wfWAFUtils::subnetContainsIP($subnet, $ip)) {
return true;
}
}
}
return false;
}
protected function ip2Country($ip){
$wordfenceLib = realpath(dirname(__FILE__) . '/../lib');
require_once(dirname(__FILE__) . '/wfWAFGeoIP.php');
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false) {
$gi = geoip_open($wordfenceLib . "/GeoIPv6.dat", WF_GEOIP_STANDARD);
$country = geoip_country_code_by_addr_v6($gi, $ip);
} else {
$gi = geoip_open($wordfenceLib . "/GeoIP.dat", WF_GEOIP_STANDARD);
$country = geoip_country_code_by_addr($gi, $ip);
}
geoip_close($gi);
return $country ? $country : '';
}
}