Skip to content

Commit f24df6f

Browse files
committed
add json to jsonp
1 parent d330c45 commit f24df6f

File tree

7 files changed

+151
-75
lines changed

7 files changed

+151
-75
lines changed
Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
package org.joychou.controller.jsonp;
22

3+
import org.springframework.beans.factory.annotation.Value;
34
import org.springframework.web.bind.annotation.ControllerAdvice;
45
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
56

7+
68
@ControllerAdvice
79
public class JSONPAdvice extends AbstractJsonpResponseBodyAdvice {
810

9-
public JSONPAdvice() {
10-
super("callback", "cback"); // Can set multiple paramNames
11+
// method of using @Value in constructor
12+
public JSONPAdvice(@Value("${joychou.security.jsonp.callback}") String[] callback) {
13+
super(callback); // Can set multiple paramNames
1114
}
1215
}

src/main/java/org/joychou/security/CsrfAccessDeniedHandler.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package org.joychou.security;
22

33

4+
import org.slf4j.Logger;
5+
import org.slf4j.LoggerFactory;
46
import org.springframework.http.MediaType;
57
import org.springframework.security.access.AccessDeniedException;
68
import org.springframework.security.web.access.AccessDeniedHandler;
@@ -17,9 +19,13 @@
1719
*/
1820
public class CsrfAccessDeniedHandler implements AccessDeniedHandler {
1921

22+
private final Logger logger= LoggerFactory.getLogger(CsrfAccessDeniedHandler.class);
23+
2024
@Override
2125
public void handle(HttpServletRequest request, HttpServletResponse response,
2226
AccessDeniedException accessDeniedException) throws IOException, ServletException {
27+
28+
logger.info("[-] URL: " + request.getRequestURL() + "?" + request.getQueryString() + "\t" + "Referer: " + request.getHeader("referer"));
2329
response.setContentType(MediaType.TEXT_HTML_VALUE); // content-type: text/html
2430
response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 403 forbidden
2531
response.getWriter().write("CSRF check failed by JoyChou."); // response contents
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package org.joychou.security;
2+
3+
4+
import javax.servlet.*;
5+
import javax.servlet.annotation.WebFilter;
6+
import javax.servlet.http.HttpServletRequest;
7+
import javax.servlet.http.HttpServletResponse;
8+
import java.io.IOException;
9+
10+
import org.apache.commons.lang.StringUtils;
11+
import org.slf4j.Logger;
12+
import org.slf4j.LoggerFactory;
13+
import org.springframework.beans.factory.annotation.Value;
14+
import org.springframework.util.AntPathMatcher;
15+
import org.springframework.util.PathMatcher;
16+
17+
18+
/**
19+
* Check referer for all GET requests with callback parameters.
20+
* If the check of referer fails, a 403 forbidden error page will be returned.
21+
*
22+
* Still need to add @ServletComponentScan annotation in Application.java.
23+
*
24+
*/
25+
@WebFilter(filterName = "referFilter", urlPatterns = "/*")
26+
public class HttpFilter implements Filter {
27+
28+
@Value("${joychou.security.referer.enabled}")
29+
private Boolean referSecEnabled = false;
30+
31+
@Value("${joychou.security.jsonp.callback}")
32+
private String[] callbacks;
33+
34+
@Value("${joychou.security.referer.hostwhitelist}")
35+
private String[] referWhitelist;
36+
37+
@Value("${joychou.security.referer.uri}")
38+
private String[] referUris;
39+
40+
@Override
41+
public void init(FilterConfig filterConfig) throws ServletException {
42+
43+
}
44+
45+
private final Logger logger= LoggerFactory.getLogger(HttpFilter.class);
46+
47+
@Override
48+
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
49+
throws IOException, ServletException {
50+
51+
HttpServletRequest request = (HttpServletRequest) req;
52+
HttpServletResponse response = (HttpServletResponse) res;
53+
54+
String refer = request.getHeader("referer");
55+
PathMatcher matcher = new AntPathMatcher();
56+
boolean isMatch = false;
57+
for (String uri: referUris) {
58+
if ( matcher.match (uri, request.getRequestURI()) ) {
59+
isMatch = true;
60+
break;
61+
}
62+
}
63+
64+
if (isMatch) {
65+
if (referSecEnabled) {
66+
// Check referer for all GET requests with callback parameters.
67+
for (String callback: callbacks) {
68+
if (request.getMethod().equals("GET") && StringUtils.isNotBlank(request.getParameter(callback)) ){
69+
// If the check of referer fails, a 403 forbidden error page will be returned.
70+
if (!SecurityUtil.checkURLbyEndsWith(refer, referWhitelist)){
71+
logger.info("[-] URL: " + request.getRequestURL() + "?" + request.getQueryString() + "\t" + "Referer: " + refer);
72+
response.sendRedirect("https://test.joychou.org/error3.html");
73+
return;
74+
}
75+
}
76+
}
77+
}
78+
}
79+
80+
81+
82+
filterChain.doFilter(req, res);
83+
}
84+
85+
@Override
86+
public void destroy() {
87+
88+
}
89+
}

src/main/java/org/joychou/security/SecurityUtil.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,23 @@ public static Boolean checkSSRF(String url) {
5555
/**
5656
* Suitable for: TTL isn't set to 0 & Redirect is forbidden.
5757
*
58-
* @param url the url needs to check
58+
* @param url The url that needs to check.
5959
* @return Safe url returns true. Dangerous url returns false.
6060
*/
6161
public static boolean checkSSRFWithoutRedirect(String url) {
6262
return !SSRFChecker.isInnerIPByUrl(url);
6363
}
6464

65+
/**
66+
* Check SSRF by host white list.
67+
* This is the simplest and most effective method to fix ssrf vul.
68+
*
69+
* @param url The url that needs to check.
70+
* @param hostWlist host whitelist
71+
* @return Safe url returns true. Dangerous url returns false.
72+
*/
73+
public static boolean checkSSRFByHostWlist(String url, String[] hostWlist) {
74+
return checkURLbyEndsWith(url, hostWlist);
75+
}
76+
6577
}

src/main/java/org/joychou/security/WebSecurityConfig.java

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,22 +20,27 @@
2020
@Configuration
2121
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
2222

23-
@Value("${org.joychou.security.csrf}")
24-
private Boolean csrfSwitch; // get csrf switch in application.properties
23+
@Value("${joychou.security.csrf.enabled}")
24+
private Boolean csrfEnabled = false;
2525

26-
RequestMatcher csrfRequestMatcher = new RequestMatcher() {
26+
@Value("${joychou.security.csrf.exclude.url}")
27+
private String[] csrfExcludeUrl;
28+
29+
@Value("${joychou.security.csrf.method}")
30+
private String[] csrfMethod = {"POST"};
2731

28-
// 配置不需要CSRF校验的请求方式
29-
private final HashSet<String> allowedMethods = new HashSet<String>(
30-
Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"));
32+
RequestMatcher csrfRequestMatcher = new RequestMatcher() {
3133

3234
@Override
3335
public boolean matches(HttpServletRequest request) {
36+
37+
// 配置需要CSRF校验的请求方式,
38+
HashSet<String> allowedMethods = new HashSet<String>(Arrays.asList(csrfMethod));
3439
// return false表示不校验csrf
35-
if (!csrfSwitch) {
40+
if (!csrfEnabled) {
3641
return false;
3742
}
38-
return !this.allowedMethods.contains(request.getMethod());
43+
return allowedMethods.contains(request.getMethod());
3944
}
4045

4146
};
@@ -47,7 +52,7 @@ protected void configure(HttpSecurity http) throws Exception {
4752
// 但存在后端多台服务器情况,session不能同步的问题,所以一般使用cookie模式。
4853
http.csrf()
4954
.requireCsrfProtectionMatcher(csrfRequestMatcher)
50-
.ignoringAntMatchers("/xxe/**", "/fastjon/**") // 不进行csrf校验的uri,多个uri使用逗号分隔
55+
.ignoringAntMatchers(csrfExcludeUrl) // 不进行csrf校验的uri,多个uri使用逗号分隔
5156
.csrfTokenRepository(new CookieCsrfTokenRepository());
5257
// 自定义csrf校验失败的代码,默认是返回403错误页面
5358
http.exceptionHandling().accessDeniedHandler(new CsrfAccessDeniedHandler());

src/main/java/org/joychou/security/jsonpFilter.java

Lines changed: 0 additions & 60 deletions
This file was deleted.

src/main/resources/application.properties

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,27 @@
33
management.security.enabled=false
44
# logging.config=classpath:logback-online.xml
55

6-
# jsonp check referer switch
7-
org.joychou.security.jsonp = false
8-
org.joychou.security.csrf = false
6+
7+
8+
### check referer configuration begins ###
9+
joychou.security.referer.enabled = true
10+
joychou.security.referer.hostwhitelist = joychou.org, joychou.com
11+
# Only support ant url style.
12+
joychou.security.referer.uri = /jsonp/**
13+
### check referer configuration ends ###
14+
15+
16+
### csrf configuration begins ###
17+
# csrf token check
18+
joychou.security.csrf.enabled = true
19+
# URI without CSRF check (only support ANT url format)
20+
joychou.security.csrf.exclude.url = /xxe/**, /fastjon/**
21+
# method for CSRF check
22+
joychou.security.csrf.method = POST
23+
### csrf configuration ends ###
24+
25+
26+
### jsonp configuration begins ### # auto convert json to jsonp
27+
# callback parameters name
28+
joychou.security.jsonp.callback = callback, _callback
29+
### jsonp configuration ends ###

0 commit comments

Comments
 (0)