Search in sources :

Example 26 with AuthenticationException

use of org.apache.hadoop.security.authentication.client.AuthenticationException in project hadoop by apache.

the class TestAuthenticationFilter method testGetTokenInvalidType.

@Test
public void testGetTokenInvalidType() throws Exception {
    AuthenticationFilter filter = new AuthenticationFilter();
    try {
        FilterConfig config = Mockito.mock(FilterConfig.class);
        Mockito.when(config.getInitParameter("management.operation.return")).thenReturn("true");
        Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(DummyAuthenticationHandler.class.getName());
        Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret");
        Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET, "management.operation.return")).elements());
        getMockedServletContextWithStringSigner(config);
        filter.init(config);
        AuthenticationToken token = new AuthenticationToken("u", "p", "invalidtype");
        token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
        SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider();
        Properties secretProviderProps = new Properties();
        secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET, "secret");
        secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
        Signer signer = new Signer(secretProvider);
        String tokenSigned = signer.sign(token.toString());
        Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
        HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        Mockito.when(request.getCookies()).thenReturn(new Cookie[] { cookie });
        boolean failed = false;
        try {
            filter.getToken(request);
        } catch (AuthenticationException ex) {
            Assert.assertEquals("Invalid AuthenticationToken type", ex.getMessage());
            failed = true;
        } finally {
            Assert.assertTrue("token not invalid type", failed);
        }
    } finally {
        filter.destroy();
    }
}
Also used : HttpCookie(java.net.HttpCookie) Cookie(javax.servlet.http.Cookie) SignerSecretProvider(org.apache.hadoop.security.authentication.util.SignerSecretProvider) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) Properties(java.util.Properties) Signer(org.apache.hadoop.security.authentication.util.Signer) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterConfig(javax.servlet.FilterConfig) Vector(java.util.Vector) Test(org.junit.Test)

Example 27 with AuthenticationException

use of org.apache.hadoop.security.authentication.client.AuthenticationException in project hadoop by apache.

the class TestWebDelegationToken method testDelegationTokenAuthenticatedURLWithNoDT.

// we are, also, implicitly testing  KerberosDelegationTokenAuthenticator
// fallback here
private void testDelegationTokenAuthenticatedURLWithNoDT(Class<? extends Filter> filterClass) throws Exception {
    final Server jetty = createJettyServer();
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/foo");
    jetty.setHandler(context);
    context.addFilter(new FilterHolder(filterClass), "/*", EnumSet.of(DispatcherType.REQUEST));
    context.addServlet(new ServletHolder(UserServlet.class), "/bar");
    try {
        jetty.start();
        final URL url = new URL(getJettyURL() + "/foo/bar");
        UserGroupInformation ugi = UserGroupInformation.createRemoteUser(FOO_USER);
        ugi.doAs(new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token();
                DelegationTokenAuthenticatedURL aUrl = new DelegationTokenAuthenticatedURL();
                HttpURLConnection conn = aUrl.openConnection(url, token);
                Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
                List<String> ret = IOUtils.readLines(conn.getInputStream());
                Assert.assertEquals(1, ret.size());
                Assert.assertEquals(FOO_USER, ret.get(0));
                try {
                    aUrl.getDelegationToken(url, token, FOO_USER);
                    Assert.fail();
                } catch (AuthenticationException ex) {
                    Assert.assertTrue(ex.getMessage().contains("delegation token operation"));
                }
                return null;
            }
        });
    } finally {
        jetty.stop();
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Server(org.eclipse.jetty.server.Server) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) URL(java.net.URL) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) List(java.util.List) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 28 with AuthenticationException

use of org.apache.hadoop.security.authentication.client.AuthenticationException in project hadoop by apache.

the class AuthenticationFilter method getToken.

/**
   * Returns the {@link AuthenticationToken} for the request.
   * <p>
   * It looks at the received HTTP cookies and extracts the value of the {@link AuthenticatedURL#AUTH_COOKIE}
   * if present. It verifies the signature and if correct it creates the {@link AuthenticationToken} and returns
   * it.
   * <p>
   * If this method returns <code>null</code> the filter will invoke the configured {@link AuthenticationHandler}
   * to perform user authentication.
   *
   * @param request request object.
   *
   * @return the Authentication token if the request is authenticated, <code>null</code> otherwise.
   *
   * @throws IOException thrown if an IO error occurred.
   * @throws AuthenticationException thrown if the token is invalid or if it has expired.
   */
protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String tokenStr = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                tokenStr = cookie.getValue();
                if (tokenStr.isEmpty()) {
                    throw new AuthenticationException("Unauthorized access");
                }
                try {
                    tokenStr = signer.verifyAndExtract(tokenStr);
                } catch (SignerException ex) {
                    throw new AuthenticationException(ex);
                }
                break;
            }
        }
    }
    if (tokenStr != null) {
        token = AuthenticationToken.parse(tokenStr);
        boolean match = verifyTokenType(getAuthenticationHandler(), token);
        if (!match) {
            throw new AuthenticationException("Invalid AuthenticationToken type");
        }
        if (token.isExpired()) {
            throw new AuthenticationException("AuthenticationToken expired");
        }
    }
    return token;
}
Also used : Cookie(javax.servlet.http.Cookie) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException)

Example 29 with AuthenticationException

use of org.apache.hadoop.security.authentication.client.AuthenticationException in project hadoop by apache.

the class AuthenticationFilter method doFilter.

/**
   * If the request has a valid authentication token it allows the request to continue to the target resource,
   * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}.
   *
   * @param request the request object.
   * @param response the response object.
   * @param filterChain the filter chain object.
   *
   * @throws IOException thrown if an IO error occurred.
   * @throws ServletException thrown if a processing error occurred.
   */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    boolean unauthorizedResponse = true;
    int errCode = HttpServletResponse.SC_UNAUTHORIZED;
    AuthenticationException authenticationEx = null;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    boolean isHttps = "https".equals(httpRequest.getScheme());
    try {
        boolean newToken = false;
        AuthenticationToken token;
        try {
            token = getToken(httpRequest);
        } catch (AuthenticationException ex) {
            LOG.warn("AuthenticationToken ignored: " + ex.getMessage());
            // will be sent back in a 401 unless filter authenticates
            authenticationEx = ex;
            token = null;
        }
        if (authHandler.managementOperation(token, httpRequest, httpResponse)) {
            if (token == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] triggering authentication", getRequestURL(httpRequest));
                }
                token = authHandler.authenticate(httpRequest, httpResponse);
                if (token != null && token != AuthenticationToken.ANONYMOUS) {
                    if (token.getMaxInactives() > 0) {
                        token.setMaxInactives(System.currentTimeMillis() + getMaxInactiveInterval() * 1000);
                    }
                    if (token.getExpires() != 0) {
                        token.setExpires(System.currentTimeMillis() + getValidity() * 1000);
                    }
                }
                newToken = true;
            }
            if (token != null) {
                unauthorizedResponse = false;
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Request [{}] user [{}] authenticated", getRequestURL(httpRequest), token.getUserName());
                }
                final AuthenticationToken authToken = token;
                httpRequest = new HttpServletRequestWrapper(httpRequest) {

                    @Override
                    public String getAuthType() {
                        return authToken.getType();
                    }

                    @Override
                    public String getRemoteUser() {
                        return authToken.getUserName();
                    }

                    @Override
                    public Principal getUserPrincipal() {
                        return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null;
                    }
                };
                // If the token is an old one, renew the its maxInactiveInterval.
                if (!newToken && !isCookiePersistent() && getMaxInactiveInterval() > 0) {
                    token.setMaxInactives(System.currentTimeMillis() + getMaxInactiveInterval() * 1000);
                    token.setExpires(token.getExpires());
                    newToken = true;
                }
                if (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), isCookiePersistent(), isHttps);
                }
                doFilter(filterChain, httpRequest, httpResponse);
            }
        } else {
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Authentication exception: " + ex.getMessage(), ex);
        } else {
            LOG.warn("Authentication exception: " + ex.getMessage());
        }
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, isCookiePersistent(), isHttps);
            // present.. reset to 403 if not found..
            if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader(KerberosAuthenticator.WWW_AUTHENTICATE))) {
                errCode = HttpServletResponse.SC_FORBIDDEN;
            }
            if (authenticationEx == null) {
                httpResponse.sendError(errCode, "Authentication required");
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) Principal(java.security.Principal)

Example 30 with AuthenticationException

use of org.apache.hadoop.security.authentication.client.AuthenticationException in project hadoop by apache.

the class KerberosAuthenticationHandler method init.

/**
   * Initializes the authentication handler instance.
   * <p>
   * It creates a Kerberos context using the principal and keytab specified in
   * the configuration.
   * <p>
   * This method is invoked by the {@link AuthenticationFilter#init} method.
   *
   * @param config configuration properties to initialize the handler.
   *
   * @throws ServletException thrown if the handler could not be initialized.
   */
@Override
public void init(Properties config) throws ServletException {
    try {
        String principal = config.getProperty(PRINCIPAL);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }
        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new ServletException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }
        String nameRules = config.getProperty(NAME_RULES, null);
        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }
        for (String spnegoPrincipal : spnegoPrincipals) {
            LOG.info("Login using keytab {}, for principal {}", keytab, spnegoPrincipal);
            final KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab, spnegoPrincipal);
            final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration);
            try {
                loginContext.login();
            } catch (LoginException le) {
                LOG.warn("Failed to login as [{}]", spnegoPrincipal, le);
                throw new AuthenticationException(le);
            }
            loginContexts.add(loginContext);
            KerberosName kerbName = new KerberosName(spnegoPrincipal);
            if (kerbName.getHostName() != null && kerbName.getServiceName() != null && kerbName.getServiceName().equals("HTTP")) {
                boolean added = serverPrincipalMap.put(kerbName.getHostName(), spnegoPrincipal);
                LOG.info("Map server: {} to principal: [{}], added = {}", kerbName.getHostName(), spnegoPrincipal, added);
            } else {
                LOG.warn("HTTP principal: [{}] is invalid for SPNEGO!", spnegoPrincipal);
            }
        }
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}
Also used : AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) PrivilegedActionException(java.security.PrivilegedActionException) KerberosName(org.apache.hadoop.security.authentication.util.KerberosName) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) LoginException(javax.security.auth.login.LoginException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) GSSException(org.ietf.jgss.GSSException) ServletException(javax.servlet.ServletException) LoginContext(javax.security.auth.login.LoginContext) LoginException(javax.security.auth.login.LoginException) File(java.io.File)

Aggregations

AuthenticationException (org.apache.hadoop.security.authentication.client.AuthenticationException)40 HttpServletRequest (javax.servlet.http.HttpServletRequest)18 Test (org.junit.Test)17 ServletException (javax.servlet.ServletException)16 HttpServletResponse (javax.servlet.http.HttpServletResponse)16 IOException (java.io.IOException)14 Cookie (javax.servlet.http.Cookie)14 Properties (java.util.Properties)12 SignedJWT (com.nimbusds.jwt.SignedJWT)10 Date (java.util.Date)9 URL (java.net.URL)7 AuthenticationToken (org.apache.hadoop.security.authentication.server.AuthenticationToken)6 UserGroupInformation (org.apache.hadoop.security.UserGroupInformation)5 File (java.io.File)4 InputStream (java.io.InputStream)4 HttpURLConnection (java.net.HttpURLConnection)4 PrivilegedActionException (java.security.PrivilegedActionException)4 HashMap (java.util.HashMap)4 Base64 (org.apache.commons.codec.binary.Base64)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3