Search in sources :

Example 11 with AuthenticationException

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

the class KMSClientProvider method call.

private <T> T call(HttpURLConnection conn, Map jsonOutput, int expectedResponse, Class<T> klass, int authRetryCount) throws IOException {
    T ret = null;
    try {
        if (jsonOutput != null) {
            writeJson(jsonOutput, conn.getOutputStream());
        }
    } catch (IOException ex) {
        IOUtils.closeStream(conn.getInputStream());
        throw ex;
    }
    if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) || conn.getResponseMessage().contains(INVALID_SIGNATURE))) || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        // Ideally, this should happen only when there is an Authentication
        // failure. Unfortunately, the AuthenticationFilter returns 403 when it
        // cannot authenticate (Since a 401 requires Server to send
        // WWW-Authenticate header as well)..
        KMSClientProvider.this.authToken = new DelegationTokenAuthenticatedURL.Token();
        if (authRetryCount > 0) {
            String contentType = conn.getRequestProperty(CONTENT_TYPE);
            String requestMethod = conn.getRequestMethod();
            URL url = conn.getURL();
            conn = createConnection(url, requestMethod);
            conn.setRequestProperty(CONTENT_TYPE, contentType);
            return call(conn, jsonOutput, expectedResponse, klass, authRetryCount - 1);
        }
    }
    try {
        AuthenticatedURL.extractToken(conn, authToken);
    } catch (AuthenticationException e) {
    // Ignore the AuthExceptions.. since we are just using the method to
    // extract and set the authToken.. (Workaround till we actually fix
    // AuthenticatedURL properly to set authToken post initialization)
    }
    HttpExceptionUtils.validateResponse(conn, expectedResponse);
    if (conn.getContentType() != null && conn.getContentType().trim().toLowerCase().startsWith(APPLICATION_JSON_MIME) && klass != null) {
        ObjectMapper mapper = new ObjectMapper();
        InputStream is = null;
        try {
            is = conn.getInputStream();
            ret = mapper.readValue(is, klass);
        } finally {
            IOUtils.closeStream(is);
        }
    }
    return ret;
}
Also used : DelegationTokenAuthenticatedURL(org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticatedURL) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) InputStream(java.io.InputStream) IOException(java.io.IOException) URL(java.net.URL) AuthenticatedURL(org.apache.hadoop.security.authentication.client.AuthenticatedURL) DelegationTokenAuthenticatedURL(org.apache.hadoop.security.token.delegation.web.DelegationTokenAuthenticatedURL) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 12 with AuthenticationException

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

the class TestWebDelegationToken method testKerberosDelegationTokenAuthenticator.

private void testKerberosDelegationTokenAuthenticator(final boolean doAs) throws Exception {
    final String doAsUser = doAs ? OK_USER : null;
    // setting hadoop security to kerberos
    org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();
    conf.set("hadoop.security.authentication", "kerberos");
    UserGroupInformation.setConfiguration(conf);
    File testDir = new File("target/" + UUID.randomUUID().toString());
    Assert.assertTrue(testDir.mkdirs());
    MiniKdc kdc = new MiniKdc(MiniKdc.createConf(), testDir);
    final Server jetty = createJettyServer();
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/foo");
    jetty.setHandler(context);
    context.addFilter(new FilterHolder(KDTAFilter.class), "/*", EnumSet.of(DispatcherType.REQUEST));
    context.addServlet(new ServletHolder(UserServlet.class), "/bar");
    try {
        kdc.start();
        File keytabFile = new File(testDir, "test.keytab");
        kdc.createPrincipal(keytabFile, "client", "HTTP/localhost");
        KDTAFilter.keytabFile = keytabFile.getAbsolutePath();
        jetty.start();
        final DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token();
        final DelegationTokenAuthenticatedURL aUrl = new DelegationTokenAuthenticatedURL();
        final URL url = new URL(getJettyURL() + "/foo/bar");
        try {
            aUrl.getDelegationToken(url, token, FOO_USER, doAsUser);
            Assert.fail();
        } catch (AuthenticationException ex) {
            Assert.assertTrue(ex.getMessage().contains("GSSException"));
        }
        doAsKerberosUser("client", keytabFile.getAbsolutePath(), new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                aUrl.getDelegationToken(url, token, doAs ? doAsUser : "client", doAsUser);
                Assert.assertNotNull(token.getDelegationToken());
                Assert.assertEquals(new Text("token-kind"), token.getDelegationToken().getKind());
                // Make sure the token belongs to the right owner
                ByteArrayInputStream buf = new ByteArrayInputStream(token.getDelegationToken().getIdentifier());
                DataInputStream dis = new DataInputStream(buf);
                DelegationTokenIdentifier id = new DelegationTokenIdentifier(new Text("token-kind"));
                id.readFields(dis);
                dis.close();
                Assert.assertEquals(doAs ? new Text(OK_USER) : new Text("client"), id.getOwner());
                if (doAs) {
                    Assert.assertEquals(new Text("client"), id.getRealUser());
                }
                aUrl.renewDelegationToken(url, token, doAsUser);
                Assert.assertNotNull(token.getDelegationToken());
                aUrl.getDelegationToken(url, token, FOO_USER, doAsUser);
                Assert.assertNotNull(token.getDelegationToken());
                try {
                    aUrl.renewDelegationToken(url, token, doAsUser);
                    Assert.fail();
                } catch (Exception ex) {
                    Assert.assertTrue(ex.getMessage().contains("403"));
                }
                aUrl.getDelegationToken(url, token, FOO_USER, doAsUser);
                aUrl.cancelDelegationToken(url, token, doAsUser);
                Assert.assertNull(token.getDelegationToken());
                return null;
            }
        });
    } finally {
        jetty.stop();
        kdc.stop();
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Configuration(javax.security.auth.login.Configuration) 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) MiniKdc(org.apache.hadoop.minikdc.MiniKdc) Text(org.apache.hadoop.io.Text) DataInputStream(java.io.DataInputStream) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) ServletException(javax.servlet.ServletException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) File(java.io.File)

Example 13 with AuthenticationException

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

the class DFSck method listCorruptFileBlocks.

/*
   * To get the list, we need to call iteratively until the server says
   * there is no more left.
   */
private Integer listCorruptFileBlocks(String dir, String baseUrl) throws IOException {
    int errCode = -1;
    int numCorrupt = 0;
    int cookie = 0;
    final String noCorruptLine = "has no CORRUPT files";
    final String noMoreCorruptLine = "has no more CORRUPT files";
    final String cookiePrefix = "Cookie:";
    boolean allDone = false;
    while (!allDone) {
        final StringBuffer url = new StringBuffer(baseUrl);
        if (cookie > 0) {
            url.append("&startblockafter=").append(String.valueOf(cookie));
        }
        URL path = new URL(url.toString());
        URLConnection connection;
        try {
            connection = connectionFactory.openConnection(path, isSpnegoEnabled);
        } catch (AuthenticationException e) {
            throw new IOException(e);
        }
        InputStream stream = connection.getInputStream();
        BufferedReader input = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        try {
            String line = null;
            while ((line = input.readLine()) != null) {
                if (line.startsWith(cookiePrefix)) {
                    try {
                        cookie = Integer.parseInt(line.split("\t")[1]);
                    } catch (Exception e) {
                        allDone = true;
                        break;
                    }
                    continue;
                }
                if ((line.endsWith(noCorruptLine)) || (line.endsWith(noMoreCorruptLine)) || (line.endsWith(NamenodeFsck.NONEXISTENT_STATUS))) {
                    allDone = true;
                    break;
                }
                if ((line.isEmpty()) || (line.startsWith("FSCK started by")) || (line.startsWith("The filesystem under path")))
                    continue;
                numCorrupt++;
                if (numCorrupt == 1) {
                    out.println("The list of corrupt files under path '" + dir + "' are:");
                }
                out.println(line);
            }
        } finally {
            input.close();
        }
    }
    out.println("The filesystem under path '" + dir + "' has " + numCorrupt + " CORRUPT files");
    if (numCorrupt == 0)
        errCode = 0;
    return errCode;
}
Also used : InputStreamReader(java.io.InputStreamReader) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) URL(java.net.URL) URLConnection(java.net.URLConnection) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) IOException(java.io.IOException)

Example 14 with AuthenticationException

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

the class DruidKerberosUtil method kerberosChallenge.

/**
   * This method always needs to be called within a doAs block so that the client's TGT credentials
   * can be read from the Subject.
   *
   * @return Kerberos Challenge String
   *
   * @throws Exception
   */
public static String kerberosChallenge(String server) throws AuthenticationException {
    kerberosLock.lock();
    try {
        // This Oid for Kerberos GSS-API mechanism.
        Oid mechOid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
        GSSManager manager = GSSManager.getInstance();
        // GSS name for server
        GSSName serverName = manager.createName("HTTP@" + server, GSSName.NT_HOSTBASED_SERVICE);
        // Create a GSSContext for authentication with the service.
        // We're passing client credentials as null since we want them to be read from the Subject.
        GSSContext gssContext = manager.createContext(serverName.canonicalize(mechOid), mechOid, null, GSSContext.DEFAULT_LIFETIME);
        gssContext.requestMutualAuth(true);
        gssContext.requestCredDeleg(true);
        // Establish context
        byte[] inToken = new byte[0];
        byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
        gssContext.dispose();
        // Base64 encoded and stringified token for server
        return new String(base64codec.encode(outToken));
    } catch (GSSException | IllegalAccessException | NoSuchFieldException | ClassNotFoundException e) {
        throw new AuthenticationException(e);
    } finally {
        kerberosLock.unlock();
    }
}
Also used : GSSName(org.ietf.jgss.GSSName) GSSException(org.ietf.jgss.GSSException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) GSSManager(org.ietf.jgss.GSSManager) GSSContext(org.ietf.jgss.GSSContext) Oid(org.ietf.jgss.Oid)

Example 15 with AuthenticationException

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

the class AtlasAuthenticationFilter method doKerberosAuth.

/**
     * This method is copied from hadoop auth lib, code added for error handling and fallback to other auth methods
     *
     * 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 org.apache.hadoop.security.authentication.server.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.
     */
public void doKerberosAuth(ServletRequest request, ServletResponse response, FilterChain filterChainWrapper, 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());
    AuthenticationHandler authHandler = getAuthenticationHandler();
    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.getExpires() != 0 && token != AuthenticationToken.ANONYMOUS) {
                    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 (newToken && !token.isExpired() && token != AuthenticationToken.ANONYMOUS) {
                    String signedToken = signer.sign(token.toString());
                    createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), isHttps);
                }
                filterChainWrapper.doFilter(httpRequest, httpResponse);
            }
        } else {
            unauthorizedResponse = false;
        }
    } catch (AuthenticationException ex) {
        // exception from the filter itself is fatal
        errCode = HttpServletResponse.SC_FORBIDDEN;
        authenticationEx = ex;
        LOG.warn("Authentication exception: {}", ex.getMessage(), ex);
    }
    if (unauthorizedResponse) {
        if (!httpResponse.isCommitted()) {
            createAuthCookie(httpResponse, "", getCookieDomain(), getCookiePath(), 0, 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) {
                // added this code for atlas error handling and fallback
                if (!supportKeyTabBrowserLogin && isBrowser(httpRequest.getHeader("User-Agent"))) {
                    filterChain.doFilter(request, response);
                } else {
                    boolean chk = true;
                    Collection<String> headerNames = httpResponse.getHeaderNames();
                    for (String headerName : headerNames) {
                        String value = httpResponse.getHeader(headerName);
                        if (headerName.equalsIgnoreCase("Set-Cookie") && value.startsWith("ATLASSESSIONID")) {
                            chk = false;
                            break;
                        }
                    }
                    String authHeader = httpRequest.getHeader("Authorization");
                    if (authHeader == null && chk) {
                        filterChain.doFilter(request, response);
                    } else if (authHeader != null && authHeader.startsWith("Basic")) {
                        filterChain.doFilter(request, response);
                    }
                }
            } else {
                httpResponse.sendError(errCode, authenticationEx.getMessage());
            }
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) KerberosAuthenticationHandler(org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler) AuthenticationHandler(org.apache.hadoop.security.authentication.server.AuthenticationHandler) Principal(java.security.Principal)

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