rae1
rae1

Reputation: 6144

How to validate a Unix path?

I'm trying to write a simple C# function to validate a full Unix path to a shell script entered by a user to avoid a couple of things:

The function would take a form like,

public bool IsUnixPathValid(string path)
{
    return !path.IsEmptyOrNull() 
        && path.StartsWith("/") 
        && !path.ContainsCharacters(";', \"")
}

Question: Is there an existing library that would perform something like this? And if not, what would be the best approach and what little details should I look out for (think secure).

Upvotes: 1

Views: 2355

Answers (1)

Celada
Celada

Reputation: 22261

If you're not trying to verify whether or not any file actually exists at the specified path, then probably the only thing you should be doing is checking that the path starts with / (because you want only absolute paths) and that there are no embedded NUL (0) bytes (because POSIX paths can't contain those). That's it. Absolutely anything else can be a valid path. Notably, spaces and semicolons are allowed in paths.

I guess you could also check for multiple adjacent slashes because those are redundant... however they are still accepted (with each group of multiple slashes having the same meaning as a single slash) so they're not actually invalid.

Checking for suspicious strings like "rm -rf /" embedded in the path is a bad idea. If you have security issues caused by unquoted paths sent directly to system commands then you need to solve those security issues (either by quoting the paths as appropriate or, better, by not passing them through things like shells that parse them) instead of blacklisting a few chosen embedded strings. If you blacklist then you're all too likely to miss something that should have been blacklisted, and, furthermore, you're liable to reject things that are actually valid benign paths.

Upvotes: 5

Related Questions