Skip to content

Instantly share code, notes, and snippets.

@k-oguma
Last active March 29, 2018 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k-oguma/7d3bb6d2b27ef23680a569b84cd7470e to your computer and use it in GitHub Desktop.
Save k-oguma/7d3bb6d2b27ef23680a569b84cd7470e to your computer and use it in GitHub Desktop.
AWS IAM STS Wrapper
# aws-IAM-STS.sh
## Description
This tool is AWS STS (AWS Security Token Service) Wrapper for safety accesss control.
Example, developmnent or test access.
By using this, it becomes possible to test safely,
for example by wrapping the local development environment at the weak IAM authority.
[AWS-Doc/STS/ja-JP](http://docs.aws.amazon.com/ja_jp/IAM/latest/UserGuide/id_credentials_temp.html)
[AWS-Doc/STS](http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html)
## Requirements
### AWS CLI
- awscli
example
```
brew install awscli
```
### Default AWS Credential
- Default your AWS credentials
- You need to obtain and set up in advance
- exapmle
```
% cat ~/.aws/credentials
[default]
aws_access_key_id = XXXXXXXX
aws_secret_access_key = XXXXXXXXXX
```
### Weak privilege IAM role is required separately.
- This is for STS lap.
- You need to prepare to create weak the IAM roles, it empowers your authority control.
- [The setting page (AWS IAM)](https://console.aws.amazon.com/iam/home?#/roles)
### Configure into the your environment variables
```
export ACCOUNT_ID=XXXXXXXX # Get ID from https://console.aws.amazon.com/organizations/home?region=us-east-2#/accounts
export ROLE='<Role name of STS>' # Create and configure at https://console.aws.amazon.com/iam/home#/home
```
- example
- Direnv or ~/.bash_profile or ~/.zshrc or etc
## Usage
### Help
```
bash ./aws-IAM-STS.sh [-h|--help]
```
### Test. Check to STS
```
bash ./aws-IAM-STS.sh [-t|--test]
```
### Exceute command on the STS
```
bash ./aws-IAM-STS.sh <Command of related to AWS>
```
example
```
% bash ./aws-IAM-STS.sh aws sts get-caller-identity
{
"UserId": "XXXXXXXXXX:<your-name>",
"Account": "XXXXXXXXXX",
"Arn": "arn:aws:sts::XXXXXXXXXX:assumed-role/<weak-role>/<your-name>"
}
./aws-IAM-STS.sh command is Successful.
```
## [Optional] When you want to change this to a command
example
```
chmod u+x ./aws-IAM-STS.sh
mv ./aws-IAM-STS.sh /usr/local/bin/aws-IAM-STS
aws-IAM-STS --help
```
#!/bin/bash
# -BEGIN USAGE-
#
# This tool configures STS on the AWS Client.
# This support GNU-based Mac on the premise.
# Maybe that runs on either Linux too.
#
# Options are:
# -h|--help display this help and exit
# -t|--test check assgin role
# -v|--version output version information and exit
#
# Configure:
# This is set by the environment variable.
#
# export ACCOUNT_ID=XXXXXXXX # Get ID from https://console.aws.amazon.com/organizations/home?region=us-east-2#/accounts
# export ROLE='<Role name of STS>' # Create and configure at https://console.aws.amazon.com/iam/home#/home
#
# [Memo] It is recommended to use Direnv etc.
#
# Optional:
# export user="foo" # If a username is different from the username used in AWS, please change it. (Default: Your name)
#
# Example: bash aws-IAM-STS.sh aws get-account-summary
#
# -END USAGE-
SCRIPT_VERSION=0.1
readonly STS_SESSIOIN_FILE='/tmp/.stssession'
ERR_MSG_NO_STS="Error: It is no STS you specified."
ERR_MSG_NO_CONF="Please setting environment variables."
STD_MSG_SUCCESS="Successful."
CONFIG_SET=(ACCOUNT_ID ROLE)
usage() {
echo "Usage: $0 [options]"
sed -ne '/-BEGIN\ USAGE-/,/-END USAGE-/s/^#//p' $0 | awk 'NR==2,NR==24 {print $0}'
exit $1
}
# Configure check
for env_var in ${CONFIG_SET[@]}
do
[ "$(eval echo \$$env_var)" ] || {
echo -e "\e[31mConfigurationError: ${env_var} is not found.\e[m";
echo -e "\e[31m${ERR_MSG_NO_CONF}\e[m";
echo; usage 1;
}
done
create_sts() {
AR=$(aws sts assume-role --role-arn arn:aws:iam::${ACCOUNT_ID}:role/${ROLE} --role-session-name "${user:-$USER}");
echo $AR > ${STS_SESSIOIN_FILE};
}
expire_check_if_file_exists() {
[[ $(expr $(cat ${STS_SESSIOIN_FILE} | jq -r '.Credentials.Expiration | fromdate') - $(date +'%s')) -gt 0 ]] && {
AR=$(cat ${STS_SESSIOIN_FILE});
}
# ${STS_SESSIOIN_FILE} の Credentials.Expiration 情報が古ければ更新する
[ "x$AR" = "x" ] && create_sts
}
# The STS session's create or update.
# sts session file が存在しない、もしくは存在しても空ファイルの場合は、新規に作成する
# ファイルが存在する場合は期限を確認して必要があれば再作成を行う
sts_session_manager() {
[ ! -f "${STS_SESSIOIN_FILE}" -o ! -s "${STS_SESSIOIN_FILE}" ] && {
create_sts;
}
[ "x$AR" = "x" ] && expire_check_if_file_exists
}
# getops とか使わないでロングオプション対応
for opt in "$1"
do
case $opt in
-t|--test)
# Identity's check
#
# Example
# % bash aws-IAM-STS.sh aws sts get-caller-identity
# {
# "UserId": "XXXXXXXXXX:${USER}",
# "Account": "${ACCOUNT_ID}",
# "Arn": "arn:aws:sts::${ACCOUNT_ID}:assumed-role/${ROLE}/$USER"
# }
# STS を通しているなら ARN が sts::${ACCOUNT_ID}:assumed-role/${ROLE}/$USER の形でSTDOUTされます。
# もし、STSを使用していない通常のAWS へのアクセスの場合は、上記のARN 例にある assumed-role/${ROLE} がありません。
# その差を利用して正常性を判定しています。
sts_session_manager
echo "You has set $ROLE into \$ROLE."
[[ "$(bash $0 aws sts get-caller-identity | jq .Arn)" =~ "${ROLE}" ]] > /dev/null 2>&1 || {
echo -e "\e[31m${ERR_MSG_NO_STS}\e[m";
exit 2;
}
bash $0 aws sts get-caller-identity
echo
echo -e "\e[1;36m${STD_MSG_SUCCESS} Test result is no error.\e[m";
exit 0
;;
-h|--help)
usage 0;
;;
-v|--version)
echo -e "\e[1;36m$0 -- Version $SCRIPT_VERSION\e[m";
exit 0
;;
*)
;;
esac
done
## STS's role assign
sts_session_manager
AWS_SECRET_ACCESS_KEY=$(echo $AR| jq -r .Credentials.SecretAccessKey) \
AWS_ACCESS_KEY_ID=$(echo $AR | jq -r .Credentials.AccessKeyId) \
AWS_SESSION_TOKEN=$(echo $AR | jq -r .Credentials.SessionToken) \
$@
[ $? -eq 0 ] && echo -e "\e[1;36m$0 command is ${STD_MSG_SUCCESS}\e[m"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment