Path.normalize()
を使用すると、パスから ".."要素(およびその先行要素)を除外できます。 "a/b /../ c"を "a/c"に変換します。パスの開始の「..」を取り除くことはないことに注意してください。これは、除去するための先行するディレクトリコンポーネントもないからです。したがって、別のパスを前に置く場合は、最初に行い、次に結果を正規化します。
Path.startsWith(Path)
を使用して、あるパスが別のパスの子孫であるかどうかを確認することもできます。 Path.isAbsolute()
は、驚くことではないが、パスが絶対パスか相対パスかを示します。
は、ここで私はAPIに入ってくる信頼されていないパスを処理したい方法は次のとおりです。
/**
* Resolves an untrusted user-specified path against the API's base directory.
* Paths that try to escape the base directory are rejected.
*
* @param baseDirPath the absolute path of the base directory that all
user-specified paths should be within
* @param userPath the untrusted path provided by the API user, expected to be
relative to {@code baseDirPath}
*/
public Path resolvePath(final Path baseDirPath, final Path userPath) {
if (!baseDirPath.isAbsolute()) {
throw new IllegalArgumentException("Base path must be absolute")
}
if (userPath.isAbsolute()) {
throw new IllegalArgumentException("User path must be relative");
}
// Join the two paths together, then normalize so that any ".." elements
// in the userPath can remove parts of baseDirPath.
// (e.g. "/foo/bar/baz" + "../attack" -> "/foo/bar/attack")
final Path resolvedPath = baseDirPath.resolve(userPath).normalize();
// Make sure the resulting path is still within the required directory.
// (In the example above, "/foo/bar/attack" is not.)
if (!resolvedPath.startsWith(baseDirPath)) {
throw new IllegalArgumentException("User path escapes the base path");
}
return resolvedPath;
}
どのようにウェブにそれらのパスを暴露していますか?一般的に、Springのようなフレームワークは、これらの攻撃に対する緩和のためにかなり良い仕事をしているので、他のセキュリティレイヤーを追加する必要はほとんどありません。 – Makoto
私はそうではありません。これは、バックエンドのdevops関連のAPIで、ファイル削除ロジックが含まれているため、OSファイルシステムの権限の助けを借りずに、特定のルートフォルダの外部にあるファイルを削除しないようにする必要があります。 – matanster
ここではどのような道筋がありますか? 'java.nio.file.Path'には相対ファイルパスをベースなどに統合するメソッドがあります。 – biziclop