Ejemplo n.º 1
0
        /// <inheritdoc/>
        public void SeedVault()
        {
            _logger.LogInformation("Starting seeding HashiCopr Vault");

            _logger.LogInformation("Creating Vault client");
            _logger.LogInformation($"Vault Address: {_options.Server}");

            IAuthenticationInfo tokenAuthenticationInfo;

            if (!string.IsNullOrWhiteSpace(_options.TokenId))
            {
                _logger.LogInformation($"Auth Token: {_options.TokenId}");
                tokenAuthenticationInfo = new TokenAuthenticationInfo(_options.TokenId);
            }
            else
            {
                _logger.LogInformation($"AppRole RoleId: {_options.RoleId}");
                _logger.LogInformation($"AppRole SecretId: {_options.SecretId}");

                tokenAuthenticationInfo = new AppRoleAuthenticationInfo("approle", _options.RoleId, _options.SecretId);
            }

            _logger.LogInformation($"Create Vault Client: {_options.Server}");
            var vaultClient = VaultClientFactory.CreateVaultClient(new Uri(_options.Server), tokenAuthenticationInfo);

            foreach (var item in _seeder)
            {
                _logger.LogDebug($"key:{item.key} -- property name: {item.values[0]} -- property value: {item.values[1]}");
                var result = vaultClient.WriteSecretAsync(item.key, new Dictionary <string, object>()
                {
                    { item.values[0], item.values[1] }
                }).Result;
                _logger.LogDebug($"Result from Vault Server: {result?.ToString()}");
            }
        }
        public TokenAuthenticationProvider(TokenAuthenticationInfo tokenAuthenticationInfo)
        {
            Checker.NotNull(tokenAuthenticationInfo, "tokenAuthenticationInfo");
            Checker.NotNull(tokenAuthenticationInfo.Token, "tokenAuthenticationInfo.Token");

            _tokenAuthenticationInfo = tokenAuthenticationInfo;
        }
Ejemplo n.º 3
0
        public VaultClient(string vaultAddr, string vaultToken, string keyName)
        {
            Uri vaultUri = new Uri(vaultAddr);
            IAuthenticationInfo tokenAuthenticationInfo = new TokenAuthenticationInfo(vaultToken);

            client         = VaultClientFactory.CreateVaultClient(vaultUri, tokenAuthenticationInfo);
            transitKeyName = keyName;
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            //start Vault Server in dev mode
            // ./vault server -dev

            string vaultAddressWithPort = "http://127.0.0.1:8200";
            string token = "75a244db-9164-4130-db60-50c7081f50ba";

            System.Console.WriteLine("Creating Vault client");
            System.Console.WriteLine($"Vault Address: {vaultAddressWithPort}");
            System.Console.WriteLine($"Auth Token: {token}");

            IAuthenticationInfo tokenAuthenticationInfo = new TokenAuthenticationInfo(token);
            var vaultClient = VaultClientFactory.CreateVaultClient(new Uri(vaultAddressWithPort), tokenAuthenticationInfo);

            System.Console.WriteLine("Writing data to Vault...");
            var resulA = vaultClient.WriteSecretAsync("secret/keyA", new Dictionary <string, object>()
            {
                { "prop1", "valueA" }
            }).Result;

            var resultB = vaultClient.WriteSecretAsync("secret/keyB", new Dictionary <string, object>()
            {
                { "prop1", "valueB" }
            }).Result;

            var resultC = vaultClient.WriteSecretAsync("secret/group1/keyC", new Dictionary <string, object>()
            {
                { "prop1", "valueC" }
            }).Result;

            var resultD = vaultClient.WriteSecretAsync("secret/group2/keyD", new Dictionary <string, object>()
            {
                { "prop1", "valueD" }
            }).Result;

            var client = new HashiCorpVaultClientWrapper(vaultAddressWithPort, token);

            IConfigurationBuilder configBuilder =
                new ConfigurationBuilder()
                .AddHashiCorpVault(client, "secret", new[] { "keyA", "keyB", "group1/keyC" })
                .AddHashiCorpVault(client, "secret/group2", new[] { "keyD" });

            System.Console.WriteLine("Building configuration...");

            IConfiguration config = configBuilder.Build();

            System.Console.WriteLine("The following settings populated:");

            foreach (var item in config.AsEnumerable())
            {
                System.Console.WriteLine(item);
            }
        }
Ejemplo n.º 5
0
        private async Task TokenAuthenticationProviderTests()
        {
            // token auth

            var secret = await _authenticatedVaultClient.CreateTokenAsync();

            var tokenAuthenticationInfo = new TokenAuthenticationInfo(secret.AuthorizationInfo.ClientToken);
            var tokenClient             = VaultClientFactory.CreateVaultClient(_vaultUri, tokenAuthenticationInfo);

            var authBackends = await tokenClient.GetAllEnabledAuthenticationBackendsAsync();

            Assert.True(authBackends.Data.Any());
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance with <see cref="VaultOptions"/>
        /// </summary>
        /// <param name="options"></param>
        public HashiCorpVaultClientWrapper(VaultOptions options)
        {
            _options = options;

            IAuthenticationInfo authInfo;

            // token present so authetnication with token
            if (!string.IsNullOrWhiteSpace(_options.TokenId))
            {
                authInfo = new TokenAuthenticationInfo(_options.TokenId);
            }
            else
            {
                authInfo = new AppRoleAuthenticationInfo("approle", _options.RoleId, _options.SecretId);
            }

            _vaultClientImpl = VaultClientFactory.CreateVaultClient(new Uri(_options.Server), authInfo);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Adds an <see cref="IConfigurationProvider"/> that reads configuration values from Hashicorp Vault.
        /// </summary>
        /// <param name="configurationBuilder">The <see cref="IConfigurationBuilder"/> to add to.</param>
        /// <param name="vaultUri">The Vault uri with port.</param>
        /// <param name="token">The token to use for authentication.</param>
        /// <param name="secretLocationPaths">The paths for the secrets to load.</param>
        /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
        public static IConfigurationBuilder AddVaultWithToken(
            this IConfigurationBuilder configurationBuilder,
            string vaultUri,
            string token,
            params string[] secretLocationPaths)
        {
            if (string.IsNullOrWhiteSpace(vaultUri))
            {
                throw new ArgumentException("vaultUri must be a valid URI", nameof(vaultUri));
            }
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentException("token must not be null or empty", nameof(token));
            }

            var authInfo = new TokenAuthenticationInfo(token);

            return(AddVault(configurationBuilder, vaultUri, authInfo, secretLocationPaths));
        }
Ejemplo n.º 8
0
        private static void InitializeVault()
        {
            // for all the tests to run smoothly, this is the only method,
            // you need to setup your initial values.
            // Ensure you have an instance of Vault Server started up but not initialized.

            /*
             *
             *  backend "file" {
             *    path = "e:\raja\work\vault\file_backend"
             *  }
             *
             *  listener "tcp" {
             *    address = "127.0.0.1:8200"
             *    tls_disable = 1
             *  }
             *
             *  rd file_backend /S /Q
             *  vault server -config f.hcl
             *
             */

            var vaultUriWithPort = "http://127.0.0.1:8200";

            _vaultUri = new Uri(vaultUriWithPort);
            _unauthenticatedVaultClient = VaultClientFactory.CreateVaultClient(_vaultUri, null);

            if (DevServer)
            {
                _masterCredentials = new MasterCredentials
                {
                    MasterKeys = new[] { MasterKey },
                    RootToken  = RootToken
                };

                IAuthenticationInfo devRootTokenInfo = new TokenAuthenticationInfo(_masterCredentials.RootToken);
                _authenticatedVaultClient = VaultClientFactory.CreateVaultClient(_vaultUri, devRootTokenInfo);

                return;
            }

            // BEGIN setting values

            var fileName = "E:\\raja\\work\\vault0.6.1\\StartVault.cmd";

            var process = Process.Start(new ProcessStartInfo(fileName));

            Assert.NotNull(process);

            _vaultServerProcessId = process.Id;

            // END setting values

            var initialized = _unauthenticatedVaultClient.GetInitializationStatusAsync().Result;

            Assert.False(initialized);

            var healthStatus = _unauthenticatedVaultClient.GetHealthStatusAsync().Result;

            Assert.False(healthStatus.Initialized);

            // try to initialize with mismatched PGP Key
            var invalidPgpException =
                Assert.Throws <AggregateException>(
                    () =>
                    _masterCredentials =
                        _unauthenticatedVaultClient.InitializeAsync(new InitializeOptions
            {
                SecretShares    = 5,
                SecretThreshold = 3,
                PgpKeys         = new[] { Convert.ToBase64String(Encoding.UTF8.GetBytes("pgp_key1")) }
            }).Result);

            Assert.NotNull(invalidPgpException.InnerException);
            Assert.True(invalidPgpException.InnerException.Message.Contains("400 BadRequest"));

            _masterCredentials = _unauthenticatedVaultClient.InitializeAsync(new InitializeOptions
            {
                SecretShares    = 7,
                SecretThreshold = 6
            }).Result;

            Assert.NotNull(_masterCredentials);
            Assert.NotNull(_masterCredentials.RootToken);
            Assert.NotNull(_masterCredentials.MasterKeys);

            Assert.True(_masterCredentials.MasterKeys.Length == 7);

            process.CloseMainWindow();
            process.WaitForExit();

            process = Process.Start(new ProcessStartInfo(fileName));
            Assert.NotNull(process);

            _vaultServerProcessId = process.Id;

            // todo find valid PGP keys
            //var pgpKeys = new[] { Convert.ToBase64String(Encoding.UTF8.GetBytes("pgp_key1")), Convert.ToBase64String(Encoding.UTF8.GetBytes("pgp_key2")) };

            //_masterCredentials = _unauthenticatedVaultClient.InitializeAsync(2, 2, pgpKeys).Result;

            //Assert.NotNull(_masterCredentials);
            //Assert.NotNull(_masterCredentials.RootToken);
            //Assert.NotNull(_masterCredentials.MasterKeys);

            //Assert.True(_masterCredentials.MasterKeys.Length == 5);

            //process.CloseMainWindow();
            //process.WaitForExit();

            //process = Process.Start(new ProcessStartInfo(fileName));
            //Assert.NotNull(process);

            //_vaultServerProcessId = process.Id;

            _masterCredentials = _unauthenticatedVaultClient.InitializeAsync(new InitializeOptions
            {
                SecretShares    = 5,
                SecretThreshold = 3
            }).Result;

            Assert.NotNull(_masterCredentials);
            Assert.NotNull(_masterCredentials.RootToken);
            Assert.NotNull(_masterCredentials.MasterKeys);

            Assert.True(_masterCredentials.MasterKeys.Length == 5);

            healthStatus = _unauthenticatedVaultClient.GetHealthStatusAsync().Result;
            Assert.True(healthStatus.Initialized);
            Assert.True(healthStatus.Sealed);

            // try to initialize an already initialized vault.
            var aggregateException =
                Assert.Throws <AggregateException>(
                    () => _masterCredentials = _unauthenticatedVaultClient.InitializeAsync(new InitializeOptions
            {
                SecretShares    = 5,
                SecretThreshold = 3
            }).Result);

            Assert.NotNull(aggregateException.InnerException);
            Assert.True(aggregateException.InnerException.Message.Contains("Vault is already initialized"));

            var sealStatus = _unauthenticatedVaultClient.GetSealStatusAsync().Result;

            if (sealStatus.Sealed)
            {
                foreach (var masterKey in _masterCredentials.MasterKeys)
                {
                    sealStatus = _unauthenticatedVaultClient.UnsealAsync(masterKey).Result;

                    if (!sealStatus.Sealed)
                    {
                        healthStatus = _unauthenticatedVaultClient.GetHealthStatusAsync().Result;
                        Assert.True(healthStatus.Initialized);
                        Assert.False(healthStatus.Sealed);

                        // we are acting as the root user here.

                        IAuthenticationInfo tokenAuthenticationInfo =
                            new TokenAuthenticationInfo(_masterCredentials.RootToken);
                        _authenticatedVaultClient = VaultClientFactory.CreateVaultClient(_vaultUri, tokenAuthenticationInfo);

                        break;
                    }
                }
            }
        }
        public HashiCorpVaultClientWrapper(string vaultAddressWithPort, string token)
        {
            IAuthenticationInfo authenticationInfo = new TokenAuthenticationInfo(token);

            _vaultClientImplementation = VaultClientFactory.CreateVaultClient(new Uri(vaultAddressWithPort), authenticationInfo);
        }
Ejemplo n.º 10
0
        public static bool AuthenticateByToken(RequestContext requestContext, IApplicationService appService, out AuthorizationUserInfo authAppInfo, out Application app)
        {
            authAppInfo = null;
            app         = null;

            var authToken = GetTokenFromAuthorizationHeader(requestContext.HttpContext.Request);

            if (string.IsNullOrWhiteSpace(authToken))
            {
                return(false);
            }

            TokenAuthenticationInfo info = null;

            try
            {
                var infoJson = Encoding.UTF8.GetString(Convert.FromBase64String(authToken.Trim()));
                info = JsonConvert.DeserializeObject <TokenAuthenticationInfo>(infoJson);
            }
            catch
            {
                // ignore
            }

            if (string.IsNullOrWhiteSpace(info?.AppToken))
            {
                throw new ChalkableSecurityException("Invalid auth token");
            }

            var ts = ChalkableAuthorization.DateTimeToUnixTimestamp(DateTime.UtcNow.AddMinutes(-5));

            if (ts > info.Timestamp)
            {
                throw new ChalkableSecurityException("Auth token has expired");
            }

            try
            {
                var authInfo = EncryptionTools.AesDecrypt(info.AppToken, Chalkable.Common.Settings.AesSecretKey);
                authAppInfo = AuthorizationUserInfo.FromString(authInfo);
            }
            catch (Exception)
            {
                throw new ChalkableSecurityException("Invalid auth app token");
            }

            app = appService.GetApplicationById(authAppInfo.ApplicationId);

            if (app == null)
            {
                throw new ChalkableSecurityException("Invalid auth app token");
            }

            var hash = ChalkableAuthorization.ComputeSignature(requestContext.HttpContext.Request.HttpMethod, requestContext.HttpContext.Request.Url
                                                               , requestContext.HttpContext.Request.ContentLength, info.Timestamp, info.AppToken, app.SecretKey);

            if (string.CompareOrdinal(hash, info.Signature) != 0)
            {
                throw new ChalkableSecurityException("Auth token has invalid signature");
            }

            return(true);
        }