Search in sources :

Example 6 with DerValue

use of sun.security.util.DerValue in project jdk8u_jdk by JetBrains.

the class KDC method processTgsReq.

/**
     * Processes a TGS_REQ and generates a TGS_REP (or KRB_ERROR)
     * @param in the request
     * @return the response
     * @throws java.lang.Exception for various errors
     */
protected byte[] processTgsReq(byte[] in) throws Exception {
    TGSReq tgsReq = new TGSReq(in);
    PrincipalName service = tgsReq.reqBody.sname;
    if (options.containsKey(KDC.Option.RESP_NT)) {
        service = new PrincipalName((int) options.get(KDC.Option.RESP_NT), service.getNameStrings(), service.getRealm());
    }
    try {
        System.out.println(realm + "> " + tgsReq.reqBody.cname + " sends TGS-REQ for " + service + ", " + tgsReq.reqBody.kdcOptions);
        KDCReqBody body = tgsReq.reqBody;
        int[] eTypes = KDCReqBodyDotEType(body);
        // etype for outgoing session key
        int e2 = eTypes[0];
        // etype for outgoing ticket
        int e3 = eTypes[0];
        PAData[] pas = KDCReqDotPAData(tgsReq);
        Ticket tkt = null;
        EncTicketPart etp = null;
        PrincipalName cname = null;
        boolean allowForwardable = true;
        if (pas == null || pas.length == 0) {
            throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
        } else {
            PrincipalName forUserCName = null;
            for (PAData pa : pas) {
                if (pa.getType() == Krb5.PA_TGS_REQ) {
                    APReq apReq = new APReq(pa.getValue());
                    EncryptedData ed = apReq.authenticator;
                    tkt = apReq.ticket;
                    int te = tkt.encPart.getEType();
                    EncryptionKey kkey = keyForUser(tkt.sname, te, true);
                    byte[] bb = tkt.encPart.decrypt(kkey, KeyUsage.KU_TICKET);
                    DerInputStream derIn = new DerInputStream(bb);
                    DerValue der = derIn.getDerValue();
                    etp = new EncTicketPart(der.toByteArray());
                    // Finally, cname will be overwritten by PA-FOR-USER
                    // if it exists.
                    cname = etp.cname;
                    System.out.println(realm + "> presenting a ticket of " + etp.cname + " to " + tkt.sname);
                } else if (pa.getType() == Krb5.PA_FOR_USER) {
                    if (options.containsKey(Option.ALLOW_S4U2SELF)) {
                        PAForUserEnc p4u = new PAForUserEnc(new DerValue(pa.getValue()), null);
                        forUserCName = p4u.name;
                        System.out.println(realm + "> presenting a PA_FOR_USER " + " in the name of " + p4u.name);
                    }
                }
            }
            if (forUserCName != null) {
                List<String> names = (List<String>) options.get(Option.ALLOW_S4U2SELF);
                if (!names.contains(cname.toString())) {
                    // Mimic the normal KDC behavior. When a server is not
                    // allowed to send S4U2self, do not send an error.
                    // Instead, send a ticket which is useless later.
                    allowForwardable = false;
                }
                cname = forUserCName;
            }
            if (tkt == null) {
                throw new KrbException(Krb5.KDC_ERR_PADATA_TYPE_NOSUPP);
            }
        }
        // Session key for original ticket, TGT
        EncryptionKey ckey = etp.key;
        // Session key for session with the service
        EncryptionKey key = generateRandomKey(e2);
        // Check time, TODO
        KerberosTime till = body.till;
        if (till == null) {
            // TODO
            throw new KrbException(Krb5.KDC_ERR_NEVER_VALID);
        } else if (till.isZero()) {
            till = new KerberosTime(new Date().getTime() + 1000 * 3600 * 11);
        }
        boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX + 1];
        if (body.kdcOptions.get(KDCOptions.FORWARDABLE) && allowForwardable) {
            List<String> sensitives = (List<String>) options.get(Option.SENSITIVE_ACCOUNTS);
            if (sensitives != null && sensitives.contains(cname.toString())) {
            // Cannot make FORWARDABLE
            } else {
                bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
            }
        }
        if (body.kdcOptions.get(KDCOptions.FORWARDED) || etp.flags.get(Krb5.TKT_OPTS_FORWARDED)) {
            bFlags[Krb5.TKT_OPTS_FORWARDED] = true;
        }
        if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
            bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
        //renew = new KerberosTime(new Date().getTime() + 1000 * 3600 * 24 * 7);
        }
        if (body.kdcOptions.get(KDCOptions.PROXIABLE)) {
            bFlags[Krb5.TKT_OPTS_PROXIABLE] = true;
        }
        if (body.kdcOptions.get(KDCOptions.POSTDATED)) {
            bFlags[Krb5.TKT_OPTS_POSTDATED] = true;
        }
        if (body.kdcOptions.get(KDCOptions.ALLOW_POSTDATE)) {
            bFlags[Krb5.TKT_OPTS_MAY_POSTDATE] = true;
        }
        if (body.kdcOptions.get(KDCOptions.CNAME_IN_ADDL_TKT)) {
            if (!options.containsKey(Option.ALLOW_S4U2PROXY)) {
                // Don't understand CNAME_IN_ADDL_TKT
                throw new KrbException(Krb5.KDC_ERR_BADOPTION);
            } else {
                Map<String, List<String>> map = (Map<String, List<String>>) options.get(Option.ALLOW_S4U2PROXY);
                Ticket second = KDCReqBodyDotFirstAdditionalTicket(body);
                EncryptionKey key2 = keyForUser(second.sname, second.encPart.getEType(), true);
                byte[] bb = second.encPart.decrypt(key2, KeyUsage.KU_TICKET);
                DerInputStream derIn = new DerInputStream(bb);
                DerValue der = derIn.getDerValue();
                EncTicketPart tktEncPart = new EncTicketPart(der.toByteArray());
                if (!tktEncPart.flags.get(Krb5.TKT_OPTS_FORWARDABLE)) {
                //throw new KrbException(Krb5.KDC_ERR_BADOPTION);
                }
                PrincipalName client = tktEncPart.cname;
                System.out.println(realm + "> and an additional ticket of " + client + " to " + second.sname);
                if (map.containsKey(cname.toString())) {
                    if (map.get(cname.toString()).contains(service.toString())) {
                        System.out.println(realm + "> S4U2proxy OK");
                    } else {
                        throw new KrbException(Krb5.KDC_ERR_BADOPTION);
                    }
                } else {
                    throw new KrbException(Krb5.KDC_ERR_BADOPTION);
                }
                cname = client;
            }
        }
        String okAsDelegate = (String) options.get(Option.OK_AS_DELEGATE);
        if (okAsDelegate != null && (okAsDelegate.isEmpty() || okAsDelegate.contains(service.getNameString()))) {
            bFlags[Krb5.TKT_OPTS_DELEGATE] = true;
        }
        bFlags[Krb5.TKT_OPTS_INITIAL] = true;
        TicketFlags tFlags = new TicketFlags(bFlags);
        EncTicketPart enc = new EncTicketPart(tFlags, key, cname, // TODO
        new TransitedEncoding(1, new byte[0]), new KerberosTime(new Date()), body.from, till, body.rtime, // always set caddr
        body.addresses != null ? body.addresses : new HostAddresses(new InetAddress[] { InetAddress.getLocalHost() }), null);
        EncryptionKey skey = keyForUser(service, e3, true);
        if (skey == null) {
            // TODO
            throw new KrbException(Krb5.KDC_ERR_SUMTYPE_NOSUPP);
        }
        Ticket t = new Ticket(service, new EncryptedData(skey, enc.asn1Encode(), KeyUsage.KU_TICKET));
        EncTGSRepPart enc_part = new EncTGSRepPart(key, new LastReq(new LastReqEntry[] { new LastReqEntry(0, new KerberosTime(new Date().getTime() - 10000)) }), // TODO: detect replay
        body.getNonce(), new KerberosTime(new Date().getTime() + 1000 * 3600 * 24), // Next 5 and last MUST be same with ticket
        tFlags, new KerberosTime(new Date()), body.from, till, body.rtime, service, // always set caddr
        body.addresses != null ? body.addresses : new HostAddresses(new InetAddress[] { InetAddress.getLocalHost() }));
        EncryptedData edata = new EncryptedData(ckey, enc_part.asn1Encode(), KeyUsage.KU_ENC_TGS_REP_PART_SESSKEY);
        TGSRep tgsRep = new TGSRep(null, cname, t, edata);
        System.out.println("     Return " + tgsRep.cname + " ticket for " + tgsRep.ticket.sname + ", flags " + tFlags);
        DerOutputStream out = new DerOutputStream();
        out.write(DerValue.createTag(DerValue.TAG_APPLICATION, true, (byte) Krb5.KRB_TGS_REP), tgsRep.asn1Encode());
        return out.toByteArray();
    } catch (KrbException ke) {
        ke.printStackTrace(System.out);
        KRBError kerr = ke.getError();
        KDCReqBody body = tgsReq.reqBody;
        System.out.println("     Error " + ke.returnCode() + " " + ke.returnCodeMessage());
        if (kerr == null) {
            kerr = new KRBError(null, null, null, new KerberosTime(new Date()), 0, ke.returnCode(), body.cname, service, KrbException.errorMessage(ke.returnCode()), null);
        }
        return kerr.asn1Encode();
    }
}
Also used : DerOutputStream(sun.security.util.DerOutputStream) DerValue(sun.security.util.DerValue) DerInputStream(sun.security.util.DerInputStream)

Example 7 with DerValue

use of sun.security.util.DerValue in project j2objc by google.

the class X400Address method encode.

/**
     * Encode the X400 name into the DerOutputStream.
     *
     * @param out the DER stream to encode the X400Address to.
     * @exception IOException on encoding errors.
     */
public void encode(DerOutputStream out) throws IOException {
    DerValue derValue = new DerValue(nameValue);
    out.putDerValue(derValue);
}
Also used : DerValue(sun.security.util.DerValue)

Example 8 with DerValue

use of sun.security.util.DerValue in project jdk8u_jdk by JetBrains.

the class KerberosTime method parse.

/**
     * Parse (unmarshal) a kerberostime from a DER input stream.  This form
     * parsing might be used when expanding a value which is part of
     * a constructed sequence and uses explicitly tagged type.
     *
     * @exception Asn1Exception on error.
     * @param data the Der input stream value, which contains
     *             one or more marshaled value.
     * @param explicitTag tag number.
     * @param optional indicates if this data field is optional
     * @return an instance of KerberosTime.
     *
     */
public static KerberosTime parse(DerInputStream data, byte explicitTag, boolean optional) throws Asn1Exception, IOException {
    if ((optional) && (((byte) data.peekByte() & (byte) 0x1F) != explicitTag))
        return null;
    DerValue der = data.getDerValue();
    if (explicitTag != (der.getTag() & (byte) 0x1F)) {
        throw new Asn1Exception(Krb5.ASN1_BAD_ID);
    } else {
        DerValue subDer = der.getData().getDerValue();
        Date temp = subDer.getGeneralizedTime();
        return new KerberosTime(temp.getTime(), 0);
    }
}
Also used : DerValue(sun.security.util.DerValue) Asn1Exception(sun.security.krb5.Asn1Exception) Date(java.util.Date)

Example 9 with DerValue

use of sun.security.util.DerValue in project jdk8u_jdk by JetBrains.

the class ESSCertId method parse.

public void parse(byte[] bytes) throws IOException {
    // Parse signingCertificate
    DerValue derValue = new DerValue(bytes);
    if (derValue.tag != DerValue.tag_Sequence) {
        throw new IOException("Bad encoding for signingCertificate");
    }
    // Parse certs
    DerValue[] certs = derValue.data.getSequence(1);
    certId = new ESSCertId[certs.length];
    for (int i = 0; i < certs.length; i++) {
        certId[i] = new ESSCertId(certs[i]);
    }
    // Parse policies, if present
    if (derValue.data.available() > 0) {
        DerValue[] policies = derValue.data.getSequence(1);
        for (int i = 0; i < policies.length; i++) {
        // parse PolicyInformation
        }
    }
}
Also used : DerValue(sun.security.util.DerValue) IOException(java.io.IOException)

Example 10 with DerValue

use of sun.security.util.DerValue in project jdk8u_jdk by JetBrains.

the class PKCS12KeyStore method engineStore.

/**
     * Stores this keystore to the given output stream, and protects its
     * integrity with the given password.
     *
     * @param stream the output stream to which this keystore is written.
     * @param password the password to generate the keystore integrity check
     *
     * @exception IOException if there was an I/O problem with data
     * @exception NoSuchAlgorithmException if the appropriate data integrity
     * algorithm could not be found
     * @exception CertificateException if any of the certificates included in
     * the keystore data could not be stored
     */
public synchronized void engineStore(OutputStream stream, char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
    // password is mandatory when storing
    if (password == null) {
        throw new IllegalArgumentException("password can't be null");
    }
    // -- Create PFX
    DerOutputStream pfx = new DerOutputStream();
    // PFX version (always write the latest version)
    DerOutputStream version = new DerOutputStream();
    version.putInteger(VERSION_3);
    byte[] pfxVersion = version.toByteArray();
    pfx.write(pfxVersion);
    // -- Create AuthSafe
    DerOutputStream authSafe = new DerOutputStream();
    // -- Create ContentInfos
    DerOutputStream authSafeContentInfo = new DerOutputStream();
    // -- create safeContent Data ContentInfo
    if (privateKeyCount > 0 || secretKeyCount > 0) {
        if (debug != null) {
            debug.println("Storing " + (privateKeyCount + secretKeyCount) + " protected key(s) in a PKCS#7 data content-type");
        }
        byte[] safeContentData = createSafeContent();
        ContentInfo dataContentInfo = new ContentInfo(safeContentData);
        dataContentInfo.encode(authSafeContentInfo);
    }
    // -- create EncryptedContentInfo
    if (certificateCount > 0) {
        if (debug != null) {
            debug.println("Storing " + certificateCount + " certificate(s) in a PKCS#7 encryptedData content-type");
        }
        byte[] encrData = createEncryptedData(password);
        ContentInfo encrContentInfo = new ContentInfo(ContentInfo.ENCRYPTED_DATA_OID, new DerValue(encrData));
        encrContentInfo.encode(authSafeContentInfo);
    }
    // wrap as SequenceOf ContentInfos
    DerOutputStream cInfo = new DerOutputStream();
    cInfo.write(DerValue.tag_SequenceOf, authSafeContentInfo);
    byte[] authenticatedSafe = cInfo.toByteArray();
    // Create Encapsulated ContentInfo
    ContentInfo contentInfo = new ContentInfo(authenticatedSafe);
    contentInfo.encode(authSafe);
    byte[] authSafeData = authSafe.toByteArray();
    pfx.write(authSafeData);
    // -- MAC
    byte[] macData = calculateMac(password, authenticatedSafe);
    pfx.write(macData);
    // write PFX to output stream
    DerOutputStream pfxout = new DerOutputStream();
    pfxout.write(DerValue.tag_Sequence, pfx);
    byte[] pfxData = pfxout.toByteArray();
    stream.write(pfxData);
    stream.flush();
}
Also used : DerOutputStream(sun.security.util.DerOutputStream) ContentInfo(sun.security.pkcs.ContentInfo) DerValue(sun.security.util.DerValue)

Aggregations

DerValue (sun.security.util.DerValue)72 DerInputStream (sun.security.util.DerInputStream)26 IOException (java.io.IOException)25 ObjectIdentifier (sun.security.util.ObjectIdentifier)17 CertificateException (java.security.cert.CertificateException)12 DerOutputStream (sun.security.util.DerOutputStream)11 UnrecoverableKeyException (java.security.UnrecoverableKeyException)10 BigInteger (java.math.BigInteger)9 KeyStoreException (java.security.KeyStoreException)9 X509Certificate (java.security.cert.X509Certificate)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 UnrecoverableEntryException (java.security.UnrecoverableEntryException)8 CertificateFactory (java.security.cert.CertificateFactory)7 DestroyFailedException (javax.security.auth.DestroyFailedException)6 X500Principal (javax.security.auth.x500.X500Principal)6 X509CertImpl (sun.security.x509.X509CertImpl)6 AlgorithmId (sun.security.x509.AlgorithmId)5 AlgorithmParameters (java.security.AlgorithmParameters)4 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)4 KeyFactory (java.security.KeyFactory)4