Esempio n. 1
0
        /// <summary>
        /// Create AP request and encode to GSSAPI token
        /// </summary>
        /// <param name="apOptions">AP options</param>
        /// <param name="data">Authorization data</param>
        /// <param name="subkey">Sub-session key in authenticator</param>
        /// <param name="checksumFlags">Checksum flags</param>
        /// <returns></returns>
        private byte[] CreateGssApiToken(ApOptions apOptions, AuthorizationData data, EncryptionKey subkey, ChecksumFlags checksumFlags, KerberosConstValue.GSSToken gssToken = KerberosConstValue.GSSToken.GSSSPNG)
        {
            APOptions options = new APOptions(KerberosUtility.ConvertInt2Flags((int)apOptions));

            Authenticator authenticator = CreateAuthenticator(Context.Ticket, data, subkey, checksumFlags);

            this.ApRequestAuthenticator = authenticator;
            KerberosApRequest request = new KerberosApRequest(
                Context.Pvno,
                options,
                Context.Ticket,
                authenticator,
                KeyUsageNumber.AP_REQ_Authenticator
                );

            this.client.UpdateContext(request);

            if ((this.Context.ChecksumFlag & ChecksumFlags.GSS_C_DCE_STYLE) == ChecksumFlags.GSS_C_DCE_STYLE)
            {
                return(request.ToBytes());
            }
            else
            {
                return(KerberosUtility.AddGssApiTokenHeader(request, this.client.OidPkt, gssToken));
            }
        }
        /// <summary>
        /// Update the Authorization Data part in Ticket with new value.
        /// </summary>
        /// <param name="ticket">Ticket to be updated with new authorizationData</param>
        /// <param name="key">The key that encrypts ticket part.</param>
        /// <param name="authorizationData">New authorizationData to update.</param>
        public static void UpdateAuthDataInTicket(Ticket ticket, byte[] key, AuthorizationData authorizationData)
        {
            EncryptionType encryptType = (EncryptionType)ticket.enc_part.etype.Value;

            byte[] clearText = KerberosUtility.Decrypt(
                encryptType,
                key,
                ticket.enc_part.cipher.ByteArrayValue,
                (int)KeyUsageNumber.AS_REP_TicketAndTGS_REP_Ticket);

            // Decode the ticket.
            Asn1DecodingBuffer decodeBuffer  = new Asn1DecodingBuffer(clearText);
            EncTicketPart      encTicketPart = new EncTicketPart();

            encTicketPart.BerDecode(decodeBuffer);

            // Set with new authorization data
            encTicketPart.authorization_data = authorizationData;
            Asn1BerEncodingBuffer ticketBerBuffer = new Asn1BerEncodingBuffer();

            encTicketPart.BerEncode(ticketBerBuffer, true);

            byte[] cipherData = KerberosUtility.Encrypt(
                encryptType,
                key,
                ticketBerBuffer.Data,
                (int)KeyUsageNumber.AS_REP_TicketAndTGS_REP_Ticket);
            ticket.enc_part = new EncryptedData(new KerbInt32((int)encryptType), null, new Asn1OctetString(cipherData));
        }
 private void UpdateContext(KerberosTgsResponse response)
 {
     if (response.Response != null)
     {
         if (response.Response.padata != null && response.Response.padata.Elements != null)
         {
             foreach (PA_DATA paData in response.Response.padata.Elements)
             {
                 var parsedPaData = PaDataParser.ParseRepPaData(paData);
                 if (parsedPaData is PaFxFastRep)
                 {
                     var armoredRep = ((PaFxFastRep)parsedPaData).GetArmoredRep();
                     var kerbRep    = ((PaFxFastRep)parsedPaData).GetKerberosFastRep(Context.FastArmorkey);
                     var strKey     = kerbRep.FastResponse.strengthen_key;
                     Context.ReplyKey = KerberosUtility.KrbFxCf2(strKey, Context.ReplyKey, "strengthenkey", "replykey");
                 }
             }
         }
         KeyUsageNumber usage =
             Context.Subkey == null ? KeyUsageNumber.TGS_REP_encrypted_part : KeyUsageNumber.TGS_REP_encrypted_part_subkey;
         response.DecryptTgsResponse(Context.ReplyKey.keyvalue.ByteArrayValue, usage);
         Context.SessionKey = response.EncPart.key;
         //Fix me: when hide-client-names is set to true, response.Response.cname is not the real CName.
         Context.Ticket        = new KerberosTicket(response.Response.ticket, response.Response.cname, response.EncPart.key);
         Context.SelectedEType = (EncryptionType)Context.Ticket.Ticket.enc_part.etype.Value;
     }
 }
Esempio n. 4
0
        private void SendTgsRequest(string sName, KdcOptions kdcOptions, Asn1SequenceOf <PA_DATA> seqPadata = null, AuthorizationData dataInAuthentiator = null, AuthorizationData dataInEncAuthData = null, MsgType msgType = MsgType.KRB_TGS_REQ)
        {
            if (string.IsNullOrEmpty(sName))
            {
                throw new ArgumentNullException("sName");
            }
            PrincipalName sname = new PrincipalName(new KerbInt32((int)PrincipalType.NT_SRV_INST), KerberosUtility.String2SeqKerbString(sName.Split('/')));

            KDC_REQ_BODY          kdcReqBody = this.CreateKdcRequestBody(kdcOptions, sname, dataInEncAuthData); // almost same as AS request
            Asn1BerEncodingBuffer bodyBuffer = new Asn1BerEncodingBuffer();

            kdcReqBody.BerEncode(bodyBuffer);

            ChecksumType checksumType = KerberosUtility.GetChecksumType(this.Context.SelectedEType);
            PA_DATA      paTgsReq     = CreatePaTgsReqest(checksumType, bodyBuffer.Data, dataInAuthentiator); // use AS session key encrypt authenticator.

            Asn1SequenceOf <PA_DATA> tempPaData = null;

            if (seqPadata == null || seqPadata.Elements == null || seqPadata.Elements.Length == 0)
            {
                tempPaData = new Asn1SequenceOf <PA_DATA>(new PA_DATA[] { paTgsReq });
            }
            else
            {
                PA_DATA[] paDatas = new PA_DATA[seqPadata.Elements.Length + 1];
                Array.Copy(seqPadata.Elements, paDatas, seqPadata.Elements.Length);
                paDatas[seqPadata.Elements.Length] = paTgsReq;
                tempPaData = new Asn1SequenceOf <PA_DATA>(paDatas);
            }

            KerberosTgsRequest tgsRequest = new KerberosTgsRequest(KerberosConstValue.KERBEROSV5, kdcReqBody, tempPaData, Context.TransportType);

            tgsRequest.Request.msg_type.Value = (long)msgType;
            this.client.SendPdu(tgsRequest);
        }
        public PaEncTimeStamp(string timeStamp, int usec, EncryptionType eType, string password, string salt)
        {
            this.TimeStamp = timeStamp;
            this.Usec      = usec;
            byte[] key = KeyGenerator.MakeKey(eType, password, salt);
            this.Key = new EncryptionKey(new KerbInt32((long)eType), new Asn1OctetString(key));

            // create a timestamp
            PA_ENC_TS_ENC         paEncTsEnc          = new PA_ENC_TS_ENC(new KerberosTime(this.TimeStamp), new Microseconds(this.Usec));
            Asn1BerEncodingBuffer currTimeStampBuffer = new Asn1BerEncodingBuffer();

            paEncTsEnc.BerEncode(currTimeStampBuffer);
            var rawData = currTimeStampBuffer.Data;

            KerberosUtility.OnDumpMessage("KRB5:PA-ENC-TS-ENC",
                                          "Encrypted Timestamp Pre-authentication",
                                          KerberosUtility.DumpLevel.PartialMessage,
                                          rawData);
            // encrypt the timestamp
            byte[] encTimeStamp = KerberosUtility.Encrypt((EncryptionType)this.Key.keytype.Value,
                                                          this.Key.keyvalue.ByteArrayValue,
                                                          rawData,
                                                          (int)KeyUsageNumber.PA_ENC_TIMESTAMP);

            // create an encrypted timestamp
            PA_ENC_TIMESTAMP paEncTimeStamp =
                new PA_ENC_TIMESTAMP(new KerbInt32(this.Key.keytype.Value), null, new Asn1OctetString(encTimeStamp));
            Asn1BerEncodingBuffer paEncTimestampBuffer = new Asn1BerEncodingBuffer();

            paEncTimeStamp.BerEncode(paEncTimestampBuffer, true);

            Data = new PA_DATA(new KerbInt32((long)PaDataType.PA_ENC_TIMESTAMP), new Asn1OctetString(paEncTimestampBuffer.Data));
        }
Esempio n. 6
0
        private KDC_REQ_BODY CreateKdcRequestBody(KdcOptions kdcOptions, PrincipalName sName, AuthorizationData authData = null)
        {
            KDC_REQ_BODY kdcReqBody = this.CreateKdcRequestBody(kdcOptions, sName);

            if (authData == null)
            {
                return(kdcReqBody);
            }

            Asn1BerEncodingBuffer asnEncBuffer = new Asn1BerEncodingBuffer();

            authData.BerEncode(asnEncBuffer, true);

            EncryptedData encryptData = new EncryptedData();

            encryptData.etype = new KerbInt32(0);
            byte[] encryptAsnEncoded = asnEncBuffer.Data;
            if (this.Context.SessionKey != null && this.Context.SessionKey.keytype != null && this.Context.SessionKey.keyvalue != null && this.Context.SessionKey.keyvalue.Value != null)
            {
                encryptAsnEncoded = KerberosUtility.Encrypt(
                    (EncryptionType)this.Context.SessionKey.keytype.Value,
                    this.Context.SessionKey.keyvalue.ByteArrayValue,
                    encryptAsnEncoded,
                    (int)KeyUsageNumber.TGS_REQ_KDC_REQ_BODY_AuthorizationData
                    );

                encryptData.etype = new KerbInt32(this.Context.SessionKey.keytype.Value);
            }
            encryptData.cipher = new Asn1OctetString(encryptAsnEncoded);
            kdcReqBody.enc_authorization_data = encryptData;

            return(kdcReqBody);
        }
        /// <summary>
        /// Add a token header for AP request/response, wrap token or getmic token to make them a complete token.
        /// </summary>
        /// <param name="tokenBody">The AP request/response, wrap token or getmic token.
        /// This argument can be null.</param>
        /// <returns>The completed token.</returns>
        public static byte[] AddGssApiTokenHeader(byte[] tokenBody,
                                                  KerberosConstValue.OidPkt oidPkt     = KerberosConstValue.OidPkt.KerberosToken,
                                                  KerberosConstValue.GSSToken gssToken = KerberosConstValue.GSSToken.GSSSPNG)
        {
            List <byte> gssDataList = new List <byte>();

            gssDataList.Add(KerberosConstValue.KERBEROS_TAG);

            // kerberos oid (1.2.840.113554.1.2.2)
            byte[] oid;
            oid = KerberosConstValue.GetKerberosOid();

            if (tokenBody == null)
            {
                tokenBody = new byte[0];
            }

            int length = tokenBody.Length + oid.Length;

            if (length > 127)
            {
                // If the indicated value is 128 or more, it shall be represented in two or more octets,
                // with bit 8 of the first octet set to "1" and the remaining bits of the first octet
                // specifying the number of additional octets. The subsequent octets carry the value,
                // 8 bits per octet, most significant digit first. [rfc 2743]
                int         temp       = length;
                int         index      = 1;
                List <byte> lengthList = new List <byte>();
                lengthList.Add((byte)(temp & 0xFF));
                while ((temp >>= 8) != 0)
                {
                    index++;
                    lengthList.Add((byte)(temp & 0xFF));
                }

                gssDataList.Add((byte)(0x80 | index));
                lengthList.Reverse();
                gssDataList.AddRange(lengthList.ToArray());
            }
            else
            {
                // If the indicated value is less than 128, it shall be represented in a single octet with bit 8
                // (high order) set to "0" and the remaining bits representing the value. [rfc 2743]
                gssDataList.Add((byte)length);
            }

            gssDataList.AddRange(oid);
            gssDataList.AddRange(tokenBody);

            if (gssToken == KerberosConstValue.GSSToken.GSSAPI)
            {
                return(gssDataList.ToArray());
            }
            else
            {
                return(KerberosUtility.EncodeInitialNegToken(gssDataList.ToArray(), oidPkt));
            }
        }
Esempio n. 8
0
        private Authenticator CreateAuthenticator(KerberosTicket ticket, AuthorizationData data, EncryptionKey subKey, ChecksumType checksumType, byte[] checksumBody)
        {
            Authenticator plaintextAuthenticator = CreateAuthenticator(ticket, data, subKey);

            byte[] checkData = KerberosUtility.GetChecksum(ticket.SessionKey.keyvalue.ByteArrayValue, checksumBody, (int)KeyUsageNumber.TGS_REQ_PA_TGS_REQ_adataOR_AP_REQ_Authenticator_cksum, checksumType);
            plaintextAuthenticator.cksum = new Checksum(new KerbInt32((int)checksumType), new Asn1OctetString(checkData));

            return(plaintextAuthenticator);
        }
Esempio n. 9
0
        private PA_DATA CreatePaTgsReqest(ChecksumType checksumType, byte[] checksumBody, AuthorizationData data)
        {
            APOptions         option    = new APOptions(KerberosUtility.ConvertInt2Flags((int)ApOptions.None));
            EncryptionKey     key       = Context.SessionKey;
            KerberosApRequest apRequest = CreateApRequest(option, Context.Ticket, null, data, KeyUsageNumber.TG_REQ_PA_TGS_REQ_padataOR_AP_REQ_Authenticator, checksumType, checksumBody);

            PaTgsReq paTgsReq = new PaTgsReq(apRequest.Request);

            return(paTgsReq.Data);
        }
        public static byte[] AddGssApiTokenHeader(KerberosApRequest request,
                                                  KerberosConstValue.OidPkt oidPkt     = KerberosConstValue.OidPkt.KerberosToken,
                                                  KerberosConstValue.GSSToken gssToken = KerberosConstValue.GSSToken.GSSSPNG)
        {
            byte[] encoded = request.ToBytes();
            byte[] token   = KerberosUtility.AddGssApiTokenHeader(ArrayUtility.ConcatenateArrays(
                                                                      BitConverter.GetBytes(KerberosUtility.ConvertEndian((ushort)TOK_ID.KRB_AP_REQ)), encoded), oidPkt, gssToken);

            return(token);
        }
Esempio n. 11
0
        /// <summary>
        /// Decode GSSAPI token to AP-REP
        /// </summary>
        /// <param name="token">GSSAPI token</param>
        /// <returns></returns>
        private KerberosApResponse GetApResponseFromToken(byte[] token, KerberosConstValue.GSSToken gssToken = KerberosConstValue.GSSToken.GSSSPNG)
        {
            if (gssToken == KerberosConstValue.GSSToken.GSSSPNG)
            {
                token = KerberosUtility.DecodeNegotiationToken(token);
            }

            if (token[0] == KerberosConstValue.KERBEROS_TAG)
            {
                byte[] apData = KerberosUtility.VerifyGssApiTokenHeader(token, this.client.OidPkt);

                // Check if it has a two-byte tok_id
                if (null == apData || apData.Length <= sizeof(TOK_ID))
                {
                    throw new FormatException(
                              "Data length is shorter than a valid AP Response data length.");
                }

                // verify TOK_ID
                byte[] tokenID = ArrayUtility.SubArray <byte>(apData, 0, sizeof(TOK_ID));
                Array.Reverse(tokenID);
                TOK_ID id = (TOK_ID)BitConverter.ToUInt16(tokenID, 0);

                if (!id.Equals(TOK_ID.KRB_AP_REP))
                {
                    throw new Exception("ApResponse Token ID should be KRB_AP_REP");
                }

                // Get apBody
                token = ArrayUtility.SubArray(apData, sizeof(TOK_ID));
            }

            KerberosApResponse apRep = new KerberosApResponse();

            apRep.FromBytes(token);

            // Get the current encryption type, cipher data
            EncryptionType encryptType = (EncryptionType)apRep.Response.enc_part.etype.Value;

            byte[] cipherData = apRep.Response.enc_part.cipher.ByteArrayValue;
            byte[] sessionKey = this.Context.ApSessionKey.keyvalue.ByteArrayValue;

            // decrypt enc_part to clear text
            byte[] clearText = KerberosUtility.Decrypt(encryptType, sessionKey, cipherData, (int)KeyUsageNumber.AP_REP_EncAPRepPart);

            // decode enc_part
            Asn1DecodingBuffer decodeBuffer = new Asn1DecodingBuffer(clearText);

            apRep.ApEncPart = new EncAPRepPart();
            apRep.ApEncPart.BerDecode(decodeBuffer);

            this.client.UpdateContext(apRep);

            return(apRep);
        }
Esempio n. 12
0
        /// <summary>
        /// Client initialize with server token
        /// </summary>
        /// <param name="serverToken">Server token</param>
        private void ClientInitialize(byte[] serverToken)
        {
            KerberosApResponse apRep = this.GetApResponseFromToken(serverToken, KerberosConstValue.GSSToken.GSSAPI);

            this.VerifyApResponse(apRep);

            token = null;
            if ((contextAttribute & ClientSecurityContextAttribute.DceStyle) == ClientSecurityContextAttribute.DceStyle)
            {
                KerberosApResponse apResponse = this.CreateApResponse(null);

                var apBerBuffer = new Asn1BerEncodingBuffer();

                if (apResponse.ApEncPart != null)
                {
                    // Encode enc_part
                    apResponse.ApEncPart.BerEncode(apBerBuffer, true);

                    EncryptionKey key = this.Context.ApSessionKey;

                    if (key == null || key.keytype == null || key.keyvalue == null || key.keyvalue.Value == null)
                    {
                        throw new ArgumentException("Ap session key is not valid");
                    }

                    // Encrypt enc_part
                    EncryptionType eType      = (EncryptionType)key.keytype.Value;
                    byte[]         cipherData = KerberosUtility.Encrypt(
                        eType,
                        key.keyvalue.ByteArrayValue,
                        apBerBuffer.Data,
                        (int)KeyUsageNumber.AP_REP_EncAPRepPart);
                    apResponse.Response.enc_part = new EncryptedData(new KerbInt32((int)eType), null, new Asn1OctetString(cipherData));
                }

                // Encode AP Response
                apResponse.Response.BerEncode(apBerBuffer, true);

                if ((this.Context.ChecksumFlag & ChecksumFlags.GSS_C_DCE_STYLE) == ChecksumFlags.GSS_C_DCE_STYLE)
                {
                    // In DCE mode, the AP-REP message MUST NOT have GSS-API wrapping.
                    // It is sent as is without encapsulating it in a header ([RFC2743] section 3.1).
                    this.token = apBerBuffer.Data;
                }
                else
                {
                    this.token = KerberosUtility.AddGssApiTokenHeader(ArrayUtility.ConcatenateArrays(
                                                                          BitConverter.GetBytes(KerberosUtility.ConvertEndian((ushort)TOK_ID.KRB_AP_REP)),
                                                                          apBerBuffer.Data));
                }
            }

            this.needContinueProcessing = false;      // SEC_E_OK;
        }
 /// <summary>
 /// Wrap a length before the buffer.
 /// </summary>
 /// <param name="buffer">The buffer to be wrapped.</param>
 /// <param name="isBigEndian">Specify if the length is Big-Endian.</param>
 /// <returns>The buffer added length.</returns>
 public static byte[] WrapLength(byte[] buffer, bool isBigEndian)
 {
     if (isBigEndian)
     {
         return(ArrayUtility.ConcatenateArrays(
                    BitConverter.GetBytes(KerberosUtility.ConvertEndian((uint)buffer.Length)), buffer));
     }
     else
     {
         return(ArrayUtility.ConcatenateArrays(BitConverter.GetBytes(buffer.Length), buffer));
     }
 }
        /// <summary>
        /// Decrypt the KRB-PRIV
        /// </summary>
        /// <param name="subkey">the subkey used to decrypt</param>
        public void DecryptKrbPriv(EncryptionKey subkey)
        {
            byte[] priv = KerberosUtility.Decrypt(
                (EncryptionType)subkey.keytype.Value,
                subkey.keyvalue.ByteArrayValue,
                krb_priv.enc_part.cipher.ByteArrayValue,
                (int)KeyUsageNumber.KRB_PRIV_EncPart);

            Asn1DecodingBuffer decodeBuffer = new Asn1DecodingBuffer(priv);

            priv_enc_part.BerDecode(decodeBuffer);
        }
        /// <summary>
        /// Generate a new key, the key type and key length are based on the input key
        /// </summary>
        /// <param name="baseKey">Base key for generation</param>
        /// <returns></returns>
        public static EncryptionKey GenerateKey(EncryptionKey baseKey)
        {
            if (baseKey == null || baseKey.keytype == null ||
                baseKey.keyvalue == null || baseKey.keyvalue.Value == null)
            {
                return(null);
            }

            byte[]        keyBuffer = KerberosUtility.GenerateRandomBytes((uint)baseKey.keyvalue.ByteArrayValue.Length);
            EncryptionKey newKey    = new EncryptionKey(new KerbInt32(baseKey.keytype.Value), new Asn1OctetString(keyBuffer));

            return(newKey);
        }
        public void Decrypt(byte[] armorKey)
        {
            ArmorKey = armorKey;
            var decrypted = KerberosUtility.Decrypt(
                (Cryptographic.EncryptionType)EncFastReq.etype.Value,
                armorKey,
                EncFastReq.cipher.ByteArrayValue,
                (int)KeyUsageNumber.FAST_ENC);
            KrbFastReq krbFastReq = new KrbFastReq();

            krbFastReq.BerDecode(new Asn1DecodingBuffer(decrypted));
            FastReq = new KerberosFastRequest(krbFastReq);
        }
Esempio n. 17
0
        private KerberosAsRequest SendAsRequest(KdcOptions kdcOptions, Asn1SequenceOf <PA_DATA> seqPaData)
        {
            string        sName  = KerberosConstValue.KERBEROS_SNAME;
            string        domain = this.Context.Realm.Value;
            PrincipalName sname  =
                new PrincipalName(new KerbInt32((int)PrincipalType.NT_SRV_INST), KerberosUtility.String2SeqKerbString(sName, domain));

            KDC_REQ_BODY      kdcReqBody = CreateKdcRequestBody(kdcOptions, sname);
            KerberosAsRequest asRequest  = this.CreateAsRequest(kdcReqBody, seqPaData);

            this.client.SendPdu(asRequest);
            return(asRequest);
        }
        /// <summary>
        /// Create an instance.
        /// </summary>
        public KpasswordRequest(KerberosTicket ticket, Authenticator authenticator, string newPwd, bool isAuthErrorRequired = false)
        {
            //Create KerberosApRequest
            long              pvno   = KerberosConstValue.KERBEROSV5;
            APOptions         option = new APOptions(KerberosUtility.ConvertInt2Flags((int)ApOptions.None));
            KerberosApRequest ap_req = new KerberosApRequest(pvno, option, ticket, authenticator, KeyUsageNumber.AP_REQ_Authenticator);
            //Create KRB_PRIV
            ChangePasswdData pwd_data = new ChangePasswdData(new Asn1OctetString(newPwd), null, null);

            priv_enc_part            = new EncKrbPrivPart();
            priv_enc_part.user_data  = pwd_data.newpasswd;
            priv_enc_part.usec       = authenticator.cusec;
            priv_enc_part.seq_number = authenticator.seq_number;
            priv_enc_part.s_address  = new HostAddress(new KerbInt32((int)AddressType.NetBios), new Asn1OctetString(Encoding.ASCII.GetBytes(System.Net.Dns.GetHostName())));
            Asn1BerEncodingBuffer asnBuffPriv = new Asn1BerEncodingBuffer();

            priv_enc_part.BerEncode(asnBuffPriv, true);
            byte[] encAsnEncodedPriv = null;

            if (!isAuthErrorRequired)
            {
                encAsnEncodedPriv = KerberosUtility.Encrypt((EncryptionType)authenticator.subkey.keytype.Value,
                                                            authenticator.subkey.keyvalue.ByteArrayValue,
                                                            asnBuffPriv.Data,
                                                            (int)KeyUsageNumber.KRB_PRIV_EncPart);
            }
            else
            {
                encAsnEncodedPriv = KerberosUtility.Encrypt((EncryptionType)authenticator.subkey.keytype.Value,
                                                            authenticator.subkey.keyvalue.ByteArrayValue,
                                                            asnBuffPriv.Data,
                                                            (int)KeyUsageNumber.None);
            }

            var encrypted = new EncryptedData();

            encrypted.etype  = new KerbInt32(authenticator.subkey.keytype.Value);
            encrypted.cipher = new Asn1OctetString(encAsnEncodedPriv);
            KRB_PRIV krb_priv = new KRB_PRIV(new Asn1Integer(pvno), new Asn1Integer((long)MsgType.KRB_PRIV), encrypted);

            //Calculate the msg_length and ap_req_length
            krb_priv.BerEncode(privBuffer, true);
            ap_req.Request.BerEncode(apBuffer, true);
            version       = 0x0001;
            ap_req_length = (ushort)apBuffer.Data.Length;
            msg_length    = (ushort)(ap_req_length + privBuffer.Data.Length + 3 * sizeof(ushort));
            //Convert Endian
            version       = KerberosUtility.ConvertEndian(version);
            ap_req_length = KerberosUtility.ConvertEndian(ap_req_length);
            msg_length    = KerberosUtility.ConvertEndian(msg_length);
        }
        public byte[] ToBytes(TransportType transportType)
        {
            Asn1BerEncodingBuffer asBerBuffer = new Asn1BerEncodingBuffer();

            this.FastReq.BerEncode(asBerBuffer, true);
            if (transportType == TransportType.TCP)
            {
                return(KerberosUtility.WrapLength(asBerBuffer.Data, true));
            }
            else
            {
                return(asBerBuffer.Data);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Encode the Krb Error to bytes
        /// </summary>
        /// <param name="buffer">The byte array to be decoded.</param>
        public override byte[] ToBytes()
        {
            Asn1BerEncodingBuffer errorBerBuffer = new Asn1BerEncodingBuffer();

            this.KrbError.BerEncode(errorBerBuffer, true);

            if (transportType == TransportType.TCP)
            {
                return(KerberosUtility.WrapLength(errorBerBuffer.Data, true));
            }
            else
            {
                return(errorBerBuffer.Data);
            }
        }
        /// <summary>
        /// Decode TGS Response from bytes
        /// </summary>
        /// <param name="buffer">byte array to be decoded</param>
        /// <exception cref="System.ArgumentNullException">thrown when input buffer is null</exception>
        public override void FromBytes(byte[] buffer)
        {
            if (null == buffer)
            {
                throw new ArgumentNullException("buffer");
            }
            KerberosUtility.OnDumpMessage("KRB5:KrbMessage",
                                          "Kerberos Message",
                                          KerberosUtility.DumpLevel.WholeMessage,
                                          buffer);
            // Decode TGS Response
            Asn1DecodingBuffer decodeBuffer = new Asn1DecodingBuffer(buffer);

            Response.BerDecode(decodeBuffer);
        }
Esempio n. 22
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="account">Account credential.</param>
        /// <param name="logonName">Logon name.</param>
        /// <param name="serviceName">Service name.</param>
        /// <param name="kdcIpAddress">KDC IP address</param>
        /// <param name="attributes">Client security attributes.</param>
        /// <param name="connectionType">Connection type.</param>
        public KerberosClientSecurityConfig(
            AccountCredential account,
            string serviceName,
            ClientSecurityContextAttribute attributes)
            : base(SecurityPackageType.Kerberos)
        {
            string fullDomainName = KerberosUtility.GetFullDomainName(serviceName, account.DomainName);

            this.clientCredential   = account;
            this.logonName          = account.AccountName;
            this.serviceName        = serviceName;
            this.kdcIpAddress       = fullDomainName.ParseIPAddress();
            this.securityAttributes = attributes;
            this.transportType      = TransportType.TCP;
        }
        private void DecryptTicket(EncryptionType type, byte[] sessionKey)
        {
            var ticketEncPartRawData = KerberosUtility.Decrypt(
                type,
                sessionKey,
                Response.ticket.enc_part.cipher.ByteArrayValue,
                (int)KeyUsageNumber.AS_REP_TicketAndTGS_REP_Ticket);

            TicketEncPart = new EncTicketPart();
            TicketEncPart.BerDecode(new Asn1DecodingBuffer(ticketEncPartRawData));
            KerberosUtility.OnDumpMessage("KRB5:TicketEncPart",
                                          "Encrypted Ticket in TGS-REP",
                                          KerberosUtility.DumpLevel.PartialMessage,
                                          ticketEncPartRawData);
        }
        public void DecryptTgsResponse(byte[] key, KeyUsageNumber usage = KeyUsageNumber.TGS_REP_encrypted_part)
        {
            var encryptType    = (EncryptionType)Response.enc_part.etype.Value;
            var encPartRawData = KerberosUtility.Decrypt(
                encryptType,
                key,
                Response.enc_part.cipher.ByteArrayValue,
                (int)usage);

            EncPart = new EncTGSRepPart();
            EncPart.BerDecode(new Asn1DecodingBuffer(encPartRawData));
            KerberosUtility.OnDumpMessage("KRB5:TGS-REP(enc-part)",
                                          "Encrypted part of TGS-REP",
                                          KerberosUtility.DumpLevel.PartialMessage,
                                          encPartRawData);
        }
Esempio n. 25
0
        /// <summary>
        /// Decode AS Response from bytes
        /// </summary>
        /// <param name="buffer">the byte array to be decoded</param>
        /// <exception cref="System.ArgumentNullException">thrown when input buffer is null</exception>
        public override void FromBytes(byte[] buffer)
        {
            if (null == buffer)
            {
                throw new ArgumentNullException("buffer");
            }
            KerberosUtility.OnDumpMessage("KRB5:KrbMessage",
                                          "Kerberos Message",
                                          KerberosUtility.DumpLevel.WholeMessage,
                                          buffer);
            // Decode AS Response
            Asn1DecodingBuffer decodeBuffer = new Asn1DecodingBuffer(buffer);

            this.Response.BerDecode(decodeBuffer);
            // Get the current encryption type, cipher data, session key
            EncryptionType encryptType = (EncryptionType)this.Response.enc_part.etype.Value;
        }
Esempio n. 26
0
        /// <summary>
        /// Decode the Krb Error from bytes
        /// </summary>
        /// <param name="buffer">The byte array to be decoded.</param>
        /// <exception cref="System.ArgumentNullException">thrown when input buffer is null</exception>
        public override void FromBytes(byte[] buffer)
        {
            if (null == buffer)
            {
                throw new ArgumentNullException("buffer");
            }
            KerberosUtility.OnDumpMessage("KRB5:KrbMessage",
                                          "Kerberos Message",
                                          KerberosUtility.DumpLevel.WholeMessage,
                                          buffer);
            // Decode Krb Error
            Asn1DecodingBuffer decodeBuffer = new Asn1DecodingBuffer(buffer);

            this.KrbError.BerDecode(decodeBuffer);

            ErrorCode = (KRB_ERROR_CODE)KrbError.error_code.Value;
        }
Esempio n. 27
0
        private KDC_REQ_BODY CreateKdcRequestBody(KdcOptions kdcOptions, PrincipalName sName)
        {
            KerbUInt32    nonce     = new KerbUInt32((uint)Math.Abs((int)DateTime.Now.Ticks));
            KerberosTime  till      = new KerberosTime(KerberosConstValue.TGT_TILL_TIME);
            KerberosTime  rtime     = new KerberosTime(KerberosConstValue.TGT_RTIME);
            HostAddresses addresses =
                new HostAddresses(new HostAddress[1] {
                new HostAddress(new KerbInt32((int)AddressType.NetBios),
                                new Asn1OctetString(Encoding.ASCII.GetBytes(System.Net.Dns.GetHostName())))
            });

            KDCOptions options = new KDCOptions(KerberosUtility.ConvertInt2Flags((int)kdcOptions));

            KDC_REQ_BODY kdcReqBody = new KDC_REQ_BODY(options, Context.CName.Name, Context.Realm, sName, null, till, rtime, nonce, Context.SupportedEType, addresses, null, null);

            return(kdcReqBody);
        }
Esempio n. 28
0
        /// <summary>
        /// Encode this class into byte array.
        /// </summary>
        /// <returns>The byte array of the class.</returns>
        public override byte[] ToBytes()
        {
            Asn1BerEncodingBuffer tgsBerBuffer = new Asn1BerEncodingBuffer();

            this.Request.BerEncode(tgsBerBuffer, true);
            KerberosUtility.OnDumpMessage("KRB5:KrbMessage",
                                          "Kerberos Message",
                                          KerberosUtility.DumpLevel.WholeMessage,
                                          tgsBerBuffer.Data);
            if (transportType == TransportType.TCP)
            {
                return(KerberosUtility.WrapLength(tgsBerBuffer.Data, true));
            }
            else
            {
                return(tgsBerBuffer.Data);
            }
        }
        /// <summary>
        /// Get Authorization Data from Ticket in AS/TGS response
        /// </summary>
        /// <param name="ticket">Ticket part that includes Auth Data.</param>
        /// <param name="key">The key that encrypts ticket part.</param>
        /// <returns>Authorization Data in the ticket</returns>
        public static AuthorizationData GetAuthDataInTicket(Ticket ticket, byte[] key)
        {
            EncryptionType encryptType = (EncryptionType)ticket.enc_part.etype.Value;

            byte[] clearText = KerberosUtility.Decrypt(
                encryptType,
                key,
                ticket.enc_part.cipher.ByteArrayValue,
                (int)KeyUsageNumber.AS_REP_TicketAndTGS_REP_Ticket);

            // Decode the ticket.
            Asn1DecodingBuffer decodeBuffer  = new Asn1DecodingBuffer(clearText);
            EncTicketPart      encTicketPart = new EncTicketPart();

            encTicketPart.BerDecode(decodeBuffer);

            return(encTicketPart.authorization_data);
        }
Esempio n. 30
0
        public KerberosFastResponse GetKerberosFastRep(EncryptionKey key)
        {
            var armoredRep = GetArmoredRep();
            var decrypted  = KerberosUtility.Decrypt((EncryptionType)key.keytype.Value,
                                                     key.keyvalue.ByteArrayValue,
                                                     armoredRep.enc_fast_rep.cipher.ByteArrayValue,
                                                     (int)KeyUsageNumber.FAST_REP
                                                     );

            KerberosUtility.OnDumpMessage("KRB5:KrbFastArmoredRep(enc-fast-req)",
                                          "An encrypted KrbFastRep in PA_FX_FAST_REPLY",
                                          KerberosUtility.DumpLevel.PartialMessage,
                                          decrypted);

            KrbFastResponse fastrep = new KrbFastResponse();

            fastrep.BerDecode(new Asn1DecodingBuffer(decrypted));
            return(new KerberosFastResponse(fastrep));
        }