[Web Practical Combat] Zero-based WeChat applet reverse engineering (very detailed) From zero-based entry to mastery, just read this article

This article takes the WeChat applet as an example and starts from actual combat to explain the penetration of the new attack surface of the applet, which is helpful to understand the security and preventive measures of the applet.

What is a mini program?

As a unique program form in China, mini programs have become ubiquitous in our daily lives. Major Internet companies such as Tencent, Baidu, Alibaba, ByteDance, and JD.com have their own ecological platforms. Of course, there are also industry alliance-type ecological platforms such as Kuai App.
Insert image description here

Compared with traditional APP development, the differences between small programs are (take WeChat as an example)

Insert image description here

WeChat Mini Program Architecture Analysis

The entire mini program framework system is divided into two parts: the logic layer (App Service) and the view layer (View). The applet provides its own view layer description language WXML and WXSS, as well as a logic layer framework based on JavaScript, and in the view layer Data transmission and event systems are provided between the logic layer and the logic layer, allowing developers to focus on data and logic.

Insert image description here

Logical layer App Service

The logic layer of the mini program development framework uses the JavaScript engine to provide the development JavaScript code running environment for the mini program as well as the unique functions of the WeChat mini program.

The logic layer processes the data and sends it to the view layer, and at the same time accepts event feedback from the view layer.

All the code written by the developer will eventually be packaged into a JavaScript file and run when the mini program starts until the mini program is destroyed. This behavior is similar to ServiceWorker, so the logic layer is also called App Service.

Based on JavaScript, WeChat has added some functions to facilitate the development of mini programs:

  • Added App and Page methods for program registration and page registration.

  • Added getApp and getCurrentPages methods to obtain the App instance and the current page stack respectively.

  • Provides rich APIs, such as WeChat user data, scanning, payment and other WeChat-specific capabilities.

  • Provides modular capabilities, and each page has an independent scope.

Note: The logic layer of the mini program framework does not run in the browser, so JavaScript some capabilities cannot be used in the web, such aswindow, document etc.

View layer View

The view layer of the framework is written in WXML and WXSS and displayed by components.

Reflect the data of the logical layer into the view, and send the events of the view layer to the logical layer.

WXML (WeiXin Markup language) is used to describe the structure of the page.

WXS (WeiXin Script) is a script language for small programs. Combined with WXML, the structure of the page can be constructed.

WXSS (WeiXin Style Sheet) is used to describe the style of the page.

Component is the basic unit of view.

Directory Structure

The applet contains a app that describes the overall program and multiple page that describe each page.

The main part of a small program consists of three files, which must be placed in the root directory of the project, as follows:

document required effect
app.js yes Mini program logic
app.json yes Mini program public configuration
app.wxss no Mini program public style sheet

A mini program page consists of four files, namely:

file type required effect
js yes Page logic
wxml yes Page structure
json no Page configuration
wxss no Page style sheet

Note: In order to facilitate developers to reduce configuration items, the four files describing the page must have the same path and file name.

Insert image description here

Judging from the above-mentioned architecture diagram and file components, the focus of analysis is the logic layer of the mini program. The main components of the logic layer are app.js, app.json, js files, json configuration files, etc., so these are the main objects analyzed during the test process.


WeChat Mini Program Source Code Extraction and Common Vulnerabilities

test preparation

system

windows

Common tool

name use download link
wxappUnpacker Mini program source code acquisition tool
wxapkgconvertor Mini program source code acquisition tool https://github.com/ezshine/wxapkg-convertor/releases
UnpackMiniApp Mini program decryption
WeChat Developer Tools Debugging the obtained applet code https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
BurpSuite Packet capture analysis test https://portswigger.net/burp
proxifier traffic proxy https://www.proxifier.com/

Test starts

Mini program search

The author’s commonly used search methods are to use the search function of WeChat’s official mini program interface and the 0.zone platform of Beijing Lingling Xin’an Technology Co., Ltd., which can fully automatically collect the target enterprise APP (APK) list, download address and its detailed introduction, etc. Information, semi-automatic collection of lists, names and addresses of mini programs, public accounts, life accounts, etc. Compared with the official search function, you can search for targets more accurately.

Insert image description here

Insert image description here

Source code extraction

location lookup

Use the Windows version of WeChat, open the applet to be tested, and click Settings-File Management-Open Folder.

Insert image description here

There is a folder named Applet in the WeChat Files directory. The folder starting with "wx" is the applet folder. If you have opened many WeChat mini programs before, there will be multiple mini program folders in the directory. The first method of differentiation is to differentiate based on modification time. The second method is to delete all browsed mini programs on the WeChat page and reopen the mini program that needs to be tested. Then there will only be one mini program folder in the directory.
Insert image description here

The file name is__APP__.wxapkg, which is an encrypted file.

Mini program decryption

The encryption method is as follows:

  • First, pbkdf2 generates the AES key. Use the WeChat applet id string as pass, salt as saltiest, and the number of generations to choose is 1000. Call pbkdf2 to generate a 32-bit key.

  • Take the first 1023 bytes of the original wxapkg package and encrypt it with the key and iv generated by AES 1 (the iv: 16 bytes).

  • Then use the penultimate character of the WeChat Xiaocheng ID string as the xor key, and sequentially XOR all the data after 1023 bytes. If the WeChat applet ID is less than 2 digits, the xorkey is 0x66.

  • Write the AES encrypted data (1024 bytes) and the xor data to the file together, and add the V1MMWX logo to the file header.

Insert image description here

The decryption tool used here is UnpackMiniApp.exe written by Code Guo. To use it, click "Select Encrypted Mini Program Package" and select the one to be decrypted__APP__.wxapkg, which will be displayed in UnpackMiniApp.exe The decrypted file is generated in the wxpack folder of the current directory.
Insert image description here

Note: Be sure to select the original location of the WeChat applet. Moving the file to be tested__APP__.wxapkg will cause the APPID to be unrecognized, resulting in decryption failure!

Insert image description here

wxapkg package file structure

After decryption, use 010Editor to open the file. It can be seen that the wxapkg package consists of three parts, namely the header segment, the index segment, and the data segment.

Head section

It starts with "BE" and ends with "ED", which contains 4 "00" blank paddings. The index segment length block and data segment length block for verification are four bits each, with a fixed length of 14 bytes.

Insert image description here

index segment

The first is 4 bytes, which is the number of files in the package. For example, "00 00 00 5F" represents a total of 95 files, and then the information about the files in the package. For example: "00 00 00 16" represents the length of the file name. 22 bytes, "2F 72 65 6F... 2E 70 6E 67" is the file name with the storage path, "00 00 11 7C" corresponds to the specific offset position of the file in the small program package, "00 01 01 F7" corresponds The data length of the file in the applet package.

Insert image description here

data segment

The data segment is the stored file content, which can be matched one-to-one through the information of the index segment.

Insert image description here
)

Mini program decompilation

Through the index segment and data segment, we can already restore a general file structure

Insert image description here

But this is not the original project file structure. The reason is that the WeChat server will push all the "js" files in the mini program source code into the "app-service.js" file and all the "json" files into the "app -config.json", push all "wxml" files into the "page-frame.html" file, and "wxss" will be stored in the corresponding page directory in the form of "html" files after processing.

The author will not go into details about the restoration of respective files. I recommend using wxappUnpacker and wxapkgconvertor. Both of them can directly decompile the decrypted wxapkg package and directly restore the file structure of the original project.

The command to use wxappUnpacker is:

node wuWxapkg.js xxxxxx.wxapkg  

The use of wxapkgconvertor is more portable. Drag the wxapkg package to be decompiled directly into the program window, and you can obtain the applet project folder with the same name in the same directory as the applet package location.

common problem
There is sub-packaging (that is, there are multiple .wxapkg files in the folder)

Decrypt them separately, decompile them, and put them together in the same directory.

After using wxappUnpacker, the "app-service.js" / "app-config.json" / "page-frame.html" / ".html" files were not successfully decompiled:
  • Split the content in app-config.json into page.json and app.json corresponding to each page;
node wuConfig.js <path/to/app-config.json>  

  • Split app-service.js into a series of original independent JS files, and use the Uglify-ES beautification tool to restore the code to the content before "compilation" as much as possible;
node wuJs.js <path/to/app-service.js>  

  • Extract and restore the .wxml, app.wxss and public .wxss style files of each page from page-frame.html;
node wuWxml.js \[-m\] <path/to/page-frame.html>  

  • The command parameter is the unpacked directory of .wxapkg. It will analyze and extract and restore the page.wxss style files of each page from each page.html.
node wuWxss.js <path/to/unpack\_dir>  

Security risks and vulnerabilities

After obtaining the source code, we can load it into the WeChat developer tools for debugging.

The following is a list of common WeChat mini program vulnerabilities in actual combat:

information leakage

Sensitive information refers to data that may cause harm to the developer's business, partners and users if leaked, including but not limited to account AppSecret, privileged account information, background encryption keys, login account passwords, user ID numbers, Mobile phone number, bank card number, etc.

You can use the search function in WeChat Developer Tools to search for keywords such as "appid", "key", and "phone".

Insert image description here

Insert image description here

Let’s talk about the utilization of AppID and AppSecret. After obtaining this information, you can access the WeChat open platform debugging tool (https://developers.weixin.qq.com/apiExplorer) and match the interface document according to the code content of the mini program. for further use.

Tip: The WeChat Mini Program Developer Tool adds AppSecret detection in the code quality analysis module after version 1.06.2206020, so AppSecret leaks can only be found in mini programs developed before 2022-06-02.

Insert image description here

SQL injection

SQL injection means that the parameters submitted by users in the web program code are directly spliced ​​into the SQL statement for execution without effective filtering. As a result, the special characters in the parameters break the original logic of the SQL statement. Hackers can use this vulnerability to execute any SQL statement.

Through proxifier's traffic proxy and BurpSuite's packet capture, we can test the function points when the mini program is running.

proxifier configuration:

Set ip to 127.0.0.1, port custom HTTPS protocol proxy server

Insert image description here

Add rule: program "wechatappex.exe", action is the proxy server just set

Insert image description here

BurpSuite configuration:

Configure the proxy server, the port is the custom port just set, the address is 127.0.0.1

Insert image description here

Through SQL injection testing on the mini program function points, the database user name was successfully returned.

Insert image description here

weak password

Weak passwords mean that the username and password of the management backend are set relatively simply or the default account is used. Attackers can log in to these accounts to modify the background data or conduct further intrusion operations.

After auditing the code of the mini program, a backlink domain name was found, and the access was found to be the management backend.

Insert image description here

Insert image description here

Use username: admin and password: 123456 to successfully log in to the backend and obtain a large amount of information.

Insert image description here

common problem
After importing the decompiled source code into the WeChat developer tool, the error "app.js error: TypeError: _typeof3 is not a function" is reported.

Find the file @babel/runtime/helpers/typeof.js according to the error prompt

Delete everything and replace it with

function _typeof2(o) {    
  "@babel/helpers - typeof";    
  return (_typeof2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {    
      return typeof o;    
  } : function(o) {    
      return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;    
  })(o);    
}    
function _typeof(o) {    
  return "function" == typeof Symbol && "symbol" === _typeof2(Symbol.iterator) ? module.exports = _typeof = function(o) {    
      return _typeof2(o);    
  } : module.exports = _typeof = function(o) {    
      return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : _typeof2(o);    
  }, _typeof(o);    
}    
module.exports = _typeof;  

Error "Dependency Exception" reported

Because the variable restoration of the program during the decompilation process is inaccurate, it can be repaired by comparing the restored directory results and deleting redundant paths in the calling code.

Test summary

Mini program developers must be based on the following principles during the development process:

Based on the principle of mutual distrust, do not trust the data submitted by users, including data provided by third-party systems. Necessary data verification must be performed in the background.

The principle of least privilege means that code, modules, etc. only have the minimum permissions that can complete the task, and no unnecessary permissions are given.

It is prohibited to store sensitive user data in clear text.

Mini program code (excluding cloud function code) is similar to the front-end code of traditional web applications and can be obtained and deobfuscated externally. Important business logic should be placed in the back-end code or cloud function.

Backend interface calls and cloud function calls must undergo effective identity authentication.


Original link: https://forum.butian.net/share/2570


How to learn hacking & network security

As long as you like my article today, my private network security learning materials will be shared with you for free. Come and see what is available.

1. Learning roadmap

There are a lot of things to learn about attack and defense. I have written down the specific things you need to learn in the road map above. If you can complete them, you will have no problem getting a job or taking on a private job.

2. Video tutorial

Although there are many learning resources on the Internet, they are basically incomplete. This is an Internet security video tutorial I recorded myself. I have accompanying video explanations for every knowledge point in the roadmap above.

The content covers the study of network security laws, network security operations and other security assessments, penetration testing basics, detailed explanations of vulnerabilities, basic computer knowledge, etc. They are all must-know learning contents for getting started with network security.

(They are all packaged into one piece and cannot be expanded one by one. There are more than 300 episodes in total)

Due to limited space, only part of the information is displayed. You need to click on the link below to obtain it.

CSDN gift package: "Hacker & Network Security Introduction & Advanced Learning Resource Package" free sharing

3. Technical documents and e-books

I also compiled the technical documents myself, including my experience and technical points in participating in large-scale network security operations, CTF, and digging SRC vulnerabilities. There are more than 200 e-books. Due to the sensitivity of the content, I will not display them one by one.

Due to limited space, only part of the information is displayed. You need to click on the link below to obtain it.

CSDN gift package: "Hacker & Network Security Introduction & Advanced Learning Resource Package" free sharing

4. Toolkit, interview questions and source code

"If you want to do your job well, you must first sharpen your tools." I have summarized dozens of the most popular hacking tools for everyone. The scope of coverage mainly focuses on information collection, Android hacking tools, automation tools, phishing, etc. Interested students should not miss it.

There is also the case source code and corresponding toolkit mentioned in my video, which you can take away if needed.

Due to limited space, only part of the information is displayed. You need to click on the link below to obtain it.

CSDN gift package: "Hacker & Network Security Introduction & Advanced Learning Resource Package" free sharing

Finally, here are the interview questions about network security that I have compiled over the past few years. If you are looking for a job in network security, they will definitely help you a lot.

These questions are often encountered when interviewing Sangfor, Qi Anxin, Tencent or other major companies. If you have good questions or good insights, please share them.

Reference analysis: Sangfor official website, Qi’anxin official website, Freebuf, csdn, etc.

Content features: Clear organization and graphical representation to make it easier to understand.

Summary of content: Including intranet, operating system, protocol, penetration testing, security service, vulnerability, injection, XSS, CSRF, SSRF, file upload, file download, file inclusion, XXE, logical vulnerability, tools, SQLmap, NMAP, BP, MSF…

Due to limited space, only part of the information is displayed. You need to click on the link below to obtain it.

CSDN gift package: "Hacker & Network Security Introduction & Advanced Learning Resource Package" free sharing

Guess you like

Origin blog.csdn.net/Python_0011/article/details/134681114