Skip to content

Instantly share code, notes, and snippets.

@chrishoffman
Last active September 17, 2021 14:25
Show Gist options
  • Save chrishoffman/f5ab74297c6a91c3da51b880dd5a709c to your computer and use it in GitHub Desktop.
Save chrishoffman/f5ab74297c6a91c3da51b880dd5a709c to your computer and use it in GitHub Desktop.
Demonstrating Vault MFA on login paths
#!/bin/bash
## Tools required
# brew install oath-tools qrencode jq
# Vault Enterprise binary in the PATH
## Vault Server Command (separate terminal)
# VAULT_LICENSE=<vault license> vault server -dev -dev-root-token-id=root
export VAULT_ADDR=http://127.0.0.1:8200
export VAULT_TOKEN=root
TOTP_NAME=my_totp
TOTP_DIGITS=6
TOTP_ALGORITHM=SHA256
TOTP_PERIOD=30
TOTP_ISSUER=Vault
# Set up userpass
vault auth enable userpass
vault write auth/userpass/users/test_user password="password"
USERPASS_ACCESSOR=$(vault auth list -format=json | jq -r '.["userpass/"].accessor')
# Create MFA key
vault write sys/mfa/method/totp/$TOTP_NAME issuer=$TOTP_ISSUER algorithm=$TOTP_ALGORITHM digits=$TOTP_DIGITS period=$TOTP_PERIOD
# Create policy
POLICY="import \"mfa\"
main = rule {
mfa.methods.$TOTP_NAME.valid
}
"
vault write sys/policies/egp/totp-mfa \
policy=- \
paths="auth/userpass/login/*" \
enforcement_level="hard-mandatory" <<< $POLICY
# Generate an identity
ENTITY_ID=$(vault write -f -format=json identity/entity | jq -r .data.id)
# Attach entity to user
vault write identity/entity-alias name=test_user canonical_id=$ENTITY_ID mount_accessor=$USERPASS_ACCESSOR
# Attached MFA to Entity
MFA_CONFIG=$(vault write -f -format=json sys/mfa/method/totp/$TOTP_NAME/admin-generate entity_id=$ENTITY_ID)
MFA_SECRET=$(jq -r .data.url <<< $MFA_CONFIG | \
cut -d'=' -f6)
# Display QR code, cannot use URL returned since Google Authenticator seems to require the secret
# to be the first parameter
MFA_URL="otpauth://totp/$TOTP_ISSUER:$ENTITY_ID?secret=$MFA_SECRET&issuer=$TOTP_ISSUER&algorithm=$TOTP_ALGORITHM&digits=$TOTP_DIGITS&period=$TOTP_PERIOD"
qrencode -t ansiutf8 <<< $MFA_URL
# Generate TOTP code
MFA_CODE=$(oathtool --totp=$TOTP_ALGORITHM --time-step-size=$TOTP_PERIOD --base32 $MFA_SECRET)
# Should fail
VAULT_TOKEN= vault write auth/userpass/login/test_user password=password
# Should succeed
VAULT_TOKEN= vault write -mfa $TOTP_NAME:$MFA_CODE auth/userpass/login/test_user password=password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment