PicoCTF: Stonks

For this walkthrough I’m going to use a different format where I show the steps to solve the puzzle first then explain the how and why afterwards as I think that will work better for this challenge.

We are given a file written in the c language as well as a netcat command we can enter at the command line to interact with the program. Our hint also mentions something about an API key. If this your first time doing this sort of thing or you don’t have much experience with the c language I recommend using a chatbot or google to break the code down line by line as well as just playing with the program to figure out how it works. The program essentially has two features.

  1. Buying stonks
  2. Viewing your protfilio

When buying stonks you are asked for an api key. You can really put anything in and you will still get an AI generated message that looks like you bough some stocks.

After looking through the code I found something that looked interesting

The code is using format strings the print items. You’ll notice that all of the format strings are in quotes except for the last one. This creates a format string vulnerability as now instead of being interpreted as a string of text the user_buf variable can be interpreted as instructions. One thing we could do is pass “%x” characters to the program as our api token when purchasing stonks. This will allow us to work backwards up the stack and return the values of anything stored in the programs memory as a hex value. And looking at an earlier piece of the code we can see that is where the flag is.

Now that we have our exploit let’s execute it

Now let’s convert our hex to ascii using an online converter

We can see a string in there that looks similar to a flag but in a different order. It looks like the flag was shifted backwards in groups of 4 so we’ll have to shift it back before we can submit it. Let’s do this using python.

NOTE: { some characters were making python upset so I deleted them one by one till it worked and then added the last “}” to the end}

First we define our string in the variable y. Then we make a for loop that will iterate through the string in groups of 4 . We can achieve this using the range function. The range syntax works like this


Our range starts at 0 which is the first character and continues for the entire length of the string, which is denoted using the len() function. Then we add our step interval which is 4 to break it up into groups of 4. Next let’s reverse these groups of 4 individually. Since we know they are in groups of for we can do this by indexing into them then using addition to shift them to the desired placement and concatenating them all together using end=”” to place them all on the same line. And then we get the flag!