Exemple #1
0
 /// <summary>Creates the LMv2 response for the supplied information.</summary>
 /// <remarks>Creates the LMv2 response for the supplied information.</remarks>
 /// <param name="domain">The domain in which the username exists.</param>
 /// <param name="user">The username.</param>
 /// <param name="password">The user's password.</param>
 /// <param name="challenge">The server challenge.</param>
 /// <param name="clientChallenge">The client challenge (nonce).</param>
 public static byte[] GetLMv2Response(string domain, string user, string password,
                                      byte[] challenge, byte[] clientChallenge)
 {
     try
     {
         byte[] hash     = new byte[16];
         byte[] response = new byte[24];
         // The next 2-1/2 lines of this should be placed with nTOWFv1 in place of password
         Md4 md4 = new Md4();
         md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding)
                    );
         Hmact64 hmac = new Hmact64(md4.Digest());
         hmac.Update(Runtime.GetBytesForString(user.ToUpper(), SmbConstants.UniEncoding
                                               ));
         hmac.Update(Runtime.GetBytesForString(domain.ToUpper(), SmbConstants.UniEncoding
                                               ));
         hmac = new Hmact64(hmac.Digest());
         hmac.Update(challenge);
         hmac.Update(clientChallenge);
         hmac.Digest(response, 0, 16);
         Array.Copy(clientChallenge, 0, response, 16, 8);
         return(response);
     }
     catch (Exception ex)
     {
         if (_log.Level > 0)
         {
             Runtime.PrintStackTrace(ex, _log);
         }
         return(null);
     }
 }
Exemple #2
0
        /// <summary>Generate the Unicode MD4 hash for the password associated with these credentials.
        ///     </summary>
        /// <remarks>Generate the Unicode MD4 hash for the password associated with these credentials.
        ///     </remarks>
        public static byte[] GetNtlmResponse(string password, byte[] challenge)
        {
            byte[] uni = null;
            byte[] p21 = new byte[21];
            byte[] p24 = new byte[24];
            try
            {
                uni = Runtime.GetBytesForString(password, SmbConstants.UniEncoding);
            }
            catch (UnsupportedEncodingException uee)
            {
                if (_log.Level > 0)
                {
                    Runtime.PrintStackTrace(uee, _log);
                }
            }
            Md4 md4 = new Md4();

            md4.Update(uni);
            try
            {
                md4.Digest(p21, 0, 16);
            }
            catch (Exception ex)
            {
                if (_log.Level > 0)
                {
                    Runtime.PrintStackTrace(ex, _log);
                }
            }
            E(p21, challenge, p24);
            return(p24);
        }
Exemple #3
0
        public UnitTestMd4()
        {
            Md4         = new Md4();
            TestVectors = new TestVectorContainer <string, byte[], string, byte[]>(Converter.Text2Bytes, Converter.HexByteDecode)
            {
                { "Empty String", "", "31d6cfe0d16ae931b73c59d7e0c089c0" },
                { "a", "a", "bde52cb31de33e46245e05fbdbd6fb24" },
                { "abc", "abc", "a448017aaf21d8525fc10ae87aa6729d" },
                { "message digest", "message digest", "d9130a8164549fe818874806e1c7014b" },
                { "a-z", "abcdefghijklmnopqrstuvwxyz", "d79e1c308aa5bbcdeea8ed63df412da9" },
                { "A-Za-z0-9", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "043f8582f241db351ce627e153e7f0e4" },
                { "LargeNumber", "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "e33b4ddc9c38f2199c3e7b164fcc0536" },
            };

            TestVectorsStream = new TestVectorContainer <string, Stream, string, byte[]>(Converter.GenerateStreamFromString, Converter.HexByteDecode)
            {
                { "Empty String", "", "31d6cfe0d16ae931b73c59d7e0c089c0" },
                { "a", "a", "bde52cb31de33e46245e05fbdbd6fb24" },
                { "abc", "abc", "a448017aaf21d8525fc10ae87aa6729d" },
                { "message digest", "message digest", "d9130a8164549fe818874806e1c7014b" },
                { "a-z", "abcdefghijklmnopqrstuvwxyz", "d79e1c308aa5bbcdeea8ed63df412da9" },
                { "A-Za-z0-9", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "043f8582f241db351ce627e153e7f0e4" },
                { "LargeNumber", "12345678901234567890123456789012345678901234567890123456789012345678901234567890", "e33b4ddc9c38f2199c3e7b164fcc0536" },
            };
        }
Exemple #4
0
        /// <summary>Calculates the effective user session key.</summary>
        /// <remarks>Calculates the effective user session key.</remarks>
        /// <param name="challenge">The server challenge.</param>
        /// <param name="dest">
        /// The destination array in which the user session key will be
        /// placed.
        /// </param>
        /// <param name="offset">
        /// The offset in the destination array at which the
        /// session key will start.
        /// </param>
        /// <exception cref="SharpCifs.Smb.SmbException"></exception>
        internal void GetUserSessionKey(byte[] challenge, byte[] dest, int offset)
        {
            if (HashesExternal)
            {
                return;
            }
            try
            {
                Md4 md4 = new Md4();
                md4.Update(Runtime.GetBytesForString(Password, SmbConstants.UniEncoding)
                           );
                switch (LmCompatibility)
                {
                case 0:
                case 1:
                case 2:
                {
                    md4.Update(md4.Digest());
                    md4.Digest(dest, offset, 16);
                    break;
                }

                case 3:
                case 4:
                case 5:
                {
                    if (ClientChallenge == null)
                    {
                        ClientChallenge = new byte[8];
                        Random.NextBytes(ClientChallenge);
                    }
                    Hmact64 hmac = new Hmact64(md4.Digest());
                    hmac.Update(Runtime.GetBytesForString(Username.ToUpper(), SmbConstants.UniEncoding
                                                          ));
                    hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(), SmbConstants.UniEncoding
                                                          ));
                    byte[] ntlmv2Hash = hmac.Digest();
                    hmac = new Hmact64(ntlmv2Hash);
                    hmac.Update(challenge);
                    hmac.Update(ClientChallenge);
                    Hmact64 userKey = new Hmact64(ntlmv2Hash);
                    userKey.Update(hmac.Digest());
                    userKey.Digest(dest, offset, 16);
                    break;
                }

                default:
                {
                    md4.Update(md4.Digest());
                    md4.Digest(dest, offset, 16);
                    break;
                }
                }
            }
            catch (Exception e)
            {
                throw new SmbException(string.Empty, e);
            }
        }
Exemple #5
0
        private String CalculateFromText(HashType ht, String str)
        {
            byte[]        hashBytes   = null;
            StringBuilder hashBuilder = new StringBuilder();

            switch (ht)
            {
            case HashType.MD5:
                //Compute hash based on source data.
                hashBytes = new MD5CryptoServiceProvider().ComputeHash(UTF8Encoding.UTF8.GetBytes(str));
                break;

            case HashType.MD4:
                //Compute hash based on source data.
                hashBytes = new Md4().ComputeHash(UTF8Encoding.UTF8.GetBytes(str));
                break;

            case HashType.ED2K:
                //Compute hash based on source data.
                hashBytes = new Ed2k().ComputeHash(UTF8Encoding.UTF8.GetBytes(str));
                break;

            case HashType.CRC32:
                hashBytes = new Crc32().ComputeHash(UTF8Encoding.UTF8.GetBytes(str));
                break;

            case HashType.SHA1:
                //Compute hash based on source data.
                hashBytes = new SHA1CryptoServiceProvider().ComputeHash(UTF8Encoding.UTF8.GetBytes(str));
                break;

            case HashType.SHA256:
                //Compute hash based on source data.
                hashBytes = SHA256.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(str));
                break;

            case HashType.SHA384:
                //Compute hash based on source data.
                hashBytes = SHA384.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(str));
                break;

            case HashType.SHA512:
                //Compute hash based on source data.
                hashBytes = SHA512.Create().ComputeHash(UTF8Encoding.UTF8.GetBytes(str));
                break;

            case HashType.TTH:
                TTH tth = new TTH();
                tth.Initialize();
                hashBytes = tth.ComputeHash(UTF8Encoding.UTF8.GetBytes(str));
                break;
            }

            foreach (Byte hashByte in hashBytes)
            {
                hashBuilder.Append(hashByte.ToString("X2").ToLower());
            }
            return(hashBuilder.ToString());
        }
Exemple #6
0
        public void CompareWithSharpCifsImpl(string src)
        {
            var data = Encoding.Unicode.GetBytes(src);

            var md4 = new SharpCifs.Util.Md4();

            md4.Update(data);

            Assert.That(Md4.Digest(data), Is.EqualTo(md4.Digest()));
        }
Exemple #7
0
        public void CompareWithSharpCifsImpl(char ch, int len)
        {
            var data = Encoding.Unicode.GetBytes(Enumerable.Repeat(ch, len).ToArray());

            var md4 = new SharpCifs.Util.Md4();

            md4.Update(data);

            Assert.That(Md4.Digest(data), Is.EqualTo(md4.Digest()));
        }
Exemple #8
0
        public void TestByteArrays()
        {
            Assert.Equal(new byte[] { 0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31, 0xb7, 0x3c, 0x59, 0xd7, 0xe0, 0xc0, 0x89, 0xc0 },
                         Md4.ComputeHash(new byte[0]));

            Assert.Equal(new byte[] { 0xd9, 0x13, 0x0a, 0x81, 0x64, 0x54, 0x9f, 0xe8, 0x18, 0x87, 0x48, 0x06, 0xe1, 0xc7, 0x01, 0x4b },
                         Md4.ComputeHash(Encoding.ASCII.GetBytes("message digest")));

            Assert.Equal(new byte[] { 0x04, 0x3f, 0x85, 0x82, 0xf2, 0x41, 0xdb, 0x35, 0x1c, 0xe6, 0x27, 0xe1, 0x53, 0xe7, 0xf0, 0xe4 },
                         Md4.ComputeHash(Encoding.ASCII.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")));
        }
Exemple #9
0
        private String CalculateFromFile(HashType ht, String filename)
        {
            byte[] hashBytes = null;
            using (FileStream file = new FileStream(filename, FileMode.Open))
            {
                switch (ht)
                {
                case HashType.MD5:
                    hashBytes = new MD5CryptoServiceProvider().ComputeHash(file);
                    break;

                case HashType.MD4:
                    hashBytes = new Md4().ComputeHash(file);
                    break;

                case HashType.ED2K:
                    hashBytes = new Ed2k().ComputeHash(file);
                    break;

                case HashType.CRC32:
                    hashBytes = new Crc32().ComputeHash(file);
                    break;

                case HashType.SHA1:
                    hashBytes = new SHA1CryptoServiceProvider().ComputeHash(file);
                    break;

                case HashType.SHA256:
                    hashBytes = SHA256.Create().ComputeHash(file);
                    break;

                case HashType.SHA384:
                    hashBytes = SHA384.Create().ComputeHash(file);
                    break;

                case HashType.SHA512:
                    hashBytes = SHA512.Create().ComputeHash(file);
                    break;

                case HashType.TTH:
                    TTH tth = new TTH();
                    tth.Initialize();
                    hashBytes = tth.ComputeHash(file);
                    break;
                }
            }
            StringBuilder hashBuilder = new StringBuilder();

            foreach (byte hashByte in hashBytes)
            {
                hashBuilder.Append(hashByte.ToString("x2").ToLower());
            }
            return(hashBuilder.ToString());
        }
    internal static Int64 GetPathId(string guid, Int64 fileId)
    {
        var input = new List <byte>();

        input.AddRange(Encoding.ASCII.GetBytes(guid));
        input.AddRange(BitConverter.GetBytes((Int32)3));
        input.AddRange(BitConverter.GetBytes(fileId));

        var output = Md4.Md4Hash(input);

        return(BitConverter.ToInt64(output.Take(8).ToArray(), 0));
    }
Exemple #11
0
        // Section 3.3.2
        // Define NTOWFv2(Passwd, User, UserDom) as HMAC_MD5(MD4(UNICODE(Passwd)), UNICODE(ConcatenationOf(Uppercase(User),
        // UserDom ) ) )
        // EndDefine
        private byte[] makeNtlm2Hash(string domain, string userName, string password)
        {
            byte[] pwHash  = new byte[DigestLength];
            byte[] pwBytes = Encoding.Unicode.GetBytes(Credentials.Password);

            Md4.Hash(pwHash, pwBytes);
            HMACMD5 hmac = new HMACMD5(pwHash);

            // strangely, user is upper case, domain is not.
            byte[] blob = Encoding.Unicode.GetBytes(String.Concat(userName.ToUpper(), domain));

            return(hmac.ComputeHash(blob));
        }
Exemple #12
0
 public static byte[] NtowFv2(string domain, string username, string password)
 {
     try
     {
         Md4 md4 = new Md4();
         md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding));
         Hmact64 hmac = new Hmact64(md4.Digest());
         hmac.Update(Runtime.GetBytesForString(username.ToUpper(), SmbConstants.UniEncoding));
         hmac.Update(Runtime.GetBytesForString(domain, SmbConstants.UniEncoding));
         return(hmac.Digest());
     }
     catch (UnsupportedEncodingException uee)
     {
         throw new RuntimeException(uee.Message);
     }
 }
Exemple #13
0
 public static byte[] NtowFv1(string password)
 {
     if (password == null)
     {
         throw new RuntimeException("Password parameter is required");
     }
     try
     {
         Md4 md4 = new Md4();
         md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding));
         return(md4.Digest());
     }
     catch (UnsupportedEncodingException uee)
     {
         throw new RuntimeException(uee.Message);
     }
 }
Exemple #14
0
        static void Main(string[] args)
        {
            Console.WriteLine("data  : {0}", args[0]);

            var data = Encoding.Unicode.GetBytes(args[0]);

            var md4 = new SharpCifs.Util.Md4();

            md4.Update(data);

            Console.WriteLine();
            Console.WriteLine("[MD4]");
            Console.WriteLine("ncrypto   : {0}", Md4.Digest(data).ToHexString(hyphenSeparated: true));
            Console.WriteLine("sharpcifs : {0}", md4.Digest().ToHexString(hyphenSeparated: true));

            Console.WriteLine();
            Console.WriteLine("[MD5]");

            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            Console.WriteLine("ncrypto   : {0}", Md5.Digest(data).ToHexString(hyphenSeparated: true));
            Console.WriteLine("standard  : {0}", md5.ComputeHash(data).ToHexString(hyphenSeparated: true));
        }
Exemple #15
0
 public static byte[] GetNtPasswordHash(SecureString password)
 {
     return(Md4.ComputeHash(GetNtPasswordBuffer(password)));
 }
 internal static string GetCabFilename(string assetBundleName)
 => "CAB-" + StringFromByteArray(Md4.Md4Hash(new List <byte>(Encoding.ASCII.GetBytes(assetBundleName)))).ToLower();
Exemple #17
0
        /// <summary>Creates a Type-3 message in response to the given Type-2 message.</summary>
        /// <remarks>Creates a Type-3 message in response to the given Type-2 message.</remarks>
        /// <param name="type2">The Type-2 message which this represents a response to.</param>
        /// <param name="password">The password to use when constructing the response.</param>
        /// <param name="domain">The domain in which the user has an account.</param>
        /// <param name="user">The username for the authenticating user.</param>
        /// <param name="workstation">
        /// The workstation from which authentication is
        /// taking place.
        /// </param>
        public Type3Message(Type2Message type2,
                            string password,
                            string domain,
                            string user,
                            string workstation,
                            int flags)
        {
            SetFlags(flags | GetDefaultFlags(type2));
            if (workstation == null)
            {
                workstation = GetDefaultWorkstation();
            }
            SetWorkstation(workstation);
            SetDomain(domain);
            SetUser(user);
            switch (LmCompatibility)
            {
            case 0:
            case 1:
            {
                if ((GetFlags() & NtlmsspNegotiateNtlm2) == 0)
                {
                    SetLmResponse(GetLMResponse(type2, password));
                    SetNtResponse(GetNTResponse(type2, password));
                }
                else
                {
                    // NTLM2 Session Response
                    byte[] clientChallenge = new byte[24];
                    //RANDOM.NextBytes(clientChallenge);
                    Arrays.Fill(clientChallenge, 8, 24, unchecked ((byte)unchecked (0x00)));
                    // NTLMv1 w/ NTLM2 session sec and key exch all been verified with a debug build of smbclient
                    byte[] responseKeyNt
                        = NtlmPasswordAuthentication.NtowFv1(password);
                    byte[] ntlm2Response
                        = NtlmPasswordAuthentication.GetNtlm2Response(responseKeyNt,
                                                                      type2.GetChallenge(),
                                                                      clientChallenge);
                    SetLmResponse(clientChallenge);
                    SetNtResponse(ntlm2Response);
                    if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
                    {
                        byte[] sessionNonce = new byte[16];
                        Array.Copy(type2.GetChallenge(), 0, sessionNonce, 0, 8);
                        Array.Copy(clientChallenge, 0, sessionNonce, 8, 8);
                        Md4 md4 = new Md4();
                        md4.Update(responseKeyNt);
                        byte[]  userSessionKey = md4.Digest();
                        Hmact64 hmac           = new Hmact64(userSessionKey);
                        hmac.Update(sessionNonce);
                        byte[] ntlm2SessionKey = hmac.Digest();
                        if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0)
                        {
                            _masterKey = new byte[16];
                            //RANDOM.NextBytes(masterKey);
                            byte[] exchangedKey = new byte[16];
                            Rc4    rc4          = new Rc4(ntlm2SessionKey);
                            rc4.Update(_masterKey, 0, 16, exchangedKey, 0);
                            SetSessionKey(exchangedKey);
                        }
                        else
                        {
                            _masterKey = ntlm2SessionKey;
                            SetSessionKey(_masterKey);
                        }
                    }
                }
                break;
            }

            case 2:
            {
                byte[] nt = GetNTResponse(type2, password);
                SetLmResponse(nt);
                SetNtResponse(nt);
                break;
            }

            case 3:
            case 4:
            case 5:
            {
                byte[] responseKeyNt1
                    = NtlmPasswordAuthentication.NtowFv2(domain, user, password);
                byte[] clientChallenge1 = new byte[8];
                //RANDOM.NextBytes(clientChallenge_1);
                SetLmResponse(GetLMv2Response(type2, domain, user, password, clientChallenge1));
                byte[] clientChallenge2 = new byte[8];
                //RANDOM.NextBytes(clientChallenge2);
                SetNtResponse(GetNtlMv2Response(type2, responseKeyNt1, clientChallenge2));
                if ((GetFlags() & NtlmsspNegotiateSign) == NtlmsspNegotiateSign)
                {
                    Hmact64 hmac = new Hmact64(responseKeyNt1);
                    hmac.Update(_ntResponse, 0, 16);
                    // only first 16 bytes of ntResponse
                    byte[] userSessionKey = hmac.Digest();
                    if ((GetFlags() & NtlmsspNegotiateKeyExch) != 0)
                    {
                        _masterKey = new byte[16];
                        //RANDOM.NextBytes(masterKey);
                        byte[] exchangedKey = new byte[16];
                        Rc4    rc4          = new Rc4(userSessionKey);
                        rc4.Update(_masterKey, 0, 16, exchangedKey, 0);
                        SetSessionKey(exchangedKey);
                    }
                    else
                    {
                        _masterKey = userSessionKey;
                        SetSessionKey(_masterKey);
                    }
                }
                break;
            }

            default:
            {
                SetLmResponse(GetLMResponse(type2, password));
                SetNtResponse(GetNTResponse(type2, password));
                break;
            }
            }
        }