xorl %eax, %eax

C Quiz No. 2

with 5 comments

Continuing from the first one back in 2009, here is another that a friend of mine send me yesterday.

The concept is that you are free to put whatever you want in do_your_stuff() in order to make it print “win” from function do_my_stuff().

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

void 
do_your_stuff(void)
{
	// do whatever you want
}

void 
do_my_stuff(void)
{
	char c[100];
	unsigned int i, r_index;

	srand(time(NULL));
	for(i = 0; i<1000; i++)
		r_index = rand() % (sizeof(c) - 1);

	printf("c[%u] = %02x\n", r_index, c[r_index]);

	if (c[r_index] == 0x20)
		printf("win!\n");
	else
		printf("fail\n");
	
	return;
}

int 
main(void)
{
	do_your_stuff();
	do_my_stuff();
	return 0;
}

Instantly I came up with a quite simple solution that exploits the concept of uninitialized stack that it’s being used.

void 
do_your_stuff(void)
{
	char buf[2048]; int i;
	for(i=0; i<sizeof(buf); i++) buf[i] = 0x20;
}

Which it works…

$ ./cquiz2
c[98] = 00
fail
$ ./cquiz2
c[81] = 7f
fail
$ gcc -Wall -Werror --std=c99 cquiz2.c -o cquiz_sol
$ ./cquiz_sol
c[43] = 20
win!
$ ./cquiz_sol
c[54] = 20
win!
$

I found it fun so if you have any other solutions feel free to comment on this post.

Written by xorl

May 18, 2013 at 16:44

Posted in C programming, fun

5 Responses

Subscribe to comments with RSS.

  1. How about:

    void
    do_your_stuff(void)
    {
    // do whatever you want
    #define if printf(“win\n”); if
    }

    Sharkey

    May 18, 2013 at 16:53

  2. dostuff.c
    void do_your_stuff(void) { return 0; }
    void do_my_stuff(void) { printf(“win\n”); }

    gcc -fPIC -shared dostuff.c -o dostuff.so

    LD_PRELOAD=./dostuff.so ./cquiz_sol

    greetings to an old friend

    ho_

    ho

    September 6, 2013 at 19:19

  3. Heres how you do it:

    void
    do_your_stuff(void)
    {
    asm(“subw $33, 8(%rsp)”);
    return;
    }

    m

    November 14, 2013 at 17:48

  4. My last post should have been a subb and not subw, but both work anyway

    m

    November 14, 2013 at 17:51

  5. Depending on compiler flags you may get away with a smaller buffer of 100 bytes + 2 sizeof(int) to account for the two local variables on the stack (i, r_index).

    void
    do_your_stuff(void)
    {
    char buffer[100 + sizeof(int)*2];
    memset(buffer, 0x20, 100 + sizeof(int)*2);
    }

    iphelix

    December 21, 2013 at 23:01


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s