Java Code Examples for org.eclipse.jetty.servlets.DoSFilter

Following code examples demonstrate how to use org.eclipse.jetty.servlets.DoSFilter from jetty. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.eclipse.jetty.servlets.DoSFilter and various code implementation of this class.

    @Test
    public void testWhitelist() throws Exception
    {
        DoSFilter filter = new DoSFilter();
        List<String> whitelist = new ArrayList<String>();
        whitelist.add("192.168.0.1");
        whitelist.add("10.0.0.0/8");
        Assert.assertTrue(filter.checkWhitelist(whitelist, "192.168.0.1"));
        Assert.assertFalse(filter.checkWhitelist(whitelist, "192.168.0.2"));
        Assert.assertFalse(filter.checkWhitelist(whitelist, "11.12.13.14"));
        Assert.assertTrue(filter.checkWhitelist(whitelist, "10.11.12.13"));
        Assert.assertTrue(filter.checkWhitelist(whitelist, "10.0.0.0"));
        Assert.assertFalse(filter.checkWhitelist(whitelist, "0.0.0.0"));
    } 


    }

    private boolean hitRateTracker(DoSFilter doSFilter, int sleep) throws InterruptedException
    {
        boolean exceeded = false;
        RateTracker rateTracker = doSFilter.new RateTracker("test2",0,4);

        for (int i = 0; i < 5; i++)
        {
            Thread.sleep(sleep);
            if (rateTracker.isRateExceeded(System.currentTimeMillis()))
                exceeded = true;
        }
        return exceeded;
    } 

    @Test
    public void isRateExceededTest() throws InterruptedException
    {
        DoSFilter doSFilter = new DoSFilter();

        boolean exceeded = hitRateTracker(doSFilter,0);
        assertTrue("Last hit should have exceeded",exceeded);

        int sleep = 250;
        exceeded = hitRateTracker(doSFilter,sleep);
        assertFalse("Should not exceed as we sleep 300s for each hit and thus do less than 4 hits/s",exceeded);
    } 

    public Server() throws IOException {
        super();
        
        ServerConfiguration config = JmeResourceWebsite.getInstance().getConfiguration().getServerConfig();
        System.setProperty("org.apache.jasper.compiler.disablejsr199", "false");

        DispatcherServlet apiServlet = new DispatcherServlet();
        apiServlet.setContextConfigLocation("classpath:spring-api.xml");
        apiServlet.setThrowExceptionIfNoHandlerFound(true);

        DispatcherServlet htmlServlet = new DispatcherServlet();
        htmlServlet.setContextConfigLocation("classpath:spring-html.xml");
        htmlServlet.setThrowExceptionIfNoHandlerFound(true);

        WebAppContext contextHandler = new WebAppContext();
        this.setClassLoader(contextHandler);
        
        contextHandler.setAttribute("javax.servlet.context.tempdir", this.getScratchDir());
        contextHandler.setAttribute("org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern", ".*/[^/]*servlet-api-[^/]*\\.jar$|.*/javax.servlet.jsp.jstl-.*\\.jar$|.*/.*taglibs.*\\.jar$");
        contextHandler.setAttribute("org.eclipse.jetty.containerInitializers", jspInitializers());
        contextHandler.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
        contextHandler.addBean(new ServletContainerInitializersStarter(contextHandler), true);

        contextHandler.setContextPath(config.getBindPath().isEmpty() ? "/" : config.getBindPath());
        contextHandler.setResourceBase(new ClassPathResource("webapp").getURI().toString());
        contextHandler.addFilter(DoSFilter.class, "*", null);
        contextHandler.addFilter(CrossOriginFilter.class, "*", null);

        String[] mimetypes = {
                "text/html",
                "application/json",
                "text/plain",
                "text/css",
                "application/javascript"
        };

        GzipHandler gzipHandler = new GzipHandler();
        gzipHandler.setIncludedMethods("GET", "POST");
        gzipHandler.setIncludedMimeTypes(mimetypes);

        contextHandler.setGzipHandler(gzipHandler);

        this.setHandler(contextHandler);
        
        HttpConfiguration httpConfig = new HttpConfiguration();
        httpConfig.setSendServerVersion(false);
        httpConfig.setSendXPoweredBy(false);
        
        HttpConnectionFactory http1 = new HttpConnectionFactory(httpConfig);

        ServerConnector httpConnector = new ServerConnector(this, http1);
        httpConnector.setPort(config.getBindPort());
        this.setConnectors(new Connector[] { httpConnector });
    } 

Advertisement
Javadoc
Denial of Service filter

This filter is useful for limiting exposure to abuse from reque

st flooding, whether malicious, or as a result of a misconfigured client.

The filter keeps track of the number of requests from a connection per second. If a limit is exceeded, the request is either rejected, delayed, or throttled.

When a request is throttled, it is placed in a priority queue. Priority is given first to authenticated users and users with an HttpSession, then connections which can be identified by their IP addresses. Connections with no way to identify them are given lowest priority.

The #extractUserId(ServletRequest request) function should be implemented, in order to uniquely identify authenticated users.

The following init parameters control the behavior of the filter: maxRequestsPerSec the maximum number of requests from a connection per second. Requests in excess of this are first delayed, then throttled. delayMs is the delay given to all requests over the rate limit, before they are considered at all. -1 means just reject request, 0 means no delay, otherwise it is the delay. maxWaitMs how long to blocking wait for the throttle semaphore. throttledRequests is the number of requests over the rate limit able to be considered at once. throttleMs how long to async wait for semaphore. maxRequestMs how long to allow this request to run. maxIdleTrackerMs how long to keep track of request rates for a connection, before deciding that the user has gone away, and discarding it insertHeaders if true , insert the DoSFilter headers into the response. Defaults to true. trackSessions if true, usage rate is tracked by session if a session exists. Defaults to true. remotePort if true and session tracking is not used, then rate is tracked by IP+port (effectively connection). Defaults to false. ipWhitelist a comma-separated list of IP addresses that will not be rate limited managedAttr if set to true, then this servlet is set as a ServletContext attribute with the filter name as the attribute name. This allows context external mechanism (eg JMX via ContextHandler#MANAGED_ATTRIBUTES) to manage the configuration of the filter. tooManyCode The status code to send if there are too many requests. By default is 429 (too many requests), but 503 (Unavailable) is another option

This filter should be configured for DispatcherType#REQUEST and DispatcherType#ASYNC and with <async-supported>true</async-supported>.

Read More
Advertisement