Ejemplo n.º 1
0
        public HighAvailabilityViewModel(IDialogCoordinator dialogCoordinator, IShellExecuteProvider shellExecuteProvider, IAmsLicenseManager licenseManager, ILogger <HighAvailabilityViewModel> logger, INotifyModelChangedEventPublisher eventPublisher, DatabaseConfigurationOptions highAvailabilityOptions, DataProtectionOptions dataProtectionOptions, ICertificateSynchronizationProvider certSyncProvider, ISecretRekeyProvider rekeyProvider, SqlServerInstanceProvider sqlInstanceProvider, IScriptTemplateProvider scriptTemplateProvider, IWindowsServiceProvider windowsServiceProvider)
        {
            this.shellExecuteProvider = shellExecuteProvider;
            this.licenseManager       = licenseManager;
            this.logger                 = logger;
            this.dbOptions              = highAvailabilityOptions;
            this.dataProtectionOptions  = dataProtectionOptions;
            this.certSyncProvider       = certSyncProvider;
            this.dialogCoordinator      = dialogCoordinator;
            this.rekeyProvider          = rekeyProvider;
            this.sqlInstanceProvider    = sqlInstanceProvider;
            this.scriptTemplateProvider = scriptTemplateProvider;
            this.windowsServiceProvider = windowsServiceProvider;

            this.licenseManager.OnLicenseDataChanged += delegate
            {
                this.NotifyOfPropertyChange(nameof(this.IsEnterpriseEdition));
                this.NotifyOfPropertyChange(nameof(this.ShowEnterpriseEditionBanner));
            };

            this.DisplayName = "High availability";
            eventPublisher.Register(this);

            this.isClusterCompatibleSecretEncryptionEnabled = this.dataProtectionOptions.EnableClusterCompatibleSecretEncryption;
        }
        public void ExpectBuilderAdditions(bool withClient)
        {
            var services = new List <ServiceDescriptor>();

            builder.Setup(x => x.Services).Returns(svcCollection.Object);
            svcCollection.Setup(x => x.GetEnumerator()).Returns(() => services.GetEnumerator());
            svcCollection.Setup(x => x.Add(It.IsAny <ServiceDescriptor>()))
            .Callback <ServiceDescriptor>(sd => { services.Add(sd); });

            var config = new KmsXmlEncryptorConfig("keyId");

            // Repeat call to ensure cumulative calls work
            if (withClient)
            {
                builder.Object.ProtectKeysWithAwsKms(client.Object, config);
                builder.Object.ProtectKeysWithAwsKms(client.Object, config);
            }
            else
            {
                builder.Object.ProtectKeysWithAwsKms(config);
                builder.Object.ProtectKeysWithAwsKms(config);
            }

            Assert.Equal(withClient ? 1 : 0, services.Count(x => x.ServiceType == typeof(IAmazonKeyManagementService)));

            // IConfigureOptions is designed & expected to be present multiple times, so expect two after two calls
            Assert.Equal(2, services.Count(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)));
            Assert.Equal(2, services.Count(x => x.ServiceType == typeof(IConfigureOptions <KmsXmlEncryptorConfig>)));

            Assert.Equal(ServiceLifetime.Singleton, services.First(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)).Lifetime);
            Assert.Equal(ServiceLifetime.Singleton, services.First(x => x.ServiceType == typeof(IConfigureOptions <KmsXmlEncryptorConfig>)).Lifetime);

            provider.Setup(x => x.GetService(typeof(IAmazonKeyManagementService))).Returns(client.Object);
            if (withClient)
            {
                Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(IAmazonKeyManagementService)).Lifetime);
                Assert.Same(client.Object, services.Single(x => x.ServiceType == typeof(IAmazonKeyManagementService)).ImplementationInstance);
            }
            // Ensure we run equivalent config for the actual configuration object
            var configureObject = services.First(x => x.ServiceType == typeof(IConfigureOptions <KmsXmlEncryptorConfig>)).ImplementationInstance;
            var optionsObject   = new KmsXmlEncryptorConfig();

            ((IConfigureOptions <KmsXmlEncryptorConfig>)configureObject).Configure(optionsObject);

            provider.Setup(x => x.GetService(typeof(ILoggerFactory))).Returns(loggerFactory.Object);
            provider.Setup(x => x.GetService(typeof(IOptions <KmsXmlEncryptorConfig>))).Returns(snapshot.Object);
            provider.Setup(x => x.GetService(typeof(IOptions <DataProtectionOptions>))).Returns(dpSnapshot.Object);
            loggerFactory.Setup(x => x.CreateLogger(typeof(KmsXmlEncryptor).FullName)).Returns(repository.Create <ILogger <KmsXmlEncryptor> >().Object);
            snapshot.Setup(x => x.Value).Returns(optionsObject);
            var dbOptions = new DataProtectionOptions();

            dpSnapshot.Setup(x => x.Value).Returns(dbOptions);

            var configure = services.First(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)).ImplementationFactory(provider.Object);
            var options   = new KeyManagementOptions();

            ((IConfigureOptions <KeyManagementOptions>)configure).Configure(options);
            Assert.IsType <KmsXmlEncryptor>(options.XmlEncryptor);
        }
Ejemplo n.º 3
0
 public static void ConfigureOptions(AntiforgeryOptions options, DataProtectionOptions dataProtectionOptions)
 {
     if (options.CookieName == null)
     {
         var applicationId = dataProtectionOptions.ApplicationDiscriminator ?? string.Empty;
         options.CookieName = ComputeCookieName(applicationId);
     }
 }
Ejemplo n.º 4
0
 public ProtectedSecretProvider(IEncryptionProvider encryptionProvider, ICertificateProvider certificateProvider, RandomNumberGenerator rng, IOptions <DataProtectionOptions> dataProtectionOptions, IWindowsServiceProvider windowsServiceProvider, IAmsLicenseManager licenseManager)
 {
     this.encryptionProvider  = encryptionProvider;
     this.certificateProvider = certificateProvider;
     this.rng = rng;
     this.dataProtectionOptions  = dataProtectionOptions.Value;
     this.windowsServiceProvider = windowsServiceProvider;
     this.licenseManager         = licenseManager;
 }
        public void ExpectEncryptToSucceed(bool useAppId, bool hashAppId, string appId, string expectedAppId)
        {
            var myEncryptedString     = "encrypted";
            var myBase64EncryptedData = Convert.ToBase64String(Encoding.UTF8.GetBytes(myEncryptedString));
            var myEncryptedXml        = new XElement(ElementName, new XElement("value", myBase64EncryptedData));
            var myOutputXml           = new XElement(ElementName, "output");

            using (var decryptedResponseStream = new MemoryStream())
            {
                myOutputXml.Save(decryptedResponseStream);
                decryptedResponseStream.Seek(0, SeekOrigin.Begin);

                var decryptResponse = new DecryptResponse
                {
                    KeyId     = KeyId,
                    Plaintext = decryptedResponseStream
                };

                var actualConfig = new KmsXmlEncryptorConfig
                {
                    EncryptionContext        = encryptionContext,
                    GrantTokens              = grantTokens,
                    KeyId                    = KeyId,
                    DiscriminatorAsContext   = useAppId,
                    HashDiscriminatorContext = hashAppId
                };

                var actualOptions = new DataProtectionOptions
                {
                    ApplicationDiscriminator = appId
                };

                encryptConfig.Setup(x => x.Value).Returns(actualConfig);
                dpOptions.Setup(x => x.Value).Returns(actualOptions);

                kmsClient.Setup(x => x.DecryptAsync(It.IsAny <DecryptRequest>(), CancellationToken.None))
                .ReturnsAsync(decryptResponse)
                .Callback <DecryptRequest, CancellationToken>((dr, ct) =>
                {
                    if (appId != null && useAppId)
                    {
                        Assert.Contains(KmsConstants.ApplicationEncryptionContextKey, dr.EncryptionContext.Keys);
                        Assert.Equal(expectedAppId, dr.EncryptionContext[KmsConstants.ApplicationEncryptionContextKey]);
                    }
                    else
                    {
                        Assert.Same(encryptionContext, dr.EncryptionContext);
                    }
                    Assert.Same(grantTokens, dr.GrantTokens);

                    Assert.Equal(myEncryptedString, Encoding.UTF8.GetString(dr.CiphertextBlob.ToArray()));
                });

                var plaintextXml = decryptor.Decrypt(myEncryptedXml);
                Assert.True(XNode.DeepEquals(myOutputXml, plaintextXml));
            }
        }
 public CertificateSynchronizationProvider(RandomNumberGenerator rng, ILogger <CertificateSynchronizationProvider> logger, IOptionsMonitor <DataProtectionOptions> dataProtectionOptions, IProtectedSecretProvider secretProvider, ICertificatePermissionProvider certPermissionProvider, IAmsLicenseManager licenseManager)
     : this(rng, logger, secretProvider, certPermissionProvider, licenseManager)
 {
     this.dataProtectionOptions = dataProtectionOptions.CurrentValue;
     dataProtectionOptions.OnChange((o, s) =>
     {
         this.dataProtectionOptions = o;
         this.ImportCertificatesFromConfig();
     });
 }
 public DependencyModule(ILogger <DependencyModule> logger, SharedOptions sharedOptions,
                         StorageOptions storageOptions, DistributedCacheOptions distributedCacheOptions,
                         DataProtectionOptions dataProtectionOptions, ResponseCachingOptions responseCachingOptions)
 {
     _logger                  = logger;
     _sharedOptions           = sharedOptions;
     _storageOptions          = storageOptions;
     _distributedCacheOptions = distributedCacheOptions;
     _dataProtectionOptions   = dataProtectionOptions;
     _responseCachingOptions  = responseCachingOptions;
 }
Ejemplo n.º 8
0
 public DependencyModule(
     ILogger <DependencyModule> logger,
     SharedOptions sharedOptions, CompaniesHouseOptions coHoOptions,
     ResponseCachingOptions responseCachingOptions, DistributedCacheOptions distributedCacheOptions,
     DataProtectionOptions dataProtectionOptions, BasicAuthenticationOptions basicAuthenticationOptions)
 {
     _logger                     = logger;
     _sharedOptions              = sharedOptions;
     _coHoOptions                = coHoOptions;
     _responseCachingOptions     = responseCachingOptions;
     _distributedCacheOptions    = distributedCacheOptions;
     _dataProtectionOptions      = dataProtectionOptions;
     _basicAuthenticationOptions = basicAuthenticationOptions;
 }
Ejemplo n.º 9
0
        public LapsConfigurationViewModel(IDialogCoordinator dialogCoordinator, ICertificateProvider certificateProvider, IX509Certificate2ViewModelFactory certificate2ViewModelFactory, IWindowsServiceProvider windowsServiceProvider, ILogger <LapsConfigurationViewModel> logger, IShellExecuteProvider shellExecuteProvider, IDomainTrustProvider domainTrustProvider, IDiscoveryServices discoveryServices, IScriptTemplateProvider scriptTemplateProvider, ICertificatePermissionProvider certPermissionProvider, DataProtectionOptions dataProtectionOptions, INotifyModelChangedEventPublisher eventPublisher)
        {
            this.shellExecuteProvider         = shellExecuteProvider;
            this.certificateProvider          = certificateProvider;
            this.certificate2ViewModelFactory = certificate2ViewModelFactory;
            this.dialogCoordinator            = dialogCoordinator;
            this.windowsServiceProvider       = windowsServiceProvider;
            this.logger = logger;
            this.domainTrustProvider    = domainTrustProvider;
            this.discoveryServices      = discoveryServices;
            this.scriptTemplateProvider = scriptTemplateProvider;
            this.dataProtectionOptions  = dataProtectionOptions;
            this.eventPublisher         = eventPublisher;

            this.Forests = new List <Forest>();
            this.AvailableCertificates  = new BindableCollection <X509Certificate2ViewModel>();
            this.DisplayName            = "Local admin passwords";
            this.certPermissionProvider = certPermissionProvider;
        }
Ejemplo n.º 10
0
        public static void ConfigureOptions(CaptchaOptions options, DataProtectionOptions dataProtectionOptions)
        {
            if (null == options.FormField.Name)
            {
                options.FormField.Name = CaptchaOptions.DefaultFormField;
            }

            if (null == options.Cookie.Name)
            {
                var applicationId = dataProtectionOptions.ApplicationDiscriminator ?? String.Empty;
                options.Cookie.Name = CaptchaOptions.DefaultCookiePrefix + GenerateCookieSuffix(applicationId);
            }

            if (false == options.Cookie.Expiration.HasValue)
            {
                options.Cookie.Expiration = TimeSpan.FromMinutes(15.0d);
            }

            if (TimeSpan.Zero >= options.Timeout)
            {
                options.Timeout = TimeSpan.FromMinutes(3.0d);
            }
        }
        public KmsIntegrationTests()
        {
            // Expectation that local SDK has been configured correctly, whether via VS Tools or user config files
            kmsClient = new AmazonKeyManagementServiceClient(RegionEndpoint.EUWest1);
            var encryptConfig = new KmsXmlEncryptorConfig(KmsTestingKey);

            dpOptions = new DataProtectionOptions {
                ApplicationDiscriminator = ApplicationName
            };
            var encryptSnapshot = new DirectOptions <KmsXmlEncryptorConfig>(encryptConfig);
            var dpSnapshot      = new DirectOptions <DataProtectionOptions>(dpOptions);

            var svcCollection = new ServiceCollection();

            svcCollection.AddSingleton <IOptions <KmsXmlEncryptorConfig> >(sp => encryptSnapshot);
            svcCollection.AddSingleton <IOptions <DataProtectionOptions> >(sp => dpSnapshot);
            svcCollection.AddSingleton(sp => kmsClient);
            svcProvider = svcCollection.BuildServiceProvider();

            encryptor = new KmsXmlEncryptor(kmsClient, encryptSnapshot, dpSnapshot);

            decryptor = new KmsXmlDecryptor(svcProvider);
        }
        public void ExpectEncryptToSucceed(bool useAppId, bool hashAppId, string appId, string expectedAppId)
        {
            var myInputXml = new XElement(ElementName, "input");

            byte[] myEncryptedData       = Encoding.UTF8.GetBytes("encrypted");
            var    myBase64EncryptedData = Convert.ToBase64String(myEncryptedData);

            using (var encryptedResponseStream = new MemoryStream())
            {
                encryptedResponseStream.Write(myEncryptedData, 0, myEncryptedData.Length);
                encryptedResponseStream.Seek(0, SeekOrigin.Begin);

                var encryptResponse = new EncryptResponse
                {
                    KeyId          = KeyId,
                    CiphertextBlob = encryptedResponseStream
                };

                var actualConfig = new KmsXmlEncryptorConfig
                {
                    EncryptionContext        = encryptionContext,
                    GrantTokens              = grantTokens,
                    KeyId                    = KeyId,
                    DiscriminatorAsContext   = useAppId,
                    HashDiscriminatorContext = hashAppId
                };

                var actualOptions = new DataProtectionOptions
                {
                    ApplicationDiscriminator = appId
                };

                encryptConfig.Setup(x => x.Value).Returns(actualConfig);
                dpOptions.Setup(x => x.Value).Returns(actualOptions);

                kmsClient.Setup(x => x.EncryptAsync(It.IsAny <EncryptRequest>(), CancellationToken.None))
                .ReturnsAsync(encryptResponse)
                .Callback <EncryptRequest, CancellationToken>((er, ct) =>
                {
                    if (appId != null && useAppId)
                    {
                        Assert.Contains(KmsConstants.ApplicationEncryptionContextKey, er.EncryptionContext.Keys);
                        Assert.Equal(expectedAppId, er.EncryptionContext[KmsConstants.ApplicationEncryptionContextKey]);
                    }
                    else
                    {
                        Assert.Same(encryptionContext, er.EncryptionContext);
                    }
                    Assert.Same(grantTokens, er.GrantTokens);

                    var body = XElement.Load(er.Plaintext);
                    Assert.True(XNode.DeepEquals(myInputXml, body));
                });

                var encryptedXml = encryptor.Encrypt(myInputXml);

                Assert.Equal(typeof(KmsXmlDecryptor), encryptedXml.DecryptorType);
                var encryptedBlob = (string)encryptedXml.EncryptedElement.Element("value");
                Assert.Equal(myBase64EncryptedData, encryptedBlob);
            }
        }
 public CertificateSynchronizationProvider(RandomNumberGenerator rng, ILogger <CertificateSynchronizationProvider> logger, DataProtectionOptions dataProtectionOptions, IProtectedSecretProvider secretProvider, ICertificatePermissionProvider certPermissionProvider, IAmsLicenseManager licenseManager)
     : this(rng, logger, secretProvider, certPermissionProvider, licenseManager)
 {
     this.dataProtectionOptions = dataProtectionOptions;
 }
Ejemplo n.º 14
0
 public AntiforgeryOptionsSetup(IOptions <DataProtectionOptions> dataProtectionOptions)
 {
     _dataProtectionOptions = dataProtectionOptions.Value;
 }
 public AntiForgeryMultitenantPostConfigureOptions(IHttpContextAccessor httpContextAccessor, IOptions <DataProtectionOptions> dataProtectionOptions)
 {
     _httpContextAccessor   = httpContextAccessor;
     _dataProtectionOptions = dataProtectionOptions.Value;
 }
        public static Dictionary <string, string> GetEncryptionContext(IKmsXmlEncryptorConfig config, DataProtectionOptions dpOptions)
        {
            var encryptionContext = config.EncryptionContext;

            // Set the application discriminator as part of the context of encryption, given the intent of the discriminator
            if (config.DiscriminatorAsContext && !string.IsNullOrEmpty(dpOptions.ApplicationDiscriminator))
            {
                encryptionContext = encryptionContext.ToDictionary(x => x.Key, x => x.Value);

                var contextValue = dpOptions.ApplicationDiscriminator;

                // Some application discriminators (like the defaults) leak sensitive file paths, so hash them
                if (config.HashDiscriminatorContext)
                {
                    using (var hasher = SHA256.Create())
                    {
                        contextValue = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(contextValue)));
                    }
                }

                encryptionContext[KmsConstants.ApplicationEncryptionContextKey] = contextValue;
            }
            return(encryptionContext);
        }
 /// <summary>   Constructor. </summary>
 /// <exception cref="ArgumentNullException">    Thrown when one or more required arguments are
 ///                                             null. </exception>
 /// <param name="options">  Options for controlling the operation. </param>
 public DataProtectionDataProvider(DataProtectionOptions options)
 {
     _options = options ?? throw new ArgumentNullException(nameof(options));
 }
Ejemplo n.º 18
0
 public AntiForgeryOptionsConfiguration(IOptions <DataProtectionOptions> dataProtectionOptions)
 {
     _dataProtectionOptions = dataProtectionOptions.Value;
 }