Search in sources :

Example 1 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 2 with AuthenticationException

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

the class DelegationTokenAuthenticationHandler method authenticate.

/**
   * Authenticates a request looking for the <code>delegation</code>
   * query-string parameter and verifying it is a valid token. If there is not
   * <code>delegation</code> query-string parameter, it delegates the
   * authentication to the {@link KerberosAuthenticationHandler} unless it is
   * disabled.
   *
   * @param request the HTTP client request.
   * @param response the HTTP client response.
   * @return the authentication token for the authenticated request.
   * @throws IOException thrown if an IO error occurred.
   * @throws AuthenticationException thrown if the authentication failed.
   */
@SuppressWarnings("unchecked")
@Override
public AuthenticationToken authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException {
    AuthenticationToken token;
    String delegationParam = getDelegationToken(request);
    if (delegationParam != null) {
        try {
            Token<AbstractDelegationTokenIdentifier> dt = new Token();
            dt.decodeFromUrlString(delegationParam);
            UserGroupInformation ugi = tokenManager.verifyToken(dt);
            final String shortName = ugi.getShortUserName();
            // creating a ephemeral token
            token = new AuthenticationToken(shortName, ugi.getUserName(), getType());
            token.setExpires(0);
            request.setAttribute(DELEGATION_TOKEN_UGI_ATTRIBUTE, ugi);
        } catch (Throwable ex) {
            token = null;
            HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, new AuthenticationException(ex));
        }
    } else {
        token = authHandler.authenticate(request, response);
    }
    return token;
}
Also used : AbstractDelegationTokenIdentifier(org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) Token(org.apache.hadoop.security.token.Token) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 3 with AuthenticationException

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

the class DelegationTokenAuthenticationHandler method managementOperation.

@Override
@SuppressWarnings("unchecked")
public boolean managementOperation(AuthenticationToken token, HttpServletRequest request, HttpServletResponse response) throws IOException, AuthenticationException {
    boolean requestContinues = true;
    String op = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.OP_PARAM);
    op = (op != null) ? StringUtils.toUpperCase(op) : null;
    if (isManagementOperation(request)) {
        KerberosDelegationTokenAuthenticator.DelegationTokenOperation dtOp = KerberosDelegationTokenAuthenticator.DelegationTokenOperation.valueOf(op);
        if (dtOp.getHttpMethod().equals(request.getMethod())) {
            boolean doManagement;
            if (dtOp.requiresKerberosCredentials() && token == null) {
                // Don't authenticate via DT for DT ops.
                token = authHandler.authenticate(request, response);
                if (token == null) {
                    requestContinues = false;
                    doManagement = false;
                } else {
                    doManagement = true;
                }
            } else {
                doManagement = true;
            }
            if (doManagement) {
                UserGroupInformation requestUgi = (token != null) ? UserGroupInformation.createRemoteUser(token.getUserName()) : null;
                // Create the proxy user if doAsUser exists
                String doAsUser = DelegationTokenAuthenticationFilter.getDoAs(request);
                if (requestUgi != null && doAsUser != null) {
                    requestUgi = UserGroupInformation.createProxyUser(doAsUser, requestUgi);
                    try {
                        ProxyUsers.authorize(requestUgi, request.getRemoteAddr());
                    } catch (AuthorizationException ex) {
                        HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex);
                        return false;
                    }
                }
                Map map = null;
                switch(dtOp) {
                    case GETDELEGATIONTOKEN:
                        if (requestUgi == null) {
                            throw new IllegalStateException("request UGI cannot be NULL");
                        }
                        String renewer = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.RENEWER_PARAM);
                        try {
                            Token<?> dToken = tokenManager.createToken(requestUgi, renewer);
                            map = delegationTokenToJSON(dToken);
                        } catch (IOException ex) {
                            throw new AuthenticationException(ex.toString(), ex);
                        }
                        break;
                    case RENEWDELEGATIONTOKEN:
                        if (requestUgi == null) {
                            throw new IllegalStateException("request UGI cannot be NULL");
                        }
                        String tokenToRenew = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.TOKEN_PARAM);
                        if (tokenToRenew == null) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Operation [{0}] requires the parameter [{1}]", dtOp, KerberosDelegationTokenAuthenticator.TOKEN_PARAM));
                            requestContinues = false;
                        } else {
                            Token<AbstractDelegationTokenIdentifier> dt = new Token();
                            try {
                                dt.decodeFromUrlString(tokenToRenew);
                                long expirationTime = tokenManager.renewToken(dt, requestUgi.getShortUserName());
                                map = new HashMap();
                                map.put("long", expirationTime);
                            } catch (IOException ex) {
                                throw new AuthenticationException(ex.toString(), ex);
                            }
                        }
                        break;
                    case CANCELDELEGATIONTOKEN:
                        String tokenToCancel = ServletUtils.getParameter(request, KerberosDelegationTokenAuthenticator.TOKEN_PARAM);
                        if (tokenToCancel == null) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Operation [{0}] requires the parameter [{1}]", dtOp, KerberosDelegationTokenAuthenticator.TOKEN_PARAM));
                            requestContinues = false;
                        } else {
                            Token<AbstractDelegationTokenIdentifier> dt = new Token();
                            try {
                                dt.decodeFromUrlString(tokenToCancel);
                                tokenManager.cancelToken(dt, (requestUgi != null) ? requestUgi.getShortUserName() : null);
                            } catch (IOException ex) {
                                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid delegation token, cannot cancel");
                                requestContinues = false;
                            }
                        }
                        break;
                }
                if (requestContinues) {
                    response.setStatus(HttpServletResponse.SC_OK);
                    if (map != null) {
                        response.setContentType(MediaType.APPLICATION_JSON);
                        Writer writer = response.getWriter();
                        ObjectMapper jsonMapper = new ObjectMapper(jsonFactory);
                        jsonMapper.writeValue(writer, map);
                        writer.write(ENTER);
                        writer.flush();
                    }
                    requestContinues = false;
                }
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, MessageFormat.format("Wrong HTTP method [{0}] for operation [{1}], it should be " + "[{2}]", request.getMethod(), dtOp, dtOp.getHttpMethod()));
            requestContinues = false;
        }
    }
    return requestContinues;
}
Also used : AuthorizationException(org.apache.hadoop.security.authorize.AuthorizationException) AuthenticationException(org.apache.hadoop.security.authentication.client.AuthenticationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AuthenticationToken(org.apache.hadoop.security.authentication.server.AuthenticationToken) Token(org.apache.hadoop.security.token.Token) IOException(java.io.IOException) AbstractDelegationTokenIdentifier(org.apache.hadoop.security.token.delegation.AbstractDelegationTokenIdentifier) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Writer(java.io.Writer) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) UserGroupInformation(org.apache.hadoop.security.UserGroupInformation)

Example 4 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 5 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)

Aggregations

AuthenticationException (org.apache.hadoop.security.authentication.client.AuthenticationException)60 IOException (java.io.IOException)23 HttpServletRequest (javax.servlet.http.HttpServletRequest)22 HttpServletResponse (javax.servlet.http.HttpServletResponse)20 Cookie (javax.servlet.http.Cookie)18 ServletException (javax.servlet.ServletException)17 Test (org.junit.Test)17 AuthenticationToken (org.apache.hadoop.security.authentication.server.AuthenticationToken)16 Properties (java.util.Properties)14 URL (java.net.URL)11 SignedJWT (com.nimbusds.jwt.SignedJWT)10 Date (java.util.Date)9 HttpURLConnection (java.net.HttpURLConnection)8 PrivilegedActionException (java.security.PrivilegedActionException)8 AuthenticatedURL (org.apache.hadoop.security.authentication.client.AuthenticatedURL)7 GSSException (org.ietf.jgss.GSSException)7 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)6 File (java.io.File)5 InputStream (java.io.InputStream)5 Principal (java.security.Principal)5