Forcing PowerShell scripts to use AWS MFA

Finally, I get to do some “real” AWS work.

The first step is to have a IAM policy that restricts access to operations unless you have a MultiFactorAuthentication token in your userIdentity.

The policy I created is below:

 

{
 "Version": "2012-10-17",
 "Statement": [
 {
    "Sid": "DenyWhenMFAIsNotPresent",
    "Effect": "Deny",
    "NotAction": "iam:ListMFADevices",
    "Resource": "*",
    "Condition": {
     "BoolIfExists": {
      "aws:MultiFactorAuthPresent": false
       }
     }
  }
 ]
}

AWS is always changing and evolving, and improving their documentation. AWS has more options listed on their document page.

If you have your PowerShell set up to run with multiple credentials, it’s easy to switch between them, you have to get a temporary token by calling Get-STSSessionToken



Get-AWSCredential -ListProfileDetail
# Changes context to run as that id, same as -credential on all aws commands
Set-AWSCredential -ProfileName <whatever>

# saves credentail for future use
Set-AWSCredential -ProfileName <whatever> -StoreAs <something>
# sets up a new session to use MFA session
$MFASession=Get-STSSessionToken -SerialNumber (Get-IAMMFADevice).SerialNumber -TokenCode  <CurrentMFAToken>
# Now use it or do -credential $MFASession.credentials on any AWS call that needs this
Set-AWSCredential -Credential $MFASession
$MFASession=Get-STSSessionToken -SerialNumber (Get-IAMMFADevice).SerialNumber -TokenCode
Set-AWSCredential -Credential $MFASession


Leave a comment