org.apache.catalina.util.SessionConfig Java Examples

The following examples show how to use org.apache.catalina.util.SessionConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CrossSubdomainSessionValve.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public @Override void invoke(Request request, Response response) throws IOException, ServletException {

        // this will cause Request.doGetSession to create the session cookie if necessary
        request.getSession(true);

        // replace any Tomcat-generated session cookies with our own
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (SessionConfig.getSessionCookieName(null).equals(cookie.getName())) {
                    replaceCookie(request, response, cookie);
                }
            }
        }

        // process the next valve
        getNext().invoke(request, response);
    }
 
Example #2
Source File: Response.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Return the specified URL with the specified session identifier
 * suitably encoded.
 *
 * @param url URL to be encoded with the session id
 * @param sessionId Session id to be included in the encoded URL
 * @return the encoded URL
 */
protected String toEncoded(String url, String sessionId) {
    if ((url == null) || (sessionId == null)) {
        return url;
    }

    String path = url;
    String query = "";
    String anchor = "";
    int question = url.indexOf('?');
    if (question >= 0) {
        path = url.substring(0, question);
        query = url.substring(question);
    }
    int pound = path.indexOf('#');
    if (pound >= 0) {
        anchor = path.substring(pound);
        path = path.substring(0, pound);
    }
    StringBuilder sb = new StringBuilder(path);
    if( sb.length() > 0 ) { // jsessionid can't be first.
        sb.append(";");
        sb.append(SessionConfig.getSessionUriParamName(
                request.getContext()));
        sb.append("=");
        sb.append(sessionId);
    }
    sb.append(anchor);
    sb.append(query);
    return sb.toString();
}
 
Example #3
Source File: Response.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Return the specified URL with the specified session identifier
 * suitably encoded.
 *
 * @param url URL to be encoded with the session id
 * @param sessionId Session id to be included in the encoded URL
 */
protected String toEncoded(String url, String sessionId) {

    if ((url == null) || (sessionId == null)) {
        return (url);
    }

    String path = url;
    String query = "";
    String anchor = "";
    int question = url.indexOf('?');
    if (question >= 0) {
        path = url.substring(0, question);
        query = url.substring(question);
    }
    int pound = path.indexOf('#');
    if (pound >= 0) {
        anchor = path.substring(pound);
        path = path.substring(0, pound);
    }
    StringBuilder sb = new StringBuilder(path);
    if( sb.length() > 0 ) { // jsessionid can't be first.
        sb.append(";");
        sb.append(SessionConfig.getSessionUriParamName(
                request.getContext()));
        sb.append("=");
        sb.append(sessionId);
    }
    sb.append(anchor);
    sb.append(query);
    return (sb.toString());

}
 
Example #4
Source File: Response.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Return the specified URL with the specified session identifier
 * suitably encoded.
 *
 * @param url URL to be encoded with the session id
 * @param sessionId Session id to be included in the encoded URL
 */
protected String toEncoded(String url, String sessionId) {

    if ((url == null) || (sessionId == null)) {
        return (url);
    }

    String path = url;
    String query = "";
    String anchor = "";
    int question = url.indexOf('?');
    if (question >= 0) {
        path = url.substring(0, question);
        query = url.substring(question);
    }
    int pound = path.indexOf('#');
    if (pound >= 0) {
        anchor = path.substring(pound);
        path = path.substring(0, pound);
    }
    StringBuilder sb = new StringBuilder(path);
    if( sb.length() > 0 ) { // jsessionid can't be first.
        sb.append(";");
        sb.append(SessionConfig.getSessionUriParamName(
                request.getContext()));
        sb.append("=");
        sb.append(sessionId);
    }
    sb.append(anchor);
    sb.append(query);
    return (sb.toString());

}
 
Example #5
Source File: CoyoteAdapter.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Parse session id in Cookie.
 *
 * @param request The Servlet request object
 */
protected void parseSessionCookiesId(Request request) {

    // If session tracking via cookies has been disabled for the current
    // context, don't go looking for a session ID in a cookie as a cookie
    // from a parent context with a session ID may be present which would
    // overwrite the valid session ID encoded in the URL
    Context context = request.getMappingData().context;
    if (context != null && !context.getServletContext()
            .getEffectiveSessionTrackingModes().contains(
                    SessionTrackingMode.COOKIE)) {
        return;
    }

    // Parse session id from cookies
    ServerCookies serverCookies = request.getServerCookies();
    int count = serverCookies.getCookieCount();
    if (count <= 0) {
        return;
    }

    String sessionCookieName = SessionConfig.getSessionCookieName(context);

    for (int i = 0; i < count; i++) {
        ServerCookie scookie = serverCookies.getCookie(i);
        if (scookie.getName().equals(sessionCookieName)) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
                // Accept only the first session id cookie
                convertMB(scookie.getValue());
                request.setRequestedSessionId
                    (scookie.getValue().toString());
                request.setRequestedSessionCookie(true);
                request.setRequestedSessionURL(false);
                if (log.isDebugEnabled()) {
                    log.debug(" Requested cookie session id is " +
                        request.getRequestedSessionId());
                }
            } else {
                if (!request.isRequestedSessionIdValid()) {
                    // Replace the session id until one is valid
                    convertMB(scookie.getValue());
                    request.setRequestedSessionId
                        (scookie.getValue().toString());
                }
            }
        }
    }

}
 
Example #6
Source File: ApplicationSessionCookieConfig.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new session cookie for the given session ID
 *
 * @param context     The Context for the web application
 * @param sessionId   The ID of the session for which the cookie will be
 *                    created
 * @param secure      Should session cookie be configured as secure
 */
public static Cookie createSessionCookie(Context context,
        String sessionId, boolean secure) {

    SessionCookieConfig scc =
        context.getServletContext().getSessionCookieConfig();

    // NOTE: The priority order for session cookie configuration is:
    //       1. Context level configuration
    //       2. Values from SessionCookieConfig
    //       3. Defaults

    Cookie cookie = new Cookie(
            SessionConfig.getSessionCookieName(context), sessionId);
   
    // Just apply the defaults.
    cookie.setMaxAge(scc.getMaxAge());
    cookie.setComment(scc.getComment());
   
    if (context.getSessionCookieDomain() == null) {
        // Avoid possible NPE
        if (scc.getDomain() != null) {
            cookie.setDomain(scc.getDomain());
        }
    } else {
        cookie.setDomain(context.getSessionCookieDomain());
    }

    // Always set secure if the request is secure
    if (scc.isSecure() || secure) {
        cookie.setSecure(true);
    }

    // Always set httpOnly if the context is configured for that
    if (scc.isHttpOnly() || context.getUseHttpOnly()) {
        cookie.setHttpOnly(true);
    }
   
    String contextPath = context.getSessionCookiePath();
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = scc.getPath();
    }
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = context.getEncodedPath();
    }
    if (context.getSessionCookiePathUsesTrailingSlash()) {
        // Handle special case of ROOT context where cookies require a path of
        // '/' but the servlet spec uses an empty string
        // Also ensure the cookies for a context with a path of /foo don't get
        // sent for requests with a path of /foobar
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
    } else {
        // Only handle special case of ROOT context where cookies require a
        // path of '/' but the servlet spec uses an empty string
        if (contextPath.length() == 0) {
            contextPath = "/";
        }
    }
    cookie.setPath(contextPath);

    return cookie;
}
 
Example #7
Source File: RealmBase.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Enforce any user data constraint required by the security constraint
 * guarding this request URI.  Return <code>true</code> if this constraint
 * was not violated and processing should continue, or <code>false</code>
 * if we have created a response already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param constraints Security constraint being checked
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean hasUserDataPermission(Request request,
                                     Response response,
                                     SecurityConstraint []constraints)
    throws IOException {

    // Is there a relevant user data constraint?
    if (constraints == null || constraints.length == 0) {
        if (log.isDebugEnabled())
            log.debug("  No applicable security constraint defined");
        return (true);
    }
    for(int i=0; i < constraints.length; i++) {
        SecurityConstraint constraint = constraints[i];
        String userConstraint = constraint.getUserConstraint();
        if (userConstraint == null) {
            if (log.isDebugEnabled())
                log.debug("  No applicable user data constraint defined");
            return (true);
        }
        if (userConstraint.equals(Constants.NONE_TRANSPORT)) {
            if (log.isDebugEnabled())
                log.debug("  User data constraint has no restrictions");
            return (true);
        }

    }
    // Validate the request against the user data constraint
    if (request.getRequest().isSecure()) {
        if (log.isDebugEnabled())
            log.debug("  User data constraint already satisfied");
        return (true);
    }
    // Initialize variables we need to determine the appropriate action
    int redirectPort = request.getConnector().getRedirectPort();

    // Is redirecting disabled?
    if (redirectPort <= 0) {
        if (log.isDebugEnabled())
            log.debug("  SSL redirect is disabled");
        response.sendError
            (HttpServletResponse.SC_FORBIDDEN,
             request.getRequestURI());
        return (false);
    }

    // Redirect to the corresponding SSL port
    StringBuilder file = new StringBuilder();
    String protocol = "https";
    String host = request.getServerName();
    // Protocol
    file.append(protocol).append("://").append(host);
    // Host with port
    if(redirectPort != 443) {
        file.append(":").append(redirectPort);
    }
    // URI
    file.append(request.getRequestURI());
    String requestedSessionId = request.getRequestedSessionId();
    if ((requestedSessionId != null) &&
        request.isRequestedSessionIdFromURL()) {
        file.append(";");
        file.append(SessionConfig.getSessionUriParamName(
                request.getContext()));
        file.append("=");
        file.append(requestedSessionId);
    }
    String queryString = request.getQueryString();
    if (queryString != null) {
        file.append('?');
        file.append(queryString);
    }
    if (log.isDebugEnabled())
        log.debug("  Redirecting to " + file.toString());
    response.sendRedirect(file.toString(), transportGuaranteeRedirectStatus);
    return (false);

}
 
Example #8
Source File: CoyoteAdapter.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Parse session id in URL.
 */
protected void parseSessionCookiesId(org.apache.coyote.Request req, Request request) {

    // If session tracking via cookies has been disabled for the current
    // context, don't go looking for a session ID in a cookie as a cookie
    // from a parent context with a session ID may be present which would
    // overwrite the valid session ID encoded in the URL
    Context context = (Context) request.getMappingData().context;
    if (context != null && !context.getServletContext()
            .getEffectiveSessionTrackingModes().contains(
                    SessionTrackingMode.COOKIE)) {
        return;
    }

    // Parse session id from cookies
    Cookies serverCookies = req.getCookies();
    int count = serverCookies.getCookieCount();
    if (count <= 0) {
        return;
    }

    String sessionCookieName = SessionConfig.getSessionCookieName(context);

    for (int i = 0; i < count; i++) {
        ServerCookie scookie = serverCookies.getCookie(i);
        if (scookie.getName().equals(sessionCookieName)) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
                // Accept only the first session id cookie
                convertMB(scookie.getValue());
                request.setRequestedSessionId
                    (scookie.getValue().toString());
                request.setRequestedSessionCookie(true);
                request.setRequestedSessionURL(false);
                if (log.isDebugEnabled()) {
                    log.debug(" Requested cookie session id is " +
                        request.getRequestedSessionId());
                }
            } else {
                if (!request.isRequestedSessionIdValid()) {
                    // Replace the session id until one is valid
                    convertMB(scookie.getValue());
                    request.setRequestedSessionId
                        (scookie.getValue().toString());
                }
            }
        }
    }

}
 
Example #9
Source File: Response.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private boolean doIsEncodeable(Request hreq, Session session,
                               String location) {
    // Is this a valid absolute URL?
    URL url = null;
    try {
        url = new URL(location);
    } catch (MalformedURLException e) {
        return (false);
    }

    // Does this URL match down to (and including) the context path?
    if (!hreq.getScheme().equalsIgnoreCase(url.getProtocol())) {
        return (false);
    }
    if (!hreq.getServerName().equalsIgnoreCase(url.getHost())) {
        return (false);
    }
    int serverPort = hreq.getServerPort();
    if (serverPort == -1) {
        if ("https".equals(hreq.getScheme())) {
            serverPort = 443;
        } else {
            serverPort = 80;
        }
    }
    int urlPort = url.getPort();
    if (urlPort == -1) {
        if ("https".equals(url.getProtocol())) {
            urlPort = 443;
        } else {
            urlPort = 80;
        }
    }
    if (serverPort != urlPort) {
        return (false);
    }

    String contextPath = getContext().getPath();
    if (contextPath != null) {
        String file = url.getFile();
        if (!file.startsWith(contextPath)) {
            return (false);
        }
        String tok = ";" +
                SessionConfig.getSessionUriParamName(request.getContext()) +
                "=" + session.getIdInternal();
        if( file.indexOf(tok, contextPath.length()) >= 0 ) {
            return (false);
        }
    }

    // This URL belongs to our web application, so it is encodeable
    return (true);

}
 
Example #10
Source File: ApplicationSessionCookieConfig.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new session cookie for the given session ID
 *
 * @param context     The Context for the web application
 * @param sessionId   The ID of the session for which the cookie will be
 *                    created
 * @param secure      Should session cookie be configured as secure
 */
public static Cookie createSessionCookie(Context context,
        String sessionId, boolean secure) {

    SessionCookieConfig scc =
        context.getServletContext().getSessionCookieConfig();

    // NOTE: The priority order for session cookie configuration is:
    //       1. Context level configuration
    //       2. Values from SessionCookieConfig
    //       3. Defaults

    Cookie cookie = new Cookie(
            SessionConfig.getSessionCookieName(context), sessionId);
   
    // Just apply the defaults.
    cookie.setMaxAge(scc.getMaxAge());
    cookie.setComment(scc.getComment());
   
    if (context.getSessionCookieDomain() == null) {
        // Avoid possible NPE
        if (scc.getDomain() != null) {
            cookie.setDomain(scc.getDomain());
        }
    } else {
        cookie.setDomain(context.getSessionCookieDomain());
    }

    // Always set secure if the request is secure
    if (scc.isSecure() || secure) {
        cookie.setSecure(true);
    }

    // Always set httpOnly if the context is configured for that
    if (scc.isHttpOnly() || context.getUseHttpOnly()) {
        cookie.setHttpOnly(true);
    }
   
    String contextPath = context.getSessionCookiePath();
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = scc.getPath();
    }
    if (contextPath == null || contextPath.length() == 0) {
        contextPath = context.getEncodedPath();
    }
    if (context.getSessionCookiePathUsesTrailingSlash()) {
        // Handle special case of ROOT context where cookies require a path of
        // '/' but the servlet spec uses an empty string
        // Also ensure the cookies for a context with a path of /foo don't get
        // sent for requests with a path of /foobar
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
    } else {
        // Only handle special case of ROOT context where cookies require a
        // path of '/' but the servlet spec uses an empty string
        if (contextPath.length() == 0) {
            contextPath = "/";
        }
    }
    cookie.setPath(contextPath);

    return cookie;
}
 
Example #11
Source File: RealmBase.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Enforce any user data constraint required by the security constraint
 * guarding this request URI.  Return <code>true</code> if this constraint
 * was not violated and processing should continue, or <code>false</code>
 * if we have created a response already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param constraints Security constraint being checked
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean hasUserDataPermission(Request request,
                                     Response response,
                                     SecurityConstraint []constraints)
    throws IOException {

    // Is there a relevant user data constraint?
    if (constraints == null || constraints.length == 0) {
        if (log.isDebugEnabled())
            log.debug("  No applicable security constraint defined");
        return (true);
    }
    for(int i=0; i < constraints.length; i++) {
        SecurityConstraint constraint = constraints[i];
        String userConstraint = constraint.getUserConstraint();
        if (userConstraint == null) {
            if (log.isDebugEnabled())
                log.debug("  No applicable user data constraint defined");
            return (true);
        }
        if (userConstraint.equals(Constants.NONE_TRANSPORT)) {
            if (log.isDebugEnabled())
                log.debug("  User data constraint has no restrictions");
            return (true);
        }

    }
    // Validate the request against the user data constraint
    if (request.getRequest().isSecure()) {
        if (log.isDebugEnabled())
            log.debug("  User data constraint already satisfied");
        return (true);
    }
    // Initialize variables we need to determine the appropriate action
    int redirectPort = request.getConnector().getRedirectPort();

    // Is redirecting disabled?
    if (redirectPort <= 0) {
        if (log.isDebugEnabled())
            log.debug("  SSL redirect is disabled");
        response.sendError
            (HttpServletResponse.SC_FORBIDDEN,
             request.getRequestURI());
        return (false);
    }

    // Redirect to the corresponding SSL port
    StringBuilder file = new StringBuilder();
    String protocol = "https";
    String host = request.getServerName();
    // Protocol
    file.append(protocol).append("://").append(host);
    // Host with port
    if(redirectPort != 443) {
        file.append(":").append(redirectPort);
    }
    // URI
    file.append(request.getRequestURI());
    String requestedSessionId = request.getRequestedSessionId();
    if ((requestedSessionId != null) &&
        request.isRequestedSessionIdFromURL()) {
        file.append(";");
        file.append(SessionConfig.getSessionUriParamName(
                request.getContext()));
        file.append("=");
        file.append(requestedSessionId);
    }
    String queryString = request.getQueryString();
    if (queryString != null) {
        file.append('?');
        file.append(queryString);
    }
    if (log.isDebugEnabled())
        log.debug("  Redirecting to " + file.toString());
    response.sendRedirect(file.toString());
    return (false);

}
 
Example #12
Source File: CoyoteAdapter.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Parse session id in URL.
 */
protected void parseSessionCookiesId(org.apache.coyote.Request req, Request request) {

    // If session tracking via cookies has been disabled for the current
    // context, don't go looking for a session ID in a cookie as a cookie
    // from a parent context with a session ID may be present which would
    // overwrite the valid session ID encoded in the URL
    Context context = (Context) request.getMappingData().context;
    if (context != null && !context.getServletContext()
            .getEffectiveSessionTrackingModes().contains(
                    SessionTrackingMode.COOKIE)) {
        return;
    }

    // Parse session id from cookies
    Cookies serverCookies = req.getCookies();
    int count = serverCookies.getCookieCount();
    if (count <= 0) {
        return;
    }

    String sessionCookieName = SessionConfig.getSessionCookieName(context);

    for (int i = 0; i < count; i++) {
        ServerCookie scookie = serverCookies.getCookie(i);
        if (scookie.getName().equals(sessionCookieName)) {
            // Override anything requested in the URL
            if (!request.isRequestedSessionIdFromCookie()) {
                // Accept only the first session id cookie
                convertMB(scookie.getValue());
                request.setRequestedSessionId
                    (scookie.getValue().toString());
                request.setRequestedSessionCookie(true);
                request.setRequestedSessionURL(false);
                if (log.isDebugEnabled()) {
                    log.debug(" Requested cookie session id is " +
                        request.getRequestedSessionId());
                }
            } else {
                if (!request.isRequestedSessionIdValid()) {
                    // Replace the session id until one is valid
                    convertMB(scookie.getValue());
                    request.setRequestedSessionId
                        (scookie.getValue().toString());
                }
            }
        }
    }

}
 
Example #13
Source File: Response.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private boolean doIsEncodeable(Request hreq, Session session,
                               String location) {
    // Is this a valid absolute URL?
    URL url = null;
    try {
        url = new URL(location);
    } catch (MalformedURLException e) {
        return (false);
    }

    // Does this URL match down to (and including) the context path?
    if (!hreq.getScheme().equalsIgnoreCase(url.getProtocol())) {
        return (false);
    }
    if (!hreq.getServerName().equalsIgnoreCase(url.getHost())) {
        return (false);
    }
    int serverPort = hreq.getServerPort();
    if (serverPort == -1) {
        if ("https".equals(hreq.getScheme())) {
            serverPort = 443;
        } else {
            serverPort = 80;
        }
    }
    int urlPort = url.getPort();
    if (urlPort == -1) {
        if ("https".equals(url.getProtocol())) {
            urlPort = 443;
        } else {
            urlPort = 80;
        }
    }
    if (serverPort != urlPort) {
        return (false);
    }

    String contextPath = getContext().getPath();
    if (contextPath != null) {
        String file = url.getFile();
        if ((file == null) || !file.startsWith(contextPath)) {
            return (false);
        }
        String tok = ";" +
                SessionConfig.getSessionUriParamName(request.getContext()) +
                "=" + session.getIdInternal();
        if( file.indexOf(tok, contextPath.length()) >= 0 ) {
            return (false);
        }
    }

    // This URL belongs to our web application, so it is encodeable
    return (true);

}
 
Example #14
Source File: ApplicationSessionCookieConfig.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Creates a new session cookie for the given session ID
 *
 * @param context     The Context for the web application
 * @param sessionId   The ID of the session for which the cookie will be
 *                    created
 * @param secure      Should session cookie be configured as secure
 * @return the cookie for the session
 */
public static Cookie createSessionCookie(Context context,
        String sessionId, boolean secure) {

    SessionCookieConfig scc =
        context.getServletContext().getSessionCookieConfig();

    // NOTE: The priority order for session cookie configuration is:
    //       1. Context level configuration
    //       2. Values from SessionCookieConfig
    //       3. Defaults

    Cookie cookie = new Cookie(
            SessionConfig.getSessionCookieName(context), sessionId);

    // Just apply the defaults.
    cookie.setMaxAge(scc.getMaxAge());
    cookie.setComment(scc.getComment());

    if (context.getSessionCookieDomain() == null) {
        // Avoid possible NPE
        if (scc.getDomain() != null) {
            cookie.setDomain(scc.getDomain());
        }
    } else {
        cookie.setDomain(context.getSessionCookieDomain());
    }

    // Always set secure if the request is secure
    if (scc.isSecure() || secure) {
        cookie.setSecure(true);
    }

    // Always set httpOnly if the context is configured for that
    if (scc.isHttpOnly() || context.getUseHttpOnly()) {
        cookie.setHttpOnly(true);
    }

    cookie.setPath(SessionConfig.getSessionCookiePath(context));

    return cookie;
}
 
Example #15
Source File: ApplicationPushBuilder.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
public ApplicationPushBuilder(Request catalinaRequest, HttpServletRequest request) {

        baseRequest = request;
        this.catalinaRequest = catalinaRequest;
        coyoteRequest = catalinaRequest.getCoyoteRequest();

        // Populate the initial list of HTTP headers
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            List<String> values = new ArrayList<>();
            headers.put(headerName, values);
            Enumeration<String> headerValues = request.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                values.add(headerValues.nextElement());
            }
        }

        // Remove the headers
        headers.remove("if-match");
        headers.remove("if-none-match");
        headers.remove("if-modified-since");
        headers.remove("if-unmodified-since");
        headers.remove("if-range");
        headers.remove("range");
        headers.remove("expect");
        headers.remove("authorization");
        headers.remove("referer");
        // Also remove the cookie header since it will be regenerated
        headers.remove("cookie");

        // set the referer header
        StringBuffer referer = request.getRequestURL();
        if (request.getQueryString() != null) {
            referer.append('?');
            referer.append(request.getQueryString());
        }
        addHeader("referer", referer.toString());

        // Session
        Context context = catalinaRequest.getContext();
        sessionCookieName = SessionConfig.getSessionCookieName(context);
        sessionPathParameterName = SessionConfig.getSessionUriParamName(context);

        HttpSession session = request.getSession(false);
        if (session != null) {
            sessionId = session.getId();
        }
        if (sessionId == null) {
            sessionId = request.getRequestedSessionId();
        }
        if (!request.isRequestedSessionIdFromCookie() && !request.isRequestedSessionIdFromURL() &&
                sessionId != null) {
            Set<SessionTrackingMode> sessionTrackingModes =
                    request.getServletContext().getEffectiveSessionTrackingModes();
            addSessionCookie = sessionTrackingModes.contains(SessionTrackingMode.COOKIE);
            addSessionPathParameter = sessionTrackingModes.contains(SessionTrackingMode.URL);
        } else {
            addSessionCookie = request.isRequestedSessionIdFromCookie();
            addSessionPathParameter = request.isRequestedSessionIdFromURL();
        }

        // Cookies
        if (request.getCookies() != null) {
            for (Cookie requestCookie : request.getCookies()) {
                cookies.add(requestCookie);
            }
        }
        for (Cookie responseCookie : catalinaRequest.getResponse().getCookies()) {
            if (responseCookie.getMaxAge() < 0) {
                // Path information not available so can only remove based on
                // name.
                Iterator<Cookie> cookieIterator = cookies.iterator();
                while (cookieIterator.hasNext()) {
                    Cookie cookie = cookieIterator.next();
                    if (cookie.getName().equals(responseCookie.getName())) {
                        cookieIterator.remove();
                    }
                }
            } else {
                cookies.add(new Cookie(responseCookie.getName(), responseCookie.getValue()));
            }
        }
        List<String> cookieValues = new ArrayList<>(1);
        cookieValues.add(generateCookieHeader(cookies,
                catalinaRequest.getContext().getCookieProcessor()));
        headers.put("cookie", cookieValues);

        // Authentication
        if (catalinaRequest.getPrincipal() != null) {
            if ((session == null) || catalinaRequest.getSessionInternal(false).getPrincipal() == null
                    || !(context.getAuthenticator() instanceof AuthenticatorBase)
                    || !((AuthenticatorBase) context.getAuthenticator()).getCache()) {
                // Set a username only if there is no session cache for the principal
                userName = catalinaRequest.getPrincipal().getName();
            }
            setHeader("authorization", "x-push");
        }
    }
 
Example #16
Source File: RealmBase.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Enforce any user data constraint required by the security constraint
 * guarding this request URI.  Return <code>true</code> if this constraint
 * was not violated and processing should continue, or <code>false</code>
 * if we have created a response already.
 *
 * @param request Request we are processing
 * @param response Response we are creating
 * @param constraints Security constraint being checked
 *
 * @exception IOException if an input/output error occurs
 */
@Override
public boolean hasUserDataPermission(Request request,
                                     Response response,
                                     SecurityConstraint []constraints)
    throws IOException {

    // Is there a relevant user data constraint?
    if (constraints == null || constraints.length == 0) {
        if (log.isDebugEnabled())
            log.debug("  No applicable security constraint defined");
        return true;
    }
    for(int i=0; i < constraints.length; i++) {
        SecurityConstraint constraint = constraints[i];
        String userConstraint = constraint.getUserConstraint();
        if (userConstraint == null) {
            if (log.isDebugEnabled())
                log.debug("  No applicable user data constraint defined");
            return true;
        }
        if (userConstraint.equals(TransportGuarantee.NONE.name())) {
            if (log.isDebugEnabled())
                log.debug("  User data constraint has no restrictions");
            return true;
        }

    }
    // Validate the request against the user data constraint
    if (request.getRequest().isSecure()) {
        if (log.isDebugEnabled())
            log.debug("  User data constraint already satisfied");
        return true;
    }
    // Initialize variables we need to determine the appropriate action
    int redirectPort = request.getConnector().getRedirectPort();

    // Is redirecting disabled?
    if (redirectPort <= 0) {
        if (log.isDebugEnabled())
            log.debug("  SSL redirect is disabled");
        response.sendError
            (HttpServletResponse.SC_FORBIDDEN,
             request.getRequestURI());
        return false;
    }

    // Redirect to the corresponding SSL port
    StringBuilder file = new StringBuilder();
    String protocol = "https";
    String host = request.getServerName();
    // Protocol
    file.append(protocol).append("://").append(host);
    // Host with port
    if(redirectPort != 443) {
        file.append(":").append(redirectPort);
    }
    // URI
    file.append(request.getRequestURI());
    String requestedSessionId = request.getRequestedSessionId();
    if ((requestedSessionId != null) &&
        request.isRequestedSessionIdFromURL()) {
        file.append(";");
        file.append(SessionConfig.getSessionUriParamName(
                request.getContext()));
        file.append("=");
        file.append(requestedSessionId);
    }
    String queryString = request.getQueryString();
    if (queryString != null) {
        file.append('?');
        file.append(queryString);
    }
    if (log.isDebugEnabled())
        log.debug("  Redirecting to " + file.toString());
    response.sendRedirect(file.toString(), transportGuaranteeRedirectStatus);
    return false;

}
 
Example #17
Source File: LoadBalancerDrainingValve.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    if  ("DIS".equals(request.getAttribute(ATTRIBUTE_KEY_JK_LB_ACTIVATION)) &&
            !request.isRequestedSessionIdValid()) {

        if (containerLog.isDebugEnabled()) {
            containerLog.debug("Load-balancer is in DISABLED state; draining this node");
        }

        boolean ignoreRebalance = false;
        Cookie sessionCookie = null;

        final Cookie[] cookies = request.getCookies();

        final String sessionCookieName = SessionConfig.getSessionCookieName(request.getContext());

        if (null != cookies) {
            for (Cookie cookie : cookies) {
                final String cookieName = cookie.getName();
                if (containerLog.isTraceEnabled()) {
                    containerLog.trace("Checking cookie " + cookieName + "=" + cookie.getValue());
                }

                if (sessionCookieName.equals(cookieName) &&
                        request.getRequestedSessionId().equals(cookie.getValue())) {
                    sessionCookie = cookie;
                } else if (null != _ignoreCookieName &&
                        _ignoreCookieName.equals(cookieName) &&
                        null != _ignoreCookieValue &&
                        _ignoreCookieValue.equals(cookie.getValue())) {
                    // The client presenting a valid ignore-cookie value?
                    ignoreRebalance = true;
                }
            }
        }

        if (ignoreRebalance) {
            if (containerLog.isDebugEnabled()) {
                containerLog.debug("Client is presenting a valid " + _ignoreCookieName +
                        " cookie, re-balancing is being skipped");
            }

            getNext().invoke(request, response);

            return;
        }

        // Kill any session cookie that was found
        // TODO: Consider implications of SSO cookies
        if (null != sessionCookie) {
            sessionCookie.setPath(SessionConfig.getSessionCookiePath(request.getContext()));
            sessionCookie.setMaxAge(0); // Delete
            sessionCookie.setValue(""); // Purge the cookie's value
            response.addCookie(sessionCookie);
        }

        // Re-write the URI if it contains a ;jsessionid parameter
        String uri = request.getRequestURI();
        String sessionURIParamName = SessionConfig.getSessionUriParamName(request.getContext());
        if (uri.contains(";" + sessionURIParamName + "=")) {
            uri = uri.replaceFirst(";" + sessionURIParamName + "=[^&?]*", "");
        }

        String queryString = request.getQueryString();

        if (null != queryString) {
            uri = uri + "?" + queryString;
        }

        // NOTE: Do not call response.encodeRedirectURL or the bad
        // sessionid will be restored
        response.setHeader("Location", uri);
        response.setStatus(_redirectStatusCode);
    } else {
        getNext().invoke(request, response);
    }
}
 
Example #18
Source File: ApplicationSessionCookieConfig.java    From Tomcat7.0.67 with Apache License 2.0 2 votes vote down vote up
/**
 * Determine the name to use for the session cookie for the provided
 * context.
 * @param context
 *
 * @deprecated  Replaced by
 *              {@link SessionConfig#getSessionCookieName(Context)}. This
 *              will be removed in Tomcat 8.0.x.
 */
@Deprecated
public static String getSessionCookieName(Context context) {
    return SessionConfig.getSessionCookieName(context);
}
 
Example #19
Source File: ApplicationSessionCookieConfig.java    From Tomcat7.0.67 with Apache License 2.0 2 votes vote down vote up
/**
 * Determine the name to use for the session cookie for the provided
 * context.
 * @param context
 *
 * @deprecated  Replaced by
 *              {@link SessionConfig#getSessionUriParamName(Context)}. This
 *              will be removed in Tomcat 8.0.x.
 */
@Deprecated
public static String getSessionUriParamName(Context context) {
    return SessionConfig.getSessionUriParamName(context);
}
 
Example #20
Source File: ApplicationSessionCookieConfig.java    From tomcatsrc with Apache License 2.0 2 votes vote down vote up
/**
 * Determine the name to use for the session cookie for the provided
 * context.
 * @param context
 *
 * @deprecated  Replaced by
 *              {@link SessionConfig#getSessionCookieName(Context)}. This
 *              will be removed in Tomcat 8.0.x.
 */
@Deprecated
public static String getSessionCookieName(Context context) {
    return SessionConfig.getSessionCookieName(context);
}
 
Example #21
Source File: ApplicationSessionCookieConfig.java    From tomcatsrc with Apache License 2.0 2 votes vote down vote up
/**
 * Determine the name to use for the session cookie for the provided
 * context.
 * @param context
 *
 * @deprecated  Replaced by
 *              {@link SessionConfig#getSessionUriParamName(Context)}. This
 *              will be removed in Tomcat 8.0.x.
 */
@Deprecated
public static String getSessionUriParamName(Context context) {
    return SessionConfig.getSessionUriParamName(context);
}