List of usage examples for org.apache.hadoop.security.authentication.client AuthenticationException AuthenticationException
public AuthenticationException(String msg)
From source file:com.bigstep.datalake.AuthToken.java
License:Apache License
public static AuthToken parse(String tokenStr) throws AuthenticationException { if (tokenStr.length() >= 2) { // strip the \" at the two ends of the tokenStr if (tokenStr.charAt(0) == '\"' && tokenStr.charAt(tokenStr.length() - 1) == '\"') { tokenStr = tokenStr.substring(1, tokenStr.length() - 1); }//from www. ja v a 2s . c om } Map<String, String> map = split(tokenStr); // remove the signature part, since client doesn't care about it map.remove("s"); if (!map.keySet().equals(ATTRIBUTES)) { throw new AuthenticationException("Invalid token string, missing attributes"); } long expires = Long.parseLong(map.get(EXPIRES)); AuthToken token = new AuthToken(map.get(USER_NAME), map.get(PRINCIPAL), map.get(TYPE)); token.setExpires(expires); return token; }
From source file:com.bigstep.datalake.AuthToken.java
License:Apache License
/** * Splits the string representation of a token into attributes pairs. * * @param tokenStr string representation of a token. * * @return a map with the attribute pairs of the token. * * @throws AuthenticationException thrown if the string representation of the token could not be broken into * attribute pairs.//w w w . j a v a 2s . co m */ private static Map<String, String> split(String tokenStr) throws AuthenticationException { Map<String, String> map = new HashMap<String, String>(); StringTokenizer st = new StringTokenizer(tokenStr, ATTR_SEPARATOR); while (st.hasMoreTokens()) { String part = st.nextToken(); int separator = part.indexOf('='); if (separator == -1) { throw new AuthenticationException("Invalid authentication token"); } String key = part.substring(0, separator); String value = part.substring(separator + 1); map.put(key, value); } return map; }
From source file:com.bigstep.datalake.KerberosIdentityAuthenticator.java
License:Apache License
/** * Implements the SPNEGO authentication sequence interaction using the current default principal * in the Kerberos cache (normally set via kinit). * * @param atoken the authentication token being used for the user. * @throws IOException if an IO error occurred. * @throws AuthenticationException if an authentication error occurred. */// w ww.j a v a2 s.c o m private void doSpnegoSequence(AuthenticatedURL.Token atoken) throws IOException, AuthenticationException { try { kerberosIdentity.doAsPriviledged(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { final Oid KERB_V5_OID = new Oid("1.2.840.113554.1.2.2"); GSSContext gssContext = null; try { GSSManager gssManager = GSSManager.getInstance(); final GSSName clientName = gssManager.createName(kerberosIdentity.getPrincipalName(), GSSName.NT_USER_NAME); LOG.info("doSpnegoSequence() using principal:" + kerberosIdentity.getPrincipalName()); final GSSCredential clientCred = gssManager.createCredential(clientName, 8 * 3600, KERB_V5_OID, GSSCredential.INITIATE_ONLY); final String applicationPrincipal = "HTTP@" + kerberosIdentity.getRealm(); final GSSName serverName = gssManager.createName(applicationPrincipal, GSSName.NT_HOSTBASED_SERVICE); gssContext = gssManager.createContext(serverName, KERB_V5_OID, clientCred, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); gssContext.requestConf(false); gssContext.requestInteg(true); byte[] inToken = new byte[0]; byte[] outToken; boolean established = false; // Loop while the context is still not established while (!established) { LOG.info("doSpnegoSequence() using token:" + new BASE64Encoder().encode(inToken)); outToken = gssContext.initSecContext(inToken, 0, 0); LOG.info("initSecContext() out token:" + new BASE64Encoder().encode(outToken)); if (outToken != null) { sendToken(outToken); } if (!gssContext.isEstablished()) { inToken = readToken(); } else { established = true; } } } finally { if (gssContext != null) { gssContext.dispose(); gssContext = null; } } return null; } }); } catch (PrivilegedActionException ex) { throw new AuthenticationException(ex.getException()); } AuthenticatedURL.extractToken(conn, atoken); }
From source file:com.bigstep.datalake.KerberosIdentityAuthenticator.java
License:Apache License
private byte[] readToken() throws IOException, AuthenticationException { int status = conn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_UNAUTHORIZED) { String authHeader = conn.getHeaderField(WWW_AUTHENTICATE); if (authHeader == null || !authHeader.trim().startsWith(NEGOTIATE)) { throw new AuthenticationException( "Invalid SPNEGO sequence, '" + WWW_AUTHENTICATE + "' header incorrect: " + authHeader); }/* ww w.j a v a2 s . c o m*/ String negotiation = authHeader.trim().substring((NEGOTIATE + " ").length()).trim(); return base64.decode(negotiation); } throw new AuthenticationException("Invalid SPNEGO sequence, status code: " + status); }
From source file:com.flipkart.fdp.migration.distcp.security.KerberosAuthenticator2.java
License:Apache License
/** * Implements the SPNEGO authentication sequence interaction using the * current default principal in the Kerberos cache (normally set via kinit). * //from w ww .j a va 2s. c o m * @param token * the authentication token being used for the user. * * @throws IOException * if an IO error occurred. * @throws AuthenticationException * if an authentication error occurred. */ private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException { try { /* * // AccessControlContext context = AccessController.getContext(); * Subject subject = Subject.getSubject(context); if (subject == * null) { subject = new Subject(); LoginContext login = new * LoginContext("", subject, null, new KerberosConfiguration()); * login.login(); } */ LoginContext loginContext = new LoginContext("", null, new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug)); loginContext.login(); // if (LOG.isDebugEnabled()) { // LOG.debug("Kerberos authenticated user: " // + loginContext.getSubject()); // } Subject subject = loginContext.getSubject(); Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { public Void run() throws Exception { GSSContext gssContext = null; try { GSSManager gssManager = GSSManager.getInstance(); Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL"); String sp = KerberosAuthenticator2.this.servicePrincipal; if (sp == null) { sp = "HTTP/" + KerberosAuthenticator2.this.url.getHost(); } GSSName serviceName = gssManager.createName(sp, oid); oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID"); gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken; boolean established = false; // Loop while the context is still not established while (!established) { outToken = gssContext.initSecContext(inToken, 0, inToken.length); if (outToken != null) { sendToken(outToken); } if (!gssContext.isEstablished()) { inToken = readToken(); } else { established = true; } } } finally { if (gssContext != null) { gssContext.dispose(); gssContext = null; } } return null; } }); } catch (PrivilegedActionException ex) { throw new AuthenticationException(ex.getException()); } catch (LoginException ex) { throw new AuthenticationException(ex); } AuthenticatedURL.extractToken(conn, token); }
From source file:io.druid.security.kerberos.DruidKerberosAuthenticationHandler.java
License:Apache License
@Override public void init(Properties config) throws ServletException { try {//from w w w. j av a 2 s.c o m 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 %s, for principal %s", keytab, spnegoPrincipal); final KerberosAuthenticator.DruidKerberosConfiguration kerberosConfiguration = new KerberosAuthenticator.DruidKerberosConfiguration( keytab, spnegoPrincipal); final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration); try { loginContext.login(); } catch (LoginException le) { log.warn(le, "Failed to login as [%s]", spnegoPrincipal); throw new AuthenticationException(le); } loginContexts.add(loginContext); } 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); } }
From source file:io.druid.security.kerberos.DruidKerberosAuthenticationHandler.java
License:Apache License
@Override public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response) throws IOException, AuthenticationException { AuthenticationToken token = null;/*from w w w. ja va 2s .com*/ String authorization = request .getHeader(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.AUTHORIZATION); if (authorization == null || !authorization .startsWith(org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE)) { return null; } else { authorization = authorization.substring( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE.length()) .trim(); final Base64 base64 = new Base64(0); final byte[] clientToken = base64.decode(authorization); final String serverName = request.getServerName(); try { token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() { @Override public AuthenticationToken run() throws Exception { AuthenticationToken token = null; GSSContext gssContext = null; GSSCredential gssCreds = null; try { gssCreds = gssManager.createCredential( gssManager.createName(KerberosUtil.getServicePrincipal("HTTP", serverName), KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL")), GSSCredential.INDEFINITE_LIFETIME, new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"), KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") }, GSSCredential.ACCEPT_ONLY); gssContext = gssManager.createContext(gssCreds); byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length); if (serverToken != null && serverToken.length > 0) { String authenticate = base64.encodeToString(serverToken); response.setHeader( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE, org.apache.hadoop.security.authentication.client.KerberosAuthenticator.NEGOTIATE + " " + authenticate); } if (!gssContext.isEstablished()) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); log.trace("SPNEGO in progress"); } else { String clientPrincipal = gssContext.getSrcName().toString(); KerberosName kerberosName = new KerberosName(clientPrincipal); String userName = kerberosName.getShortName(); token = new AuthenticationToken(userName, clientPrincipal, getType()); response.setStatus(HttpServletResponse.SC_OK); log.trace("SPNEGO completed for principal [%s]", clientPrincipal); } } finally { if (gssContext != null) { gssContext.dispose(); } if (gssCreds != null) { gssCreds.dispose(); } } return token; } }); } catch (PrivilegedActionException ex) { if (ex.getException() instanceof IOException) { throw (IOException) ex.getException(); } else { throw new AuthenticationException(ex.getException()); } } } return token; }
From source file:io.druid.security.kerberos.DruidKerberosUtil.java
License:Apache License
/** * This method always needs to be called within a doAs block so that the client's TGT credentials * can be read from the Subject./*from w ww .ja va 2 s . com*/ * * @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), StandardCharsets.US_ASCII); } catch (GSSException | IllegalAccessException | NoSuchFieldException | ClassNotFoundException e) { throw new AuthenticationException(e); } finally { kerberosLock.unlock(); } }
From source file:io.druid.security.kerberos.KerberosAuthenticator.java
License:Apache License
@Override public Filter getFilter() { return new AuthenticationFilter() { private Signer mySigner; @Override// www . j a va 2 s .com public void init(FilterConfig filterConfig) throws ServletException { ClassLoader prevLoader = Thread.currentThread().getContextClassLoader(); try { // AuthenticationHandler is created during Authenticationfilter.init using reflection with thread context class loader. // In case of druid since the class is actually loaded as an extension and filter init is done in main thread. // We need to set the classloader explicitly to extension class loader. Thread.currentThread().setContextClassLoader(AuthenticationFilter.class.getClassLoader()); super.init(filterConfig); String configPrefix = filterConfig.getInitParameter(CONFIG_PREFIX); configPrefix = (configPrefix != null) ? configPrefix + "." : ""; Properties config = getConfiguration(configPrefix, filterConfig); String signatureSecret = config.getProperty(configPrefix + SIGNATURE_SECRET); if (signatureSecret == null) { signatureSecret = Long.toString(new Random().nextLong()); log.warn("'signature.secret' configuration not set, using a random value as secret"); } final byte[] secretBytes = StringUtils.toUtf8(signatureSecret); SignerSecretProvider signerSecretProvider = new SignerSecretProvider() { @Override public void init(Properties config, ServletContext servletContext, long tokenValidity) throws Exception { } @Override public byte[] getCurrentSecret() { return secretBytes; } @Override public byte[][] getAllSecrets() { return new byte[][] { secretBytes }; } }; mySigner = new Signer(signerSecretProvider); } finally { Thread.currentThread().setContextClassLoader(prevLoader); } } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling in doFilterSuper @Override 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(); try { tokenStr = mySigner.verifyAndExtract(tokenStr); } catch (SignerException ex) { throw new AuthenticationException(ex); } break; } } } if (tokenStr != null) { token = AuthenticationToken.parse(tokenStr); if (!token.getType().equals(getAuthenticationHandler().getType())) { throw new AuthenticationException("Invalid AuthenticationToken type"); } if (token.isExpired()) { throw new AuthenticationException("AuthenticationToken expired"); } } return token; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; // If there's already an auth result, then we have authenticated already, skip this. if (request.getAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT) != null) { filterChain.doFilter(request, response); return; } if (loginContext == null) { initializeKerberosLogin(); } String path = ((HttpServletRequest) request).getRequestURI(); if (isExcluded(path)) { filterChain.doFilter(request, response); } else { String clientPrincipal = null; try { Cookie[] cookies = httpReq.getCookies(); if (cookies == null) { clientPrincipal = getPrincipalFromRequestNew((HttpServletRequest) request); } else { clientPrincipal = null; for (Cookie cookie : cookies) { if ("hadoop.auth".equals(cookie.getName())) { Matcher matcher = HADOOP_AUTH_COOKIE_REGEX.matcher(cookie.getValue()); if (matcher.matches()) { clientPrincipal = matcher.group(1); break; } } } } } catch (Exception ex) { clientPrincipal = null; } if (clientPrincipal != null) { request.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, new AuthenticationResult(clientPrincipal, authorizerName, null)); } } doFilterSuper(request, response, filterChain); } // Copied from hadoop-auth's AuthenticationFilter, to allow us to change error response handling private void doFilterSuper(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 (getAuthenticationHandler().managementOperation(token, httpRequest, httpResponse)) { if (token == null) { if (log.isDebugEnabled()) { log.debug("Request [{%s}] triggering authentication", getRequestURL(httpRequest)); } token = getAuthenticationHandler().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 [{%s}] user [{%s}] 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 = mySigner.sign(token.toString()); createAuthCookie(httpResponse, signedToken, getCookieDomain(), getCookiePath(), token.getExpires(), 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, isHttps); // If response code is 401. Then WWW-Authenticate Header should be // present.. reset to 403 if not found.. if ((errCode == HttpServletResponse.SC_UNAUTHORIZED) && (!httpResponse.containsHeader( org.apache.hadoop.security.authentication.client.KerberosAuthenticator.WWW_AUTHENTICATE))) { errCode = HttpServletResponse.SC_FORBIDDEN; } if (authenticationEx == null) { // Don't send an error response here, unlike the base AuthenticationFilter implementation. // This request did not use Kerberos auth. // Instead, we will send an error response in PreResponseAuthorizationCheckFilter to allow // other Authenticator implementations to check the request. filterChain.doFilter(request, response); } else { // Do send an error response here, we attempted Kerberos authentication and failed. httpResponse.sendError(errCode, authenticationEx.getMessage()); } } } } }; }
From source file:main.client.http.KerberosAuthenticator2.java
License:Apache License
/** * Implements the SPNEGO authentication sequence interaction using the * current default principal in the Kerberos cache (normally set via kinit). * //from w w w .j a v a 2 s .c o m * @param token * the authentication token being used for the user. * * @throws IOException * if an IO error occurred. * @throws AuthenticationException * if an authentication error occurred. */ private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException { try { /* // AccessControlContext context = AccessController.getContext(); Subject subject = Subject.getSubject(context); if (subject == null) { subject = new Subject(); LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration()); login.login(); } */ LoginContext loginContext = new LoginContext("", null, new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug)); loginContext.login(); if (LOG.isDebugEnabled()) { LOG.debug("Kerberos authenticated user: " + loginContext.getSubject()); } Subject subject = loginContext.getSubject(); Subject.doAs(subject, new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { GSSContext gssContext = null; try { GSSManager gssManager = GSSManager.getInstance(); String servicePrincipal = "HTTP/" + KerberosAuthenticator2.this.url.getHost(); Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL"); GSSName serviceName = gssManager.createName(servicePrincipal, oid); oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID"); gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME); gssContext.requestCredDeleg(true); gssContext.requestMutualAuth(true); byte[] inToken = new byte[0]; byte[] outToken; boolean established = false; // Loop while the context is still not established while (!established) { outToken = gssContext.initSecContext(inToken, 0, inToken.length); if (outToken != null) { sendToken(outToken); } if (!gssContext.isEstablished()) { inToken = readToken(); } else { established = true; } } } finally { if (gssContext != null) { gssContext.dispose(); gssContext = null; } } return null; } }); } catch (PrivilegedActionException ex) { throw new AuthenticationException(ex.getException()); } catch (LoginException ex) { throw new AuthenticationException(ex); } AuthenticatedURL.extractToken(conn, token); }