Search in sources :

Example 6 with ServletRequest

use of javax.servlet.ServletRequest in project jetty.project by eclipse.

the class DoSFilter method doFilter.

protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    if (!isEnabled()) {
        filterChain.doFilter(request, response);
        return;
    }
    // Look for the rate tracker for this request.
    RateTracker tracker = (RateTracker) request.getAttribute(__TRACKER);
    if (tracker == null) {
        // This is the first time we have seen this request.
        if (LOG.isDebugEnabled())
            LOG.debug("Filtering {}", request);
        // Get a rate tracker associated with this request, and record one hit.
        tracker = getRateTracker(request);
        // Calculate the rate and check it is over the allowed limit
        final boolean overRateLimit = tracker.isRateExceeded(System.currentTimeMillis());
        // Pass it through if  we are not currently over the rate limit.
        if (!overRateLimit) {
            if (LOG.isDebugEnabled())
                LOG.debug("Allowing {}", request);
            doFilterChain(filterChain, request, response);
            return;
        }
        // We are over the limit.
        // So either reject it, delay it or throttle it.
        long delayMs = getDelayMs();
        boolean insertHeaders = isInsertHeaders();
        switch((int) delayMs) {
            case -1:
                {
                    // Reject this request.
                    LOG.warn("DOS ALERT: Request rejected ip={}, session={}, user={}", request.getRemoteAddr(), request.getRequestedSessionId(), request.getUserPrincipal());
                    if (insertHeaders)
                        response.addHeader("DoSFilter", "unavailable");
                    response.sendError(getTooManyCode());
                    return;
                }
            case 0:
                {
                    // Fall through to throttle the request.
                    LOG.warn("DOS ALERT: Request throttled ip={}, session={}, user={}", request.getRemoteAddr(), request.getRequestedSessionId(), request.getUserPrincipal());
                    request.setAttribute(__TRACKER, tracker);
                    break;
                }
            default:
                {
                    // Insert a delay before throttling the request,
                    // using the suspend+timeout mechanism of AsyncContext.
                    LOG.warn("DOS ALERT: Request delayed={}ms, ip={}, session={}, user={}", delayMs, request.getRemoteAddr(), request.getRequestedSessionId(), request.getUserPrincipal());
                    if (insertHeaders)
                        response.addHeader("DoSFilter", "delayed");
                    request.setAttribute(__TRACKER, tracker);
                    AsyncContext asyncContext = request.startAsync();
                    if (delayMs > 0)
                        asyncContext.setTimeout(delayMs);
                    asyncContext.addListener(new DoSTimeoutAsyncListener());
                    return;
                }
        }
    }
    if (LOG.isDebugEnabled())
        LOG.debug("Throttling {}", request);
    // Throttle the request.
    boolean accepted = false;
    try {
        // Check if we can afford to accept another request at this time.
        accepted = _passes.tryAcquire(getMaxWaitMs(), TimeUnit.MILLISECONDS);
        if (!accepted) {
            // We were not accepted, so either we suspend to wait,
            // or if we were woken up we insist or we fail.
            Boolean throttled = (Boolean) request.getAttribute(__THROTTLED);
            long throttleMs = getThrottleMs();
            if (throttled != Boolean.TRUE && throttleMs > 0) {
                int priority = getPriority(request, tracker);
                request.setAttribute(__THROTTLED, Boolean.TRUE);
                if (isInsertHeaders())
                    response.addHeader("DoSFilter", "throttled");
                AsyncContext asyncContext = request.startAsync();
                request.setAttribute(_suspended, Boolean.TRUE);
                if (throttleMs > 0)
                    asyncContext.setTimeout(throttleMs);
                asyncContext.addListener(_listeners[priority]);
                _queues[priority].add(asyncContext);
                if (LOG.isDebugEnabled())
                    LOG.debug("Throttled {}, {}ms", request, throttleMs);
                return;
            }
            Boolean resumed = (Boolean) request.getAttribute(_resumed);
            if (resumed == Boolean.TRUE) {
                // We were resumed, we wait for the next pass.
                _passes.acquire();
                accepted = true;
            }
        }
        // If we were accepted (either immediately or after throttle)...
        if (accepted) {
            // ...call the chain.
            if (LOG.isDebugEnabled())
                LOG.debug("Allowing {}", request);
            doFilterChain(filterChain, request, response);
        } else {
            // ...otherwise fail the request.
            if (LOG.isDebugEnabled())
                LOG.debug("Rejecting {}", request);
            if (isInsertHeaders())
                response.addHeader("DoSFilter", "unavailable");
            response.sendError(getTooManyCode());
        }
    } catch (InterruptedException e) {
        LOG.ignore(e);
        response.sendError(getTooManyCode());
    } finally {
        if (accepted) {
            try {
                // Wake up the next highest priority request.
                for (int p = _queues.length - 1; p >= 0; --p) {
                    AsyncContext asyncContext = _queues[p].poll();
                    if (asyncContext != null) {
                        ServletRequest candidate = asyncContext.getRequest();
                        Boolean suspended = (Boolean) candidate.getAttribute(_suspended);
                        if (suspended == Boolean.TRUE) {
                            if (LOG.isDebugEnabled())
                                LOG.debug("Resuming {}", request);
                            candidate.setAttribute(_resumed, Boolean.TRUE);
                            asyncContext.dispatch();
                            break;
                        }
                    }
                }
            } finally {
                _passes.release();
            }
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) AsyncContext(javax.servlet.AsyncContext)

Example 7 with ServletRequest

use of javax.servlet.ServletRequest in project nhin-d by DirectProject.

the class DirectSOAPHandler method handleMessage.

/**
     * This method handles the incoming and outgoing SOAP-Message. It's an
     * excellent point to manipulate the SOAP.
     * 
     * @param SOAPMessageContext
     *            The SOAPMessageContext object.
     * @return true for successful handling, false otherwise.
     */
@Override
public boolean handleMessage(SOAPMessageContext context) {
    LOGGER.info("Entering DirectSOAPHandler.handleMessage(SOAPMessageContext)");
    // Inquire incoming or outgoing message.
    boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    try {
        if (outbound) {
            LOGGER.info("Handling an outbound message");
            boolean isACK = !context.containsKey(ENDPOINT_ADDRESS);
            SafeThreadData threadData = SafeThreadData.GetThreadInstance(Thread.currentThread().getId());
            SOAPMessage msg = ((SOAPMessageContext) context).getMessage();
            dumpSOAPMessage(msg);
            SOAPPart sp = msg.getSOAPPart();
            // edit Envelope
            SOAPEnvelope env = sp.getEnvelope();
            SOAPHeader sh = env.addHeader();
            @SuppressWarnings("unused") SOAPBody sb = env.getBody();
            try {
                if (threadData.getAction() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "Action");
                    SOAPHeaderElement saction = sh.addHeaderElement(qname);
                    boolean must = true;
                    saction.setMustUnderstand(must);
                    saction.setValue(threadData.getAction());
                }
                if (threadData.getRelatesTo() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "RelatesTo");
                    SOAPHeaderElement relates = sh.addHeaderElement(qname);
                    relates.setValue(threadData.getRelatesTo());
                }
                if (threadData.getFrom() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "From");
                    QName child = new QName("http://www.w3.org/2005/08/addressing", "Address");
                    SOAPHeaderElement efrom = sh.addHeaderElement(qname);
                    SOAPElement address = efrom.addChildElement(child);
                    address.setValue(threadData.getFrom());
                }
                if (threadData.getMessageId() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "MessageID");
                    SOAPHeaderElement message = sh.addHeaderElement(qname);
                    message.setValue(threadData.getMessageId());
                }
                if (threadData.getTo() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "To");
                    SOAPHeaderElement sto = sh.addHeaderElement(qname);
                    sto.setValue(threadData.getTo());
                }
                SOAPHeaderElement directHeader = sh.addHeaderElement(new QName("urn:direct:addressing", "addressBlock"));
                directHeader.setPrefix("direct");
                directHeader.setRole("urn:direct:addressing:destination");
                directHeader.setRelay(true);
                if (StringUtils.isNotBlank(threadData.getDirectFrom())) {
                    SOAPElement directFromElement = directHeader.addChildElement(new QName("from"));
                    directFromElement.setPrefix("direct");
                    URI uri = new URI(threadData.getDirectFrom());
                    directFromElement.setValue((new URI("mailto", uri.getSchemeSpecificPart(), null)).toString());
                }
                if (StringUtils.isNotBlank(threadData.getDirectTo())) {
                    /**
                         * consider multiple recipients
                         */
                    String[] directTos = threadData.getDirectTo().split(";");
                    for (String directToAddr : directTos) {
                        SOAPElement directToElement = directHeader.addChildElement(new QName("to"));
                        directToElement.setPrefix("direct");
                        URI uri = new URI(directToAddr);
                        directToElement.setValue((new URI("mailto", uri.getSchemeSpecificPart(), null)).toString());
                    }
                }
                SOAPElement directMetadataLevelElement = directHeader.addChildElement(new QName("metadata-level"));
                directMetadataLevelElement.setPrefix("direct");
                directMetadataLevelElement.setValue(MetadataLevelEnum.MINIMAL.getLevel());
            } catch (Throwable tb) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Failed to write SOAP Header", tb);
                } else {
                    LOGGER.error("Failed to write SOAP Header: " + tb.getMessage());
                }
            }
            if (isACK) {
                SafeThreadData.clean(Thread.currentThread().getId());
            }
        } else {
            LOGGER.info("Handling an inbound message");
            SOAPMessage msg = ((SOAPMessageContext) context).getMessage();
            boolean isResponse = isResponse(msg);
            if (!isResponse) {
                // Issue 249 - before handling the inbound case, we should clear 
                // out the old thread data if we don't this the To: (SMTP recipients) will 
                // append from the previous thread data 
                SafeThreadData.clean(Thread.currentThread().getId());
            }
            SafeThreadData threadData = SafeThreadData.GetThreadInstance(Thread.currentThread().getId());
            ServletRequest sr = (ServletRequest) context.get(MessageContext.SERVLET_REQUEST);
            if (sr != null) {
                threadData.setRemoteHost(sr.getRemoteHost());
                threadData.setThisHost(sr.getServerName());
                threadData.setPid(getPID());
            }
            SOAPPart sp = msg.getSOAPPart();
            // edit Envelope
            SOAPEnvelope env = sp.getEnvelope();
            SOAPHeader sh = env.getHeader();
            @SuppressWarnings("unchecked") Iterator<Node> it = sh.extractAllHeaderElements();
            while (it.hasNext()) {
                try {
                    Node header = it.next();
                    if (StringUtils.contains(header.toString(), "MessageID")) {
                        threadData.setMessageId(header.getTextContent());
                    } else if (StringUtils.contains(header.toString(), "Action")) {
                        threadData.setAction(header.getTextContent());
                    } else if (StringUtils.contains(header.toString(), "RelatesTo")) {
                        threadData.setRelatesTo(header.getTextContent());
                    } else if (StringUtils.contains(header.toString(), "ReplyTo")) {
                        NodeList reps = header.getChildNodes();
                        for (int i = 0; i < reps.getLength(); i++) {
                            Node address = reps.item(i);
                            if (StringUtils.contains(address.getNodeName(), "Address")) {
                                threadData.setEndpoint(address.getTextContent());
                            }
                        }
                    } else if (StringUtils.contains(header.toString(), "From")) {
                        NodeList reps = header.getChildNodes();
                        for (int i = 0; i < reps.getLength(); i++) {
                            Node address = reps.item(i);
                            if (StringUtils.contains(address.getNodeName(), "Address")) {
                                threadData.setFrom(address.getTextContent());
                            }
                        }
                    } else if (// must be after ReplyTo
                    StringUtils.contains(header.toString(), "To")) {
                        threadData.setTo(header.getTextContent());
                    } else if (StringUtils.contains(header.toString(), "addressBlock")) {
                        NodeList childNodes = header.getChildNodes();
                        for (int i = 0; i < childNodes.getLength(); i++) {
                            Node node = childNodes.item(i);
                            if (StringUtils.contains(node.getNodeName(), "from")) {
                                threadData.setDirectFrom(node.getTextContent());
                            } else if (StringUtils.contains(node.getNodeName(), "to")) {
                                // XDR-MULTIPLE-RECIPIENT-ISSUE - this is the part where old thread data 
                                // gets into the To: and will cause unwanted recipients 
                                // (see above for the clear)
                                String recipient = node.getTextContent();
                                if (threadData.getDirectTo() == null) {
                                    threadData.setDirectTo(recipient);
                                } else {
                                    /**
                                         * if multiple recipients, save addresses in one parameters separate by (;)
                                         */
                                    threadData.setDirectTo(threadData.getDirectTo() + ";" + recipient);
                                }
                            } else if (StringUtils.contains(node.getNodeName(), "metadata-level")) {
                                threadData.setDirectMetadataLevel(node.getTextContent());
                            }
                        }
                    }
                } catch (Throwable tb) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Failed to read input parameter.", tb);
                    } else {
                        LOGGER.error("Failed to read input parameter.");
                    }
                }
            }
            threadData.save();
        }
    } catch (Exception e) {
        LOGGER.warn("Error handling SOAP message.", e);
        return false;
    }
    return true;
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) ServletRequest(javax.servlet.ServletRequest) QName(javax.xml.namespace.QName) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) SOAPMessage(javax.xml.soap.SOAPMessage) URI(java.net.URI) SOAPException(javax.xml.soap.SOAPException) SOAPBody(javax.xml.soap.SOAPBody) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) SOAPPart(javax.xml.soap.SOAPPart) SOAPElement(javax.xml.soap.SOAPElement) SOAPHeader(javax.xml.soap.SOAPHeader)

Example 8 with ServletRequest

use of javax.servlet.ServletRequest in project wildfly by wildfly.

the class JASPICSecurityContext method buildAppContext.

/**
     * <p>
     * Builds the JASPIC application context.
     * </p>
     *
     * @return a {@code String} representing the application context.
     */
private String buildAppContext() {
    final ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    ServletRequest servletRequest = requestContext.getServletRequest();
    return servletRequest.getServletContext().getVirtualServerName() + " " + servletRequest.getServletContext().getContextPath();
}
Also used : ServletRequest(javax.servlet.ServletRequest) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext)

Example 9 with ServletRequest

use of javax.servlet.ServletRequest in project wildfly by wildfly.

the class AuditNotificationReceiver method handleNotification.

@Override
public void handleNotification(SecurityNotification notification) {
    EventType event = notification.getEventType();
    if (event == EventType.AUTHENTICATED || event == EventType.FAILED_AUTHENTICATION) {
        AuditEvent auditEvent = new AuditEvent(event == EventType.AUTHENTICATED ? AuditLevel.SUCCESS : AuditLevel.FAILURE);
        Map<String, Object> ctxMap = new HashMap<String, Object>();
        Account account = notification.getAccount();
        if (account != null) {
            ctxMap.put("principal", account.getPrincipal().getName());
        }
        ctxMap.put("message", notification.getMessage());
        ServletRequestContext src = notification.getExchange().getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        if (src != null) {
            ServletRequest hsr = src.getServletRequest();
            if (hsr instanceof HttpServletRequest) {
                ctxMap.put("request", WebUtil.deriveUsefulInfo((HttpServletRequest) hsr));
            }
        }
        ctxMap.put("Source", getClass().getCanonicalName());
        auditEvent.setContextMap(ctxMap);
        auditManager.audit(auditEvent);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Account(io.undertow.security.idm.Account) ServletRequest(javax.servlet.ServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) EventType(io.undertow.security.api.SecurityNotification.EventType) HashMap(java.util.HashMap) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) AuditEvent(org.jboss.security.audit.AuditEvent)

Example 10 with ServletRequest

use of javax.servlet.ServletRequest in project lucene-solr by apache.

the class DelegationTokenKerberosFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    // HttpClient 4.4.x throws NPE if query string is null and parsed through URLEncodedUtils.
    // See HTTPCLIENT-1746 and HADOOP-12767
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String queryString = httpRequest.getQueryString();
    final String nonNullQueryString = queryString == null ? "" : queryString;
    HttpServletRequest requestNonNullQueryString = new HttpServletRequestWrapper(httpRequest) {

        @Override
        public String getQueryString() {
            return nonNullQueryString;
        }
    };
    // include Impersonator User Name in case someone (e.g. logger) wants it
    FilterChain filterChainWrapper = new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            UserGroupInformation ugi = HttpUserGroupInformation.get();
            if (ugi != null && ugi.getAuthenticationMethod() == UserGroupInformation.AuthenticationMethod.PROXY) {
                UserGroupInformation realUserUgi = ugi.getRealUser();
                if (realUserUgi != null) {
                    httpRequest.setAttribute(KerberosPlugin.IMPERSONATOR_USER_NAME, realUserUgi.getShortUserName());
                }
            }
            filterChain.doFilter(servletRequest, servletResponse);
        }
    };
    super.doFilter(requestNonNullQueryString, response, filterChainWrapper);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) FilterChain(javax.servlet.FilterChain) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation) HttpUserGroupInformation(org.apache.hadoop.security.token.delegation.web.HttpUserGroupInformation)

Aggregations

ServletRequest (javax.servlet.ServletRequest)314 HttpServletRequest (javax.servlet.http.HttpServletRequest)188 ServletResponse (javax.servlet.ServletResponse)183 HttpServletResponse (javax.servlet.http.HttpServletResponse)118 FilterChain (javax.servlet.FilterChain)113 Test (org.junit.Test)82 IOException (java.io.IOException)65 ServletException (javax.servlet.ServletException)64 Filter (javax.servlet.Filter)41 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)28 Injector (com.google.inject.Injector)26 JspException (javax.servlet.jsp.JspException)26 RequestContext (com.agiletec.aps.system.RequestContext)25 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)25 FilterConfig (javax.servlet.FilterConfig)24 MockFilterChain (org.springframework.mock.web.MockFilterChain)24 ServletContext (javax.servlet.ServletContext)23 HttpSession (javax.servlet.http.HttpSession)21 ServletTestUtils.newFakeHttpServletRequest (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletRequest)18 ServletTestUtils.newFakeHttpServletResponse (com.google.inject.servlet.ServletTestUtils.newFakeHttpServletResponse)18