Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Installing Maldet to Automate Malware Detection on CentOS

Linux Malware Detect (LMD), or maldet for short, is an incredibly useful tool for detecting malware in a Linux environment. There are several different antivirus/malware detection suites available, but most primarily focus on traditional OS level threats. Maldet instead focuses its efforts on user account level threats allowing it to be a good fit for webmasters/systems administrators. Those of you that are running multiple websites should consider taking advantage of this software as the risk of infection increases with each website.
Maldet works by implementing threat data gathered from network edge detection systems, malware registries, and user submissions in the form of “signatures”. Signatures being md5 hashes and hex pattern matches of commonly found malware. The software then compares the files being scanned against these signatures and returns a “hit” if it believes that it has found a match for known malware.
Provided below are the installation and configuration steps necessary to automate malware detection on your own web hosting environment with LMD.
CentOS 6.x
Step One: Installing Maldet
First, let’s download LMD using our terminal:
[root@localhost ~] wget http://www.rfxn.com/downloads/maldetect-current.tar.gz
Extract the compressed file we just downloaded:
[root@localhost ~] tar -xzvf maldetect-current.tar.gz 
Once it has finished extracting all the files, you can run the installer script:
[root@localhost ~] cd maldetect-1.6.1/ && ./install.sh 
The version you download may be different than the one referenced in this tutorial, so be sure to update your installation directory accordingly in the command above. As of the writing of this article, the latest stable version is 1.4.2.
The install should finish shortly thereafter and inform you as such:
[root@localhost ~] 
Linux Malware Detect v1.4.2
            (C) 2002-2013, R-fx Networks 
            (C) 2013, Ryan MacDonald 
inotifywait (C) 2007, Rohan McGovern 
This program may be freely redistributed under the terms of the GNU GPL

installation completed to /usr/local/maldetect
config file: /usr/local/maldetect/conf.maldet
exec file: /usr/local/maldetect/maldet
exec link: /usr/local/sbin/maldet
exec link: /usr/local/sbin/lmd
cron.daily: /etc/cron.daily/maldet

imported config options from /usr/local/maldetect.last/conf.maldet
maldet(26481): {sigup} performing signature update check...
maldet(26481): {sigup} local signature set is version 201205035915
maldet(26481): {sigup} new signature set (2015051822776) available
maldet(26481): {sigup} downloaded http://cdn.rfxn.com/downloads/md5.dat
maldet(26481): {sigup} downloaded http://cdn.rfxn.com/downloads/hex.dat
maldet(26481): {sigup} downloaded http://cdn.rfxn.com/downloads/rfxn.ndb
maldet(26481): {sigup} downloaded http://cdn.rfxn.com/downloads/rfxn.hdb
maldet(26481): {sigup} downloaded http://cdn.rfxn.com/downloads/maldet-clean.tgz
maldet(26481): {sigup} signature set update completed
maldet(26481): {sigup} 10775 signatures (8863 MD5 / 1912 HEX) 
Basic Usage:
Use the scanning tool by passing the maldet command any of the arguments described below:
 -b, --background
      Execute operations in the background, ideal for large scans
      e.g: maldet -b -r /home/?/public_html 7

    -u, --update
       Update malware detection signatures from rfxn.com

    -d, --update-ver
       Update the installed version from rfxn.com

    -m, --monitor USERS|PATHS|FILE
       Run maldet with inotify kernel level file create/modify monitoring
       If USERS is specified, monitor user homedirs for UID's > 500
       If FILE is specified, paths will be extracted from file, line spaced
       If PATHS are specified, must be comma spaced list, NO WILDCARDS!
       e.g: maldet --monitor users
       e.g: maldet --monitor /root/monitor_paths
       e.g: maldet --monitor /home/mike,/home/ashton

    -k, --kill
       Terminate inotify monitoring service

    -r, --scan-recent PATH DAYS
       Scan files created/modified in the last X days (default: 7d, wildcard: ?)
       e.g: maldet -r /home/?/public_html 2

    -a, --scan-all PATH
       Scan all files in path (default: /home, wildcard: ?)
       e.g: maldet -a /home/?/public_html

    -c, --checkout FILE
       Upload suspected malware to rfxn.com for review & hashing into signatures

    -l, --log
       View maldet log file events

    -e, --report SCANID email
       View scan report of most recent scan or of a specific SCANID and optionally
       e-mail the report to a supplied e-mail address
       e.g: maldet --report
       e.g: maldet --report list
       e.g: maldet --report 050910-1534.21135
       e.g: maldet --report SCANID user@domain.com

    -s, --restore FILE|SCANID
       Restore file from quarantine queue to orginal path or restore all items from
       a specific SCANID
       e.g: maldet --restore /usr/local/maldetect/quarantine/config.php.23754
       e.g: maldet --restore 050910-1534.21135

    -q, --quarantine SCANID
       Quarantine all malware from report SCANID
       e.g: maldet --quarantine 050910-1534.21135

    -n, --clean SCANID
       Try to clean & restore malware hits from report SCANID
       e.g: maldet --clean 050910-1534.21135

    -U, --user USER
       Set execution under specified user, ideal for restoring from user quarantine or
       to view user reports.
       e.g: maldet --user nobody --report
       e.g: maldet --user nobody --restore 050910-1534.21135

    -co, --config-option VAR1=VALUE,VAR2=VALUE,VAR3=VALUE
       Set or redefine the value of conf.maldet config options
       e.g: maldet --config-option email_addr=you@domain.com,quar_hits=1

    -p, --purge
       Clear logs, quarantine queue, session and temporary data.
Scan single files or entire directories if you wish. For example, we can run a scan on the home directory:
[root@localhost ~] maldet -a /home
Linux Malware Detect v1.4.2
            (C) 2002-2013, R-fx Networks 
            (C) 2013, Ryan MacDonald 
inotifywait (C) 2007, Rohan McGovern 
This program may be freely redistributed under the terms of the GNU GPL v2

maldet(17439): {scan} signatures loaded: 10775 (8863 MD5 / 1912 HEX)
maldet(17439): {scan} building file list for /home, this might take awhile...
maldet(17439): {scan} file list completed, found 35640 files... 
Run commands in a screen or tmux session if it’s likely to take severals hours so that you can check its status at a later time.
Step Two: Updating conf.maldet for Automation
The following configuration changes are optional and only necessary if you wish automate the detection of malware on your system.
Now that the installation has finished let’s open up its configuration file with a text editor to make some changes:
[root@localhost ~] vi /usr/local/maldetect/conf.maldet 
The first setting we’ll want to update is email_alert. Set this to ‘1’ so that it’s enabled and will email reports to the email address you configure next. Now, let’s find the email_addr setting. Insert your email address inside the quotes to replace the default setting of ‘you@domain.com’.
At this point, we have configured maldet to notify us via email whenever any hit is detected upon completion of a scan. However, we’re not finished so let’s enable some additional parameters so that we can further automate the detection process for maldet’s monitor mode. Locate the quar_hits parameter and set this to ‘1’. This setting quarantines any malware found to the /usr/local/maldetect/quarantine/ directory and emails the address configured. Additionally, it creates a corresponding .info file containing the original file ownership and permissions for use with the restore command (should you decide that you want to restore it at a later time).
Moving along, let’s update our last two parameters in our configuration file: quar_susp and public_scan. Set them both to ‘1’ and save the file. The first parameter (quar_susp) enables account suspension for cPanel or sets the shell to /bin/false for non-cPanel servers. The second parameter allows non-root users to perform malware scans and is necessary for the mod_security script we’ll be enabling later in this tutorial.
Step Three: Ensure Glibc and Mail Are Installed
To automate the detection of malware, we will need to install the Glibc library so we can use the kernel’s inotify feature with maldet. Without this library, maldet’s monitor mode will return an error. This can be completed by running the following command:
[root@localhost ~] yum install glibc.i686 -y 
Additionally, we want to confirm that the mail command is available for use by running the following command:
[root@localhost ~] whereis mail
mail: /bin/mail /etc/mail /etc/mail.rc /usr/share/man/man1/mail.1.gz 
If it does not return any directories, then you will want to install it using the following command:
[root@localhost ~] yum install mailx -y 
This ensures that maldet will be able to send its scanning reports to the email we specified in the configuration file earlier.
Step Four: Configuring mod_security (Optional)
First, we’ll need to ensure that the Apache module mod_security is enabled, which can be confirmed by running the following command:
root@localhost [~] httpd -M | grep sec
 security2_module (shared)
If it does not return the above result, then you’ll need to install it via cPanel’s EasyApache tool or the EPEL repository for non-cPanel servers:
root@localhost [~] yum install epel-release -y
root@localhost [~] yum --enablerepo=epel install mod_security -y 
Alternatively, you can use the following commands if the above doesn’t work:
root@localhost [~] wget http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm rpm -Uvh epel-release-6*.rpm
root@localhost [~] yum --enablerepo=epel install mod_security -y 
Once you’ve confirmed that mod_security is enabled, we will want to add a custom modsecurity rule:
root@localhost [~] vi /etc/httpd/modsecurity.d/activated_rules/my_custom_rule 
If you’re on a cPanel server with mod_security installed via EasyApache, then use the following configuration file:
root@localhost [~] vi /usr/local/apache/conf/modsec2.user.conf 
Then paste in the following text and save the file:
SecRequestBodyAccess On
SecTmpSaveUploadedFiles On
SecRule FILES_TMPNAMES "@inspectFile /usr/local/maldetect/modsec.sh" "log,auditlog,deny,severity:2,phase:2,t:none,id:99,msg:'Malware found'" 
The id and msg parameters can be updated to your choosing, but just be sure that you follow the guidelines in mod_security’s documentation for ids.
Lastly, restart Apache so that the changes take effect:
root@localhost [~] service httpd restart 
We have now completed the mod_security configuration for malware scanning of file uploads via HTTP. Any files prevented from being uploaded will now be logged to /var/log/httpd/modsec_audit.log or /usr/local/apache/logs/modsec_audit.log if you’re using cPanel’s EasyApache installation of mod_security.
Step Five: Adding a More Frequent Cronjob
The default cronjob that maldet configures is set to generate one malware report daily and can be found in /etc/cron.daily/maldet. Should you want reports and account suspensions to occur more frequently — e.g. an hour, then you’ll want to create a cronjob in the /etc/cron.hourly directory. If you do intend on proceeding with a more frequent cron job, then you’ll want to remove the relevant --alert-daily if statement in /etc/cron.daily/maldet and add it to your own instead. Creating an hourly cron job with this if statement can be completed by creating a text file for your new cron job:
root@localhost [~] vi /etc/cron.hourly/hourly_maldet_report 
Then paste in the following and save the file:
if [ "$(ps -A --user root -o "comm" | grep inotifywait)" ]; then /usr/local/maldetect/maldet --alert-daily >> /dev/null 2>&1
Lastly, update its permissions so that it’s executable:
root@localhost [~] chmod 755 /etc/cron.hourly/hourly_maldet_report 
Step Six: Running Maldet in Monitor Mode
All we need to do now to is have maldet run in your preferred monitoring mode:
root@localhost [~] maldet -m users 
Monitoring users will only scan your users’ public_html directory that have a UID greater than 500. To change the user directory that it scans, you can update conf.maldet’s inotify_webdir parameter.
If you want to monitor a specific directory, specifiy it after the -m argument:
root@localhost [~] maldet -m /root/some_specific_directory
If you want to monitor multiple directories, then separate each directory with a comma like so:
[root@localhost [~] maldet -m /root/this_directory,/root/that_directory,/root/another_directory 

The cleaner function looks for signature-named rules under the clean/ path,
these rules can consist of any command that is designed to clean a file of
malware. A cleaner rule must result in a file being able to pass a scan
without tripping a HIT otherwise it will classify the clean action as FAILED.

Let us assume for a moment we have malware that we want to clean and it trips
with the signature "{HEX}php.cmdshell.r57.89". The actual signature string in
this is "php.cmdshell.r57", the "{HEX}" just defines the format and ".89" is
the variant number. So, to create a clean rule for php.cmdshell.r57 we would
add a file 'clean/php.cmdshell.r57' and this would be executed against any
file that hits on the signature of the same name.

The actual contents of the rule should be a single line command that will be
executed against the hit file, for example the execution looks something like:


So, for a string based malware injection you could easily throw in a 'sed -i'
into the rule file with the appropriate pattern to strip the string(s) from
the file. Once the clean command has run, a rescan will be performed on the
file and if it causes causes a hit, the clean will be marked as FAILED. A
successful clean ALWAYS results in the file being restored if possible to
its original path, owner and mode.

An important note is that the cleaner function is a subfunction of the
quarantine, so if the quarantine is disabled then by default, malware hits
will not have clean attempts made. There are two ways around this, apart from
the obvious of turning on quarantine and rescanning (which is a waste of time).
The best way is to enable the quarantine and then use the -q|--quarantine flag
to batch through the scan results, which will quarantine and clean files. The
second is to use the -n|--clean flag which will try to clean files in place,
be that in the quarantine or the files original path, wherever it can be found.

e.g: maldet -q SCANID

e.g: maldet --clean SCANID
Manually fending off malware can become quite the time-consuming task. Automating this task will be beneficial to anyone running a server with multiple websites. Especially for those that are running multiple WordPress, Joomla, etc. installations as these seem to be frequent targets of user account level malware due to their widespread use and plugin vulnerabilities.
Sample Scan:
After configuring, you can scan the system manually using the following command:
# maldet --scan-all /
Linux Malware Detect v1.5
            (C) 2002-2016, R-fx Networks 
            (C) 2016, Ryan MacDonald 
This program may be freely redistributed under the terms of the GNU GPL v2

maldet(8097): {scan} signatures loaded: 11294 (9343 MD5 / 1951 HEX / 0 USER)
maldet(8097): {scan} building file list for "/", this might take awhile...
maldet(8097): {scan} setting nice scheduler priorities for all operations: cpunice 19 , ionice 6
maldet(8097): {scan} file list completed in 0s, found 20620 files...
maldet(8097): {scan} scan of "/" (20620 files) in progress...
maldet(8097): {scan} scan completed on "/": files 20620, malware hits 0, cleaned hits 0, time 117s
maldet(8097): {scan} scan report saved, to view run: maldet --report 170210-0351.8097
After scanning, you can examine malware scan report by running the following command:
# maldet --report 170210-0351.8097
HOST:      techoism.com
SCAN ID:   170210-0351.8097
STARTED:   Feb 10 2017 03:51:48 -0600
COMPLETED: Feb 10 2017 03:53:45 -0600
ELAPSED:   117s [find: 0s]

PATH:          "/"
TOTAL FILES:   20620

Linux Malware Detect v1.5 < proj@rfxn.com >
You can also scan the specific filesystem on server.
# maldet -m /var,/home,/opt
Quarantine the Infected Files
Quarantine the Infected Files
Run the following command with the scan report ID to clean the effected files.
# maldet -q 170210-0351.8097
Update LMD & Signatures to Latest:
Use below both command to update your LMD version & virus signatures to latest.
# Update the installed version #
# maldet -d
# Update malware detection signatures #
# maldet -u


Popular posts from this blog

How to Get Table Size, Database Size, Indexes Size, schema Size, Tablespace Size, column Size in PostgreSQL Database

PostgreSQL Pgbadger Installation On Linux

PostgreSQL pgBadger

How to configure Replication Manager (repmgr) ?

Migrating From Oracle to PostgreSQL using ora2pg open source tools