AWS STS

AWS STS – Complete Guide

AWS STS is an API that helps you to secure your AWS resources. This article will teach you everything you need about this service and why it’s crucial. Also, you will learn how aws sts work.

What is AWS STS? How does AWS STS work?

AWS STS is known as Security Token Service. The main goal of this API is to provide temporary access to resources in AWS.

It’s similar to IAM User and Role, which provide permanent access.

What are the main differences between AWS STS and IAM?

An excellent approach to understanding STS is comparing it with IAM user credentials, also listing some advantages.

  • Calls utilizing temporary security credentials, the call must contain a session token, which you can find along with the temporary credentials returned from STS. 
  • AWS uses the session token to validate the temporary security token.
  • Temporary credentials expire after a specified interval. So, after it expires, AWS will not recognize the token, and the request will fail.
  • You don’t need to spread or embed long-term AWS security credentials with an application.
  • You can supply access to some of your AWS resources to users without having to create an AWS identity for them.
  • The temporary security credentials expire, so you do not have to rotate or revoke them when they’re no longer required. After temporary security credentials expire, they become invalid. You can determine how long the credentials will remain valid, up to a maximum limit.

The AWS STS is a global service, and you can call this API using the global endpoint https://sts.amazonaws.com.

To protect your requests to AWS STS, you can create one AWS VPC Endpoint to make all your requests to STS without using the internet, so force them to go through the AWS network.

Latency Issues

The AWS STS is a global service, but it’s physically deployed in North Virginia (us-east-1). However, you can use the region endpoint available for most of the region instead of the global endpoint to avoid issues with latency.

In some regions, the STS endpoint is not enabled by default, but you can enable it.

For example, if you are close to Frankfurt, you can use the endpoint:

sts.eu-central-1.amazonaws.com

Who can use AWS STS?

IAM (Identity and Access Management) users or enterprise users authenticated using a federation approach.

How to use AWS STS?

You can use the STS API in several ways. 

AWS SDK

You can programmatically use and call AWS STS using the official SDK available for 12 programming languages below:

  1. Swift
  2. Rust
  3. Ruby
  4. Python
  5. PHP
  6. Node.Js
  7. .NET
  8. Kotlin
  9. JavaScript
  10. Java
  11. Go
  12. C++

On Windows, you can use the AWS STS using PowerShell.

HTTPS Requests

You can use AWS STS also by using simple HTTPS requests to provide temporary access. However, this approach’s a little different.

For example, you will need an Access Key and the Secret (The token from STS) in your request. Also, you need to include one Header to your HTTPS request named “X-Amz-Security-Token“, which is your session token retrieved from AWS STS.

AWS Command Line Tool (CLI)

Example:


aws sts assume-role --role-arn arn:aws:iam::014458101123:role/role-name --role-session-name "RoleSTSSession" --profile IAM-user-name > output.txt

Continue reading, and we have a complete example of how to use AWS STS with S3 using AWS CLI.

Different Method to Request Temporary Security Credentials using AWS STS

Using AssumeRole with AWS STS

You can use the AssumeRole API operation to help allow existing IAM users to access AWS resources when they don’t have access.

For instance, the user might require access to resources in another AWS account. It is also helpful to temporarily earn privileged access—for example, to supply multi-factor authentication (MFA). Also, you must reach this API using active credentials.

AWS STS Assume Role Example

Let’s see a complete example of how to use AWS STS Tokens to download objects from S3 Bucket.

Let’s create a new IAM Role for our example:


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

Screenshot:

AWS STS - Assume Role Example - Trusted Entities
AWS STS – Assume Role Example – Trusted Entities

The Policy example:


{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "*"
        }
    ]
}

Screenshot:

Copy S3 Object using AWS STS
Copy S3 Object using AWS STS

Now, with IAM Role created, you can use the AWS CLI to request the temporary access token and perform the action you need on a specific S3 Bucket. In our scenario will try to download one object.

AWS CLI with Assume Role

Let’s see How to generate AWS STS Token using AWS CLI.

The command below will give you the token that you need on the output:


aws sts assume-role --role-arn arn:aws:iam::123456789011:role/AllowS3 --role-session-name dev

Replace the ARN with your IAM Role. You should see similar output:

AWS STS Example


{
    "Credentials": {
        "AccessKeyId": "ASIAWPFXN1E7YYZPNVFI",
        "SecretAccessKey": "GE9wScakZ1mjCvdRidIYxbGgqy+PWtqnHYhaql0F",
        "SessionToken": "IQoJb3JpZ2luX2VjEBkaCXVzLWVsc3QtsSJIMEYCIQDj//7HD1woBOEIE5ZZMBjmMhrR5gX1zoeQCkqL
+EGTEgIhAM/dfUsvKtJ2Mp2h+pOH5JqliiJAtkaBpNecRtfpQCyyKpkCCPH//////////wEQAxoMNDQ0OTEzODAzNTgzIgzY/ga8Rd7l+
Y7zEF0q7QGGbrGnrHT2LL/PjYctJ9ag1j78mft2A1ZMwjhMsKwlesCT1afabao39IN9s2lHBdiala1PKeNKPNFAGBcHG7Ut2tVArD8/ak
iDggi71As9bALoCFq7t17w3Sz3YAcYMhYzqYncxDvbkIsAga1xoqDL1vjsj2Nb50ut9UBFjmpLcAOW8NH5lB1cBfBEbZsqXYvYzTio1RY
f28beb791yhbrTI1Gx1/WfUhw3XH9P1uwe0nqtco0aNsrWD1HXMEmXzfWaTL/np0+EmMmE1Wsi+WT9J1urwchRgt1KULILCHPUYb3lr3T
c1WHTrhkjkgw27vlmgY1nAGRr1ocicoGU3/V1ZyQ/KNF5T9Y0YIYbsiPS/GNRlHhTc5b8SQC8/e1avO3+lxOJ0fg0cRpAl1oUltJnpOyF
ifXF1bx8JvVoMweYZb12IR/KCBzaANjLAPsrvXA0aWk1lrQPmp1DDfiZXQI/rPZXiWinOWT1Ye0k9GI8HP1JEFcrPaXDIQsYi1VizLGxh
8dx+vo1dFGJe/SdqTrhNY=",
        "Expiration": "2022-10-21T17:18:35+00:00"
    },
    "AssumedRoleUser": {
        "AssumedRoleId": "AROAWPFXN1E7WLHSILNFG:dev",
        "Arn": "arn:aws:sts::123456789011:assumed-role/AllowS3/dev"
    }

Take notes of your output, especially the AccessKeyIdSecretAccessKey, and SessionToken. You will need them to make your API requests.

Export the values to the environment variables:


export AWS_ACCESS_KEY_ID=_from_AWS_STS_output
export AWS_SECRET_ACCESS_KEY=_from_AWS_STS_output
export AWS_SESSION_TOKEN=_from_AWS_STS_output

If you forget to pass the AWS_SESSION_TOKEN, you will get access denied, like:

Fatal error: An error occurred (403) when calling the HeadObject operation: Forbidden

Downloading S3 Object with AWS STS

If all variables are configured and valid, you can run the AWS CLI to download the files you need or any operation allowed on your IAM Policy.


aws s3 cp s3://bitslovers-bucket/accesslogs/aws-sts-with-s3.log .

Easy, right? Here are more tips to boost your learning and take all the advantages of AWS STS. Continue reading.

How to Recover Session Token

If for some reason, you lose the Session Token, you can use the AWS CLI and use STS API to recover it using get-session-token.


aws sts get-session-token

AWS STS with Python – Example

The python code below will retrieve a session token using MFA credentials as input and utilizes the temporary session credentials to print out a list of S3 buckets.

This example needs an MFA device serial number and token.

Parameters:

mfa_sn: The serial number of the MFA device. For a virtual MFA device, this is an ARN.

mfa_totp: A time-based, one-time password allocated by the MFA device.

sts_client: A Boto3 STS client that has permission to assume the role.


def get_s3_buckets_session_token_mfa(mfa_sn, mfa_totp, sts_client):
    
    if mfa_sn is not None:
        response = sts_client.get_session_token(
            SerialNumber=mfa_sn, TokenCode=mfa_totp)
    else:
        response = sts_client.get_session_token()
    temp_credentials = response['Credentials']

    client = boto3.resource(
        's3',
        aws_access_key_id=temp_credentials['AccessKeyId'],
        aws_secret_access_key=temp_credentials['SecretAccessKey'],
        aws_session_token=temp_credentials['SessionToken'])

    print(f"List of Buckets:")
    for bucket in client.buckets.all():
        print(bucket.name)

Using AWS STS with Federation

The AWS STS also provides support federation. And the good news is that you can create the IAM User without creating the IAM User. 

It means you can use Single sign-on (SSO) to permit users to access any AWS resources without creating one identity inside the AWS (IAM User). For example, if the user is already logged in using the company network, the user will already have the temporary session token to interact with any resource in AWS.

When to use AWS STS?

If you already share AWS resources between different AWS accounts, you may already use AWS STS.

When you give one AWS account access to one resource from another account, we usually create an IAM Role, which uses the AssumeRole.


{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "sts:AssumeRole"
      ],
      "Resource": [
        "arn:aws:iam::DESTINATION-ACCOUNT-ID:role/DESTINATION-ROLENAME"
      ]
    }
  ]
}

How can you audit the AWS STS calls?

AWS STS supports CloudTrail, so you can find any call to STS and discover who sent the requests and when someone sent the request.

How does the AWS STS expire?

You can define the duration of the temporary credentials. Then, when you call the AWS STS, you can pass the param DurationSeconds.

DurationSeconds determine the life of the role session from 900 seconds up to the maximum session duration setting for a specific role. The default maximum session duration is 1 hour. You can check this value on the IAM Role. 

AWS STS - Maximum Session Duration
AWS STS – Maximum Session Duration

How to decode the AWS STS authorization message

Decodes extra information regarding the authorization process of a request from an encoded message produced in response to an AWS API request.

For instance, if a user is not allowed to execute an operation that they have requested, the request returns a Client.UnauthorizedOperation response (in other words, one HTTP 403 response). Some AWS operations return an encoded message that can supply details regarding this authorization failure. So, to make it easier to troubleshoot AWS STS errors, you can use the following command:


aws sts decode-authorization-message --encoded-message 

Leave a Comment

Your email address will not be published. Required fields are marked *

Free PDF with a useful Mind Map that illustrates everything you should know about AWS VPC in a single view.