From 1004753a485e256bc17daec788c3c219ddbb1e6e Mon Sep 17 00:00:00 2001 From: CaptainB Date: Fri, 13 Oct 2023 14:17:59 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=A0=A1=E9=AA=8Corigin,=20=E6=9C=89?= =?UTF-8?q?=E4=BA=9Bsocket=E8=AF=B7=E6=B1=82=E4=B8=8D=E5=AE=89=E5=85=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../io/metersphere/security/CsrfFilter.java | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/backend/src/main/java/io/metersphere/security/CsrfFilter.java b/backend/src/main/java/io/metersphere/security/CsrfFilter.java index 9ced1b365d..8abb2bda22 100644 --- a/backend/src/main/java/io/metersphere/security/CsrfFilter.java +++ b/backend/src/main/java/io/metersphere/security/CsrfFilter.java @@ -37,6 +37,12 @@ public class CsrfFilter extends AnonymousFilter { if (ApiKeyHandler.isApiKeyCall(WebUtils.toHttp(request))) { return true; } + // 校验 referer + validateReferer(httpServletRequest); + + // 校验 origin + validateOrigin(httpServletRequest); + // websocket 不需要csrf String websocketKey = httpServletRequest.getHeader("Sec-WebSocket-Key"); if (StringUtils.isNotBlank(websocketKey)) { @@ -47,11 +53,27 @@ public class CsrfFilter extends AnonymousFilter { String csrfToken = httpServletRequest.getHeader(TOKEN_NAME); // 校验 token validateToken(csrfToken); - // 校验 referer - validateReferer(httpServletRequest); + return true; } + private void validateOrigin(HttpServletRequest httpServletRequest) { + Environment env = CommonBeanFactory.getBean(Environment.class); + String domains = env.getProperty("origin.urls"); + if (StringUtils.isBlank(domains)) { + // 没有配置不校验 + return; + } + + String[] split = StringUtils.split(domains, ","); + String origin = httpServletRequest.getHeader(HttpHeaders.ORIGIN); + if (split != null) { + if (!ArrayUtils.contains(split, origin)) { + throw new RuntimeException("csrf origin error"); + } + } + } + private void validateReferer(HttpServletRequest request) { Environment env = CommonBeanFactory.getBean(Environment.class); String domains = env.getProperty("referer.urls"); @@ -64,7 +86,7 @@ public class CsrfFilter extends AnonymousFilter { String referer = request.getHeader(HttpHeaders.REFERER); if (split != null) { if (!ArrayUtils.contains(split, referer)) { - throw new RuntimeException("csrf error"); + throw new RuntimeException("csrf referer error"); } } }