본문 바로가기

Write-Up/pwnable.kr

[pwnable.kr] mistake 풀이

 

#include <stdio.h>
#include <fcntl.h>

#define PW_LEN 10
#define XORKEY 1

void xor(char* s, int len){
	int i;
	for(i=0; i<len; i++){
		s[i] ^= XORKEY;
	}
}

int main(int argc, char* argv[]){
	
	int fd;
	if(fd=open("/home/mistake/password",O_RDONLY,0400) < 0){
		printf("can't open password %d\n", fd);
		return 0;
	}

	printf("do not bruteforce...\n");
	sleep(time(0)%20);

	char pw_buf[PW_LEN+1];
	int len;
	if(!(len=read(fd,pw_buf,PW_LEN) > 0)){
		printf("read error\n");
		close(fd);
		return 0;		
	}

	char pw_buf2[PW_LEN+1];
	printf("input password : ");
	scanf("%10s", pw_buf2);

	// xor your input
	xor(pw_buf2, 10);

	if(!strncmp(pw_buf, pw_buf2, PW_LEN)){
		printf("Password OK\n");
		system("/bin/cat flag\n");
	}
	else{
		printf("Wrong Password\n");
	}

	close(fd);
	return 0;
}

힌트는 연산자 우선순위라는데....

코드부분을 차근차근 해석해보면

int fd;
	if(fd=open("/home/mistake/password",O_RDONLY,0400) < 0){
		printf("can't open password %d\n", fd);
		return 0;
	}

open함수는

int open(const char *FILENAME, int FLAGS[, mode_t MODE])이다.

O_RDONLY 파일을 읽기 전용으로 open한다. 0400은 owner에 대한 읽기 권한이다.

'open의 리턴값을 fd에 넣고 비교한다.' 라고 처음 생각했지만

힌트가 연산자 우선순위이다.

<는 =보다 연산순위가 높다.

보통 open하게 된다음 fd값은 3이니 

fd = 3 < 0

fd = 0

 

char pw_buf[PW_LEN+1];
	int len;
	if(!(len=read(fd,pw_buf,PW_LEN) > 0)){
		printf("read error\n");
		close(fd);
		return 0;		
	}

len = read(fd, pw_buf, PW_LEN) > 0

fd = 0 (표준 입력)이므로 pw_buf는 원하는 값을 입력할 수 있다. 또한

 

	char pw_buf2[PW_LEN+1];
	printf("input password : ");
	scanf("%10s", pw_buf2);

여기서 pw_buf2를 입력받는다.

그 이후 pw_buf2를 xor 연산을 한 후

if(!strncmp(pw_buf, pw_buf2, PW_LEN)){
		printf("Password OK\n");
		system("/bin/cat flag\n");
	}
	else{
		printf("Wrong Password\n");
	}

pw_buf와 pw_buf2를 비교해 flag를 얻을 수 있다.

Mommy, the operator priority always confuses me :(

 

 

'Write-Up > pwnable.kr' 카테고리의 다른 글

[pwnable.kr] input 풀이  (0) 2021.07.28
[pwnable.kr] random 풀이  (0) 2021.07.26
[pwnable.kr] passcode 풀이  (0) 2021.07.22
[pwnable.kr] blukat 풀이  (0) 2021.03.26
[pwnable.kr] memcpy 풀이  (0) 2021.03.25