Leveraging DNS Logs for Endpoint Defense
local graph
Chapter 7 — Leveraging DNS Logs for Endpoint Defense
Section titled “Chapter 7 — Leveraging DNS Logs for Endpoint Defense”If I had to choose only a single point of focus for cyber visibility and cyber defense, I would, without a doubt, choose the Domain Name System (DNS) protocol. DNS is a basic protocol, but one of the most important of all computer science and network technologies. DNS logs play a pivotal role in fortifying cybersecurity defenses by serving as a critical intelligence source to detect and thwart malicious activities. As the fundamental translator between user-friendly domain names and machine-readable IP addresses, DNS is an indispensable component of internet communication. Analyzing DNS logs provides a granular view of network traffic, enabling the identification of anomalous patterns and suspicious domain resolutions. This invaluable insight allows cybersecurity professionals to uncover signs of malware infections, Command-and-Control (C2) communications, and other nefarious activities. By scrutinizing DNS logs, organizations can proactively detect and block malicious domains, preventing cyber threats such as phishing attacks, ransomware, and data exfiltration. The real-time visibility offered by DNS logs empowers security teams to respond swiftly, mitigating potential damage and bolstering the overall resilience of their network infrastructure. In essence, leveraging DNS logs is a proactive and indispensable measure in the ongoing battle against cyber threats.
Before starting the chapter, I would like to clarify a misconception related to DNS log analysis. You cannot protect your inbound traffic with DNS logs, but you can protect outbound traffic from hackers, which is an important part of the exfiltrated data. I know this sentence will sound unusual, but if you can control your outbound traffic, being hacked or infected is not a problem. In this chapter, we will discuss the following:
- DNS protocol and enrichment
- DNS firewall
- Domain categorization
- Domains without an IP address
- Detecting DNS tunneling
DNS protocol and enrichment
Section titled “DNS protocol and enrichment”DNS is a critical protocol that translates human-readable domain names into machine-readable IP addresses, facilitating the seamless communication of devices on the internet. A DNS transaction involves a series of steps, and the data is encapsulated in DNS packets. In Figure 7*.1*, you can see a diagrammatic representation of the DNS structure:

Figure 7.1 – A sample DNS protocol packet
Here’s a breakdown of the important components of a DNS data packet shown in Figure 7*.1*:
- Header:
- Identification: A 16-bit field that helps match responses with the corresponding queries
- Flags: Various control flags, including query/response indicators, recursion desired, recursion available, and so on
- Question count: Indicates the number of questions in the question section
- Answer, authority, and additional resource record counts: Indicates the number of records in each of these sections
- Identification: A 16-bit field that helps match responses with the corresponding queries
- Query:
- QNAME: The domain name being queried
- QTYPE: The type of resource record being queried (e.g.,
A,MX, orCNAME) - QCLASS: The class of the query (usually
INfor internet)
- QTYPE: The type of resource record being queried (e.g.,
- QNAME: The domain name being queried
- Answer:
- NAME: The domain name to which the resource records in this section apply
- TYPE: The type of resource record (e.g.,
A,AAAA, orCNAME) - CLASS: The class of the data (usually
INfor internet) - TTL (Time to Live): The time in seconds that the record can be cached
- RDLENGTH: The length of the
RDATAfield - RDATA: The data associated with the resource record
- TYPE: The type of resource record (e.g.,
- NAME: The domain name to which the resource records in this section apply
- Authority and Additional Section:
- Similar structure to the Answer section, providing additional information about authoritative servers and supplementary data.
- UDP is the most common transport protocol for DNS, and the typical size of a DNS packet is 512 bytes. However, larger packets can be transmitted using the EDNS0 extension mechanism.
- Similar structure to the Answer section, providing additional information about authoritative servers and supplementary data.
The following figure shows the real DNS query and the answer with the help of the nslookup comment in Linux (it is also available in different OS):

Figure 7.2 – Real DNS query and answer
In Figure 7*.2*, a DNS query was initiated using the nslookup tool. When executing the nslookup command, the domain name being queried and the address of the forwarding DNS server should be specified. The result typically displays a non-authoritative answer, which is the answer in DNS that indicates a response provided by a server that doesn’t directly manage the domain’s records. It gets the information from another DNS server in the hierarchy.
Note
Forwarding DNS servers and internal DNS servers serve distinct roles in the resolution of domain names to IP addresses, and their combined use contributes to a resilient and efficient network setup:
Forwarding DNS server:
- Function: Acts as an intermediary between your network and the broader internet.
- Operation: When a device on your network seeks the IP address for a domain (e.g.,
google.com), it initiates contact with the forwarding DNS server. - Response: If the forwarding DNS server possesses the IP address in its cache, it provides it directly. If not, it relays the request to external DNS servers on the internet until a response is obtained.
- Benefits: Reduces internet traffic through caching frequently accessed domains, enhances performance, and allows flexibility for implementing security policies.
- Internal DNS server:
- Function: Responsible for resolving domain names within your internal network.
- Operation: Stores and manages DNS records for internal resources such as servers, applications, and file shares. These domains are not accessible from the internet and have private IP addresses.
- Response: When a device on your network requests an internal domain name, it directly queries the internal DNS server for the corresponding IP address.
- Benefits: Enhances security by restricting access to internal resources from external sources, simplifies internal name resolution, and facilitates custom domain names for internal resources.
Effective network architecture within organizations necessitates the implementation of two crucial types of DNS services, with the internal DNS server playing a pivotal role. In my professional experience, the Microsoft DNS server emerges as the de facto standard for enterprise-level organizations. This dual approach involves the utilization of both internal and forwarding DNS servers, each serving distinct functions to optimize the overall network infrastructure.
The internal DNS server, being an integral component, serves as the backbone for resolving domain names within the organization’s internal network. With the Microsoft DNS server often being the preferred choice, it becomes the bedrock for storing and managing DNS records related to internal resources such as servers, applications, and file shares. These internal domains are intentionally not accessible from the internet and are associated with private IP addresses. This setup not only enhances security by preventing external access to sensitive internal resources but also facilitates custom domain names for internal entities.
On the other hand, the forwarding DNS server assumes the role of an intermediary between the organization’s network and the broader internet. This server efficiently handles external requests by caching frequently accessed domain information, subsequently reducing internet traffic. In scenarios where a device on the network requests the IP address for an external domain, the forwarding DNS server either directly provides the cached information or forwards the request to external DNS servers on the internet until a response is obtained.
The decision to employ both types of DNS services is driven by a range of factors, each contributing to the overall efficiency, security, and control of the network. For instance, the forwarding DNS server optimizes efficiency and reduces internet traffic, while the internal DNS server adds a layer of security by safeguarding sensitive internal resources and enabling customized access control. Additionally, the internal DNS server offers administrators full control over internal domain names and their resolution within the network. It further excels in performance, resolving internal names more rapidly than relying on external servers.
Practical instances of this dual DNS setup are evident in organizational use cases. For example, a company might deploy a forwarding DNS server for external website access, while relying on an internal DNS server for critical internal functions such as employee portals, file servers, and applications. Similarly, a school might leverage a forwarding DNS server for students’ internet access, complemented by an internal DNS server that resolves names for classroom computers and the administrative network. This comprehensive approach ensures a secure, controlled, and efficient DNS resolution system tailored to the unique needs of each organization.
Example use cases
Section titled “Example use cases”Let’s look at a few example use cases:
- A company employs a forwarding DNS server for external website access and an internal DNS server for its employee portal, file servers, and internal applications
- A school utilizes a forwarding DNS server for students’ internet access and an internal DNS server for resolving names for its classroom computers and administrative network
The Windows DNS debug log, generated by Microsoft’s DNS service, contains detailed information about the DNS queries, responses, and server activities. Enabling DNS debug logging is a useful troubleshooting and diagnostic tool, providing insights into DNS-related issues. The log entries include various details that can help administrators understand the behavior of the DNS service. Here are some key pieces of information typically found in Windows DNS debug logs in addition to DNS protocol packets:
- Timestamp: Each log entry includes a timestamp indicating when the DNS event occurred, helping in chronological analysis
- Client IP address: The IP address of the client making the DNS query
- Server IP address: The IP address of the DNS server handling the query
Also, there is other information, such as error messages, debugging information, and configuration changes. But these are not important to us right now.
We will examine a real DNS debug log example. With the help of this log, we can understand the outbound traffic and learn about the baseline traffic. By doing so, we can detect anomalies and also see whether there are any malicious domain queries. These are good indicators of any type of suspicious activity and help us understand whether we should block any traffic. But in modern cybersecurity, we need to understand the root cause and mitigate it; we cannot handle millions of daily queries or traffic activities one by one.
The information provided in the DNS debug log is insufficient for fully grasping the root cause. DNS logs lack reliability in pinpointing the exact source due to the dynamic nature of private IP addresses within the company network, which are subject to change. Furthermore, even with the source IP address, user identification remains elusive. Here’s a sample excerpt from the DNS debug log:
<13>Aug 01 07:46:17 microsoft.dns.test AgentDevice=WindowsDNS AgentLogFile=dns.log PluginVersion=192.168.63.93 Date=2019-08-01 Time=07:46:13 ThreadID=a.m.0E40 Context=PACKET Message=Internal packet identifier=000000A018724240 Protocol=UDP Action=Send RemoteIP=192.168.113.142 Xid=0f5f QueryType=A QueryName=d3hb14vkzrxvla.cloudfront.netLet’s interpret this code and make it more readable for us:
<13>: This is the priority or severity level of the log message. In this case, it indicates a relatively low priority level.Aug 01 07:46:17: This is the timestamp indicating when the log message was generated, showing the month (August), day (01), and time (07:46:17).microsoft.dns.test: This is the source or facility of the log message, indicating where it originated from.AgentDevice=WindowsDNS: This parameter specifies the type of agent device involved, which in this case is a Windows DNS server.AgentLogFile=dns.log: This parameter specifies the log file related to the agent device. Here it’s nameddns.log.PluginVersion=192.168.63.93: This indicates the version or IP address of the plugin used.Date=2019-08-01: This parameter provides the date when the event occurred in the YYYY-MM-DD format.Time=07:46:13: This parameter provides the time when the event occurred in the HH:MM:SS format.ThreadID=a.m.0E40: This identifies the thread or process involved, though the format here might be specific to the system’s logging conventions.Context=PACKET: This parameter provides contextual information about the log message, indicating it’s related to a network packet.Message=Internal packet identifier=000000A018724240: This is a specific message related to the internal packet identifier.Protocol=UDP: Indicates the protocol used. Here it’s User Datagram Protocol (UDP).Action=Send: Specifies the action taken with the packet, which in this case is sending it.RemoteIP=192.168.113.142: This indicates the IP address of the remote endpoint involved.Xid=0f5f: This is the transaction ID, represented in hexadecimal format.QueryType=A: Specifies the type of DNS query made, which in this case is for an IPv4 address (A record).QueryName=d3hb14vkzrxvla.cloudfront.net: Specifies the domain name being queried.
Overall, this log entry provides detailed information about a DNS-related event, including timestamps, source information, packet details, and network protocol specifics.
As can be seen, we can understand the malicious activity and block it by analyzing the DNS debug log. But there is one important factor we cannot see to mitigate this threat from its root: the source. Maybe you think that there is a source of this activity on the DNS debug log. For example, in our case, it was 192.168.113.142. But it is important to understand that the client IP address is not a reliable source inside the internal network. The reason for this is that the client’s internal IP address can be changed easily. So, we need specific information about which device was using that private IP address at that specific time. Even that is not enough—we need to know who the user of that specific device was, because devices can be used by multiple users. DNS security tools enrich the DNS logs with Dynamic Host Configuration Protocol (DHCP) logs for Mac address and IP matching in terms of time and Active Directory (AD) logs for user identity and user activities to tackle this issue.
Note
AD is a Microsoft-developed directory service designed for Windows domain networks. It functions as a centralized and hierarchical database responsible for storing and overseeing information related to network resources, users, groups, and various other objects associated with the network. AD offers a suite of services that streamline network management and enhance security measures within an organizational framework.
DHCP is a network protocol employed for the automated allocation and administration of IP addresses and configuration details to devices within a network. By doing so, DHCP eliminates the necessity for administrators to manually allocate IP addresses to individual devices, offering a more efficient and scalable solution that is particularly beneficial for extensive networks.
If your organization does not currently use DNS security devices, I strongly recommend that it does as soon as possible. But until then, you can enrich the security with the help of SIEM devices and correlation rules. We should enrich DNS logs with AD logs and DHCP logs. Now, we will learn what AD logs and DHCP logs are and what we will observe when we are correlating them.
This is an example of an AD log for a log-on event:
2023-12-31 12:30:45.678 INFO [Active Directory] Event ID: 4624 User: DOMAIN\JohnDoe Logon Type: 3 Logon Process: Kerberos Authentication Package: NTLM Source Network Address: 192.168.1.101 Workstation Name: PC123 Successful LogonAlso, upon getting details from the AD log-off event, now our DNS debug log (shown previously) and AD log indicate the activity and user details. With the help of DHCP logs, now we have also regarding device Mac address, which is shown in the DHCP log example here:
2023-12-31 15:20:30.123 INFO [DHCP] Event ID: 1001 Scope: 192.168.1.0 IP Address: 192.168.1.100 MAC Address: 00:1A:2B:3C:4D:5E Hostname: Device-123 Lease Duration: 86400 seconds Lease Request: Offered IP 192.168.1.100 to MAC 00:1A:2B:3C:4D:5E (Hostname: Device-123)To summarize, up till now, we have learned that DNS is one of the most important protocols for endpoint security. We have also seen some details about protocol packets and logs. To unveil its power, some extra information should be merged with the DNS debug log, such as DHCP and AD logs. With the help of this information, we can analyze all outbound traffic. Also, with the help of a DNS firewall, we can detect any malicious or suspicious activities and respond. In addition to blocking this activity, in the next section, we will see what else we can do with this information.
DNS firewall
Section titled “DNS firewall”Imagine a vigilant gatekeeper strategically positioned at the very foundation of your network’s navigation system, DNS. This gatekeeper is a DNS firewall, meticulously filtering and controlling DNS traffic to safeguard against various cyber threats.
How does it work?
Section titled “How does it work?”A DNS firewall works as follows:
- Domain filtering: The firewall maintains a comprehensive database of known malicious domains, acting as a protective shield against them. This prevents accidental connections to websites or servers associated with phishing, malware, or other harmful activities.
- Customizable control: Security administrators can flexibly create blacklists of restricted domains and whitelists of trusted ones, ensuring alignment with organizational policies.
- Staying ahead of threats: The firewall stays vigilant by integrating with threat intelligence feeds, constantly updating its knowledge to identify and block newly emerging threats in real time.
- Protecting against common attacks: DNS firewalls effectively combat malware and phishing attempts by blocking access to domains known for hosting malware or engaging in deceptive tactics.
- Content filtering: Some firewalls offer additional content-filtering capabilities, enabling organizations to regulate access to specific content categories or websites, enhancing overall control.
- Gaining valuable insights: Logging and reporting features provide administrators with comprehensive insights into DNS traffic patterns and potential security risks, facilitating informed decision-making.
- Enforcing security policies: The firewall empowers administrators to define and enforce security policies consistently across devices, promoting adherence to organizational guidelines.
Key advantages of DNS firewalls
Section titled “Key advantages of DNS firewalls”The following are the advantages of DNS firewalls:
- Proactive threat blocking: They intercept threats at the DNS level, preventing them from even reaching your network
- Defense-in-depth strategy: They complement traditional firewalls, adding an extra layer of protection
- Flexible deployment: They can be implemented as standalone appliances, integrated into existing infrastructure, or accessed as cloud-based services
In conclusion, DNS firewalls stand as a vital component of a comprehensive cybersecurity strategy. Proactively filtering DNS traffic and enforcing security policies effectively mitigate a wide range of cyber threats, safeguarding your network and devices from harm. DNS firewalls have a comprehensive database of known malicious domains. But how can a DNS firewall understand which domain is malicious and which is suspicious or safe? This is what we will learn about next.
Domain categorization
Section titled “Domain categorization”Efficient domain categorization is essential for managing internet traffic. Early in my career, I observed organizations grappling with content filtering using the blacklist/whitelist approach—an arduous task for IT personnel. Handling the vast number of domains, which is projected to reach nearly 600 million in 2024, along with numerous subdomains, becomes impractical for humans. AI surpasses human capabilities in identifying malicious domains.
Certain firewall vendors employ proprietary categorization engines, leverage cyber threat intelligence, or a combination of both. Although cyber threat intelligence is beyond the scope of this discussion, I’ll delve into the logic behind domain categorization.
Establishing trust on the internet parallels real-life dynamics. Like relying on references and common friends, web page popularity serves as a reference online. The PageRank algorithm aids machine learning systems in this regard. Google’s PageRank algorithm assesses the significance of web pages by considering the quantity and quality of clicks and views they receive. This foundation is built on the premise that more important websites attract a higher number of links from visitors. While Google uses diverse algorithms for search result organization, PageRank remains its inaugural algorithm.
Beyond domain significance, analyzing content provides additional insights. Suspicious activities, such as frequent changes in IP addresses and MX servers, are often employed by hackers to circumvent IP blacklisting. Trustworthy SSL usage serves as a positive indicator for machine learning systems. The number and content of redirections are also valuable indicators. Additionally, the prolonged absence of content updates raises suspicion about a domain.
While each of these indicators alone may not conclusively label a domain as malicious, feeding sufficient data to machine learning systems enables them to instantly discern the potential threat. As an enterprise-level customer, you need not educate your own AI system. Armed with this understanding, you can choose the appropriate solution for domain categorization, whether through DNS firewalls or web filters.
We have now understood the importance of DNS firewalls and their domain categorization mechanism. But why do we need a DNS firewall in addition to a regular firewall or proxy web filtering? Because there are some malicious activities you can only monitor and detect with DNS security devices. We will learn about these domains in the next section.
Domains without an IP address
Section titled “Domains without an IP address”In contrast to cinematic portrayals, successful cybersecurity attacks are not rapid occurrences measured in minutes or seconds; they can span years. Take, for instance, the notorious 2015-2016 Swift banking hacks, where attackers infiltrated the network years in advance to abscond with a staggering $101 million. The C2 logic is a common thread in many cyber-attacks.
In the realm of cybersecurity, command and control signifies the methods employed by cyber-attackers to maintain communication with compromised systems or malware-infected devices. This term is typically linked with sophisticated cyber threats such as Advanced Persistent Threats (APTs) and botnets. Here’s a simpler breakdown. In essence, attackers execute two primary functions:
- Firstly, they issue commands to compromised systems or malware, directing specific actions, data extraction, or updates to the malicious code
- Secondly, attackers establish a means of controlling the compromised systems, usually through a centralized server or infrastructure managing communication between the attacker and the infected devices
Here’s how it generally unfolds. Attackers gain entry into a system or network, by exploiting vulnerabilities or utilizing social engineering techniques. They then implant malicious software into the compromised system, granting them control over it. The malware subsequently establishes a covert communication channel with the attacker’s C2 server, often utilizing encryption or obfuscation techniques. Finally, attackers leverage this connection to send instructions to the compromised system, directing it to perform various tasks, such as extracting sensitive information or perpetrating further attacks.
However, to evade detection by Endpoint Detection and Response (EDR), firewalls, or other security devices, attackers may initiate their control center (malicious domain) only when starting an attack. As a result, security devices that analyze traffic at the application layer (HTTP/HTTPS) may not detect these unestablished C2 connection attempts until the attack begins.
DNS security plays a crucial role in detecting and blocking such activities. Organizations can identify and thwart malicious traffic by monitoring DNS logs through tools such as DNS firewalls or SIEM rules. Another scenario where DNS log analysis is indispensable is the detection of Domain Generation Algorithm (DGA) domains.
DGA domains, generated by malware using specific algorithms, aim to dynamically create numerous domain names, making it challenging for security solutions relying on static domain blacklists to keep up. Here’s an overview of how DGA works:
- Algorithm generation: Malware authors design algorithms generating pseudo-random domain names based on factors such as date and time.
- Communication: Infected systems use the algorithm to generate domain names at intervals, attempting to connect to these domains to establish communication with the C2 server.
- Dynamic nature: The dynamically generated domains pose challenges for security solutions using static blacklists.
Detecting and mitigating DGA-based communication demands advanced threat intelligence and analysis techniques, with DNS logs proving instrumental in this endeavor.
Yet another notorious and widely employed method for data theft and communication with external attackers from within a network is the DNS tunneling attack, a topic we’ll explore in the next section.
DNS tunneling
Section titled “DNS tunneling”DNS tunneling is a technique that involves encasing non-DNS traffic within DNS packets to bypass network security controls. The DNS protocol is used for legitimate purposes, such as translating domain names to IP addresses, but attackers can abuse this protocol to send unauthorized data or commands.
Here’s a simplified overview of how DNS tunneling works in Figure 7*.3*:

Figure 7.3 – Real DNS query and answer
Figure 7*.*3 suggests that malware residing within the victim’s computer initiates a compromised DNS query devoid of a legitimate DNS answer, including an IP address. This query appears as a random and nonsensical DNS request, concealing encrypted data within its structure. Since there is no registration for such a domain name, only the attacker’s deceptive DNS server can intercept and respond to this query.
By possessing the decryption key, the attacker can extract the concealed data from the DNS query and reply with a seemingly innocuous IP address along with a command such as I got your message; send me more. The absence of a default DNS tunneling algorithm grants attackers the flexibility to devise their own methods. The lack of a universal detection algorithm transforms the situation into a dynamic cat-and-mouse game, prompting security measures to evolve continually in response to emerging threats. Notable tools for DNS tunneling attacks encompass DNScapy, Iodine, OzymanDNS, dns2tcp, and tcp-over-dns, as well as an array of bespoke tools tailored to the specific needs of attackers.
Important elements of detection techniques
Section titled “Important elements of detection techniques”- Size analysis of DNS packets: Scrutinizing the size of DNS request and response packets is one method of identifying suspicious DNS tunneling traffic by assessing the ratio of source and destination bytes. However, recent advanced DNS tunneling attacks often divide packets into smaller chunks, challenging the effectiveness of this approach.
- Variability of domain names: Detection based on the entropy of requested hostnames remains valuable. Legitimate DNS names exhibit recognizable patterns, while encoded names used in tunneling display higher entropy and a more uniform character set, providing a useful source for identifying DNS tunneling attacks.
- Repeated consonants and numbers: Examining repeated consonants, and numbers in hostnames can reveal signs of DNS tunneling. While not foolproof, this can contribute to score-based detection or detection AI.
- Specific signatures: Researchers have developed signatures for specific DNS tunneling tools, but this simplistic technique can be bypassed with small modifications that alter packet hashes, enabling them to evade signature-based comparison techniques.
- The volume of DNS traffic per domain: Monitoring the volume of traffic per domain is indicative of DNS tunneling since it typically involves a specific domain. However, the possibility of multiple configured domains distributing the traffic should be considered. The count of hostnames for a given domain, particularly the number of subdomains, can be a potent indicator.
- Learning DNS traffic patterns: A proactive method involves understanding typical DNS traffic patterns and identifying anomalies. DNS firewalls and DNS security devices provide visualization reports, emphasizing their importance as mandatory tools in enterprise-level companies.
Detecting and preventing DNS tunneling demands advanced security measures, including DNS traffic analysis, anomaly detection, and the use of security tools specifically designed to identify and block such malicious activities, such as a DNS firewall and logging, IDSs and IPSs, and DNS sinkholing.
Summary
Section titled “Summary”At the start of this chapter, we mentioned the pivotal role of DNS as one of the most crucial protocols in the realm of cybersecurity. The significance of DNS security extends beyond endpoint protection, making it a paramount topic in the broader landscape of cybersecurity. Our journey commenced with a granular exploration of DNS packets, unraveling the intricacies of how the DNS system operates. We delved into the rationale behind companies segregating local DNS and forwarding DNS services.
Expanding our understanding, we delved into the limitations of relying solely on DNS logs and explored the need to enhance their utility. Additionally, we explored the intricacies of enriching DNS logs to bolster their effectiveness in detecting and thwarting malicious activities. Among the nefarious activities we dissected in detail were requests for domains without IP addresses and the insidious practice of DNS tunneling.
As we transition to the next chapter, our focus will shift to gaining insights into the future of endpoint security. This exploration promises to shed light on forthcoming developments and trends in the dynamic landscape of cybersecurity, ensuring that our knowledge remains not only current but also anticipatory of emerging challenges and advancements.