├── Convert-BitsToSV.ps1 ├── Convert-HandleToSV.ps1 ├── Convert-NetstatToSV.ps1 ├── Convert-SvcFailToSV.ps1 ├── Convert-SvcTrigToSV.ps1 ├── Get-HostData.ps1 ├── LICENSE ├── Mal-Seine-Common.ps1 ├── README.md └── ToDo /Convert-BitsToSV.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Convert-BitsXfersToSV.ps1 takes the output from Get-HostData.ps1's Bits Transfer 4 | collection and parses the FileList data into delimited format suitable for stack 5 | ranking via get-stakrank.ps1. 6 | 7 | .PARAMETER FileNamePattern 8 | Specifies the naming pattern common to the handle file output to be converted. 9 | .PARAMETER Delimiter 10 | Specifies the delimiter character to use for output. Tab is default. 11 | .PARAMETER ToFile 12 | Specifies that output be written to a file matching the FileNamePattern (same path), 13 | but with .tsv or .csv extension depending on delimtier (.tsv is default). 14 | #> 15 | 16 | [CmdletBinding()] 17 | Param( 18 | [Parameter(Mandatory=$True,Position=0)] 19 | [string]$FileNamePattern, 20 | [Parameter(Mandatory=$False,Position=1)] 21 | [string]$Delimiter="`t", 22 | [Parameter(Mandatory=$False,Position=2)] 23 | [switch]$tofile=$False 24 | ) 25 | 26 | 27 | function Convert { 28 | Param( 29 | [Parameter(Mandatory=$True,Position=0)] 30 | [String]$File, 31 | [Parameter(Mandatory=$True,Position=1)] 32 | [char]$Delimiter 33 | ) 34 | Write-Verbose "Entering $($MyInvocation.MyCommand)" 35 | Write-Verbose "Processing $File." 36 | $RemoteName = $Localname = $IsTransferComplete = $BytesTotal = $BytesTransferrred = $False 37 | $data = Import-Clixml $File 38 | $data | % { $_.FileList } | ConvertTo-Csv -NoTypeInformation -Delimiter $Delimiter 39 | } 40 | 41 | . .\mal-seine-common.ps1 42 | 43 | Convert-Main -FileNamePattern $FileNamePattern -Delimiter $Delimiter -tofile $tofile 44 | -------------------------------------------------------------------------------- /Convert-HandleToSV.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Convert-HandleToSV.ps1 takes the output from Sysinternals handle.exe -a and parses 4 | it into delimited format suitable for stack ranking via get-stakrank.ps1. 5 | 6 | NOTE: 7 | Handle Ids are discarded and remaining lines are deduped. 8 | 9 | .PARAMETER FileNamePattern 10 | Specifies the naming pattern common to the handle file output to be converted. 11 | .PARAMETER Delimiter 12 | Specifies the delimiter character to use for output. Tab is default. 13 | .PARAMETER ToFile 14 | Specifies that output be written to a file matching the FileNamePattern (same path), 15 | but with .tsv or .csv extension depending on delimtier (.tsv is default). 16 | #> 17 | 18 | [CmdletBinding()] 19 | Param( 20 | [Parameter(Mandatory=$True,Position=0)] 21 | [string]$FileNamePattern, 22 | [Parameter(Mandatory=$False,Position=1)] 23 | [string]$Delimiter="`t", 24 | [Parameter(Mandatory=$False,Position=2)] 25 | [switch]$tofile=$False 26 | ) 27 | 28 | function Convert { 29 | Param( 30 | [Parameter(Mandatory=$True,Position=0)] 31 | [String]$File, 32 | [Parameter(Mandatory=$True,Position=1)] 33 | [char]$Delimiter 34 | ) 35 | Write-Verbose "Entering $($MyInvocation.MyCommand)" 36 | Write-Verbose "Processing $File." 37 | $data = gc $File | select -skip 6 38 | ("Process","PId","Owner","Type","Perms","Name") -join $Delimiter 39 | foreach($line in $data) { 40 | $line = $line.Trim() 41 | if ($line -match " pid: ") { 42 | $HandleId = $Type = $Perms = $Name = $null 43 | $pattern = "(?^[-a-zA-Z0-9_.]+) pid: (?\d+) (?.+$)" 44 | if ($line -match $pattern) { 45 | $ProcessName,$ProcId,$Owner = ($matches['ProcessName'],$matches['PId'],$matches['Owner']) 46 | } 47 | } else { 48 | $pattern = "(?^[a-f0-9]+): (?\w+)" 49 | if ($line -match $pattern) { 50 | $HandleId,$Type = ($matches['HandleId'],$matches['Type']) 51 | $Perms = $Name = $null 52 | switch ($Type) { 53 | "File" { 54 | $pattern = "(?^[a-f0-9]+):\s+(?\w+)\s+(?\([-RWD]+\))\s+(?.*)" 55 | if ($line -match $pattern) { 56 | $Perms,$Name = ($matches['Perms'],$matches['Name']) 57 | } 58 | } 59 | default { 60 | $pattern = "(?^[a-f0-9]+):\s+(?\w+)\s+(?.*)" 61 | if ($line -match $pattern) { 62 | $Name = ($matches['Name']) 63 | } 64 | } 65 | } 66 | if ($Name -ne $null) { 67 | # ($ProcessName,$ProcId,$Owner,$HandleId,$Type,$Perms,$Name) -join $Delimiter 68 | ($ProcessName,$ProcId,$Owner,$Type,$Perms,$Name) -join $Delimiter 69 | } 70 | } 71 | } 72 | } 73 | } 74 | 75 | . .\mal-seine-common.ps1 76 | 77 | Convert-Main -FileNamePattern $FileNamePattern -Delimiter $Delimiter -tofile $tofile -------------------------------------------------------------------------------- /Convert-NetstatToSV.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Convert-NetstatToSV.ps1 takes the output from netstat.exe -n -a -o -b and parses 4 | it into delimited format suitable for stack ranking via get-stakrank.ps1. 5 | 6 | NOTE: This script is SPECIFICALLY WRITTEN to parse Windows netstat.exe output 7 | WITH THE -a -o and -b ARGUMENTS! If your data set does not include these args, 8 | this script's OUTPUT WILL BE WRONG! Yes, -n is optional, but recommended. 9 | 10 | .PARAMETER FileNamePattern 11 | Specifies the naming pattern common to the netstat files to be converted. 12 | .PARAMETER Delimiter 13 | Specifies the delimiter character to use for output. Tab is default. 14 | .PARAMETER ToFile 15 | Specifies that output be written to a file matching the FileNamePattern (same path), 16 | but with .tsv or .csv extension depending on delimtier (.tsv is default). 17 | #> 18 | 19 | [CmdletBinding()] 20 | Param( 21 | [Parameter(Mandatory=$True,Position=0)] 22 | [string]$FileNamePattern, 23 | [Parameter(Mandatory=$False,Position=1)] 24 | [string]$Delimiter="`t", 25 | [Parameter(Mandatory=$False,Position=2)] 26 | [switch]$tofile=$False 27 | ) 28 | 29 | function Convert { 30 | Param( 31 | [Parameter(Mandatory=$True,Position=0)] 32 | [String]$File, 33 | [Parameter(Mandatory=$True,Position=1)] 34 | [char]$Delimiter 35 | ) 36 | Write-Verbose "Entering $($MyInvocation.MyCommand)" 37 | Write-Verbose "Processing $File." 38 | $data = gc $File 39 | ("Protocol","LocalAddress","LocalPort","ForeignAddress","ForeignPort","State","PId","Component","Process") -join $Delimiter 40 | foreach($line in $data) { 41 | if ($line.length -gt 1 -and $line -notmatch "Active |Proto ") { 42 | $line = $line.trim() 43 | if ($line.StartsWith("TCP")) { 44 | $Protocol, $LocalAddress, $ForeignAddress, $State, $ConPId = ($line -split '\s{2,}') 45 | $Component = $Process = $False 46 | } elseif ($line.StartsWith("UDP")) { 47 | $State = "STATELESS" 48 | $Protocol, $LocalAddress, $ForeignAddress, $ConPid = ($line -split '\s{2,}') 49 | $Component = $Process = $False 50 | } elseif ($line -match "^\[[-_a-zA-Z0-9.]+\.(exe|com|ps1)\]$") { 51 | $Process = $line 52 | if ($Component -eq $False) { 53 | # No Component given 54 | $Component = $Process 55 | } 56 | } elseif ($line -match "Can not obtain ownership information") { 57 | $Process = $Component = $line 58 | } else { 59 | # We have the $Component 60 | $Component = $line 61 | } 62 | if ($State -match "TIME_WAIT") { 63 | $Component = "Not provided" 64 | $Process = "Not provided" 65 | } 66 | if ($Component -and $Process) { 67 | $LocalAddress, $LocalPort = Get-AddrPort($LocalAddress) 68 | $ForeignAddress, $ForeignPort = Get-AddrPort($ForeignAddress) 69 | ($Protocol, $LocalAddress, $LocalPort, $ForeignAddress, $ForeignPort, $State, $ConPid, $Component, $Process) -join $Delimiter 70 | } 71 | } 72 | } 73 | Write-Verbose "Exiting $($MyInvocation.MyCommand)" 74 | } 75 | 76 | function Get-AddrPort { 77 | Param( 78 | [Parameter(Mandatory=$True,Position=0)] 79 | [String]$AddrPort 80 | ) 81 | Write-Verbose "Entering $($MyInvocation.MyCommand)" 82 | Write-Verbose "Processing $AddrPort" 83 | if ($AddrPort -match '[0-9a-f]*:[0-9a-f]*:[0-9a-f%]*\]:[0-9]+') { 84 | $Addr, $Port = $AddrPort -split "]:" 85 | $Addr += "]" 86 | } else { 87 | $Addr, $Port = $AddrPort -split ":" 88 | } 89 | $Addr, $Port 90 | Write-Verbose "Exiting $($MyInvocation.MyCommand)" 91 | } 92 | . .\mal-seine-common.ps1 93 | 94 | Convert-Main -FileNamePattern $FileNamePattern -Delimiter $Delimiter -tofile $tofile -------------------------------------------------------------------------------- /Convert-SvcFailToSV.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Convert-SvcFailToSV.ps1 takes the output from Get-HostData.ps1's Service Failure 4 | collection and parses it into delimited format suitable for stack ranking via 5 | get-stakrank.ps1. 6 | 7 | .PARAMETER FileNamePattern 8 | Specifies the naming pattern common to the handle file output to be converted. 9 | .PARAMETER Delimiter 10 | Specifies the delimiter character to use for output. Tab is default. 11 | .PARAMETER ToFile 12 | Specifies that output be written to a file matching the FileNamePattern (same path), 13 | but with .tsv or .csv extension depending on delimtier (.tsv is default). 14 | #> 15 | 16 | [CmdletBinding()] 17 | Param( 18 | [Parameter(Mandatory=$True,Position=0)] 19 | [string]$FileNamePattern, 20 | [Parameter(Mandatory=$False,Position=1)] 21 | [string]$Delimiter="`t", 22 | [Parameter(Mandatory=$False,Position=2)] 23 | [switch]$tofile=$False 24 | ) 25 | 26 | function Convert { 27 | Param( 28 | [Parameter(Mandatory=$True,Position=0)] 29 | [String]$File, 30 | [Parameter(Mandatory=$True,Position=1)] 31 | [char]$Delimiter 32 | ) 33 | Write-Verbose "Entering $($MyInvocation.MyCommand)" 34 | Write-Verbose "Processing $File." 35 | $ServiceName = $RstPeriod = $RebootMsg = $CmdLine = $FailAction1 = $FailAction2 = $FailAction3 = $False 36 | $data = gc $File 37 | ("ServiceName","ResetPeriod","RebootMessage","CommandLine", "FailureAction1", "FailureAction2", "FailureAction3") -join $Delimiter 38 | foreach($line in $data) { 39 | if ($line.StartsWith("[SC]")) { 40 | continue 41 | } 42 | $line = $line.Trim() 43 | if ($line -match "^S.*\:\s(?[-_A-Za-z0-9]+)") { 44 | if ($ServiceName) { 45 | ($ServiceName,$RstPeriod,$RebootMsg,$CmdLine,$FailAction1,$FailAction2,$FailAction3) -replace "False", $null -join $Delimiter 46 | $ServiceName = $RstPeriod = $RebootMsg = $CmdLine = $FailAction1 = $FailAction2 = $FailAction3 = $False 47 | } 48 | $ServiceName = $matches['SvcName'] 49 | } elseif ($line -match "^RESE.*\:\s(?[0-9]+|INFINITE)") { 50 | $RstPeriod = $matches['RstP'] 51 | } elseif ($line -match "^REB.*\:\s(?.*)") { 52 | $RebootMsg = $matches['RbtMsg'] 53 | } elseif ($line -match "^C.*\:\s(?.*)") { 54 | $CmdLine = $matches['Cli'] 55 | } elseif ($line -match "^F.*\:\s(?.*)") { 56 | $FailAction1 = $matches['Fail1'] 57 | $FailAction2 = $FailAction3 = $False 58 | } elseif ($line -match "^(?REST.*)") { 59 | if ($FailAction2) { 60 | $FailAction3 = $matches['FailNext'] 61 | } else { 62 | $FailAction2 = $matches['FailNext'] 63 | } 64 | } 65 | } 66 | ($ServiceName,$RstPeriod,$RebootMsg,$CmdLine,$FailAction1,$FailAction2,$FailAction3) -replace "False", $null -join $Delimiter 67 | } 68 | . .\mal-seine-common.ps1 69 | 70 | Convert-Main -FileNamePattern $FileNamePattern -Delimiter $Delimiter -tofile $tofile -------------------------------------------------------------------------------- /Convert-SvcTrigToSV.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Convert-SvcTrigsToSV.ps1 takes the output from Get-HostData.ps1's Service Trigger 4 | collection and parses it into delimited format suitable for stack ranking via 5 | get-stakrank.ps1. 6 | 7 | .PARAMETER FileNamePattern 8 | Specifies the naming pattern common to the handle file output to be converted. 9 | .PARAMETER Delimiter 10 | Specifies the delimiter character to use for output. Tab is default. 11 | .PARAMETER ToFile 12 | Specifies that output be written to a file matching the FileNamePattern (same path), 13 | but with .tsv or .csv extension depending on delimtier (.tsv is default). 14 | .PARAMETER NameProviders 15 | Looks up LogProviders names and where matches are found, replaces GUIDs with "friendly" 16 | names. 17 | #> 18 | 19 | [CmdletBinding()] 20 | Param( 21 | [Parameter(Mandatory=$True,Position=0)] 22 | [string]$FileNamePattern, 23 | [Parameter(Mandatory=$False,Position=1)] 24 | [string]$Delimiter="`t", 25 | [Parameter(Mandatory=$False,Position=2)] 26 | [switch]$tofile=$False, 27 | [Parameter(Mandatory=$False,Position=3)] 28 | [switch]$NameProviders=$False 29 | ) 30 | 31 | function Get-LogProviderHash { 32 | Write-Verbose "Entering $($MyInvocation.MyCommand)" 33 | $LogProviders = @{} 34 | foreach ($provider in (& $env:windir\system32\logman.exe query providers)) { 35 | if ($provider -match "\{") { 36 | $LogName, $LogGuid = ($provider -split "{") -replace "}" 37 | $LogName = $LogName.Trim() 38 | $LogGuid = $LogGuid.Trim() 39 | if ($LogProviders.ContainsKey($LogGuid)) {} else { 40 | Write-Verbose "Adding ${LogGuid}:${LogName} to `$LogProviders hash." 41 | $LogProviders.Add($LogGuid, $LogName) 42 | } 43 | } 44 | } 45 | $LogProviders 46 | Write-Verbose "Exiting $($MyInvocation.MyCommand)" 47 | } 48 | 49 | function Convert { 50 | Param( 51 | [Parameter(Mandatory=$True,Position=0)] 52 | [String]$File, 53 | [Parameter(Mandatory=$True,Position=1)] 54 | [char]$Delimiter, 55 | [Parameter(Mandatory=$False,Position=2)] 56 | [hashtable]$LogProviders 57 | ) 58 | Write-Verbose "Entering $($MyInvocation.MyCommand)" 59 | Write-Verbose "Processing $File." 60 | $ServiceName = $Action = $Condition = $Value = $False 61 | $CondPattern = '(?[-_ A-Za-z0-9]+)\s:\s(?[-0-9a-fA-F]+)\s(?[-\[A-Za-z0-9 ]+\]*)' 62 | $data = gc $File 63 | ("ServiceName","Action","Condition","Value") -join $Delimiter 64 | foreach($line in $data) { 65 | $line = $line.Trim() 66 | if ($line -match "SERVICE_NAME:\s(?[-_A-Za-z0-9]+)") { 67 | if ($ServiceName) { 68 | ($ServiceName,$Action,$Condition,$Value) -replace "False", $null -join $Delimiter 69 | } 70 | $ServiceName = $matches['SvcName'] 71 | $Action = $Condition = $Value = $False 72 | } elseif ($line -match "(START SERVICE|STOP SERVICE)") { 73 | if ($ServiceName -and $Action -and $Condition) { 74 | ($ServiceName,$Action,$Condition,$Value) -replace "False", $null -join $Delimiter 75 | } 76 | $Action = ($matches[1]) 77 | $Condition = $Value = $False 78 | } elseif ($line -match "DATA\s+") { 79 | $Value = $line -replace "\s+", " " 80 | } else { 81 | $Condition = $line -replace "\s+", " " 82 | if ($LogProviders) { 83 | $ProviderName = $False 84 | if ($Condition -match $CondPattern) { 85 | $Guid = $($matches['Guid']).ToUpper() 86 | $ProviderName = $LogProviders.$Guid 87 | if ($ProviderName) { 88 | $Condition = ($matches['Desc'] + ": " + $LogProviders.$Guid) #+ " " + $matches['Trailer']) 89 | } 90 | } 91 | } 92 | $Value = $False 93 | } 94 | } 95 | ($ServiceName,$Action,$Condition,$Value) -replace "False", $null -join $Delimiter 96 | } 97 | 98 | . .\mal-seine-common.ps1 99 | 100 | if ($NameProviders) { 101 | $LogProviders = Get-LogProviderHash 102 | 103 | $Files = Get-Files -FileNamePattern $FileNamePattern 104 | 105 | foreach ($File in $Files) { 106 | $data = Convert $File $Delimiter $LogProviders 107 | if ($tofile) { 108 | $path = ls $File 109 | $outpath = $path.DirectoryName + "\" + $path.BaseName 110 | if ($Delimiter -eq "`t") { 111 | $outpath += ".tsv" 112 | } elseif ($Delimiter -eq ",") { 113 | $outpath += ".csv" 114 | } else { 115 | $outpath += ".sv" 116 | } 117 | Write-Verbose "Writing output to ${outpath}." 118 | $data | Select -Unique | Set-Content -Encoding Ascii $outpath 119 | } else { 120 | $data | Select -Unique 121 | } 122 | } 123 | } else { 124 | Convert-Main -FileNamePattern $FileNamePattern -Delimiter $Delimiter -tofile $tofile 125 | } -------------------------------------------------------------------------------- /Get-HostData.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | A reference script for collecting data from hosts in an organization when seining for evil. 4 | What does the script collect: 5 | 1. Prefetch 6 | 2. Processes using Powershell Get-Process (includes modules, threads, etc.) 7 | 3. Processes using tasklist (includes owner) 8 | 4. Open handles using Sysinternals Handle.exe 9 | 5. DNS cache 10 | 6. ARP cache 11 | 7. Netstat with process name and PID 12 | 8. Autoruns using Sysinternals Autorunsc.exe 13 | 9. Bits Transfers 14 | 10. Service Triggers 15 | 11. Service failures 16 | 12. WMI Event Consumers 17 | 13. Powershell profiles 18 | 19 | All output is copied to a zip archive for offline analysis. 20 | 21 | I have run this script or slight variations of it over 10s of 1000s of hosts at a time and performed analysis beginning 22 | with stack ranking the data (see https://github.com/davehull/Get-StakRank#get-stakrank) and reviewing outliers. There 23 | are commercial products that will gather much of this data, and in more robust ways, bypassing the WinAPI and scraping 24 | memory for process and networking artifacts, but those tools can take hours to run depending on the amount of RAM in 25 | the box. This script takes a couple minutes per host. 26 | 27 | Average size of collected data is around 1.5 - 2 MiB with compression. Uncompressed data averages around 10 - 12MiB per 28 | host, but YMMV depending on what your hosts are doing. 29 | #> 30 | 31 | $sharename = "\\CONFIGURE\THIS" 32 | # $sharename = ".\" 33 | # make a \bin\ dir in the share for latest version of Sysinternals autorunsc.exe and handle.exe 34 | # available from http://technet.microsoft.com/en-us/sysinternals 35 | 36 | 37 | if ($sharename -match "CONFIGURE") { 38 | Write-Host "`n[*] ERROR: You must edit the script and configure a share for the data to be written to, and for autorunsc.exe to be run from.`n" 39 | Exit 40 | } 41 | 42 | #put autorunsc.exe, handle.exe in the following path 43 | $sharebin = $sharename + "\bin\" 44 | 45 | $temp = $env:temp 46 | $this_computer = $($env:COMPUTERNAME) 47 | $zipfile = $temp + "\" + $this_computer + "_bh.zip" 48 | $ErrorLog = $temp + "\" + $this_computer + "_error.log" 49 | 50 | 51 | # get prefetch listing 52 | $pfconf = (gp "hklm:\system\currentcontrolset\control\session manager\memory management\prefetchparameters").EnablePrefetcher 53 | Switch -Regex ($pfconf) { 54 | "[1-3]" { 55 | $pffiles = $temp + "\" + $this_computer + "_pffiles.txt" 56 | ls $env:windir\Prefetch\*.pf | Set-Content -Encoding Ascii $pffiles 57 | } 58 | default { } 59 | } 60 | 61 | # get process data 62 | $procout = $temp + "\" + $this_computer + "_prox.xml" 63 | Get-Process | Export-Clixml $procout 64 | 65 | # tasklist gives username 66 | $tlist = $temp + "\" + $this_computer + "_tlist.csv" 67 | & tasklist.exe /v /fo csv | Set-Content -Encoding Ascii $tlist 68 | 69 | # get handle 70 | $handleout = $temp + "\" + $this_computer + "_handle.txt" 71 | & "$sharebin\handle.exe" /accepteula -a | Set-Content -Encoding Ascii $handleout 72 | 73 | # get dnscache 74 | $dnsout = $temp + "\" + $this_computer + "_dnscache.txt" 75 | & ipconfig.exe /displaydns | Select-String 'Record Name' | ForEach-Object { $_.ToString().Split(' ')[-1] } | ` 76 | select -Unique | sort | Set-Content -Encoding Ascii $dnsout 77 | 78 | # get arp cache 79 | $arpout = $temp + "\" + $this_computer + "_arp.txt" 80 | & ARP.EXE -a | Set-Content -Encoding Ascii $arpout 81 | 82 | # get netstat 83 | $netstatout = $temp + "\" + $this_computer + "_netstat.txt" 84 | & NETSTAT.EXE -n -a -o -b | Set-Content -Encoding Ascii $netstatout 85 | 86 | # get autoruns 87 | $arunsout = $temp + "\" + $this_computer + "_aruns.csv" 88 | & "$sharebin\autorunsc.exe" /accepteula -a -c -v -f '*' | Set-Content -Encoding Ascii $arunsout 89 | 90 | # get bits transfers 91 | $bitsxferout = $temp + "\" + $this_computer + "_bitsxfer.xml" 92 | Get-BitsTransfer -AllUsers | Export-Clixml $bitsxferout 93 | 94 | # get service triggers 95 | $svctrigout = $temp + "\" + $this_computer + "_svctriggers.txt" 96 | $($(foreach ($svc in (& c:\windows\system32\sc query)) { 97 | if ($svc -match "SERVICE_NAME:\s(.*)") { 98 | & c:\windows\system32\sc qtriggerinfo $($matches[1]) 99 | } 100 | })|?{$_.length -gt 1 -and $_ -notmatch "\[SC\] QueryServiceConfig2 SUCCESS|has not registered for any" }) | Set-Content -Encoding Ascii $svctrigout 101 | 102 | # get service failure 103 | $svcfailout = $temp + "\" + $this_computer + "_svcfailout.txt" 104 | $($(foreach ($svc in (& c:\windows\system32\sc query)) { 105 | if ($svc -match "SERVICE_NAME:\s(.*)") { 106 | & c:\windows\system32\sc qfailure $($matches[1])}})) | Set-Content -Encoding Ascii $svcfailout 107 | 108 | # get wmi event consumers 109 | $wmievtconsmr = $temp + "\" + $this_computer + "_wmievtconsmr.xml" 110 | Get-WmiObject -Namespace root\subscription -ComputerName $this_computer -Query "select * from __EventConsumer" | Export-Clixml $wmievtconsmr 111 | 112 | $wmievtfilter = $temp + "\" + $this_computer + "_wmievtfilter.xml" 113 | Get-WmiObject -Namespace root\subscription -ComputerName $this_computer -Query "select * from __EventFilter" | Export-Clixml $wmievtfilter 114 | 115 | $wmievtfltbind = $temp + "\" + $this_computer + "_wmievtfltbind.xml" 116 | Get-WmiObject -Namespace root\subscription -ComputerName $this_computer -Query "select * from __FilterToConsumerBinding" | Export-Clixml $wmievtfltbind 117 | 118 | # get powershell profiles 119 | $alluserprofile = ($env:windir + "\System32\WindowsPowershell\v1.0\Microsoft.Powershell_profile.ps1") 120 | if (Test-Path $alluserprofile) { 121 | $psalluserprofile = $temp + "\" + $this_computer + "_alluserprofile.txt" 122 | gc $alluserprofile | Set-Content -Encoding Ascii $psalluserprofile 123 | } 124 | 125 | $psuserprofiles = $temp + "\" + $this_computer + "_userprofiles.txt" 126 | $null | Set-Content -Encoding Ascii $psuserprofiles 127 | foreach($path in (gwmi win32_userprofile | select localpath -ExpandProperty localpath)) { 128 | $prfile = ($path + "\Documents\WindowsPowershell\Microsoft.Powershell_profile.ps1") 129 | if (Test-Path $prfile) { 130 | $("Profile ${prfile}:"; gc $prfile) | Add-Content -Encoding Ascii $psuserprofiles 131 | } 132 | } 133 | 134 | 135 | # check for locked files 136 | function Test-FileLock { 137 | param([parameter(Mandatory=$true)] 138 | [string]$Path 139 | ) 140 | 141 | $oFile = New-Object System.IO.FileInfo $Path 142 | 143 | if ((Test-Path -Path $Path) -eq $false) 144 | { 145 | $false 146 | return 147 | } 148 | 149 | try { 150 | $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) 151 | if ($oStream) { 152 | $oStream.Close() 153 | } 154 | $false 155 | } 156 | catch { 157 | $true 158 | } 159 | } 160 | 161 | 162 | # consolidate all 163 | function add-zip 164 | { 165 | param([string]$zipfilename) 166 | 167 | if (-not (Test-Path($zipfilename))) { 168 | Set-Content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 169 | (dir $zipfilename).IsReadOnly = $false 170 | } 171 | 172 | $shellApplication = New-Object -com shell.application 173 | $zipPackage = $shellApplication.NameSpace($zipfilename) 174 | 175 | foreach($file in $input) { 176 | $zipPackage.CopyHere($file.FullName) 177 | Start-Sleep -milliseconds 500 178 | } 179 | } 180 | 181 | # wait for locked zipfile 182 | function ziplock 183 | { 184 | param([string]$zipfilename) 185 | $tries = 0 186 | while ($tries -lt 100) { 187 | if (Test-FileLock($zipfile)) { 188 | Start-Sleep -seconds 1 189 | $tries++ 190 | continue 191 | } else { 192 | break 193 | } 194 | } 195 | } 196 | 197 | try { 198 | if (Test-Path $dnsout -ErrorAction SilentlyContinue) { 199 | ls $dnsout | add-zip $zipfile 200 | Write-Verbose "`$dnsout added" 201 | ziplock $zipfile 202 | rm $dnsout 203 | } 204 | } catch { 205 | $_.Exception.Message | Add-Content $ErrorLog 206 | } 207 | 208 | try { 209 | if (Test-Path $procout -ErrorAction SilentlyContinue) { 210 | ls $procout | add-zip $zipfile 211 | Write-Verbose "`$procout added" 212 | ziplock $zipfile 213 | rm $procout 214 | } 215 | } catch { 216 | $_.Exception.Message | Add-Content $ErrorLog 217 | } 218 | 219 | try { 220 | if (Test-Path $tlist -ErrorAction SilentlyContinue) { 221 | ls $tlist | add-zip $zipfile 222 | Write-Verbose "`$tlist added" 223 | ziplock $zipfile 224 | rm $tlist 225 | } 226 | } catch { 227 | $_.Exception.Message | Add-Content $ErrorLog 228 | } 229 | 230 | try { 231 | if (Test-Path $arpout -ErrorAction SilentlyContinue) { 232 | ls $arpout | add-zip $zipfile 233 | Write-Verbose "`$arpout added" 234 | ziplock $zipfile 235 | rm $arpout 236 | } 237 | } catch { 238 | $_.Exception.Message | Add-Content $ErrorLog 239 | } 240 | 241 | try { 242 | if (Test-Path $netstatout -ErrorAction SilentlyContinue) { 243 | ls $netstatout | add-zip $zipfile 244 | Write-Verbose "`$netstatout added" 245 | ziplock $zipfile 246 | rm $netstatout 247 | } 248 | } catch { 249 | $_.Exception.Message | Add-Content $ErrorLog 250 | } 251 | 252 | try { 253 | if (Test-Path $arunsout -ErrorAction SilentlyContinue) { 254 | ls $arunsout | add-zip $zipfile 255 | Write-Verbose "`$arunsout added" 256 | ziplock $zipfile 257 | rm $arunsout 258 | } 259 | } catch { 260 | $_.Exception.Message | Add-Content $ErrorLog 261 | } 262 | 263 | try { 264 | if (Test-Path $handleout -ErrorAction SilentlyContinue) { 265 | ls $handleout | add-zip $zipfile 266 | Write-Verbose "`$handleout added" 267 | ziplock $zipfile 268 | rm $handleout 269 | } 270 | } catch { 271 | $_.Exception.Message | Add-Content $ErrorLog 272 | } 273 | 274 | try { 275 | if (Test-Path $bitsxferout -ErrorAction SilentlyContinue) { 276 | ls $bitsxferout | add-zip $zipfile 277 | Write-Verbose "`$bitsxferout added" 278 | ziplock $zipfile 279 | rm $bitsxferout 280 | } 281 | } catch { 282 | $_.Exception.Message | Add-Content $ErrorLog 283 | } 284 | 285 | try { 286 | if (Test-Path $svctrigout -ErrorAction SilentlyContinue) { 287 | ls $svctrigout | add-zip $zipfile 288 | Write-Verbose "`$svctrigout added" 289 | ziplock $zipfile 290 | rm $svctrigout 291 | } 292 | } catch { 293 | $_.Exception.Message | Add-Content $ErrorLog 294 | } 295 | 296 | try { 297 | if (Test-Path $svcfailout -ErrorAction SilentlyContinue) { 298 | ls $svcfailout | add-zip $zipfile 299 | Write-Verbose "`$svcfailout added" 300 | ziplock $zipfile 301 | rm $svcfailout 302 | } 303 | } catch { 304 | $_.Exception.Message | Add-Content $ErrorLog 305 | } 306 | 307 | try { 308 | if (Test-Path $wmievtconsmr -ErrorAction SilentlyContinue) { 309 | ls $wmievtconsmr | add-zip $zipfile 310 | Write-Verbose "`$wmievtconsmr added" 311 | ziplock $zipfile 312 | rm $wmievtconsmr 313 | } 314 | } catch { 315 | $_.Exception.Message | Add-Content $ErrorLog 316 | } 317 | 318 | try { 319 | if (Test-Path $psalluserprofile -ErrorAction SilentlyContinue) { 320 | ls $psalluserprofile | add-zip $zipfile 321 | Write-Verbose "`$psalluserprofile added" 322 | ziplock $zipfile 323 | rm $psalluserprofile 324 | } 325 | } catch { 326 | $_.Exception.Message | Add-Content $ErrorLog 327 | } 328 | 329 | try { 330 | if (Test-Path $psuserprofiles -ErrorAction SilentlyContinue) { 331 | ls $psuserprofiles | add-zip $zipfile 332 | Write-Verbose "`$psuserprofiles added" 333 | ziplock $zipfile 334 | rm $psuserprofiles 335 | } 336 | } catch { 337 | $_.Exception.Message | Add-Content $ErrorLog 338 | } 339 | 340 | try { 341 | if (Test-path $pffiles -ErrorAction SilentlyContinue) { 342 | ls $pffiles | add-zip $zipfile 343 | Write-Verbose "`$pffiles added" 344 | ziplock $zipfile 345 | rm $pffiles 346 | } 347 | } catch { 348 | $_.Exception.Message | Add-Content $ErrorLog 349 | } 350 | 351 | copy $zipfile $sharename 352 | 353 | ls $ErrorLog | add-zip $zipfile 354 | ziplock $zipfile 355 | rm $zipfile -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /Mal-Seine-Common.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | .SYNOPSIS 3 | Common functions used by more than one of the Mal-Seine scripts. 4 | #> 5 | 6 | function Get-Files { 7 | <# 8 | .SYNOPSIS 9 | Returns the list of input files matching the user supplied file name pattern. 10 | Traverses subdirectories. 11 | #> 12 | Param( 13 | [Parameter(Mandatory=$True,Position=0)] 14 | [String]$FileNamePattern 15 | ) 16 | Write-Verbose "Entering $($MyInvocation.MyCommand)" 17 | Write-Verbose "Looking for files matching user supplied pattern, $FileNamePattern" 18 | Write-Verbose "This process traverses subdirectories so it may take some time." 19 | $Files = @(ls -r $FileNamePattern | % { $_.FullName }) 20 | if ($Files) { 21 | Write-Verbose "File(s) matching pattern, ${FileNamePattern}:`n$($Files -join "`n")" 22 | $Files 23 | } else { 24 | Write-Error "No input files were found matching the user supplied pattern, ` 25 | ${FileNamePattern}." 26 | Write-Verbose "Exiting $($MyInvocation.MyCommand)" 27 | exit 28 | } 29 | Write-Verbose "Exiting $($MyInvocation.MyCommand)" 30 | } 31 | 32 | function Convert-Main { 33 | <# 34 | .SYNOPSIS 35 | Main function that drives multiple conversion scripts. 36 | #> 37 | Param( 38 | [Parameter(Mandatory=$True,Position=0)] 39 | [string]$FileNamePattern, 40 | [Parameter(Mandatory=$True,Position=1)] 41 | [char]$Delimiter, 42 | [Parameter(Mandatory=$True,Position=2)] 43 | [boolean]$tofile=$False 44 | ) 45 | 46 | $Files = Get-Files -FileNamePattern $FileNamePattern 47 | 48 | foreach ($File in $Files) { 49 | $data = Convert $File $Delimiter 50 | if ($tofile) { 51 | $path = ls $File 52 | $outpath = $path.DirectoryName + "\" + $path.BaseName 53 | if ($Delimiter -eq "`t") { 54 | $outpath += ".tsv" 55 | } elseif ($Delimiter -eq ",") { 56 | $outpath += ".csv" 57 | } else { 58 | $outpath += ".sv" 59 | } 60 | Write-Verbose "Writing output to ${outpath}." 61 | $data | Select -Unique | Set-Content -Encoding Ascii $outpath 62 | } else { 63 | $data | Select -Unique 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Mal-Seine 2 | ========= 3 | 4 | If you're looking at this, you should check out Kansa (https://github.com/davehull/Kansa). 5 | 6 | A reference script for collecting data from hosts in an organization when seining for evil. 7 | What does the script collect: 8 | 1. Prefetch 9 | 2. Processes using Powershell Get-Process (includes modules, threads, etc.) 10 | 3. Processes using tasklist (includes owner) 11 | 4. Open handles using Sysinternals Handle.exe 12 | 5. DNS cache 13 | 6. ARP cache 14 | 7. Netstat with process name and PID 15 | 8. Autoruns using Sysinternals Autorunsc.exe 16 | 9. Bits Transfers 17 | 10. Service Triggers 18 | 11. Service failures 19 | 12. WMI Event Consumers 20 | 13. Powershell profiles 21 | 22 | All output is copied to a zip archive for offline analysis. 23 | 24 | I have run this script or slight variations of it over 10s of 1000s of hosts at time and performed analysis beginning with stack ranking the data (see https://github.com/davehull/Get-StakRank#get-stakrank) and reviewing outliers. There are commercial products that will gather much of this data, and in more robust ways, bypassing the WinAPI and scraping memory for process and networking artifacts, but those tools can take hours to run depending on the amount of RAM in the box. This script takes a couple minutes per host. 25 | 26 | Average size of collected data is around 1.5 - 2 MiB with compression. Uncompressed data averages around 10 - 12MiB per 27 | host, but YMMV depending on what your hosts are doing. 28 | 29 | Some of the collected data doesn't immediately lend itself to easy analysis. You can use the conversion scripts to convert those data sets to delimited values that can be stack ranked, loaded into Excel, a database or other analysis tools. These include: 30 | 1. Convert-NetstatToSV.ps1 31 | 2. Convert-HandleToSV.ps1 32 | 3. Convert-SvcTrigToSV.ps1 33 | 4. Convert-SvcFailToSV.ps1 34 | 5. Convert-BitsToSV.ps1 35 | -------------------------------------------------------------------------------- /ToDo: -------------------------------------------------------------------------------- 1 | 1. Incorporate post-processing modules into collection script, test timing and utilization issues around doing 2 | conversions at the time of collection on the hosts where collection is happening. Possibly provide a command-line 3 | flag to make it optional to do the conversions at collection time. 4 | 2. Add sigcheck collector. 5 | 6 | 7 | Done: Add logic to pull local powershell profiles. 8 | --------------------------------------------------------------------------------