Cheat Sheet

Investigating With PowerShell

#REMOVE WMI PERSISTENCE
pwsh -command "Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter \"Name='SCM Event4 Log Filter'\" | Remove-WmiObject"

#remove namespace
Get-WmiObject -Namespace root\Default -List | where {$_.Name -match 'systemcore_Updater?'}

#Recursive shortcut lookup with expansion.
pwsh $lnk = gci -Path 'C:\FILEPATH' *.lnk -Recurse -ErrorAction SilentlyContinue -Force | select -exp Fullname ; ForEach ($lnk in $lnk) {$sh = New-Object -COM WScript.Shell ; $targetPath = $sh.CreateShortcut($lnk) ; $targetPath}

#ECKING DOWNLOADS DIRECTORY FOR FILE HASH.
Get-ChildItem -Path C:\Users\ -Filter *.exe -Recurse -ErrorAction SilentlyContinue -Force | Get-FileHash | Where-Object {$_.Hash -eq 'be3fc53bdc3a68eb2150f62a96b30ec9efbc2f99e6166a6a737a00467cdf1f08'}

#DISPLAY DISK NAMES
Get-Disk | % {$_.FriendlyName}

#ADS
pwsh Get-Item FILEPATH* -Stream zone* | cat
pwsh Get-Item .\a.zip -Stream *
pwsh Get-Content .\a.zip -Stream Zone.Identifier
pwsh wmic process get 'processid,parentprocessid'

#Show Original Recycle.Bin Names
pwsh (New-Object -ComObject Shell.Application).NameSpace(0x0a).Items() | select @{n="OriginalLocation"; e={$_.ExtendedProperty("{9B174B33-40FF-11D2-A27E-00C04FC30871} 2")}},Name

#SHOW DATE
pwsh get-date

#IIS vs Apache

#FIND SHARE DRIVES
net share

#Svchost Service Names
tasklist /svc /fi "imagename eq svchost.exe"

#Read Windows Logs
cat '\inetpub\logs\LogFiles\w3svc1\u_ex221006.log' | sls 'MDEDiscovery' | out-string

#SORT LAST WRITE TIME
pwsh gci 'C:\Users\USERNAME\Downloads\*' | sort lastwritetime

#FIND NETWORK SHARE ON HOST
pwsh cmd.exe /c net share

#GET SCHEDULED TASK INFO
pwsh Export-ScheduledTask -TaskName 'TaskName'

#SechuledTask Removal
pwsh schtasks /delete /tn '<schduledtaskname>' /F

#Remove Registry Key/Property
reg delete "<Registry Location>" <property value>

#DELETE ALL FILES IN A FOLDER+SUBFOLDERS
Get-ChildItem -Path 'C:\Exmaple' -Include *.* -File -Recurse | foreach { $_.Delete()}

#GET PROCESS USING DLL
pwsh get-process | Where {$_.Modules -like '*CloverSvc.dll'}

#IDENTIFY MOUNTED DRIVES
pwsh Get-WmiObject -Class Win32_logicaldisk

#IDENTIFY LOCATION OF MOUNTED FILE
pwsh Get-DiskImage -DevicePath \\.\CDROM0

#UNMOUNTING FILE
pwsh Dismount-DiskImage -ImagePath 'PATH_TO_ISO'

#FIND FILE NAME WITH FULL PATH INCLUDED IN USERS
pwsh Get-ChildItem -Path C:\Users -Filter *FILEPATH* -Recurse -ErrorAction SilentlyContinue -Force | select -exp Fullname

##Take Ownership of File
takeown /F FILEPATH
icacls FILEPATH /grant Administrators:F;

#list running proccesses and thier commandline
pwsh wmic process get processid,commandline

##LIST USBS
Get-PnpDevice -PresentOnly | Where-Object { $_. InstanceId -match '^USB'
wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

#See History of Devices Plugge in
pnputil /enum-devices
pnputil /enum-interfaces

#
Q3Jvd2QkdHJpa2VFbmNyeXB0c0ZpbEVuY3J5cHQzZCE=

#New Service was Installed
pwsh Get-WinEvent –Logname 'System' -MaxEvents 10 -FilterXPath '*[System[EventID=7045]]' | FL TimeCreated,Message

#User Logon
pwsh Get-WinEvent –Logname 'Security' -MaxEvents 10 -FilterXPath '*[System[EventID=4624]]' | FL TimeCreated,Message

#Event Logs
Get-WinEvent -FilterHashtable @{ LogName='Security'; Id='4624'; Data='3'} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Security'; Id='4672';} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Microsoft-Windows-PowerShell/Operational'; Id='4103';} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Microsoft-Windows-PowerShell/Operational'; Id='4104';} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Microsoft-Windows-PowerShell/Operational'; Id='53504';} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Windows PowerShell'; Id='400';} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Windows PowerShell'; Id='403';} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Microsoft-Windows-WinRM/Operational'; Id='91';} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Microsoft-Windows-WinRM/Operational'; Id='168';} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Application'; Id='326'} | FL TimeCreated,Message
Get-WinEvent -FilterHashtable @{ LogName='Application'; Id='327'} | FL TimeCreated,Message

#Exchange ProxyShell
pwsh Get-WinEvent -FilterHashtable @{LogName='MSExchange Management';} | ? {$_.Message -match 'aspx'} | FL TimeCreated, Message | Out-String

#ANDROMEDA
pwsh Get-Item -LiteralPath D:\$([char]0xA0)\ -Force
Get-Item -LiteralPath E:\$([char]0xA0)\ -Force | Rename-Item -NewName 'FOR_REVIEW_RenamedFolder' -Force

#Show full Target Path for all .lnk
$WSShell = New-Object -ComObject Wscript.Shell
$shortcutfiles = dir .\*.lnk
foreach ($shortcutfile in $shortcutfiles ) {
    $Shortcut = $WSShell.CreateShortcut($shortcutfile.FullName)
    Write-Host $Shortcutfile.Name $Shortcut.TargetPath $shortcut.Arguments
}

##Display a list of path exceptions for Windows Defender:
Get-MpPreference | fl excl*

##To remove an exception for a specific folder:
Remove-MpPreference -ExclusionPath C:\install

##Check last bootup time
pwsh Get-WmiObject -Class win32_operatingsystem -Property LastBootUpTime

##PWSH sort processes
pwsh get-process | where {$_.path -like '*ProgramData*'} | select ProcessName

#Hash of unsigned or invalid signed DLLs currently loaded by processes
pwsh $A=$(foreach ($dll in gps|select -ExpandProperty modules -ea ig){Get-AuthenticodeSignature $dll.FileName |Where-Object Status -NE "Valid"|Select Path});$B=$(foreach ($dll in $A){Get-FileHash $dll.Path| select Hash -ExpandProperty Hash})|Sort-Object| Get-Unique;$B


#List all IIS websites with physical paths and binds
#IIS logs are located in C:\Inet\logs\logfiles\W3SVC2 if ID is 2
#IIS logs:
C:\inetpub\logs\LogFiles\W3SVC<instanceIDnumber>\
#find instance ID number:
pwsh Import-Module Webadministration;Get-Website|out-string

#Software Version with WMI
wmic datafile where 'name="C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"'

#LIST EVERY \Device\Harddiskvolume.?
$signature = @'
[DllImport("kernel32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetVolumePathNamesForVolumeNameW([MarshalAs(UnmanagedType.LPWStr)] string lpszVolumeName,
        [MarshalAs(UnmanagedType.LPWStr)] [Out] StringBuilder lpszVolumeNamePaths, uint cchBuferLength,
        ref UInt32 lpcchReturnLength);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr FindFirstVolume([Out] StringBuilder lpszVolumeName,
   uint cchBufferLength);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool FindNextVolume(IntPtr hFindVolume, [Out] StringBuilder lpszVolumeName, uint cchBufferLength);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax);

'@;
Add-Type -MemberDefinition $signature -Name Win32Utils -Namespace PInvoke -Using PInvoke,System.Text;

[UInt32] $lpcchReturnLength = 0;
[UInt32] $Max = 65535
$sbVolumeName = New-Object System.Text.StringBuilder($Max, $Max)
$sbPathName = New-Object System.Text.StringBuilder($Max, $Max)
$sbMountPoint = New-Object System.Text.StringBuilder($Max, $Max)
[IntPtr] $volumeHandle = [PInvoke.Win32Utils]::FindFirstVolume($sbVolumeName, $Max)
do {
    $volume = $sbVolumeName.toString()
    $unused = [PInvoke.Win32Utils]::GetVolumePathNamesForVolumeNameW($volume, $sbMountPoint, $Max, [Ref] $lpcchReturnLength);
    $ReturnLength = [PInvoke.Win32Utils]::QueryDosDevice($volume.Substring(4, $volume.Length - 1 - 4), $sbPathName, [UInt32] $Max);
    if ($ReturnLength) {
           $DriveMapping = @{
               DriveLetter = $sbMountPoint.toString()
               VolumeName = $volume
               DevicePath = $sbPathName.ToString()
           }

           Write-Output (New-Object PSObject -Property $DriveMapping)
       }
       else {
           Write-Output "No mountpoint found for: " + $volume
       }
} while ([PInvoke.Win32Utils]::FindNextVolume([IntPtr] $volumeHandle, $sbVolumeName, $Max));



#DLL SEARCH
$files = (get-process lsass).modules
$results = @()
ForEach ($f in $files)
    {
        $file = ls -path $f.FileName
        $authenticode = Get-AuthenticodeSignature -FilePath $file.FullName -ErrorAction SilentlyContinue
        $sha256 = Get-FileHash -Path $file.FullName -Algorithm SHA256 -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Hash
        $NameMatch = $false
        if($file.Name -like $file.VersionInfo.OriginalFilename) { $NameMatch = $true }
        $PSObjectRow = New-Object PSObject -Property @{
            FullName                = $file.FullName
            Size                    = $file.Length
            CreationTimeUtc         = $file.CreationTimeUtc
            LastAccessTimeUtc       = $file.LastAccessTimeUtc
            LastWriteTimeUtc        = $file.LastWriteTimeUtc
            Sha256                  = $sha256
            OriginalFilename        = $file.VersionInfo.OriginalFilename
            NameMatch               = $NameMatch
            CompanyName             = $file.VersionInfo.CompanyName
            FileDescription         = $file.VersionInfo.FileDescription
            AuthenticodeStatus      = $authenticode.Status
            AuthenticodePath        = $authenticode.Path
            AuthenticodeSigType     = $authenticode.SignatureType
            AuthenticodeIsOSbinary  = $authenticode.IsOSBinary
        }
        $results += $PSObjectRow
    }
$results | Select-Object FullName, OriginalFilename, NameMatch, FileDescription, CompanyName, Size, Sha256, CreationTimeUtc, LastAccessTimeUtc, LastWriteTimeUtc, AuthenticodeStatus, AuthenticodeSigType, AuthenticodeIsOSbinary | Out-String -width 1000


#TRIAGE SCRIPT TEMPLATE
function triage {
    $fileArray = checkFiles
    echo '';
    echo '------------------------------';
    echo 'File System Artifacts Found:';
    echo '------------------------------';
    if ($fileArray){
        foreach($file in $fileArray){
            echo "[-] $file"
        }
    }
    else {echo '[-] No Files Found'}

}

function checkFiles{
    $fileList = New-Object System.Collections.ArrayList
    $badDirs = @('C:\PerfLogs\rundll32.exe', 'c:\users\*\downloads\scaler.exe', 'c:\users\public\downloads\gst2.exe', 'c:\users\public\downloads\*.exe', 'C:\windows\temp\winsys.mdp', 'C:\windows\temp\winsys.zip', 'C:\Users\Public\svcss.csv', 'C:\Temp\1.bat', 'C:\Temp\*.bat', 'C:\temp\2.bat', 'C:\Users\*\*\mimikatz.exe', 'C:\Users\*\*\mimilib.dll', 'C:\Users\*\*\mimidrv.sys', 'C:\Users\*\*\mimikatz-master.zip', 'C:\Users\*\*\1', 'C:\Users\Public\gsc3.exe', 'C:\Users\Public\*.exe')

    foreach ($badDir in $badDirs){
        if (Test-Path $badDir) {
            $dirPath = get-item $badDir
            [void]$fileList.add($dirPath)
        }
    }
    return $fileList
}

triage;

Linux

##PS grep
ps -ef | grep -i NAME

##Display All User Directories
ls /home/*/

##SSH Logs
cat /var/log/secure | grep oracle

##Read Crontab File
cat /var/spool/cron/crontabs

Splunk

#File Writes
event_simpleName IN (ZipFileWritten, NewScriptWritten, DirectoryCreate, FileCreateInfo, FileDeleteInfo, JarFileWritten, NewExecutableWritten, NewScriptWritten, NewExecutableRenamed, OleFileWritten, PeFileWritten, SevenZipFileWritten, NewExecutableRenamed, ExecutableDeleted, BZip2FileWritten, DmpFileWritten, DwgFileWritten, ELFFileWritten, GenericFileWritten, GzipFileWritten, IdwFileWritten, JarFileWritten, JavaClassFileWritten, JavaClassFileWritten, MachOFileWritten, OoxmlFileWritten, OoxmlFileWritten, PdfFileWritten, RarFileWritten, RtfFileWritten, SevenZipFileWritten, TarFileWritten, DexFileWritten, XarFileWritten, PackedExecutableWritten, SuspiciousPeFileWritten, SuspiciousEseFileWritten, ModuleDetectInfo) | table SourceFileName TargetFileName event_simpleName _time SHA256HashData | search TargetFileName!="*avast*" AND TargetFileName!="*api-ms*"  AND TargetFileName!="*PSScriptPolicyTest*" | dedup TargetFileName,event_simpleName | sort _time

#SPLUN USER ACTIVITY
event_simpleName IN (UserLogon*, UserLogoff*, UserIdentity) AND NOT UserName IN (DWM*) | eval LogonType = case(LogonType_decimal==2 , "Interactive", LogonType_decimal==3, "Network", LogonType_decimal==4, "Batch", LogonType_decimal==5, "Service", LogonType_decimal==8, "Network_ClearText", LogonType_decimal==9, "New_Credentials", LogonType_decimal==10, "Remote Interactive") |  table _time, name, UserName, LogonDomain, LogonType, UserIsAdmin_decimal, RemoteIP, ClientComputerName | rename UserIsAdmin_decimal as Admin | sort _time

#Failed Logons by Account
aid=3495356af785464e881bbd6f023570eb event_simpleName=UserLogonFailed2
 | stats count by UserName

#USB SEARCH
earliest=-30d | eval timestamp = 1657182696 | eval begin = timestamp-1200 | eval end = timestamp+1200 | where _time > begin AND _time < end | search event_simpleName=RemovableMedia* OR event_simpleName=DcUsb*| table _time aid event_simpleName ComputerName VolumeDriveLetter DiskParentDeviceInstanceId DeviceManufacturer DeviceProduct DeviceInstanceId | rename DiskParentDeviceInstanceId as "Device Hardware/Vendor ID", VolumeDriveLetter as "Volume Drive Letter", ComputerName as "Hostname", aid as AID, DeviceInstanceId as "Device Hardware/Vendor ID (External HDD)" | sort _time

#User Account Created Locally
event_simpleName=UserAccountCreated event_simpleName=UserAccountCreated

#EAM String Match
| eval Activity1 = coalesce(CommandLine, ScriptContentName, TaskName, TargetFileName, FileName, RegObjectName, RemoteIP, RemoteAddressIP6, DomainName, DeviceProduct, ApplicationName, ImageFileName, FilePath, NetworkContainmentState, ServiceDisplayName, LocalIP, DesiredAccess, SessionId, InjectedDll, WmiQuery, EtwRawProcessId, SmbShareName, DeviceInstanceId, VolumeName, AppName, AmsiStatusCode, FirewallRuleId, SmbClientName, ServiceDisplayName, DomainSid, AssemblyName, HttpUrl, CallStackModuleNames, LogonType_decimal)
| eval Activity2 = coalesce(ParentBaseFileName, ScriptContent, TaskExecCommand, VnodeModificationType, RegValueName, RegOperationType, SourceFileName, ServiceDisplayName, RemotePort_decimal, CNAMERecords, DeviceSerialNumber, CommandHistory, QuarantinedFileState, SHA256HashData, ServiceImagePath, LPort, SuspiciousHandleOpenReason, WmiNamespaceName, EtwRawThreadId, SmbClientName, DeviceManufacturer, VolumeDriveLetter, AppVersion, AmsiRegistrationState, FirewallRule, ServiceType, GroupRid, AssemblyName, HttpRequestHeader)  
| table  _time event_simpleName DetectName Activity1 LogonType_decimal Activity2 UserName ComputerName IntegrityLevel_decimal RawProcessId_decimal TargetProcessId_decimal ContextProcessId_decimal ContextThreadId_decimal RpcClientProcessId_decimal ParentProcessId_decimal SourceProcessId_decimal SourceThreadId_decimal ImageFileName ZoneIdentifier_decimal LinkName SHA256HashData PatternId_decimal Technique Tactic Comment _raw
| sort  0 _time

#restore point
event_simpleName=AgentOnline |table ComputerName aid BootId_decimal timestamp | eval timestamp=timestamp/1000  | convert ctime(timestamp)

#processes ran
event_simpleName IN (ProcessRollup2, ProcessBlocked, SyntheticProcessRollup2) | table _time, FileName, CommandLine, ParentBaseFileName, LinkName, SHA256HashData | sort _time  

#HEATBEAT
event_simpleName=SensorHeartbeat OR event_simpleName=AcUninstallConfirmation OR event_simpleName=FalconHostFileTamperingInfo OR event_simpleName=FalconHostRegTamperingInfo

#Network Events
aid="5e6a62fcdaf244b9acd28c4133da1f37" "10.1.10.167" event_simpleName=NetworkReceiveAcceptIP4 OR event_simpleName=SuspectNetworkConnectIP4Stack OR event_simpleName=NetworkConnectIP4 OR event_simpleName=NetworkListenIP4
|  table _time, LocalAddressIP4, RemoteAddressIP4, RPort, LPort, event_simpleName

#failed Logins
aid=7c773c5553274778b91e6b0e7342a0a1 sourcetype="UserLogonFailed2V2-v02"
|  stats count values(UserName) by RemoteIP
|  sort - count

##Failed Logons From IP
10.50.85.100  |  table _time event_simpleName ComputerName DetectDescription TargetFileName UserName LogonDomain RemoteAddressIP4 RPort LPort LocalIP FileName  SHA256HashData RegObjectName RegValueName RemoteIP | sort _time asc

#DNS Requests by Number
aid=25442ae5e52c4236bcf1aa878fd023d7 event_simpleName=DnsRequest OR DetectName=*Dns* | eval size=len(DomainName)
| eval timez=strftime(_time, "%Y-%m-%dT%H:%M:%S.%Q")
| stats values(DomainName) values(timez) by size
| sort - size

#SensorService Tampering
event_simpleName IN (FileSystemOperation*, RegistryOperationDetectInfo, FalconHostRegTamperingInfo, FalconHostFileTamperingInfo, *AssociateTreeIdWithRoot) | eval RegOperationType = case(RegOperationType_decimal==1, "REG_SET_VALUE_KEY", RegOperationType_decimal==2, "REG_DELETE_VALUE_KEY", RegOperationType_decimal==3, "REG_CREATE_KEY", RegOperationType_decimal==4, "REG_DELETE_KEY", RegOperationType_decimal==5, "REG_SET_KEY_SECURITY", RegOperationType_decimal==6, "REG_LOAD_KEY", RegOperationType_decimal==7, "REG_RENAME_KEY", RegOperationType_decimal==8, "REG_OPEN_KEY", RegOperationType_decimal==9, "REG_QUERY_NAME_KEY", RegOperationType_decimal==101, "REG_SET_VALUE_KEY_ANTI_TAMPER", RegOperationType_decimal==102, "REG_DELETE_VALUE_KEY_ANTI_TAMPER") | eval FS_OP_Type=case(FileSystemOperationType_decimal==0,"OP_INVALID",FileSystemOperationType_decimal==1, "OP_RENAME", FileSystemOperationType_decimal==2, "OP_DELETE") | eval mitrett=tactic." via ".technique | table _time aid ComputerName event_simpleName DetectName mitrett CommandLine RegObjectName RegValueName RegStringValue RegOperationType TargetFileName SourceFileName FS_OP_Type  ContextProcessId_decimal | rename aid AS "Host ID", ComputerName AS "Host Name", event_simpleName AS "Event", DetectName AS "Detection", mitrett AS "MITRE", CommandLine as CLI, ImageFileName AS "Process Name", RegObjectName AS "Registry Object", RegValueName AS "Registry Value", RegStringValue AS "Registry String Value", RegOperationType AS "Registry Operation Type", FS_OP_Type AS "File System Operation Type"| sort - _time

#.ASXP WebShell Write
event_simpleName=NewScriptWritten* TargetFileName=*.aspx | table _time ComputerName event_simpleName TargetFileName

#Dump File EAM Search
(ExecutableDeleted OR NewExecutableRenamed OR NewExecutableWritten OR PeFileWritten OR DmpFileWritten)
|  table _time TargetFileName SourceFileName

Last updated