WireGuard on Azure · Appendix to part 2
Wiring Terraform to Azure
Creating a dedicated identity for Terraform on Azure: key pair and certificate, Service Principal, and RBAC permissions narrowed by a condition to contain the blast radius.
- Azure
- Terraform
- Service Principal
- RBAC
- ABAC
As you can imagine, when we talk about cloud deployment, we also talk about identities, and how their authentication and authorizations are handled. The wonderful world where Terraform would connect to our cloud instance with zero configuration is not here yet :)
Following the documentation of Terraform’s azurerm provider, several options are available:
- “Authenticating to Azure using Managed Service Identity”
- “Authenticating to Azure using the Azure CLI”
- “Authenticating to Azure using a Service Principal and a Client Certificate”
- “Authenticating to Azure using a Service Principal and a Client Secret”
- “Authenticating to Azure using OpenID Connect”
The most obvious one for the case documented here (a personal deployment from a personal machine) is “Authenticating to Azure using the Azure CLI”. So naturally, I went with “Authenticating to Azure using a Service Principal and a Client Certificate” 🤡
Why? Because in spirit, although the technical implementation differs, it is close to what you find with Kubernetes. Since I work with Azure and K8s, I might as well keep similar practices. Our “sp-terraform” identity will therefore have its certificate, and that is what it will use to authenticate with Azure. It will then need the right permissions: the RBAC roles.
Speaking of which, let’s talk about these RBAC roles. A design choice lies ahead:
- Full permissions on the subscription, so at least no headaches? (At the risk of some nasty surprises if the cert leaks)
- Rights on a dedicated resource group? But very little room to maneuver for Terraform and for what the project can do
Or else… there is the dark and painful path… the path of RBAC CONDITIONS 😧 (My AZ-104 trauma; if you are curious, have fun (or maybe I just never understood it because I am plain dumb, which is a highly plausible theory))
Once everything is in place, it will look like this:
Authn
Create a self-signed certificate:
openssl req -x509 -newkey rsa:4096 -sha256 -days 365 -noenc `
-keyout sp-terraform.key `
-out sp-terraform.crt `
-subj "/CN=sp-terraform"The certificate is needed base64-encoded, on a single line, without BEGIN/END… So you have to play a little with the .NET classes to extract it cleanly:
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($(Resolve-Path ~\Desktop\sp-terraform.crt).Path)
$certValue = [System.Convert]::ToBase64String($cert.GetRawCertData())Then we create the Service Principal on Azure, passing the certificate extracted above:
$sp = New-AzADServicePrincipal -DisplayName "sp-terraform" `
-CertValue $certValue `
-StartDate $cert.NotBefore `
-EndDate $cert.NotAfterTerraform needs a certificate in PFX format to authenticate; generate it with a passphrase:
$pw = Read-Host "Passphrase" -AsSecureString
$env:ARM_CLIENT_CERTIFICATE_PASSWORD = [System.Net.NetworkCredential]::new('', $pw).Password
openssl pkcs12 -export -out sp-terraform.pfx `
-inkey sp-terraform.key `
-in sp-terraform.crt `
-passout env:ARM_CLIENT_CERTIFICATE_PASSWORDA small adventure in itself, but at least we now have a dedicated identity for Terraform, easy to carry from one environment to another, and traceable.
We can then fill in the variables Terraform needs to authenticate to Azure. Several options: declare them as variables in an HCL file read by Terraform, set them directly in the “provider” block, or declare them as environment variables. I go with the last option:
$env:ARM_CLIENT_ID = (Get-AzADServicePrincipal -DisplayName "sp-terraform").AppId
$env:ARM_TENANT_ID = (Get-AzContext).Tenant.Id
$env:ARM_SUBSCRIPTION_ID = (Get-AzSubscription -SubscriptionName "Root subscription").Id
$env:ARM_CLIENT_CERTIFICATE_PATH = (Resolve-Path -Path "~\Desktop\sp-terraform.pfx").Path
$env:ARM_CLIENT_CERTIFICATE_PASSWORD = "don't push your luck"Authz
Assigning the Contributor role: manage resources, without being able to touch RBAC:
$subId = (Get-AzSubscription -SubscriptionName "Root subscription").Id
$scope = "/subscriptions/$subId"
New-AzRoleAssignment -ObjectId $sp.Id `
-RoleDefinitionName "Contributor" `
-Scope $scopeCondition to narrow the RBAC Administrator role:
# Get the ID of the Key Vault Secrets User role, used by the condition
$kvRoleId = (Get-AzRoleDefinition -Name "Key Vault Secrets User").Id
$condition = @"
(
(!(ActionMatches{'Microsoft.Authorization/roleAssignments/write'}))
OR
(
@Request[Microsoft.Authorization/roleAssignments:RoleDefinitionId] ForAnyOfAnyValues:GuidEquals {$kvRoleId}
AND
@Request[Microsoft.Authorization/roleAssignments:PrincipalType] ForAnyOfAnyValues:StringEqualsIgnoreCase {'ServicePrincipal'}
)
)
AND
(
(!(ActionMatches{'Microsoft.Authorization/roleAssignments/delete'}))
OR
(
@Resource[Microsoft.Authorization/roleAssignments:RoleDefinitionId] ForAnyOfAnyValues:GuidEquals {$kvRoleId}
)
)
"@Well… this syntax is a bit hard to swallow, but it rests on a single pattern, repeated twice. I might as well make the most of all the fun I had with it (not) and write a short recap. At least after this, the AZ-104 will no longer be scary on this point, because yes, there are questions about it.
The pattern: a disguised “if … then”
The condition language has no “if … then”. To express “if the action is X, then this constraint must hold”, we use a small logic trick: “if X then Y” is written "(NOT X) OR Y"
In other words: either we are not doing X (and all is well), or we are doing X and Y must be true. In the example: either we want to do something other than write (assign) an RBAC role, and that is fine, or, if we want to assign an RBAC role, it must be the “KV Secrets User” role. That’s all.
Here is a recap with a truth table (wow, jargon from distant classes):
| X (action of writing a “Role Assignment”) | Y (Role = KV Secrets User) | Result “(NOT X) OR Y” |
|---|---|---|
| true | true | ✅ true |
| true | false | ❌ false |
| false | true | ✅ true |
| false | false | ✅ true |
Our condition is therefore simply:
- Block 1: if the SP creates a role assignment, then it must be
Key Vault Secrets User, and for a service principal. - Block 2: if the SP deletes a role assignment, then it must be a
Key Vault Secrets Userassignment. - The two blocks are joined by an AND: both rules must hold at all times.
A golden rule
A condition can only restrict. It filters the actions already granted by the role, it never adds any. The “RBAC Administrator” role grants, among others, “roleAssignments/write” and “roleAssignments/delete”: these are exactly the two actions our condition narrows. Everything else (reading, in particular) goes through untouched.
When the condition is not met, Azure returns a nice “403 AuthorizationFailed” mentioning “ABAC condition that is not fulfilled”. We will trigger it on purpose right after 🙃
The truth table
| Action attempted by sp-terraform | Block 1 (write) | Block 2 (delete) | Result |
|---|---|---|---|
| Read anything | ✅ not a write | ✅ not a delete | ✅ Allowed |
Assign Reader | ❌ wrong role | ✅ | ❌ Denied |
Assign itself RBAC Administrator | ❌ wrong role | ✅ | ❌ Denied |
Assign Key Vault Secrets User to an SP | ✅ | ✅ | ✅ Allowed |
Assign Key Vault Secrets User to a user | ❌ wrong type | ✅ | ❌ Denied |
Delete a Key Vault Secrets User assignment | ✅ | ✅ | ✅ Allowed |
Delete your account’s Owner assignment | ✅ | ❌ wrong role | ❌ Denied |
Result: even if the certificate leaks, the attacker can indeed manage the subscription’s resources (Contributor oblige), but can neither grant themselves more rights nor remove anyone else’s. The blast radius is contained. But now it would be better to actually assign this role with its condition, instead of rambling on.
Assigning the RBAC Administrator role, with the condition defined above:
$subId = (Get-AzContext).Subscription.Id
New-AzRoleAssignment -ObjectId $sp.Id `
-RoleDefinitionName "Role Based Access Control Administrator" `
-Scope $scope `
-Condition $condition `
-ConditionVersion "2.0" `
-Description "sp-terraform: can only assign/remove Key Vault Secrets User, to service principals only"Tests
Checking the roles assigned to the Service Principal
Get-AzRoleAssignment -ObjectId $sp.Id `
| Select-Object RoleDefinitionName, Scope, Condition `
| Format-ListOutput
RoleDefinitionName : Contributor
Scope : /subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx
Condition :
RoleDefinitionName : Role Based Access Control Administrator
Scope : /subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx
Condition : (
(!(ActionMatches{'Microsoft.Authorization/roleAssignments/write'}))
OR
(
@Request[Microsoft.Authorization/roleAssignments:RoleDefinitionId]
ForAnyOfAnyValues:GuidEquals {4633458b-17de-408a-b874-0445c86b69e6}
AND
@Request[Microsoft.Authorization/roleAssignments:PrincipalType]
ForAnyOfAnyValues:StringEqualsIgnoreCase {'ServicePrincipal'}
)
)
AND
(
(!(ActionMatches{'Microsoft.Authorization/roleAssignments/delete'}))
OR
(
@Resource[Microsoft.Authorization/roleAssignments:RoleDefinitionId]
ForAnyOfAnyValues:GuidEquals {4633458b-17de-408a-b874-0445c86b69e6}
)
)Signing in with the Service Principal
Connect-AzAccount -ServicePrincipal `
-ApplicationId $sp.AppId `
-Tenant (Get-AzContext).Tenant.Id `
-CertificatePath (Resolve-Path ~\Desktop\sp-terraform.pfx).Path `
-CertificatePassword (ConvertTo-SecureString $env:ARM_CLIENT_CERTIFICATE_PASSWORD -AsPlainText -Force)Output
Subscription name Tenant
----------------- ------
Root subscription xxxx-xxxx-xxxx-xxxx-xxxxTesting the assignment of a forbidden role
# Should fail: Reader is not allowed by the condition
New-AzRoleAssignment -ObjectId $sp.Id -RoleDefinitionName "Reader" -Scope $scopeOutput
New-AzRoleAssignment: Operation returned an invalid status code 'Forbidden'. AuthorizationFailed: The client
'xxxx-xxxx-xxxx-xxxx-xxxx' with object id 'xxxx-xxxx-xxxx-xxxx-xxxx' has an authorization with
ABAC condition that is not fulfilled to perform action 'Microsoft.Authorization/roleAssignments/write' over scope '/sub
scriptions/xxxx-xxxx-xxxx-xxxx-xxxx/providers/Microsoft.Authorization/roleAssignments/fc847e5c-a150-42f7-b4ca-9eb7921f501c' or the scope is invalid. If access was recently granted, please refresh your credentials.Testing the assignment of the “Key Vault Secrets User” role to a ServicePrincipal
# Should succeed: Key Vault Secrets User is allowed by the condition
New-AzRoleAssignment -ObjectId $sp.Id -RoleDefinitionName "Key Vault Secrets User" -Scope $scopeOutput
RoleAssignmentName : xxxx-xxxx-xxxx-xxxx-xxxx
RoleAssignmentId : /subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx/providers/Microsoft.Authorization/roleAssignments/xxxx-xxxx-xxxx-xxxx-xxxx
Scope : /subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx
DisplayName : sp-terraform
SignInName :
RoleDefinitionName : Key Vault Secrets User
RoleDefinitionId : 4633458b-17de-408a-b874-0445c86b69e6
ObjectId : xxxx-xxxx-xxxx-xxxx-xxxx
ObjectType : ServicePrincipal
CanDelegate : False
Description :
ConditionVersion :
Condition :Testing the assignment of the “Key Vault Secrets User” role to a user
# Should fail: right role, but the assignee is not a service principal
$user = Get-AzADUser -UserPrincipalName "[email protected]"
New-AzRoleAssignment -ObjectId $user.Id -RoleDefinitionName "Key Vault Secrets User" -Scope $scopeOutput
New-AzRoleAssignment: Operation returned an invalid status code 'Forbidden'. AuthorizationFailed: The client 'xxxx-xxxx-xxxx-xxxx-xxxx' with object id 'xxxx-xxxx-xxxx-xxxx-xxxx' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write' over scope '/subscriptions/xxxx-xxxx-xxxx-xxxx-xxxx/providers/Microsoft.Authorization/roleAssignments/9abc1263-fee2-4581-a06e-c305619cafbf' or the scope is invalid. If access was recently granted, please refresh your credentialsConclusion
Well, I once again went way down the rabbit hole, spending far too much time on something an az login would have settled in ten seconds. But at least we come away with much more than a working connection:
- An identity dedicated to Terraform, separate from my personal account (and its Owner rights)
- Certificate-based authentication, with no shared secret in transit
- Broad permissions where Terraform needs them (
Contributor), and narrowed ones where it gets dangerous (delegating rights) - A tested RBAC condition: escalation is denied, the legitimate case goes through
- My traumatic AZ-104 topic on the road to recovery :)
Let’s also be honest about what can still be improved:
- The .pfx lives on my machine. It is protected by a passphrase, but if it leaks along with it,
sp-terraformcan still do quite a bit of damage in the subscription. The blast radius is contained, not zero. - The certificate expires in a year. And by then, I will have completely forgotten about it.
In the meantime, Terraform finally has its identity papers. All that is left is to make it do something useful… and that is where another identity comes on stage: the VM’s own, to fetch its WireGuard key from the Key Vault (after all, this is precisely the case I had so much fun with RBAC conditions for). Two identities, two roles, and a confusion trap we will defuse in the next article!