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?

7 comments:

Up_There said...

First of all, scanf() should be taking &name as the second argument.
After that is done, if the user enters something like %s as the string, there is a possibility of a security leak cuz the stack contents would be printed on to the console. To avoid this, printf() should be used with the format string.

Also, if the string entered by the user has more than 99 characters( 100th one would be used by \0) you could be overwriting sensitive data !


Some other notes :

It is generally considered a better practice to have the return type of the function as int, rather than void.

Up_There said...

To avoid the '> 99 char' problem, use some length limiting mechanism like
scanf("%99s",&name);

Up_There said...

This code also doesn't allow the use of white space within the string !

I hope you didnt hire this person ;)

Alpha0 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??

life-kamaal-hai said...
This comment has been removed by a blog administrator.
life-kamaal-hai said...

Man there are so many bugs in this 2 lines of code, infact more to come???
seriously i admit that i dont know much abt security, sounds really interesting.
PS: dont get confused that I was the one to be interviewed

Alpha0 said...

Hehe:))

Wish you could attend my secure programming workshops.