Search in sources :

Example 16 with DerOutputStream

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

the class NotPreferredMech method main.

public static void main(String[] argv) throws Exception {
    // Generates a NegTokenInit mechTypes field, with an
    // unsupported mech as the preferred.
    DerOutputStream mech = new DerOutputStream();
    mech.write(new Oid("1.2.3.4").getDER());
    mech.write(GSSUtil.GSS_KRB5_MECH_OID.getDER());
    DerOutputStream mechTypeList = new DerOutputStream();
    mechTypeList.write(DerValue.tag_Sequence, mech);
    // Generates a NegTokenInit mechToken field for 1.2.3.4 mech
    GSSHeader h1 = new GSSHeader(new ObjectIdentifier("1.2.3.4"), 1);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    h1.encode(bout);
    bout.write(new byte[1]);
    // Generates the NegTokenInit token
    Constructor<NegTokenInit> ctor = NegTokenInit.class.getDeclaredConstructor(byte[].class, BitArray.class, byte[].class, byte[].class);
    ctor.setAccessible(true);
    NegTokenInit initToken = ctor.newInstance(mechTypeList.toByteArray(), new BitArray(0), bout.toByteArray(), null);
    Method m = Class.forName("sun.security.jgss.spnego.SpNegoToken").getDeclaredMethod("getEncoded");
    m.setAccessible(true);
    byte[] spnegoToken = (byte[]) m.invoke(initToken);
    // and wraps it into a GSSToken
    GSSHeader h = new GSSHeader(new ObjectIdentifier(GSSUtil.GSS_SPNEGO_MECH_OID.toString()), spnegoToken.length);
    bout = new ByteArrayOutputStream();
    h.encode(bout);
    bout.write(spnegoToken);
    byte[] token = bout.toByteArray();
    // and feeds it to a GSS acceptor
    GSSManager man = GSSManager.getInstance();
    GSSContext ctxt = man.createContext((GSSCredential) null);
    token = ctxt.acceptSecContext(token, 0, token.length);
    NegTokenTarg targ = new NegTokenTarg(token);
    // Make sure it's a GO-ON message
    Method m2 = NegTokenTarg.class.getDeclaredMethod("getNegotiatedResult");
    m2.setAccessible(true);
    int negResult = (int) m2.invoke(targ);
    if (negResult != 1) /* ACCEPT_INCOMPLETE */
    {
        throw new Exception("Not a continue");
    }
}
Also used : NegTokenTarg(sun.security.jgss.spnego.NegTokenTarg) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Method(java.lang.reflect.Method) DerOutputStream(sun.security.util.DerOutputStream) NegTokenInit(sun.security.jgss.spnego.NegTokenInit) BitArray(sun.security.util.BitArray) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 17 with DerOutputStream

use of sun.security.util.DerOutputStream 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 18 with DerOutputStream

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

the class KerberosTime method asn1Encode.

/**
     * Encodes this object to a byte array.
     * @return a byte array of encoded data.
     * @exception Asn1Exception if an error occurs while decoding an ASN1 encoded data.
     * @exception IOException if an I/O error occurs while reading encoded data.
     */
public byte[] asn1Encode() throws Asn1Exception, IOException {
    DerOutputStream out = new DerOutputStream();
    out.putGeneralizedTime(this.toDate());
    return out.toByteArray();
}
Also used : DerOutputStream(sun.security.util.DerOutputStream)

Example 19 with DerOutputStream

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

the class PAForUserEnc method asn1Encode.

public byte[] asn1Encode() throws Asn1Exception, IOException {
    DerOutputStream bytes = new DerOutputStream();
    bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x00), name.asn1Encode());
    bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x01), name.getRealm().asn1Encode());
    try {
        Checksum cks = new Checksum(Checksum.CKSUMTYPE_HMAC_MD5_ARCFOUR, getS4UByteArray(), key, KeyUsage.KU_PA_FOR_USER_ENC_CKSUM);
        bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x02), cks.asn1Encode());
    } catch (KrbException ke) {
        throw new IOException(ke);
    }
    DerOutputStream temp = new DerOutputStream();
    temp.putDerValue(new KerberosString(AUTH_PACKAGE).toDerValue());
    bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0x03), temp);
    temp = new DerOutputStream();
    temp.write(DerValue.tag_Sequence, bytes);
    return temp.toByteArray();
}
Also used : DerOutputStream(sun.security.util.DerOutputStream) IOException(java.io.IOException) KerberosString(sun.security.krb5.internal.util.KerberosString)

Example 20 with DerOutputStream

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

the class SignerInfo method derEncode.

/**
     * DER encode this object onto an output stream.
     * Implements the {@code DerEncoder} interface.
     *
     * @param out
     * the output stream on which to write the DER encoding.
     *
     * @exception IOException on encoding error.
     */
public void derEncode(OutputStream out) throws IOException {
    DerOutputStream seq = new DerOutputStream();
    seq.putInteger(version);
    DerOutputStream issuerAndSerialNumber = new DerOutputStream();
    issuerName.encode(issuerAndSerialNumber);
    issuerAndSerialNumber.putInteger(certificateSerialNumber);
    seq.write(DerValue.tag_Sequence, issuerAndSerialNumber);
    digestAlgorithmId.encode(seq);
    // encode authenticated attributes if there are any
    if (authenticatedAttributes != null)
        authenticatedAttributes.encode((byte) 0xA0, seq);
    digestEncryptionAlgorithmId.encode(seq);
    seq.putOctetString(encryptedDigest);
    // encode unauthenticated attributes if there are any
    if (unauthenticatedAttributes != null)
        unauthenticatedAttributes.encode((byte) 0xA1, seq);
    DerOutputStream tmp = new DerOutputStream();
    tmp.write(DerValue.tag_Sequence, seq);
    out.write(tmp.toByteArray());
}
Also used : DerOutputStream(sun.security.util.DerOutputStream)

Aggregations

DerOutputStream (sun.security.util.DerOutputStream)79 IOException (java.io.IOException)9 DerValue (sun.security.util.DerValue)8 ObjectIdentifier (sun.security.util.ObjectIdentifier)6 CertificateException (java.security.cert.CertificateException)5 BitArray (sun.security.util.BitArray)5 X509Certificate (java.security.cert.X509Certificate)4 AlgorithmId (sun.security.x509.AlgorithmId)4 KeyStoreException (java.security.KeyStoreException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 UnrecoverableEntryException (java.security.UnrecoverableEntryException)3 UnrecoverableKeyException (java.security.UnrecoverableKeyException)3 CertificateEncodingException (java.security.cert.CertificateEncodingException)3 Date (java.util.Date)3 SecretKey (javax.crypto.SecretKey)3 DestroyFailedException (javax.security.auth.DestroyFailedException)3 ContentInfo (sun.security.pkcs.ContentInfo)3 DerInputStream (sun.security.util.DerInputStream)3 PolicyQualifierInfo (java.security.cert.PolicyQualifierInfo)2 X509CertSelector (java.security.cert.X509CertSelector)2