WWW2Exec - atexit()

Support HackTricks

__atexit 구조체

현재는 이를 악용하는 것이 매우 이상합니다!

**atexit()**은 매개변수로 전달된 다른 함수들을 가지고 있는 함수입니다. 이러한 함수들은 **exit()**를 실행하거나 main반환 시에 실행됩니다. 만약 이러한 함수들 중 하나의 주소를 예를 들어 셸코드를 가리키도록 수정할 수 있다면, 프로세스를 제어할 수 있지만, 현재 이는 더 복잡해졌습니다. 현재 실행될 함수들의 주소는 여러 구조체 뒤에 숨겨져 있고, 마지막으로 그 주소가 가리키는 곳은 함수들의 주소가 아니라 XOR로 암호화되고 임의의 키로 이동된 것입니다. 따라서 현재 이 공격 벡터는 적어도 x86x64_86에서는 매우 유용하지 않습니다. 암호화 함수는 **PTR_MANGLE**입니다. m68k, mips32, mips64, aarch64, arm, hppa와 같은 다른 아키텍처들은 입력으로 받은 것과 동일한 것을 반환하기 때문에 암호화 함수를 구현하지 않습니다. 따라서 이러한 아키텍처는 이 벡터에 의해 공격당할 수 있습니다.

이 작동 방식에 대한 자세한 설명은 https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html에서 찾을 수 있습니다.

이 게시물에서 설명한대로, 프로그램이 return 또는 exit()를 사용하여 종료되면 등록된 소멸자를 호출하는 __run_exit_handlers()가 실행됩니다.

프로그램이 _exit() 함수를 통해 종료되면 exit 시스템 호출이 이루어지고 종료 핸들러는 실행되지 않습니다. 따라서 __run_exit_handlers()가 실행되는지 확인하려면 해당 부분에 중단점을 설정할 수 있습니다.

중요한 코드는 (원본)입니다:

ElfW(Dyn) *fini_array = map->l_info[DT_FINI_ARRAY];
if (fini_array != NULL)
{
ElfW(Addr) *array = (ElfW(Addr) *) (map->l_addr + fini_array->d_un.d_ptr);
size_t sz = (map->l_info[DT_FINI_ARRAYSZ]->d_un.d_val / sizeof (ElfW(Addr)));

while (sz-- > 0)
((fini_t) array[sz]) ();
}
[...]




// This is the d_un structure
ptype l->l_info[DT_FINI_ARRAY]->d_un
type = union {
Elf64_Xword d_val;	// address of function that will be called, we put our onegadget here
Elf64_Addr d_ptr;	// offset from l->l_addr of our structure
}

map -> l_addr + fini_array -> d_un.d_ptr을 사용하여 호출할 함수 배열의 위치를 계산하는 방법에 주목하세요.

다음과 같은 두 가지 옵션이 있습니다:

  • map->l_addr의 값을 덮어쓰고, 임의의 코드를 실행하는 **가짜 fini_array**를 가리키도록 만듭니다.

  • 메모리 상에서 거의 연속적인 l_info[DT_FINI_ARRAY]l_info[DT_FINI_ARRAYSZ] 항목을 덮어쓰고, 다시 array가 공격자가 제어하는 메모리 영역을 가리키도록 하는 Elf64_Dyn 구조체를 가리키도록 만듭니다.

  • 이 writeup에서는 .bss에 있는 제어된 메모리의 주소로 l_info[DT_FINI_ARRAY]를 덮어쓰고, 가짜 fini_array를 포함하는 가짜 배열을 만듭니다. 이 가짜 배열은 먼저 실행될 원 가젯 주소를 포함하고, 그 다음에는 이 가짜 배열의 주소와 map->l_addr값 간의 차이가 있습니다. 따라서 *array는 가짜 배열을 가리키게 됩니다.

  • 이 기술의 주요 게시물 및 이 writeup에 따르면 ld.so는 ld.so 내의 이진 link_map을 가리키는 스택에 포인터를 남깁니다. 임의 쓰기를 사용하여 덮어쓰고, 공격자가 제어하는 가짜 fini_array를 가리키도록 만들고, 예를 들어 원 가젯의 주소를 포함할 수 있습니다.

이전 코드를 따라가면 코드에서 또 다른 흥미로운 섹션을 찾을 수 있습니다:

/* Next try the old-style destructor.  */
ElfW(Dyn) *fini = map->l_info[DT_FINI];
if (fini != NULL)
DL_CALL_DT_FINI (map, ((void *) map->l_addr + fini->d_un.d_ptr));
}

이 경우 map->l_info[DT_FINI]의 값을 조작하여 위조된 ElfW(Dyn) 구조체를 가리킬 수 있습니다. 여기에서 자세한 정보를 확인하세요.

TLS-Storage dtor_list 덮어쓰기 __run_exit_handlers

여기에서 설명된 것처럼, 프로그램이 return 또는 exit()를 통해 종료되면 **__run_exit_handlers()**가 실행되어 등록된 소멸자 함수를 호출합니다.

_run_exit_handlers()에서의 코드:

/* Call all functions registered with `atexit' and `on_exit',
in the reverse of the order in which they were registered
perform stdio cleanup, and terminate program execution with STATUS.  */
void
attribute_hidden
__run_exit_handlers (int status, struct exit_function_list **listp,
bool run_list_atexit, bool run_dtors)
{
/* First, call the TLS destructors.  */
#ifndef SHARED
if (&__call_tls_dtors != NULL)
#endif
if (run_dtors)
__call_tls_dtors ();

__call_tls_dtors() 함수에서의 코드:

typedef void (*dtor_func) (void *);
struct dtor_list //struct added
{
dtor_func func;
void *obj;
struct link_map *map;
struct dtor_list *next;
};

[...]
/* Call the destructors.  This is called either when a thread returns from the
initial function or when the process exits via the exit function.  */
void
__call_tls_dtors (void)
{
while (tls_dtor_list)		// parse the dtor_list chained structures
{
struct dtor_list *cur = tls_dtor_list;		// cur point to tls-storage dtor_list
dtor_func func = cur->func;
PTR_DEMANGLE (func);						// demangle the function ptr

tls_dtor_list = tls_dtor_list->next;		// next dtor_list structure
func (cur->obj);
[...]
}
}

모든 등록된 함수에 대해 **tls_dtor_list**에서 포인터를 **cur->func**에서 demangle하고 인자 **cur->obj**와 함께 호출합니다.

GEF의 fork에서 tls 함수를 사용하면 실제로 **dtor_list**가 스택 캐너리PTR_MANGLE 쿠키에 매우 가깝다는 것을 확인할 수 있습니다. 따라서 이를 오버플로우하여 쿠키스택 캐너리덮어쓸 수 있습니다. PTR_MANGLE 쿠키를 덮어쓰면 0x00으로 설정하여 PTR_DEMANLE 함수를 우회할 수 있으며, 이는 실제 주소를 얻기 위해 사용된 **xor**가 구성된 주소일 뿐이라는 것을 의미합니다. 그런 다음 **dtor_list**에 쓰면 함수 주소인자여러 함수를 연결할 수 있습니다.

마지막으로 저장된 포인터가 쿠키와 xor뿐만 아니라 17비트로 회전됨에 유의하세요:

0x00007fc390444dd4 <+36>:	mov    rax,QWORD PTR [rbx]      --> mangled ptr
0x00007fc390444dd7 <+39>:	ror    rax,0x11		        --> rotate of 17 bits
0x00007fc390444ddb <+43>:	xor    rax,QWORD PTR fs:0x30	--> xor with PTR_MANGLE

그래서 새 주소를 추가하기 전에 이를 고려해야 합니다.

원본 게시물에서 예제를 찾으세요.

**__run_exit_handlers**에서 다른 망가진 포인터들

이 기술은 여기에서 설명되어 있습니다 그리고 다시 한 번 return 또는 exit()를 호출하여 프로그램이 종료되면 **__run_exit_handlers()**가 호출됩니다.

이 함수의 더 많은 코드를 확인해 봅시다:

while (true)
{
struct exit_function_list *cur;

restart:
cur = *listp;

if (cur == NULL)
{
/* Exit processing complete.  We will not allow any more
atexit/on_exit registrations.  */
__exit_funcs_done = true;
break;
}

while (cur->idx > 0)
{
struct exit_function *const f = &cur->fns[--cur->idx];
const uint64_t new_exitfn_called = __new_exitfn_called;

switch (f->flavor)
{
void (*atfct) (void);
void (*onfct) (int status, void *arg);
void (*cxafct) (void *arg, int status);
void *arg;

case ef_free:
case ef_us:
break;
case ef_on:
onfct = f->func.on.fn;
arg = f->func.on.arg;
PTR_DEMANGLE (onfct);

/* Unlock the list while we call a foreign function.  */
__libc_lock_unlock (__exit_funcs_lock);
onfct (status, arg);
__libc_lock_lock (__exit_funcs_lock);
break;
case ef_at:
atfct = f->func.at;
PTR_DEMANGLE (atfct);

/* Unlock the list while we call a foreign function.  */
__libc_lock_unlock (__exit_funcs_lock);
atfct ();
__libc_lock_lock (__exit_funcs_lock);
break;
case ef_cxa:
/* To avoid dlclose/exit race calling cxafct twice (BZ 22180),
we must mark this function as ef_free.  */
f->flavor = ef_free;
cxafct = f->func.cxa.fn;
arg = f->func.cxa.arg;
PTR_DEMANGLE (cxafct);

/* Unlock the list while we call a foreign function.  */
__libc_lock_unlock (__exit_funcs_lock);
cxafct (arg, status);
__libc_lock_lock (__exit_funcs_lock);
break;
}

if (__glibc_unlikely (new_exitfn_called != __new_exitfn_called))
/* The last exit function, or another thread, has registered
more exit functions.  Start the loop over.  */
goto restart;
}

*listp = cur->next;
if (*listp != NULL)
/* Don't free the last element in the chain, this is the statically
allocate element.  */
free (cur);
}

__libc_lock_unlock (__exit_funcs_lock);

변수 finitial 구조체를 가리키며, f->flavor 값에 따라 다른 함수가 호출됩니다. 값에 따라 호출할 함수의 주소는 다른 위치에 있지만 항상 demangled됩니다.

또한, ef_onef_cxa 옵션에서 **인수(argument)**를 제어할 수도 있습니다.

디버깅 세션에서 **gef> p initial**을 실행하여 initial 구조체를 확인할 수 있습니다.

이를 악용하려면 PTR_MANGLE 쿠키를 노출하거나 지우고, 그 후 initial에서 system('/bin/sh')으로 cxa 항목을 덮어쓰면 됩니다. 이 기술에 대한 원본 블로그 게시물에서 이에 대한 예제를 찾을 수 있습니다.

Last updated