Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Powershell Website "Ping" using the winsystems web proxy

If you want to monitor/check (every 10s) continuesly if a website (in this exampe http://www.google.de) is reachable using powershell and also using the configured webproxy in your windows system, then you can use the following example:


while ($true) {
    $webClient = New-Object System.Net.WebClient
    $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
    $proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
    $webClient.Proxy = $proxy

    $proxyUri = $proxy.GetProxy([System.Uri]::new("http://www.google.de"))
    $proxyIp = $proxyUri.Host
    $proxyPort = $proxyUri.Port

    $startTime = Get-Date
    try {
        $response = $webClient.DownloadString("http://www.google.de")
        $endTime = Get-Date
        $latency = ($endTime - $startTime).TotalMilliseconds
        $statusCode = 200 # WebClient doesn't expose status code directly, assuming success here
        Write-Output "[$startTime] Latency: ${latency}ms, HTTP Status Code: $statusCode, Proxy:         $proxyIp :$proxyPort"
    } catch {
        $endTime = Get-Date
        $latency = ($endTime - $startTime).TotalMilliseconds
        $errorMessage = $_.Exception.Message
        Write-Output "[$startTime] Latency: ${latency}ms, Error: $errorMessage, Proxy: $proxyIp :$proxyPort"
    }

Start-Sleep -Seconds 10
}


powershell "ping" of website using proxy


Security Testing - Review LAPS

It is a good idea to review your companys Microsoft's Local Administrator Password Solution LAPS installation. Leo Loobeek published a nice powershell-script which helps in finding groups which are specifically delegated by sysadmins and finding users with "All Extended Rights" that can view passwords, and viewing all computers with LAPS enabled.

https://github.com/leoloobeek/LAPSToolkit
https://github.com/leoloobeek/LAPSToolkit/blob/master/LAPSToolkit.ps1

  • Get-LAPSComputers
    Displays all computers with LAPS enabled, password expriation, and password if user has access

  • Find-LAPSDelegatedGroups
    Searches through all OUs to see which AD groups can read the ms-Mcs-AdmPwd attribute

  • Find-AdmPwdExtendedRights
    Parses through ExtendedRights for each AD computer with LAPS enabled and looks for which group has read access and if any user has "All Extended Rights". Sysadmins may not be aware the users with All Extended Rights can view passwords and may be less protected than the users in the delegated groups. An example is the user which adds a computer to the domain automatically receives the "All Extended Rights" permission. Since this function will parse ACLs for each AD computer, this can take very long with a larger domain.
I've seen installations, where LAPS was implemented to improve security. However due to wrong configuration way to many people where able to read passwords in Active Directory (Mitre Att&ck Tactic Credential Access)

Splunk PowerShell SIEM use cases from splunk .conf

Ryan Kovar and Steve Brant from Splunk released on Splunk .conf 2016 a bunch of useful PowerShell SIEM use cases: https://conf.splunk.com/files/2016/slides/hunting-the-known-unknowns-the-powershell-edition.pdf

Finding Un-­encoded IEX Acivity  

Splunk search: sourcetype="WinEventLog:Security" Process_Command_Line=* | evalProcess_Command_Line=lower(Process_Command_Line) | search Process_Command_Line="*iex (new-­‐object net.webclient).downloadstring(*" | stats VALUES(Process_Command_Line) BY host

Screenshot Page 70 from https://conf.splunk.com/files/2016/slides/hunting-the-known-unknowns-the-powershell-edition.pdf

Source: Page 69 and 70 from https://conf.splunk.com/files/2016/slides/hunting-the-known-unknowns-the-powershell-edition.pdf

New Process Started (EventCode 4688)

Splunk search: index=windows source="WinEventLog:Security" (EventCode=4688) NOT (Account_Name=*$) (at.exe OR bcdedit.exe OR chcp.exe OR cmd.exe OR cscript.exe OR ipconfig.exe OR mimikatz.exe OR nbtstat.exe OR nc.exe OR netcat.exe OR netstat.exe OR nmap OR nslookup.exe OR bcp.exe OR sqlcmd.exe OR OSQL.exe OR ping.exe OR powershell.exe OR powercat.ps1 OR psexec.exe OR psexecsvc.exe OR psLoggedOn.exe OR procdump.exe OR rar.exeOR reg.exe OR route.exe OR runas.exe OR sc.exe OR schtasks.exe OR sethc.exe OR ssh.exe OR sysprep.exe OR systeminfo.exe OR system32\\net.exe OR tracert.exe OR vssadmin.exe OR whoami.exe OR winrar.exe OR wscript.exe OR winrm.* OR winrs.* OR wmic.exe OR wsmprovhost.exe) | evalMessage=split(Message,".") | evalShort_Message=mvindex(Message,0) | table _Ome, host, Account_Name, Process_Name, Process_ID, Process_Command_Line, New_Process_Name, New_Process_ID, Creator_Process_ID, Short_Message

Page 83 from https://conf.splunk.com/files/2016/slides/hunting-the-known-unknowns-the-powershell-edition.pdf
 

Source: Page 82 and 83 from https://conf.splunk.com/files/2016/slides/hunting-the-known-unknowns-the-powershell-edition.pdf

Finding Modules (EventCode 4103 or 4104)  

Splunk search: sourcetype="WinEventLog:Microsoft-Windows-PowerShell/Operational" (EventCode=4104) OR (EventCode=4103)(Set-ExecutionPolicyOR Set-MasterBootRecordl OR Get-WMIObject OR Get-GPPPassword OR Get-Keystrokes OR Get-TimedScreenshot OR Get-VaultCredential OR GetServiceUnquoted OR Get-ServiceEXEPerms OR Get-ServicePerms OR Get-RegAlwaysInstallElevated OR Get-RegAutoLogon OR Get-UnattendedInstallFiles OR Get-Webconfig OR Get-ApplicationHost OR Get-PassHashes OR Get-LsaSecret OR GetInformation OR Get-PSADForestInfo OR Get-KerberosPolicy OR Get-PSADForestKRBTGTInfo OR Get-PSADForestInfo OR GetKerberosPolicy OR Invoke-Command OR Invoke-Expression OR iex OR Invoke-Shellcode OR Invoke--Shellcode OR Invoke-ShellcodeMSIL OR InvokeMimikatzWDigestDowngrade OR Invoke-NinjaCopy OR Invoke-CredentialInjection OR Invoke-TokenManipulation OR InvokeCallbackIEX OR Invoke-PSInject OR Invoke-DllEncode OR Invoke-ServiceUserAdd OR Invoke-ServiceCMDOR Invoke-ServiceStart OR Invoke-ServiceStop OR Invoke-ServiceEnable OR Invoke-ServiceDisable OR Invoke-FindDLLHijack OR Invoke-FindPathHijack OR Invoke-AllChecks OR Invoke-MassCommand OR Invoke-MassMimikatz OR Invoke-MassSearch OR Invoke-MassTemplate OR Invoke-MassTokens OR Invoke-ADSBackdoor OR Invoke-CredentialsPhish OR Invoke-BruteForce OR Invoke-PowerShellIcmp OR Invoke-PowerShellUdp OR Invoke-PsGcatAgent OR Invoke-PoshRatHttps OR Invoke-PowerShellTcp OR Invoke-PoshRatHttp OR Invoke-PowerShellWmi OR Invoke-PSGcat OR Invoke-Encode OR Invoke-Decode OR Invoke-CreateCertificate OR InvokeNetworkRelay OR EncodedCommand OR New-ElevatedPersistenceOption OR wsman OR Enter-PSSession OR DownloadString OR DownloadFile OR Out-Word OR Out-Excel OR Out-Java OR Out-Shortcut OR Out-CHM OR Out-HTA OR Out-Minidump OR HTTP-Backdoor OR FindAVSignature OR DllInjection OR ReflectivePEInjection OR Base64 OR System.Reflection OR System.Management OR Restore-ServiceEXE OR Add-ScrnSaveBackdoor OR Gupt-Backdoor OR Execute-OnTime OR DNS_TXT_Pwnage OR WriteUserAddServiceBinary OR Write-CMDServiceBinary OR Write-UserAddMSI OR Write-ServiceEXE OR Write-ServiceEXECMD OR Enable-DuplicateToken  OR Remove-Update OR Execute-DNSTXT-Code OR Download-Execute-PS OR Execute-CommandMSSQL OR Download_Execute OR Copy-VSS OR Check-VM OR Create-MultipleSessions OR Run-EXEonRemote OR Port-Scan OR Remove-PoshRat OR TexttoEXE OR Base64ToString OR StringtoBase64 OR Do-Exfiltration OR Parse_Keys OR Add-Exfiltration OR AddPersistence OR Remove-Persistence OR Find-PSServiceAccounts OR Discover-PSMSSQLServers OR DiscoverPSMSExchangeServers OR Discover-PSInterestingServices OR Discover-PSMSExchangeServers OR DiscoverPSInterestingServices OR Mimikatz OR powercat OR powersploit OR PowershellEmpire OR Payload OR GetProcAddress) 

Page 85 from https://conf.splunk.com/files/2016/slides/hunting-the-known-unknowns-the-powershell-edition.pdf

Source: Page 84 and 85 from https://conf.splunk.com/files/2016/slides/hunting-the-known-unknowns-the-powershell-edition.pdf

Ping with timestamp in powershell

Sometimes you want to simply check something from a Windows system with ping and review it with timestamps. In order to do that you may use the following commands in powershell

 ping.exe -t 8.8.4.4 |Foreach{"{0} - {1}" -f (Get-Date),$_} > C:\temp\ping_googledns1ipv4.txt
 ping.exe -t 8.8.8.8 |Foreach{"{0} - {1}" -f (Get-Date),$_} > C:\temp\ping_googledns2ipv4.txt
 ping.exe -t 2001:4860:4860::8844 |Foreach{"{0} - {1}" -f (Get-Date),$_} > C:\temp\ping_googledns1ipv4.txt
 ping.exe -t 2001:4860:4860::8888 |Foreach{"{0} - {1}" -f (Get-Date),$_} > C:\temp\ping_googledns2ipv4.txt


Example without writing the output into a file:

PS C:\Users\flo>
PS C:\Users\flo>  ping.exe -t 8.8.4.4 |Foreach{"{0} - {1}" -f (Get-Date),$_}
02.12.2020 08:53:32 -
02.12.2020 08:53:32 - Ping wird ausgeführt für 8.8.4.4 mit 32 Bytes Daten:
02.12.2020 08:53:32 - Antwort von 8.8.4.4: Bytes=32 Zeit=34ms TTL=56
02.12.2020 08:53:33 - Antwort von 8.8.4.4: Bytes=32 Zeit=42ms TTL=56
02.12.2020 08:53:34 - Antwort von 8.8.4.4: Bytes=32 Zeit=32ms TTL=56
02.12.2020 08:53:35 - Antwort von 8.8.4.4: Bytes=32 Zeit=34ms TTL=56
02.12.2020 08:53:36 - Antwort von 8.8.4.4: Bytes=32 Zeit=28ms TTL=56
02.12.2020 08:53:37 - Antwort von 8.8.4.4: Bytes=32 Zeit=31ms TTL=56

SIEM Use Case - find suspicious powershell commands

Microsofts Powershell is a very mighty tool, which can be used as LoLBin. To detect suspicious powershell commands or scripts, a SIEM use case in order to find suspicious powershell-commands can be:

Logging / Data Source

Active PowerShell Script Block Logging (Event ID 4104) OR use your Advanced Endpoint Protection AEP or Endpoint Detection and Response EDR tool like VMware Carbon Black, Microsoft Defender ATP, Crowdstrike or the other tools.

SIEM use case / fetch suspicious powershell

1. process = powershell.exe

&&

2. cmd = ToBase64String OR FromBase64String OR -e OR -en OR -enc OR -enco OR -encod OR -encode OR -encoded OR -encodedc OR -encodedco OR -encodedcom OR -encodedcomm OR -encodedcomma OR -encodedcomman OR -encodedcommand OR -ec

&&

3. not cmd = Windows\CCM\*

More very useful information

Real world examples of attack chains with Att&ck mapping

Microsoft Threat Protection Intelligence Team released in the past some great detailed articles (e.g. 2020-03 Ransomware, 2018-03 FinFisher, 2017-05 wannacry, 2017-06 petya) about different real world attack chains including a mapping to MITREs framework Att&ck. 

Parinacota attack chain


Picture from Microsoft Security https://www.microsoft.com/security/blog/2020/03/05/human-operated-ransomware-attacks-a-preventable-disaster/ 
The article on Parinacota includes details like how for example persistence is archived:
  • Windows Registry modifications using .bat or .reg files to allow RDP connections Picture from https://www.microsoft.com/security/blog/2020/03/05/human-operated-ransomware-attacks-a-preventable-disaster/
  • Setting up access through existing remote assistance apps or installing a backdoor
  • Creating new local accounts and adding them to the local administrators group 
    Picture from https://www.microsoft.com/security/blog/2020/03/05/human-operated-ransomware-attacks-a-preventable-disaster/

 Wadhrama attack chain

Microsoft Threat Protection Intelligence Team https://www.microsoft.com/security/blog/2020/03/05/human-operated-ransomware-attacks-a-preventable-disaster/

 Ryuk attack chain

Doppelpaymer attack chain



Microsoft Threat Protection Intelligence Team https://www.microsoft.com/security/blog/2020/03/05/human-operated-ransomware-attacks-a-preventable-disaster/

Restore CHK files

I just had to restore many broken CHK files of a SD card from a hidden FOUND.000 folder. The program "unchk.exe" helped me: http://www.ericphelps.com/uncheck/. As described I had to install the Microsoft Visual Basic 5 Runtime because of an "MSVBM50.dll not found" error, which can be downloaded from Microsoft.

I checked and noticed, that all the big files of the broken SD card were restored by unchk.exe as *.WRI files. However they actually were AVI video files which can be opened with VLC video player, which I didn't know at that time.

When checking unchk.exe with Sysinternals Process Explorer, I've noticed the description says "Identifies and renames CHK files":
process-explorer-unchk.exe

So I simply renamed the bigger files from *.CHK to *.AVI using the following powershell-script and it worked fine:

Powershell CHK files to AVI:
Dir *.CHK | rename-item -newname { [io.path]::ChangeExtension($_.name, "AVI") }

Powershell WRI (from unchk.exe) files to AVI:
Dir *.WRI | rename-item -newname { [io.path]::ChangeExtension($_.name, "AVI") }

=> ✅ VLC Video LAN Player was able to open the files
=> ✅ You can directly open the CHK files with VLC Video LAN Player (if they were video files in the first place)

Malware using PowerShell - PowerShell Logging "Script Block Logging"

More and more so called "fileless malware" uses powershell in order to execute malicious actions. In order to find possible malicious powershell commands or ps-scripts, it is very useful to log them, automatically send them to your SIEM and analyze them. Also if possible, disable Powershell for your users, but this is in the real-world sometimes hard or even not possible.

1. Disable PowerShell for users if possible via GPO
2. Fileless malware using PowerShell - PowerShell Logging using Script Block Logging

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_logging_windows?view=powershell-6#enabling-script-block-logging


Enabling Script Block Logging

When you enable Script Block Logging, PowerShell records the content of all script blocks that it processes. Once enabled, any new PowerShell session logs this information. It's recommended to enable Protected Event Logging.

Using Group Policy

To enable automatic transcription, enable the Turn on PowerShell Script Block Logging feature in Group Policy through Administrative Templates -> Windows Components -> Windows PowerShell.

Using the Registry

Run the following function:
PowerShell
function Enable-PSScriptBlockLogging
{
    $basePath = 'HKLM:\Software\Policies\Microsoft\Windows' +
      '\PowerShell\ScriptBlockLogging'

    if(-not (Test-Path $basePath))
    {
        $null = New-Item $basePath -Force
    }

    Set-ItemProperty $basePath -Name EnableScriptBlockLogging -Value "1"
}
 
Powershell-Commands will be logged in Windows Eventlog with Event-ID 4104.

Monitor UniFi WLAN Access Point with PRTG with SNMPv3 Auth+Encrypted

This is a tiny guide howto monitor your UniFi wireless accesspoint, in this case a Unifi U7 pro with SNMPv3 with AES-Encryption and SHA-Auth...