Example #1
0
        private IVaultClient CreateVaultClient()
        {
            var authMethod          = new TokenAuthMethodInfo(_configuration["VAULT_TOKEN_ID"]);
            var vaultClientSettings = new VaultClientSettings(_configuration["VAULT_ADDRESS"], authMethod);

            return(new VaultClient(vaultClientSettings));
        }
Example #2
0
        /// <inheritdoc/>
        public override void Load()
        {
            try
            {
                IAuthMethodInfo authMethod;
                if (!string.IsNullOrEmpty(this._source.Options.VaultRoleId) &&
                    !string.IsNullOrEmpty(this._source.Options.VaultSecret))
                {
                    authMethod = new AppRoleAuthMethodInfo(
                        this._source.Options.VaultRoleId,
                        this._source.Options.VaultSecret);
                }
                else
                {
                    authMethod = new TokenAuthMethodInfo(this._source.Options.VaultToken);
                }

                var vaultClientSettings = new VaultClientSettings(this._source.Options.VaultAddress, authMethod)
                {
                    UseVaultTokenHeaderInsteadOfAuthorizationHeader = true,
                };
                IVaultClient vaultClient = new VaultClient(vaultClientSettings);

                using var ctx = new JoinableTaskContext();
                var jtf = new JoinableTaskFactory(ctx);
                jtf.RunAsync(
                    async() => { await this.LoadVaultDataAsync(vaultClient).ConfigureAwait(true); }).Join();
            }
            catch (Exception e) when(e is VaultApiException || e is System.Net.Http.HttpRequestException)
            {
                this._logger?.Log(LogLevel.Error, e, "Cannot load configuration from Vault");
            }
        }
Example #3
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            CancelAddButton.IsEnabled = false;
            AddKeyButton.IsEnabled    = false;
            AddKeyButton.Content      = "Processing...";

            IAuthMethodInfo authMethod          = new TokenAuthMethodInfo(Properties.Settings.Default.VaultToken);
            var             vaultClientSettings = new VaultClientSettings(Properties.Settings.Default.VaultURL, authMethod);

            IVaultClient         vaultClient      = new VaultClient(vaultClientSettings);
            TOTPCreateKeyRequest createKeyRequest = new TOTPCreateKeyRequest
            {
                AccountName         = ProductBox.Text,
                Algorithm           = "SHA1",
                Period              = "30",
                Issuer              = VendorBox.Text,
                KeyGenerationOption = new TOTPNonVaultBasedKeyGeneration {
                    AccountName = ProductBox.Text,
                    Issuer      = VendorBox.Text,
                    Key         = SecretBox.Text,
                },
            };



            Secret <TOTPCreateKeyResponse> createResponse = await vaultClient.V1.Secrets.TOTP.CreateKeyAsync(Guid.NewGuid().ToString(), createKeyRequest);



            this.DialogResult = true;
            this.Close();
        }
        public static IVaultClient GetVaultClient(string token, string vaultUri)
        {
            IAuthMethodInfo authMethod          = new TokenAuthMethodInfo(token);
            var             vaultClientSettings = new VaultClientSettings(vaultUri, authMethod);
            IVaultClient    vaultClient         = new VaultSharp.VaultClient(vaultClientSettings);

            return(vaultClient);
        }
Example #5
0
        private async Task LoadDataAsync(string secretPath, string jsonData)
        {
            var authMethod = new TokenAuthMethodInfo("root");

            var          vaultClientSettings = new VaultClientSettings("http://localhost:8200", authMethod);
            IVaultClient vaultClient         = new VaultClient(vaultClientSettings);

            var dictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonData);
            await vaultClient.V1.Secrets.KeyValue.V2.WriteSecretAsync(secretPath, dictionary).ConfigureAwait(false);
        }
Example #6
0
        public VaultSrnProvider(IConfiguration options)
        {
            _mountPoint = options["MountPoint"];

            // Instantiate the client
            var authMethod = new TokenAuthMethodInfo(options["Token"]);
            var settings   = new VaultClientSettings(options["Url"], authMethod);

            _client = new VaultClient(settings);
            _engine = _client.V1.Secrets.KeyValue.V2;
        }
        private IVaultClient CreateVaultClient()
        {
            var vaultToken   = Environment.GetEnvironmentVariable("VAULT_TOKEN_ID");
            var vaultAddress = Environment.GetEnvironmentVariable("VAULT_ADDRESS");

            var authMethod          = new TokenAuthMethodInfo(vaultToken);
            var vaultClientSettings = new VaultClientSettings(vaultAddress, authMethod);

            var vaultClient = new VaultClient(vaultClientSettings);

            return(vaultClient);
        }
        public async System.Threading.Tasks.Task <ActionResult> GetAsync()
        {
            IAuthMethodInfo authMethod          = new TokenAuthMethodInfo("s.FwVyy3qj5MxKm7PlbVsnRgiV");
            var             vaultClientSettings = new VaultClientSettings("http://127.0.0.1:8200/", authMethod);

            IVaultClient vaultClient = new VaultClient(vaultClientSettings);

            Secret <SecretData> kv2Secret = await vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync("RSG_UK_WCNP_RetailInsight/CERT");


            return(null);
        }
Example #9
0
        public AccountController(IHostingEnvironment env, IConfiguration configuration, IOptions <GlobalSettings> globalSettings, UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager)
        {
            _env            = env;
            _configuration  = configuration;
            _userManager    = userManager;
            _signInManager  = signInManager;
            _globalSettings = globalSettings;

            var authMethod          = new TokenAuthMethodInfo(configuration.GetValue <string>("VaultToken"));
            var vaultClientSettings = new VaultClientSettings(configuration.GetConnectionString("Vault"), authMethod);

            _vaultClient = new VaultClient(vaultClientSettings);
        }
Example #10
0
        static void Main(string[] args)
        {
            IAuthMethodInfo authMethod = new TokenAuthMethodInfo("s.C979mWsj0zzHUoZjqgfeobqI");

            // Initialize settings. You can also set proxies, custom delegates etc. here.
            var          vaultClientSettings = new VaultClientSettings("http://127.0.0.1:8200", authMethod);
            IVaultClient vaultClient         = new VaultClient(vaultClientSettings);

            // Use client to read a key-value secret
            Secret <SecretData> kv2Secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync("test", null, "kv").Result;

            Console.WriteLine(kv2Secret.Data.Data["login"]);
        }
Example #11
0
        static async Task <Secret <SecretData> > getSecret()
        {
            // Initialize one of the several auth methods.
            IAuthMethodInfo authMethod = new TokenAuthMethodInfo("s.pgAZ2CkI4CqPT0SJ7H5iQZOJ");

// Initialize settings. You can also set proxies, custom delegates etc. here.
            var vaultClientSettings = new VaultClientSettings("http://127.0.0.1:8200", authMethod);

            IVaultClient vaultClient = new VaultClient(vaultClientSettings);

// Use client to read a key-value secret.
            Secret <SecretData> kv2Secret = await vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync("secret/aws2");

            return(kv2Secret);
        }
Example #12
0
 public void SetPluginConfiguration(Dictionary <string, string> configuration)
 {
     if (configuration != null && configuration.ContainsKey(_authTokenName) &&
         configuration.ContainsKey(_addressName) && configuration.ContainsKey(_mountPointName))
     {
         var authMethod          = new TokenAuthMethodInfo(configuration[_authTokenName]);
         var vaultClientSettings = new VaultClientSettings(configuration[_addressName], authMethod);
         _vaultClient   = new VaultClient(vaultClientSettings);
         _configuration = configuration;
         _logger.Information($"Plugin {Name} has been successfully configured.");
     }
     else
     {
         _logger.Error("Some parameters are missing from the configuration.");
     }
 }
Example #13
0
        private async Task LoadDataAsync(Dictionary <string, string> values)
        {
            var authMethod = new TokenAuthMethodInfo("root");

            var          vaultClientSettings = new VaultClientSettings("http://localhost:8200", authMethod);
            IVaultClient vaultClient         = new VaultClient(vaultClientSettings);

            foreach (var pair in values)
            {
                var data = new Dictionary <string, object>()
                {
                    ["value"] = pair.Value
                };
                await vaultClient.V1.Secrets.KeyValue.V2.WriteSecretAsync(pair.Key, data).ConfigureAwait(false);
            }
        }
Example #14
0
        public ConfigurationService()
        {
            try
            {
                string secretToken = Environment.GetEnvironmentVariable("SECRET_TOKEN");
                string secretIp    = Environment.GetEnvironmentVariable("SECRET_IP");
                string secretPort  = Environment.GetEnvironmentVariable("SECRET_PORT");

                IAuthMethodInfo authMethod          = new TokenAuthMethodInfo(secretToken);
                var             vaultClientSettings = new VaultClientSettings($"http://{secretIp}:{secretPort}", authMethod);
                _VaultClient = new VaultClient(vaultClientSettings);
            }
            catch (Exception e)
            {
                _VaultClientError = e;
            }
        }
Example #15
0
        async Task UpdateContent()
        {
            OtpViewPanel.Children.Clear();

            IAuthMethodInfo authMethod          = new TokenAuthMethodInfo(Properties.Settings.Default.VaultToken);
            var             vaultClientSettings = new VaultClientSettings(Properties.Settings.Default.VaultURL, authMethod);

            IVaultClient vaultClient = new VaultClient(vaultClientSettings);

            Secret <ListInfo> keys = await vaultClient.V1.Secrets.TOTP.ReadAllKeysAsync();

            foreach (var key in  keys.Data.Keys)
            {
                var otpView = new OtpView(key);
                OtpViewPanel.Children.Add(otpView);
            }
        }
Example #16
0
        public void GetAsync()
        {
            // EntityFrameworkConnectionTest();

            IAuthMethodInfo authMethod          = new TokenAuthMethodInfo("s.Dfg02Jl4MxuD7SMjBGccldga");
            var             vaultClientSettings = new VaultClientSettings("http://127.0.0.1:8200/", authMethod);

            IVaultClient vaultClient = new VaultClient(vaultClientSettings);

            // await GetSecretsViaHttp();

            // await this.GetKeyValueAsync(vaultClient);

            // await this.WriteKeyValueAsync(vaultClient);

            // await this.GetCubbyholeAsync(vaultClient);
        }
        public async Task <IActionResult> LoginTotp(LoginTotpViewModel model)
        {
            if (!TempData.ContainsKey(nameof(VaultClaims)))
            {
                return(RedirectToAction("Login", "Account", new { model.ReturnUrl }));
            }

            // Retrieve the vault claims from TempData
            // Data has been set by the Login method
            var vaultClaims = TempData.Peek(nameof(VaultClaims)) as string[];
            var claims      = vaultClaims.Select(x => { var claim = x.Split("::"); return(new Claim(claim[0], claim[1])); });

            // Use the ClientToken from the claimset to make authenticated Vault calls
            var authMethod          = new TokenAuthMethodInfo(claims.First(x => x.Type == VaultClaims.ClientToken).Value);
            var vaultClientSettings = new VaultClientSettings(_vaultSettings.VaultEndpointUri, authMethod);
            var vaultClient         = new VaultClient(vaultClientSettings);


            var  nameClaim       = claims.First(x => x.Type == ClaimTypes.Name).Value;
            bool isValidTotpCode = await ValidateTotpCodeAsync(vaultClient, nameClaim, model.TotpCode);

            if (isValidTotpCode)
            {
                var claimsIdentity = new ClaimsIdentity(
                    claims, CookieAuthenticationDefaults.AuthenticationScheme);

                var authProperties = new AuthenticationProperties();

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    authProperties);

                TempData.Remove(nameof(VaultClaims));
                return(LocalRedirect(model.ReturnUrl ?? "/"));
            }
            else
            {
                ModelState.Remove(nameof(model.TotpCode));
                ModelState.AddModelError(nameof(model.TotpCode), "Invalid code. Try again.");
                return(View(new LoginTotpViewModel()
                {
                    ReturnUrl = model.ReturnUrl
                }));
            }
        }
Example #18
0
        private static void SdkSecretWriterV1()
        {
            IAuthMethodInfo authMethod          = new TokenAuthMethodInfo(vaultToken: "s.4jsklbJUaQuMKmgEESZYLuWS");
            var             vaultClientSettings = new VaultClientSettings("http://127.0.0.1:8200", authMethod)
            {
                ContinueAsyncTasksOnCapturedContext = false
            };

            var vaultClient = new VaultClient(vaultClientSettings);

            vaultClient.V1.Secrets.KeyValue.V1
            .WriteSecretAsync(mountPoint: "edge", path: "/password/password/userlogging/secretkey", values: new Dictionary <string, object>
            {
                {
                    "/password/password/userlogging/secretkey", "there"
                }
            }).Wait();
        }
Example #19
0
        private async Task LoadDataAsync(Dictionary <string, IEnumerable <KeyValuePair <string, object> > > values)
        {
            var authMethod = new TokenAuthMethodInfo("root");

            var          vaultClientSettings = new VaultClientSettings("http://localhost:8200", authMethod);
            IVaultClient vaultClient         = new VaultClient(vaultClientSettings);

            foreach (var sectionPair in values)
            {
                var data = new Dictionary <string, object>();
                foreach (var pair in sectionPair.Value)
                {
                    data.Add(pair.Key, pair.Value);
                }

                await vaultClient.V1.Secrets.KeyValue.V2.WriteSecretAsync(sectionPair.Key, data)
                .ConfigureAwait(false);
            }
        }
Example #20
0
    public VaultClient InitVaultClient(ConfigFile configFile)
    {
        var authMethod          = new TokenAuthMethodInfo(configFile.Vault.Token);
        var vaultClientSettings = new VaultClientSettings(configFile.Vault.Url, authMethod)
        {
            MyHttpClientProviderFunc = (messageHandler) =>
            {
                var handler = new HttpClientHandler();

                if (configFile.Vault.TlsSkipVerify)
                {
                    handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                }

                return(new HttpClient(handler));
            }
        };

        return(new VaultClient(vaultClientSettings));
    }
Example #21
0
        private static void SdkSecretReaderV1()
        {
            IAuthMethodInfo authMethod          = new TokenAuthMethodInfo(vaultToken: "s.4jsklbJUaQuMKmgEESZYLuWS");
            var             vaultClientSettings = new VaultClientSettings("http://127.0.0.1:8200", authMethod)
            {
                ContinueAsyncTasksOnCapturedContext = false
            };

            var vaultClient = new VaultClient(vaultClientSettings);

            Dictionary <string, object> secrets = vaultClient.V1.Secrets.KeyValue.V1
                                                  .ReadSecretAsync(mountPoint: "edge", path: "/password/password/userlogging/secretkey").Result.Data;

            foreach (var keyValuePair in secrets)
            {
                Console.WriteLine($"[{keyValuePair.Key}]=[{keyValuePair.Value}]");
            }

            Console.WriteLine(secrets);
        }
Example #22
0
        private static void SdkSecretReaderV2()
        {
            IAuthMethodInfo authMethod          = new TokenAuthMethodInfo(vaultToken: "s.NfKF7cpNmpvy3o76BaiY5d7O");
            var             vaultClientSettings = new VaultClientSettings("http://127.0.0.1:8200", authMethod)
            {
                ContinueAsyncTasksOnCapturedContext = false
            };

            var vaultClient = new VaultClient(vaultClientSettings);

            Dictionary <string, object> secrets = vaultClient.V1.Secrets.KeyValue.V2
                                                  .ReadSecretAsync(mountPoint: "secret", path: "hello").Result.Data.Data;

            foreach (var keyValuePair in secrets)
            {
                Console.WriteLine($"[{keyValuePair.Key}]=[{keyValuePair.Value}]");
            }

            Console.WriteLine(secrets);
        }
Example #23
0
        async Task GetTokenData()
        {
            IAuthMethodInfo authMethod          = new TokenAuthMethodInfo(Properties.Settings.Default.VaultToken);
            var             vaultClientSettings = new VaultClientSettings(Properties.Settings.Default.VaultURL, authMethod);

            IVaultClient     vaultClient = new VaultClient(vaultClientSettings);
            Secret <TOTPKey> key         = await vaultClient.V1.Secrets.TOTP.ReadKeyAsync(this.KeyName);

            Secret <TOTPCode> totpSecret = await vaultClient.V1.Secrets.TOTP.GetCodeAsync(this.KeyName);


            ProviderName.Content = key.Data.Issuer;
            AccountName.Content  = key.Data.AccountName;
            SecondsLeft.Content  = "";
            OTPValue.Text        = totpSecret.Data.Code;
            if (!timer.IsEnabled)
            {
                timer.Start();
            }
        }
 public void SetVaultCredential(string credential)
 {
     if (_configuration != null && credential != null)
     {
         try
         {
             var authMethod          = new TokenAuthMethodInfo(credential);
             var vaultClientSettings = new VaultClientSettings(_configuration[AddressName], authMethod);
             _vaultClient = new VaultClient(vaultClientSettings);
             _logger.Information($"Plugin {Name} successfully authenticated.");
         }
         catch (Exception ex)
         {
             _logger.Information($"Invalid configuration for {Name}. Please use the api to set a valid configuration. {ex.Message}");
         }
     }
     else
     {
         _logger.Error("The plugin configuration or credential is missing.");
     }
 }
Example #25
0
        private IVaultClient CreateVaultClient()
        {
            IAuthMethodInfo authMethod;

            switch (_context.AuthenticationType)
            {
            case AuthenticationType.AppRole:
                authMethod = new AppRoleAuthMethodInfo(_context.RoleId, _context.SecretId);
                break;

            case AuthenticationType.UsernamePassword:
                authMethod = new UserPassAuthMethodInfo(_context.Username, _context.Password);
                break;

            case AuthenticationType.Ldap:
                authMethod = new LDAPAuthMethodInfo(_context.Username, _context.Password);
                break;

            case AuthenticationType.Token:
                authMethod = new TokenAuthMethodInfo(_context.Token);
                break;

            default:
                throw new NotSupportedException($"Authentication type '{_context.AuthenticationType}' is not supported.");
            }

            var vaultClientSettings = new VaultClientSettings(_context.VaultUri.ToString(), authMethod)
            {
                VaultServiceTimeout = TimeSpan.FromSeconds(30)
            };

            if (!string.IsNullOrWhiteSpace(_context.Namespace))
            {
                vaultClientSettings.Namespace = _context.Namespace;
            }

            return(new VaultClient(vaultClientSettings));
        }
Example #26
0
        static void Main(string[] args)
        {
            var cfg = new ConfigurationBuilder()
                      .AddCommandLine(args)
                      .SetBasePath(Directory.GetCurrentDirectory())
                      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                      .AddEnvironmentVariables().Build();

            var vaultUrl = cfg.GetSection("vault-url").Value;

            if (string.IsNullOrEmpty(vaultUrl))
            {
                throw new ArgumentNullException("vault-url not provided in the appsettings!");
            }

            var vaultToken = cfg.GetSection("vault-token").Value;

            if (string.IsNullOrEmpty(vaultToken))
            {
                throw new ArgumentNullException("vault-token not provided in the appsettings!");
            }

            // Initialize one of the several auth methods.
            var authMethod = new TokenAuthMethodInfo(vaultToken);

            // Initialize settings. You can also set proxies, custom delegates etc. here.
            var vaultClientSettings = new VaultClientSettings(vaultUrl, authMethod);

            IVaultClient vaultClient = new VaultClient(vaultClientSettings);

            Secret <SecretData> kv2Secret = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync("sample-secret").Result;
            var login    = kv2Secret.Data.Data["login"];
            var password = kv2Secret.Data.Data["password"];

            Console.WriteLine($"data from vault.\nLogin:{login} \nPassword{password}");
        }