[英]What's the best way to defend against a path traversal attack?
我有一個Java服務器實現(TFTP,如果它對你很重要),我想確保它不容易受到路徑遍歷攻擊,允許訪問不應該可用的文件和位置。
到目前為止,我最好的防御嘗試是拒絕任何與File.isAbsolute()
匹配的條目,然后依賴File.getCanonicalPath()
來解析路徑中的任何../
和./
組件。 最后,我確保生成的路徑仍在我的服務器所需的根目錄中:
public String sanitize(final File dir, final String entry) throws IOException {
if (entry.length() == 0) {
throw new PathTraversalException(entry);
}
if (new File(entry).isAbsolute()) {
throw new PathTraversalException(entry);
}
final String canonicalDirPath = dir.getCanonicalPath() + File.separator;
final String canonicalEntryPath = new File(dir, entry).getCanonicalPath();
if (!canonicalEntryPath.startsWith(canonicalDirPath)) {
throw new PathTraversalException(entry);
}
return canonicalEntryPath.substring(canonicalDirPath.length());
}
是否存在未命中的安全問題? 是否更好/更快地可靠地實現相同的結果?
代碼需要在Windows和Linux上一致地工作。
以下可能有所幫助。 它比較了規范和絕對路徑,如果它們不同,那么它就會失敗。 僅在mac / linux系統上測試(即沒有窗口)。
這適用於您希望允許用戶提供相對路徑而非絕對路徑的情況,並且您不允許任何父目錄引用。
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?");
}
}
如果你在unix機器上運行它(我不確定Windows是否有類似的東西,但它可能),你會想看看chroot。 即使你認為你已經找到了某人推薦幾個目錄的所有方法,但讓操作系統強制執行這一事實是很好的。
(chroot導致'/'引用其他目錄,所以“/”可能是“/ home / me / project”,而“/../../ ..”仍然是“/ home / me / project”。 )
編輯:
有一個chroot系統調用以及一個chroot命令行工具。 我不知道Java是否有本機方法,但沒有什么能阻止您使用命令行工具運行服務器。 當然,這應該是盡力防止其他路徑操縱。
您可以查看文件名中允許的字符( http://en.wikipedia.org/wiki/Filename )並過濾掉所有不允許的字符(白名單),然后您可以確定在那里有文件名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.