Intrusion analysis ๐Ÿ› ๏ธ

Created: 18.11.2020

Legend

Below is the skeleton from SAN508 course description. I am using it to make up my study plan. For each step of this plan I estimate my current level of training and I am also collecting resourced for this topic under Resources.

๐Ÿซ‘ - level 0. I know nothing and not even where to start. I might have some embarrassingly fundamental knowledge which is not good enough even for the start.

๐Ÿฅ’ - level 1. I know something about the subject, but this only gives me an approximate plan and kind of things to look for.

๐Ÿฅ— - level 2. I know something about the subject, I’ve even read something about it. But no hands-on eperience.

๐ŸŒฎ - level 3. I know quite a lot about the subject, I’ve read something about it and some hands-on eperience.

๐Ÿฅ˜ - level 4. I know a lot about the subject and quite a decent experience. This one I will only use when I am done preparing and have the first mock exam. Bonus - ๐Ÿญ real-life expreience (not just labs).

๐Ÿ—’- Topic specific plan. ๐Ÿ‘Œ-done, ๐Ÿšง - in progress

๐Ÿ—‚ - references and resources.

๐ŸŽฏ- objectives.

๐Ÿบ- artifacts

๐Ÿ›  - tools to learn/use.

Exercises

  • Hunting and Detecting Evidence of Execution at Scale with Shimcache and Amcache
  • Discovering Credential abuse with Event Log Collection and Analysis
  • Tracking Lateral Movement with Event Log Analysis
  • Hunting Malicious use of WMI and PowerShell

Topics

Application execution artifacts, account auditing is a powerful means of identifying malicious actions. An attacker also needs a means to move throughout the network, so we look for artifacts left by the relatively small number of ways there are to accomplish this part of their mission. In this section, we cover common attacker tradecraft and discuss the various data sources and forensic tools you can use to identify malicious activity in the enterprise.

Stealing and Utilization of Legitimate Credentials

There are limimted amount of techniques for gaining authorization and moving laterally. However, there are thousands of ways to execute code, exfiltrate or collect data. So, in hunting focus on this limited techniques, since at some point the adversary will have to use one of them.

If you are not very important, then it’s less likely to face a cool 0-day. Why would anyone use a “bargaining chip” to hack something small? 0-days are costly.

โš ๏ธ Don’t give every user local admin rights! Windows XP - every user is admin.

Hashes

Hashes on Windows: LM, NTHash, TsPkg, WDigest, LiveSSP (can be decrypted on Windows8-). These hashes are available withing the address space range of LSASS process and can be extracted with admin privileges. NTHash and LM are used in NTLMv1 and NTLMv2. WDigest and TsPkg are no longer stored by default. HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential = 1 to turn storing WDigest on.

PsExec.exe -s -accepteula \\127.0.0.1 cmd.exe
gsecdump.exe -a > 1.txt

Pass the Hash. Use the hash and pass to some applicaiton during authentication or authorization.

mimikatz # securlsa::pth /user:username /domain:domainname /ntlm:NTHash /run:".\psexec.exe -accepteula \\IP cmd.exe"

Crack the hash. NThash is stored in SAM and enrypted with AES key.

Password is hashed in the following way: MD4(UTF-16-LE(password)). To decrypt the password, you’ll need both SAM and the system file. Password cracking methodology:

  • Export SAM and SYSTEM hives from the forensic image/suspect machine.
  • Unencrypt the hash stored in the SAM file (๐Ÿ›  mimikatz).
  • Create a word list from the current case (may export from Autopsy, EnCase etc).
  • Run a dictionary ๐Ÿ“– or brute-force attack ๐Ÿ’ช against this NTHash (๐Ÿ› : hashcat ๐Ÿˆโ€โฌ› , John the Ripper ๐Ÿ”ช, Cain and Able ๐Ÿ”ช ๐Ÿ).
# decrypt the hashes:
mimikatz
> lsadump::sam /system:"path_to_SYSTEM" /SAM:"path_to_SAM"

# crack the hash with john (NTHash)
john --format=nt hash.txt
# crack the hash with hashcat (NTHash)
hashcat -m 1000 -a 3 hash.txt

# crack the hash with john (NTLMv1) 
john --format=netntlm hash.txt
# crack the hash with hashcat (NTLMv1) 
hashcat -m 5500 -a 3 hash.txt

# crack the hash with john (NTLMv2) 
john --format=netntlmv2 hash.txt
# crack the hash with hashcat (NTLMv2) 
hashcat -m 5600 -a 3 hash.txt

More about Windows hashes.

For LM hash:

  1. Convert all lower case to upper case
  2. Pad password to 14 characters with NULL characters
  3. Split the password to two 7 character chunks
  4. Create two DES keys from each 7 character chunk
  5. DES encrypt the string “KGS!@#$%” with these two chunks
  6. Concatenate the two DES encrypted strings. This is the LM hash.
john --format=lm hash.txt
hashcat -m 3000 -a 3 hash.txt

NTLM Relaying. There are two versions of this protocol: NTLMv1 and NTLMv2. Both are challenge-response protocols that use NT hashes. Read more here.

Single Sign On (SSO) Dumping using Mimikatz

Tokens

Every process in Windows has a token associated. This token determines the process rights. SeImpersonate privilege is required to extract this token. Tokens are preresnt on the system only during interactive logins (RDP, console, runas). Restricted admin (-> Remote CredGuard) prevents hashes and tokens be kept on a target system. RDP session must be scplicitly terminated, otherwise, the token can be stolen.

Token Stealing

# local admin privileges are required, of course
# run mimikatz
privilege::debug 
token::elevate /domainadmin

Cached Credentials

When DC is unavailable, cached creds can be used. Hashes or clear text passwords can be residing in cache. Key ๐Ÿ”‘: SECURITY\Cache in mscash2 format. Min admin privileges required.

./pwdump.py SYSTEM SAM true # to get local hashes
./cachedump SYSTEM SECURITY true # cached. Salted with the account username and thus need to be bruteforced to crack.

Without admin privileges, an attacker won’t be able to get to the SECURITY hive. To limit the cache edit this ๐Ÿ”‘: SOFTWARE\Microsoft\Windows NT\ Current Version\Winlogon. Protected users security group intruduced in Windows 8.1 has solved the issues with cached creds.

LSA Secrets

SECURITY\Policy\Secrets contains various secrets like VPN passwords, IIS app passwords etc. SECURITY\Policy contains the key ๐Ÿ”‘ that’s required for decryption.

๐Ÿ›  Nishang

Enable-DuplicateToken # elevate privileges
Get-LsaSecret

To make sure this shit won’t happen in your enterprise, don’t run high-privileged accounts on untrustworthy systems. Group Managed Service is an additional protection. It ensures that certain service accounts are protected.

Kerberos Attacks

I have finished an article describing Kerberos protocol in the investigations section.

Pass the Ticket. Steal the ticket and reuse it. This is possible because tickets are stored in RAM while they are valid (which is usually around 10 hrs). Something similar to replay attack.

mimikatz #
sekurlsa::tickets /export # dump tickets
kerberos::ptt [ticket]

โš”๏ธ CredGuard and Remote CredGuard help mitigate this attack.

Overpass the Hash (aka Pass the Key). Use NT hash to login from another user’s behalf.

โš”๏ธ CredGuard, Protected Users Group, RC4 auth disabled.

Silver Ticket. Get the black key (service key).

โš”๏ธ Password updates.

Golden Ticket. Get the yellow key (TGS private key, krbtgt account’s). This key ๐Ÿ”‘ can be extracted from memory of the DC or from NTDS.DIT AD database.

โš”๏ธ Change pass to krbtgt twice regularily, protect domain admin accs.

Skeleton ๐Ÿ’€ key. Patch LSASS with a backdoor.

โš”๏ธ Protect domain admin accs, use smart cards for high-priv accs.

Kerberoasting. Request ticket for priveleged service and crack NT hash of that service. Any user can request a ticket for any service! And inside that ticket there is hashed password stored as well… .

โš”๏ธ Complex and long service acc passwords, Managed Service Accounts.

GCSync. Use fake DC to sync with other DCs and get hashes and history for any accounts.

โš”๏ธ Protect domain admin accs, limit accs with replication rights.

NTDS.DIT theft

\Windows\NTDS. Can be stoled either with raw accesss or VSC. Either way, admin privileges are required. SAM and SYSTEM hive are also required. ๐Ÿ›  NTDSXtract.

Event Log (User logon tracking)

Open Log file -> New API. Choose evtx file. View -> Time Correction and check “Set UTC time”. 4776 to look for failed logins. Find suspicious ones. Then, get to 4624 and see if any of these failed loging resulted in successful login. Note the processes responsible for these events (in the event description). For example, WmiPrvSE.exe is a remote WMI activity.

Remember that not all processes record network info (like Kerberos).

To check RDP connections, first filter by 4624 Type 10 Event, then see 4778 (reconnection) events. Finally, check for acc privileges by looking at 4672 events.

Good practice in the enterprise to minimize admin rights usage. If you see admin accs or accs that have elevated privileges used on workstations, that’s a food for thought.

It’s better to filter out all built-in accs on Windows. SID can be used to do so. Built-in accounts don’t have Unique domain identifier and RID.

evtxecmd --sync
evtxecmd -f path\to\evtx --csv target\path -csvf target\file\name

Use TimeLine Explorer to analyse the results. Intersting and useful feature is “column grouping”.

Another way to see into OS Event Logs is to use a free tool chainsaw:

chainsaw hunt . --mapping /path/to/chainsaw/mapping_files/sigma-mapping.yml --rules /path/to/chainsaw/sigma_rules/ --csv result.csv 

The above command will find everything that’s considered suspicious. Indicators can be commented or added.

Logon Types

2 - Interactive (also known as, Logon locally). Creds: Password, Smartcard, other. Examples: IIS Basic Auth (before IIS 6.0), Console, RunAs. Unless CredGuard is enabled, creds are stored on target.

3 - Network. Examples: Net use, PS remoting, PsExec w/o explicit creds, remote registry - all the login ways that are using login type 3. Creds are not stored on target. Creds: Password, NT Hash, Kerberos ticket.

2+3 - PsExec alternate creds. -u -p . Saved on the ta

4 - Batch. Example: Remote Scheduled Task. Password saved on target as LSA secret. Creds: Password (stored as LSA secret).

5 - Service. Password saved on the target as LSA secret. Creds: Password (stored as LSA secret).

8 - Network Clear Text. Examples: IIS Basic Auth (IIS 6.0 and newer); Windows PowerShell with CredSSP.

9 - NewCreds. Examples: RunAs, Network. Creds: Password.

10 - Remote Desktop. Credentials on target are available unless Remore CredGuard is enabled.

Advanced Evidence of Execution Detection

Attacker Tactics, Techniques, and Procedures (TTPs) Observed Via Process Execution

Prefetch Analysis

Udemy SDF series about Prefetch, Digital Archaeology, SDF podcast. Review my article about prefetch forensics (based on the previously mentioned sources). Below information is copied from there

WinPrefetchView

To view pretech files (decompressed as well) in GUI.

Fred - Forensic Registry Editor

To view exported hives.

FTK Imager Lite

Fairly heavy footprint - 15-16Mb.

CDQR

This tool focuses on the pf intself rather than on a data it contains. It’s useful for making timelines.

RegRipper (GUI and CUI)

rip.exe -r SYSTEM -p prefetch # to show whether prefetch is enabled

Prefetch parser

More info than with WinPrefetchView

prefetch.py -c -d -e
prefetch.py -c -d > pf.csv
prefetch.py -f <file_to_parse> > pf.txt

Columns: last executed, MFT sequence number, MFT record number, executable name, run counter.

If collecting prfethc on a live system, run volatile collection tools before that.

Prefetch is for efficiency of starting processes and their resources (movies for media players, spreadsheets for Excel for example). Improves startup time of applications. Filename, Creation time, Modified time, File Size, Process EXE, Process Path, Run Counter, Last Run Time, Missing Process + libraries and resources for each process.

Forensics value - tracks the execution of programs. Central repository of what was run on the system. File size can be used to search for the same process with a different name on a different machine.

C:\Windows\Prefetch.

All prefetch have a signature at offset 4th byte. MAM - compressed and SCCA - plain text.

OS Signature1 (version) signature2 (type)
WinXP & 2003 0x00000011 or 17 SCCA
Vista 0x00000023 or 23 SCCA
W8 0x0000001a or 26 SCCA
W10 MAM 0x04
W10 0x0000001e or 30 SCCA

Prefetch can be disabled in registry C:\Windows\System32\config\SYSTEM. Export it and open, for example, in Fred. CurrentControlSet -> SessionManager -> Memory Managment -> Prefetch Parameters -> Enable Prefetcher:

key meaning
0 disabled
1 enabled for apps only
2 enabled for boot only
3 boot and app enabled (default)

You can check it with rip.exe:

rip.exe -r SYSTEM -p prefetch # to show whether prefetch is enabled

Caveats

On servers is usually turned off. And starting with Win10 - compressed. For systems with solid state drives it’s also disabled. With Win8 - additional run times recorded. Also, there is latency issue - some apps are not closed upon clicking X, but remain running in background. Hence, the last time run might be different.

If the app was deleted and then reinstalled? What the firtst run time will be?

What if I rename an executable?

If the exe is substitued?

If the same exe was run from different locations - different .pf files. If the application was deleted, the info remains in prefetch.

Write a sctipt to determine deleted files


pecmd -f "path/to/pf/file.pf" # for a single file
pecmd -d "dir/with/pfs" -q --csvf <filename> --csv <wheretoputtheresult>
# Review in TimeLine Explorer

Information that can be got from the pf files:

  • Executable name. If it was changed or run from a different location it will have a different name (different suffix at the end, for example CHROME-12345BC and CHROME-43216AD).
  • Run times
  • Other run times (not always, if run times > 1)
  • Referenced files and directories
  • File size
  • Hash
  • Last Run

Stacking with Kansa

# run this Kansa script from the directory with all the csv (results of pecmd) files from all the machines you need to review.
Get-PrefetchListingStack.ps1 > result.csv

# look for files that were run once first. These are the most suspocious. 
# if you have an approximate dates of infection, sort by this data as well.

Application Compatibility Cache (ShimCache)

My article about Registry and ShimCache.

Key ๐Ÿ”‘: CurrentControlSet\Control\Session Manager\AppCompatCache\AppCompatCache.

๐Ÿ› : ShimCacheParser.py (requires Python2), AppCompatCacheParser, shimcache plugin for vol.py

Originally was used to identify compatibility issues between 32 and 64 bit progs. Track the file name, file path, size, last modified time, execution flag* โฐ.

Can be used to see installed apps, deleted apps, wiping apps, notable directories, malware.

Only logs specific file extensions (exe, dll, bat). It might not be a reliable evidnce that the program was executed or even installation, but if the program was installed and deleted - it won’t be deleted from here. ShimCache is another name for this artifact. โš ๏ธ Uses file system timestamps. Last modified ~ when the file was created, changed (the exe itself) or renamed.

โš ๏ธ Written at shutdown!

โš ๏ธ Doesnโ€™t track the file execution for Win7+ systems.

โš ๏ธ Got an error File "ShimCacheParser.py", line 148, except OverflowError, err: ^, SyntaxError: invalid syntax.

โœ๏ธ Use python 2.6+. Command python27 in my case (alias for pyenv activate python27). It should be installed of course.

Dropped exe. Last Modified - when the exe was dropped on the system.

Executed exe. Last Modified is updated.

Deleted exe. Last Modified is not updated.

grep -A10 -i "last modified" "path/to/csv/from/shimcacheparser" > results.csv

grep -iv "windows" "path/to/csv/from/shimcacheparser" > resultsExcluded.csv # targeting notable directories

grep -E i "[\\][a-Z0-9]{1,4}\.(exe|bat|dll|py|txt|vbs)" "path/to/csv/from/shimcacheparser" > resultNotables.csv

๐Ÿ“ Tried running these test myself on a Win11 Parallels VM on macOS. cat resultInstalledAndExecuted.csv | awk -F "," '/Procmon64/ {print $0}'. In my case these entries remained intact after execution or deletion. I should install something new and see the result then.

appcompatcacheparser -f "SYSTEM/hive" --csv "savetodir" --csvf "savetofileindir.csv"

Tips:

  • Different entries with the last modification date being the same - most probably a rename activity. Use $UsnJrnl and $Logfile for proof. Sort by the MT in TimeLine Explorer
  • In case of UNC path (those starting from an IP of the machines) could be an indicator that the file was browsed and launched with Explorer, or malware ran it using UNC path.
  • Check for the NTFS last modified timestamp with powershell Get-ChildItem <file> | Select Name, LastWriteTime. If this date and time and the timestamp shown by ShimCache are different (NTFS ts being much older), then there probably was a timestomping at place. It’s impossible for a ShimCache entry to have a newer ts than the NTFS ts. Also, this would indicate that the file was not executed after the ShimCache entry was created.

Amcache Registry Examination

Path to file ๐Ÿ›ฃ๏ธ: C:\Windows\AppCompat\Programs.

Since Windows 8. Stored information about program execution, including those, that were run from a USB drive. Contains install date and time, name, version, path to exe/dll, source info, path to uninstall, publisher name, volume GUIDs, container ID of the device from which the program was run.

DeviceCensus - some information about the physical machine itself. For example, for my Parallels VM there was also a VM subkey that contained some value VMId.

File. Full path to the executable.

โš ๏ธ Not present on my Windows 10 (Parallels VM).

InventoryApplication. Consists of folders/subkeys named by the program id. Each folder will contain the following important information: OSVersionAtInstallTime, InstallDateMsi, InstallDate, InstallDateArpLastModified, InstallDateFromLinkFile, Name, Publisher, RegistryKeyPath (may show user SID), Source, UninstallString, ProgramID (consistent accross systems).

โš ๏ธ On my Parallels Windows 10/11 machine I noticed that here not only Windows, but also Mac executables are listed even though I have specifically set in preferences that I am not sharing Mac folders or disks with the VM.

InventoryApplicationFile. Contains a fileid which is actually a SHA-1 hash, padded with 4 leading zeros and full path to the executable. Use a list of known good or VirusTotal.

InventoryDeviceContainer. Contains ModelName and FriendlyName. When devices get connected, they might install some software to be able to work correctly.

InventoryDevicePnp. Contains ContainerID, DriverID, Description, Manufacturer and Model.

Programs. Where this program is located within the FS and the source (for example, AddRemoveProgram). And also information path to the uninstaller in registry.

Tools ๐Ÿ› : AmCacheParser.exe + Timeline Explorer.

AmcacheParser.exe -f <path_to_AmCache.hve> -i on --csv <export_to_folder_no_quotes> --csvf <desired_filename> 

What are unassociated files? Those that are not associated with a known source. Good starting point when looking for bad files.

โš ๏ธ In my case on a macOS with Parallels and Windows 10 installed, this evidence also contained mac executables.

Scaling ShimCache and Amcache Investigations

Stacking with Kansa

# Linux
sudo su -
# AppCompatProcessor.py 
# Step 1. Connect Amcache.hve and SYSTEM hives to the SQL DB.
AppCompatProcessor.py ./db.db load "path/to/hives.zip"
AppCompatProcessor.py ./db.db search # /etc/AppCompatProcessor/AppCompatSearch.txt contains signatures to look for and can be changed.
# Result is stored in Output.txt

# Stacking examples:
AppCompatProcessor.py ./db.db stack "Filename" LIKE '%<partialname>%'
AppCompatProcessor.py ./db.db stack "Filename" "length(filename)<3" # malware is often named with 1 or 2 characters. Let's make the max 3 just in case

AppCompatProcessor.py ./db.db reconscan # /etc/AppCompatProcessor.reconFiles.txt - common attackers' recon techniques (interesting commands that could be indicators of recon)

AppCompatProcessor.py ./db.db list #???

Could not make the tool run against the hive collected with FTK from my Windows 11 machine.

Lateral Movement Adversary Tactics, Techniques, and Procedures (TTPs)

To do anything on a Windows machine (doesn’t this apply to UNIX system as well?) you need a user account. So, at least some account is needed. But the altimate goal is an admin account (domain, if there is a DC).

Detection is possible when you know what’s not ok. For example, suspicious logins after hours or unusual account for this machine or for this employee.

Types Of Credentials

Hashes. LM (not used anymore) and NT hashes.

Tokens.

Cached credentials.

LSA secrets.

Tickets. ๐Ÿ• ๐Ÿฉ ๐Ÿถ.

NTDS.DIT.

Security features protecting user accounts

Conf2017 presentation.

On Windows XP every used had admin privileges ๐Ÿ˜ฌ. So, at least some work needed to be done. Below are some features added in order to solve this problem.

Managed service accounts. Windows 7+. Special accounts for some services, that are not used by normal users. These accounts have an automatically-managed, complex password removing the requirement of manually dealing with password rotation and security.

Group managed service accounts. Windows 8+ From the Microsoft docs: “The group Managed Service Account (gMSA) provides the same functionality within the domain but also extends that functionality over multiple servers.”.

Domain Protected Users Security Group.

KB2871997 patch. Windows 7+ & Windows Server 2008R2+. Contains a bunch of security improvements (protected groups, lsa update etc). More here.

UAC. Windows Vista +. It means User Account Control. Whenever something admin-like is requested by a process, the user needs to aprove this explicitly (consent.exe process with a GUI window), i.e. elevate privileges. There were some exploits that allowed UAC bypass and may there is somewhere another one lurking in the wild, but officially it’s now pretty safe.

Restricted admin. Windows 8.1+ and Server 2012 R2+. It’s a mode and it prevents storing an RDP user’s credentials in memory on the machine to which an RDP connection is made.

Local admin logon restrictions. Windows 8+

SSP passwords in plaintext mitigation. Windows 8+

Protected Processes. Windows 8+

LSA Cache cleanup. Windows 8+

Credential Guard and Remote Credential Guard. Windows 10+. This topic is described in more details by Artyom Sinitsin on PhDays 2019 (here).

Device Guard. Windows 10+. Prevents execution of untrusted code.

Compromising Credentials Techniques

Remote Desktop Services Misuse

Windows Admin Share Abuse

PsExec and Cobalt Strike Beacon PsExec Activity

Windows Remote Management Tool Techniques

PowerShell Remoting/WMIC Hacking

Vulnerability Exploitation

Tracking Lateral Movement

Shares. Can be used to track this sort of activity. Mounted shares is one way (5140). ANONYMOUS LOGON is a common thing produced by a built-in accounts on Windows machines (filter it out). If you see a PC name it’s not usually suspicious. However, keep an eye on those accounts that mounted shared on remote systems if they are not domain admins!

Services. Start types. 0 boot, 1 loaded by i/o subsystem, 2 always loaded and run, 3 - manually, 4 - disabled. So, during investiagtion we’d be looking primarily for 0, 1 and 2. 7045 - Services started with user credentials are suspicious. To map SIDs and RIDs to the actual user names, use Security event log, eid 4624 (logins, obviously).

Tasks. TaskScheduler Operational logs, 106 to get all the registered tasks. Then, use the name of this tasks to filter other events and see what happened (if anything happened). If the task was successful - look for 200 (task executed) and 201 (task completed). Otherwise, look for 332 warning or other errors. Check at C:\Windows\System32\Tasks, open the xml associated with your loot ๐Ÿ’ฐ.

Log Clearing. Attackers are not interested in investigation, so they are likely to be covering their tracks. One of the way to do so - simply clear the logs. Although it’s raising alert on its own, it still deleted valuable source of information.

RunAs. Logged on both machines if it was remote. 4648.

Log Analysis for Incident Responders and Hunters

Profiling Account Usage and Logons

Tracking and Hunting Lateral Movement

Identifying Suspicious Services

Detecting Rogue Application Installation

Finding Malware Execution and Process Tracking

Capturing Command Lines and Scripts

PowerShell Transcript and ScriptBlock Logging

Discovering Cobalt Strike beacon PowerShell Import Activity

PowerShell Script Obfuscation

WMI Activity Logging

Anti-Forensics and Event Log Clearing

Resources

[1] About some APT groups

[2] Practical Malware Analysis book