Documenting with PowerShell: Documenting Remote Access

A friend of mine recently requested if it would be possible to document some of the types of remote access tools that are installed on a computer, and list the possible access URLs; that way he could easily document which access methods are open and audit them once in a while to see if he should not be closing things down.

It actually got my gears grinding a bit; how about not just documenting which Remote Access tools are installed, but also update some form of audit log when there’s been a successful connection. Of course, I only have a limited subset of remote access tools that are available, so I did this for the following;

  • Remote Desktop
  • DattoRMM Web Remote
  • Screenconnect / Control
  • Take Control
  • Teamviewer

I’ve added Teamviewer to the list, but strongly advise not to use that as they’ve known many security incident in the past which they’ve only admitted long after. In any case, enough about my opinions and let’s get to scripting. As always, I’ve made two versions; One for IT-Glue, and one for generic documentation systems.

For both scripts, you’ll need to enter some variables and which tool you want to register and not. Remove the tools you don’t need simply by deleting them from the list.

HTML version

##### Variables
$CheckTools = "Screenconnect", "RemoteDesktop", "TakeControl", "DattoWebRemote", "Teamviewer"
$ScreenconnectURL = "https://YourScreenConnectURL.com/access"
#####
If (Get-Module -ListAvailable -Name "PsWriteHTML") { 
    Import-module PswriteHTML
}
Else { 
    Install-Module PsWriteHTML -Force
    Import-Module PsWriteHTML
}

function get-ScreenconnectInfo {
    param (
        $URL
    )
    $null = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\ScreenConnect Client *' -Name ImagePath).ImagePath -Match '(&s=[a-f0-9\-]*)'
    $GUID = $Matches[0] -replace '&s='
    $RawLog = get-winevent -FilterHashtable @{
        Logname      = 'Application'
        ProviderName = 'Screenconnect*'
        StartTime    = (get-date).adddays(-7)
    } | Where-Object -Property LeveldisplayName -ne "error"

    $AuditLog = foreach ($log in $Rawlog) {
        switch -Wildcard ($log.message) {
            "*Disconnected*" { $reason = 'Disconnected' }
            "*connected*" { $reason = 'Connected' }
            "**Transfer*" { $reason = 'File Transfer' }
        }
        [PSCustomObject]@{
            Date    = $log.TimeCreated
            Reason  = $Reason
            Message = $log.message
        }
    }

    $RemoteControlURL = "$ScreenconnectURL/$guid//Join"
    [PSCustomObject]@{
        'Type'              = "Screenconnect / Control"
        'Enabled'           = if ($guid) { $true } else { $false }
        'RemoteControl URL' = $RemoteControlURL
        AuditLog            = $auditLog
    }
}


function Get-RDPInfo {
    $enabled = (get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\').fDenyTSConnections
    $RawLog = get-winevent -FilterHashtable @{
        Logname   = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
        StartTime = (get-date).adddays(-7)
        ID        = 21, 22, 24, 25, 39, 40
    } | Where-Object -Property LeveldisplayName -ne "error" | Where-Object { $_.message -notlike "*Source Network Address: LOCAL*" }

    $AuditLog = foreach ($log in $Rawlog) {
        switch -Wildcard ($log.message) {
            "*Disconnected*" { $reason = 'Disconnected' }
            "*reconnection*" { $reason = 'Reconnected' }
            "*Shell Start*" { $reason = 'Connected' }
        }
        [PSCustomObject]@{
            Date    = $log.TimeCreated
            Reason  = $Reason
            Message = $log.message
        }
    }

    [PSCustomObject]@{
        'Type'              = "RDP"
        'Enabled'           = [bool]!$enabled
        'RemoteControl URL' = "mstsc /v $ENV:COMPUTERNAME"
        AuditLog            = $auditLog
    }
}


function Get-TakeControlInfo {
    $enabled = (Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Services\BASupportExpressStandaloneService*' -erroraction SilentlyContinue)
    $RawLog = get-winevent -FilterHashtable @{
        Logname      = 'Application'
        Providername = 'Solarwinds*'
        StartTime    = (get-date).adddays(-7)
        ID           = 8193, 4102
    } 

    $AuditLog = foreach ($log in $Rawlog) {
        switch -Wildcard ($log.message) {
            "*Session ended*" { $reason = 'Disconnected' }
            "*Logged*" { $reason = 'Connected' }
        }
        [PSCustomObject]@{
            Date    = $log.TimeCreated
            Reason  = $Reason
            Message = $log.message
        }
    }

    [PSCustomObject]@{
        'Type'              = "Takecontrol"
        'Enabled'           = $enabled
        'RemoteControl URL' = "mspancsxvp:/$ENV:COMPUTERNAME"
        AuditLog            = $auditLog
    }
}

function Get-DattoWebInfo {
    $enabled = (Test-Path "C:\ProgramData\CentraStage\AEMAgent\DataLog\webremote.log" -erroraction SilentlyContinue)
    $RawLog = get-content "C:\ProgramData\CentraStage\AEMAgent\DataLog\webremote.log" -ErrorAction SilentlyContinue | convertfrom-csv -Delimiter ' ' -Header Version, datetime, processid, threadid, level, message | Where-Object -Property Message -like "*WEBRTC*"

    $AuditLog = foreach ($log in $Rawlog) {
        switch -Wildcard ($log.message) {
            "*REQUEST*" { $reason = 'Request to join session' }
            "*|WEBRTC|JOIN" { $reason = 'Joined session' }
            "*CLOSED*" { $reason = 'Disconnected session' }
            default { $reason = "INFO" }
        }
        [PSCustomObject]@{
            Date    = $log.DateTime
            Reason  = $Reason
            Message = $log.message
        }
    }

    [PSCustomObject]@{
        'Type'              = "Datto Web Remote"
        'Enabled'           = $enabled
        'RemoteControl URL' = "Not Available"
        AuditLog            = $auditLog
    }
}


function Get-TeamviewerInfo {
    $enabledQS = (Test-Path "C:\Users\*\AppData\Roaming\TeamViewer" -erroraction SilentlyContinue)
    $enabledPermantely = (Test-Path "C:\Program Files *\TeamViewer" -erroraction SilentlyContinue)
    if ($enabledQS) { $enabled = "True - Via Quick Support" }
    if ($enabledPermantely) { $enabled = "True, full installation" }
    $RawLog = get-item "C:\Users\*\AppData\Roaming\TeamViewer\Connections_incoming.txt", "C:\Program Files*\TeamViewer\Connections_incoming.txt" | get-content | convertfrom-csv -Delimiter "`t" -Header ExternalID, ExternalHostname, ConnectedAt, DisconnectedAt, Username, Action, ID

    $AuditLog = foreach ($log in $Rawlog) {
        $Reason = "Event"
        $message = "ID $($log.externalid) with hostname $($log.externalhostname) connected to username $($log.username) at $($log.connectedat) and disconnected at $($log.disconnectedat)"
        [PSCustomObject]@{
            Date    = $log.ConnectedAt
            Reason  = $Reason
            Message = $message
        }
    }

    [PSCustomObject]@{
        'Type'              = "Teamviewer"
        'Enabled'           = $enabled
        'RemoteControl URL' = "Not Available"
        AuditLog            = $auditLog
    }
}



$Data = foreach ($tool in $CheckTools) {
    switch ($tool) {
        "Screenconnect" { Get-ScreenconnectInfo -url $ScreenconnectURL }
        "RemoteDesktop" { Get-RDPInfo }
        "TakeControl" { Get-TakeControlInfo }
        "DattoWebRemote" { Get-DattoWebInfo }
        "Teamviewer" { get-TeamviewerInfo }
    }
}

New-HTML {
    New-HTMLTab -Name 'Audit logs'{
        New-HTMLSection -Invisible {
            New-HTMLSection -HeaderText 'Remote Control Settings' {
                New-HTMLTable -DataTable ($Data | Select-Object Type, Enabled ,'RemoteControl URL')
            }
            New-HTMLSection -HeaderText 'AuditLogs' {
                New-HTMLTable -DataTable $data.auditlog
            }
        }
    }
} -FilePath "C:\temp\$($ENV:COMPUTERNAME).html" -Online

IT-Glue version

The IT-Glue version creates a Remote Access Logs flexible asset, and tags the asset if it can find it based on the serialnumber.

##### Variables
$CheckTools = "Screenconnect", "RemoteDesktop", "TakeControl", "DattoWebRemote", "Teamviewer"
$ScreenconnectURL = "https://YourScreenConnectURL.com/access"
#####
######################### IT-Glue ############################
$ITGkey = "YourITGKey"
$APIEndpoint = "https://api.eu.itglue.com"
$ORGID = "ORGIDFORCLIENT"
$FlexAssetName = "Remote Access logs"
$Description = "A logbook of Remote Access methods and enabled methods"
$TableStyling = "<th>", "<th style=`"background-color:#4CAF50`">"
########################## IT-Glue ############################
If (Get-Module -ListAvailable -Name "ITGlueAPI") { 
    Import-module ITGlueAPI
}
Else { 
    Install-Module ITGlueAPI -Force
    Import-Module ITGlueAPI
}
Add-ITGlueBaseURI -base_uri $APIEndpoint
Add-ITGlueAPIKey $ITGkey
write-host "Checking if Flexible Asset exists in IT-Glue." -foregroundColor green
$FilterID = (Get-ITGlueFlexibleAssetTypes -filter_name $FlexAssetName).data
if (!$FilterID) { 
    write-host "Does not exist, creating new." -foregroundColor green
    $NewFlexAssetData = 
    @{
        type          = 'flexible-asset-types'
        attributes    = @{
            name        = $FlexAssetName
            icon        = 'sitemap'
            description = $description
        }
        relationships = @{
            "flexible-asset-fields" = @{
                data = @(
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order           = 1
                            name            = "Device Name"
                            kind            = "Text"
                            required        = $true
                            "show-in-list"  = $true
                            "use-for-title" = $true
                        }
                    },
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order          = 2
                            name           = "Access Methods"
                            kind           = "Textbox"
                            required       = $false
                            "show-in-list" = $false
                        }
                    },
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order          = 3
                            name           = "Logs"
                            kind           = "Textbox"
                            required       = $false
                            "show-in-list" = $false
                        }
                    },
                    @{
                        type       = "flexible_asset_fields"
                        attributes = @{
                            order          = 4
                            name           = "Tagged configuration"
                            kind           = "Tag"
                            "tag-type"     = "Configurations"
                            required       = $false
                            "show-in-list" = $false
                        }
                    }
                )
            }
        }
    }
    New-ITGlueFlexibleAssetTypes -Data $NewFlexAssetData
    $FilterID = (Get-ITGlueFlexibleAssetTypes -filter_name $FlexAssetName).data
}
   


function get-ScreenconnectInfo {
    param (
        $URL
    )
    $null = (Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\ScreenConnect Client *' -Name ImagePath).ImagePath -Match '(&s=[a-f0-9\-]*)'
    $GUID = $Matches[0] -replace '&s='
    $RawLog = get-winevent -FilterHashtable @{
        Logname      = 'Application'
        ProviderName = 'Screenconnect*'
        StartTime    = (get-date).adddays(-7)
    } | Where-Object -Property LeveldisplayName -ne "error"

    $AuditLog = foreach ($log in $Rawlog) {
        switch -Wildcard ($log.message) {
            "*Disconnected*" { $reason = 'Disconnected' }
            "*connected*" { $reason = 'Connected' }
            "**Transfer*" { $reason = 'File Transfer' }
        }
        [PSCustomObject]@{
            Type    = "Screenconnect"
            Date    = $log.TimeCreated
            Reason  = $Reason
            Message = $log.message
        }
    }

    $RemoteControlURL = "$ScreenconnectURL/$guid//Join"
    [PSCustomObject]@{
        'Type'              = "Screenconnect / Control"
        'Enabled'           = if ($guid) { $true } else { $false }
        'RemoteControl URL' = $RemoteControlURL
        AuditLog            = $auditLog
    }
}


function Get-RDPInfo {
    $enabled = (get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\').fDenyTSConnections
    $RawLog = get-winevent -FilterHashtable @{
        Logname   = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational'
        StartTime = (get-date).adddays(-7)
        ID        = 21, 22, 24, 25, 39, 40
    } | Where-Object -Property LeveldisplayName -ne "error" | Where-Object { $_.message -notlike "*Source Network Address: LOCAL*" }

    $AuditLog = foreach ($log in $Rawlog) {
        switch -Wildcard ($log.message) {
            "*Disconnected*" { $reason = 'Disconnected' }
            "*reconnection*" { $reason = 'Reconnected' }
            "*Shell Start*" { $reason = 'Connected' }
        }
        [PSCustomObject]@{
            Type    = "RDP"
            Date    = $log.TimeCreated
            Reason  = $Reason
            Message = $log.message
        }
    }

    [PSCustomObject]@{
        'Type'              = "RDP"
        'Enabled'           = [bool]!$enabled
        'RemoteControl URL' = "mstsc /v $ENV:COMPUTERNAME"
        AuditLog            = $auditLog
    }
}


function Get-TakeControlInfo {
    $enabled = (Test-Path 'HKLM:\SYSTEM\CurrentControlSet\Services\BASupportExpressStandaloneService*' -erroraction SilentlyContinue)
    $RawLog = get-winevent -FilterHashtable @{
        Logname      = 'Application'
        Providername = 'Solarwinds*'
        StartTime    = (get-date).adddays(-7)
        ID           = 8193, 4102
    } 

    $AuditLog = foreach ($log in $Rawlog) {
        switch -Wildcard ($log.message) {
            "*Session ended*" { $reason = 'Disconnected' }
            "*Logged*" { $reason = 'Connected' }
        }
        [PSCustomObject]@{
            Type    = "TakeControl"
            Date    = $log.TimeCreated
            Reason  = $Reason
            Message = $log.message
        }
    }

    [PSCustomObject]@{
        'Type'              = "Takecontrol"
        'Enabled'           = $enabled
        'RemoteControl URL' = "mspancsxvp:/$ENV:COMPUTERNAME"
        AuditLog            = $auditLog
    }
}

function Get-DattoWebInfo {
    $enabled = (Test-Path "C:\ProgramData\CentraStage\AEMAgent\DataLog\webremote.log" -erroraction SilentlyContinue)
    $RawLog = get-content "C:\ProgramData\CentraStage\AEMAgent\DataLog\webremote.log" -ErrorAction SilentlyContinue | convertfrom-csv -Delimiter ' ' -Header Version, datetime, processid, threadid, level, message | Where-Object -Property Message -like "*WEBRTC*"

    $AuditLog = foreach ($log in $Rawlog) {
        switch -Wildcard ($log.message) {
            "*REQUEST*" { $reason = 'Request to join session' }
            "*|WEBRTC|JOIN" { $reason = 'Joined session' }
            "*CLOSED*" { $reason = 'Disconnected session' }
            default { $reason = "INFO" }
        }
        [PSCustomObject]@{
            Type    = "Datto Web"
            Date    = $log.DateTime
            Reason  = $Reason
            Message = $log.message
        }
    }

    [PSCustomObject]@{
        'Type'              = "Datto Web Remote"
        'Enabled'           = $enabled
        'RemoteControl URL' = "Not Available"
        AuditLog            = $auditLog
    }
}


function Get-TeamviewerInfo {
    $enabledQS = (Test-Path "C:\Users\*\AppData\Roaming\TeamViewer" -erroraction SilentlyContinue)
    $enabledPermantely = (Test-Path "C:\Program Files *\TeamViewer" -erroraction SilentlyContinue)
    if ($enabledQS) { $enabled = "True - Via Quick Support" }
    if ($enabledPermantely) { $enabled = "True, full installation" }
    $RawLog = get-item "C:\Users\*\AppData\Roaming\TeamViewer\Connections_incoming.txt", "C:\Program Files*\TeamViewer\Connections_incoming.txt" | get-content | convertfrom-csv -Delimiter "`t" -Header ExternalID, ExternalHostname, ConnectedAt, DisconnectedAt, Username, Action, ID

    $AuditLog = foreach ($log in $Rawlog) {
        $Reason = "Event"
        $message = "ID $($log.externalid) with hostname $($log.externalhostname) connected to username $($log.username) at $($log.connectedat) and disconnected at $($log.disconnectedat)"
        [PSCustomObject]@{
            Type    = "Teamviewer"
            Date    = $log.ConnectedAt
            Reason  = $Reason
            Message = $message
        }
    }

    [PSCustomObject]@{
        'Type'              = "Teamviewer"
        'Enabled'           = $enabled
        'RemoteControl URL' = "Not Available"
        AuditLog            = $auditLog
    }
}



$Data = foreach ($tool in $CheckTools) {
    switch ($tool) {
        "Screenconnect" { Get-ScreenconnectInfo -url $ScreenconnectURL }
        "RemoteDesktop" { Get-RDPInfo }
        "TakeControl" { Get-TakeControlInfo }
        "DattoWebRemote" { Get-DattoWebInfo }
        "Teamviewer" { get-TeamviewerInfo }
    }
}

$TaggedResource = (Get-ITGlueConfigurations -organization_id $orgID -filter_serial_number (get-ciminstance win32_bios).serialnumber).data

$FlexAssetBody = 
@{
    type       = 'flexible-assets'
    attributes = @{
        name   = $FlexAssetName
        traits = @{
            "device-name"          = $($ENV:COMPUTERNAME)
            "access-methods"       = ($Data | Select-Object Type, Enabled , 'RemoteControl URL' | convertto-html -frag | Out-String) -replace $TableStyling
            "logs"                 = ($data.auditlog | ConvertTo-Html -frag | Out-String)  -replace $TableStyling
            "tagged-configuration" = $TaggedResource.id
        }
    }
}

#Upload data to IT-Glue. We try to match the Server name to current computer name.
$ExistingFlexAsset = (Get-ITGlueFlexibleAssets -filter_flexible_asset_type_id $Filterid.id -filter_organization_id $orgID).data | Where-Object { $_.attributes.traits.'device-name' -eq $ENV:COMPUTERNAME } | Select-Object -last 1
#If the Asset does not exist, we edit the body to be in the form of a new asset, if not, we just upload.
if (!$ExistingFlexAsset) {
    $FlexAssetBody.attributes.add('organization-id', $orgID)
    $FlexAssetBody.attributes.add('flexible-asset-type-id', $FilterID.id)
    Write-Host "Creating new flexible asset"
    New-ITGlueFlexibleAssets -data $FlexAssetBody
}
else {
    Write-Host "Updating Flexible Asset"
    Set-ITGlueFlexibleAssets -id $ExistingFlexAsset.id  -data $FlexAssetBody
}

And that’s it! As always, Happy PowerShelling 🙂

1 Comment

  1. Luke Whitelock May 13, 2021 at 5:04 pm

    This should add support for AnyDesk if anyone wants:
    function Get-AnyDeskInfo {
    $enabledRO = (Test-Path “C:\Users\*\AppData\Roaming\AnyDesk” -erroraction SilentlyContinue)
    $enabledPermantely = (Test-Path “C:\ProgramData\AnyDesk” -erroraction SilentlyContinue)
    if ($enabledRO) { $enabled = “True, via run only” }
    if ($enabledPermantely) { $enabled = “True, full installation” }
    $RawFiles = get-item “C:\Users\*\AppData\Roaming\AnyDesk\connection_trace.txt”, “C:\Users\*\AppData\Roaming\AnyDesk\*\connection_trace.txt”, “C:\ProgramData\AnyDesk\connection_trace.txt”, “C:\ProgramData\AnyDesk\*\connection_trace.txt” | get-content -encoding Unicode -raw | Out-String
    $ParsedFiles = ($RawFiles -split ” ” | % {if ($_ -ne “”){$_}}) -join ” ”
    $RawLog = $ParsedFiles | convertfrom-csv -Delimiter ” ” -Header Direction, Date, Time, Status, Alias, ID
    $AuditLog = foreach ($log in $Rawlog) {
    if ($log.direction -ne “”){
    $Reason = “Event”
    $message = “$($log.Date) $($log.Time): $($log.Direction) connection with ID $($log.id) and alias $($log.alias). Status was ‘$($log.Status)'”
    [PSCustomObject]@{
    Type = “AnyDesk”
    Date = “$($log.Date) $($log.Time)”
    Reason = $Reason
    Message = $message
    }
    }
    }
    [PSCustomObject]@{
    ‘Type’ = “AnyDesk”
    ‘Enabled’ = $enabled
    ‘RemoteControl URL’ = “Not Available”
    AuditLog = $auditLog
    }
    }

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.