Accessing AWS API using short-lived (temporary) credentials

This is a quick demonstration of a way to mitigate risk by generating and using temporary AWS access credentials for the interaction with the API, with the permanent credentials stored in a password manager (1Password)

This is a demonstration only, we are not looking at using this script in class since the students do not have 1Password readily available for the lab

Required tools:

The script assumes the user has an AWS user account protected via MFA and a pair of long-lived AWS API keys, and the information is stored in a 1Password vault

Config file

====================================================================================

{
  "aws":
     {
        "org_id":            "nsrc",
        "name":              "NSRC AWS Training Account",
        "access_key_id":     "op://NSRC/NSRC AWS Training Account/access_key_id",
        "secret_access_key": "op://NSRC/NSRC AWS Training Account/secret_access_key",
        "otp":               "op://NSRC/NSRC AWS Training Account/totp" ,
        "mfa_id":            "op://NSRC/NSRC AWS Training Account/mfa_id"
     }
}

=====================================================================================

#### Script - relevant sections

Obtain variables from password manager app:

op_access_key_id=$(echo "${JSON}" | jq -r '.access_key_id'  )
op_secret_access_key=$(echo "${JSON}" | jq -r '.secret_access_key'  )
op_otp=$(echo "${JSON}" | jq -r '.otp'  )
op_mfa_id=$(echo "${JSON}" | jq -r '.mfa_id'  )
op_name=$(echo "${JSON}" | jq -r '.name'  )

#Retrieve value from 1Password, requires biometrics
access_key_id=$(op read "${op_access_key_id}")
secret_access_key=$(op read "${op_secret_access_key}")
mfa_id=$(op read "${op_mfa_id}")
otp=$(op item get "${op_name}" --otp)

Obtain short-lived credentials using protected long-lived ones

#### temporarily export perm credentials to obtain
###  temporary ones
export AWS_ACCESS_KEY_ID="${access_key_id}"
export AWS_SECRET_ACCESS_KEY="${secret_access_key}"

# Request issue temporary credentials
JSON_TOKEN=$(aws sts get-session-token --duration 28800 --serial-number "${mfa_id}" --token-code "${otp}")

# Extract credentials and token from JSON payload
access_key_id=$(echo "${JSON_TOKEN}" | jq -r '.Credentials.AccessKeyId')
secret_access_key=$(echo "${JSON_TOKEN}" | jq -r '.Credentials.SecretAccessKey')
token=$(echo "${JSON_TOKEN}" | jq -r '.Credentials.SessionToken')


# replace credentialds in memory with temporary ones
export AWS_ACCESS_KEY_ID="${access_key_id}"
export AWS_SECRET_ACCESS_KEY="${secret_access_key}"
export AWS_SESSION_TOKEN="${token}"

Verify we obtained valid short-lived credentials

aws sts get-caller-identity

{
    "UserId": "AIDAQ3EGUL3QDCR5WLY7F",
    "Account": "058264411872",
    "Arn": "arn:aws:iam::058264411872:user/carmas"
}

=====================================================================================

Run script live

Comment on results