public ISecretReader CreateSecretReader(IGalleryConfigurationService configurationService)
        {
            if (configurationService == null)
            {
                throw new ArgumentNullException(nameof(configurationService));
            }

            ISecretReader secretReader;

            var vaultName = configurationService.ReadSetting(
                string.Format(CultureInfo.InvariantCulture, "{0}{1}", KeyVaultConfigurationPrefix, VaultNameConfigurationKey)).Result;

            if (!string.IsNullOrEmpty(vaultName))
            {
                var clientId = configurationService.ReadSetting(
                    string.Format(CultureInfo.InvariantCulture, "{0}{1}", KeyVaultConfigurationPrefix, ClientIdConfigurationKey)).Result;
                var certificateThumbprint = configurationService.ReadSetting(
                    string.Format(CultureInfo.InvariantCulture, "{0}{1}", KeyVaultConfigurationPrefix, CertificateThumbprintConfigurationKey)).Result;

                var keyVaultConfiguration = new KeyVaultConfiguration(vaultName, clientId, certificateThumbprint, validateCertificate: true);

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

            return new CachingSecretReader(secretReader, _diagnosticsService);
        }
Exemplo n.º 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));
        }
Exemplo n.º 3
0
        public async Task <ActionResult> About()
        {
            var dbUserName = "******";
            var dbPassword = "******";

            var secrets = await KeyVaultReader.ReadSecrets(new string[] { dbUserName, dbPassword });

            var dbUserNameValue = secrets[dbUserName];
            var dbPasswordValue = secrets[dbPassword];

            ViewBag.Message  = $"Credential information";
            ViewBag.UserName = $"{dbUserNameValue}";
            ViewBag.Password = $"{dbPasswordValue}";

            // Modify credential of ConnectionString
            var connString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
            var conn       = new SqlConnection(connString);

            var securePassword = new SecureString();

            foreach (char character in dbPasswordValue)
            {
                securePassword.AppendChar(character);
            }
            securePassword.MakeReadOnly();
            conn.Credential = new SqlCredential(dbUserNameValue, securePassword);

            return(View());
        }
        public ISecretReader CreateSecretReader(IGalleryConfigurationService configurationService)
        {
            if (configurationService == null)
            {
                throw new ArgumentNullException(nameof(configurationService));
            }

            ISecretReader secretReader;

            var vaultName = configurationService.ReadSetting(
                string.Format(CultureInfo.InvariantCulture, "{0}{1}", KeyVaultConfigurationPrefix, VaultNameConfigurationKey)).Result;

            if (!string.IsNullOrEmpty(vaultName))
            {
                var clientId = configurationService.ReadSetting(
                    string.Format(CultureInfo.InvariantCulture, "{0}{1}", KeyVaultConfigurationPrefix, ClientIdConfigurationKey)).Result;
                var certificateThumbprint = configurationService.ReadSetting(
                    string.Format(CultureInfo.InvariantCulture, "{0}{1}", KeyVaultConfigurationPrefix, CertificateThumbprintConfigurationKey)).Result;

                var keyVaultConfiguration = new KeyVaultConfiguration(vaultName, clientId, certificateThumbprint, validateCertificate: true);

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

            return(new CachingSecretReader(secretReader, _diagnosticsService));
        }
        public ISecretReader CreateSecretReader(IConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            var vaultName = configuration.Get(VaultNameKey);
            ISecretReader secretReader;

            // Is key vault configured?
            if (string.IsNullOrEmpty(vaultName))
            {
                secretReader = new EmptySecretReader();
            }
            else
            {
                var clientId = configuration.Get(ClientIdKey);
                var certificateThumbprint = configuration.Get(CertificateThumbprintKey);

                // KeyVault is configured, but not all data is provided. Fail.
                if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(certificateThumbprint))
                {
                    throw new ArgumentException("Not all KeyVault configuration provided. " +
                                                $"Parameter: {VaultNameKey} Value: {VaultNameKey}, " +
                                                $"Parameter: {ClientIdKey} Value: {ClientIdKey}, " +
                                                $"Parameter: {CertificateThumbprintKey} Value: {certificateThumbprint}");
                }
               
                secretReader = new KeyVaultReader(new KeyVaultConfiguration(vaultName, clientId, certificateThumbprint, validateCertificate: true));
            }

            return secretReader;
        }
Exemplo n.º 6
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));
        }
Exemplo n.º 7
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);
        }
        public async Task AddReportDataAsync(AbstractReport reportData)
        {
            var secret = await KeyVaultReader.FetchSecret(
                MailConfiguration.KeyVaultName,
                MailConfiguration.SecretName,
                MailConfiguration.RetryCount,
                _logger);

            reportData.SmtpConfiguration = new SmtpConfiguration()
            {
                EnableSSL = true,
                SmtpHost  = MailConfiguration.SmtpHost,
                UserName  = MailConfiguration.MailSenderAddress,
                Password  = secret.Value
            };
        }
Exemplo n.º 9
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);
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
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));
        }
Exemplo n.º 12
0
        private static async Task <int> ExecuteUploadAsync(string[] args)
        {
            if (args.Length < 5)
            {
                Console.WriteLine("The first parameter is the command name: 'upload'.");
                Console.WriteLine("The second parameter must be a directory to non-recursively enumerate for files to upload.");
                Console.WriteLine("The third parameter must be a wildcard pattern of file names to upload.");
                Console.WriteLine("The fourth parameter must be a Azure Storage connection string.");
                Console.WriteLine("The fifth parameter must be a blob storage container to upload the files to.");
                Console.WriteLine("The optional sixth parameter can be a KeyVault name to inject secrets from. A managed identity will be used.");
                Console.WriteLine();
                Console.WriteLine("After uploading each file to the root of the storage container, the file will be deleted.");
                Console.WriteLine("The blob name will be the same as the original file name.");
                return(1);
            }

            var directory        = args[1];
            var pattern          = args[2];
            var connectionString = args[3];
            var containerName    = args[4];

            if (args.Length >= 6)
            {
                var vaultName = args[5];
                Console.WriteLine($"Injecting secrets into the connection string from KeyVault '{vaultName}'...");
                var keyVaultReader = new KeyVaultReader(new KeyVaultConfiguration(vaultName));
                var secretInjector = new SecretInjector(keyVaultReader);
                connectionString = await secretInjector.InjectAsync(connectionString);
            }

            Console.Write($"Searching for '{pattern}' in {directory}...");
            var files = Directory.EnumerateFiles(directory, pattern, SearchOption.TopDirectoryOnly).ToList();

            Console.WriteLine($" found {files.Count} files to upload.");

            var account   = CloudStorageAccount.Parse(connectionString);
            var client    = account.CreateCloudBlobClient();
            var container = client.GetContainerReference(containerName);

            Console.Write($"Checking the connection to {account.BlobEndpoint.AbsoluteUri}, container '{containerName}'...");
            var exists = await container.ExistsAsync();

            if (exists)
            {
                Console.WriteLine(" the container exists.");
            }
            else
            {
                Console.WriteLine(" the container does not exist. Halting.");
                return(1);
            }

            Console.WriteLine();

            var failures = 0;

            foreach (var filePath in files)
            {
                try
                {
                    var fileName = Path.GetFileName(filePath);
                    var blob     = container.GetBlockBlobReference(fileName);
                    Console.WriteLine($"File src: {filePath}");
                    Console.WriteLine($"Blob dst: {blob.Uri.AbsoluteUri}");
                    Console.Write("  Uploading the file to blob storage...");
                    await blob.UploadFromFileAsync(filePath);

                    Console.WriteLine(" done.");
                    Console.Write("  Deleting the file from the file system...");
                    File.Delete(filePath);
                    Console.WriteLine(" done.");
                    Console.WriteLine();
                }
                catch (Exception ex)
                {
                    failures++;
                    Console.WriteLine(" failed. Continuing to the next file.");
                    Console.WriteLine(ex.ToString());
                    Console.WriteLine();
                }
            }

            return(failures);
        }