Docas95 / CHIP8-Emulator-C

An emulator for the CHIP-8 virtual machine.
0 stars 0 forks source link

Multiple memory corruption bugs #1

Open lucabtz opened 1 day ago

lucabtz commented 1 day ago

Hello, I was looking through the code and I found multiple memory corruption bugs

Buffer overflow in load_ROM

The file size is not checked before its contents are written using fread

// load content from ROM into memory
void load_ROM(char* filename){
    FILE* f = fopen(filename, "rb");
    if(!f){
        printf("Error opening file!\n");
        exit(1);
    }

    fseek(f, 0L, SEEK_END);
    size_t size = ftell(f);
    fseek(f, 0L, SEEK_SET);

    fread(&chip.memory[ROM_START_ADDRESS], 1, size, f);

    fclose(f);
}

Out-of-bounds read and write in decode_instruction

In the fuction decode_instruction the decrement of the stack pointer for the return instruction

                case 0x00EE:
                    // return from subroutine
                    chip.pc = chip.stack[chip.stack_pointer-1];
                    chip.stack_pointer--;               
                break; 

and the increment of the stack pointer for the call instruction

        case 0x2000:
            // call subroutine
            chip.stack[chip.stack_pointer] = chip.pc;
            chip.stack_pointer++;
            chip.pc = NNN;
            break;

do not check if the stack will under/over-flow respectively. This can allow writing out-of-bounds of the chip.stack array.

Out-of-bounds QUIT

In the function main there is the following code

    while(!chip.input[QUIT]){

however in the definitions in main.h we have

    uint8_t input[16];

and

#define QUIT 254

so this read is always out-of-bounds there.

I took this as a CTF challenge to myself and tried to write an exploit for this, while I could achieve some interesting behaviours when PIE is disabled I could not achieve full arbitrary code execution. I may publish this as a blog post because it was fairly fun.

Keep up the good work!

Docas95 commented 1 day ago

Wow! I never thought someone would end up finding this repository if I'm being honest haha. Thanks for the feedback, I'll make sure to fix these bugs.

People who can write exploits are really cool, I have to try it sometime. If you publish a blog post, I would enjoy reading it :)