访问路径遍历漏洞(Path Traversal Vulnerability)
确保所有来自用户的输入都被认为是不可信的,并对其进行严格的验证。例如,如果你的应用程序允许用户上传或下载文件,请确保这些文件名不包含任何可能用于遍历目录的特殊字符(如..)。
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class PathTraversalProtectionFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String path = request.getServletPath();
if (path.contains("..")) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid path.");
return;
}
filterChain.doFilter(request, response);
}
}