What's the best way to defend against a path traversal attack?

一世执手 提交于 2019-11-30 03:11:26

The following may help. It compares the canonical and absolute paths, and if they differ, then it'll fail. Only tested on a mac/linux system (ie no windows).

This is for the case where you want to allow the user to supply a relative path, not an absolute path, and you don't allow any parent directory references.

public void failIfDirectoryTraversal(String relativePath)
{
    File file = new File(relativePath);

    if (file.isAbsolute())
    {
        throw new RuntimeException("Directory traversal attempt - absolute path not allowed");
    }

    String pathUsingCanonical;
    String pathUsingAbsolute;
    try
    {
        pathUsingCanonical = file.getCanonicalPath();
        pathUsingAbsolute = file.getAbsolutePath();
    }
    catch (IOException e)
    {
        throw new RuntimeException("Directory traversal attempt?", e);
    }


    // Require the absolute path and canonicalized path match.
    // This is done to avoid directory traversal 
    // attacks, e.g. "1/../2/" 
    if (! pathUsingCanonical.equals(pathUsingAbsolute))
    {
        throw new RuntimeException("Directory traversal attempt?");
    }
}

If you're running this on a unix machine (I'm not sure if windows has something similar, but it might) you'll want to look at chroot. Even if you think you hit all the ways for someone to refer up a few directories, it's nice to have the operating system there enforcing the fact.

(chroot causes '/' to refer to some other directory, so "/" might be "/home/me/project" and "/../../.." is still "/home/me/project".)

EDIT:

There's a chroot system call as well as a chroot command-line tool. I don't know if Java has a native method, but nothing would prevent you from running your server with the command-line tool. This should, of course, be in addition to doing your best to prevent other path manipulations.

Tower

You could check out the allowed characters in filenames (http://en.wikipedia.org/wiki/Filename) and filter out all non-allowed characters (white listing) and then you could be sure you've got a filename there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!