Ejemplo n.º 1
0
        internal HashAlgorithm GetAlgo()
        {
            if (algo != null)
            {
                return(algo);
            }
            if (!EnableMac)
            {
                return(null);
            }

            byte [] algoKey;
            if (page != null)
            {
#if NET_2_0
                MachineKeySection mconfig = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection("system.web/machineKey");
                algoKey = MachineKeySectionUtils.ValidationKeyBytes(mconfig);
#else
                MachineKeyConfig mconfig = HttpContext.GetAppConfig("system.web/machineKey") as MachineKeyConfig;
                algoKey = mconfig.ValidationKey;
#endif
            }
            else
            {
                algoKey = vkey;
            }

            algo = new HMACSHA1(algoKey);
            return(algo);
        }
Ejemplo n.º 2
0
 public byte [] DecryptPassword(byte [] encodedPassword)
 {
     using (SymmetricAlgorithm sa = GetAlgorithm())
     {
         return(MachineKeySectionUtils.Decrypt(sa, encodedPassword, 0, encodedPassword.Length));
     }
 }
Ejemplo n.º 3
0
        SymmetricAlgorithm GetAlg()
        {
            MachineKeySection section = (MachineKeySection)WebConfigurationManager.GetSection("system.web/machineKey");

            if (section.DecryptionKey.StartsWith("AutoGenerate"))
            {
                throw new ProviderException("You must explicitly specify a decryption key in the <machineKey> section when using encrypted passwords.");
            }

            string alg_type = section.Decryption;

            if (alg_type == "Auto")
            {
                alg_type = "AES";
            }

            SymmetricAlgorithm alg = null;

            if (alg_type == "AES")
            {
                alg = Rijndael.Create();
            }
            else if (alg_type == "3DES")
            {
                alg = TripleDES.Create();
            }
            else
            {
                throw new ProviderException(String.Format("Unsupported decryption attribute '{0}' in <machineKey> configuration section", alg_type));
            }

            alg.Key = MachineKeySectionUtils.DecryptionKey192Bits(section);
            return(alg);
        }
Ejemplo n.º 4
0
        public static byte[] Unprotect(byte[] protectedData, params string[] purposes)
        {
            if (protectedData == null)
            {
                throw new ArgumentNullException("protectedData");
            }

            foreach (var purpose in purposes)
            {
                if (string.IsNullOrWhiteSpace(purpose))
                {
                    throw new ArgumentException("all purpose parameters must contain text");
                }
            }

            var config        = WebConfigurationManager.GetWebApplicationSection("system.web/machineKey") as MachineKeySection;
            var purposeJoined = string.Join(";", purposes);
            var purposeBytes  = GetHashed(purposeJoined);
            var unprotected   = MachineKeySectionUtils.Decrypt(config, protectedData);

            for (int i = 0; i < purposeBytes.Length; i++)
            {
                if (purposeBytes [i] != unprotected [i])
                {
                    throw new CryptographicException();
                }
            }

            var dataLength = unprotected.Length - purposeBytes.Length;
            var result     = new byte [dataLength];

            Array.Copy(unprotected, purposeBytes.Length, result, 0, dataLength);
            return(result);
        }
Ejemplo n.º 5
0
        public static string Encode(byte[] data, MachineKeyProtection protectionOption)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            var config = WebConfigurationManager.GetWebApplicationSection("system.web/machineKey") as MachineKeySection;

            byte[] result;
            switch (protectionOption)
            {
            case MachineKeyProtection.All:
                result = MachineKeySectionUtils.EncryptSign(config, data);
                break;

            case MachineKeyProtection.Encryption:
                result = MachineKeySectionUtils.Encrypt(config, data);
                break;

            case MachineKeyProtection.Validation:
                result = MachineKeySectionUtils.Sign(config, data);
                break;

            default:
                return(String.Empty);
            }

            return(MachineKeySectionUtils.GetHexString(result));
        }
Ejemplo n.º 6
0
        static FormsAuthenticationTicket Decrypt2(byte [] bytes)
        {
            if (protection == FormsProtectionEnum.None)
            {
                return(FormsAuthenticationTicket.FromByteArray(bytes));
            }

            MachineKeySection config = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection(machineKeyConfigPath);

            byte [] result = null;
            if (protection == FormsProtectionEnum.All)
            {
                result = MachineKeySectionUtils.VerifyDecrypt(config, bytes);
            }
            else if (protection == FormsProtectionEnum.Encryption)
            {
                result = MachineKeySectionUtils.Decrypt(config, bytes);
            }
            else if (protection == FormsProtectionEnum.Validation)
            {
                result = MachineKeySectionUtils.Verify(config, bytes);
            }

            return(FormsAuthenticationTicket.FromByteArray(result));
        }
Ejemplo n.º 7
0
        public string Serialize(object stateGraph)
        {
            if (stateGraph == null)
            {
                return(String.Empty);
            }

            byte[] data = null;
            using (MemoryStream ms = new MemoryStream()) {
                Serialize(ms, stateGraph);
                data = ms.GetBuffer();
            }

            if (NeedViewStateEncryption)
            {
                if (EnableMac)
                {
                    data = MachineKeySectionUtils.EncryptSign(Section, data);
                }
                else
                {
                    data = MachineKeySectionUtils.Encrypt(Section, data);
                }
            }
            else if (EnableMac)
            {
                data = MachineKeySectionUtils.Sign(Section, data);
            }

            return(Convert.ToBase64String(data, 0, data.Length));
        }
Ejemplo n.º 8
0
        public static string Encrypt(FormsAuthenticationTicket ticket)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }

            Initialize();
            byte [] ticket_bytes = ticket.ToByteArray();
            if (protection == FormsProtectionEnum.None)
            {
                return(Convert.ToBase64String(ticket_bytes));
            }

            byte []           result = null;
            MachineKeySection config = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection(machineKeyConfigPath);

            if (protection == FormsProtectionEnum.All)
            {
                result = MachineKeySectionUtils.EncryptSign(config, ticket_bytes);
            }
            else if (protection == FormsProtectionEnum.Encryption)
            {
                result = MachineKeySectionUtils.Encrypt(config, ticket_bytes);
            }
            else if (protection == FormsProtectionEnum.Validation)
            {
                result = MachineKeySectionUtils.Sign(config, ticket_bytes);
            }

            return(Convert.ToBase64String(result));
        }
Ejemplo n.º 9
0
        public void Encrypt_RoundTrip(MachineKeySection section)
        {
            byte [] data    = new byte [14];
            byte [] encdata = MachineKeySectionUtils.Encrypt(section, data);
            byte [] decdata = MachineKeySectionUtils.Decrypt(section, encdata);
            Assert.AreEqual(data, decdata, "roundtrip");

            // changing length (missing first byte)
            byte [] cut = new byte [encdata.Length - 1];
            Array.Copy(encdata, 1, cut, 0, cut.Length);
            Assert.IsNull(MachineKeySectionUtils.Decrypt(section, cut), "bad length");

            // changing last byte (padding)
            byte be = encdata [encdata.Length - 1];

            encdata [encdata.Length - 1] = ChangeByte(be);
            byte[] result = MachineKeySectionUtils.Decrypt(section, encdata);
            // this will return null if a bad padding is detected - OTOH since we're using a random key and we
            // encrypt a random IV it's possible the decrypted stuff will randomly have a "valid" padding (there's
            // only so much possible values and the bots runs those tests pretty often and give false positive)
            // To avoid this we fallback to ensure the data is invalid (if should be empty)
            int total = 0;

            if (result != null)
            {
                for (int i = 0; i < result.Length; i++)
                {
                    total += result [i];
                }
            }
            Assert.IsTrue(result == null || total != 0, "bad padding");
        }
Ejemplo n.º 10
0
 public byte[] EncryptPassword(byte[] password)
 {
     using (SymmetricAlgorithm sa = GetAlgorithm())
     {
         return(MachineKeySectionUtils.Encrypt(sa, password));
     }
 }
Ejemplo n.º 11
0
        static byte[] GetBytes(string val)
        {
#if NET_2_0
            return(MachineKeySectionUtils.GetBytes(val, val.Length));
#else
            return(MachineKeyConfig.GetBytes(val, val.Length));
#endif
        }
Ejemplo n.º 12
0
        public static byte[] Decode(string encodedData, MachineKeyProtection protectionOption)
        {
            if (encodedData == null)
            {
                throw new ArgumentNullException("encodedData");
            }

            int dlen = encodedData.Length;

            if (dlen == 0 || dlen % 2 == 1)
            {
                throw new ArgumentException("encodedData");
            }

            byte[] data = MachineKeySectionUtils.GetBytes(encodedData, dlen);
            if (data == null || data.Length == 0)
            {
                throw new ArgumentException("encodedData");
            }

            var config = WebConfigurationManager.GetWebApplicationSection("system.web/machineKey") as MachineKeySection;

            byte[]    result = null;
            Exception ex     = null;

            try
            {
                switch (protectionOption)
                {
                case MachineKeyProtection.All:
                    result = MachineKeySectionUtils.VerifyDecrypt(config, data);
                    break;

                case MachineKeyProtection.Encryption:
                    result = MachineKeySectionUtils.Decrypt(config, data);
                    break;

                case MachineKeyProtection.Validation:
                    result = MachineKeySectionUtils.Verify(config, data);
                    break;

                default:
                    return(MachineKeySectionUtils.GetBytes(encodedData, dlen));
                }
            }
            catch (Exception e)
            {
                ex = e;
            }

            if (result == null || ex != null)
            {
                throw new HttpException("Unable to verify passed data.", ex);
            }

            return(result);
        }
Ejemplo n.º 13
0
        internal static string Create()
        {
            byte[] key = new byte [half_len];

            lock (rng) {
                rng.GetBytes(key);
            }
            return(MachineKeySectionUtils.GetHexString(key));
        }
Ejemplo n.º 14
0
        static byte[] GetEncryptionKey()
        {
#if NET_2_0
            return(MachineKeySectionUtils.DecryptionKey192Bits());
#else
            MachineKeyConfig config = HttpContext.GetAppConfig("system.web/machineKey") as MachineKeyConfig;
            return(config.DecryptionKey192Bits);
#endif
        }
Ejemplo n.º 15
0
 private void SetMacKey(byte[] macKeyModifier)
 {
     try {
         osf.Section.ValidationKey = MachineKeySectionUtils.GetHexString(macKeyModifier);
     }
     catch (ArgumentException) {
     }
     catch (ConfigurationErrorsException) {
         // bad key (e.g. size), default key will be used
     }
 }
Ejemplo n.º 16
0
        public void Validation_RoundTrip(MachineKeySection section)
        {
            byte [] data  = new byte [] { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 };
            byte [] block = MachineKeySectionUtils.Sign(section, data);
            Assert.AreEqual(data, MachineKeySectionUtils.Verify(section, block), "OK");

            // changing last byte
            for (int i = 0; i < data.Length; i++)
            {
                byte b = block [i];
                block [i] = ChangeByte(b);
                Assert.IsNull(MachineKeySectionUtils.Verify(section, block), "bad-" + i.ToString());
                block [i] = b;
            }
        }
Ejemplo n.º 17
0
        internal static string GetResourceUrl(Assembly assembly, string resourceName, bool notifyScriptLoaded)
        {
            if (assembly == null)
            {
                return(String.Empty);
            }
#if NET_2_0
            MachineKeySection mks = MachineKeySection.Config;
#else
            MachineKeyConfig mks = MachineKeyConfig.Config;
#endif
            using (KeyedHashAlgorithm kha = MachineKeySectionUtils.GetValidationAlgorithm(mks)) {
                kha.Key = MachineKeySectionUtils.GetValidationKey(mks);
                return(GetResourceUrl(kha, assembly, resourceName, notifyScriptLoaded));
            }
        }
Ejemplo n.º 18
0
        public object Deserialize(string inputString)
        {
            if (inputString == null)
            {
                throw new ArgumentNullException("inputString");
            }
#if NET_2_0
            if (inputString.Length == 0)
            {
                throw new ArgumentNullException("inputString");
            }
#else
            if (inputString == "")
            {
                return("");
            }
#endif
            byte [] data = Convert.FromBase64String(inputString);
            if (data == null || (data.Length) == 0)
            {
                throw new ArgumentNullException("inputString");
            }
            if (NeedViewStateEncryption)
            {
                if (EnableMac)
                {
                    data = MachineKeySectionUtils.VerifyDecrypt(Section, data);
                }
                else
                {
                    data = MachineKeySectionUtils.Decrypt(Section, data);
                }
            }
            else if (EnableMac)
            {
                data = MachineKeySectionUtils.Verify(Section, data);
            }

            if (data == null)
            {
                throw new HttpException("Unable to validate data.");
            }

            using (MemoryStream ms = new MemoryStream(data)) {
                return(Deserialize(ms));
            }
        }
Ejemplo n.º 19
0
        public string ToEncryptedTicket()
        {
            string roles           = string.Join(",", GetRoles());
            string cookiePath      = RoleManagerConfig.CookiePath;
            int    approxTicketLen = roles.Length + cookiePath.Length + 64;

            if (_cachedArray.Length > Roles.MaxCachedResults)
            {
                return(null);
            }

            MemoryStream ticket = new MemoryStream(approxTicketLen);
            BinaryWriter writer = new BinaryWriter(ticket);

            // version
            writer.Write(Version);

            // issue datetime
            DateTime issueDate = DateTime.Now;

            writer.Write(issueDate.Ticks);

            // expiration datetime
            writer.Write(_expireDate.Ticks);

            writer.Write(cookiePath);
            writer.Write(roles);

            CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;

            byte[] ticket_data = ticket.GetBuffer();
            if (cookieProtection == CookieProtection.All)
            {
                ticket_data = MachineKeySectionUtils.EncryptSign(MachineConfig, ticket_data);
            }
            else if (cookieProtection == CookieProtection.Encryption)
            {
                ticket_data = MachineKeySectionUtils.Encrypt(MachineConfig, ticket_data);
            }
            else if (cookieProtection == CookieProtection.Validation)
            {
                ticket_data = MachineKeySectionUtils.Sign(MachineConfig, ticket_data);
            }

            return(GetBase64FromBytes(ticket_data, 0, ticket_data.Length));
        }
        public void Encrypt_RoundTrip(MachineKeySection section)
        {
            byte [] data    = new byte [14];
            byte [] encdata = MachineKeySectionUtils.Encrypt(section, data);
            byte [] decdata = MachineKeySectionUtils.Decrypt(section, encdata);
            Assert.AreEqual(data, decdata, "roundtrip");

            // changing length (missing first byte)
            byte [] cut = new byte [encdata.Length - 1];
            Array.Copy(encdata, 1, cut, 0, cut.Length);
            Assert.IsNull(MachineKeySectionUtils.Decrypt(section, cut), "bad length");

            // changing last byte (padding)
            byte be = encdata [encdata.Length - 1];

            encdata [encdata.Length - 1] = ChangeByte(be);
            Assert.IsNull(MachineKeySectionUtils.Decrypt(section, encdata), "bad padding");
        }
Ejemplo n.º 21
0
        public void EncryptSign_RoundTrip(MachineKeySection section)
        {
            byte [] data    = new byte [14];
            byte [] block   = MachineKeySectionUtils.EncryptSign(section, data);
            byte [] decdata = MachineKeySectionUtils.VerifyDecrypt(section, block);
            Assert.AreEqual(data, decdata, "roundtrip");

            // changing a byte of the data
            byte b0 = block [0];

            block [0] = ChangeByte(b0);
            Assert.IsNull(MachineKeySectionUtils.VerifyDecrypt(section, block), "bad data");
            block [0] = b0;

            // changing a byte of the signature
            byte be = block [block.Length - 1];

            block [block.Length - 1] = ChangeByte(be);
            Assert.IsNull(MachineKeySectionUtils.VerifyDecrypt(section, block), "bad signature");
        }
Ejemplo n.º 22
0
        public static string Encrypt(FormsAuthenticationTicket ticket)
        {
            if (ticket == null)
            {
                throw new ArgumentNullException("ticket");
            }

            Initialize();
            byte [] ticket_bytes = ticket.ToByteArray();
            if (protection == FormsProtectionEnum.None)
            {
                return(GetHexString(ticket_bytes));
            }

            byte [] result = ticket_bytes;
#if NET_2_0
            MachineKeySection config = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection(machineKeyConfigPath);
#else
            MachineKeyConfig config = HttpContext.GetAppConfig(machineKeyConfigPath) as MachineKeyConfig;
#endif
            bool all = (protection == FormsProtectionEnum.All);
            if (all || protection == FormsProtectionEnum.Validation)
            {
                byte [] valid_bytes = null;
#if NET_2_0
                byte [] vk = MachineKeySectionUtils.ValidationKeyBytes(config);
#else
                byte [] vk = config.ValidationKey;
#endif
                byte [] mix = new byte [ticket_bytes.Length + vk.Length];
                Buffer.BlockCopy(ticket_bytes, 0, mix, 0, ticket_bytes.Length);
                Buffer.BlockCopy(vk, 0, mix, result.Length, vk.Length);

                switch (
#if NET_2_0
                    config.Validation
#else
                    config.ValidationType
#endif
                    )
                {
Ejemplo n.º 23
0
        void SetMacKey(byte[] macKeyModifier)
        {
            try {
#if NET_2_0
                osf.Section.ValidationKey = MachineKeySectionUtils.GetHexString(macKeyModifier);
#else
                osf.Section.SetValidationKey(MachineKeySectionUtils.GetHexString(macKeyModifier));
#endif
            }
            catch (ArgumentException) {
            }
#if NET_2_0
            catch (ConfigurationErrorsException) {
                // bad key (e.g. size), default key will be used
            }
#else
            catch (HttpException) {
                // bad key (e.g. size), default key will be used
            }
#endif
        }
Ejemplo n.º 24
0
        internal static string GetResourceUrl(Assembly assembly, string resourceName, bool notifyScriptLoaded)
        {
            if (assembly == null)
            {
                return(String.Empty);
            }

            KeyedHashAlgorithm kha = ReusableHashAlgorithm;

            if (kha != null)
            {
                return(GetResourceUrl(kha, assembly, resourceName, notifyScriptLoaded));
            }
            else
            {
                MachineKeySection mks = MachineKeySection.Config;
                using (kha = MachineKeySectionUtils.GetValidationAlgorithm(mks)) {
                    kha.Key = MachineKeySectionUtils.GetValidationKey(mks);
                    return(GetResourceUrl(kha, assembly, resourceName, notifyScriptLoaded));
                }
            }
        }
Ejemplo n.º 25
0
        static string HashPasswordForStoringInConfigFile(string password, FormsAuthPasswordFormat passwordFormat)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            byte [] bytes;
            switch (passwordFormat)
            {
            case FormsAuthPasswordFormat.MD5:
                bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
                break;

            case FormsAuthPasswordFormat.SHA1:
                bytes = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
                break;

            default:
                throw new ArgumentException("The format must be either MD5 or SHA1", "passwordFormat");
            }

            return(MachineKeySectionUtils.GetHexString(bytes));
        }
Ejemplo n.º 26
0
        public static FormsAuthenticationTicket Decrypt(string encryptedTicket)
        {
            if (encryptedTicket == null || encryptedTicket == String.Empty)
            {
                throw new ArgumentException("Invalid encrypted ticket", "encryptedTicket");
            }

            Initialize();

            FormsAuthenticationTicket ticket;

#if NET_2_0
            byte [] bytes = MachineKeySectionUtils.GetBytes(encryptedTicket, encryptedTicket.Length);
#else
            byte [] bytes = MachineKeyConfig.GetBytes(encryptedTicket, encryptedTicket.Length);
#endif
            try {
                ticket = Decrypt2(bytes);
            } catch (Exception) {
                ticket = null;
            }

            return(ticket);
        }
Ejemplo n.º 27
0
        public static byte[] Protect(byte[] userData, params string[] purposes)
        {
            if (userData == null)
            {
                throw new ArgumentNullException("userData");
            }

            foreach (var purpose in purposes)
            {
                if (string.IsNullOrWhiteSpace(purpose))
                {
                    throw new ArgumentException("all purpose parameters must contain text");
                }
            }

            var config        = WebConfigurationManager.GetWebApplicationSection("system.web/machineKey") as MachineKeySection;
            var purposeJoined = string.Join(";", purposes);
            var purposeBytes  = GetHashed(purposeJoined);
            var bytes         = new byte [userData.Length + purposeBytes.Length];

            purposeBytes.CopyTo(bytes, 0);
            userData.CopyTo(bytes, purposeBytes.Length);
            return(MachineKeySectionUtils.Encrypt(config, bytes));
        }
Ejemplo n.º 28
0
        void DecryptTicket(string encryptedTicket)
        {
            if (encryptedTicket == null || encryptedTicket == String.Empty)
            {
                throw new ArgumentException("Invalid encrypted ticket", "encryptedTicket");
            }

            byte [] ticketBytes          = GetBytesFromBase64(encryptedTicket);
            byte [] decryptedTicketBytes = null;

            CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;

            if (cookieProtection == CookieProtection.All)
            {
                decryptedTicketBytes = MachineKeySectionUtils.VerifyDecrypt(MachineConfig, ticketBytes);
            }
            else if (cookieProtection == CookieProtection.Encryption)
            {
                decryptedTicketBytes = MachineKeySectionUtils.Decrypt(MachineConfig, ticketBytes);
            }
            else if (cookieProtection == CookieProtection.Validation)
            {
                decryptedTicketBytes = MachineKeySectionUtils.Verify(MachineConfig, ticketBytes);
            }

            if (decryptedTicketBytes == null)
            {
                throw new HttpException("ticket validation failed");
            }

            MemoryStream ticket = new MemoryStream(decryptedTicketBytes);
            BinaryReader reader = new BinaryReader(ticket);

            // version
            _version = reader.ReadInt32();

            // issued date
            _issueDate = new DateTime(reader.ReadInt64());

            // expire date
            _expireDate = new DateTime(reader.ReadInt64());

            // cookie path
            _cookiePath = reader.ReadString();

            // roles
            string roles = reader.ReadString();

            if (!Expired)
            {
                InitializeRoles(roles);
                //update ticket if less than half of CookieTimeout remaining.
                if (Roles.CookieSlidingExpiration)
                {
                    if (_expireDate - DateTime.Now < TimeSpan.FromTicks(RoleManagerConfig.CookieTimeout.Ticks / 2))
                    {
                        _issueDate  = DateTime.Now;
                        _expireDate = DateTime.Now.Add(RoleManagerConfig.CookieTimeout);
                        SetDirty();
                    }
                }
            }
            else
            {
                // issue a new ticket
                _issueDate  = DateTime.Now;
                _expireDate = _issueDate.Add(RoleManagerConfig.CookieTimeout);
            }
        }
Ejemplo n.º 29
0
 public void GetHexString()
 {
     Assert.AreEqual("DEADC0DE", MachineKeySectionUtils.GetHexString(new byte [] { 0xde, 0xad, 0xc0, 0xde }), "deadcode");
 }
Ejemplo n.º 30
0
 static ScriptResourceHandler()
 {
     MachineKeySectionUtils.AutoGenKeys();
 }