-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsecurity-malware-firewall.php
2033 lines (1728 loc) · 69 KB
/
security-malware-firewall.php
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: Security by CleanTalk
Plugin URI: https://wordpress.org/plugins/security-malware-firewall/
Description: Security & Malware scan by CleanTalk to protect your website from online threats and viruses. IP/Country FireWall, Web application FireWall. Detailed stats and logs to have full control.
Author: CleanTalk Security
Version: 2.151
Author URI: https://cleantalk.org
Text Domain: security-malware-firewall
Domain Path: /i18n
*/
use CleantalkSP\SpbctWP\Activator;
use CleantalkSP\SpbctWP\AdjustToEnvironmentModule\AdjustToEnvironmentHandler;
use CleantalkSP\SpbctWP\DTO\SecurityLogsDataRowDTO;
use CleantalkSP\SpbctWP\DTO\SecurityLogsDTO;
use CleantalkSP\SpbctWP\FSWatcher\Controller as FSWatcherController;
use CleantalkSP\SpbctWP\DB;
use CleantalkSP\SpbctWP\Firewall\BFP;
use CleantalkSP\SpbctWP\Firewall\FW;
use CleantalkSP\SpbctWP\Cron as SpbcCron;
use CleantalkSP\SpbctWP\HTTP\CDNHeadersChecker;
use CleantalkSP\SpbctWP\RemoteCalls as SpbcRemoteCalls;
use CleantalkSP\SpbctWP\RenameLoginPage;
use CleantalkSP\SpbctWP\Sanitize;
use CleantalkSP\SpbctWP\Scanner\Stages\SignatureAnalysis\SignatureAnalysisFacade;
use CleantalkSP\SpbctWP\State;
use CleantalkSP\SpbctWP\Transaction;
use CleantalkSP\SpbctWP\Variables\Cookie;
use CleantalkSP\SpbctWP\VulnerabilityAlarm\VulnerabilityAlarmService;
use CleantalkSP\Updater\Updater;
use CleantalkSP\Updater\UpdaterScripts;
use CleantalkSP\Variables\Get;
use CleantalkSP\Variables\Post;
use CleantalkSP\Variables\Server;
use CleantalkSP\SpbctWP\Helpers\IP;
use CleantalkSP\SpbctWP\Helpers\HTTP;
use CleantalkSP\SpbctWP\API as SpbcAPI;
use CleantalkSP\SpbctWP\Scanner\ScanRepository;
use CleantalkSP\SpbctWP\Scanner\ScanStorage;
use CleantalkSP\SpbctWP\VulnerabilityAlarm\VulnerabilityAlarm;
// Prevent direct call
if ( ! defined('WPINC') ) {
die('Not allowed!');
}
// Getting version form main file (look above)
$plugin_info = get_file_data(__FILE__, array('Version' => 'Version', 'Name' => 'Plugin Name', 'Description' => 'Description'));
$plugin_version__agent = $plugin_info['Version'];
// Converts xxx.xxx.xx-dev to xxx.xxx.2xx
// And xxx.xxx.xx-fix to xxx.xxx.1xx
if ( preg_match('@^(\d+)\.(\d+)\.(\d{1,2})-(dev|fix)$@', $plugin_version__agent, $m) ) {
$plugin_version__agent = $m[1] . '.' . $m[2] . '.' . ($m[4] === 'dev' ? '2' : '1') . str_pad($m[3], 2, '0', STR_PAD_LEFT);
}
// Common params
define('SPBC_NAME', $plugin_info['Name']);
define('SPBC_VERSION', $plugin_info['Version']);
define('SPBC_AGENT', 'wordpress-security-' . $plugin_version__agent);
define('SPBC_USER_AGENT', 'Cleantalk-Security-Wordpress-Plugin/' . $plugin_info['Version']);
define('SPBC_API_URL', 'https://api.cleantalk.org'); //Api URL
define('SPBC_PLUGIN_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR); //System path. Plugin root folder with '/'.
define('SPBC_PLUGIN_BASE_NAME', plugin_basename(__FILE__)); //Plugin base name.
define(
'SPBC_PATH',
is_ssl()
? preg_replace('/^http(s)?/', 'https', plugins_url('', __FILE__))
: plugins_url('', __FILE__)
); //HTTP(S)? path. Plugin root folder without '/'.
// SSL Serttificate path
if ( ! defined('CLEANTALK_CASERT_PATH') ) {
define('CLEANTALK_CASERT_PATH', file_exists(ABSPATH . WPINC . '/certificates/ca-bundle.crt') ? ABSPATH . WPINC . '/certificates/ca-bundle.crt' : '');
}
// Options names
define('SPBC_DATA', 'spbc_data'); //Option name with different plugin data.
define('SPBC_SETTINGS', 'spbc_settings'); //Option name with plugin settings.
define('SPBC_NETWORK_SETTINGS', 'spbc_network_settings'); //Option name with plugin network settings.
define('SPBC_CRON', 'spbc_cron'); //Option name with scheduled tasks.
define('SPBC_ERRORS', 'spbc_errors'); //Option name with errors.
define('SPBC_DEBUG', 'spbc_debug'); //Option name with a debug data. Empty by default.
define('SPBC_PLUGINS', 'spbc_plugins'); //Option name with a debug data. Empty by default.
define('SPBC_THEMES', 'spbc_themes'); //Option name with a debug data. Empty by default.
// Different params
define('SPBC_REMOTE_CALL_SLEEP', 10); //Minimum time between remote call
define('SPBC_LAST_ACTIONS_TO_VIEW', 20); //Nubmer of last actions to show in plugin settings page.
// Auth params
define('SPBC_2FA_KEY_TTL', 600); // 2fa key lifetime in seconds
// DataBase params
global $wpdb;
define('SPBC_TBL_FIREWALL_DATA', $wpdb->base_prefix . 'spbc_firewall_data');
define('SPBC_TBL_FIREWALL_DATA_V4', SPBC_TBL_FIREWALL_DATA . '_v4');
define('SPBC_TBL_FIREWALL_DATA_V6', SPBC_TBL_FIREWALL_DATA . '_v6');
define('SPBC_TBL_FIREWALL_DATA__IPS', $wpdb->prefix . 'spbc_firewall__personal_ips');
define('SPBC_TBL_FIREWALL_DATA__IPS_V4', SPBC_TBL_FIREWALL_DATA__IPS . '_v4'); // Table with firewall IPS v4
define('SPBC_TBL_FIREWALL_DATA__IPS_V6', SPBC_TBL_FIREWALL_DATA__IPS . '_v6'); // Table with firewall IPS v6
define('SPBC_TBL_FIREWALL_DATA__COUNTRIES', $wpdb->prefix . 'spbc_firewall__personal_countries'); // Table with firewall countries.
define('SPBC_TBL_FIREWALL_LOG', $wpdb->prefix . 'spbc_firewall_logs'); // Table with firewall logs.
define('SPBC_TBL_SESSIONS', $wpdb->prefix . 'spbc_sessions'); // Alternative sessions table
define('SPBC_TBL_MONITORING_USERS', $wpdb->prefix . 'spbc_monitoring_users'); // Table with users monitoring data
define('SPBC_TBL_SECURITY_LOG', $wpdb->prefix . 'spbc_auth_logs'); // Table with security logs.
define('SPBC_TBL_TC_LOG', $wpdb->prefix . 'spbc_traffic_control_logs'); // Table with traffic control logs.
define('SPBC_TBL_BFP_BLOCKED', $wpdb->prefix . 'spbc_bfp_blocked'); // Table with traffic control logs.
define('SPBC_TBL_SCAN_FILES', $wpdb->base_prefix . 'spbc_scan_results'); // Table with scan results.
define('SPBC_TBL_SCAN_RESULTS_LOG', $wpdb->base_prefix . 'spbc_scan_results_log'); // Table with log of scan results.
define('SPBC_TBL_SCAN_LINKS', $wpdb->prefix . 'spbc_scan_links_logs'); // For links scanner. Results of scan.
define('SPBC_TBL_SCAN_FRONTEND', $wpdb->base_prefix . 'spbc_scan_frontend'); // For frontend scanner. Results of scan.
define('SPBC_TBL_SCAN_SIGNATURES', $wpdb->base_prefix . 'spbc_scan_signatures'); // For malware signatures.
define('SPBC_TBL_BACKUPED_FILES', $wpdb->prefix . 'spbc_backuped_files'); // Contains backuped files
define('SPBC_TBL_BACKUPS', $wpdb->prefix . 'spbc_backups'); // Contains backup info.
define('SPBC_TBL_CURE_LOG', $wpdb->base_prefix . 'spbc_cure_log'); // Table with scan results.
define('SPBC_SURFACE_COMPLETED_DIRS', $wpdb->base_prefix . 'spbc_surface_completed_dirs'); // Table with scan results.
define('SPBC_SELECT_LIMIT', 1500); // Select limit for logs.
define('SPBC_WRITE_LIMIT', 5000); // Write limit for firewall data.
// Multisite
define('SPBC_WPMS', (is_multisite() ? true : false)); // WMPS is enabled
// Scanner params for background scanning
define('SPBC_SCAN_SURFACE_AMOUNT', 1000); // Surface scan amount for 1 iteration
define('SPBC_SCAN_SURFACE_PERIOD', 30); // Surface scan call period
define('SPBC_SCAN_MODIFIED_AMOUNT', 5); // Deep scan amount for 1 iteration
define('SPBC_SCAN_SIGNATURE_AMOUNT', 20); // Deep scan amount for 1 iteration
define('SPBC_SCAN_MODIFIED_PERIOD', 30); // Deep scan call period
define('SPBC_SCAN_LINKS_AMOUNT', 10); // Links scan amount for 1 iteration
define('SPBC_SCAN_FRONTEND_AMOUNT', 10); // Links scan amount for 1 iteration
define('SPBC_SCAN_LINKS_PERIOD', 30); // Links scan call period
define('SPBC_PSCAN_UPDATE_FILES_STATUS_PERIOD', 60); // Check cloud analysis files status period
define('SPBC_PSCAN_RESEND_FILES_STATUS_PERIOD', 300); // Resend files
// brief data limits
define('SPBC_BRIEF_DATA_DAYS_LIMIT', 7); // how many days will be logs looked for
define('SPBC_BRIEF_DATA_ACTIONS_LIMIT', 10); // how many actions will be logs looked for
require_once SPBC_PLUGIN_DIR . 'lib/spbc-php-patch.php'; // PHP functions patches
require_once SPBC_PLUGIN_DIR . 'lib/autoloader.php'; // Autoloader
require_once SPBC_PLUGIN_DIR . 'inc/spbc-backups.php';
require_once SPBC_PLUGIN_DIR . 'inc/fw-update.php';
// Misc libs
require_once SPBC_PLUGIN_DIR . 'inc/spbc-tools.php'; // Different helper functions
require_once SPBC_PLUGIN_DIR . 'inc/spbc-pluggable.php'; // WordPress functions
require_once SPBC_PLUGIN_DIR . 'inc/spbc-scanner.php';
// ArrayObject with settings and other global variables
global $spbc;
$spbc = new State(
'spbc',
array(
'settings',
'data',
'remote_calls',
'debug',
'installing',
'errors',
'fw_stats',
'scan_plugins_info',
'scan_themes_info'
),
is_multisite(),
is_main_site()
);
require_once SPBC_PLUGIN_DIR . 'inc/spbc-auth.php';
// Update plugin's data to current version
spbc_update_actions();
// Remote calls
if ( SpbcRemoteCalls::check() ) {
try {
if ( Get::get('spbc_remote_call_action') === 'run_service_template_get' ) {
require_once(SPBC_PLUGIN_DIR . 'inc/spbc-settings.php');
}
$rc = new SpbcRemoteCalls($spbc);
$rc->process();
} catch ( Exception $e ) {
die(json_encode(array('ERROR:' => $e->getMessage())));
}
}
//First start
if ( $spbc->settings && $spbc->key_is_ok) {
require_once SPBC_PLUGIN_DIR . 'inc/spbc-firewall.php';
if ( ! spbc_firewall_skip_check()) {
if ( is_admin() && spbc_is_user_logged_in() ) {
//do this if in admin area and user is logged in - check only admin area (WAF run)
spbc_firewall_check_admin_area();
if ( ! empty($_FILES) ) {
spbc_upload_checker__check();
}
} else {
//if not in admin area and user is not logged in - check with all modules
spbc_firewall__check();
}
}
} elseif ( isset($spbc->errors) && ! isset($spbc->errors['apikey']) ) {
if ($spbc->settings['spbc_key'] === '') {
$text = __('Access key is empty.', 'security-malware-firewall');
} else {
$text = __('Unknown access key.', 'security-malware-firewall');
}
$spbc->error_add('apikey', $text);
}
// Disable XMLRPC if setting is enabled
if ( $spbc->settings['wp__disable_xmlrpc'] ) {
add_filter('xmlrpc_enabled', '__return_false');
}
// Disable WordPress REST API for non-authenticated
if ( $spbc->settings['wp__disable_rest_api_for_non_authenticated'] ) {
add_filter(
'rest_authentication_errors',
function ($result) {
if ( empty($result) && ! is_user_logged_in() ) {
return new WP_Error(
'rest_not_logged_in',
'You are not currently logged in.',
array('status' => 401)
);
}
return $result;
}
);
}
// Disable the WordPress endpoint "users" REST API
add_filter('rest_authentication_errors', 'spbc_rest_authentication_errors');
function spbc_rest_authentication_errors($result)
{
global $spbc;
if (
$spbc->settings['wp__disable_rest_api_route_users'] &&
Server::inUri('/wp/') &&
Server::inUri('users')
) {
return new WP_Error(
'access_denied',
__('Access is closed (Security by CleanTalk)'),
array( 'status' => 401 )
);
}
return $result;
}
if ( ! is_admin() && $spbc->settings['misc__prevent_logins_collecting'] ) {
add_filter('redirect_canonical', 'spbc_redirect_to_honeypot_login', 1, 2);
}
/**
* This is the Cron handler for the `spbc_security_check_vulnerabilities` task
*
* @return array|void
*/
function spbc_security_check_vulnerabilities()
{
global $spbc;
try {
VulnerabilityAlarm::updateWPModulesVulnerabilities();
$spbc->data['spbc_security_check_vulnerabilities_last_call'] = time();
$spbc->save('data');
// Send found vulnerabilities to the cloud
VulnerabilityAlarmService::sendReport();
} catch ( \Exception $exception ) {
return ['error' => $exception->getMessage()];
}
}
function spbc_update_scan_settings_exclusions()
{
global $spbc;
$settings = $spbc->settings;
try {
$dirExclusion = new \CleantalkSP\SpbctWP\Settings\FilesScanDirExclusion();
$settings['scanner__dir_exclusions_view'] = $dirExclusion->dirExclusionsView($settings['scanner__dir_exclusions_view']);
$settings['scanner__dir_exclusions'] = $dirExclusion->dirExclusions($settings['scanner__dir_exclusions_view']);
$domainExclusion = new \CleantalkSP\SpbctWP\Settings\FrontendScanDomainExclusion();
$domainExclusionView = $domainExclusion->frontendScanDomainExclusionsView($settings['scanner__frontend_analysis__domains_exclusions_view']);
$settings['scanner__frontend_analysis__domains_exclusions_view'] = $domainExclusionView;
$domainExclusionSets = $domainExclusion->domainExclusions($settings['scanner__frontend_analysis__domains_exclusions_view']);
$settings['scanner__frontend_analysis__domains_exclusions'] = $domainExclusionSets;
$domainExclusion->resetScannerFrontendResult($settings);
$spbc->settings = $settings;
$spbc->save('settings');
} catch ( \Exception $exception ) {
return ['error' => $exception->getMessage()];
}
}
function spbc_redirect_to_honeypot_login($redirect, $request)
{
if ( preg_match('/author=\d+/i', $request) ) {
add_filter('author_link', 'spbc_change_author_name', 10, 3);
}
return $redirect;
}
function spbc_change_author_name($link, $_author_id, $_author_nicename)
{
$link = preg_replace('@(.*?)([\w-]+\/)$@', '$1honeypot_login_' . microtime(true), $link);
wp_redirect($link);
die();
}
if ( $spbc->settings['monitoring__users'] ) {
add_action('admin_head', array( '\CleantalkSP\Monitoring\User', 'record' ));
add_action('wp_head', array( '\CleantalkSP\Monitoring\User', 'record' ));
}
//Password-protected pages also uses wp-login page, we should not break it
if ( $spbc->settings['login_page_rename__enabled'] ) {
if ( Get::get('action') === 'postpass' ) {
require ABSPATH . 'wp-includes/pluggable.php';
require ABSPATH . 'wp-login.php';
}
new RenameLoginPage(
$spbc->settings['login_page_rename__name'],
$spbc->settings['login_page_rename__redirect']
);
}
// Logged hooks
register_activation_hook(__FILE__, 'spbc_activation');
register_deactivation_hook(__FILE__, 'spbc_deactivation');
register_uninstall_hook(__FILE__, 'spbc_uninstall');
// Hook for newly added blog
Activator::addActionForNetworkBlogLegacy(get_bloginfo('version'));
add_action('plugins_loaded', 'spbc_plugin_loaded', 1); // Main hook
// Posts hooks
add_action('wp_insert_post', 'spbc_update_postmeta_links', 10, 3);
add_action('wp_insert_comment', 'spbc_update_postmeta_links__by_comment', 10, 2);
// Set headers
add_action('init', 'spbc_set_headers');
if ( $spbc->settings['spbc_trusted_and_affiliate__footer'] === '1' ) {
add_action('wp_enqueue_scripts', 'spbc_attach_public_css');
add_action('wp_footer', 'spbc_hook__wp_footer_trusted_text', 998);
}
// Cron
global $spbc_cron; // Letting know functions that they are running under spbc_cron
$spbc_cron = new SpbcCron();
! SpbcRemoteCalls::check() && $spbc_cron->execute();
unset($spbc_cron);
if ( is_admin() || is_network_admin() ) {
// Async loading for JavaScript
add_filter('script_loader_tag', 'spbc_admin_add_script_attribute', 10, 3);
include_once SPBC_PLUGIN_DIR . 'inc/spbc-admin.php';
include_once SPBC_PLUGIN_DIR . 'templates/spbc_settings_main.php'; // Templates for settings pgae
add_action('admin_init', array('CleantalkSP\SpbctWP\Activator', 'redirectAfterActivation'), 1); // Redirect after activation
add_action('admin_init', 'spbc_admin_init', 1, 1); // Main admin hook
add_action('admin_menu', 'spbc_admin_add_page'); // Admin pages
add_action('network_admin_menu', 'spbc_admin_add_page'); // Network admin pages
add_action('admin_enqueue_scripts', 'spbc_enqueue_scripts'); // Scripts
// Getting dashboard widget statistics by click
if ( (int) Post::get('spbc_brief_refresh') === 1 ) {
spbc_set_brief_data();
}
if ( $spbc->settings['wp__dashboard_widget__show'] ) {
add_action('wp_dashboard_setup', 'spbc_widget_scripts_init');
add_action('wp_dashboard_setup', 'spbc_dashboard_statistics_widget');
}
add_action('admin_init', function () {
global $spbc;
$admin_banners_handler = new \CleantalkSP\SpbctWP\AdminBannersModule\AdminBannersHandler($spbc);
$admin_banners_handler->handle();
});
// Customize row with the plugin on plugins list page.
if ( ( isset($pagenow) && $pagenow === 'plugins.php' ) || ( isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], 'plugins.php') !== false ) ) {
add_filter('plugin_action_links_' . SPBC_PLUGIN_BASE_NAME, 'spbc_plugin_action_links', 10, 2);
add_filter('network_admin_plugin_action_links_' . SPBC_PLUGIN_BASE_NAME, 'spbc_plugin_action_links', 10, 2);
add_filter('all_plugins', 'spbc_admin__change_plugin_description');
add_filter('plugin_row_meta', 'spbc_plugin_links_meta', 10, 2);
}
}
add_action('init', function () use ($spbc) {
if ( $spbc->feature_restrictions->getState($spbc, 'fswatcher')->is_active && $spbc->settings['scanner__fs_watcher'] ) {
$fswatcher_params = new \CleantalkSP\SpbctWP\FSWatcher\Dto\FSWatcherParams();
$fswatcher_params->dir_to_watch = ABSPATH;
$fswatcher_params->exclude_dirs = [];
$fswatcher_params->extensions_to_watch = ['php'];
$fswatcher = new FSWatcherController($fswatcher_params);
$fswatcher::work();
}
});
function spbc_set_headers()
{
global $spbc;
if ( ! headers_sent() ) {
// Additional headers
if ( $spbc->settings['data__additional_headers'] ) {
header('X-XSS-Protection: 1; mode=block');
header('X-Content-Type-Options: nosniff');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
header('Referrer-Policy: strict-origin-when-cross-origin');
}
// Forbid to show in iframes
if ( $spbc->settings['misc__forbid_to_show_in_iframes'] ) {
header('X-Frame-Options: sameorigin', false);
}
// Set cookie to detect any logged in user
if (
spbc_is_user_logged_in() &&
! empty($spbc->settings['data__set_cookies']) &&
(
! Cookie::get('spbc_is_logged_in') ||
Cookie::get('spbc_is_logged_in') !== md5($spbc->data['salt'] . get_option('home'))
)
) {
// skip rewriting spbc_is_logged_in cookie on favicon request for WPMS - its always run on main site url and returns it`s home url
if (
is_multisite() &&
strpos(Server::get('REQUEST_URI'), 'favicon.ico') !== false
) {
return;
}
//rewrite spbc_is_logged_in cookie
Cookie::set('spbc_is_logged_in', md5($spbc->data['salt'] . get_option('home')), time() + 86400 * 365, '/');
}
}
}
function spbc_update_actions()
{
global $spbc;
//Update logic
$current_version = $spbc->data['plugin_version'];
if ( $current_version != SPBC_VERSION ) {
//Migrate DB data on updating to 2.128.1
add_action('ColumnCreator_before_drop_column_analysis_status', [UpdaterScripts::class, 'migrateDbData_2_128_1']);
add_action('ColumnCreator_before_change_column_event', [UpdaterScripts::class, 'migrateDbData_2_141_0']);
// Perform a transaction and exit transaction ID isn't match
if ( ! Transaction::get('updater', 5)->perform() ) {
return;
}
Updater::runUpdateScripts($current_version, SPBC_VERSION);
$spbc->data['plugin_version'] = SPBC_VERSION;
$spbc->save('data');
Transaction::get('updater')->clearTransactionTimer();
}
}
/**
* Plugin activation
*
* @param $network
* @param $redirect
*
* @return void
* @throws Exception
*/
function spbc_activation($network, $redirect = true)
{
Activator::activation($network, $redirect);
}
/**
* A code during plugin deactivation.
*
* @param $network
*
* @return void
*/
function spbc_deactivation($network)
{
\CleantalkSP\SpbctWP\Deactivator::deactivation($network);
}
/**
* Run deactivation process (complete deactivation forced) for hook register_uninstall_hook.
* @param bool $network Is network wide command.
* @return void
*/
function spbc_uninstall($network)
{
global $spbc;
$spbc->settings['misc__complete_deactivation'] = 1;
$spbc->save('settings');
\CleantalkSP\SpbctWP\Deactivator::deactivation($network);
}
/**
* @deprecated 2.125 use Deactivator::deleteBlogTables()
* @return void
*/
function spbc_deactivation__delete_blog_tables() //deprecated
{
\CleantalkSP\SpbctWP\Deactivator::deleteBlogTables();
}
/**
* @deprecated 2.125 use Deactivator::deleteCommonTables()
* @return void
*/
function spbc_deactivation__delete_common_tables() //deprecated
{
\CleantalkSP\SpbctWP\Deactivator::deleteCommonTables();
}
// Misc functions to test the plugin.
function spbc_plugin_loaded()
{
global $spbc;
if ( is_admin() || is_network_admin() ) {
$dir = plugin_basename(dirname(__FILE__)) . '/i18n';
load_plugin_textdomain('security-malware-firewall', false, $dir);
}
if ( $spbc->settings['spbc_trusted_and_affiliate__shortcode'] === '1' ) {
add_action('wp_enqueue_scripts', 'spbc_attach_public_css');
add_shortcode('cleantalk_security_affiliate_link', 'spbc_trusted_text_shortcode_handler');
}
}
/**
* Check brute force attack
*
* @return void
*/
function spbc_authenticate__check_brute_force()
{
global $spbc;
$login_url = wp_login_url();
if ($spbc->settings['login_page_rename__enabled']) {
$GLOBALS['wp_rewrite'] = new WP_Rewrite();
$login_url = RenameLoginPage::getURL($spbc->settings['login_page_rename__name']);
}
$bfp = new BFP(
array(
'api_key' => $spbc->api_key,
'state' => $spbc,
'is_login_page' => strpos(trim(Server::getURL(), '/'), trim($login_url, '/')) === 0,
'is_logged_in' => Cookie::get('spbc_is_logged_in') === md5($spbc->data['salt'] . get_option('home')),
'bf_limit' => $spbc->settings['bfp__allowed_wrong_auths'],
'block_period' => $spbc->settings['bfp__block_period__5_fails'],
'count_period' => $spbc->settings['bfp__count_interval'],
)
);
$bfp->setDb(new DB());
$bfp->setIpArray([IP::get()]);
$bfp_result = $bfp->check();
$bfp->middleAction();
if (!empty($bfp_result)) {
$bfp->_die($bfp_result[0]);
}
}
//
// Sorts some data.
//
function spbc_usort_desc($a, $b)
{
return $b->datetime_ts - $a->datetime_ts;
}
/**
* Function to get the countries by IPs list.
*
* @param $ips_data
*
* @return array
*/
function spbc_get_countries_by_ips($ips_data = '')
{
$ips_c = array();
if ( $ips_data === '' ) {
return $ips_c;
}
$result = SpbcAPI::method__ip_info($ips_data);
if ( empty($result['error']) ) {
foreach ( $result as $ip_dec => $v2 ) {
if ( isset($v2['country_code']) ) {
$ips_c[ $ip_dec ]['country_code'] = $v2['country_code'];
}
if ( isset($v2['country_name']) ) {
$ips_c[ $ip_dec ]['country_name'] = $v2['country_name'];
}
}
}
return $ips_c;
}
/**
* Gets and write new signatures in local database
*
* @return bool|array
* @global State $spbc
* @global WPDB $wpdb
*/
function spbc_scanner__signatures_update()
{
global $spbc;
/**
* @psalm-suppress InvalidScalarArgument
*/
$spbc->error_delete('scanner_update_signatures_bad_signatures', 'save');
$latest_signature_submitted_time = SignatureAnalysisFacade::getLatestSignatureSubmittedTime();
$signatures_from_cloud = SignatureAnalysisFacade::getSignaturesFromCloud($latest_signature_submitted_time);
// Signatures updated
if (isset($signatures_from_cloud['error']) && $signatures_from_cloud['error'] === 'UP_TO_DATE') {
return array('success' => 'UP_TO_DATE');
}
// There is errors
if (isset($signatures_from_cloud['error'])) {
return $signatures_from_cloud;
}
$signatures = $signatures_from_cloud['values'];
$map = $signatures_from_cloud['map'];
SignatureAnalysisFacade::clearSignaturesTable();
$signatures_added = SignatureAnalysisFacade::addSignaturesToDb($map, $signatures);
if (!$signatures_added) {
// Attempt to record one at a time
$signatures_added = SignatureAnalysisFacade::addSignaturesToDbOneByOne($map, $signatures);
if (isset($signatures_added['bad_signatures'])) {
$spbc->error_add('scanner_update_signatures_bad_signatures', $signatures_added['bad_signatures']);
}
}
$spbc->data['scanner']['last_signature_update'] = current_time('timestamp');
$spbc->data['scanner']['signature_count'] = count($signatures);
$spbc->save('data');
return true;
}
/**
* Sending Security FireWall logs
*
* @param $api_key
*
* @return array|int
*/
function spbc_send_firewall_logs($api_key = false)
{
global $spbc;
$api_key = ! empty($api_key) ? $api_key : $spbc->api_key;
if ( ! empty($api_key) ) {
$result = FW::sendLog(
DB::getInstance(),
SPBC_TBL_FIREWALL_LOG,
$api_key
);
if ( empty($result['error']) ) {
$spbc->fw_stats['last_send'] = current_time('timestamp');
$spbc->fw_stats['last_send_count'] = $result;
$spbc->save('fw_stats', true, false);
return $result;
}
return $result;
}
return array(
'error' => 'KEY_EMPTY'
);
}
/**
* Drop Security FireWall data
*
* @return bool|string[]
*/
function spbc_security_firewall_drop()
{
global $wpdb;
// @psalm-suppress WpdbUnsafeMethodsIssue
$result = $wpdb->query('DELETE FROM `' . SPBC_TBL_FIREWALL_DATA . '`;');
if ( $result !== false ) {
return true;
}
return array( 'error' => 'DELETE_ERROR' );
}
/**
* Handle firewall private_records remote call.
* @param $action string 'add','delete'
* @param $test_data string JSON string used in test cases
* @return string JSON string of results
* @throws Exception
*/
function spbct_sfw_private_records_handler($action, $test_data = null)
{
$error = 'secfw_private_records_handler: ';
if ( !empty($action) && (in_array($action, array('add', 'delete'))) ) {
$metadata = !empty($test_data) ? $test_data : Post::get('metadata');
/**
* Validate JSON
*/
if ( !empty($metadata) ) {
$metadata = json_decode(stripslashes($metadata), true);
if ( $metadata === 'NULL' || $metadata === null ) {
throw new InvalidArgumentException($error . 'metadata JSON decoding failed');
}
} else {
throw new InvalidArgumentException($error . 'metadata is empty');
}
foreach ( $metadata as $_key => &$row ) {
$row = explode(',', $row);
/**
* Validation of JSON decoded array data
*/
$ip_validated = false;
$validation_error = '';
//validate IP
if ( IP::validate($row[0]) === 'v6' ) {
$ip_validated = $row[0];
} elseif (
IP::validate(long2ip((int)$row[0])) === 'v4'
&& (int)($row[0]) === ip2long(long2ip((int)$row[0]))
) {
$ip_validated = (int)$row[0];
} else {
$validation_error = 'network value does not look like IP address ';
}
//do this to get info more obvious
$metadata_assoc_array = array(
'network' => $ip_validated ?: null,
'mask' => (int)$row[1],
'status' => isset($row[2]) && $row[2] !== '' ? (int)$row[2] : null,
);
//validate mask and status
if ( $metadata_assoc_array['mask'] === 0
|| $metadata_assoc_array['mask'] > 4294967295
) {
$validation_error = 'metadata validate failed on "mask" value';
}
//only for adding
if ( $action === 'add' ) {
if ( !in_array($metadata_assoc_array['status'], array(-4, -3, -2, -1, 0, 1, 2, 99)) ) {
$validation_error = 'metadata validate failed on "status" value';
}
}
if ( !empty($validation_error) ) {
throw new InvalidArgumentException($error . $validation_error);
}
/**
* Ip version logic
*/
if ( is_string($metadata_assoc_array['network']) ) {
$metadata_assoc_array['network'] = IP::convertIPv6ToFourIPv4(IP::extendIPv6(IP::normalizeIPv6($metadata_assoc_array['network'])));
if ($metadata_assoc_array['mask'] > 128) {
$validation_error = 'metadata validate failed on "mask" value';
break;
}
/**
* Versatility for mask for v6 and v4
* @psalm-suppress LoopInvalidation
*/
for ( $masks = array(), $mask = $metadata_assoc_array['mask'], $k = 4; $k >= 1; $k-- ) {
$masks[$k] = (2 ** 32) - (2 ** (32 - ($mask > 32 ? 32 : $mask)));
$mask -= 32;
$mask = $mask > 0 ? $mask : 0;
}
$metadata_assoc_array['mask'] = $masks;
}
//all checks done, change on link
$row = $metadata_assoc_array;
}
unset($row);
if ( !empty($validation_error) ) {
throw new InvalidArgumentException($error . $validation_error);
}
//method selection
if ( $action === 'add' ) {
$handler_output = FW::privateRecordsAdd(
DB::getInstance(),
$metadata
);
} elseif ( $action === 'delete' ) {
$handler_output = FW::privateRecordsDelete(
DB::getInstance(),
$metadata
);
} else {
$error .= 'unknown action name: ' . $action;
throw new InvalidArgumentException($error);
}
} else {
throw new InvalidArgumentException($error . 'empty action name');
}
return json_encode(array('OK' => $handler_output));
}
function spbc_update_postmeta_links($post_ID)
{
delete_post_meta($post_ID, '_spbc_links_checked');
delete_post_meta($post_ID, 'spbc_links_checked');
}
function spbc_update_postmeta_links__by_comment($id)
{
$comment = get_comment($id);
spbc_update_postmeta_links($comment->comment_post_ID);
}
// Install MU-plugin
function spbc_mu_plugin__install()
{
// If WPMU_PLUGIN_DIR is not exists -> create it
if ( ! is_dir(WPMU_PLUGIN_DIR) && ! mkdir(WPMU_PLUGIN_DIR) && ! is_dir(WPMU_PLUGIN_DIR) ) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', WPMU_PLUGIN_DIR));
}
// Get data from info file and write it to new plugin file
$file = '<?php' . PHP_EOL . file_get_contents(SPBC_PLUGIN_DIR . '/install/security-malware-firewall-mu.php');
return @file_put_contents(WPMU_PLUGIN_DIR . '/0security-malware-firewall-mu.php', $file) ? true : false;
}
/**
* Uninstall MU-plugin
* @deprecated 2.125 Use Deactivator::muPluginUninstall
* @return bool
*/
function spbc_mu_plugin__uninstall()
{
return \CleantalkSP\SpbctWP\Deactivator::muPluginUninstall();
}
function spbc_user_is_admin()
{
global $spbc;
if (!empty($spbc->settings['data__set_cookies'])) {
return
Cookie::get('spbc_is_logged_in') === md5($spbc->data['salt'] . get_option('home')) &&
Cookie::get('spbc_admin_logged_in') === md5($spbc->data['salt'] . 'admin' . get_option('home'));
}
return is_admin();
}
//Function to send logs
function spbc_send_logs($api_key = null)
{
global $spbc, $wpdb;
if ( $api_key == null ) {
if ( ! $spbc->is_mainsite && $spbc->ms__work_mode == 2 ) {
$api_key = $spbc->network_settings['spbc_key'];
} else {
$api_key = $spbc->settings['spbc_key'];
}
}
if ( ! $api_key ) {
return array(
'error' => 'KEY_EMPTY'
);
}
$wpms_snippet = SPBC_WPMS
? (" WHERE blog_id = " . get_current_blog_id() . ' AND ')
: " WHERE ";
// @psalm-suppress WpdbUnsafeMethodsIssue
$rows = $wpdb->get_results(
"SELECT id, datetime, timestamp_gmt, user_login, page, page_time, event, auth_ip, role, user_agent, browser_sign
FROM " . SPBC_TBL_SECURITY_LOG
. $wpms_snippet
. " sent <> 1"
. " ORDER BY datetime DESC"
. " LIMIT " . SPBC_SELECT_LIMIT . ";"
);
$rows_count = count($rows);
if ( $rows_count ) {
$data = array();
foreach ( $rows as $record ) {
$page_time = (string) $record->page_time;
if ((int)$page_time <= 0) {
$page_time = '1';
}
$user_agent = null;
$browser_signature = null;
if ( in_array(strval($record->event), array( 'login', 'login_2fa', 'login_new_device', 'logout', )) ) {
$user_agent = $record->user_agent;
$browser_signature = $record->browser_sign;
}
$security_logs_row_dto = new SecurityLogsDataRowDTO(array(
'log_id' => (string) $record->id,
'datetime' => (string) $record->datetime,
'datetime_gmt' => $record->timestamp_gmt,
'user_log' => (string) $record->user_login,
'event' => (string) $record->event,
'auth_ip' => strpos($record->auth_ip, ':') === false
? (int) sprintf('%u', ip2long($record->auth_ip))
: (string) $record->auth_ip,
'page_url' => (string) $record->page,
'event_runtime' => $page_time,
'role' => (string) $record->role,
'user_agent' => (string) $user_agent,
'browser_signature' => (string) $browser_signature,
));
$data[] = $security_logs_row_dto->getArray();
}
$security_logs_method_dto = new SecurityLogsDTO(
array(
'auth_key' => $api_key,
'method_name' => 'security_logs',
'timestamp' => current_time('timestamp'),
'data' => json_encode($data),