Saturday, April 02, 2005

A simple C code.

I asked an interviewee to write a code that should take a string from user and print it back.

He scribbled it in a fraction of second:

void main()
{
char name[100];
scanf("%s", name);
printf(name);
}

Do you think this code is secure? If not, how many bugs does it have?

2 comments:

SG said...

Damn, You got me.
I just can say 'Great'.
Well lemme consolidate your replies.
You found basically four flaws
1. Buffer overflow
Name is of 100 size. if user enters input beyond 100 chars, its gonna overflow the buffer. Attacker can inject asm instructions to execute the command of his choice. I will explain in future how exactly to exploit these flaws.
The solution to such problems is to use boundry check.
You must be cautious while using other function like strcpy, strcat etc.
2. Format String problem.
You should provide the format.
printf("%s", name);
3. Coding Best Practices
Use int rather than void to help OS know what the return value of your application was.
4. Logical Error
The task was to take the input containing white spaces too. So use gets() but gets is also not size-consious. Use fgets() from gets family.

Any other flaws??

SG said...

Hehe:))

Wish you could attend my secure programming workshops.