https://arjunbrar.com/post/ios-application-injection

 

iOS Application Injection

Having been interested jailbreaking iOS devices for going on almost a decade, mixing security and this makes sense. Within this entry, I document my method of checking if an application can have code injected. Method 1 - Theos The first method of testing f

arjunbrar.com

 

 

 

Method 1 - Theos

The first method of testing for this is to check is to create a tweak using Theos. To get all the necessary information, I use a combination of other tools, namely:

블로그 이미지

wtdsoul

,

ARM 어셈블리어

모바일 2019. 12. 5. 15:58

https://achiven.tistory.com/entry/%EC%A3%BC%EC%9A%94-ARM-%EC%96%B4%EC%85%88%EB%B8%94%EB%A6%AC-%EB%AA%85%EB%A0%B9

 

주요 ARM 어셈블리 명령

자주 사용되는 ARM 어셈블리 명령어 요약 1. MOV ARM 어셈블리 명령어는 MOV 명령어와 논리 및 사칙연산 명령어에 모두 쉬프트 연..

achiven.tistory.com

 

1. MOV

ARM 어셈블리 명령어는 MOV 명령어와 논리 및 사칙연산 명령어에 모두 쉬프트 연산이

 

가능한데이것을 나타내는 표지가 끝에 붙을 수 있다는 것에 유의한다.

 

쉬프트 연산에는 ASR(오른쪽 쉬프트빈자리는 부호가 따라옴),

 

LSR(오른쪽으로 쉬프트빈자리는 0으로 채워짐),

 

LSL(왼쪽으로 쉬프트빈자리는 0으로 채워짐),

 

ROR(오른쪽으로 rotation )

 

정도를 알아두면 유용하다.

 

)

 

MOV r0, [r2,r4] ; r2+r4 의 주소에 있는 값을 읽어서 r0에 저장한다.

 

MOV r1, r2, ROR #1 ; r2를 오른쪽으로 한 비트만큼 rotation 해서 r1에 저장

 

2. ADD, SUB, AND, ORR

 

)

 

ADD r1, r2, #4 ; r2에 4를 더해서 r1에 저장

 

SUB r1, r1, #1 ; r1의 값을 하나 감소

 

ORR r4, r5, r7, LSR r2 ; r7을 오른쪽으로 논리 쉬프트를 r2만큼 한다음 그 결과를

 

; r5와 or 연산하여 r4에 저장한다.

 

3. UMULL, SMULL

 

곱하기 연산이다. 32비트짜리 두 개를 곱하면 64비트짜리가 나오므로 결과값을 저장하는

 

데 두 개의 레지스터가 필요하다결과 레지스터의 위치에 주의한다. UMULL은 부호가

 

없는 곱하기이고, SMULL은 부호가 있는 곱하기 이다.

 

)

 

UMULL r4, r5, r1, r2 ; r1과 r2를 곱해서 상위 32비트는 r5에 저장하고 하위 32비트는

 

; r4에 저장한다.

 

5. B, BL, BNE, BEQ, CMP

 

BL은 분기 명령이다.

 

)

 

B there ; 라벨이 there인 곳으로 무조건 분기한다.

 

BL sub+ROM ; 계산된 위치의 서브루틴을 호출한다.

 

BNE(0이 아닌 경우 분기)와 BEQ(0이면 분기는 branch 명령어이고 CMP는 비교 명령

 

어이지만 둘이 같이 쓰이는 경우가 많으므로 한꺼번에 설명한다.

 

)

 

CMP r1, #4 ; r1이 4이면 플래그가 0으로 셋팅된다.

 

BEQ there ; 플래그가 0이면 라벨이 there인 곳으로 분기하고그렇지 않으면

 

다음 명령어가 수행된다.

 

6. LDR, STR

 

LDR은 load 명령이다. LDR에는 불러오는 변수의 크기에 따라 LDRB, LDRH, LDR의 세

 

가지 종류가 있다. LDRB는 byte 변수를 불러올 때, LDRH는 short 변수를 불러올 때,

 

LDR은 int 변수를 불어올 때 쓴다. STR는 store 명령으로 마찬가지로 STRB, STRH, STR

 

이 있다.

 

첫 번째 인자는 레지스터가 두번 째 인자는 주소가 된다세 번째 인자는 load/store 

 

산을 한 다음 주소값을 증가시키고자 할 때얼마만큼 증가시킬 지를 지정한다.

 

)

 

LDR r1, [r2, #16] ; r2에 16 byte만큼 더한 주소에서 정수형 값을 읽어와 r1에 저장한다.

 

STR r1, [r2], #4 ; r2의 주소에 r1을 저장하고 난 후, r2를 4만큼 증가시킨다.

 

7. LDMFD, STMFD

 

LDM/STM은 LDR/STR의 변종으로 블록 단위로 load/store 할 때 사용한다중요한 용도

 

는 스택에 레지스터 값을 저장하거나 복원하는 것이다왜냐하면 스택에 저장/복원할 때

 

는 여러 개의 레지스터를 저장/복원해야 하기 때문이다.

 

스택과 관련해서는 LDMFD/STMFD, LDMED/STMED, LDMFA/STMFA, LDMEA/STMEA 

 

이 사용되고스택과 관련없이 사용할 때는 LDMIA,LDMIB, LDMDA, LDMDB, STMIA,

 

STMIB, STMDA,STMDB 가 사용된다.

 

중요한 것은 스택과 관련해서 실제 사용할 때쌍으로 사용한다는 것이다.

 

LDMFD/STMFD 정도만 잘 사용하면 된다자세한 사항은 ADS 문서를 참고하기 바란다.

 

)

 

STMFD sp!, {r4-r6, lr} ; 스택에 r4-r6와 lr 레지스터를 저장하고 sp를 그만큼 감소시킨다.

 

LDMFD sp!, {r4-r6, pc} ; 스택에서 r4-r6와 pc를 복원하고 sp를 그만큼 증가시킨다.

 


ARM Developer Suite(ADS) 1.2 
에서 코드와 ASM 코드 섞어 쓰기

 

1. C 코드 내에 어셈블리 코드를 inline으로 사용하기

 

(1) 사용방식

asm("instruction[;instruction]");

또는 C 컴파일러의 구문을 사용하면 다음과 같다.

__asm

{

instruction [; instruction]

...

[instruction]

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

remote-iphone-exploitation(project zero)  (0) 2020.01.10
iOS Application Injection  (0) 2020.01.02
iOS Penetration Testing Part 3  (0) 2019.11.25
The Universal SSL pinning bypass for Android applications  (0) 2019.11.21
iOS 무결성 내용  (0) 2019.11.21
블로그 이미지

wtdsoul

,

https://hackersonlineclub.com/ios-penetration-testing-frida-and-objection/

 

iOS Penetration Testing- Frida And Objection- Part 3 - HackersOnlineClub

iOS Penetration Testing Part 3 This post is part 3 of a series giving an overview of the most useful iOS app pentesting tools,...

hackersonlineclub.com

 

 

 

 

 

 

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

remote-iphone-exploitation(project zero)  (0) 2020.01.10
iOS Application Injection  (0) 2020.01.02
ARM 어셈블리어  (0) 2019.12.05
The Universal SSL pinning bypass for Android applications  (0) 2019.11.21
iOS 무결성 내용  (0) 2019.11.21
블로그 이미지

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

,

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

,