-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathcsi.pl
executable file
·4933 lines (4642 loc) · 195 KB
/
csi.pl
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
#!/usr/local/cpanel/3rdparty/bin/perl
# CSI - cPanel Security Investigator
# Current Maintainer: Peter Elsner
use strict;
my $version = "3.5.42";
use Cpanel::Config::LoadWwwAcctConf();
use Cpanel::Config::LoadCpConf();
use Cpanel::Config::LoadUserDomains();
use Text::Tabs;
$tabstop = 4;
use File::Basename;
use File::Path;
use File::Find;
use File::stat;
use File::Slurp;
use IO::Prompt;
use LWP::UserAgent;
use DateTime;
use HTTP::Tiny;
use Cpanel::Exception ();
use Cpanel::FindBin ();
use Cpanel::Version ();
use Cpanel::Kernel::Status ();
use Cpanel::IONice ();
use Cpanel::OSSys::Env; ();
use Cpanel::PwCache ();
use Cpanel::PwCache::Get ();
use Cpanel::SafeRun::Timed ();
use Cpanel::SafeRun::Errors();
use Cpanel::Validate::IP ();
use utf8;
use JSON::PP;
use List::MoreUtils qw(uniq);
use Math::Round;
use POSIX;
use Getopt::Long;
use Path::Iterator::Rule;
use IO::Socket::INET;
use IO::Prompt;
use Term::ANSIColor qw(:constants);
use Time::Piece;
use Time::Seconds;
$Term::ANSIColor::AUTORESET = 1;
our $RUN_STATE;
our $gl_is_kernel=0;
###################################################
# Check to see if the calling user is root or not #
###################################################
if ( $> != 0 ) {
print "This script must be run as root\n";
exit;
}
_init_run_state();
if ( exists $ENV{'PACHA_AUTOFIXER'} ) {
_set_run_type('cptech');
}
elsif ( defined $ENV{'HISTFILE'}
and index( $ENV{'HISTFILE'}, 'cpanel_ticket' ) != -1 )
{
_set_run_type('cptech');
}
else {
foreach ( @ENV{ 'SSH_CLIENT', 'SSH_CONNECTION' } ) {
next unless defined $_;
next unless m{\A (184\.94\.197\.[2-6]|208\.74\.123\.98)}xms;
_set_run_type('cptech');
last;
}
}
my $rootdir = "/root";
my $csidir = "$rootdir/CSI";
our @HISTORY;
our $spincounter;
our $CPANEL_CONFIG_FILE = q{/var/cpanel/cpanel.config};
my $conf = Cpanel::Config::LoadWwwAcctConf::loadwwwacctconf();
my $cpconf = Cpanel::Config::LoadCpConf::loadcpconf();
my $allow_accesshash = $cpconf->{'allow_deprecated_accesshash'};
my $sha256only;
our $HOMEDIR = $conf->{'HOMEDIR'};
our @FILESTOSCAN = undef;
our $rootkitsfound = 0;
our @process_list = get_process_list();
my $hostname = Cpanel::SafeRun::Timed::timedsaferun( 10, 'hostname', '-f' );
chomp $hostname if defined $hostname;
if ( not length($hostname) ) {
$hostname = hostname();
}
###########################################################
# Parse positional parameters for flags and set variables #
###########################################################
# Set defaults for positional parameters
my (
$full, $shadow, $symlink, $yarascan,
$secadv, $help, $debug, $userscan,
$customdir, $scan, $skipkernel, %process,
%ipcs, $distro, $distro_version, $distro_major,
$distro_minor, $ignoreload, $overwrite, $cron,
$skipauthchk
);
get_ipcs_hash( \%ipcs );
$distro = Cpanel::OS->_instance->distro;
$distro_major = Cpanel::OS->_instance->major;
$distro_minor = Cpanel::OS->_instance->minor;
$distro_version = $distro_major . "." . $distro_minor;
our $OS_RELEASE = ucfirst($distro) . " Linux release " . $distro_version;
our $HTTPD_PATH = get_httpd_path();
our $LIBKEYUTILS_FILES_REF = build_libkeyutils_file_list();
our $IPCS_REF;
our $PROCESS_REF;
our @RPM_LIST;
our $OPT_TIMEOUT;
GetOptions(
'userscan=s' => \$userscan,
'customdir=s' => \$customdir,
'full' => \$full,
'skipauthchk' => \$skipauthchk,
'shadow' => \$shadow,
'symlink' => \$symlink,
'yarascan' => \$yarascan,
'secadv' => \$secadv,
'ignoreload' => \$ignoreload,
'help' => \$help,
'debug' => \$debug,
'overwrite' => \$overwrite,
'cron' => \$cron,
'skipkernel' => \$skipkernel,
);
#######################################
# Set variables needed for later subs #
#######################################
our $CSISUMMARY;
our @SUMMARY;
our @RECOMMENDATIONS;
our @INFO;
my $content=get_hashes();
our @knownhashes = split /\n/, $content;
my $docdir = '/usr/share/doc';
check_for_touchfile();
my @logfiles = ( '/var/log/wtmp' );
if ( ! -e '/var/cpanel/dnsonly' ) {
push @logfiles, '/var/log/apache2/access_log';
push @logfiles, '/var/log/apache2/error_log';
}
if ( $distro eq "ubuntu" ) {
push @logfiles, '/var/log/syslog';
push @logfiles, '/var/log/auth.log';
push @logfiles, '/var/log/mail.log';
}
else {
push @logfiles, '/var/log/messages';
push @logfiles, '/var/log/maillog';
push @logfiles, '/var/log/secure';
push @logfiles, '/var/log/cron';
}
######################
# Run code main body #
######################
if ($help) {
show_help();
exit;
}
if ( $cron ) {
$overwrite=1;
$full=1;
$yarascan=1;
logit("Running with cron switch (full, yarascan and overwrite are automatically added)");
}
check_previous_scans();
logit("=== STARTING CSI on $hostname ===");
sub get_loadavg {
my ($load_avg) = (
split(
/\s+/,
Cpanel::SafeRun::Timed::timedsaferun( 0, 'cat', '/proc/loadavg' )
)
)[0];
chomp($load_avg);
return $load_avg;
}
my $corecnt = Cpanel::SafeRun::Timed::timedsaferun( 0, 'nproc' );
chomp($corecnt);
my $loadavg = get_loadavg();
if ( $loadavg > ( $corecnt * 3 ) && !$ignoreload ) {
print RED
"Load Average is too high ($loadavg) which is greater than 3 times the number of cores\n";
print WHITE "If you really want to continue, pass --ignoreload\n";
logit( 'Load average too high: ' . $loadavg );
exit;
}
my %cpconf = get_conf($CPANEL_CONFIG_FILE);
if (
Cpanel::IONice::ionice(
'best-effort',
exists $cpconf{'ionice_import_exim_data'}
? $cpconf{'ionice_import_exim_data'}
: 6
)
)
{
print_info( "Setting I/O priority to reduce system load: "
. Cpanel::IONice::get_ionice()
. "\n" );
setpriority( 0, 0, 19 );
}
my $scanstarttime = Time::Piece->new;
print_header( YELLOW "Scan started on $scanstarttime" );
logit("Scan started on $scanstarttime");
logit("Showing disclaimer");
print_info("Usage: /root/csi.pl [functions] [options]");
print_info("See --help for a full list of options");
print_normal('');
disclaimer();
print_header(
"Checking for RPM database corruption and repairing as necessary...")
unless ( $distro eq "ubuntu" );
my $findRPMissues =
Cpanel::SafeRun::Timed::timedsaferun( 0,
'/usr/local/cpanel/scripts/find_and_fix_rpm_issues' )
unless ( $distro eq "ubuntu" );
my $isRPMYUMrunning = rpm_yum_running_chk();
if ($userscan) {
my $usertoscan = $userscan;
chomp($usertoscan);
userscan($usertoscan);
exit;
}
logit("Running default scan");
scan();
my $scanendtime = Time::Piece->new;
print_header( YELLOW "\nScan completed on $scanendtime" );
logit("Scan completed on $scanendtime");
my $scantimediff = ( $scanendtime - $scanstarttime );
my $scanTotTime = $scantimediff->pretty;
$scanTotTime = $scanTotTime . "\n";
print_header("Elapsed Time: $scanTotTime");
logit("Elapsed Time: $scanTotTime");
logit("=== COMPLETED CSI ===");
if ( $cron ) {
send_email();
}
exit;
########
# Subs #
########
sub show_help {
print_header("\ncPanel Security Investigator Version $version");
print_header(
"Usage: /usr/local/cpanel/3rdparty/bin/perl csi.pl [options]\n"
);
print_header("Functions");
print_header("=================");
print_status("With no arguments [WHICH IS THE DEFAULT] a quick scan is performed.");
print_normal(" ");
print_status( "--userscan cPanelUser Installs Yara if not already installed & performs a Yara scan for a single cPanel User.");
print_normal(" ");
print_header("Additional scan options available");
print_header("=================");
print_header( "--shadow Performs a check on all email accounts looking for variants of shadow.roottn hack.");
print_header( "--symlink Performs a symlink hack check for all accounts.");
print_header( "--secadv Runs Security Advisor");
print_header( "--skipkernel Skip kernel update checks. Useful if a custom kernel is installed and kernel checking fails.");
print_header( "--yarascan Skips confirmation during --full scan. CAUTION - Can cause very high load and take a very long time!");
print_header( "--full Performs all of the above checks - very time consuming. Can cause HIGH LOAD DURING YARA SCANS!!!");
print_header( "--skipauthchk - Skip check for infected openssh backdoors");
print_header( "--overwrite Overwrite last summary and skip creation of new CSI directory under root.");
print_header( "--cron Run via cron. Note: --full, --overwrite and --yarascan options will also be passed.");
print_header( "--debug Shows additional extrenuous info including errors if any. Use only at direction of cPanel Support.");
print_normal(" ");
print_header("Examples");
print_header("=================");
print_status(" /root/csi.pl with no arguments does a quick scan [DEFAULT]");
print_status(" /root/csi.pl --symlink");
print_status(" /root/csi.pl --secadv");
print_status(" /root/csi.pl --skipkernel");
print_status(" /root/csi.pl --full [--yarascan] [--skipauthchk]");
print_status(" /root/csi.pl --overwrite");
print_status(" /root/csi.pl --cron [ add this to roots crontab or to a file in /etc/cron.d or /etc/cron.daily ]");
print_status("Userscan ");
print_status(" /root/csi.pl --userscan myuser");
print_status(
" /root/csi.pl --userscan myuser --customdir mycustomdir");
print_status(
" (must be relative to the myuser homedir and defaults to public_html if non-existent!"
);
print_normal(" ");
}
sub disclaimer {
print_normal('');
print_header(
'########################################################################'
);
print_header(
'### DISCLAIMER! cPanel\'s Technical Support does not provide #'
);
print_header(
'### security consultation services. The only support services we #'
);
print_header(
'### can provide at this time is to perform a minimal analysis of the #'
);
print_header(
'### possible security breach solely for the purpose of determining if #'
);
print_header(
'### cPanel\'s software was involved or used in the security breach. #'
);
print_header(
'########################################################################'
);
print_header(
'### As with any anti-malware scanning system false positives may occur #'
);
print_header(
'### If anything suspicious is found, it should be investigated by a #'
);
print_header(
'### professional security consultant. There are never any guarantees #'
);
print_header(
'########################################################################'
);
print_normal('');
}
# BEGIN DEFAULT SCAN HERE!
sub scan {
print_normal('');
print_header('[ Starting cPanel Security Investigator SCAN Mode ]');
print_header("[ System: $OS_RELEASE ]");
print_normal('');
print_header("[ Available flags when running csi.pl scan ]");
print_header(
MAGENTA '[ --full Performs a more compreshensive scan (includes the options below)]' );
print_header( MAGENTA
'[ --shadow Scans all accounts for variants of shadow.roottn email hack ]'
);
print_header(
MAGENTA '[ --symlink Scans for symlink hacks going back to / ]' );
print_header( MAGENTA '[ --secadv Performs a Security Advisor run ]' );
print_normal('');
print_header('[ Checking logfiles ]');
logit("Checking logfiles");
check_logfiles();
print_header('[ Checking for bad UIDs ]');
logit("Checking for bad UIDs");
check_uids();
print_header('[ Checking /etc/passwd file for suspicious users ]');
logit("Checking /etc/passwd for suspicious users");
check_for_suspicious_user();
print_header('[ Checking /etc/hosts file for suspicious entries ]');
logit("Checking /etc/hosts for suspicious entries");
check_hosts_file();
print_header('[ Checking for known Indicators of Compromise (IoC) ]');
logit("Checking for known IoC's");
all_malware_checks();
print_header('[ Checking installed packages for CVEs ]');
logit("Checking installed packages for CVEs");
check_for_cve_vulnerabilities();
print_header('[ Checking if polkit/policykit has been exploited by CVE-2021-4034 ]');
logit("Checking if polkit/policykit has been exploited by CVE-2021-4034");
check_for_cve_2021_4034();
print_header('[ Checking for BPFDoor ]');
logit("Checking for BPFDoor");
check_for_bpfdoor();
print_header('[ Checking for suspicious /etc/rc.modules file ]');
logit("Checking for suspicious /etc/rc.modules file");
check_for_susp_rc_modules();
print_header('[ Checking for Free Download Manager Malware ]');
logit("Checking for Free Download Manager Malware");
check_for_freedownloadmanager_malware();
print_header('[ Checking if Use MD5 passwords with Apache is disabled ]');
logit("Checking if Use MD5 passwords with Apache is disabled");
chk_md5_htaccess();
print_header('[ Checking for index.html in /tmp and /home ]');
logit("Checking for index file in /tmp and $HOMEDIR");
check_index();
print_header('[ Checking for suspicious files ]');
logit("Checking for suspicious files");
look_for_suspicious_files();
print_header('[ Checking if root bash history has been tampered with ]');
logit("Checking roots bash_history for tampering");
check_history();
print_header('[ Checking for open files that have been deleted ]');
logit("Checking for open files that have been deleted");
check_lsof_deleted();
print_header('[ Checking /etc/ld.so.preload for compromised library ]');
logit("Checking /etc/ld.so.preload for compromised library");
check_preload();
print_header('[ Checking for LKM rootkits ]');
logit("Checking for Loadable Kernel Module rootkits");
check_for_lkm_rootkits();
print_header('[ Checking /dev/shm for binaries that are scripts or ELF fileyptes ]');
logit("Checking /dev/shm for scripts and ELF file types");
check_dev_shm_for_elf();
print_header('[ Checking process list for suspicious processes ]');
logit("Checking process list for suspicious processes");
check_processes();
print_header('[ Checking for suspicious bitcoin miners ]');
logit("Checking for suspicious bitcoin miners");
bitcoin_chk();
print_header('[ Checking for suspicious mount points ]') if iam('cptech');
logit("Checking for suspicious mount points") if iam('cptech');;
check_mounts() if iam('cptech');
print_header('[ Checking reseller ACLs ]');
logit("Checking reseller ACLs");
check_resellers_for_all_ACL();
print_header( '[ Checking if /var/cpanel/authn/api_tokens_v2/whostmgr/root.json is IMMUTABLE ]');
logit( "Checking if /var/cpanel/authn/api_tokens_v2/whostmgr/root.json is IMMUTABLE");
check_apitokens_json();
print_header( '[ Checking /usr/local/cpanel/logs/api_tokens_log for passwd changes ]');
logit("Checking api_tokens_log for passwd changes");
check_api_tokens_log();
print_header( '[ Obtaining API Tokens ]');
logit("Obtaining api tokens");
get_api_tokens();
print_header('[ Checking for PHP backdoors in unprotected path ]');
logit("Checking /usr/local/cpanel/base/unprotected for PHP backdoors");
check_for_unprotected_backdoors();
print_header('[ Checking for miscellaneous compromises ]');
logit("Checking for miscellaneous compromises");
misc_checks();
check_changepasswd_modules();
print_header('[ Checking Binary Headers ]');
logit("Checking Binary Headers (using hexdump -C)");
check_binaries_for_shell();
print_header('[ Checking Apache Modules ]');
logit("Checking Apache Modules (owned by RPM)");
check_apache_modules();
print_header('[ Checking for sshd_config ]');
logit("Checking sshd_config");
check_sshd_config();
print_header('[ Checking vm.nr.hugepages in /proc/sys/vm ]');
logit("Checking vm.nr.hugepages value");
check_proc_sys_vm();
print_header('[ Checking for modified/hacked SSH ]');
logit("Checking for modified/hacked ssh");
check_ssh();
print_header('[ Checking /root/.bash_history for anomalies ]');
logit("Checking /root/.bash_history");
check_for_TTY_shell_spawns();
check_roots_history();
print_header( '[ Checking for non-root users with ALL privileges in /etc/sudoers file ]');
logit("Checking /etc/sudoers file");
check_sudoers_file();
print_header('[ Checking for spam sending script in /tmp ]');
logit("Checking for spam sending script in /tmp");
spamscriptchk();
print_header('[ Checking for root owned spam sending directory under /usr/local/share/. /ita/ ]');
logit("Checking for root owned spam sending directory under /usr/local/share/. /ita/");
check_for_ita_perl_hack();
print_header('[ Checking user level crons for suspicious entries ]');
logit("Checking user level crons");
user_crons();
print_header('[ Checking for ransomwareEXX ]');
logit("Checking for ransomwareEXX");
check_for_ransomwareEXX();
print_header('[ Checking kernel status ]') unless( $skipkernel );
logit("Checking kernel status") unless( $skipkernel );
check_kernel_updates() unless( $skipkernel );
print_header( '[ Checking for suspicious MySQL users (Including Super privileges) ]');
logit("Checking for suspicious MySQL users including Super privileges");
check_for_Super_privs();
check_for_mysqlbackups_user();
print_header('[ Checking for unowned files/libraries ]');
logit("Checking for non-owned files/libraries");
check_lib();
print_header('[ Checking for suspicious users under /etc ]');
logit("Checking for suspicious users under /etc");
check_etc_files();
print_header('[ Checking for suspicious Email Filters ]');
logit("Checking for suspicious Email Filters");
check_email_filters();
if ( $full or $symlink ) {
print_header( YELLOW '[ Additional check for symlink hacks ]' );
logit("Checking for symlink hacks");
check_for_symlinks();
}
if ( $full or $shadow ) {
print_header( YELLOW '[ Additional check for shadow.roottn.bak hacks ]' );
logit("Checking for shadow.roottn.bak hacks");
chk_shadow_hack();
}
if ( $full ) {
unless( $skipauthchk ) {
print_header( YELLOW '[ Additional check for infected openssh backdoors ]' );
logit("Checking for infected openssh config files");
check_auth_keys_for_commands();
}
}
if ( $full ) {
print_header( YELLOW '[ Additional check for infections using YARA rules ]' );
my $yara_available = check_for_yara();
if ($yara_available) {
my $abort_scan=0;
if ( ! $yarascan ) {
my $continue_yara_scan = "This process can cause very high loads and may take a long time!!!";
if ( !IO::Prompt::prompt( $continue_yara_scan . " [y/N]: ", -default => 'n', -yes_no)) {
print_status("User opted to NOT continue with Yara scan!");
logit("User aborted Yara scan");
$abort_scan=1;
}
}
if ( $abort_scan == 0 ) {
my $url = URI->new( 'https://raw.githubusercontent.com/CpanelInc/tech-CSI/master/csi_rules.yara');
my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0 } );
my $res = $ua->get($url);
my $yara_data = $res->decoded_content;
my @yara_data = split /\n/, $yara_data;
print_header("Downloading csi_rules.yara file to $csidir");
open( YARAFILE, ">$csidir/csi_rules.yara" );
foreach my $yara_line (@yara_data) {
chomp($yara_line);
print YARAFILE $yara_line . "\n";
}
close(YARAFILE);
my @dirs = qw( /bin /boot /etc /lib /lib64 /opt /root /sbin /tmp /usr );
for my $dir (@dirs) {
chomp($dir);
next unless -d $dir;
print_status("\tScanning $dir directory");
my $loadavg = get_loadavg();
print_status( expand( "\t\t\\_ Yara file: csi_rules.yara [ Load: $loadavg ]") );
my $results = Cpanel::SafeRun::Timed::timedsaferun( 0, 'yara', '-fwNr', "$csidir/csi_rules.yara", "$dir" );
my @results = split /\n/, $results;
my $resultcnt = @results;
if ( $resultcnt > 0 ) {
my $showHeader = 0;
foreach my $yara_result (@results) {
chomp($yara_result);
next if ( $yara_result =~ m{.yar|.yara|CSI|rfxn|.hdb|.ndb|csi.pl|modsec_vendor_configs|access_log|swpDSK} );
my ( $triggered_rule, $triggered_file ) = ( split( '\s+', $yara_result ) );
my $ignore = _ignore( $triggered_rule, $triggered_file );
next unless( $ignore );
push @SUMMARY, "> A Yara scan found some suspicious files..." unless ( $showHeader );
$showHeader = 1;
push @SUMMARY, expand( "\t\\_ Rule Triggered: " . CYAN $triggered_rule . YELLOW " in the file: " . MAGENTA $triggered_file ) unless ( $triggered_file =~ m/\.yar|\.yara|CSI|rfxn|\.hdb|\.ndb|\/usr\/swpDSK|csi.pl/ );
}
}
}
sub _ignore {
my $rule2ignore = shift;
my $file2ignore = shift;
if ( $rule2ignore =~ m{} ) {
return 0;
}
if ( $file2ignore =~ m{/usr/local/cpanel/logs/access_log|/root/.bash_history} ) {
return 0;
}
return 1;
}
}
}
}
print_normal(' ');
print_header( GREEN 'Looking for recommendations' );
print_normal(' ');
# Checking for recommendations
print_header('[ Checking for obsolete password hashes in /etc/shadow ]');
logit("Checking for obsolete password hashes");
check_for_obsolete_shadow_hashes();
print_header('[ Comparing hashes in /etc/shells to /sbin/nologin ]');
logit("Comparing hashes in /etc/shells to /sbin/nologin");
compare_hash_of_shells();
print_header('[ Checking if updates are enabled ]');
logit("Checking if updates are enabled");
check_cpupdate_conf();
print_header('[ Checking for mod_security ]');
logit("Checking if ModSecurity is enabled");
check_modsecurity();
print_header('[ Checking for Two-Factor Authentication ]');
logit("Checking if Two-Factor Authentication is enabled");
check_2FA_enabled();
print_header('[ Checking login_access Tweak Setting ]');
logit("Checking login_access Tweak Setting");
check_account_login_access();
print_header('[ Checking for accesshash ]');
logit("Checking for accesshash");
check_for_accesshash();
print_header('[ Checking if SymLinkProtection is enabled ]');
logit("Checking if SymLinkProtection is enabled");
check_if_symlink_protect_on();
print_header('[ Checking setting of Cookie IP Validation ]');
logit("Checking setting of Cookie IP Validation");
check_cookieipvalidation();
print_header( '[ Checking setting of X-Frame/X-Content Type headers with cpsrvd ]');
logit("Checking setting of X-Frame/X-Content Type headers with cpsrvd");
check_xframe_content_headers();
print_header('[ Checking for deprecated plugins/modules ]');
logit("Checking for deprecated plugins");
check_for_deprecated();
print_header( '[ Gathering the IP addresses that logged on successfully as root ]');
logit("Gathering IP address that logged on as root successfully");
get_last_logins_WHM("root");
get_session_logins("root:");
get_whm_terminal_logins("root");
get_last_logins_SSH("root");
check_secure_log("root");
get_root_pass_changes("root");
push( @INFO, CYAN "\nDo you recognize the above IP addresses? If not, then further investigation should be performed\nby a qualified security specialist.");
if ( $full or $secadv ) {
print_header( YELLOW '[ Additional check Security Advisor ]' );
logit("Running Security Advisor");
security_advisor();
}
print_header('[ cPanel Security Investigator Complete! ]');
logit( 'cPanel Security Investigator Complete!' );
print_header('[ CSI Summary ]');
print_normal('');
dump_summary();
}
sub check_previous_scans {
print_info("CSI version: $version");
print_status('Running in debug mode - Extrenuous output will be present') if ( $debug );
logit('Running in debug mode') if ( $debug );
if ( $overwrite ) {
unlink( "$csidir/csi.log" );
return;
}
print_status('Checking for a previous run of CSI');
if ( -d $csidir ) {
logit( 'Previous CSI directory found, backing up and creating a new one' );
chomp( my $date = Cpanel::SafeRun::Timed::timedsaferun( 0, 'date', "+%Y-%m-%d-%H:%M:%S" ) );
print_info("Existing $csidir is present, moving to $csidir-$date");
rename "$csidir", "$csidir-$date";
mkdir( "$csidir", 0755 );
}
return;
}
sub check_webtemplates_for_hack_page {
my $dir='/var/cpanel/webtemplates/root/english';
return unless( -d $dir );
opendir my $dh, $dir;
my @templatefiles = readdir($dh);
closedir $dh;
my $showHeader=0;
foreach my $file(@templatefiles) {
chomp($file);
next if $file eq "." or $file eq "..";
my $isHacked=Cpanel::SafeRun::Timed::timedsaferun( 0, 'grep', '-i', 'hack', "$dir/$file" );
if ( $isHacked ) {
push @SUMMARY, "> Web template file under: " . CYAN "$dir" . YELLOW " might contain a hack page." unless( $showHeader );
$showHeader=1;
push @SUMMARY, MAGENTA "\t\\_ $file";
}
}
}
sub check_kernel_updates {
my $envtype = Cpanel::OSSys::Env::get_envtype();
return if ( $envtype =~ m/lxc|viruozzo|vzcontainer/ );
if ( Cpanel::Version::compare( Cpanel::Version::getversionnumber(), '<', '11.102.0.0')) {
use Cpanel::Kernel::GetDefault;
my $boot_kernelversion = Cpanel::Kernel::GetDefault::get();
my $running_kernelversion = Cpanel::Kernel::get_running_version();
my $has_kernelcare=0;
my $reboot_required=0;
$has_kernelcare if ( Cpanel::KernelCare::kernelcare_responsible_for_running_kernel_updates() );
if ( $running_kernelversion ne $boot_kernelversion ) {
$reboot_required=1;
if ($has_kernelcare) {
if ($reboot_required) {
push @SUMMARY, "> KernelCare installed but running kernel version does not match boot version (contact provider):";
push @SUMMARY, expand( CYAN "\t \\_ Running Version: [ " . $running_kernelversion . " ]" );
push @SUMMARY, expand( CYAN "\t \\_ Boot Version: [ " . $boot_kernelversion . " ]" );
}
}
else {
push @RECOMMENDATIONS, "> Running kernel version does not match boot version (a reboot should be scheduled)";
push @RECOMMENDATIONS, expand( CYAN "\t \\_ Running Version: [ " . $running_kernelversion . " ]" );
push @RECOMMENDATIONS, expand( CYAN "\t \\_ Boot Version: [ " . $boot_kernelversion . " ]" );
}
}
}
else { ## 102+
my $KernelStatus = Cpanel::Kernel::Status::kernel_status();
if ( $KernelStatus->{has_kernelcare} ) {
if ( $KernelStatus->{running_version} ne $KernelStatus->{boot_version} ) {
push @SUMMARY, "> KernelCare installed but running kernel version does not match boot version (contact provider):";
push @SUMMARY, expand( CYAN "\t \\_ Running Version: [ " . $KernelStatus->{running_version} . " ]" );
push @SUMMARY, expand( CYAN "\t \\_ Boot Version: [ " . $KernelStatus->{boot_version} . " ]" );
}
}
else {
if ( $KernelStatus->{reboot_required} ) {
push @RECOMMENDATIONS, "> Running kernel version does not match boot version (a reboot is required)";
push @RECOMMENDATIONS, expand( CYAN "\t \\_ Running Version: [ " . $KernelStatus->{running_version} . " ]" );
push @RECOMMENDATIONS, expand( CYAN "\t \\_ Boot Version: [ " . $KernelStatus->{boot_version} . " ]" );
}
}
}
}
sub check_logfiles {
my $apachelogpath;
#$apachelogpath = "/etc/apache2/logs";
$apachelogpath = "/var/log/apache2";
chomp($apachelogpath);
if ( !-d $apachelogpath ) {
push @SUMMARY, "> $apachelogpath directory is not present";
}
foreach my $log (@logfiles) {
if ( !-f $log ) {
push @SUMMARY, "> Log file $log is missing or not a regular file";
}
elsif ( -z $log ) {
# Check if journal logging is enabled. If so, these may be empty on purpose.
my $HasJournalLogging = "";
if ( -e "/run/systemd/journal/syslog" ) {
$HasJournalLogging =
" [ Might be configured to use imJournal ]";
}
push @SUMMARY,
"> Log file $log exists, but is empty $HasJournalLogging";
}
}
}
sub check_index {
if ( -f '/tmp/index.htm' or -f '/tmp/index.html' ) {
push @SUMMARY, '> Index file found in /tmp';
}
}
sub check_history {
if ( -e '/root/.bash_history' ) {
if ( -l '/root/.bash_history' ) {
my $result = Cpanel::SafeRun::Timed::timedsaferun( 0, 'ls', '-la', '/root/.bash_history' );
push @SUMMARY, "> /root/.bash_history is a symlink, $result";
}
my $attr = isImmutable("/root/.bash_history");
my $lcisImmutable = "";
if ($attr) {
push @SUMMARY, "> /root/.bash_history is set to " . CYAN "[ IMMUTABLE ]";
}
if ( !-s '/root/.bash_history' and !-l '/root/.bash_history' ) {
push @SUMMARY, "> /root/.bash_history is a 0 byte file";
}
# Load /root/.bash_history into @HISTORY array
open( HISTORY, "/root/.bash_history" );
@HISTORY = <HISTORY>;
close(HISTORY);
}
else {
push @SUMMARY,
"> /root/.bash_history is not present, this indicates possible root-level compromise";
}
}
sub check_modsecurity {
my $resultJSON = get_whmapi1('modsec_is_installed');
if ( !$resultJSON->{data}->{data}->{installed} ) {
push @RECOMMENDATIONS, "> Mod Security is disabled";
return;
}
my $modsec_vendorsJSON = get_whmapi1('modsec_get_vendors');
my $rules_found = 0;
for my $modsec_vendor ( @{ $modsec_vendorsJSON->{data}->{vendors} } ) {
if ( $modsec_vendor->{cpanel_provided} ) {
if ( !defined( $modsec_vendor->{is_rpm} ) ) {
push @RECOMMENDATIONS,
"> Using $modsec_vendor->{description} YAML rules - Please consider using the RPM\n"
. CYAN expand( "\t\\_ yum install ea-modsec2-rules-owasp-crs" )
unless ( $distro eq "ubuntu" );
}
if ( !defined( $modsec_vendor->{is_pkg} ) ) {
push @RECOMMENDATIONS,
"> Using $modsec_vendor->{description} YAML rules - Please consider using the RPM\n"
. CYAN expand( "\t\\_ apt install ea-modsec2-rules-owasp-crs" )
unless ( $distro ne "ubuntu" );
}
if ( $modsec_vendor->{enabled} == 0 ) {
push @RECOMMENDATIONS,
"> The $modsec_vendor->{description} is installed but not enabled\n\t\\_ Please consider running "
. CYAN
"/usr/local/cpanel/scripts/modsec_vendor enable OWASP3";
}
}
$rules_found = 1;
}
if ( !$rules_found ) {
push @RECOMMENDATIONS,
"> Mod Security is installed but there were no active Mod Security vendor rules found.";
}
}
sub check_2FA_enabled {
my $resultJSON = get_whmapi1('twofactorauth_policy_status');
if ( !$resultJSON->{data}->{is_enabled} ) {
push @RECOMMENDATIONS,
"> Two-Factor Authentication Policy is disabled - Consider enabling this.";
return;
}
}
sub check_account_login_access {
my $resultJSON =
get_whmapi1( 'get_tweaksetting', 'key=account_login_access' );
if ( $resultJSON->{data}->{tweaksetting}->{value} =~ m/owner|owner_root/ ) {
push @RECOMMENDATIONS,
"> Consider changing Accounts that can access cPanel user account to "
. CYAN "cPanel User Only.";
}
}
sub check_uids {
my @baduids;
while ( my ( $user, $pass, $uid, $gid, $group, $home, $shell ) =
getpwent() )
{
if ( $uid == 0 && $user ne 'root' ) {
push( @baduids, $user );
}
if ( $user eq 'firefart' ) {
push @SUMMARY,
"> firefart user found [Possible DirtyCow root-level compromise].";
}
if ( $user eq 'sftp' ) {
push @SUMMARY,
"> sftp user found [Possible HiddenWasp root-level compromise].";
}
}
endpwent();
if (@baduids) {
push @SUMMARY, '> Users with UID of 0 detected:';
foreach (@baduids) {
push( @SUMMARY, expand( CYAN "\t \\_ " . $_ ) );
get_last_logins_WHM($_);
get_session_logins($_ . ':');
get_whm_terminal_logins($_);
get_last_logins_SSH($_);
check_secure_log($_);
get_root_pass_changes($_);
}
}
}
sub check_for_TTY_shell_spawns {
my $histline;
foreach $histline (@HISTORY) {
chomp($histline);
if ( $histline =~
m/pty.spawn("\/bin\/sh")|pty.spawn\("\/bin\/bash"\)|os.system\('\/bin\/bash'\)|os.system\('\/bin\/sh'\)|\/bin\/sh -i|\/bin\/bash -i|cpuminer-gr-avx2/
)
{
push( @SUMMARY,
"> Found evidence in /root/.bash_history of a possible TTY shell being spawned"
);
push( @SUMMARY, expand( "\t \\_ $histline\n" ) );
}
}
}
sub check_roots_history {
my $histline;
foreach $histline (@HISTORY) {
chomp($histline);
#if ( $histline =~ m/\/etc\/cxs\/uninstall.sh|rm -rf \/etc\/apache2\/conf.d\/modsec|bash \/etc\/csf\/uninstall.sh|yum remove -y cpanel-clamav|remove bcm-agent|mdkri|unaem 0a|cd \/ev\/network/) {
if ( $histline =~ m{/etc/cxs/uninstall.sh|rm -rf /etc/apache2/conf.d/modsec|bash /etc/csf/uninstall.sh|yum remove -y cpanel-clamav|remove bcm-agent|mdkri|unaem 0a|cd /ev/network/|unset HISTFILE|grep -c ^processor /proc/cpuinfo|/usr/bin/tactu_cpanel}) {
push( @SUMMARY,
"> Suspicious entries found in /root/.bash_history" );
push( @SUMMARY, expand( "\t\\_ $histline" ) );
}
}
}
sub check_processes {
my $url = URI->new( 'https://raw.githubusercontent.com/CpanelInc/tech-CSI/master/suspicious_procs.txt');
my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0 } );
my $res = $ua->get($url);
my $susp_procs = $res->decoded_content;
my @susp_procs = split /\n/, $susp_procs;
my $headerPrint = 0;
foreach my $suspicious_process (@susp_procs) {
chomp($suspicious_process);
next if ( _ignore_susp_proc( $suspicious_process ) );
foreach my $line(@process_list) {
chomp($line);
if ( $line =~ m/\b$suspicious_process\b/ ) {
my ( $u, $p, $c ) = (split /\s+/, $line );
my ( $a1,$a2,$a3,$a4,$a5,$a6,$a7 ) = (split( /\s+/, $line ))[3,4,5,6,7,8,9];
my $a = $a1 . " " . $a2 . " " . $a3 . " " . $a4 . " " . $a5 . " " . $a6 . " " . $a7;
push @SUMMARY, "> The following suspicious process was found (please verify)" unless ( $headerPrint == 1 );
$headerPrint = 1;
push @SUMMARY, CYAN expand( "\t\\_ Found suspicious process " . YELLOW $suspicious_process . CYAN " running" );
push @SUMMARY, "\t\\_ " . MAGENTA "User: " . YELLOW $u . MAGENTA " / Pid: " . YELLOW $p . MAGENTA " / Command: " . YELLOW $c . MAGENTA " / Arguments: " . YELLOW $a;
my $proclink = '/proc/' . $p . '/exe';
if ( -l $proclink && readlink( $proclink ) ) {
push @SUMMARY, "\t\\_ " . YELLOW $proclink . " -> " . RED readlink($proclink) . CYAN " - Checking this binary at VirusTotal.com";
vtlink(readlink( $proclink ));
}
}
}
}
return;
}
sub _ignore_susp_proc {
my $tcProc = shift;
return 1 if ( $tcProc =~ m{log4j} && -e '/usr/bin/log4j-cve-2021-44228-hotpatch' );
return 1 if ( $tcProc =~ m{log4j} && -d '/home/cpanelsolr/server/lib/ext/' );
return 0;
}
sub bitcoin_chk {
my @cronlist = glob(q{ /var/spool/cron/* /var/spool/cron/crontabs/* });
my $xmrig_cron;
foreach my $cronfile (@cronlist) {
chomp($cronfile);
$xmrig_cron =
Cpanel::SafeRun::Timed::timedsaferun( 0, 'grep', '-srl', '.xmr',
$cronfile );
chomp($xmrig_cron);
if ($xmrig_cron) {
push @SUMMARY, "> Found suspicious data in: "
. CYAN $xmrig_cron;
}
}
my $xm2sg_socket = Cpanel::SafeRun::Timed::timedsaferun( 0, 'netstat', '-plant' );
my @xm2sg_socket = split /\n/, $xm2sg_socket;
if ( grep { /xm2sg/ } @xm2sg_socket ) {
push @SUMMARY,
"> Found evidence of possible bitcoin miner via "
. CYAN "netstat -plant | grep 'xm2sg'";
}
}
sub get_process_list {
my $continue = has_ps_command();
return unless ($continue);
return split /\n/,
Cpanel::SafeRun::Timed::timedsaferun( 0, 'ps', '--no-header', '--width=1000', 'axwwwf', '-o', 'user,pid,args' );
}
sub check_ssh {
my @ssh_errors;
my $ssh_verify;
my $keyutils_verify;
my $name;
return unless my $rpms = get_rpm_href();
my @openssh_pkgs = grep { /^openssh*/ } keys(%{$rpms} );
my @keyutillibs_pkgs = grep { /^(libkeyutils1|keyutils-libs)/ } keys(%{$rpms} );
foreach my $rpm (@openssh_pkgs) {
chomp($rpm);
$ssh_verify = Cpanel::SafeRun::Timed::timedsaferun( 0, 'dpkg', '--verify', $rpm ) unless( $distro ne 'ubuntu' );
$ssh_verify = Cpanel::SafeRun::Timed::timedsaferun( 0, 'rpm', '--verify', $rpm ) unless( $distro eq 'ubuntu' );
my @ssh_verify = split /\n/, $ssh_verify;
my $showHeader = 0;
foreach my $ssh_verify( @ssh_verify ) {
next if( grep { m{ssh_config|sshd_config|pam.d|/usr/libexec/openssh/ssh-keysign|/usr/bin/ssh-agent|.build-id} } $ssh_verify );
push( @ssh_errors, MAGENTA "RPM verification on $rpm failed for the following:" ) unless( $showHeader );;
$showHeader = 1;
push( @ssh_errors, expand( $ssh_verify ) ) unless( $distro eq 'ubuntu');
}
}
foreach my $rpm (@keyutillibs_pkgs) {
chomp($rpm);
$keyutils_verify = Cpanel::SafeRun::Timed::timedsaferun( 0, 'dpkg', '--verify', $rpm ) unless( $distro ne 'ubuntu' );
$keyutils_verify = Cpanel::SafeRun::Timed::timedsaferun( 0, 'rpm', '--verify', $rpm ) unless( $distro eq 'ubuntu' );
my @keyutils_verify = split /\n/, $keyutils_verify;
my $showHeader = 0;
foreach my $keyutils_verify( @keyutils_verify ) {
next if( grep { m{.build-id} } $keyutils_verify );