Skip to content

Instantly share code, notes, and snippets.

@jimdigriz
Last active June 19, 2022 06:59
Show Gist options
  • Save jimdigriz/2698028557ab3f9efcc02e6bfd7b1f14 to your computer and use it in GitHub Desktop.
Save jimdigriz/2698028557ab3f9efcc02e6bfd7b1f14 to your computer and use it in GitHub Desktop.
AWS GetCallerIdentity in POSIX Shell

I wanted to be able to use AWS GetCallerIdentity in a Lambda function but without having to import all of the AWS CLI (and Python runtime) in order to do so.

This involves the AWS Signature Version 4 Signing Process which a lot of online examples made look pretty complicated and were really hard to follow, so I decided to make the situation worse by adding my own implementation to the tirefire!

To use this you need at least AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, but otherwise just run the script. The example shows how to request temporary security credentials and you can use that reponse to populate the environment variables manually when calling the script:

aws sts get-session-token --duration-seconds 900
env AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... AWS_SESSION_TOKEN=... sh aws-getcallerid.sh

N.B. AWS_SESSION_TOKEN is not required unless you are using a session token (as in the above example) rather than an IAM user account

#!/bin/sh
set -eu
sha256 () {
echo -n "$1" | openssl dgst -sha256 | cut -d' ' -f2 | tr -d '\n'
}
hmac () {
echo -n "$1" | openssl dgst -sha256 -mac HMAC -macopt "$2" | cut -d' ' -f2 | tr -d '\n'
}
AWS_DATE=$(date -u +%Y%m%dT%H%M%S)Z
AWS_ALGO=AWS4-HMAC-SHA256
AWS_SERVICE=sts
AWS_HOST=$AWS_SERVICE.amazonaws.com
AWS_PATH=/
AWS_QUERY='Action=GetCallerIdentity&Version=2011-06-15'
AWS_REQUEST=aws4_request
# seems to need to be us-east-1
AWS_REGION=us-east-1
PCHK=$(sha256 '')
CCHK=$(sha256 "GET
$AWS_PATH
$AWS_QUERY
host:$AWS_HOST
x-amz-content-sha256:$PCHK
x-amz-date:$AWS_DATE${AWS_SESSION_TOKEN:+
x-amz-security-token:$AWS_SESSION_TOKEN}
host;x-amz-content-sha256;x-amz-date${AWS_SESSION_TOKEN:+;x-amz-security-token}
$PCHK")
SKEY=$(hmac aws4_request hexkey:$(hmac $AWS_SERVICE hexkey:$(hmac $AWS_REGION hexkey:$(hmac ${AWS_DATE%T*} key:"AWS4$AWS_SECRET_ACCESS_KEY"))))
SIG=$(hmac "$AWS_ALGO
$AWS_DATE
${AWS_DATE%T*}/$AWS_REGION/$AWS_SERVICE/$AWS_REQUEST
$CCHK" hexkey:$SKEY)
exec curl -sfS --max-time 3 \
-H "Authorization: $AWS_ALGO Credential=$AWS_ACCESS_KEY_ID/${AWS_DATE%T*}/$AWS_REGION/$AWS_SERVICE/$AWS_REQUEST, SignedHeaders=host;x-amz-content-sha256;x-amz-date${AWS_SESSION_TOKEN:+;x-amz-security-token}, Signature=$SIG" \
-H "x-amz-content-sha256: $PCHK" \
-H "x-amz-date: $AWS_DATE" \
${AWS_SESSION_TOKEN:+-H "x-amz-security-token: $AWS_SESSION_TOKEN"} \
"https://$AWS_HOST$AWS_PATH?$AWS_QUERY"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment