Node.js安全监控完全指南:攻防实战与运维监控教程

Node.js安全监控完全指南:攻防实战与运维监控教程

Node.js作为高性能的JavaScript运行时环境,广泛应用于Web应用、API服务、实时通信等场景。随着Node.js应用的普及,安全问题也日益突出。本文将从安全防护到监控运维,全面介绍Node.js应用的安全监控实践。

一、SSL证书与HTTPS安全

1.1 SSL证书类型详解

SSL证书根据验证级别和适用范围可分为三类:

类型 全称 验证级别 适用场景 价格
DV Domain Validation(域名型) 域名所有权验证 个人博客、测试环境 免费/低价
OV Organization Validation(组织型) 域名+组织身份验证 企业官网、电商平台 中等
EV Extended Validation(扩展型) 严格的企业身份验证 金融、银行、政务 较高

DV证书特点:

  • 自动签发,验证速度快
  • 浏览器显示小锁图标
  • 适合个人和非商业用途

OV证书特点:

  • 需要人工审核组织信息
  • 证书详情显示组织名称
  • 适合中小企业

EV证书特点:

  • 浏览器地址栏变绿
  • 显示企业名称
  • 提供最高级别的信任

1.2 Let’s Encrypt免费证书配置

Let’s Encrypt是一个免费、自动化、开放的证书颁发机构。

使用Certbot申请证书:

1
2
3
4
5
6
7
8
# 安装Certbot
yum install -y certbot python2-certbot-nginx

# 申请证书
certbot --nginx -d example.com -d www.example.com

# 自动续期测试
certbot renew --dry-run

Node.js HTTPS服务器配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const express = require('express');
const https = require('https');
const fs = require('fs');

const app = express();

// 读取SSL证书
const privateKey = fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/example.com/fullchain.pem', 'utf8');
const credentials = { key: privateKey, cert: certificate };

// 配置中间件
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));

// 路由配置
app.get('/', (req, res) => {
res.json({ message: 'Secure HTTPS Server' });
});

// 启动HTTPS服务
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(443, () => {
console.log('HTTPS Server running on port 443');
});

// HTTP重定向到HTTPS
const http = require('http');
http.createServer((req, res) => {
res.writeHead(301, { 'Location': 'https://' + req.headers['host'] + req.url });
res.end();
}).listen(80);

1.3 沃通免费SSL证书申请

申请步骤:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1. 注册沃通账号
↓ https://login.wosign.com/login.html

2. 申请免费SSL证书
↓ https://buy.wosign.com/free/FreeSSL.html#ssl

3. 域名验证
↓ 下载验证文件并上传到服务器web根目录

4. 完成验证
↓ 等待审核通过

5. 下载证书
↓ 获取for Nginx格式的证书文件

6. 部署到Node.js
↓ 配置HTTPS服务

Node.js中使用沃通证书:

1
2
3
4
5
6
7
8
const options = {
key: fs.readFileSync('ssl/www.abc.net.key', 'utf8'),
cert: fs.readFileSync('ssl/www.abc.net.crt', 'utf8'),
// 如果使用中间证书,需要添加ca
ca: fs.readFileSync('ssl/ca.crt', 'utf8')
};

https.createServer(options, app).listen(443);

二、网络攻击原理与防御

2.1 DDOS攻击类型与原理

DDOS(分布式拒绝服务)攻击通过大量恶意流量使服务器瘫痪。

攻击原理图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
攻击者

│ 控制

┌───────────────────────────────────┐
│ 僵尸网络 │
│ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │
│ │肉鸡1│ │肉鸡2│ │肉鸡3│ │肉鸡N│ │
│ └──┬──┘ └──┬──┘ └──┬──┘ └──┬──┘ │
└─────┼───────┼───────┼───────┼────┘
│ │ │ │
└───────┴───┬───┴───────┘

目标服务器
┌───────────┐
│ 带宽耗尽 │
│ 资源耗尽 │
│ 服务瘫痪 │
└───────────┘

常见DDOS攻击方法:

攻击类型 原理 特点
SYN Flood 发送大量SYN包不完成握手 消耗TCP连接资源
UDP Flood 发送大量UDP数据包 消耗带宽和处理能力
HTTP Flood 发送大量HTTP请求 难以与正常流量区分
Slowloris 慢速发送HTTP请求头 保持连接不释放
CC攻击 模拟真实用户访问 针对应用层,最难防御

2.2 SYN变种攻击详解

攻击机制:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
正常TCP三次握手:
客户端 ──SYN──→ 服务器
客户端 ←─SYN+ACK── 服务器
客户端 ──ACK──→ 服务器

连接建立

SYN Flood攻击:
攻击者 ──SYN──→ 服务器(伪造源IP)
攻击者 ←─SYN+ACK── 服务器

攻击者不回应ACK

服务器半连接队列满

无法处理正常连接

防御措施:

1
2
3
4
5
6
7
8
9
10
11
# 启用SYN Cookies
sysctl -w net.ipv4.tcp_syncookies=1

# 缩短SYN超时时间
sysctl -w net.ipv4.tcp_synack_retries=2

# 增大半连接队列
sysctl -w net.ipv4.tcp_max_syn_backlog=65535

# 启用SYN洪水保护
sysctl -w net.ipv4.tcp_syncookies=1

2.3 CC攻击防御

CC攻击通过模拟大量真实用户访问消耗服务器资源。

攻击特征:

  • 来自大量真实IP
  • 访问正常URL
  • 请求频率有规律
  • 难以通过IP封禁防御

防御策略:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Node.js限流中间件
const rateLimit = require('express-rate-limit');

// 基础限流
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 每个IP限制100次请求
message: 'Too many requests from this IP'
});

// 严格限流(针对敏感接口)
const strictLimiter = rateLimit({
windowMs: 60 * 1000, // 1分钟
max: 10,
skipSuccessfulRequests: true
});

app.use('/api/', apiLimiter);
app.use('/api/login', strictLimiter);

基于令牌桶的限流:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class TokenBucket {
constructor(capacity, refillRate) {
this.capacity = capacity; // 桶容量
this.tokens = capacity; // 当前令牌数
this.refillRate = refillRate; // 每秒填充速率
this.lastRefill = Date.now();
}

refill() {
const now = Date.now();
const timePassed = (now - this.lastRefill) / 1000;
this.tokens = Math.min(
this.capacity,
this.tokens + timePassed * this.refillRate
);
this.lastRefill = now;
}

consume(tokens = 1) {
this.refill();
if (this.tokens >= tokens) {
this.tokens -= tokens;
return true;
}
return false;
}
}

// 应用限流
const buckets = new Map();

function rateLimitMiddleware(req, res, next) {
const ip = req.ip;
if (!buckets.has(ip)) {
buckets.set(ip, new TokenBucket(100, 10)); // 容量100,每秒10个
}

const bucket = buckets.get(ip);
if (bucket.consume()) {
next();
} else {
res.status(429).json({ error: 'Rate limit exceeded' });
}
}

三、高防服务器与防御方案

3.1 高防服务器防御机制

高防服务器通过多层防护抵御大规模攻击。

防御体系:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
┌─────────────────────────────────────────────┐
│ 第一层:骨干节点防护 │
│ ┌─────────────────────────────────────┐ │
│ │ • 定期安全扫描 │ │
│ │ • 流量清洗(清洗中心) │ │
│ │ • 异常流量过滤 │ │
│ └─────────────────────────────────────┘ │
└───────────────────┬─────────────────────────┘

┌─────────────────────────────────────────────┐
│ 第二层:防火墙防护 │
│ ┌─────────────────────────────────────┐ │
│ │ • 480G+ DDOS防御 │ │
│ │ • CC攻击防护 │ │
│ │ • 协议异常检测 │ │
│ └─────────────────────────────────────┘ │
└───────────────────┬─────────────────────────┘

┌─────────────────────────────────────────────┐
│ 第三层:服务器防护 │
│ ┌─────────────────────────────────────┐ │
│ │ • 带宽冗余(抵御带宽消耗攻击) │ │
│ │ • IP/端口过滤 │ │
│ │ • 真实IP隐藏 │ │
│ └─────────────────────────────────────┘ │
└─────────────────────────────────────────────┘

3.2 高防服务器选择标准

指标 要求 说明
机房带宽 >100G 足够的带宽应对流量攻击
防御能力 单机10G-480G 根据业务规模选择
防火墙 集群防火墙 分布式防护能力
服务器品牌 DELL/HP等品牌 保证硬件稳定性
线路质量 电信/BGP 低延迟高可用

3.3 企业级防御方案

运营商级防护(最彻底方案):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
                    运营商网络

┌───────────────┼───────────────┐
↓ ↓ ↓
移动线路 联通线路 电信线路
┌─────┐ ┌─────┐ ┌─────┐
│省级 │ │省级 │ │省级 │
│接入 │ │接入 │ │接入 │
└──┬──┘ └──┬──┘ └──┬──┘
└──────────────┼──────────────┘

┌───────────────┐
│ 清洗中心 │
│ 攻击流量过滤 │
└───────┬───────┘

┌───────────────┐
│ 源站服务器 │
└───────────────┘

优势:攻击在运营商层面就被拦截,不会到达源站
成本:比云厂商高防服务更便宜

四、服务器入侵检测与防御

4.1 入侵检测清单

登录检查:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 查看当前登录用户
w

# 查看登录历史
last

# 查看失败登录
lastb

# 查看特定用户登录历史
lastlog -u username

# 查看SSH登录日志
tail -f /var/log/secure

进程检查:

1
2
3
4
5
6
7
8
9
10
11
12
# 查看所有进程
ps auxf

# 查看资源占用
# 关注CPU/内存异常高的进程
top -c

# 查看进程打开的文件
lsof -p PID

# 追踪系统调用
strace -p PID

网络连接检查:

1
2
3
4
5
6
7
8
9
10
11
# 查看网络连接
netstat -plunt

# 查看TCP连接状态统计
netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'

# 查看端口监听
ss -tlnp

# 实时监控网络流量
iftop

4.2 发现入侵后的应急处理

紧急响应流程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
发现异常

立即隔离(只保留你的IP访问)

├─ 修改防火墙规则:只允许你的IP访问SSH
├─ 保存现场(不要重启或修复)
└─ 记录所有可疑进程和连接

数据备份

├─ 备份重要数据到安全位置
└─ 注意:程序可能已经不可信,只备份数据

系统重建

├─ 不要尝试修复,直接重装系统
└─ 恢复数据并加强安全配置

安全加固

重新上线

立即执行的防火墙规则:

1
2
3
4
5
6
7
# 只允许你的IP访问SSH(假设你的IP是1.2.3.4)
iptables -A INPUT -p tcp --dport 22 -s 1.2.3.4 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP

# 封禁其他所有访问(除了已建立的连接)
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -P INPUT DROP

4.3 SSH安全加固

安全SSH配置:

1
2
# 编辑SSH配置文件
vi /etc/ssh/sshd_config

推荐配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 修改默认端口
Port 2222

# 禁止root登录
PermitRootLogin no

# 使用密钥认证,禁用密码
PubkeyAuthentication yes
PasswordAuthentication no

# 限制登录用户
AllowUsers admin deploy

# 空闲超时断开
ClientAliveInterval 300
ClientAliveCountMax 2

# 最大尝试次数
MaxAuthTries 3

# 仅允许IPv4
AddressFamily inet

使用Fail2ban自动封禁:

1
2
3
4
5
# 安装Fail2ban
yum install -y fail2ban

# 配置SSH防护
vi /etc/fail2ban/jail.local
1
2
3
4
5
6
7
8
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/secure
maxretry = 3
bantime = 3600
findtime = 600

4.4 防暴力破解方案

iptables自动封禁脚本:

1
2
3
4
# 限制SSH连接频率
iptables -A INPUT -p tcp --dport 22 -m recent --name ROUTER-SSH --update --seconds 300 --hitcount 3 -j DROP
iptables -A INPUT -p tcp --dport 22 -m recent --name ROUTER-SSH --set -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m limit --limit 3/hour --limit-burst 3 -j ACCEPT

密码策略:

1
2
3
4
5
6
7
8
9
10
# 设置密码复杂度
vi /etc/security/pwquality.conf

# 配置项:
minlen = 14 # 最小长度14位
minclass = 4 # 必须包含4种字符类型
dcredit = -1 # 至少1个数字
ucredit = -1 # 至少1个大写字母
lcredit = -1 # 至少1个小写字母
ocredit = -1 # 至少1个特殊字符

五、过载保护与流量控制

5.1 过载保护概念

过载原因:

  • 处理能力下降(硬件故障、代码问题)
  • 请求量上升(突发流量、攻击)

保护行为三阶段:

1
2
3
4
5
6
7
8
9
┌─────────────┐    ┌─────────────┐    ┌─────────────┐
│ 过载前 │ │ 过载时 │ │ 过载后 │
│ 预防 │ │ 处置 │ │ 恢复 │
├─────────────┤ ├─────────────┤ ├─────────────┤
│• 优化服务 │ │• 限流控制 │ │• 自动恢复 │
│• 负载均衡 │ │• 请求丢弃 │ │• 慢启动 │
│• 前端防御 │ │• 服务降级 │ │• 监控观察 │
│• 缓冲区设计 │ │• 熔断保护 │ │ │
└─────────────┘ └─────────────┘ └─────────────┘

5.2 Node.js过载保护实现

基于连接数限流:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class OverloadProtection {
constructor(options = {}) {
this.maxConnections = options.maxConnections || 1000;
this.maxQPS = options.maxQPS || 1000;
this.currentConnections = 0;
this.currentQPS = 0;
this.qpsResetInterval = options.qpsResetInterval || 1000;

// 定时重置QPS计数
setInterval(() => {
this.currentQPS = 0;
}, this.qpsResetInterval);
}

// 检查是否过载
isOverloaded() {
return this.currentConnections > this.maxConnections ||
this.currentQPS > this.maxQPS;
}

// 记录新连接
acquire() {
if (this.isOverloaded()) {
return false;
}
this.currentConnections++;
this.currentQPS++;
return true;
}

// 释放连接
release() {
this.currentConnections = Math.max(0, this.currentConnections - 1);
}
}

// 应用中间件
const protection = new OverloadProtection({
maxConnections: 5000,
maxQPS: 3000
});

app.use((req, res, next) => {
if (!protection.acquire()) {
res.status(503).json({
error: 'Server overloaded',
retryAfter: 5
});
return;
}

res.on('finish', () => {
protection.release();
});

next();
});

基于延时的过载检测:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 基于请求处理时长的过载检测
class LatencyBasedProtection {
constructor(options = {}) {
this.maxLatency = options.maxLatency || 5000; // 5秒
this.checkInterval = options.checkInterval || 1000;
this.latencies = [];
}

recordLatency(latency) {
this.latencies.push({
timestamp: Date.now(),
value: latency
});

// 清理过期数据
const cutoff = Date.now() - 60000; // 保留1分钟
this.latencies = this.latencies.filter(l => l.timestamp > cutoff);
}

// 计算P99延迟
getP99Latency() {
if (this.latencies.length === 0) return 0;

const sorted = this.latencies
.map(l => l.value)
.sort((a, b) => a - b);

const index = Math.floor(sorted.length * 0.99);
return sorted[index];
}

isOverloaded() {
return this.getP99Latency() > this.maxLatency;
}
}

5.3 服务降级策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// 降级策略管理器
class DegradationManager {
constructor() {
this.strategies = new Map();
this.isDegraded = false;
}

register(name, strategy) {
this.strategies.set(name, strategy);
}

// 触发降级
degrade() {
if (this.isDegraded) return;
this.isDegraded = true;

console.log('Service degradation activated');
for (const [name, strategy] of this.strategies) {
strategy.onDegrade();
}
}

// 恢复服务
recover() {
if (!this.isDegraded) return;
this.isDegraded = false;

console.log('Service recovered');
for (const [name, strategy] of this.strategies) {
strategy.onRecover();
}
}
}

// 具体降级策略
const degradationManager = new DegradationManager();

// 关闭非核心功能
degradationManager.register('nonEssential', {
onDegrade: () => {
// 关闭推荐、统计等功能
app.disable('/api/recommendations');
app.disable('/api/statistics');
},
onRecover: () => {
app.enable('/api/recommendations');
app.enable('/api/statistics');
}
});

// 简化响应
degradationManager.register('simplifyResponse', {
onDegrade: () => {
app.use('/api/products', (req, res, next) => {
// 只返回核心字段
req.simplifiedResponse = true;
next();
});
},
onRecover: () => {
app.use('/api/products', (req, res, next) => {
req.simplifiedResponse = false;
next();
});
}
});

六、运维监控体系

6.1 Open-Falcon监控系统

Open-Falcon是小米开源的企业级监控系统。

架构组件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
┌─────────────────────────────────────────────────────┐
│ 数据采集层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │falcon-agent│ │User Push│ │SNMP │ │Plugin │ │
│ └────┬────┘ └────┬────┘ └────┬────┘ └────┬────┘ │
└───────┼────────────┼────────────┼────────────┼──────┘
└────────────┴──────┬─────┴────────────┘

┌─────────────────────────────────────────────────────┐
│ 数据传输层 │
│ ┌───────────────────────────────────────────────┐ │
│ │ Transfer(数据转发) │ │
│ └────────────────────┬──────────────────────────┘ │
└───────────────────────┼─────────────────────────────┘

┌─────────────────────────────────────────────────────┐
│ 数据处理层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Judge │ │ Graph │ │ Index │ │ Alarm │ │
│ │(告警判断)│ │(时序存储)│ │(索引) │ │(告警) │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────┐
│ 展示层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Dashboard│ │ Portal │ │ Query │ │
│ │(仪表盘) │ │(配置门户)│ │(查询) │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────────────┘

核心特性:

  • 单机支持200万metric上报
  • 秒级返回上百metric一年的历史数据
  • 高可用无单点设计
  • 支持多种数据采集方式

6.2 Node.js应用监控

自定义指标上报:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const http = require('http');

class FalconClient {
constructor(endpoint) {
this.endpoint = endpoint;
}

push(metric, value, tags = {}) {
const data = [{
endpoint: this.endpoint,
metric: metric,
timestamp: Math.floor(Date.now() / 1000),
step: 60,
value: value,
counterType: 'GAUGE',
tags: Object.entries(tags).map(([k, v]) => `${k}=${v}`).join(',')
}];

// 发送给Agent
const options = {
hostname: '127.0.0.1',
port: 1988,
path: '/v1/push',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};

const req = http.request(options);
req.write(JSON.stringify(data));
req.end();
}
}

// 应用监控
const falcon = new FalconClient('nodejs-app');

// 监控HTTP请求
app.use((req, res, next) => {
const start = Date.now();

res.on('finish', () => {
const duration = Date.now() - start;

// 上报响应时间
falcon.push('api.response.time', duration, {
method: req.method,
route: req.route.path
});

// 上报状态码
falcon.push('api.status.code', 1, {
status: res.statusCode
});
});

next();
});

// 定时上报系统指标
setInterval(() => {
const memUsage = process.memoryUsage();

falcon.push('process.memory.rss', memUsage.rss);
falcon.push('process.memory.heapUsed', memUsage.heapUsed);
falcon.push('process.memory.heapTotal', memUsage.heapTotal);

// CPU使用率需要计算
const cpuUsage = process.cpuUsage();
falcon.push('process.cpu.user', cpuUsage.user);
falcon.push('process.cpu.system', cpuUsage.system);
}, 60000);

6.3 日志收集与分析

Exceptionless日志收集:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const { ExceptionlessClient } = require('exceptionless');

const client = new ExceptionlessClient('your-api-key', 'https://collector.exceptionless.io');

// 提交错误
app.use((err, req, res, next) => {
client.submitError(err, {
user: req.user?.id,
tags: [req.path, req.method],
data: {
request: {
path: req.path,
method: req.method,
query: req.query,
body: req.body
}
}
});

res.status(500).json({ error: 'Internal Server Error' });
});

// 提交自定义事件
function trackEvent(eventName, data) {
client.submitEvent({
type: 'custom',
message: eventName,
data: data
});
}

6.4 流量监控工具bwm-ng

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 安装bwm-ng
wget https://www.gropp.org/bwm-ng/bwm-ng-0.6.2.tar.gz
tar -xzf bwm-ng-0.6.2.tar.gz
cd bwm-ng-0.6.2
./configure && make && make install

# 启动监控
bwm-ng

# 显示格式
# iface: 网络接口
# bytes_out/s: 每秒发送字节数
# bytes_in/s: 每秒接收字节数
# total_out: 总发送字节数
# total_in: 总接收字节数

七、杀毒与安全防护

7.1 ClamAV开源杀毒软件

安装配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 安装ClamAV
yum install epel-release -y
yum install clamav-server clamav-data clamav-update clamav-filesystem \
clamav clamav-scanner-systemd clamav-devel clamav-lib clamav-server-systemd -y

# 配置扫描服务
sed -i -e "s/^Example/#Example/" /etc/clamd.d/scan.conf
sed -i -e "s/^Example/#Example/" /etc/freshclam.conf

# 更新病毒库
freshclam

# 启动服务
systemctl start clamd@scan
systemctl enable clamd@scan

定期扫描脚本:

1
2
3
4
5
6
7
8
9
10
#!/bin/bash

# 全盘扫描
clamscan -r / --infected --remove=no --log=/var/log/clamscan.log

# 扫描特定目录并自动删除病毒
clamscan -r /var/www --infected --remove=yes --log=/var/log/clamscan-www.log

# 扫描并移动病毒文件到隔离区
clamscan -r /tmp --infected --move=/var/quarantine --log=/var/log/clamscan-tmp.log

7.2 安全扫描工具

Nmap端口扫描:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 安装nmap
yum install nmap -y

# 基础扫描
nmap 192.168.1.1

# 扫描所有端口
nmap -p- 192.168.1.1

# 扫描并检测服务版本
nmap -sV 192.168.1.1

# 扫描并检测操作系统
nmap -O 192.168.1.1

# 全面扫描
nmap -sV -O -p- 192.168.1.1

SQL注入检测(sqlmap):

1
2
3
4
5
6
7
8
# 检测GET请求
sqlmap -u "http://example.com/page?id=1"

# 检测POST请求
sqlmap -u "http://example.com/login" --data="username=admin&password=test"

# 检测Cookie注入
sqlmap -u "http://example.com/page" --cookie="id=1"

八、总结

Node.js应用的安全监控是一个系统工程,需要从多个层面进行防护:

安全层面:

  1. 传输安全:使用HTTPS/SSL加密通信
  2. 攻击防护:防御DDOS/CC等各类攻击
  3. 服务器安全:SSH加固、入侵检测
  4. 应用安全:输入验证、权限控制

监控层面:

  1. 系统监控:CPU、内存、磁盘、网络
  2. 应用监控:QPS、响应时间、错误率
  3. 业务监控:关键业务指标
  4. 安全监控:异常登录、攻击检测

运维建议:

  • 建立完善的监控告警体系
  • 制定应急响应预案
  • 定期进行安全审计
  • 保持系统和依赖更新
  • 做好数据备份和恢复演练

通过建立纵深防御体系和完善的监控机制,可以有效保障Node.js应用的安全稳定运行。