RanZilber
RanZilber

Reputation: 1930

How to compile C file but limit the library usage?

I'm working with a unix server.

I'm getting a c file as input from my client ,which i compile.

The c file should be very basic , and contain only functions from stdio , stdlib , math, string.

Is there any flag in GCC compiler that will not allow usage of any other library and will throw a compilation error in case other library is used?

If there is a solution not involving GCC it might be good too , but I don't want to inspect the file.

thanks.

Upvotes: 1

Views: 306

Answers (3)

Daniel Roethlisberger
Daniel Roethlisberger

Reputation: 7065

Limiting libraries (both header includes at compile time and library linkage at link time) is not going to stop untrusted code from directly calling dangerous (as in security-relevant) kernel syscalls. This could be done by the untrusted code e.g. by using inline assembly or shellcode/exploit techniques, for example by deliberately overwriting a return address on the stack to point to a string containing shellcode.

Having said that, you can use the -nostdlib -nodefaultlibs linker options to prevent linking to libraries. However, this will still only allow you to have either the whole of libc, or none of it. You cannot selectively link to only part of libc (say, have printf() but not system()).

Only allowing certain includes is not very effective either: code can just copy the declarations from the include files instead of including certain headers to get around a limitation to only allow specific #include statements. Example:

int system(const char *);
int main() {
    return system("uname -a");
}

If it has to be secure, you should probably look into sandboxing the code at runtime instead of trying to prevent insecure code from compiling.

Upvotes: 6

Dunes
Dunes

Reputation: 40753

Just to illustrate how insecure you allowing the inclusion of stdlib.h is I'll write a small program that can run arbitrary code on your machine.

#include <stdlib.h>

int main() {
    system("`which python` -c \"print 'hello word'\"");
    // instead of simply printing hello world i could open a socket back to the 
    // attacker's machine and start reading in abitrary code and executing it.
    return 0;
}

Upvotes: 1

Dheeraj Vepakomma
Dheeraj Vepakomma

Reputation: 28737

Pass the option -nodefaultlibs or -nostdlib to gcc, along with options to include only the permitted libraries (like -lm for the math library). Check the gcc manual for more information on these options.

-nodefaultlibs
Do not use the standard system libraries when linking. Only the libraries you specify will be passed to the linker.

Upvotes: 1

Related Questions