5

Deep Dive: AWS AssumeRole using STS API

 2 years ago
source link: https://blog.knoldus.com/deep-dive-aws-temporary-security-credentials-assumerole-and-iam-role/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Reading Time: 4 minutes

Introduction

In this blog post we shall be discussing on AWS:AssumeRole approach for obtaining temporary security credentials using STS(Security Token Service) end to end setup. 

Temporary Security Credentials (consisting of access key id, secret access key and a security token) enables you to have an access to AWS Environment for a specified duration. It solves use cases like cross account access and single sign-on to AWS.

During our journey we will be visiting, exploring and understanding following checkpoints :-
1. IAM Users
2. Attaching policy to IAM User
3. Using sts:AssumeRole to obtain temporary credentials
4. Attaching session policy for a specified duration

Understanding power of IAM USER

Lets say there is a use case where you want different users in your organization to have access to your AWS resources with specific set of permissions. In that scenario you need not give out your root user credentials as it can be difficult to revoke them and give separate permissions to each of them. Here, Power of IAM Users come into play.

By creating individual IAM users for people accessing your account.You can give each IAM user a unique set of security credentials. You can also grant different permissions to each IAM user.

Note: It is a good practice to create IAM User with Administrative permissions to complete your work,instead of ROOT user.

Attaching policies to IAM User

Managed Policy -An AWS managed policy is a standalone policy that is created and administered by AWS. Standalone policy means that the policy has its own Amazon Resource Name (ARN) that includes the policy name. For example, arn:aws:iam::aws:policy/IAMReadOnlyAccess is an AWS managed policy.

Inline Policies –An inline policy is a policy that’s embedded in a principal entity (a user, group, or role). This policy is an inherent part of the principal entity. You can create a policy and embed it in a principal entity, either when you create the principal entity or later. Basically it is one to one mapping of user to inline policy.Managed policy provides one to many mapping of users to its policy.

For implementation perspective, we will be using  IAMFullAccess Managed policy that define permissions for service IAM Users by granting full access to a service. In cases where you want to allow IAM Users to have access only to S3 Service use AmazonS3FullAccess

Note: You can use policy depending on your use case. In case you want your IAM roles to have restricted access to a particular resource (in my case S3), assign permissions accordingly.

Now lets dive deeper in AWS STS(Security Token Service) that allows to actually request Temporary Credentials.

Using AWS STS API

The AWS Security Token Service (STS) is a web service that enables you to request temporary, limited-privilege credentials for AWS Identity and Access Management (IAM) users.

Using STS: AWS AssumeRole API

AWS AssumeRole is used for cross account access or federation purposes. If you already have an identity and authentication system in your corporate network. You don’t have to recreate user identities in AWS in order to grant those user identities access to AWS. Instead, after a user has been authenticated, you call AssumeRole to get temporary security credentials for that user. With those temporary security credentials, you construct a sign-in URL that users can use to access the console.

Follow below Steps to use sts: AWS AssumeRole :-

1.Create an IAM role in your AWS account that allows S3 to call AWS Services on behalf of IAM user. Set Maximum CLI/Session duration depending on your Use case. Attach following trust policy to IAM Role :-

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::1234567890:user/temp-user"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

2. Create an instance of AssumeRoleRequest that takes role name which you created in Step 1 as an argument.Specify role ARN of respective role and  session policy that restricts the IAM Role to have permissions restricted to that session.Optional,the DurationSeconds parameter that specifies duration of your session. This setting can have a value from 1 hour to 12 hours at most.

val userName = "Bob"
val role = getRole("temp-role")
val request: AssumeRoleRequest = new AssumeRoleRequest()
      .withRoleSessionName(userName)
      .withRoleArn(role.getArn)
      .withPolicy(policy)
      .withDurationSeconds(43200)
      .withRoleArn(role.getArn)

3. AssumeRoleResult instance is generated as a response to call AssumeRoleRequest. This will have the temporary security credentials, which include an access key ID, a secret access key, and a security (or session) token.

 val response: AssumeRoleResult = client.assumeRole(request)
 val tempCredentials: Credentials = response.getCredentials
    

Output :-

{
    "Credentials": {
        "SecretAccessKey": "",
        "SessionToken": "AQoDYXdzEGcaEXAMPLE2gs==",
        "Expiration": "2014-12-11T23:08:07Z",
        "AccessKeyId": "AKIAIOSFODN"
    }
}

Attaching Session Policy to the Role

AWS AssumeRole sessions derive their permissions from the role policies that you’ve pre-defined, scoped down by the optional permissions attached in the request.  The actual permissions associated with the session are the intersection of the role’s permissions and the permissions attached as an API parameter(Session Policy).Only an IAM user or another role with permissions to call AssumeRole can assume a role.  By default, you can define up to 1,000. If you need more roles, submit the IAM limit increase request form with your use case.

{
  "Version": "2012-10-17",
  "Statement": [{
		  "Sid": "AllowListingOfUserFolder",
		  "Action": ["s3:ListBucket"],
		  "Effect": "Allow",
		  "Resource": ["arn:aws:s3:::test"],
		    "Condition": {
			 "StringLike": {
				"s3:prefix": [
					       "$id/*",
					       "$id"  
					     ]
				      }
			        }
		 },
		{
		  "Sid": "AllowAllS3ActionsInUserFolder",
		  "Action": ["s3:*"],
		  "Effect": "Allow",
		  "Resource": ["arn:aws:s3:::test/$id"]
		}
	 ]
}

Common errors

  • AccessDeniedException (403) – When you use ARN of IAM Role instead of IAM User.
  • MalformedPolicyDocumentException- The request was rejected because the policy document was malformed. The error message describes the specific error.
  • RegionDisabledException – STS is not activated in the requested region for the account that is being asked to generate credentials. The account administrator must use the IAM console to activate STS in that region.

References


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK