Search in sources :

Example 46 with GSSContext

use of org.ietf.jgss.GSSContext in project cxf by apache.

the class KerberosAuthenticationFilter method filter.

@Override
public void filter(ContainerRequestContext context) {
    List<String> authHeaders = messageContext.getHttpHeaders().getRequestHeader(HttpHeaders.AUTHORIZATION);
    if (authHeaders == null || authHeaders.size() != 1) {
        LOG.fine("No Authorization header is available");
        throw ExceptionUtils.toNotAuthorizedException(null, getFaultResponse());
    }
    String[] authPair = authHeaders.get(0).split(" ");
    if (authPair.length != 2 || !NEGOTIATE_SCHEME.equalsIgnoreCase(authPair[0])) {
        LOG.fine("Negotiate Authorization scheme is expected");
        throw ExceptionUtils.toNotAuthorizedException(null, getFaultResponse());
    }
    byte[] serviceTicket = getServiceTicket(authPair[1]);
    try {
        Subject serviceSubject = loginAndGetSubject();
        GSSContext gssContext = createGSSContext();
        Subject.doAs(serviceSubject, new ValidateServiceTicketAction(gssContext, serviceTicket));
        GSSName srcName = gssContext.getSrcName();
        if (srcName == null) {
            throw ExceptionUtils.toNotAuthorizedException(null, getFaultResponse());
        }
        String complexUserName = srcName.toString();
        String simpleUserName = complexUserName;
        int index = simpleUserName.lastIndexOf('@');
        if (index > 0) {
            simpleUserName = simpleUserName.substring(0, index);
        }
        Message m = JAXRSUtils.getCurrentMessage();
        m.put(SecurityContext.class, createSecurityContext(simpleUserName, complexUserName, gssContext));
        if (!gssContext.getCredDelegState()) {
            gssContext.dispose();
        }
    } catch (LoginException e) {
        LOG.fine("Unsuccessful JAAS login for the service principal: " + e.getMessage());
        throw ExceptionUtils.toNotAuthorizedException(e, getFaultResponse());
    } catch (GSSException e) {
        LOG.fine("GSS API exception: " + e.getMessage());
        throw ExceptionUtils.toNotAuthorizedException(e, getFaultResponse());
    } catch (PrivilegedActionException e) {
        LOG.fine("PrivilegedActionException: " + e.getMessage());
        throw ExceptionUtils.toNotAuthorizedException(e, getFaultResponse());
    }
}
Also used : GSSName(org.ietf.jgss.GSSName) Message(org.apache.cxf.message.Message) PrivilegedActionException(java.security.PrivilegedActionException) Subject(javax.security.auth.Subject) GSSException(org.ietf.jgss.GSSException) GSSContext(org.ietf.jgss.GSSContext) LoginException(javax.security.auth.login.LoginException)

Example 47 with GSSContext

use of org.ietf.jgss.GSSContext in project cxf by apache.

the class AbstractSpnegoAuthSupplier method getToken.

/**
 * Create and return a service ticket token for a given service principal
 * name
 *
 * @param authPolicy
 * @param spn
 * @return service ticket token
 * @throws GSSException
 * @throws LoginException
 */
private byte[] getToken(AuthorizationPolicy authPolicy, String spn, Oid oid, Message message) throws GSSException, LoginException {
    GSSCredential delegatedCred = (GSSCredential) message.getContextualProperty(GSSCredential.class.getName());
    Subject subject = null;
    if (authPolicy != null && delegatedCred == null) {
        String contextName = authPolicy.getAuthorization();
        if (contextName == null) {
            contextName = "";
        }
        if (!(StringUtils.isEmpty(authPolicy.getUserName()) && StringUtils.isEmpty(contextName) && loginConfig == null)) {
            CallbackHandler callbackHandler = getUsernamePasswordHandler(authPolicy.getUserName(), authPolicy.getPassword());
            LoginContext lc = new LoginContext(contextName, null, callbackHandler, loginConfig);
            lc.login();
            subject = lc.getSubject();
        }
    }
    GSSManager manager = GSSManager.getInstance();
    GSSName serverName = manager.createName(spn, serviceNameType);
    GSSContext context = manager.createContext(serverName.canonicalize(oid), oid, delegatedCred, GSSContext.DEFAULT_LIFETIME);
    context.requestCredDeleg(isCredDelegationRequired(message));
    // If the delegated cred is not null then we only need the context to
    // immediately return a ticket based on this credential without attempting
    // to log on again
    final byte[] token = new byte[0];
    if (delegatedCred != null) {
        return context.initSecContext(token, 0, token.length);
    }
    decorateSubject(subject);
    try {
        return Subject.doAs(subject, new CreateServiceTicketAction(context, token));
    } catch (PrivilegedActionException e) {
        if (e.getCause() instanceof GSSException) {
            throw (GSSException) e.getCause();
        }
        LOG.log(Level.SEVERE, "initSecContext", e);
        return null;
    }
}
Also used : GSSName(org.ietf.jgss.GSSName) NamePasswordCallbackHandler(org.apache.cxf.interceptor.security.NamePasswordCallbackHandler) CallbackHandler(javax.security.auth.callback.CallbackHandler) LoginContext(javax.security.auth.login.LoginContext) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) PrivilegedActionException(java.security.PrivilegedActionException) GSSManager(org.ietf.jgss.GSSManager) GSSContext(org.ietf.jgss.GSSContext) Subject(javax.security.auth.Subject)

Example 48 with GSSContext

use of org.ietf.jgss.GSSContext in project async-http-client by AsyncHttpClient.

the class SpnegoEngine method generateToken.

public String generateToken(String host) throws SpnegoEngineException {
    GSSContext gssContext = null;
    // base64 decoded challenge
    byte[] token = null;
    Oid negotiationOid;
    try {
        /*
       * Using the SPNEGO OID is the correct method. Kerberos v5 works for IIS but not JBoss. Unwrapping the initial token when using SPNEGO OID looks like what is described
       * here...
       *
       * http://msdn.microsoft.com/en-us/library/ms995330.aspx
       *
       * Another helpful URL...
       *
       * http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/tsec_SPNEGO_token.html
       *
       * Unfortunately SPNEGO is JRE >=1.6.
       */
        // Try SPNEGO by default, fall back to Kerberos later if error
        negotiationOid = new Oid(SPNEGO_OID);
        boolean tryKerberos = false;
        String spn = getCompleteServicePrincipalName(host);
        try {
            GSSManager manager = GSSManager.getInstance();
            GSSName serverName = manager.createName(spn, GSSName.NT_HOSTBASED_SERVICE);
            GSSCredential myCred = null;
            if (username != null || loginContextName != null || (customLoginConfig != null && !customLoginConfig.isEmpty())) {
                String contextName = loginContextName;
                if (contextName == null) {
                    contextName = "";
                }
                LoginContext loginContext = new LoginContext(contextName, null, getUsernamePasswordHandler(), getLoginConfiguration());
                loginContext.login();
                final Oid negotiationOidFinal = negotiationOid;
                final PrivilegedExceptionAction<GSSCredential> action = () -> manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, negotiationOidFinal, GSSCredential.INITIATE_AND_ACCEPT);
                myCred = Subject.doAs(loginContext.getSubject(), action);
            }
            gssContext = manager.createContext(useCanonicalHostname ? serverName.canonicalize(negotiationOid) : serverName, negotiationOid, myCred, GSSContext.DEFAULT_LIFETIME);
            gssContext.requestMutualAuth(true);
            gssContext.requestCredDeleg(true);
        } catch (GSSException ex) {
            log.error("generateToken", ex);
            // Rethrow any other exception.
            if (ex.getMajor() == GSSException.BAD_MECH) {
                log.debug("GSSException BAD_MECH, retry with Kerberos MECH");
                tryKerberos = true;
            } else {
                throw ex;
            }
        }
        if (tryKerberos) {
            /* Kerberos v5 GSS-API mechanism defined in RFC 1964. */
            log.debug("Using Kerberos MECH {}", KERBEROS_OID);
            negotiationOid = new Oid(KERBEROS_OID);
            GSSManager manager = GSSManager.getInstance();
            GSSName serverName = manager.createName(spn, GSSName.NT_HOSTBASED_SERVICE);
            gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, GSSContext.DEFAULT_LIFETIME);
            gssContext.requestMutualAuth(true);
            gssContext.requestCredDeleg(true);
        }
        // TODO suspicious: this will always be null because no value has been assigned before. Assign directly?
        if (token == null) {
            token = new byte[0];
        }
        token = gssContext.initSecContext(token, 0, token.length);
        if (token == null) {
            throw new SpnegoEngineException("GSS security context initialization failed");
        }
        /*
       * IIS accepts Kerberos and SPNEGO tokens. Some other servers Jboss, Glassfish? seem to only accept SPNEGO. Below wraps Kerberos into SPNEGO token.
       */
        if (spnegoGenerator != null && negotiationOid.toString().equals(KERBEROS_OID)) {
            token = spnegoGenerator.generateSpnegoDERObject(token);
        }
        gssContext.dispose();
        String tokenstr = Base64.getEncoder().encodeToString(token);
        log.debug("Sending response '{}' back to the server", tokenstr);
        return tokenstr;
    } catch (GSSException gsse) {
        log.error("generateToken", gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
            throw new SpnegoEngineException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.NO_CRED)
            throw new SpnegoEngineException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new SpnegoEngineException(gsse.getMessage(), gsse);
        // other error
        throw new SpnegoEngineException(gsse.getMessage());
    } catch (IOException | LoginException | PrivilegedActionException ex) {
        throw new SpnegoEngineException(ex.getMessage());
    }
}
Also used : GSSName(org.ietf.jgss.GSSName) PrivilegedActionException(java.security.PrivilegedActionException) Oid(org.ietf.jgss.Oid) IOException(java.io.IOException) LoginContext(javax.security.auth.login.LoginContext) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) GSSContext(org.ietf.jgss.GSSContext) GSSManager(org.ietf.jgss.GSSManager) LoginException(javax.security.auth.login.LoginException)

Example 49 with GSSContext

use of org.ietf.jgss.GSSContext in project qpid-broker-j by apache.

the class SpnegoAuthenticator method doAuthenticate.

private AuthenticationResult doAuthenticate(final Subject subject, final byte[] negotiateToken) {
    GSSContext context = null;
    try {
        final int credentialLifetime;
        if (String.valueOf(System.getProperty(StandardSystemProperty.JAVA_VENDOR.key())).toUpperCase().contains("IBM")) {
            credentialLifetime = GSSCredential.INDEFINITE_LIFETIME;
        } else {
            credentialLifetime = GSSCredential.DEFAULT_LIFETIME;
        }
        final GSSManager manager = GSSManager.getInstance();
        final PrivilegedExceptionAction<GSSCredential> credentialsAction = () -> manager.createCredential(null, credentialLifetime, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY);
        final GSSContext gssContext = manager.createContext(Subject.doAs(subject, credentialsAction));
        context = gssContext;
        final PrivilegedExceptionAction<byte[]> acceptAction = () -> gssContext.acceptSecContext(negotiateToken, 0, negotiateToken.length);
        final byte[] outToken = Subject.doAs(subject, acceptAction);
        if (outToken == null) {
            LOGGER.debug("Ticket validation failed");
            return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR);
        }
        final PrivilegedAction<String> authenticationAction = () -> {
            if (gssContext.isEstablished()) {
                GSSName gssName = null;
                try {
                    gssName = gssContext.getSrcName();
                } catch (final GSSException e) {
                    LOGGER.error("Unable to get src name from gss context", e);
                }
                if (gssName != null) {
                    return stripRealmNameIfRequired(gssName.toString());
                }
            }
            return null;
        };
        final String principalName = Subject.doAs(subject, authenticationAction);
        if (principalName != null) {
            TokenCarryingPrincipal principal = new TokenCarryingPrincipal() {

                private Map<String, String> _tokens = Collections.singletonMap(RESPONSE_AUTH_HEADER_NAME, NEGOTIATE_PREFIX + Base64.getEncoder().encodeToString(outToken));

                @Override
                public Map<String, String> getTokens() {
                    return _tokens;
                }

                @Override
                public ConfiguredObject<?> getOrigin() {
                    return _kerberosProvider;
                }

                @Override
                public String getName() {
                    return principalName;
                }

                @Override
                public boolean equals(final Object o) {
                    if (this == o) {
                        return true;
                    }
                    if (!(o instanceof TokenCarryingPrincipal)) {
                        return false;
                    }
                    final TokenCarryingPrincipal that = (TokenCarryingPrincipal) o;
                    if (!getName().equals(that.getName())) {
                        return false;
                    }
                    if (!getTokens().equals(that.getTokens())) {
                        return false;
                    }
                    return getOrigin() != null ? getOrigin().equals(that.getOrigin()) : that.getOrigin() == null;
                }

                @Override
                public int hashCode() {
                    int result = getName().hashCode();
                    result = 31 * result + (getOrigin() != null ? getOrigin().hashCode() : 0);
                    result = 31 * result + getTokens().hashCode();
                    return result;
                }
            };
            return new AuthenticationResult(principal);
        }
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR);
    } catch (GSSException e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Ticket validation failed", e);
        }
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    } catch (PrivilegedActionException e) {
        final Exception cause = e.getException();
        if (cause instanceof GSSException) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Service login failed", e);
            }
        } else {
            LOGGER.error("Service login failed", e);
        }
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    } finally {
        if (context != null) {
            try {
                context.dispose();
            } catch (GSSException e) {
            // Ignore
            }
        }
    }
}
Also used : GSSName(org.ietf.jgss.GSSName) PrivilegedActionException(java.security.PrivilegedActionException) Oid(org.ietf.jgss.Oid) TokenCarryingPrincipal(org.apache.qpid.server.security.TokenCarryingPrincipal) LoginException(javax.security.auth.login.LoginException) PrivilegedActionException(java.security.PrivilegedActionException) GSSException(org.ietf.jgss.GSSException) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) GSSContext(org.ietf.jgss.GSSContext) GSSManager(org.ietf.jgss.GSSManager) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) Map(java.util.Map)

Example 50 with GSSContext

use of org.ietf.jgss.GSSContext in project ats-framework by Axway.

the class GGSSchemeBase method generateGSSToken.

protected byte[] generateGSSToken(final byte[] input, final Oid oid) throws GSSException {
    byte[] token = input;
    if (token == null) {
        token = new byte[0];
    }
    GSSManager manager = getManager();
    GSSName serverName = manager.createName(servicePrincipalName, servicePrincipalOid);
    GSSContext gssContext = manager.createContext(serverName.canonicalize(oid), oid, null, GSSContext.DEFAULT_LIFETIME);
    gssContext.requestMutualAuth(true);
    gssContext.requestCredDeleg(true);
    // Get client to login if not already done
    return gssClient.negotiate(gssContext, token);
}
Also used : GSSName(org.ietf.jgss.GSSName) GSSManager(org.ietf.jgss.GSSManager) GSSContext(org.ietf.jgss.GSSContext)

Aggregations

GSSContext (org.ietf.jgss.GSSContext)55 GSSManager (org.ietf.jgss.GSSManager)37 GSSName (org.ietf.jgss.GSSName)35 Oid (org.ietf.jgss.Oid)35 GSSException (org.ietf.jgss.GSSException)29 GSSCredential (org.ietf.jgss.GSSCredential)25 Subject (javax.security.auth.Subject)19 PrivilegedActionException (java.security.PrivilegedActionException)14 LoginException (javax.security.auth.login.LoginException)14 IOException (java.io.IOException)10 LoginContext (javax.security.auth.login.LoginContext)9 Principal (java.security.Principal)5 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)5 AuthenticationException (org.apache.hadoop.security.authentication.client.AuthenticationException)5 Test (org.junit.Test)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 SecurityTest (org.apache.drill.categories.SecurityTest)3 SystemOptionManager (org.apache.drill.exec.server.options.SystemOptionManager)3 AuthenticationException (com.hortonworks.registries.auth.client.AuthenticationException)2