Blog | G5 Cyber Security

Java Servlet Filter: Blocking Unapproved Scripts

TL;DR

Yes, a Java servlet filter can effectively block scripts that aren’t on an approved whitelist. This guide shows you how to create and configure such a filter.

Steps

  1. Create the Whitelist: First, define a list of allowed script sources (URLs or paths). This is your ‘whitelist’. You can store this in a file, database, or directly within your code. For simplicity, we’ll use an array in our example.
    String[] whitelist = {"https://trusted-cdn.example.com/", "/static/js/"};
  2. Create the Filter Class: Create a Java class that extends javax.servlet.Filter and implements the necessary methods.
    public class ScriptBlockerFilter implements Filter {
  3. Implement `doFilter` Method: This is where the core logic resides. Inside this method, you’ll examine the request headers (specifically looking for script tags in HTML responses) and block requests containing unapproved scripts.
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Get the original request URI.
        String requestURI = ((HttpServletRequest) request).getRequestURI();
    
        // Check if the request is for a script resource (e.g., .js file).
        if (requestURI.endsWith(".js")) {
            boolean allowed = false;
            for (String whitelistedPath : whitelist) {
                if (requestURI.startsWith(whitelistedPath)) {
                    allowed = true;
                    break;
                }
            }
    
            if (!allowed) {
                // Block the request.
                response.getWriter().println("Script access denied!");
                return;
            }
        }
    
        chain.doFilter(request, response);
    }
  4. Implement `init` Method: This method is called when the filter is initialized. You can use it to load your whitelist from a configuration file or database.
    @Override
    public void init(FilterConfig config) throws ServletException {
        // Load whitelist here if needed.
    }
  5. Configure the Filter in `web.xml` (or equivalent): Add a filter declaration to your web application’s deployment descriptor (`web.xml`). This tells the servlet container which URLs the filter should intercept.
    <filter>
        <filter-name>ScriptBlockerFilter</filter-name>
        <filter-class>com.example.ScriptBlockerFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>ScriptBlockerFilter</filter-name>
        <url-pattern>*.js</url-pattern>
    </filter-mapping>
  6. Test the Filter: Deploy your web application and test that requests for unapproved scripts are blocked, while requests for approved scripts are allowed. Try accessing a script from a trusted CDN and one from an untrusted source.

    Important Considerations

    • HTML Responses: This example focuses on blocking direct .js file requests. To block inline scripts within HTML pages, you’ll need to parse the HTML response body *before* it’s sent to the client and remove or modify unapproved script tags. This is more complex and requires an HTML parser library (e.g., Jsoup).
    • Performance: Parsing HTML responses can be resource-intensive. Consider caching parsed results if possible.
    • False Positives/Negatives: Ensure your whitelist is comprehensive to avoid blocking legitimate scripts or allowing malicious ones.
    • cyber security Best Practices: This filter is one layer of cyber security. Implement other measures like Content Security Policy (CSP) for robust protection.
Exit mobile version