public void GetAllKeys_WithEnvironmentKeyPresent_UsesEnvironmentKey()
        {
            var    configuration = new AuthenticatedEncryptorConfiguration(new AuthenticatedEncryptionSettings());
            var    resolver      = new AzureWebsitesXmlRepository(configuration);
            string keyValue      = "0F75CA46E7EBDD39E4CA6B074D1F9A5972B849A55F91A249";

            using (new TestScopedEnvironmentVariable(Constants.AzureWebsiteInstanceId, "test"))
                using (new TestScopedEnvironmentVariable(Constants.AzureWebsiteEnvironmentMachineKey, keyValue))
                {
                    IReadOnlyCollection <XElement> keys = resolver.GetAllElements();

                    Assert.Equal(1, keys.Count);

                    string key = ((IEnumerable)keys.First().XPathEvaluate("descriptor/descriptor/masterKey/value"))
                                 .Cast <XElement>()
                                 .FirstOrDefault()
                                 .Value;

                    var id = ((IEnumerable)keys.First().XPathEvaluate("@id"))
                             .Cast <XAttribute>()
                             .FirstOrDefault()
                             .Value;

                    Assert.Equal(Util.ConvertHexToByteArray(keyValue), System.Convert.FromBase64String(key));
                    Assert.Equal(Constants.DefaultEncryptionKeyId, id);
                }
        }
    /// <summary>
    /// Imports the <see cref="AuthenticatedEncryptorDescriptor"/> from serialized XML.
    /// </summary>
    public IAuthenticatedEncryptorDescriptor ImportFromXml(XElement element)
    {
        if (element == null)
        {
            throw new ArgumentNullException(nameof(element));
        }

        // <descriptor>
        //   <encryption algorithm="..." />
        //   <validation algorithm="..." /> <!-- only if not GCM -->
        //   <masterKey requiresEncryption="true">...</masterKey>
        // </descriptor>

        var configuration = new AuthenticatedEncryptorConfiguration();

        var encryptionElement = element.Element("encryption") !;

        configuration.EncryptionAlgorithm = (EncryptionAlgorithm)Enum.Parse(typeof(EncryptionAlgorithm), (string)encryptionElement.Attribute("algorithm") !);

        // only read <validation> if not GCM
        if (!AuthenticatedEncryptorFactory.IsGcmAlgorithm(configuration.EncryptionAlgorithm))
        {
            var validationElement = element.Element("validation") !;
            configuration.ValidationAlgorithm = (ValidationAlgorithm)Enum.Parse(typeof(ValidationAlgorithm), (string)validationElement.Attribute("algorithm") !);
        }

        Secret masterKey = ((string)element.Elements("masterKey").Single()).ToSecret();

        return(new AuthenticatedEncryptorDescriptor(configuration, masterKey));
    }
        internal IAuthenticatedEncryptor CreateAuthenticatedEncryptorInstance(
            ISecret secret,
            AuthenticatedEncryptorConfiguration authenticatedConfiguration)
        {
            if (authenticatedConfiguration == null)
            {
                return(null);
            }

            if (IsGcmAlgorithm(authenticatedConfiguration.EncryptionAlgorithm))
            {
                // GCM requires CNG, and CNG is only supported on Windows.
                if (!OSVersionUtil.IsWindows())
                {
                    throw new PlatformNotSupportedException(Resources.Platform_WindowsRequiredForGcm);
                }

                Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));

                var configuration = new CngGcmAuthenticatedEncryptorConfiguration()
                {
                    EncryptionAlgorithm        = GetBCryptAlgorithmNameFromEncryptionAlgorithm(authenticatedConfiguration.EncryptionAlgorithm),
                    EncryptionAlgorithmKeySize = GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm)
                };

                return(new CngGcmAuthenticatedEncryptorFactory(_loggerFactory).CreateAuthenticatedEncryptorInstance(secret, configuration));
            }
            else
            {
                if (OSVersionUtil.IsWindows())
                {
                    Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));
                    // CNG preferred over managed implementations if running on Windows
                    var configuration = new CngCbcAuthenticatedEncryptorConfiguration()
                    {
                        EncryptionAlgorithm        = GetBCryptAlgorithmNameFromEncryptionAlgorithm(authenticatedConfiguration.EncryptionAlgorithm),
                        EncryptionAlgorithmKeySize = GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm),
                        HashAlgorithm = GetBCryptAlgorithmNameFromValidationAlgorithm(authenticatedConfiguration.ValidationAlgorithm)
                    };

                    return(new CngCbcAuthenticatedEncryptorFactory(_loggerFactory).CreateAuthenticatedEncryptorInstance(secret, configuration));
                }
                else
                {
                    // Use managed implementations as a fallback
                    var configuration = new ManagedAuthenticatedEncryptorConfiguration()
                    {
                        EncryptionAlgorithmType    = GetManagedTypeFromEncryptionAlgorithm(authenticatedConfiguration.EncryptionAlgorithm),
                        EncryptionAlgorithmKeySize = GetAlgorithmKeySizeInBits(authenticatedConfiguration.EncryptionAlgorithm),
                        ValidationAlgorithmType    = GetManagedTypeFromValidationAlgorithm(authenticatedConfiguration.ValidationAlgorithm)
                    };

                    return(new ManagedAuthenticatedEncryptorFactory(_loggerFactory).CreateAuthenticatedEncryptorInstance(secret, configuration));
                }
            }
        }
    /// <summary>
    /// Initializes a new instance of <see cref="AuthenticatedEncryptorDescriptor"/>.
    /// </summary>
    /// <param name="configuration">The <see cref="AuthenticatedEncryptorDescriptor"/>.</param>
    /// <param name="masterKey">The master key.</param>
    public AuthenticatedEncryptorDescriptor(AuthenticatedEncryptorConfiguration configuration, ISecret masterKey)
    {
        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }

        if (masterKey == null)
        {
            throw new ArgumentNullException(nameof(masterKey));
        }

        Configuration = configuration;
        MasterKey     = masterKey;
    }
Exemplo n.º 5
0
    /// <summary>
    /// Configures the data protection system to use the specified cryptographic algorithms
    /// by default when generating protected payloads.
    /// </summary>
    /// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param>
    /// <param name="configuration">Information about what cryptographic algorithms should be used.</param>
    /// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns>
    public static IDataProtectionBuilder UseCryptographicAlgorithms(this IDataProtectionBuilder builder, AuthenticatedEncryptorConfiguration configuration)
    {
        if (builder == null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (configuration == null)
        {
            throw new ArgumentNullException(nameof(configuration));
        }

        return(UseCryptographicAlgorithmsCore(builder, configuration));
    }
Exemplo n.º 6
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // these don't seem to change the behavior
            if (CryptoConfig.AllowOnlyFipsAlgorithms)
            {
                CryptoConfig.AddAlgorithm(
                    typeof(AesCryptoServiceProvider),
                    "AES",
                    "AesCryptoServiceProvider",
                    "System.Security.Cryptography.AesCryptoServiceProvider",
                    "System.Security.Cryptography.AES"
                    );

                CryptoConfig.AddAlgorithm(
                    typeof(SHA256CryptoServiceProvider),
                    "SHA256",
                    "SHA256CryptoServiceProvider",
                    "System.Security.Cryptography.SHA256CryptoServiceProvider",
                    "System.Security.Cryptography.SHA256"
                    );

                CryptoConfig.AddAlgorithm(
                    typeof(SHA256CryptoServiceProvider),
                    "SHA512",
                    "SHA512CryptoServiceProvider",
                    "System.Security.Cryptography.SHA512CryptoServiceProvider",
                    "System.Security.Cryptography.SHA512"
                    );
            }

            var encryptionSettings = new AuthenticatedEncryptorConfiguration()
            {
                EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
                ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
            };

            // apply AppPool identity or service account permissions to registry path
            var regPath = @"SOFTWARE\SharedCookieTest\Keys";

            Registry.LocalMachine.CreateSubKey(regPath, true);

            /*
             * Certificate Thumbprints
             * 6bee3f190055703c0dcd01e7c433462069549762 - dev.sharedcookietest.cert02
             * d74e3a5413047996a10bda4661d296ca7f741ff8 - Dev.SharedCookieTest.Cert01
             */

            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.OpenExistingOnly);
            var cert = store.Certificates
                       .OfType <X509Certificate2>()
                       .FirstOrDefault(c => c.Thumbprint.Equals("6bee3f190055703c0dcd01e7c433462069549762", StringComparison.CurrentCultureIgnoreCase));

            var protectionProvider = DataProtectionProvider.Create(
                new DirectoryInfo($@"{HostingEnvironment.MapPath("~")}\keys"),
                options =>
            {
                options.SetDefaultKeyLifetime(TimeSpan.FromDays(365));
                options.UseCryptographicAlgorithms(encryptionSettings);

                //options.UseCustomCryptographicAlgorithms(
                //	new CngCbcAuthenticatedEncryptorConfiguration()
                //	{
                //		EncryptionAlgorithm = "AES",
                //		//EncryptionAlgorithmProvider = WhatShouldThisBe?,//"Advanced Encryption Standard",//"ECDiffieHellmanCng",//"BCryptCloseAlgorithmProvider",//"MS_ENH_RSA_AES_PROV",
                //		EncryptionAlgorithmKeySize = 256,
                //		HashAlgorithm = "SHA256"
                //		//HashAlgorithmProvider = WhatShouldThisBe?//null//"SHA256CryptoServiceProvider"//"Microsoft Enhanced RSA and AES Cryptographic Provider"
                //	});

                options.PersistKeysToRegistry(Registry.LocalMachine.OpenSubKey(regPath, true));
                options.ProtectKeysWithCertificate(cert);
            });

            var dataProtector = protectionProvider.CreateProtector(
                "CookieAuthenticationMiddleware",
                "Cookie",
                "v2");

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                TicketDataFormat   = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector)),
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                CookieDomain       = "localhost",
                CookieName         = ".AspNet.SharedCookie",
                CookiePath         = "/",
                CookieSecure       = CookieSecureOption.SameAsRequest
            });
        }
Exemplo n.º 7
0
 public AzureWebsitesXmlRepository(IAuthenticatedEncryptorConfiguration encryptorConfiguration)
 {
     _encryptorConfiguration = encryptorConfiguration as AuthenticatedEncryptorConfiguration;
 }