# Safety Protection

# I. Introduction to Safety and Protection

In order to solve the risk and safety problems of Weixin Mini Program business encountered in various application scenarios, such as malicious registration, false brushing, group control number maintenance, marketing cheating, etc.WeChat The WeChat Gateway has introduced security protection capabilities to help developers cope with the risk of marketing cheating such as swiping bills, fake transactions, malicious cheating of subsidies, and the risk of registration black production such as bulk registration, falsification of identity, and serious brand image issues such as second-time high-price sales after a snap purchase.

WeChat WeChat gateway security protection capability is based on the threat intelligence information provided by WeChat.For example, multidimensional data such as account identity and user characteristics can be analysed intelligently, comprehensively determine whether the current request is safe, and can more precisely identify various different black and grey technologies and means such as fakes, fake real machines, real real machines, and real real machines. Developers can configure security policies in core business processes, support blocking by the WeChat gateway or recognizing by the Weixin gateway after the business decides whether to block, or perform secondary human-machine interaction verification for exceptional requests, with greater flexibility.

# II. Capacity advantages

  1. Multiple levels of protection, three lines of security, from intelligent identification of environmental risks to WeChat gateway risk control strategy blocking, to advanced security protection, the WeChat gateway fully ensures business security;
  2. Accurate identification, based on intelligent analysis model, comprehensive account identity, equipment, user behavior characteristics, environment, etc. Weixin Mini Program multi-dimensional digital analysis in scenarios;
  3. High flexibility, supporting business-custom blocking policies, business-custom interception display pages, and business-custom human-machine interaction validation pages;
  4. Human-computer interaction verification, WeChat gateway detects the user's current network environment anomaly, and supports man-machine waterproofing wall verification;
  5. Real-time data monitoring, minute-level intercept exception request data monitoring, support for viewing detailed intercept logs;

# III. Use scenarios

  1. Marketing offers, such as coupons, sweepstakes, stakes, discount coupons for new users, and other marketing campaign scenarios, the security protection capability can detect multiple dimensions of equipment, IP, user behavior, account, etc., allowing woolly parties to escape, effectively protecting marketing campaigns and giving benefits to the target user.
  2. Activity scenarios such as liking posts, high-liking comments to obtain event gifts, posting to obtain prize draws, and security protection capabilities can accurately identify cheating means such as simulators, group control, automated clicks, and effectively solve the problem of ad trolling, malicious flooding, and ticket swipes.
  3. Malicious registration. For malicious registration activities such as machine bulk registration, junk small numbers, and falsification of identity, security-protected account risk control can be effectively identified and intercepted.

# IV. Introduction of multi-layered protection

# The first layer of protection

Based on the private WeChat link of the WeChat gateway, when requesting the private WeChat protocol of the WeChat gateway, the WeChat network can identify various protocol headers, crawling features, emulator attacks, black and grey IP access, DDoS attacks and other unusual requests, and intercept them in a timely manner.After the initial filtering of the first layer of security protection, the traffic that is initially determined to be normal is placed in the WeChat server in the WeChat gateway for the second layer of traffic filtering and purification. (The QPS statistics in the WeChat gateway package are concurrent requests after the first cleaning, such as finding access to the WeChat gateway, the same activity QPS has declined, which is normal.))

# The second layer of protection

WeChat The gateway will perform a second layer of risk protection for requests after the first initial cleaning,Cleans out requests that forge / tamper with the gateway's private protocol, and filters out illegal requests, overprivileged requests, high-frequency requests, etc., in conjunction with user request frequency and permission verification. After the second cleaning of the second layer of security, more than 90% of the unusual traffic has been intercepted, and the remaining traffic is forwarded to the business source.

# Third layer of protection

In order to prevent missing fish, the WeChat gateway has launched the advanced ability of the third layer of custom safety protection strategy to actively identify missing fish.Combine multidimensional data such as request characteristics, device information, and account numbers to form intelligent analysis models, and conduct higher-level processing of traffic such as environment detection and intelligent verification, supporting the business to make its own decisions on the protection form and supporting the switch to a more secure form of verification code. The third layer of advanced security capabilities is detailed below.

# V. Guidelines for use

The security policy is WeChat WeChat Gateway Advanced capability. Currently, a standard version (specification: 1000QPS * 20Mbps) and above gateway packages can be configured in the console, and the capability is not supported under standard packages.

The detailed usage steps are as follows:

# 5.1 Capacity Access

Go to the Gateway Console - Security Protection to configure.In order to not affect the normal external services of the business and not obviously cause black and white confrontation, only the core URL security protection policy in the URL, business scenario can be configured, and unconfigured Mini Program URL requests will be directly released unprocessed.

# 5.2 Choice of Protective Strategies

Security currently supports two protection strategies, with more protection strategies continuing to be iterated.Console configuration, the minute level will take effect, no code changes, no Weixin Mini Program version.

# A. Gateway Interception

Select the gateway intercept policy, WeChat gateway will directly return to the specified response page according to the response content of the service configuration, and the request will no longer flow to the service side.The developer can configure the response content on the page, and after the interception is triggered, the gateway will send the configured content directly to the client.

# B. Operational decision-making

Select the business decision policy, the WeChat gateway will add [[to the request'sheader`` x-wx-risk-rankx-wx-device-risk-rankparameter parameters.

When a business receives a request, it can execute a business-side processing policy based on this parameter.x-wx-risk-rankParameters range from 0 to 4, with higher numbers indicating higher risks. The level of risk explaination and recommendations for use are as follows:

Level of risk Proposed disposal scheme
Level of risk 0 There's no risk, no blocking.
Level of risk 1 Low suspicious risk, and simple verification (e.g. verification code, SMS, etc.) is recommended.
Level of risk 2 Slight suspicious risks. Simple verification (e.g. verification code, SMS, etc.) is recommended.
Level of risk 3 Moderate suspicious risk, and it is recommended to take certain measures to avoid harm depending on the business scenario. For example, marketing campaigns can reduce the probability of high-level rewards; List-based campaigns reduce the weight of such votes; Login registration requires secondary verification, etc.
Level of risk 4 Highly suspicious risk, recommended direct interception based on business logic. For example, red envelopes-type activities return no winnings or a minimum amount of red envelope; No counting of votes is taken at a list-based event; The login / registration operation requires secondary verification; High-risk businesses have the option to restrict this operation.

The x-wx-device-risk-rankparameter ranges from 0 to 4, with higher numbers indicating higher risk.Other equipment-related parameters are described as follows:

Header Introductions
x-wx-platform Operating system: ios / android / windows / mac / devtools / ohos
x-wx-device-risk-rank Equipment level of risk, "0-4," the larger the word, the higher the risk.
x-wx-device-security-status The security status of the device is more accurate when the security plug-in is plugged in.
x-wx-device Detailed source information for the operational equipment.
x-wx-device-uv-1d The number of current Weixin Mini Program UVs of the current device in the last 1 day, that is, the number of WeChat that the current device has logged in to the current Mini Program only 1 day.
x-wx-sub-session Information on attached equipment.

The developer can judge the level of risk according to the level of risk. The significance of the level of risk and the use of the corresponding business, please refer to the above instructions and suggestions, specific use can be adjusted dynamically according to the actual situation of the business, in order to achieve accurate intercept, protect the sound development of the business.

# VI. Safety detection plug-ins

Developers can customize the security detection plug-in to be used to detect the security of the current environment. After access, it can provide more comprehensive and accurate security protection than ordinary gateways. The user needs to complete the environment verification before moving on.Access needs to modify the Weixin Mini Program code, after the completion of the Mini Program version of the effective.

Detailed access guidelines are as follows:

# 6.1 Quick introduction

  1. In Weixin Mini Program apagejson, introduce [WeChat gateway] plug-in, wait for plug-in access audit, can be used in Mini programs.
{
   "plugins": {
    "gateway-challenge": {
      "version": "1.3.2",
      "provider": "wxfe70b3f986aad2fb"
    }
  }
}
  1. In the Weixin Mini Program onLaunch callback, activate the behavior detection capability with the following code.
let gatewayChallenge = requirePlugin('gateway-challenge');
App({
  onLaunch() {
    gatewayChallenge.start();
  }
})
  1. At this point Weixin Mini Program will complete the silent detection, which usually takes a few seconds to complete. The normal use of the Mini Program during the test does not affect the normal use of it.

  2. (Optional) Insert a security detection component in key pages such as active pages in Weixin Mini Program (it does not affect the rendering of the page, just insert it at the top of the page)

<gateway-challenge
  <!-- 检测成功的回调 -->
  bindchallengesuccess="onChallengeSuccess"
  <!-- 检测失败的回调 -->
  bindchallengefail="onChallengeFail"
></gateway-challenge>
  1. Obtain test results where Weixin Mini Program requires the submission of sensitive information.
Page({
  async onBtnClick() {
    let gatewayChallenge = requirePlugin('gateway-challenge');
    let res;
    try {
      await gatewayChallenge.getClearance(); // 获取检测结果
    } catch (e) {
      // 行为检测出现异常,提示并返回
      wx.showToast({
        title: "出现错误,请稍后再试。"
      });
      return;
    }
    wx.request({
      // 敏感接口请求,需要在检测完成后发起
    });
  }
});

# 6.2 API Dxplaination

The plug-in itself is exported as follows (using requirePlugin):

interface ChallengePlugin {
    /* 初始化,需要在小程序加载时执行,只需要执行一次 */
    start: () => Promise<void>;
    
    /* 获取当前运行环境的校验结果(推荐),可以在任意时刻执行 */
    getClearance: () => Promise<ChallengeResult>;
    
    /* 监听检测成功的事件,在检测成功时执行回调 */
    onChallengeSuccess: (cb: (res: ChallengeResult) => void) => void;
    
    /* 监听检测失败的事件,在检测失败时执行回调 */
    onChallengeFail: (cb: () => void) => void;
}

interface ChallengeResult {
    err_code: number; // 检测错误码
    success: boolean; // 检测结果
    cid: string; // 检测 id,用于标识单次检测结果,在出现误判时可提供排查
}

The properties supported by the detection component are as follows (using customComponent)

<gateway-challenge
  <!-- 检测成功的回调 -->
  bindchallengesuccess="onChallengeSuccess"
  <!-- 检测失败的回调 -->
  bindchallengefail="onChallengeFail"
></gateway-challenge>

# 6.3 compatibility

In WeChat 8.0.28 above the passenger terminal (not included) test passed, below this version will prompt WeChat version too low, please update WeChat.

# 6.4 life cycle

The test results will cover the entire life cycle of Weixin Mini Program until the user exits the Mini Program.

In the case of a successful detection, getClearance will synchronize the Weixin Mini Program lifecycle with a successful return, along with the same Clearance ID.In the case of a failed detection, getClearance fires the detection again until it succeeds.

# VII. FAQS

# 1. How do you ensure that the business interface is not hacked by [crawlers, woolly people, scripts]?

After the WeChat gateway detects the execution of the plug-in, it calls the core to snap up and places a single class interface.If possible, execute wx.request after getClearance returns asynchronously, ensuring that the request is made after detection is completed, thus ensuring the security of the request.

# 2. PC side, WeChat developer tools, some low-end devices can not complete the detection / I was mistakenly intercepted, how to deal with?

We conduct custom security detections for most devices, and if a user experiences an exception, we recommend a retry (getClearance), and if persistent failures, we can provide the user's cid information for us to locate and resolve.

# 3. How can we improve the accuracy of detection?

It is recommended to pull up the detection module at onLaunch and call the start interface, insert the 'tag' on the active page, and ensure that the page has some explicit interaction (in the form of clicks, scrolling, sliding, etc.).

# 4. Will the plugin affect my Weixin Mini Program performance? Can this be introduced in sub-packageing?

The plug-in code package size is about 200 KB, and the detection plug-in has basically no perceptible effect on Weixin Mini Program interaction, load time, etc.Plugins can be introduced in subpackages and loaded later.

# 5. How long does it take to test once?

On low-end Android devices, the test is done in 1.5 seconds. On mobile phones with mainstream performance, the detection generally does not exceed 500ms.

# 6. Can Security Testing Cause Weixin Mini Program Catten?Can additional actions be taken during the inspection?

Detects a fully asynchronous execution that does not block the main thread of Weixin Mini Program and cause a stutter. During the detection process, other non-sensitive logic of the Mini Program can be performed normally, only to ensure that the detection is completed before the sensitive interface is called.