Search in sources :

Example 11 with Cookie

use of javax.servlet.http.Cookie in project hadoop by apache.

the class TestAmFilter method testFilter.

/**
   * Test AmIpFilter
   */
@Test(timeout = 10000)
@SuppressWarnings("deprecation")
public void testFilter() throws Exception {
    Map<String, String> params = new HashMap<String, String>();
    params.put(AmIpFilter.PROXY_HOST, proxyHost);
    params.put(AmIpFilter.PROXY_URI_BASE, proxyUri);
    FilterConfig config = new DummyFilterConfig(params);
    // dummy filter
    FilterChain chain = new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
            doFilterRequest = servletRequest.getClass().getName();
            if (servletRequest instanceof AmIpServletRequestWrapper) {
                servletWrapper = (AmIpServletRequestWrapper) servletRequest;
            }
        }
    };
    AmIpFilter testFilter = new AmIpFilter();
    testFilter.init(config);
    HttpServletResponseForTest response = new HttpServletResponseForTest();
    // Test request should implements HttpServletRequest
    ServletRequest failRequest = Mockito.mock(ServletRequest.class);
    try {
        testFilter.doFilter(failRequest, response, chain);
        fail();
    } catch (ServletException e) {
        assertEquals(ProxyUtils.E_HTTP_HTTPS_ONLY, e.getMessage());
    }
    // request with HttpServletRequest
    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getRemoteAddr()).thenReturn("nowhere");
    Mockito.when(request.getRequestURI()).thenReturn("/app/application_00_0");
    // address "redirect" is not in host list for non-proxy connection
    testFilter.doFilter(request, response, chain);
    assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, response.status);
    String redirect = response.getHeader(ProxyUtils.LOCATION);
    assertEquals("http://bogus/app/application_00_0", redirect);
    // address "redirect" is not in host list for proxy connection
    Mockito.when(request.getRequestURI()).thenReturn("/proxy/application_00_0");
    testFilter.doFilter(request, response, chain);
    assertEquals(HttpURLConnection.HTTP_MOVED_TEMP, response.status);
    redirect = response.getHeader(ProxyUtils.LOCATION);
    assertEquals("http://bogus/proxy/redirect/application_00_0", redirect);
    // "127.0.0.1" contains in host list. Without cookie
    Mockito.when(request.getRemoteAddr()).thenReturn("127.0.0.1");
    testFilter.doFilter(request, response, chain);
    assertTrue(doFilterRequest.contains("javax.servlet.http.HttpServletRequest"));
    // cookie added
    Cookie[] cookies = new Cookie[] { new Cookie(WebAppProxyServlet.PROXY_USER_COOKIE_NAME, "user") };
    Mockito.when(request.getCookies()).thenReturn(cookies);
    testFilter.doFilter(request, response, chain);
    assertEquals("org.apache.hadoop.yarn.server.webproxy.amfilter.AmIpServletRequestWrapper", doFilterRequest);
    // request contains principal from cookie
    assertEquals("user", servletWrapper.getUserPrincipal().getName());
    assertEquals("user", servletWrapper.getRemoteUser());
    assertFalse(servletWrapper.isUserInRole(""));
}
Also used : Cookie(javax.servlet.http.Cookie) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) Test(org.junit.Test)

Example 12 with Cookie

use of javax.servlet.http.Cookie in project hadoop by apache.

the class WebAppProxyServlet method methodAction.

/**
   * The action against the HTTP method.
   * @param req the HttpServletRequest
   * @param resp the HttpServletResponse
   * @param method the HTTP method
   * @throws ServletException
   * @throws IOException
   */
private void methodAction(final HttpServletRequest req, final HttpServletResponse resp, final HTTP method) throws ServletException, IOException {
    try {
        String userApprovedParamS = req.getParameter(ProxyUriUtils.PROXY_APPROVAL_PARAM);
        boolean userWasWarned = false;
        boolean userApproved = Boolean.parseBoolean(userApprovedParamS);
        boolean securityEnabled = isSecurityEnabled();
        boolean isRedirect = false;
        String pathInfo = req.getPathInfo();
        final String remoteUser = req.getRemoteUser();
        String[] parts = null;
        if (pathInfo != null) {
            // parsed
            if (pathInfo.startsWith(REDIRECT)) {
                pathInfo = pathInfo.substring(REDIRECT.length());
                isRedirect = true;
            }
            parts = pathInfo.split("/", 3);
        }
        if ((parts == null) || (parts.length < 2)) {
            LOG.warn("{} gave an invalid proxy path {}", remoteUser, pathInfo);
            notFound(resp, "Your path appears to be formatted incorrectly.");
            return;
        }
        //parts[0] is empty because path info always starts with a /
        String appId = parts[1];
        String rest = parts.length > 2 ? parts[2] : "";
        ApplicationId id = Apps.toAppID(appId);
        if (id == null) {
            LOG.warn("{} attempting to access {} that is invalid", remoteUser, appId);
            notFound(resp, appId + " appears to be formatted incorrectly.");
            return;
        }
        // already redirected the response, so we can just return.
        if (isRedirect && handleRedirect(appId, req, resp)) {
            return;
        }
        if (securityEnabled) {
            String cookieName = getCheckCookieName(id);
            Cookie[] cookies = req.getCookies();
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if (cookieName.equals(c.getName())) {
                        userWasWarned = true;
                        userApproved = userApproved || Boolean.parseBoolean(c.getValue());
                        break;
                    }
                }
            }
        }
        boolean checkUser = securityEnabled && (!userWasWarned || !userApproved);
        FetchedAppReport fetchedAppReport;
        try {
            fetchedAppReport = getFetchedAppReport(id);
        } catch (ApplicationNotFoundException e) {
            fetchedAppReport = null;
        }
        ApplicationReport applicationReport = null;
        if (fetchedAppReport != null) {
            applicationReport = fetchedAppReport.getApplicationReport();
        }
        if (applicationReport == null) {
            LOG.warn("{} attempting to access {} that was not found", remoteUser, id);
            URI toFetch = ProxyUriUtils.getUriFromTrackingPlugins(id, this.trackingUriPlugins);
            if (toFetch != null) {
                ProxyUtils.sendRedirect(req, resp, toFetch.toString());
                return;
            }
            notFound(resp, "Application " + appId + " could not be found " + "in RM or history server");
            return;
        }
        URI trackingUri = getTrackingUri(req, resp, id, applicationReport.getOriginalTrackingUrl(), fetchedAppReport.getAppReportSource());
        // If the tracking URI is null, there was a redirect, so just return.
        if (trackingUri == null) {
            return;
        }
        String runningUser = applicationReport.getUser();
        if (checkUser && !runningUser.equals(remoteUser)) {
            LOG.info("Asking {} if they want to connect to the " + "app master GUI of {} owned by {}", remoteUser, appId, runningUser);
            warnUserPage(resp, ProxyUriUtils.getPathAndQuery(id, rest, req.getQueryString(), true), runningUser, id);
            return;
        }
        // Append the user-provided path and query parameter to the original
        // tracking url.
        URI toFetch = buildTrackingUrl(trackingUri, req, rest);
        LOG.info("{} is accessing unchecked {}" + " which is the app master GUI of {} owned by {}", remoteUser, toFetch, appId, runningUser);
        switch(applicationReport.getYarnApplicationState()) {
            case KILLED:
            case FINISHED:
            case FAILED:
                ProxyUtils.sendRedirect(req, resp, toFetch.toString());
                return;
            default:
        }
        Cookie c = null;
        if (userWasWarned && userApproved) {
            c = makeCheckCookie(id, true);
        }
        proxyLink(req, resp, toFetch, c, getProxyHost(), method);
    } catch (URISyntaxException | YarnException e) {
        throw new IOException(e);
    }
}
Also used : Cookie(javax.servlet.http.Cookie) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) YarnException(org.apache.hadoop.yarn.exceptions.YarnException) ApplicationReport(org.apache.hadoop.yarn.api.records.ApplicationReport) ApplicationNotFoundException(org.apache.hadoop.yarn.exceptions.ApplicationNotFoundException) ApplicationId(org.apache.hadoop.yarn.api.records.ApplicationId) FetchedAppReport(org.apache.hadoop.yarn.server.webproxy.AppReportFetcher.FetchedAppReport)

Example 13 with Cookie

use of javax.servlet.http.Cookie in project hive by apache.

the class ThriftHttpServlet method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String clientUserName = null;
    String clientIpAddress;
    boolean requireNewCookie = false;
    try {
        if (hiveConf.getBoolean(ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname, false)) {
            boolean continueProcessing = Utils.doXsrfFilter(request, response, null, null);
            if (!continueProcessing) {
                LOG.warn("Request did not have valid XSRF header, rejecting.");
                return;
            }
        }
        // request and validate the request cookies.
        if (isCookieAuthEnabled) {
            clientUserName = validateCookie(request);
            requireNewCookie = (clientUserName == null);
            if (requireNewCookie) {
                LOG.info("Could not validate cookie sent, will try to generate a new cookie");
            }
        }
        // depending on the server setup.
        if (clientUserName == null) {
            // For a kerberos setup
            if (isKerberosAuthMode(authType)) {
                String delegationToken = request.getHeader(HIVE_DELEGATION_TOKEN_HEADER);
                // Each http request must have an Authorization header
                if ((delegationToken != null) && (!delegationToken.isEmpty())) {
                    clientUserName = doTokenAuth(request, response);
                } else {
                    clientUserName = doKerberosAuth(request);
                }
            } else // For password based authentication
            {
                clientUserName = doPasswdAuth(request, authType);
            }
        }
        LOG.debug("Client username: " + clientUserName);
        // Set the thread local username to be used for doAs if true
        SessionManager.setUserName(clientUserName);
        // find proxy user if any from query param
        String doAsQueryParam = getDoAsQueryParam(request.getQueryString());
        if (doAsQueryParam != null) {
            SessionManager.setProxyUserName(doAsQueryParam);
        }
        clientIpAddress = request.getRemoteAddr();
        LOG.debug("Client IP Address: " + clientIpAddress);
        // Set the thread local ip address
        SessionManager.setIpAddress(clientIpAddress);
        // get forwarded hosts address
        String forwarded_for = request.getHeader(X_FORWARDED_FOR);
        if (forwarded_for != null) {
            LOG.debug("{}:{}", X_FORWARDED_FOR, forwarded_for);
            List<String> forwardedAddresses = Arrays.asList(forwarded_for.split(","));
            SessionManager.setForwardedAddresses(forwardedAddresses);
        } else {
            SessionManager.setForwardedAddresses(Collections.<String>emptyList());
        }
        // Generate new cookie and add it to the response
        if (requireNewCookie && !authType.equalsIgnoreCase(HiveAuthFactory.AuthTypes.NOSASL.toString())) {
            String cookieToken = HttpAuthUtils.createCookieToken(clientUserName);
            Cookie hs2Cookie = createCookie(signer.signCookie(cookieToken));
            if (isHttpOnlyCookie) {
                response.setHeader("SET-COOKIE", getHttpOnlyCookieHeader(hs2Cookie));
            } else {
                response.addCookie(hs2Cookie);
            }
            LOG.info("Cookie added for clientUserName " + clientUserName);
        }
        super.doPost(request, response);
    } catch (HttpAuthenticationException e) {
        LOG.error("Error: ", e);
        // Send a 401 to the client
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (isKerberosAuthMode(authType)) {
            response.addHeader(HttpAuthUtils.WWW_AUTHENTICATE, HttpAuthUtils.NEGOTIATE);
        }
        response.getWriter().println("Authentication Error: " + e.getMessage());
    } finally {
        // Clear the thread locals
        SessionManager.clearUserName();
        SessionManager.clearIpAddress();
        SessionManager.clearProxyUserName();
        SessionManager.clearForwardedAddresses();
    }
}
Also used : NewCookie(javax.ws.rs.core.NewCookie) Cookie(javax.servlet.http.Cookie) HttpAuthenticationException(org.apache.hive.service.auth.HttpAuthenticationException)

Example 14 with Cookie

use of javax.servlet.http.Cookie 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 15 with Cookie

use of javax.servlet.http.Cookie in project tomcat by apache.

the class RequestDumperFilter method doFilter.

/**
     * Log the interesting request parameters, invoke the next Filter in the
     * sequence, and log the interesting response parameters.
     *
     * @param request  The servlet request to be processed
     * @param response The servlet response to be created
     * @param chain    The filter chain being processed
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest hRequest = null;
    HttpServletResponse hResponse = null;
    if (request instanceof HttpServletRequest) {
        hRequest = (HttpServletRequest) request;
    }
    if (response instanceof HttpServletResponse) {
        hResponse = (HttpServletResponse) response;
    }
    // Log pre-service information
    doLog("START TIME        ", getTimestamp());
    if (hRequest == null) {
        doLog("        requestURI", NON_HTTP_REQ_MSG);
        doLog("          authType", NON_HTTP_REQ_MSG);
    } else {
        doLog("        requestURI", hRequest.getRequestURI());
        doLog("          authType", hRequest.getAuthType());
    }
    doLog(" characterEncoding", request.getCharacterEncoding());
    doLog("     contentLength", Long.toString(request.getContentLengthLong()));
    doLog("       contentType", request.getContentType());
    if (hRequest == null) {
        doLog("       contextPath", NON_HTTP_REQ_MSG);
        doLog("            cookie", NON_HTTP_REQ_MSG);
        doLog("            header", NON_HTTP_REQ_MSG);
    } else {
        doLog("       contextPath", hRequest.getContextPath());
        Cookie[] cookies = hRequest.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                doLog("            cookie", cookies[i].getName() + "=" + cookies[i].getValue());
            }
        }
        Enumeration<String> hnames = hRequest.getHeaderNames();
        while (hnames.hasMoreElements()) {
            String hname = hnames.nextElement();
            Enumeration<String> hvalues = hRequest.getHeaders(hname);
            while (hvalues.hasMoreElements()) {
                String hvalue = hvalues.nextElement();
                doLog("            header", hname + "=" + hvalue);
            }
        }
    }
    doLog("            locale", request.getLocale().toString());
    if (hRequest == null) {
        doLog("            method", NON_HTTP_REQ_MSG);
    } else {
        doLog("            method", hRequest.getMethod());
    }
    Enumeration<String> pnames = request.getParameterNames();
    while (pnames.hasMoreElements()) {
        String pname = pnames.nextElement();
        String[] pvalues = request.getParameterValues(pname);
        StringBuilder result = new StringBuilder(pname);
        result.append('=');
        for (int i = 0; i < pvalues.length; i++) {
            if (i > 0) {
                result.append(", ");
            }
            result.append(pvalues[i]);
        }
        doLog("         parameter", result.toString());
    }
    if (hRequest == null) {
        doLog("          pathInfo", NON_HTTP_REQ_MSG);
    } else {
        doLog("          pathInfo", hRequest.getPathInfo());
    }
    doLog("          protocol", request.getProtocol());
    if (hRequest == null) {
        doLog("       queryString", NON_HTTP_REQ_MSG);
    } else {
        doLog("       queryString", hRequest.getQueryString());
    }
    doLog("        remoteAddr", request.getRemoteAddr());
    doLog("        remoteHost", request.getRemoteHost());
    if (hRequest == null) {
        doLog("        remoteUser", NON_HTTP_REQ_MSG);
        doLog("requestedSessionId", NON_HTTP_REQ_MSG);
    } else {
        doLog("        remoteUser", hRequest.getRemoteUser());
        doLog("requestedSessionId", hRequest.getRequestedSessionId());
    }
    doLog("            scheme", request.getScheme());
    doLog("        serverName", request.getServerName());
    doLog("        serverPort", Integer.toString(request.getServerPort()));
    if (hRequest == null) {
        doLog("       servletPath", NON_HTTP_REQ_MSG);
    } else {
        doLog("       servletPath", hRequest.getServletPath());
    }
    doLog("          isSecure", Boolean.valueOf(request.isSecure()).toString());
    doLog("------------------", "--------------------------------------------");
    // Perform the request
    chain.doFilter(request, response);
    // Log post-service information
    doLog("------------------", "--------------------------------------------");
    if (hRequest == null) {
        doLog("          authType", NON_HTTP_REQ_MSG);
    } else {
        doLog("          authType", hRequest.getAuthType());
    }
    doLog("       contentType", response.getContentType());
    if (hResponse == null) {
        doLog("            header", NON_HTTP_RES_MSG);
    } else {
        Iterable<String> rhnames = hResponse.getHeaderNames();
        for (String rhname : rhnames) {
            Iterable<String> rhvalues = hResponse.getHeaders(rhname);
            for (String rhvalue : rhvalues) {
                doLog("            header", rhname + "=" + rhvalue);
            }
        }
    }
    if (hRequest == null) {
        doLog("        remoteUser", NON_HTTP_REQ_MSG);
    } else {
        doLog("        remoteUser", hRequest.getRemoteUser());
    }
    if (hResponse == null) {
        doLog("        remoteUser", NON_HTTP_RES_MSG);
    } else {
        doLog("            status", Integer.toString(hResponse.getStatus()));
    }
    doLog("END TIME          ", getTimestamp());
    doLog("==================", "============================================");
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Cookie(javax.servlet.http.Cookie) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Aggregations

Cookie (javax.servlet.http.Cookie)522 Test (org.junit.Test)207 HttpServletRequest (javax.servlet.http.HttpServletRequest)84 HttpServletResponse (javax.servlet.http.HttpServletResponse)61 IOException (java.io.IOException)45 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)44 ServletException (javax.servlet.ServletException)40 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)32 HashMap (java.util.HashMap)28 HttpSession (javax.servlet.http.HttpSession)26 Locale (java.util.Locale)23 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)23 HttpCookie (java.net.HttpCookie)19 Properties (java.util.Properties)19 Date (java.util.Date)18 PrintWriter (java.io.PrintWriter)17 ArrayList (java.util.ArrayList)17 Map (java.util.Map)16 MvcResult (org.springframework.test.web.servlet.MvcResult)15 ResultMatcher (org.springframework.test.web.servlet.ResultMatcher)15