forked from Sucuri/sucuri-wordpress-plugin
/
sucuri.php
15061 lines (13084 loc) · 549 KB
/
sucuri.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: Sucuri Security - Auditing, Malware Scanner and Hardening
Plugin URI: https://wordpress.sucuri.net/
Description: The <a href="https://sucuri.net/" target="_blank">Sucuri</a> plugin provides the website owner the best Activity Auditing, SiteCheck Remote Malware Scanning, Effective Security Hardening and Post-Hack features. SiteCheck will check for malware, spam, blacklisting and other security issues like .htaccess redirects, hidden eval code, etc. The best thing about it is it's completely free.
Author: Sucuri, INC
Version: 1.7.17
Author URI: https://sucuri.net
*/
/**
* Main file to control the plugin.
*
* @package Sucuri Security
* @author Daniel Cid <dcid@sucuri.net>
* @copyright Since 2010-2015 Sucuri Inc.
* @license Released under the GPL - see LICENSE file for details.
* @link https://wordpress.sucuri.net/
* @since File available since Release 0.1
*/
/**
* Plugin dependencies.
*
* List of required functions for the execution of this plugin, we are assuming
* that this site was built on top of the WordPress project, and that it is
* being loaded through a pluggable system, these functions most be defined
* before to continue.
*
* @var array
*/
$sucuriscan_dependencies = array(
'wp',
'wp_die',
'add_action',
'remove_action',
'wp_remote_get',
'wp_remote_post',
);
// Terminate execution if any of the functions mentioned above is not defined.
foreach ($sucuriscan_dependencies as $dependency) {
if (!function_exists($dependency)) {
exit(0);
}
}
/**
* Plugin's constants.
*
* These constants will hold the basic information of the plugin, file/folder
* paths, version numbers, read-only variables that will affect the functioning
* of the rest of the code. The conditional will act as a container helping in
* the readability of the code considering the total number of lines that this
* file will have.
*/
/**
* Unique name of the plugin through out all the code.
*/
define('SUCURISCAN', 'sucuriscan');
/**
* Current version of the plugin's code.
*/
define('SUCURISCAN_VERSION', '1.7.17');
/**
* The name of the Sucuri plugin main file.
*/
define('SUCURISCAN_PLUGIN_FILE', 'sucuri.php');
/**
* The name of the folder where the plugin's files will be located.
*/
define('SUCURISCAN_PLUGIN_FOLDER', 'sucuri-scanner');
/**
* The fullpath where the plugin's files will be located.
*/
define('SUCURISCAN_PLUGIN_PATH', WP_PLUGIN_DIR.'/'.SUCURISCAN_PLUGIN_FOLDER);
/**
* The fullpath of the main plugin file.
*/
define('SUCURISCAN_PLUGIN_FILEPATH', SUCURISCAN_PLUGIN_PATH.'/'.SUCURISCAN_PLUGIN_FILE);
/**
* The local URL where the plugin's files and assets are served.
*/
define('SUCURISCAN_URL', rtrim(plugin_dir_url(SUCURISCAN_PLUGIN_FILEPATH), '/'));
/**
* Checksum of this file to check the integrity of the plugin.
*/
define('SUCURISCAN_PLUGIN_CHECKSUM', @md5_file(SUCURISCAN_PLUGIN_FILEPATH));
/**
* Remote URL where the public Sucuri API service is running.
*/
define('SUCURISCAN_API', 'sucuri://wordpress.sucuri.net/api/');
/**
* Latest version of the public Sucuri API.
*/
define('SUCURISCAN_API_VERSION', 'v1');
/**
* Remote URL where the CloudProxy API service is running.
*/
define('SUCURISCAN_CLOUDPROXY_API', 'sucuri://waf.sucuri.net/api');
/**
* Latest version of the CloudProxy API.
*/
define('SUCURISCAN_CLOUDPROXY_API_VERSION', 'v2');
/**
* The maximum quantity of entries that will be displayed in the last login page.
*/
define('SUCURISCAN_LASTLOGINS_USERSLIMIT', 25);
/**
* The maximum quantity of entries that will be displayed in the audit logs page.
*/
define('SUCURISCAN_AUDITLOGS_PER_PAGE', 50);
/**
* The maximum quantity of buttons in the paginations.
*/
define('SUCURISCAN_MAX_PAGINATION_BUTTONS', 20);
/**
* The minimum quantity of seconds to wait before each filesystem scan.
*/
define('SUCURISCAN_MINIMUM_RUNTIME', 10800);
/**
* The life time of the cache for the results of the SiteCheck scans.
*/
define('SUCURISCAN_SITECHECK_LIFETIME', 1200);
/**
* The life time of the cache for the results of the get_plugins function.
*/
define('SUCURISCAN_GET_PLUGINS_LIFETIME', 1800);
/**
* The maximum execution time of a HTTP request before timeout.
*/
define('SUCURISCAN_MAX_REQUEST_TIMEOUT', 15);
/**
* The maximum execution time for SiteCheck requests before timeout.
*/
define('SUCURISCAN_MAX_SITECHECK_TIMEOUT', 60);
/**
* Plugin's global variables.
*
* These variables will be defined globally to allow the inclusion in multiple
* functions and classes defined in the libraries loaded by this plugin. The
* conditional will act as a container helping in the readability of the code
* considering the total number of lines that this file will have.
*/
if (defined('SUCURISCAN')) {
/**
* Define the prefix for some actions and filters that rely in the
* differentiation of the type of site where the extension is being used. There
* are a few differences between a single site installation that must be
* correctly defined when the extension is in a different environment, for
* example, in a multisite installation.
*
* @var string
*/
$sucuriscan_action_prefix = SucuriScan::is_multisite() ? 'network_' : '';
/**
* List an associative array with the sub-pages of this plugin.
*
* @return array
*/
$sucuriscan_pages = array(
'sucuriscan' => 'Dashboard',
'sucuriscan_scanner' => 'Malware Scan',
'sucuriscan_firewall' => 'Firewall (WAF)',
'sucuriscan_hardening' => 'Hardening',
'sucuriscan_posthack' => 'Post-Hack',
'sucuriscan_lastlogins' => 'Last Logins',
'sucuriscan_settings' => 'Settings',
'sucuriscan_infosys' => 'Site Info',
);
/**
* Settings options.
*
* The following global variables are mostly associative arrays where the key is
* linked to an option that will be stored in the database, and their
* correspondent values are the description of the option. These variables will
* be used in the settings page to offer the user a way to configure the
* behaviour of the plugin.
*
* @var array
*/
$sucuriscan_notify_options = array(
'sucuriscan_notify_plugin_change' => 'Receive email alerts for <b>Sucuri</b> plugin changes',
'sucuriscan_prettify_mails' => 'Receive email alerts in HTML <em>(there may be issues with some mail services)</em>',
'sucuriscan_use_wpmail' => 'Use WordPress functions to send mails <em>(uncheck to use native PHP functions)</em>',
'sucuriscan_lastlogin_redirection' => 'Allow redirection after login to report the last-login information',
'sucuriscan_notify_scan_checksums' => 'Receive email alerts for core integrity checks',
'sucuriscan_notify_available_updates' => 'Receive email alerts for available updates',
'sucuriscan_notify_user_registration' => 'user:Receive email alerts for new user registration',
'sucuriscan_notify_success_login' => 'user:Receive email alerts for successful login attempts',
'sucuriscan_notify_failed_login' => 'user:Receive email alerts for failed login attempts <em>(you may receive tons of emails)</em>',
'sucuriscan_notify_bruteforce_attack' => 'user:Receive email alerts for password guessing attacks <em>(summary of failed logins per hour)</em>',
'sucuriscan_notify_post_publication' => 'Receive email alerts for Post-Type changes <em>(configure from Ignore Alerts)</em>',
'sucuriscan_notify_website_updated' => 'Receive email alerts when the WordPress version is updated',
'sucuriscan_notify_settings_updated' => 'Receive email alerts when your website settings are updated',
'sucuriscan_notify_theme_editor' => 'Receive email alerts when a file is modified with theme/plugin editor',
'sucuriscan_notify_plugin_installed' => 'plugin:Receive email alerts when a <b>plugin is installed</b>',
'sucuriscan_notify_plugin_activated' => 'plugin:Receive email alerts when a <b>plugin is activated</b>',
'sucuriscan_notify_plugin_deactivated' => 'plugin:Receive email alerts when a <b>plugin is deactivated</b>',
'sucuriscan_notify_plugin_updated' => 'plugin:Receive email alerts when a <b>plugin is updated</b>',
'sucuriscan_notify_plugin_deleted' => 'plugin:Receive email alerts when a <b>plugin is deleted</b>',
'sucuriscan_notify_widget_added' => 'widget:Receive email alerts when a <b>widget is added</b> to a sidebar',
'sucuriscan_notify_widget_deleted' => 'widget:Receive email alerts when a <b>widget is deleted</b> from a sidebar',
'sucuriscan_notify_theme_installed' => 'theme:Receive email alerts when a <b>theme is installed</b>',
'sucuriscan_notify_theme_activated' => 'theme:Receive email alerts when a <b>theme is activated</b>',
'sucuriscan_notify_theme_updated' => 'theme:Receive email alerts when a <b>theme is updated</b>',
'sucuriscan_notify_theme_deleted' => 'theme:Receive email alerts when a <b>theme is deleted</b>',
);
$sucuriscan_schedule_allowed = array(
'hourly' => 'Every three hours (3 hours)',
'twicedaily' => 'Twice daily (12 hours)',
'daily' => 'Once daily (24 hours)',
'_oneoff' => 'Never',
);
$sucuriscan_interface_allowed = array(
'spl' => 'SPL (high performance)',
'opendir' => 'OpenDir (medium)',
'glob' => 'Glob (low)',
);
$sucuriscan_emails_per_hour = array(
'5' => 'Maximum 5 per hour',
'10' => 'Maximum 10 per hour',
'20' => 'Maximum 20 per hour',
'40' => 'Maximum 40 per hour',
'80' => 'Maximum 80 per hour',
'160' => 'Maximum 160 per hour',
'unlimited' => 'Unlimited',
);
$sucuriscan_maximum_failed_logins = array(
'30' => '30 failed logins per hour',
'60' => '60 failed logins per hour',
'120' => '120 failed logins per hour',
'240' => '240 failed logins per hour',
'480' => '480 failed logins per hour',
);
$sucuriscan_verify_ssl_cert = array(
'true' => 'Verify peer\'s cert',
'false' => 'Stop peer\'s cert verification',
);
$sucuriscan_no_notices_in = array(
/* Value of the page parameter to ignore. */
);
$sucuriscan_email_subjects = array(
'Sucuri Alert, :domain, :event',
'Sucuri Alert, :domain, :event, :remoteaddr',
'Sucuri Alert, :domain, :event, :username',
'Sucuri Alert, :domain, :event, :email',
'Sucuri Alert, :event, :remoteaddr',
'Sucuri Alert, :event',
);
$sucuriscan_date_format = get_option('date_format');
$sucuriscan_time_format = get_option('time_format');
/**
* Remove the WordPress generator meta-tag from the source code.
*/
remove_action('wp_head', 'wp_generator');
/**
* Run a specific function defined in the plugin's code to locate every
* directory and file, collect their checksum and file size, and send this
* information to the Sucuri API service where a security and integrity scan
* will be performed against the hashes provided and the official versions.
*/
add_action('sucuriscan_scheduled_scan', 'SucuriScan::run_scheduled_task');
/**
* Initialize the execute of the main plugin's functions.
*
* This will load the menu options in the WordPress administrator panel, and
* execute the bootstrap function of the plugin.
*/
add_action('init', 'SucuriScanInterface::initialize', 1);
add_action('init', 'SucuriScanBlockedUsers::blockUserLogin', 1);
add_action('admin_init', 'SucuriScanInterface::handleOldPlugins');
add_action('admin_init', 'SucuriScanInterface::createStorageFolder');
add_action('admin_enqueue_scripts', 'SucuriScanInterface::enqueueScripts', 1);
/**
* Display extension menu and submenu items in the correct interface. For single
* site installations the menu items can be displayed normally as always but for
* multisite installations the menu items must be available only in the network
* panel and hidden in the administration panel of the subsites.
*/
add_action($sucuriscan_action_prefix . 'admin_menu', 'SucuriScanInterface::addInterfaceMenu');
/**
* Attach Ajax requests to a custom page handler.
*/
foreach ($sucuriscan_pages as $page_func => $page_title) {
$ajax_func = $page_func . '_ajax';
if (function_exists($ajax_func)) {
add_action('wp_ajax_' . $ajax_func, $ajax_func);
}
}
/**
* Function call interceptors.
*
* Define the names for the hooks that will intercept specific function calls in
* the admin interface and parts of the external site, an event report will be
* sent to the API service and an email notification to the administrator of the
* site.
*
* @see Class SucuriScanHook
*/
if (class_exists('SucuriScanHook')) {
$sucuriscan_hooks = array(
'add_attachment',
'add_link',
'create_category',
'delete_post',
'delete_user',
'login_form_resetpass',
'private_to_published',
'publish_page',
'publish_phone',
'publish_post',
'retrieve_password',
'switch_theme',
'user_register',
'wp_insert_comment',
'wp_login',
'wp_login_failed',
'wp_trash_post',
'xmlrpc_publish_post',
);
if (SucuriScanOption::is_enabled(':xhr_monitor')) {
$sucuriscan_hooks[] = 'all';
}
foreach ($sucuriscan_hooks as $hook_name) {
$hook_func = 'SucuriScanHook::hook_' . $hook_name;
add_action($hook_name, $hook_func, 50, 5);
}
add_action('admin_init', 'SucuriScanHook::hook_undefined_actions');
add_action('login_form', 'SucuriScanHook::hook_undefined_actions');
} else {
SucuriScanInterface::error('Function call interceptors are not working properly.');
}
/**
* Display a message if the plugin is not activated.
*
* Display a message at the top of the administration panel with a button that
* once clicked will send the site's email and domain name to the Sucuri API
* service where an API key will be generated for the site, this key will allow
* the plugin to execute the filesystem scans, the project integrity, and the
* email notifications.
*/
add_action($sucuriscan_action_prefix . 'admin_notices', 'SucuriScanInterface::setup_notice');
/**
* Heartbeat API
*
* Update the settings of the Heartbeat API according to the values set by an
* administrator. This tool may cause an increase in the CPU usage, a bad
* configuration may cause low account to run out of resources, but in better
* cases it may improve the performance of the site by reducing the quantity of
* requests sent to the server per session.
*/
add_filter('init', 'SucuriScanHeartbeat::register_script', 1);
add_filter('heartbeat_settings', 'SucuriScanHeartbeat::update_settings');
add_filter('heartbeat_send', 'SucuriScanHeartbeat::respond_to_send', 10, 3);
add_filter('heartbeat_received', 'SucuriScanHeartbeat::respond_to_received', 10, 3);
add_filter('heartbeat_nopriv_send', 'SucuriScanHeartbeat::respond_to_send', 10, 3);
add_filter('heartbeat_nopriv_received', 'SucuriScanHeartbeat::respond_to_received', 10, 3);
}
/**
* Miscellaneous library.
*
* Multiple and generic functions that will be used through out the code of
* other libraries extending from this and functions defined in other files, be
* aware of the hierarchy and check the other libraries for duplicated methods.
*/
class SucuriScan
{
/**
* Class constructor.
*/
public function __construct()
{
}
/**
* Return name of a variable with the plugin's prefix (if needed).
*
* To facilitate the development, you can prefix the name of the key in the
* request (when accessing it) with a single colon, this function will
* automatically replace that character with the unique identifier of the
* plugin.
*
* @param string $var_name Name of a variable with an optional colon at the beginning.
* @return string Full name of the variable with the extra characters (if needed).
*/
public static function variable_prefix($var_name = '')
{
if (!empty($var_name) && $var_name[0] === ':') {
$var_name = sprintf(
'%s_%s',
SUCURISCAN,
substr($var_name, 1)
);
}
return $var_name;
}
/**
* Gets the value of a configuration option.
*
* @param string $property The configuration option name.
* @return string Value of the configuration option as a string on success.
*/
public static function ini_get($property = '')
{
$ini_value = ini_get($property);
$default = array(
'error_log' => 'error_log',
'safe_mode' => 'Off',
'memory_limit' => '128M',
'upload_max_filesize' => '2M',
'post_max_size' => '8M',
'max_execution_time' => '30',
'max_input_time' => '-1',
);
if ($ini_value === false) {
$ini_value = 'Undefined';
} elseif (empty($ini_value) || $ini_value === null) {
if (array_key_exists($property, $default)) {
$ini_value = $default[$property];
} else {
$ini_value = 'Off';
}
}
if ($property == 'error_log') {
$ini_value = basename($ini_value);
}
return $ini_value;
}
/**
* Encodes the less-than, greater-than, ampersand, double quote and single quote
* characters, will never double encode entities.
*
* @param string $text The text which is to be encoded.
* @return string The encoded text with HTML entities.
*/
public static function escape($text = '')
{
// Escape the value of the variable using a built-in function if possible.
if (function_exists('esc_attr')) {
$text = esc_attr($text);
} else {
$text = htmlspecialchars($text);
}
return $text;
}
/**
* Generates a lowercase random string with an specific length.
*
* @param integer $length Length of the string that will be generated.
* @return string The random string generated.
*/
public static function random_char($length = 4)
{
$string = '';
$offset = 25;
$chars = array(
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
);
for ($i = 0; $i < $length; $i++) {
$index = rand(0, $offset);
$string .= $chars[$index];
}
return $string;
}
/**
* Translate a given number in bytes to a human readable file size using the
* a approximate value in Kylo, Mega, Giga, etc.
*
* @link https://www.php.net/manual/en/function.filesize.php#106569
* @param integer $bytes An integer representing a file size in bytes.
* @param integer $decimals How many decimals should be returned after the translation.
* @return string Human readable representation of the given number in Kylo, Mega, Giga, etc.
*/
public static function human_filesize($bytes = 0, $decimals = 2)
{
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[ $factor ];
}
/**
* Fix the deliminar of a resource path.
*
* In Windows based system the directory separator is a back slash which
* differs from what other file systems use. To keep consistency during the
* unit-tests we have decided to replace any non forward slash with it.
*
* @return string Fixed file path.
*/
public static function fixPath($path = '')
{
$delimiter = '/' /* Forward slash */;
$path = str_replace(DIRECTORY_SEPARATOR, $delimiter, $path);
$path = rtrim($path, $delimiter);
return $path;
}
/**
* Returns the system filepath to the relevant user uploads directory for this
* site. This is a multisite capable function.
*
* @param string $path The relative path that needs to be completed to get the absolute path.
* @return string The full filesystem path including the directory specified.
*/
public static function datastore_folder_path($path = '')
{
$default_dir = 'sucuri';
$abspath = self::fixPath(ABSPATH);
if (defined('SUCURI_DATA_STORAGE')
&& file_exists(SUCURI_DATA_STORAGE)
&& is_dir(SUCURI_DATA_STORAGE)
) {
$datastore = SUCURI_DATA_STORAGE;
} else {
$datastore = SucuriScanOption::get_option(':datastore_path');
}
// Use the uploads folder by default.
if (empty($datastore)) {
$uploads_path = false;
// Multisite installations may have different paths.
if (function_exists('wp_upload_dir')) {
$upload_dir = wp_upload_dir();
if (isset($upload_dir['basedir'])) {
$uploads_path = rtrim($upload_dir['basedir'], DIRECTORY_SEPARATOR);
}
}
if ($uploads_path === false) {
if (defined('WP_CONTENT_DIR')) {
$uploads_path = implode(DIRECTORY_SEPARATOR, array(WP_CONTENT_DIR, 'uploads'));
} else {
$uploads_path = implode(DIRECTORY_SEPARATOR, array($abspath, 'wp-content', 'uploads'));
}
}
$datastore = $uploads_path . DIRECTORY_SEPARATOR . $default_dir;
$datastore = self::fixPath($datastore);
SucuriScanOption::update_option(':datastore_path', $datastore);
}
// Keep consistency with the directory separator.
$final = $datastore . DIRECTORY_SEPARATOR . $path;
$final = self::fixPath($final);
return $final;
}
/**
* Check whether the current site is working as a multi-site instance.
*
* @return boolean Either TRUE or FALSE in case WordPress is being used as a multi-site instance.
*/
public static function is_multisite()
{
return (bool) (function_exists('is_multisite') && is_multisite());
}
public static function admin_url($url = '')
{
if (self::is_multisite()) {
return network_admin_url($url);
} else {
return admin_url($url);
}
}
/**
* Find and retrieve the current version of Wordpress installed.
*
* @return string The version number of Wordpress installed.
*/
public static function site_version()
{
global $wp_version;
if ($wp_version === null) {
$wp_version_path = ABSPATH . WPINC . '/version.php';
if (file_exists($wp_version_path)) {
include($wp_version_path);
$wp_version = isset($wp_version) ? $wp_version : '0.0';
} else {
$option_version = get_option('version');
$wp_version = $option_version ? $option_version : '0.0';
}
}
$wp_version = self::escape($wp_version);
return $wp_version;
}
/**
* Find and retrieve the absolute path of the WordPress configuration file.
*
* @return string Absolute path of the WordPress configuration file.
*/
public static function get_wpconfig_path()
{
if (defined('ABSPATH')) {
$file_path = ABSPATH . '/wp-config.php';
// if wp-config.php doesn't exist, or is not readable check one directory up.
if (!file_exists($file_path)) {
$file_path = ABSPATH . '/../wp-config.php';
}
// Remove duplicated double slashes.
$file_path = @realpath($file_path);
if ($file_path) {
return $file_path;
}
}
return false;
}
/**
* Find and retrieve the absolute path of the main WordPress htaccess file.
*
* @return string Absolute path of the main WordPress htaccess file.
*/
public static function get_htaccess_path()
{
if (defined('ABSPATH')) {
$base_dirs = array(
rtrim(ABSPATH, '/'),
dirname(ABSPATH),
dirname(dirname(ABSPATH)),
);
foreach ($base_dirs as $base_dir) {
$htaccess_path = sprintf('%s/.htaccess', $base_dir);
if (file_exists($htaccess_path)) {
return $htaccess_path;
}
}
}
return false;
}
/**
* Get the pattern of the definition related with a WordPress secret key.
*
* @return string Secret key definition pattern.
*/
public static function secret_key_pattern()
{
return '/define\(\s*\'([A-Z_]+)\',(\s*)\'(.+)\'\s*\);/';
}
/**
* Execute the plugin' scheduled tasks.
*
* @return void
*/
public static function run_scheduled_task()
{
SucuriScanEvent::filesystem_scan();
sucuriscan_core_files_data(true);
sucuriscan_posthack_updates_content(true);
}
/**
* List of allowed HTTP headers to retrieve the real IP.
*
* Once the DNS lookups are enabled to discover the real IP address of the
* visitors the user may choose the HTTP header that will be used by default to
* retrieve the real IP address of each HTTP request, generally they do not need
* to set this but in rare cases the hosting provider may have a load balancer
* that can interfere in the process, in which case they will have to explicitly
* specify the main HTTP header. This is a list of the allowed headers that the
* user can choose.
*
* @param boolean $with_keys Return the array with its values are keys.
* @return array Allowed HTTP headers to retrieve real IP.
*/
public static function allowedHttpHeaders($with_keys = false)
{
$allowed = array(
/* CloudProxy custom HTTP headers */
'HTTP_X_SUCURI_CLIENTIP',
/* CloudFlare custom HTTP headers */
'HTTP_CF_CONNECTING_IP', /* Real visitor IP. */
'HTTP_CF_IPCOUNTRY', /* Country of visitor. */
'HTTP_CF_RAY', /* https://support.cloudflare.com/entries/23046742-w. */
'HTTP_CF_VISITOR', /* Determine if HTTP or HTTPS. */
/* Possible HTTP headers */
'HTTP_X_REAL_IP',
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'SUCURI_RIP',
'REMOTE_ADDR',
);
if ($with_keys === true) {
$verbose = array();
foreach ($allowed as $header) {
$verbose[$header] = $header;
}
return $verbose;
}
return $allowed;
}
/**
* List HTTP headers ordered.
*
* The list of HTTP headers is ordered per relevancy, and having the main HTTP
* header as the first entry, this guarantees that the IP address of the
* visitors will be retrieved from the HTTP header chosen by the user first and
* fallback to the other alternatives if available.
*
* @return array Ordered allowed HTTP headers.
*/
private static function orderedHttpHeaders()
{
$ordered = array();
$allowed = self::allowedHttpHeaders();
$addr_header = SucuriScanOption::get_option(':addr_header');
$ordered[] = $addr_header;
foreach ($allowed as $header) {
if (!in_array($header, $ordered)) {
$ordered[] = $header;
}
}
return $ordered;
}
/**
* Retrieve the real ip address of the user in the current request.
*
* @param boolean $with_header Return HTTP header where the IP address was found.
* @return string Real IP address of the user in the current request.
*/
public static function get_remote_addr($with_header = false)
{
$remote_addr = false;
$header_used = 'unknown';
$headers = self::orderedHttpHeaders();
foreach ($headers as $header) {
if (array_key_exists($header, $_SERVER)
&& self::is_valid_ip($_SERVER[$header])
) {
$remote_addr = $_SERVER[$header];
$header_used = $header;
break;
}
}
if (!$remote_addr || $remote_addr === '::1') {
$remote_addr = '127.0.0.1';
}
if ($with_header) {
return $header_used;
}
return $remote_addr;
}
/**
* Return the HTTP header used to retrieve the remote address.
*
* @return string The HTTP header used to retrieve the remote address.
*/
public static function get_remote_addr_header()
{
return self::get_remote_addr(true);
}
/**
* Retrieve the user-agent from the current request.
*
* @return string The user-agent from the current request.
*/
public static function get_user_agent()
{
if (isset($_SERVER['HTTP_USER_AGENT'])) {
return self::escape($_SERVER['HTTP_USER_AGENT']);
}
return false;
}
/**
* Get the clean version of the current domain.
*
* @return string The domain of the current site.
*/
public static function get_domain($return_tld = false)
{
if (function_exists('get_site_url')) {
$site_url = get_site_url();
$pattern = '/([fhtps]+:\/\/)?([^:\/]+)(:[0-9:]+)?(\/.*)?/';
$replacement = ( $return_tld === true ) ? '$2' : '$2$3$4';
$domain_name = @preg_replace($pattern, $replacement, $site_url);
return $domain_name;
}
return false;
}
/**
* Get top-level domain (TLD) of the website.
*
* @return string Top-level domain (TLD) of the website.
*/
public static function get_top_level_domain()
{
return self::get_domain(true);
}
/**
* Check whether reverse proxy servers must be supported.
*
* @return boolean TRUE if reverse proxies must be supported, FALSE otherwise.
*/
public static function support_reverse_proxy()
{
return SucuriScanOption::is_enabled(':revproxy');
}
/**
* Check whether the DNS lookups should be execute or not.
*
* DNS lookups are only necessary if you are planning to use a reverse proxy or
* firewall (like CloudProxy), this is used to set the correct IP address when
* the firewall/proxy filters the requests. If you are not planning to use any
* of these is better to disable this option, otherwise the load time of your
* site may be affected.
*
* @return boolean True if the DNS lookups should be executed, false otherwise.
*/
public static function execute_dns_lookups()
{
if (( defined('NOT_USING_CLOUDPROXY') && NOT_USING_CLOUDPROXY === true )
|| SucuriScanOption::is_disabled(':dns_lookups')
) {
return false;
}
return true;
}
/**
* Check whether the site is behind the Sucuri CloudProxy network.
*
* @param boolean $verbose Return an array with the hostname, address, and status, or not.
* @return boolean Either TRUE or FALSE if the site is behind CloudProxy.
*/
public static function is_behind_cloudproxy($verbose = false)
{
$http_host = self::get_top_level_domain();
if (self::execute_dns_lookups()) {
$host_by_addr = @gethostbyname($http_host);
$host_by_name = @gethostbyaddr($host_by_addr);
$status = (bool) preg_match('/^cloudproxy[0-9]+\.sucuri\.net$/', $host_by_name);
} else {
$status = false;
$host_by_addr = '::1';
$host_by_name = 'localhost';
}
/*
* If the DNS reversion failed but the CloudProxy API key is set, then consider
* the site as protected by a firewall. A fake key can be used to bypass the DNS
* checking, but that is not something that will affect us, only the client.
*/
if ($status === false
&& SucuriScanAPI::getCloudproxyKey()
) {
$status = true;
}
if ($verbose) {
return array(
'http_host' => $http_host,
'host_name' => $host_by_name,
'host_addr' => $host_by_addr,
'status' => $status,
);
}
return $status;
}
/**
* Get the email address set by the administrator to receive the notifications
* sent by the plugin, if the email is missing the WordPress email address is
* chosen by default.
*
* @return string The administrator email address.
*/
public static function get_site_email()
{
$email = get_option('admin_email');
if (self::is_valid_email($email)) {
return $email;
}
return false;
}
/**
* Get user data by field and data.
*
* @param integer $identifier User account identifier.
* @return object WordPress user object with data.
*/
public static function get_user_by_id($identifier = 0)
{
if (function_exists('get_user_by')) {
$user = get_user_by('id', $identifier);
if ($user instanceof WP_User) {
return $user;
}
}