Search in sources :

Example 56 with GSSManager

use of org.ietf.jgss.GSSManager 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 57 with GSSManager

use of org.ietf.jgss.GSSManager in project tigervnc by TigerVNC.

the class GSSContextKrb5 method create.

public void create(String user, String host) throws JSchException {
    try {
        // RFC 1964
        Oid krb5 = new Oid("1.2.840.113554.1.2.2");
        // Kerberos Principal Name Form
        Oid principalName = new Oid("1.2.840.113554.1.2.2.1");
        GSSManager mgr = GSSManager.getInstance();
        GSSCredential crd = null;
        /*
      try{
        GSSName _user=mgr.createName(user, principalName);
        crd=mgr.createCredential(_user,
                                 GSSCredential.DEFAULT_LIFETIME,
                                 krb5,
                                 GSSCredential.INITIATE_ONLY);
      }
      catch(GSSException crdex){
      }
      */
        String cname = host;
        try {
            cname = InetAddress.getByName(cname).getCanonicalHostName();
        } catch (UnknownHostException e) {
        }
        GSSName _host = mgr.createName("host/" + cname, principalName);
        context = mgr.createContext(_host, krb5, crd, GSSContext.DEFAULT_LIFETIME);
        // RFC4462  3.4.  GSS-API Session
        // 
        // When calling GSS_Init_sec_context(), the client MUST set
        // integ_req_flag to "true" to request that per-message integrity
        // protection be supported for this context.  In addition,
        // deleg_req_flag MAY be set to "true" to request access delegation, if
        // requested by the user.
        // 
        // Since the user authentication process by its nature authenticates
        // only the client, the setting of mutual_req_flag is not needed for
        // this process.  This flag SHOULD be set to "false".
        // TODO: OpenSSH's sshd does accepts 'false' for mutual_req_flag
        // context.requestMutualAuth(false);
        context.requestMutualAuth(true);
        context.requestConf(true);
        // for MIC
        context.requestInteg(true);
        context.requestCredDeleg(true);
        context.requestAnonymity(false);
        return;
    } catch (GSSException ex) {
        throw new JSchException(ex.toString());
    }
}
Also used : JSchException(com.jcraft.jsch.JSchException) GSSName(org.ietf.jgss.GSSName) UnknownHostException(java.net.UnknownHostException) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) Oid(org.ietf.jgss.Oid)

Example 58 with GSSManager

use of org.ietf.jgss.GSSManager 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 59 with GSSManager

use of org.ietf.jgss.GSSManager 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 60 with GSSManager

use of org.ietf.jgss.GSSManager 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

GSSManager (org.ietf.jgss.GSSManager)67 GSSName (org.ietf.jgss.GSSName)56 Oid (org.ietf.jgss.Oid)51 GSSContext (org.ietf.jgss.GSSContext)38 GSSCredential (org.ietf.jgss.GSSCredential)38 GSSException (org.ietf.jgss.GSSException)34 Subject (javax.security.auth.Subject)29 PrivilegedActionException (java.security.PrivilegedActionException)19 Principal (java.security.Principal)17 IOException (java.io.IOException)10 LoginContext (javax.security.auth.login.LoginContext)10 LoginException (javax.security.auth.login.LoginException)10 Test (org.junit.Test)9 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)7 KerberosCredentials (org.apache.http.auth.KerberosCredentials)7 SaslException (javax.security.sasl.SaslException)6 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)5 KerberosPrincipal (javax.security.auth.kerberos.KerberosPrincipal)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4