Bypass access() CTF challenge

Jason Wright Source

On the weekend I went to a CTF and spend a few hours on this challenge but am unsure what I was doing wrong. I'm still a beginner in cyber security, coding and binary exploitation so if i'm making dumb assumptions please correct me.

The challenge was set up as a binary with guid bit set to be able to read contents of flag.txt The source code was supplied and is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char **argv)
    int fd = -1;
    char buf[512] = {0};

    if(argc <= 1) {
        printf("%s <file>\n", argv[0] == NULL ? "./challenge" : argv[0]);

    if(access(argv[1], R_OK)) {
        perror("failed access check");

    fd = open(argv[1], O_RDONLY);
    if(fd == -1) {
        perror("failed file open");
    read(fd, &buf, sizeof(buf)-1);
    printf("%s\n", buf);

    return 0;

So from what I can understand it checks if you have access to the file passed then im a little confused about the fd = open(... line as fd is an int variable. I'm guessing it returns 0 if it can open in read only? I tried in gdb to set fd to 0 then jump to read function or just before it but only got ?be return so I can only guess that fd should be something else or im just way off. I also tried just jumping over the access check which worked but then I got a read error.

Actual questions here:

reading man for access() says that checks in context of the process so why does it fail?

What is that fd = open... line doing?

What am I missing getting it open the flag.txt file?

Thank you



comments powered by Disqus