5

Active Manipulation

When you encounter your opponent before they are aware of your presence, you can gain a unique opportunity to tamper with their perception. By tampering with the opponent before they notice your presence, you can further hinder their ability to detect your existence. This can be risky as it involves active deception, but it can pay great dividends when pulled off successfully. While the attacker's methodology can embrace this deception, with techniques such as log deletion and the use of rootkits, the defenders can also invoke active manipulation to slow down attackers in their environment. They can remove the offense's ability to operate effectively, frustrate malicious actors in their environment, and ultimately increase the telemetry of any malicious actions. In practice, this can mean identifying a specific malicious actor and drilling into their operations or setting up several ubiquitous defensive technologies that thwart malicious actions in general. Specifically, in this chapter, we will visit several popular security techniques such as:

  • Deleting logs
  • Backdooring frameworks
  • Rootkits
  • Data integrity
  • Detecting rootkits
  • Manipulating the home-field advantage
  • Deceiving attackers on the network
  • Tricking attackers into executing your code

Offensive perspective

As the attacker, if we land on a well-instrumented host, we can take several advanced steps to reduce the data the defender may collect. As we saw in the previous chapters, the defender will heavily rely on host-based technologies to generate the necessary security telemetry. The attacker, who may have similar privileges on this host, should naturally reduce these defensive capabilities before they result in the attacker being detected. By removing the defender's logs and tampering with their tools, we can severely hamper the defender's ability to detect and then respond to the event. In their most pure form, these deceptive techniques, which wrestle the basic perspective operations away from the defenders, are known as rootkits. While traditional rootkits often require kernel-level permissions, we can understand them as any attacker technique that actively changes defensive perceptions about a host to hide attacker tools. In practice, this means many userland techniques for hijacking control and showing deceptive results in common tools or logs can be considered a rootkit technique[1]. In this section, we will delve into many of these techniques, starting with simpler solutions and moving to full-blown, traditional rootkits. While I will show many specific implementations, it is important to think of these capabilities in general terms, as these deceptive techniques have seen countless implementations in different tools over their short tenure.

Clearing logs

Let's start by looking at cleaning up some of our previous Windows activity. Say you have landed on a Windows host as an attacker, and you can tell it is well instrumented to produce local logs. Specifically, we saw how effective sysmon could be in the previous chapters for getting new signals into the Windows event log. As an attacker, we want to remove some of our specific events from these log sources before the defenders can analyze them. First, it is critically important to understand if the defenders have centralized logging, and then to potentially disable that log collection. Further, we do not want to clear the event logs or turn the logs off, as this is an alarming event on its own. Instead, we will focus on removing selective alerts that will arise from the offensive actions, while leaving the benign activity in the logs.

Because the event log can be such a complex file format, we can learn from the fantastic project Eventlogedit by 3gstudent to understand several of these techniques from an offensive perspective[2]. I really like this project because it comes with a series of blog posts explaining the various techniques, albeit in Chinese. At a high level, this process starts with parsing the event log file, which has its own unique header, data chunks (which may contain multiple records), and the individual event records or log entries[3].

The 3gstudent series of blog posts shows various techniques and implementations for both getting access to the Windows event log file of a running system and modifying the file once you can write to it. One technique for deleting the logs, used in the NSA's Danderspritz framework, is increasing the length of an individual event record such that the size in an individual record header includes the content of the next event record. This means the event log file will read this header and parse all of that content as a single log entry, while only displaying the content of the first log entry. There are ways to detect this however, for example an open-source Fox-IT script can detect these events altered by the Danderspritz framework[4]. As a follow-up on this technique, 3gstudent shows what would be required to actually delete an entire event record. However, several locations in both the event log file header as well as individual event records will need to be corrected, such as length fields, last record fields, and multiple checksums, to name a few. 3gstudent then goes on to develop a method that uses the Windows API to read the entire event log, simply omit the logs in question, then write a new event log file without the target record. Revisiting the detection ideas, using these different techniques will evade the Fox-IT detection scripts, despite leaving obvious gaps of missing recordIDs in the event log file. 3gstudent goes on to show how you could even correct the recordIDs. Further, to delete the event log file in use by the system, you need to release the file handle the process has on the event log file to edit the file maliciously, or execute your techniques within the process' context to modify the file. Still, 3gstudent's project is mostly a proof of concept based on EquationGroup's stuff, exploring many various procedures on the same general technique. For our actual operations, we will use a more tested and ready-for-production-use version of the technique from QAX-A-Team, EventCleaner[5]. EventCleaner works in a very similar manner to 3gstudent's proof of concept, in that it uses the Windows API to omit the target log and rewrite the file. The really nice part about EventCleaner is it will find the event log service process, enumerate the open handles, and close the handle to the file in question, such that the program can then edit the file:

> EventCleaner.exe suspend
> EventCleaner.exe closehandle
> EventCleaner.exe [Target EventRecordID]
> EventCleaner.exe normal

However, this requires parsing the event log, knowing your event's recordID, and lots of tampering with the event log service to get this to work. A situationally better technique is suspending or even crashing the event log service before your target actions, such that the logs will not be there in the first place. In the preceding implementation of suspend, the EventCleaner project will also turn off several dependent services using the sc control manager, which may be an interesting observation when viewed in an EDR parent-child relationship.

In a similar manner, we can also suspend the event log service and perform our malicious actions after. However, suspending the event log service may look suspicious when investigated. You can also apply the concept of suspending processes to almost any extra telemetry the host may be generating, such as an EDR agent.

Another, potentially better way to stop the event log service is to crash the service, as this will look less suspicious than suspending the process. There is a really great blog post by Benjamin Lim that describes crashing the event log service by calling advapi32.dll!ElfClearEventLogFileW with a handle from advapi32.dll!OpenEventLogA. Benjamin also notes the service will restart twice by default, but if the attacker crashes it three times it won't restart by default[6]. Luckily for us, this exact technique has already been implemented in a C# project by Justin Bui (https://github.com/slyd0g/SharpCrashEventLog/blob/main/SharpCrashEventLog/Program.cs#L15). We can use his SharpCrashEventLog program to repeatedly crash the event log from memory, using the DLL calls mentioned earlier, which may look fairly normal from an incident response perspective.

To take this concept of log and service tampering even further, you can also tamper with any EDR agents that may be on the host. There are many similar tricks we can do to mess with an EDR agent that is stopping us as an attacker. If you learn your target is using a specific agent, you will need to research techniques that work against that specific agent before trying things live on the host. Trying random techniques on the host where you are unsure if they will work is often referred to as flailing and is not something experienced hackers should engage in. Still, one of the simplest tricks that you can test is to privilege escalate, kill, suspend, or crash the process, and then move the directory such that the EDR agent can't restart or run properly. We can view this reaction correspondence of the offense attacking the defender's telemetry on a host in Figure 5.1. This is a great example of a reaction correspondence because it is a direct reaction in offensive strategy based on the defenders increasing their capabilities and visibility:

Figure 5.1: In step 3, an attacker can delete the defender's logs, tampering with the defensive collection they have set up

Let's switch gears now to look at some Linux victims and some stealthy post-exploitation techniques we can leverage on production Linux machines. These can be an easy pivot from the corporate environment if you exploit a developer or someone with credentials to the production environment, potentially where the attacker's goal lies. In the next chapter, we will also examine more techniques for discovering and abusing pivots, but for now let us assume we have access to more Linux systems in a production environment.

Hybrid approach

We can also tamper with logs on Linux or in a production environment. On Linux, most log files are simple text files stored in /var/log/. To start, we will use a similar method as before where we essentially copy a log with our specific entry omitted. It is also easier to edit these logs as compared to Windows, as we do not have to stop any processes, terminate file handles, or fix any log-specific checksums. Similar to Windows, there are many different application-specific logs, although they are easier to navigate and parse on Linux, in my opinion. As an example, let's say we found a web vulnerability that we exploited to get access to the Linux system, we may want to clean up the web logs after we get access to such a system. The following commands will remove all occurrences of a specific IP address from the Apache web access log with a simple grep command:

$ egrep -v "172.31.33.7" /var/log/apache2/access2.log > /var/log/apache2/tmp.log; 
$ mv /var/log/apache2/tmp.log /var/log/apache2/access2.log;

In the preceding example, the specific IP address the attacker is removing is the local 172.31.33.7 address, which you will want to replace with your attacker source IP address. However, this may still be weird from an analysis perspective as it may show inconsistencies within the application logs. Further, you can forensically recover the original file to discover some of the missing entries. We will look at these two counter-techniques in more depth in the following Defensive perspective section. A better offensive technique may be to install a special backdoor that will leave out certain logs rather than delete them retrospectively. Like our binary backdooring in Chapter 4, Blending In, our goal is to hijack and manipulate normal service functionality, however this time we will achieve this by installing a module in Apache on Linux. Modules are an interesting way to get malicious code into frameworks, as it leaves the original binaries untampered and often requires application-specific expertise to be able to check the modules. Our module is special because it will remove logs that start with a header cookie that we specify, or the default password=backdoor. Using such a backdoor the process will look as if it is operating normally, all the while leaving out the attacker's records of abuse from the logs. This essentially attacks the defender's ability for non-repudiation and log integrity. For our example we will leverage Vlad Rico's apache2_BackdoorMod[7]. One drawback to using this tool and technique is that if the defender lists out the loaded modules, they can clearly see the names and module loaded, including our malicious module:

$ apache2ctl -t -D DUMP_MODULES

Therefore, as an attacker, you will probably want to rename your modules and backdoors to blend in with other existing modules. Still, as an attacker, once we compile our module, load it into Apache, and restart the Apache service, we can begin to trigger the various parts of the backdoor with our secret backdoor cookie. Not only will this backdoor hide our malicious activity from the logs, but we can use it to spawn root bind shells, reverse shells, and even a network SOCKS proxy. The following command will both launch a root bind shell and whitelist our IP for future connections:

$ curl -H "Cookie: password=backdoor" https://target_victim/bind/1234

When the preceding command spawns a new bind shell, it both executes as root and as a child of PID 1, which is nice for decoupling the new shell from the apache2_BackdoorMod. Further, once we trigger the backdoor it will whitelist the IP address that made the request with the special cookie, such that we do not need to use the password in the future. This is a helpful feature when spawning the SOCKS proxy or using an application like Firefox to connect to the proxy and browse through the target. Granted, if you use the SOCKS proxy then your general network traffic will still be visible on the host. This emphasizes the need to have multiple ways to verify that logs are robust and show data integrity, which we will revisit later in the defensive section. Similarly, many of these techniques exist on Windows, such as using a WinPcap driver and filter to intercept network requests before they are logged[8]. Let us move on to a way that we can completely hide these network connections, by invoking a more traditional rootkit solution.

Rootkits

Rootkits are the ultimate method of tampering with the opposition's perception. There are many different kinds of rootkits, from userland rootkits to kernel-level rootkits. Some of my favorites are rootkits that load their own kernel modules or drivers as these tend to be some of the most popular open-source examples. While there are many rootkits that target Windows with similar or unique techniques[9], in this section, we will be focusing on a Linux LKM rootkit. LKM means loadable kernel module, which is how the rootkit gets installed. On Windows, such driver-based rootkits require being signed for x64 systems, however it's important to note that driver signing isn't enforced on x86 Windows systems, making them a much easier target for such activities.

For our example, we will focus on Reptile, one of my favorite LKM rootkits[10]. Reptile has a fairly basic feature set, it can hide directories, files, contents within files, processes, and even network connections. Hiding contents in files is a handy feature for backdooring configuration files or hiding web shells. Tools like Reptile will be important for hiding our various forms of persistence and attacker utilities. Under the hood, Reptile makes heavy use of the khook framework and the kmatryoshka loader. Reptile uses the khook framework to make hooking API calls from the kernel much easier[11]. Function hooking is a popular technique where a program will intercept an API call and substitute its own function before calling the normal API handler. In the case of khook, it will add a jump at the beginning of the hooked function to call a custom function defined by the developer. There are some really good forum posts if you're looking for a more in-depth analysis of the khook framework[12]. The kmatryoshka program is an encrypted loader designed as a kernel module[13]. It is the basis for the LKM, consisting of two parts, a parasite loader and the userland code, called the parasite, to be loaded into memory. Reptile also makes use of several userland programs, such as reptile_cmd, which act as controls for letting the operator turn features of the LKM on and off dynamically.

Reptile is an incredibly fun tool to use operationally. When you build Reptile, you can specify several configuration features such as the key words you will use to hide content. It is important to change the default configurations, as with a tool like Reptile there are many obvious locations to check and it will also reveal the tool in use very quickly. Operationally, the attacker will use Reptile to hide their working directory and other malicious processes. Our goal is to use Reptile as an obfuscation layer, to protect other attacker tools from generating as much telemetry. Sometimes these rootkits can require a bit of memorization or keeping a runbook on hand[14] as the directories and files will be hidden from the operator as well while the backdoor is enabled. This is where operator training and expertise also pays dividends. Once Reptile has been installed, issue the following command to trigger the basic backdoor functionality for hiding files, directories, content in files, and processes:

$ /reptile/reptile_cmd hide

Reptile also comes with an independent network client that can send a magic packet through TCP, UDP, and even ICMP, similar to the ICMP backdoor Prism that we looked at in Chapter 4, Blending In. Unlike the apache2_BackdoorMod, which only offered protection within its specific service, an LKM rootkit such as Reptile can easily hide all connections to a specific IP address. To hide all of the attacker's network connections with the Reptile rootkit, execute the following with your IP address, instead of the private IP address 172.31.33.7:

$ /reptile/reptile_cmd conn 172.31.33.7 hide

Reptile is epic because it can even hide its own kernel module by unlinking it from lsmod[15]. Unlike before with the Apache2 modules, this time if we list out the loaded kernel module, we will not see the Reptile module loaded. Reptile can also be used to escalate privileges, in the event we come back as an unprivileged user. To upgrade to a root shell, use the command tool with a root flag: /reptile/reptile_cmd root. When hiding processes, Reptile will hide the entire process tree, so the attacker can shell out from their existing backdoors now.

Defensive perspective

From the defender's perspective, there is a lot you can do to throw the attacker off their game plan. It is famously said that defenders have the home-field advantage and thus can craft the environment to their advantage, or the disadvantage of an uninformed visitor. You may have heard of the 5 Ds of physical security: Deter, Detect, Delay, Deny, and Defend[16]. These are principles security professionals leverage when they have the home-field advantage to prevent physical threats. These are principles we will adapt to help prevent an attacker from reaching their end goal. We can also add a 6th D for our purposes, Deceive. Using these principles and the home-field advantage we can set up infrastructure that will actively hinder and frustrate the attacker, which will buy us more time to observe and respond as a defender. Thus far in this book, we've seen a bunch of ways to defend, deceive, and detect. In this section, we will start to visit some ways that the defender can delay, deny, and deter the attacker. These will be methods that waste the attacker's time, frustrate them with unexpected situations, and ultimately deny them recon data they previously would freely collect. But before we dive into such deceptive methods, let's first look at some techniques for detecting and defending against the previous log deletion and rootkit techniques. Two major themes you will see in this section are recognizing what isn't normal, so you can understand when something is slightly amiss, as well as comparing multiple datasets to prove that a select set of tools may not be returning accurate data. These techniques boil down to integrity verification – methods to ensure the system is returning truthful data.

Data integrity and verification

One of the strongest counters to host-based log editing is centralized logging. As we saw in Chapter 2, Preparing for Battle, the investment in centralized logging can be significant but pays dividends in terms of availability, organization, triage time, and infrastructure integrity. By maintaining centralized logging, the attackers will need to tamper with the logs in near real time, meaning techniques like the Windows event log editing will be far less effective.

Further, by enumerating all of the event logs that you collect it may become evident that some event recordIDs are missing, which could be another sign that someone has tampered with the event log. As a defender, it is important to understand when you have bad data or when your sensors go offline. For example, a good alert to create in your SIEM is on the health of logging pipelines, such that if you do not receive any logs from a specific host or pipeline for an extended period of time, you will want to raise an event to investigate that host or logging pipeline. Such alerts could help detect when an attacker has disabled, suspended, or shorted logging in some location. As a defender, it is critically important to occasionally check the integrity of your data. Thinking back to our apache2_BackdoorMod example, there is a lot of other data the defender can use to understand when their logs are being tampered with. If the defender also collects network telemetry, they can compare the network requests to the web logs to find any discrepancies in the host-based logging. As a technical example, we can compare NetFlow or raw pcap data to the Apache logs that should be there. We can even automate this review with the Haka security framework and a Lua plugin from Xavier Mertens[17]. Xavier's Lua script is a plugin for the Haka security framework, which is designed for custom alerts on pcap data[18]. We can pull down the latest Haka release and easily analyze some pcap traffic using Xavier's HTTP format script (https://github.com/xme/toolbox/blob/master/haka_http_log.lua). Once we have the Haka framework and Xavier's script ready, we can generate near identical Apache2 logs from pcap traffic. Further, we simplify, normalize, and compare both sets of logs with a cut and diff, to clean the logs up and drop fields that may be inconsistent:

$ hakapcap ./haka_http_log.lua traffic.pcap |grep "GET" > http_pcap.log
$ cut -d" " -f1,4,5,6,7,8,9,12 /var/log/apache2/access.log > host.log
$ cut -d" " -f1,4,5,6,7,8,9,12 http_pcap.log > network.log
$ diff host.log network.log

Detecting rootkits

As we saw in the previous section, rootkits can be extremely deceptive and hard to detect. To start, there are some existing tools that work by checking for known rootkits. As we will see in Chapter 7, The Research Advantage, by examining specific attacker tools we can often create unique signatures based on their tells or how they are uniquely implemented. Often these rootkit-specific detection tools rely on flaws that exist in the tools and are generally good for detecting well-known rootkits, but not so much for detecting unknown or novel rootkits. Another thing we can do while the system is running is attempt to brute-force hidden objects, such as PIDs, file locations, or sockets.

As we saw with Reptile, even when all of the files are hidden the operator still needs to be able to access and control them. Similarly, you may want to check common locations for rootkits, such as the loaded kernel modules or the LD_PRELOAD variable[19]. A classic tool for checking many known locations and for many known rootkits is rkhunter[20], however, by default, this will not detect the Reptile LKM rootkit for whatever reason. Luckily, we can use the Sandfly Security Go tool, processdecloak[21]. Simply running the tool will reveal processes hidden by Reptile. That said, a savvy operator would also notice several crucial files and directories missing once Reptile has been enabled, such as /etc/ and /var/ no longer being in the root directory. Additionally, if you notice a critical directory missing, but can still cd into that location, you probably have a rootkit on your hands.

The following techniques will work better in a general sense when you don't know what tools or rootkits your opponent might be using. One general rootkit detection tool is called unhide[22]. While unhide won't call out Reptile by name, it can be used to find some of Reptile's hidden processes with:

$ sudo unhide brute -v -f

Beyond specific rootkit detection tools, there are a number of general techniques we can still leverage. The network-based log verification techniques we described previously can be immensely helpful when trying to detect rootkits. By simply installing a tap on both the network and the host, you can verify the host integrity by spotting missing traffic. You can compare the traffic that you should be seeing on the local tap to the network tap, as the rootkit will not be able to manipulate the network traffic the same as it will on the host. Essentially, you can look for discrepancies by leveraging other network telemetry, such as NetFlow on the host compared to network traffic on the wire.

Memory forensics are also still viable with rootkits. As we saw in Chapter 3, Invisible is Best (Operating in Memory), Volatility is always a great framework for memory analysis[23]. For example, the Volatility function linux_hidden_modules will reveal the kernel module that Reptile hides. Volatility is so powerful it can uncover Reptile in several different ways, such as the linux_enumerate_files function that will find the hidden Reptile directories and files in memory, and the linux_netscan function that will show the hidden network connections. Another Volatility function that will reveal generic foul play is linux_check_syscall, which will show when several syscalls have been hooked by Reptile.

You can still perform dead disk forensics when examining a rootkitted host. As we saw with Reptile, when the kernel module is loaded it hides files, directories, and even the module itself. But when looking at the disk when nothing is running, these files and directories won't be hidden, which should be a very clear discrepancy when examining the host. If Reptile, for example, is unmodified, then performing dead disk forensics will clearly reveal a /reptile/ folder in the root directory.

Finally, despite what we saw earlier in this chapter, log analysis can still help detect rootkits. The trick is to look for missing data or large gaps in the data. Things like inconsistencies in file inodes within a particular system directory can indicate a file was recently added[24]. Another potential indicator is large gaps of time in a log file, which can indicate perhaps the process was suspended or even terminated for a while. Additionally, you can sometimes forensically recover the original logs or even the missing log entries directly by carving them out of slack space. A cheap way to do this would be to make a forensic image of an entire disk, then run strings and grep on it to find deleted log entries. We can see this technique exemplified in the following snippet to find deleted SSH auth logs:

# dd if=/dev/input_disk of=/dev/output_drive/disk.img bs=64K conv=noerror,sync
# strings /dev/output_drive/disk.img | grep "sshd:session"

Manipulating attackers

As a defender, there are many ways we can manipulate an attacker to hamper their abilities, to frustrate them, and ultimately make them ineffective in our environment. When an attacker wastes their time trying many attacks, colloquially known as flailing, this will continue to highlight their presence and give insight into their operating methodology. Some simple hardening tricks involve renaming or removing many common utilities that an attacker relies on. If an attacker commonly ends up shelling out or executing commands through systems utilities, then we can inhibit them by changing the name of many of the tools (if we need them for some other reason), or by removing them altogether from production systems. On many production or single-use systems, a lot of the system tools required for general computing simply aren't necessary. Tools like whoami, ping, chattr, gcc, and even common text editors aren't needed for production usage. If you can alter your environment, consider removing many common utilities to reduce the general capabilities of any malicious actor that gets access to these systems. You could even go as far as to remove the normal package manager; however, I would only really do this in a competition setting or with an alternative update mechanism as updates in a computer security context are very important (the principle of time tells us we will need to update over time).

An even more deceptive technique, although it takes more time to set up, is to replace the common utilities with scripts or binaries that will alert the defender when they are used. The following is part of a universal Go utility that can replace any system binary on Windows, Linux, or macOS. Simply rename the system utility with .bak on the end, and put the newly compiled binary in its place, such that the Go program is called when someone calls the system utility. The Go utility will log the usage but can be tailored to alert or do something else, like shut down the machine. Also note that this program uses two helper functions that can be found in the full program (https://github.com/ahhh/Cybersecurity-Tradecraft/blob/main/Chapter5/wrap_log.go):

  //Prep vars
  logFile := "log.txt";
  hostName, _ := os.Hostname();
  user, _ := user.Current();
  programName := os.Args[0];
  //Check for backup program
  backStatus := "backup program is there";
  if !Exists(programName+".bak") { backStatus = "backup program is not there"; }
  //Notify area
  notification := fmt.Sprintf("%s: User %s is calling %s on %s and %s 
", time.Now(), user.Username, programName, hostName, backStatus);
  //Send or store notification
  //fmt.Println(notification);
  err := WriteFile(notification, logFile);
  //Execute
  results, _ := RunCommand(programName+".bak", os.Args[1:]);
  //Send results back to user
  fmt.Println(results);  

One technique for keeping attackers delayed or spinning over their limited access is by throttling their network connections to frustrating speeds. A popular implementation of this is trolling attackers with some restrictive iptables rules. iptables is one of the default userland firewalls tools on Linux and leverages Netfilter modules for manipulating the Linux kernel firewall. iptables is feature-rich, with abilities to redirect traffic, limit the number of connections over a certain port, and even restrict connections based on frequency. If they are coming in over SSH or another inbound service they have access to, we can drop a random percentage of traffic to hinder and frustrate the attacker:

$ sudo iptables -A INPUT -m statistic --mode random --probability 0.7 -s 0/0 -d 0/0 -p tcp --dport 22 -j DROP

Make sure you have alternative means of access if you do something like this, as it can also restrict your own ability to control the machine if this is the same service you use for administration. Likewise, if you see the attacker has some form of limited access or a basic outbound connection, such as a reverse shell, you can frustrate them by dropping the outbound packets of this tool. By dropping the response, you can still pick up the intel on the commands they send you but make the shell mostly useless as they wait for responses that will never arrive complete:

$ sudo iptables -A OUTPUT -m statistic --mode random --probability 0.7 -s 0/0 -d 0/0 -p tcp --dport 9999 -j DROP

Remember, when you're done trolling or testing you can drop your firewall rules with iptables (this also works if you want to drop the defender's rules as an attacker):

$ sudo iptables -F

Keeping attackers distracted

There are even more techniques we can use to keep the attacker on the hook to observe them while they flail around the network. Let's continue to look at techniques to frustrate and thwart attackers on the network. Portspoof is an incredible tool we can use to obfuscate our production systems[25]. Portspoof isn't a honeypot but instead will show the attackers all ports are open on the target system, and even includes a database to emulate many of these service banners. Rather than reducing port scans to only the available services, the defender will make it appear that all ports are open and running services, which in reality is a deception. What this means is the attacker's network scans will show all ports open and they won't be able to differentiate the real services from the fake services. This will dramatically hinder the attacker's ability to scan and enumerate their targets. Portspoof technically only listens on a single port, so we need to use iptables again to set up a NAT from our external ports to our Portspoof system. The following iptables rule will leave out ports 22 and 80, but will redirect all others to Portspoof:

$ sudo iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp -m multiport --dports 1:21,23:52,54:79,81:65535 -j REDIRECT --to-ports 4444

Once you compile the tool you can get it running, with the default configurations from the tools directory, using the following command-line flags:

$ sudo ./portspoof -s ./portspoof_signatures -c ./portspoof.conf

However, for now I would recommend copying that config file and editing it to remove the ASCII trollface, remove the various exploits, and edit the port list to something more tailored for your server. It is critically important to review the default configurations from your tools before you run them, as they can give away what technologies and deceptions the defense has at play. This is also an older tool, so when I run Portspoof I tend to reduce the list of exposed ports to increase the stability with high bandwidth scans. The tool can be run in daemon mode, which should help increase the stability as well. By default, Portspoof will write its logs to /var/log/syslog, which is nice for highlighting attackers scanning your infrastructure. Portspoof has even more features, such as exploitation, that we will revisit in the next chapter.

Another incredible active-defense tool is the LaBrea tarpit application[26]. LaBrea will keep attackers' scans hung up such that they won't finish without some extreme tuning. The LaBrea tarpit is another great example of delaying, deceiving, and denying the offense. LaBrea works by purposefully slowing down connections so people performing network reconnaissance get less accurate results. LaBrea can either occupy a single or set of IPs specified by the operator, or it can be set to dynamically claim unused IP addresses on the local network. Either way, once LaBrea is running it will wait for new TCP connections on a number of sockets it opens. Once there is a request, LaBrea will respond to these TCP connections with a SYN/ACK that has a window size of 10, then either stop responding or continue to send delayed ACKs with a window size of 10 (https://github.com/Hirato/LaBrea/blob/7d2e667cdf91c754d60a01104724474c0746a277/inc/labrea.h#L93). The window size of a TCP packet is the maximum data in bytes that a single packet can contain, so a window size of 10 severely limits how much data a scanner can send to the tarpit at a given time[27]. This makes scanning extremely slow as thousands of packets need to be sent to compensate for this small window size. Unfortunately, LaBrea is so old that it is difficult to get running on modern systems due to some older library dependencies. Luckily though, this general functionality has been ported to the Xtables_addons of iptables[28]. The difference with the iptables implementation is it will set the TCP window size to 0, but it will also ignore TCP requests to close the connection, leaving the TCP connection alive till it naturally times out. We can use iptables' tarpit with the following commands. Granted you will need the ports open to begin with, so this tool works very well with Portspoof:

$ sudo iptables -A INPUT -p tcp --dport 3306 -j TARPIT

We can see some of these ideas in the reaction correspondence in Figure 5.2. Here we see defenders can now alert on their logging pipelines or when a host stops sending logs. The defenders could also leverage a SOAR application to verify alerts or data as a post-processing function.

Further, the defenders can make it much harder to pivot to any production system by denying the attackers reliable scan data. By showing excessive ports as open and delaying TCP connections to these services, the defenders can make traditional network scanning scripts or techniques useless. This evolution of tactics doesn't happen on its own though, these are direct responses to known attacker techniques of network enumeration and clearing logs:

Figure 5.2: In step 4, remote logging capabilities allow the defender to still capture attacker activity, even when they delete local logs

Tricking attackers

In this section, we will look at methods for not only identifying and generating data around threats on your network, but we will go further by tampering with the data the attackers are looking to gain. By giving the attackers bad data, the defenders can continue to foil the attacker's progression while gaining vital information on their operations. As we saw previously, delaying the attacker can give the incident responders more time and information to respond to and eliminate a threat before it gets out of hand. The key here is to critically analyze what you own that the attacker wants to take, and how you can tamper with it. One technique I've personally used to great success is leaving booby-trapped code and data that I knew the attackers were interested in taking. By backdooring your own code, then letting the attackers take it and run it, you can get code execution on their systems and perform reconnaissance on the attacker in this way.

One example of backdooring your code that I have personally used to great success is backdooring the JavaScript on a major website targeted by a phishing campaign. We had phishers cloning our main web page and phishing our customers every day, effectively stealing their credentials, then logging into their accounts and cashing out their digital wallets. While we could detect and take down the phishing pages, the attackers would simply clone the website and launch the campaign again the next day. To counter the attackers, we placed a backdoor in the JavaScript of our own homepage, such that the attackers ran this code when they cloned our page and when the victims would visit these cloned phishing pages. This technique provided excellent early intel on their new phishing sites as well as the users that were submitting their credentials. Not only would we see the attackers working locally on the page as they tested it before deployment, but we would also see where the new phishing pages were hosted. Further, the JavaScript would then check if the code was running on the proper domain, and in the event it was the phishing page, it would simultaneously send us the users that were being phished via a webhook. We could then add protections to the victim's accounts before the attackers had the opportunity to exploit the users, giving us the upper hand and leaving the attackers stupefied at how we were locking the accounts as they got phished. Also, we used the local telemetry gained when the attackers cloned the page to deanonymize the attackers and ultimately bring them to justice.

Another idea comes from a presentation by Mathias Jenssen[29]. This technique is a counter to the specific threat of ransomware in 2015, which has become even more popular in recent years. The concept is simple, ransomware will enumerate the drives of a system in alphabetical order. By creating a B: drive, before the C: drive, and filling it with some fake data for the ransomware to encrypt, you can generate an early notification system for ransomware. Such a system could be used to automatically shut the system down, in an attempt to save and recover as many files as possible, as well as stopping the spread. One part to the trick Mathias mentions is using group policy to hide the directory from its own users, as the deception may bait curious users and thus create false positives. You can use this idea in conjunction with a tool like RansomTraps to generate the fake files and be alerted when they've been altered[30]. This isn't a very elaborate deception, as these are random junk files with just a file extension of .jpg, .txt, .docx, or .mp3, for example. But these simple traps will exploit the logic of most automated ransomware, making it an effective technique for tricking and countering a threat's automated tools. We will continue to revisit these concepts of reversing an operator's tools to get an advantage over their automated processes in Chapter 7, The Research Advantage. This is also another aspect where attribution on your threats is important. By understanding who your specific threats are, their goals, and modes of operating, we can build traps that will uniquely entice and counter those threats.

Yet another interesting idea is to use a zip bomb to troll attackers. A zip bomb is a specially compressed file that when uncompressed will expand to a ridiculously large file[31]. The idea behind this technique is similar to a honeypot except that it can slow down the attacker's data collection and exfiltration by making their host machine a mess. One trick to pulling this off is to remove the compression tools from the host machine that you leave the zip bomb on, such that the attackers do not expand the zip bomb on your systems but pull them back locally to their attacker infrastructure. Further, as we saw in Chapter 4, Blending In, the key to a successful honey trap is making the data enticing for the taking, which means naming it something that attackers would want to steal. Traditional zip bombs like 42.zip use recursive zipping to achieve their large size[32], but unfortunately, a smart attacker can unzip just the first layer and realize that this is a recursive zip bomb before subjecting themselves to the pain. Instead, we can leverage David Fifield's non-recursive zip bomb technique to achieve similarly overwhelming decompression sizes[33]. We can download his code from his website and make a whopping 281 TB zip bomb from a .zip file that is only 10 MB large. He shows how to make even larger zip bombs on his site, although they begin to use less compatible compression algorithms, so we will stick with the zip compression algorithm. The following will grab his zip bomb Python program and generate our 281 TB compressed .zip file:

$ git clone https://bamsoftware.com/git/zipbomb.git; cd zipbomb
$ zipbomb --mode=quoted_overlap --num-files=65534 --max-uncompressed-size=4292788525 > backupkeys.zip

Finally, as a defender is observing and drilling down on the attacker, they will want to identify them and hopefully bring them to justice or hold them responsible for these attacks. A key aspect of this is attributing or identifying the attacker. While this can be an entire arena and specialty unto itself, there are some neat, deceptive tricks the defense can use. One technique I've used to great success against real attackers is creating fake datasets, such as unique users and hashes that I knew a specific attacker was going to take. Later, when these dummy creds and fake data surfaced on the dark web as a data dump, we knew this was our attacker or a reseller, giving us another data point to attempt to deanonymize and identify specific attackers in the physical world. This is a risky technique because it involves simulating a breach, although it should be easy to prove a fake dataset from real users by comparing it to your real user base. One way to make fake datasets stick out more is to seed a known fake user into them, such that you can easily search for this user in the dataset to determine if it is your purposefully leaked data.

You can also use these leaked accounts as phishing bait, or honey accounts, by submitting them to phishing portals then setting alerts for when these accounts are used. Having multiple points of telemetry on an attacker that you can definitively tie together is immensely helpful when working toward attribution on that attacker. We will revisit more of these techniques in the next chapter with a focus on leveraging these tricks to deanonymize and get an advantage over the attacker.

We can see many of the deceptive and tricky techniques that we have explored in this chapter in the following kill chain diagram. Specifically, note how the defender can get early alerting on the attacker by using backdoored applications they place around the system. Once the defender has reliable alerting that the host is compromised, they can begin to perform a deeper forensic analysis, using memory forensics techniques or dead disk forensic techniques, to find the attacker's hidden technology at play:

Figure 5.3: Layered defensive utilities create multiple trip points for an attacker, even when they actively tamper with defensive controls

Summary

In this chapter, we explored many techniques for manipulating and deceiving the opponent into collecting false or useless data about the environment. The concept of tampering with logs and host-based telemetry can take an attacker further, but these techniques are still detectable from a forensics point of view. Being able to tell when a system is not reporting proper telemetry as a defender is critical to understanding when there is foul play. We saw in practice how multiple data sources could point out when one source has been tampered with. From the attacker's perspective we took the idea of hiding data to the extreme by showing a common rootkit, how to use it, and later looked at multiple techniques for detecting rootkits. We deep dived into various rootkit detection techniques, showing how we could use various datasets to discover and investigate such extremely deceptive tools. Later in the defensive section, I showed several tried-and-true techniques for both misdirecting the attacker and tricking them to gain more information or frustrate them. We also explored several common utilities an attacker may leverage on a host, and techniques where the defender can remove or even backdoor these common utilities as a way to delay or set traps for the attacker. In the next chapter, we will take this even further by exploring real-time techniques to counter the opposition, block their access, and ultimately stop them through various means.

References

  1. Simple userland rootkit – A case study: https://blog.malwarebytes.com/threat-analysis/2016/12/simple-userland-rootkit-a-case-study/#:~:text=Rootkits%20are%20tools%20and%20techniques,being%20noticed%20by%20system%20monitoring
  2. Eventlogedit-evtx--Evolution – A project devoted to different event log clearing techniques: https://github.com/3gstudent/Eventlogedit-evtx--Evolution
  3. Windows XML event log Editing: https://3gstudent.github.io/Windows-XML-Event-Log-(EVTX)%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E6%B8%85%E9%99%A4-%E4%BA%8C-%E7%A8%8B%E5%BA%8F%E5%AE%9E%E7%8E%B0%E5%88%A0%E9%99%A4evtx%E6%96%87%E4%BB%B6%E7%9A%84%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E8%AE%B0%E5%BD%95
  4. danderspritz-evtx – The event log cleaning code from the leaked NSA toolkit: https://github.com/fox-it/danderspritz-evtx
  5. EventCleaner – A project for removing Windows event logs: https://github.com/QAX-A-Team/EventCleaner
  6. How to crash the Windows' event logging Service: https://limbenjamin.com/articles/crash-windows-event-logging-service.html
  7. apache2_BackdoorMod: https://github.com/VladRico/apache2_BackdoorMod
  8. dragon – An older Windows service and WinPcap backdoor: https://github.com/Shellntel/backdoors
  9. Windows-Rootkits – An assorted collection of Windows rootkits: https://github.com/LycorisGuard/Windows-Rootkits
  10. Reptile – Linux loadable kernel module rootkit: https://github.com/f0rb1dd3n/Reptile
  11. khook – A simplified Linux kernel hooking engine: https://github.com/milabs/khook
  12. khook – Deep-dive on the Linux kernel hooking framework: https://dk72njlsmbogubz637bkapyxvm--www-cnblogs-com.translate.goog/likaiming/p/10970543.html
  13. kmatryoshka – A framework for loading objects into an lkm: https://github.com/milabs/kmatryoshka
  14. The rootkit Reptile's local cli usage: https://github.com/f0rb1dd3n/Reptile/wiki/Local-Usage
  15. Reptile hiding its kernel module: https://github.com/linux-rootkits/Reptile/blob/master/rep_mod.c#L145
  16. The Five D's of Defense: https://alamom.com/5defense/
  17. Converting PCAP Web Traffic to Apache Log – Xavier Merten's Lua Script: https://isc.sans.edu/forums/diary/Converting+PCAP+Web+Traffic+to+Apache+Log/23739/
  18. Haka Security, a framework for alerting on pcap data: http://www.haka-security.org/
  19. The LD_PRELOAD trick: www.goldsborough.me/c/low-level/kernel/2016/08/29/16-48-53-the_-ld_preload-_trick/
  20. rkhunter – Linux rootkit detection tool: https://en.wikipedia.org/wiki/Rkhunter
  21. processdecloak: https://github.com/sandflysecurity/sandfly-processdecloak
  22. unhide – Linux rootkit detection tool: https://linux.die.net/man/8/unhide
  23. Linux Memory Forensics Part 2 – Detection Of Malicious Artifacts: https://www.otorio.com/resources/linux-memory-forensics-part-2-detection-of-malicious-artifacts/
  24. SANS: Discovery of a Rootkit: https://web.archive.org/web/20210216065908/https://digital-forensics.sans.org/community/papers/gcfa/discovery-rootkit-simple-scan-leads-complex-solution_244
  25. Portspoof – A unique approach to countering network scanning: https://drk1wi.github.io/portspoof
  26. LaBrea – Old-school network tarpit utility: https://github.com/Hirato/LaBrea
  27. Description of Windows TCP features: https://docs.microsoft.com/en-us/troubleshoot/windows-server/networking/description-tcp-features
  28. Tarpit functionality added to iptables with Xtables-addons: https://inai.de/projects/xtables-addons/
  29. Mathias Jessen - Attack Surface Reductions for Adventurous Admins: https://youtube.com/watch?v=KVYtPpxj_S0&t=2167
  30. RansomTraps – Ransomware early detection project: https://github.com/DrMint/Anti-Ransomware
  31. Zip bomb basics: https://en.wikipedia.org/wiki/Zip_bomb
  32. The classic 42.zip zip bomb: https://www.unforgettable.dk/
  33. A better zip bomb: https://www.bamsoftware.com/hacks/zipbomb/
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
44.199.241.53