AWS and Switching Roles

When i first started with AWS, i was unsure how this works, but after looking into it and getting it to work successfully, i thought i would write it down. The command below is really useful for connecting to a windows machine and having an RDP session locally, rather than connecting through a browser.

AUTH account

As best practice we would normally deploy a new AWS customer with an AUTH account in order to have a centralised point for IAM users. This prevents having multiple passwords and MFA that need changing or rotating.

This is where you would create your IAM user with MFA and password.

Once the user has been created you create a policy granting them permission to assume a role in another account. Obviously, the ARN’s are account specific, so make sure these are updated to the roles that are created in your accounts.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "User",
            "Effect": "Allow",
            "Action": "sts:AssumeRole",
            "Resource": [
                "arn:aws:iam::<accountid>:role/aws_role",
                "arn:aws:iam::<accountid>:role/aws_role"
            ]
        }
    ]
}

This policy can be attached to multiple IAM users directly, or attached to a group containing the users and will allow them to assume a role in another account granting them the privileges and policies needed for them.

AWS Account

In the accounts specified above, ensure you have created your policies either allowing or denying certain actions. I particularly like this policy allowing only SSM access and port forwarding to access RDP remotely. This securely ensures the users above are only able to start SSM sessions to a limited number of instances.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "SSMAccess",
            "Effect": "Allow",
            "Action": [
                "ssm:StartSession",
                "ssm:TerminateSession",
                "ssm:ResumeSession"
            ],
            "Resource": [
                "arn:aws:ec2:<region>:<accountid>:instance/<instanceid>",
                "arn:aws:ec2:<region>:<accountid>:instance/<instanceid>",
                "arn:aws:ssm:*::document/AWS-StartPortForwardingSession",
                "arn:aws:ssm:<region>:<accountid>:session/*"
            ]
        }
    ]
}

Once the role has been created with the attached policy, you would be able to run this command in order to start an SSM session remotely and forward the port locally to enable RDP access from your machine.

aws sts assume-role --role-arn arn:aws:iam::<accountid>:role/aws_role  --role-session-name "aws ssm session" --profile AUTH_ACCOUNT

aws ssm start-session --target <instanceid> --document-name AWS-StartPortForwardingSession --parameters "portNumber=3389, localPortNumber=9000" --profile OTHER_ACCOUNT