Tags:
In my previous blog post, I introduced the intertwined roles of Identity and Access Management (IAM) and Infrastructure as Code (IaC) in elevating cloud security while trying to stay cloud agnostic. Now, let me take you on the next part of our journey by diving deeper into how tools like Terraform can refine IAM strategies, specifically within the AWS ecosystem, to forge a more secure, efficient, and future-ready cloud infrastructure.
Streamlining Identity and Access Management with Terraform
I am probably not the only one that has noticed that as organizations expand their cloud presence and adopt multi-cloud strategies, voluntarily or not, the complexities of managing identity and access become increasingly challenging. Centralized User Management and SSO across Cloud Service Providers (CSPs) offer possible solutions to these challenges and can be efficiently automated with tools like Terraform.
Centralized User Management via Terraform
Efficiently managing user access at scale is crucial for cloud security and IAM. Terraform provides an avenue for the automation needed to centralize user management, allowing you to encode and enforce consistent IAM policies across your entire cloud infrastructure.
By leveraging a tool like Terraform, we can define IAM policies that grant the necessary permissions to handle user accounts within AWS, linked to their corporate identities managed in Google Workspace. Here is a practical example of how this centralized management policy could be written:
# Terraform Code for Central User Management Policy
resource "aws_iam_policy" "central_user_management_policy" {
name = "CentralUserManagementPolicy"
description = "Manage user roles and permissions centrally"
policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Effect = "Allow",
Action = [
"iam:CreateUser",
"iam:DeleteUser",
"iam:UpdateUser"
],
Resource = "arn:aws:iam::*:user/*"
},
{
Effect = "Allow",
Action = [
"iam:AttachUserPolicy",
"iam:DetachUserPolicy",
"iam:PutUserPermissionsBoundary"
],
Resource = "arn:aws:iam::*:user/*"
}
// Additional permissions and statements as needed
]
})
}
resource "aws_iam_role_policy_attachment" "central_management_attachment" {
policy_arn = aws_iam_policy.central_user_management_policy.arn
role = aws_iam_role.user_sso_role.name
}
This policy, when attached to a role, ensures that administrators have the capability to update user roles and permissions in AWS, mirroring changes made in the corporate directory. As organizational roles evolve, Terraform can apply updates across the cloud environment, maintaining access integrity and reducing administrative overhead.
IAM Federation: Bridging Identity Gaps
Following the theme of central management, I will be delving into streamlining human user access through single sign-on (SSO) and federated identity management (FIM). Terraform can be used to create and manage AWS IAM Identity Providers (IdPs) that connect to external identity sources, such as Google Workspace. This allows users to access AWS services using their existing corporate credentials, streamlining the authentication process.
IAM federation is instrumental in simplifying user access in a multi-cloud or hybrid cloud environment. With Terraform, we can codify and automate user access patterns, enabling users to log in once and gain access to resources across AWS, regardless of the underlying complexities. These concepts can also be extrapolated to on-premises infrastructure in a hybrid environment.
Consider the setup of SSO for users to access AWS resources, using Google Workspace as the identity provider:
# Terraform Code for SAML Provider Configuration
resource "aws_iam_saml_provider" "google_sso" {
name = "GoogleSSO"
saml_metadata_document = file("saml-metadata.xml")
}
resource "aws_iam_role" "user_sso_role" {
name = "UserSSORole"
assume_role_policy = data.aws_iam_policy_document.sso_trust_relationship.json
}
data "aws_iam_policy_document" "sso_trust_relationship" {
statement {
actions = ["sts:AssumeRoleWithSAML"]
effect = "Allow"
principals {
type = "Federated"
identifiers = [aws_iam_saml_provider.google_sso.arn]
}
condition {
test = "StringEquals"
variable = "SAML:aud"
values = ["<a href="https://signin.aws.amazon.com/saml">https://signin.aws.amazon.com/saml</a>"]
}
}
}
This configuration defines a SAML provider and a role in AWS that users from Google Workspace can assume. It is a vital part of the SSO setup, which automates the granting of access to AWS services based on the user's authentication with Google. With Terraform, these federated access rules ensure that the right users have the right access, all managed from a central point of control.
By leveraging Terraform for such configurations, we ensure that user access setup is not only automated and error-free but also easily replicable and version-controlled. This becomes particularly crucial in managing access at scale and adhering to strict compliance requirements.
If you want to play around with other aspects of identity federation Eric Johnson does a great deed in describing how to work with Workload Identity Federation and avoiding long lived credentials on his webcast. He is even offering a free hands-on workshop for you to play around with the topic: Destroying Long-Lived Cloud Credentials with Workload Identity Federation.
Enhancing AWS IAM Workflows with Advanced Terraform Techniques
Having explored the synergy between IAM and IaC, I hope you now recognize that Terraform does more than just streamline infrastructure management—it embeds security best practices into the very fabric of our cloud environments. By defining IAM roles, policies, and permissions as code, Terraform enables precise control over who accesses what, and how, within our infrastructure. From here I will be diving into the more nuanced realms of AWS IAM, where conditional policies refine access control and Multi-Factor Authentication (MFA) fortifies security defenses.
Advanced Conditional Access and the Role of MFA
For organizations across all sectors, and especially critical infrastructure like transportation, finance, and healthcare, implementing conditional IAM policies and Multi-Factor Authentication (MFA) should not just be a best practice—it must be a necessity. You have to remember: these tools are not only for restricting access. They are about intelligent access tailored to your organization's operational rhythms and risk profile.
At my organization, Danish State Railways (DSB), we have integrated MFA not merely as a compliance requirement but as a core component of our security architecture. Amongst other things, we use it as part of our defense of public-facing login portals and as a central component in our privileged access management scheme. This is especially crucial in our domain, where public safety and critical operations hinge on robust security measures.
But the effectiveness of MFA extends beyond its mere presence; it lies in its strategic implementation and continuous reassessment. At DSB, one of the things I am working on is looking for answers to the following questions. How do we enhance the robustness of our MFA implementation? How do we ensure MFA is a meaningful barrier rather than a procedural afterthought? How do we strike that delicate balance where MFA becomes a seamless yet unyielding barrier against unauthorized access?
It is a common challenge in deploying MFA; maintaining the delicate balance between security and user experience. Working with the questions above, I have come to realize that it requires a lot of stakeholder management and listening to user feedback, to understand their individual use cases. It requires diverse MFA methods that support those different use cases. And it requires adaptive MFA concepts which adjust the authentication challenges based on defined risk context like location, network, or time of access.
It is a delicate balance to strike, especially in sectors like transportation and critical infrastructure, where the stakes are high, and compliance with standards like the EU's NIS directive is non-negotiable. As a critical infrastructure organization, we at DSB became ISO27001 certified a few years back—so we know we are on the right track (pun intended). But security is not a sprint, it is a marathon. And we are still continuously improving.
An area of improvement that I am actively working on would be the integration of adaptive MFA, where the system assesses the risk context—like login behavior or geolocation—to determine when to prompt for MFA, ensuring that balance between security and user experience. Being a train operator, having a very mobile workforce, you can probably imagine that it is not exactly easy.
Alright, let me show you how to utilize the role of MFA and how we can leverage Terraform to enforce it, alongside conditional access, to elevate our security measures:
In AWS, conditional IAM policies can be fine-tuned to enforce MFA, not just for high-privilege roles but as a widespread practice. Below is an example of how we might enforce MFA for accessing S3 buckets, ensuring that sensitive data is only accessible under the right conditions:
# Definition of Production Account Policy
resource "aws_iam_policy" "custom_storage_policy" {
name = "CustomStoragePolicy"
description = "A custom policy for read access to specific s3 buckets with MFA and IP restrictions"
policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Sid = "MFARestrictedGetObject"
Action = "s3:GetObject",
Effect = "Allow",
Resource = [
"arn:aws:s3:::example-bucket/*", # Specify actual bucket name
// Add additional bucket ARNs if necessary
],
Condition = {
Bool : {
"aws:MultiFactorAuthPresent" : "true"
},
IpAddress : {
"aws:SourceIp" : [
"192.168.1.0/24", # Define allowed IP range here
// Add additional IP ranges if necessary
]
}
}
},
// Add additional statements for other permissions if necessary
]
})
}
By combining a requirement for MFA with IP whitelisting, we craft a security environment that is both resilient and responsive to our operational context. The Terraform code above illustrates this principle: it enforces MFA, but also ensures access is only possible from trusted networks. This dual condition approach significantly reduces the risk of unauthorized access and potential data breaches.
As I continue my work to improve the security measures at DSB and share some of our insights with the broader community, I encourage a proactive stance on MFA and conditional access policies. It is not just about having the basic measures in place—it is about ensuring they are as effective as they are intended to be, continually evolving alongside emerging threats and organizational changes. We also see this from Microsoft, who will soon be rolling out Microsoft-managed conditional access policies enforcing MFA to all their customers.
Cross-Account Access Control with Terraform
In the realm of AWS, the ability to orchestrate resource access across multiple accounts is not just a feature—it is a strategic enabler of security and operational efficiency. It is not about sharing user accounts; it is about crafting a seamless yet secure bridge between separate AWS environments. Closely related to the federated identities we discussed previously.
Cross-account access is a practice that reinforces the principle of least privilege by granting users in one AWS account the ability to assume specific roles in another, all while maintaining a stringent boundary of permissions. It enables you to define roles and policies with precision, ensuring that every cross-account action aligns with the governance policies and security posture.
Consider the scenario where troubleshooting in the production environment is necessary. Instead of duplicating user identities, Terraform allows us to create a role within the production environment with permissions scoped precisely to the task at hand. This role can then be assumed by a designated troubleshooter role from the development account.
Here is how we write this in Terraform:
# Definition of Production Role for Cross-Account Access
resource "aws_iam_role" "cross_account_troubleshooting_role" {
name = "CrossAccountTroubleshootingRole"
description = "Role to be assumed by DevTroubleshooters for cross-account access"
assume_role_policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Effect = "Allow",
Action = "sts:AssumeRole",
Principal = {
AWS = "arn:aws:iam::DEVELOPMENT_ACCOUNT_ID:role/DevTroubleshooter" # Replace with actual development account ID
}
}
]
})
tags = {
Role = "CrossAccountTroubleshooting",
Environment = "Production"
}
}
# Attachment of Custom Storage Policy to Production Role
resource "aws_iam_role_policy_attachment" "custom_storage_policy_attachment" {
policy_arn = aws_iam_policy.custom_storage_policy.arn
role = aws_iam_role.cross_account_troubleshooting_role.name
}
This code encapsulates the trust relationship, bridging the development and production accounts without intermingling their resources. It is about granting just-in-time access with just-enough privilege—no more, no less.
Similarly, in the development account, we define a role that is designed to assume the production troubleshooting role. This is not a duplication but a construction of access that respect the autonomy of each environment:
# Definition of Development Account Role for Cross-Account Role Assumption
resource "aws_iam_role" "development_troubleshooter" {
name = "DevTroubleshooter"
description = "Role that can assume CrossAccountTroubleshootingRole in the production account"
assume_role_policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Effect = "Allow",
Action = "sts:AssumeRole",
Principal = {
AWS = "arn:aws:iam::PRODUCTION_ACCOUNT_ID:role/CrossAccountTroubleshootingRole" # Replace with actual production account ID
}
}
]
})
tags = {
Role = "DevelopmentTroubleshooter",
Environment = "Development"
}
}
# Definition of Development Account Policy for assuming the production role
resource "aws_iam_policy" "development_troubleshooter_policy" {
name = "DevelopmentTroubleshooterPolicy"
description = "Policy that allows assuming the CrossAccountTroubleshootingRole in production"
policy = jsonencode({
Version = "2012-10-17",
Statement = [
{
Effect = "Allow",
Action = "sts:AssumeRole",
Resource = "arn:aws:iam::PRODUCTION_ACCOUNT_ID:role/CrossAccountTroubleshootingRole" # Replace with actual production account ID
}
]
})
}
# Attachment of the Development Troubleshooter Policy to the Development Role
resource "aws_iam_role_policy_attachment" "development_troubleshooter_policy_attachment" {
policy_arn = aws_iam_policy.development_troubleshooter_policy.arn
role = aws_iam_role.development_troubleshooter.name
}
In constructing these roles and policies, we are effectively laying down a blueprint for secure, cross-account interactions. It is a setup that not only safeguards our resources but also streamlines the developer experience, allowing for agile responses to operational demands without compromising on security.
Cross-account access control, when managed through Terraform, transforms what could be an intricate web of permissions into a streamlined, auditable, and secure concept. It is a testament to how Terraform's infrastructure as code philosophy is not just about infrastructure—it is about embedding security as a foundational element of cloud architecture.
SEC510: Cloud Security Controls and Mitigations
This blog supports content taught in SEC510: Cloud Security Controls and Mitigation. Learn more about the course here.
About the Author
Andreas Laursen Lindhagen is a Senior IT Security Architect at DSB A/S, Danish State Railways. He holds multiple certifications, including GCLD and GPCS, and has more than six years of experience in information security, from both consultancy and critical infrastructure companies, focusing on cloud and security architecture. Andreas has a MSc in Information Technology with a specialization in Cybersecurity from the Technical University of Denmark. Connect with Andreas on LinkedIn.