Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

---Please find a secure way so sql injection won\'t happen Zap\' 1=1 <html> <hea

ID: 3835691 • Letter: #

Question

---Please find a secure way so sql injection won't happen Zap' 1=1

<html>

   <head>

   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <link rel="stylesheet" type="text/css" href="Rehema.css">

   <title>CSTutot Authenticate</title>

</head>

<body>

<?php

      

   // Needed For SQLFunctions getFaculty call

   require_once('Includes/SQLFunctions.php');

  

   // Needed For Utils check_input call

   require_once('Includes/Utils.php');

  

  

  

   // Retrieve Post Data

   $wsuser = check_input($_POST["wsuser"]);  

   $wsemail = check_input($_POST["wsemail"]);  

  

   // Authenticate User

   $student = getStudent($wsuser,$wsemail);      

        if (strlen($student->getTychoname())==0)

        {

         // Show the login form again.

       include('index.html');  

   ?>

         <p></p>

   <p></p>

   <div><table id="myerror">

   <tr><td>             

   <h4>Login Error</h4>

   </td></tr>

   <tr><td>

   Sorry, the username and email do not match any current account.

   </td></tr>

   <tr><td>  

   Try again, or create an account using the link above.

   </td></tr>

   </table>

   </div>

<?php  

   }          

        else

        {

            // Set the session information

                      session_start();

                      $_SESSION['wsuser'] = $wsuser;                     

                    include('SearchSessions.php');  

        }

?>

</body>

</html>

Explanation / Answer

To avoid SQL injection and to handle Zap' 1=1 condition, update the sql query in a manner such that its not concatenating the user input directly with the query.

To prevent this,

1.  Try to remove or escape any possible SQL code from user input before concatenating it with the SQL code to be executed

2.  Use parameterized queries: Define the SQL code that is to be executed with placeholders for parameter values, programmatically adding the parameter values, then executing the query. Doing this allows the server to create an execution plan for the query, which prevents any “injected” SQL from being executed.

In above code snippet,

a. Create an array of username and password which will be passed to the backend to get data.

b. Use, sqlsrv_query to execute the parameterized query.

e.g., $stmt = sqlsrv_query($conn, $sql, $params);

c. When sqlsrv_query is called, an execution plan is created on the server before the query is executed. Parameter values (even if they are injected SQL) won’t be executed because they are not part of the plan. So, if a password like 1=1 is submitted, it will be treated as user input and not SQL code.