Although it would prohibit some legitimate uses, you could just prohibit any usage of '../' anywhere in the path.
Although it would prohibit some legitimate uses, you could just prohibit any usage of '../' anywhere in the path.
def is_secure_path(path):
path = posixpath.normpath(path)
return not path.startswith(('/', '../'))
The call to `normpath` normalises the path, e.g. >>> normpath('./../foo')
'../foo'Now obviously doesn't apply if you figure out which page to serve based on a submitted GET variable, like the OP seems to suggest doing. I'd see about using PATH_INFO instead (it would also make the Urls easier to read, obscure the implementation a little and potentially be more portable) But it's reasonable, and safer, to just say "the page variable has a specific subdir/subdir/file.html structure and immediately 404 if any of those components don't match ([\w–]), rather than trying to use filesystem-path semantics to resolve to a file and trusting that'll be secure and does what you want.
Don't ever allow the client to specify a filename; use an indirect reference such as a uuid. If you must, always perform path normalization and/or only allow alphanumeric characters.
>>> import posixpath
>>> posixpath.normpath('./../test')
'../test'