Featured image of post Documenting with PowerShell: Documenting Remote Access

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

  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
##### 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.

  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
269
270
271
272
273
274
275
276
277
278
279
280
##### 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 🙂

All blogs are posted under AGPL3.0 unless stated otherwise
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy