侧边栏壁纸
博主头像
CYC的个人博客博主等级

学习使人进步

  • 累计撰写 113 篇文章
  • 累计创建 14 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

modsecurity+nginx守护域名安全

我是一条酸菜鱼
2026-02-09 / 0 评论 / 0 点赞 / 26 阅读 / 9295 字

modsecurity+nginx守护域名安全

本系统centos8

为了防止域名接口被频繁攻击,开源的modsecurtiy防火墙是个不错的产品,废话不多说直接上技术

install_modsecurity


#!/bin/bash

# 更新系统
dnf update -y

# 安装编译依赖
dnf install -y gcc gcc-c++ make automake autoconf libtool wget git zlib-devel pcre-devel openssl-devel GeoIP-devel yajl-devel curl-devel libxml2-devel

# 安装 ModSecurity v3
cd /tmp
git clone --depth 1 -b v3/master --single-branch https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
git submodule init
git submodule update
./build.sh
./configure
make
make install

# 下载 OWASP Core Rule Set
cd /etc
git clone https://github.com/coreruleset/coreruleset.git modsecurity-crs
cd modsecurity-crs
cp crs-setup.conf.example crs-setup.conf
cp rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf.example rules/REQUEST-900-EXCLUSION-RULES-BEFORE-CRS.conf
cp rules/RESPONSE-999-EXCLUSION-RULES-AFTER-CRS.conf.example rules/RESPONSE-999-EXCLUSION-RULES-AFTER-CRS.conf

# 创建 ModSecurity 配置文件
cat > /etc/modsecurity.conf << 'EOF'
# 包含 OWASP CRS 规则
Include /etc/modsecurity-crs/crs-setup.conf
Include /etc/modsecurity-crs/rules/*.conf


cp /data/yshop-server/ModSecurity/unicode.mapping  /etc/


# 基本配置
SecRuleEngine On
SecRequestBodyAccess On
SecRule REQUEST_HEADERS:Content-Type "text/xml" \
    "id:'200000',phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=XML"
SecRule REQUEST_HEADERS:Content-Type "application/json" \
    "id:'200001',phase:1,t:none,t:lowercase,pass,nolog,ctl:requestBodyProcessor=JSON"
SecRequestBodyLimit 13107200
#SecRequestBodyInMemoryLimit 131072
SecRequestBodyLimitAction Reject
SecRule REQBODY_ERROR "!@eq 0" \
    "id:'200002', phase:2,t:none,log,deny,status:400,msg:'Failed to parse request body.',logdata:'%{reqbody_error_msg}',severity:2"
SecRule MULTIPART_STRICT_ERROR "!@eq 0" \
    "id:'200003',phase:2,t:none,log,deny,status:400, \
    msg:'Multipart request body failed strict validation: \
    PE %{REQBODY_PROCESSOR_ERROR}, \
    BQ %{MULTIPART_BOUNDARY_QUOTED}, \
    BW %{MULTIPART_BOUNDARY_WHITESPACE}, \
    DB %{MULTIPART_DATA_BEFORE}, \
    DA %{MULTIPART_DATA_AFTER}, \
    HF %{MULTIPART_HEADER_FOLDING}, \
    LF %{MULTIPART_LF_LINE}, \
    SM %{MULTIPART_MISSING_SEMICOLON}, \
    IQ %{MULTIPART_INVALID_QUOTING}, \
    IP %{MULTIPART_INVALID_PART}, \
    IH %{MULTIPART_INVALID_HEADER_FOLDING}, \
    FL %{MULTIPART_FILE_LIMIT_EXCEEDED}'"
SecRule MULTIPART_UNMATCHED_BOUNDARY "!@eq 0" \
    "id:'200004',phase:2,t:none,log,deny,status:44, \
    msg:'Multipart parser detected a possible unmatched boundary.'"

SecResponseBodyAccess On
# 响应体检查限制 (512KB)
SecResponseBodyLimit 524288
# 响应体内存缓冲限制
SecResponseBodyLimitAction ProcessPartial
SecTmpDir /data/yshop-server/modsectmp
SecDataDir /data/yshop-server/modsectmp

# =============================
# ModSecurity Audit Log Configuration
# =============================

# 启用审计日志引擎
SecAuditEngine RelevantOnly

#最大单个审计日志文件大小 (100MB)
SecAuditLogRelevantStatus "^(?:5|4(?!04))"
#ABIJDEFHZ
# 审计日志分区格式
SecAuditLogParts ABCFHZ

#审计日志存储类型 序列
SecAuditLogType Serial

# 审计日志文件路径
SecAuditLog /data/yshop-server/modseclog/modsec_audit.log

# 自定义审计日志格式
#SecAuditLogFormat JSON

SecArgumentSeparator &
SecCookieFormat 0
SecUnicodeMapFile unicode.mapping 20127
SecCollectionTimeout 600


EOF



# 创建日志目录
mkdir -p /data/yshop-server/modsecuritylog/
touch /data/yshop-server/modseclog/modsec_audit.log
chmod 644  /data/yshop-server/modseclog/modsec_audit.log



权限相关
#放开路径权限
#SecRule REQUEST_URI "@beginsWith /yourapipath" "id:200005,phase:1,pass,nolog,ctl:ruleRemoveById=953120"
#SecRule REQUEST_URI "@beginsWith /yourapipath" "id:200006,phase:1,pass,nolog,ctl:ruleRemoveById=959100"



echo "ModSecurity 安装完成,请手动配置 Nginx 以加载 ModSecurity 模块"

nginx_install

如果用到其他反向代理请注意自己的版本是否对应

njs-master.zip

ModSecurity-nginx.tar.gz


#!/bin/bash

# 安装 Nginx 源码编译依赖
dnf install -y perl perl-devel perl-ExtUtils-Embed libxslt libxslt-devel libxml2 libxml2-devel gd gd-devel GeoIP GeoIP-devel

# 下载 Nginx 源码
NGINX_VERSION="1.20.1"
cd /yshop-server/modsectmp/
wget http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz
tar -zxpf nginx-${NGINX_VERSION}.tar.gz
cd nginx-${NGINX_VERSION}

# 下载 ModSecurity-nginx 连接器
git clone --depth 1 https://github.com/SpiderLabs/ModSecurity-nginx.git

# 配置并编译 Nginx(保留原有配置)
./configure \
    --prefix=/etc/nginx \
    --sbin-path=/usr/sbin/nginx \
    --modules-path=/usr/lib64/nginx/modules \
    --conf-path=/etc/nginx/nginx.conf \
    --error-log-path=/var/log/nginx/error.log \
    --http-log-path=/var/log/nginx/access.log \
    --pid-path=/var/run/nginx.pid \
    --lock-path=/var/run/nginx.lock \
    --user=nginx \
    --group=nginx \
    --build=CentOS \
    --builddir=nginx-${NGINX_VERSION} \
    --with-select_module \
    --with-poll_module \
    --with-threads \
    --with-file-aio \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-http_realip_module \
    --with-http_addition_module \
    --with-http_xslt_module=dynamic \
    --with-http_image_filter_module=dynamic \
    --with-http_geoip_module=dynamic \
    --with-http_sub_module \
    --with-http_dav_module \
    --with-http_flv_module \
    --with-http_mp4_module \
    --with-http_gunzip_module \
    --with-http_gzip_static_module \
    --with-http_auth_request_module \
    --with-http_random_index_module \
    --with-http_secure_link_module \
    --with-http_degradation_module \
    --with-http_slice_module \
    --with-http_stub_status_module \
    --http-proxy-temp-path=/var/cache/nginx/proxy_temp \
    --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
    --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
    --http-scgi-temp-path=/var/cache/nginx/scgi_temp \
    --with-mail=dynamic \
    --with-mail_ssl_module \
    --with-stream=dynamic \
    --with-stream_ssl_module \
    --with-stream_realip_module \
    --with-stream_geoip_module=dynamic \
    --with-http_perl_module=dynamic \
    --add-dynamic-module=ModSecurity-nginx \
    --with-perl_modules_path=/usr/lib/perl5/vendor_perl \
    --with-perl=/usr/bin/perl \
    --add-dynamic-module=njs-master/nginx/
#https://github.com/nginx/njs

make modules

mkdir -p /usr/lib64/nginx/modules/
cp /data/yshop-server/modsectmp/nginx-1.20.1/nginx-/ngx_http_modsecurity_module.so /usr/lib64/nginx/modules/




#./configure  --prefix=/data/nginx/appt --with-http_stub_status_module --with-http_realip_module --with-stream --with-compat --with-http_v2_module --add-module=/data/nginx/appt/modules/ngx_http_upstream_consistent_hash_module --add-module=/data/nginx/appt/modules/ngx_http_upstream_check_module --add-module=/data/nginx/appt/modules/ngx_http_upstream_fair_module   --add-dynamic-module=ModSecurity-nginx --add-dynamic-module=njs-master/nginx/

nginx_modsecurity.conf

centos8 安装相关依赖
# 在 nginx.conf 的 http 块中添加以下配置
#安全防火墙拦截模块
load_module /data/nginx/appt/modules/ngx_http_modsecurity_module.so;

http {
	# 定义限流区域,使用客户端IP地址作为键,共享内存大小为10MB,限速为每秒1个请求
	#limit_req_zone $binary_remote_addr zone=perip:10m rate=1r/s;

	# 定义并发连接限制区域,同样以客户端IP为键,共享内存大小为10MB,限制每个IP最多10个并发连接
	#limit_conn_zone $binary_remote_addr zone=connlimit:10m;
    
    # 其他配置...
    
    server {
        listen 80;
        server_name example.com;
        
        # 启用 ModSecurity
        modsecurity on;
        modsecurity_rules_file /etc/modsecurity.conf;
        
   # 拒绝根路径访问
    location = / {
   add_header Content-Type text/plain;
   add_header X-Frame-Options SAMEORIGIN;
   add_header Set-Cookie "Path=/; HttpOnly; Secure";
   add_header Access-Control-Allow-Methods "GET, POST, OPTIONS,PUT,DELETE";
  


limit_except GET POST OPTIONS PUT DELETE{

deny all;

}

   return 200 "Dear friend, I'm just an ordinary working stiff-please don't attack the site I deployed! The worst consequence could be losing my job.\n";


     }


    location / 
		 {

   limit_except GET POST OPTIONS PUT DELETE {
   
       deny all;

  }   
  
            
            # 应用请求速率限制,允许最多5个突发请求,不延迟处理
            #limit_req zone=perip burst=5 nodelay;

            # 应用并发连接限制,每个IP最多10个并发连接
            #limit_conn connlimit 20;		        

            proxy_http_version 1.1;
						proxy_read_timeout 120s;
            proxy_set_header Connection ""; #始终避免加超时               
            proxy_set_header Host $host;
   	        proxy_set_header X-Forward-For $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://XXXAPi;
            proxy_redirect off;
            proxy_ignore_headers Set-Cookie;
            proxy_hide_header Set-Cookie;
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
            
   
    }
    
  location = /favicon.ico {
    return 404;
}






}



}

0

评论区