# Common risks and recommendations for dealing with them

Weixin Mini Program During the routine security inspection, the team found that some Weixin Mini Program have unauthorized or lax interface security risks. In order to efficiently identify and handle vulnerabilities and avoid threats and losses to the developer's own business, this article takes stock of the security risks that often occur during the development of Mini Programs. developers are encouraged to pay attention to Mini Programs and self-correct their own Mini Programs before and after launch.

# I. Business risks

# 1.1 Interface Privilege

Risk Identification

Interface authorization means that a backend interface (including self-built backend interfaces and cloud functions) needs to verify permission for this interface call when it is called, otherwise it is prone to over-privileges.

For example, the item removal interface, the background should verify the caller's identity information (such as openid, ip address, developer-custom login information, etc.) when receiving the request, and only the specified user can be verified for removal.

Overreach is usually divided into parallel overreach and vertical overreach:

(1) Parallel overriding power

Parallel ultra vires refers to the ultra vires between the same role, the user can access the other user data or operation interface under the same permission.

A1, A2 are ordinary users, A1 through the request background interfaceuserinfo.php?Id = A1to get user A1's own information. If userinfo.php does not perform a permission check, user A1 changes the request touserinfo.php?Id = A2can obtain A2 user information, resulting in A2 user information disclosure.

(2) vertical oversight

Vertical overreach refers to overreach between different roles, where the system fails to properly verify user rights and the user can access unauthorized resources.

B1 is an administrator, and B2 is a normal user. Administrator B1 can get the information of all registered users by requesting the back-end interface getalluserinfo.php. If getalluser info.php does not perform permission checking, the B2 user can also request getalluserdetails.php to get the information for all registered people, and there is a pervert.

(3) Not authorized

Section Weixin Mini Program does not set a login authorization check because the business is public information.As a result, the interface will be used by black and grey enterprises to conduct malicious activities such as information sales and information monitoring.

Users can access the details directly through information such as order ID, mobile number, license plate and so on without logging in.

Addressing recommendations

Regardless of whether the business model requires authentication, you should set up authentication validation and record detailed operational logs for subsequent analysis and malicious risk identification.

Sensitive data and capability-related interfaces need to be authenticated in the background. Information such as openid, IP address, custom login state can usually be checked.

The authentication logic should be carried out in the background, and should not be replaced by hidden pages, hidden buttons, etc. in the Weixin Mini Program front end.

Examples of contextual code (for informational purposes only)

// Build your own back office.
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") {
            // 进行删除操作
            // ...
            return 0;
        } else {
            // 记录非法请求
            // ...
            return -1;
        }
}
// Cloud Function Interface Privilege
exports.main = async (event, context) => {
    const { OPENID, APPID, UNIONID } = cloud.getWXContext();
    if (OPENID === "xxx") {
        // 进行删除操作
        // ...
    } else {
        // 记录非法请求
        // ...
    }
}

# 1.2 Breach of business information

Risk Identification

Sensitive information refers to information that could be potentially damaging to a developer's business,Data harmful to partners and users, including but not limited to account AppSecret, privileged account information, back-end encryption keys, login account passwords, user ID numbers, mobile phone numbers, bank card numbers, etc. .

Addressing recommendations

Sensitive information should not appear in Weixin Mini Program files in the form of plaintext, annotations, reversible encoding (e.g., base64), unsafe hash functions (e.g., MD5, SHA1), etc.

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 Show examples
Full name The name has only two words, the first word is coded, such as:*three.More than two words, keep only the first and last one, the rest are coded, such as: Wang*four, Ou** five
ID Only the first and last bits are displayed, such as: 3****************1
Mobile phone number Excluding the international code of the phone, when the number of numbers of the phone is not less than 10, only the first three and last two are shown, such as: 156******77。When the number of phone numbers is less than 10, only the first two and the last two are shown, for example: 12*****89。The national code can be fully displayed.
Bank card Only the last 4 bits are displayed, such as:***\ [\ [*******1234

If Weixin Mini Program has a problem with the disclosure of sensitive information, WeChat may remove the Mini Program and suspend the service of the Mini Program.

# 1.3 Authorized User Information Change

Risk Identification

The developer obtained user data through the Weixin Mini Program API with the explicit consent of the user,When encountering cases where user data is expired, users voluntarily revoke, users log out of accounts, etc., developers need to clean up the user data previously obtained in a timely manner, fulfill the corresponding personal information protection obligations in accordance with regulations, and protect the rights and interests of users.

Addressing recommendations

Developers need to set up a Messaging Server configuration to receive and process notifications of authorization information from the WeChat platform in a timely manner. For more information, see this document

# 1.4 The crawlers are all over the place

Risk Identification

If the message retrieval interface uses digital self-increasing ID (or has a specific rule), and the interface does not do man-machine and login authentication, it is easy to cause data information to be dragged.

Addressing recommendations

The ID information should not be simply incremented, and if it must be incremented, the suffix should be added with a random code.

The numeric ID is encrypted, and only the ID query request is received by the server.

# 1.5 Weak password

Risk Identification

A weak password refers to a user name password that is relatively simple to set up for managing the background or using the default account. An attacker could modify the backend data or make the next intrusion by logging into these accounts.

Addressing recommendations

Background service to disable the default account name (such as root, admin, administer, master, etc.), modify the background weak password.

Sensitive services add secondary verification mechanisms, such as SMS verification codes, mailbox verification Codes, etc.

# II. Development risk

# 2.1 Code management and leakage

Risk Identification

When using version management tools such as git, svn, etc., directories such as.git are generated. Some editors or software also generate temporary files during run time. If these directories or files are brought to a production environment, a source code leak can occur.

When using Weixin Mini Program code management platforms or Third Party Platform such as github, be careful with project permissions and don't expose sensitive, internal projects.

Addressing recommendations
  1. Backup files and files generated by versioning tools should not be synchronized to Web directories.
  2. Disable external access to directories and files such as.git.
  3. Configure appropriate access right within management platforms such as Weixin Mini Program code management platform .

# 2.2 SQL injection vulnerability.

Risk Identification

SQL injection refers to the Web program code for user-submitted parameters directly spliced into SQL statements without effective filtering, resulting in the parameters of the special character to break the original logic of SQL statements, hackers can take advantage of this vulnerability to execute arbitrary SQL statements.

Addressing recommendations

Use the parametric inquiry that the database provides to carry on the database operation, do not allow to compose SQL statement directly through the way of joining together the character string.

If there are some cases that need to be concatenated to synthesize SQL, the concatenated variables must be processed: "For integers, we need to determine whether the variable is an integer type; For character strings, escape single quotes, double quotes, etc. "

Avoid web applications displaying SQL error messages.

Ensure uniform coding for each data layer in a web application.

# 2.3 Command Injection Vulnerability

Risk Identification

Command injection vulnerability means that the Web application does not filter the user's controllable parameters effectively, and the attacker can construct malicious parameters to execute arbitrary commands.

Addressing recommendations

Data entered by the user (e.g.;、 |, &, etc. filter or translate.

Do not trust the front end (WEB, Weixin Mini Program) to send any content of the request, all parameters are type verified, and avoid directly using the command passed by the front end to execute.

# 2.4 File upload vulnerability

Risk Identification

File upload vulnerability refers to a web application that allows users to upload specified files, but does not verify the correctness of the document type, format, etc., resulting in uploading files in unexpected formats.

Addressing recommendations

Correctly parse the file type of the uploaded file and limit the types of files that can be uploaded by whitelisting.

# 2.5 File Download

Risk Identification

A file download vulnerability is when a Web application allows the user to download the corresponding file by specifying the path and file name, but does not correctly limit the range of directories where the downloadable file is located, resulting in the download of files outside the intended range.

Addressing recommendations

Correctly limit the range of directories in which files can be downloaded

Find the downloaded file by specifying the file id

# 2.6 Directory Throughout

Risk Identification

Directory traversing is a leak of the contents of a server's directory caused by a back-office service that fails to verify user input or is poorly configured. Externally, sensitive files such as system files, background code, etc. may be obtained through directory traversals.

Addressing recommendations

Web service configuration

  • The server forbids displaying directories
  • Set directory access right
  • Place an empty index.html page under each directory

Web application code

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

# 2.7 Competition on Conditions

Risk Identification

The more common example of conditional competition is that the attacker achieves multiple awards, multiple harvests, multiple gifts and other abnormal logic triggered by concurrent https requests. Example of vulnerability code

// Query the remaining number of awards from the DB, and the initial value is 1
int remain_times = SelectRemainTimes();

if(remain_times > 0){
    EarnRewards();          // 用户获得奖励
    ClearRemainTimes();     // 在DB里把该用户的剩余获奖次数清零
}

The developers were designed to allow users to receive a reward only once, but when concurrent requests occur, There is a possibility that both request A and request B have just finished row 2 of code, when both requests have a remain_times of 1, which means that two rewards can be judged by row 4 of code.

Addressing recommendations

Lock operations on critical (complete) logic or process critical logic as a queue task.

# III. CONCLUSIONS

Developers must always base their development on the following principles:

  1. The principle of non-trust. Do not trust the data submitted by users, including those provided by third-party systems. The necessary data validation must be placed in the background.
  2. The principle of minimum permissions is that code, modules, etc. have only the minimum permissions that can accomplish the task, and do not give unnecessary permissions.
  3. Explicit storage of user sensitive data is prohibited.
  4. Weixin Mini Program Code (excluding cloud function code) is similar to the front-end code of a traditional Web application and can be externally obtained and counter-communicated, and important business logic should be located in back-end code or cloud functions.
  5. Background interface calls and cloud function calls must be effectively authenticated.