bubictf-2019

대회 문제 & CTF 2019. 11. 21. 16:45

https://github.com/grigoritchy/bubictf-2019?fbclid=IwAR1D9dxheOb_WVVRNvUnCmWR9U8TwrqrfWfJq0jo7PQP0oojkHU6izQeDkE

불러오는 중입니다...

 

Challenges

  • Binary From Web

  • Custom Printf Pt.II

  • Hex Gaming

  • SickMode VM

 

'대회 문제 & CTF' 카테고리의 다른 글

CTF Write up 참고  (0) 2022.05.30
블로그 이미지

wtdsoul

,

https://teamcrak.tistory.com/380?category=180158

 

Shellshock 분석 및 테스트

Shellshock 분석 및 테스트 maz3 (maz3@a3security.com) CrazyPure (jschoi@a3security.com) Shellshock 취약점은 리눅스를 포함한 유닉스 계열 운영체제에서 사용되는 명령어 실행 툴인 bash로부터 발생하는 취약..

teamcrak.tistory.com

 

 

 

https://www.krcert.or.kr/filedownload.do?attach_file_seq=869&attach_file_id=EpF869.pdf

불러오는 중입니다...

 

20141112_GNU_Bash_원격코드실행_취약점_이슈분석_및_대응방안_보고서.pdf
0.85MB

https://m.blog.naver.com/renucs/220144713558

 

Bash 취약점(CVE-2014-6271) 원리 및 공격기법의 이해

올 해 Heart Bleed 이후 가장 파급력이 크다는 bash 쉘쇼크(Shell shock) 취약점으로 인해 며칠 간 보안...

blog.naver.com

 

1. bash 취약점 확인 방법

bash 취약점은 간단하게 확인 할 수 있습니다. 프롬프트 상에서 

 env x='() { :;}; echo vulnerable' bash -c "echo test"

​명령을 실행하는 것 만으로도 확인이 가능합니다. 

 

<그림 1> 환경변수 x='() {:;}' 이 후 명령이 수행 사례 

 

 

환경변수 설정을 하는 env 를 통해 환경변수 x = (함수명) {수행코드}; 라고 환경변수를 등록하는 ; ② 까지는 정상적인 동작이나, 그 이후에 삽입되어 있는 echo vulnerable' bash -c "echo test" ③의 명령어는 무시되거나 오류를 발생해야 하지만 실제로는 수행이되어 화면상에    

vulnerable 
test

를 출력하는 것을 알 수 있습니다.

전형적인 입력값 유효성 검증이 정상적으로 수행되지 않은 버그 이며 이를 통해 다양한 공격이 가능합니다.

 

2. bash를 통한 공격

bash 취약점이 보고 되고 몇몇분들이 콘솔이나 ssh 같은 터미널 접속만 차단되면 크게 문제가 없지 않느냐는 이야기를 했습니다. 하지만 콘솔 환경이 아니더라도 bash 수행이 가능한 몇 가지 환경이 있는데 가장 알기쉬운 웹서비스 요청 환경을 가정하여 공격 시나리오를 만들어 보도록 하겠습니다.

 

1) CGI 요청을 통한 bash 수행

 

웹 서버에 bash를 이용한 CGI 실행 설정이 되어 있는 경우, 사용자가 해당 cgi 페이지를 요청하면 웹서버에서 요청 결과를 bash 에 전달하고 수행 결과를 받아 사용자에게 응답을 해주는 동작 구조를 가지고 있습니다.

즉, 브라우저 요청 패킷에 bash 취약점 코드를 삽입하여 전송하면 해당 코드가 bash에서 실행이 가능합니다.

 

2) 일단 테스트 환경에서 Apache에 cgi 실행이 가능하도록 설정을 한 후 테스트를 위한 간단한 cgi 코드를 작성합니다.

 

 

사용자에게 ShellShock Test 라는 문장을 화면에 출력해주는 간단한 코드 입니다.

테스트 삼아 해당 페이지를 호출해 볼까요?

 

 

의도한 대로 잘 출력 되는것을 확인 할 수 있습니다.

 

3) 요청 헤더에 bash 취약점을 이용한 명령어 삽입

HTTP요청 헤더에 쉘코드를 삽입하는 방법은 여러가지가 있습니다. curl 같은 웹페이지 요청 유틸을 사용 할 수도 있고 파이썬 같은 스크립트 언어로 간단하게 구현 할 수 도 있습니다.

본 포스팅에서는 가장 손쉽게 요청 메세지를 조작 할 수 있도록 프록시를 사용하겠습니다.

 

우선 테스트로 만들어 둔 cgi 페이지를 정상적으로 요청 할 경우 패킷 입니다.

별 특이 사항은 눈에 띄지 않습니다. (프록시는 Burp Suit 가 수고해 주셨습니다.)



다음은 HTTP 요청의 헤더부분 중 사용자 브라우저 정보를 담고 있는 User-Agent 부분에 bash 명령어를 삽입합니다.(Cookie, Referrer 등 다른 헤더값 이라도 상관없습니다.)

 

 

() { :;}; echo bashtest>/tmp/test 라는 명령어를 헤더에 삽입하여 "bashtest" 라는 문자를 /tmp 디렉토리에 test라는 파일을 생성하여 기록하도록 합니다.

 

해당 요청 조작이 완료되면 패킷을 전송합니다. 그 결과는. . 

 



브라우저에 500코드 내부 오류가 발생했다는 메세지를 출력해 줍니다.

일단 전송은 정상적으로 된 듯 하니 실제로 해당 명령이 정상적으로 수행되었는지 확인해 보겠습니다.

 

4) 결과 확인

 

 

/tmp 디렉토리에 test 라는 파일이 생성된 것을 확인 할 수 있고, test 파일의 내용을 보니 브라우저로 요청했던 bashtest 라는 문자열이 저장되어 있는 것을 볼 수 있습니다.

 

실제 테스트에 사용한 명령은 PoC코드라 단순하게 파일 생성 기능만 수행했으나, wget 으로 특정 악성코드를 다운로드 받아 실행하거나 서버내부의 환경설정 파일을 읽어온다던가 리버스커넥션을 통한  백도어를 만드는 것도 가능합니다. 즉, 원격으로 모든 명령어 실행이 가능하다는 것 입니다.

 

3. 대응 방법

가장 간단한 방법은 bash 패치를 수행하면 됩니다.

 yum -y update bash (레드헷 계열 기준) 

yum 이나 atp-get 을 사용 할 수 없는 환경이라면 직접 재 컴파일이 필요하지만, bash 같은 쉘 프로그램을 직접 컴파일 하기에는 아무래도 부담 스럽겠죠;

 두번째 방법은 임시 조치지만 SNORT 같은 N-IDS 에서 HTTP HEADER 값에 () {  라는 문자열이 포함되어 있는지 Rule 을 세팅하여 탐지하는 방법이 있습니다.(일반적인 경우라면 http 헤더값에 () { 이 들어 갈 일이 없겠죠)

 

 

<패치 후 에는 더이상 vulnerable 출력 명령이 수행되지 않습니다>

블로그 이미지

wtdsoul

,

http://blog.naver.com/ljsk139/30143768284

 

함수호출규약(Calling Convention) 간단 정리

__cdecl (default 설정) 인자전달방법 : 스택에 저장하여 전달인자전달순서 : 오른쪽에서 왼쪽으로스택의 ...

blog.naver.com

 

__cdecl (default 설정)

 

  • 인자전달방법 : 스택에 저장하여 전달
  • 인자전달순서 : 오른쪽에서 왼쪽으로
  • 스택의 정리 : Caller에서 정리
  • 장점 : 가변인자를 사용할 수 있다.

 

__stdcall

 

  • 인자전달방법 : 스택에 저장하여 전달
  • 인자전달순서 : 오른쪽에서 왼쪽으로
  • 스택의 정리 : Callee에서 정리
  • 장점 : __cdecl보다 코드의 길이가 짧다. (좀 더 빠르다.)

 

 

__fastcall

 

  • 인자전달방법 : 처음 두개는 ECX, EDX를 이용, 나머지는 스택에 저장하여 전달
  • 인자전달순서 : 오른쪽에서 왼쪽으로
  • 스택의 정리 : Callee에서 정리
  • 장점 : 레지스터에 인자를 저장하기 때문에 속도가 더 빠르다.

 

Calling Convention에서의 중요한 것은 스택의 정리를 Caller에서 하느냐 Callee에서 하느냐이다.

 

 

  왼쪽의 그림의 경우는 Caller에 인자를 저장하는 형태이고 오른쪽 그림의 경우는 Callee에 인자를 저장하는 형태이다.

 

왼쪽의 그림에서 Callee가 스택을 정리한다고 생각을 해보자.

 

Callee는 인자가 자신의 스택영역에 있는 것이 아니기 때문에 인자의 개수가 몇개인지 체크를 해야하고, 그 이후에 정리를 해야한다. 그렇기에 절차가 복잡해 진다. 

 

하지만 Caller가 스택을 정리한다면 Callee를 호출하는 순간 인자의 개수를 이미 알고 있기 때문에, 스택을 정리하는 작업이 복잡하지 않다. 

 

그리고 또한 Caller에서 인자의 개수를 정해서 함수를 호출하는 것이기 때문에 인자의 개수는 변할 수가 있다. 그렇기에 __cdecl에서 가변인자함수를 지원하는 것이다.

 

반대로 오른쪽의 경우는 Caller보다 Callee가 스택을 정리하는 것이 유리하다. 하지만 이 경우는 가변인자함수를 지원할 수 없다. 

 

왜냐하면 스택의 정리 코드를 작성하려면 인자의 총 크기를 미리 알아야 하는데 가변인자함수의 경우는 인자의 개수가 가변적이므로 미리 예측할 수 없기 때문이다.

 

 

 

__cdecl과 __stdcall이 속도차이가 나는 이유는 정리 코드에서의 차이 때문이다.

 

__stdcall의 경우는 Callee가 작업을 마치고 스택을 정리할 때 

ret (인자의 총 크기)

로 정리를 한다.

 

__cdecl의 경우에는 Callee가 ret을 하고 나면 Caller가

add esp, (인자의 총 크기)

로 정리를 한다.

 

 

 

[정리]

 

 

 

 

https://ezbeat.tistory.com/425

'리버싱' 카테고리의 다른 글

RVA to RWA 쉽게 계산하기 [펌]  (0) 2022.04.27
EAT IAT 계산  (0) 2022.04.25
C#은 SecureSting 클래스  (0) 2021.07.09
.Net De'obfuscator 분석(진행 중)  (0) 2020.11.08
게임 해킹 띠오리(경로)  (0) 2020.11.02
블로그 이미지

wtdsoul

,

This article will cover:

  1. Introduction to Frida and SSL pinning
  2. Requirements
  3. Setup and Installation
  4. Frida Server Setup
  5. Setup BurpSuite
  6. Pushing the proxy’s CA Certificate:
  7. Script injection to bypass SSL pinning
  8. All stuff in a nutshell
  9. Troubleshooting



https://codeshare.frida.re/@pcipolloni/universal-android-ssl-pinning-bypass-with-frida/
 

Frida CodeShare

 

codeshare.frida.re

or you can save this code as fridascript.js in same folder as adb.

/*
Android SSL Re-pinning frida script v0.2 030417-pier
$ adb push burpca-cert-der.crt /data/local/tmp/cert-der.crt
$ frida -U -f it.app.mobile -l frida-android-repinning.js --no-pause
https://techblog.mediaservice.net/2017/07/universal-android-ssl-pinning-bypass-with-frida/

UPDATE 20191605: Fixed undeclared var. Thanks to @oleavr and @ehsanpc9999 !
*/
setTimeout(function(){
Java.perform(function (){
console.log("");
console.log("[.] Cert Pinning Bypass/Re-Pinning");
var CertificateFactory = Java.use("java.security.cert.CertificateFactory");
var FileInputStream = Java.use("java.io.FileInputStream");
var BufferedInputStream = Java.use("java.io.BufferedInputStream");
var X509Certificate = Java.use("java.security.cert.X509Certificate");
var KeyStore = Java.use("java.security.KeyStore");
var TrustManagerFactory = Java.use("javax.net.ssl.TrustManagerFactory");
var SSLContext = Java.use("javax.net.ssl.SSLContext");
// Load CAs from an InputStream
console.log("[+] Loading our CA...")
var cf = CertificateFactory.getInstance("X.509");

try {
var fileInputStream = FileInputStream.$new("/data/local/tmp/cert-der.crt");
}
catch(err) {
console.log("[o] " + err);
}

var bufferedInputStream = BufferedInputStream.$new(fileInputStream);
var ca = cf.generateCertificate(bufferedInputStream);
bufferedInputStream.close();
var certInfo = Java.cast(ca, X509Certificate);
console.log("[o] Our CA Info: " + certInfo.getSubjectDN());
// Create a KeyStore containing our trusted CAs
console.log("[+] Creating a KeyStore for our CA...");
var keyStoreType = KeyStore.getDefaultType();
var keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

// Create a TrustManager that trusts the CAs in our KeyStore
console.log("[+] Creating a TrustManager that trusts the CA in our KeyStore...");
var tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
var tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
console.log("[+] Our TrustManager is ready...");
console.log("[+] Hijacking SSLContext methods now...")
console.log("[-] Waiting for the app to invoke SSLContext.init()...")
SSLContext.init.overload("[Ljavax.net.ssl.KeyManager;", "[Ljavax.net.ssl.TrustManager;", "java.security.SecureRandom").implementation = function(a,b,c) {
console.log("[o] App invoked javax.net.ssl.SSLContext.init...");
SSLContext.init.overload("[Ljavax.net.ssl.KeyManager;", "[Ljavax.net.ssl.TrustManager;", "java.security.SecureRandom").call(this, a, tmf.getTrustManagers(), c);
console.log("[+] SSLContext initialized with our custom TrustManager!");
}
});
},0);



'모바일' 카테고리의 다른 글

remote-iphone-exploitation(project zero)  (0) 2020.01.10
iOS Application Injection  (0) 2020.01.02
ARM 어셈블리어  (0) 2019.12.05
iOS Penetration Testing Part 3  (0) 2019.11.25
iOS 무결성 내용  (0) 2019.11.21
블로그 이미지

wtdsoul

,

https://thehackernews.com/2019/11/whatsapp-hacking-vulnerability.html?fbclid=IwAR29_Ta1wgs0itQkPCIQgtxvuXAzXtsMohZD38kRe152DVJUYvWZnma8TKo

 

New WhatsApp Bug Could Have Let Hackers Secretly Install Spyware On Your Devices

New WhatsApp Flaw (CVE-2019-11931) Could Have Allowed Hackers to Install Spyware On Your Device Just by Singing MP4 Media File

thehackernews.com

 

According to an advisory published by Facebook, which owns WhatsApp, the list of affected app versions are as follows:


  • Android versions before 2.19.274
  • iOS versions before 2.19.100
  • Enterprise Client versions before 2.25.3
  • Windows Phone versions before and including 2.18.368
  • Business for Android versions before 2.19.104
  • Business for iOS versions before 2.19.100
블로그 이미지

wtdsoul

,

Android Camera Apps

CVE 2019. 11. 21. 15:41

https://securityaffairs.co/wordpress/94089/hacking/cve-2019-2234-android-camera-apps-flaws.html?fbclid=IwAR0tjThpkEnxEgEum9RVgqoz41egBSwBneoMb9BtnjhbH1LoKMEhPFcmPyI

 

CVE-2019-2234 flaws in Android Camera Apps exposed millions of users surveillance

Experts found multiple flaws (CVE-2019-2234) in the Android camera apps provided by Google and Samsung that could allow attackers to spy on users. Cybersecurity experts from Checkmarx discovered multiple vulnerabilities in the Android camera apps provided

securityaffairs.co

 

Below the video PoC of the attack:

 

https://youtu.be/XJAMJOVoVyw

 

The researchers reported the flaws to Google in early July and the company confirmed that a security patch addressed them was released in the same month. Samsung also confirmed to have addressed the issue.

“This type of research activity is part of the Checkmarx Security Research Team’s ongoing efforts to drive the necessary changes in software security practices among vendors that manufacture consumer-based smartphones and IoT devices, while bringing more security awareness amid the consumers who purchase and use them. Protecting privacy of consumers must be a priority for all of us in today’s increasingly connected world”

'CVE' 카테고리의 다른 글

POODLE Attack  (0) 2020.08.09
CVE-2020-0796-RCE-POC  (0) 2020.07.14
CVE-2019-8805 - A macOS Catalina privilege escalation  (0) 2019.12.10
CVE-2019-2890  (0) 2019.12.10
WhatsApp exploit poc  (0) 2019.11.21
블로그 이미지

wtdsoul

,

https://thehackernews.com/2019/11/zombieload-cpu-vulnerability.html?fbclid=IwAR37AZD8rQ5ZbbUMXadMyekGZeuB4fEilrPcOmcmm_wZwDw0dPzkCUR-2qo

 

New ZombieLoad v2 Attack Affects Intel's Latest Cascade Lake CPUs

ZombieLoad variant 2 of the side-channel MDS vulnerabilities affects the most recent Intel CPUs, including the latest Cascade Lake, which are otherwise resistant against attacks like Meltdown, Foreshadow and other MDS variants (RIDL and Fallout)

thehackernews.com

 

ZombieLoad v2 Affects Latest Intel CPUs


Now, the same group of researchers has disclosed details of a second variant of the vulnerability, dubbed ZombieLoad v2 and tracked as CVE-2019-11135, that resides in Intel's Transactional Synchronization Extensions (TSX).

Intel TSX provides transactional memory support in hardware, aiming to improve the performance of the CPU by speeding up the execution of multi-threaded software and aborting a transaction when a conflict memory access was found.


Intel has referred ZombieLoad v2 as "Transactional Synchronization Extensions (TSX) Asynchronous Abort (TAA)" vulnerability because the exploitation of this flaw requires a local attacker, with the ability to monitor execution time of TSX regions, to infer memory state by comparing abort execution times.

 

 

블로그 이미지

wtdsoul

,

https://hakin9.org/sgx-step-a-practical-attack-framework-for-precise-enclave-execution-control/

 

Sgx-Step-Practical Attack Framework For Precise Enclave Execution Control

SGX-Step is an open-source framework to facilitate side-channel attack research on Intel SGX platforms. SGX-Step consists of an adversarial Linux kernel driver and user space library that allow to configure untrusted page table entries and/or

hakin9.org

 

 

Overview

Crucial to the design of SGX-Step, as opposed to previous enclave preemption proposals, is the creation of user-space virtual memory mappings for physical memory locations holding page table entries, as well as for the local APIC memory-mapped I/O configuration registers and the x86 Interrupt Descriptor Table (IDT). This allows an untrusted, attacker-controlled host process to easily (i) track or modify enclave page table entries, (ii) configure the APIC timer one-shot/periodic interrupt source, (iii) trigger inter-processor interrupts, and (iv) register custom interrupt handlers completely within user space.

The above figure summarizes the sequence of hardware and software steps when interrupting and resuming an SGX enclave through our framework.

  1. The local APIC timer interrupt arrives within an enclaved instruction.
  2. The processor executes the AEX procedure that securely stores execution context in the enclave’s SSA frame, initializes CPU registers, and vectors to the (user space) interrupt handler registered in the IDT.
  3. At this point, any attack-specific, spy code can easily be plugged in.
  4. The library returns to the user space AEP trampoline. We modified the untrusted runtime of the official SGX SDK to allow easy registration of a custom AEP stub. Furthermore, to enable precise evaluation of our approach on attacker-controlled benchmark debug enclaves, SGX-Step can optionally be instrumented to retrieve the stored instruction pointer from the interrupted enclave’s SSA frame. For this, our /dev/sgx-step driver offers an optional IOCTL call for the privileged EDBGRD instruction.
  5. Thereafter, we configure the local APIC timer for the next interrupt by writing into the initial-count MMIO register, just before executing (6) ERESUME.

 

'경로 및 정보' 카테고리의 다른 글

IIS Crypto 설정 툴(비영리)  (0) 2020.11.25
FTP 클라이언트 능동형 설정 관련  (0) 2020.11.20
크롬 UTF 인코딩 확장  (0) 2020.11.08
Kubernetes Nginx Ingress Controller  (0) 2020.01.06
정보 공유 및 정리(?)  (0) 2019.11.21
블로그 이미지

wtdsoul

,

 

 

'경로 및 정보' 카테고리의 다른 글

IIS Crypto 설정 툴(비영리)  (0) 2020.11.25
FTP 클라이언트 능동형 설정 관련  (0) 2020.11.20
크롬 UTF 인코딩 확장  (0) 2020.11.08
Kubernetes Nginx Ingress Controller  (0) 2020.01.06
A Practical Attack Framework  (0) 2019.11.21
블로그 이미지

wtdsoul

,

iOS 무결성 내용

모바일 2019. 11. 21. 14:22

https://github.com/olxios/SmartSec_iOS_Security/blob/master/README.md

 

olxios/SmartSec_iOS_Security

Basic collection of security controls for iOS apps - olxios/SmartSec_iOS_Security

github.com

iOS 무결성 검증하는 소스 코드를 찾던 중 해당 내용을 확인하게 되어 글을 작성 합니다.

 

iOS Anti-Reversing Defenses

File Integrity Checks

등등에 대한 내용을 확인할 수 있다.

 

 

https://github.com/OWASP/owasp-mstg/blob/master/Document/0x06j-Testing-Resiliency-Against-Reverse-Engineering.md#file-integrity-checks

 

OWASP/owasp-mstg

The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering. - OWASP/owasp-mstg

github.com

 

 

File Integrity Checks (MSTG-RESILIENCE-3 and MSTG-RESILIENCE-11)

Overview

There are two topics related to file integrity:

  1. Application source code integrity checks: In the "Tampering and Reverse Engineering" chapter, we discussed the iOS IPA application signature check. We also saw that determined reverse engineers can easily bypass this check by re-packaging and re-signing an app using a developer or enterprise certificate. One way to make this harder is to add an internal run-time check that determines whether the signatures still match at run time.

  2. File storage integrity checks: When files are stored by the application, key-value pairs in the Keychain, UserDefaults/NSUserDefaults, a SQLite database, or a Realm database, their integrity should be protected.

Sample Implementation - Application Source Code

Apple takes care of integrity checks with DRM. However, additional controls (such as in the example below) are possible. The mach_header is parsed to calculate the start of the instruction data, which is used to generate the signature. Next, the signature is compared to the given signature. Make sure that the generated signature is stored or coded somewhere else.

int xyz(char *dst) { const struct mach_header * header; Dl_info dlinfo; if (dladdr(xyz, &dlinfo) == 0 || dlinfo.dli_fbase == NULL) { NSLog(@" Error: Could not resolve symbol xyz"); [NSThread exit]; } while(1) { header = dlinfo.dli_fbase; // Pointer on the Mach-O header struct load_command * cmd = (struct load_command *)(header + 1); // First load command // Now iterate through load command //to find __text section of __TEXT segment for (uint32_t i = 0; cmd != NULL && i < header->ncmds; i++) { if (cmd->cmd == LC_SEGMENT) { // __TEXT load command is a LC_SEGMENT load command struct segment_command * segment = (struct segment_command *)cmd; if (!strcmp(segment->segname, "__TEXT")) { // Stop on __TEXT segment load command and go through sections // to find __text section struct section * section = (struct section *)(segment + 1); for (uint32_t j = 0; section != NULL && j < segment->nsects; j++) { if (!strcmp(section->sectname, "__text")) break; //Stop on __text section load command section = (struct section *)(section + 1); } // Get here the __text section address, the __text section size // and the virtual memory address so we can calculate // a pointer on the __text section uint32_t * textSectionAddr = (uint32_t *)section->addr; uint32_t textSectionSize = section->size; uint32_t * vmaddr = segment->vmaddr; char * textSectionPtr = (char *)((int)header + (int)textSectionAddr - (int)vmaddr); // Calculate the signature of the data, // store the result in a string // and compare to the original one unsigned char digest[CC_MD5_DIGEST_LENGTH]; CC_MD5(textSectionPtr, textSectionSize, digest); // calculate the signature for (int i = 0; i < sizeof(digest); i++) // fill signature sprintf(dst + (2 * i), "%02x", digest[i]); // return strcmp(originalSignature, signature) == 0; // verify signatures match return 0; } } cmd = (struct load_command *)((uint8_t *)cmd + cmd->cmdsize); } } }

Sample Implementation - Storage

When ensuring the integrity of the application storage itself, you can create an HMAC or signature over either a given key-value pair or a file stored on the device. The CommonCrypto implementation is best for creating an HMAC. If you need encryption, make sure that you encrypt and then HMAC as described in Authenticated Encryption.

When you generate an HMAC with CC:

  1. Get the data as NSMutableData.
  2. Get the data key (from the Keychain if possible).
  3. Calculate the hash value.
  4. Append the hash value to the actual data.
  5. Store the results of step 4.

// Allocate a buffer to hold the digest and perform the digest. NSMutableData* actualData = [getData]; //get the key from the keychain NSData* key = [getKey]; NSMutableData* digestBuffer = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, [actualData bytes], (CC_LONG)[key length], [actualData bytes], (CC_LONG)[actualData length], [digestBuffer mutableBytes]); [actualData appendData: digestBuffer];

Alternatively, you can use NSData for steps 1 and 3, but you'll need to create a new buffer for step 4.

When verifying the HMAC with CC, follow these steps:

  1. Extract the message and the hmacbytes as separate NSData.
  2. Repeat steps 1-3 of the procedure for generating an HMAC on the NSData.
  3. Compare the extracted HMAC bytes to the result of step 1.

NSData* hmac = [data subdataWithRange:NSMakeRange(data.length - CC_SHA256_DIGEST_LENGTH, CC_SHA256_DIGEST_LENGTH)]; NSData* actualData = [data subdataWithRange:NSMakeRange(0, (data.length - hmac.length))]; NSMutableData* digestBuffer = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, [actualData bytes], (CC_LONG)[key length], [actualData bytes], (CC_LONG)[actualData length], [digestBuffer mutableBytes]); return [hmac isEqual: digestBuffer];

Bypassing File Integrity ChecksWhen you're trying to bypass the application-source integrity checks

  1. Patch the anti-debugging functionality and disable the unwanted behavior by overwriting the associated code with NOP instructions.
  2. Patch any stored hash that's used to evaluate the integrity of the code.
  3. Use Frida to hook file system APIs and return a handle to the original file instead of the modified file.

When you're trying to bypass the storage integrity checks

  1. Retrieve the data from the device, as described in the "Device Binding" section.
  2. Alter the retrieved data and return it to storage.

Effectiveness Assessment

For the application source code integrity checks Run the app on the device in an unmodified state and make sure that everything works. Then apply patches to the executable using optool, re-sign the app as described in the chapter "Basic Security Testing", and run it. The app should detect the modification and respond in some way. At the very least, the app should alert the user and/or terminate the app. Work on bypassing the defenses and answer the following questions:

  • Can the mechanisms be bypassed trivially (e.g., by hooking a single API function)?
  • How difficult is identifying the anti-debugging code via static and dynamic analysis?
  • Did you need to write custom code to disable the defenses? How much time did you need?
  • What is your assessment of the difficulty of bypassing the mechanisms?

For the storage integrity checks A similar approach works. Answer the following questions:

  • Can the mechanisms be bypassed trivially (e.g., by changing the contents of a file or a key-value pair)?
  • How difficult is obtaining the HMAC key or the asymmetric private key?
  • Did you need to write custom code to disable the defenses? How much time did you need?
  • What is your assessment of the difficulty of bypassing the mechanisms??

'모바일' 카테고리의 다른 글

remote-iphone-exploitation(project zero)  (0) 2020.01.10
iOS Application Injection  (0) 2020.01.02
ARM 어셈블리어  (0) 2019.12.05
iOS Penetration Testing Part 3  (0) 2019.11.25
The Universal SSL pinning bypass for Android applications  (0) 2019.11.21
블로그 이미지

wtdsoul

,