在Serverless中配置基于速率的规则抵御DDoS攻击是否可行?
完全可以在Serverless Framework中配置AWS WAF的基于速率的防护规则,无需手动在控制台操作,目前有两种常用实现方案:
方案1:使用第三方Serverless插件
可以直接用社区维护的serverless-associate-waf插件快速实现配置,操作步骤如下:
- 安装插件:
npm install serverless-associate-waf --save-dev
- 在
serverless.yml中添加插件声明和WAF规则配置即可,插件会自动完成规则创建和API Gateway的绑定操作。
方案2:直接声明CloudFormation资源(无需额外插件)
你可以直接在serverless.yml的resources字段中定义WAFv2速率规则,再关联到你部署的API Gateway实例即可,以下是参考配置示例,实现的效果为:单个IP 5分钟内请求超过100次时自动拦截:
service: demo-service provider: name: aws runtime: nodejs18.x stage: dev functions: demoApi: handler: handler.demo events: - http: path: /demo method: get resources: Resources: # 定义速率限制规则组 WafRateLimitRuleGroup: Type: AWS::WAFv2::RuleGroup Properties: Capacity: 100 Scope: REGIONAL Rules: - Name: IP-Rate-Limit Priority: 1 Action: Block: {} Statement: RateBasedStatement: Limit: 100 # 5分钟内单IP请求上限,可自行调整 AggregateKeyType: IP VisibilityConfig: SampledRequestsEnabled: true CloudWatchMetricsEnabled: true MetricName: IP-Rate-Limit-Metric VisibilityConfig: SampledRequestsEnabled: true CloudWatchMetricsEnabled: true MetricName: Waf-Rule-Group-Metric # 绑定WAF规则到API Gateway WafApiBind: Type: AWS::WAFv2::WebACLAssociation Properties: ResourceArn: !Sub arn:aws:apigateway:${AWS::Region}::/restapis/${ApiGatewayRestApi}/stages/${self:provider.stage} WebACLArn: !GetAtt WafRateLimitRuleGroup.Arn
配置完成后直接执行sls deploy即可完成全量部署,规则会自动生效。如果你的API是HTTP API类型,只需调整ResourceArn的格式为对应HTTP API的ARN即可。
内容的提问来源于stack exchange,提问作者Jake Owen
相关产品推荐
相关产品推荐

