PowerShell

Getting Started Guide using REST APIs in PowerShell with Privileged Access Management.

This page outlines several specific scenarios in which REST APIs in PAM can be called using PowerShell scripts.

Please note that security is strictly enforced, so ensure the account executing the scripts has the appropriate permissions to access the objects in PAM.

In addition to this detailed guide you can also view the list of other functions you can call using REST API by navigating to Administration > Settings > Application Nodes > API Documentation.

Looking for REST API examples using other scripts? Click Shell examples, VBScript examples or Python examples for additional information.

 

The following scripts are provided as an example of what is possible, however they can and should be customized to meet your requirements including outside script integration, formatting and proper error handling.

Create a Record

Provides the ability to create a new record with the defined parameters.

Copy
$folderId="183320"   # ID of Parent Folder
$typeId = "1724"   #  ID of Record Type
$recordName = "Name"   # Record Name (required)
$recordDescription = "Description"  # Record Description (optional)

$rhost = "host.company.com"   # Host URL
$rport = "22"   # Host Port
$ruser = "user"   # Host User
$rpassword="myPassw0rd"   # Host Password

$rest = "$url/rest/record/new/$folderId/$typeId"

$Custom = '{{"Host":"{0}","Port":{1},"User":"{2}","Password":"{3}"}}' -f $rhost, $rport, $ruser, $rpassword

$Body = @{
    name = $recordName
    description = $recordDescription
    custom = $Custom
}

Invoke-RestMethod -Method Post  -ContentType 'application/x-www-form-urlencoded' -Headers @{'X-XSRF-TOKEN' = $apiToken} -Credential $mycreds -Uri "$($rest)" -Body $body

Write-Host Done

 

Create a Folder

Provides the ability to create a new folder with the defined parameters.

Copy
$folderId="183320"   # ID of Parent Folder
$folderName = "Name"   # Folder Name (required)
$folderDescription = "Description"   # Folder Description (optional)

$rest = "$url/rest/folder/create/$folderId"

$folder = @{
    name = $folderName
    description = $folderDescription
}

$body = $folder | ConvertTo-Json

Invoke-RestMethod -Method Post  -ContentType 'application/json' -Headers @{'X-XSRF-TOKEN' = $apiToken} -Credential $mycreds -Uri "$($rest)" -Body $body

Write-Host Done

 

Retrieve Root Folder

Provides the ability to retrieve the Root Folder (All Records) and its parameters including ID.

Copy
$rest = "$url/rest/folder/root"

Invoke-RestMethod -Method Get  -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

Write-Host Done

 

List Folder Content

Provides the ability to list all content of the specified folder.

Copy
$folderId="183320"    # Folder ID

$rest = "$url/rest/folder/list/$folderId"

Invoke-RestMethod -Method Get  -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

Write-Host Done

 

Retrieve a Record

Provides the ability to retrieve all the parameters of an existing record excluding the password.

Copy
$recordId="168351"   # Record ID

$rest = "$url/rest/record/get/" + $recordId

$secret= Invoke-RestMethod -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

$custom= $secret.custom | ConvertFrom-Json

Write-Output "$($secret.name): $($custom.User) / $($custom.Password)"

Write-Output $secret
Write-Output $custom
Write-Host Done

 

Retrieve a Record with Password Unlock

Provides the ability to retrieve all the parameters of an existing record including the password.

Copy
$recordId="168351"   # Record ID

$rest = "$url/rest/record/unlock/" + $recordId

$secret= Invoke-RestMethod -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

$custom= $secret.custom | ConvertFrom-Json

Write-Output "$($secret.name): $($custom.User) / $($custom.Password)"

Write-Output $secret
Write-Output $custom
Write-Host Done

 

Retrieve a Record Field Unlock

Provides the ability to retrieve a single parameter from a record’s field including the password.

Copy
$recordId="168351"   # Record ID
$field="Password"   # The (internal) Name of the field

$rest = "$url/rest/record/unlock/$recordId/" + $field

$secret= Invoke-RestMethod -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

Write-Output "$($field): $($secret)"
Write-Host Done

 

Update a Record

Provides the ability to update an existing record.

Copy
$recordId="183323"   # Record ID
$recordTypeId="e9uc9Av36zM" # Record Type ID
$RecordName = "Updated Name"   # Updated Record Name
$RecordDescription = "Updated Description"   # Updated Record Description

$rhost = "host1.company.com"   # Updated Host URL
$rport = "3389"   # Updated Host Port
$ruser = "user1"   # Updated Host User
$rpassword="myPassw0rd1"   # Updated Host Password

$password = $mycreds.GetNetworkCredential().password

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/record/update/$recordId"

$Custom = '{{"Host":"{0}","Port":{1},"User":"{2}","Password":"{3}"}}' -f $rhost, $rport, $ruser, $rpassword

Write-Host $Custom

$Body = @{
    name = $RecordName
    description = $RecordDescription
    custom = $Custom
    rtid = $recordTypeId
}

Invoke-RestMethod -Method Put  -ContentType 'application/x-www-form-urlencoded'  -Credential $mycreds -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken} -Uri "$($rest)" -Body $body

Write-Host Done

 

Download a File

Provides the ability to download a file (certificate, SSH key, secured file) associated to a record.

Copy
$recordId="183323"   # Record ID
$fieldName = "Cert"   # Internal Name of Field that contains the file

$rest = "$url/rest/record/unlock/" + $recordId

$secret= Invoke-RestMethod -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

$custom= $secret.custom | ConvertFrom-Json
$file= $custom.$fieldName
$fileName= $file.name

$dwnld = "$url/rest/content/record/$recordId/$fieldName"
$output = "C:\Folder\" + $fileName   # Save To Location

Invoke-WebRequest -Credential $mycreds -Uri $dwnld -OutFile $output

Write-Output Done

 

Share a Record or Folder

Provides the ability to share a record or folder with other users or groups.

Copy
$shareUser = "user"   # Share object with User or Group Login

$rest = "$url/rest/user/ensure/$shareUser"
$shareUserId = Invoke-RestMethod -Method Get  -ContentType 'application/x-www-form-urlencoded' -Credential $mycreds -Uri "$($rest)"

$objectId="186460"   # Record or Folder ID to Share
$userId = $shareUserId.id
$recordControl = "View"   # Permission Options: View / Unlock / Edit / Admin
$sessionControl = "None"   # Permission Options: None / Recording / Connect
$taskControl = "None"   # Permission Options: None / Execute / Review / Manage

$rest = "$url/rest/permissions/share/$objectId/$userId/$recordControl/$sessionControl/$taskControl"

Invoke-RestMethod -Method Post  -ContentType 'application/json' -Headers @{'X-XSRF-TOKEN' = $apiToken} -Credential $mycreds -Uri "$($rest)"

Write-Host Done

 

Delete a Record

Provides the ability to delete an existing record.

Copy
$recordId="186008"   # Record ID to Delete
$folderId="183320"   # Parent Folder ID

$password = $mycreds.GetNetworkCredential().password

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/record/delete/$folderId/$recordId"

Invoke-RestMethod -Method Delete -ContentType 'application/json' -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken } -Uri "$($rest)"

Write-Host Done

 

Look up for Objects

Search for Objects (Record or Folder).

Provides the ability to search for existing objects, like records or folders, using search query types.

A list of query types can be found here and will allow you to target specific objects like folders, ACLs or shadow accounts. For example, if you use the search term folder:Production, it will return all folders found using the term Production.

Copy
$searchTerm = "object name"   # Value to Search

$rest = "$url/rest/record/find/View/$searchTerm"

$secret=Invoke-RestMethod -Method Get  -ContentType 'application/json'  -Credential $mycreds -Uri "$($rest)"

Write-Host Results:
foreach ($results in $secret){ 
Write-Host "Object Name:" $results.name "( Object ID:" $results.id")"
}

Write-Host Search Complete

 

List Record Types

Provides the ability to output a list of all currently available Record Types.

Copy
$rest = "$url/rest/recordtype/list"

Invoke-RestMethod -Method Get  -ContentType 'application/json' -Credential $mycreds -Uri "$($rest)"

Write-Host Done

 

Database Export Decrypted

Provides the ability to export the PAM database to a decrypted file(s).

Copy
$password = $mycreds.GetNetworkCredential().password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/application/export/false"

Invoke-RestMethod -Method Put  -ContentType 'application/json' -Credential $mycreds -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken } -Uri "$($rest)"

Write-Host Done

 

Database Export Encrypted

Provides the ability to export the PAM database to an encrypted file(s).

Copy
$password = $mycreds.GetNetworkCredential().password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/application/export/true"

Invoke-RestMethod -Method Put  -ContentType 'application/json' -Credential $mycreds -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken } -Uri "$($rest)"

Write-Host Done

 

Database Import

Provides the ability to import an exported PAM database file.

Copy
$exportName="xtamexp-20180313152316-120"  # Export file name

$password = $mycreds.GetNetworkCredential().password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))

$rest = "$url/rest/application/import/$exportName"
Invoke-RestMethod -Method Put  -ContentType 'application/json' -Credential $mycreds -Headers @{Authorization = "Basic $base64AuthInfo"; 'X-XSRF-TOKEN' = $apiToken } -Uri "$($rest)"

Write-Host Done

 

API Token

To provide protection against Cross-Site Request Forgery (CSRF) attacks each PAM API function that changes something in the system (mostly, POST, PUT and DELETE REST methods) requires an API Token passed using X-XSRF-TOKEN header. To obtain a token, an PAM REST client has to request it from PAM server by calling /rest/user/whoami function that sets XSRF-TOKEN cookie with the value of the token. Below is the example of PowerShell functions that obtain the API token from PAM server by the server base URL and credentials (ApiToken) or a session (ApiTokenCas) objects depending on the style of the authentication. See examples of using this token in the code samples above.

Copy
Function ApiTokenCas() {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)] $session,
        [Parameter(Mandatory=$true)] $url
    )

    process {
        $rest = "$url/rest/user/whoami"
        $resp=Invoke-RestMethod -WebSession $session -Method Get -Uri $rest -MaximumRedirection 5

        $session.Cookies.getCookies($rest) | % { if ($_.Name -eq 'XSRF-TOKEN') { $apiToken = $_.Value } }
        return $apiToken
    }
}

Function ApiToken() {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)] $creds,
        [Parameter(Mandatory=$true)] $url
    )

    process {
        $rest = "$url/rest/user/whoami"
        $resp=Invoke-RestMethod -Credential $creds -Method Get -Uri $rest -MaximumRedirection 5

        $session.Cookies.getCookies($rest) | % { if ($_.Name -eq 'XSRF-TOKEN') { $apiToken = $_.Value } }
        return $apiToken
    }
}

 

API token enforcement could be disabled by defining parameter xtam.api.token.verification=false

Secure Authentication

PAM provides several methods for authenticating, first is a standard, non-federated username and password login, the second is a form-based login method, the third is a more robust federated login experience that supports multi-factor authentication and additional options and the fourth is using Authentication Tokens. Depending on how your PAM installation is configured, the following authentication methods will be used.

 

Standard Authentication (non-federated)

If your login experience to PAM is a simple prompt like the one shown below, then you will use the following to authenticate using our REST APIs.

 

NoCAS-Login

 

Copy
$url= "http://localhost:8080/xtam"   # PAM URL
$user = "admin"   # PAM User

$mycreds= Get-Credential $user

# Your code starts here

 

 

Form-Based Authentication

If your login experience to PAM is a form-based login page like the one shown below, then you will use the following to authenticate using our REST APIs.

 

Form-Based-Login-Page

 

Copy
$base= "https://pam.company.com/xtam"   # PAM URL
$UserName="admin"   # PAM User
$Password="myPassword"   # PAM Password
$body=@{j_username=$UserName;j_password=$Password}
$step1=Invoke-RestMethod -Uri "$($base)/rest/user/whoami" -SessionVariable 'session'
$step2=Invoke-RestMethod -Method Post -Uri "$($base)/j_security_check" -Body $body -WebSession $session 

# Your code starts here

 

Copy
Invoke-RestMethod -WebSession $session ... # Form-Based Authentication Invoke-RestMethod cmdlet requires a web request session

 

Federated Authentication

If your login experience to PAM is a federated sign-in page like the one shown below, then you will use the following to authenticate using our REST APIs.

CAS-Login

 

Copy
Function CasAuth() {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)] $Base,
        [Parameter(Mandatory=$true)] $CasBase,
        [Parameter(Mandatory=$true)] $UserName,
        [Parameter(Mandatory=$true)] $Password
    )

    process {
        # post credentials
        $body=@{username=$UserName;password=$Password}
        $resp=Invoke-WebRequest -Method Post -Uri "$($CasBase)/v1/tickets" -Body $body -SessionVariable 'session'

        # get service ticket
        If($resp.Headers.Location.GetType() -Eq [string]) {
            $st=Invoke-WebRequest -Method Post -Uri $resp.Headers.Location -Body "service=$($Base)/"
        } Else {
            $st=Invoke-WebRequest -Method Post -Uri $resp.Headers.Location[0] -Body "service=$($Base)/"
        }

        # get authenticated session using service ticket
        $resp=Invoke-WebRequest -Uri "$Base/?ticket=$st" -SessionVariable 'session'

        return $session
    }
}

$url="https://pam.company.com/xtam"   # PAM URL
$cas_url="https://pam.company.com/cas"   # PAM Signin Page URL

$user = "admin"   # PAM User

$mycreds=Get-Credential $user
$password=$mycreds.GetNetworkCredential().password
$session=CasAuth -Base $url -CasBase $cas_url -UserName $user -Password $password

# Your code starts here

 

Copy
Invoke-RestMethod -WebSession $session ... # Federated Authentication Invoke-RestMethod cmdlet requires a web request session

 

Token Authentication

If you are using Authentication Tokens, then you will use the following to authenticate using our REST APIs.

Copy
Function TokenAuth() {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)] $Base,
        [Parameter(Mandatory=$true)] $CasBase,
        [Parameter(Mandatory=$true)] $Token
    )
    
    process {
       try {
           $resp=Invoke-WebRequest -Method Get -Uri "$($CasBase)/login?service=$Base/" -Headers @{"token"="$Token"} -SessionVariable 'session' -UseBasicParsing -MaximumRedirection 0 -ErrorAction Ignore
           If($resp.Headers.Location.GetType() -Eq [string]) {
              $loc=$resp.Headers.Location
           } Else {
              $loc=$resp.Headers.Location[0]
           }
       } catch {
           $loc=$_.Exception.Response.Headers.Location
       }
       $resp=Invoke-WebRequest -Uri "$loc" -SessionVariable 'session'
       
       return $session
    }
}

$url="https://pam.company.com/xtam"   # PAM URL
$cas_url="https://pam.company.com/cas"   # PAM Signin Page URL

$token = "yourXTAMtoken"   # PAM Token

$session=TokenAuth -Base $url -CasBase $cas_url -Token $token

# Your code starts here

 

Copy
Invoke-RestMethod -WebSession $session ... # Token Authentication Invoke-RestMethod cmdlet requires a web request session