Search in sources :

Example 1 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class FormAuthenticator method restoreRequest.

/**
     * Restore the original request from information stored in our session.
     * If the original request is no longer present (because the session
     * timed out), return <code>false</code>; otherwise, return
     * <code>true</code>.
     *
     * @param request The request to be restored
     * @param session The session containing the saved information
     * @return <code>true</code> if the request was successfully restored
     * @throws IOException if an IO error occurred during the process
     */
protected boolean restoreRequest(Request request, Session session) throws IOException {
    // Retrieve and remove the SavedRequest object from our session
    SavedRequest saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
    session.removeNote(Constants.FORM_REQUEST_NOTE);
    session.removeNote(Constants.FORM_PRINCIPAL_NOTE);
    if (saved == null) {
        return false;
    }
    // Swallow any request body since we will be replacing it
    // Need to do this before headers are restored as AJP connector uses
    // content length header to determine how much data needs to be read for
    // request body
    byte[] buffer = new byte[4096];
    InputStream is = request.createInputStream();
    while (is.read(buffer) >= 0) {
    // Ignore request body
    }
    // Modify our current request to reflect the original one
    request.clearCookies();
    Iterator<Cookie> cookies = saved.getCookies();
    while (cookies.hasNext()) {
        request.addCookie(cookies.next());
    }
    String method = saved.getMethod();
    MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders();
    rmh.recycle();
    boolean cacheable = "GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method);
    Iterator<String> names = saved.getHeaderNames();
    while (names.hasNext()) {
        String name = names.next();
        // BZ 43687
        if (!("If-Modified-Since".equalsIgnoreCase(name) || (cacheable && "If-None-Match".equalsIgnoreCase(name)))) {
            Iterator<String> values = saved.getHeaderValues(name);
            while (values.hasNext()) {
                rmh.addValue(name).setString(values.next());
            }
        }
    }
    request.clearLocales();
    Iterator<Locale> locales = saved.getLocales();
    while (locales.hasNext()) {
        request.addLocale(locales.next());
    }
    request.getCoyoteRequest().getParameters().recycle();
    request.getCoyoteRequest().getParameters().setQueryStringEncoding(request.getConnector().getURIEncoding());
    ByteChunk body = saved.getBody();
    if (body != null) {
        request.getCoyoteRequest().action(ActionCode.REQ_SET_BODY_REPLAY, body);
        // Set content type
        MessageBytes contentType = MessageBytes.newInstance();
        // If no content type specified, use default for POST
        String savedContentType = saved.getContentType();
        if (savedContentType == null && "POST".equalsIgnoreCase(method)) {
            savedContentType = "application/x-www-form-urlencoded";
        }
        contentType.setString(savedContentType);
        request.getCoyoteRequest().setContentType(contentType);
    }
    request.getCoyoteRequest().method().setString(method);
    return true;
}
Also used : Cookie(javax.servlet.http.Cookie) Locale(java.util.Locale) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) InputStream(java.io.InputStream) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) MimeHeaders(org.apache.tomcat.util.http.MimeHeaders)

Example 2 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class SpnegoAuthenticator method doAuthenticate.

@Override
protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
    if (checkForCachedAuthentication(request, response, true)) {
        return true;
    }
    MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders().getValue("authorization");
    if (authorization == null) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("authenticator.noAuthHeader"));
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    authorization.toBytes();
    ByteChunk authorizationBC = authorization.getByteChunk();
    if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("spnegoAuthenticator.authHeaderNotNego"));
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    authorizationBC.setOffset(authorizationBC.getOffset() + 10);
    byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength());
    if (getApplyJava8u40Fix()) {
        SpnegoTokenFixer.fix(decoded);
    }
    if (decoded.length == 0) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("spnegoAuthenticator.authHeaderNoToken"));
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
    LoginContext lc = null;
    GSSContext gssContext = null;
    byte[] outToken = null;
    Principal principal = null;
    try {
        try {
            lc = new LoginContext(getLoginConfigName());
            lc.login();
        } catch (LoginException e) {
            log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return false;
        }
        Subject subject = lc.getSubject();
        // Assume the GSSContext is stateless
        // TODO: Confirm this assumption
        final GSSManager manager = GSSManager.getInstance();
        // IBM JDK only understands indefinite lifetime
        final int credentialLifetime;
        if (JreVendor.IS_IBM_JVM) {
            credentialLifetime = GSSCredential.INDEFINITE_LIFETIME;
        } else {
            credentialLifetime = GSSCredential.DEFAULT_LIFETIME;
        }
        final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {

            @Override
            public GSSCredential run() throws GSSException {
                return manager.createCredential(null, credentialLifetime, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY);
            }
        };
        gssContext = manager.createContext(Subject.doAs(subject, action));
        outToken = Subject.doAs(lc.getSubject(), new AcceptAction(gssContext, decoded));
        if (outToken == null) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"));
            }
            // Start again
            response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        principal = Subject.doAs(subject, new AuthenticateAction(context.getRealm(), gssContext, storeDelegatedCredential));
    } catch (GSSException e) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"), e);
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof GSSException) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
            }
        } else {
            log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e);
        }
        response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    } finally {
        if (gssContext != null) {
            try {
                gssContext.dispose();
            } catch (GSSException e) {
            // Ignore
            }
        }
        if (lc != null) {
            try {
                lc.logout();
            } catch (LoginException e) {
            // Ignore
            }
        }
    }
    // Send response token on success and failure
    response.setHeader(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_NEGOTIATE + " " + Base64.encodeBase64String(outToken));
    if (principal != null) {
        register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null);
        Pattern p = noKeepAliveUserAgents;
        if (p != null) {
            MessageBytes ua = request.getCoyoteRequest().getMimeHeaders().getValue("user-agent");
            if (ua != null && p.matcher(ua.toString()).matches()) {
                response.setHeader("Connection", "close");
            }
        }
        return true;
    }
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return false;
}
Also used : Pattern(java.util.regex.Pattern) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) PrivilegedActionException(java.security.PrivilegedActionException) MessageBytes(org.apache.tomcat.util.buf.MessageBytes) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Oid(org.ietf.jgss.Oid) Subject(javax.security.auth.Subject) LoginContext(javax.security.auth.login.LoginContext) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) GSSContext(org.ietf.jgss.GSSContext) GSSManager(org.ietf.jgss.GSSManager) LoginException(javax.security.auth.login.LoginException) Principal(java.security.Principal)

Example 3 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class AjpProcessor method populateSslRequestAttributes.

@Override
protected final void populateSslRequestAttributes() {
    if (!certificates.isNull()) {
        ByteChunk certData = certificates.getByteChunk();
        X509Certificate[] jsseCerts = null;
        ByteArrayInputStream bais = new ByteArrayInputStream(certData.getBytes(), certData.getStart(), certData.getLength());
        // Fill the  elements.
        try {
            CertificateFactory cf;
            String clientCertProvider = protocol.getClientCertProvider();
            if (clientCertProvider == null) {
                cf = CertificateFactory.getInstance("X.509");
            } else {
                cf = CertificateFactory.getInstance("X.509", clientCertProvider);
            }
            while (bais.available() > 0) {
                X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
                if (jsseCerts == null) {
                    jsseCerts = new X509Certificate[1];
                    jsseCerts[0] = cert;
                } else {
                    X509Certificate[] temp = new X509Certificate[jsseCerts.length + 1];
                    System.arraycopy(jsseCerts, 0, temp, 0, jsseCerts.length);
                    temp[jsseCerts.length] = cert;
                    jsseCerts = temp;
                }
            }
        } catch (java.security.cert.CertificateException e) {
            getLog().error(sm.getString("ajpprocessor.certs.fail"), e);
            return;
        } catch (NoSuchProviderException e) {
            getLog().error(sm.getString("ajpprocessor.certs.fail"), e);
            return;
        }
        request.setAttribute(SSLSupport.CERTIFICATE_KEY, jsseCerts);
    }
}
Also used : ByteChunk(org.apache.tomcat.util.buf.ByteChunk) ByteArrayInputStream(java.io.ByteArrayInputStream) NoSuchProviderException(java.security.NoSuchProviderException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate)

Example 4 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class Http11Processor method parseHost.

/**
     * Parse host.
     */
private void parseHost(MessageBytes valueMB) {
    if (valueMB == null || valueMB.isNull()) {
        // HTTP/1.0
        // If no host header, use the port info from the endpoint
        // The host will be obtained lazily from the socket if required
        // using ActionCode#REQ_LOCAL_NAME_ATTRIBUTE
        request.setServerPort(protocol.getPort());
        return;
    }
    ByteChunk valueBC = valueMB.getByteChunk();
    byte[] valueB = valueBC.getBytes();
    int valueL = valueBC.getLength();
    int valueS = valueBC.getStart();
    int colonPos = -1;
    if (hostNameC.length < valueL) {
        hostNameC = new char[valueL];
    }
    boolean ipv6 = (valueB[valueS] == '[');
    boolean bracketClosed = false;
    for (int i = 0; i < valueL; i++) {
        char b = (char) valueB[i + valueS];
        hostNameC[i] = b;
        if (b == ']') {
            bracketClosed = true;
        } else if (b == ':') {
            if (!ipv6 || bracketClosed) {
                colonPos = i;
                break;
            }
        }
    }
    if (colonPos < 0) {
        request.serverName().setChars(hostNameC, 0, valueL);
    } else {
        request.serverName().setChars(hostNameC, 0, colonPos);
        int port = 0;
        int mult = 1;
        for (int i = valueL - 1; i > colonPos; i--) {
            int charValue = HexUtils.getDec(valueB[i + valueS]);
            if (charValue == -1 || charValue > 9) {
                // Invalid character
                // 400 - Bad request
                response.setStatus(400);
                setErrorState(ErrorState.CLOSE_CLEAN, null);
                break;
            }
            port = port + (charValue * mult);
            mult = 10 * mult;
        }
        request.setServerPort(port);
    }
}
Also used : ByteChunk(org.apache.tomcat.util.buf.ByteChunk)

Example 5 with ByteChunk

use of org.apache.tomcat.util.buf.ByteChunk in project tomcat by apache.

the class TestNonLoginAndBasicAuthenticator method doTestBasic.

private void doTestBasic(String uri, BasicCredentials credentials, boolean useCookie, int expectedRC) throws Exception {
    Map<String, List<String>> reqHeaders = new HashMap<>();
    Map<String, List<String>> respHeaders = new HashMap<>();
    if (useCookie) {
        addCookies(reqHeaders);
    } else {
        if (credentials != null) {
            List<String> auth = new ArrayList<>();
            auth.add(credentials.getCredentials());
            reqHeaders.put(CLIENT_AUTH_HEADER, auth);
        }
    }
    ByteChunk bc = new ByteChunk();
    int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders, respHeaders);
    if (expectedRC != HttpServletResponse.SC_OK) {
        assertEquals(expectedRC, rc);
        assertTrue(bc.getLength() > 0);
        if (expectedRC == HttpServletResponse.SC_UNAUTHORIZED) {
            // The server should identify the acceptable method(s)
            boolean methodFound = false;
            List<String> authHeaders = respHeaders.get(SERVER_AUTH_HEADER);
            for (String authHeader : authHeaders) {
                if (authHeader.indexOf(NICE_METHOD) > -1) {
                    methodFound = true;
                    break;
                }
            }
            assertTrue(methodFound);
        }
    } else {
        assertEquals("OK", bc.toString());
        List<String> newCookies = respHeaders.get(SERVER_COOKIE_HEADER);
        if (newCookies != null) {
            // harvest cookies whenever the server sends some new ones
            saveCookies(respHeaders);
        }
    }
}
Also used : HashMap(java.util.HashMap) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint)

Aggregations

ByteChunk (org.apache.tomcat.util.buf.ByteChunk)274 Test (org.junit.Test)201 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)180 Tomcat (org.apache.catalina.startup.Tomcat)129 Context (org.apache.catalina.Context)98 File (java.io.File)49 List (java.util.List)48 AsyncContext (javax.servlet.AsyncContext)40 HashMap (java.util.HashMap)35 Wrapper (org.apache.catalina.Wrapper)22 StandardContext (org.apache.catalina.core.StandardContext)21 ArrayList (java.util.ArrayList)20 TesterContext (org.apache.tomcat.unittest.TesterContext)18 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)16 ServletRequestWrapper (javax.servlet.ServletRequestWrapper)13 ServletResponseWrapper (javax.servlet.ServletResponseWrapper)13 ServletContext (javax.servlet.ServletContext)10 WsContextListener (org.apache.tomcat.websocket.server.WsContextListener)10 TesterAccessLogValve (org.apache.catalina.valves.TesterAccessLogValve)9 InitialContext (javax.naming.InitialContext)8