-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebdecoy.php
More file actions
3379 lines (2971 loc) · 126 KB
/
Copy pathwebdecoy.php
File metadata and controls
3379 lines (2971 loc) · 126 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin Name: WebDecoy Bot Detection
* Plugin URI: https://webdecoy.com/wordpress
* Description: Protect your WordPress site from bots, spam, and carding attacks with WebDecoy's advanced threat detection.
* Version: 2.4.0
* Requires at least: 6.1
* Requires PHP: 7.4
* Author: WebDecoy
* Author URI: https://webdecoy.com
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: webdecoy
* Domain Path: /languages
* WC requires at least: 5.0
* WC tested up to: 9.4
*
* @package WebDecoy
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
// PHP 7.4 polyfills for functions available in PHP 8.0+
if (!function_exists('str_ends_with')) {
function str_ends_with(string $haystack, string $needle): bool
{
if ($needle === '') {
return true;
}
return substr($haystack, -strlen($needle)) === $needle;
}
}
if (!function_exists('str_starts_with')) {
function str_starts_with(string $haystack, string $needle): bool
{
return strncmp($haystack, $needle, strlen($needle)) === 0;
}
}
// Plugin constants
define('WEBDECOY_VERSION', '2.4.0');
define('WEBDECOY_PLUGIN_FILE', __FILE__);
define('WEBDECOY_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('WEBDECOY_PLUGIN_URL', plugin_dir_url(__FILE__));
define('WEBDECOY_PLUGIN_BASENAME', plugin_basename(__FILE__));
// Load the SDK (bundled)
$sdk_paths = [
WEBDECOY_PLUGIN_DIR . 'sdk/',
];
$sdk_loaded = false;
foreach ($sdk_paths as $sdk_path) {
// Try Composer autoloader first
if (file_exists($sdk_path . 'vendor/autoload.php')) {
require_once $sdk_path . 'vendor/autoload.php';
$sdk_loaded = true;
break;
}
// Fall back to manual includes
if (file_exists($sdk_path . 'src/Client.php')) {
require_once $sdk_path . 'src/Exception/WebDecoyException.php';
require_once $sdk_path . 'src/Detection.php';
require_once $sdk_path . 'src/DetectionResult.php';
require_once $sdk_path . 'src/GoodBotList.php';
require_once $sdk_path . 'src/SignalCollector.php';
require_once $sdk_path . 'src/BotDetector.php';
require_once $sdk_path . 'src/Client.php';
// Rules engine (tripwires, filters, rate-limit rules) — pure logic.
require_once $sdk_path . 'src/Rules/RuleInterface.php';
require_once $sdk_path . 'src/Rules/RuleContext.php';
require_once $sdk_path . 'src/Rules/RuleResult.php';
require_once $sdk_path . 'src/Rules/RuleEngineResult.php';
require_once $sdk_path . 'src/Rules/ViolationEvent.php';
require_once $sdk_path . 'src/Rules/RuleEngine.php';
require_once $sdk_path . 'src/Rules/TripwireRule.php';
// Filter expression language (tokenizer → parser → evaluator).
require_once $sdk_path . 'src/Rules/Filter/FilterSyntaxException.php';
require_once $sdk_path . 'src/Rules/Filter/Tokenizer.php';
require_once $sdk_path . 'src/Rules/Filter/Parser.php';
require_once $sdk_path . 'src/Rules/Filter/Evaluator.php';
require_once $sdk_path . 'src/Rules/FilterRule.php';
$sdk_loaded = true;
break;
}
}
if (!$sdk_loaded) {
add_action('admin_notices', function () {
echo '<div class="notice notice-error"><p>';
echo '<strong>' . esc_html__('WebDecoy:', 'webdecoy') . '</strong> ' . esc_html__('SDK not found. Please reinstall the plugin.', 'webdecoy');
echo '</p></div>';
});
return;
}
/**
* Main WebDecoy Plugin Class
*/
final class WebDecoy_Plugin
{
/**
* Plugin instance
*
* @var WebDecoy_Plugin|null
*/
private static ?WebDecoy_Plugin $instance = null;
/**
* Plugin options
*
* @var array
*/
private array $options = [];
/**
* Set by build_rule_engine() when a configured filter rule references an
* ip.* field, signalling build_rule_context() to fetch IP enrichment.
*
* @var bool
*/
private bool $rules_need_enrichment = false;
/**
* WebDecoy API Client
*
* @var \WebDecoy\Client|null
*/
private ?\WebDecoy\Client $client = null;
/**
* Bot Detector
*
* @var \WebDecoy\BotDetector|null
*/
private ?\WebDecoy\BotDetector $detector = null;
/**
* Cloud connect controller (one-click connect + entitlements sync).
*
* @var WebDecoy_Cloud_Connect|null
*/
private ?WebDecoy_Cloud_Connect $cloud_connect = null;
/**
* Actor feed controller (hourly network-block sync — Pro+ only).
*
* @var WebDecoy_Actor_Feed|null
*/
private ?WebDecoy_Actor_Feed $actor_feed = null;
/**
* Post-CRITICAL moment controller (one-shot upgrade notice).
*
* @var WebDecoy_Critical_Moment|null
*/
private ?WebDecoy_Critical_Moment $critical_moment = null;
/**
* Get plugin instance
*
* @return WebDecoy_Plugin
*/
public static function instance(): WebDecoy_Plugin
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Constructor
*/
private function __construct()
{
$this->load_options();
$this->init_hooks();
}
/**
* Load plugin options
*/
private function load_options(): void
{
$defaults = [
// API Configuration - only API key required now
'api_key' => '',
// Publishable site key (org id) for the browser clearance client.
// Distinct from the secret api_key: minting needs no secret, so this
// is safe to expose in page markup. Enables silent wd_clearance
// cookie minting so tripwire/decoy hits bind to a device fingerprint.
'site_key' => '',
// Optional scope passed to the clearance client (advanced).
'clearance_scope' => '',
// Cloud connection metadata, populated by the one-click connect flow
// (WebDecoy_Cloud_Connect). Managed outside the settings form; the
// sanitizer carries these forward so a normal save never wipes them.
'organization_id' => '',
'organization_name' => '',
'plan' => '',
// Proxy / client IP resolution. By default the plugin uses the direct
// connection IP (REMOTE_ADDR) and IGNORES forwarding headers, which are
// spoofable. Sites behind a reverse proxy/CDN must opt in so that
// X-Forwarded-For / CF-Connecting-IP are honored ONLY from trusted hops.
'behind_cloudflare' => false,
'trusted_proxies' => '', // newline/comma separated IPs or CIDRs
// Detection Settings
'enabled' => true,
'sensitivity' => 'medium',
'min_score_to_block' => 75,
'min_threat_level' => 'HIGH',
// Good Bot Handling
'allow_search_engines' => true,
'allow_social_bots' => true,
'block_ai_crawlers' => false,
'custom_allowlist' => [],
// Blocking Settings
// Monitor mode is the safe default: everything is detected, logged and
// reported, and nothing is ever blocked, throttled or 403'd. Turn it off
// deliberately, once the Detections page shows what enforcement would do.
'monitor_mode' => true,
'ip_allowlist' => [], // IPs/CIDRs that bypass all detection
'block_action' => 'block',
// 93% of hostile addresses are gone inside an hour, so a longer default
// buys almost nothing against the adversary and carries a full extra day
// of exposure to blocking whoever inherits the address next.
'block_duration' => 1,
'show_block_page' => true,
'block_page_message' => 'Access to this site has been restricted.',
// Rate Limiting
'rate_limit_enabled' => true,
'rate_limit_requests' => 60,
'rate_limit_window' => 60,
// Algorithm: fixed window (DB) or sliding window (object cache when a
// persistent one is present, else fixed). Key: per IP, IP+route, or
// logged-in user. Dry-run records without throttling.
'rate_limit_algorithm' => 'fixed',
'rate_limit_key' => 'ip',
'rate_limit_dry_run' => false,
// Tripwires (F4 deception layer). Deterministic, zero-false-positive:
// a request for a scanner-bait honeypot path is automated by
// construction. On by default — the built-in bait paths carry no
// false-positive risk for real visitors, so protection is active
// out of the box.
'tripwire_enabled' => true,
'tripwire_include_defaults' => true,
'tripwire_paths' => [], // extra exact paths
'tripwire_prefixes' => [], // startsWith matches
'tripwire_patterns' => [], // regex bodies (no delimiters)
'tripwire_action' => 'block', // block | throttle
'tripwire_dry_run' => false, // record violations without blocking
// How a tripwire hit responds: block (403), notfound (404), decoy
// (200 fake content w/ canary credentials), or tarpit (slow drip).
'tripwire_response' => 'block',
// Honeytoken: auto-inject a hidden decoy link on front-end pages and
// arm its secret path as a tripwire. Only link-following scrapers
// ever hit it — deterministic, zero false positives. On by default.
'honeytoken_enabled' => true,
'honeytoken_rotate' => false, // rotate the token daily (with grace)
// WordPress-native traps.
'traps_fake_plugins' => true, // arm fake vulnerable-plugin paths (absent plugins only)
'traps_xmlrpc' => false, // trap xmlrpc.php (off: legit clients use it)
'traps_author_enum' => true, // trap ?author=N + REST user enumeration
// Filter rules: expression-based rules evaluated by the rule engine.
// Each entry: ['expression'=>string, 'action'=>'block'|'throttle',
// 'dry_run'=>bool, 'name'=>string]. Empty by default.
'filter_rules' => [],
// Form Protection
'protect_comments' => true,
'protect_login' => true,
'protect_registration' => true,
'inject_honeypot' => true,
// WooCommerce
'protect_checkout' => true,
'checkout_velocity_limit' => 5,
'checkout_velocity_window' => 3600,
// Plant a hidden honeytoken coupon; applying it is a deterministic
// bot signal (no human ever sees the code).
'woo_honeytoken_coupons' => true,
// Client-side Scanner
'scanner_enabled' => true,
'scanner_min_score' => 20,
'scanner_on_all_pages' => true,
'scanner_exclude_logged_in' => false,
// Proof-of-Work
'pow_enabled' => true,
'pow_difficulty' => 4,
'challenge_duration' => 15,
// "Protected by WebDecoy" credit on the challenge page. Off by
// default: WordPress.org guideline 10 requires user-facing
// attribution to be an explicit admin opt-in.
'challenge_show_credit' => false,
];
$saved = get_option('webdecoy_options', []);
$this->options = array_merge($defaults, $saved);
// Decrypt API key if it's encrypted
if (!empty($this->options['api_key']) && $this->is_encrypted($this->options['api_key'])) {
$this->options['api_key'] = $this->decrypt_value($this->options['api_key']);
}
}
/**
* Cloudflare published IP ranges (https://www.cloudflare.com/ips/).
* Used to verify that a request claiming a CF-Connecting-IP actually arrived
* via Cloudflare, rather than trusting the header from any direct connection.
*/
private const CLOUDFLARE_RANGES = [
'173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22',
'141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20',
'197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
'104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
'2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32',
'2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32',
];
/**
* Build the list of trusted proxy IPs/CIDRs from plugin settings. Returns an
* empty array (= direct mode, ignore forwarding headers) unless the site is
* explicitly configured to be behind Cloudflare and/or trusted proxies.
*
* @return string[]
*/
public function get_trusted_proxies(): array
{
$proxies = [];
if (!empty($this->options['behind_cloudflare'])) {
$proxies = array_merge($proxies, self::CLOUDFLARE_RANGES);
}
$configured = $this->options['trusted_proxies'] ?? '';
if (is_array($configured)) {
$proxies = array_merge($proxies, $configured);
} elseif (is_string($configured) && $configured !== '') {
// Allow newline- or comma-separated entries.
$parts = preg_split('/[\s,]+/', $configured) ?: [];
$proxies = array_merge($proxies, $parts);
}
return array_values(array_filter(array_map('trim', $proxies)));
}
/**
* True when the request arrived through a proxy the plugin has not been told
* about. In that state SignalCollector::getIP() correctly refuses the spoofable
* forwarding headers and returns REMOTE_ADDR — which is the proxy, not the
* visitor — so every visitor resolves to the same address and any IP-keyed
* action hits all of them at once.
*
* This is a detection of OUR misconfiguration. It must never cause the plugin to
* start trusting the headers: that would let any client choose their own identity
* and frame a third party into the block table.
*/
public function proxy_misconfigured(): bool
{
// NEVER infer this from the CURRENT request's headers. Forwarding headers are
// client-controlled, so `forwarding_headers_present() && no trusted proxy`
// would let any visitor send `X-Forwarded-For:` and switch the whole
// enforcement stack off for their own request — a complete bypass, and worse
// than the bug this state exists to contain.
//
// The flag is written only from an authenticated administrator's request
// (maybe_flag_proxy(), on admin_init), which is a trustworthy sample of how
// traffic actually reaches this site and cannot be forged by a visitor.
return $this->get_trusted_proxies() === []
&& (bool) get_option('webdecoy_proxy_detected', false);
}
/**
* Record whether this site sits behind an unconfigured reverse proxy, sampled
* from an administrator's own request. Front-end code reads the stored flag; it
* must never read the headers directly. See proxy_misconfigured().
*/
public function maybe_flag_proxy(): void
{
if (!current_user_can('manage_options')) {
return;
}
$seen = WebDecoy_Blocker::forwarding_header_seen();
$flagged = (bool) get_option('webdecoy_proxy_detected', false);
if ($seen !== '' && !$flagged) {
update_option('webdecoy_proxy_detected', $seen, false);
} elseif ($seen === '' && $flagged) {
// The proxy is gone, or the admin is reaching the origin directly.
delete_option('webdecoy_proxy_detected');
}
}
/**
* Why enforcement is currently suppressed, or '' when it is live.
*
* Detection, logging and cloud reporting continue in every suppressed state —
* only the act of blocking, throttling or serving a 403 is withheld.
*/
public function suppression_reason(): string
{
if (defined('WEBDECOY_DISABLE') && WEBDECOY_DISABLE) {
return 'disabled';
}
if (!empty($this->options['monitor_mode'])) {
return 'monitor';
}
if ($this->proxy_misconfigured()) {
return 'proxy';
}
return '';
}
/** Convenience wrapper: is any enforcement action allowed on this request? */
public function enforcement_suppressed(): bool
{
return $this->suppression_reason() !== '';
}
/**
* One-time migrations, keyed on the stored schema version.
*/
public function maybe_upgrade(): void
{
$stored = get_option('webdecoy_schema_version', '0');
if (version_compare($stored, '2.3.2', '>=')) {
return;
}
// 2.3.2: the cross-site actor feed no longer writes to the block table.
// Remove every row it wrote, so upgrading actually stops the enforcement
// rather than leaving up to 2,000 stale addresses blocked until they age
// out. Refs WebDecoy/app#476.
if (class_exists('WebDecoy_Actor_Feed')) {
$purged = WebDecoy_Actor_Feed::purge_feed_blocks();
if ($purged > 0) {
set_transient('webdecoy_upgrade_notice_232', $purged, DAY_IN_SECONDS);
}
}
// 2.3.2: bring sites still sitting on the old 24-hour default down to the
// new 1-hour default. A site that deliberately chose some other number keeps
// it; only the untouched default moves. 24 is indistinguishable from a
// deliberate 24, and on a safety release the shorter block is the safer of
// the two mistakes.
$saved = get_option('webdecoy_options', []);
if (!is_array($saved)) {
$saved = [];
}
$dirty = false;
// 2.3.2: PERSIST the new monitor_mode default. load_options() merges it in at
// runtime, but the settings form reads the stored array directly — without this
// the checkbox renders unchecked while the plugin is in monitor mode, and
// because an unchecked box submits nothing and sanitize_options() rebuilds the
// array from scratch, the next save of ANY setting writes false and silently
// turns full enforcement on.
if (!array_key_exists('monitor_mode', $saved)) {
$saved['monitor_mode'] = true;
$dirty = true;
}
if (isset($saved['block_duration']) && (int) $saved['block_duration'] === 24) {
$saved['block_duration'] = 1;
$dirty = true;
}
if ($dirty) {
$this->update_options_raw($saved);
$this->load_options();
}
update_option('webdecoy_schema_version', '2.3.2', true);
}
/**
* Tell the administrator, on every admin screen, when the plugin is watching
* rather than acting — and why. A security plugin that has silently stopped
* enforcing is worse than one that never did.
*/
public function render_state_notices(): void
{
if (!current_user_can('manage_options')) {
return;
}
$settings_url = admin_url('admin.php?page=webdecoy-settings');
if (defined('WEBDECOY_DISABLE') && WEBDECOY_DISABLE) {
printf(
'<div class="notice notice-warning"><p><strong>%s</strong> %s</p></div>',
esc_html__('WebDecoy is disabled.', 'webdecoy'),
esc_html__('WEBDECOY_DISABLE is defined in wp-config.php, so nothing is detected or blocked on the front end. Remove it to resume.', 'webdecoy')
);
return;
}
// The dangerous state: a proxy in front, and we were never told about it,
// so every visitor resolves to the same address.
if ($this->proxy_misconfigured()) {
// The stored flag holds the header name that was seen on an admin request.
$seen = (string) get_option('webdecoy_proxy_detected', '');
if ($seen === '' || $seen === '1') {
$seen = __('a forwarding header', 'webdecoy');
}
$header_html = '<code>' . esc_html($seen) . '</code>';
printf(
'<div class="notice notice-error"><p><strong>%s</strong> %s</p><p>%s</p><p><a class="button button-primary" href="%s">%s</a></p></div>',
esc_html__('WebDecoy is not blocking: this site is behind a proxy it has not been told about.', 'webdecoy'),
wp_kses(
sprintf(
/* translators: %s: comma-separated list of HTTP header names */
esc_html__('Your requests arrive with %s, but no trusted proxy is configured. Until that is fixed every visitor looks like the same address, so blocking anyone would block everyone.', 'webdecoy'),
$header_html
),
['code' => []]
),
esc_html__('Detection, logging and reporting continue as normal. Only blocking, rate limiting and the 403 page are withheld.', 'webdecoy'),
esc_url($settings_url),
esc_html__('Configure trusted proxies', 'webdecoy')
);
return;
}
if (!empty($this->options['monitor_mode'])) {
$stats = get_option('webdecoy_suppressed_actions', []);
$total = 0;
if (is_array($stats)) {
foreach ($stats as $day) {
$total += (int) ($day['count'] ?? 0);
}
}
printf(
'<div class="notice notice-info"><p><strong>%s</strong> %s</p><p><a class="button" href="%s">%s</a></p></div>',
esc_html__('WebDecoy is in monitor mode.', 'webdecoy'),
$total > 0
? sprintf(
/* translators: %d: number of actions that were withheld */
esc_html__('Everything is detected and logged; nothing is blocked. Enforcing would have acted on %d requests in the last 30 days.', 'webdecoy'),
(int) $total
)
: esc_html__('Everything is detected and logged; nothing is blocked. No request has met the bar for enforcement yet.', 'webdecoy'),
esc_url($settings_url),
esc_html__('Review and turn on blocking', 'webdecoy')
);
}
}
/**
* Sanitize the trusted-proxies setting: accept newline/comma separated IPs or
* CIDR ranges, discard anything that isn't a valid IP or CIDR, and store back
* as a newline-separated string. This prevents garbage entries from widening
* the trusted set.
*/
private function sanitize_trusted_proxies($input): string
{
if (is_array($input)) {
$entries = $input;
} else {
$entries = preg_split('/[\s,]+/', (string) $input) ?: [];
}
$valid = [];
foreach ($entries as $entry) {
$entry = trim((string) $entry);
if ($entry === '') {
continue;
}
if (strpos($entry, '/') !== false) {
[$addr, $bits] = array_pad(explode('/', $entry, 2), 2, '');
if (filter_var($addr, FILTER_VALIDATE_IP) && ctype_digit($bits) && (int) $bits >= 0 && (int) $bits <= 128) {
$valid[] = $entry;
}
} elseif (filter_var($entry, FILTER_VALIDATE_IP)) {
$valid[] = $entry;
}
}
return implode("\n", array_unique($valid));
}
/**
* Sanitize a newline/comma separated list of URL paths into a clean array.
* Each entry is normalized to begin with a leading slash.
*
* @param mixed $input
* @return string[]
*/
private function sanitize_path_list($input): array
{
if (is_array($input)) {
$entries = $input;
} else {
$entries = preg_split('/[\r\n,]+/', (string) $input) ?: [];
}
$valid = [];
foreach ($entries as $entry) {
$entry = trim((string) $entry);
if ($entry === '') {
continue;
}
// Strip whitespace and control chars; keep it a bare path.
$entry = sanitize_text_field($entry);
if ($entry === '') {
continue;
}
if ($entry[0] !== '/') {
$entry = '/' . $entry;
}
$valid[] = $entry;
}
return array_values(array_unique($valid));
}
/**
* Sanitize a newline separated list of regex bodies (no delimiters).
* Discards any pattern that isn't a valid PCRE so a bad rule can never
* throw at evaluation time.
*
* @param mixed $input
* @return string[]
*/
private function sanitize_pattern_list($input): array
{
if (is_array($input)) {
$entries = $input;
} else {
$entries = preg_split('/[\r\n]+/', (string) $input) ?: [];
}
$valid = [];
foreach ($entries as $entry) {
$entry = trim((string) $entry);
if ($entry === '') {
continue;
}
$delimited = '#' . str_replace('#', '\\#', $entry) . '#';
// phpcs:ignore
if (@preg_match($delimited, '') !== false) {
$valid[] = $entry;
}
}
return array_values(array_unique($valid));
}
/**
* Sanitize the filter-rules repeater. Each rule's expression is validated by
* attempting to parse it; a malformed expression is kept (so the admin can
* fix it) but flagged with an `error` and surfaced as a settings notice, and
* skipped at engine-build time so it can never fatal a request.
*
* @param mixed $input
* @return array<int,array<string,mixed>>
*/
private function sanitize_filter_rules($input): array
{
if (!is_array($input)) {
return [];
}
$rules = [];
foreach ($input as $row) {
if (!is_array($row)) {
continue;
}
$expression = trim((string) ($row['expression'] ?? ''));
if ($expression === '') {
continue;
}
$rule = [
'name' => sanitize_text_field($row['name'] ?? ''),
'expression' => $expression,
'action' => in_array($row['action'] ?? 'block', ['block', 'throttle'], true) ? $row['action'] : 'block',
'dry_run' => !empty($row['dry_run']),
];
// Validate by parsing. Keep the text either way; flag on failure.
try {
new \WebDecoy\Rules\FilterRule(['expression' => $expression]);
} catch (\Throwable $e) {
$rule['error'] = $e->getMessage();
add_settings_error(
'webdecoy_options',
'filter_rule_invalid',
sprintf(
/* translators: 1: filter expression, 2: parser error */
__('Filter rule "%1$s" is invalid and was disabled: %2$s', 'webdecoy'),
$expression,
$e->getMessage()
),
'error'
);
}
$rules[] = $rule;
}
return $rules;
}
/**
* Get the scanner ID (auto-generated from site URL)
*
* @return string
*/
private function get_scanner_id(): string
{
return 'wp-' . substr(md5(get_site_url()), 0, 12);
}
/**
* Get encryption key (unique per site)
*
* @return string
*/
private function get_encryption_key(): string
{
// Use AUTH_KEY if available, otherwise generate and store one
if (defined('AUTH_KEY') && AUTH_KEY !== '') {
return hash('sha256', AUTH_KEY . 'webdecoy_api_key');
}
// Fallback: get or create a stored key
$key = get_option('webdecoy_encryption_key');
if (!$key) {
$key = wp_generate_password(64, true, true);
update_option('webdecoy_encryption_key', $key, false);
}
return hash('sha256', $key);
}
/**
* Encrypt a value
*
* @param string $value
* @return string Encrypted value with prefix
*/
private function encrypt_value(string $value): string
{
if (empty($value)) {
return '';
}
$key = $this->get_encryption_key();
// Use OpenSSL if available
if (function_exists('openssl_encrypt')) {
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($value, 'AES-256-CBC', $key, 0, $iv);
if ($encrypted !== false) {
return 'enc:' . base64_encode($iv . $encrypted);
}
}
// Fallback: simple obfuscation (not secure, but better than plaintext)
return 'obs:' . base64_encode($value ^ str_repeat($key, ceil(strlen($value) / strlen($key))));
}
/**
* Decrypt a value
*
* @param string $value Encrypted value with prefix
* @return string Decrypted value
*/
private function decrypt_value(string $value): string
{
if (empty($value)) {
return '';
}
$key = $this->get_encryption_key();
// Check for encryption prefix
if (strpos($value, 'enc:') === 0) {
// OpenSSL encryption
$data = base64_decode(substr($value, 4));
if ($data === false || strlen($data) < 16) {
return ''; // Invalid data
}
$iv = substr($data, 0, 16);
$encrypted = substr($data, 16);
$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
return $decrypted !== false ? $decrypted : '';
}
if (strpos($value, 'obs:') === 0) {
// Simple obfuscation fallback
$data = base64_decode(substr($value, 4));
return $data ^ str_repeat($key, ceil(strlen($data) / strlen($key)));
}
// Not encrypted (legacy value)
return $value;
}
/**
* Check if a value is encrypted
*
* @param string $value
* @return bool
*/
private function is_encrypted(string $value): bool
{
return strpos($value, 'enc:') === 0 || strpos($value, 'obs:') === 0;
}
/**
* Initialize hooks
*/
private function init_hooks(): void
{
// Activation/Deactivation
register_activation_hook(WEBDECOY_PLUGIN_FILE, [$this, 'activate']);
register_deactivation_hook(WEBDECOY_PLUGIN_FILE, [$this, 'deactivate']);
// Self-hosted update mechanism: CDN distribution only, gated behind the
// WEBDECOY_SELF_HOSTED constant AND the presence of the updater file.
// The WordPress.org build (build.sh --org) omits class-webdecoy-updater.php,
// so this stays inert there — .org installs update exclusively via .org.
if (defined('WEBDECOY_SELF_HOSTED') && WEBDECOY_SELF_HOSTED) {
$updater_file = WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-updater.php';
if (file_exists($updater_file)) {
require_once $updater_file;
new WebDecoy_Updater();
}
}
// Early request check (as early as possible)
add_action('init', [$this, 'early_check'], 1);
// Load includes
add_action('plugins_loaded', [$this, 'load_includes']);
// Admin hooks
if (is_admin()) {
add_action('admin_menu', [$this, 'admin_menu']);
add_action('admin_init', [$this, 'register_settings']);
add_action('admin_init', [$this, 'maybe_upgrade']);
// Sample "are we behind a proxy" from a trusted (admin) request, so the
// front end never has to consult a client-controlled header.
add_action('admin_init', [$this, 'maybe_flag_proxy']);
add_action('admin_notices', [$this, 'render_state_notices']);
add_action('wp_dashboard_setup', [$this, 'dashboard_widget']);
add_action('admin_enqueue_scripts', [$this, 'admin_scripts']);
}
// Form protection hooks - always active when enabled
if ($this->options['protect_comments']) {
add_action('pre_comment_on_post', [$this, 'check_comment']);
add_filter('preprocess_comment', [$this, 'filter_comment']);
}
if ($this->options['protect_login']) {
add_filter('authenticate', [$this, 'check_login'], 30, 3);
}
// Canary-credential login detection: a login attempt using a fake
// credential we only ever handed out via a decoy response is
// unambiguous exfiltration evidence. Active whenever tripwires are on
// (the canaries' source), independent of login protection.
if (!empty($this->options['tripwire_enabled']) || !empty($this->options['honeytoken_enabled'])) {
add_filter('authenticate', [$this, 'check_canary_login'], 5, 3);
}
if ($this->options['protect_registration']) {
add_action('register_post', [$this, 'check_registration'], 10, 3);
}
// Honeypot injection
if ($this->options['inject_honeypot']) {
add_action('comment_form', [$this, 'inject_comment_honeypot']);
add_action('login_form', [$this, 'inject_login_honeypot']);
add_action('register_form', [$this, 'inject_register_honeypot']);
}
// WooCommerce hooks
if ($this->options['protect_checkout'] && class_exists('WooCommerce')) {
add_action('woocommerce_checkout_process', [$this, 'check_checkout']);
add_action('woocommerce_payment_complete', [$this, 'track_payment']);
add_action('woocommerce_checkout_order_processed', [$this, 'track_checkout_attempt']);
}
// AJAX handlers (admin)
add_action('wp_ajax_webdecoy_test_connection', [$this, 'ajax_test_connection']);
add_action('wp_ajax_webdecoy_get_stats', [$this, 'ajax_get_stats']);
add_action('wp_ajax_webdecoy_block_ip', [$this, 'ajax_block_ip']);
add_action('wp_ajax_webdecoy_unblock_ip', [$this, 'ajax_unblock_ip']);
add_action('wp_ajax_webdecoy_bulk_block', [$this, 'ajax_bulk_block']);
// AJAX handlers for client-side scanner (both logged-in and guests)
add_action('wp_ajax_webdecoy_client_detection', [$this, 'ajax_client_detection']);
add_action('wp_ajax_nopriv_webdecoy_client_detection', [$this, 'ajax_client_detection']);
// PoW challenge AJAX handlers
add_action('wp_ajax_webdecoy_pow_challenge', [$this, 'ajax_pow_challenge']);
add_action('wp_ajax_nopriv_webdecoy_pow_challenge', [$this, 'ajax_pow_challenge']);
add_action('wp_ajax_webdecoy_pow_verify', [$this, 'ajax_pow_verify']);
add_action('wp_ajax_nopriv_webdecoy_pow_verify', [$this, 'ajax_pow_verify']);
// Frontend scanner script (only if API is active)
if ($this->options['scanner_enabled'] && !is_admin()) {
add_action('wp_enqueue_scripts', [$this, 'frontend_scripts']);
}
// Browser clearance client: mints the wd_clearance cookie for real
// visitors so tripwire/decoy hits bind to a device fingerprint. Needs
// only the publishable site key (no secret / premium gate).
if (!empty($this->options['site_key']) && !is_admin()) {
add_action('wp_enqueue_scripts', [$this, 'enqueue_clearance_client']);
}
// Honeytoken: inject the hidden decoy link on front-end pages. The path
// itself is armed as a tripwire in build_rule_engine().
if (!empty($this->options['honeytoken_enabled']) && !is_admin()) {
add_action('wp_footer', [$this, 'inject_honeytoken_link'], 99);
}
// WordPress-native query/REST traps (author enumeration). Registered
// after includes are loaded so the traps class is available.
if (!empty($this->options['traps_author_enum'])) {
add_action('plugins_loaded', [$this, 'register_wp_traps'], 20);
}
// JS execution verification: inject challenge token meta tag and report page serve
// Only active when scanner is enabled and API key is configured (premium)
if ($this->options['scanner_enabled'] && !is_admin() && $this->is_premium()) {
add_action('wp_head', [$this, 'inject_js_verification_token'], 1);
}
// Clear API cache when settings are saved
add_action('update_option_webdecoy_options', [$this, 'clear_api_status_cache']);
// Safety-net cron drain of the violation-report spool.
add_action('webdecoy_flush_violations', [$this, 'cron_flush_violations']);
// Load text domain
// Declare HPOS compatibility for WooCommerce
add_action('before_woocommerce_init', [$this, 'declare_hpos_compatibility']);
// Add defer attribute to frontend scanner script for better performance
add_filter('script_loader_tag', [$this, 'add_defer_to_scanner'], 10, 3);
}
/**
* Declare High-Performance Order Storage (HPOS) compatibility for WooCommerce
*/
public function declare_hpos_compatibility(): void
{
if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', WEBDECOY_PLUGIN_FILE, true);
}
}
/**
* Add defer attribute to scanner script for non-blocking page load
*
* @param string $tag Script HTML tag
* @param string $handle Script handle
* @param string $src Script source URL
* @return string Modified script tag
*/
public function add_defer_to_scanner(string $tag, string $handle, string $src): string
{
if ($handle === 'webdecoy-scanner') {
return str_replace(' src', ' defer src', $tag);
}
// The clearance client auto-starts from data-* attributes on its own
// script tag; inject them here (WP core has no API to set arbitrary
// script-tag attributes on older versions). Also load it async.
if ($handle === 'webdecoy-clearance') {
$attrs = ' async data-site-key="' . esc_attr((string) $this->options['site_key']) . '"';
$scope = (string) ($this->options['clearance_scope'] ?? '');
if ($scope !== '') {
$attrs .= ' data-scope="' . esc_attr($scope) . '"';
}
return str_replace(' src', $attrs . ' src', $tag);