AWSLogin.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268

Function SHA256{
  Param
  (
    [String]$String
  )

  $StringBuilder = New-Object -TypeName System.Text.StringBuilder
  [System.Security.Cryptography.HashAlgorithm]::Create( 'SHA256' ).ComputeHash( [System.Text.Encoding]::Unicode.GetBytes( $String ) ) | ForEach-Object {
    [Void]$Builder.Append( $_.ToString( 'x2' ) )
  }
  $StringBuilder.ToString().ToLower()
}

Function Get-AWSToken
{
  <#
    .SYNOPSIS
    Gets an AWS token via STS.

    .DESCRIPTION
    Gets an AWS token via STS. Tokens are suitable for use in API
    calls, including use of AWS CLI. By default token data is written
    to environment variables.

    .PARAMETER Profile
    Stored profile to load parameters from. Profiles are defined in
    AWSLogin.csv, in the module directory, $env:APPDATA, or
    Documents. Format "Name","OktaAppURI","RoleARN","PrincipalARN".

    .PARAMETER OktaAppURI
    The full URI to the Okta app instance. This is the URI one would
    navigate to if clicking on the application instance in the Okta
    portal.

    .PARAMETER RoleARN
    Full ARN of the AWS role to assume.

    .PARAMETER PrincipalARN
    Full ARN of the AWS-integrated Identity Provider to use.

    .EXAMPLE
    Get-AWSToken -Profile MyProfile
    
    .EXAMPLE
    Get-AWSToken `
      -OktaAppURI 'https://mycompany.okta.com/home/SomeApp/AppID/Instance' `
      -RoleARN 'arn:aws:iam::XXXXXXXXXXXX:role/RoleToAssume' `
      -PrincipalARN 'arn:aws:iam::XXXXXXXXXXXX:saml-provider/MySAMLProvider'

    .EXAMPLE
    Get-AWSToken -OktaAppURI 'https://mycompany.okta.com/home/SomeApp/AppID/Instance'
    
    .LINK
    https://github.com/bad2beef/AWSLogin
  #>


  [CmdletBinding()]
  Param
  (
    [Parameter(ParameterSetName='Manual', Mandatory=$true)]
    [String]$OktaAppURI,

    [Parameter(ParameterSetName='Manual')]
    [String]$RoleARN,

    [Parameter(ParameterSetName='Manual')]
    [String]$PrincipalARN,

    [System.Management.Automation.PSCredential]$Credential = ( Get-Credential ),

    [ValidateSet(
      'call',
      'push',
      'sms',
      'token:software:totp'
    )]
    [String]$MFAType = 'push',
    [String]$MFACode,

    [Parameter(DontShow)]
    [String]$STSEndpoint = 'https://sts.amazonaws.com/'
  )

  DynamicParam
  {
    $ParameterAttribute = New-Object -TypeName System.Management.Automation.ParameterAttribute
    $ParameterAttribute.Mandatory = $true
    $ParameterAttribute.Position = 1
    $ParameterAttribute.ParameterSetName = 'Profile'
    
    $AttributeCollection = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute]
    $AttributeCollection.Add( $ParameterAttribute )

    $ConfigPaths = @( # Must declare in Process as well
      ( ( Get-Module -ListAvailable 'AWSLogin' ).Path | Split-Path ),
      $env:APPDATA,
      [Environment]::GetFolderPath( 'MyDocuments' )
    )

    $Profiles = @()
    ForEach ( $ConfigPath in $ConfigPaths )
    {
      $ProfilePath = ( '{0}\AWSLogin.csv' -f @( $ConfigPath ) )
      If ( Test-Path -Path $ProfilePath -ErrorAction SilentlyContinue )
      {
        $Profiles = Import-Csv -Path $ProfilePath | Select-Object -ExpandProperty Name
      }
    }

    $AttributeCollection.Add( ( New-Object -TypeName System.Management.Automation.ValidateSetAttribute( $Profiles ) ) )
    
    $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter( 'Profile', [String], $AttributeCollection )
    $RuntimeParameterDictionary = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameterDictionary
    $RuntimeParameterDictionary.Add( 'Profile', $RuntimeParameter )

    return $RuntimeParameterDictionary
  }

  Process
  {
    # Verify AWS CLI command exist as we use it to get a token later.
    Try
    {
      Get-Command -Name 'aws' | Out-Null
    }
    Catch
    {
      Write-Error '''aws'' command not found.'
      return
    }

    # Load Profile if needed
    If ( $PsBoundParameters.Profile ){
      $ProfileDefinition = $null

      $ConfigPaths = @( # Must declare in DynamicParam as well
        ( ( Get-Module -ListAvailable 'AWSLogin' ).Path | Split-Path ),
        $env:APPDATA,
        [Environment]::GetFolderPath( 'MyDocuments' )
      )

      ForEach ( $ConfigPath in $ConfigPaths )
      {
        $ProfilePath = ( '{0}\AWSLogin.csv' -f @( $ConfigPath ) )
        If ( Test-Path -Path $ProfilePath -ErrorAction SilentlyContinue )
        {
          $ProfileDefinition = Import-Csv -Path $ProfilePath | Where-Object { $_.Name -like $PsBoundParameters.Profile }
        }
      }

      If ( $ProfileDefinition )
      {
        $OktaAppURI = $ProfileDefinition.OktaAPPUri
        $RoleARN = $ProfileDefinition.RoleARN
        $PrincipalARN = $ProfileDefinition.PrincipalARN
      }
      Else
      {
        Write-Error ( 'Profile ''{0}'' not found.' -f @( $PsBoundParameters.Profile ) )
        return
      }
    }

    # Validate OKTA App URI. Must be https://domain.okta.com/some/app/path/id (ish)
    If ( -not ( $OktaAppUri -match '^https\:\/\/[\w\d\-\.]+[\w\d\-\/]+$' ) )
    {
      Write-Error 'Invalid Okta App URI.'
      return
    }

    $OktaDomain = $OktaAppUri.Split( '/' )[2]

    Write-Verbose 'Getting Okta session token.'
    $OktaSessionToken = Get-OktaSessionToken -OktaDomain $OktaDomain -Credential $Credential -MFAType $MFAType -MFACode $MFACode
    If ( -not $OktaSessionToken )
    {
      Write-Error 'Could not obtain session token.'
      return
    }

    Write-Verbose 'Getting Okta SAML assertion.'
    $OktaSAMLAssertion = Get-OktaSAMLAssertion -OktaAppURI $OktaAppURI -OktaSessionToken $OktaSessionToken
    If ( -not $OktaSAMLAssertion )
    {
      Write-Error 'Could not obtain Okta SAML assertion.'
      return
    }

    # If no ARNs provided parse assertion for roles.
    If ( ( -not $RoleARN ) -or ( -not $PrincipalARN ) )
    {
      $OktaSAMLAssertionParsed = [XML][System.Text.Encoding]::UTF8.GetString( [System.Convert]::FromBase64String( $OktaSAMLAssertion ) )
      $PrincipalRolePairs = $OktaSAMLAssertionParsed.Response.Assertion.AttributeStatement.Attribute | Where-Object { $_.Name -like 'https://aws.amazon.com/SAML/Attributes/Role' } | Select-Object -ExpandProperty AttributeValue | Select-Object -ExpandProperty '#text' | Sort-Object
      
      [System.Collections.ArrayList]$Roles = @()
      ForEach ( $PrincipalRolePair in $PrincipalRolePairs )
      {
        $Roles.Add( @( $PrincipalRolePair.Split( ',' ) ) ) | Out-Null
      }
      
      $RoleIndex = 0
      If ( -not $Roles.Count )
      {
        Write-Error 'SAML assertion contains no identifiable roles.'
        return
      }
      ElseIf ( $Roles.Count -gt 1 )
      {
        Write-Host 'Select a role to assume.'
        $LastAccount = $Null
        For ( $Index = 0 ; $Index -lt $Roles.Count ; $Index++ )
        {
          $RoleParts = $Roles[ $Index ][1].Split( ':' )
          If ( $RoleParts[4] -notlike $LastAcount )
          {
            $LastAccount = $RoleParts[4]
            Write-Host ''
            Write-Host ( ' Account {0}' -f @( $RoleParts[4] ) )
          }
          Write-Host ( ' {0,2}: {1}' -f @( ( $Index + 1 ), $RoleParts[5].Substring(5) ) )
        }

        Write-Host ''
        [Int]$RoleIndex = Read-Host -Prompt ( 'Role ({0}-{1})' -f @( 1, $Roles.Count ) )
        If ( ( $RoleIndex -lt 1 ) -or ( $RoleIndex -gt $Roles.Count ) )
        {
          Write-Error 'Invalid role index.'
          return
        }
        Else
        {
          $RoleIndex--
        }
      }

      Write-Verbose ( 'Assuming role with ARN "{0}" via IdP "{1}"' -f @( $Roles[ $RoleIndex  ][1], $Roles[ $RoleIndex ][0] ) )

      $PrincipalARN = $Roles[ $RoleIndex ][0]
      $RoleARN = $Roles[ $RoleIndex ][1]
    }

    Write-Verbose 'Getting AWS token.'
    $RequestBody_PrincipalARN = [uri]::EscapeDataString( $PrincipalARN )
    $RequestBody_RoleARN = [uri]::EscapeDataString( $RoleARN )
    $RequestBody_SAML = [uri]::EscapeDataString( $OktaSAMLAssertion )

    [XML]$Response = Invoke-RestMethod `
      -Method Post `
      -Uri 'https://sts.amazonaws.com/' `
      -Body ( 'Action=AssumeRoleWithSAML&Version=2011-06-15&PrincipalArn={0}&RoleArn={1}&SAMLAssertion={2}' -f @( $RequestBody_PrincipalARN, $RequestBody_RoleARN, $RequestBody_SAML ) )

    # If we have SecretAccessKey, it all worked. Set in ENV to avoid persistence of creds on disk.
    If ( $Response.AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.SecretAccessKey )
    {
      $env:AWS_ACCESS_KEY_ID   = $Response.AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.AccessKeyId
      $env:AWS_SECRET_ACCESS_KEY = $Response.AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.SecretAccessKey
      $env:AWS_SESSION_TOKEN   = $Response.AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.SessionToken
      Write-Verbose ( 'Assumed role {0}' -f @( $Response.AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.AssumedRoleUser.Arn ) )
    }
    Else
    {
      Write-Warning $Response.GetElementsByTagName( 'Message' )
      Write-Error 'Could not obtain a token.'
    }
  }
}