Пример #1
0
        public ISecretReader CreateSecretReader()
        {
            if (string.IsNullOrEmpty(_vaultName))
            {
                return(new EmptySecretReader());
            }

            var certificate = CertificateUtility.FindCertificateByThumbprint(
                !string.IsNullOrEmpty(_storeName)
                    ? (StoreName)Enum.Parse(typeof(StoreName), _storeName)
                    : StoreName.My,
                !string.IsNullOrEmpty(_storeLocation)
                    ? (StoreLocation)Enum.Parse(typeof(StoreLocation), _storeLocation)
                    : StoreLocation.LocalMachine,
                _certificateThumbprint,
                _validateCertificate);

            var keyVaultConfiguration = new KeyVaultConfiguration(
                _vaultName,
                _clientId,
                certificate,
                _sendX5c);

            return(new KeyVaultReader(keyVaultConfiguration));
        }
Пример #2
0
        public ISecretReader CreateSecretReader()
        {
            ISecretReader secretReader;

            var vaultName = _configurationService.ReadRawSetting(ResolveKeyVaultSettingName(VaultNameConfigurationKey));

            if (!string.IsNullOrEmpty(vaultName))
            {
                var clientId = _configurationService.ReadRawSetting(ResolveKeyVaultSettingName(ClientIdConfigurationKey));
                var certificateThumbprint = _configurationService.ReadRawSetting(ResolveKeyVaultSettingName(CertificateThumbprintConfigurationKey));
                var storeName             = GetOptionalKeyVaultEnumSettingValue(CertificateStoreName, StoreName.My);
                var storeLocation         = GetOptionalKeyVaultEnumSettingValue(CertificateStoreLocation, StoreLocation.LocalMachine);
                var certificate           = CertificateUtility.FindCertificateByThumbprint(storeName, storeLocation, certificateThumbprint, validationRequired: true);

                var keyVaultConfiguration = new KeyVaultConfiguration(vaultName, clientId, certificate);

                secretReader = new KeyVaultReader(keyVaultConfiguration);
            }
            else
            {
                secretReader = new EmptySecretReader();
            }

            return(new CachingSecretReader(secretReader));
        }
Пример #3
0
        public ISecretReader CreateSecretReader(IDictionary <string, string> settings)
        {
            if (JobConfigurationManager.TryGetArgument(settings, JobArgumentNames.VaultName) == null)
            {
                return(new EmptySecretReader());
            }

            var storeName     = JobConfigurationManager.TryGetArgument(settings, JobArgumentNames.StoreName);
            var storeLocation = JobConfigurationManager.TryGetArgument(settings, JobArgumentNames.StoreLocation);

            var certificate = CertificateUtility.FindCertificateByThumbprint(
                storeName != null ? (StoreName)Enum.Parse(typeof(StoreName), storeName) : StoreName.My,
                storeLocation != null ? (StoreLocation)Enum.Parse(typeof(StoreLocation), storeLocation) : StoreLocation.LocalMachine,
                JobConfigurationManager.GetArgument(settings, JobArgumentNames.CertificateThumbprint),
                JobConfigurationManager.TryGetBoolArgument(settings, JobArgumentNames.ValidateCertificate, defaultValue: true));

            var keyVaultConfiguration =
                new KeyVaultConfiguration(
                    JobConfigurationManager.GetArgument(settings, JobArgumentNames.VaultName),
                    JobConfigurationManager.GetArgument(settings, JobArgumentNames.ClientId),
                    certificate);

            var refreshIntervalSec = JobConfigurationManager.TryGetIntArgument(settings,
                                                                               JobArgumentNames.RefreshIntervalSec) ?? CachingSecretReader.DefaultRefreshIntervalSec;

            return(new CachingSecretReader(new KeyVaultReader(keyVaultConfiguration), refreshIntervalSec));
        }
Пример #4
0
        public ISecretReader CreateSecretReader()
        {
            ISecretReader secretReader;

            var vaultName = _configurationService.ReadRawSetting(ResolveKeyVaultSettingName(VaultNameConfigurationKey));

            if (!string.IsNullOrEmpty(vaultName))
            {
                var useManagedIdentity = GetOptionalKeyVaultBoolSettingValue(UseManagedIdentityConfigurationKey, defaultValue: false);

                KeyVaultConfiguration keyVaultConfiguration;
                if (useManagedIdentity)
                {
                    keyVaultConfiguration = new KeyVaultConfiguration(vaultName);
                }
                else
                {
                    var clientId = _configurationService.ReadRawSetting(ResolveKeyVaultSettingName(ClientIdConfigurationKey));
                    var certificateThumbprint = _configurationService.ReadRawSetting(ResolveKeyVaultSettingName(CertificateThumbprintConfigurationKey));
                    var storeName             = GetOptionalKeyVaultEnumSettingValue(CertificateStoreName, StoreName.My);
                    var storeLocation         = GetOptionalKeyVaultEnumSettingValue(CertificateStoreLocation, StoreLocation.LocalMachine);
                    var certificate           = CertificateUtility.FindCertificateByThumbprint(storeName, storeLocation, certificateThumbprint, validationRequired: true);
                    keyVaultConfiguration = new KeyVaultConfiguration(vaultName, clientId, certificate);
                }

                secretReader = new KeyVaultReader(keyVaultConfiguration);
            }
            else
            {
                secretReader = new EmptySecretReader();
            }

            return(new CachingSecretReader(secretReader, refreshIntervalSec: SecretCachingRefreshInterval));
        }
Пример #5
0
        public ISecretReader CreateSecretReader(IConfigurationService configurationService)
        {
            var           vaultName = configurationService.Get(VaultNameKey).Result;
            ISecretReader secretReader;

            // Is key vault configured?
            if (string.IsNullOrEmpty(vaultName))
            {
                secretReader = new EmptySecretReader();
            }
            else
            {
                var clientId = configurationService.Get(ClientIdKey).Result;
                var certificateThumbprint = configurationService.Get(CertificateThumbprintKey).Result;
                var storeLocation         = (StoreLocation)Enum.Parse(typeof(StoreLocation), configurationService.Get(StoreLocationKey).Result);
                var storeName             = (StoreName)Enum.Parse(typeof(StoreName), configurationService.Get(StoreNameKey).Result);
                var validateCertificate   = bool.Parse(configurationService.Get(ValidateCertificateKey).Result);

                var certificate = CertificateUtility.FindCertificateByThumbprint(storeName, storeLocation, certificateThumbprint, validateCertificate);

                secretReader = new KeyVaultReader(
                    new KeyVaultConfiguration(
                        vaultName,
                        clientId,
                        certificate));
            }

            return(secretReader);
        }
        private static ISecretInjector GetSecretInjector(IDictionary <string, string> arguments)
        {
            ISecretReader secretReader;

            var vaultName = arguments.GetOrDefault <string>(Arguments.VaultName);

            if (string.IsNullOrEmpty(vaultName))
            {
                secretReader = new EmptySecretReader();
            }
            else
            {
                var clientId = arguments.GetOrThrow <string>(Arguments.ClientId);
                var certificateThumbprint = arguments.GetOrThrow <string>(Arguments.CertificateThumbprint);
                var storeName             = arguments.GetOrDefault(Arguments.StoreName, StoreName.My);
                var storeLocation         = arguments.GetOrDefault(Arguments.StoreLocation, StoreLocation.LocalMachine);
                var shouldValidateCert    = arguments.GetOrDefault(Arguments.ValidateCertificate, true);

                var keyVaultCertificate = CertificateUtility.FindCertificateByThumbprint(storeName, storeLocation, certificateThumbprint, shouldValidateCert);
                var keyVaultConfig      = new KeyVaultConfiguration(vaultName, clientId, keyVaultCertificate);

                secretReader = new CachingSecretReader(new KeyVaultReader(keyVaultConfig),
                                                       arguments.GetOrDefault(Arguments.RefreshIntervalSec, CachingSecretReader.DefaultRefreshIntervalSec));
            }

            return(new SecretInjector(secretReader));
        }
Пример #7
0
        public ISecretReader CreateSecretReader()
        {
            ISecretReader secretReader;

            // Is KeyVault configured?
            if (!_configurationDictionary.TryGetValue(VaultNameKey, out var vaultName) ||
                string.IsNullOrEmpty(vaultName))
            {
                secretReader = new EmptySecretReader();
            }
            else
            {
                KeyVaultConfiguration keyVaultConfiguration;
                if (_configurationDictionary.TryGetValue(UseManagedIdentityKey, out var useManagedIdentityStr) &&
                    bool.TryParse(useManagedIdentityStr, out var useManagedIdentity) &&
                    useManagedIdentity)
                {
                    keyVaultConfiguration = new KeyVaultConfiguration(vaultName);
                }
                else
                {
                    var clientId = _configurationDictionary[ClientIdKey];
                    var certificateThumbprint = _configurationDictionary[CertificateThumbprintKey];
                    var storeLocation         = _configurationDictionary[StoreLocationKey];
                    var storeName             = _configurationDictionary[StoreNameKey];
                    var validateCertificate   = _configurationDictionary[ValidateCertificateKey];
                    var certificate           = CertificateUtility.FindCertificateByThumbprint(
                        (StoreName)Enum.Parse(typeof(StoreName), storeName),
                        (StoreLocation)Enum.Parse(typeof(StoreLocation), storeLocation),
                        certificateThumbprint,
                        bool.Parse(validateCertificate));
                    keyVaultConfiguration = new KeyVaultConfiguration(vaultName, clientId, certificate);
                }

                if (!_configurationDictionary.TryGetValue(CacheRefreshIntervalKey, out var cacheRefresh) ||
                    !int.TryParse(cacheRefresh, out int refreshIntervalSec))
                {
                    refreshIntervalSec = CachingSecretReader.DefaultRefreshIntervalSec;
                }

                secretReader = new KeyVaultReader(keyVaultConfiguration);
                secretReader = new CachingSecretReader(secretReader, refreshIntervalSec);
            }

            return(secretReader);
        }
Пример #8
0
        private async Task <ISecretReader> CreateSecretReaderAsync()
        {
            var config =
                await new ConfigurationFactory(
                    new EnvironmentSettingsConfigurationProvider(CreateSecretInjector(new EmptySecretReader())))
                .Get <BasicSearchConfiguration>();

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

            ISecretReader secretReader;

            // Is KeyVault configured?
            if (string.IsNullOrEmpty(config.VaultName))
            {
                secretReader = new EmptySecretReader();
            }
            else
            {
                // KeyVault is configured, but not all data is provided. Fail.
                if (string.IsNullOrEmpty(config.ClientId) || string.IsNullOrEmpty(config.CertificateThumbprint))
                {
                    throw new ArgumentException("Not all KeyVault configuration provided. " +
                                                $"Parameter: {nameof(BasicSearchConfiguration.VaultName)} Value: {config.VaultName}, " +
                                                $"Parameter: {nameof(BasicSearchConfiguration.ClientId)} Value: {config.ClientId}, " +
                                                $"Parameter: {nameof(BasicSearchConfiguration.CertificateThumbprint)} Value: {config.CertificateThumbprint}, " +
                                                $"Parameter: {nameof(BasicSearchConfiguration.StoreName)} Value: {config.StoreName}, " +
                                                $"Parameter: {nameof(BasicSearchConfiguration.StoreLocation)} Value: {config.StoreLocation}, " +
                                                $"Parameter: {nameof(BasicSearchConfiguration.ValidateCertificate)} Value: {config.ValidateCertificate}");
                }

                var keyVaultCertificate = CertificateUtility.FindCertificateByThumbprint(
                    config.StoreName,
                    config.StoreLocation,
                    config.CertificateThumbprint,
                    config.ValidateCertificate);
                secretReader =
                    new KeyVaultReader(new KeyVaultConfiguration(config.VaultName, config.ClientId, keyVaultCertificate));
            }

            return(secretReader);
        }
Пример #9
0
        /// <summary>
        /// Initializes a new instance of <see cref="Tailspin.Surveys.Security.CertificateCredentialService"/>.
        /// </summary>
        /// <param name="options">Configuration options for this instance."/></param>
        public CertificateCredentialService(IOptions <ConfigurationOptions> options)
        {
            var aadOptions = options.Value?.AzureAd;

            Guard.ArgumentNotNull(aadOptions, "configOptions.AzureAd");
            Guard.ArgumentNotNull(aadOptions.Asymmetric, "configOptions.AzureAd.Assymetric");

            _credential = new Lazy <Task <AdalCredential> >(() =>
            {
                X509Certificate2 cert = CertificateUtility.FindCertificateByThumbprint(
                    aadOptions.Asymmetric.StoreName,
                    aadOptions.Asymmetric.StoreLocation,
                    aadOptions.Asymmetric.CertificateThumbprint,
                    aadOptions.Asymmetric.ValidationRequired);
                string password = null;
                var certBytes   = CertificateUtility.ExportCertificateWithPrivateKey(cert, out password);
                return(Task.FromResult(new AdalCredential(new ClientAssertionCertificate(aadOptions.ClientId, new X509Certificate2(certBytes, password)))));
            });
        }
Пример #10
0
        public ISecretReader CreateSecretReader()
        {
            ISecretReader secretReader;

            var vaultName = _configurationService.ReadRawSetting(ResolveKeyVaultSettingName(VaultNameConfigurationKey));

            if (!string.IsNullOrEmpty(vaultName))
            {
                var clientId = _configurationService.ReadRawSetting(ResolveKeyVaultSettingName(ClientIdConfigurationKey));
                var certificateThumbprint = _configurationService.ReadRawSetting(ResolveKeyVaultSettingName(CertificateThumbprintConfigurationKey));
                var certificate           = CertificateUtility.FindCertificateByThumbprint(StoreName.My, StoreLocation.LocalMachine, certificateThumbprint, true);

                var keyVaultConfiguration = new KeyVaultConfiguration(vaultName, clientId, certificate);

                secretReader = new KeyVaultReader(keyVaultConfiguration);
            }
            else
            {
                secretReader = new EmptySecretReader();
            }

            return(new CachingSecretReader(secretReader, _diagnosticsService));
        }
Пример #11
0
        /// <summary>
        /// Loads all secrets which are delimited by : so that they can be retrieved by the config system
        /// Since KeyVault does not  allow : as delimiters in the share secret name, the actual name is not used as key for configuration.
        ///  The Tag property is used instead
        /// The tag should always be of the form "ConfigKey"="ParentKey1:Child1:.."
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        private async Task LoadAsync(CancellationToken token)
        {
            string password;
            var    cert      = CertificateUtility.FindCertificateByThumbprint(_storeName, _storeLocation, _certificateThumbprint, _validateCertificate);
            var    certBytes = CertificateUtility.ExportCertificateWithPrivateKey(cert, out password);

            _assertion = new ClientAssertionCertificate(_appClientId, certBytes, password);
            Data       = new Dictionary <string, string>();

            // This returns a list of identifiers which are uris to the secret, you need to use the identifier to get the actual secrets again.
            var kvClient            = new KeyVaultClient(GetTokenAsync);
            var secretsResponseList = await kvClient.GetSecretsAsync(_vault, MaxSecrets, token);

            foreach (var secretItem in secretsResponseList.Value ?? new List <SecretItem>())
            {
                //The actual config key is stored in a tag with the Key "ConfigKey" since : is not supported in a shared secret name by KeyVault
                if (secretItem.Tags != null && secretItem.Tags.ContainsKey(ConfigKey))
                {
                    var secret = await kvClient.GetSecretAsync(secretItem.Id, token);

                    Data.Add(secret.Tags[ConfigKey], secret.Value);
                }
            }
        }
Пример #12
0
 private static X509Certificate2 GetKeyVaultCertificate(string kvCertThumbprint)
 {
     return(CertificateUtility.FindCertificateByThumbprint(
                StoreName.My, StoreLocation.LocalMachine, kvCertThumbprint, validationRequired: true));
 }