-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathexploit-scanner.php
1002 lines (870 loc) · 37.3 KB
/
exploit-scanner.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: Exploit Scanner
Plugin URI: http://ocaoimh.ie/exploit-scanner/
Description: Scans your WordPress site for possible exploits.
Version: 1.3.3
Author: Donncha O Caoimh
Author URI: http://ocaoimh.ie/
*/
@ini_set( 'max_execution_time', 120 );
include_once 'exploit-scanner-cli.php';
/**
* Set up the menu item and register with hooks to print JS and help.
*/
function exploitscanner_menu() {
$page_hook = add_management_page( 'Exploit Scanner', 'Exploit Scanner', 'manage_options', 'exploit-scanner', 'exploitscanner_admin_page' );
if ( $page_hook ) {
add_action( "admin_print_styles-$page_hook", 'add_thickbox' );
add_action( "admin_footer-$page_hook", 'exploitscanner_admin_scripts' );
add_action( "load-$page_hook", 'exploitscanner_help_tabs' );
}
}
add_action( 'admin_menu', 'exploitscanner_menu' );
function exploitscanner_help_tabs() {
$screen = get_current_screen();
$screen->add_help_tab( array(
'id' => 'interpreting-results',
'title' => 'Interpreting the Results',
'content' => '<p><strong>Interpreting the Results</strong></p>
<p>It is likely that this scanner will find false positives (i.e. files which do not contain malicious code). However, it is best to err
on the side of caution; if you are unsure then ask in the <a href="http://wordpress.org/support/" target="_blank">Support Forums</a>,
download a fresh copy of a plugin, search the Internet for similar situations, et cetera. You should be most concerned if the scanner is:
making matches around unknown external links; finding obfuscated text in modified core files or the <code>wp-config.php</code> file;
listing extra admin accounts; or finding content in posts which you did not put there.</p>
<p>Understanding the three different result levels:</p>
<ul>
<li><strong>Severe:</strong> results that are often strong indicators of a hack (though they are not definitive proof)</li>
<li><strong>Warning:</strong> these results are more commonly found in innocent circumstances than Severe matches, but they should still be treated with caution</li>
<li><strong>Note:</strong> lowest priority, showing results that are very commonly used in legitimate code or notifications about events such as skipped files</li>
</ul>',
) );
$screen->add_help_tab( array(
'id' => 'advice-for-the-owned',
'title' => 'Help! I think I have been hacked!',
'content' => '<p><strong>Help! I think I have been hacked!</strong></p>
<p>Follow the guides from the Codex:</p>
<ul>
<li><a href="http://codex.wordpress.org/FAQ_My_site_was_hacked">Codex: FAQ - My site was hacked</a></li>
<li><a href="http://codex.wordpress.org/Hardening_WordPress">Codex: Hardening WordPress</a></li>
</ul>
<p>Ensure that you change <strong>all</strong> of your WordPress related passwords (site, FTP, MySQL, etc.). A regular backup routine
(either manual or plugin powered) is extremely useful; if you ever find that your site has been hacked you can easily restore your site from
a clean backup and fresh set of files and, of course, use a new set of passwords.</p>',
) );
}
/**
* Print scripts that power paged scanning and diff modal.
*/
function exploitscanner_admin_scripts() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#run-scanner').click( function() {
var fsl = $('#filesize_limit').val(),
max = parseInt( $('#max_test_files').val(), 10 ),
dis = ($('#display_pattern:checked').val() !== undefined);
$.ajaxSetup({
type: 'POST',
url: ajaxurl,
complete: function(xhr,status) {
if ( status != 'success' ) {
$('#scan-loader img').hide();
$('#scan-loader span').html( 'An error occurred. Please try again later.' );
}
}
});
$('#scan-results').hide();
$('#scan-loader').show();
exploitscanner_file_scan(0, fsl, max, dis);
return false;
});
$('#hide-skipped').toggle( function() {
$('.skipped-file').hide();
$(this).html('Show skipped files');
}, function() {
$('.skipped-file').show();
$(this).html('Hide skipped files');
});
$('.view-diff').click( function() {
// escaped ampersands returned by wp_nonce_url don't play nicely here
var nonce = '_ajax_nonce=<?php echo wp_create_nonce( 'exploit-scanner_view_diff' ); ?>';
tb_show( 'File changes', ajaxurl + '?action=exploit-scanner_view_diff&' + nonce + '&file=' + this.id, false );
return false;
});
});
var exploitscanner_nonce = '<?php echo wp_create_nonce( 'exploit-scanner_scan' ); ?>',
exploitscanner_file_scan = function(s, fsl, max, dis) {
jQuery.ajax({
data: {
action: 'exploit-scanner_file_scan',
start: s,
filesize_limit: fsl,
max_batch_size: max,
display_pattern: dis,
_ajax_nonce: exploitscanner_nonce
}, success: function(r) {
var res = jQuery.parseJSON(r);
if ( 'running' == res.status ) {
jQuery('#scan-loader span').html(res.data);
exploitscanner_file_scan(s+max, fsl, max, dis);
} else if ( 'error' == res.status ) {
// console.log( r );
jQuery('#scan-loader img').hide();
jQuery('#scan-loader span').html(
'An error occurred: <pre style="overflow:auto">' + r.toString() + '</pre>'
);
} else {
exploitscanner_db_scan();
}
}
});
}, exploitscanner_db_scan = function() {
jQuery('#scan-loader span').html('Scanning database...');
jQuery.ajax({
data: {
action: 'exploit-scanner_db_scan',
_ajax_nonce: exploitscanner_nonce
}, success: function(r) {
jQuery('#scan-loader img').hide();
jQuery('#scan-loader span').html('Scan complete. Refresh the page to view the results.');
window.location.reload(false);
}
});
};
</script>
<?php
}
/**
* add_management_page callback
*/
function exploitscanner_admin_page() {
// non-ajax scan form processing
if ( isset($_POST['action']) && 'scan' == $_POST['action'] ) {
check_admin_referer( 'exploitscanner-scan_all' );
$fsl = ( ! isset($_POST['filesize_limit']) || ! is_numeric($_POST['filesize_limit']) ) ? 400 : (int) $_POST['filesize_limit'];
$dis = isset( $_POST['display_pattern'] );
$scanner = new File_Exploit_Scanner( ABSPATH, array( 'start' => 0, 'fsl' => $fsl, 'display_pattern' => $dis ) );
$scanner->run();
$scanner = new DB_Exploit_Scanner();
$scanner->run();
}
echo '<div class="wrap">';
echo '<h2>Exploit Scanner</h2>';
if ( isset($_GET['view']) && 'diff' == $_GET['view'] )
exploitscanner_diff_page();
elseif ( isset( $_GET['action'] ) && 'fix' == $_GET['action'] )
exploitscanner_fix_vulnerability_page();
else
exploitscanner_results_page();
echo '</div>';
}
/**
* Display scan initiation form and any stored results.
*/
function exploitscanner_results_page() {
global $wp_version;
delete_transient( 'exploitscanner_results_trans' );
delete_transient( 'exploitscanner_files' );
$results = get_option( 'exploitscanner_results' );
?>
<p>This script searches through your WordPress install for signs that may indicate that your website has been compromised by hackers. It does <strong>NOT</strong> remove anything, this is left for the user to do.</p>
<form action="<?php admin_url( 'tools.php?page=exploit-scanner' ); ?>" method="post">
<?php wp_nonce_field( 'exploitscanner-scan_all' ); ?>
<input type="hidden" name="action" value="scan" />
<table class="form-table">
<tr>
<th scope="row"><label for="display_pattern">Search for suspicious styles:</label></th>
<td><input type="checkbox" id="display_pattern" name="display_pattern" checked="checked" value="1" /> <span class="description">(<code>display:none</code> and <code>visibility:hidden</code> can be used to hide spam, but may cause many false positives)</span></td>
</tr>
<tr>
<th scope="row"><label for="filesize_limit">Upper file size limit:</label></th>
<td><input type="text" size="3" id="filesize_limit" name="filesize_limit" value="400" />KB <span class="description">(files larger than this are skipped and will be listed at the end of scan)</span></td>
</tr>
<tr class="hide-if-no-js">
<th scope="row"><label for="max_test_files">Number of files per batch:</label></th>
<td>
<select id="max_test_files" name="max_test_files">
<option value="100">100</option>
<option value="150">150</option>
<option value="250" selected="selected">250</option>
<option value="500">500</option>
<option value="1000">1000</option>
</select>
<span class="description">(to help reduce memory limit errors the scan processes a series of file batches)</span>
</td>
</tr>
</table>
<p class="submit"><input type="submit" id="run-scanner" class="button-primary" value="Run the Scan" /></p>
</form>
<div id="scan-loader" style="display:none;margin:10px;padding:10px;background:#f7f7f7;border:1px solid #c6c6c6;text-align:center">
<p><strong>Searching your filesystem and database for possible exploit code</strong></p>
<p><span style="margin-right:5px">Files scanned: 0...</span><img src="<?php echo plugins_url( 'loader.gif', __FILE__ ); ?>" height="16px" width="16px" alt="loading-icon" /></p>
</div>
<div id="scan-results">
<?php if ( ! $results ) : ?>
<h3>Results</h3><p>Nothing found.</p>
<?php else : exploitscanner_show_results( $results ); endif; ?>
</div>
<h3>General Information</h3>
<?php echo exploitscanner_list_admins(); ?>
<h4>DISCLAIMER</h4>
<p>Unfortunately it's impossible to catch every hack and it's all too easy to catch false positives (show a file as suspicious when in reality it is clean). If you have been hacked, this script may help you track down what files, comments or posts have been modified. On the other hand, if this script indicates your blog is clean, don't believe it. This is far from foolproof.</p>
<p><strong>For the paranoid...</strong><br />
To prevent someone hiding malicious code inside this plugin and to check that the signatures file hasn't been changed, here are the MD5 hashes of these files. Compare them with the references on the plugin homepage. You'll get extra points if you check this file has the actual md5_file() calls.</p>
<p style="text-align: center">MD5 of exploit-scanner.php: <code><?php echo md5_file( __FILE__ ); ?></code></p>
<?php if ( file_exists( dirname( __FILE__ ) . '/hashes/hashes-' . $wp_version . '.php' ) ) : ?>
<p style="text-align: center">MD5 of hashes-<?php echo $wp_version; ?>.php: <code><?php echo md5_file( dirname( __FILE__ ) . '/hashes/hashes-' . $wp_version . '.php' ); ?></code></p>
<?php endif;
}
/**
* Display table of results.
*/
function exploitscanner_show_results( $results ) {
if ( ! is_array($results) ) {
echo 'Unfortunately the results appear to be malformed/corrupted. Try scanning again.';
return;
}
$result = '<h3>Results</h3>';
foreach ( array('severe','warning','note') as $l ) {
if ( ! empty($results[$l]) ) {
if ( $l == 'note' ) $result .= '<div style="float:right;font-size:11px;margin-top:1.3em"><a href="#" id="hide-skipped" class="hide-if-no-js">Hide skipped files</a></div>';
$result .= '<h4>Level ' . ucwords($l) . ' (' . count($results[$l]) . ' matches)</h4>';
$result .= '<table class="widefat fixed">
<thead>
<tr>
<th scope="col" style="width:50%">Location / Description</th>
<th scope="col">What was matched</th>
</tr>
</thead>
<tbody>';
foreach ( $results[$l] as $r )
$result .= exploitscanner_draw_row( $r );
$result .= '</tbody></table>';
}
}
echo $result;
}
/**
* Draw a single result row.
*/
function exploitscanner_draw_row( $r ) {
$class = ( ! empty($r['class']) ) ? ' class="'.$r['class'].'"' : '';
$html = '<tr' . $class . '><td><strong>' . esc_html( $r['loc'] );
if ( ! empty($r['line_no']) )
$html .= ':' . $r['line_no'] . '</strong>';
elseif ( ! empty($r['post_id']) )
$html .= '</strong> <a href="' . get_edit_post_link($r['post_id']) . '" title="Edit this item">Edit</a>';
elseif ( ! empty($r['comment_id']) )
$html .= '</strong> <a href="' . admin_url( "comment.php?action=editcomment&c={$r['comment_id']}" ) . '" title="Edit this comment">Edit</a>';
else
$html .= '</strong>';
$html .= '<br />'.$r['desc'].'</td><td>';
if ( ! empty($r['line']) ) {
$html .= '<code>' . exploitscanner_hilight( esc_html($r['line']) ) . '</code>';
} else if ( 'Modified core file' == $r['desc'] ) {
$url = add_query_arg( array( 'view' => 'diff', 'file' => $r['loc'] ), menu_page_url( 'exploit-scanner', false ) );
$url = wp_nonce_url( $url, 'exploit-scanner_view_diff' );
$html .= '<a href="'.$url.'" id="'.esc_attr($r['loc']).'" class="view-diff">See what has been modified</a>';
} else if ( ! empty( $r['vuln'] ) ) {
$url = add_query_arg( array( 'action' => 'fix', 'vulnerability' => $r['vuln'], 'file' => $r['loc'] ), menu_page_url( 'exploit-scanner', false ) );
$url = wp_nonce_url( $url, 'exploit-scanner_fix_' . $r['vuln'] . '_' . $r['loc'] );
$html .= '<a href="'. esc_url( $url ) .'">Fix now</a>';
}
return $html . '</td></tr>';
}
/**
* Display the modifications made to a core file.
*/
function exploitscanner_diff_page() {
if ( ! current_user_can( 'manage_options' ) )
die('-1');
check_ajax_referer( 'exploit-scanner_view_diff' );
$file = $_GET['file'];
echo '<h3>Changes made to ' . esc_html($file) . '</h3>';
echo exploitscanner_display_file_diff( $file );
// exit if this was AJAX
if ( isset($_GET['_ajax_nonce']) )
exit;
// otherwise display return link
else
echo '<p><a href="' . menu_page_url('exploit-scanner',false) . '">Go back.</a></p>';
}
add_action( 'wp_ajax_exploit-scanner_view_diff', 'exploitscanner_diff_page' );
/**
* Generate the diff of a modified core file.
*/
function exploitscanner_display_file_diff( $file ) {
global $wp_version;
// core file names have a limited character set
$file = preg_replace( '#[^a-zA-Z0-9/_.-]#', '', $file );
if ( empty( $file ) || ! is_file( ABSPATH . $file ) )
return '<p>Sorry, an error occured. This file might not exist!</p>';
$key = $wp_version . '-' . $file;
$cache = get_option( 'exploitscanner_diff_cache' );
if ( ! $cache || ! is_array($cache) || ! isset($cache[$key]) ) {
$url = "http://core.svn.wordpress.org/tags/$wp_version/$file";
$response = wp_remote_get( $url );
if ( is_wp_error( $response ) || 200 != $response['response']['code'] )
return '<p>Sorry, an error occured. Please try again later.</p>';
$clean = $response['body'];
if ( is_array($cache) ) {
if ( count($cache) > 4 ) array_shift( $cache );
$cache[$key] = $clean;
} else {
$cache = array( $key => $clean );
}
update_option( 'exploitscanner_diff_cache', $cache );
} else {
$clean = $cache[$key];
}
$modified = file_get_contents( ABSPATH . $file );
$text_diff = new Text_Diff( explode( "\n", $clean ), explode( "\n", $modified ) );
$renderer = new ES_Text_Diff_Renderer();
$diff = $renderer->render( $text_diff );
$r = "<table class='diff'>\n<col style='width:5px' /><col />\n";
$r .= "<tbody>\n$diff\n</tbody>\n";
$r .= "</table>";
return $r;
}
function exploitscanner_fix_vulnerability_page() {
if ( ! current_user_can( 'edit_plugins' ) )
wp_die( 'You do not have sufficient permissions to perform this action.' );
if ( ! in_array( $_GET['vulnerability'], array( 'timthumb' ) ) )
wp_die( 'Unknown action.' );
if ( validate_file( $_GET['file'] ) || ! is_file( ABSPATH . $_GET['file'] ) )
wp_die( 'Invalid file.' );
if ( ! File_Exploit_Scanner::is_vulnerable_file( $_GET['file'], ABSPATH ) )
wp_die( 'Invalid file.' );
check_admin_referer( 'exploit-scanner_fix_' . $_GET['vulnerability'] . '_' . $_GET['file'] );
if ( $_GET['vulnerability'] == 'timthumb' ) {
echo '<h3>Fixing TimThumb vulnerability</h3>';
$contents = file_get_contents( ABSPATH . $_GET['file'] );
$fix = '
// Exploit Scanner security fix
if ( ! defined( "ALLOW_EXTERNAL" ) || ! ALLOW_EXTERNAL ) {
$isAllowedSite = false;
foreach ( $allowedSites as $site ) {
if ( preg_match (\'/(?:^|\.)\' . preg_quote( $site ) . \'$/i\', $url_info[\'host\'] ) )
$isAllowedSite = true;
}
}
// End fix
if ($isAllowedSite) {
';
$contents = str_replace( 'if ($isAllowedSite) {', $fix, $contents );
if ( file_put_contents( ABSPATH . $_GET['file'], $contents ) ) {
echo '<p>This instance of TimThumb has had a security fix applied. It is recommended that you download the latest version of TimThumb and completely replace this file.</p>';
} else {
echo '<p>An error occurred. It was not possible to apply a fix to this file. It is recommended that you download the latest version of TimThumb and completely replace this file.</p>';
}
}
echo '<p>The vulnerability will still show in your scan results until you run another scan.</p>';
echo '<p><a href="' . menu_page_url('exploit-scanner',false) . '">Go back.</a></p>';
}
/**
* AJAX callback to initiate a file scan.
*/
function exploitscanner_ajax_file_scan() {
ob_get_clean();
check_ajax_referer( 'exploit-scanner_scan' );
if ( ! isset($_POST['start']) )
die( json_encode( array( 'status' => 'error', 'data' => 'Error: start not set.' ) ) );
else
$start = (int) $_POST['start'];
$fsl = ( ! isset($_POST['filesize_limit']) || ! is_numeric($_POST['filesize_limit']) ) ? 400 : (int) $_POST['filesize_limit'];
$max = ( ! isset($_POST['max_batch_size']) || ! is_numeric($_POST['max_batch_size']) ) ? 100 : (int) $_POST['max_batch_size'];
$display_pattern = ( $_POST['display_pattern'] != 'false' ) ? true : false;
$args = compact( 'start', 'fsl', 'max', 'display_pattern' );
$scanner = new File_Exploit_Scanner( ABSPATH, $args );
$result = $scanner->run();
if ( is_wp_error($result) ) {
$message = $result->get_error_message();
$data = $result->get_error_data();
echo json_encode( array( 'status' => 'error', 'message' => $message, 'data' => $data ) );
} else if ( $result ) {
echo json_encode( array( 'status' => 'complete' ) );
} else {
echo json_encode( array( 'status' => 'running', 'data' => 'Files scanned: ' . ($start+$max) . '...' ) );
}
exit;
}
add_action( 'wp_ajax_exploit-scanner_file_scan', 'exploitscanner_ajax_file_scan' );
/**
* AJAX callback to initiate a database scan.
*/
function exploitscanner_ajax_db_scan() {
check_ajax_referer( 'exploit-scanner_scan' );
$scanner = new DB_Exploit_Scanner();
$scanner->run();
echo 'Done';
exit;
}
add_action( 'wp_ajax_exploit-scanner_db_scan', 'exploitscanner_ajax_db_scan' );
/**
* Display a list of users with administrator capabilities.
*/
function exploitscanner_list_admins() {
global $wpdb;
if ( method_exists( $wpdb, 'get_blog_prefix' ) )
$level_key = $wpdb->get_blog_prefix() . 'capabilities';
else
$level_key = $wpdb->prefix . 'capabilities';
$user_ids = $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value LIKE %s", $level_key, '%administrator%') );
ob_start();
?>
<h4>Users with admin privileges</h4>
<table class="widefat">
<thead>
<tr>
<th scope="col" style="width: 5%">ID</th>
<th scope="col">Username</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
</tr>
</thead>
<tbody>
<?php
foreach ( $user_ids as $id ) {
$user = get_userdata( $id );
echo '<tr><td>' . intval($user->ID) . '</td><td>' . esc_html($user->user_login) . '</td><td>';
if ( isset( $user->first_name ) ) echo esc_html($user->first_name) . ' ';
if ( isset( $user->last_name ) ) echo esc_html($user->last_name);
echo '</td><td>' . esc_html($user->user_email) . '</td></tr>';
} ?>
</tbody>
</table>
<?php
$admin_table = ob_get_clean();
return $admin_table;
}
/**
* Insert highlighted <span> tags around content matched by a scan.
*/
function exploitscanner_hilight( $text ) {
if ( strlen( $text ) > 200 ) {
$start = strpos( $text, '$#$#' ) - 50;
if ( $start < 0 )
$start = 0;
$end = strrpos( $text, '#$#$' ) + 50;
$text = substr( $text, $start, $end - $start + 1 );
}
return str_replace( array('$#$#','#$#$'), array('<span style="background:#ff0">','</span>'), $text );
}
/**
* Activation callback.
*
* Add database version info. Set up non-autoloaded options as there is no need
* to load results or clean core files on any page other than the exploit scanner page.
*/
function exploitscanner_activate() {
add_option( 'exploitscanner', 1 );
add_option( 'exploitscanner_results', 0, '', 'no' );
add_option( 'exploitscanner_diff_cache', 0, '', 'no' );
register_uninstall_hook( __FILE__, 'exploitscanner_uninstall' );
}
register_activation_hook( __FILE__, 'exploitscanner_activate' );
/**
* Deactivation callback. Remove transients.
*/
function exploitscanner_deactivate() {
delete_transient( 'exploitscanner_results_trans' );
delete_transient( 'exploitscanner_files' );
}
register_deactivation_hook( __FILE__, 'exploitscanner_deactivate' );
/**
* Uninstall callback. Remove all data stored by the plugin.
*/
function exploitscanner_uninstall() {
delete_option( 'exploitscanner' );
delete_option( 'exploitscanner_results' );
delete_option( 'exploitscanner_diff_cache' );
}
/**
* Update routine to perform database cleanup and to ensure that newly
* introduced settings and defaults are enforced.
*/
function exploitscanner_update() {
$db_version = 1;
$local_version = get_option( 'exploitscanner' );
if ( false === $local_version || $local_version < $db_version ) {
$count = get_option( 'exploit_scanner_result_count' );
if ( $count ) {
$opts = array('exploit_scanner_result_count','exploit_scanner_file_count','exploit_scanner_other','exploit_scanner_wp-admin','exploit_scanner_wp-content','exploit_scanner_wp-includes');
foreach ( $opts as $opt )
delete_option( $opt );
for( $i = 0; $i < $count; $i++ )
delete_option( 'exploit_scanner_results_' . $i );
}
delete_option( 'exploitscanner_results' );
exploitscanner_activate();
}
}
add_action( 'admin_init', 'exploitscanner_update' );
/**
* Exploit Scanner base class. Scanners should extend this.
*/
class Exploit_Scanner {
var $results;
function add_result( $level, $info ) {
$this->results[$level][] = $info;
}
function store_results( $done = false ) {
$stored = get_transient( 'exploitscanner_results_trans' );
if ( empty($this->results) ) {
if ( $done )
update_option( 'exploitscanner_results', $stored );
return;
}
if ( $stored && is_array($stored) )
$this->results = array_merge_recursive( $stored, $this->results );
if ( $done ) {
update_option( 'exploitscanner_results', $this->results );
delete_transient( 'exploitscanner_results_trans' );
} else {
set_transient( 'exploitscanner_results_trans', $this->results );
}
}
}
/**
* File Scanner. Scans all files in given path for suspicious text.
*/
class File_Exploit_Scanner extends Exploit_Scanner {
var $path;
var $start;
var $filesize_limit;
var $max_batch_size;
var $report_all_unknown_files = false;
var $paged = true;
var $files = array();
var $modified_files = array();
var $skip;
var $complete = false;
var $suspicious_patterns = array(
'/(\$wpdb->|mysql_).+DROP/siU' => array( 'level' => 'note', 'desc' => 'Possible database table deletion' ),
'/(echo|print|<\?=).+(\$GLOBALS|\$_SERVER|\$_GET|\$_REQUEST|\$_POST)/siU' => array( 'level' => 'note', 'desc' => 'Possible output of restricted variables' ),
'/ShellBOT/i' => array( 'level' => 'severe', 'desc' => 'This may be a script used by hackers to get control of your server' ),
'/uname -a/i' => array( 'level' => 'severe', 'desc' => 'Tells a hacker what operating system your server is running' ),
'/YW55cmVzdWx0cy5uZXQ=/i' => array( 'level' => 'severe', 'desc' => 'base64 encoded text found in Search Engine Redirect hack <a href="http://blogbuildingu.com/wordpress/wordpress-search-engine-redirect-hack">[1]</a>' ),
'/eval\s*\(/i' => array( 'level' => 'severe', 'desc' => 'Often used to execute malicious code' ),
'/\$_COOKIE\[\'yahg\'\]/i' => array( 'level' => 'severe', 'desc' => 'YAHG Googlerank.info exploit code <a href="http://creativebriefing.com/wordpress-hacked-googlerankinfo/">[1]</a>' ),
'/ekibastos/i' => array( 'level' => 'severe', 'desc' => 'Possible Ekibastos attack <a href="http://ocaoimh.ie/did-your-wordpress-site-get-hacked/">[1]</a>' ),
'/base64_decode\s*\(/i' => array( 'level' => 'severe', 'desc' => 'Used by malicious scripts to decode previously obscured data/programs' ),
'/<script>\/\*(GNU GPL|LGPL)\*\/ try\{window.onload.+catch\(e\) \{\}<\/script>/siU' => array( 'level' => 'severe', 'desc' => 'Possible "Gumblar" JavaScript attack <a href="http://threatinfo.trendmicro.com/vinfo/articles/securityarticles.asp?xmlfile=042710-GUMBLAR.xml">[1]</a> <a href="http://justcoded.com/article/gumblar-family-virus-removal-tool/">[2]</a>' ),
'/php \$[a-zA-Z]*=\'as\';/i' => array( 'level' => 'severe', 'desc' => 'Symptom of the "Pharma Hack" <a href="http://blog.sucuri.net/2010/07/understanding-and-cleaning-the-pharma-hack-on-wordpress.html">[1]</a>' ),
'/defined?\(\'wp_class_support/i' => array( 'level' => 'severe', 'desc' => 'Symptom of the "Pharma Hack" <a href="http://blog.sucuri.net/2010/07/understanding-and-cleaning-the-pharma-hack-on-wordpress.html">[1]</a>' ),
'/str_rot13/i' => array( 'level' => 'severe', 'desc' => 'Decodes/encodes text using ROT13. Could be used to hide malicious code.' ),
'/uudecode/i' => array( 'level' => 'severe', 'desc' => 'Decodes text using uuencoding. Could be used to hide malicious code.' ),
//'/[^_]unescape/i' => array( 'level' => 'severe', 'desc' => 'JavaScript function to decode encoded text. Could be used to hide malicious code.' ),
'/<!--[A-Za-z0-9]+--><\?php/i' => array( 'level' => 'warning', 'desc' => 'Symptom of a link injection attack <a href="http://www.kyle-brady.com/2009/11/07/wordpress-mediatemple-and-an-injection-attack/">[1]</a>' ),
'/<iframe/i' => array( 'level' => 'warning', 'desc' => 'iframes are sometimes used to load unwanted adverts and code on your site' ),
'/String\.fromCharCode/i' => array( 'level' => 'warning', 'desc' => 'JavaScript sometimes used to hide suspicious code' ),
'/preg_replace\s*\(\s*(["\'])(.).*(?<!\\\\)(?>\\\\\\\\)*\\2([a-z]|\\\x[0-9]{2})*(e|\\\x65)([a-z]|\\\x[0-9]{2})*\\1/si' => array( 'level' => 'warning', 'desc' => 'The e modifier in preg_replace can be used to execute malicious code' ),
);
function __construct( $path, $args ) {
$this->path = $path;
if ( ! empty($args['max']) )
$this->max_batch_size = $args['max'];
else
$this->paged = false;
if ( $args['display_pattern'] ) {
$this->suspicious_patterns['/visibility: ?hidden/i'] = array( 'level' => 'note', 'desc' => 'CSS style used to hide parts of a web page (often used legitimately)' );
$this->suspicious_patterns['/display: ?none/i'] = array( 'level' => 'note', 'desc' => 'CSS style used to hide parts of a web page (often used legitimately)' );
}
if ( $args['report_all_unknown_files'] ) {
$this->report_all_unknown_files = $args['report_all_unknown_files'];
}
$this->start = $args['start'];
$this->filesize_limit = $args['fsl'];
$this->skip = ltrim( str_replace( array( untrailingslashit( ABSPATH ), '\\' ), array( '', '/' ), __FILE__ ), '/' );
}
function run() {
$this->get_files( $this->start );
$this->file_pattern_scan();
$this->store_results();
return $this->complete;
}
function get_files( $s ) {
global $wp_version;
if ( 0 == $s ) {
unset( $filehashes );
$hashes = dirname(__FILE__) . '/hashes/hashes-'. $wp_version .'.php';
if ( file_exists( $hashes ) )
include( $hashes );
else
$this->add_result( 'severe', array(
'loc' => 'hashes-'. $wp_version .'.php missing',
'desc' => 'The file containing hashes of all WordPress core files appears to be missing; modified core files will no longer be detected and a lot more suspicious strings will be detected'
) );
$this->recurse_directory( $this->path );
foreach( $this->files as $k => $file ) {
// don't scan unmodified core files
if ( isset( $filehashes[$file] ) ) {
if ( $filehashes[$file] == md5_file( $this->path.'/'.$file ) ) {
unset( $this->files[$k] );
continue;
} else {
$this->add_result( 'warning', array(
'loc' => $file,
'desc' => 'Modified core file'
) );
}
} else {
list( $dir ) = explode( '/', $file );
if ( $dir == 'wp-includes' || $dir == 'wp-admin' || $dir == $file ) {
$severity = substr( $file, -4 ) == '.php' ? 'severe' : 'warning';
$this->add_result( $severity, array(
'loc' => $file,
'desc' => 'Unknown file found in wp-includes/ or wp-admin/ or wp root directory.'
) );
} else if ( true === $this->report_all_unknown_files ) {
$severity = substr( $file, -4 ) == '.php' ? 'warning' : 'note';
$this->add_result( $severity, array(
'loc' => $file,
'desc' => 'Unknown file found in ' . $dir
) );
}
}
// detect old export files
if ( substr( $file, -9 ) == '.xml_.txt' ) {
$this->add_result( 'warning', array(
'loc' => $file,
'desc' => 'It is likely that this is an old export file. If so it is recommended that you delete this file to stop it from exposing potentially private information.'
) );
}
$vulnerable_file = $this->is_vulnerable_file( $file, $this->path . '/' );
if ( $vulnerable_file ) {
$this->add_result( 'severe', array(
'loc' => $file,
'desc' => $vulnerable_file['desc'],
'vuln' => $vulnerable_file['vuln']
) );
}
// don't scan files larger than given limit
if ( filesize($this->path . $file) > ($this->filesize_limit * 1024) ) {
unset( $this->files[$k] );
$this->add_result( 'note', array(
'loc' => $file,
'desc' => 'File skipped due to size',
'class' => 'skipped-file'
) );
}
}
$this->files = array_values( $this->files );
$result = set_transient( 'exploitscanner_files', $this->files, 3600 );
if ( ! $result ) {
$this->paged = false;
$data = array( 'files' => esc_html( serialize( $this->files ) ) );
if ( ! empty($GLOBALS['EZSQL_ERROR']) )
$data['db_error'] = $GLOBALS['EZSQL_ERROR'];
$this->complete = new WP_Error( 'failed_transient', '$this->files was not properly saved as a transient', $data );
}
} else {
$this->files = get_transient( 'exploitscanner_files' );
}
if ( ! is_array( $this->files ) ) {
$data = array(
'start' => $s,
'files' => esc_html( serialize( $this->files ) ),
);
if ( ! empty( $GLOBALS['EZSQL_ERROR'] ) )
$data['db_error'] = $GLOBALS['EZSQL_ERROR'];
$this->complete = new WP_Error( 'no_files_array', '$this->files was not an array', $data );
$this->files = array();
return;
}
// use files list to get a batch if paged
if ( $this->paged && (count($this->files) - $s) > $this->max_batch_size ) {
$this->files = array_slice( $this->files, $s, $this->max_batch_size );
} else {
$this->files = array_slice( $this->files, $s );
if ( ! is_wp_error( $this->complete ) )
$this->complete = true;
}
}
function recurse_directory( $dir ) {
if ( $handle = @opendir( $dir ) ) {
while ( false !== ( $file = readdir( $handle ) ) ) {
if ( $file != '.' && $file != '..' ) {
$file = $dir . '/' . $file;
if ( is_dir( $file ) ) {
$this->recurse_directory( $file );
} elseif ( is_file( $file ) ) {
$this->files[] = str_replace( $this->path.'/', '', $file );
}
}
}
closedir( $handle );
}
}
function file_pattern_scan() {
foreach ( $this->files as $file ) {
if ( $file != $this->skip ) {
$contents = file( $this->path . $file );
foreach ( $contents as $n => $line ) {
foreach ( $this->suspicious_patterns as $pattern => $p ) {
$test = preg_replace_callback( $pattern, array( &$this, 'replace' ), $line );
if ( $line !== $test ) {
$test = trim( $test );
$start = strpos( $test, '$#$#' ) - 50;
if ( $start < 0 )
$start = 0;
$append = '';
$end = strrpos( $test, '#$#$' );
// if the text to display is longer than 150 characters truncate it
if ( ( $end - $start ) > 150 ) {
$end = $start + 150;
$append = '#$#$ [line truncated]';
} else {
$end += 50;
}
$test = substr( $test, $start, $end - $start + 1 ) . $append;
$this->add_result( $p['level'], array(
'loc' => $file,
'line' => esc_html( $test ),
'line_no' => $n+1,
'desc' => $p['desc']
) );
}
}
}
}
}
}
function replace( $matches ) {
return '$#$#' . $matches[0] . '#$#$';
}
function is_vulnerable_file( $file, $path ) {
$timthumb = array( 'timthumb.php', 'thumb.php', 'thumbs.php', 'thumbnail.php', 'thumbnails.php', 'thumnails.php', 'cropper.php', 'picsize.php', 'resizer.php' );
if ( in_array( strtolower( basename( $file ) ), $timthumb ) ) {
$contents = file_get_contents( $path . $file );
if (
false !== strpos( $contents, 'TimThumb' ) &&
false !== strpos( $contents, '$allowedSites' ) &&
false === strpos( $contents, 'Exploit Scanner security fix' ) &&
false === strpos( $contents, 'VaultPress HotFix' )
) {
$version = 'unknown';
if ( preg_match( "/define\s*\([\\'\"]VERSION[\\'\"]\s*,\s*[\\'\"](.*)[\\'\"]/", $contents, $matches ) )
$version = $matches[1];
if ( 'unknown' == $version || version_compare( $version, '1.34', '<' ) )
return array(
'desc' => sprintf( 'You are using an old version (%s) of TimThumb. This could allow attackers to take control of your site.', esc_html( $version ) ),
'vuln' => 'timthumb'
);
}
}
return false;
}
}
/**
* Database Scanner. Scans WordPress database for suspicious post/comment text and plugins.
*/
class DB_Exploit_Scanner extends Exploit_Scanner {
var $suspicious_text = array(
'eval(' => array( 'level' => 'severe', 'desc' => 'Often used by hackers to execute malicious code' ),
'<script' => array( 'level' => 'severe', 'desc' => 'JavaScript hidden in the database is normally a sign of a hack' ),
);
var $suspicious_post_text = array(
'<iframe' => array( 'level' => 'warning', 'desc' => 'iframes are sometimes used to load unwanted adverts and code on your site' ),
'<noscript' => array( 'level' => 'warning', 'desc' => 'Could be used to hide spam in posts/comments' ),
'display:' => array( 'level' => 'warning', 'desc' => 'Could be used to hide spam in posts/comments' ),
'visibility:' => array( 'level' => 'warning', 'desc' => 'Could be used to hide spam in posts/comments' ),
'<script' => array( 'level' => 'severe', 'desc' => 'Malicious scripts loaded in posts by hackers perform redirects, inject spam, etc.' ),
);
function __construct() {}
function run() {
$this->scan_posts();
$this->scan_plugins();
$this->store_results(true);
}
function replace( $content, $text ) {
$s = strpos( $content, $text ) - 25;
if ( $s < 0 ) $s = 0;
$content = preg_replace( '/('.$text.')/', '$#$#\1#$#$', $content );
$content = substr( $content, $s, 150 );
return $content;
}
function scan_posts() {
global $wpdb;
foreach ( $this->suspicious_post_text as $text => $info ) {
$posts = $wpdb->get_results( "SELECT ID, post_title, post_content FROM {$wpdb->posts} WHERE post_type<>'revision' AND post_content LIKE '%{$text}%'" );
if ( $posts )
foreach ( $posts as $post ) {
$content = $this->replace( $post->post_content, $text );
$this->add_result( $info['level'], array(
'loc' => 'Post: ' . esc_html($post->post_title),
'line' => esc_html($content),
'post_id' => $post->ID,
'desc' => $info['desc']
) );
}
$comments = $wpdb->get_results( "SELECT comment_ID, comment_author, comment_content FROM {$wpdb->comments} WHERE comment_content LIKE '%{$text}%'" );
if ( $comments )
foreach ( $comments as $comment ) {
$content = $this->replace( $comment->comment_content, $text );
$this->add_result( $info['level'], array(
'loc' => 'Comment by ' . esc_html($comment->comment_author),
'line' => esc_html($content),
'comment_id' => $comment->comment_ID,
'desc' => $info['desc']
) );
}
}
}
function scan_plugins() {
$active_plugins = get_option( 'active_plugins' );
if ( ! empty( $active_plugins ) && is_array( $active_plugins ) ) {
foreach ( $active_plugins as $plugin ) {
if ( strpos( $plugin, '..' ) !== false || substr( $plugin, -4 ) != '.php' ) {
if ( $plugin == '' )
$desc = 'Blank entry found. Should be removed. It will look like \'i:0;s:0:\"\";\' in the active_records field.';
else
$desc = 'Active plugin with a suspicious name.';
$this->add_result( 'severe', array(
'loc' => 'Plugin: ' . esc_html( $plugin ),
'desc' => $desc
) );
}
}
}
}
}
include_once( ABSPATH . WPINC . '/wp-diff.php' );
if ( class_exists( 'Text_Diff_Renderer' ) ) :
class ES_Text_Diff_Renderer extends Text_Diff_Renderer {
function ES_Text_Diff_Renderer() {
parent::Text_Diff_Renderer();
}
function _startBlock( $header ) {
return "<tr><td></td><td><code>$header</code></td></tr>\n";
}
function _lines( $lines, $prefix = ' ' ) {
$r = '';
foreach ( $lines as $line ) {
$line = esc_html( $line );
$r .= "<tr><td>{$prefix}</td><td>{$line}</td></tr>\n"; //class='{$class}'
}
return $r;
}
function _added( $lines ) {
return $this->_lines( $lines, '+', 'diff-addedline' );
}
function _deleted( $lines ) {
return $this->_lines( $lines, '-', 'diff-deletedline' );
}
function _context( $lines ) {
return $this->_lines( $lines, '', 'diff-context' );
}
function _changed( $orig, $final ) {
return $this->_deleted( $orig ) . $this->_added( $final );
}
}
endif;
function exploit_scanner_plugin_actions( $links, $file ) {
if( $file == 'exploit-scanner/exploit-scanner.php' && function_exists( "admin_url" ) ) {
$settings_link = '<a href="' . admin_url( 'tools.php?page=exploit-scanner' ) . '">' . __('Scanner Settings') . '</a>';
array_unshift( $links, $settings_link ); // before other links
}
return $links;