Skip to content

Commit

Permalink
Fetch new IMDS token for every request
Browse files Browse the repository at this point in the history
  • Loading branch information
cartermckinnon committed Aug 17, 2023
1 parent 1f49248 commit 97233b3
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 101 deletions.
34 changes: 4 additions & 30 deletions files/bin/imds
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ CURRENT_TIME=$(date '+%s')
IMDS_DEBUG="${IMDS_DEBUG:-false}"
# default ttl is 15 minutes
IMDS_TOKEN_TTL_SECONDS=${IMDS_TOKEN_TTL_SECONDS:-900}
# max ttl is 6 hours, see: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html
IMDS_MAX_TOKEN_TTL_SECONDS=${IMDS_MAX_TOKEN_TTL_SECONDS:-21600}
IMDS_RETRIES=${IMDS_RETRIES:-10}
IMDS_RETRY_DELAY_SECONDS=${IMDS_RETRY_DELAY_SECONDS:-1}
IMDS_ENDPOINT=${IMDS_ENDPOINT:-169.254.169.254}
Expand Down Expand Up @@ -49,34 +47,10 @@ function imdscurl() {
}

function get-token() {
local TOKEN_DIR="/tmp/imds-tokens/$(whoami)"
mkdir -p -m 0600 $TOKEN_DIR

# cleanup expired tokens
local DELETED_TOKENS=0
for TOKEN_FILE in $(ls $TOKEN_DIR | awk '$0 < '$(($CURRENT_TIME - $IMDS_MAX_TOKEN_TTL_SECONDS))); do
rm $TOKEN_DIR/$TOKEN_FILE
DELETED_TOKENS=$(($DELETED_TOKENS + 1))
done
if [ "$DELETED_TOKENS" -gt 0 ]; then
log "🗑️ Deleted $DELETED_TOKENS expired IMDS token(s)."
fi

local TOKEN_FILE=$(ls $TOKEN_DIR | awk '$0 > '$CURRENT_TIME | sort -n -r | head -n 1)

if [ "$TOKEN_FILE" = "" ]; then
TOKEN_FILE=$(($CURRENT_TIME + $IMDS_TOKEN_TTL_SECONDS))
local TOKEN=$(imdscurl \
-H "X-aws-ec2-metadata-token-ttl-seconds: $IMDS_TOKEN_TTL_SECONDS" \
-X PUT \
"http://$IMDS_ENDPOINT/latest/api/token")
echo "$TOKEN" > "$TOKEN_DIR/$TOKEN_FILE"
chmod 0600 "$TOKEN_DIR/$TOKEN_FILE"
log "🔑 Retrieved a fresh IMDS token that will expire in $IMDS_TOKEN_TTL_SECONDS seconds."
else
log "ℹ️ Using cached IMDS token that expires in $(($TOKEN_FILE - $CURRENT_TIME)) seconds."
fi
cat "$TOKEN_DIR/$TOKEN_FILE"
imdscurl \
-H "X-aws-ec2-metadata-token-ttl-seconds: $IMDS_TOKEN_TTL_SECONDS" \
-X PUT \
"http://$IMDS_ENDPOINT/latest/api/token"
}

function get-with-token() {
Expand Down
3 changes: 1 addition & 2 deletions scripts/cleanup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ sudo rm -rf \
/var/log/secure \
/var/log/wtmp \
/var/log/messages \
/var/log/audit/* \
/tmp/imds-tokens
/var/log/audit/*

sudo touch /etc/machine-id
69 changes: 0 additions & 69 deletions test/cases/imds-token-refresh.sh

This file was deleted.

0 comments on commit 97233b3

Please sign in to comment.