Thursday, July 30, 2009

How can "foo.c" be passed into filename? char* filename = "foo.c"; system("find -name filename");

How can I get "foo.c" passed in for filename in the system call?





char* filename = "foo.c";


system("find -name filename");





This is in a C file in linux...

How can "foo.c" be passed into filename? char* filename = "foo.c"; system("find -name filename");
Mn is close, but there are 2 errors:





1) There is no len() function. Use strlen() instead of len().





2) He didn't allocate enough memory for the sprintf to fit the entire result string in the buffer. The line needs room to store the \n (or in windows, 2 chars - cr and lf ) in addition to the null terminator. So, his code needs to add 2 instead of 1 to the length calculation.





Taking this a little further, the number of chars should be multiplied by the sizeof(t_char), which MIGHT NOT be 1 byte if the code is destined to use unicode.





Chances are, this is ascii, so the multiplication is unnecessary, but it is better to be safe than sorry. Besides, if this was production code, you'd want to be able to use the same code in both places without any need to change it. Nothing worse than having to go back and recalculate buffer manipulation code during a port.





The above subtleties demonstrate precisely how and why it is so very easy to make a mistake in c/c++, leading to a buffer underallocation or overwrite, and hence a security hole.
Reply:char* filename = "foo.c";


char * command = "find -name ";


char * fullcommand = malloc(len(filename) + len(command) + 1)


sprintf(fullcommand, "%s%s\n", command, filename);





system(fullcommand);





Not certain about how to concatenate but you should get the idea.


No comments:

Post a Comment