Search in sources :

Example 41 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project hadoop by apache.

the class KerberosTestUtils method doAs.

public static <T> T doAs(String principal, final Callable<T> callable) throws Exception {
    LoginContext loginContext = null;
    try {
        Set<Principal> principals = new HashSet<Principal>();
        principals.add(new KerberosPrincipal(KerberosTestUtils.getClientPrincipal()));
        Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
        loginContext = new LoginContext("", subject, null, new KerberosConfiguration(principal));
        loginContext.login();
        subject = loginContext.getSubject();
        return Subject.doAs(subject, new PrivilegedExceptionAction<T>() {

            @Override
            public T run() throws Exception {
                return callable.call();
            }
        });
    } catch (PrivilegedActionException ex) {
        throw ex.getException();
    } finally {
        if (loginContext != null) {
            loginContext.logout();
        }
    }
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) PrivilegedActionException(java.security.PrivilegedActionException) Subject(javax.security.auth.Subject) PrivilegedActionException(java.security.PrivilegedActionException) LoginContext(javax.security.auth.login.LoginContext) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal) HashSet(java.util.HashSet)

Example 42 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project jdk8u_jdk by JetBrains.

the class ServiceCreds method getInstance.

/**
     * Creates a ServiceCreds object based on info in a Subject for
     * a given principal name (if specified).
     * @return the object, or null if there is no private creds for it
     */
public static ServiceCreds getInstance(Subject subj, String serverPrincipal) {
    ServiceCreds sc = new ServiceCreds();
    sc.allPrincs = subj.getPrincipals(KerberosPrincipal.class);
    // Compatibility. A key implies its own principal
    for (KerberosKey key : SubjectComber.findMany(subj, serverPrincipal, null, KerberosKey.class)) {
        sc.allPrincs.add(key.getPrincipal());
    }
    if (serverPrincipal != null) {
        // A named principal
        sc.kp = new KerberosPrincipal(serverPrincipal);
    } else {
        // only one KerberosPrincipal and there is no unbound keytabs
        if (sc.allPrincs.size() == 1) {
            boolean hasUnbound = false;
            for (KeyTab ktab : SubjectComber.findMany(subj, null, null, KeyTab.class)) {
                if (!ktab.isBound()) {
                    hasUnbound = true;
                    break;
                }
            }
            if (!hasUnbound) {
                sc.kp = sc.allPrincs.iterator().next();
                serverPrincipal = sc.kp.getName();
            }
        }
    }
    sc.ktabs = SubjectComber.findMany(subj, serverPrincipal, null, KeyTab.class);
    sc.kk = SubjectComber.findMany(subj, serverPrincipal, null, KerberosKey.class);
    sc.tgt = SubjectComber.find(subj, null, serverPrincipal, KerberosTicket.class);
    if (sc.ktabs.isEmpty() && sc.kk.isEmpty() && sc.tgt == null) {
        return null;
    }
    sc.destroyed = false;
    return sc;
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) KerberosKey(javax.security.auth.kerberos.KerberosKey) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) KeyTab(javax.security.auth.kerberos.KeyTab)

Example 43 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project jdk8u_jdk by JetBrains.

the class GSSUtil method getSubject.

/**
     * Note: The current impl only works with Sun's impl of
     * GSSName and GSSCredential since it depends on package
     * private APIs.
     */
public static Subject getSubject(GSSName name, GSSCredential creds) {
    HashSet<Object> privCredentials = null;
    // empty Set
    HashSet<Object> pubCredentials = new HashSet<Object>();
    Set<GSSCredentialSpi> gssCredentials = null;
    Set<KerberosPrincipal> krb5Principals = new HashSet<KerberosPrincipal>();
    if (name instanceof GSSNameImpl) {
        try {
            GSSNameSpi ne = ((GSSNameImpl) name).getElement(GSS_KRB5_MECH_OID);
            String krbName = ne.toString();
            if (ne instanceof Krb5NameElement) {
                krbName = ((Krb5NameElement) ne).getKrb5PrincipalName().getName();
            }
            KerberosPrincipal krbPrinc = new KerberosPrincipal(krbName);
            krb5Principals.add(krbPrinc);
        } catch (GSSException ge) {
            debug("Skipped name " + name + " due to " + ge);
        }
    }
    if (creds instanceof GSSCredentialImpl) {
        gssCredentials = ((GSSCredentialImpl) creds).getElements();
        privCredentials = new HashSet<Object>(gssCredentials.size());
        populateCredentials(privCredentials, gssCredentials);
    } else {
        // empty Set
        privCredentials = new HashSet<Object>();
    }
    debug("Created Subject with the following");
    debug("principals=" + krb5Principals);
    debug("public creds=" + pubCredentials);
    debug("private creds=" + privCredentials);
    return new Subject(false, krb5Principals, pubCredentials, privCredentials);
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Krb5NameElement(sun.security.jgss.krb5.Krb5NameElement) Subject(javax.security.auth.Subject) GSSNameSpi(sun.security.jgss.spi.GSSNameSpi) GSSCredentialSpi(sun.security.jgss.spi.GSSCredentialSpi) HashSet(java.util.HashSet)

Example 44 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project jdk8u_jdk by JetBrains.

the class KerberosClientKeyExchangeImpl method init.

/**
     * Creates an instance of KerberosClientKeyExchange from its ASN.1 encoding.
     * Used by ServerHandshaker to verify and obtain premaster secret.
     *
     * @param protocolVersion current protocol version
     * @param clientVersion version requested by client in its ClientHello;
     *          used by premaster secret version check
     * @param rand random number generator used for generating random
     *          premaster secret if ticket and/or premaster verification fails
     * @param input inputstream from which to get ASN.1-encoded KerberosWrapper
     * @param acc the AccessControlContext of the handshaker
     * @param serviceCreds server's creds
     */
@Override
public void init(ProtocolVersion protocolVersion, ProtocolVersion clientVersion, SecureRandom rand, HandshakeInStream input, AccessControlContext acc, Object serviceCreds) throws IOException {
    // Read ticket
    encodedTicket = input.getBytes16();
    if (debug != null && Debug.isOn("verbose")) {
        Debug.println(System.out, "encoded Kerberos service ticket", encodedTicket);
    }
    EncryptionKey sessionKey = null;
    try {
        Ticket t = new Ticket(encodedTicket);
        EncryptedData encPart = t.encPart;
        PrincipalName ticketSname = t.sname;
        final ServiceCreds creds = (ServiceCreds) serviceCreds;
        final KerberosPrincipal princ = new KerberosPrincipal(ticketSname.toString());
        // For bound service, permission already checked at setup
        if (creds.getName() == null) {
            SecurityManager sm = System.getSecurityManager();
            try {
                if (sm != null) {
                    // Eliminate dependency on ServicePermission
                    sm.checkPermission(Krb5Helper.getServicePermission(ticketSname.toString(), "accept"), acc);
                }
            } catch (SecurityException se) {
                serviceCreds = null;
                // Do not destroy keys. Will affect Subject
                if (debug != null && Debug.isOn("handshake")) {
                    System.out.println("Permission to access Kerberos" + " secret key denied");
                }
                throw new IOException("Kerberos service not allowedy");
            }
        }
        KerberosKey[] serverKeys = AccessController.doPrivileged(new PrivilegedAction<KerberosKey[]>() {

            @Override
            public KerberosKey[] run() {
                return creds.getKKeys(princ);
            }
        });
        if (serverKeys.length == 0) {
            throw new IOException("Found no key for " + princ + (creds.getName() == null ? "" : (", this keytab is for " + creds.getName() + " only")));
        }
        /*
             * permission to access and use the secret key of the Kerberized
             * "host" service is done in ServerHandshaker.getKerberosKeys()
             * to ensure server has the permission to use the secret key
             * before promising the client
             */
        // See if we have the right key to decrypt the ticket to get
        // the session key.
        int encPartKeyType = encPart.getEType();
        Integer encPartKeyVersion = encPart.getKeyVersionNumber();
        KerberosKey dkey = null;
        try {
            dkey = findKey(encPartKeyType, encPartKeyVersion, serverKeys);
        } catch (KrbException ke) {
            // a kvno mismatch
            throw new IOException("Cannot find key matching version number", ke);
        }
        if (dkey == null) {
            // %%% Should print string repr of etype
            throw new IOException("Cannot find key of appropriate type" + " to decrypt ticket - need etype " + encPartKeyType);
        }
        EncryptionKey secretKey = new EncryptionKey(encPartKeyType, dkey.getEncoded());
        // Decrypt encPart using server's secret key
        byte[] bytes = encPart.decrypt(secretKey, KeyUsage.KU_TICKET);
        // Reset data stream after decryption, remove redundant bytes
        byte[] temp = encPart.reset(bytes);
        EncTicketPart encTicketPart = new EncTicketPart(temp);
        // Record the Kerberos Principals
        peerPrincipal = new KerberosPrincipal(encTicketPart.cname.getName());
        localPrincipal = new KerberosPrincipal(ticketSname.getName());
        sessionKey = encTicketPart.key;
        if (debug != null && Debug.isOn("handshake")) {
            System.out.println("server principal: " + ticketSname);
            System.out.println("cname: " + encTicketPart.cname.toString());
        }
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        if (debug != null && Debug.isOn("handshake")) {
            System.out.println("KerberosWrapper error getting session key," + " generating random secret (" + e.getMessage() + ")");
        }
        sessionKey = null;
    }
    // XXX Read and ignore authenticator
    input.getBytes16();
    if (sessionKey != null) {
        preMaster = new KerberosPreMasterSecret(protocolVersion, clientVersion, rand, input, sessionKey);
    } else {
        // Generate bogus premaster secret
        preMaster = new KerberosPreMasterSecret(clientVersion, rand);
    }
}
Also used : Ticket(sun.security.krb5.internal.Ticket) KerberosTicket(javax.security.auth.kerberos.KerberosTicket) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) ServiceCreds(sun.security.jgss.krb5.ServiceCreds) EncryptionKey(sun.security.krb5.EncryptionKey) PrincipalName(sun.security.krb5.PrincipalName) IOException(java.io.IOException) EncTicketPart(sun.security.krb5.internal.EncTicketPart) KrbException(sun.security.krb5.KrbException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) KerberosKey(javax.security.auth.kerberos.KerberosKey) KrbException(sun.security.krb5.KrbException) EncryptedData(sun.security.krb5.EncryptedData)

Example 45 with KerberosPrincipal

use of javax.security.auth.kerberos.KerberosPrincipal in project jdk8u_jdk by JetBrains.

the class KrbCredSubKey method main.

public static void main(String[] args) throws Exception {
    // We don't care about clock difference
    new FileOutputStream("krb5.conf").write("[libdefaults]\nclockskew=999999999".getBytes());
    System.setProperty("java.security.krb5.conf", "krb5.conf");
    Config.refresh();
    Subject subj = new Subject();
    KerberosPrincipal kp = new KerberosPrincipal(princ);
    KerberosKey kk = new KerberosKey(kp, key, EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96, 0);
    subj.getPrincipals().add(kp);
    subj.getPrivateCredentials().add(kk);
    Subject.doAs(subj, new PrivilegedExceptionAction() {

        public Object run() throws Exception {
            GSSManager man = GSSManager.getInstance();
            GSSContext ctxt = man.createContext(man.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY));
            return ctxt.acceptSecContext(token, 0, token.length);
        }
    });
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) KerberosKey(javax.security.auth.kerberos.KerberosKey) FileOutputStream(java.io.FileOutputStream) GSSManager(org.ietf.jgss.GSSManager) GSSContext(org.ietf.jgss.GSSContext) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Subject(javax.security.auth.Subject)

Aggregations

KerberosPrincipal (javax.security.auth.kerberos.KerberosPrincipal)71 Principal (java.security.Principal)36 Subject (javax.security.auth.Subject)31 HashSet (java.util.HashSet)21 LoginContext (javax.security.auth.login.LoginContext)20 Test (org.junit.Test)14 X500Principal (javax.security.auth.x500.X500Principal)13 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)11 IOException (java.io.IOException)10 File (java.io.File)9 KerberosKey (javax.security.auth.kerberos.KerberosKey)9 PrivilegedActionException (java.security.PrivilegedActionException)8 StringTokenizer (java.util.StringTokenizer)6 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)3 ArrayList (java.util.ArrayList)3 Date (java.util.Date)3 HashMap (java.util.HashMap)3 Properties (java.util.Properties)3 CallbackHandler (javax.security.auth.callback.CallbackHandler)3 KeyTab (javax.security.auth.kerberos.KeyTab)3