Search in sources :

Example 1 with Credentials

use of sun.security.krb5.internal.ccache.Credentials in project jdk8u_jdk by JetBrains.

the class Krb5Util method getTicketFromSubjectAndTgs.

/**
     * Retrieve the service ticket for serverPrincipal from caller's Subject
     * or from Subject obtained by logging in, or if not found, via the
     * Ticket Granting Service using the TGT obtained from the Subject.
     *
     * Caller must have permission to:
     *    - access and update Subject's private credentials
     *    - create LoginContext
     *    - read the auth.login.defaultCallbackHandler security property
     *
     * NOTE: This method is used by JSSE Kerberos Cipher Suites
     */
public static KerberosTicket getTicketFromSubjectAndTgs(GSSCaller caller, String clientPrincipal, String serverPrincipal, String tgsPrincipal, AccessControlContext acc) throws LoginException, KrbException, IOException {
    // 1. Try to find service ticket in acc subject
    Subject accSubj = Subject.getSubject(acc);
    KerberosTicket ticket = SubjectComber.find(accSubj, serverPrincipal, clientPrincipal, KerberosTicket.class);
    if (ticket != null) {
        // found it
        return ticket;
    }
    Subject loginSubj = null;
    if (!GSSUtil.useSubjectCredsOnly(caller)) {
        // 2. Try to get ticket from login
        try {
            loginSubj = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
            ticket = SubjectComber.find(loginSubj, serverPrincipal, clientPrincipal, KerberosTicket.class);
            if (ticket != null) {
                // found it
                return ticket;
            }
        } catch (LoginException e) {
        // No login entry to use
        // ignore and continue
        }
    }
    // Service ticket not found in subject or login
    // Try to get TGT to acquire service ticket
    // 3. Try to get TGT from acc subject
    KerberosTicket tgt = SubjectComber.find(accSubj, tgsPrincipal, clientPrincipal, KerberosTicket.class);
    boolean fromAcc;
    if (tgt == null && loginSubj != null) {
        // 4. Try to get TGT from login subject
        tgt = SubjectComber.find(loginSubj, tgsPrincipal, clientPrincipal, KerberosTicket.class);
        fromAcc = false;
    } else {
        fromAcc = true;
    }
    // 5. Try to get service ticket using TGT
    if (tgt != null) {
        Credentials tgtCreds = ticketToCreds(tgt);
        Credentials serviceCreds = Credentials.acquireServiceCreds(serverPrincipal, tgtCreds);
        if (serviceCreds != null) {
            ticket = credsToTicket(serviceCreds);
            // Store service ticket in acc's Subject
            if (fromAcc && accSubj != null && !accSubj.isReadOnly()) {
                accSubj.getPrivateCredentials().add(ticket);
            }
        }
    }
    return ticket;
}
Also used : KerberosTicket(javax.security.auth.kerberos.KerberosTicket) LoginException(javax.security.auth.login.LoginException) Subject(javax.security.auth.Subject) Credentials(sun.security.krb5.Credentials)

Example 2 with Credentials

use of sun.security.krb5.internal.ccache.Credentials in project jdk8u_jdk by JetBrains.

the class Realm method parseCapaths.

/**
     * Parses the [capaths] stanza of the configuration file for a
     * list of realms to traverse to obtain credentials from the
     * initiating realm cRealm to the target realm sRealm.
     *
     * For a given client realm C there is a tag C in [capaths] whose
     * subtag S has a value which is a (possibly partial) path from C
     * to S. When the path is partial, it contains only the tail of the
     * full path. Values of other subtags will be used to build the full
     * path. The value "." means a direct path from C to S. If realm S
     * does not appear as a subtag, there is no path defined here.
     *
     * The implementation ignores all values which equals to C or S, or
     * a "." in multiple values, or any duplicated realm names.
     *
     * When a path value has more than two realms, they can be specified
     * with multiple key-value pairs each having a single value, but the
     * order must not change.
     *
     * For example:
     *
     * [capaths]
     *    TIVOLI.COM = {
     *        IBM.COM = IBM_LDAPCENTRAL.COM MOONLITE.ORG
     *        IBM_LDAPCENTRAL.COM = LDAPCENTRAL.NET
     *        LDAPCENTRAL.NET = .
     *    }
     *
     * TIVOLI.COM has a direct path to LDAPCENTRAL.NET, which has a direct
     * path to IBM_LDAPCENTRAL.COM. It also has a partial path to IBM.COM
     * being "IBM_LDAPCENTRAL.COM MOONLITE.ORG". Merging these info together,
     * a full path from TIVOLI.COM to IBM.COM will be
     *
     *   TIVOLI.COM -> LDAPCENTRAL.NET -> IBM_LDAPCENTRAL.COM
     *              -> IBM_LDAPCENTRAL.COM -> MOONLITE.ORG
     *
     * Please note the sRealm IBM.COM does not appear in the path.
     *
     * @param cRealm the initiating realm
     * @param sRealm the target realm, not the same as cRealm
     * @returns array of realms including at least cRealm as the first
     *          element
     * @throws KrbException if the config does not contain a sub-stanza
     *          for cRealm in [capaths] or the sub-stanza does not contain
     *          sRealm as a tag
     */
private static String[] parseCapaths(String cRealm, String sRealm) throws KrbException {
    // This line could throw a KrbException
    Config cfg = Config.getInstance();
    if (!cfg.exists("capaths", cRealm, sRealm)) {
        throw new KrbException("No conf");
    }
    LinkedList<String> path = new LinkedList<>();
    String head = sRealm;
    while (true) {
        String value = cfg.getAll("capaths", cRealm, head);
        if (value == null) {
            break;
        }
        String[] more = value.split("\\s+");
        boolean changed = false;
        for (int i = more.length - 1; i >= 0; i--) {
            if (path.contains(more[i]) || more[i].equals(".") || more[i].equals(cRealm) || more[i].equals(sRealm) || more[i].equals(head)) {
                // Ignore invalid values
                continue;
            }
            changed = true;
            path.addFirst(more[i]);
        }
        if (!changed)
            break;
        head = path.getFirst();
    }
    path.addFirst(cRealm);
    return path.toArray(new String[path.size()]);
}
Also used : KerberosString(sun.security.krb5.internal.util.KerberosString)

Example 3 with Credentials

use of sun.security.krb5.internal.ccache.Credentials in project jdk8u_jdk by JetBrains.

the class KrbApReq method authenticate.

private void authenticate(Krb5AcceptCredential cred, InetAddress initiator) throws KrbException, IOException {
    int encPartKeyType = apReqMessg.ticket.encPart.getEType();
    Integer kvno = apReqMessg.ticket.encPart.getKeyVersionNumber();
    EncryptionKey[] keys = cred.getKrb5EncryptionKeys(apReqMessg.ticket.sname);
    EncryptionKey dkey = EncryptionKey.findKey(encPartKeyType, kvno, keys);
    if (dkey == null) {
        throw new KrbException(Krb5.API_INVALID_ARG, "Cannot find key of appropriate type to decrypt AP REP - " + EType.toString(encPartKeyType));
    }
    byte[] bytes = apReqMessg.ticket.encPart.decrypt(dkey, KeyUsage.KU_TICKET);
    byte[] temp = apReqMessg.ticket.encPart.reset(bytes);
    EncTicketPart enc_ticketPart = new EncTicketPart(temp);
    checkPermittedEType(enc_ticketPart.key.getEType());
    byte[] bytes2 = apReqMessg.authenticator.decrypt(enc_ticketPart.key, KeyUsage.KU_AP_REQ_AUTHENTICATOR);
    byte[] temp2 = apReqMessg.authenticator.reset(bytes2);
    authenticator = new Authenticator(temp2);
    ctime = authenticator.ctime;
    cusec = authenticator.cusec;
    authenticator.ctime = authenticator.ctime.withMicroSeconds(authenticator.cusec);
    if (!authenticator.cname.equals(enc_ticketPart.cname)) {
        throw new KrbApErrException(Krb5.KRB_AP_ERR_BADMATCH);
    }
    if (!authenticator.ctime.inClockSkew())
        throw new KrbApErrException(Krb5.KRB_AP_ERR_SKEW);
    byte[] hash;
    try {
        hash = MessageDigest.getInstance("MD5").digest(apReqMessg.authenticator.cipher);
    } catch (NoSuchAlgorithmException ex) {
        throw new AssertionError("Impossible");
    }
    char[] h = new char[hash.length * 2];
    for (int i = 0; i < hash.length; i++) {
        h[2 * i] = hexConst[(hash[i] & 0xff) >> 4];
        h[2 * i + 1] = hexConst[hash[i] & 0xf];
    }
    AuthTimeWithHash time = new AuthTimeWithHash(authenticator.cname.toString(), apReqMessg.ticket.sname.toString(), authenticator.ctime.getSeconds(), authenticator.cusec, new String(h));
    rcache.checkAndStore(KerberosTime.now(), time);
    if (initiator != null) {
        // sender host address
        HostAddress sender = new HostAddress(initiator);
        if (enc_ticketPart.caddr != null && !enc_ticketPart.caddr.inList(sender)) {
            if (DEBUG) {
                System.out.println(">>> KrbApReq: initiator is " + sender.getInetAddress() + ", but caddr is " + Arrays.toString(enc_ticketPart.caddr.getInetAddresses()));
            }
            throw new KrbApErrException(Krb5.KRB_AP_ERR_BADADDR);
        }
    }
    // XXX check for repeated authenticator
    // if found
    //    throw new KrbApErrException(Krb5.KRB_AP_ERR_REPEAT);
    // else
    //    save authenticator to check for later
    KerberosTime now = KerberosTime.now();
    if ((enc_ticketPart.starttime != null && enc_ticketPart.starttime.greaterThanWRTClockSkew(now)) || enc_ticketPart.flags.get(Krb5.TKT_OPTS_INVALID))
        throw new KrbApErrException(Krb5.KRB_AP_ERR_TKT_NYV);
    // than the allowable clock skew, throws ticket expired exception.
    if (enc_ticketPart.endtime != null && now.greaterThanWRTClockSkew(enc_ticketPart.endtime)) {
        throw new KrbApErrException(Krb5.KRB_AP_ERR_TKT_EXPIRED);
    }
    creds = new Credentials(apReqMessg.ticket, authenticator.cname, apReqMessg.ticket.sname, enc_ticketPart.key, enc_ticketPart.flags, enc_ticketPart.authtime, enc_ticketPart.starttime, enc_ticketPart.endtime, enc_ticketPart.renewTill, enc_ticketPart.caddr, enc_ticketPart.authorizationData);
    if (DEBUG) {
        System.out.println(">>> KrbApReq: authenticate succeed.");
    }
}
Also used : AuthTimeWithHash(sun.security.krb5.internal.rcache.AuthTimeWithHash) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 4 with Credentials

use of sun.security.krb5.internal.ccache.Credentials in project jdk8u_jdk by JetBrains.

the class Credentials method acquireTGTFromCache.

/**
     * Returns a TGT for the given client principal from a ticket cache.
     *
     * @param princ the client principal. A value of null means that the
     * default principal name in the credentials cache will be used.
     * @param ticketCache the path to the tickets file. A value
     * of null will be accepted to indicate that the default
     * path should be searched
     * @returns the TGT credentials or null if none were found. If the tgt
     * expired, it is the responsibility of the caller to determine this.
     */
public static Credentials acquireTGTFromCache(PrincipalName princ, String ticketCache) throws KrbException, IOException {
    if (ticketCache == null) {
        // The default ticket cache on Windows and Mac is not a file.
        String os = java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("os.name"));
        if (os.toUpperCase(Locale.ENGLISH).startsWith("WINDOWS") || os.toUpperCase(Locale.ENGLISH).contains("OS X")) {
            Credentials creds = acquireDefaultCreds();
            if (creds == null) {
                if (DEBUG) {
                    System.out.println(">>> Found no TGT's in LSA");
                }
                return null;
            }
            if (princ != null) {
                if (creds.getClient().equals(princ)) {
                    if (DEBUG) {
                        System.out.println(">>> Obtained TGT from LSA: " + creds);
                    }
                    return creds;
                } else {
                    if (DEBUG) {
                        System.out.println(">>> LSA contains TGT for " + creds.getClient() + " not " + princ);
                    }
                    return null;
                }
            } else {
                if (DEBUG) {
                    System.out.println(">>> Obtained TGT from LSA: " + creds);
                }
                return creds;
            }
        }
    }
    /*
         * Returns the appropriate cache. If ticketCache is null, it is the
         * default cache otherwise it is the cache filename contained in it.
         */
    CredentialsCache ccache = CredentialsCache.getInstance(princ, ticketCache);
    if (ccache == null) {
        return null;
    }
    sun.security.krb5.internal.ccache.Credentials tgtCred = ccache.getDefaultCreds();
    if (tgtCred == null) {
        return null;
    }
    if (EType.isSupported(tgtCred.getEType())) {
        return tgtCred.setKrbCreds();
    } else {
        if (DEBUG) {
            System.out.println(">>> unsupported key type found the default TGT: " + tgtCred.getEType());
        }
        return null;
    }
}
Also used : CredentialsCache(sun.security.krb5.internal.ccache.CredentialsCache)

Example 5 with Credentials

use of sun.security.krb5.internal.ccache.Credentials in project jdk8u_jdk by JetBrains.

the class Klist method displayCache.

void displayCache() {
    CredentialsCache cache = (CredentialsCache) target;
    sun.security.krb5.internal.ccache.Credentials[] creds = cache.getCredsList();
    if (creds == null) {
        System.out.println("No credentials available in the cache " + name);
        System.exit(-1);
    }
    System.out.println("\nCredentials cache: " + name);
    String defaultPrincipal = cache.getPrimaryPrincipal().toString();
    int num = creds.length;
    if (num == 1)
        System.out.println("\nDefault principal: " + defaultPrincipal + ", " + creds.length + " entry found.\n");
    else
        System.out.println("\nDefault principal: " + defaultPrincipal + ", " + creds.length + " entries found.\n");
    if (creds != null) {
        for (int i = 0; i < creds.length; i++) {
            try {
                String starttime;
                String endtime;
                String renewTill;
                String servicePrincipal;
                if (creds[i].getStartTime() != null) {
                    starttime = format(creds[i].getStartTime());
                } else {
                    starttime = format(creds[i].getAuthTime());
                }
                endtime = format(creds[i].getEndTime());
                servicePrincipal = creds[i].getServicePrincipal().toString();
                System.out.println("[" + (i + 1) + "] " + " Service Principal:  " + servicePrincipal);
                System.out.println("     Valid starting:     " + starttime);
                System.out.println("     Expires:            " + endtime);
                if (creds[i].getRenewTill() != null) {
                    renewTill = format(creds[i].getRenewTill());
                    System.out.println("     Renew until:        " + renewTill);
                }
                if (options[0] == 'e') {
                    String eskey = EType.toString(creds[i].getEType());
                    String etkt = EType.toString(creds[i].getTktEType());
                    System.out.println("     EType (skey, tkt):  " + eskey + ", " + etkt);
                }
                if (options[1] == 'f') {
                    System.out.println("     Flags:              " + creds[i].getTicketFlags().toString());
                }
                if (options[2] == 'a') {
                    boolean first = true;
                    InetAddress[] caddr = creds[i].setKrbCreds().getClientAddresses();
                    if (caddr != null) {
                        for (InetAddress ia : caddr) {
                            String out;
                            if (options[3] == 'n') {
                                out = ia.getHostAddress();
                            } else {
                                out = ia.getCanonicalHostName();
                            }
                            System.out.println("     " + (first ? "Addresses:" : "          ") + "       " + out);
                            first = false;
                        }
                    } else {
                        System.out.println("     [No host addresses info]");
                    }
                }
            } catch (RealmException e) {
                System.out.println("Error reading principal from " + "the entry.");
                if (DEBUG) {
                    e.printStackTrace();
                }
                System.exit(-1);
            }
        }
    } else {
        System.out.println("\nNo entries found.");
    }
}
Also used : sun.security.krb5.internal(sun.security.krb5.internal) InetAddress(java.net.InetAddress)

Aggregations

sun.security.krb5.internal (sun.security.krb5.internal)2 CredentialsCache (sun.security.krb5.internal.ccache.CredentialsCache)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 InetAddress (java.net.InetAddress)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 Subject (javax.security.auth.Subject)1 KerberosTicket (javax.security.auth.kerberos.KerberosTicket)1 LoginException (javax.security.auth.login.LoginException)1 sun.security.krb5 (sun.security.krb5)1 Credentials (sun.security.krb5.Credentials)1 CCacheInputStream (sun.security.krb5.internal.ccache.CCacheInputStream)1 Credentials (sun.security.krb5.internal.ccache.Credentials)1 AuthTimeWithHash (sun.security.krb5.internal.rcache.AuthTimeWithHash)1 KerberosString (sun.security.krb5.internal.util.KerberosString)1 DerOutputStream (sun.security.util.DerOutputStream)1 DerValue (sun.security.util.DerValue)1