Dreamhack/Dreamhack Wargame (Challenge)

[99] IT 비전공자 [dreamhack]pwn-library문제 풀기

imaginefuture-1 2024. 12. 17. 08:58

도서관..내가 좋아하는..

 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct bookstruct{
	char bookname[0x20];
	char* contents;
};

__uint32_t booksize;
struct bookstruct listbook[0x50];
struct bookstruct secretbook;

void booklist(){
	printf("1. theori theory\n");
	printf("2. dreamhack theory\n");
	printf("3. einstein theory\n");
}

int borrow_book(){
	if(booksize >= 0x50){
		printf("[*] book storage is full!\n");
		return 1;
	}
	__uint32_t select = 0;
	printf("[*] Welcome to borrow book menu!\n");
	booklist();
	printf("[+] what book do you want to borrow? : ");
	scanf("%u", &select);
	if(select == 1){
		strcpy(listbook[booksize].bookname, "theori theory");
		listbook[booksize].contents = (char *)malloc(0x100);
		memset(listbook[booksize].contents, 0x0, 0x100);
		strcpy(listbook[booksize].contents, "theori is theori!");
	} else if(select == 2){
		strcpy(listbook[booksize].bookname, "dreamhack theory");
		listbook[booksize].contents = (char *)malloc(0x200);
		memset(listbook[booksize].contents, 0x0, 0x200);
		strcpy(listbook[booksize].contents, "dreamhack is dreamhack!");
	} else if(select == 3){
		strcpy(listbook[booksize].bookname, "einstein theory");
		listbook[booksize].contents = (char *)malloc(0x300);
		memset(listbook[booksize].contents, 0x0, 0x300);
		strcpy(listbook[booksize].contents, "einstein is einstein!");

	} else{
		printf("[*] no book...\n");
		return 1;
	}
	printf("book create complete!\n");
	booksize++;
	return 0;
}

int read_book(){
	__uint32_t select = 0;
	printf("[*] Welcome to read book menu!\n");
	if(!booksize){
		printf("[*] no book here..\n");
		return 0;
	}
	for(__uint32_t i = 0; i<booksize; i++){
		printf("%u : %s\n", i, listbook[i].bookname);
	}
	printf("[+] what book do you want to read? : ");
	scanf("%u", &select);
	if(select > booksize-1){
		printf("[*] no more book!\n");
		return 1;
	}
	printf("[*] book contents below [*]\n");
	printf("%s\n\n", listbook[select].contents);
	return 0;
}

int return_book(){
	printf("[*] Welcome to return book menu!\n");
	if(!booksize){
		printf("[*] no book here..\n");
		return 1;
	}
	if(!strcmp(listbook[booksize-1].bookname, "-----returned-----")){
		printf("[*] you alreay returns last book!\n");
		return 1;
	}
	free(listbook[booksize-1].contents);
	memset(listbook[booksize-1].bookname, 0, 0x20);
	strcpy(listbook[booksize-1].bookname, "-----returned-----");
	printf("[*] lastest book returned!\n");
	return 0;
}

int steal_book(){
	FILE *fp = 0;
	__uint32_t filesize = 0;
	__uint32_t pages = 0;
	char buf[0x100] = {0, };
	printf("[*] Welcome to steal book menu!\n");
	printf("[!] caution. it is illegal!\n");
	printf("[+] whatever, where is the book? : ");
	scanf("%144s", buf);
	fp = fopen(buf, "r");
	if(!fp){
		printf("[*] we can not find a book...\n");
		return 1;
	} else {
		fseek(fp, 0, SEEK_END);
    	filesize = ftell(fp);
    	fseek(fp, 0, SEEK_SET);
		printf("[*] how many pages?(MAX 400) : ");
		scanf("%u", &pages);
		if(pages > 0x190){
			printf("[*] it is heavy!!\n");
			return 1;
		}
		if(filesize > pages){
			filesize = pages;
		}
		secretbook.contents = (char *)malloc(pages);
		memset(secretbook.contents, 0x0, pages);
		__uint32_t result = fread(secretbook.contents, 1, filesize, fp);

		if(result != filesize){
			printf("[*] result : %u\n", result);
			printf("[*] it is locked..\n");
			return 1;
		}
		
		memset(secretbook.bookname, 0, 0x20);
		strcpy(secretbook.bookname, "STOLEN BOOK");
		printf("\n[*] (Siren rangs) (Siren rangs)\n");
		printf("[*] Oops.. cops take your book..\n");
		fclose(fp);
		return 0;
	}

}


void menuprint(){
	printf("1. borrow book\n");
	printf("2. read book\n");
	printf("3. return book\n");
	printf("4. exit library\n");
}
void main(){
	__uint32_t select = 0;
	printf("\n[*] Welcome to library!\n");
	setvbuf(stdin, 0, 2, 0);
	setvbuf(stdout, 0, 2, 0);
	while(1){
		menuprint();
		printf("[+] Select menu : ");
		scanf("%u", &select);
		switch(select){
			case 1:
				borrow_book();
				break;
			case 2:
				read_book();
				break;
			case 3:
				return_book();
				break;
			case 4:
				printf("Good Bye!");
				exit(0);
				break;
			case 0x113:
				steal_book();
				break;
			default:
				printf("Wrong menu...\n");
				break;
		}
	}
}

 

 

이 코드는 도서관 시스템을 시뮬레이션하는 프로그램으로, 사용자 입력을 통해 책을 빌리고, 읽고, 반납하며, 심지어 "책을 훔치는" 기능까지 포함되어 있습니다. 프로그램은 여러 가지 보안 취약점을 내포하고 있으며, 주로 C 언어 메모리 관리입력 처리에서 발생하는 문제들입니다.


프로그램 주요 기능

  1. 책 대여 (borrow_book):
    • 미리 정의된 책 목록에서 책을 대여합니다.
    • 책 이름과 내용이 구조체에 저장되며, malloc을 통해 메모리를 할당.
  2. 책 읽기 (read_book):
    • 대여한 책 목록을 출력하고 선택한 책의 내용을 보여줍니다.
  3. 책 반납 (return_book):
    • 마지막으로 대여한 책을 반납하면서 free()를 통해 메모리를 해제.
    • 책 이름을 "-----returned-----"로 변경합니다.
  4. 책 훔치기 (steal_book):
    • 파일에서 데이터를 읽어 secretbook.contents에 저장.
    • "불법적인" 동작을 시뮬레이션하는 기능이며, 파일 읽기와 메모리 할당을 수행.
  5. 메뉴 시스템:
    • 사용자가 다양한 기능을 선택할 수 있도록 메뉴를 제공합니다.
    • 0x113 옵션을 통해 숨겨진 "steal_book" 기능을 실행할 수 있습니다.

취약점 분석

이 프로그램은 여러 가지 보안 취약점을 내포하고 있습니다.

1. borrow_book 함수: 메모리 할당 누수

  • 문제: malloc()을 통해 메모리를 할당했지만, 프로그램에서 모든 메모리를 반환하지 않습니다.
  • 코드 예시:
    listbook[booksize].contents = (char *)malloc(0x200);
    memset(listbook[booksize].contents, 0x0, 0x200);
    strcpy(listbook[booksize].contents, "dreamhack is dreamhack!");
    
  • 위험 요소:
    • borrow_book() 함수에서 책을 계속 빌리면 listbook 배열의 메모리가 계속 할당되지만, 반납은 마지막 책만 수행됩니다.
    • 메모리 누수로 인해 프로그램이 비정상적으로 종료되거나 시스템 자원을 소모할 수 있습니다.

2. return_book 함수: Double Free 취약점 가능성

  • 문제: 이미 반납된 책에 대해 다시 free()를 호출할 수 있습니다.
  • 코드:
    if(!strcmp(listbook[booksize-1].bookname, "-----returned-----")){
        printf("[*] you alreay returns last book!\n");
        return 1;
    }
    free(listbook[booksize-1].contents);
    
  • 위험 요소:
    • 책 이름이 "-----returned-----"로 설정되었는지만 검사하고, contents 포인터를 NULL로 초기화하지 않습니다.
    • 이미 free()된 메모리를 다시 해제하거나 접근하면 Double Free 또는 Use-After-Free (UAF) 취약점이 발생할 수 있습니다.

3. steal_book 함수: 버퍼 오버플로우

  • 문제: 파일 이름 입력 시 버퍼의 최대 크기(144 바이트)를 초과하는 입력을 처리하지 않습니다.
  • 코드:
    char buf[0x100] = {0, };
    scanf("%144s", buf);
    
  • 위험 요소:
    • scanf("%144s", buf)는 입력을 제한하지만, 파일 입력이 너무 커질 경우 다른 변수나 메모리를 덮어쓸 수 있습니다.
    • 특히 fread() 함수로 읽어들인 데이터를 secretbook.contents에 저장할 때 할당된 메모리보다 큰 데이터를 읽어올 수 있습니다:
      secretbook.contents = (char *)malloc(pages);
      fread(secretbook.contents, 1, filesize, fp);
      

4. Hidden 기능 (메뉴 0x113): Steal Book

  • 의도된 취약점:
    • 사용자가 메뉴에서 0x113을 선택하면 steal_book() 함수가 호출됩니다.
    • 파일 시스템의 파일을 열어 내용을 읽어옵니다.
    • 이 기능을 이용해 중요한 파일(예: 시스템 비밀번호 파일)을 읽을 수 있습니다.

5. 전체적인 취약점 요약

  1. 메모리 누수:
    • malloc()으로 할당한 메모리가 적절히 free()되지 않음.
  2. Double Free:
    • return_book() 함수에서 동일한 메모리를 여러 번 해제할 수 있음.
  3. 버퍼 오버플로우:
    • 입력 제한이 있지만, 예상치 못한 상황에서 버퍼를 초과할 수 있음.
  4. 파일 읽기 취약점:
    • steal_book()을 통해 임의의 파일을 읽을 수 있음.

익스플로잇 시나리오

  1. 책 훔치기 기능 악용:
    • 메뉴에서 0x113을 선택하여 시스템의 중요 파일(예: /etc/passwd)을 읽습니다.
    • 입력:
      [+] whatever, where is the book? : /etc/passwd
      
  2. 메모리 누수 및 UAF:
    • 책을 여러 번 빌리고, 반납한 책을 다시 조작하여 메모리 상태를 오염시킬 수 있습니다.
  3. 버퍼 오버플로우:
    • 입력 버퍼(buf)를 오버플로우 시켜 다른 변수나 메모리를 조작할 수 있습니다.

보안 개선점

  1. 메모리 관리 개선:
    • free() 이후 포인터를 NULL로 초기화하여 UAF와 Double Free 방지.
  2. 버퍼 크기 검사 강화:
    • fread()와 malloc() 호출 시 입력 크기를 엄격히 검증.
  3. 파일 접근 제한:
    • steal_book()에서 허용된 파일 경로만 접근하도록 설정.
  4. 메모리 누수 방지:
    • 프로그램 종료 시 모든 할당된 메모리를 해제.

결론

이 프로그램은 메모리 관리 취약점, 버퍼 오버플로우, 파일 읽기 취약점을 포함하고 있어, 악의적인 사용자가 이를 악용할 수 있습니다. 특히 steal_book 기능을 통해 중요한 파일을 읽을 수 있다는 점에서 보안적 위험이 큽니다. 이러한 취약점을 이해하고 패치하는 것이 중요합니다.

 

 

중요한건 2번!

  •  이름이 "-----returned-----"로 설정되었는지만 검사하고, contents 포인터를 NULL로 초기화하지 않습니다.
  • 이미 free()된 메모리를 다시 해제하거나 접근하면 Double Free 또는 Use-After-Free (UAF) 취약점이 발생할 수 있습니다.

코드 내용을 정리하자면, 빌리기, 읽기, 반납이 가능한 프로그램인데, 275를 입력하면 훔치기라는 숨겨진 기능이 있다.
275번, 훔치는 기능에서는 파일을 열 수 있고, 해당 파일의 내용이 비밀책의 내용으로 들어간다.
이때, 훔친 책의 길이는 0x190을 넘으면 안된다고 한다.
1번, 빌리는 기능에서는 고른 책마다 정해진 크기(0x100, 0x200, 0x300)를 할당하고 내용을 복사한다.
훔치는 기능에서는 책 개수가 증가하지 않아 책 목록에 추가되지 않았는데, 빌리는 기능에서는 책 목록에 추가된다. (책 개수가 증가하니까...)
2번, 읽는 기능에서는 빌린 책 목록 중 선택한 책의 내용을 출력해준다.
3번, 반납하는 기능에서는 빌렸던 책, 즉 할당받았던 메모리를 해제해주는 기능을 한다.
여기에서 중요한 것은, 메모리를 할당 후 해제하고 다시 같은 크기의 메모리를 할당한다면 이전에 사용한 메모리를 재사용한다는 것!

출처 ㅣ https://limu-study.tistory.com/12

 

 

 

 

 

	if(select == 1){
		strcpy(listbook[booksize].bookname, "theori theory");
		listbook[booksize].contents = (char *)malloc(0x100);
		memset(listbook[booksize].contents, 0x0, 0x100);
		strcpy(listbook[booksize].contents, "theori is theori!");

 

0x100 책 길이

 

 

 


우리는 이점을 사용해서 먼저 0x190을 넘지 않는 책인 1번 책을 빌린다.
이후 다시 반납하면 할당후 해제가 완료.
275번 메뉴를 사용하여 훔치는 기능으로 들어가, 플래그가 있다는 /home/pwnlibrary/flag.txt로 들어간다.
책의 길이는 0x100, 즉 10진수로 하면 256이 된다.
비밀 책을 할당해주어야 하는데, 크기가 이전에 할당받았다가 해제한 1번 책의 0x100과 똑같으므로 재사용한다.
읽는 기능으로 들어가면, 책 개수는 줄어들지 않으므로 이미 해제된 것도 뜨게 되어있다.
하지만, 우리는 해당 메모리가 재사용되어 flag.txt의 내용이 들어있는 것을 알고있다..!

출처 ㅣ https://limu-study.tistory.com/12