2

In a C program I'm writing I need to check if a file is contained inside a directory.

This is because the file path is provided by the user and I don't want him to be able to access files he's not supposed to by providing paths such as "../../whatever" or "~/.bashrc".

Is there any way to do that with ANSI C and POSIX only (I'm trying to avoid third party libraries)?

Or should I check the path string instead? That was my first idea but it sounds a bit complicated (e.g.: paths containing "." are ok but paths containing ".." are not).

Thanks

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
capitano666
  • 656
  • 1
  • 9
  • 24

1 Answers1

1

What about symbolic links?

I think the real problem here is that you want to convert a possible path into its "absolute" path. Luckily, there's a function that can help you.

From http://linux.die.net/man/3/realpath:

realpath() expands all symbolic links and resolves references to /./, /../ and extra '/' 
characters in the null-terminated string named by path to produce a canonicalized absolute 
pathname. The resulting pathname is stored as a null-terminated string, up to a maximum of 
PATH_MAX bytes, in the buffer pointed to by resolved_path. The resulting path will have no 
symbolic link, /./ or /../ components.

And so, you could convert the path they're attempting to access into the absolute path, and then check if that absolute path is allowed. There's another method called getcwd() that you could use to determine the current working directory.

sgwizdak
  • 101
  • 1