-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebdecoy.php
More file actions
2760 lines (2406 loc) · 98.7 KB
/
Copy pathwebdecoy.php
File metadata and controls
2760 lines (2406 loc) · 98.7 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.2.3
* 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.2.3');
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;
/**
* 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' => '',
// 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
'ip_allowlist' => [], // IPs/CIDRs that bypass all detection
'block_action' => 'block',
'block_duration' => 24,
'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)));
}
/**
* 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('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);
}
return $tag;
}
/**
* Load plugin includes
*/
public function load_includes(): void
{
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-activator.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-blocker.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-detector.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-rate-limiter.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-pow.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-behavioral-scorer.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-violation-reporter.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-honeytoken.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-ip-enrichment.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-decoy-response.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-rate-limit-rule.php';
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-wp-traps.php';
if (class_exists('WooCommerce')) {
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-woocommerce.php';
}
}
/**
* Plugin activation
*/
public function activate(): void
{
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-activator.php';
WebDecoy_Activator::activate();
}
/**
* Plugin deactivation
*/
public function deactivate(): void
{
require_once WEBDECOY_PLUGIN_DIR . 'includes/class-webdecoy-activator.php';
WebDecoy_Activator::deactivate();
}
/**
* Early request check
*/
public function early_check(): void
{
// Skip if disabled
if (!$this->options['enabled']) {
return;
}
// Skip admin and AJAX requests
if (is_admin() || wp_doing_ajax()) {
return;
}
// Check if IP is blocked
$blocker = new WebDecoy_Blocker();
$ip = $this->get_client_ip();
// Allowlisted IPs bypass all detection entirely.
if ($blocker->is_allowlisted($ip)) {
return;
}
if ($blocker->is_blocked($ip)) {
$this->block_request(__('Your IP has been blocked.', 'webdecoy'));
return;
}
// Deterministic rule engine (tripwires / filters). Runs before heuristic
// scoring: a rule DENY/THROTTLE short-circuits and scoring never runs,
// matching @webdecoy/node's protect() flow. Rules also record violations
// (reported to the cloud) even when they don't decide the outcome.
$engine = $this->build_rule_engine();
if ($engine !== null) {
$context = $this->build_rule_context($ip);
$engineResult = $engine->evaluate($context);
if ($engineResult->violations) {
// Log locally so hits show in the Detections admin page even for
// local-only installs and dry-run rules (which record but don't
// block).
$this->log_rule_violations($engineResult->violations);
// Report to the cloud (premium only). Tripwire hits carry
// wd_clearance so the backend can durably deny the actor's
// device fingerprint.
$reporter = WebDecoy_Violation_Reporter::instance($this->is_premium() ? (string) $this->options['api_key'] : '');
if ($reporter !== null) {
$reporter->report($engineResult->violations);
}
}
if (!$engineResult->isAllowed()) {
$this->handle_rule_decision($engineResult, $ip);
return;
}
}
// Rate limiting now runs as a rule inside the engine above (THROTTLE →
// 429 + Retry-After + X-RateLimit-* headers), so it evaluates in order
// with tripwires and filters rather than as a separate pre-check.
// Run bot detection through the WebDecoy_Detector wrapper — the single
// detector path (SDK BotDetector + WP-specific signals), the same one
// WooCommerce uses. It collects request signals, adds the request path
// for MITRE ATT&CK path analysis, and merges WP context.
$result = (new WebDecoy_Detector($this->options))->analyze();
// Skip if good bot
if ($result->isGoodBot()) {
return;
}
// Log any detection with score >= 40 (captures MITRE tactic detections)
// This is lower than the blocking threshold (default 75)
$log_threshold = 40;
if ($result->getScore() >= $log_threshold) {
// Always log detection locally
$this->log_detection($result, $ip);
// Submit to API (fail open)
try {
$this->submit_detection($result, $ip);
} catch (\Exception $e) {
error_log('WebDecoy API error: ' . $e->getMessage());
}
}
// Check if should block (higher threshold)
if ($result->shouldBlock($this->options['min_score_to_block'])) {
$this->handle_blocking($result, $ip);
}
}
/**
* Build the rule engine from current settings, or null when no rules are
* configured (so the common case adds zero overhead).
*
* @return \WebDecoy\Rules\RuleEngine|null
*/
private function build_rule_engine(): ?\WebDecoy\Rules\RuleEngine
{
$rules = [];
$action = ($this->options['tripwire_action'] ?? 'block') === 'throttle'
? \WebDecoy\Rules\RuleResult::THROTTLE
: \WebDecoy\Rules\RuleResult::DENY;
$dryRun = !empty($this->options['tripwire_dry_run']);
if (!empty($this->options['tripwire_enabled'])) {
$rules[] = new \WebDecoy\Rules\TripwireRule([
'paths' => is_array($this->options['tripwire_paths'] ?? null) ? $this->options['tripwire_paths'] : [],
'prefixes' => is_array($this->options['tripwire_prefixes'] ?? null) ? $this->options['tripwire_prefixes'] : [],
'patterns' => is_array($this->options['tripwire_patterns'] ?? null) ? $this->options['tripwire_patterns'] : [],
'includeDefaults' => !empty($this->options['tripwire_include_defaults']),
'action' => $action,
'dryRun' => $dryRun,
]);
}
// Arm the honeytoken path(s) as a tripwire. Independent of the general
// tripwire toggle: if honeytokens are on, their secret path is always
// enforced (the hidden link is only useful if a hit actually trips).
if (!empty($this->options['honeytoken_enabled'])) {
$honeytoken = new WebDecoy_Honeytoken(!empty($this->options['honeytoken_rotate']));
$rules[] = new \WebDecoy\Rules\TripwireRule([
'paths' => $honeytoken->active_paths(),
'includeDefaults' => false,
'action' => $action,
'dryRun' => $dryRun,
]);
}
// WordPress-native path traps: fake vulnerable-plugin routes (only for
// absent plugins) and, optionally, xmlrpc.php. Armed as a tripwire so
// they get the full DENY + violation + clearance + optional-decoy path.
$trap_prefixes = [];
$trap_paths = [];
if (!empty($this->options['traps_fake_plugins'])) {
$trap_prefixes = array_merge($trap_prefixes, WebDecoy_WP_Traps::plugin_path_prefixes());
}
if (!empty($this->options['traps_xmlrpc'])) {
$trap_paths[] = '/xmlrpc.php';
}
if ($trap_prefixes !== [] || $trap_paths !== []) {
$rules[] = new \WebDecoy\Rules\TripwireRule([
'paths' => $trap_paths,
'prefixes' => $trap_prefixes,
'includeDefaults' => false,
'action' => $action,
'dryRun' => $dryRun,
]);
}
// Filter (expression) rules. A malformed stored expression is skipped
// defensively so it can never fatal a request (it was already flagged in
// the admin on save). Track whether any rule needs IP enrichment.
$filterRules = $this->options['filter_rules'] ?? [];
if (is_array($filterRules)) {
foreach ($filterRules as $fr) {
if (!is_array($fr) || empty($fr['expression']) || !empty($fr['error'])) {
continue;
}
try {
$rule = new \WebDecoy\Rules\FilterRule([
'expression' => (string) $fr['expression'],
'name' => (string) ($fr['name'] ?? ''),
'action' => ($fr['action'] ?? 'block') === 'throttle'
? \WebDecoy\Rules\RuleResult::THROTTLE
: \WebDecoy\Rules\RuleResult::DENY,
'dryRun' => !empty($fr['dry_run']),
]);
} catch (\Throwable $e) {
continue; // malformed despite the save-time check — skip
}
if ($rule->needsEnrichment()) {
$this->rules_need_enrichment = true;
}
$rules[] = $rule;
}
}
// Rate limiting runs last: a deterministic tripwire/filter DENY should
// win over a THROTTLE for the same request.
if (!empty($this->options['rate_limit_enabled'])) {
$rules[] = new WebDecoy_Rate_Limit_Rule([
'limit' => (int) ($this->options['rate_limit_requests'] ?? 60),
'window' => (int) ($this->options['rate_limit_window'] ?? 60),
'algorithm' => $this->options['rate_limit_algorithm'] ?? 'fixed',
'keyBy' => $this->options['rate_limit_key'] ?? 'ip',
'dryRun' => !empty($this->options['rate_limit_dry_run']),
]);
}
if ($rules === []) {