Search in sources :

Example 16 with GSSCredential

use of org.ietf.jgss.GSSCredential in project zookeeper by apache.

the class ZooKeeperSaslServer method createSaslServer.

private SaslServer createSaslServer(final Login login) {
    synchronized (login) {
        Subject subject = login.getSubject();
        if (subject != null) {
            // server is using a JAAS-authenticated subject: determine service principal name and hostname from zk server's subject.
            if (subject.getPrincipals().size() > 0) {
                try {
                    final Object[] principals = subject.getPrincipals().toArray();
                    final Principal servicePrincipal = (Principal) principals[0];
                    // e.g. servicePrincipalNameAndHostname := "zookeeper/myhost.foo.com@FOO.COM"
                    final String servicePrincipalNameAndHostname = servicePrincipal.getName();
                    int indexOf = servicePrincipalNameAndHostname.indexOf("/");
                    // e.g. serviceHostnameAndKerbDomain := "myhost.foo.com@FOO.COM"
                    final String serviceHostnameAndKerbDomain = servicePrincipalNameAndHostname.substring(indexOf + 1, servicePrincipalNameAndHostname.length());
                    int indexOfAt = serviceHostnameAndKerbDomain.indexOf("@");
                    // Handle Kerberos Service as well as User Principal Names
                    final String servicePrincipalName, serviceHostname;
                    if (indexOf > 0) {
                        // e.g. servicePrincipalName := "zookeeper"
                        servicePrincipalName = servicePrincipalNameAndHostname.substring(0, indexOf);
                        // e.g. serviceHostname := "myhost.foo.com"
                        serviceHostname = serviceHostnameAndKerbDomain.substring(0, indexOfAt);
                    } else {
                        servicePrincipalName = servicePrincipalNameAndHostname.substring(0, indexOfAt);
                        serviceHostname = null;
                    }
                    // TODO: should depend on zoo.cfg specified mechs, but if subject is non-null, it can be assumed to be GSSAPI.
                    final String mech = "GSSAPI";
                    LOG.debug("serviceHostname is '" + serviceHostname + "'");
                    LOG.debug("servicePrincipalName is '" + servicePrincipalName + "'");
                    LOG.debug("SASL mechanism(mech) is '" + mech + "'");
                    boolean usingNativeJgss = Boolean.getBoolean("sun.security.jgss.native");
                    if (usingNativeJgss) {
                        // """
                        try {
                            GSSManager manager = GSSManager.getInstance();
                            Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2");
                            GSSName gssName = manager.createName(servicePrincipalName + "@" + serviceHostname, GSSName.NT_HOSTBASED_SERVICE);
                            GSSCredential cred = manager.createCredential(gssName, GSSContext.DEFAULT_LIFETIME, krb5Mechanism, GSSCredential.ACCEPT_ONLY);
                            subject.getPrivateCredentials().add(cred);
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Added private credential to subject: " + cred);
                            }
                        } catch (GSSException ex) {
                            LOG.warn("Cannot add private credential to subject; " + "clients authentication may fail", ex);
                        }
                    }
                    try {
                        return Subject.doAs(subject, new PrivilegedExceptionAction<SaslServer>() {

                            public SaslServer run() {
                                try {
                                    SaslServer saslServer;
                                    saslServer = Sasl.createSaslServer(mech, servicePrincipalName, serviceHostname, null, login.callbackHandler);
                                    return saslServer;
                                } catch (SaslException e) {
                                    LOG.error("Zookeeper Server failed to create a SaslServer to interact with a client during session initiation: " + e);
                                    e.printStackTrace();
                                    return null;
                                }
                            }
                        });
                    } catch (PrivilegedActionException e) {
                        // TODO: exit server at this point(?)
                        LOG.error("Zookeeper Quorum member experienced a PrivilegedActionException exception while creating a SaslServer using a JAAS principal context:" + e);
                        e.printStackTrace();
                    }
                } catch (IndexOutOfBoundsException e) {
                    LOG.error("server principal name/hostname determination error: ", e);
                }
            } else {
                // TODO: use 'authMech=' value in zoo.cfg.
                try {
                    SaslServer saslServer = Sasl.createSaslServer("DIGEST-MD5", "zookeeper", "zk-sasl-md5", null, login.callbackHandler);
                    return saslServer;
                } catch (SaslException e) {
                    LOG.error("Zookeeper Quorum member failed to create a SaslServer to interact with a client during session initiation", e);
                }
            }
        }
    }
    LOG.error("failed to create saslServer object.");
    return null;
}
Also used : GSSName(org.ietf.jgss.GSSName) PrivilegedActionException(java.security.PrivilegedActionException) SaslServer(javax.security.sasl.SaslServer) Oid(org.ietf.jgss.Oid) SaslException(javax.security.sasl.SaslException) Subject(javax.security.auth.Subject) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) Principal(java.security.Principal)

Example 17 with GSSCredential

use of org.ietf.jgss.GSSCredential in project blade by biezhi.

the class SpnegoLoginService method login.

/**
     * username will be null since the credentials will contain all the relevant info
     */
@Override
public UserIdentity login(String username, Object credentials, ServletRequest request) {
    String encodedAuthToken = (String) credentials;
    byte[] authToken = B64Code.decode(encodedAuthToken);
    GSSManager manager = GSSManager.getInstance();
    try {
        // http://java.sun.com/javase/6/docs/technotes/guides/security/jgss/jgss-features.html
        Oid krb5Oid = new Oid("1.3.6.1.5.5.2");
        GSSName gssName = manager.createName(_targetName, null);
        GSSCredential serverCreds = manager.createCredential(gssName, GSSCredential.INDEFINITE_LIFETIME, krb5Oid, GSSCredential.ACCEPT_ONLY);
        GSSContext gContext = manager.createContext(serverCreds);
        if (gContext == null) {
            LOG.debug("SpnegoUserRealm: failed to establish GSSContext");
        } else {
            while (!gContext.isEstablished()) {
                authToken = gContext.acceptSecContext(authToken, 0, authToken.length);
            }
            if (gContext.isEstablished()) {
                String clientName = gContext.getSrcName().toString();
                String role = clientName.substring(clientName.indexOf('@') + 1);
                LOG.debug("SpnegoUserRealm: established a security context");
                LOG.debug("Client Principal is: " + gContext.getSrcName());
                LOG.debug("Server Principal is: " + gContext.getTargName());
                LOG.debug("Client Default Role: " + role);
                SpnegoUserPrincipal user = new SpnegoUserPrincipal(clientName, authToken);
                Subject subject = new Subject();
                subject.getPrincipals().add(user);
                return _identityService.newUserIdentity(subject, user, new String[] { role });
            }
        }
    } catch (GSSException gsse) {
        LOG.warn(gsse);
    }
    return null;
}
Also used : GSSName(org.ietf.jgss.GSSName) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager) GSSContext(org.ietf.jgss.GSSContext) Oid(org.ietf.jgss.Oid) Subject(javax.security.auth.Subject)

Example 18 with GSSCredential

use of org.ietf.jgss.GSSCredential in project hadoop by apache.

the class KerberosAuthenticationHandler method runWithPrincipal.

private AuthenticationToken runWithPrincipal(String serverPrincipal, byte[] clientToken, Base64 base64, HttpServletResponse response) throws IOException, AuthenticationException, ClassNotFoundException, GSSException, IllegalAccessException, NoSuchFieldException {
    GSSContext gssContext = null;
    GSSCredential gssCreds = null;
    AuthenticationToken token = null;
    try {
        LOG.trace("SPNEGO initiated with server principal [{}]", serverPrincipal);
        gssCreds = this.gssManager.createCredential(this.gssManager.createName(serverPrincipal, 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 = this.gssManager.createContext(gssCreds);
        byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length);
        if (serverToken != null && serverToken.length > 0) {
            String authenticate = base64.encodeToString(serverToken);
            response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, 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 client principal [{}]", clientPrincipal);
        }
    } finally {
        if (gssContext != null) {
            gssContext.dispose();
        }
        if (gssCreds != null) {
            gssCreds.dispose();
        }
    }
    return token;
}
Also used : GSSCredential(org.ietf.jgss.GSSCredential) GSSContext(org.ietf.jgss.GSSContext) Oid(org.ietf.jgss.Oid) KerberosName(org.apache.hadoop.security.authentication.util.KerberosName)

Example 19 with GSSCredential

use of org.ietf.jgss.GSSCredential in project jdk8u_jdk by JetBrains.

the class OkAsDelegate method go.

void go(boolean forwardable, boolean requestDelegState, boolean requestDelegPolicyState, boolean delegState, boolean delegPolicyState, boolean delegated) throws Exception {
    OneKDC kdc = new OneKDC(null);
    kdc.setOption(KDC.Option.OK_AS_DELEGATE, System.getProperty("test.kdc.policy.ok-as-delegate"));
    kdc.writeJAASConf();
    if (!forwardable) {
        // The default OneKDC always includes "forwardable = true"
        // in krb5.conf, override it.
        KDC.saveConfig(OneKDC.KRB5_CONF, kdc, "default_keytab_name = " + OneKDC.KTAB);
        Config.refresh();
    }
    Context c, s;
    c = Context.fromJAAS("client");
    s = Context.fromJAAS("com.sun.security.jgss.krb5.accept");
    Oid mech = GSSUtil.GSS_KRB5_MECH_OID;
    if (System.getProperty("test.spnego") != null) {
        mech = GSSUtil.GSS_SPNEGO_MECH_OID;
    }
    c.startAsClient(OneKDC.SERVER, mech);
    ExtendedGSSContext cx = (ExtendedGSSContext) c.x();
    cx.requestCredDeleg(requestDelegState);
    cx.requestDelegPolicy(requestDelegPolicyState);
    s.startAsServer(mech);
    ExtendedGSSContext sx = (ExtendedGSSContext) s.x();
    Context.handshake(c, s);
    if (cx.getCredDelegState() != delegState) {
        throw new Exception("Initiator cred state error");
    }
    if (sx.getCredDelegState() != delegState) {
        throw new Exception("Acceptor cred state error");
    }
    if (cx.getDelegPolicyState() != delegPolicyState) {
        throw new Exception("Initiator cred policy state error");
    }
    GSSCredential cred = null;
    try {
        cred = s.x().getDelegCred();
    } catch (GSSException e) {
    // leave cred as null
    }
    if (delegated != (cred != null)) {
        throw new Exception("get cred error");
    }
}
Also used : ExtendedGSSContext(com.sun.security.jgss.ExtendedGSSContext) ExtendedGSSContext(com.sun.security.jgss.ExtendedGSSContext) GSSException(org.ietf.jgss.GSSException) GSSCredential(org.ietf.jgss.GSSCredential) Oid(org.ietf.jgss.Oid) GSSException(org.ietf.jgss.GSSException)

Example 20 with GSSCredential

use of org.ietf.jgss.GSSCredential in project jdk8u_jdk by JetBrains.

the class LifeTimeInSeconds method main.

public static void main(String[] args) throws Exception {
    new OneKDC(null).writeJAASConf();
    System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
    GSSManager gm = GSSManager.getInstance();
    GSSCredential cred = gm.createCredential(GSSCredential.INITIATE_AND_ACCEPT);
    int time = cred.getRemainingLifetime();
    int time2 = cred.getRemainingInitLifetime(null);
    // The test KDC issues a TGT with a default lifetime of 11 hours
    int elevenhrs = 11 * 3600;
    if (time > elevenhrs + 60 || time < elevenhrs - 60) {
        throw new Exception("getRemainingLifetime returns wrong value.");
    }
    if (time2 > elevenhrs + 60 || time2 < elevenhrs - 60) {
        throw new Exception("getRemainingInitLifetime returns wrong value.");
    }
}
Also used : GSSCredential(org.ietf.jgss.GSSCredential) GSSManager(org.ietf.jgss.GSSManager)

Aggregations

GSSCredential (org.ietf.jgss.GSSCredential)23 GSSException (org.ietf.jgss.GSSException)16 GSSManager (org.ietf.jgss.GSSManager)14 Oid (org.ietf.jgss.Oid)14 GSSName (org.ietf.jgss.GSSName)13 GSSContext (org.ietf.jgss.GSSContext)11 Subject (javax.security.auth.Subject)9 PrivilegedActionException (java.security.PrivilegedActionException)8 Principal (java.security.Principal)7 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)4 ExtendedGSSContext (com.sun.security.jgss.ExtendedGSSContext)3 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)3 LoginContext (javax.security.auth.login.LoginContext)3 LoginException (javax.security.auth.login.LoginException)3 SaslException (javax.security.sasl.SaslException)3 KrbException (org.apache.kerby.kerberos.kerb.KrbException)3 Test (org.junit.Test)3 ExtendedGSSCredential (com.sun.security.jgss.ExtendedGSSCredential)2 IOException (java.io.IOException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2