public/New-VPASPSMSession.ps1

<#
.Synopsis
   CONNECT WITH PSM
   CREATED BY: Vadim Melamed, EMAIL: vmelamed5@gmail.com
.DESCRIPTION
   USE THIS FUNCTION TO MAKE A CONNECTION VIA PSM
.PARAMETER token
   HashTable of data containing various pieces of login information (PVWA, LoginToken, HeaderType, etc).
   If -token is not passed, function will use last known hashtable generated by New-VPASToken
.PARAMETER safe
   Safe name that will be used to query for the target account if no AcctID is passed
.PARAMETER username
   Username that will be used to query for the target account if no AcctID is passed
.PARAMETER platform
   PlatformID that will be used to query for the target account if no AcctID is passed
.PARAMETER address
   Address that will be used to query for the target account if no AcctID is passed
.PARAMETER AcctID
   Unique ID that maps to a single account, passing this variable will skip any query functions
.PARAMETER OpenRDPFile
   Trigger the RDPFile to open by default, rather then just display the RDPFile contents
.PARAMETER ConnectionComponent
   Define which connection component will be used via ConnectionComponentID
   ConnectionComponentID is the ID given to the Connection Component (for example PSM-RDP for RDP, and PSM-SSH for SSH)
.PARAMETER TargetServer
   Define the target server if the connection component prompts for a server
   Commonly used for domain accounts connecting via PSM-RDP
.PARAMETER Reason
   Define a reason for connecting for audit purposes
.EXAMPLE
   $ConnectWithPSMRDPFile = New-VPASPSMSession -safe {SAFE VALUE} -username {USERNAME VALUE} -address {ADDRESS VALUE}
.EXAMPLE
   $ConnectWithPSMRDPFile = New-VPASPSMSession -AcctID {ACCTID VALUE}
.OUTPUTS
   RDPFile if successful
   $false if failed
#>

function New-VPASPSMSession{
    [OutputType('System.Object',[bool])]
    [CmdletBinding()]
    Param(

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=0)]
        [String]$safe,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=1)]
        [String]$platform,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=2)]
        [String]$username,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=3)]
        [String]$address,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=4)]
        [Switch]$OpenRDPFile,

        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="Enter target ConnectionComponent (for example: PSM-RDP)",Position=5)]
        [String]$ConnectionComponent,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=6)]
        [String]$TargetServer,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=7)]
        [String]$Reason,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=8)]
        [String]$AcctID,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=9)]
        [hashtable]$token
    )

    Begin{
        $tokenval,$sessionval,$PVWA,$Header,$ISPSS,$IdentityURL,$EnableTextRecorder,$AuditTimeStamp,$NoSSL,$VaultVersion,$HideWarnings,$AuthenticatedAs,$SubDomain = Get-VPASSession -token $token
        $CommandName = $MyInvocation.MyCommand.Name
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType COMMAND
    }
    Process{
        Write-Verbose "SUCCESSFULLY PARSED PVWA VALUE"
        Write-Verbose "SUCCESSFULLY PARSED TOKEN VALUE"

        try{

            if([String]::IsNullOrEmpty($AcctID)){
                Write-Verbose "NO ACCOUNT ID PROVIDED...INVOKING HELPER FUNCTION TO RETRIEVE UNIQUE ACCOUNT ID BASED ON SPECIFIED PARAMETERS"
                $AcctID = Get-VPASAccountIDHelper -token $token -safe $safe -platform $platform -username $username -address $address
                Write-Verbose "RETURNING ACCOUNT ID"
            }
            else{
                Write-Verbose "ACCOUNT ID SUPPLIED, SKIPPING HELPER FUNCTION"
            }

            write-verbose "INITIALIZING BODY PARAMETERS"
            $params = @{
                Reason = $Reason
                ConnectionComponent = $ConnectionComponent
                ConnectionParams = @{
                    PSMRemoteMachine = @{
                        value = $TargetServer
                    }
                }
            }
            $log = Write-VPASTextRecorder -inputval $params -token $token -LogType PARAMS
            $params = $params | ConvertTo-Json


            if($NoSSL){
                Write-Verbose "NO SSL ENABLED, USING HTTP INSTEAD OF HTTPS"
                $uri = "http://$PVWA/PasswordVault/API/Accounts/$AcctID/PSMConnect/"
            }
            else{
                Write-Verbose "SSL ENABLED BY DEFAULT, USING HTTPS"
                $uri = "https://$PVWA/PasswordVault/API/Accounts/$AcctID/PSMConnect/"
            }
            $log = Write-VPASTextRecorder -inputval $uri -token $token -LogType URI
            $log = Write-VPASTextRecorder -inputval "POST" -token $token -LogType METHOD
            write-verbose "MAKING API CALL TO CYBERARK"

            if($sessionval){
                $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method POST -Body $params -ContentType "application/json" -WebSession $sessionval
            }
            else{
                $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method POST -Body $params -ContentType "application/json"
            }

            Write-Verbose "CONSTRUCTING FILENAME"
            $tempResponse = $response -split "`r`n"
            $GUID = $tempResponse[2] -split ":"
            $tempName = $GUID[2] + "Vpas.rdp"

            Write-Verbose "CREATING RDP FILE"
            $curUser = $env:UserName
            $outputPath = "C:\Users\$curUser\Downloads\$tempName"
            write-output $response | Set-Content $outputPath

            Write-Verbose "RDP FILE CREATED: $outputPath"

            if($OpenRDPFile){
                write-verbose "OPENING RDP FILE"
                #Invoke-Expression "mstsc.exe '$outputPath'"
                Start-Process "$env:windir\system32\mstsc.exe" -ArgumentList "$outputPath"
            }
            else{
                Write-VPASOutput -str "RDP FILE CREATED: $outputPath" -type M
                Write-VPASOutput -str "PLEASE NOTE THIS FILE IS VALID FOR ~15 SECONDS ONLY" -type M
            }
            $outputlog = $response
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: $outputlog" -token $token -LogType MISC
            Write-Verbose "RETURNING RDP FILE CONTENT"
            return $response
        }catch{
            $log = Write-VPASTextRecorder -inputval $_ -token $token -LogType ERROR
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
            Write-Verbose "UNABLE TO CONNECT TO PSM SESSION"
            Write-VPASOutput -str $_ -type E
            return $false
        }
    }
    End{
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType DIVIDER
    }
}