Java Web应用如何防范跨站请求伪造攻击
2014-08-15 14:13
453 查看
Preventing CSRF in Java Web Apps
Cross-site request forgery attacks (CSRF) are very common in web applications and can cause significant harm if allowed. If you have never heard of CSRF I recommend you check out OWASPspage about it.
Luckily preventing CSRF attacks is quite simple, I’ll try to show you how they work and how we can defend from them in the least obtrusive way possible in Java based web apps.
Imagine you are about to perform a money transfer in your bank’s secure web page, when you click on the transfer option a form page is loaded that allows you to choose the debit and credit accounts, and enter the amount of money to move. When you are satisfied
with your options you press “submit” and send the form information to your bank’s web server, which in turns performs the transaction.
Now add the following to the picture, a malicious website (which you think harmless of course) is open on another window/tab of your browser while you are innocently moving all your millions in your bank’s site. This evil site knows the bank’s web forms structure,
and as you browse through it, it tries to post transactions withdrawing money from your accounts and depositing it on the evil overlord’s accounts, it can do it because you have an open and valid session with the banks site in the same browser! This is the
basis for a CSRF attack.
One simple and effective way to prevent it is to generate a random (i.e. unpredictable) string when the initial transfer form is loaded and send it to the browser. The browser then sends this piece of data along with the transfer options, and the server validates
it before approving the transaction for processing. This way, malicious websites cannot post transactions even if they have access to a valid session in a browser.
To implement this mechanism in Java I choose to use two filters, one to create the salt for each request, and another to validate it. Since the users request and subsequent POST or GETs that should be validated do not necessarily get executed in order, I decided
to use a time based cache to store a list of valid salt strings.
The first filter, used to generate a new salt for a request and store it in the cache can be coded as follows:
LoadSalt生成tokens并缓存到本地
ValidateSalt从request parameter中读取页面提交过来的csrfPreventionSalt后检查salt是否存在于缓存中。
依赖guava-library(http://search.maven.org/remotecontent?filepath=com/google/guava/guava/17.0/guava-17.0.jar)
view
sourceprint?
01.
package
com.ricardozuasti.csrf;
02.
03.
import
com.google.common.cache.Cache;
04.
import
com.google.common.cache.CacheBuilder;
05.
import
com.google.common.cache.CacheLoader;
06.
import
com.google.common.cache.LoadingCache;
07.
import
java.io.IOException;
08.
import
java.security.SecureRandom;
09.
import
java.util.concurrent.ExecutionException;
10.
import
java.util.concurrent.TimeUnit;
11.
import
javax.servlet.*;
12.
import
javax.servlet.http.HttpServletRequest;
13.
import
org.apache.commons.lang.RandomStringUtils;
14.
15.
public
class
LoadSalt
implements
Filter {
16.
17.
@Override
18.
public
void
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
19.
throws
IOException, ServletException {
20.
21.
// Assume its HTTP
22.
HttpServletRequest httpReq = (HttpServletRequest) request;
23.
24.
// Check the user session for the salt cache, if none is present we create one
25.
Cache<String, Boolean> csrfPreventionSaltCache = (Cache<String, Boolean>)
26.
httpReq.getSession().getAttribute(
"csrfPreventionSaltCache"
);
27.
28.
if
(csrfPreventionSaltCache ==
null
){
29.
csrfPreventionSaltCache = CacheBuilder.newBuilder()
30.
.maximumSize(
5000
)
31.
.expireAfterWrite(
20
, TimeUnit.MINUTES)
32.
.build();
33.
34.
httpReq.getSession().setAttribute(
"csrfPreventionSaltCache"
, csrfPreventionSaltCache);
35.
}
36.
37.
// Generate the salt and store it in the users cache
38.
String salt = RandomStringUtils.random(
20
,
0
,
0
,
true
,
true
,
null
,
new
SecureRandom());
39.
csrfPreventionSaltCache.put(salt, Boolean.TRUE);
40.
41.
// Add the salt to the current request so it can be used
42.
// by the page rendered in this request
43.
httpReq.setAttribute(
"csrfPreventionSalt"
, salt);
44.
45.
chain.doFilter(request, response);
46.
}
47.
48.
@Override
49.
public
void
init(FilterConfig filterConfig)
throws
ServletException {
50.
}
51.
52.
@Override
53.
public
void
destroy() {
54.
}
55.
}
I used Guava
CacheBuilder to create the salt cache since it has both a size limit and an expiration timeout per entry. To generate the actual salt I used Apache
Commons RandomStringUtils, powered by Java 6 SecureRandom to ensure a strong generation seed.
This filter should be used in all requests ending in a page that will link, post or call via AJAX a secured transaction, so in most cases it’s a good idea to map it to every request (maybe with the exception of static content such as images, CSS, etc.). It’s
mapping in your web.xml should look similar to:
view
sourceprint?
01.
...
02.
<
filter
>
03.
<
filter-name
>loadSalt</
filter-name
>
04.
<
filter-class
>com.ricardozuasti.csrf.LoadSalt</
filter-class
>
05.
</
filter
>
06.
...
07.
<
filter-mapping
>
08.
<
filter-name
>loadSalt</
filter-name
>
09.
<
url-pattern
>*</
url-pattern
>
10.
</
filter-mapping
>
11.
...
As I said, to validate the salt before executing secure transactions we can write another filter:
view
sourceprint?
01.
package
com.ricardozuasti.csrf;
02.
03.
import
com.google.common.cache.Cache;
04.
import
java.io.IOException;
05.
import
javax.servlet.*;
06.
import
javax.servlet.http.HttpServletRequest;
07.
08.
public
class
ValidateSalt
implements
Filter {
09.
10.
@Override
11.
public
void
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
12.
throws
IOException, ServletException {
13.
14.
// Assume its HTTP
15.
HttpServletRequest httpReq = (HttpServletRequest) request;
16.
17.
// Get the salt sent with the request
18.
String salt = (String) httpReq.getParameter(
"csrfPreventionSalt"
);
19.
20.
// Validate that the salt is in the cache
21.
Cache<String, Boolean> csrfPreventionSaltCache = (Cache<String, Boolean>)
22.
httpReq.getSession().getAttribute(
"csrfPreventionSaltCache"
);
23.
24.
if
(csrfPreventionSaltCache !=
null
&&
25.
salt !=
null
&&
26.
csrfPreventionSaltCache.getIfPresent(salt) !=
null
){
27.
28.
// If the salt is in the cache, we move on
29.
chain.doFilter(request, response);
30.
}
else
{
31.
// Otherwise we throw an exception aborting the request flow
32.
throw
new
ServletException(
"Potential CSRF detected!! Inform a scary sysadmin ASAP."
);
33.
}
34.
}
35.
36.
@Override
37.
public
void
init(FilterConfig filterConfig)
throws
ServletException {
38.
}
39.
40.
@Override
41.
public
void
destroy() {
42.
}
43.
}
You should configure this filter for every request that needs to be secure (i.e. retrieves or modifies sensitive information, move money, etc.), for example:
view
sourceprint?
01.
...
02.
<
filter
>
03.
<
filter-name
>validateSalt</
filter-name
>
04.
<
filter-class
>com.ricardozuasti.csrf.ValidateSalt</
filter-class
>
05.
</
filter
>
06.
...
07.
<
filter-mapping
>
08.
<
filter-name
>validateSalt</
filter-name
>
09.
<
url-pattern
>/transferMoneyServlet</
url-pattern
>
10.
</
filter-mapping
>
11.
...
After configuring both servlets all your secured requests should fail :). To fix it you have to add, to each link and form post that ends in a secure URL, the csrfPreventionSalt parameter
containing the value of the request parameter with the same name. For example, in an HTML form within a JSP page:
view
sourceprint?
1.
...
2.
<
form
action
=
"/transferMoneyServlet"
method
=
"get"
>
3.
<
input
type
=
"hidden"
name
=
"csrfPreventionSalt"
value="<c:out
value
=
'${csrfPreventionSalt}'
/>"/>
4.
...
5.
</
form
>
6.
...
Of course you can write a custom tag, a nice Javascript code or whatever you prefer to inject the new parameter in every needed link/form.
相关文章推荐
- 如何写安全的Java Web应用之输入校验(二):不要依赖客户端的校验
- WEB应用中普通Java程序如何读取资源文件
- 攻击JavaWeb应用[6]-程序架构与代码审计
- Web应用漏洞攻击分析与防范
- 关于如何在java的web应用获取服务器资源。
- Java应用中的SQL依赖注入攻击和防范
- WEB应用中的普通Java程序如何读取资源文件
- 攻击JavaWeb应用[4]-SQL注入[2]
- 攻击JavaWeb应用[7]-Server篇[1]
- web安全之跨站请求伪造攻击(CSRF)与防范方法
- 如何将Web应用打包成.war文件? 转自:http://blog.csdn.net/code_JAVA/archive/2008/05/19/2457749.aspx
- 攻击JavaWeb应用[8]-后门篇
- 攻击JavaWeb应用[1]
- 攻击JavaWeb应用[3]-SQL注入[1]
- Java Web应用中如何实现任务有效调度-Java基础-Java-编程开发
- 使用 PHP 构建的 Web 应用如何避免 XSS 攻击
- 使用 PHP 构建的 Web 应用如何避免 XSS 攻击
- 使用PHP 构建的Web 应用如何避免XSS 攻击
- 使用 PHP 构建的 Web 应用如何避免 XSS 攻击
- 攻击JavaWeb应用[2]-CS交互安全