180 likes | 198 Views
Understand what SQL injection is, how attackers can exploit it to steal sensitive information or gain unauthorized access, and learn about solutions to prevent SQL injection attacks.
E N D
PHP-part3 Spring 2018 Dr Emad Nabil Lec#9
What is SQL Injection? • an attacker can inject or execute malicious SQL code via the input data from the browser to the application server, such as web-form input. • The purpose is to: • steal sensitive information like user's contact numbers, credit card information and so on. • bypass authentication process and get access to the entire database.
anything cn '; drop table tmp;--
SQL injection Example To login the following SQL statement is executed on the DB If username = john and password = 123, then the SQL will look like: Now consider that the user write username = ‘ OR ‘x’=‘x and password = ‘ OR ‘x’=‘x The SQL statement will look like ‘ ‘ OR ‘x’=‘x’
cn Check example on notes of this slide
cn <html> <body> <form action="<?php $_SERVER['PHP_SELF']?>" method="post"> <table width="50%"> <tr> <td>User</td> <td><input type="text" name="username"></td> </tr> <tr> <td>password</td> <td><input type="password" name="password"></td> </tr> </table> <input type="submit" value="OK" name="send"> </form> </body> </html> <?php //write in the two textboxes the value //' or 'x'=‘x //or the value // ' or ''=''and username <> ‘ahm if ($_POST['send']) { $user = $_POST['username']; $pass = $_POST['password']; ////////////////////////////////////////////////////////// $servername = "localhost"; $username = "root"; $password = "temp1234"; $dbname = "demo"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "select * from users where username = '$user' and password = '$pass'"; $records = $conn->query($sql); $results = $records->fetchAll(PDO::FETCH_ASSOC); $total = count($results); if ($total > 0) { $row= $results[0]; echo "successful login, welcome: ".$row['username']; } else { echo "invalid username or password"; } } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; } ?>
Solution for SQL injection The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally, and not as part of the SQL to be executed.
Problem solution cn The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally, and not as part of the SQL to be executed. The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it
cn PDO select output
Select cn
Without checking remember checkbox cn Code in PPT notes