Skip to content

Piggy Frotress

  • #Project
  • #Cybersecurity
Read time: 3 minutes
Zane LI
Zane LI

SQL Injection

Website LogicπŸ”—

Team members hid the link to this page in the user diary, but there are many other ways to get the running port of this page. You can view the source code in var/www/html (but the service runs in docker, this is only used as a source code reference to find vulnerabilities).

Brief analysis of key documentsπŸ”—

πŸ“ login_create.php
if (isset($_POST['submit']))
{
    # Validating the user input........
    //$username=  $_POST['username'] ;
    $username = mysqli_real_escape_string($con, $_POST['username']);
    $pass = mysqli_real_escape_string($con, $_POST['password']);
    $re_pass = mysqli_real_escape_string($con, $_POST['re_password']);
    
    echo "<font size='3' color='#FFFF00'>";
    $sql = "SELECT COUNT(*) FROM users WHERE username='$username'";
    $res = mysqli_query($con, $sql) or die('You tried to be smart, Try harder!!!! :( ');
    $row = mysqli_fetch_row($res);

    //print_r($row);
    if (!$row[0] == 0) 
    {
        ?>
        <script>alert("The username Already exists, Please choose a different username ")</script>;
        <?php
        header('refresh:1, url=new_user.php');
    } 
    else 
    {
        if ($pass == $re_pass)
        {
            # Building up the query........
            $sql = "INSERT INTO users (username, password) VALUES (\"$username\", \"$pass\")";
            mysqli_query($con, $sql) or die('Error Creating your user account,  : ' . mysqli_error($con));
            echo "</br>";
            echo "<center><img src=../images/Less-24-user-created.jpg><font size='3' color='#FFFF00'>";   				
            //echo "<h1>User Created Successfully</h1>";
            echo "</br>";
            echo "</br>";
            echo "</br>";					
            echo "</br>Redirecting you to login page in 5 sec................";
            echo "<font size='2'>";
            echo "</br>If it does not redirect, click the home button on top right</center>";
            header('refresh:5, url=index.php');
        }
        else
        {
            ?>
            <script>alert('Please make sure that password field and retype password match correctly')</script>
            <?php
            header('refresh:1, url=new_user.php');
        }
    }
}
?>

</body>
</html>
  • login_create.phpΒ summary: First, it receives the username and password values ​​submitted by the user, and escapes them using the mysql filter function. Next, it queries the input user to see if it exists. If it does, registration will fail.
    After the judgment, it checks whether the two passwords are consistent. If they are, the record is inserted into the database. Otherwise, the two passwords are inconsistent.
πŸ“ pass_change.php
if (!isset($_COOKIE["Auth"]))
{
	if (!isset($_SESSION["username"])) 
	{
   		header('Location: index.php');
	}
	header('Location: index.php');
}
?>
<?php
//including the Mysql connect parameters.
include("../sql-connections/sqli-connect.php");
if (isset($_POST['submit']))
{
	# Validating the user input........
	$username= $_SESSION["username"];
	$curr_pass= mysqli_real_escape_string($con1, $_POST['current_password']);
	$pass= mysqli_real_escape_string($con1, $_POST['password']);
	$re_pass= mysqli_real_escape_string($con1, $_POST['re_password']);
	
	if($pass==$re_pass)
	{	
		$sql = "UPDATE users SET PASSWORD='$pass' where username='$username' and password='$curr_pass' ";
		$res = mysqli_query($con1, $sql) or die('You tried to be smart, Try harder!!!! :( ');
		$row = mysqli_affected_rows($con1);
		echo '<font size="3" color="#FFFF00">';
		echo '<center>';
		if($row==1)
		{
			echo "Password successfully updated";
		}
		else
		{
			header('Location: failed.php');
			//echo 'You tried to be smart, Try harder!!!! :( ';
		}
	}
	else
	{
		echo '<font size="5" color="#FFFF00"><center>';
		echo "Make sure New Password and Retype Password fields have same value";
		header('refresh:2, url=index.php');
	}
}
?>
<?php
if(isset($_POST['submit1']))
{
	session_destroy();
	setcookie('Auth', 1 , time()-3600);
	header ('Location: index.php');
}
?>
  • First, check whether you are logged in, use the Auth cookie to judge, if not logged in, redirect to the home page, if the form is submitted, first filter the username and password, and then perform a nested if to determine whether the two passwords are consistent. If they are consistent, directly splice the username into the SQL statement, otherwise, prompt inconsistency and redirect to fail.php.

Ideas Breakdown:πŸ”—

  • User Creation and Input Filtering:
    (login_create.php line20)

$username = mysql_escape_string($_POST['username']);

  • In this line of code, mysql_escape_string() is used to escape the $_POST['username'] input. This function prevents direct SQL injection by escaping special characters:Because of this, attempting to inject SQL directly during user creation becomes difficult, as special characters like quotes are properly escaped.
    • Backslash (\) is escaped as double backslash (\\);
    • Single quote (') is escaped as escaped single quote (\').
  • Potential Injection in Password Update:
    login_create.php line25

UPDATE users SET PASSWORD='$pass' WHERE username='$username' AND password='$curr_pass';

  • This SQL statement is used to update the user's password, where $username and $curr_pass are values taken directly from user input (e.g., from a form submission).The author points out a possible injection vulnerability here:
    • $username is directly concatenated into the SQL query without proper sanitization. If an attacker sets the username value to admin'#, the SQL query would be transformed into:

UPDATE users SET PASSWORD='$pass' WHERE username='admin'# AND password='$curr_pass';

  • Injection Result: In SQL, the # symbol is used to comment out the rest of the query. As a result, everything after # (including AND password='$curr_pass') gets ignored. The final SQL query would be:

UPDATE users SET PASSWORD='$pass' WHERE username='admin';

  • This allows the attacker to bypass password verification, as the condition AND password='$curr_pass' is effectively removed. Therefore, the attacker can update the admin password without needing to know the current password.

Attack ProcessπŸ”—

1. Create a New User:πŸ”—
  • set user name: admin'#zy
  • set password: 12345
2. Login admin'#zyπŸ”—
  • admin'#zy
  • 12345
3. change the password into 123πŸ”—
  • This will trigger
    • UPDATE users SET PASSWORD='$pass' WHERE username='admin'# AND password='$curr_pass';
  • admin password now changing into 123
  • admin
  • 123
5. Now we have two more questions.πŸ”—