Accessing AKS cluster configuration (specifically OIDC issuer URI) from within the cluster - azure

I am writing a job in golang that sets up an Azure user assigned managed identity using the Azure Go SDK, specifically github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/msi/armmsi, a Kubernetes service account using the go-client for Kubernetes k8s.io/client-go/kubernetes and then using the Azure SDK to set up a Federated Identity Credential on the new user assigned managed identity.
In order to set up a federated credential on azure I need to get the oidc issuer uri.
I know how to get it using the Azure CLI, and I can simply paste a string. But I expect this code to be running on any cluster and i would expect the issuer to change. Id rather just get the issuer from a config file on the cluster itself or through the azure sdk. I am not sure how to do that. any help...
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
....some code here to set up azure clients and Kubernetes client...
//creating a new managed identity using azure client
msi, err := azureMsiClient.CreateOrUpdate(ctx, "new-umid-resource-group", "new-umid", armmsi.Identity{Location: strPtr(`East US`)}, &armmsi.UserAssignedIdentitiesClientCreateOrUpdateOptions{})
if err != nil {
fmt.Printf("could not create a managed identity", err.Error())
return err
}
....
//creating the new service account
annotations := make(map[string]string)
annotations["azure.workload.identity/client-id"] = *msi.Properties.ClientID
annotations["azure.workload.identity/tenant-id"] = "<myazuretenantid>"
labels := make(map[string]string)
labels["azure.workload.identity/use"] = "true"
mainSA := &v1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: "myserviceaccount",
Namespace: "my-namespace",
Annotations: annotations,
Labels: labels,
},
_, err = kubeClientSet.CoreV1().ServiceAccounts("my-namespace").Create(ctx, mainSA, metav1.CreateOptions{})
if err != nil {
fmt.Println("could not create k8 service account")
return err
}
....
//creating the federated credential
aud := make([]*string, 1)
aud[0] = strPtr("api://AzureADTokenExchange")
beParms := armmsi.FederatedIdentityCredential{
Properties: &armmsi.FederatedIdentityCredentialProperties{
Audiences: aud,
Issuer: strPtr(<my cluster's OidcIssuerUri>),
Subject: strPtr(`system:serviceaccount:my-namespace:myserviceaccount`),
},
}
_, err := azureFedIdClient.CreateOrUpdate(ctx, "new-umid-resource-group","new-umid", "new-umid-fed-id", beParms, nil)
if err != nil {
fmt.Println("could not create a new federation between be auth service account and federated identity")
return err
}

Related

Creating a container under a private storage account in Azure

I have a storage account created for an AKS cluster, which is configured with a private endpoint. Public access is denied on it.
There is a client service installed in the same network as the cluster, which is trying to create a container within this storage account.
Here is the code snippet:
c, err: = azblob.NewSharedKeyCredential(accountName, accountKey)
if err != nil {
return azblob.ContainerURL {}, err
}
p: = azblob.NewPipeline(c, azblob.PipelineOptions {
Telemetry: azblob.TelemetryOptions {
Value: "test-me"
},
})
u, err: = url.Parse(fmt.Sprintf(blobFormatString, accountName))
if err != nil {
return azblob.ContainerURL {}, err
}
service: = azblob.NewServiceURL( * u, p)
container: = service.NewContainerURL(containerName)
c, err: = GetContainerURL(a.Log, ctx, a.SubscriptionID, a.ClientID, a.ClientSecret, a.TenantID, a.StorageAccount, accountKey, a.ResourceGroup, a.Bucket)
if err != nil {
return err
}
_, err = c.GetProperties(ctx, azblob.LeaseAccessConditions {})
if err != nil {
if strings.Contains(err.Error(), "ContainerNotFound") {
_, err = c.Create(
ctx,
azblob.Metadata {},
azblob.PublicAccessContainer)
if err != nil {
return err
}
}
}
This code when executed throws an error like:
Details: \n Code: PublicAccessNotPermitted\n PUT https://storageaccountname.blob.core.windows.net/containername?restype=container&timeout=61\n Authorization: REDACTED
RESPONSE Status: 409 Public access is not permitted on this storage account
Should not the container creation be completed, since the client is already on the cluster. What is it that i am doing wrong?
Many thanks!!
Details: \n Code: PublicAccessNotPermitted\n PUT https://storageaccountname.blob.core.windows.net/containername?restype=container&timeout=61\n Authorization: REDACTED RESPONSE Status: 409 Public access is not permitted on this storage account
• The error code that you are interacting with clearly states that ‘public access is not permitted on your storage account’, i.e., either the private endpoint connection that you have configured on your storage account is not configured properly and the account is not secured by configuring the storage firewall to block all connections on the public endpoint for the storage service.
• Thus, I would suggest you increase the security for the virtual network (VNET), by enabling you to block the exfiltration of data from the VNET. Also, securely connect to storage accounts from on-premises networks that connect to the VNET using VPN or ExpressRoutes with private-peering.
• Also, please ensure that the IP address that is assigned to the private endpoint is an IP address from the address range of the VNET and it is excluded from any restrictions in the network security group or AKS ingress controller or the Azure Firewall.
• Finally, ensure that the private endpoints provisioned for the storage account are not general-purpose v1 storage accounts as private endpoints for these storage accounts are not permitted. Also, configure the storage firewall for the storage account as described in the documentation link below: -
https://learn.microsoft.com/en-us/azure/storage/common/storage-network-security?tabs=azure-portal#change-the-default-network-access-rule
To know more about the details regarding the configuration of private endpoints for storage accounts, kindly refer to the documentation link below: -
https://learn.microsoft.com/en-us/azure/storage/common/storage-private-endpoints

How to specify x509 certificate for Azure SDK in Golang

I am trying to connect to use the Azure SDK for Golang to download files from a container online to my device and am using the connection string provided from azure to connect. For context this is running on a version of embedded Linux
I have two questions, first how do I pass a specific certificate to the azure SDK to use to connect, as currently when I connect, I get this issue
Get "https://transaction.blob.core.windows.net/transactions?comp=list&restype=container": x509: certificate signed by unknown authority
or failing that how do I generate the correct certificate to put it in /etc/ssl? Which I think is where go is looking for certificates as far as I understand.
Also second question what function from the azure sdk for go should I be using to download from a blob online if my folder structure looks like /transaction/my-libs/images/1.0.0/libimage.bin where transaction is my blob container.
func testConnection(){
Println("TESTING CONNECTION")
connStr := "..." // actual connection string hidden
serviceClient, err := azblob.NewServiceClientFromConnectionString(connStr, nil)
// crashes here <------------
//ctx := context.Background()
//container := serviceClient.NewContainerClient("transactions")
//
//_, err = container.Create(ctx, nil)
//
//blockBlob := container.NewBlockBlobClient("erebor-libraries")
//_, err = blockBlob.Download(ctx, nil)
//Open a buffer, reader, and then download!
downloadedData := &bytes.Buffer{}
reader := get.Body(RetryReaderOptions{}) // RetryReaderOptions has a lot of in-depth tuning abilities, but for the sake of simplicity, we'll omit those here.
_, err = downloadedData.ReadFrom(reader)
err = reader.Close()
if data != downloadedData.String() {
err := errors.New("downloaded data doesn't match uploaded data")
if err != nil {
return
}
}
pager := container.ListBlobsFlat(nil)
for pager.NextPage(ctx) {
resp := pager.PageResponse()
for _, v := range resp.ContainerListBlobFlatSegmentResult.Segment.BlobItems {
fmt.Println(*v.Name)
}
}
• You can use the following Azure SDK for Go command for passing a specific certificate to the Azure SDK to connect to other Azure resources by creating a service principal for it: -
‘ type ClientCertificateConfig struct {
ClientID string
CertificatePath string
CertificatePassword string
TenantID string
AuxTenants []string
AADEndpoint string
Resource string
} ‘
For more information on the creation of the client certificate and its usage, please refer to the documentation link below for more details: -
https://pkg.go.dev/github.com/Azure/go-autorest/autorest/azure/auth#ClientCertificateConfig
Also, even if your folder structure is ‘/transaction/my-libs/images/1.0.0/libimage.bin’, but the blob URL is unique with folder hierarchy mentioned in the blob URL, thus when connecting to the Azure storage account to download the blob, mention the URL in single inverted comma notation for the blob path to be specific.
Please refer to the sample code below for downloading the blobs through Azure SDK for Go: -
https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/storage/azblob#example-package
https://pkg.go.dev/github.com/Azure/azure-storage-blob-go/azblob#pkg-examples

Go client example to fetch storage account keys

How can we get the Azure storage account key from storage account name and other parameters ?
I tried to build the storage account client but it requires, storage account name and key to build the client. I want to fetch programatically storage account key using storage account name and other parameters. Equivalent Go Sample code to below Azure CLI command.
az storage account keys list --resource-group --account-name
Can you please give some pointer, how can i fetch using Go sample code ?
Thank you
To get keys for a storage account, you will need to make use of Azure SDK for Go especially armstorage`.
Here's the code sample for listing account keys:
func ExampleStorageAccountsClient_ListKeys() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
client := armstorage.NewStorageAccountsClient(arm.NewDefaultConnection(cred, nil), "<subscription ID>")
resp, err := client.ListKeys(context.Background(), "<resource group name>", "<storage account name>", nil)
if err != nil {
log.Fatalf("failed to delete account: %v", err)
}
for _, k := range resp.StorageAccountListKeysResult.Keys {
log.Printf("account key: %v", *k.KeyName)
}
}
This sample and more code examples are available here: https://github.com/Azure/azure-sdk-for-go/blob/main/sdk/storage/armstorage/example_storageaccounts_test.go.

Authentication successful but unable to retrieve and list Azure AD Users using Azure Golang SDK

I am trying to use Azure Golang SDK to pull the list of Azure AD users.
Few things to Note:
1. Authentication is successful. "Authorization successful." is displayed when I use below code to fetch bearer token for Azure SPN.
This is pretty much vanilla code picked from Azure-Go-SDK repo.
//GetGraphAuthorizer gets an OAuthTokenAuthorizer for graphrbac API.
func GetGraphAuthorizer(fs auth.FileSettings) (autorest.Authorizer, error) {
if graphAuthorizer != nil {
return graphAuthorizer, nil
}
var a autorest.Authorizer
var err error
a, err = getAuthorizerForResource(grantType(), Environment().GraphEndpoint, fs)
if err == nil {
// cache
graphAuthorizer = a
fmt.Println("Authorization successful.")
} else {
graphAuthorizer = nil
fmt.Println ("Authorization failed.")
}
return graphAuthorizer, err
}
Defined a wrapper on around GetGraphAuthorizer function to instantiate userClient object:
func getADUserClient(fs auth.FileSettings) graphrbac.UsersClient {
userClient := graphrbac.NewUsersClient(azure.GetTenantId(fs))
a, _ := azure.GetGraphAuthorizer(fs)
userClient.Authorizer = a
userClient.AddToUserAgent(azure.UserAgent())
return userClient
}
Then I use the token to list users in Azure AD in below function:
adUserClient := getADUserClient(fs)
// if auth failed, then it should've displayed the failure message here but prints "Authorization successful instead"
for list, err := adUserClient.ListComplete(context.Background(), ""); list.NotDone(); err = list.Next() {
if err != nil {
fmt.Print("got error while traversing User list: ", err)
}
i := list.Value()
fmt.Println(*i.DisplayName)
fmt.Println(*i.GivenName)
}
No output what so ever!!
FYI:- I have users in Azure tenant.
I have granted SPN access to Graph API.
Any help is appreciated.
Not 100% sure but for some reason I had to grant Azure SPN "Delegated" permission to:
Directory.ReadWrite.All
Groups.ReadWrite.All
Surprisingly, Once the program listed users, I removed above "Delegated" permissions off SPN and just left the Application permissions and it continues to work!

Authorization for azure app resource management without client ID and client secret

I'm trying to create an application where the user can manage their Azure resources (sql databases, storage). How can I authorize the user without needing their client ID and client secret.
I've looked at their documentation: https://godoc.org/github.com/Azure/go-autorest/autorest/azure/auth, however all of them requires environment variables and/or clientID/clientSecret. Is there a way where a user can provide username/password and I can get back an authorizer
type Client struct {
ServersClient postgresql.ServersClient
}
func NewCloudClient() *Client {
return &Client{}
}
func (c *Client) Init(config map[string]string) error {
var (
subscriptionID = config["subscriptionID"]
// tenantID = config["tenantID"]
// clientID = config["clientID"]
// clientSecret = config["clientSecret"]
// resourceGroup = config["resourceGroup"]
)
// oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, tenantID)
// if err != nil {
// return errors.Wrap(err, "error getting OAuthConfig")
// }
// spt, err := adal.NewServicePrincipalToken(*oauthConfig, clientID, clientSecret, resourceGroup)
serversClient := postgresql.NewServersClient(subscriptionID)
//serversClient.BaseClient.Authorizer = autorest.NewBearerAuthorizer(spt)
c.ServersClient = serversClient
return nil
}
In all cases of authorization flow you will need at least client id. In some you will need more like client secret.
You can read about OAuth authorization here https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-app-types
but in general what you are aiming for is either of two cases
Authorize as user without internaction using username and password (this would be client resource owner flow
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc
Authorize as user with his interaction
if this is code that can't get postback URL then use device code flow https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code
or for anything in the browser use standard implicit grant flow https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow
You will quickly notice that in all cases you NEED to have client ID. This is because how Azure Authentication works.

Resources