The IP anti-brush function is designed to prevent access to certain IPs and prevent cloud functions or databases from being unable to respond in time due to a large number of requests for the same IP in a short period of time.

While uniCloud is serverless, cloud functions are hard to beat. but

  1. If attackers continue to attack long-running cloud functions, the cloud vendors will be billed according to GBS, which will cause economic losses to developers. It is necessary to block the cloud function operation in the shortest possible time
  2. If the cloud functions that access a large number of database operations are attacked, the overall performance of the database will be degraded, which will hinder normal users from reading and writing the database.

Whether the developer is attacked by ddos, or is swiped or swiped for incentives due to issuing rewards, promotions or rewarded video ads, the ip anti-swiping function should be enabled.

IP Anti-Brush contains two sub-functions:

  • IP blacklist: Manually block certain IPs.
  • IP access frequency control: automatically block certain IPs for a period of time according to the frequency of accessing cloud functions from the same IP.

目前实现的方案有两种:

  • 基于Redis:服务空间开通Redis后,利用Redis的高并发及存储机制来实现。
  • 云厂商支持:不需要开通Redis,IP防刷机制依赖云厂商网关。

阿里云、腾讯云未提供网关层面的IP防刷功能,所以需要开通Redis来采用基于Redis的方案。该方案是在云函数中执行IP防刷功能相关的逻辑,因此在拒绝IP请求时也会消耗最小计费单元(配置的内存*100ms)的GBs

支付宝小程序云提供的是网关层面的IP防刷功能,不需要依赖Redis,命中防刷规则的请求会自动被网关拦截不会进入云函数执行逻辑,因此不会消耗GBs,被拒的请求在云函数内也查不到请求日志

# 基于Redis(阿里&腾讯云)

仅本地调试时需HBuilderX 3.5.4+。云端无版本限制,在uniCloud web控制台打开ip防刷即可 基于Redis方案适用于阿里云、腾讯云服务空间

# 启用IP防刷功能

  1. Open redis in the service space
  2. Navigate to the left side of the uniCloud web console to enable IP anti-swipe: uniCloud web console

# 生效范围

In the service space after completing the previous two steps, ip anti-brush is supported in the following ranges:

  1. Cloud functions/cloud objects with redis extension or jql extension enabled (jql extension depends on redis extension) will have the anti-swipe function. Cloud functions that do not load related extension libraries do not take effect.
  2. clientDB, that is, the database request directly initiated by the client also takes effect.
  3. The IP anti-swipe function will only be enabled when the client calls cloud functions/cloud objects. URLization, timing triggering, and cloud function calling cloud functions do not trigger this function

The reason for needing redis is that the blocked IP needs to exist in redis, and its key is: unicloud:ip-black-list:set. If this information exists in MongoDB, there is no meaning of anti-brush, and redis, as an in-memory database, has extremely fast access speed and does not charge according to the number of visits, which is the best solution.

# IP黑名单

IP blacklist is used to completely block the set IP or IP network segment (cidr specification) from accessing cloud functions or clientDB.

black list

The blocked IP will receive an error response when accessing cloud functions and clientDB, the error code is: ACCESS_DENIED, and the error message is: Access denied

// cloud function
const res = await uniCloud.callFunction({
  name: 'test',
  data: {}
})
// res.result = {
//   errCode: 'ACCESS_DENIED',
//   errMsg: 'Access denied'
// }

// For cloud objects, the above return result conforms to the response body specification because it will be converted into an error thrown
const obj = uniCloud.importObject('obj')
try {
  const res = await obj.test()
} catch (e) {
  // e.errCode = 'ACCESS_DENIED'
  // e.errMsg = 'Access denied'
}

# IP网段规则

Usually, when writing an IPv4 address, the IPv4 address is written as four segments of numbers separated by dots, and each segment ranges from 0 to 255. An IP network segment is a string consisting of IP plus mask digits, which is used to represent an IP range.

Taking 192.168.12.1/20 as an example, to calculate the IP range represented by it, you can first convert the four segments of IP into binary (add 0 to the front if each segment is less than 8 bits) 11000000.10101000.00001100.00000001, the number of mask bits is 20 It means that as long as the first 20 digits of the IP converted by this rule are the same as 192.168.12.1 after conversion, the IP is in the 192.168.12.1/20 IP network segment. That is, the IP range is 11000000.10101000.00000000.00000000(192.168.0.0) - 11000000.10101000.00001111.11111111(192.168.15.255)

# 黑名单用到的Redis key

The blacklist configured by the developer will be stored in redis in the Set type, and its key is: unicloud:ip-black-list:set

# 注意事项

  • Toggle the state of the switch will update all cloud functions and clientDB that depend on or indirectly depend on redis extensions
  • Multiple users within a zone may have the same IP

# IP访问频率控制

IP access frequency control is used to limit the frequency of a single IP's access to cloud functions. As shown in the figure, developers can configure ${duration} seconds to request more than ${limit} times, which will temporarily block ${blockTime} seconds.

As far as the client experience is concerned, this configuration means that any continuous duration seconds cannot access more than the limit times, otherwise it will be temporarily banned for blockTime seconds. It should be easy for developers with relevant development experience to see that this is the implementation of a leaky bucket algorithm.

  • When the blockTime is set to 0, the limit will not be blocked, but the request will be rejected.
  • When the duration or limit is set to 0, the access frequency will no longer be restricted, but users who have been temporarily banned still need to wait until they are unblocked before they can access

frequency limit

Users with high access frequency and users who are temporarily banned due to high access frequency will receive an error response when accessing cloud functions and clientDB. The error code is: OPERATION_TOO_FREQUEENT, and the error message is: Operation is too frequent, please try again later

// cloud function
const res = await uniCloud.callFunction({
  name: 'test',
  data: {}
})
// res.result = {
//   errCode: 'OPERATION_TOO_FREQUENT',
//   errMsg: 'Operation is too frequent, please try again later'
// }

// For cloud objects, the above return result conforms to the response body specification because it will be converted into an error thrown
const obj = uniCloud.importObject('obj')
try {
  const res = await obj.test()
} catch (e) {
  // e.errCode = 'OPERATION_TOO_FREQUENT'
  // e.errMsg = 'Operation is too frequent, please try again later'
}

# IP访问频率控制用到的Redis key

Access Frequency Control Configuration

The three parameters of duration, limit, and blockTime configured by the developer are stored in redis in hash type, and the key is: unicloud:ip-freq-config:hash.

The structure is as follows:

{
	"duration": 10, // 单位秒
	"limit": 10, // 10(duration)秒内允许访问10次
	"blockTime": 1800 // 超限后封禁1800秒
}

IP Frequency Control Information

The IP frequency control information is stored in redis in the hash type, and the key is: unicloud:ip-info:${ip}:hash where ${ip} represents the ip of the client

An example of the structure is as follows:

{
	"bucket": 20, // 剩余访问次数,最大为配置的limit,最小为 0,以上面的访问频率控制配置为例
	"lastTime": 1656399171851 // 上次剩余访问次数变动的时间
}

Temporary ban information

Temporary blocking information is stored in redis in string type, and the key is: unicloud:ip-blocked:${ip}:string where ${ip} represents the client's ip

Its value is the timestamp when the temporary ban started

# 注意事项

  • Toggle the state of the switch will update all cloud functions and clientDB that depend on or indirectly depend on redis extensions
  • 一个区域内的多个用户可能拥有同一IP
  • 本地调试期间如果开启或关闭了IP防刷功能,应停止所有客户端等待5秒重新运行才可生效

# 支付宝小程序云

在uniCloud web控制台左侧导航开启ip防刷:uniCloud web控制台,IP防刷配置项修改大约需要3分钟生效。

frequency limit

IP访问频率控制用于限制单个IP访问云函数的频率,可实现 x 秒内请求超过 y 次,则超限制的请求会被临时封禁 z 秒。

x取值范围:60-86400(秒),y取值范围:100-99999999(次),z取值范围:60-259200(秒)。

# IP信息列表

列表类型分为三种:

  • 黑名单IP:手动添加到黑名单的IP/IP段,该类IP发起的请求会自动被网关拒绝
  • 命中防刷规则的IP:命中同IP请求频率限制的IP会自动被添加到该列表,支持手动解禁
  • 访问最多的IP:可查询访问云函数最多的IP及访问次数,仅支持查询近7天访问数据

被封禁IP访问云函数及clientDB时会收到http状态码为500的错误响应,错误码为:50050,错误信息为:防刷限流异常-触发黑名单规则,内容如下:

{
    "errDetail": "Anti Brushing RateLimit Error, Please Check The black list configs : anti_brushing_rateLimit blacklist configs limited",
    "errCode": "50050",
    "errMsg": "防刷限流异常-触发黑名单规则"
}