# Safety guidelines

# Development Principles and Considerations

This document collates some common security risks and vulnerabilities in the development of Mini programs, which are used to help developers find and repair related vulnerabilities in the development process, and avoid loss of business and data after the launch. Developers must base their development on the following principles:

  1. The principle of mutual distrust, do not trust the data submitted by users, including data provided by third-party systems, and the necessary data verification must be placed in the background.
  2. Principle of Least Privilege: Code, module, etc. only have the smallest privilege to complete the task, and do not give unnecessary privileges.
  3. Storing user sensitive data in plaintext is prohibited.
  4. Mini Program code (excluding cloud function code) and traditional Web The front-end code of the application is similar, can be externally obtained and de-obfuscated, and important business logic should be placed in the back-end code or cloud functions.
  5. Background interface calls and cloud function calls must be effectively authenticated.

# currency

# Interface authentication

Interface authentication refers to the background interface (including self-built background interface and cloud function) need to check the permission of the interface call when it is called, otherwise it is prone to ultra vires behavior. Such as product deletion interface, the background should verify the identity of the caller when receiving the request (such as openid、 ip Address, developer-defined login status information, etc.), only the specified user can be deleted through validation.

Ultra vires are usually divided into parallel and vertical vires:

  • Parallel ultra vires

    Parallel overreach refers to overreach between the same roles. A1、 A2 Are regular users, A1 Request the backend interface userinfo.php?id=A1 To get users. A1 Own information. If userinfo.php Permission validation is not performed. The user A1 The request should read userinfo.php?id=A2 You can get access to A2 User's information, causing A2 Disclosure of user information.

  • Vertical ultra vires

    Vertical overreach refers to overreach between different roles. B1 Is the caretaker, B2 Is a regular user. The administrator B1 Request the backend interface getalluserinfo.php Can get information about all registered users if getalluserinfo.php Without permission checks, B2 Users can also request getalluserinfo.php To gain access to all registered users.

Development Proposals:

  1. Sensitive data and capability related interfaces need to be authenticated in the background. Usually checked. openid、 IP Address, custom login status and other information.

  2. The authentication logic should be placed in the background, and should not be replaced by hidden pages and hidden buttons in the front end of the Mini Program. Reference Principle 4.

  3. Authentication code example (for reference only)

    • Self-built backend authentication

      function actionDelete(){
          $item_id = $_POST["item_id"] 
          $openid  = $_POST["openid"]
          $ip = $_SERVER['REMOTE_ADDR']
          $user_Role = $_SESSION["user_role"]
          if ($openid  === "xxx" &&
              $ip === "192.168.0.101" &&
              $user_Role === "admin") {
                  // To perform a delete operation
                  // ...
                  return 0
              } else {
                  // Recording illegal requests
                  // ...
                  return -1
              }
      }
      
    • Cloud function interface authentication

      exports.main = async (event, context) => {
          const { OPENID, APPID, UNIONID } = cloud.getWXContext()
          if (OPENID === "xxx") {
              // To perform a delete operation
              // ...
          } else {
              // Recording illegal requests
              // ...
          }
      }
      

# Code Management and Leaks

  1. When using Git. svn And other version management tools, will produce .git And so on. Some editors or software also generate temporary files during run time. If these directories or files are taken to production, a source leak may occur.

  2. useMini Program code management platformor github When waiting for a third-party platform, you need to pay attention to project permissions, and do not disclose sensitive, internal projects.

Development Proposals:

  1. Do not synchronize files generated by backup files and version management tools to Web Under the directory.
  2. External access prohibited .git Such as directories and documents.
  3. inMini Program code management platformSuch as management platform to configure the appropriate access right.

# Mini Program

# Information leakage

Sensitive information is data that, if divulged, could be detrimental to the developer's business, partners and users, including but not limited toaccount Appsecret, privileged account information, background encryption key, login account password, user body ID, mobile phone number, Silverbank card number, etc.

Development Proposals:

  1. Sensitive information should not be encoded in plain text, annotated, or reversibly Base64), insecure hash functions such as MD5、 SHA1) and other forms appear in the Mini Program file.

  2. Part of the sensitive information such as the user's bank card number, mobile phone number, etc. need to be desensitized. Commonly used desensitization specifications are as follows:

    Sensitive information type Sample display
    Full name The name has only two words, type the first word, such as:Three. More than two words, only keep the first and last, the rest are typed, such as: KingIV. O**five
    ID Show only the first and last bits, such as: 3****************1
    Phone number After removing the international code, when the number of mobile phone numbers is not less than 10, only the first three digits and the last two digits are displayed, such as: 156*77。When the number of mobile phone numbers is less than 10, only the first and last two digits are displayed, such as: 1289。Country codes can be fully displayed.
    Bank card Show only the last 4 bits, such as:************1234
  3. If sensitive information is leaked, WeChat Open Platform may remove the app and suspend its related services.

# Authorized User Information Changes

1、 Authorized user data change: When some user data is at risk, the platform will clean up the user data. And through the push message server to notify the authorized Mini Program developers in the last 30 days, we recommend that developers pay attention to the response event, and take the initiative to update or clean up the user's avatar and nickname in time to reduce risk.
2、 Authorization User Data Withdrawal: When the user withdraws the authorization information, the platform will notify the Mini Program developer through the message push server, and ask the developer to delete the user information in a timely manner.
3、 Authorized users complete the logout: When the authorized users complete the logout, the platform will notify the mini program developer through the message push server, and please fulfill the corresponding personal information protection obligations in accordance with the law and regulations in a timely manner to protect the rights and interests of users.
Click to viewMessage Push Server Configuration

# Event push example:

# XML
<xml>

<ToUser ><![CDATA[gh_870882ca4b1]]></ToUser >

<FromUserName><![CDATA[owAqB1v0ahK_Xlc7GshIDdf2yf7E]]></FromUserName>

<CreateTime>1626857200</CreateTime>

<MsgType ><![CDATA[event]]></MsgType >

<Event><![CDATA[user_authorization_revoke]]></Event>

<OpenID><![CDATA[owAqB1nqaOYYWl0Ng484G2z5NIwU]]></OpenID>

<AppID><![CDATA[wx13974bf780d3dc89 ]]></AppID>

<RevokeInfo ><![CDATA[1]]></RevokeInfo >

<PluginID><![CDATA[wx13974bf780d3dc89 ]]></PluginID>

< OpenPID><![CDATA[G7esq5NVzP76HIHoB95t4CVBP6to]]></OpenPID>

</xml>

# JSON
{

"ToUserName":  "gh_870882ca4b1",

"FromUserName": "oaKk346BaWE-eIn4oSRWbaM9vR7s",

"CreateTime": 1627359464,

"MsgType": "event",

"Event": "user_authorization_revoke",

"OpenID": "oaKk343WOktAaT2ygsX138BGblrg",

"AppID": "wx13974bf780d3dc89", 

"RevokeInfo":  "1",

"PluginID": "wx13974bf780d3dc89", 

"OpenPID": " G7esq5NVzP76HIHoB95t4CVBP6to"

}

# Event field definition

attribute type Introductions
ToUser string UserName for Mini Programs
FromUserName string Platform Push Service UserName
MsgType string Default is: Event
Event string user_Info_Modified: user profile changes, user_authorization_Revoke: user revocation, user_authorization_Cancellation: User completes the cancellation
CreateTime number Sending time
OpenID string Authorized User OpenID
AppID string Mini Program's AppID
RevokeInfo string Authorization information withdrawn by the user, 1: License Plate Number, 2: Address, 3: Invoice Info, 4: Bluetooth, 5: Microphone, 6: Nickname and Avatar, 7: Camera, 8: Phone Number, 12: WeRun Steps, 13: Location Info, 14: Selected Picture or Video, 15: Selected File, 16: Email Address , 18: Location information selected, 19: Nickname Enter the WeChat nickname selected in the keyboard, 20: Get the WeChat avatar selected in the User Avatar component
PluginID string Plug-in scenario user withdrawal, Plug-in AppID
OpenPID string Plug-in scenario user withdrawal, withdrawal of the user's OpenPID

# Small Program Violation Penalty Information Notice

When there is a violation of the mini program, the platform will notify the mini program developer through the message push server, and it is recommended that the mini program developer pay attention to receiving the relevant notice in time for investigation and rectification, and this notice does not affect the notification methods such as the existing station letter. Click to viewMessage Push Server Configuration

# 1. Event field definition

1.1 Field [Event] is equal to" wxa_punish_event " At the time, it means that this is a notice about the "Mini Program violation incident."

attribute type Introductions
Event string Event Name: wxa_punish_Event, that is, Mini Program violation penalty information
event_type number Event type. 1: Warning2: Functional blocking3: Off the Shelf4: Account Blocking10: Page blocked.
punish_id string Violation Penalty ID, used to uniquely identify each violation
appid string AppID of Penalized Mini Program
punish_Time number Time of violation (UNIX timestamp)
illegal_reason string Reasons for violations
illegal_content string Content violations
Rule_Name string Name of Violation
Rule_url string Breaking Rules Links
adjust_Guide_url string Links to Complaints and Rectification Guidelines
detail string Details of the violation penalty, the content of which is a JSON character string, depending on the event_Type, please refer to the instructions below for the correct parsing of the JSON character string contained in this field
# 1.2 Details of the incident (detailed interpretation)
  • whenevent_type=1timedetailThe JSON character string in

    attribute type Introductions
    warned_type number Warning type. 1: Warning Account Blocking2: Warning function blocked3: Warning off the shelf.
    rectify_deadline number Deadline for warning(UNIX Time Stamp)
    warned_function_names array Warning to block the list of features, if you want to get the list of each feature block duration, you can directly in the warned_ban_Get the corresponding index of days, warned_function_Names and warned_ban_Days is always one-to-one correspondence. (This field is only used when warned_Type = 2)
    warned_ban_days array List of days blocked by warnings. When warned_When type = 1, the list has only one item, which represents the number of days that the Mini Program account is warned to block.When warned_When type = 2, each item in the list represents warned_function_The number of days a feature at the corresponding index in names was warned to block. When warned_When type = 3, the list has only one item, which represents the number of days that the Mini Program is warned to take down.Note: 0 is permanently blocked
  • whenevent_type=2timedetailThe JSON character string in

    attribute type Introductions
    banned_days array A list of days for which a feature item is banned, each item in the list represents banned_function_The number of days a feature at the corresponding index in names was blocked. Note: 0 is permanently blocked
    banned_function_names array The list of banned features, if you need to get the banned duration of each feature in the list, you can directly find the banned feature in the banned list._Get at the corresponding index of days, banned_Days and banned_function_The names are always one-to-one correspondence.
  • whenevent_type=3timedetailThe JSON character string in

    attribute type Introductions
    suspended_days number Days off the shelf. Note: 0 is permanently off the shelf
  • whenevent_type=4timedetailThe JSON character string in

    attribute type Introductions
    banned_days number Number of days the account is blocked. Note: 0 is permanently blocked
  • whenevent_type=5timedetailThe JSON character string in

    attribute type Introductions
    path string Blocked page path

# 2. Event Push Parameters Example

  • event_type=1

    • warned_type=1
      {
          "ToUserName":  "gh_1d6c1222test",
          "FromUserName": "oyeHc4i5LqBbWLVTfnhf-3TZ4BNk",
          "CreateTime": 1699803867,
          "MsgType": "event",
          "Event": "wxa_punish_event",
          "punish_id": "649557",
          "appid":  "wx54a8eaa26606test",
          "punish_time": 1699803865,
          "illegal_reason": Presence induced sharing behavior,
          "illegal_content": [
              "Breach Content Testing"
          ],
          "detail": "{"warned_type":1,"rectify_deadline":1699796571,"warned_function_names":[],"warned_ban_days":[3]}",
          "rule_url": "https://developers.weixin.qq.com/miniprogram/product/index.html#_5-1 - Abuse of Sharing " ,
          "rule_name": "WeChat Mini Program Platform Operation Code 5. Code of Conduct -5.1 Abuse of Sharing Behavior,"
          "adjust_Guide_url": "https://mp.weixin.qq.com/s/73rLZmwPeQ87Q89DYQcfkw " ,
          "event_type": 1
      }
      
    • warned_type=2
      {
          "ToUserName":  "gh_1d6c1222test",
          "FromUserName": "oyeHc4pIdqHZwh80SufyUuIzSenw",
          "CreateTime": 1699795665,
          "MsgType": "event",
          "Event": "wxa_punish_event",
          "punish_id": "649551",
          "appid":  "wx54a8eaa26606test",
          "punish_time": 1699795663,
          "illegal_reason": Presence induced sharing behavior,
          "illegal_content": [
              "Breach Content Testing"
          ],
          "detail": "{"warned_type":2,"rectify_deadline":1699796571,"warned_function_names":[" Share WeChat Moments"," Customer Service Message Interface"],"warned_ban_days":[1,1]}",
          "rule_url": "https://developers.weixin.qq.com/miniprogram/product/index.html#_5-1 - Abuse of Sharing " ,
          "rule_name": "WeChat Mini Program Platform Operation Code 5. Code of Conduct -5.1 Abuse of Sharing Behavior,"
          "adjust_Guide_url": "https://mp.weixin.qq.com/s/73rLZmwPeQ87Q89DYQcfkw " ,
          "event_type": 1
      }
      
    • warned_type=3
      {
          "ToUserName":  "gh_1d6c1222test",
          "FromUserName": " oyeHc4tGxCvPcXlKeFI5tU0jV_is",
          "CreateTime": 1699795665,
          "MsgType": "event",
          "Event": "wxa_punish_event",
          "punish_id": "649551",
          "appid":  "wx54a8eaa26606test",
          "punish_time": 1699795663,
          "illegal_reason": Presence induced sharing behavior,
          "illegal_content": [
              "Breach Content Testing"
          ],
          "detail": "{"warned_type":3,"rectify_deadline":1699796571,"warned_function_names":[],"warned_ban_days":[1]}",
          "rule_url": "https://developers.weixin.qq.com/miniprogram/product/index.html#_5-1 - Abuse of Sharing " ,
          "rule_name": "WeChat Mini Program Platform Operation Code 5. Code of Conduct -5.1 Abuse of Sharing Behavior,"
          "adjust_Guide_url": "https://mp.weixin.qq.com/s/73rLZmwPeQ87Q89DYQcfkw " ,
          "event_type": 1
      }
      
  • event_type=2

    {
        "ToUserName":  "gh_1d6c1222test",
        "FromUserName": "oyeHc4gSrT2S8jG2Ll1ZS16rwqQk",
        "CreateTime": 1699791600,
        "MsgType": "event",
        "Event": "wxa_punish_event",
        "punish_id": "13577492",
        "appid":  "wx54a8eaa26606test",
        "punish_time": 1699791599,
        "illegal_reason": Presence induced sharing behavior,
        "illegal_content": [
            "Breach Content Testing"
        ],
        "detail": "{"banned_days":[1,1],"banned_function_names":[" Share WeChat Moments"," Customer Service Message Interface"]}",
        "rule_url": "https://developers.weixin.qq.com/miniprogram/product/index.html#_5-1 - Abuse of Sharing " ,
        "rule_name": "WeChat Mini Program Platform Operation Code 5. Code of Conduct -5.1 Abuse of Sharing Behavior,"
        "adjust_Guide_url": "https://mp.weixin.qq.com/s/73rLZmwPeQ87Q89DYQcfkw " ,
        "event_type": 2
    }
    
  • event_type=3

    {
        "ToUserName":  "gh_1d6c1222test",
        "FromUserName": "oyeHc4qHkaYV-0NYupPZBTBrBNuw",
        "CreateTime": 1699801563,
        "MsgType": "event",
        "Event": "wxa_punish_event",
        "punish_id": "13577869",
        "appid":  "wx54a8eaa26606test",
        "punish_time": 1699801560,
        "illegal_reason": Presence induced sharing behavior,
        "illegal_content": [
            "Breach Content Testing"
        ],
        "detail": "{"suspended_days":1}",
        "rule_url": "https://developers.weixin.qq.com/miniprogram/product/index.html#_5-1 - Abuse of Sharing " ,
        "rule_name": "WeChat Mini Program Platform Operation Code 5. Code of Conduct -5.1 Abuse of Sharing Behavior,"
        "adjust_Guide_url": "https://mp.weixin.qq.com/s/73rLZmwPeQ87Q89DYQcfkw " ,
        "event_type": 3
    }
    
  • event_type=4

    {
        "ToUserName":  "gh_1d6c1222test",
        "FromUserName": "oyeHc4jjAdCWq1klrk-puPMe0FC4",
        "CreateTime": 1699784111,
        "MsgType": "event",
        "Event": "wxa_punish_event",
        "punish_id": "9328325",
        "appid":  "wx54a8eaa26606test",
        "punish_time": 1699784109,
        "illegal_reason": Presence induced sharing behavior,
        "illegal_content": [
            " Test the offending content/evidence "
        ],
        "detail": "{"banned_days":3}",
        "rule_url": "https://developers.weixin.qq.com/miniprogram/product/index.html#_5-1 - Abuse of Sharing " ,
        "rule_name": "WeChat Mini Program Platform Operation Code 5. Code of Conduct -5.1 Abuse of Sharing Behavior,"
        "adjust_Guide_url": "https://mp.weixin.qq.com/s/73rLZmwPeQ87Q89DYQcfkw " ,
        "event_type": 4
    }
    
  • event_type=10

    {
        "ToUserName":  "gh_1d6c1222test",
        "FromUserName": "oyeHc4n0I6U3A4Fq7tfOAqmAJy8E",
        "CreateTime": 1699802583,
        "MsgType": "event",
        "Event": "wxa_punish_event",
        "punish_id": "94185814",
        "appid":  "wx54a8ea266009d6a" 
        "punish_time": 1699802425,
        "illegal_reason": "posting vulgar, sexually suggestive or pornographic information,"
        "illegal_content": [
            "test the evidence."
        ],
        "detail": "{" path":"pages/fengjin/fengjin"}",
        "rule_url": "https://developers.weixin.qq.com/miniprogram/product/index.html#_6-2 - Porn Vulgar Content " ,
        "rule_name": "WeChat Mini Program Platform Operation Specification 6. Information Content Specification - 6.2. Pornographic and vulgar content."
        "adjust_Guide_url": "https://mp.weixin.qq.com/s/73rLZmwPeQ87Q89DYQcfkw " ,
        "event_type": 10
    }
    

# Backend (including cloud functions and self-built backend)

# Injection vulnerability

Injection vulnerability (SQL, Commands, etc.) usually refers to the user bypassing the background code restrictions and working directly in the database, shell Execute custom code inside.

Common injection vulnerabilities are:

# SQL injection

SQL Injection means Web Program code for the user-submitted parameters do not do effective filtering directly spliced to the SQL Statement, causing the special characters in the arguments to break SQL Statement original logic, hackers can use this vulnerability to execute arbitrary SQL Statement.

Development Proposals:

  1. Use parametric queries provided by the database to carry out database operations, do not allow directly through the stitching of character strings to the composition SQL Statement.
  2. If there are some situations that need to be synthesized by splicing SQL Variables must be processed:
    • For integers, you need to determine whether the variable is an integer type.
    • For character strings, you want to escape single quotes, double quotes, and so on.
  3. avoid Web Application display SQL The error message.
  4. ensure Web Uniform coding of each data layer in the application.

# Command injection

A command injection vulnerability is Web The application does not filter the user-controllable parameters effectively, and the attacker can construct malicious parameters to execute arbitrary commands.

Development Proposals:

  • To the data entered by the user (such as 、|, &, etc.) for filtering or escaping.

# Weak password

Weak password means that the user name and password of the administrative background is set relatively simple or use the default account. Attackers can log in to these accounts to modify the background data or the next step of the intrusion operations.

Development Proposals:

  1. Background services disable the default account, change the background weak password.
  2. Sensitive services to increase the secondary verification mechanism, such as SMS verification code, email verification code.

# File upload vulnerability

A file upload vulnerability means Web The application allows the user to upload the specified file, but does not verify the validity of the file type and format, so that the file can be uploaded in an unexpected format.

Development Proposals:

  • Correctly parse the file type of the uploaded file, and limit the file type that can be uploaded by whitelist.

# File download

File download vulnerability refers to Web The application allows the user to download the corresponding file by specifying the path and file name, but does not properly limit the directory where the downloadable file is located, resulting in the download of files outside the expected range.

Development Proposals:

  1. Correctly limit the scope of the directory where the downloadable file is located
  2. By designatefile id The way to find the download of the corresponding file

# Directory traversal

Directory traversal refers to the server directory content leakage caused by insufficient validation of user input by back-end services or improper configuration. External directory traversal may get system files, background code and other sensitive files.

Development Proposals:

  1. web Service Configuration

    • The server prohibits the display of directories
    • Set directory access right
    • Under each directory place an empty index.html page
  2. web Application code

    • Strictly check the file path parameters and limit the scope of the file

# Conditional competition

A common example of conditional competition is when an attacker uses concurrent https Request to achieve multiple awards, multiple harvests, multiple gifts and other abnormal logic can trigger the effect.

  • Vulnerability Code Examples

    // Query the remaining number of awards from the DB, and the initial value is 1
    int Remain_times = SelectRemainTimes()
    
    if(Remain_times > 0){
        EarnRewards()          // Users are rewarded
        ClearRemainTimes()     // In the DB to clear the user's remaining number of awards
    }
    

    The developer's design is intended to allow the user to receive a reward only once, but when there are concurrent requests, it is possible that a request may occur A And requests B The second line of code is executed, at which point the two requests Remain_times Are 1, that is, you can judge by the fourth line of code, get two rewards.

Development Proposals:

  • A lock operation on critical (complete) logic or processing of critical logic in the form of queued tasks.