DEV Community

Cross-Account Resource Access Using EC2 Instance Metadata.

Cross-Account Resource Access Using EC2 Instance Metadata

In today’s cloud landscape, it’s common for organizations to utilize multiple AWS accounts to manage different aspects of their infrastructure. While maintaining isolation between accounts enhances security, there are scenarios where collaboration across accounts is necessary. Amazon Elastic Compute Cloud (EC2) instances provide a secure way to facilitate cross-account interactions through the use of instance metadata and profiles. This article delves into the process of enabling an EC2 instance in one AWS account to access resources in another AWS account using instance metadata and profiles. We’ll also explore alternative methods for cross-account resource access.

Understanding Cross-Account Access with EC2 Instance Metadata and Profiles

Cross-account resource access involves allowing an entity in one AWS account (the source account) to access resources in another AWS account (the target account). EC2 instance metadata and profiles provide a mechanism to achieve this securely:

  1. **Instance Metadata : **EC2 instance metadata is a service provided by AWS that offers a way to retrieve information about an instance without the need to authenticate. This metadata is stored in a well-known URL, http://169.254.169.254/latest/meta-data/, within the instance itself. By accessing this URL, instances can retrieve details such as instance ID, instance type, security groups, IAM role name, and much more. In addition to providing instance information, EC2 instance metadata is also used to retrieve temporary security credentials. These credentials grant the instance permissions to access resources in the target account. This capability provides a way to grant instances specific permissions without having to embed long-lived credentials directly into the instance.

  2. Profiles : A profile is a collection of settings and credentials that you can use to specify the AWS resources you want to interact with. Further, profiles allow instances to assume cross-account roles using instance metadata without explicitly specifying role ARNs.

Cross-account access using EC2 instance metadata involves the following components:

  1. *Cross-Account IAM Role *:: In the target AWS account, you create an IAM role with the necessary permissions. This role defines which resources the EC2 instance in the source account is allowed to access.

  2. Trust Relationship : The cross-account IAM role must have a trust relationship policy that specifies the AWS account of the source EC2 instance. This trust policy establishes a connection between the two accounts.

  3. Instance Metadata : The EC2 instance in the source AWS account accesses instance metadata to retrieve temporary credentials associated with the cross-account IAM role. These credentials grant the instance access to resources in the target account.

Real World Use Cases

  • *Data Aggregation *: An EC2 instance in one account could collect and aggregate data from multiple AWS accounts without exposing long-lived credentials.

  • Centralized Logging : Instances in various accounts can push logs to a central logging bucket in a different account.

  • Cross-Account Data Processing : Instances in one account can process data stored in buckets owned by other accounts.

Steps to Enable Cross-Account Access

Let’s illustrate the process with a practical example:

Scenario: An EC2 instance in Account A(source account) requires access a particular Route53 hosted zone residing in Account B(target account) for the purpose of creating Route53 records.

  1. ) Launch an EC2 Instance in Account A

ec2 Instance residing in Account A

An EC2 instance initiated within Account A and associated with an IAM Role named “AppServerRole”

AppServerRole Trust Policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "ec2.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

AppServerRole Permission Policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "assumerole",
            "Action": [
                "sts:AssumeRole"
            ],
            "Resource": "arn:aws:iam::<<Account Number of Account B>>:role/<<Role Name>>",
            "Effect": "Allow"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

The JSON policy document provided above grants permissions for the AppServerRole to assume a role (sts:AssumeRole) in Account B.

Please substitute <> with the name of the Cross Account Role that will be generated in Step 2.

Retrieving Ec2 Instance Metadata

Retrieving EC2 instance metadata involves accessing information about an Amazon EC2 instance’s configuration and identity. This information is available via a web service running on a special IP address, 169.254.169.254, within the EC2 instance's network.

IMDSv1

curl http://169.254.169.254/latest/meta-data/
Enter fullscreen mode Exit fullscreen mode

he above curl command is used to directly access the EC2 instance metadata service without using IMDSv2 authentication. This approach uses IMDSv1, which can be susceptible to certain security vulnerabilities, especially Server-Side Request Forgery (SSRF) attacks.

IMDSv2

IMDSv2

The above curl command is used to securely access the instance metadata service using IMDSv2 authentication. The session token adds an additional layer of security and helps mitigate potential vulnerabilities associated with directly accessing instance metadata using IMDSv1. This approach is recommended for security-sensitive environments and scenarios.

The key differences between Instance Metadata Service Version 1 (IMDSv1) and Instance Metadata Service Version 2 (IMDSv2) in Amazon Web Services (AWS) lie in their security mechanisms and protections. IMDSv2 was introduced to address security concerns and enhance the overall security posture when accessing instance metadata.

2.) Create an IAM Role in Account B (Cross-Account IAM Role)

R53 Role in Account B

3.) Attach Policies to Cross-Account IAM Role in Account B

R53Role Trust Policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Statement1",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<<Account Number of Account B>>:role/AppServerRole"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

The above trust policy grants permissions for ‘AppServerRole’ residing in Account A to assume ‘R53Role’ residing in Account B.

R53Role Permission Policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "r53",
            "Effect": "Allow",
            "Action": [
                "route53:GetHostedZone",
                "route53:ChangeResourceRecordSets",
                "route53:GetChange"                
            ],
            "Resource": "arn:aws:route53:::hostedzone/<<hosted-zone-id>>"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

The above policy enables permission for specific Route 53 Actions (querying hosted zones, modifying resource record sets, and obtaining change details) to a designated hostedzone in Account B.

4.) Configuring a profile for Amazon EC2 metadata in Account A

Prerequisite : Ensure that the AWS CLI is installed and properly configured on the EC2 instance

Access the EC2 instance through SSH or AWS Systems Manager (SSM). Navigate to the AWS CLI configuration file located at ~/.aws/config and append a new profile, such as "account-B" or a name you prefer. In the profile definition, include the ARN of the role you intend to assume (the ARN of the R53Role residing in Account B). Additionally, set the credential_source as Ec2InstanceMetadata.

[profile account-B]
role_arn = arn:aws:iam::<<Account Number of Account B>>:role/R53Role
credential_source = Ec2InstanceMetadata
region = ap-southeast-2
Enter fullscreen mode Exit fullscreen mode

Above configuration snippet for an AWS CLI profile named “account-B” that assumes an IAM role from Account B using EC2 instance metadata. This profile allows an EC2 instance to assume the specified role in Account B and use the obtained credentials to interact with AWS resources (Route 53 Hosted Zone in Account B).

5.) Verifying Cross Account Access

Connect to the EC2 instance via SSH or AWS Systems Manager (SSM), then execute the following AWS CLI command :

 aws route53 get-hosted-zone --id <<hosted zone id>> --profile account-B
Enter fullscreen mode Exit fullscreen mode

Query HostedZone Details

The output above verifies that the EC2 instance located in Account A successfully retrieved details about a hosted zone situated in Account B.

Now, let’s try to perform an action in Account B that lacks the necessary authorization, such as attempting to list hosted zones.

List Hosted Zones

This error message indicates that the AWS identity associated with the role R53Role assumed by the EC2 instance in Account A does not possess the necessary permissions to perform the route53:ListHostedZones action.

Other Cross-Account Access Methods

  • IAM Role Switching : Instances assume roles directly using temporary credentials from instance metadata. This method requires explicit role switching and doesn’t rely on profiles.

  • *AWS STS *: Account A requests temporary credentials from STS to assume a cross-account role. This method can be used programmatically to generate credentials. This method can be used for cross-account access beyond EC2 instances.

  • *Resource Based Access *: Resources like Amazon S3 buckets can be configured to allow access from specific AWS accounts, enabling cross-account resource sharing without temporary credentials.

Conclusion

Leveraging EC2 instance metadata and profiles enables seamless cross-account interactions while maintaining a high level of security. This approach provides the necessary permissions to access resources across accounts without exposing long-lived credentials. In scenarios where security and collaboration are paramount, this mechanism shines.

Other methods like IAM role switching, AWS STS, and resource-based access offer different avenues for cross-account resource sharing, each with its own use cases and considerations. Understanding these methods empowers you to choose the most suitable approach for your specific requirements.

As you embrace cross-account interactions, remember to follow best practices, manage permissions judiciously, and keep security at the forefront of your architecture.

Top comments (0)