Linux Malware Detection: Security Guide for System Administrators
Knowledge Overview
Prerequisites
- Basic Linux command line proficiency and terminal navigation
- System administration fundamentals including user/process management
- File permissions and ownership concepts for security configuration
- Network protocols understanding (TCP/IP, DNS, HTTP/HTTPS basics)
- Log file analysis skills for security event interpretation
- Package management experience (apt/yum/dnf for tool installation)
What You'll Learn
- Multi-layered malware detection strategies using ClamAV, rkhunter, and chkrootkit
- Real-time monitoring implementation with inotify and process tracking
- Automated incident response procedures for immediate threat containment
- False positive investigation techniques to optimize detection accuracy
- Performance tuning methods for enterprise-grade security systems
- Network-based threat detection and traffic analysis methodologies
Tools Required
- Linux system (Ubuntu 20.04+, CentOS 8+, or equivalent distribution)
- Root/sudo privileges for security tool installation and configuration
- Internet connectivity for signature updates and tool downloads
- Minimum 2GB RAM for effective scanning performance
- Email server access for automated alert notifications (optional)
- Terminal access via SSH or direct console for remote management
Time Investment
36 minutes reading time
72-108 minutes hands-on practice
Guide Content
What are the essential components of a comprehensive Linux malware detection strategy?
Linux malware detection requires a multi-layered approach combining signature-based scanners (ClamAV), rootkit hunters (rkhunter, chkrootkit), behavioral analysis tools, and real-time monitoring. Furthermore, effective detection involves regular system scans, file integrity monitoring, and network traffic analysis to identify suspicious activities before they compromise system security.
# Quick malware scan commands
sudo rkhunter --check --report-warnings-only
sudo chkrootkit
sudo clamscan -r --infected /
Table of Contents
- How to Detect Malware on Linux Systems?
- What are the Best Linux Malware Detection Tools?
- How to Configure Rootkit Detection?
- How to Set Up Real-time Malware Monitoring?
- How to Analyze Suspicious Files and Processes?
- How to Create Automated Detection Scripts?
- What Network-based Detection Methods Work Best?
- How to Respond to Detected Threats?
- Troubleshooting Detection Issues
- Additional Security Resources
How to Detect Malware on Linux Systems?
Linux malware detection encompasses multiple security layers that work together to identify various types of threats. Moreover, effective detection requires understanding different malware types, from traditional viruses to sophisticated rootkits and advanced persistent threats.
Understanding Linux Malware Types
Linux systems face several malware categories that require different detection approaches. Additionally, each type exhibits unique characteristics that security professionals must recognize for effective identification.
Common Linux Malware Categories:
| Malware Type | Detection Method | Primary Tools | Impact Level |
|---|---|---|---|
| Rootkits | System file analysis | rkhunter, chkrootkit | Critical |
| Trojans | Behavioral monitoring | ClamAV, AIDE | High |
| Backdoors | Network analysis | Wireshark, netstat | Critical |
| Cryptominers | Resource monitoring | htop, iotop | Medium |
| Ransomware | File system monitoring | inotify, AIDE | Critical |
Core Detection Methodology
Successful Linux malware detection follows a systematic methodology that combines multiple detection techniques. Therefore, administrators should implement layered security approaches for comprehensive threat identification.
#!/bin/bash
# Comprehensive malware detection workflow
echo "=== Linux Malware Detection Suite ==="
# 1. System file integrity check
echo "Checking system file integrity..."
sudo aide --check
# 2. Rootkit detection with multiple tools
echo "Running rootkit detection..."
sudo rkhunter --check --skip-keypress --report-warnings-only
sudo chkrootkit
# 3. Antivirus scanning
echo "Performing antivirus scan..."
sudo freshclam
sudo clamscan -r --infected --log=/var/log/clamav-scan.log /
# 4. Process and network analysis
echo "Analyzing running processes..."
ps aux --sort=-%cpu | head -20
netstat -tulnp | grep ESTABLISHED
# 5. File system anomaly detection
echo "Checking for unusual file modifications..."
find / -type f -mtime -1 -executable 2>/dev/null | head -10
What are the Best Linux Malware Detection Tools?
Professional Linux malware detection requires specialized tools designed for different threat vectors. Consequently, system administrators must select appropriate tools based on their specific security requirements and threat landscape.
Signature-based Detection Tools
Signature-based detection tools identify malware by comparing files against known threat databases. Furthermore, these tools provide excellent detection rates for known threats while requiring regular signature updates.
ClamAV Configuration and Usage
ClamAV serves as the industry standard open-source antivirus solution for Linux systems. Additionally, it integrates effectively with mail servers and provides comprehensive scanning capabilities.
# Install ClamAV on different distributions
# Ubuntu/Debian
sudo apt update && sudo apt install clamav clamav-daemon
# CentOS/RHEL/Fedora
sudo dnf install clamav clamav-update
# Configure ClamAV daemon
sudo systemctl enable clamav-daemon
sudo systemctl start clamav-daemon
# Update virus signatures
sudo freshclam
# Scan specific directories with detailed logging
sudo clamscan -r --infected --log=/var/log/clamav-scan.log --max-filesize=500M /home/
sudo clamscan -r --infected --bell --move=/quarantine/ /var/www/
# Schedule automatic scanning
echo "0 2 * * * root /usr/bin/clamscan -r --quiet --infected /home/ >> /var/log/clamav-daily.log" | sudo tee -a /etc/crontab
Rootkit Detection with rkhunter
Rkhunter provides comprehensive rootkit detection capabilities through multiple testing methodologies. Moreover, it performs both file-based and behavioral analysis to identify sophisticated threats.
# Install and configure rkhunter
sudo apt install rkhunter
# Initial configuration
sudo rkhunter --update
sudo rkhunter --propupd
# Comprehensive system scan
sudo rkhunter --check --report-warnings-only --logfile /var/log/rkhunter.log
# Configure automatic daily scans
sudo tee /etc/cron.daily/rkhunter << 'EOF'
#!/bin/bash
/usr/bin/rkhunter --cronjob --update --quiet 2>&1
/usr/bin/rkhunter --cronjob --check --quiet 2>&1
EOF
sudo chmod +x /etc/cron.daily/rkhunter
# Custom rkhunter configuration
sudo tee -a /etc/rkhunter.conf << 'EOF'
# Enhanced detection settings
PKGMGR=DPKG
ALLOW_SSH_ROOT_USER=no
ALLOW_SSH_PROT_V1=0
SCRIPTWHITELIST=/usr/bin/egrep
SCRIPTWHITELIST=/usr/bin/fgrep
SCRIPTWHITELIST=/usr/bin/which
SCRIPTWHITELIST=/usr/bin/ldd
WEB_CMD=""
EOF
Traditional Detection with chkrootkit
Chkrootkit provides fast rootkit detection using simple but effective signature matching. Therefore, it serves as an excellent complement to more sophisticated detection tools.
# Install chkrootkit
sudo apt install chkrootkit
# Basic rootkit scan
sudo chkrootkit
# Detailed scan with specific checks
sudo chkrootkit -q -x
# Automated scanning with email alerts
sudo tee /etc/cron.weekly/chkrootkit << 'EOF'
#!/bin/bash
LOGFILE="/var/log/chkrootkit.log"
/usr/sbin/chkrootkit > $LOGFILE 2>&1
if [ $? -ne 0 ]; then
mail -s "chkrootkit: Potential rootkit detected" admin@company.com < $LOGFILE
fi
EOF
sudo chmod +x /etc/cron.weekly/chkrootkit
Behavioral Analysis Tools
Behavioral analysis tools monitor system activities to identify suspicious patterns that may indicate malware presence. Additionally, these tools excel at detecting zero-day threats and advanced persistent threats.
AIDE File Integrity Monitoring
AIDE (Advanced Intrusion Detection Environment) provides comprehensive file integrity monitoring capabilities. Furthermore, it establishes system baselines and detects unauthorized modifications.
# Install AIDE
sudo apt install aide
# Initialize AIDE database
sudo aideinit
# Copy database to protected location
sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db
# Perform integrity check
sudo aide --check
# Configure custom monitoring rules
sudo tee -a /etc/aide/aide.conf << 'EOF'
# Custom monitoring rules for malware detection
/etc p+i+n+u+g+s+b+m+c+md5+sha1+rmd160
/bin p+i+n+u+g+s+b+m+c+md5+sha1+rmd160
/sbin p+i+n+u+g+s+b+m+c+md5+sha1+rmd160
/lib p+i+n+u+g+s+b+m+c+md5+sha1+rmd160
/opt p+i+n+u+g+s+b+m+c+md5+sha1+rmd160
/usr p+i+n+u+g+s+b+m+c+md5+sha1+rmd160
/tmp n+p+u+g+i
EOF
# Schedule regular integrity checks
echo "0 3 * * * root /usr/bin/aide --check 2>&1 | mail -s 'AIDE Report' admin@company.com" | sudo tee -a /etc/crontab
How to Configure Rootkit Detection?
Rootkit detection requires specialized approaches because rootkits specifically target detection evasion. Consequently, effective rootkit detection employs multiple detection engines and cross-verification techniques.
Advanced rkhunter Configuration
Professional rkhunter deployment involves extensive customization for specific environments. Moreover, proper configuration reduces false positives while maintaining detection sensitivity.
# Advanced rkhunter configuration
sudo tee /etc/rkhunter.conf.local << 'EOF'
# Network configuration
ALLOW_SSH_ROOT_USER=unset
ALLOW_SSH_PROT_V1=0
ENABLE_TESTS="all"
DISABLE_TESTS="suspscan hidden_procs deleted_files packet_cap_apps apps"
# File system checks
SCANROOTKITMODE=1
UNHIDESCANDIR="/dev /etc /usr /tmp"
PHALANX2_DIRTEST=0
ALLOW_SYSLOG_REMOTE_LOGGING=0
# Hash database configuration
HASH_FUNC=SHA256
HASH_FLD_IDX=2
PKGMGR=DPKG
# Logging configuration
USE_SYSLOG=authpriv.notice
APPEND_LOG=1
COPY_LOG_ON_ERROR=1
# Email configuration
MAIL-ON-WARNING=admin@company.com
MAIL_CMD=mail -s "[rkhunter] Warnings found for ${HOSTNAME}"
EOF
# Update file properties database after configuration
sudo rkhunter --propupd
# Test configuration with verbose output
sudo rkhunter --check --enable all --disable none --report-warnings-only
Enhanced chkrootkit Deployment
Enhanced chkrootkit deployment involves systematic scanning schedules and result analysis. Therefore, administrators should implement comprehensive monitoring workflows.
# Create enhanced chkrootkit wrapper script
sudo tee /usr/local/bin/enhanced-chkrootkit.sh << 'EOF'
#!/bin/bash
LOGFILE="/var/log/enhanced-chkrootkit.log"
ALERTFILE="/var/log/chkrootkit-alerts.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
echo "=== Enhanced chkrootkit Scan - $TIMESTAMP ===" >> $LOGFILE
# Run chkrootkit with enhanced detection
/usr/sbin/chkrootkit -x -q >> $LOGFILE 2>&1
# Check for infections
if grep -i "infected\|suspicious\|trojan\|rootkit" $LOGFILE | tail -10; then
echo "$TIMESTAMP: Potential threats detected" >> $ALERTFILE
# Send immediate alert
tail -20 $LOGFILE | mail -s "URGENT: chkrootkit detected threats on ${HOSTNAME}" admin@company.com
fi
# Additional system checks
echo "=== Process Analysis ===" >> $LOGFILE
ps auxf | awk '{if($3>80.0) print $0}' >> $LOGFILE
echo "=== Network Connections ===" >> $LOGFILE
netstat -tulpn | grep LISTEN | grep -v "127.0.0.1\|::1" >> $LOGFILE
# Rotate logs if they become too large
if [ $(stat --printf="%s" $LOGFILE) -gt 10485760 ]; then
mv $LOGFILE $LOGFILE.old
gzip $LOGFILE.old
fi
EOF
sudo chmod +x /usr/local/bin/enhanced-chkrootkit.sh
# Schedule enhanced scanning
echo "0 */6 * * * root /usr/local/bin/enhanced-chkrootkit.sh" | sudo tee -a /etc/crontab
How to Set Up Real-time Malware Monitoring?
Real-time malware monitoring provides immediate threat detection and response capabilities. Furthermore, continuous monitoring enables rapid containment of security incidents before significant damage occurs.
Process Monitoring with psacct
Process accounting provides detailed information about executed commands and processes. Additionally, it enables forensic analysis of potentially malicious activities.
# Install process accounting
sudo apt install acct
# Start process accounting
sudo systemctl enable psacct
sudo systemctl start psacct
# Monitor command execution
sudo lastcomm | head -20
# Create real-time monitoring script
sudo tee /usr/local/bin/process-monitor.sh << 'EOF'
#!/bin/bash
LOGFILE="/var/log/suspicious-processes.log"
ALERT_THRESHOLD=5
while true; do
# Monitor for suspicious process patterns
SUSPICIOUS_PROCS=$(ps aux | grep -E "(nc|netcat|ncat|socat|python.*socket|perl.*socket|ruby.*socket)" | grep -v grep | wc -l)
if [ $SUSPICIOUS_PROCS -gt $ALERT_THRESHOLD ]; then
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
echo "$TIMESTAMP: $SUSPICIOUS_PROCS suspicious processes detected" >> $LOGFILE
ps aux | grep -E "(nc|netcat|ncat|socat|python.*socket|perl.*socket|ruby.*socket)" | grep -v grep >> $LOGFILE
# Send alert
echo "Suspicious network processes detected on ${HOSTNAME}" | mail -s "Security Alert" admin@company.com
fi
# Check for high CPU usage processes
HIGH_CPU=$(ps aux --sort=-%cpu | head -5 | awk 'NR>1 {if($3>90) print $2,$11}')
if [ -n "$HIGH_CPU" ]; then
echo "$(date): High CPU processes: $HIGH_CPU" >> $LOGFILE
fi
sleep 30
done
EOF
sudo chmod +x /usr/local/bin/process-monitor.sh
# Create systemd service for process monitoring
sudo tee /etc/systemd/system/process-monitor.service << 'EOF'
[Unit]
Description=Real-time Process Monitor
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/process-monitor.sh
Restart=always
User=root
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl enable process-monitor.service
sudo systemctl start process-monitor.service
File System Monitoring with inotify
File system monitoring detects real-time changes to critical system files and directories. Moreover, inotify provides efficient kernel-level monitoring with minimal system overhead.
# Install inotify tools
sudo apt install inotify-tools
# Create comprehensive file monitoring script
sudo tee /usr/local/bin/file-monitor.sh << 'EOF'
#!/bin/bash
LOGFILE="/var/log/file-changes.log"
CRITICAL_DIRS="/etc /bin /sbin /usr/bin /usr/sbin /lib /lib64"
# Monitor critical directories
inotifywait -m -r --format '%T %w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' $CRITICAL_DIRS |
while read timestamp file event; do
echo "$timestamp: $file -> $event" >> $LOGFILE
# Alert on specific events
case $event in
"CREATE"|"DELETE"|"MOVE")
echo "$timestamp: ALERT - $event on $file" | mail -s "File System Alert" admin@company.com
;;
"MODIFY")
# Check if it's a binary file
if file "$file" | grep -q "executable"; then
echo "$timestamp: CRITICAL - Binary modification: $file" | mail -s "CRITICAL: Binary Modified" admin@company.com
fi
;;
esac
done &
# Monitor for new files in /tmp with executable permissions
inotifywait -m --format '%T %w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' /tmp |
while read timestamp file event; do
if [ "$event" = "CREATE" ] && [ -x "$file" ]; then
echo "$timestamp: Executable created in /tmp: $file" >> $LOGFILE
# Quarantine suspicious executables
mv "$file" "/quarantine/$(basename $file).$(date +%s)"
echo "$timestamp: Quarantined executable from /tmp: $file" | mail -s "Executable Quarantined" admin@company.com
fi
done &
EOF
sudo chmod +x /usr/local/bin/file-monitor.sh
# Create quarantine directory
sudo mkdir -p /quarantine
sudo chmod 700 /quarantine
# Start file monitoring as service
sudo tee /etc/systemd/system/file-monitor.service << 'EOF'
[Unit]
Description=File System Monitor
After=network.target
[Service]
Type=forking
ExecStart=/usr/local/bin/file-monitor.sh
Restart=always
User=root
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl enable file-monitor.service
sudo systemctl start file-monitor.service
How to Analyze Suspicious Files and Processes?
Suspicious file analysis requires systematic approaches combining static and dynamic analysis techniques. Therefore, security professionals must employ multiple analysis methods to accurately assess threat levels.
Static File Analysis
Static analysis examines files without executing them, providing safe initial assessment. Additionally, static analysis techniques reveal file characteristics and potential threat indicators.
# Comprehensive file analysis script
sudo tee /usr/local/bin/analyze-file.sh << 'EOF'
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 <file_path>"
exit 1
fi
FILE="$1"
REPORT_FILE="/tmp/analysis_$(basename $FILE)_$(date +%s).txt"
echo "=== File Analysis Report ===" > $REPORT_FILE
echo "File: $FILE" >> $REPORT_FILE
echo "Analysis Date: $(date)" >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Basic file information
echo "=== Basic Information ===" >> $REPORT_FILE
file "$FILE" >> $REPORT_FILE
ls -la "$FILE" >> $REPORT_FILE
stat "$FILE" >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Hash calculations
echo "=== Checksums ===" >> $REPORT_FILE
md5sum "$FILE" >> $REPORT_FILE
sha1sum "$FILE" >> $REPORT_FILE
sha256sum "$FILE" >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Strings analysis for suspicious content
echo "=== Suspicious Strings ===" >> $REPORT_FILE
strings "$FILE" | grep -i -E "(password|wget|curl|nc|netcat|/bin/sh|/bin/bash|socket|connect)" >> $REPORT_FILE
echo "" >> $REPORT_FILE
# ELF analysis if applicable
if file "$FILE" | grep -q "ELF"; then
echo "=== ELF Analysis ===" >> $REPORT_FILE
readelf -h "$FILE" 2>/dev/null >> $REPORT_FILE
ldd "$FILE" 2>/dev/null >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Check for suspicious system calls
echo "=== System Call Analysis ===" >> $REPORT_FILE
objdump -T "$FILE" 2>/dev/null | grep -E "(socket|connect|exec|system)" >> $REPORT_FILE
fi
# ClamAV scan
echo "=== Antivirus Scan ===" >> $REPORT_FILE
clamscan "$FILE" >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Size and entropy analysis
echo "=== File Characteristics ===" >> $REPORT_FILE
echo "File size: $(stat -c%s "$FILE") bytes" >> $REPORT_FILE
echo "Last modified: $(stat -c%y "$FILE")" >> $REPORT_FILE
cat $REPORT_FILE
echo "Full report saved to: $REPORT_FILE"
EOF
sudo chmod +x /usr/local/bin/analyze-file.sh
# Example usage for suspicious files
sudo /usr/local/bin/analyze-file.sh /tmp/suspicious_binary
Process Analysis and Investigation
Process analysis reveals runtime behavior patterns that indicate malicious activities. Furthermore, systematic process investigation enables identification of attack vectors and persistence mechanisms.
# Advanced process analysis script
sudo tee /usr/local/bin/analyze-process.sh << 'EOF'
#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 <PID>"
exit 1
fi
PID="$1"
REPORT_FILE="/tmp/process_analysis_${PID}_$(date +%s).txt"
echo "=== Process Analysis Report ===" > $REPORT_FILE
echo "PID: $PID" >> $REPORT_FILE
echo "Analysis Date: $(date)" >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Process information
echo "=== Process Information ===" >> $REPORT_FILE
ps -p $PID -o pid,ppid,user,cmd,etime,pcpu,pmem >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Process tree
echo "=== Process Tree ===" >> $REPORT_FILE
pstree -p $PID >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Open files and network connections
echo "=== Open Files ===" >> $REPORT_FILE
lsof -p $PID 2>/dev/null >> $REPORT_FILE
echo "" >> $REPORT_FILE
echo "=== Network Connections ===" >> $REPORT_FILE
netstat -anp 2>/dev/null | grep $PID >> $REPORT_FILE
ss -anp 2>/dev/null | grep $PID >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Memory analysis
echo "=== Memory Information ===" >> $REPORT_FILE
cat /proc/$PID/maps 2>/dev/null | head -20 >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Environment variables
echo "=== Environment Variables ===" >> $REPORT_FILE
cat /proc/$PID/environ 2>/dev/null | tr '\0' '\n' | head -20 >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Command line
echo "=== Command Line ===" >> $REPORT_FILE
cat /proc/$PID/cmdline 2>/dev/null | tr '\0' ' ' >> $REPORT_FILE
echo "" >> $REPORT_FILE
# Check if process binary exists and analyze it
BINARY=$(readlink /proc/$PID/exe 2>/dev/null)
if [ -n "$BINARY" ] && [ -f "$BINARY" ]; then
echo "=== Binary Analysis ===" >> $REPORT_FILE
file "$BINARY" >> $REPORT_FILE
ls -la "$BINARY" >> $REPORT_FILE
clamscan "$BINARY" 2>/dev/null >> $REPORT_FILE
fi
cat $REPORT_FILE
echo "Full report saved to: $REPORT_FILE"
EOF
sudo chmod +x /usr/local/bin/analyze-process.sh
# Monitor for processes with unusual characteristics
sudo tee /usr/local/bin/suspicious-process-monitor.sh << 'EOF'
#!/bin/bash
LOGFILE="/var/log/suspicious-processes.log"
while true; do
# Find processes without proper binary paths
ps aux | while read user pid cpu mem vsz rss tty stat start time command; do
if [ "$pid" != "PID" ]; then # Skip header line
# Check if process binary exists
if [ ! -f "/proc/$pid/exe" ] && [ ! -L "/proc/$pid/exe" ]; then
echo "$(date): Missing binary for PID $pid: $command" >> $LOGFILE
fi
# Check for processes running from /tmp
if echo "$command" | grep -q "^/tmp/"; then
echo "$(date): Process running from /tmp - PID $pid: $command" >> $LOGFILE
/usr/local/bin/analyze-process.sh $pid >> $LOGFILE
fi
# Check for high CPU usage with suspicious names
if (( $(echo "$cpu > 80" | bc -l) )) && echo "$command" | grep -qE "(nc|netcat|python|perl|ruby|tmp)"; then
echo "$(date): High CPU suspicious process - PID $pid: $command" >> $LOGFILE
fi
fi
done
sleep 60
done
EOF
sudo chmod +x /usr/local/bin/suspicious-process-monitor.sh
How to Create Automated Detection Scripts?
Automated detection scripts provide continuous monitoring capabilities without manual intervention. Moreover, well-designed automation reduces response times and ensures consistent security monitoring coverage.
Comprehensive Malware Detection Framework
A comprehensive detection framework integrates multiple security tools into coordinated scanning workflows. Therefore, automated frameworks provide systematic threat detection across all attack vectors.
# Master malware detection script
sudo tee /usr/local/bin/malware-detection-suite.sh << 'EOF'
#!/bin/bash
# Configuration
LOGFILE="/var/log/malware-detection.log"
EMAIL_ALERT="admin@company.com"
QUARANTINE_DIR="/quarantine"
SCAN_DIRS="/home /var/www /opt /tmp"
# Ensure quarantine directory exists
mkdir -p $QUARANTINE_DIR
# Function to log messages
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" | tee -a $LOGFILE
}
# Function to send alerts
send_alert() {
local subject="$1"
local message="$2"
echo "$message" | mail -s "$subject" $EMAIL_ALERT
log_message "Alert sent: $subject"
}
log_message "=== Starting Comprehensive Malware Detection ==="
# 1. Update virus signatures
log_message "Updating virus signatures..."
freshclam --quiet
if [ $? -eq 0 ]; then
log_message "Virus signatures updated successfully"
else
log_message "WARNING: Failed to update virus signatures"
fi
# 2. ClamAV full system scan
log_message "Starting ClamAV system scan..."
CLAMAV_LOG="/tmp/clamav_scan_$(date +%s).log"
clamscan -r --infected --move=$QUARANTINE_DIR $SCAN_DIRS > $CLAMAV_LOG 2>&1
INFECTED_FILES=$(grep "FOUND" $CLAMAV_LOG | wc -l)
if [ $INFECTED_FILES -gt 0 ]; then
send_alert "CRITICAL: Malware detected by ClamAV" "$(cat $CLAMAV_LOG)"
log_message "CRITICAL: $INFECTED_FILES infected files detected and quarantined"
else
log_message "ClamAV scan completed - No threats detected"
fi
# 3. Rootkit detection with rkhunter
log_message "Running rkhunter scan..."
rkhunter --check --report-warnings-only --quiet --logfile $LOGFILE.rkhunter
if grep -q "Warning" $LOGFILE.rkhunter; then
send_alert "WARNING: rkhunter detected issues" "$(cat $LOGFILE.rkhunter)"
log_message "WARNING: rkhunter detected potential issues"
else
log_message "rkhunter scan completed - No issues detected"
fi
# 4. chkrootkit scan
log_message "Running chkrootkit scan..."
CHKROOTKIT_LOG="/tmp/chkrootkit_scan_$(date +%s).log"
chkrootkit > $CHKROOTKIT_LOG 2>&1
if grep -i "infected\|suspicious" $CHKROOTKIT_LOG; then
send_alert "WARNING: chkrootkit detected threats" "$(cat $CHKROOTKIT_LOG)"
log_message "WARNING: chkrootkit detected potential threats"
else
log_message "chkrootkit scan completed - No threats detected"
fi
# 5. File integrity check
log_message "Running AIDE file integrity check..."
if [ -f /var/lib/aide/aide.db ]; then
AIDE_LOG="/tmp/aide_check_$(date +%s).log"
aide --check > $AIDE_LOG 2>&1
if grep -q "changed\|added\|removed" $AIDE_LOG; then
send_alert "WARNING: File integrity violations detected" "$(cat $AIDE_LOG)"
log_message "WARNING: File integrity violations detected"
else
log_message "AIDE integrity check completed - No changes detected"
fi
else
log_message "WARNING: AIDE database not found - skipping integrity check"
fi
# 6. Network connection analysis
log_message "Analyzing network connections..."
SUSPICIOUS_CONNECTIONS=$(netstat -tuln | grep -E ":6667|:6697|:1234|:31337|:12345" | wc -l)
if [ $SUSPICIOUS_CONNECTIONS -gt 0 ]; then
NETWORK_LOG="/tmp/network_analysis_$(date +%s).log"
netstat -tulpn > $NETWORK_LOG
send_alert "WARNING: Suspicious network connections detected" "$(cat $NETWORK_LOG)"
log_message "WARNING: $SUSPICIOUS_CONNECTIONS suspicious network connections detected"
fi
# 7. Process analysis
log_message "Analyzing running processes..."
SUSPICIOUS_PROCESSES=$(ps aux | grep -E "(nc |netcat|ncat|socat)" | grep -v grep | wc -l)
if [ $SUSPICIOUS_PROCESSES -gt 0 ]; then
PROCESS_LOG="/tmp/process_analysis_$(date +%s).log"
ps auxf > $PROCESS_LOG
send_alert "WARNING: Suspicious processes detected" "$(cat $PROCESS_LOG)"
log_message "WARNING: $SUSPICIOUS_PROCESSES suspicious processes detected"
fi
# 8. Check for unusual system modifications
log_message "Checking for unusual system modifications..."
RECENT_MODS=$(find /bin /sbin /usr/bin /usr/sbin -type f -mtime -1 2>/dev/null | wc -l)
if [ $RECENT_MODS -gt 0 ]; then
MODS_LOG="/tmp/recent_modifications_$(date +%s).log"
find /bin /sbin /usr/bin /usr/sbin -type f -mtime -1 -exec ls -la {} \; > $MODS_LOG 2>/dev/null
send_alert "WARNING: Recent system file modifications" "$(cat $MODS_LOG)"
log_message "WARNING: $RECENT_MODS recent system file modifications detected"
fi
# 9. Generate summary report
log_message "=== Malware Detection Summary ==="
log_message "Scan completed at $(date)"
log_message "Infected files quarantined: $(ls -1 $QUARANTINE_DIR 2>/dev/null | wc -l)"
log_message "Log files generated in /tmp/"
# Cleanup old log files (keep last 10)
find /tmp -name "*_scan_*.log" -o -name "*_analysis_*.log" | sort | head -n -10 | xargs rm -f
log_message "=== Malware Detection Complete ==="
EOF
sudo chmod +x /usr/local/bin/malware-detection-suite.sh
# Schedule automated scanning
echo "0 2 * * * root /usr/local/bin/malware-detection-suite.sh" | sudo tee -a /etc/crontab
echo "0 14 * * * root /usr/local/bin/malware-detection-suite.sh" | sudo tee -a /etc/crontab
Incident Response Automation
Incident response automation enables immediate threat containment and evidence preservation. Furthermore, automated response reduces human error during high-stress security incidents.
# Automated incident response script
sudo tee /usr/local/bin/incident-response.sh << 'EOF'
#!/bin/bash
# Configuration
INCIDENT_LOG="/var/log/incident-response.log"
EVIDENCE_DIR="/evidence/$(date +%Y%m%d_%H%M%S)"
EMAIL_ALERT="security@company.com"
# Create evidence directory
mkdir -p $EVIDENCE_DIR
# Function to log actions
log_action() {
echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" | tee -a $INCIDENT_LOG
}
# Function to collect evidence
collect_evidence() {
log_action "Collecting system evidence..."
# System information
uname -a > $EVIDENCE_DIR/system_info.txt
date > $EVIDENCE_DIR/timestamp.txt
uptime > $EVIDENCE_DIR/uptime.txt
# Process information
ps auxf > $EVIDENCE_DIR/processes.txt
pstree -p > $EVIDENCE_DIR/process_tree.txt
# Network information
netstat -tuln > $EVIDENCE_DIR/network_listening.txt
netstat -tulpn > $EVIDENCE_DIR/network_processes.txt
ss -tuln > $EVIDENCE_DIR/sockets.txt
arp -a > $EVIDENCE_DIR/arp_table.txt
# User information
who > $EVIDENCE_DIR/logged_users.txt
w > $EVIDENCE_DIR/user_activity.txt
last -20 > $EVIDENCE_DIR/last_logins.txt
# File system information
df -h > $EVIDENCE_DIR/disk_usage.txt
mount > $EVIDENCE_DIR/mounted_filesystems.txt
find /tmp -type f -mtime -1 -exec ls -la {} \; > $EVIDENCE_DIR/recent_tmp_files.txt
# Running services
systemctl list-units --type=service --state=running > $EVIDENCE_DIR/running_services.txt
# System logs (last 100 lines)
tail -100 /var/log/syslog > $EVIDENCE_DIR/syslog.txt 2>/dev/null
tail -100 /var/log/auth.log > $EVIDENCE_DIR/auth.log 2>/dev/null
tail -100 /var/log/messages > $EVIDENCE_DIR/messages.txt 2>/dev/null
log_action "Evidence collected in $EVIDENCE_DIR"
}
# Function to isolate system
isolate_system() {
log_action "Initiating system isolation..."
# Block all outbound connections except SSH (if needed)
iptables -P OUTPUT DROP
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Save iptables rules
iptables-save > $EVIDENCE_DIR/isolation_iptables.rules
log_action "System network isolation activated"
}
# Function to terminate suspicious processes
terminate_threats() {
local pid_list="$1"
for pid in $pid_list; do
if [ -n "$pid" ] && kill -0 $pid 2>/dev/null; then
log_action "Terminating suspicious process PID: $pid"
# Collect process information before termination
ps -p $pid -o pid,ppid,user,cmd > $EVIDENCE_DIR/terminated_process_$pid.txt
lsof -p $pid > $EVIDENCE_DIR/terminated_process_files_$pid.txt 2>/dev/null
# Terminate process
kill -TERM $pid
sleep 5
# Force kill if still running
if kill -0 $pid 2>/dev/null; then
kill -KILL $pid
log_action "Force killed process PID: $pid"
fi
fi
done
}
# Main incident response workflow
log_action "=== INCIDENT RESPONSE ACTIVATED ==="
# Collect initial evidence
collect_evidence
# Check for command line arguments (PIDs to terminate)
if [ $# -gt 0 ]; then
log_action "Received suspicious PIDs for termination: $*"
terminate_threats "$*"
fi
# Check for active malware indicators
SUSPICIOUS_PIDS=$(ps aux | grep -E "(nc |netcat|ncat|socat|/tmp/)" | grep -v grep | awk '{print $2}' | tr '\n' ' ')
if [ -n "$SUSPICIOUS_PIDS" ]; then
log_action "Auto-detected suspicious processes: $SUSPICIOUS_PIDS"
terminate_threats "$SUSPICIOUS_PIDS"
fi
# Check for unusual network connections
UNUSUAL_CONNECTIONS=$(netstat -tuln | grep -E ":6667|:6697|:1234|:31337|:12345")
if [ -n "$UNUSUAL_CONNECTIONS" ]; then
log_action "Unusual network connections detected"
echo "$UNUSUAL_CONNECTIONS" > $EVIDENCE_DIR/unusual_connections.txt
# Option to isolate system
read -t 30 -p "Isolate system network? (y/N): " ISOLATE
if [ "$ISOLATE" = "y" ] || [ "$ISOLATE" = "Y" ]; then
isolate_system
fi
fi
# Create incident summary
log_action "Creating incident summary..."
SUMMARY_FILE="$EVIDENCE_DIR/incident_summary.txt"
cat > $SUMMARY_FILE << SUMMARY_EOF
=== INCIDENT RESPONSE SUMMARY ===
Timestamp: $(date)
System: $(hostname)
Incident ID: $(basename $EVIDENCE_DIR)
Evidence Location: $EVIDENCE_DIR
Total Evidence Files: $(ls -1 $EVIDENCE_DIR | wc -l)
Suspicious Processes Terminated: $(echo "$SUSPICIOUS_PIDS" | wc -w)
Network Isolation Active: $(iptables -L OUTPUT | grep -q DROP && echo "YES" || echo "NO")
Next Steps:
1. Review evidence files in $EVIDENCE_DIR
2. Perform forensic imaging if required
3. Contact security team for further analysis
4. Document incident in security log
SUMMARY_EOF
# Send incident notification
echo "$(cat $SUMMARY_FILE)" | mail -s "INCIDENT RESPONSE: Security event on $(hostname)" $EMAIL_ALERT
log_action "=== INCIDENT RESPONSE COMPLETE ==="
log_action "Evidence preserved in: $EVIDENCE_DIR"
echo "Incident response complete. Summary available in: $SUMMARY_FILE"
EOF
sudo chmod +x /usr/local/bin/incident-response.sh
# Create evidence directory
sudo mkdir -p /evidence
sudo chmod 750 /evidence
What Network-based Detection Methods Work Best?
Network-based detection methods identify malware through communication pattern analysis and traffic inspection. Moreover, network monitoring provides early warning capabilities before malware establishes persistent system presence.
Network Traffic Analysis
Network traffic analysis reveals communication patterns that indicate malware activity. Additionally, systematic traffic monitoring identifies command and control communications and data exfiltration attempts.
# Install network monitoring tools
sudo apt install tcpdump wireshark-common tshark nmap
# Network monitoring script
sudo tee /usr/local/bin/network-monitor.sh << 'EOF'
#!/bin/bash
LOGFILE="/var/log/network-monitor.log"
ALERT_FILE="/var/log/network-alerts.log"
CAPTURE_DIR="/var/log/network-captures"
# Create capture directory
mkdir -p $CAPTURE_DIR
# Function to log network events
log_network_event() {
echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" | tee -a $LOGFILE
}
# Function to analyze DNS queries
monitor_dns_queries() {
log_network_event "Starting DNS query monitoring..."
# Monitor DNS queries for suspicious domains
tcpdump -i any -n port 53 -l | while read line; do
# Check for suspicious TLDs and patterns
if echo "$line" | grep -qE "\.tk|\.ml|\.ga|\.cf|dyndns|no-ip|suspicious-domain"; then
echo "$line" >> $ALERT_FILE
log_network_event "SUSPICIOUS DNS: $line"
fi
# Check for DNS tunneling indicators
if echo "$line" | grep -qE "[a-zA-Z0-9]{20,}\."; then
echo "$line" >> $ALERT_FILE
log_network_event "POSSIBLE DNS TUNNELING: $line"
fi
done &
}
# Function to monitor HTTP traffic
monitor_http_traffic() {
log_network_event "Starting HTTP traffic monitoring..."
# Capture HTTP traffic for analysis
tcpdump -i any -w $CAPTURE_DIR/http_traffic_$(date +%s).pcap \
'port 80 or port 443 or port 8080' &
# Monitor for suspicious HTTP patterns
tcpdump -i any -A 'port 80' | while read line; do
# Check for malware user agents
if echo "$line" | grep -qiE "User-Agent.*bot|crawler|wget|curl|python|perl"; then
echo "$line" >> $ALERT_FILE
log_network_event "SUSPICIOUS USER AGENT: $line"
fi
# Check for base64 encoded content
if echo "$line" | grep -qE "[A-Za-z0-9+/]{50,}="; then
echo "$line" >> $ALERT_FILE
log_network_event "POSSIBLE BASE64 CONTENT: $line"
fi
done &
}
# Function to detect port scans
detect_port_scans() {
log_network_event "Starting port scan detection..."
# Monitor for rapid connection attempts (potential port scan)
netstat -tuln | while read line; do
# Extract connections by IP
IP=$(echo "$line" | awk '{print $5}' | cut -d: -f1)
# Count connections per IP
CONNECTIONS=$(netstat -tuln | grep "$IP" | wc -l)
if [ $CONNECTIONS -gt 10 ]; then
log_network_event "HIGH CONNECTION COUNT from $IP: $CONNECTIONS"
# Block IP if it's external
if [[ ! "$IP" =~ ^(10\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\.|127\.) ]]; then
iptables -A INPUT -s "$IP" -j DROP
log_network_event "BLOCKED IP: $IP"
fi
fi
done
}
# Function to monitor unusual protocols
monitor_protocols() {
log_network_event "Starting protocol monitoring..."
# Monitor for unusual protocol usage
tcpdump -i any -c 1000 -n | awk '{print $3}' | sort | uniq -c | sort -nr | while read count proto; do
if [ $count -gt 100 ]; then
log_network_event "HIGH PROTOCOL USAGE: $proto ($count packets)"
fi
done
}
# Main monitoring loop
log_network_event "=== Starting Network Monitoring ==="
# Start individual monitoring functions
monitor_dns_queries
monitor_http_traffic
detect_port_scans
# Periodic protocol analysis
while true; do
monitor_protocols
sleep 300 # Run every 5 minutes
done
EOF
sudo chmod +x /usr/local/bin/network-monitor.sh
# Create systemd service for network monitoring
sudo tee /etc/systemd/system/network-monitor.service << 'EOF'
[Unit]
Description=Network Security Monitor
After=network.target
[Service]
Type=simple
ExecStart=/usr/local/bin/network-monitor.sh
Restart=always
User=root
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl enable network-monitor.service
sudo systemctl start network-monitor.service
Intrusion Detection Integration
Intrusion detection systems provide automated network-based threat identification. Furthermore, IDS integration enables comprehensive security event correlation and automated response capabilities.
# Install and configure Snort
sudo apt install snort
# Basic Snort configuration for malware detection
sudo tee -a /etc/snort/snort.conf << 'EOF'
# Custom malware detection rules
include $RULE_PATH/local.rules
# Set network variables for your environment
ipvar HOME_NET 192.168.1.0/24
ipvar EXTERNAL_NET !$HOME_NET
# Enable malware detection preprocessors
preprocessor http_inspect_server: \
server default \
profile all \
ports { 80 8080 8000 } \
enable_cookie \
extended_response_inspection
preprocessor ssl: \
ports { 443 465 993 995 636 }, \
trustservers, \
noinspect_encrypted
# Output configuration
output alert_syslog: LOG_AUTH LOG_ALERT
output log_tcpdump: /var/log/snort/snort.log
EOF
# Create custom malware detection rules
sudo tee /etc/snort/rules/local.rules << 'EOF'
# Malware communication detection rules
alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"Potential malware HTTP communication"; content:"GET"; http_method; content:"/gate.php"; http_uri; sid:1000001;)
alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"Potential botnet IRC communication"; content:"JOIN #"; depth:10; sid:1000002;)
alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"Suspicious base64 HTTP POST"; content:"POST"; http_method; content:"|3d|"; http_client_body; sid:1000003;)
alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"Potential data exfiltration"; content:"POST"; http_method; dsize:>10000; sid:1000004;)
alert tcp $EXTERNAL_NET any -> $HOME_NET any (msg:"Suspicious executable download"; content:"HTTP/1."; content:".exe"; http_header; sid:1000005;)
# DNS-based malware detection
alert udp $HOME_NET any -> any 53 (msg:"Suspicious DNS query length"; content:"|01 00 00 01|"; offset:2; depth:4; dsize:>100; sid:1000006;)
alert udp any 53 -> $HOME_NET any (msg:"Potential DNS tunneling response"; content:"|81 80|"; offset:2; depth:2; dsize:>200; sid:1000007;)
# Network scanning detection
alert tcp $EXTERNAL_NET any -> $HOME_NET any (msg:"Port scan detected"; flags:S; threshold: type both, track by_src, count 20, seconds 60; sid:1000008;)
# Malware persistence indicators
alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"Suspicious user agent"; content:"User-Agent|3a| Bot"; http_header; nocase; sid:1000009;)
alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"Potential C&C communication"; content:"Mozilla/4.0"; http_header; content:"cmd="; http_uri; sid:1000010;)
EOF
# Configure Snort logging and alerting
sudo mkdir -p /var/log/snort
sudo chmod 755 /var/log/snort
# Create Snort startup script
sudo tee /usr/local/bin/start-snort.sh << 'EOF'
#!/bin/bash
INTERFACE="eth0" # Adjust for your network interface
LOGDIR="/var/log/snort"
CONF="/etc/snort/snort.conf"
# Start Snort in daemon mode
/usr/bin/snort -D -i $INTERFACE -c $CONF -l $LOGDIR -u snort -g snort
# Monitor Snort alerts and send notifications
tail -f /var/log/syslog | grep -i snort | while read line; do
echo "$line" | mail -s "Snort Alert: $(hostname)" admin@company.com
done
EOF
sudo chmod +x /usr/local/bin/start-snort.sh
# Install and configure fail2ban for automated blocking
sudo apt install fail2ban
# Configure fail2ban for malware-related activities
sudo tee /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
backend = systemd
[malware-connections]
enabled = true
filter = malware-connections
logpath = /var/log/network-alerts.log
maxretry = 1
bantime = 86400
action = iptables-multiport[name=malware, port="all", protocol=all]
[suspicious-dns]
enabled = true
filter = suspicious-dns
logpath = /var/log/network-alerts.log
maxretry = 5
bantime = 7200
action = iptables-multiport[name=dns-abuse, port="53", protocol=udp]
EOF
# Create custom fail2ban filters
sudo tee /etc/fail2ban/filter.d/malware-connections.conf << 'EOF'
[Definition]
failregex = ^.*SUSPICIOUS.*<HOST>.*$
^.*BLOCKED IP.*<HOST>.*$
ignoreregex =
EOF
sudo tee /etc/fail2ban/filter.d/suspicious-dns.conf << 'EOF'
[Definition]
failregex = ^.*SUSPICIOUS DNS.*<HOST>.*$
^.*DNS TUNNELING.*<HOST>.*$
ignoreregex =
EOF
# Enable and start fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
How to Respond to Detected Threats?
Threat response requires systematic approaches that prioritize containment, evidence preservation, and system recovery. Therefore, effective incident response follows established procedures while adapting to specific threat characteristics.
Immediate Response Procedures
Immediate response procedures focus on threat containment and damage limitation. Additionally, rapid response prevents threat escalation and minimizes potential system compromise.
# Emergency response script for detected malware
sudo tee /usr/local/bin/emergency-response.sh << 'EOF'
#!/bin/bash
# Emergency response configuration
LOCKDOWN_MODE=${1:-false}
THREAT_TYPE=${2:-unknown}
EVIDENCE_DIR="/emergency-evidence/$(date +%Y%m%d_%H%M%S)"
LOG_FILE="/var/log/emergency-response.log"
# Create evidence directory
mkdir -p $EVIDENCE_DIR
# Function to log emergency actions
emergency_log() {
echo "$(date '+%Y-%m-%d %H:%M:%S') [EMERGENCY]: $1" | tee -a $LOG_FILE
}
# Function for immediate system lockdown
initiate_lockdown() {
emergency_log "INITIATING EMERGENCY LOCKDOWN"
# 1. Block all network traffic except SSH
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP
# Allow localhost
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow SSH (emergency access)
iptables -A INPUT -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
# Save lockdown rules
iptables-save > $EVIDENCE_DIR/lockdown-iptables.rules
emergency_log "Network lockdown activated - SSH access maintained"
}
# Function to terminate all user sessions except current
terminate_user_sessions() {
emergency_log "Terminating user sessions..."
# Get current session
CURRENT_TTY=$(tty | sed 's|/dev/||')
# Terminate other sessions
who | while read user tty rest; do
if [ "$tty" != "$CURRENT_TTY" ]; then
emergency_log "Terminating session: $user on $tty"
pkill -TERM -t $tty
fi
done
}
# Function to stop non-essential services
stop_services() {
emergency_log "Stopping non-essential services..."
# List of services to stop during emergency
SERVICES_TO_STOP="apache2 nginx mysql postgresql docker httpd"
for service in $SERVICES_TO_STOP; do
if systemctl is-active --quiet $service; then
emergency_log "Stopping service: $service"
systemctl stop $service
echo "Stopped $service at $(date)" >> $EVIDENCE_DIR/stopped-services.log
fi
done
}
# Function to collect critical evidence
collect_critical_evidence() {
emergency_log "Collecting critical evidence..."
# System state at time of incident
ps auxf > $EVIDENCE_DIR/processes-full.txt
netstat -tulpn > $EVIDENCE_DIR/network-connections.txt
ss -tulpn > $EVIDENCE_DIR/socket-statistics.txt
lsof > $EVIDENCE_DIR/open-files.txt
# Memory dump of critical processes
pidof systemd | head -1 | xargs -I {} cat /proc/{}/maps > $EVIDENCE_DIR/systemd-memory-map.txt
# Network configuration
ip route > $EVIDENCE_DIR/routing-table.txt
ip addr > $EVIDENCE_DIR/ip-configuration.txt
arp -a > $EVIDENCE_DIR/arp-table.txt
# Recently modified files
find / -type f -mtime -1 -executable 2>/dev/null > $EVIDENCE_DIR/recent-executables.txt
find /tmp -type f -mtime -1 2>/dev/null > $EVIDENCE_DIR/recent-tmp-files.txt
# System logs
cp /var/log/syslog $EVIDENCE_DIR/ 2>/dev/null
cp /var/log/auth.log $EVIDENCE_DIR/ 2>/dev/null
cp /var/log/daemon.log $EVIDENCE_DIR/ 2>/dev/null
emergency_log "Critical evidence collected in $EVIDENCE_DIR"
}
# Function to quarantine suspicious files
quarantine_threats() {
emergency_log "Quarantining identified threats..."
QUARANTINE_DIR="/quarantine/emergency-$(date +%s)"
mkdir -p $QUARANTINE_DIR
# Move files from common malware locations
for dir in "/tmp" "/var/tmp" "/dev/shm"; do
find $dir -type f -executable -mtime -1 2>/dev/null | while read file; do
emergency_log "Quarantining: $file"
mv "$file" "$QUARANTINE_DIR/$(basename $file)-$(date +%s)"
done
done
# Quarantine files with suspicious names
find / -name "*.tmp.exe" -o -name "*.scr" -o -name "*backdoor*" 2>/dev/null | while read file; do
emergency_log "Quarantining suspicious file: $file"
mv "$file" "$QUARANTINE_DIR/$(basename $file)-$(date +%s)"
done
}
# Function to create forensic image
create_forensic_image() {
if command -v dd >/dev/null 2>&1; then
emergency_log "Creating forensic disk image..."
# Create compressed disk image of root partition
ROOT_DEV=$(df / | tail -1 | awk '{print $1}')
dd if=$ROOT_DEV | gzip > $EVIDENCE_DIR/forensic-image-$(hostname)-$(date +%s).gz &
DD_PID=$!
emergency_log "Forensic imaging started (PID: $DD_PID) for device: $ROOT_DEV"
echo $DD_PID > $EVIDENCE_DIR/forensic-imaging.pid
else
emergency_log "WARNING: dd not available for forensic imaging"
fi
}
# Main emergency response workflow
emergency_log "=== EMERGENCY RESPONSE ACTIVATED ==="
emergency_log "Lockdown mode: $LOCKDOWN_MODE"
emergency_log "Threat type: $THREAT_TYPE"
emergency_log "Evidence directory: $EVIDENCE_DIR"
# Step 1: Immediate evidence collection (before any changes)
collect_critical_evidence
# Step 2: Quarantine threats
quarantine_threats
# Step 3: Conditional lockdown
if [ "$LOCKDOWN_MODE" = "true" ]; then
initiate_lockdown
terminate_user_sessions
stop_services
fi
# Step 4: Create forensic evidence
create_forensic_image
# Step 5: Generate incident report
INCIDENT_REPORT="$EVIDENCE_DIR/incident-report.txt"
cat > $INCIDENT_REPORT << 'REPORT_EOF'
=== EMERGENCY INCIDENT REPORT ===
Timestamp: $(date)
Hostname: $(hostname)
Threat Type: $THREAT_TYPE
Lockdown Active: $LOCKDOWN_MODE
Response Actions Taken:
1. Critical evidence collected
2. Suspicious files quarantined
3. Network lockdown: $([ "$LOCKDOWN_MODE" = "true" ] && echo "ACTIVE" || echo "NOT APPLIED")
4. User sessions terminated: $([ "$LOCKDOWN_MODE" = "true" ] && echo "YES" || echo "NO")
5. Services stopped: $([ "$LOCKDOWN_MODE" = "true" ] && echo "YES" || echo "NO")
6. Forensic imaging: $([ -f "$EVIDENCE_DIR/forensic-imaging.pid" ] && echo "IN PROGRESS" || echo "NOT STARTED")
Evidence Location: $EVIDENCE_DIR
Total Evidence Files: $(ls -1 $EVIDENCE_DIR | wc -l)
Next Steps Required:
1. Contact incident response team
2. Review collected evidence
3. Determine recovery procedures
4. Update security controls
Contact Information:
- Security Team: security@company.com
- IT Manager: it-manager@company.com
- Emergency Contact: +1-XXX-XXX-XXXX
REPORT_EOF
# Step 6: Send emergency notification
emergency_log "Sending emergency notification..."
echo "$(cat $INCIDENT_REPORT)" | mail -s "EMERGENCY: Security Incident on $(hostname)" security@company.com
emergency_log "=== EMERGENCY RESPONSE COMPLETE ==="
emergency_log "Incident report available: $INCIDENT_REPORT"
# Display summary to console
echo ""
echo "=== EMERGENCY RESPONSE SUMMARY ==="
echo "Evidence collected in: $EVIDENCE_DIR"
echo "Incident report: $INCIDENT_REPORT"
echo "Lockdown status: $([ "$LOCKDOWN_MODE" = "true" ] && echo "ACTIVE" || echo "INACTIVE")"
echo ""
echo "To recover from lockdown:"
echo "sudo iptables -F && sudo iptables -P INPUT ACCEPT && sudo iptables -P OUTPUT ACCEPT"
echo ""
EOF
sudo chmod +x /usr/local/bin/emergency-response.sh
# Create emergency response aliases
echo 'alias emergency-lockdown="sudo /usr/local/bin/emergency-response.sh true malware"' >> ~/.bashrc
echo 'alias emergency-collect="sudo /usr/local/bin/emergency-response.sh false investigation"' >> ~/.bashrc
Troubleshooting Detection Issues
Common False Positives
Detection tools occasionally generate false positive alerts that require systematic investigation. Moreover, understanding false positive patterns helps optimize detection accuracy while maintaining security effectiveness.
| Issue | Symptoms | Diagnosis | Resolution |
|---|---|---|---|
| ClamAV false positives | Clean files quarantined | Check signature version | Update signatures, allowlist files |
| rkhunter warnings | System file changes | Verify legitimate updates | Update file database: rkhunter --propupd |
| chkrootkit alerts | Process name matches | Check process legitimacy | Investigate parent process and file origin |
| AIDE modifications | Unexpected file changes | Review change logs | Update baseline after verification |
# False positive investigation script
sudo tee /usr/local/bin/investigate-alert.sh << 'EOF'
#!/bin/bash
if [ $# -ne 2 ]; then
echo "Usage: $0 <tool_name> <file_or_process>"
echo "Examples:"
echo " $0 clamav /home/user/document.pdf"
echo " $0 rkhunter /usr/bin/find"
echo " $0 chkrootkit suspicious_process"
exit 1
fi
TOOL="$1"
TARGET="$2"
INVESTIGATION_LOG="/var/log/false-positive-investigation.log"
# Function to log investigation steps
log_investigation() {
echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" | tee -a $INVESTIGATION_LOG
}
log_investigation "=== Starting False Positive Investigation ==="
log_investigation "Tool: $TOOL"
log_investigation "Target: $TARGET"
case $TOOL in
"clamav")
log_investigation "Investigating ClamAV detection..."
# Check file type and properties
file "$TARGET" | tee -a $INVESTIGATION_LOG
ls -la "$TARGET" | tee -a $INVESTIGATION_LOG
# Check signature details
clamscan --debug "$TARGET" 2>&1 | grep -E "(FOUND|signature)" | tee -a $INVESTIGATION_LOG
# Submit to VirusTotal (if available)
HASH=$(sha256sum "$TARGET" | cut -d' ' -f1)
log_investigation "File SHA256: $HASH"
log_investigation "Submit to VirusTotal: https://www.virustotal.com/gui/file/$HASH"
;;
"rkhunter")
log_investigation "Investigating rkhunter warning..."
# Check file properties
file "$TARGET" | tee -a $INVESTIGATION_LOG
ls -la "$TARGET" | tee -a $INVESTIGATION_LOG
stat "$TARGET" | tee -a $INVESTIGATION_LOG
# Check package management
if command -v dpkg >/dev/null 2>&1; then
dpkg -S "$TARGET" 2>&1 | tee -a $INVESTIGATION_LOG
elif command -v rpm >/dev/null 2>&1; then
rpm -qf "$TARGET" 2>&1 | tee -a $INVESTIGATION_LOG
fi
# Check rkhunter database
rkhunter --check --enable file_properties --file "$TARGET" | tee -a $INVESTIGATION_LOG
;;
"chkrootkit")
log_investigation "Investigating chkrootkit alert..."
# If it's a process, analyze it
if pgrep "$TARGET" >/dev/null; then
PID=$(pgrep "$TARGET" | head -1)
log_investigation "Process PID: $PID"
ps -p $PID -o pid,ppid,user,cmd | tee -a $INVESTIGATION_LOG
lsof -p $PID | tee -a $INVESTIGATION_LOG
# Check binary
BINARY=$(readlink /proc/$PID/exe)
log_investigation "Binary path: $BINARY"
file "$BINARY" | tee -a $INVESTIGATION_LOG
ls -la "$BINARY" | tee -a $INVESTIGATION_LOG
fi
;;
"aide")
log_investigation "Investigating AIDE file changes..."
# Show detailed file information
ls -la "$TARGET" | tee -a $INVESTIGATION_LOG
stat "$TARGET" | tee -a $INVESTIGATION_LOG
# Check recent package changes
if command -v dpkg >/dev/null 2>&1; then
dpkg -S "$TARGET" 2>/dev/null | tee -a $INVESTIGATION_LOG
grep "$(basename $TARGET)" /var/log/dpkg.log | tail -5 | tee -a $INVESTIGATION_LOG
fi
# Compare with AIDE database
aide --compare --file="$TARGET" | tee -a $INVESTIGATION_LOG
;;
*)
log_investigation "Unknown tool: $TOOL"
log_investigation "Performing generic investigation..."
# Generic file analysis
if [ -f "$TARGET" ]; then
file "$TARGET" | tee -a $INVESTIGATION_LOG
ls -la "$TARGET" | tee -a $INVESTIGATION_LOG
# Check if it's executable
if [ -x "$TARGET" ]; then
strings "$TARGET" | head -20 | tee -a $INVESTIGATION_LOG
fi
fi
;;
esac
# Final recommendations
log_investigation "=== Investigation Recommendations ==="
case $TOOL in
"clamav")
log_investigation "ClamAV: Check signature database version and consider whitelisting if legitimate"
;;
"rkhunter")
log_investigation "rkhunter: Update file properties database if changes are legitimate"
;;
"chkrootkit")
log_investigation "chkrootkit: Verify process legitimacy through parent process analysis"
;;
"aide")
log_investigation "AIDE: Update baseline if changes are from legitimate updates"
;;
esac
log_investigation "=== Investigation Complete ==="
echo "Investigation results logged to: $INVESTIGATION_LOG"
EOF
sudo chmod +x /usr/local/bin/investigate-alert.sh
Performance Optimization
Detection system performance optimization ensures comprehensive security monitoring without system degradation. Furthermore, optimized detection maintains security effectiveness while minimizing resource consumption.
# Detection performance tuning script
sudo tee /usr/local/bin/optimize-detection.sh << 'EOF'
#!/bin/bash
OPTIMIZATION_LOG="/var/log/detection-optimization.log"
# Function to log optimization actions
log_optimization() {
echo "$(date '+%Y-%m-%d %H:%M:%S'): $1" | tee -a $OPTIMIZATION_LOG
}
log_optimization "=== Starting Detection System Optimization ==="
# 1. ClamAV optimization
log_optimization "Optimizing ClamAV configuration..."
# Backup original configuration
cp /etc/clamav/clamd.conf /etc/clamav/clamd.conf.backup
# Optimize ClamAV settings
tee -a /etc/clamav/clamd.conf << 'CLAMAV_EOF'
# Performance optimizations
MaxDirectoryRecursion 20
MaxFiles 50000
MaxFileSize 100M
MaxScanSize 500M
MaxEmbeddedPE 40M
MaxHTMLNormalize 40M
MaxHTMLNoTags 2M
MaxScriptNormalize 5M
MaxZipTypeRcg 1M
# Scanning optimizations
ScanPE yes
ScanELF yes
DetectBrokenExecutables yes
ScanOLE2 yes
ScanPDF yes
ScanSWF yes
ScanXMLDOCS yes
ScanHWP3 yes
ScanArchive yes
# Memory and CPU optimizations
DatabaseDirectory /var/lib/clamav
TemporaryDirectory /tmp
ThreadTimeout 300
ReadTimeout 300
CLAMAV_EOF
log_optimization "ClamAV configuration optimized"
# 2. rkhunter optimization
log_optimization "Optimizing rkhunter configuration..."
# Create optimized rkhunter configuration
tee -a /etc/rkhunter.conf.local << 'RKHUNTER_EOF'
# Performance optimizations
PKGMGR=DPKG
UPDATE_MIRRORS=1
MIRRORS_MODE=0
WEB_CMD=""
# Reduce false positives
SCRIPTWHITELIST=/usr/bin/groups
SCRIPTWHITELIST=/usr/bin/ldd
SCRIPTWHITELIST=/usr/bin/which
SCRIPTWHITELIST=/usr/sbin/adduser
# Disable resource-intensive tests for scheduled runs
DISABLE_TESTS="suspscan"
# Optimize logging
APPEND_LOG=1
COPY_LOG_ON_ERROR=0
RKHUNTER_EOF
log_optimization "rkhunter configuration optimized"
# 3. AIDE optimization
log_optimization "Optimizing AIDE configuration..."
# Backup AIDE configuration
cp /etc/aide/aide.conf /etc/aide/aide.conf.backup
# Optimize AIDE rules for better performance
tee -a /etc/aide/aide.conf << 'AIDE_EOF'
# Optimized monitoring rules
# Quick checks for critical directories
/etc p+i+n+u+g+s+b+m+c+sha256
/bin p+i+n+u+g+s+b+m+c+sha256
/sbin p+i+n+u+g+s+b+m+c+sha256
/usr/bin p+i+n+u+g+s+b+m+c+sha256
/usr/sbin p+i+n+u+g+s+b+m+c+sha256
# Exclude frequently changing directories to improve performance
!/proc
!/sys
!/dev
!/tmp
!/var/tmp
!/var/log
!/var/cache
!/home/*/.cache
!/var/lib/apt
!/var/lib/dpkg
AIDE_EOF
log_optimization "AIDE configuration optimized"
# 4. System resource optimization
log_optimization "Optimizing system resources for detection..."
# Create nice levels for detection processes
tee /etc/security/limits.d/malware-detection.conf << 'LIMITS_EOF'
# Nice levels for malware detection tools
* soft nice -5
* hard nice -5
# I/O scheduling for detection tools
* soft priority 4
* hard priority 4
LIMITS_EOF
# Optimize scheduled scan times to avoid conflicts
log_optimization "Optimizing scan schedules..."
# Remove existing detection cron jobs
crontab -l | grep -v -E "(clamscan|rkhunter|chkrootkit|aide)" | crontab -
# Create optimized scanning schedule
tee /etc/cron.d/optimized-malware-detection << 'CRON_EOF'
# Optimized malware detection schedule
# ClamAV signature updates (multiple times daily)
0 */6 * * * clamav /usr/bin/freshclam --quiet
# Quick rkhunter check (daily, low priority)
30 2 * * * root /usr/bin/nice -n 10 /usr/bin/rkhunter --cronjob --check --quiet
# chkrootkit quick scan (daily, staggered)
45 2 * * * root /usr/bin/nice -n 10 /usr/sbin/chkrootkit > /dev/null 2>&1
# AIDE integrity check (weekly, low priority)
0 3 * * 0 root /usr/bin/nice -n 15 /usr/bin/aide --check --quiet
# Full system ClamAV scan (weekly, very low priority)
0 1 * * 0 root /usr/bin/nice -n 19 /usr/bin/ionice -c 3 /usr/bin/clamscan -r --quiet --infected /
# Monthly full rkhunter check with updates
0 4 1 * * root /usr/bin/rkhunter --update --check --cronjob --report-warnings-only
CRON_EOF
log_optimization "Optimized scan schedules configured"
# 5. File system optimization
log_optimization "Configuring file system optimizations..."
# Configure tmpfs for temporary scanning operations
if ! grep -q "/tmp/malware-scan" /etc/fstab; then
echo "tmpfs /tmp/malware-scan tmpfs defaults,size=1G,mode=1777 0 0" >> /etc/fstab
mkdir -p /tmp/malware-scan
mount /tmp/malware-scan
log_optimization "Temporary scanning directory configured in RAM"
fi
# 6. Network optimization
log_optimization "Optimizing network monitoring..."
# Configure kernel parameters for better network monitoring
tee /etc/sysctl.d/99-malware-detection.conf << 'SYSCTL_EOF'
# Optimize network monitoring for malware detection
net.core.netdev_max_backlog = 5000
net.core.rmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_default = 262144
net.core.wmem_max = 16777216
SYSCTL_EOF
sysctl -p /etc/sysctl.d/99-malware-detection.conf
# 7. Log rotation optimization
log_optimization "Configuring log rotation for detection tools..."
# Configure logrotate for malware detection logs
tee /etc/logrotate.d/malware-detection << 'LOGROTATE_EOF'
/var/log/malware-detection.log {
weekly
rotate 12
compress
delaycompress
missingok
create 644 root root
postrotate
systemctl reload rsyslog > /dev/null 2>&1 || true
endscript
}
/var/log/network-monitor.log {
daily
rotate 7
compress
delaycompress
missingok
create 644 root root
}
/var/log/suspicious-processes.log {
daily
rotate 14
compress
delaycompress
missingok
create 644 root root
}
LOGROTATE_EOF
# 8. Create performance monitoring
log_optimization "Setting up performance monitoring..."
tee /usr/local/bin/detection-performance.sh << 'PERF_EOF'
#!/bin/bash
PERF_LOG="/var/log/detection-performance.log"
echo "=== Detection System Performance Report - $(date) ===" >> $PERF_LOG
# CPU usage of detection tools
ps aux | grep -E "(clam|rkhunter|chkrootkit|aide)" | grep -v grep >> $PERF_LOG
# Memory usage
free -h >> $PERF_LOG
# Disk I/O
iostat -x 1 1 | tail -n +4 >> $PERF_LOG
# Load average
uptime >> $PERF_LOG
echo "" >> $PERF_LOG
PERF_EOF
chmod +x /usr/local/bin/detection-performance.sh
# Schedule performance monitoring
echo "*/15 * * * * root /usr/local/bin/detection-performance.sh" >> /etc/cron.d/detection-performance
log_optimization "=== Detection System Optimization Complete ==="
# Display optimization summary
echo ""
echo "=== OPTIMIZATION SUMMARY ==="
echo "1. ClamAV: Performance settings optimized"
echo "2. rkhunter: False positives reduced, performance improved"
echo "3. AIDE: Monitoring rules optimized for speed"
echo "4. Scheduling: Scan times staggered to avoid conflicts"
echo "5. System: Resource limits and priorities configured"
echo "6. Storage: RAM-based temporary scanning directory"
echo "7. Logging: Rotation configured to prevent disk space issues"
echo "8. Monitoring: Performance tracking enabled"
echo ""
echo "Restart detection services to apply changes:"
echo "sudo systemctl restart clamav-daemon"
echo "sudo systemctl restart clamav-freshclam"
echo ""
echo "Optimization log: $OPTIMIZATION_LOG"
EOF
sudo chmod +x /usr/local/bin/optimize-detection.sh
FAQ Section
How often should I run malware scans on Linux?
The optimal scanning frequency depends on your security requirements and system usage patterns. Additionally, balanced scanning schedules provide comprehensive coverage without excessive resource consumption.
Recommended scanning schedule:
- Real-time monitoring: Continuous for critical systems
- Quick scans: Daily during off-peak hours
- Full system scans: Weekly for production systems, daily for high-risk environments
- Signature updates: Every 6 hours for antivirus databases
- Rootkit detection: Daily quick scans, weekly comprehensive scans
What are the signs of Linux malware infection?
Linux malware infections exhibit various symptoms that require systematic investigation. Moreover, early detection depends on recognizing subtle behavioral changes and system anomalies.
Primary infection indicators:
- Unexpected network activity or connections to unknown hosts
- Unusual process behavior or high CPU usage from unknown processes
- Modified system files or unexpected file changes
- Suspicious network listening ports or services
- Degraded system performance without apparent cause
- Unauthorized user accounts or privilege escalations
Can Linux malware be completely prevented?
While complete prevention remains challenging, layered security approaches significantly reduce infection risks. Therefore, comprehensive security strategies combine prevention, detection, and response capabilities.
Prevention strategies:
- Regular system updates and patch management
- Proper user privilege management and access controls
- Network segmentation and firewall protection
- Application allowlisting and execution controls
- Regular security training and awareness programs
- Backup and disaster recovery planning
How do I distinguish between false positives and real threats?
False positive identification requires systematic analysis combining multiple verification methods. Furthermore, experienced administrators develop pattern recognition skills through consistent investigation practices.
Verification techniques:
- Cross-reference detections with multiple scanning tools
- Analyze file signatures and submission to reputation services
- Review process behavior and network communications
- Examine file origins and installation history
- Consult threat intelligence databases and security communities
What should I do if multiple detection tools disagree?
Tool disagreements require careful analysis considering each tool's strengths and detection methodologies. Additionally, conflicting results often indicate sophisticated threats requiring advanced investigation techniques.
Resolution approaches:
- Prioritize tools with higher accuracy rates for specific threat types
- Perform manual analysis using static and dynamic techniques
- Submit samples to specialized analysis services
- Correlate findings with network and system behavior
- Consult security experts for complex cases
How can I improve detection accuracy while reducing false positives?
Detection accuracy improvement involves tool tuning, baseline establishment, and continuous refinement. Moreover, balanced configurations maintain security effectiveness while minimizing operational overhead.
Optimization strategies:
- Customize detection rules for specific environments
- Maintain updated tool configurations and signatures
- Establish system baselines for behavioral analysis
- Implement graduated alert levels and response procedures
- Regular review and tuning based on historical data
Additional Security Resources {#additional-resources}
External Authoritative Sources
Linux Security Organizations:
- Linux Foundation Security - Industry standards and best practices
- NIST Cybersecurity Framework - Comprehensive security guidance
- CIS Controls - Security control frameworks and benchmarks
Malware Analysis Resources:
- VirusTotal - Multi-engine malware analysis platform
- Hybrid Analysis - Advanced malware analysis environment
- YARA Rules - Pattern matching engine for malware research
Tool Documentation:
- ClamAV Documentation - Comprehensive antivirus configuration guide
- rkhunter Project - Rootkit detection tool resources
- AIDE Documentation - File integrity monitoring guidance
Related LinuxTips.pro Articles
Foundational Security Topics:
- Post #26: Linux Security Essentials - Hardening Your System
- Post #27: SELinux - Mandatory Access Control Explained
- Post #29: Fail2ban - Automated Intrusion Prevention
Advanced Monitoring and Analysis:
- Post #45: Linux Performance Troubleshooting Methodology
- Post #47: Log Analysis with ELK Stack
- Post #95: Log Analysis for Problem Resolution
Incident Response and Recovery:
- Post #97: Forensic Analysis - Investigating System Compromise
- Post #99: Security Patch Management
- Post #100: Linux Hardening Checklist - Complete Security Guide
This comprehensive guide provides system administrators with professional-grade Linux malware detection capabilities. Furthermore, implementing these security measures significantly enhances overall system protection against sophisticated threats while maintaining operational efficiency.