干货分享(nginx防ddos攻击)

干货分享(nginx防ddos攻击)

浏览次数:
信息来源: 用户投稿
更新日期: 2025-10-25
文章简介

我们用的高防服务器只防流量攻击不防CC,现在的攻击多数都是混合型的,而且CC攻击很多,防CC只能自己搞了,按照第一篇的配置,在实际的使用中效果并不理想。限制每秒钟的请求数和ip连接数,属于杀敌一

2025阿里云双十一服务器活动

  我们用的高防服务器只防流量攻击不防CC,现在的攻击多数都是混合型的,而且CC攻击很多,防CC只能自己搞了,按照第一篇的配置,在实际的使用中效果并不理想。限制每秒钟的请求数和ip连接数,属于杀敌一千自损八百的做法。是可以防小规模的cc攻击,但是不够灵活,限制严谨,误杀率很大;限制少了,当攻击的ip量达到一定规模的时候,传递到初始化的请求还是非常多,导致php撑不住挂掉。这里在上一篇的基础上详细介绍一下我在生产中使用的配置。

  最大连接数不够的话,出现“打开文件过多”错误。系统放置的1024太小了,在/etc/security/limits.conf中增加:

  这个比较考验内功,暂时还没太多研究,从网上搬运了一份,以后在慢慢学习:

  #ControlstheSystemRequestdebuggingfunctionalityofthekernel

  #ControlswhethercoredumpswillappendthePIDtothecorefilename.

  #Usefulfordebuggingmulti-threadedapplications.

  kernel.core_uses_pid=1

  kernel.pid_max=65535

  #Thecontentsof/proc/

/mapsandsmapsfilesareonlyvisibleto

  #readersthatareallowedtoptrace()theprocess

  kernel.maps_protect=1

  #EnableExecShieldprotection

  kernel.exec-shield=1

  kernel.randomize_va_space=2

  #Controlsthemaximumsizeofamessage,inbytes

  #Controlsthedefaultmaxmimumsizeofamesagequeue

  #Hideexposedkernelpointers

  kernel.kptr_restrict=1

  #Increasesizeoffilehandlesandinodecache

  vm.dirty_background_ratio=5

  #specifiestheminimumvirtualaddressthataprocessisallowedtommap

  vm.mmap_min_addr=4096

  #50%overcommitmentofavailablememory

  vm.overcommit_ratio=50

  vm.overcommit_memory=0

  #Setmaximumamountofmemoryallocatedtoshmto256MB

  kernel.shmmax=268435456

  kernel.shmall=268435456

  #Keepatleast64MBoffreeRAMspaceavailable

  vm.min_free_kbytes=65535

  #PreventSYNattack,enableSYNcookies(theywillkick-inwhenthemax_syn_backlogreached)

  net.ipv4.tcp_syncookies=1

  net.ipv4.tcp_syn_retries=2

  net.ipv4.tcp_synack_retries=2

  net.ipv4.tcp_max_syn_backlog=4096

  #Disablespacketforwarding

  net.ipv4.ip_forward=0

  net.ipv4.conf.all.forwarding=0

  net.ipv4.conf.default.forwarding=0

  net.ipv6.conf.all.forwarding=0

  net.ipv6.conf.default.forwarding=0

  #DisablesIPsourcerouting

  net.ipv4.conf.all.send_redirects=0

  net.ipv4.conf.default.send_redirects=0

  net.ipv4.conf.all.accept_source_route=0

  net.ipv4.conf.default.accept_source_route=0

  net.ipv6.conf.all.accept_source_route=0

  net.ipv6.conf.default.accept_source_route=0

  #EnableIPspoofingprotection,turnonsourcerouteverification

  net.ipv4.conf.all.rp_filter=1

  net.ipv4.conf.default.rp_filter=1

  #DisableICMPRedirectAcceptance

  net.ipv4.conf.all.accept_redirects=0

  net.ipv4.conf.default.accept_redirects=0

  net.ipv4.conf.all.secure_redirects=0

  net.ipv4.conf.default.secure_redirects=0

  net.ipv6.conf.all.accept_redirects=0

  net.ipv6.conf.default.accept_redirects=0

  #EnableLogSpoofedPackets,SourceRoutedPackets,RedirectPackets

  net.ipv4.conf.all.log_martians=1

  net.ipv4.conf.default.log_martians=1

  #Decreasethetimedefaultvaluefortcp_fin_timeoutconnection

  net.ipv4.tcp_fin_timeout=7

  #Decreasethetimedefaultvalueforconnectionstokeepalive

  net.ipv4.tcp_keepalive_time=300

  net.ipv4.tcp_keepalive_probes=5

  net.ipv4.tcp_keepalive_intvl=15

  net.ipv4.conf.all.bootp_relay=0

  39;tproxyarpforanyone

  net.ipv4.conf.all.proxy_arp=0

  #Turnonthetcp_timestamps,accuratetimestampmakeTCPcongestioncontrolalgorithmsworkbetter

  net.ipv4.tcp_timestamps=1

  39;tignoredirectedpings

  net.ipv4.icmp_echo_ignore_all=0

  #Enableignoringbroadcastsrequest

  net.ipv4.icmp_echo_ignore_broadcasts=1

  #EnablebaderrormessageProtection

  net.ipv4.icmp_ignore_bogus_error_responses=1

  #Allowedlocalportrange

  net.ipv4.ip_local_port_range=1638465535

  #EnableafixforRFC1337-time-waitassassinationhazardsinTCP

  net.ipv4.tcp_rfc1337=1

  #Donotauto-configureIPv6

  net.ipv6.conf.all.autoconf=0

  net.ipv6.conf.all.accept_ra=0

  net.ipv6.conf.default.autoconf=0

  net.ipv6.conf.default.accept_ra=0

  net.ipv6.conf.eth0.autoconf=0

  net.ipv6.conf.eth0.accept_ra=0

  39;htcp'congestioncontrol

  39;modprobetcp_htcp'first

  net.ipv4.tcp_congestion_control=htcp

  39;fq'queuemanagementscheduler(kernel>3.12)

  net.core.default_qdisc=fq

  #Turnonthetcp_window_scaling

  net.ipv4.tcp_window_scaling=1

  #Increasetheread-bufferspaceallocatable

  net.ipv4.tcp_rmem=81928738016777216

  net.ipv4.udp_rmem_min=16384

  net.core.rmem_default=262144

  net.core.rmem_max=16777216

  #Increasethewrite-buffer-spaceallocatable

  net.ipv4.tcp_wmem=81926553616777216

  net.ipv4.udp_wmem_min=16384

  net.core.wmem_default=262144

  net.core.wmem_max=16777216

干货分享,nginx防ddos攻击

  net.core.somaxconn=32768

  #Increasenumberofincomingconnectionsbacklog

  net.core.netdev_max_backlog=16384

  net.core.dev_weight=64

  #Increasethemaximumamountofoptionmemorybuffers

  net.core.optmem_max=65535

  #Increasethetcp-time-waitbucketspoolsizetopreventsimpleDOSattacks

  net.ipv4.tcp_max_tw_buckets=1440000

  39;trecyclethem(recyclecanbreakclientsbehindNAT)

  net.ipv4.tcp_tw_recycle=0

  net.ipv4.tcp_tw_reuse=1

  #Limitnumberoforphans,eachorphancaneatupto16M(maxwmem)ofunswappablememory

  net.ipv4.tcp_max_orphans=16384

  net.ipv4.tcp_orphan_retries=0

  #IncreasethemaximummemoryusedtoreassembleIPfragments

  net.ipv4.ipfrag_high_thresh=512000

  net.ipv4.ipfrag_low_thresh=446464

  39;tcachessthreshfrompreviousconnection

  net.ipv4.tcp_no_metrics_save=1

  net.ipv4.tcp_moderate_rcvbuf=1

  #IncreasesizeofRPCdatagramqueuelength

  net.unix.max_dgram_qlen=50

  39;tallowthearptabletobecomebiggerthanthis

  net.ipv4.neigh.default.gc_thresh3=2048

  #Tellthegcwhentobecomeaggressivewitharptablecleaning.

  #AdjustthisbasedonsizeoftheLAN.1024issuitableformost/24networks

  net.ipv4.neigh.default.gc_thresh2=1024

  #Adjustwherethegcwillleavearptablealone-setto32.

  net.ipv4.neigh.default.gc_thresh1=32

  #Adjusttoarptablegctoclean-upmoreoften

  net.ipv4.neigh.default.gc_interval=30

  #IncreaseTCPqueuelength

  net.ipv4.neigh.default.proxy_qlen=96

  net.ipv4.neigh.default.unres_qlen=6

  net.ipv4.tcp_reordering=3

  #HowmanytimestoretrykillinganaliveTCPconnection

  net.ipv4.tcp_retries2=15

  net.ipv4.tcp_retries1=3

  #Avoidfallingbacktoslowstartafteraconnectiongoesidle

  #keepsourcwndlargewiththekeepaliveconnections(kernel>3.6)

  net.ipv4.tcp_slow_start_after_idle=0

  #AllowtheTCPfastopenflagtobeused,bewaresomefirewallsdonotlikeTFO!(kernel>3.7)

  net.ipv4.tcp_fastopen=3

  #Thiswillenusrethatimmediatlysubsequentconnectionsusethenewvalues

  net.ipv4.route.flush=1

  net.ipv6.route.flush=1

  #具体值根据服务器硬件计算,配置不当可能导致过早关闭TCP连接

  #net.netfilter.nf_conntrack_max=1048576

  #net.netfilter.nf_conntrack_tcp_timeout_established=1200

  3.nginx和lua防御cc攻击

  参考了opencdn团队的做法,通过nginx和lua来防御cc,原理见下面的参考文章,效果很好

  nginx需要编译lua模块

  在nginx.conf的http段中加入:

  limit_req_zone$cookie_tokenzone=session_limit:20mrate=1r/s;

  limit_req_zone$binary_remote_addr$urizone=auth_limit:20mrate=1r/m;

  limit_reqzone=session_limitburst=5;

  localrandom=ngx.var.cookie_random

  returnngx.redirect("/auth?url="..ngx.var.request_uri)

  localtoken=ngx.md5("opencdn"..ngx.var.remote_addr..random)

  if(ngx.var.cookie_token~=token)then

  returnngx.redirect("/auth?url="..ngx.var.request_uri)

  proxy_set_headerHost$host;

  proxy_set_headerX-Real-IP$remote_addr;

  proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;

  proxy_passhttp://backend;

  limit_reqzone=auth_limitburst=1;

  if($arg_url=""){

  localrandom=math.random(9999)

  localtoken=ngx.md5("opencdn"..ngx.var.remote_addr..random)

  if(ngx.var.cookie_token~=token)then

  ngx.header["Set-Cookie"]={"token="..token,"random="..random}

  returnngx.redirect(ngx.var.arg_url)

  这个方法会造成搜索引擎蜘蛛一直处在302中,不利于seo,可以通过智能dns来为蜘蛛指定单独的线路。和被打到停机机比起来,seo几乎可以无视

  4.iptables限制tcp连接和频率

  通过上述的配置,cc攻击流量就处在302中了,但是保险起见对ip进行连接频率和并发限制,限制单ip连接和频率,在/etc/sysconfig/iptables中加入:

  #单个IP在60秒内只允许新建20个连接

  -AINPUT-ieth0-ptcp-mtcp--dport80-mstate--stateNEW-mrecent--update--seconds60--hitcount20--nameDEFAULT--rsource-jDROP

  -AINPUT-ieth0-ptcp-mtcp--dport80-mstate--stateNEW-mrecent--set--nameDEFAULT--rsource

  #控制单个IP的最大并发连接数为20

  -IINPUT-ptcp--dport80-mconnlimit--connlimit-above20-jREJECT

  #每个IP最多20个初始连接

  -AINPUT-ptcp--syn-mconnlimit--connlimit-above20-jDROP

  这样配置后,个别ip能建立的连接不是只有20个,具体能建立多少连接还要看tcp的超时设置,但唯一ip不会建立大量的tcp连接消耗系统资源

  5.使用fail2ban屏蔽攻击ip

  通过上面的设置nginx后,cc攻击请求转换302,直接由性能强大的nginx处理。但是攻击ip还是在不停的访问服务器,消耗着防御服务器的资源,一旦达到一定数量级,也会严重影响到系统的性能,所以通过分析nginx的访问日志彻底屏蔽这些ip

  安装fail2ban并升级iptables至最新:

  yuminstall-yepel-release

  yuminstall-yfail2baniptablespython-inotify

  先看下我nginx的访问日志格式:

  159.138.198.106302GET/auth?url=/HTTP/1.1235[17/Oct/2015:21:06:22+0800]Mozilla/5.0(Macintosh;IntelMacOSX10_10_2)AppleWebKit/600.4.10(KHTML,likeGecko)Version/8.0.4Safari/600.4.10------

  cc攻击的ip会经过nginx和lua处理后,访问状态转换302,根据nginx的访问日志格式,过滤这些ip和302状态,加入黑名单即可。

  新建fail2ban的规则文件/etc/fail2ban/filter。d/nginx-302-cc.conf,内容为:

  failregex=302.(GET|POST)*.*HTTP/1.*$

  新建fail2ban的配置文件/etc/fail2ban/jail.d/nginx-anti-302.conf,内容为:

  logpath=/opt/nginx/logs/52os.net/access_web.log

  findtime=60#检测60秒内的日志

  bantime=900#屏蔽ip的时间为15分钟

  maxretry=90#达到90次就屏蔽

  backend=pyinotify#使用pyinotify检测日志变化,被攻击时检测海量日志时性能最好

  banaction=iptables-ipset-proto6-allports#使用ipset屏蔽IP,使用iptables屏蔽大量IP需要时非常慢,并且资源占用非常大

  访客访问一次网站会产生2次302,这样配置后60秒内允许45次正常的访问,基本上不会屏蔽正常访客

  如果使用iptables屏蔽,需注意fail2ban-0.9.3在执行iptables命令时,会加上了-w参数防止规则冲突,iptables-1.4.20之后才有这个参数,而CentOS6的iptables是1.4.7,导致iptables规则添加失败,解决方法是删除iptables-common.conf中的

  sed-i&39;/etc/fail2ban/action.d/iptables-common.conf

  servicefail2banstart

  通过以上设置实现了:

  cc流量直接由高性能的nginx返回302,不会proxy_pass到放置的服务器或应用

  限制级别ip建立的tcp连接数量和频率

  恶意攻击ip实时黑名单

  实际使用效果非常不错。面对专业的ddos玩家,在好的系统中终有薄弱的转移,攻击达到一定规模,基本上是不可防的,但是可以尝试利用有限的资源和攻击者周旋,提高攻击的当然,要是烧的起钱,这篇文章可以无视

标签:
美国无限流量vps
« 上一篇
返回列表
下一篇 »

如本文对您有帮助,就请抽根烟吧!