As with other inputs, file paths should be validated before thay could be passed to operating system interfaces. Since chroot(2)
has a bit more than some portability issues, oftentimes it is desireable to use a path-validating function.
The general idea, is that no path component should be ..
, and that if we chdir(2)
to the path in question, we must make sure it doesn't begin with a <slash> ("/").
Also, for some application, files or directories with certain prefix (say <dot> (".")) should be outright rejected.
Here's my example of PHP code that does path-validation. I'd like some expertized opinion from the members of the site.
<?php
function antitraversal($s)
{
if( !is_string($s) ) die("Invalid argument: $s");
$components = explode("/", $s);
foreach($components as $component) {
if( $component[0] === "." ) die("Invalid argument: $s");
}
if( $s[0] === "/" ) { return ".$s"; } else { return $s; };
}
For simplicity, we'll assume the script runs in Unix-like environments.