LAB_02 / SYSTEM Intermediate

One text field. Shell access. Find where the risk begins.

Experiment hint

First, try ordinary input. Then use an example from the lesson and compare the result in the vulnerable and protected variants. The code panels highlight the boundaries relevant to the attack or defense.

Command Injection

01 / THEORY · ⚠ VULNERABLE CODE

Vulnerable variant

Command Injection lets an attacker run operating system commands through a vulnerable application. In this variant, user input is concatenated directly into a system command. For example, consider this code that runs ping:

                        
                        if (isset($_GET['ip'])) {
                            $ip = $_GET['ip'];
                            $output = shell_exec($pingCommand . $ip);
                            echo nl2br($output);
                        }
                        
                    
The command is built by concatenating a string with user input. Shell operators such as ; & && | || can change how the shell interprets the command. An attacker can use them to run additional commands on the server.

The example form runs ping for the entered IP address. In the vulnerable variant, input is passed directly to the shell, so it can contain an additional command.
Try entering an IP address followed by whoami, which prints the account running the command. Use the following payload (input designed to demonstrate the vulnerability):

                        
                            127.0.0.1; whoami
                        
                    

02 / EXPLOIT · TEST THE INPUT

The output includes both the ping result and the account executing it. The same vulnerability can allow other commands to read, modify or delete files. To list files in the current working directory, try:

                        
                            127.0.0.1; ls
                        
                    

03 / DEFENSE · ✓ PROTECTED CODE

How the defense works

Avoid building shell commands from raw user input. If an application must invoke a command, validate the input and restrict the commands that can be run. The escapeshellarg() function quotes an argument so shell operators inside it are treated as data rather than as commands. The following example uses it with ping:

                        
                            if (isset($_GET['ip'])) {
                                $ip = escapeshellarg($_GET['ip']);
                                system($pingCommand . $ip);
                            }
                        
                    
The input becomes one quoted argument. This prevents it from changing the shell command structure.

Try the same payload in the protected form. It is passed as a single argument rather than executed as an additional shell command. The command may reject it as an invalid address.