注入攻击(Injection Attack)是OWASP Top 10中排名第一的Web应用安全风险,指攻击者通过向应用程序输入恶意数据来改变程序执行流程的攻击方式。
使用PreparedStatement:
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
ORM框架安全使用:
输出编码:
Content Security Policy(CSP):
response.setHeader("Content-Security-Policy", "default-src 'self'")
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.headers()
.xssProtection()
.contentSecurityPolicy("script-src 'self'");
}
}
添加XSS防护过滤器:
@WebFilter("/*")
public class XSSFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(new XSSRequestWrapper((HttpServletRequest) request), response);
}
}