# 安装ModSecurity for Apache/Nginx
sudo apt-get install libapache2-mod-security2 # Apache
sudo apt-get install nginx-module-security # Nginx
# 配置OWASP核心规则集
git clone https://github.com/coreruleset/coreruleset.git
cp -r coreruleset/rules/ /etc/modsecurity/
{
"Name": "SQLiProtection",
"Priority": 1,
"Action": { "Block": {} },
"VisibilityConfig": {
"SampledRequestsEnabled": true,
"CloudWatchMetricsEnabled": true,
"MetricName": "SQLiProtection"
},
"Statement": {
"SqliMatchStatement": {
"FieldToMatch": { "AllQueryArguments": {} },
"TextTransformations": [
{ "Priority": 0, "Type": "URL_DECODE" }
]
}
}
}
# kong.yml 安全配置示例
plugins:
- name: rate-limiting
config:
minute: 100
policy: local
- name: key-auth
config:
key_names: ["apikey"]
hide_credentials: true
- name: bot-detection
config:
allow: ["googlebot"]
deny: ["curl", "wget"]
# 使用OpenSSL生成JWT密钥
openssl genrsa -out jwt-private.key 2048
openssl rsa -in jwt-private.key -pubout -out jwt-public.key
# 安装SPIRE服务器
wget https://github.com/spiffe/spire/releases/download/v1.5.0/spire-1.5.0-linux-x86_64.tar.gz
tar -xvf spire-1.5.0-linux-x86_64.tar.gz
cd spire-1.5.0/bin/
# 启动SPIRE服务器
./spire-server run -config /opt/spire/conf/server/server.conf
// Go语言mTLS客户端示例
cert, err := tls.LoadX509KeyPair("client.crt", "client.key")
if err != nil {
log.Fatal(err)
}
caCert, err := os.ReadFile("ca.crt")
if err != nil {
log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
MinVersion: tls.VersionTLS13,
}
// Apollo Server深度限制插件
const depthLimit = require('graphql-depth-limit');
const server = new ApolloServer({
typeDefs,
resolvers,
validationRules: [depthLimit(5)],
context: ({ req }) => {
return {
user: req.user
};
}
});
// API请求模式定义
syntax = "proto3";
message APIRequest {
string user_id = 1 [(validate.rules).string.uuid = true];
int32 page = 2 [(validate.rules).int32.gt = 0];
string query = 3 [(validate.rules).string.max_len = 100];
}
# falco_rules.yaml 自定义规则
- rule: UnauthorizedProcessInWebServer
desc: Detect processes not whitelisted running in web server containers
condition: >
container.image contains "nginx" or container.image contains "apache"
and not proc.name in (nginx, apache2, sh, bash)
output: >
Unauthorized process (%proc.name) running in web server container
(user=%user.name container_id=%container.id container_name=%container.name)
priority: WARNING
-- 监控Web目录文件变化
SELECT * FROM file_events
WHERE path LIKE '/var/www/%'
AND timestamp > (SELECT strftime('%s', 'now') - 300;
# Python自动化扫描脚本
from zapv2 import ZAPv2
zap = ZAPv2(apikey='your-api-key', proxies={'http': 'http://localhost:8080'})
target = 'https://your-web-api.example.com'
scan_id = zap.ascan.scan(target)
while int(zap.ascan.status(scan_id)) < 100:
time.sleep(5)
report = zap.core.htmlreport()
with open('security_report.html', 'w') as f:
f.write(report)
# 使用RESTler进行模糊测试
docker run -it --rm -v $(pwd):/results mcr.microsoft.com/restler/restler \
restler --api_spec /openapi.json --settings /engine_settings.json \
--output_dir /results/fuzz_results
深度防御策略:组合使用网络层WAF、应用层验证和运行时保护
最小权限原则:
# 使用Linux能力而非root权限
setcap 'cap_net_bind_service=+ep' /usr/sbin/nginx
持续监控:实现SIEM集成
# 将审计日志转发到SIEM系统
auditctl -a always,exit -F arch=b64 -S execve -k web_exec
自动化证书管理:
# 使用Certbot自动续期
certbot renew --pre-hook "systemctl stop nginx" \
--post-hook "systemctl start nginx"
容器安全扫描:
# 使用Trivy扫描镜像
trivy image --severity HIGH,CRITICAL your-web-app:latest
这些先进技术的组合应用可以显著提升Linux服务器上Web接口的安全性,适应现代API驱动的架构需求。