1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.cms.security;
35
36 import info.magnolia.audit.AuditLoggingUtil;
37 import info.magnolia.context.Context;
38 import info.magnolia.context.MgnlContext;
39
40 import java.io.IOException;
41 import java.net.URI;
42 import java.net.URISyntaxException;
43
44 import javax.servlet.http.HttpServletRequest;
45 import javax.servlet.http.HttpServletResponse;
46
47 import org.apache.commons.lang.StringUtils;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 public class CsrfSecurityFilter extends BaseSecurityFilter {
68
69 private static final Logger log = LoggerFactory.getLogger(CsrfSecurityFilter.class);
70
71 protected final String ADMINCENTRAL_LOGIN_PATH = ".magnolia/pages/adminCentral.html";
72
73 @Override
74 public boolean isAllowed(HttpServletRequest request, HttpServletResponse response) throws IOException {
75
76 final String refererURL = request.getHeader("referer");
77 final String actualURL = request.getRequestURL().toString();
78
79 try {
80
81 final String actualPath = new URI(actualURL).getPath();
82 if (!isLoginPage(actualPath)){
83
84 if (StringUtils.isEmpty(refererURL)){
85 handlePossibleCsrf(request, response, refererURL, actualURL);
86 return false;
87 }
88
89 final String referrerHost = new URI(refererURL).getHost();
90 final String actualHost = new URI(actualURL).getHost();
91 if (!referrerHost.equalsIgnoreCase(actualHost)) {
92 handlePossibleCsrf(request, response, refererURL, actualURL);
93 return false;
94 }
95 }
96 } catch (URISyntaxException ex) {
97 handlePossibleCsrf(request, response, refererURL, actualURL);
98 return false;
99 }
100
101 return true;
102 }
103
104
105
106
107
108 protected void handlePossibleCsrf(HttpServletRequest request, HttpServletResponse response, String referer, String url){
109 log.warn("Possible Csrf Attack. request.referer='{}' User {} attempts to access url '{}'.", new Object[] { referer, MgnlContext.getUser().getName(), url });
110 final String auditDetails = "request.referer='" + referer + "' attempting to access url '" + url + "'.";
111 AuditLoggingUtil.logSecurity(request.getRemoteAddr(), "Possible CSRF Attack", auditDetails);
112 MgnlContext.setAttribute(Context.ATTRIBUTE_POSSIBLE_CSRF, true);
113 response.setStatus(HttpServletResponse.SC_FORBIDDEN);
114 }
115
116
117
118
119 protected boolean isLoginPage(String actualPath){
120 final String adminCentralLoginPath = MgnlContext.getContextPath() + "/" + ADMINCENTRAL_LOGIN_PATH;
121 return adminCentralLoginPath.equals(actualPath);
122 }
123
124
125 }