我有一個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之間一致工作。
不要忘記禁止訪問文件系統中隨處可見的Windows特殊設備(NUL,COM1等)。 – 2010-03-03 23:46:33
好思想希思。以下鏈接似乎有一個Windows的保留文件名的權威列表:http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx – 2010-03-04 00:13:08
爲什麼你不能在你的配置Apache/IIS服務器呢? – kikito 2010-03-04 10:00:14