Hashicorp Vault Kerberos Auth with VaultSharp - hashicorp-vault

I'm having great difficulty getting Kerberos Auth working with Vault using VaultSharp.
I don't have control over Vault server but I've been informed that it is configured and ready to use.
I'm using .NET running in IIS and I want to make use of the service account that IIS is running under so that I don't need to store additional secrets or user/passwords.
Here is the code I'm using and the error:
public string GetSecretWithKerberosAuthUsingVaultSharp(string keyName, string vaultBaseAddress, string vaultResourcePath, string mountPoint)
{
IAuthMethodInfo authMethod = new KerberosAuthMethodInfo(); // uses network credential by default.
var vaultClientSettings = new VaultClientSettings(vaultBaseAddress, authMethod);
IVaultClient vaultClient = new VaultClient(vaultClientSettings);
var result = vaultClient.V1.Secrets.KeyValue.V2.ReadSecretAsync(vaultResourcePath, mountPoint: mountPoint).Result;
//Above line gives this error message:
//{"request_id":"a85dfbb3-b283-3513-7cd3-01ad757eed1b","lease_id":"","renewable":false,"lease_duration":0,"data":null,"wrap_info":null,"warnings":["Unauthorised.\n\n"],"auth":null}
var resultData = result.Data;
string secret = resultData.Data[keyName].ToString();
return secret;
}
I have managed to get it working using token auth as well as through the CLI but that is not quite what I want.
authMethod.Credentials.UserName/Domain both are empty strings.
Don't know if they are supposed to be populated in this case or not but documentation states that it "uses network credentials by default"
Any help appreciated.

Is your web application running in integrated Windows Auth mode, with anonymous auth disabled?
If no, please make it work in that mode for your web app to have the Windows Integrated Auth context so that web calls from VaultSharp to Vault API can have the security context.
If yes, then can you please try a couple of things?
var kerberosAuthInfo = new KerberosAuthMethodInfo(CredentialCache.DefaultCredentials);
If the above doesn't work, then can you try explicit credentials.
var kerberosAuthInfo = new KerberosAuthMethodInfo(new NetworkCredential(userName, password, domain));
Ideally, the web app context should carry the integrated windows context so that you don't need to provide explicit credentials, but it might be worth trying to ensure that it works first and then we can backtrack as to why the context is not being passed.

Related

How to Get Azure Access Token using DefaultAzureCredential without storing secrets

I am trying to setup my environment to be able to to access Azure resources from outside Azure.
While looking at different options I cam across mainly below options of many others
Option 1:
Creating a Service Principal with the Azure CLI and use client secrets for Token retrieval and accessing Resources
Get Client secrets Run Time
Option 2:
Using DefaultAzureCredential (Azure.Identity) for Token retrieval and accessing Resources
DefaultAzureCredential
I am currently trying out DefaultAzureCredential option to be able to access Azure resources such as ADF, Blob storage etc.
I am able to do this using the Visual Studio credentials (VS 2019). However challenge remains to perform same action via a Pipeline running outside Azure. I do not want to save any secrets in the code. Does this means that I cannot use environment variables for the Purpose?
If indeed this is still possible then need help with the code.
Environment:
. Net Framework 4.8/Core 3.1
Desired Flow:
Use Visual Studio Credentials for local Development and Test.
Use Environment Variables OR other tasks supported by DefaultAzureCredential via DevOps Pipeline task.
Code:
var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { ResourceId + "/.default" }) { }
);
I was able to solve this using DefaultAzureCredential. We followed the below approach to solve this
Added code to read the secrets from appsetting.json
Add secrets to environment variables
Use DefaultAzureCredential* to reach to correct override.
Add replace token task in Build/Release pipelines to replace client secret variables with secrets from pipeline parameters.
Code when executed from Visual studio does not find actual value to secret variables from appsetting.json and then uses VisualStudio Credentials.
Read values
string AZURE_CLIENT_SECRET = ConfigurationHelper.GetByName("AZURE_CLIENT_SECRET");
string AZURE_CLIENT_ID = ConfigurationHelper.GetByName("AZURE_CLIENT_ID");
string AZURE_TENANT_ID = ConfigurationHelper.GetByName("AZURE_TENANT_ID");
// Check whether the environment variable exists.
if (AZURE_CLIENT_SECRET != "{{AZURE_CLIENT_SECRET}}"
&& AZURE_CLIENT_ID != "{{AZURE_CLIENT_ID}}" &&
AZURE_TENANT_ID != "{{AZURE_TENANT_ID}}")
{
Environment.SetEnvironmentVariable("AZURE_CLIENT_SECRET", AZURE_CLIENT_SECRET);
Environment.SetEnvironmentVariable("AZURE_CLIENT_ID", AZURE_CLIENT_ID);
Environment.SetEnvironmentVariable("AZURE_TENANT_ID", AZURE_TENANT_ID);
Console.WriteLine("Setting Environment Variables");
}
Call DefaultAzureCredential
var objDefaultAzureCredentialOptions = new DefaultAzureCredentialOptions
{
ExcludeEnvironmentCredential = false,
ExcludeManagedIdentityCredential = true,
ExcludeSharedTokenCacheCredential = true,
ExcludeVisualStudioCredential = false,
ExcludeVisualStudioCodeCredential = false,
ExcludeAzureCliCredential = true,
ExcludeInteractiveBrowserCredential = true
};
var tokenCredential = new DefaultAzureCredential(objDefaultAzureCredentialOptions);
ValueTask<AccessToken> accessToken = tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new[] { "https://management.azure.com/.default" }));
If environment variables are present in the active session then the code uses environment variables

Error : No such host is Known in Asp.net Core Application while configuring Azure key vault

I am facing an issue while configuring Azure Key vault in Asp.net core Web API project .
Below is the code snippet as well as error for reference and I tried to find the root cause but no luck.
Error while Run() method execution.
Exception details
Please help me out in solving this issue .Thanks in advance.
It can be issue from .net end mostly ,in .NET Core 3.0.100 or 3.1. This seems to occur when running under the debugger in Visual Studio mostly and when long parallel calls are made and retrypolicy may help stop this from giving exception for sometime and tries again.
So Please try to Upgrade/Update the .NET Project SDK if any updates
available in Visual Studio.
Try running with command line
Also in the message of error you can see retry faild after 4 tries..
You can check ReloadInterval Property which is used in 3.0 and 3.1
builder.AddAzureKeyVault(
new Uri(Configuration["KeyVault:URI"]),
new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
ExcludeSharedTokenCacheCredential = true,
VisualStudioTenantId = Configuration["AzureAd:TenantId"]
}),
new AzureKeyVaultConfigurationOptions()
{
ReloadInterval = TimeSpan.FromMinutes(15)
}
);
You could try catching this exception and implementing a retry mechanism for your code if this exception is thrown so that it could try with retry time and delay required for next attempt.
Azure Key Vault throttling guidance | Microsoft Docs
SecretClientOptions options = new SecretClientOptions()
{
Retry =
{
Delay= TimeSpan.FromSeconds(2),
MaxDelay = TimeSpan.FromSeconds(16),
MaxRetries = 5,
Mode = RetryMode.Exponential
}
};
var client = new SecretClient(new Uri("https://keyVaultName.vault.azure.net"), new DefaultAzureCredential(),options);
//Retrieve Secret
secret = client.GetSecret(secretName);
Also see GitHub discussion
If still issue remains, it may be calling several times due to
network issue also.So please check the network , firewall and if there is any DNS issue for that endpoint.
Check URI if endpoint is incorrect or Managed Identity does not have
Data owner or Reader role.Please make sure that you have proper
permissions to access azure keyvault and give proper access
policies atleast get , list and create if needed .
Make sure to have one of the roles(RBAC) provided here to access the
keyvault .
References:
asp.net core - How to configure Azure KeyVault refresh interval
with the Azure.Security.KeyVault libraries - Stack Overflow
azure sdk .net issues(github)

How do I get the full uri including username and password with the mongodbatlas provider in terraform

When I try to output the mongodb uri with Terraform and the mongodb atlas provider, I can't get the full uri with username and password. For example, when I do something like:
terraform {
required_version = "~> 0.14.7"
required_providers {
mongodbatlas = {
source = "mongodb/mongodbatlas"
version = "0.8.2"
}
}
}
provider "mongodbatlas" {
public_key = var.mongodbatlas_public_key
private_key = var.mongodbatlas_private_key
}
data "mongodbatlas_cluster" "db" {
project_id = var.mongodbatlas_project_id
name = format("some-db-name-%s", var.env)
}
output "db_url" {
value = data.mongodbatlas_cluster.db.connection_strings[0].address_srv
}
I always get a uri of the form: mongodb+srv://some-db-name-staging.xjcol.mongodb.net
Adding that as an environment variable to my web app in order to connect to db does not work as it needs to authenticate with a username and password. Manually adding the username and password to that string as in mongodb+srv://[username]:[password]#some-db-name-staging.xjcol.mongodb.net works and the app can connect to the db fine.
While I get what you're trying to achieve, I suspect you're mixing things here. Let me explain:
MongoDB allows you to create database users that are able to authenticate using password. Those can be created using mongodbatlas_database_user resource.
You can create your cluster (or source cluster information) using both the resource or data source the way you're trying to achieve it.
However, cluster creation is independent of database and database user creation, meaning that what you're getting from Terraform is just a generic connection string from Mongo where not even Mongo knows which user/database you want to connect to.
I suggest you to compose your own connection string and pass it along to your application using a post-provisioning script, either using your Terraform outputs of cluster and database user, or simply composing it by yourself if you already know the info upfront.
In case you're using AWS, MongoDB Atlas supports connection strings using IAM Users and IAM Roles. This is a much better, safer approach than dealing with passwords and all the extra burden managing passwords implies. If this sounds like something you'd like to explore, do let me know.
My solution was to use the string replace function with mongodbatlas_database_user resource:
replace(mongodbatlas_advanced_cluster.mongodb_cluster.connection_strings[0].standard_srv, "mongodb+srv://", "mongodb+srv://${mongodbatlas_database_user.userspace_db_user.username}:${coalesce(nonsensitive(mongodbatlas_database_user.userspace_db_user.password), "null")}#")

AWS MobileAnalyticsManager access to folder 'AWS Mobile Services\M4SP' is denied

I am trying to add the AWSSDK DLL into my C# code to collect my event data and pass the data to the AWS bucket. My C# code is created with VS Share point template. The project contains WSP files. The following code indicates how I use the AWSSDK :
using Amazon;
using Amazon.CognitoIdentity;
using Amazon.MobileAnalytics.MobileAnalyticsManager;
CognitoAWSCredentials credentials = new CognitoAWSCredentials(
"us-east-1:xxxxxx",//PoolID
RegionEndpoint.USEast1
);
Amazon.AWSConfigs.ApplicationName = "M4SP";
AWSConfigs.LoggingConfig.LogMetrics = true;
AWSConfigs.LoggingConfig.LogResponses = ResponseLoggingOption.Always;
AWSConfigs.LoggingConfig.LogMetricsFormat = LogMetricsFormatOption.JSON;
MobileAnalyticsManager manager = MobileAnalyticsManager.GetOrCreateInstance(
"xxxxxxxxxxxxxxxxxxx",//AppID
credentials,
RegionEndpoint.USEast1 // Region
);
CustomEvent customEvent = new CustomEvent("TestRecordEvent");
customEvent.AddAttribute("label", "M4SP");
customEvent.AddAttribute("action", "invoke");
customEvent.AddAttribute("details", "run the workflow test");
manager.RecordEvent(customEvent);
I found the code inside AWSSDK DLL was trying to log the data to local folder before passing it to AWS database. The location of the folder is C:\Users\[userid]\AppData\Roaming\AWS Mobile Services.
There is no problem in a standalone project since it always uses current user’s identity to run the application so it has access to the folder. But, because of the authentication mechanism of SharePoint solutions, it uses Application Pool Identity to access the folder and it gets access denied issue and the whole process fails.
Here is the error:
"Access to the path 'AWS Mobile Services\M4SP' is denied."
I modified the access right of Share point Application Pool Identity (in my case, it is “network service” account) but it still can’t access the folder .
Does anyone have a solution for this issue? Thanks very much for the help!!

Can't connect to SugarCRM Soap API

I've just started on a project where I need to insert contacts into a SugarCRM system using the SOAP interface.
So far I have created a reference to the service http://sugar-dev.walkinwifi.net/soap.php?wsdl=sugarsoap
Then writen some code like this
public SugarHelper()
{
//Create a new instance of the client proxy
this.sugarClient = new sugarsoapPortTypeClient();
//Set the default value
this.sessionId = String.Empty;
}
public bool Authenticate(string Username, string Password)
{
//Create an authentication object
user_auth user = new user_auth();
//Set the credentials
user.user_name = Username;
user.password = this.computeMD5String(Password);
//Try to authenticate
set_entry_result authentication_result = this.sugarClient.login(user, "");
this gives you the jest.
The last line gives me an exception when login is called.
The exception I get has an inner exception complaining it can't connect to https://sugar-dev.walkinwifi.net/soap.php
{"An error occurred while making the HTTP request to https://sugar-dev.walkinwifi.net/soap.php. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server."}
Where does the https part come from? I have used no other reference other than http yet the error clearly states https.
Can I connect to SugarCRM soap via http or must I use https?
In all the examples I can find on the net it's http but most of them are php with very c# ones.
I'm looking in the wrong place. Inside the Soap configuration of Sugar you specify the url that will be used for soap calls. This is set to https://sugar-dev.walkinwifi.com.
Changed it to http and all is well.
In any case, the SOAP services must also work over HTTPS. Personally I have not had any problems, even with a C # client. Verify that the server certificate and the certificate chain are valid.
Bye,
Antonio.