Inf226-ctf™

INF226 2026 Portfolio Assignment 1

Capture the Flag

Intro: JSON Web Tokens

A JSON Web Token (JWT) is a “a compact and self-contained way for securely transmitting information between parties as a JSON object” [jwt.io]. You've probably been using them every day for years: every time you log in somewhere using OIDC, the login provider (e.g. Feide, ID-porten, Google, Facebook, Github, Gitlab, etc.) issues a JSON Web Token with your login information, signs it and gives it to the place you're logging in to (the client, or relying party). The client can then check the signature against the provider's public key, and trust that the provider has verified that you are who you say you are – i.e., use it to authenticate you. JWTs are also commonly used for authorization – e.g., “Would you like to give $APP_NAME access to your Google Drive?”

A JWT consists of:

It's the same concept that we've been using for thousands of years, except with a digital cryptographic signature instead of seals, stamps and hand-written signatures.

Your Personal Portfolio-1 Token

For this assignment, you're going to use JWTs to prove who you are and that you've completed the assignment. For each part of the assignment, you have to use buffer overflows to break into a server. Once you're successful, you'll be issued a signed token that proves you've completed the task. (It's like completing a scavenger hunt with a passport, where each station on the hunt will stamp your passport!)

To get you're initial token that prove that you're you, log in below with UiB's Gitlab server, git.app.uib.no. If you don't have an account there already (26 of you don't), log in to UiB's GitLab first picking the option “Students and employees at UiB, UiO... (via Feide)”, not “External Users (GitHub)” – you'll have to wait a few minutes before your account is ready.

and the information inside looks like this:

{
    "sub": "anya",      // the username
    "iss": "https://inf226.puffling.no",  // who issued the token
    "iat": 1758110453,  // when it was issued
    "scope": ["id"],    // the purpose, in this case identification
                        // when you complete a task, it'll say ["id","task-1"]
}

Rules & Practical Information

Before You Start

You should do Pwnexercise and Ropexercise first, so that you're somewhat familiar with pwntools and buffer overflow techniques. The instructions and hints will use pwntools and Python, though you may use any language you like to implement your solution.

Note that the tasks have been designed so that the output from the server typically ends with a : or a ?. This makes it easier to use recvuntil() (or next_qa() from ctf-helper.py). Also, in the cases where you need to input the address of getFlag() (only some of the tasks need this), you may have to add 5 to it, for reasons explained elsewhere.

Learning Objectives

Afterwards, you should be able to explain…

  • how a buffer overflow attack works,
  • how the computer knows which code to run,
  • how function calls work,
  • roughly how code and data for a program is represented on disk and in memory

and you should be able to…

  • identify data on a stack frame,
  • find memory addresses of code / data (symbols)
  • use pwntools (or similar) to connect to and communicate with a program, locally or over the network

Also, you should have a rough idea of how to mitigate / prevent buffer overflow attacks. Additionally, you might have so fun (or find the whole thing extremely frustrating).

Deadline, Deliverables and Grading

  • The deadline is Friday, September 25th 2026 at 23:59.
  • This assignment counts towards your grade. Each task counts as 2% of your final grade, for a total of 10%. The next 30% will be the other assignments, and the final 60% the exam. All the assignments and the exam must be passed in order to pass the course.
  • The assignment is individual and the results/report you submit must be your own.
  • All you need to do is complete the tasks, so that the Current Status above shows Success. You don't have to deliver anything.
  • To pass this assignment, all you need is an honest attempt at completing the assignment – there is no minimum score required. (If there's any doubt, we can tell from the logs whether you've made an honest attempt or not.)

Plagiarism / Cheating / Collaboration

  • You may discuss / sit together with / try and figure things out together with other students, but your work must be your own.
  • You can ask AI for assistance in explaining things, but not for generating a solution. Generally, it is better that you ask us or other students to explain stuff (no question is too stupid and no time (before the deadline) is too late to ask!).
  • When/if helping each other, please try to not ask for / give solutions, but rather explanations of how things work, or other hint. Explaining how [you think] your [non-functioning] code works can be useful for both you and the your collaborator. Anya can provide you with your own personal rubber duck if you ask (Acme, Inc.'s rubber duck division seems to be struggling with deliveries nowadays, for some reason.)
  • If possible, try to ask for help on a Discord channel rather than with private messages – there are probably others who wonder about the exact same thing, but are too shy to ask!
  • But: don't post screenshots/listings with your (almost) complete solution, or showing the flag, etc. There are still lots of useful things to ask/answer regarding library function, how does return-oriented-programing work, etc.

Deadline extensions, etc

If you for some reason see that you can't deliver on time, you can get a deadline extension. You don't have to explain why – we trust that you have a sensible reason (and certainly understand if you don't!). It's better to spend a bit of extra time and get it right, than to take shortcuts and learn nothing.

  • You can get an (up to) 64 hour extension if you need it. However: for the next compulsory exercise, you will then have to deliver a draft of that exercise 64 hours before that deadline, so we know you're on the right track next time!

  • If you really need a longer extension, please include the code of whatever you have so far (even if it's nothing) and a brief plan for how you intend to complete the exercise in the remaining time. Unless we have arranged otherwise due to special circumstances, any work done more than 64 hours after the deadline won't be counted.

  • If you've solved the assignment and just think you could do a bit better with a bit more time – don't bother, you probably have more useful stuff to do, and small fixes won't make any practical difference. Perfection is overrated!

The Tasks

Task-0 (Warming Up)

You'll find task-0 running on inf226.puffling.no at port 7000. Connect, send your id token, and you will then get the following question:

  • Are you ready for a challenge (no/maybe/yes)?

The task will be more difficult depending on whether you answer n/no (easy mode), m/maybe (moderate mode, the default) or y/yes (hard mode).

To solve it, you must answer four simple questions of the form What does the <ANIMAL> say?. If you enjoy guessing, you can try to guess, or you can just read the source code. The difficulty modes have the following effect:

  • no/easy mode: the questions are always presented in the same order (so, you can just send all the answers without reading the questions)
  • maybe/moderate mode: the questions appear in random order
  • yes/hard mode: the fox sound is a random byte string, 16 bytes long, including \0 terminator (it's “just” pseudo-random, so it's theoretically predictable, but you should be able to find an easier way)

Purpose: Make sure that your token and basic setup works, before you move on to more advanced stuff. You don't need to deal with return addresses and such for this task, overwriting local variables should be enough.

Success criterion: To get your success token (“capture the flag”), you'll need to succeed in yes/hard mode.

Hints:

Files

  • Download: task-0 (Linux ELF executable w/debugging symbols), task-0.c (C program)
View source code
const char rodata[] = "abcd";
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>

void getFlag(unsigned int mode);
char fox_sound[16] = "pwnpwnpwnpwnpwn";
const char *riddles[] = {
    "rubber duck", "squeak",
    "non-rubber duck", "quack",
    "parrot", "squawk",
    "fox", fox_sound};
void randomize(char *s, unsigned int n);

int main(int argc, char **argv)
{
    setbuf(stdout, NULL); // turn off output buffering
    srand(time(NULL));

    /////////// INTERESTING CODE BELOW //////////////

    unsigned int nRiddles = sizeof(riddles) / sizeof(char *) / 2;
    int start = 0, challenge = 1;
    char animal[16];
    char sound[16];
    char buffer[16];

    printf("Are you ready for a challenge (no/maybe/yes)? ");
    if (!gets(buffer))
        return 1;
    if (tolower(buffer[0]) == 'y')
    {
        randomize(fox_sound, sizeof(fox_sound));
        start = rand() % nRiddles;
        challenge = 2;
    }
    else if (tolower(buffer[0]) == 'n')
    {
        start = 0;
        challenge = 0;
    }
    else
    {
        start = rand() % nRiddles;
        challenge = 1;
    }

    int i;
    for (int k = 0; k < nRiddles; k++)
    {
        i = (start + k) % nRiddles;
        strcpy(animal, riddles[i * 2]);
        strcpy(sound, riddles[i * 2 + 1]);

        printf("What does the %s say? ", animal);

        if (!gets(buffer))
            return 1;

        if (strcmp(buffer, sound) != 0)
        {
            printf("Nope :(\n");
            exit(0);
        }
    }

    printf("You are truly wise in the ways of the %s. Proceed.\n", riddles[i * 2]);

    getFlag(challenge);

    return 0;
}

void getFlag(unsigned int mode)
{
    const char *modes[] = {"easy", "moderate", "hard"};
    if (getenv("TASK_NAME"))
    {
        char cmdline[48];
        snprintf(cmdline, 47, "python ctf.py check %d", mode);
        system(cmdline);
    }
    else
    {
        printf("Success (%s mode)!\n", modes[mode]);
    }
}

void randomize(char *s, unsigned int n)
{
    int i = 0;
    while (i < n - 1)
    {
        s[i++] = rand() % 256;
    }
    s[i] = 0;
}

Task-1 (E-commerce Fraud)

A rubber duck vendor is operating on port 7001 on inf226.puffling.no, and you've been given $1000 credit to buy ducks. Their developer has been reading the INF226 textbook – specifically the example about a bookstore that lost money to customers who fraudulently ordered a negative number of books – and devised a way to protect against such fraud. But with your experience in buffer overflows, you may still be able to scam them out of some money and/or ducks.

Note the order data structure – we'll use structs to make the variable layout more predictable. The C compiler is free to choose how local variables are laid out on the stack since local variables are only accessible inside a function. But data structures have to be compatible across function calls, so they have a well-defined layout. GCC will typically place arrays and buffers above scalar (i.e., closer to the return address), to protect them from buffer overflows.

Stack canary active: The Stack Canary is enabled for this task, so you probably won't be able to overwrite the return address – but you don't need to. Note that data is packed tightly on the stack, so if you write past the order structure, you will overwrite the canary and the program will crash. This might happen if you use io.sendline(…) since it sends an extra newline character after the payload. To avoid the problem, you can use io.send(…) instead, followed by io.shutdown('send') – or just let it crash, it won't affect your success.

Wallet: The money (and your duck collection) is stored in the token, so as long as you use your original token, you'll always start out with $1000 and 0 rubber ducks. If you want to complete the task in multiple transactions, you need to save the token you get back and use it for the next connection attempt.

Success criterion: You start with $1000 in your account. Rubber duck prices vary, but start at $20. To get your success token (“capture the flag”), you need to complete a transaction and end up with at least 100 rubber ducks. For extra bragging rights, become a billionaire or buy enough ducks to fill a bathtub! Current Status above shows your account / duck collection after your last successful attack (if any).

Hints:
  • Writes past the end of order.buffer will overwrite order.nDucks and order.unitPrice, which might come in handy for this task. If you write past order.unitPrice, you'll touch the stack canary.
  • You don't need to deal with return addresses and such for this task, overwriting local variables should be enough.

Files

  • Download: task-1 (Linux ELF executable w/debugging symbols), task-1.c (C program)
View source code
const char rodata[] = "abcd";
#include <stdio.h>
#include <stdlib.h>
#define _GNU_SOURCE
#include <string.h>
#include <time.h>
#include <stddef.h>

struct account
{
    long money;
    long ducks;
    const char *name;
};
void retrieve_account(struct account *acc);
void check_flag(const struct account *acc);

int main(int argc, char **argv)
{
    struct account acc; // current user and their money
    retrieve_account(&acc);
    srand((int)time(NULL));
    /////////// INTERESTING CODE BELOW //////////////

    // these are the interesting local variables, packed in a struct so the layout doesn't change
    struct Order
    {
        char buffer[12];
        int nDucks;
        long unitPrice;
    } order;

    order.unitPrice = 20 + rand() % 10;

    setbuf(stdout, NULL); // turn off output buffering
    printf("Welcome to *Acme Rubber Ducks, Inc.*!……"
           "For a limited time only, we'd like to *personally* offer *you*, %s, quality rubber ducks at the low, low price of only $%ld per unit!……"
           "(NOTE!! This offer is NON-TRANSFERABLE and for a LIMITED TIME ONLY. Special TERMS AND CONDITIONS may apply.)……"
           "You have $%ld in your account, and you have %ld ducks. How many rubber ducks would you like to order? ",
           acc.name, order.unitPrice, acc.money, acc.ducks);

    fgets(order.buffer, 512, stdin);
    order.nDucks = atoi(order.buffer); // atoi converts a string to an int

    if (order.nDucks < 1)
    { // we're certainly not going to get tricked by anyone ordering a negative amount of ducks!
        printf("Sorry, minimum order size is 1\n");
        return 0;
    }

    long total = order.nDucks * order.unitPrice;
    if (total > acc.money)
    { // input validation is important. we're checking everything here!
        printf("%d ducks @ $%ld/unit makes $%ld, but you only have $%ld! Sorry!\n", order.nDucks, order.unitPrice, total, acc.money);
    }
    else
    {
        acc.money -= total;
        acc.ducks += order.nDucks;
        printf("Thank you for your order of %d ducks @ $%ld/unit!…"
               "We have charged your account $%ld, and you now have $%ld left and you have %ld rubber ducks in your collection.\n",
               order.nDucks, order.unitPrice, total, acc.money, acc.ducks);
        check_flag(&acc);
    }

    return 0;
}

void retrieve_account(struct account *acc)
{
    const char *m = getenv("MONEY");
    if (m != NULL)
        acc->money = atol(m);
    else
        acc->money = 1000;
    const char *d = getenv("DUCKS");
    if (d != NULL)
        acc->ducks = atol(d);
    else
        acc->ducks = 0;
    acc->name = getenv("USER") ? getenv("USER") : "anonymous";
    // ^^^ the arrow operator (->) gets a field value from a *pointer to a struct*; it is
    // equivalent to dereferencing the pointer (*acc) and then selecting the field: (*acc).name
}

// check if the flag was captured
// ctf.py will check if money > 1000 and if so issue a success token
void check_flag(const struct account *acc)
{
    if (getenv("TASK_NAME"))
    {
        char cmdline[48];
        snprintf(cmdline, 47, "python ctf.py check %ld %ld", acc->money, acc->ducks);
        system(cmdline);
    }
    else
    {
        printf("Success!\n");
    }
}

Task-2

Tech mogul Sheev Hobbs, famous for his Orange line of user-friendly computers, has moved on to his latest project: the revolutionary, fully object-oriented THiSSTEP¹ operating system. The first thing he needs to make it work is an object-oriented variant of C². The scheme he has come up with is simple: since an object is just data bunded together with methods to act on that data, he can encode an object as a normal C struct where the methods are simply function pointers. So, for example, a Duck object might look like this:

struct Duck {
    float x,y; /* Current position */
    float dx, dy; /* Current velocity */
    char name[16]; /* Name of the (individual) animal */

    void (*step)(struct Duck* this); /* Pointer to the object's step method */
};

The function pointers can be accessed like any other field, and called like any other function:

    struct Duck duck = { … };
    duck.step(&duck); // or duck->step if accessed through a pointer

The only limitation is that we need to explicitly pass a pointer to the current object as the first argument, so the syntax is a little bit clunky. To chech that this new object-oriented C style is actually usable, Sheev has made a small demo program – a simple simulation of ducks and frogs in a pond – and connected it to the Internet, so he can evaluate not just the usability of his invention but also the security. You have been asked to do a penetration test to see if there are any security flaws in his approach to object-oriented C programming.

The simulation is live at port 7002 on inf226.puffling.no. When you connect (and enter your token as usual), you'll see a menu of valid commands and a one-dimensional display of the current pond state:

Welcome to THiS, Inc.'s Object-Oriented Pond Simulator.

(e)xit           -- end the simulation
(h)elp           -- print help
(m)em            -- dump memory
(n)ame           -- rename animal
(s)tep, NEWLINE  -- move one step
(e)xit, EOF      -- exit

[🐸                                                              ]  command? name
This animal's current name is 'froggie'. What do you want to call it? Bubbles
PondAnimal renamed to 'Bubbles'.
[🐸                                                              ]  command? step
[  🐸                                                            ]  command? step
[    🐸                                                          ]  command? s
[      🐸                                                        ]  command? s
[        🐸                                                      ]  command? s
[          🐸                                                    ]  command? s
[            🐸                                                  ]  command? 
[              🐸                                                ]  command? 
 Bubbles says "croaaAAAAAKKK!!!"
[                🐸                                              ]  command? exit

Your task is to use a buffer overflow attack to make the program call the getFlag() function. More details:

Jump-Oriented Programming: To solve this task, you must overwrite a function pointer so the program ends up calling getFlag() instead of whatever it was supposed to call. To do this, you'll have to figure out the correct address for getFlag() – you can find this by disassembling the ELF executable, or printing its symbol tables, or by loading the ELF file with pwntools and looking it up in the symbol table.

Stack canary active: The Stack Canary is enabled for this task, so you probably won't be able to overwrite the return address – but you don't need to, just overwrite a function pointer instead.

Locals in a struct: As before, the locals are put into a struct to make the stack frame layout more predictable. Use the stack visualiser to see the exact layout if needed. You can also use the mem command to see the exact contents of the stack frame. The offsets on the left-hand side correspond to what you see in the visualiser.

Source code: C supports separate compilation and the separation of declarations and definitions. The implementations of methods and some other functions has been placed in a separate file, so you can't see them. You can try to guess what's going on, or you can look at the hints for some more details.

Extra difficulty: If you want an extra challenge, add -H before your token when you connect, this will turn on hard mode where you can no longer overwrite data.buffer. If you use ctf_helper.py, you can enable this with read_welcome('-H' + id_token).

Success criterion: To get your success token (“capture the flag”), you need to use jump-oriented programming to call the getFlag() function.

A note on C pointers, structs and syntax When using C structs, we must distinguish between a struct as a value and a pointer to a struct:

  • If we declare a variable struct Pond pondstruct = {…};, the variable pondstruct is the struct, and we refer to its fields using pondstruct.animal, pondstruct.draw, etc. The stack frame will include space for the complete struct, and if we pass it as an argument, the entire struct will be copied and changes to the copy won't affect the original. There is nothing like this in a language like Java or Python.
  • On the other hand, with struct Pond* pondptr = &pondstruct;, the variable pondptr is a pointer to a struct; the stack frame only stores a 64-bit pointer. If we pass it as an argument, only the pointer is copied, and both caller and callee work on and modify the same struct. To access the struct itself, we need to reference it (*pondptr). C has the convenient arrow operator -> for this use case: for example, pondptr->animal is equivalent to (*pondptr).animal and means "pick the field animal in the struct pointed to by pondptr". In Java, Python and many other languages, object variables are always references to objects rather than the objects themselves, so there is no need for a separate dot (.) and arrow (->) syntax.
  • As you might recall, C arrays are also just pointers, and array indexing is just syntactic sugar for adding the index to the pointer and then dereferencing it: array[4] is the same as *(array+4). In fact, we could use this syntax instead of the arrow: pondptr->animal->name and pondptr->animal[0].name are equivalent.
Hints:
  • Overflowing the command buffer (data.buffer) lets you overwrite the fields and methods of pond. This doesn't work in hard mode.
  • By sending the name command, you get a chance to overflow animal.name and overwrite the methods of the animal object.
  • Use the mem command to see the current contents of the stack frame. You can find the index of the fields and methods in the stack visualiser.
  • Click here to see Exactly when the various methods are called
    • pond.draw() gets called before reading the command. It will call animal.get_icon() if animal is not null.
    • pond.step() gets called for every step. It will call animal.step() and pond.contains(). It doesn't check the animal pointer first.
    • animal.step() will call animal.make_noise() for every eighth step.

Files

  • Download: task-2 (Linux ELF executable w/debugging symbols), task-2.c (C program)
View source code
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdbool.h>
#include <string.h>

// This one has been removed from the library due to security issues...
char* gets(char* s);

//////////
// Forward/external declarations
//////////

/** The gadget */
void getFlag();
/** Print help */
void help();

/** Prints the contents of main's stack frame (defined externally) */
void dump_mem();
/** Check if 's' matches 'command_name'; abbreviations allowed */
bool is_command(const char* command_name, const char* s);

// In Java, Python, etc. an object variable is always a *reference* to an object.
// C doesn't have references, so we have to use pointers instead.
typedef struct PondAnimal* PondAnimal; // PondAnimal type is now a pointer to a PondAnimal
typedef struct Pond* Pond;             // Pond type is now a pointer to a Pond

//////////
// *** Class interface declaration for Pond
//////////

struct Pond {
    //// fields
    /** Pond size */
    long width;
    /** Points to the resident animal */
    PondAnimal animal;

    //// "methods" – we have to pass 'this' manually when we call them

    /** Do one step of the pond simulation, return true if we should continue */
    bool (*step)(const Pond this);

    /** Returns false if animal is outside the bounds of the pond */
    bool (*contains)(const Pond this, const PondAnimal animal);

    /** Print the pond to the console. Animals will be displayed using their get_icon() method */
    void (*draw)(const Pond pond);
};
// constructors (defined externally)
Pond Pond_init(Pond this);

//////////
// *** Class interface declaration for PondAnimal
//////////

struct PondAnimal {
    //// fields
    /* Current position */
    float x;
    /* Current velocity */
    float dx;
    /* Name of the (individual) animal */
    char name[16]; // *** perhaps we can overflow this buffer?

    //// "methods" – we have to pass 'this' manually when we call them

    /** Print whatever the animal says */
    void (*make_noise)(const PondAnimal this);

    /** Returns an icon to be displayed on screen */
    const char* (*get_icon)(const PondAnimal this);

    /** Move and maybe make some noise */
    void (*step)(PondAnimal this);
};
// constructors for two variants ("subclasses") of PondAnimal
PondAnimal Duck_init(PondAnimal this, const Pond pond);
PondAnimal Frog_init(PondAnimal this, const Pond pond);

// ignore – these are used by dump_mem()
void* bottom_of_main_stackframe;
const int stackframe_size_in_words = 20;

int main(int argc, char** argv) {
    bottom_of_main_stackframe = &argv;
    srand(time(NULL));

    // With HARD_MODE, limit reads into the command buffer so it can't overflow
    int BUFFER_SIZE = getenv("HARD_MODE") ? 16 : 128;

    // Put local vars in a struct so they are more buffer-overflowable...
    struct {
        char buffer[16]; // *** perhaps we can overflow this buffer?
        struct Pond pond; // *** interesting function pointers here?
        struct PondAnimal animal; // *** interesting function pointers here?
    } data;

    register Pond pond = &data.pond;   // just convenient short-hand
    register PondAnimal animal = &data.animal;// just convenient short-hand

    // "Construct" the pond
    Pond_init(pond);
    // Fill it with a duck or a frog
    pond->animal = rand() % 2 == 0 ? Duck_init(animal, pond) : Frog_init(animal, pond);

    printf("Welcome to THiS, Inc.'s Object-Oriented Pond Simulator.\n");
    help();
    printf("\n");

    while (true) {

        // draw pond and prompt for command 
        pond->draw(pond); // calls animal->get_icon() to draw animal
        printf(" command? "); fflush(stdout);

        // read command into buffer
        if (!fgets(data.buffer, BUFFER_SIZE, stdin)) // *** overflowable in easy mode
            break;

        // evaluate command
        if (is_command("exit", data.buffer)) {
            break;
        }
        else if (is_command("mem", data.buffer)) {
            dump_mem();
        }
        else if (is_command("name", data.buffer)) {
            printf("This animal's current name is '%s'. What do you want to call it? ", animal->name);
            fflush(stdout);
            if (!gets(animal->name)) // *** uses unsafe gets()
                break;
            printf("PondAnimal renamed to '%s'.\n", animal->name);
        }
        else if (is_command("step", data.buffer) || is_command("", data.buffer)) {
            // pond->step() will call pond->contains() and animal->step() (which  might call animal->make_noise())
            if (!pond->step(pond))
                break;
        }
        else if (is_command("help", data.buffer)) {
            help();
        }
        else {
            printf("Unknown command %s", data.buffer);
        }
    }

    printf("Exiting\n");
    fflush(stdout);
    return 0;
}

// Call this to win!
void getFlag() {
    if (getenv("TASK_NAME")) {
        printf("Success!\n");
        fflush(stdout);
        system("python ctf.py success");
        exit(0);
    }
    else {
        printf("Success!\n");
        fflush(stdout);
        exit(0);
    }
}

void help() {
    printf("\n" //
        "(e)xit           -- end the simulation\n"
        "(h)elp           -- print help\n"
        "(m)em            -- dump memory\n"
        "(n)ame           -- rename animal\n"
        "(s)tep, NEWLINE  -- move one step\n"
        "(e)xit, EOF      -- exit\n" //
    );
}

¹ Unfortunately, THiSSTEP doesn't have a Wikipedia page yet, but here's a description of a popular clone.

² He's thinking of maybe calling it Objectish-C, C** or maybe C with Classes.

Task-3

This single-question trivia quiz runs on inf226.puffling.no at port 7003. Your goal is to call the getFlag() function, by overwriting the return address from main(). But the trick you used last time won't work, since the stack is protected by a stack canary. You need to figure out the canary value and include that in your payload when you overwrite the return address.

Success criterion: To get your success token (“capture the flag”), you need to use return-oriented programming to call the getFlag() function. Be careful so you don't trip the stack canary!

Hints:
  • Find the offset of the stack canary from the start of the buffer to reveal the canary value.
  • You can convert the hex string in the hint to a number with int(s, 16).

Files

  • Download: task-3 (Linux ELF executable w/debugging symbols), task-3.c (C program)
View source code
#include <stdio.h>
#include <stdlib.h>

void getFlag();

int main(int argc, char** argv) {
    struct {
        int  answer;
        short _reserved;
        char buffer[9];
        int correct;
    } data;

    data.correct = 42;

    setbuf(stdout, NULL); // turn off output buffering
    printf("What's the average weight of an Atlantic canary? ");

    fgets(data.buffer, 512, stdin);
    data.answer = atoi(data.buffer);

    if(data.answer != data.correct) {
        printf("Here's a hint: %lx\n", *(unsigned long*)(data.buffer + data.answer));

        // ask again
        printf("What's average weight of an Atlantic canary? ");
        fgets(data.buffer, 512, stdin);
        data.answer = atoi(data.buffer);
    }

    if(data.answer == data.correct) {
        printf("How do you know so much about canaries?\n");
    }

    return 0;
}


void getFlag() {
    if (getenv("TASK_NAME")) {
        printf("Success!\n");
        system("python ctf.py success");
        exit(0);
    }
    else {
        printf("Success!");
        exit(0);
    }
}

Task-4 (A Very Basic Language Server)

Young software mogul Jill Yates has developed a new online BASIC programming environment for enthusiastic hobbyists*, and you've been hired to do penetration testing. The BASIC interpreter is running on inf226.puffling.no port 7004. Connect to it, and it will prompt you to enter a BASIC program line-by-line (put a -b in front of your token to get verbose output from the BASIC interpreter):

[pnxd5t] Please enter your token: -b eyJhbGciOiJFZERTQ…
[pnxd5t] Welcome, Jill.Yates! Best of luck with task-4!

Ready for some BASIC programming?
100  LET W$="WORLD"
110  PRINT "HELLO "; W$
120  END
BASIC> LIST
BASIC:    100 LET W$="WORLD"
BASIC:    110 PRINT "HELLO "; W$
BASIC:    120 END
BASIC> RUN
HELLO WORLD

You've noticed two potential issues in the main loop:

   while (locals.buffer[0] != '\0')
    {
        printf("%lu ", *locals.line_pointer);

        if(!gets(locals.buffer)) // reads line, with newline replaced by '\0'
            break;

        output_line(outfile, line_no, locals.buffer);
        line_no = line_no + 10;
    }
  • Line 3 in the fragment prints the current line number by reading it through a pointer.
  • Line 5 calls gets() which is unsafe because it doesn't protect agains buffer overflows – in fact, it's so unsafe that it's been removed from the C standard. GCC says this about it if you compile against the older standard that still included gets():
/usr/bin/ld: /tmp/ccz7bQiC.o: in function `main':
/home/anya/inf226/oblig1/server/deploy/task-4/task-4.c:31:(.text+0x8a): warning: the `gets' function is dangerous and should not be used.

Using gets(), you should be able to overwrite the return address, but the stack is protected against buffer overflows with a stack canary. In combination, these two things should allow you to read arbitrary memory addresses, which you'll need to find the stack canary.

Success criterion: To get your success token (“capture the flag”), you need traverse the stack and find the stack canary, then use return-oriented programming to call the getFlag() function.

Hints:
  • You need to figure out where the stack is, and search until you find the active stack frame (put something there that you'll recognize). Unlike Task 3, you need the whole 64-bit address of the word you want to read, not just an offset.
  • cyclic() may be useful to make the buffer recognisable in memory. Also: what value will you get back when you're looking at locals.line_pointer?
  • Use print_mem_entry(address, data) for a nice display of the memory you're examining.
  • Unlike the other tasks, this one has output terminated by a space, so you may need to adjust your recvuntil() calls.
  • In BASIC, comments are introduced by a REM command. See if you can solve the task without getting a syntax error! (Add a -b in front of your token to see errors from the BASIC interpreter.)
  • It's probably a good idea to make a recvmem function, which takes care of doing the buffer overflow, sending the address you're interested in and reading the result.
  • There may be ways to solve this task without using a buffer overflow...
Memory map: This is the (formatted) output of /proc/$PID/maps for task-4 running on the server:
  start addr–    end addr mode   offset   dev inode         file path
–––––––––––– –––––––––––– –––– –––––––– ––––– ––––––        –––––––––––––––––––––––––––––––––––––––––––
    00400000-    00401000 r--p 00000000 08:10 655640                             /srv/2026-portfolio-1/task-4
    00401000-    00402000 r-xp 00001000 08:10 655640                             /srv/2026-portfolio-1/task-4
    00402000-    00403000 r--p 00002000 08:10 655640                             /srv/2026-portfolio-1/task-4
    00403000-    00404000 r--p 00002000 08:10 655640                             /srv/2026-portfolio-1/task-4
    00404000-    00405000 rw-p 00003000 08:10 655640                             /srv/2026-portfolio-1/task-4
    00405000-    00426000 rw-p 00000000 00:00 0                                  [heap]
7ffff7dc1000-7ffff7dc4000 rw-p 00000000 00:00 0 
7ffff7dc4000-7ffff7dec000 r--p 00000000 00:244 151835                    /usr/lib/x86_64-linux-gnu/libc.so.6
7ffff7dec000-7ffff7f4f000 r-xp 00028000 00:244 151835                    /usr/lib/x86_64-linux-gnu/libc.so.6
7ffff7f4f000-7ffff7fa5000 r--p 0018b000 00:244 151835                    /usr/lib/x86_64-linux-gnu/libc.so.6
7ffff7fa5000-7ffff7fa9000 r--p 001e0000 00:244 151835                    /usr/lib/x86_64-linux-gnu/libc.so.6
7ffff7fa9000-7ffff7fab000 rw-p 001e4000 00:244 151835                    /usr/lib/x86_64-linux-gnu/libc.so.6
7ffff7fab000-7ffff7fb8000 rw-p 00000000 00:00 0 
7ffff7fbf000-7ffff7fc1000 rw-p 00000000 00:00 0 
7ffff7fc1000-7ffff7fc5000 r--p 00000000 00:00 0                          [vvar]
7ffff7fc5000-7ffff7fc7000 r-xp 00000000 00:00 0                          [vdso]
7ffff7fc7000-7ffff7fc8000 r--p 00000000 00:244 151815                    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7ffff7fc8000-7ffff7ff0000 r-xp 00001000 00:244 151815                    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7ffff7ff0000-7ffff7ffb000 r--p 00029000 00:244 151815                    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7ffff7ffb000-7ffff7ffd000 r--p 00034000 00:244 151815                    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7ffff7ffd000-7ffff7ffe000 rw-p 00036000 00:244 151815                    /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
7ffff7ffe000-7ffff7fff000 rw-p 00000000 00:00 0 
7ffffffde000-7ffffffff000 rw-p 00000000 00:00 0                          [stack]
Start address (inclusive), end address (exclusive) is the memory area; mode is the permissions:read, write, execute, private; if the memory area is mapped from a file, offset is how far the mapped memory is from the start of the file; dev is the device number, which together with inode identifies the file, and file path is the corresponding path in the file system. The [stack] is probably the most interesting thing here. With ASLR, the library and stack addresses will be randomized, and with position-independed executable enabled, the first five entries would be randomized as well.

Files

  • Download: task-4 (Linux ELF executable w/debugging symbols), task-4.c (C program)
View source code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void getFlag();
void output_line(FILE *outfile, unsigned long line, char *s);
// int gets(char *s);

unsigned long line_no = 100;


int main(int argc, char **argv)
{
    setbuf(stdout, NULL); // turn off output buffering

    FILE *outfile = fopen("/tmp/prog.bas", "w");
    struct
    {
        char buffer[72];
        unsigned long *line_pointer;
    } locals;
    locals.buffer[0] = ' ';
    locals.line_pointer = &line_no;

    printf("Ready for some BASIC programming?\n");

    while (locals.buffer[0] != '\0')
    {
        printf("%lu ", *locals.line_pointer);

        if(!gets(locals.buffer)) // reads line, with newline replaced by '\0'
            break;

        output_line(outfile, line_no, locals.buffer);
        line_no = line_no + 10;
    }

    if (outfile) {
        fclose(outfile);
        system("python ctf.py run /tmp/prog.bas");
    }

    return 0;
}

void output_line(FILE *outfile, unsigned long line, char *s)
{
    static int state = 1;
    if (outfile && state)
    {
        fprintf(outfile, "%lu ", line);
        if (*s < ' ' || strncmp(s, "END", 4) == 0 || strncmp(s, "end", 4) == 0)
        {
            fprintf(outfile, "END\n");
            *s = '\0';
            state = 0;
        }
        else
        {
            while (*s >= ' ')
                fputc(toupper(*(s++)), outfile);
            fputc('\n', outfile);
        }
    }
}
void getFlag()
{
    if (getenv("TASK_NAME"))
    {
        system("python ctf.py success");
        exit(0);
    }
    else
    {
        printf("Success!");
        exit(0);
    }
}

Resources

These resouces may help you get started.

Python pwntools skeleton

You can use this – together with ctf_helper.py (below) – as a starting point for your solutions.

from ctf_helper import *
id_token = ""  # insert your token here

_io : tube = start(7000)

read_welcome(id_token) # send token, and read the (first) question

### REPLACE WITH YOUR CODE
_io.sendline(b'something')


s = next_qa() # reads until the next ? or :

### May help you decode the final success/fail response
log_answer(read_answer())

#### DELETE BEFORE USE
### useful idioms
# log a message
info('hello')

# Padbyte string to fixed size
answer = b'foo'
answer = answer + b'x' * (16 - len(answer)) # pad to 16 bytes
# answer = answer + cyclic(16 - len(answer))) # or use this

# send a pointer
_io.send(p64(0x4012c9))  

# decode/encode hex numbers
info(hex(int(b'0x1235', base=16))) 

# send payload without extra newline
_io.send(b'payload')
_io.shutdown('send')

# values you might see often
# null = 0x00 # '\0'
# newline = 0x0a # '\n'
# cr = 0x0d # '\r' – rare on Unix, used with newline as end-of-line on Windows ('\r\n')
# space = 0x20 # ' '
# 0x21–0x2f – symbol
# 0x30–0x39 – digit
# 0x41–0x5a – uppercase letter
# 0x61–0x7a – lowercase letter
# 0x80–0xff – probably UTF-8 or binary

CTF Helper

Implements a few functions for connecting and receiving data that may be useful.

You can also download the file here: ctf_helper.py.

from pwn import * # type: ignore
import sys

id_token = ""  # insert your token here

# Set to 'info' if you don't want a trace of data sent and received
context.log_level = "debug"

_io : tube = None # type: ignore

def start(port: int):
    """
    Connect to INF226 server. Port number should be 7000-7004.

    With command line arguments (in sys.argv):
        - `FILE`              -- load ELF file (probably requires Posix system)
        - `--process FILE`    -- start local process instead (requires Linux)
        - `--gdb FILE CMDS`   -- start local debugger process instead (requires Linux)
        - `--remote`          -- connect to server (default)

    *(Call this first, then proceed with `read_welcome`)*
    """
    global _io, _elf_file
    action = "--remote"
    file = None
    _io = None # type:ignore
    # very crude commandline option parser
    if len(sys.argv) < 2:
        pass
    elif sys.argv[1].startswith('--'):
        action = sys.argv[1]
        file = sys.argv[2] if len(sys.argv) > 2 else  None
    else:
        file = sys.argv[1]

    if file:
        try:
            _elf_file = ELF(file)
        except Exception as e:
            error("Failed to load ELF file %s", file)

        if action == "--gdb":
            gdb_script = ''.join([f'{a}\n' for a in sys.argv[3:]])
            _io = gdb.debug(file, gdb_script or "break main\n")
        elif action == "--process":
            _io = process(file)
    # By default, we connect to the official assignment servers
    if not _io:
        _io = remote("inf226.puffling.no", port)
    _io.timeout = 2  # wait max 5 seconds when reading data
    return _io

_elf_file = None
def elf_file():
    """Return the ELF executable for the current task, if available."""
    return _elf_file


question_delims = [b": ", b"? ", b":", b"?", b"Success!", b"Failure!"]


def read_welcome(tok: str | None = None, io : tube|None = None):
    """
    Send token and read the welcome/first question. Questions end with '?' or ':'.

    *(It's a good idea to call this first for all the tasks!)*
    """
    io = io or _io
    tok = tok or id_token
    question = io.recvuntil(question_delims, timeout=1024).decode(errors='replace')  # type: ignore # read welcome or token request

    if "Please enter your token:" in question:
        if not tok:
            io.warning_once("WARNING: No token specified!")
        io.sendline(b"" + tok.encode())  # send token
        question = io.recvuntil(question_delims).decode(errors='replace').replace('\u0085','\n')  # read welcome

    return question


def next_qa() -> str:
    """
    Read a question/answer from the tube. (In practice, reads until the next `?` or `:`.

    *(Might be useful for any task)*
    """

    return _io.recvuntil(question_delims).decode(errors='replace').replace('\u0085','\n').strip()


def read_answer(io : tube|None = None) -> tuple[str, str | None]:
    """
    Read and decode answer once you've completed the challenge.

    Call this after you've sent your exploit. Print the result with `log_answer`.

    *(Might be useful for any task)*
    """
    io = io or _io
    a = io.recvuntil(question_delims).decode(errors='replace').replace('\u0085','\n')

    if "signed success token" in a or "signed failure token" in a:
        new_tok = io.recvline().decode(errors='replace').replace('\u0085','\n').strip()
        return a, new_tok
    else:
        rest = io.recvall(timeout=5).decode(errors='replace').replace('\u0085','\n')
        return a + rest, None


def log_answer(answer_and_token: tuple[str, str | None]) -> None:
    """
    Combine with read_answer() to get pretty output.

    *(Might be useful for any task)*
    """
    answer, token = answer_and_token
    if token:
        info("Success!!")
        info("")
        info(
            "*** Please submit the new token to https://inf226.puffling.no/oblig1/ as proof you have completed the task:"
        )
        info("")
        info("        " + token)
        info("")
    else:
        for line in answer.splitlines():
            warning(line)


def chars(n: int):
    """
    Reinterpret a 64-bit integer as a string. Non-ASCII characters are displayed as `.`

    *(Might be useful for task-4)*
    """

    def convert_char(c):
        return chr(c) if 32 <= c < 127 else "."

    return "".join([convert_char(c) for c in unpack_many(p64(n), word_size=8)])


def print_mem_entry(addr: int | str, data: int | str | bytes):
    """
    Helper for printing a memory location.

    Arguments:
        addr (int): the memory address the word was found at
        word (int|str|bytes): contents of memory location, as an integer (possibly encoded as str or bytes)

    *(Useful for task-4)*
    """
    if addr == 0:
        info(f'        {"Address":12s}   {"Word":16s}  {"Chars":8s}  {"Original":24s}')
        info(f'        {"-" * 12}   {"-"*16}  {"-"*8}  {"-"*24}')
    else:
        if isinstance(data, bytes):
            text = repr(data)
            word = int(data, 10)
        if isinstance(data, str):
            text = repr(data)
            word = int(data, 10)
        elif isinstance(data, int):
            text = ""
            word = data
        if isinstance(addr, int):
            info(f"------  {addr:12x}:  {word:016x}  {chars(word):8s}  {text:24s}")
        else:
            info(f"{addr:20s}:  {word:016x}  {chars(word):8s}  {text:24s}")

Using gdb

If you're on Linux (or something close enough to be able to run Linux programs) and you have gdb and gdb-server installed, you can use the GDB debugger to see what's going on while the program is running.

For example, here is a small script of GDB commands that would help you debug task-0:

# put breakpoint at main+370, right after gets() – this will be breakpoint 1
break *main+370
# give list of commands to run when reaching breakpoint 1
commands 1
   # print stack pointer, address of buffer and contents of buffer, sound, animal
   print $rsp    
   print &buffer
   print buffer
   print sound
   print animal
end
# now, run until breakpoint
continue

You can type them in manually, or give them as the gdbscript argument to io.remote; or if you're using ctf_helper.py, you can save them to a file gdb_script and run with:

$ python my_solution.py --gdb ./task-0 "$(cat gdb_script)"

The ELF file includes debugging information (in the DWARF format (pun apparently intended)), so gdb knows where to find variables, how long the buffer array is, and so on.

Without pwntools you could also start gdb with:

$ gdb ./task-0 -x gdb_script

If so, you should replace continue with run in the script.

Other useful gdb commands include disas (print disassembled code) and help.

Hints

  • If you get confused, it may be useful to draw a diagram of the memory, pointers and variables. (Or, if you're lazy, use Explore stack frame layout in the sidebar.)
  • Kenneth's support material from 2020 may be useful, with hints for setting things up and using pwntools.
  • ctf101.org has a useful intro to C and overview of binary exploitation, buffer overflows, return oriented programming, and bypassing stack canaries.
  • If you try to run the code for task-4 yourself (on Linux or in a virtual machine), you'll need to turn off ASLR. You can do this with setarch -R task-4 (or setarch -R gdb task-4 for debugging with gdb), or for the whole system by doing echo 0 > /proc/sys/kernel/randomize_va_space (remember to turn it back on again afterwards with echo 2 > /proc/sys/kernel/randomize_va_space)

Connecting manually:

If you want to talk directly to the servers, you have (at least) a few options:

  • pwntools has io.interactive() – though it seems be make trouble sometimes
  • netcat (nc) is a popular tool for interacting with network sockets. For example:
$ nc inf226.puffling.no 7000
[uiianz] Please enter your token: 
[uiianz] Proceeding as unauthenticated user.
[uiianz] Welcome, 2a01:799:…! Best of luck with task-0!

Are you ready for a challenge (no/maybe/yes)? n
What does the rubber duck say? glurbledörk
Nope :(
  • If your system doesn't have nc, you might have still have old-fashioned telnet installed. Although it's originally meant to connect to a Telnet server (which isn't used much anymore, now that we have SSH), you can also connect directly to a port, just like with nc. If the connection hangs, you can “escape” by pressing Ctrl-] (which is Ctrl-AltGr-9 on a Norwegian keyboard), and quit.
$ telnet inf226.puffling.no 7000
Trying 2001:700:2:8300::2264...
Connected to inf226.puffling.no.
Escape character is '^]'.
[uipmv9] Please enter your token: ^]
telnet> quit
Connection closed.
  • Task-0 and Task-1 should be solvable this way.

Address space:

  • These files are compiled without the position-independent executable (more info) option, so the code is always loaded at the same address (somewhere around 0x401000). Linux (or at least the our server) uses this memory layout:
  • 0x7ffffffffff0 – top of memory, the stack typically starts ~-0x1000 from here (depends on environment variables – should be the same for each run). Each stack frame is aligned so that the address ends with a 0 – some system calls may crash with a SIGSEGV if this is not the case. (See ROP#Solving the system crash.)
  • With a non-PIE executable, the addresses of code and data are hardcoded, so what you see in the ELF file (0x401xxx) will be the actual memory addresses when the program is running. objdump -t shows you all the symbol addresses.
  • The main function gets called from one of the dynamic libraries (__libc_start_call_main in /lib/x86_64-linux-gnu/libc.so.6), so you'll see a return pointer to there on the stack.
  • Dynamic libraries get put somewhere below the stack, addresses may start with 0x7f…. The output of running ldd on a file shows you the libraries. With ASLR, these addresses will be random:
$ ldd task-4
    linux-vdso.so.1 (0x00007c3f9e53c000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007c3f9e200000)
    /lib64/ld-linux-x86-64.so.2 (0x00007c3f9e53f000)
$ ldd task-4
    linux-vdso.so.1 (0x00007b61fa0bc000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007b61f9e00000)
    /lib64/ld-linux-x86-64.so.2 (0x00007b61fa0bf000)
  • With ASLR turned off, the libraries will appear at the same location every time:
$ setarch -R ldd task-4
    linux-vdso.so.1 (0x00007ffff7fbe000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ffff7c00000)
    /lib64/ld-linux-x86-64.so.2 (0x00007ffff7fc1000)
$ setarch -R ldd task-4
    linux-vdso.so.1 (0x00007ffff7fbe000)
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ffff7c00000)
    /lib64/ld-linux-x86-64.so.2 (0x00007ffff7fc1000)

Compiler command lines

  • If you try to compile the C files yourself (on Linux), you may want to turn of PIE (position-independent executable mode). Use this command gcc -g -no-pie -fno-pie 00.c -o 00 (both -no-pie and -fno-pie are necessary; the first is an option to the linker and the latter to the compiler). If you compile with PIE, the code will be placed wherever Linux finds convenient. With ASLR turned off, this will be in the middle of memory, so main might be at 0x5555555551fc, for example.
  • The C programs should work similarly on Mac and Windows – feel free to try! In particular, if you have an M1/M2 Mac, see what difference that makes to the disassembled code, and if the exploits still work.

The commands below are what was actually used to compile the task programs. The option -Wstringop-overflow=0 makes the compiler stop complaining about potential buffer overflows, -g enables debug info (needed to visualize the stack and to use variable names in gdb), and -o specifies the output file (the default is a.out, which is not very useful).

  • Task-0 needs C99 (--std=c99) to use gets(). -fno-stack-protector -fno-pie -no-pie makes no difference in this task:
$ gcc -Wstringop-overflow=0 --std=c99 -g -fno-stack-protector -fno-pie -no-pie task-0.c -o task-0
  • Task-1 is relocatable, and will have randomized addresses:
$ gcc -Wno-stringop-overflow -g task-1.c -o task-1
  • Task-2 has stack canary disabled (-fno-stack-protector):
$ gcc -Wstringop-overflow=0 -g -fno-stack-protector -fno-pie -no-pie task-2.c -o task-2
  • Task-3 has stack canary enabled:
$ gcc -Wstringop-overflow=0 -g -fno-pie -no-pie task-3.c -o task-3
  • Task-4 needs C99 (--std=c99) to use gets(); must be run with setarch -R
$ gcc -Wstringop-overflow=0 --std=c99 -g -fno-pie -no-pie task-4.c -o task-4