【问题标题】:How can i securely implement CSRF tokens in java我如何在 Java 中安全地实现 CSRF 令牌
【发布时间】:2016-02-27 21:11:03
【问题描述】:

问题背后的问题: 我试图在我的 java web 应用程序中防止 csrf 攻击,为了实现它,我尝试了 X-CSRF-Token 的实现,无论何时发出请求,请求都会像这样传输:

POST /sessions HTTP/1.1
Host: sample.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-CSRF-Token: Ma7g2c5tpeJGcenBa0S4rGtPaHLe2o+kO5AXz+Uk2WnpaTp1J9jdZMPcE1mMSLxZ/7BA1nCBxvLKiZwtepKdoA==
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: https://sample.com
Content-Length: 67

现在,作为攻击者,我试图实现的目标是,我拦截了 post 请求,而不是攻击令牌,我试图攻击参数,例如,请参阅以下请求:

POST /sessions HTTP/1.1
Host: sample.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:42.0) Gecko/20100101 Firefox/42.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
testX-CSRF-Token: Ma7g2c5tpeJGcenBa0S4rGtPaHLe2o+kO5AXz+Uk2WnpaTp1J9jdZMPcE1mMSLxZ/7BA1nCBxvLKiZwtepKdoA==
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: https://sample.com
Content-Length: 67

当我尝试上述请求时,CSRF 令牌实现失败,我能够成功绕过 csrf 注入,

减轻这种攻击的最佳方法是什么?它是有效的 csrf 注入吗?如何优化我的 java web 应用程序以防止这种攻击?

我是如何实现java代码的:

在我的 xml 中:

<http>
    <!-- ... -->
    <csrf disabled="true"/>
</http>

在我的代码中:

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable();
}
}

在提交表单时:

<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}"
    method="post">
<input type="submit"
    value="Log out" />
<input type="hidden"
    name="${_csrf.parameterName}"
    value="${_csrf.token}"/>
</form>

我也遵循了here 提供的推荐方法 ,在上述情况下,csrf 失败,可能有什么缓解措施?

【问题讨论】:

    标签: java json security csrf-protection


    【解决方案1】:

    根据 spring 的文档,您可以注入您的自定义 RequestMatcher 来验证 CSRF 令牌的 HTTP 请求。 Spring 为您提供了覆盖默认值的功能。

    见第 16.6 节http://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html

    class CSRFRequestMatcher implements RequestMatcher{
        public boolean matches (HttpServletRequest req){
            //Check if request contains valid header name & header value
        }
    }
    

    【讨论】:

    • 但是如果标头被删除并受到攻击怎么办?我们可以验证标头的存在吗?
    • 我注意到了一件事。为什么你在你的 spring 配置中禁用了 CSRF - 和 http.csrf().disable();
    猜你喜欢
    • 2015-08-17
    • 2022-07-11
    • 2012-01-07
    • 2012-05-27
    • 2014-01-05
    • 2012-05-01
    • 2021-05-20
    • 2017-01-15
    相关资源
    最近更新 更多