# Security-in-bits - full archive > AI-assisted, human-validated detection engineering and threat hunting, proven on real lab telemetry. Ransomware and RMM abuse in KQL, ES|QL and Sigma. 29 posts, newest first. Markdown rendering of https://www.securityinbits.com/blog/ . --- # wbadmin NTDS.dit dump detection for Domain Controllers URL: https://www.securityinbits.com/detection-engineering/wbadmin-ntds-dit-dump-detection/ Published: 2026-01-03 (updated 2026-01-03) Tags: elasticsearch, ntds, sigma-rules, t1003-003, wbadmin wbadmin NTDS.dit dump detection for DCs using Sigma, MDE KQL, and Elastic plus fast triage with Backup logs. When wbadmin.exe is used to back up NTDS.dit + registry hives, treat it as credential access, not routine IT backup. This post is for Elastic + Sigma + Windows logs and focuses on wbadmin NTDS.dit dump detection you can validate end-to-end in a lab. You will: spot the command, confirm artifacts on disk, and alert in MDE/Elastic with Sigma-derived logic. 🔎 ## Why this matters wbadmin.exe can create VSS backups of files that are normally locked, including: - C:\Windows\NTDS\ntds.dit (AD database) - SYSTEM and SECURITY hives (needed for offline credential) The signal is in what is included and where the backup is written. ## Step 1: The wbadmin pattern to watch Attackers commonly run a one-time backup and write output to a convenient local path via a loopback UNC. ### Executed command ``` wbadmin.exe start backup -backuptarget:\\127.0.0.1\C$\ProgramData\ -include":C:\windows\NTDS\ntds.dit,C:\windows\system32\config\SYSTEM,C:\windows\system32\config\SECURITY" -quiet ``` What to notice: - -include targets NTDS.dit and SYSTEM/SECURITY. That is the high-signal part. - -backuptarget:\\127.0.0.1\C$\ProgramData\ writes to the local C: drive through an admin share (easy staging). ⚠️ #### Example output [image: wbadmin Admin Output] _wbadmin Admin Output_ ## Step 2: Confirm the backup artifacts on disk Use filesystem artifacts to confirm the alert is real and to find what needs containment. This dir structure may be already removed by the attacker. ### Dir structure After dump this is how it looks like [image: Dir Structure After Dumping] _Dir Structure After Dumping_ Look for: - New backup directory created under the target path. - Backup container VHDX files with timestamps matching the wbadmin execution. ## Step 3: Validate the copied files (mount the container) After mounting vhdx files vhdx file will contain the files included in the backup [image: Vhdx Dir Structure] _Vhdx Dir Structure_ If NTDS/hives are missing after mounting, the job likely failed or you mounted the wrong container. Use backup logs below to confirm. ## Step 4: Correlate with Windows Backup logs Backup logs tell you whether the job completed and can help you scope impact fast. ### Event Viewer Logs [image: Event Viewer Backup Logs] _Event Viewer Backup Logs_ Get the logs about backup operation from Microsoft-Windows-Backup ``` Get-WinEvent -FilterHashtable @{ LogName = 'Microsoft-Windows-Backup' Id = 1,4,5,14 # 1=Started, 4=Success, 5=Failure, 14=Completed StartTime = (Get-Date).AddHours(-1.5) } | Sort-Object TimeCreated | Format-Table TimeCreated, Id, LevelDisplayName, Message -Wrap ``` [image: Get Winevent Output] _Get Winevent Output_ What you want: - A start event near the wbadmin process time. - A completed/success event if a usable copy exists on disk. - Any failure details (permissions, target path, missing components). ## Step 5: Detections (Sigma, MDE, Elastic) Upstream Sigma already covers this pattern (wbadmin NTDS.dit dump detection). Use it as a baseline, then tune around maintenance windows and known backup accounts. Sigma Alert in Kibana [image: Sigma Alert For Wbadmin Process] _Sigma Alert For Wbadmin Process_ Elastic Process Tree [image: Sigma Rule Process Tree] _Sigma Rule Process Tree_ Practical tuning Prioritize alerts where ProcessCommandLine also contains admin shares (for example \\127.0.0.1\C$\) or unusual backup targets. Suppress only after baselining normal backup tooling on DCs. ## SIEM Detections These queries were generated by converting the Sigma rule with pySigma backends. ### Sensitive File Dump Via Wbadmin.EXE Detects the dump of highly sensitive files such as “NTDS.DIT” and “SECURITY” hive. Attackers can leverage the “wbadmin” utility in order to dump sensitive files that might contain credential or sensitive information. Microsoft Defender (KQL) ```kql DeviceProcessEvents | where (FolderPath endswith "\\wbadmin.exe" or ProcessVersionInfoOriginalFileName =~ "WBADMIN.EXE") and (ProcessCommandLine contains "start" or ProcessCommandLine contains "backup") and (ProcessCommandLine contains "\\config\\SAM" or ProcessCommandLine contains "\\config\\SECURITY" or ProcessCommandLine contains "\\config\\SYSTEM" or ProcessCommandLine contains "\\Windows\\NTDS\\NTDS.dit") ``` Elastic ```lucene (process.executable:*\\wbadmin.exe OR process.pe.original_file_name:WBADMIN.EXE) AND (process.command_line:(*start* OR *backup*)) AND (process.command_line:(*\\config\\SAM* OR *\\config\\SECURITY* OR *\\config\\SYSTEM* OR *\\Windows\\NTDS\\NTDS.dit*)) ``` SigmaView rule on GitHub Thanks to @frack113 and @nas_bench for publishing the awesome Sigma rules and helping the community. ## Triage checklist - Who ran it (user, logon type, remote session)? - Did backup logs show success (a real copy likely exists)? - What is the backup target path and what files were written there? - Any follow-on activity touching the backup path (archive tools, outbound transfers, remote tooling)? ✅ If the job completed and this activity is not expected, escalate as probable domain compromise. ## Further reading (same stack) - How to set up Sigma rules for Elasticsearch SIEM - LSASS Dump via comsvcs.dll: Defender Detection Guide - Discovery using nltest, net and whoami ## Known in-the-wild incidents Source Title Source (with link) Publish Date Technical Advisory: SonicWall Targeted by Ransomware Group Bitdefender 7 Aug, 2025 From Bing Search to Ransomware: Bumblebee and AdaptixC2 Deliver Akira The DFIR Report 5 Aug, 2025 Undisclosed SonicWall Zero Day Leading to Akira Ransomware eSentire 5 Aug, 2025 The Exploitation of SonicWall SSL VPNs Huntress 4 Aug, 2025 ## References - Detects the dump of highly sensitive files such as “NTDS.DIT” and “SECURITY” hive. - Wbadmin | LOLBAS - From Bing Search to Ransomware: Bumblebee and AdaptixC2 Deliver Akira – The DFIR Report - wbadmin start backup | Microsoft Learn - OS Credential Dumping: NTDS (T1003.003) | MITRE ATT&CK --- # How to set up Sigma rules for Elasticsearch SIEM URL: https://www.securityinbits.com/detection-engineering/sigma-rules-elasticsearch/ Published: 2025-11-23 (updated 2025-11-23) Tags: elasticsearch, kibana, siem, sigma, sigma-cli End-to-end workflow to convert Sigma rules into Elasticsearch SIEM detection rules using sigma-cli, Elasticsearch backend, and Kibana NDJSON imports. Got a fresh Sigma release and an Elasticsearch lab, but no clear path from Sigma YAML rules to detection rules in Elasticsearch SIEM? This guide shows how to set up sigma rules for Elasticsearch SIEM so you can turn community content into Elastic Security rules you can actually run. We will stay focused on Elastic Security with Windows telemetry mapped to ECS, using sigma-cli, the Elasticsearch backend plugin, and the official Sigma rule packages. By the end of this guide you will: - Install sigma-cli with either pip or uv - Install the Elasticsearch backend plugin so sigma-cli can output lucene - Download Sigma rules from the latest GitHub release - Convert Windows and Emerging Threats rules into Kibana compatible NDJSON - Import all generated rules into Kibana Detection rules in one go The official Sigma Getting Started | Sigma Detection Format guide walks through a Splunk focused example. If you want a Splunk specific setup, follow that article. In this post we will do the same pipeline for Elasticsearch (lucene). If you want to see how these Sigma based detections look for concrete techniques, check out: - LSASS Dump via comsvcs.dll: Defender Detection Guide - Discovery using nltest, net and whoami ## 1. Install sigma-cli You can install sigma-cli in two ways, depending on whether you use uv in your environment or not. sigma-cli is the command line interface built on top of pySigma, the Python library that parses and converts Sigma rules into backend specific queries. Without uv (standard way) ``` pip3 install sigma-cli ``` Using uv ``` uv tool install sigma-cli --with pip ``` If you install with uv tool install, sigma-cli is available on your PATH while still being managed in an isolated environment, which is useful on lab boxes where you do not want to pollute the system Python. ⚙️ ## 2. Install the Elasticsearch backend plugin We need to install our backend plugin through sigma-cli so it knows how to talk to Elasticsearch and Elastic Security. First, list any backends that are available using: sigma plugin list -t backend You should see existing backends similar to the screenshot below. [image: Sigma Plugin List For Backend] _Sigma Plugin List For Backend_ Now install the Elasticsearch plugin: sigma plugin install elasticsearch This pulls the plugin that knows how to translate Sigma rules into Elasticsearch Lucene queries and Elastic Security detection rule formats. [image: Sigma Plugin Install Elasticsearch] _Sigma Plugin Install Elasticsearch_ ## 3. Download Sigma rules You can download the Sigma rules from the latest release page: Releases · SigmaHQ/sigma. There are different rule packages available for download. Which Sigma rule package should I use? A detailed explanation can be found in the sigma/Releases.md file. If you are new, best start with the Core Sigma package. It includes high quality rules of high confidence and relevance and should not produce many false positives. In this guide I am using Core++ and ET (Emerging Threats) AddOn Rules to get stronger coverage. Once downloaded, extract the archive so that you have a rules and a rules-emerging-threats directory that matches the repository layout. Why this step matters for detection: these packages give you a curated, maintained Sigma ruleset instead of random one off rules from the internet. ## 4. Convert Sigma rules to Elasticsearch Lucene Our goal is to convert many Sigma rules into NDJSON so we can upload them into Kibana in one go instead of creating each rule manually. For converting the rules, we need to use sigma convert. [image: Sigma Convert Cmd Help] _Sigma Convert Cmd Help_ For our case sigma convert needs three things: - targets - pipelines - formats If you have not installed any backend yet, the targets and pipelines list will be empty. To see which targets and pipelines are available: [image: Sigma List Targets Pipelines] _Sigma List Targets Pipelines_ After installing the Elasticsearch plugin, check targets and pipelines again: ``` sigma list targets sigma list pipelines ``` This confirms that the lucene target and the ecs_windows pipeline are available and ready to use. [image: Sigma Targets Pipelines] _Sigma Targets Pipelines_ Because we will import multiple rules in one go and upload them to Kibana, we will use the lucene target and a format that generates Elastic Security detection rules. For listing formats supported by lucene use: sigma list formats lucene [image: Sigma List Formats Lucene] _Sigma List Formats Lucene_ I am only converting rules present in sigma_core++.zip (only Windows) and sigma_emerging_threats_addon.zip from Releases · SigmaHQ/sigma. For Windows rules: ``` sigma convert -t lucene -p ecs_windows -f siem_rule_ndjson ./rules/windows --skip-unsupported -o windows_rules.ndjson ``` For Emerging Threats: ``` sigma convert -t lucene -p ecs_windows -f siem_rule_ndjson ./rules-emerging-threats --skip-unsupported -o emerging_threat_rules.ndjson ``` What these commands do for elasticsearch backend: - -t lucene selects the Elasticsearch Lucene query language. - -p ecs_windows applies the ECS Windows pipeline for correct field mappings. - -f siem_rule_ndjson outputs Kibana SIEM rules in NDJSON format. - --skip-unsupported skips rules that cannot be converted by this backend. - -o .ndjson writes all generated rules into a single NDJSON file, ready for import. At the end of this step you should have two files: - windows_rules.ndjson - emerging_threat_rules.ndjson These will be imported into Kibana in the next step. From a defender perspective this means you have turned upstream Sigma content into concrete Elastic Security rules you can enable, tune, and monitor. ## 5. Upload NDJSON rules to Kibana Open Kibana and navigate to Security -> Rules -> Detection rules (SIEM). Click Import Rules and upload the two NDJSON files you generated in the previous step. [image: Import Sigma Rules Kibana] _Import Sigma Rules Kibana_ For more detail on import and export behavior, see the official Elastic documentation on managing detection rules. I have not enabled Elastic prebuilt rules in this lab, but you can enable them alongside your Sigma based rules if you want more coverage. After importing all rules, the Sigma based rules appear in the rules table: [image: Imported Rules Into Elastic] _Imported Rules Into Elastic_ At this point Elasticsearch is running Sigma rules converted by sigma-cli for the Elasticsearch backend, and you can start tuning, disabling noisy rules, and adding environment specific exceptions. ✅ ## Key takeaways for defenders - You now have a repeatable pipeline from upstream Sigma releases to Elastic detection rules. - Core++ rules give you broad coverage of common Windows TTPs, while Emerging Threats AddOn Rules track specific actors and exploits that may age faster. - The Elasticsearch backend and ecs_windows pipeline ensure field names line up with ECS, so matches are reliable instead of brittle string searches. - NDJSON export and bulk import let you treat detection rules as code and re seed a new Elastic lab in minutes. ## References - Getting Started | Sigma Detection Format - GitHub – SigmaHQ/pySigma: Python library to parse and convert Sigma rules into queries (and whatever else you could imagine) - GitHub – SigmaHQ/pySigma-backend-elasticsearch: pySigma Elasticsearch backend - Releases · SigmaHQ/sigma --- # Discovery using nltest, net and whoami URL: https://www.securityinbits.com/detection-engineering/nltest-whoami-net-discovery/ Published: 2025-10-02 (updated 2025-11-23) Tags: elasticsearch, kql, kusto, nltest, sigma-rules, t1016, t1033, t1087-001, t1087-002, t1482, whoami Learn how adversaries run nltest, whoami, and net for AD recon, with ready Sigma detections and process context to detect and triage. Quick, high-signal ways to enumerate DCs, trusts, and privileged groups in Active Directory plus how to detect them. Overview - Why it matters: these commands are common during early recon. - What you get: exact commands, sample output, Sigma detections, and in-the-wild cases. - Defend: pair command-line telemetry with parent/child process context and alert tuning. ## Known in-the-wild incidents Source Title Source (with link) Publish Date Commands referred Blurring the Lines: Intrusion Shows Connection With Three Major Ransomware Gangs The DFIR Report 8 Sep, 2025 nltest for AD/DC enumeration From Bing Search to Ransomware: Bumblebee and AdaptixC2 Deliver Akira The DFIR Report 5 Aug, 2025 nltest /dclist:; nltest /domain_trusts; whoami /groups; net group "domain admins" /dom; net group "enterprise admins" /dom SharePoint ToolShell – Zero-Day Exploited in-the-Wild Targets Enterprise Servers SentinelLabs 21 Jul, 2025 whoami (captured via webshell command execution) #StopRansomware: Play Ransomware CISA 4 Jun, 2025 nltest used for network discovery (behavior described, exact switches not quoted) QSC: new modular framework in CloudComputating campaigns Securelist 8 Nov, 2024 net group "domain admins" /domain; whoami Attack Cases Against HTTP File Server (HFS) (CVE-2024-23692) AhnLab ASEC 28 Jun, 2024 whoami during post-exploitation reconnaissance Operation Crimson Palace: A Technical Deep Dive Sophos X-Ops 5 Jun, 2024 net group "domain admins" /domain; nltest /domain_trusts (plus related domain enumeration) ## Sigma Rules ### Visual mapping Command-to-rule mapping for nltest, whoami, and net. [image: Discovery Sigma Mapping] _Discovery Sigma Mapping_ Elastic Sigma alerts [image: Discovery Sigma Rules] _Discovery Sigma Rules_ ### Potential Recon Activity Via Nltest.EXE Nltest is a Windows command-line utility used to list domain controllers and enumerate domain trusts. ``` nltest.exe /dclist: domain nltest.exe /domain_trusts ``` #### Example output ``` C:\Users\john>nltest /dclist:DC1 Get list of DCs in domain 'DC1' from '\\HOME-DC'. HOME-DC.DC1.local [PDC] [DS] Site: Default-First-Site-Name The command completed successfully C:\Users\john>nltest /domain_trusts List of domain trusts: 0: DC1 DC1.local (NT 5) (Forest Tree Root) (Primary Domain) (Native) The command completed successfully ``` ### Suspicious Group And Account Reconnaissance Activity Using Net.EXE ``` net.exe group "domain admins" /dom net.exe group "enterprise admins" /dom ``` #### Example output - net group "domain admins" /dom ``` C:\Users\john>net group "domain admins" /dom The request will be processed at a domain controller for domain DC1.local. Group name Domain Admins Comment Designated administrators of the domain Members ------------------------------------------------------------------------------- Administrator MSSQLService user2 The command completed successfully. ``` [image: Process Tree Net Cmd] _Process Tree Net Cmd_ - net group "enterprise admins" /dom ``` C:\Users\john>net group "enterprise admins" /dom The request will be processed at a domain controller for domain DC1.local. Group name Enterprise Admins Comment Designated administrators of the enterprise Members ------------------------------------------------------------------------------- Administrator MSSQLService user1 The command completed successfully. ``` ### Group Membership Reconnaissance Via Whoami.EXE whoami.exe /groups #### Example output ``` C:\Users\john>whoami /groups GROUP INFORMATION ----------------- Group Name Type SID Attributes ========================================== ================ ============ ================================================== Everyone Well-known group S-1-1-0 Mandatory group, Enabled by default, Enabled group BUILTIN\Administrators Alias S-1-5-32-544 Group used for deny only BUILTIN\Users Alias S-1-5-32-545 Mandatory group, Enabled by default, Enabled group NT AUTHORITY\INTERACTIVE Well-known group S-1-5-4 Mandatory group, Enabled by default, Enabled group CONSOLE LOGON Well-known group S-1-2-1 Mandatory group, Enabled by default, Enabled group NT AUTHORITY\Authenticated Users Well-known group S-1-5-11 Mandatory group, Enabled by default, Enabled group .... ``` ## SIEM Detections These queries were generated by converting the Sigma rule with pySigma backends. ### Potential Recon Activity Via Nltest.EXE Detects nltest commands that can be used for information discovery Microsoft Defender (KQL) ```kql DeviceProcessEvents | where (FolderPath endswith "\\nltest.exe" or ProcessVersionInfoOriginalFileName =~ "nltestrk.exe") and ((ProcessCommandLine contains "server" and ProcessCommandLine contains "query") or (ProcessCommandLine contains "/user" or ProcessCommandLine contains "all_trusts" or ProcessCommandLine contains "dclist:" or ProcessCommandLine contains "dnsgetdc:" or ProcessCommandLine contains "domain_trusts" or ProcessCommandLine contains "dsgetdc:" or ProcessCommandLine contains "parentdomain" or ProcessCommandLine contains "trusted_domains")) ``` Elastic ```lucene (process.executable:*\\nltest.exe OR process.pe.original_file_name:nltestrk.exe) AND ((process.command_line:*server* AND process.command_line:*query*) OR (process.command_line:(*\/user* OR *all_trusts* OR *dclist\:* OR *dnsgetdc\:* OR *domain_trusts* OR *dsgetdc\:* OR *parentdomain* OR *trusted_domains*))) ``` SigmaView rule on GitHub ### Suspicious Group And Account Reconnaissance Activity Using Net.EXE Detects suspicious reconnaissance command line activity on Windows systems using Net.EXE Check if the user that executed the commands is suspicious (e.g. service accounts, LOCAL_SYSTEM) Microsoft Defender (KQL) ```kql DeviceProcessEvents | where ((FolderPath endswith "\\net.exe" or FolderPath endswith "\\net1.exe") or (ProcessVersionInfoOriginalFileName in~ ("net.exe", "net1.exe"))) and ((((ProcessCommandLine contains " group " or ProcessCommandLine contains " localgroup ") and (ProcessCommandLine contains "domain admins" or ProcessCommandLine contains " administrator" or ProcessCommandLine contains " administrateur" or ProcessCommandLine contains "enterprise admins" or ProcessCommandLine contains "Exchange Trusted Subsystem" or ProcessCommandLine contains "Remote Desktop Users" or ProcessCommandLine contains "Utilisateurs du Bureau à distance" or ProcessCommandLine contains "Usuarios de escritorio remoto" or ProcessCommandLine contains " /do")) and (not(ProcessCommandLine contains " /add"))) or (ProcessCommandLine contains " accounts " and ProcessCommandLine contains " /do")) ``` Elastic ```lucene ((process.executable:(*\\net.exe OR *\\net1.exe)) OR (process.pe.original_file_name:(net.exe OR net1.exe))) AND ((((process.command_line:(*\ group\ * OR *\ localgroup\ *)) AND (process.command_line:(*domain\ admins* OR *\ administrator* OR *\ administrateur* OR *enterprise\ admins* OR *Exchange\ Trusted\ Subsystem* OR *Remote\ Desktop\ Users* OR *Utilisateurs\ du\ Bureau\ à\ distance* OR *Usuarios\ de\ escritorio\ remoto* OR *\ \/do*))) AND (NOT process.command_line:*\ \/add*)) OR (process.command_line:*\ accounts\ * AND process.command_line:*\ \/do*)) ``` SigmaView rule on GitHub ### Group Membership Reconnaissance Via Whoami.EXE Detects the execution of whoami.exe with the /group command line flag to show group membership for the current user, account type, security identifiers (SID), and attributes. Microsoft Defender (KQL) ```kql DeviceProcessEvents | where (FolderPath endswith "\\whoami.exe" or ProcessVersionInfoOriginalFileName =~ "whoami.exe") and (ProcessCommandLine contains " /groups" or ProcessCommandLine contains " -groups") ``` Elastic ```lucene (process.executable:*\\whoami.exe OR process.pe.original_file_name:whoami.exe) AND (process.command_line:(*\ \/groups* OR *\ \-groups*)) ``` SigmaView rule on GitHub Thanks to @svch0st, Craig Young, @cyb3rops, Georg Lauenstein, @nas_bench, omkar72, and oscd.community for publishing the awesome Sigma rules and helping the community. ## References - Potential Recon Activity Via Nltest.EXE - Suspicious Group And Account Reconnaissance Activity Using Net.EXE - Group Membership Reconnaissance Via Whoami.EXE --- # LSASS Dump via comsvcs.dll: Defender Detection Guide URL: https://www.securityinbits.com/detection-engineering/lsass-dump-comsvcs-rundll32/ Published: 2025-09-25 (updated 2025-11-23) Tags: elasticsearch, kql, lsass, sigma-rules, t1003-001, t1027-010, t1036, t1057 Detect LSASS dump with comsvcs.dll and rundll32. Clear command breakdown and Sigma mappings for Defender and Elastic Attackers dump LSASS with comsvcs.dll to steal credentials; here’s how to spot rundll32 + MiniDump fast and reliably. 🙂 ## What the technique is Adversaries attempt to access credential stored in the process memory of the Local Security Authority Subsystem Service (LSASS). After a user logs on, the system generates and stores a variety of credential materials in LSASS process memory. LSASS.exe process memory can be dumped using comsvcs.dll’s MiniDump export (ordinal 24) via rundll32. The dump is often written to a temp path, sometimes disguised with a benign extension. ## Exact command executed LSASS.exe process memory is dumped via comsvcs.dll ordinal 24. Requires sufficient privileges to access LSASS memory. ``` cmd.exe /Q /c for /f "tokens=1,2 delims= " %%A in ('"tasklist /fi "Imagename eq lsass.exe" | find "lsass""') do rundll32.exe C:\windows\System32\comsvcs.dll, #+000024 %%B C:\Windows\Temp\file.docx full ``` Breakdown - Spins up a quiet, one-shot cmd: /Q hides echo, /c runs the line and exits. - Grabs LSASS’s PID: the for /f ... in ('tasklist … | find "lsass"') bit parses tasklist output and stores the 2nd column (PID) in %%B. It’s just – get the PID number for lsass.exe. - Dumps the process via comsvcs: rundll32 … comsvcs.dll,#24 %%B … full calls the MiniDump export (ordinal 24) inside comsvcs.dll to write a full memory dump to the path you give (here masquerading as .docx). ## Detecting LSASS dump via comsvcs.dll (rundll32) ### Visual Sigma mapping Command-to-rule mapping for the lsass.exe dump via comsvcs.dll (ordinal 24). [image: Sigma Mapping Lsass Comsvcs.dll] _Sigma Mapping Lsass Comsvcs.dll_ ### Sigma rules that trigger on comsvcs.dll [image: Lsass Dump Sigma Rules] _Lsass Dump Sigma Rules_ - Potential Obfuscated Ordinal Call Via Rundll32 – catches #,#+000024 style calls - Process Memory Dump Via Comsvcs.DLL – rundll32 invoking comsvcs MiniDump/ordinal 24 - Recon Command Output Piped To Findstr.EXE – flags recon where output is piped to findstr ## SIEM Detections These queries were generated by converting the Sigma rule with pySigma backends. ### Potential Obfuscated Ordinal Call Via Rundll32 Detects execution of “rundll32” with potential obfuscated ordinal calls Microsoft Defender (KQL) ```kql DeviceProcessEvents | where (FolderPath endswith "\\rundll32.exe" or ProcessVersionInfoOriginalFileName =~ "RUNDLL32.EXE" or ProcessCommandLine contains "rundll32") and (ProcessCommandLine contains "#+" or ProcessCommandLine contains "#-" or ProcessCommandLine contains "#0" or ProcessCommandLine contains "#655" or ProcessCommandLine contains "#656") ``` Elastic ```lucene (process.executable:*\\rundll32.exe OR process.pe.original_file_name:RUNDLL32.EXE OR process.command_line:*rundll32*) AND (process.command_line:(*#\+* OR *#\-* OR *#0* OR *#655* OR *#656*)) ``` SigmaView rule on GitHub ### Process Memory Dump Via Comsvcs.DLL Detects a process memory dump via “comsvcs.dll” using rundll32, covering multiple different techniques (ordinal, minidump function, etc.) Microsoft Defender (KQL) ```kql DeviceProcessEvents | where ((FolderPath endswith "\\rundll32.exe" or ProcessVersionInfoOriginalFileName =~ "RUNDLL32.EXE" or ProcessCommandLine contains "rundll32") and ((ProcessCommandLine contains "comsvcs" and ProcessCommandLine contains "full") and (ProcessCommandLine contains "#-" or ProcessCommandLine contains "#+" or ProcessCommandLine contains "#24" or ProcessCommandLine contains "24 " or ProcessCommandLine contains "MiniDump" or ProcessCommandLine contains "#65560"))) or ((ProcessCommandLine contains "24" and ProcessCommandLine contains "comsvcs" and ProcessCommandLine contains "full") and (ProcessCommandLine contains " #" or ProcessCommandLine contains ",#" or ProcessCommandLine contains ", #" or ProcessCommandLine contains "\"#")) ``` Elastic ```lucene ((process.executable:*\\rundll32.exe OR process.pe.original_file_name:RUNDLL32.EXE OR process.command_line:*rundll32*) AND ((process.command_line:*comsvcs* AND process.command_line:*full*) AND (process.command_line:(*#\-* OR *#\+* OR *#24* OR *24\ * OR *MiniDump* OR *#65560*)))) OR ((process.command_line:*24* AND process.command_line:*comsvcs* AND process.command_line:*full*) AND (process.command_line:(*\ #* OR *,#* OR *,\ #* OR *\"#*))) ``` SigmaView rule on GitHub ### Recon Command Output Piped To Findstr.EXE Detects the execution of a potential recon command where the results are piped to “findstr”. This is meant to trigger on inline calls of “cmd.exe” via the “/c” or “/k” for example. Attackers often time use this technique to extract specific information they require in their reconnaissance phase. Microsoft Defender (KQL) ```kql DeviceProcessEvents | where (ProcessCommandLine contains "ipconfig" and ProcessCommandLine contains "|" and ProcessCommandLine contains "find") or (ProcessCommandLine contains "net" and ProcessCommandLine contains "|" and ProcessCommandLine contains "find") or (ProcessCommandLine contains "netstat" and ProcessCommandLine contains "|" and ProcessCommandLine contains "find") or (ProcessCommandLine contains "ping" and ProcessCommandLine contains "|" and ProcessCommandLine contains "find") or (ProcessCommandLine contains "systeminfo" and ProcessCommandLine contains "|" and ProcessCommandLine contains "find") or (ProcessCommandLine contains "tasklist" and ProcessCommandLine contains "|" and ProcessCommandLine contains "find") or (ProcessCommandLine contains "whoami" and ProcessCommandLine contains "|" and ProcessCommandLine contains "find") ``` Elastic ```lucene process.command_line:(*ipconfig*\|*find* OR *net*\|*find* OR *netstat*\|*find* OR *ping*\|*find* OR *systeminfo*\|*find* OR *tasklist*\|*find* OR *whoami*\|*find*) ``` SigmaView rule on GitHub Thanks to @cyb3rops, @frack113, Modexp, @nas_bench, and @swachchhanda for publishing the awesome Sigma rules and helping the community. ## Known in-the-wild incidents A compact, source-linked index of public reports where LSASS dumping via comsvcs.dll appears in real intrusions. Source Title Source (with link) Publish Date UAT-7237 targets Taiwanese web hosting infrastructure Cisco Talos 15 Aug, 2025 From Bing Search to Ransomware: Bumblebee and AdaptixC2 Deliver Akira The DFIR Report 5 Aug, 2025 Inside a Real Ransomware Attack: What Happened and How Solis Security 9 Jul, 2025 Credential Theft: Expanding Your Reach Huntress 8 Apr, 2025 ## References - From Bing Search to Ransomware: Bumblebee and AdaptixC2 Deliver Akira – The DFIR Report - Comsvcs | LOLBAS - OS Credential Dumping: LSASS Memory, Sub-technique T1003.001 – Enterprise | MITRE ATT&CK® --- # Deobfuscate PowerShell using MinusOne URL: https://www.securityinbits.com/malware-analysis/deobfuscation/deobfuscate-powershell-reverse-shell/ Published: 2025-09-21 (updated 2025-09-20) Tags: minusone, powershell, reverse-shell Learn how Reverse Shell Generator creates obfuscated PowerShell and how MinusOne (by AirbusCERT) quickly deobfuscates it. Obfuscated PowerShell is everywhere – this post shows how the Reverse Shell Generator produces randomized scripts and how MinusOne deobfuscates them in seconds. It generates a different PowerShell variant every time you click Generate. ## Obfuscated PowerShell [image: Obfuscated Revshell Powershell] _Obfuscated Revshell Powershell_ ## Deobfuscated PowerShell But here’s the fix 👇 MinusOne – Powershell Deobfuscator – written in Rust by AirbusCERT – cleans it up in seconds [image: Deobfuscate PowerShell] _Deobfuscate PowerShell_ What does it do? - It’s an obfuscated PowerShell TCP reverse shell. - It creates a System.Net.Sockets.TCPClient to :and reads bytes from the stream - It decodes bytes to text with System.Text.ASCIIEncoding, executes via Invoke-Expression. - It then returns output plus a fake PS > prompt using ASCII.GetBytes() and Write() ## References - MinusOne – Powershell Deobfuscator - GitHub – airbus-cert/minusone: Powershell Linter --- # AdaptixC2 Defender URL: https://www.securityinbits.com/threat-intelligence/adaptixc2-defender-guide/ Published: 2025-09-20 (updated 2026-01-24) Tags: adaptixc2, c2-frameworks, post-exploitation Practical AdaptixC2 defender guide with real incidents, quick detection tips, default user agent, YARA, and a config extractor. In July 2025 AdaptixC2 moved from red team lab to real breaches; this guide shows how defenders can spot it fast using Yara, C2 Feeds, User agent etc. What it is? AdaptixC2 is an open-source post-exploitation/C2 framework and adversarial emulation framework made for penetration testers. The Adaptix server is written in Golang and to allow operator flexibility. The GUI Client is written in C++ QT, allowing it to be used on Linux, Windows, and MacOS AdaptixC2’s functionality is identical to traditional penetration frameworks such as Cobalt Strike, Sliver, Havoc, and Mythic. [image: Adaptixc2 Gui] _Adaptixc2 Gui_ ## Timeline - Jan 2025 – v0.1 released - May 2025 – First seen on ThreatFox and MalwareBazaar. Observed in the wild by Symantec and Unit 42 - Jul 2025 – Observed in the wild by The DFIR Report and QiAnXin - Aug 2025 – v0.8 released - Dec 2025 – v1.0 released ## Known In-the-Wild Incidents A compact, source-linked index of public reports where AdaptixC2 appears in real intrusions. Blog Source Publish Date When it was used? Cyber Warfare Amidst Gold’s Skyrocketing Price: UTG-Q-010 Group’s Supply-Chain Attack QiAnXin TI Center 4 Sep, 2025 Jul 2025 From Bing Search to Ransomware: Bumblebee and AdaptixC2 Deliver Akira The DFIR Report 5 Aug, 2025 Jul 2025 AdaptixC2: A New Open-Source Framework Leveraged in Real-World Attacks Unit 42 10 Sep, 2025 May 2025 Unusual Fog ransomware activity Symantec (Broadcom) 12 Jun, 2025 May 2025 Last updated: 2025-09-20 ## Detection Default user agent If the actor did not change it, hunt for this in your web logs: `Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20121202 Firefox/20.0 Based on the User agent website this maps to Firefox browser running on Windows 8, which should be rare in most networks. Treat matches as suspicious and pivot by source IP, URI path, and user account. Yara Rules AdaptixC2 yara rules from then Unit42 blog, mirrored for convenience: AdaptixC2 YARA rules — GitHub. [image: Adaptixc2 Yara Rules] _Adaptixc2 Yara Rules_ ## Config extractor The config extractor (by the Unit 42 team) is here: AdaptixC2 config extractor — GitHub. This executable was created with the latest AdaptixC2 version and extracts the C2 cleanly. This exe file was created using the latest AdaptixC2 version and it works perfectly fine , extract the C2 without any issue. [image: Adaptixc2 Config Extractor] _Adaptixc2 Config Extractor_ ## C2 Feeds - ThreatFox | AdaptixC2 – First Seen – 2025-05-25 18:22:59 UTC - GitHub – drb-ra/C2IntelFeeds: Automatically created C2 Feeds [image: Drb Ra Intelfeeds] _Drb Ra Intelfeeds_ ## Hash Feed - MalwareBazaar | AdaptixC2 ## References - AdaptixC2 Github - X hacker_ralf - AdaptixC2: A New Open-Source Framework Leveraged in Real-World Attacks --- # Unpack RedLine stealer using dnSpyEx – Part 3 URL: https://www.securityinbits.com/malware-analysis/unpack-redline-stealer-using-dnspyex-part-3/ Published: 2024-02-12 (updated 2024-02-12) Tags: net, config, debugging, dnspyex, infostealer, malware-series, redline Dive into unpacking and extracting config from RedLine Stealer using dnSpyEx. This is the 3rd part in our RedLine malware series. In this article, we dive into process of unpacking and extracting config from RedLine Stealer using dnSpyEx. It’s a bit lengthy but a great way to learn about the unpacking process using dnSpyEx. 🔍 This is the 3rd part in our deep dive series on RedLine. If you need a refresher on the infection chain, check out Part 1 –🔍 Dive into the RedLine Stealer Infection Chain – Part 1. And if you’re interested in using the pe-sieve tool, explore Part 2 – Unpack RedLine stealer to extract config using pe-sieve -Part 2. To follow along, download the file line.exe from MalwareBazaar. ### Using dnSpyEx for Manual Debugging – RedLine Stealer Let’s embark on the unpacking journey with dnSpyEx: ##### 1. Loading line.exe into dnSpyEx Load line.exe to dnSpyEx and navigate to the EP you will see MainWindow.NON() This section contains critical code snippets, including Activator.CreateInstance(GeneralMessageForm.VCTull); Activator.CreateInstance is use to execute the 2nd stage dll dynamically. Activator.CreateInstanceCreate instances of types dynamically during runtime. It is commonly used with reflection to instantiate types during runtime. [image: 1. Load line.exe CreateInstance] _1. Load line.exe CreateInstance_ ##### 2. Loads & execute the 2nd Stage dll (HiTechDistribution.dll) It loads assembly using AppDomain.CurrentDomain.Load(), then, it fetches all the public (exported) types from that assembly using GetExportedTypes()& returns the first one. [image: 2. Load assembly in dnSpyEx] _2. Load assembly in dnSpyEx_ PantosTExBwBQpyLp function decrypt this embedded resource (Resources.HiTechDistribution) using hard-coded key. In summary, it loads and execute the .NET assembly (2nd Stage) using Activator.CreateInstance after decrypting the resources embedded in line.exe. Now let’s analyse the 2nd Stage dll. [image: 3. Summary of line.exe] _3. Summary of line.exe_ ##### 3. Analyze & Debug the 2nd Stage DLL Let’s set a bp in line.exe at return exportedTypes[0];, to analyze the loaded assembly in memory. Navigate to Debug -> Windows -> Modules. You can see the new module HiTechDistribution. [image: 4. First bp set in RedLine] _4. First bp set in RedLine_ Let’s open the module, then go to Analayzer method & set a bp at Program.Main() [image: 5. 2nd stage dll loaded] _5. 2nd stage dll loaded_ ##### 4. Persistency using Startup folder Let’s continue debugging, & our goal for analysis is to dump Happy.exe (unpacked malware) manually to extract config. First function which start with class name FormGestionApp* is empty. 2nd function(rBB*) decrypt the strings, then execute PowerShell to copy line.exe to the Startup folder with the name “anydesk.exe.exe”. [image: 6. 2nd Stage dll Overview dnSpyEx] _6. 2nd Stage dll Overview_ 2nd function(rBB*) decrypt the strings, then execute PowerShell to copy line.exe to the Startup folder with the name “anydesk.exe.exe”. [image: 7. Using PS to copy in startup folder] _7. Using PS to copy in startup folder_ Note: The Call Stack window in dnSpyEx is quite useful for seeing how the code jumps from one module to another. In this case it jumps from line.exe -> HiTechDistribution.dll (2nd stage dll) -> 2.7.dll – Injector (3rd stage dll). [image: Call stack for RedLine] ##### 5. Load and dump 3rd stage dll (2.7.dll) At line 19, it loads another injector named as (2.7), which is shown below in Modules section in dnSpyEx. It uses the Invoke method with two parameters as mentioned below: - InstallUtil.exe path - Assembly to inject (unpacked Happy.exe) [image: 8. Dump 3rd Stage dll from modules] _8. Dump 3rd Stage dll from modules_ This HumanTrace function based on the the flag it inject into itself  or InstallUtil.exe . For this execution, it return the complete path for InstallUtil.exe as shown below. [image: 9. Humantrace function for InstallUtil in dnSpyEx] _9. Humantrace function for InstallUtil_ ##### 6. Extracting the Unpacked Malware Then Step Into Invoke function, you will see two parameter and final unpacked payload Happy.exe is present in the 2nd parameter as shown below. Right-click and save the unpacked payload to disk. [image: 10. Injector- Dump Unpacked RedLine] _10. Injector- Dump Unpacked RedLine_ ##### 7. Extract RedLine config using dnSpyEx Open this Happy.exe in dnSpyEx. Go to the assembly , right click then select “Go to Entry Point”. Click on the IP text, it will show you the config class EntryPoint. In this sample, there is no XOR key used, so the C&C in plain text. [image: 4. Config Redline stealer] Conclusion: Unpacking RedLine Stealer using dnSpyEx is a meticulous yet rewarding process that offers invaluable insights into malware analysis and detection. --- # Unpack RedLine stealer to extract config using pe-sieve -Part 2 URL: https://www.securityinbits.com/malware-analysis/unpack-redline-stealer-to-extract-config-using-pe-sieve-part-2/ Published: 2024-02-06 (updated 2024-02-06) Tags: net, dnspyex, infostealer, malware-series, pe-sieve, procmon, redline Unpack RedLine stealer to extract config using pe-sieve. pe-sieve dumps then unpacked files from memory. Then, extract the config from the dumped file. RedLine Stealer config extraction using two ways: - Fast & Easy Method: Use the awesome pe-sieve tool from @hasherezade, which dumps unpacked file from memory. Then, extract the config from dumped file. - Using dnSpyEx for manual debugging. It’s a bit lengthy but a great way to learn about the unpacking process. We will cover this in our next article in this series. Signup for our newsletter 👆to receive exclusive notification about upcoming articles. This is the 2nd part of the deep dive into the RedLine, if you want to refresh about the RedLine Stealer infection chain, check out our previous article 🔍 Dive into the RedLine Stealer Infection Chain – Part 1 . If you’d like to follow along, start by downloading this file line.exe from MalwareBazaar. #### Fast & Easy Method: Using pe-sieve One efficient way to extract the configuration of RedLine Stealer is by leveraging the powerful pe-sieve tool.This tool excels in dumping unpacked files from memory, simplifying the extraction process. Follow these steps to extract the config: ###### 1. Monitor the malware using ProcMon & Process hacker Use ProcMon Sysinternal tool to monitor the execution of line.exe. You’ll see a process tree like this. [image: .NET Stealer Infection chain] After a few seconds, PowerShell will exit, and you’ll see a new process, InstallUtil.exe, with a child process, conhost.exe. The malicious code is injected inside InstallUtil process [image: 1. Process hacker process tree] _1. Process hacker process tree_ ###### 2. Dump the code using pe-sieve Let’s use pe-sieve to dump the unpacked code. - Get the process id of InstallUtil.exe (e.g. 8284) - Execute this cmd pe-sieve /pid 8284 to dump the unpacked code from this InstallUtil.exe process. [image: Unapck using pe-sieve] _2. Dump using pe-sieve_ Open this 400000.InstallUtil.exe in your favourite tool, I am using Die which is already installed in my Flare-VM. As you can see its 32 bit .NET file. [image: RedLine Stealer Die screenshot] _Die screenshot_ ###### 3. Extract config using dnSpyEx Open the dumped 400000.InstallUtil.exe from pe-sieve in dnSpyEx. Go to the assembly , right click then select “Go to Entry Point”. Click on the IP text, it will show you the config class EntryPoint. In this sample, there is no XOR key used, so the C&C in plain text. [image: 3. Load the file in dnSpyEx] _3. Load the file in dnSpyEx_ Now we have extracted the RedLine Stealer config. [image: 4. Config Redline stealer] _4. Config Redline stealer_ For those seeking a deeper understanding of the unpacking process, manual debugging using dnSpyEx provides invaluable insights. I am excited for next article as it will cover unpacking in details. Stay tuned for our next article in this series, where we will explore this technique in detail. --- # 🔍 Dive into the RedLine Stealer Infection Chain – Part 1 URL: https://www.securityinbits.com/malware-analysis/🔍-dive-into-the-redline-stealer-infection-chain-part-1/ Published: 2024-01-30 (updated 2024-02-13) Tags: cyberchef, infostealer, lnk, malware-series, mshta, powershell, redline, vbscript This article talks about RedLine Stealer infection chain which uses LNK, PowerShell, mshta and URLs to download final payload. This include VBScript analysis using CyberChef & Wscript.Echo. RedLine Stealer Infection Chain: Zip ➡️ LNK PS ➡️ mshta (URL1) ➡️ PS ➡️ cmd ➡️ PS ➡️ URL2 ➡️ exe What’s Inside: - LNK using \W*\\2\\msh*e to dodge detection - VBScript analysis using CyberChef & Wscript.Echo - Utilize CyberChef recipe to decode VBScript & PowerShell - How to deobfuscate PowerShell with PowerShell logging [image: .NET Stealer Infection chain] _RedLine Stealer Infection chain process tree_ #### What is RedLine Stealer? According to malpedia, RedLine Stealer is a malware available on underground forums for sale apparently as standalone ($100/$150 depending on the version) or also on a subscription basis ($100/month). This malware harvests information from browsers such as saved credentials, autocomplete data, and credit card information. More recent versions of RedLine added the ability to steal cryptocurrency. This malware is always in last week’s top 10 according to ANY.RUN. [image: Any run top 10] _Any run top 10_ If you want to follow along, please downlaod the files from MalwareBazaar. 086F03FD9AC1C3C8CFB239AE987E3BD5 PRODUCT DESIGN AND SPECIFICATION.zip --> 8D35E46911450C731F76F311BAAD7EF0 PRODUCT DESIGN AND SPECIFICATION.lnk --> D88EE271FCA9CC237C2C5A8EFCC744DB line.hta --> 5E3B97C3D2825D9D448AB145C6F0FB64 line.exe #### 1. The Zip File Containing the LNK: - LNK uses PowerShell to execute mshta.exe. - Executes the HTA from the URL present inside the LNK file. - Uses \W*\\2\\msh*einstead of mshta.exe, to evade static detection 💡. - In simple terms \W*\\2\\msh*e points to C:\Windows\System32\mshta.exe [image: RedLine Infection Chain Step 1] _RedLine Infection Chain Step 1_ #### 2. HTA uses VBScript ‘chr’ function to obfuscatation: chr returns the character represented by an Ascii code. e.g. Chr(65) will return ‘A’. Let’s try to decode using CyberChef recipe then use alternate method using Wscript.Echo. [image: HTA file content] _HTA file content_ ##### 2.1. Decoding the Obfuscated VBScript: Copy the obfuscated VBScript from HTA file to CyberChef Input. Then load the below VBScript deobfuscation CyberChef recipe to decode VBScript. CyberChef Recipe: ``` Find_/_Replace({'option':'Simple string','string':'&H'},'0x',true,false,true,false Subsection('chr\\(\\d+-\\((0x[A-Fa-f0-9]+)\\)\\)',true,true,false) From_Base(16) Merge(true) Find_/_Replace({'option':'Simple string','string':'-('},':',true,false,true,false) Find_/_Replace({'option':'Simple string','string':'))'},')',true,false,true,false) Regular_expression('User defined','chr\\(([^)]+)\\)',true,true,false,false,false,false,'List capture groups') Fork('\\n','',false) Subtract('Colon') From_Decimal('Space',false) ``` It will look like this as shown below. If you want to learn about this CyberChef recipe, please read this Deobfuscate Script using CyberChef – Recipe 0x3. [image: CyberChef Recipe decode VBScript] _CyberChef Recipe decode VBScript_ ##### 2.2 Alternatively, decode VBScript using Wscript.Echo - Save the VBScript from HTA file to new file named extracted_from_hta.vbs - Replace Execute with Wscript.Echo in the new VBS file - Execute the above file with cscript.exe, & you will see the deobfuscated script [image: Deobfuscate VBScript using cscript] _Deobfuscate VBScript using cscript_ #### 3. Deobfuscate the PowerShell using Write-Host or PowerShell Logging Extract the PowerShell code from deobfusacted VBScript present in line.hta. This PowerShell utilize AES decryption along with Gzip decompress, then execute the 2nd stage PowerShell. Using Write-Host at the bottom we can dump the code. [image: PowerShell Stage1 to Stage2] _PowerShell Stage1 to Stage2_  Or, If PowerShell module logging is enabled, then we can see the 2nd stage PowerShell in event log. [image: Deobfuscate using PowerShell logging] _Deobfuscate using PowerShell logging_ If you want to read more about “Deobfuscate PowerShell using PowerShell Logging”, check this Deobfuscate PowerShell using PowerShell Logging article. #### 4. Decoding the stage 2 PowerShell Using CyberChef PowerShell is using Ddy function to decode the array by subtracting 7390. [image: RedLine Stealer Stage 2 PowerShell beautify script] _RedLine Stealer Stage 2 PowerShell beautify script_ We can use CyberChef subsection operation to select the data array, then use subtract operation and From Decimal to decode the string. I will recommend to read this Deobfuscate PowerShell using subtract CyberChef Recipe 0x4 for details regarding CyberChef Recipe. CyberChef Recipe: ``` Generic_Code_Beautify() Subsection('@\\([^)]*\\)',true,true,false) Find_/_Replace({'option':'Regex','string':'[@()]'},'',true,false,true,false) Find_/_Replace({'option':'Regex','string':','},'\\n',true,false,true,false) Find_/_Replace({'option':'Regex','string':'$'},',7390',true,false,true,false) Fork('\\n','',false) Subtract('Comma') From_Decimal('Space',false) Merge(true) Find_/_Replace({'option':'Regex','string':'Ddy'},'',true,false,true,false) Syntax_highlighter('powershell') ``` [image: Decoded Stage 2 PowerShell with CyberChef] _Decoded Stage 2 PowerShell with CyberChef_ Now we have decoded the final stage of PowerShell and can read the script to understand its working.  Stay tuned for unpacking RedLine Stealer’s final payload and config extraction in the next post. --- # Linux Cheat Sheet URL: https://www.securityinbits.com/cheatsheet/linux-cheat-sheet/ Published: 2024-01-26 (updated 2024-01-24) Tags: linux Explore essential Linux commands in this regularly updated cheat sheet, tested on Debian-based systems like Ubuntu. Bookmark for future reference! I frequently leverage the following Linux commands in my daily work, and I’m excited to share them with you in this cheat sheet. As I continue to learn and explore, I’ll be updating this resource regularly. It’s worth noting that I’ve tested all the commands on Debian-based Linux systems, particularly Ubuntu. Feel free to bookmark this page for future reference and stay tuned for regular updates! ##### Navigation/Editing - Ctrl + a – Go to start of line - Ctrl + e – Go to end of line - Ctrl + u – Cut from start of line - Ctrl + k – Cut to end of line - Ctrl + w – Cut the word before the cursor - Ctrl + y – Paste the last cut text - Ctrl + L – Clear the screen ##### History - Ctrl + r – Search history - !! -Repeat last cmd - !abc – Run last command starting with abc ##### Misc Commands - sudo shutdown -h now – Shutdown system now - sudo shutdown -r now – Reboot system now #### Resources All credit for these commands goes to the creators behind the below cheatsheet, and I’m grateful for their contribution to the community. - Linux cmds 1 - Linux cmds 2 --- # Vim Cheat Sheet URL: https://www.securityinbits.com/cheatsheet/vim-cheat-sheet/ Published: 2024-01-21 (updated 2024-01-18) Tags: vim Mastering Vim has been both challenging and rewarding. In this evolving cheat sheet, I share frequently used shortcuts seamlessly integrated into my VSCode and Obsidian workflow. Mastering Vim has been both challenging and rewarding. In this evolving cheat sheet, I share frequently used shortcuts seamlessly integrated into my VSCode and Obsidian workflow. Here are key commands that have proven invaluable in my ongoing Vim journey. ##### Cursor Movement - h – move cursor left - j – move cursor down - k – move cursor up - l – move cursor right - f/F – move to next( or previous) occurrence of character - 0 – jump to the start of the line - $ – jump to the end of the line - gg – go to the first line of the document - G – go to the last line of the document - w – jump forwards to the start of a word - W – jump forwards to the start of a word (words can contain punctuation) - Ctrl + b – move screen up one page (cursor to last line) - Ctrl + f – move screen down one page (cursor to first line) - ##### Editing - . – repeat last command - u – undo - Ctrl + r – redo - r – replace a single character. - R – replace more than one character, until ESC is pressed. ##### Cut & Paste - yy – yank (copy) a line - 2yy -yank (copy) 2 lines - yw – copy word - p – put (paste) the clipboard after cursor   - d$ or D – delete (cut) to the end of the line - dd – delete a line - 2dd – delete 2 lines - dw – delete word - d2w – delete 2 words - di' – delete inside ‘ - x – delete (cut) character - :g/{pattern}/d – delete all lines containing pattern - :g!/{pattern}/d – delete all lines not containing pattern ##### Search & replace - /pattern – search for pattern - ?pattern – search backward for pattern - \vpattern – ‘very magic’ pattern: non-alphanumeric characters are interpreted as special regex symbols (no escaping needed) - n – repeat search in same direction - N – repeat search in opposite direction - :%s/old/new/g – replace all old with new throughout file - :%s/old/new/gc – replace all old with new throughout file with confirmations - :noh – remove highlighting of search matches #### Tips - Use this to see help for cmd :help w - Prefix a cursor movement command with a number to repeat it. For example, 4j moves down 4 lines. - W– Much faster than w #### Resources All credit for these commands goes to the creators behind the below cheatsheet, and I’m grateful for their contribution to the Vim community. - Comprehensive cheatsheet --- # Deobfuscate PowerShell using subtract – CyberChef Recipe 0x4 URL: https://www.securityinbits.com/tools/cyberchef/deobfuscate-powershell-using-subtract-cyberchef-recipe-0x4/ Published: 2024-01-10 (updated 2024-01-22) Tags: cyberchef, cyberchef-recipe, infostealer, powershell, redline We’ll explore CyberChef operations e.g Generic code Beautify, Subsection, Fork, Subtract etc. to deobfuscate the 2nd stage PowerShell script used in the RedLine stealer infection chain. In this quick blog post, we’ll explore the various combination of CyberChef operations e.g Generic code Beautify, Subsection, Fork, Subtract etc. to deobfuscate the second-stage PowerShell script used in the RedLine stealer infection chain. The PowerShell contain multiple array consist of integer. It employs a straightforward function to decode the array by subtracting 7390 from each element. #### CyberChef Recipe Overview - Utilize subsection regex to capture the integer array after @ e.g. @(7436, 7490, 7498, 7498). Now we can execute operations on this part of the script - Cleanup this subsection using Find/Replace operation - Use the Find/Replace operation to replace ‘$’ with ‘,’ and ‘7390’. This “,” delimiter used in below subtract operation - Apply subtract operation (Delimiter ,) and using From Decimal to deobfuscate PowerShell script. This is similar to CyberChef Recipe 0x3. #### Input required Feel free to follow along by copying the obfuscated VBScript input from my GitHub link. [image: CyberChef Input Obfuscated PowerShell] _CyberChef Input Obfuscated PowerShell_ #### Output After loading the CyberChef recipe, your script should look like the image below. [image: Stage 2 PowerShell deobfuscated] _Stage 2 PowerShell deobfuscated_ #### CyberChef Recipe Generic_Code_Beautify() Subsection('@\\([^)]*\\)',true,true,false) Find_/_Replace({'option':'Regex','string':'[@()]'},'',true,false,true,false) Find_/_Replace({'option':'Regex','string':','},'\\n',true,false,true,false) Find_/_Replace({'option':'Regex','string':'$'},',7390',true,false,true,false) Fork('\\n','',false) Subtract('Comma') From_Decimal('Space',false) Merge(true) Find_/_Replace({'option':'Regex','string':'Ddy'},'',true,false,true,false) Syntax_highlighter('powershell') --- # Deobfuscate Script using CyberChef – Recipe 0x3 URL: https://www.securityinbits.com/tools/cyberchef/deobfuscate-script-using-cyberchef-recipe-3/ Published: 2023-10-17 (updated 2024-01-22) Tags: cyberchef, cyberchef-recipe, infostealer, redline, vbscript Explore Deobfuscation with CyberChef as we decode VBScript used in the RedLine stealer infection chain. We’ll explore the various CyberChef operations e.g Subsection, From Base, Fork etc. In this quick blog post, we’ll explore the various combination of CyberChef operations e.g Subsection, From Base, Fork etc for deobfuscating VBScript used in the RedLine stealer infection chain. VBScript often employs the ‘chr’ function to obfuscate its code, where ‘chr’ converts Ascii codes to characters e.g. Chr(65) will return ‘A’. In this script it uses simple subtraction before converting the character to Ascii using chr. Our goal is to demonstrate various CyberChef operations that help us clean up and understand this malicious code effectively. #### CyberChef Recipe Overview - Replace ‘&H’ with ‘0x’ using the Find/Replace operation. - Utilize subsection regex to capture the hex part inside chr e.g. chr(303-(0xE9)). Now we can execute other operations on this part of the script - Convert this hex to decimal using the ‘From Base’ operation. - Use regex to capture the part inside chr - Apply subtract operation (Delimiter :) and using From Decimal to deobfuscate the script. #### Input Feel free to follow along by copying the obfuscated VBScript input from my GitHub link. [image: Input Obfuscated Script] _Input Obfuscated Script_ #### Output After loading the CyberChef recipe, your script should look like the image below. [image: CyberChef Recipe decode VBScript] _CyberChef Recipe decode VBScript_ #### CyberChef Recipe for Deobfuscation Find_/_Replace({'option':'Simple string','string':'&H'},'0x',true,false,true,false) Subsection('chr\\(\\d+-\\((0x[A-Fa-f0-9]+)\\)\\)',true,true,false) From_Base(16) Merge(true) Find_/_Replace({'option':'Simple string','string':'-('},':',true,false,true,false) Find_/_Replace({'option':'Simple string','string':'))'},')',true,false,true,false) Regular_expression('User defined','chr\\(([^)]+)\\)',true,true,false,false,false,false,'List capture groups') Fork('\\n','',false) Subtract('Colon') From_Decimal('Space',false) According to a recent announcement, Microsoft has stated that VBScript will be removed from Windows in a future release, which is a positive development for us. However, the CyberChef operations mentioned above will still be useful. --- # AsyncRAT config decryption using CyberChef – Recipe 0x2 URL: https://www.securityinbits.com/tools/cyberchef/asyncrat-config-decryption-using-cyberchef-recipe-2/ Published: 2023-08-07 (updated 2024-01-22) Tags: net, asyncrat, config, cyberchef, cyberchef-recipe, rat, remote-access-tool Decrypt AsyncRAT configurations effortlessly using CyberChef with our step-by-step guide. Dive into the recipe and enhance your malware analysis skills. In the realm of malware analysis, tools like CyberChef play a pivotal role. One of the challenges that malware analysts often face is decrypting configurations of Remote Access Trojans (RATs) like AsyncRAT. This article provides a step-by-step guide on how to decrypt AsyncRAT configurations using CyberChef. #### Decrypting AsyncRAT Configurations AsyncRAT is a notorious RAT that enables attackers to remotely control infected systems. Decrypting its configurations can be a daunting task, but with the right tools and techniques, it’s achievable. For those keen on exploring more about config decryption techniques, I recommend diving into my previous article. #### CyberChef Recipe for AsyncRAT config decryption Regular_expression('User defined','public static string \\w+\\s+\\=[ "0-9a-zA-Z+/=]{12,}',true,true,false,false,false,false,'List matches') Find_/_Replace({'option':'Simple string','string':'public static string '},'',true,false,true,false) Register('([\\s\\S]*)',true,false,false) Comment('Input: In the filter operation box below, add the variable name that stores the AES key, e.g. Key') Filter('Line feed','',false) Regular_expression('User defined','(?<=\\")(.+?)(?=\\")',true,true,false,false,false,false,'List matches') Register('([\\s\\S]*)',true,false,false) Comment('Input: If you don\'t know the salt value, then try using the following salts. Don\'t forget to select the proper salt format HEX or UTF8.\n\nI have encountered only 2 salts for AsyncRAT:\n\nbfeb1e56fbcd973bb219022430a57843003d5644d21e62b9d4f180e7e6c33941 (Format: HEX)\n\nDcRatByqwqdanchun (Format: UTF8)') Derive_PBKDF2_key({'option':'Base64','string':'$R1'},256,50000,'SHA1',{'option':'Hex','string':''}) Register('([\\s\\S]*)',true,false,false) Find_/_Replace({'option':'Regex','string':'.*'},'$R0',false,false,false,true) Comment('Input: In the filter operation box below, add the variable name that stores the AES key, e.g. Key') Filter('Line feed','',true) Subsection('(?<=\\")([0-9a-zA-Z+/=]{32,})(?=\\")',true,true,false) Fork('\\n','\\n',false) From_Base64('A-Za-z0-9+/=',true,false) To_Hex('None',0) Drop_bytes(0,64,false) Register('(.{32})(.*)',true,false,false) Drop_bytes(0,32,false) AES_Decrypt({'option':'Hex','string':'$R2'},{'option':'Hex','string':'$R3'},'CBC','Hex','Raw',{'option':'Hex','string':''},{'option':'Hex','string':''}) Merge(true) Find_/_Replace({'option':'Regex','string':'$'},'\\nAES_KEY = "$R2"',false,false,false,true) #### Input required - The AsyncRAT line of code which contain encrypted setting - Salt bfeb1e56fbcd973bb219022430a57843003d5644d21e62b9d4f180e7e6c33941 (Format: HEX) - DcRatByqwqdanchun (Format: UTF8) - The variable name that stores the AES key #### Md5: 37e965330586a51125db2a420917db17 Follow the steps below to decrypt AsyncRAT configurations: ##### Step 1 Load the file in dnSpyEx. After loading the assembly, right click & select  ‘Go to Entry point‘. Navigate to the first function present inside if ()  i.e. Settings.InitializeSettings(). Click on this function to navigate to the definition of this function in the Settings class. [image: AsyncRAT Step 1] _AsyncRAT Step 1_ ##### Step 2 Navigate to the Setting class and copy all public static declarations to CyberChef. [image: AsyncRAT Setting class Step 2] _AsyncRAT Setting class Step 2_ ##### Step 3 Load the CyberChef recipe and the public static string block of code. The variable name ‘Key’ will be used in Step 4 [image: AsyncRAT CyberChef recipe Load Step 3] _AsyncRAT CyberChef recipe Load Step 3_ ##### Step 4 Add the AES key variable name from the previous step. Note: Comments have been added in this CyberChef recipe for clarity. ##### Step 5 Input the salt and select utf-8, or try both salts, one should work. For more details read the comment in the recipe. [image: AsyncRAT CyberChef recipe Step 4 and Step 5] _AsyncRAT CyberChef recipe Step 4 and Step 5_ ##### Last Step Add the same AES key variable name from the previous steps. Click ‘Bake’; it should decrypt the config. [image: AsyncRAT CyberChef Recipe last step] _AsyncRAT CyberChef Recipe last step_ #### Conclusion Decrypting AsyncRAT configurations can be a complex task, but with the right tools and recipes, it becomes manageable. CyberChef, with its versatile set of operations, is an excellent tool for this job. We hope this guide helps you in your malware analysis endeavors, especially when dealing with AsyncRAT. Note: This recipe was initially developed by Srujan Kumar. I have made few modifications to support the new AsyncRAT files. --- # AsyncRAT: Config Decryption Techniques and Salt Analysis URL: https://www.securityinbits.com/malware-analysis/asyncrat-config-decryption-techniques-and-salt-analysis/ Published: 2023-08-05 (updated 2023-11-23) Tags: net, asyncrat, config, cyberchef, cyberchef-recipe, rat, remote-access-tool Explore AsyncRAT inner workings. Learn unique decryption techniques to enhance your cybersecurity skills today! In this article, we dive into the inner workings of AsyncRAT. This Remote Access Trojan (RAT) has seen a staggering 20% surge in its activity during the last quarter, as reported by the Spamhaus report. We’ll explore diverse decryption methods for the AsyncRAT configuration and explore the AES Salts used in various files. ### What is AsyncRAT? AsyncRAT is a Remote Access Tool (RAT) designed to remotely monitor and control other computers through a secure encrypted connection. It is an open source remote administration tool, however, it could also be used maliciously because it provides functionality such as keylogger, remote desktop control, and many other functions.  (Source: Malpedia) ##### Delivery Methods: How Malware Spreads Spear-phishing, malvertising, exploit kit, and other techniques serve as delivery methods for this malware. ### AsyncRAT Config Decryption via Static Extractors Let’s dig deeper into decrypting the AsyncRAT configuration with static extractors like CyberChef Recipe and Python script. [image: Decryption Code for AsyncRAT] _Decryption Code for AsyncRAT_ ##### CyberChef Recipe One of the most efficient ways to decode the AsyncRAT config is by using the CyberChef Recipe developed by Srujan Kumar. I have made few modifications to existing recipe which support new AsyncRAT files. The updated recipe, available on GitHub, works by decoding the AsyncRAT config. You need the code, salt, and variable name that stores the AES key. My research suggests that the current AsyncRAT samples predominantly use two salts. For a step-by-step guide to use CyberChef to decrypt the AsyncRAT, check this article. ##### Python Script Abdallah Elnoty has developed a small python script to decode the config. You can find all the details in this article (Feb 2022). ### Dynamic Approach: Reflection in PowerShell For those who prefer a more dynamic approach, @vinopaljiri has shared an innovative technique for config decoding. This method involves using reflection and PowerShell to load the binary and then invoke the InitializeSettings method, providing a quick and efficient approach. You can find more details here. ### AsyncRAT Analysis: AES Salt In my analysis of approximately 10-20 files, , I encountered only two distinct salts for AsyncRAT. You can find more details on my Github page. [image: AsyncRAT Salt list with hashes] _AsyncRAT Salt list with hashes_ ##### Salt 1: bfeb1e56fbcd973bb219022430a57843003d5644d21e62b9d4f180e7e6c33941 (Format: HEX) This salt is referenced in the AsyncRAT source code available on Github (Last commit: May 10, 2020). It is also utilized in Quasar RAT 1.3, as indicated in the QuasarRAT-Analysis from December 1, 2020. ##### Salt 2: DcRatByqwqdanchun (Format: UTF8) This salt is also used by DcRat malware (First commit: Mar 20, 2021). ### Conclusion These techniques are still effective on unpacked files, with some minor modifications. In the next blog post, we will delve deeper into CyberChef recipe and dynamic approach. Stay tuned! --- # Converting Integers to Hex with CyberChef – Recipe 0x1 URL: https://www.securityinbits.com/tools/cyberchef/converting-integers-to-hex-with-cyberchef-recipe-1/ Published: 2023-07-14 (updated 2024-01-09) Tags: net, amsi, asyncrat, cyberchef, cyberchef-recipe, rat We will use CyberChef to decode the integer array into hex and pad it with extra 0s if needed. Then, we can disassemble the code using an online tool or CyberChef. While analyzing malware, it’s common to encounter situations where you need to disassemble code sourced from an integer array. However, when you attempt to use the ‘To Hex’ function in CyberChef, it won’t work. The solution is to employ the ‘To Base’ operation with a radix value of 16. I was working on an initial .NET file that drops AsyncRAT. It contains following code to evade AMSI and found this sample from OALABS Twitch stream. SHA256 43cc6ed0dcd1fa220283f7bbfa79aaf6342fdb5e73cdabdde67debb7e2ffc945 For a quick guide to converting the integer array into Hex, padding zeros, and disassembling the code using CyberChef tool, follow the steps detailed below. Update: Reddit pimmytrousers suggested the simple method to use From Decimal , update the below recipe with the same. Thank you for suggestion. [image: .NET code for AMSI Bypass] _.NET code for AMSI Bypass_ ### Complete CyberChef Recipe From_Decimal('Comma',false) To_Hex('Space',0) Disassemble_x86('32','Full x86 architecture',16,0,true,true) ###### Step 1 Using the To Decimal operation with a  delimiter ,. ###### Step 2 Use the To Hex operation with delimiter Space to convert this in hex format. [image: CyberChef recipe step 2] _CyberChef recipe step 2_ ###### Final step Then, you can either leverage an online disassembler or the built-in CyberChef Disassemble x86 operation to get the final result. [image: CyberChef recipe final step] _CyberChef recipe final step_ This is another method to do the same thing, but it requires more operations. Use the above recipe to decode it. ##### Complete CyberChef Recipe Fork(',',' ',false) To_Base(16) Merge(true) Find_/_Replace({'option':'Regex','string':'\\b(\\w)\\b'},'0$1',true,false,true,false) Disassemble_x86('32','Full x86 architecture',16,0,true,true) ###### Step 1 Input: 184, 87, 0, 7, 128, 195 We’ll employ the Fork operation to separate the input based on the ‘,’ delimiter, then proceed to run the next operation on each individual integer. [image: Step 1 - CyberChef using Fork] _Step 1 CyberChef Recipe using Fork_ ###### Step 2 Using the To Base operation with a radix of 16, convert the integers to hex. Then, use the Merge operation to consolidate all the inputs into a single string. [image: Step 2 - CyberChef using To Base] _Step 2 - CyberChef using To Base_ ###### Final step Upon completion of the previous steps, it’s likely that some of the hex bytes are missing a leading zero. b8 57 0 7 80 c3 Let’s fix this using a simple regex \b(\w)\b to detect single characters and replace the matches with 0$1 to add an extra zero in front. Once adjusted, you can either leverage an online disassembler or the built-in CyberChef Disassemble x86 operation. [image: Last Step CyberChef Recipe] And there we have it – our integer array has been decoded to code: b8 57 00 07 80  mov eax,0x80070057 c3               ret This code helps in AMSI bypass, for more details please read this AMSI Bypass Using Memory Patching --- # Interesting tactic by Ratty & Adwind for distribution of JAR appended to signed MSI – CVE-2020-1464 URL: https://www.securityinbits.com/malware-analysis/interesting-tactic-by-ratty-adwind-distribution-of-jar-appended-to-signed-msi/ Published: 2020-06-28 (updated 2023-07-26) Tags: adwind, binwalk, bytecode-viewer, cve-2020-1464, file, glueball, iocs, jar, java, msi, rat, ratty, xxd, yara, zip This article discusses an interesting tactic (CVE-2020-1464) actively used by different Java RAT malware authors like Ratty & Adwind to distribute malicious JAR appended to signed MSI files. This article discusses an interesting tactic actively used by different Java RAT malware authors like Ratty & Adwind  to distribute malicious JAR appended to signed MSI files. This technique was discovered by VT Team in Aug 2018[9] but that time it was not used by malware authors to distribute malicious JAR files. Thanks to EKTracker tweet[1], where I found this interesting Ratty hashes using this technique. Our goal is to understand the unique technique instead of analysing the Java RAT. 1/ Interesting technique used by #Ratty sample for distribution of malicious JAR(zip) appended to MSI So when the OS sees jar ext it executes jre to handle the file, but unique about zip files are read from bottom to top so jar is executed instead of msi file, details below https://t.co/3u7487kUZy pic.twitter.com/jZw9s07X5z — Securityinbits (@Securityinbits) June 12, 2020 ### CONTENTS - Overview of ZIP, JAR & MSI file format - How does it work? - Analysis of JAR appended to signed MSI files using Ratty RAT - Timeline - Conclusion - Yara Signature - Indicator of Compromise - References ### 1. Overview of ZIP, JAR & MSI file format Before we discuss the technique we need to understand some concepts regarding ZIP, JAR and Windows Installer MSI files. If you already know this, please skip to the next section. ##### ZIP PE files are read from top to bottom but ZIP files are read from bottom to top due to their design. Some more details from Wikipedia[2] A directory is placed at the end of a ZIP file. This identifies what files are in the ZIP and identifies where in the ZIP that file is located. This allows ZIP readers to load the list of files without reading the entire ZIP archive. A ZIP file is correctly identified by the presence of an end of central directory record(EOCD) which is located at the end of the archive structure in order to allow the easy appending of new files. [image: ZIP-64 Internal Layout] _Zip format from Wikipedia [2]_ ##### JAR JAR files follow the zip format. Some more details from Wikipedia[3] A JAR (Java ARchive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file for distribution. JAR files are archive files that include a Java-specific manifest file. They are built on the ZIP format and typically have a .jar file extension. ##### MSI or Windows Installer MSI file follows Compound File/Composite Document File V2 Document/Object Linking and Embedding (OLE). A compound file is a structure that is used to store a hierarchy of storage objects and stream objects into a single file or memory buffer. oletools and oledump can be used to browse the structure of MSI files[5]. We will not go in so much detail of OLE file. ### 2. How does it work? Malware author takes two files, one is a clean digital signed MSI file let say with filename clean_signed.msi and other is malicious JAVA RAT malware filename malicious.jar. [image: JAR appended to signed MSI] _Malicious JAR appended to signed MSI_ Steps: - Malware author select a clean clean_signed.msi MSI file which is digitally code signed from Microsoft, Google etc. So maybe security control will not not scan the file due to it’s digital signature. The OS reads the file from top to bottom and see the digital signature, so everything is good till now. - Other malicious.jar is essentially a zip file which is read from bottom to top as discussed above. - On Microsoft Windows systems, the Java Runtime Environment’s installation program will register a default association for JAR files so that double-clicking a JAR file on the desktop will automatically run it. - Now, attackers just need to append the jar file to the MSI file and change the extension to jar. - Attackers can use this command copy /b clean_signed.msi + malicious.jar signed_malicious.jar to generate malicious signed file. - When the user executes the signed_malicious.jar, it will execute the malicious jar file as it’s read from bottom to top. ##### Why is digital signature still valid? After the attacker creates the signed_malicious.jar the digital signature is still valid due to the reason mentioned in the VirusTotal blog post. Code signing is the method of using a certificate-based digital signature to sign executables and scripts in order to verify the author’s identity and ensure that the code has not been changed or corrupted since it was signed by the author. This way, for example, if you modify the content or append any data to a signed Windows PE (.EXE) file the signature of the resulting file will not be valid for Microsoft Windows, as expected. This behaviour changes when you append any data to the end of a signed Windows Installer (.MSI), the resulting file will pass the verification process of Microsoft Windows and will show just the original signature as valid without any other warning. ### 3. Analysis of JAR appended to signed MSI files using Ratty RAT We will analyse this Ratty 06-01-20.jar (MD5: 13a4072d8d0eba59712bb4ec251e0593) [10] but the same process is applicable for the Adwind sample. 1. Let’s start with checking the magic byte or file header of this file using file cmd and xxd.  Please feel free to use any other hex viewer. [image: MSI header using file and xxd for Ratty] _MSI header using file and xxd for Ratty_ Based on the extension jar this file should have magic bytes for zip but the above figure shows the standard MSI file header with magic bytes D0 CF 11 E0 A1 B1 1A E1. Note: This anomaly for extension not matching header is a good indicator to detect this and other kinds of attack. 2. Now if you check the digital signature using properties it looks ok. [image: Ratty Digital Signature] _Ratty Digital Signature_ [image: Sigcheck on Ratty] _Sigcheck on Ratty_ But using Sigcheck will say “Signed but the filesize is invalid (the file is too large)“. This is another good detection point.   3. Investigating further using binwalk on this 06-01-20.jar file you will see it matches different zip signatures starting from offset 0xc600 as shown in the figure below. [image: binwalk Ratty output] _binwalk Ratty output_ Based on the output, you can easily guess there is a JAR appended to this MSI file. 4. If you dump some bytes at offset using xxd you will see a zip header. xxd -s 0xc600 -l 0x100 06-01-20.jar [image: Hexdump at 0xc600] _Hexdump at 0xc600_ 5. Let’s extract the JAR file from offset 0xc600 then use  Bytecode Viewer to analyze the jar file. I am using dd for this but you can use any hex editor. dd skip=0xc600 if=06-01-20.jar of=extracted_ratty.jar bs=1 If you are new to Java reversing or Bytecode Viewer, you may want to check this Pyrogenic/Qealler Infostealer static analysis – Part 0x1. [image: dd cmd for extracting Ratty jar] _dd cmd for extracting Ratty jar_ 6. The extracted file is not packed so if you open the extracted_ratty.jar in Bytecode Viewer, you can see the decompiled Java Code. Based on the package and folder structure this  extracted_ratty.jar is based on this GitHub Ratty repo. I will not dig any further in this Ratty malware and decompiled Java code can be easily analysed.   [image: Decompiled Ratty Code & Github repo] _Decompiled Ratty Code & Github repo_ ### 4. Timeline This technique was discovered by VirusTotal team[9] VirusTotal posted a blog post[6] about this technique and mentioned that it’s not being used massively to distribute malware. There were two other notable blog posts[7] [8] discussing VirusTotal blog. All three blog posts gives a great explanation of this technique. Malware author started using this technique for distribution of malicious Java RATs like Adwind and Ratty. At last, Microsoft decided to fix this CVE-2020-1464 | Windows Spoofing Vulnerability. I suspect as malware authors started using this old bug which was discovered in Aug 2018, so Microsoft decided to fix it. ### 5. Conclusion When I saw this interesting technique, I was puzzled.Hopefully, I have explained this technique detailed enough in this post. ##### Detection - Anomaly for extension not matching header is a good indicator to detect this technique and below yara rule can be used. - Check Sigcheck output “Signed but the filesize is invalid (the file is too large)” for digital signed files - AV may detect this suspicious behaviour of malicious JAR Sharing Yara signature to detect this technique and IoCs below. Update 17 Aug, 2020 - Microsoft fixed this CVE-2020-1464 (Windows Spoofing Vulnerability) as malware authors started actively exploiting this old bug which was discovered in Aug 2018. If you are interested to also learn about technical analysis about GlueBall CVE-2020-1464, please check out the awesome article [13] by @TalBeerySec. - Brian Krebs posted an article [14] about this CVE-2020-1464 (GlueBall). ### 6. Yara Signature ```yara rule jar_in_msi { meta: description = "Detect jar appended to MSI" author = "Securityinbits" date = "2020-06-14" reference = "https://twitter.com/Securityinbits/status/1271406138588708866" hash_1 = "13a4072d8d0eba59712bb4ec251e0593" hash_2 = "63bed40e369b76379b47818ba912ee43" hash_3 = "85eb931d0d27179ae7c13085fb050b11" strings: $msi_magic = { D0 CF 11 E0 A1 B1 1A E1} //To detect zip Local file header(lfh) & End of central directory record(eocd) $s_zip_magic_lfh = {50 4B 03 04} $s_zip_magic_eocd = {50 4B 05 06} $s_jar = "META-INF/MANIFEST.MF" $s_java_class = ".class" condition: $msi_magic at 0 and filesize > 60KB and all of ($s_*) } ``` View on GitHub Note: I haven’t checked this yara signature on a clean set of files so it may cause FP. ### 7. Indicator of Compromise(IOCs) ##### MD5 Ratty ``` 13a4072d8d0eba59712bb4ec251e0593 -> This hash analysed in this post 63bed40e369b76379b47818ba912ee43 fa8118a9fa20a17018cb2f60fd28a5b7 4a3d69c28c4742177d6238bc16486f0d 48a5714147ee85374ab74174a82ab77a ``` Adwind ``` 85eb931d0d27179ae7c13085fb050b11 ``` Thanks to @c_APT_ure for sharing following hashes related to this technique Ratty ``` 800fbf461f13facf4799e96f5026fd47 shipment.label.jar f3ea296ad35eec33ea436febd97ff0e2 Shipment-label.jar 80908e5e21c3aff7e8bcaccdbb99e02e 21-04-2020.jar 83aaba8a3cd871441d2c386aaa3ee0e0 TrackingOrder.jar c50b8615b8d6613f92586224b15bc9ac tracking.update.jar 1eb30fec5a58dc7a6af2c17d7e8327d0 ups-label.jar 85e8e4e814c29ce8779772fca4df64d7 21-05-2020.jar a49c0e0d1ca8a829a8175a3931e5cba1 a49c0e0d1ca8a829a8175a3931e5cba1.jar 4a2d5424f87d1d4cdcd8a9bea81d2e2a shipment.delivery.label.06-03.jar ``` Adwind, Thanks to @c_APT_ure for sharing the hashes ``` 0559defe2122020a2733fafbd6443fd6 2.jar 7239fb81b1771e2aa38edbe0b68e40d5 CONFIRMATION_SWIFT.pdf.jar ``` ### 8. References - Tweet by Ektracker - ZIP file format - JAR file format - Compound File Binary Format (CDF) - Analyzing MSI files - Distribution of malicious JAR appended to MSI files signed by third parties - Thoughts on the MSI/JAR Authenticode Bypass - Making Meterpreter Look Google-Signed (Using MSI & JAR Files) - Reply to the tweet by @bquintero - Hashes shared by @c_APT_ure - ANY.RUN– (MD5: 13a4072d8d0eba59712bb4ec251e0593) Ratty - Revamped jRAT Uses New Anti-Parsing Techniques - GlueBall: The story of CVE-2020–1464 - Microsoft Put Off Fixing Zero Day for 2 Years by Brian Krebs --- # PowerShell Commands for Incident Response URL: https://www.securityinbits.com/incident-response/powershell-commands-for-incident-response/ Published: 2020-05-25 (updated 2023-07-26) Tags: blue-team, cheat-sheet, commands, nanocore, powershell, rat We will learn different PowerShell Commands can be used in Incident Response to remediate the machine. I will take a scenario where a machine is infected with NanoCore malware to explain this PowerShell Commands. We will learn different PowerShell Commands can be used in Incident Response to remediate the machine. I will take a real world scenario where a machine is infected with malware e.g. NanoCore RAT to explain this PowerShell Commands. These commands can be very useful in a limited Windows environment where you don’t have access to tools like GNU core utilities, Python interpreters etc. If PowerShell remoting [2] is configured in your environment then you run these commands even on a remote infected machine from your clean machine. ### CONTENTS - Overview of PowerShell - Malware infection scenario- NanoCore - PowerShell Commands for Incident Response - Conclusion - References ### Overview of PowerShell From Microsoft[1] – “PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes”. PowerShell is based on object not text. The output of a command is an object. You can send the output object, through the pipeline, to another command as its input. This pipeline provides a familiar interface for people experienced with other shells. PowerShell extends this concept by sending objects rather than text. These are two types of PowerShell: - PowerShell or PowerShell Core – This is the current/latest version and built on .NET core framework. It’s open-source and run on Windows, Linux, macOS and ARM. The latest version is PowerShell 7 and main focus is making it a viable replacement for Windows PowerShell 5.1. This version needs to be manually installed from Github releases pages[3]. - Windows PowerShell – This is a legacy version and built on the .NET Framework and only worked on Windows systems. This is default installed on Windows systems and the latest version is 5.1. How to execute PowerShell? - Local Machine- Simplest way is to launch PowerShell via the start menu, select Windows PowerShell or PowerShell 7. - Remote Machine – Configure PowerShell remoting [2] in your environment then you run commands on the remote machine as shown below. [image: PowerShell Commands for Incident Response-Execution of PowerShell Command in PS Remoting] _Execution of PowerShell Command in PS Remoting_ Show MoreShow Less ### Malware infection scenario – NanoCore Suppose there is a NanoCore malware infection in our environment and we are at the eradication step of Incident Response.  We will learn which PowerShell Commands can be used for Incident Response but it can be applicable to any malware family . To keep it simple, we will consider following points: - Only one Windows 10 machine is infected with NanoCore malware in our environment based on Network logs. - We have physical access to this machine so no need for PowerShell Remoting. - We have the copy of the initial NanoCore sample 0ed2be7c91efdb87c98084bb0a22d8d7 [4] which infected the machine, so we know the IoCs. ##### NanoCore IoCs - Drop RAVBg64.exe and bat files in $Env:TEMP - Create run.dat and other files in the GUID directory in $Env:APPDATA. - Create Persistency by creating autorun entry in HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run - CC: anunankis3[.]duckdns[.]org ### PowerShell Commands for Incident Response The main goal of this Eradication step in Incident response is to remove all the malware artifacts from the system and verify if the system is completely cleaned or not. One of the good things about PowerShell Commands is you don’t need to use different tools for working with files, registry or processes, all the things you can manage using inbuilt PowerShell cmdlets. All the PowerShell commands are tested on PowerShell 7 (or Core) but should work on Windows PowerShell 5.1. #### Steps for removing NanoCore infection: - ##### Check for malicious process - ##### Terminate malicious process - ##### Remove the persistency - ##### Check for files in $env:APPDATA\GUID\ - ##### Get the Hashes of the files - ##### Copy artifacts for analysis - ##### Delete malware artifacts Please make sure you are running the PowerShell with admin privilege otherwise you will not be able to remediate the system. ##### 1. Check for malicious process We have to check if the malicious process RAVBg64.exe is currently executing from $env:TEMP directory or not. Get-Process cmdlet can be used to get currently executing processes as shown in the pic below. Get-Process For quick reference, check PowerShell Cheat Sheet at Github which include all the commands discussed in this article. [image: Get-Process PowerShell cmdlet output] _Get-Process PowerShell cmdlet output_ We know this RAVBg64 .exe process is executing as shown in the above image but we need to know the complete path to identify if it’s running from the temp directory. Get-Process RAVBg64 | Select-Object Id, ProcessName, Path, Company, StartTime | Format-Table Get-Process cmdlet doesn’t support the process command line so use Get-WmiObject command Only applicable for Windows PowerShell 5.1 Get-WmiObject -Class Win32_Process -Filter "name='RAVBg64.exe'" | Select-Object ProcessId, ProcessName, CommandLine But Get-Wmiobject is deprecated so use Get-CimInstance for PowerShell 7 as mentioned by reddit user. Get-CimInstance -Class Win32_Process | Format-Table -Property ProcessId, ProcessName, CommandLine -Autosize [image: Get-Process & Get-WmiObject PowerShell cmdlets output] _Get-Process & Get-WmiObject PowerShell cmdlets output_ ##### 2. Terminate malicious process Stop-Process can be used to terminate processes based on process name or process ID (PID), or pass a process object. Get-Process RAVBg64 | Stop-Process You may need to stop this process imapsv.exe instead of RAVBg64.exe, if the machine has already restarted as this filename is used in registry for persistence. [image: PowerShell Command for Stop-Process] _PowerShell Command for Stop-Process_ If you don’t stop the malicious process and try to delete the file from disk then it will give you access error due to the open handle. ##### 3. Remove Persistence Get-ItemProperty cmdlet can be used for listing registry entries as shown below: Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name 'IMAP Service' Remove-ItemProperty can be used for removing NanoCore persistence registry entry Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' | Remove-ItemProperty -Name 'IMAP Service' Get-ItemProperty 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' [image: PowerShell Commands for Incident Response - Query & remove NanoCore registry entry using PowerShell Command] _Query & remove NanoCore registry entry using PowerShell Command_ ##### 4. Check for files in $env:APPDATA\GUID\ -Force – It is used to list hidden or system files. Some malware use the hidden attribute for their files, so always use this parameter. NanoCore creates a unique GUID dir in $env:APPDATA to keep it’s copy and logs. We can Get-ChildItem cmdlet to list the directory it’s like dir cmd. This cmdlet can be used in file system directory, registry hive, or a certificate store. -Recurse – Used to recursive list all the sub-dir -Filter – You can use the parameter to filter the path and it supports * and ? wildcards e.g *.dat, *.exe Get-ChildItem -Path $Env:APPDATA -Force -Recurse -Filter run.dat Instead of Get-ChildItem, we can Test-Path to check if the dir or file exists or not Test-Path -Path $Env:APPDATA\*\run.dat [image: Test-Path & Get-ChildItem PowerShell cmdlets] _Test-Path & Get-ChildItem PowerShell cmdlets_ After running the above cmds you will be able to know the unique GUID directory name 0319B08F-2B65-4192-B2D2-1E2F62087064 , this folder contain other artifacts as shown in below screenshot Get-ChildItem -Path C:\Users\admin\AppData\Roaming\0319B08F-2B65-4192-B2D2-1E2F62087064\ -Force -Recurse [image: PowerShell Commands for Incident Response - Get-ChildItem cmdlets using Force & Recurse parameters] _Get-ChildItem cmdlets using Force & Recurse parameters_ ##### 5. Gather hashes Get-FileHash cmdlet can be used to get the hash using a different algorithm e.g. MD5. SHA1 , SHA256 etc. By default, the Get-FileHash cmdlet uses the SHA256 algorithm, although any hash algorithm that is supported by the target operating system can be used. SHA256 Get-FileHash -Path 'C:\Users\admin\AppData\Roaming\0319B08F-2B65-4192-B2D2-1E2F62087064\IMAP Service\imapsv.exe' MD5 Get-FileHash -Algorithm MD5 -Path 'C:\Users\admin\AppData\Roaming\0319B08F-2B65-4192-B2D2-1E2F62087064\IMAP Service\imapsv.exe' [image: Get-FileHash PowerShell cmdlet] _Get-FileHash PowerShell cmdlet_ We can use Get-ChildItem & Get-FileHash cmdlets for collecting the file hashes in the directory with MD5, SHA256, Name & FullName. We will use calculated properties that require a Hashtable with a Name/label and an Expression key. The name key is the property name and the Expression key is a scriptblock that will be executed as Select-Object receives input. Please read this great article [5] by @adbertram regarding calculated properties using Hashtable @{ Name = ''; Expression = {}} Using E/Expression we are calculating the MD5 & SHA256 of each file returned by Get-ChildItem Get-ChildItem -Path C:\Users\admin\AppData\Roaming\0319B08F-2B65-4192-B2D2-1E2F62087064\ -Force -Recurse -File | Select-Object @{Name='MD5';E={(Get-FileHash -Algorithm MD5 $_).Hash}}, @{N='SHA256';E={(Get-FileHash -Algorithm SHA256 $_).Hash}}, Name, FullName [image: Gather MD5, SHA256, Name and FullName of NanoCore files] _Gather MD5, SHA256, Name and FullName of NanoCore files_ Now we will export the result in FileHashes.csv format using Export-Csv Get-ChildItem -Path C:\Users\admin\AppData\Roaming\0319B08F-2B65-4192-B2D2-1E2F62087064\ -Force -Recurse -File | Select-Object @{Name='MD5';E={(Get-FileHash -Algorithm MD5 $_).Hash}}, @{N='SHA256';E={(Get-FileHash -Algorithm SHA256 $_).Hash}},Name, FullName | Export-Csv -Path FileHashes.csv [image: PowerShell Commands for Incident Response - Exporting hashes to csv] _PowerShell Command for exporting hashes to csv_ ##### 5. Copy artifacts for analysis Before removing the artifacts, we may want to copy them for further analysis if needed by other teams. Let’s use the New-Item cmdlet to create the directory and use Copy-Item to copy the files to IoCs dir New-Item -ItemType Directory -Path C:\Users\admin\IoCs Copy-Item C:\Users\admin\AppData\Roaming\0319B08F-2B65-4192-B2D2-1E2F62087064\ -Destination C:\Users\admin\IoCs\ -Recurse [image: PowerShell Commands for Incident Response - New-Item & Copy-Item PowerShell cmdlets for directory] _New-Item & Copy-Item PowerShell cmdlets for directory_ ##### 6. Delete malware artifacts Note: Don’t forget to use -Force in Remove-Item, otherwise you cannot delete read-only or hidden files which are frequently used in Malware. We have already removed the persistence mechanism, now we just need to delete the files from the infected machine using Remove-Item cmdlet. Delete the complete dir recursively Remove-Item -Path $env:APPDATA\0319B08F-2B65-4192-B2D2-1E2F62087064\ -Recurse -Force Remove the copy of the NanoCore malware Remove-Item -Path $env:TEMP\RAVBg64.exe -Force Delete the initial file Remove-Item -Path $env:USERPROFILE\Desktop\Serial.exe [image: Remove-Item for file & directory] _Remove-Item cmdlet for file & directory_ #### Conclusion In this article, I have explained useful PowerShell Commands which can be used in Incident Response for NanoCore but these commands can be applied to any malware infection. There are a lot more PowerShell Commands which can be used in Incident Response. For the next iteration, you can even write the PowerShell script and deploy to multiple machines over your network for cleanup. If you are looking for an easy way to deobfuscate PowerShell then check this Deobfuscate PowerShell using PowerShell Logging. #### References - PowerShell Overview – Microsoft - PowerShell remoting - Installing PowerShell Core - ANY.RUN – (MD5: 0ed2be7c91efdb87c98084bb0a22d8d7) NanoCore - Using PowerShell’s Calculated Properties --- # Similarity between Qealler/Pyrogenic variants -Part 0x3 URL: https://www.securityinbits.com/malware-analysis/similarity-between-qealler-pyrogenic-variants-part-0x3/ Published: 2020-02-04 (updated 2023-07-26) Tags: bytecode-viewer, infostealer, java, pyrogenic, qealler In this last part, we will compare Old Qealler with new Qealler/Pyrogenic variant based on static code analysis. In this last part, we will compare Old Qealler with the new Qealler/Pyrogenic variant. The previous posts Pyrogenic Infostealer static analysis – Part 0x1 & Unpacking Pyrogenic/Qealler using Java agent -Part 0x2  went through the latest Pyrogenic/Qealler [6] statically and dumping the unpacked code using Java agent. ##### CONTENTS - Brief Timeline - Similarity between Qealler variants - Conclusion - References #### Brief Timeline ##### June 2018 First Old Qealler sample [4] (MD5: 65ab1ef8e9cef5c489d4b01cbb8a2a22)  found on ANY.RUN ##### Aug-Sep 2018 The tweet[1] by @James_inthe_box first mentioned the Old Qealler. @jeFF0Falltrades posted Qealler Unloaded deep dive analysis [2] . ##### Jan-Feb 2019 Multiple cyber security company posted articles[3] about Qealler variant using the Qazagne Python credential harvester. ##### April 2019 Based on ANY.RUN submissions, Old Qealler variant using the Qazagne stopped around April 2019 ##### Aug 2019 – Now Based on ANY.RUN submissions, Qealler tagged samples started around Aug 2019 and continue till now Aug 2020. Note: When this post mention Old Qealler it means that the variant which was using the Qazagne Python credential harvester. #### Similarity between Qealler variants For easy/fast comparison, I have imported unpacked code of both Qealler variant in Eclipse IDE.  I will compare this Old Qealler (MD5: 8D564A18B902461C19936CCB1F4E2F12) [5] and new Pyrogenic/Qealler sample (MD5: F0E21C7789CD57EEBF8ECDB9FADAB26B) [6] used in the previous posts. Highly recommended to read through the existing analysis of Old Qealler Unloaded[2] by @jeFF0Falltrades & article [3] by Zscaler. Both Qealler variants use the same Qrypter packer variant. ##### 1. AES Key bbb6fec5ebef0d93 You will find multiple references to bbb6fec5ebef0d93 as shown below.  This is the AES key used in both variant. [image: Same AES Key bbb6fec5ebef0d93] _Same AES Key bbb6fec5ebef0d93_ ##### 2. UUID Key 2a898bc98aaf6c96f2054bb1eadc9848eb77633039e9e9ffd833184ce553fe9b Config is stored in a key value pair and key for UUID present in both variants. This key is also present in the Old Qealler Unloaded[2]  article and the same string “Loaded:” is used in both variants. [image: Same UUID key] _Same UUID key_ ##### 3. Systeminfo in JSON format It collects the system info in JSON format before encrypting and sending it to CC.  Both Qealler variants use the same key e.g osName, osVersion, osArch, totalMemory and code structure as shown below.  localIpAddress & globalIpAddress keys are added to the new Qealler version.  [image: Systeminfo in Json format Qealler Pyrogenic] _Systeminfo in JSON format Qealler Pyrogenic_ ##### 4. ShutdownHook It is used when we want to run some code when JVM is shutting down and both variants use the addShutdownHook()  to delete the files. [image: ShutdownHook Qealler] _ShutdownHook_ ##### 5. QeallerV4 string Found this string “obfuscated/META-INF/QeallerV4.kotlin_module” in memory in the new Qealler/Pyrogenic sample. Maybe this is version 4 ? #### Conclusion In this Java malware analysis series we started with static analysis, then moved to Unpacking code using Java agent and in this last part we compared the Qealler variant. These above similarities are the most significant which I can find based on code analysis. I can conclude that the Malware author moved the Credential stealing from Python to Java based code.  Malware authors are experienced coder as they divided the source code in multiple sensible packages and gave proper name to functions, variables and classes. #### References - Tweet by @James_inthe_box – (MD5: 65ab1ef8e9cef5c489d4b01cbb8a2a22) First Old Qealler tweet Aug 2018 - Qealler Unloaded by @jeFF0Falltrades – Sep 2018 - Qealler – a new JAR-based information stealer – Feb 2019 - ANY.RUN – (MD5: 65ab1ef8e9cef5c489d4b01cbb8a2a22) Old Qealler June 2018 - ANY.RUN – (MD5: 8D564A18B902461C19936CCB1F4E2F12) Old Qealler Sep 2018 - ANY.RUN – (MD5: F0E21C7789CD57EEBF8ECDB9FADAB26B) New Qealler/Pyrogenic Nov 2019 --- # Unpacking Pyrogenic/Qealler using Java agent -Part 0x2 URL: https://www.securityinbits.com/malware-analysis/unpacking/unpacking-pyrogenic-qealler-using-java-agent-part-0x2/ Published: 2020-01-17 (updated 2023-07-26) Tags: bytecode-viewer, infostealer, java, java-agent, pyrogenic, qealler We will learn how and when we can use Java agent to quickly unpack the Pyrogenic/Qealler Infostealer. We will learn how and when we can use Java agent to quickly unpack the Pyrogenic Infostealer. In the earlier post Pyrogenic Infostealer static analysis – Part 0x1 we statically analysed the Pyrogenic/Qealler Infostealer but this requires more time and effort.  We will be using the same sample PaymAdviceVend_LLCRep.jar from ANY.RUN (MD5: F0E21C7789CD57EEBF8ECDB9FADAB26B) used in Part 0x1. Let’s start with a basic introduction to Java agent. ##### CONTENTS - Introduction to Java agent - Unpacking using Java agent - Dumped class file analysis - When will it fail? - Conclusion - Targeted Application list - References ### Introduction to Java agent A Java agent is used to instrument programs running on the JVM and it can modify the Java bytecode at runtime without source code. In this post we will be using a Java agent to dump the classes during runtime without any bytecode modification but for more details please check this Java Agents Tutorial [1]. These are the minimum requirement for Java agent to work: - Java agent class file should have a premain method which acts as the entry-point.This method is executed before the real java application main method, premain method it’s like TLS callback. - MANIFEST.MF should be defined with the Premain-Class attribute, which will point to class name with premain method. Another important point is there must be a new line at the end of the MANIFEST file. Otherwise, the last header is ignored. - javaagent parameter should be specified to load java agent jar file with premain method e.g .java -javaagent:dumper.jar -jar malware.jar ### Unpacking using Java agent dumper.java & MANIFEST.mf are used to build Java agent dumper.jar. dumper.java code is copied from Reversing an obfuscated java malware pdf [2]  and I will highly recommend to go through the pdf[2] to understand the different methods which can be used to analyse Java malware. Note: All java, MANIFEST and jar files are uploaded to GitHub repo[3]. dumper.java ``` import java.io.*; import java.lang.instrument.*; import java.security.*; // This code is copied from "Reversing an obfuscated java malware by Extreme Coders" public class dumper { //A java agent must have a premain method which acts as the entry-point public static void premain(String agentArgs, Instrumentation inst) { System.out.println("agent loaded"); // Register out trasnformer inst.addTransformer(new transformer()); } } class transformer implements ClassFileTransformer { // The transform method is called for each non-system class as they are being loaded public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (className != null) { // Skip all system classes if (!className.startsWith("java") && !className.startsWith("sun") && !className.startsWith("javax") && !className.startsWith("com") && !className.startsWith("jdk") && !className.startsWith("org")) { System.out.println("Dumping: " + className); // Replace all separator characters with _ String newName = className.replaceAll("/", "_") + ".class"; try { FileOutputStream fos = new FileOutputStream(newName); fos.write(classfileBuffer); fos.close(); } catch (Exception ex) { System.out.println("Exception while writing: " + newName); } } } // We are not modifying the bytecode in anyway, so return it as-is return classfileBuffer; } } ``` MANIFEST.mf Manifest-Version: 1.0 Premain-Class: dumper Note: If you know the basic of Java or any other object oriented programming language then it will be much easier to understand this dumped unpacked code. - Uploaded the jar file in GitHub repo[3]which is generated using following command: javac dumper.java jar cmf MANIFEST.MF dumper.jar dumper.class transformer.class - Execute this command java -javaagent:dumper.jar -jar BankPaymAdviceVend_LLCRep.jar to run the malware with java agent and it will dump all the accessed classes at runtime to the current working directory. [image: Pyrogenic java agent cmdline] _Pyrogenic java agent cmdline_ [image: Pyrogenic malware classes with comment] _Pyrogenic malware classes with comment_ - Please decompile all the dumped class files which start with q0b4 and j/t/e package name files using ByteCodeViewer FernFlower Java decompiler. One of the easiest way is to zip all classes and then use BCV. Then, import decompiled java source files from BCV into any Java IDE, this will help you in code navigation. - Start from the bottom and go up in the above pic then you will find the first proper package name q0b4/bootstrap/templates/Header which can be our starting point for unpacked code. We are Reverse engineers, we always start in reverse order :). - Below pic shows all the unpacked classes dumped using Java agent dumper.jar. It starts from Header.java which uses a decrypt function to AES decrypt the classes at runtime and invoke the main method. It invokes j.t.e.Main package main method. [image: Dumped Classes List with Header.java] _Dumped Classes List with Header.java_ Other approach is to dump all the classes present in obfuscatedEntryList using for loop and continue analysis ### Dumped class file analysis Malware authors divided the source code in multiple sensible packages. They have made our job easier by giving proper names to functions, variables and classes. We will go through some of the classes Main, Server, MainEx and one util IPAddress class, as it will take too much time to go through each one of them. ##### Main & Server class - Main class invokes the loadLibrary method which sends the cmd to CC using sendCmd method. [image: Pyrogenic Main class with loadLibrary] _Pyrogenic Main class with loadLibrary_ - Server class contains function loadLibrary which is used above and pushCredentials which is used to send the stolen credential to CC. [image: Pyrogenic Server class with functions] _Pyrogenic Server class with functions_ - Server class contain the following list of available library and cmds: public static final int PYTHON = 162144; public static final int SQLITE = 4353152; public static final int JNA = 224288; public static final int JNA_PLATFORM = 3048576; public static final int JNA_4 = 307200; public static final int JNA_PLATFORM_4 = 308224; public static final int BCPROV = 310272; public static final int INI4J = 311296; public static final int XML = 312320; public static final int JSON = 313344; public static final int W3DOM = 314368; public static final int Q4_PASS_LIB = 315392; public static final int JPOWERSHELL = 316416; private static final int LIBRARY_CMD = 16384; private static final int CREDENTIAL_CMD = 32768; private static final byte[] SEED = "uisdfysdgfbsdyufbsiybfsdyb733grfsudbfjh".getBytes(); private static final int MAX_TRY_COUNT = 20; [image: Pyrogenic Server class with cmd] _Pyrogenic Server class with cmd_ Malware author didn’t pack all the required Java libraries in the jar but it is requested when needed at runtime. This significantly decreased the malware size to 153.27 Kb. Let’s discuss some of the library and commands used: - Server JNA, JNA_4, JNA_PLATFORM, JNA_PLATFORM_4 – JNA (Java Native Access ) provides simplified access to native library methods without requiring any additional JNI or native code. For example you can call printf, GetSystemTime Windows API function directly from Java Code. - INI4j – Java API for handling configuration files in Windows .ini format - JPOWERSHELL – Simple Java API that allows programs to interact with PowerShell console. It may be used when malware invokes any PowerShell commands. - Q4_PASS_LIB – May be Qealler v4 Password Library loaded first using list.add(server.loadLibrary(315392)); - LIBRARY_CMD – May be used to load the clean dll used sqlitejdbc.dll and jnidispatch.dll - CREDENTIAL_CMD – This cmd is used to pushCredentials to CC ##### MainEx class - j.t.e.Main main method invokes the j.t.e.MainEx main method as shown above in Main class. It sent credential and system info in JSON format to CC. All the communication are AES encrypted using EncryptedCipherOutputStream and EncryptedCipherInputStream which extends CipherOutputStream & CipherInputStream respectively. [image: Pyrogenic MainEx main method] _Pyrogenic MainEx main method_ - MainEx class contains two important methods: run() and getSysinfo() as shown below. [image: Pyrogenic MainEx credential stealer method] _Pyrogenic MainEx credential stealer method_ - Malware steal credential from list of software mentioned in the run() method ``` this.addAll(ChromiumBased.chromiumBasedBrowsers); this.addAll(MozillaBased.mozillaBasedBrowsers); this.add(new IExplorer()); this.add(new UCBrowser()); this.add(new Composer()); this.add(new Credman()); this.add(new Outlook()); this.add(new Pidgin()); this.add(new PostgreSQL()); this.add(new Squirrel()); this.add(new Tortoise()); ``` - getSysinfo() collect osName, osVersion, osArch, javaHome, userName, userHome, availableProcessor, freeMemory, totalMemory, localIpAddress & globalIpAddress in JSON format which is encrypted and sent to CC with other info. ##### IPAddress class - IPAddress class is one of the classes present in package j.t.e.core.utils which gets the IP address of the infected system and sends it to CC with other system info. It uses http://bot.whatismyipaddress.com for collecting the public IP of infected systems. [image: Pyrogenic IPAddress util class] _Pyrogenic IPAddress util class_   ### When will it fail? Unpacking using Java agent will be unable to dump all the classes at runtime due to following conditions: - When malware is unable to interact with CC then it will not be able to exhibit complete behaviour. - Malware is using some anti analysis technique e.g checking for vmware etc. - Malware is unable to run due to some supporting files, command line etc. ### Conclusion Unpacking using a Java agent is quite simple and can speed up your analysis, you can use the dumper.jar uploaded in Github [3]. This method can be used in any Java based malware. We have also gone through some of the dumped Pyrogenic/Qealler source code to understand the stealer functionality. In the last part 0x3 we find similarity between Qealler/Pyrogenic variants based on static code analysis. ### Targeted Application list This is the list of application collected from the dumped unpacked classes: - ChromiumBased Browser 7Star - amigo - brave - centbrowser - chedot - chrome canary - chromium - coccoc - comodo dragon - elements browser - epic privacy browser - google chrome - kometa - opera - orbitum - sputnik - torch - uran - vivaldi - yandexBrowser - MozillaBased Browser firefox - blackHawk - cyberfox - comodo IceDragon - k-Meleon - icecat - IExplorer - UCBrowser - Composer - Windows Credential - Outlook - Pidgin - PostgreSQL - Squirrel - Tortoise ### References - Java Agents Tutorial - Reversing an obfuscated java malware by Extreme Coders - GitHub repo --- # Qealler Infostealer static analysis – Part 0x1 URL: https://www.securityinbits.com/malware-analysis/pyrogenic-infostealer-static-analysis-part-0x1/ Published: 2020-01-06 (updated 2023-11-23) Tags: bytecode-viewer, infostealer, java, pyrogenic, qealler, t1555-003 Pyrogenic/Qealler is heavily obfuscated Java based Infostealer which is quiet active based on ANY.RUN and this post will focus on Pyrogenic Infostealer static analysis Qealler is heavily obfuscated Java based Infostealer which is quite active based on ANY.RUN submission. This will be a three part blog series, this post will focus on Qealler/Pyrogenic static analysis, next part 0x2 we learn unpacking using Java agent and in the last part 0x3 we find similarity between Qealler/Pyrogenic variants based on static code analysis . You may download the BankPaymAdviceVend_LLCRep.jar from ANY.RUN (MD5: F0E21C7789CD57EEBF8ECDB9FADAB26B) and follow along or download the latest Qealler sample from ANY.RUN submission. ##### CONTENTS - Overview - Quick dynamic analysis - Packed Pyrogenic static analysis - Conclusion - References #### Overview It’s currently targeting different regions e.g. Australian companies[1], Africa and the Middle East[2] based on the references. I will be using Bytecode Viewer to decompile Jar using FernFlower Java Decompiler. Let’s start with quick dynamic analysis. Our main goal for the blog series is to unpack this jar so we can analyse the capability and compare it with Qealler. #### Quick Dynamic Analysis - Connect to CC 157.245.160[.]150 at port 80 and create the below process. cmd.exe /c chcp 1252 > NUL & powershell.exe -ExecutionPolicy Bypass -NoExit -NoProfile -Command - - Drop these two clean files sqlitejdbc.dll (MD5: a4e510d903f05892d77741c5f4d95b5d) and jnidispatch.dll (MD5: d2f0da769204b8c45c207d8f3d8fc37e) but it deletes these two file before exiting. - Connect to bot.whatismyipaddress.com to get the public IP of the infected system. - Steal credential from different applications #### Packed Pyrogenic static analysis - Open the jar file in BCV (Bytecode Viewer), you will see multiple class files in different packages. Below pic shows the main entry point of the jar file. [image: Packed Pyrogenic BCV] _Packed Pyrogenic BCV_ - For this sample, I found out that FernFlower decompiled the source code correctly. Select View -> Pane 1 -> FernFlower -> Java in BCV as shown below. [image: Bytecode Viewer FernFlower selection] _Bytecode Viewer FernFlower selection_ - If you browse the different class files in BCV, you will find many encrypted class files which don’t translate to Java src code. e.g. one of them is shown below [image: Pyrogenic encrypted class] _Pyrogenic encrypted class_ - Based on the above encrypted class file, you can guess that there should be some decryption algorithm used to decrypt those files. - Decryption algorithms can be custom or well known e.g. AES. Study this example java code [3] which encrypt/decrypt using AES. [image: AES Java Encrypt Decrypt Example] _AES Java Encrypt Decrypt Example_ Some of the keyword mentioned in the above java code e.g. getInstance can help us to find the encryption algorithm and doFinal can point to final decryption result. - Let’s search for AES references after importing the decompiled src code to Eclipse IDE. [image: Pyrogenic AES references] _Pyrogenic AES references_ [image: Pyrogenic doFinal reference] _Pyrogenic doFinal reference_ [image: Pyrogenic PBKDF2WithHmacSHA1 reference] _Pyrogenic PBKDF2WithHmacSHA1 reference_ - Based on the above images which shows multiple references, we can confirm that this sample uses the algo “AES/ECB/PKCS5Padding” and key may be generated using “PBKDF2WithHmacSHA1” . So it confirmed that it doesn’t use any custom decryption algorithm. - We can add our code to write the data to file after doFinal call and execute the sample in IDE to get the dumped class file Then we can decompile the class file using BCV and continue analysis. But it can be multiple layer obfuscation which can make our analysis harder and slower. #### Conclusion This above static analysis method to find the encryption routine and interesting breakpoint (doFinal) while debugging is very useful in Java Malware analysis. Using this approach you will not miss any code path but this requires more time and effort. So in the upcoming part 0x2 , we will unpack this malware using Java agent which will speed up our analysis. #### References - NEW PYROGENIC JAR-BASED MALWARE CAMPAIGN - Pyrogenic – The JAR-Based Malware Spreading Across Africa and the Middle East - Java AES Encryption Decryption Example --- # Parent PID Spoofing (Stage 2) Ataware Ransomware – Part 0x3 URL: https://www.securityinbits.com/malware-analysis/parent-pid-spoofing-stage-2-ataware-ransomware-part-3/ Published: 2019-05-14 (updated 2023-07-26) Tags: ataware, ghidra, pe, ransomware, strings, sysmon Ataware Ransomware Stage 2 uses Parent PID Spoofing technique to change it parent PID to lsass.exe and download the final Ataware Ransomware. Ataware Ransomware Stage 2 uses Parent PID Spoofing technique to change its parent PID to lsass.exe and this article is also referred to in Mitre Attack website [4]. You may download the ATAPIConfiguration.exe file from ANY.RUN (MD5: 04a2e6400b22a3a5e5e277eceaf2ce0c) Please check previous posts, if you are interested in the complete infection chain Excel 4.0 Macro Analysis – Ataware Ransomware Part 1 & UAC bypass analysis (Stage 1) Ataware Ransomware Part 2. [image: Ataware Ransomware Overview] _Ataware Ransomware Overview_ #### Overview of ATAPIConfiguration.exe (Stage 2) Stage 2 downloads the final Ataware Ransomware (ATAPIUpdtr.exe) from CC which can encrypt files. Then, it uses Parent PID Spoofing to change the parent PID to lsass.exe before executing it. ##### CONTENTS - Static Analysis - Parent PID Spoofing - Analysis steps in Ghidra - Conclusion - References #### Static Analysis - 32bit PE, compiled using GCC MINGW - Nothing interesting in overlay, no resources - Compiler timestamp invalid is 1997 - File contain TLS callback but nothing interesting [image: ExeInfo & Strings tool] _ExeInfo & Strings tool_ ##### Strings Based on the strings berylia[.]net and /index/, we can guess that malware may be downloading something. wininet.dll InternetConnectW berylia.net HttpOpenRequestW /index/ GET InternetQueryOptionW InternetSetOptionW HttpSendRequestA TEMP kernel32.dll CreateFileW InternetReadFile WriteFile InternetCloseHandle Advapi32.dll LookupPrivilegeValueW AdjustTokenPrivileges OpenThreadToken ImpersonateSelf SeDebugPrivilege CreateToolhelp32Snapshot Process32FirstW Process32NextW lsass.exe OpenProcess InitializeProcThreadAttributeList UpdateProcThreadAttribute CreateProcessA #### Parent PID Spoofing Stage 2 mainly uses InitializeProcThreadAttributeList, UpdateProcThreadAttribute & CreateProcessA with STARTUPINFOEXA structure API for spoofing. Didier Stevens already blogged about this in 2009 [1], “Normally the parent process of a new process is the process that created the new process (via CreateProcess). But when using STARTUPINFOEX with the right LPPROC_THREAD_ATTRIBUTE_LIST to create a process, you can arbitrarily specify the parent process, provided you have the debug rights.” Before spoofing, this Stage 2 enables SeDebugPrivilege of current thread. UpdateProcThreadAttribute function[2] is called with PROC_THREAD_ATTRIBUTE_PARENT_PROCESS (0x00020000) attribute with the handle of lsass.exe. At last, CreateProcessA is called with STARTUPINFOEXA Structure which contain new StartupInfoEx.lpAttributeList and creation flag 0x80010 (EXTENDED_STARTUPINFO_PRESENT | CREATE_NEW_CONSOLE) for creating new process with different Parent PID. [image: Parent PID Spoofing final code in Ghidra] _Parent PID Spoofing final code_ #### Analysis steps in Ghidra 1. Navigate to entry function, then to WinMain address @ 0x4013dd as shown below [image: Before any comment Main function Ghidra] _Before any comment Main function_ 2. We will concentrate on download_spoof_parent_process_exe (0x40208b) in main function as shown below [image: Main function in Ghidra] _Main function in Ghidra_ 3. Before any rename/comment @ 0x401cb7 [image: Before Parent PID Spoofing function in Ghidra] _Before Parent PID Spoofing function_ 4. This function contains two main functions FUN_00401b91() & FUN_00401579(). 5. Let’s focus on FUN_00401b91 (adjust_priv_current_thread_sedebug), this function enables SeDebugPrivilege of current thread. [image: Adjust privilege of current thread Ghidra] _Adjust privilege of current thread_ [image: Enable SeDebugPrivilege using AdjustTokenPrivileges] _Enable SeDebugPrivilege using AdjustTokenPrivileges_ Tip: LookupPrivilegeValueW & AdjustTokenPrivileges API are very common in malware when they want to enable SeDebugPrivilege privilege. For details, please check this msdn [3]. 6. FUN_00401579()/download_save_ATAPIUpdtr_exe function download the file from CC hxxps://berylia[.]net/index/ and save it to $temp directory as ATAPIUpdtr.exe. [image: Download and save ATAPIUpdtr.exe] _Download and save ATAPIUpdtr.exe - Using https, send GET request to CC_ 7. Parent PID Spoofing is shown below in the final code download_spoof_parent_process_exe. [image: Parent PID Spoofing final code in Ghidra] _Parent PID Spoofing final code_ #### Dynamic Analysis using Sysmon File Create event Sysmon [image: Sysmon File Create for ATAPIUpdtr.exe] _Sysmon File Create for ATAPIUpdtr.exe_ Here you can see Process Create with spoofing in action with Parent Image lsass.exe. [image: Parent PID Spoofing Sysmon] _Parent PID Spoofing Sysmon_ #### Conclusion - Analysed Parent PID Spoofing and saw this in action using Sysmon - Malware uses this technique to evade detection which is based on parent-child process - We understood how malware author can enable SeDebugPrivilege #### References - SelectMyParent or Playing With the Windows Process Tree - UpdateProcThreadAttribute function - Enabling and Disabling Privileges in C++ - Access Token Manipulation: Parent PID Spoofing --- # UAC bypass analysis (Stage 1) Ataware Ransomware – Part 0x2 URL: https://www.securityinbits.com/malware-analysis/uac-bypass-analysis-stage-1-ataware-ransomware-part-2/ Published: 2019-05-07 (updated 2023-07-26) Tags: ataware, cmstp, ghidra, pe, ransomware, strings, sysmon, t1548-002, t1218-003, t1218 Ataware Ransomware uses UAC bypass using CMSTPLUA COM interface in ATAPIinit.exe (Stage 1). It was downloaded from Dropbox url when user open the malicious Excel. Ataware Ransomware uses UAC bypass using CMSTPLUA COM interface in ATAPIinit.exe (Stage 1). It was downloaded from Dropbox url when the user opened the malicious Excel and enabled the Macro. For details, please check the previous Excel 4.0 Macro Analysis – Ataware Ransomware Part 1. You may download the ATAPIinit.exe file from ANY.RUN (Md5: 097cc44444c6733bc6b32cb1c4c87ddd). [image: Ataware Ransomware Overview] _Ataware Ransomware Overview_ #### Overview of ATAPIinit.exe (Stage1) The main purpose is to UAC bypass using CMSTPLUA COM interface and download another binary ATAPIConfiguration.exe (Stage 2) from dropbox url. Then, it executes the downloaded file. #### Static Analysis - 32bit PE, Compiled using GCC MINGW - Nothing interesting in overlay, no resources - Compiler timestamp invalid is 1970 - File contain TLS callback but nothing interesting [image: UAC bypass] _Exeinfo & Strings tool_ ##### Strings Found some interesting strings, if you google “{3E5FC7F9-9A51-4367-9063-A120244FBEC7}” you will find multiple links related to UAC bypass. So, you can guess that malware may be bypassing UAC and downloading something from dropbox. We will check this in detail later using Ghidra. CLSIDFromString IIDFromString {3E5FC7F9-9A51-4367-9063-A120244FBEC7} {6EDD6D74-C007-4E75-B76A-E5740995E24C} Elevation:Administrator!new: CoGetObject wininet.dll InternetOpenW WINDOWS wininet.dll InternetConnectW dl.dropboxusercontent.com HttpOpenRequestW /s/uzu60whrg1spnyy/ATAPIConfiguration GET InternetQueryOptionW InternetSetOptionW HttpSendRequestA TEMP ##### Ghidra Setup Import Windows API Ghidra Data Type Archives (winapi_32.gdt) in Data Type manager from github. For more details, check this Youtube Video. Retype Variable will be used frequently to fix decompiled code, so please check this short video. ##### Analysis steps in Ghidra After initial Static analysis, we can open this in IDA or Ghidra, whichever you prefer. I will be using Ghidra for this series. 1. Navigate to entry function, then to WinMain address @0x004013dd as shown below _Navigate to WinMain - Navigate to WinMain 0x004013dd_ 2. We will concentrate on uac_bypass_download_execute (0x40151c) as shown below _WinMain Decompiled Code_ 3. Start analysing below function @ 0x004017e4 [image: Before any Comment UAC bypass] _Before any comment/Retype - uac_bypass_download_execute function_ 4. After we rename/retype variable/comment this function looks as shown below. [image: UAC bypass] _UAC bypass - uac_bypass_download_execute function_ Let’s see what’s going on here, bypassing the UAC using CMSTPLUA COM interface and using The COM Elevation Moniker [4]. Using CoGetObject and CMLuaUtil->lpVtbl->ShellExec to execute the downloaded file. Malware author may have copied this GitHub gist [1] and used this to bypass UAC. I will recommend to look up all the API in MSDN which are used in GitHub gist [1]. This will help in understanding the code better. CLSIDFromString_addr = (CLSIDFromString *)GetProcAddress(hModule,"CLSIDFromString"); hModule = GetModuleHandleW(L"Ole32.dll"); IIDFromString_addr = (IIDFromString *)GetProcAddress(hModule,"IIDFromString"); /* CLSID of CMSTPLUA Çom object */ HVar1 = (*CLSIDFromString_addr)(L"{3E5FC7F9-9A51-4367-9063-A120244FBEC7}",(LPCLSID)&local_4c); if ((HVar1 == 0) && (HVar1 = (*IIDFromString_addr)(L"{6EDD6D74-C007-4E75-B76A-E5740995E24C}",(LPIID)&local_3c), HVar1 == 0 /* Interface ID of ICMLuaUtil */)) { RtlSecureZeroMemory(elevate_string,0x208); wcscpy(elevate_string,L"Elevation:Administrator!new:"); wcscat(elevate_string,L"{3E5FC7F9-9A51-4367-9063-A120244FBEC7}"); RtlSecureZeroMemory(&local_74,0x24); local_74.cbStruct = 0x24; local_60 = 4; hModule = GetModuleHandleW(L"Ole32.dll"); CoGetObject_addr = (CoGetObject *)GetProcAddress(hModule,"CoGetObject"); (*CoGetObject_addr)(elevate_string,&local_74,&local_3c,&local_50); /* file_path points to %temp%ATAPIConfiguration.exe */ download_save_ATAPIConfiguration_exe(); /* execute downloaded file using COM interface which bypass UAC */ (**(code **)(*local_50 + 0x24))(local_50,file_path,0,0,0,5); 5. Analysing below function @ 0x00401a0f [image: Before any comment/Retype] _Before any comment/Retype - download_save_ATAPIConfiguration_exe function_ 6. After we rename/retype variable/comment, this is how functions look as shown below. [image: UAC bypass & Download code in Ghidra] _UAC bypass & Download code in Ghidra_ This function download_save_ATAPIConfiguration_exe download the file from hxxps://dl[.]dropboxusercontent[.]com/s/uzu60whrg1spnyy/ATAPIConfiguration and save it to $temp directory as ATAPIConfiguration.exe. If you see the following API in the function then you can guess it download and save file. InternetOpenW InternetConnectW HttpOpenRequestW HttpSendRequestA InternetReadFile CreateFileW WriteFile We have statically analysed uac_bypass_download_execute (@ 0x004017e4) and download_save_ATAPIConfiguration_exe (@ 0x00401a0f) in Ghidra. #### Dynamic Analysis Before executing, setup Sysmon logging and enable UAC in VM. After executing you can see the below ProcessCreate event with Integrity level medium as it is executed with UAC. [image: Process create event using Sysmon] _Process create event using Sysmon - Integrity Level - Medium (UAC enabled)_ Then you can see another ProcessCreate of DllHost.exe CommandLine: C:WINDOWSSysWOW64DllHost.exe /Processid:{3E5FC7F9-9A51-4367-9063-A120244FBEC7} with CMSTPLUA CLSID. [image: UAC Bypass event using Sysmon] _UAC Bypass event using Sysmon - Integrity Level - High (UAC Bypass)_ #### Detection This CommandLine: C:WINDOWSSysWOW64DllHost.exe /Processid:{3E5FC7F9-9A51-4367-9063-A120244FBEC7} with the CLSID can be used to detect UAC bypass in our environment [2] [3]. #### Conclusion - Analysed one of the technique which malware author uses for UAC bypass - We can guess with high probability that malware author stole this code from gist [1] - Other malware like Trickbot uses the same technique [5] Upcoming part 0x3 we will analyse the ATAPIConfiguration.exe (Stage 2) which uses Parent PID Spoofing. #### References - GitHub gist for UAC bypass using CMSTPLUA COM interface - Method 3 – UAC Bypass via Direct Utilization of COM Interfaces - CMSTP MITRE T1191 - The COM Elevation Moniker - Trickbot uses the same technique --- # Excel 4.0 Macro, hta, VBScript & PowerShell Analysis Ataware Ransomware – Part 0x1 URL: https://www.securityinbits.com/malware-analysis/excel-4-0-macro-hta-vbscript-powershell-analysis-ataware-ransomware-part-1/ Published: 2019-04-30 (updated 2023-07-26) Tags: ataware, deobfuscation, hta, macro-analysis, powershell, ransomware, t1059-001, t1218-005, vbscript, xls Excel 4.0 Macro technique with mshta and PowerShell. This will be blog series analysing complete infection chain from Excel to Ataware Ransomware This will be a multiple part blog series analysing the complete infection chain from Excel to Ataware Ransomware. In this post we will discuss analysis steps for hta, VBScript & PowerShell code to extract the final payload url. Let’s start with xls, I was browsing Twitter for an interesting sample, then I found this tweet from @nao_sec and started investigating. You can download the xls from ANY.RUN. [image: nao_sec Tweet] _nao_sec Tweet_ #### Overview of analysis steps _Ataware Infection Vector - Overview of analysis steps_ #### xls analysis steps - Check the file type and extract the string strings "563902-IT Services Procurement Catalog updated.xls" > str_excel.txt [image: file and strings on xls] _file and strings on xls_ - Go through the strings output and you will find the mshta cmd with Dropbox url _mshta string - Output from string cmd_ - Now you know, this excel is definitely malicious by using only string tool - Let’s analyse it further to understand how this mshta is invoked - Run olevba on xls, as you can see in the output below it uses Excel 4.0 macro hidden sheet to execute mshta cmd. _Olevba tool - Detecting Excel 4.0 Macro_ For more details on Excel 4.0 Macro, check the references section[1]. Now we will move on the hta file analysis. #### htseelaaa.hta analysis _Content of hta file_ ##### Why are attacker using hta? HTAs are standalone applications that execute using the same models and technologies of Internet Explorer, but outside of the browser [2]. hta file can be executed using inbuilt trusted Windows utility mshta which can bypass Application Whitelisting. ##### Deobfuscate Steps - Extract the vbs code from hta file and save as vbs - Replace the eval with Wscript.Echo and execute using cscript _Execute cscript - Replace Eval with Wscript.Echo and run using cscript_ - Now you can see the base64 encoded PowerShell code, instead of manual deobfuscation let’s run the PowerShell code inside our VM with FakeNet-NG _Execute PowerShell - Execute PowerShell code extracted from VBScript_ - Enable PowerShell Enhanced Logging before running above PowerShell code, for more details check this Deobfuscate PowerShell using PowerShell Logging - After executing, go through PowerShell logs in EventViewer to find out the debofuscate code as shown below _Decoded PowerShell - Decoded PowerShell in PowerShell Logs_ - Copy the PowerShell code after removing iex and execute it to see the final decoded code shown below _Final Decoded PS_ - This PowerShell download the PE file from the dropbox link and executes it in the $temp directory with filename ATAPIinit.exe. #### Conclusion - Infection vector is unique as it is using Excel 4.0 Macro technique with mshta and PowerShell. - Heavily obfuscated to slow down analysis - Using dropbox as initial payload delivery, as dropbox may be allowed in proxy Upcoming part 0x2 we will analyse the UAC bypass using CMSTPLUA COM interface technique used by PE file downloaded from PowerShell. #### References - XLM Excel 4.0 Macro Details - Mshta technique --- # Deobfuscate PowerShell using PowerShell Logging URL: https://www.securityinbits.com/malware-analysis/deobfuscate-powershell-using-powershell-logging/ Published: 2019-04-20 (updated 2023-08-14) Tags: deobfuscation, emotet, powershell, qakbot Analyze/Deobfuscate malicious PowerShell faster by enabling PowerShell Enhanced logging. Example scenario Using Emotet & Qbot We will use inbuilt PowerShell Logging in Windows 10 VM to deobfuscate PowerShell code used to deliver Emotet & Qakbot. Malware uses PowerShell mostly to download payload from CC and execute it. #### Why do we need to do this? - Easy technique to deobfuscate PowerShell without using any external tool - Extract CC from PowerShell #### Sample - Qakbot: Download hta file (Md5: 9ce2f8566be903e4bd9159b1b06900f4) used by Qakbot from ANY.RUN. - Emotet: Download Emotet downloader sample from zip archive 2018-05-04-Emotet-malware.zip / Virustotal #### Enable PowerShell Logging Windows 10 VM doesn’t require any software updates to support enhanced PowerShell logging. But if you still want to configure Windows 7 VM, please check the FireEye article Greater Visibility Through PowerShell Logging. 1. Open Local Group Policy editor and navigate to Computer Configuration -> Administrative Templates -> Windows Components -> Windows PowerShell [image: Initial PowerShell Logging Setting] _Initial PowerShell Logging Setting_ 2. Enable the following three options shown below. Enter * in Module Names for Module logging. [image: PowerShell Group Policy Setting] _PowerShell Group Policy Setting_ Tip: Enter gpedit.msc in Run to open Local Group policy and eventvwr.msc for Event Viewer #### Steps - Open Event Viewer and navigate to Windows Logs -> Application and Service Logs -> Windows PowerShell, right click and clear the existing logs - Execute the malware and wait for some time 30-60 sec. - Open ProcessHacker and check for termination of PowerShell process. - Open EventViewer and navigate to Windows PowerShell log and check the entries, you will see some deobfuscated PowerShell - Analyze PowerShell if needed to extract CC info #### Example of Emotet & Qakbot ##### Qakbot - hta file contain Obfuscated VBScript code [image: Initial Obfuscated hta] _Initial Obfuscated hta - Initial Obfuscated hta file which contain VBScript_ - Deobfuscate VBScript by replacing ]+($)#!%/=[?-_&*<> with ” and you can see obfuscated PowerShell. [image: Initial Obfuscate PowerShell] _Initial Obfuscate PowerShell - Initial Obfuscate PowerShell_ - But we don’t need to do above step, we can just run the hta file and see more clearer PowerShell code shown below. [image: Qakbot PowerShell Deobfuscation] _Qakbot PowerShell Deobfuscation - 2nd level deobfuscated code is much better as you can see the CC_ - Extract CC by executing below PowerShell code _Qakbot CC - Execute PowerShell Code to extract CC_ ##### Emotet [image: Obfuscated Emotet PoweShell cmd] _Obfuscated Emotet PoweShell cmd - Contain PowerShell cmd extracted from Emotet doc_ [image: Emotet_Powershell 1st] _Emotet Powershell 1st Entry_ [image: Emotet Deobfuscated Powershell] _Emotet Deobfuscated Powershell - Check the highlighted Deobfuscated Code_ --- # Deobfuscate Emotet PowerShell – Part 0x2 URL: https://www.securityinbits.com/malware-analysis/deobfuscate-emotet-powershell/ Published: 2018-05-26 (updated 2023-07-26) Tags: deobfuscation, downloader, emotet, powershell, video-tutorial Deobfuscate and extract CC from the PowerShell cmd extracted from the Emotet downloader. We will deobfuscate PowerShell and extract CC from the PowerShell cmd extracted from the Emotet downloader macro discussed in the previous article. If you want to learn how to deobfuscate and analyse the malicious macro code, please check this article and video. #### Video Tutorial Let see how to use this above concepts to deobfuscate the PowerShell #### Why do we need to do this? - Extract CC info from Obfuscated PowerShell - Clean up the code, so we can analyse the Powershell easily #### Sample You can download the Emotet downloader sample from zip archive 2018-05-04-Emotet-malware.zip mentioned in this link / Virustotal #### Important PowerShell concepts We will look into some of the techniques and functions used in this Emotet doc. [image: Obfuscated Emotet PoweShell cmd] ##### Variable You can create a new variable on the fly simply by assigning a value to it: $url = 'https://twitter.com/Securityinbits' ##### Download File This cmd is used in this macro to download Emotet sample from CC. (New-Object System.Net.WebClient).DownloadFile($url, $output) e.g. $url = "http://httpbin.org/image/jpeg" (New-Object System.Net.WebClient).DownloadFile($url, "C:image.jpeg") ##### Invoke-Item This cmd is used to start the exe downloaded from Emotet CC. The Invoke-Item cmdlet performs the default action on the specified item. For example, it runs an executable file or opens a document file in the application associated with the document file type. The default action depends on the type of item and is determined by the Windows PowerShell provider that provides access to the data. For more details check this link. PS C:> Invoke-Item "C:Windowssystem32calc.exe" ##### Invoke-Expression (or iex) This iex is used to invoke the malicious PowerShell cmd. iex is an alias for Invoke-Expression. Runs commands or expressions on the local computer. For more details check this link. PS C:> $Command = "Get-Process" PS C:> $Command Get-Process PS C:> iex $Command Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 296 4 1572 1956 20 0.53 1348 AdtAgent 270 6 1328 800 34 0.06 2396 alg 67 2 620 484 20 0.22 716 ati2evxx 1060 15 12904 11840 74 11.48 892 CcmExec 1400 33 25280 37544 223 38.44 2564 communicator ... #### Some obfuscation technique These are some of the techniques used in Emotet PowerShell to obfuscate the code to make the analysis difficult. - ` or ^ (escape character) used in front of a character with no change in the result when starting PowerShell from cmd.exe. $YYU."Do`Wnl`OadFI`le"($asfc."ToStr`i`Ng"(), $SDC); - iex alias is used to invoke the PowerShell command. ( $env:comSpeC[4,26,25]-JoIn'') --> iex - Strings are concatenate using ‘+’ to reduce readability '6 http'+':'+'//'+'a'+'lian'+'.'+'d'+'e'+'/'+'4wBY'+'ki/@' - Strings encoded with ascii e.g [chaR]34 –> “ - Replacing garbage character -repLACE '0mI',[chaR]96 #### After Deobfuscation [image: Deobfuscated PowerShell] #### CC hxxp://alian[.]de/4wBYki/ hxxp://againstperfection[.]net/6kWq0/ hxxp://globalreachadvertising[.]com/zfFgSQ/ hxxp://www[.]fanoff[.]com/ZVljVr/ hxxp://thurtell[.]com/TCyk/ --- # Deobfuscate malicious macro – Part 0x1 URL: https://www.securityinbits.com/malware-analysis/deobfuscate-malicious-macro/ Published: 2018-05-20 (updated 2023-07-26) Tags: deobfuscation, doc, downloader, emotet, macro-analysis, video-tutorial We will concentrate on malicious macro embedded in Emotet downloader office document and see how to deobfuscate the macro code. We will concentrate on malicious macro embedded in Emotet downloader office documents and see how to deobfuscate the macro code. In the next post we will deobfuscate the PowerShell executed by Word Doc. #### Why do we need to do this? - Malicious code embedded in macro instead of exploit - Clean up the code, so we can analyse the macro easily #### Sample You can download the Emotet downloader sample from zip archive 2018-05-04-Emotet-malware.zip mentioned in this link / Virustotal. #### Important Macro concepts Macros are written in VBScript commands. The steps to show the developer tab varies based on the Office version, check this link for more details. Tip: You can use Alt + F11 keyboard shortcut to open Visual basic Editor ##### Sub Procedure A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements that performs actions but doesn’t return a value. For more details check this msdn link. This following procedure contains junk code which is not used anywhere. Sub jpiWVs(tssPw) twzSX = 89948 * CByte(bcDtOn) wvGHf = Int(92496) - Oct(30921 - 82308 * TYNLPB) YCFNn = 98570 * CByte(NSkFX) End Sub Tip: Just search the function/variable name in VB project to check if this in junk code ##### Function A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but a function can also return a value. For more details check this msdn link. Function nFODYizhYv() On Error Resume Next HaPTn = 36440 * CByte(cGdhi) AqKKP = Int(78184) - Oct(38288 - 29334 * FjYvSt) GJKXZG = 1995 * CByte(GZUcj) ...... MUtvc = 12179 * CByte(GKtld) JLfpah = Int(41681) - Oct(37691 - 32289 * NGzQXX) LPHts = 34930 * CByte(wKlPaU) End Function ##### On Error Resume Next It means that whenever there is any error in the program then continue to the next line. Due to this statement malware authors can write junk statements to obfuscate code to make our(or security product) analysis difficult . ##### Autoopen One of the important functions used in the malicious macro is Autoopen(). This function execute when we open a document, so malware execution starts from the function. Autopen function present in this word doc Sub Autoopen() On Error Resume Next bfBwfX = 82635 * CByte(XGMXEm) mVfwi = Int(47288) - Oct(94569 - 38523 * LlJCD) CMjPum = 57434 * CByte(iWvcC) TiOoQjQV (tCXUs + nFODYizhYv + KsQPV) ... End Sub ##### Debug.Print We can print any value of variable by adding Debug.Print variable_name, it will display the output in View-> Immediate Window (Ctrl+G) ##### Shell Shell function is used to run any code, for more details check this link msdn link. This function is used to execute the malicious power shell cmd to download and execute Emotet malware. [Shell] ZHBuq + Chr(vbKeyC) + qFkOSjfj + qjXrchNTBZRhNs + sEPXQbb, ciXcjw + 0 + ciXcjw ##### Mid MID function extracts a substring from a string (starting at any position). For more details check this link. #### Deobfuscation This macro is heavily obfuscated with junk code and random variable/function name. For deobfuscation we just need to check if the variable/function is used in the program. This macro uses the StrReverse and Mid function on different strings to build the malicious PowerShell code. [image: Before and after Macro Deobfuscation] #### Video Tutorial Let’s see how to use the above concepts to deobfuscate the macro. In this post we will not concentrate on the PowerShell part, we will just deobfuscate the macro. Check this article which explain how to deobfuscate and extract CC In the next post we will concentrate on the deobfuscation of PowerShell. --- # Important Wireshark filters URL: https://www.securityinbits.com/tools/wireshark-filters/ Published: 2018-05-05 (updated 2023-07-26) Tags: filter, video-tutorial, wireshark We will look into some of the Wireshark display filters which can be used in malware analysis. We will look into some of the Wireshark display filters which can be used in malware analysis. We can use this Wireshark display filter after we capture pcap during dynamic malware analysis. #### Why do we need to do this? - Help us to remove the noise from pcap - Easy to extract IoC (e.g Domain, IP etc) from pcap - Understanding of network behaviour during dynamic malware analysis #### Wireshark display columns setup But before proceeding, I will highly recommend you to follow these two tutorials to modify the column setting of Wireshark, it will make the analysis much easier and efficient. - Changing the column display in Wireshark - Adding HTTPS server names to the column display in Wireshark #### Wireshark display filters Display filterComments !(ssdp or udp)This not filter can be used when you want to filter any noise from specific protocol dns or httpIt will show all the packets with protocol dns or http. It can be used as starting point in analysis for checking any suspicious dns request or http to identify any CC. ip.addr == 192.168.0.1 same as ip.src == 192.168.0.1 or ip.dst == 192.168.0.1Matches against both the IP source and destination addresses in the IP header. It can be used to filter when you know ip address of CC/victim machine. http.requestDisplay all types of http request e.g GET, POST etc. This can be also good starting point to check if malware is sending any http request to CC. http contains "Mozilla/5.0"Search for the string in http protocol. It is very useful if you are looking for specific strings. http contains 6d:73:77:6f:72:64You can also search using hex instead of ascii strings. 6d:73:77:6f:72:64 == msword http.file_data matches "^MZ"Match the given case-insensitive Perl-compatible regular expression(PCRE) with file_data. It can be used to match any file type magic bytes which is present in http filedata. ssl.handshake.type == 1Matches ssl client hello type request. Good for extracting CC for malware using SSL. tcp.port == 1300 same as tcp.dstport == 1300 or tcp.srcport == 1300Matches source or destination port for tcp protocol. It's useful when malware uses custom port for communication to CC e.g Darkcomet. tcp.port == 1300 and tcp.flags == 0x2Filter based on port and SYN flag in tcp packet. It useful to remove the noise and extract CC. Note: When you enter invalid filter in Wireshark then the colour will change to red. #### Download pcap I will highly recommend downloading the infection traffic pcap from this link and practicing different display filters. After going through the pcap, I was able to create the following display filter which shows all valid IoCs and remove the noise from pcap. http.request or dns.qry.name matches "(hopto|ddns)" or ssl.handshake.type == 1 or (tcp.flags == 0x2 and not tcp.dstport in {443 80}) #### References - https://www.wireshark.org/docs/man-pages/wireshark-filter.html - https://wiki.wireshark.org/DisplayFilters - https://www.malware-traffic-analysis.net/index.html --- # Extract strings URL: https://www.securityinbits.com/malware-analysis/extract-strings/ Published: 2018-04-29 (updated 2023-07-26) Tags: pe, rokrat, strings Extracting strings is important step in malware anlaysis. We will learn how we can extract/interpret strings from malware. Extracting strings is an important step in malware analysis. In this post we will concentrate on static analysis and learn how we can extract/interpret strings from malware. You can download Rokrat (MD5: b441d9a75c60b222e3c9fd50c0d14c5b) from VirusTotal / VirusBay / ANY.RUN. #### Why do we need to do this? - Guess the malware functionality based on the strings. - If we google some of the strings, we may find some related articles/hashes online. - Guess file type, compiler info, packer etc. #### Tools - Windows: Sysinternals Strings - Linux: Install binutils e.g. sudo apt install binutils for GNU strings utility - macOS: Inbuilt strings tool doesn’t cover the Unicode strings, it only extract the ASCII strings so we need to install GNU strings using brew install binutils #### How to extract? For Linux/macOS, if you use GNU strings then use following command and default minimum length is 4 strings -a malware.exe. --> ASCII strings strings -a -el malware.exe --> Unicode Strings For Windows, I use strings from Sysinternals and default minimum length is 3 strings malware.exe --> ASCII and Unicode strings Sysinternals Strings tool search for ASCII and Unicode strings in binary images.After you execute the tool without any parameter it will show you different options. [image: Sysinternal strings help] When strings is executed without any option it will extract Unicode and ascii strings with default string length of 3. ##### Steps - strings > output.txt - Open output.txt in your favourite editor #### Packed Dummy Rokrat strings strings -nobanner rokrat_dummy.sample > packed_strings.txt [image: Packed Rokrat strings] Note: If you feel there is a lot of noise generated then you can change the minimum length to 6 using cmd mentioned below. But you may lose some important strings. strings -nobanner -n 6 rokrat_dummy.sample > packed_strings.txt It generated around 5014 strings, please go through the strings output(i.e. packed_strings.txt) before reading further and try to guess the usage. ###### Some observations from extracted strings StringsComments .text `.rdata @.data .rsrc @.relocSection names An application has made an attempt to load the C runtime library incorrectly. Please contact the application's support team for more information. R6033 - Attempt to use MSIL code from this assembly during native code initialization Strings related to library code >@| 3@| K@| &@| #@} Some of the strings are not useful, you can ignore them GetTempPathW VirtualAllocEx LockResource WriteProcessMemoryAPI name ###### Few important strings StringsGuess (or comments) cmd.exeMaybe it is using cmd.exe to execute some program? Maybe looking for this process name? d:\HighSchool\version 13\2ndBD\T+M\T+M\Result\DocPrint.pdb PDB Path: After googling, you may find related samples/articles PST PDT photo.jpg Exif Adobe Photoshop CC 2017 (Windows) 2017:09:29 23:17:46 Adobe Photoshop CC 2017 photo.jpg file embedded in the file? Made by Adobe photoshop CC ? 2017:09:29 23:17:46 May be creation date? #### Unpacked Rokrat strings I have unpacked the b441d9a75c60b222e3c9fd50c0d14c5b sample and extracted the unpacked strings with minimum length 6. strings -nobanner -n 6 unpacked_rokrat.sample > rokrat_unpacked_strings.txt ###### Few important strings StringsGuess (or comments) https://api.box.com/oauth2/token https://account.box.com/api/oauth2/authorize https://cloud-api.yandex.net/v1/disk/resources?path=%s&permanently=%s ...Used as CC? System manufacturer (Other) (Unknown) (Desktop) (Low Profile Desktop) (Mini Tower) .... Collecting systeminfo and sending this info to CC ? SbieDll.dll api_log.dll C:\Program Files\VMware\VMware Tools\vmtoolsd.exe .....Anti-analysis techniques #### What to look for? - Domain names/IP address(or CC) - Registry keys - Network request pattern - PDB path - Directory/File path or name - List of application names e.g Chrome, Firefox, Skype, FTP application etc. - Malware analysis tools - Any other unique strings #### When will it fail? - File is packed - Strings are encrypted/encoded - Maybe the file is just a downloader and CC are encrypted? - Many others…..