简体   繁体   English

如何使用 ZD52387880E1EA293817A 防止 Rest API JSON 中的 XSS 攻击或不可信数据

[英]How to prevent XSS attacks or untrusted data in Rest API JSON using Java?

I had developed a Rest API application and have handled Authentication and Authorization using custom JWT.我开发了一个 Rest API 应用程序,并使用自定义 JWT 处理了身份验证和授权。 I want to further make the application secure from XSS attacks or validation for untrusted data which could be handled for each and every field of JSON request.我想进一步使应用程序免受 XSS 攻击或验证不受信任的数据,这些数据可以针对 JSON 请求的每个字段进行处理。

Can I get some help in this regard so that efficient data processing will happen at the entry-level of the request without touching internal business validation?我能否在这方面获得一些帮助,以便在请求的入门级进行有效的数据处理,而无需触及内部业务验证?

For this you need XSS filter using HTMLUtils which will filter any injected script and prevent your site.为此,您需要使用 HTMLUtils 进行 XSS 过滤器,该过滤器将过滤任何注入的脚本并阻止您的站点。 Please refer my answer https://stackoverflow.com/a/55741351/10232467 for its complete code and implementation.请参考我的回答https://stackoverflow.com/a/55741351/10232467了解其完整代码和实现。

@Pralay Mallick: Is it for the JSON body or the parameter values? @Pralay Mallick:是针对 JSON 主体还是参数值? I faced a similar kind of issue at my project.我在我的项目中遇到了类似的问题。

Need to override the HttpServletRequest in a Servlet Filter(if you are using Servlet).需要覆盖 Servlet 过滤器中的 HttpServletRequest(如果您使用的是 Servlet)。

  1. Extends HttpServletRequestWrapper that stores JSON body(intention is to sanitize JSON body).扩展存储 JSON 主体的 HttpServletRequestWrapper(目的是清理 JSON 主体)。

  2. Strip/ escape the eligible JSON value剥离/转义符合条件的 JSON 值

Extented "HttpServletRequestWrapper" :扩展的“HttpServletRequestWrapper”

public class SanitizationRequestWrapper extends HttpServletRequestWrapper {
    
        public byte[] getBody() {
            return body;
        }
    
        public void setBody(byte[] body) {
            this.body = body;
        }
    
        private byte[] body;
    
        public SanitizationRequestWrapper(HttpServletRequest request) throws IOException {
            super(request);
            try {
                body = IOUtils.toByteArray(super.getInputStream());
            }catch (NullPointerException e){
    
            }
        }
    
        @Override
        public ServletInputStream getInputStream() throws IOException {
            return new ServletInputStreamImpl(new ByteArrayInputStream(body));
        }
    
        @Override
        public BufferedReader getReader() throws IOException {
            String enc = getCharacterEncoding();
            if (enc == null) enc = "UTF-8";
            return new BufferedReader(new InputStreamReader(getInputStream(), enc));
        }
    
        private class ServletInputStreamImpl extends ServletInputStream {
    
            private InputStream is;
    
            public ServletInputStreamImpl(InputStream is) {
                this.is = is;
            }
    
            public int read() throws IOException {
                return is.read();
            }
    
            public boolean markSupported() {
                return false;
            }
    
            public synchronized void mark(int i) {
                throw new RuntimeException(new IOException("mark/reset not supported"));
            }
    
            public synchronized void reset() throws IOException {
                throw new IOException("mark/reset not supported");
            }
        }
    }
    

Servlet filter which sanitize request body:净化请求正文的 Servlet 过滤器:

    public class XSSSanitizeFilters implements Filter {
            @Override
        public void destroy() {
        }
    
        @Override
        public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) arg0;
            HttpServletResponse response = (HttpServletResponse) arg1;
            SanitizationRequestWrapper sanitizeRequest = new SanitizationRequestWrapper(request);
                if (null != sanitizeRequest.getBody()) {
                    try {
                        sanitizeJson(sanitizeRequest);
                    } catch (ParseException e) {
                        LOG.error("Unable to Sanitize the provided JSON .");
                    }
                    arg2.doFilter(sanitizeRequest, arg1);
    
                } else {
                    arg2.doFilter(arg0, arg1);
                }       
        }
    
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        private void sanitizeJson(SanitizationRequestWrapper sanitizeRequest ) throws IOException, ParseException {
                JSONParser parser= new JSONParser();
                Object obj = parser.parse(sanitizeRequest.getReader());
                 ObjectMapper oMapper = new ObjectMapper();
                Map <String, Object> map = oMapper.convertValue(obj, Map.class);
                sanitizeRequest.setBody((new JSONObject(map)).toString().getBytes());
        }
    
       

If your API doesn't accecpt any HTML Characters then you can follow the below logic.如果您的 API 不接受任何 HTML 字符,那么您可以遵循以下逻辑。

You can Sanitize the Input Payload with EncodeHtml and Compare it with Provided Payload.您可以使用 EncodeHtml 清理输入有效负载并将其与提供的有效负载进行比较。

If both Sanitized Payload and Provided payload doesn't match then there exists some Html Content and straight way throw an Excpetion.如果 Sanitized Payload 和 Provided Payload 不匹配,则存在一些 Html 内容并直接抛出异常。

String unsanitizedPayload = IOUtils.toString(multiReadRequest.getReader());
String sanitizedPayload = Encode.forHtmlContent(unsanitizedPayload);

if(!unsanitizedPayload.equals(sanitizedPayload)) {
    throw new Exception("Improper Payload");
}

If you're using Spring, Spring security guarantees basic level of protection against XSS attack.如果您使用的是 Spring,Spring 安全性可保证基本级别的 XSS 攻击防护。 You can also use你也可以使用

@SafeHtml
private String value;

You will also need to add org.jsoup dependency.您还需要添加 org.jsoup 依赖项。

You don't filter or escape data in a restful API.您不会在宁静的 API 中过滤或转义数据。 API's should be client agnostic. API 应该与客户端无关。 It is the clients responsibility to provide XSS protection.提供 XSS 保护是客户的责任。 If the clients are doing their job appropriately you will end up with doubly escaped data.如果客户正确地完成了他们的工作,您最终会得到双重转义的数据。 Remember potential clients can be:请记住,潜在客户可以是:

  • Mobile Apps移动应用
  • Backend Web Servers后端 Web 服务器
  • Web Browsers Web 浏览器
  • Desktop Applications桌面应用程序
  • Embedded systems/ IoT嵌入式系统/物联网

In the above only a limited number of clients and configurations are vulnerable to XSS.在上述情况下,只有有限数量的客户端和配置容易受到 XSS 攻击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM