Pages

Saturday, 30 November 2019

Forensics traces of NTDS.dit dumping using ntdsutil utility

Active Directory stores information about members of the domain including devices and users to verify credentials and define access rights. The Active Directory domain database is stored in the NTDS.dit file. By default the NTDS file will be located in %SystemRoot%\NTDS\Ntds.dit of a domain controller.

The following tools and techniques can be used to enumerate the NTDS file and the contents of the entire Active Directory hashes.

  • Volume Shadow Copy
  • secretsdump.py
  • Using the in-built Windows tool, ntdsutil.exe
  • Invoke-NinjaCopy

In this post we will test in-built command ntdsutil.exe (Windows 2008 and later) that does a backup of the crucial NTDS.dit file, and the SYSTEM file (containing the key required to extract the password hashes), without the need to use VB Script, third-party tools or injecting into running processes.

All you need is a command prompt running with administrator privileges, and the following commands:



This same technique is implemented in one of OilRig/APT34 post exploitation tools named Gon.exe (xHunt campaign) described here by Unit42:


Upon execution, Gon.exe process will create a process "cmd.exe /c" with following commandline:



Threat hunters can create a real time detection for this by monitoring cmd.exe with similar command line and ntdsutil execution.

Checking Domain Controller default application event logs, we come accross an interesting set of events that can be used as a forensic indicator for this technique:
  • Log Name: Application
  • Provider Name: "ESENT"
  • EventIDs of interest: 325, 326, 327 and 216
Below example of traces of the NTDS.dit copy creation:



As can be seen above the same volume snapshot path is reported in both screenshots (Event Log and Gon.exe console).

More related events capturing other interesting details:




The path of the created ntds.dit copy is also captured in eventids 325 and 327. Eventid 216 also shows the creation of  a fresh copy of ntds.dit.

The only limitation of those events is their highvolatility in time, as the application events logs get filled quickly thus chances finding them post compromise are lower (it's recommended to augment the size of all event logs in general).

MITRE ATT&CK Mapping:

Tactic: Crednetial Access
Technique: Credential Dumping
Technique ID: T1003
Procedure: Ntdsutil 

References:


Friday, 22 November 2019

Hunting for suspicious use of TeamViewer - Part 1/2

N.B: TeamViewer (TV) is a great Remote Support (++) tool, and the objective of this post is to share some threat hunting ideas that could help spot malicious or abnormal usage of such tools (same principles can be applied to other third party legit Remote Support Tools).



Tools such as TV are used in a lot of environment for legit/justified business reasons, and for us as defenders we need to find ways to detect if indeed those tools are used as expected and what are the forensics and real time artefacts that we can leverage to get a better visibility level.

TV Components (High Level):
  • TeamViewer_Service.exe: TV core process which install itself as a standalone service (System Integrity Level)
  • TeamViewer.exe: is the main process for TV user GUI functions (Medium Integrity Level)
  • tv_w32.exe & tv_x64.exe: both used for TV logging (lock access to log file) and hooking specific functions (High IL)
  • TeamViewer_Desktop.exe: executes only when there is an active incoming remote support session via unattended access (System IL)


In term of networking, with exception of TeamViewer_Service.exe, all other processes connect to local host as a form of IPC between TV processes:




TV Netcon behavior can be summarized as below:

teamviwer_desktop.exe|teamviewer.exe:[localhost:high port] <-> teamviewer_service.exe [5939]<->*.teamviewer.com:5938 

In term of logging TV creates the following main "log" files:
  • tvchatfiledownloadhistory.db (encrypted)
  • TeamViewer**_Logfile.log: where * is indicative of TV version, 2 files with same file name one in program files and 2nd is in appdata\roaming)
  • Connections_Incoming.txt : logs time, userid and TV Session ID which can be used to correlate events - incoming connections.
  • Connections_Outgoing.txt: logs time, userid and TV Session ID which can be used to correlate events - outgoing connections.





The most verbose/useful log file is the TeamViwer**_Logfile.log within program files folder and with a DACL set to deny users from writing or changing the content of the file (administrators can of course delete the whole log file).

Logging is ON by default but can be turned off via GUI or setting propoerly certain registry values:


Once the logging is truned off (e.g. via GUI), following registry values get created (by default they get created only if you want to disable logging):



In this 1st part we will be covering the following hunting scenarios:
  1. Tampering attempts with TV logging
  2. File Transfer from attacker machine to TV client
  3. Request to autorize a new device (by default TV send email notification for the 1st time a new device connects to a TV client)
a) Defense Evasion - TV Logging Disabled:



b) File Transfer:

  • If tansfer is done using TV transfer files feature then the file creation on destination machine (TV client) will be logged as following:


While reviweing File Creation activity using production historical data, it shows that TeamViewer.exe usually create few files and majority of them are caching related files in:
  • AppData\Local\Microsoft\Windows\INetCache\IE\*
  • AppData\LocalLow\Microsoft\CryptnetUrlCache\MetaData\*
So if you are interested to be informed of what files were dropped via TeamViewer File Transfer then use Sysmon or your EDR to monitor/hunt file creation activities by process name TeamViewer.exe.  We can also see traces ("FileDataSinkFileListWin::CreateFileInternal" and PID of TeamViewer.exe) of file transfer activity in the TeamViewer**_LogFile.log:



Unfortunately if the file was dropped via Drag and drop it's logged as being created by explorer.exe:


Looking at traces of file transfer within TeamViewer**_Logfile.log (program files) we can clearly see the explorer.exe PID (5244) and also clues ("DragInterceptor: Interception successful") about a file transfer activity:



For outbound file transfer (from TV client to attacker machine), Teamviewer.exe will read the file, then send it over the IPC netcon (port 5939) to TeamViewer_service.exe which send it to the *.teamviewer.com (port 5938)



All the transfered file names are not captured in the "TeamViewer**_LogFile.log", but high likely are captured in the tvchatfiledownloadhistory.db (encrypted/protected - will be covered in part 2).

c) New Device Autorization:

If the online (TV unattended access) credentials were compromised, once the attacker will try to logon for first time and supposedly that TV account is linked to the corporate email address, then high likely you can detect this notification email via your mail security gateway (custom message filter) which can be of huge value at warning your SOC and the TV account owner to reset the password before the damage is done (btw: enable TV 2FA ASAP!)



As a conclusion for this 1st part, you will need to understand it's usage mode (incoming or outgoing) as well as file transfer activity (needed/no) which can be disabled if not needed, alert on TV log file tampering including the log file deletion (if your EDR supports file deletion logging) and lastly make sure to enable 2FA for this kind of Remote Support tools even if it's rarely used.


That's all for this part, see you in part 2.







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!