Retrieving Credentials in a PowerShell Session
- Kim Landis (Unlicensed)
- Patrick Parker
Granting permanent elevated privileges to your admins represents an open security vulnerability. You can avoid this by using vaulted admin credentials in EmpowerID so that usernames and passwords are stored in a secure, encrypted password vault. When your system admins require elevated privileges for use in a PowerShell script, the EmpowerID system retrieves the credentials and generates a PSCredential object for them to use.
This topic shows how non-admins can retrieve shared admin credentials from EmpowerID for use in your PowerShell scripts.
Prerequisites
Create a shared credential in EmpowerID. For more information, see Vaulting Non-Computer Credentials.
To create an OAuth client application (one time setup)
- In the Navigation Sidebar, expand Admin, then SSO Connections, and click OAuth.
- In the EmpowerID OAuth Client Apps tab of the OAuth page, click the Add button above the grid.
In the OAuth Provider Application Details page that appears, enter information in the fields about the application for which you want to share credentials to use in your PowerShell script.
For more information on OAuth applications, see Creating an OAuth Application for Andy's Beans.
- Scroll to the bottom and click Save. When it finishes, click the Find Apps link in the breadcrumbs to return to the list of OAuth Client Apps.
- Find your app in the list and click the Name value to open the OAuth Provider Application Details page.
- The Connection Details section contains the values that you can copy for use in the PowerShell script:
- Client ID (Key) – copy this value to use for the $ClientID
- Client Secret – copy this value to use for the $ClientSecret
- API Key – copy this value to use for the $APIKey
To create a PowerShell script to retrieve the credentials
In Windows PowerShell ISE (or any text editor), paste the following script:
##Configuration $ClientID = 'xxx' $ClientSecret = 'xxx' $APIKey = 'xxx' $RedirectURL = 'https://sso.empoweriam.com/EmpowerIDWebIdPForms/OAuth/V2' $TokenURL = 'https://sso.empoweriam.com/oauth/v2/token' $CheckoutURL ='https://sso.empoweriam.com/api/services/v1/password/checkoutcredential' $GetCredentialURL = 'https://sso.empoweriam.com/api/services/v1/password/getexternalcredential' $SearchURL = 'https://sso.empoweriam.com/api/webui/v1/ExternalCredentialView/GetAllSearch' $Debug = $TRUE ##Null check function function IsNull($objectToCheck) { if ($objectToCheck -eq $null) { return $true } if ($objectToCheck -is [String] -and $objectToCheck -eq [String]::Empty) { return $true } if ($objectToCheck -is [DBNull] -or $objectToCheck -is [System.Management.Automation.Language.NullString]) { return $true } return $false } ##Input from user $EidUsername = Read-Host 'What is your EmpowerID username?' $EidPassword = Read-Host 'What is your EmpowerID password?' -AsSecureString $MasterPassword = Read-Host 'What is your master password?' -AsSecureString $CredentialGuid = $NULL #Read-Host 'GUID of the credential?' #$EidPasswordPlain = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($EidPassword)) #$MasterPasswordPlain = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($MasterPassword)) #$Base64Credentials=[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($EidUsername+':'+[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($EidPassword)))) #get OAuth token Write-Host "Getting OAUTH token...." $AccessTokenheaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $AccessTokenheaders.Add("Content-Type", 'application/x-www-form-urlencoded') $AccessTokenheaders.Add("Authorization", 'Basic '+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($EidUsername+':'+[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($EidPassword))))) $AccessTokenheaders.Add("X-EmpowerID-API-Key", $APIKey) $AccessTokenBody = @{ client_id = $ClientID client_secret = $ClientSecret grant_type = "password" redirect_uri = $RedirectURL } $AccessTokenResponse = Invoke-RestMethod $TokenURL -Method Post -Body $AccessTokenBody -Headers $AccessTokenheaders if($Debug){ Write-Host ($AccessTokenResponse | Format-Table | Out-String) } if (IsNull($AccessTokenResponse.access_token)) { throw $AccessTokenResponse.error_description } #Search $CredentialDictionary = New-Object "System.Collections.Generic.Dictionary[[String],[Object]]" $NeedSearch = Read-Host "Do you have the guid of the credential, yes/no?" if($NeedSearch -eq "yes") { $CredentialGuid = Read-Host 'GUID of the credential?' } if($NeedSearch -eq "no") { $SearchHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $SearchHeaders.Add("Content-Type", 'application/json') $SearchHeaders.Add("Authorization", 'Bearer '+$AccessTokenResponse.access_token) $SearchHeaders.Add("X-EmpowerID-API-Key", $APIKey) $SearchText = Read-Host 'Enter the text to search' while($CredentialGuid -eq $NULL ) { $SearchBody = "{ 'TypeName':'ExternalCredentialView', 'MethodName': 'GetByCurrentPersonID', 'Parameters': { 'IsPSMPolicy' : false, 'ExternalCredentialPolicyID' : null, 'ResourceTags': null, 'ColumnsToSearch': '', 'TextToSearch': '$SearchText' }}" $SearchResponse = Invoke-RestMethod $SearchURL -Method Post -Body $SearchBody -Headers $SearchHeaders if($SearchResponse.Data -eq $NULL -Or $SearchResponse.Data.Count -eq 0 ) { $SearchText = Read-Host 'Your search did not return any results. Enter new text to search' continue } else { Write-Host ($SearchResponse.Data | Select-Object -Property ExternalCredentialID,FriendlyName,Name,Description | Format-Table | Out-String) $Selected = Read-Host "Did you find the credential you need? yes/no" if($Selected -eq "yes") { $ExternalCredentialID = Read-Host 'Enter the ID of the Credential you want to get' Foreach ($cred in $SearchResponse.Data) { if($cred.ExternalCredentialID -eq $ExternalCredentialID) { #Write-Host $cred.ExternalCredentialGUID $CredentialGuid = $cred.ExternalCredentialGUID break } } if($CredentialGuid -eq $NULL) { $SearchText = Read-Host 'The ID you entered did not match any of the entries! Please enter new text to search' } } else { $SearchText = Read-Host 'Enter new text to search' continue } } } } #Check out credentials Write-Host "Checking out credentials......" try{ $CheckoutHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $CheckoutHeaders.Add("Content-Type", 'application/json') $CheckoutHeaders.Add("Authorization", 'Bearer '+$AccessTokenResponse.access_token) $CheckoutHeaders.Add("X-EmpowerID-API-Key", $APIKey) $datetime = Get-Date $CheckoutBody="{ credential: '"+$CredentialGuid+"', datestart: '" + $datetime.ToUniversalTime() + "', durationinminutes: 10, justification: 'PowerShell' } " $CheckoutResponse = Invoke-RestMethod $CheckoutURL -Method Post -Body $CheckoutBody -Headers $CheckoutHeaders if($Debug){ Write-Host ($CheckoutResponse | Format-Table | Out-String) } if ($CheckoutResponse.Result -eq "WentForApproval") { Write-host "The checkout procedure went for approval" throw "The checkout procedure went for approval" } } catch{ throw $_.Exception.Response.StatusCode } try{ #Get Credentials Write-Host "Getting Credentials" $GetCredentialsHeaders = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $GetCredentialsHeaders.Add("Content-Type", 'application/json') $GetCredentialsHeaders.Add("Authorization", 'Bearer '+$AccessTokenResponse.access_token) $GetCredentialsHeaders.Add("X-EmpowerID-API-Key", $APIKey) $GetCredentialsBody="{'credential':'"+$CredentialGUID+"','password' : '"+[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($MasterPassword))+"'}" $GetCredentialsBody $GetCredentialsResponse = Invoke-RestMethod $GetCredentialURL -Method Post -Body $GetCredentialsBody -Headers $GetCredentialsHeaders if($Debug){ Write-Host ($GetCredentialsResponse | Format-Table | Out-String) } $secpasswd = ConvertTo-SecureString $GetCredentialsResponse.Password -AsPlainText -Force $global:CredentialsfromAPI = new-object -typename System.Management.Automation.PSCredential -argumentlist $GetCredentialsResponse.UserName,$secpasswd Write-Host "Credentials from the API call are saved in a PSCredential object CredentialsfromAPI" } catch { throw $_.Exception.Response.StatusCode } $CredentialsfromAPI
Replace the following values in the script:
$ClientID – replace the xxx with the GUID value from the Client ID (Key) of your OAuth application
$ClientSecret – replace the xxx with the GUID value from the Client Secret of your OAuth application
$APIKey – replace the xxx with the GUID value from the API Key of your OAuth application
- $RedirectURL – replace sso.empoweriam.com with the FQDN of your server
- $TokenURL – replace sso.empoweriam.com with the FQDN of your server
- $CheckoutURL – replace sso.empoweriam.com with the FQDN of your server
- $GetCredentialURL – replace sso.empoweriam.com with the FQDN of your server
- $SearchURL – replace sso.empoweriam.com with the FQDN of your server
- Save the file as GetCredentials.ps1.
To run the PowerShell file
- In File Explorer, right-click the saved file and select Run with PowerShell.
- PowerShell opens and prompts you for several values. Answer each and press Enter. The script retrieves the OAuth token.
- Once the token is retrieved, you are asked whether you have the GUID of the credential. If you respond yes, you must provide the GUID, otherwise, you are prompted to search for the credential. Here we respond yes.
- To copy the GUID for the credential:
- In the Navigation Sidebar, expand Resources and click Shared Credentials.
- Click the Credentials I Manage tab, and then click the display name of the credential we created above.
- In the Credential Details page, expand the Advanced section and copy the ExternalCredentialGUID value.
Paste this value at the PowerShell prompt and press Enter. PowerShell proceeds to check out the credentials.
If your PowerShell instance disappears instead of checking out the credentials, your server may not be set to allow you to execute scripts.
See About Execution Policies in the Microsoft PowerShell documentation to learn how to change your execution policy.
- The retrieved credentials are stored in a global variable: $credentialsfromREST.
- In EmpowerID, you can verify that the credentials are checked out on the Shared Credentials page, Credentials I Manage tab.