1 / 39

SQL with PHP and SQL Injection Attacks

SQL with PHP and SQL Injection Attacks. Basic PHP Syntax. <html> <head><title>Hello World</title></head> <body> <?php echo ‘ <p>Hello, how are you?</p> ‘ ; ?> <p>This will be ignored by PHP.</p> <?php print( ‘ <p> welcome to my web site! </p>' ); ?> <?php

Download Presentation

SQL with PHP and SQL Injection Attacks

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SQL with PHP and • SQL Injection Attacks

  2. Basic PHP Syntax <html> <head><title>Hello World</title></head> <body> <?php echo ‘<p>Hello, how are you?</p>‘; ?> <p>This will be ignored by PHP.</p> <?php print(‘<p>welcome to my web site! </p>'); ?> <?php //This is a comment in PHP /* This is a comment block in PHP */ ?> </body> </html>

  3. Basic PHP Syntax output:

  4. Scalars All variables in PHP start with a $ sign symbol. A variable's type is determined by the context in which that variable is used <html> <body> <p> <?php $boolvar = True; if ($boolvar) echo "It is TRUE! <br> "; $mystr='1234'; echo "String is $mystr <br>"; $a = 1234; echo "Integer is $a <br />"; $a = 314.2E-2; echo "Float is $a <br />"; echo 'Arnold said: "I\'ll be back"', "<br /> "; $str = <<<EOD An example of a string that spans Multiple lines EOD; echo $str; ?> </p> </body></html> <p><br> line <br/><br> line2<br/><p/> br:line brak, <p> paragraph. <<<EOD EOD like “” with multiple lines. ‘‘ for simple strings and “” for strings with variables, etc.

  5. Scalars

  6. Arrays <html> <body> <?php $arr = array("foo" => "bar", 3 => true); $arr[4] = "barrr"; echo 'Array elements are ' . $arr["foo"]. ','. $arr[3]. ','. $arr[4]. "<br>"; echo 'Array length (before delete) is ‘. ‘,’. count($arr).’,’ '<br>'; unset($arr[3]); // delete element 3 echo 'Array length (after delete) is ‘.’,’ count($arr).’,’. '<br>'; $array = array(1, 2, 3, 4, 5); print_r($array); ?> </body></html>:w

  7. Arrays

  8. Operators Arithmetic Operators:+, -, *,/ , %, ++, -- Assignment Operators:=, +=, -=, *=, /=, %= Comparison Operators:==, !=, >, <, >=, <= Logical Operators:&&, ||, ! String Operators: . , .=

  9. Conditionals: if else <html><head></head> <body> <?php $d=date("D"); echo "Today is ", $d, "day <br>"; $ctime = localtime(time(), true);true returns associative array if ($ctime["tm_hour"]==12) { echo "The local time now is 12:", $ctime["tm_min"], "pm <br>"; } else if ($ctime["tm_hour"]>12) { echo "The local time now is ", $ctime["tm_hour"]-12,":", $ctime["tm_min"], "pm <br>"; } else { echo "The local time now is ", $ctime["tm_hour"], ":", $ctime["tm_min"], "am <br>"; } ?> </body> </html>

  10. Conditionals: if else

  11. Looping: while <html><head></head> <body> <?php $array = array(5, 4, 3, 2, 1); $i = 0; while ($i < 5) { echo "Element $i is ", $array[$i], "<br>"; $i++; } ?> </body> </html>

  12. Looping: while

  13. Looping: for and foreach <html><head></head> <body> <?php $array = array(5, 4, 3, 2, 1); for ($i=0; $i<5; $i++) { echo "Element $i is ", $array[$i], "<br>"; } $i=0; foreach ($array as $value) { echo "Element $i is ", $value, "<br>"; $i++; } ?> foreach is good for associative array </body> </html>

  14. Looping: for and foreach

  15. User Defined Functions <html><body> <?php $array = array(5, 4, 3, 2, 1); function quicksort($myarray) { $len = count($myarray); if ($len <= 1) return $myarray; $pivot = $myarray[$len-1]; unset($myarray[$len-1]); foreach ($myarray as $value) { if ($value < $pivot) $less[] = $value; // append $value to less elseif ($value > $pivot) $more[] = $value; // append $value to more else $equal[] = $value; // append $value to equal } $result = quicksort($less); $result[] = $pivot; if (count($equal) > 0) $result = array_merge($result, $equal); $result = array_merge($result, quicksort($more)); return $result; } echo 'Before sorting: '; print_r($array); echo '<BR>'; $array = quicksort($array); echo 'After sorting: '; print_r($array); ?> </body></html>

  16. User Defined Functions

  17. Server Variables The $_SERVER is a variable that contains system information <html><head></head> <body> <?php echo "User's IP address: ".$_SERVER["REMOTE_ADDR"]. "<br>"; echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br>"; echo "Browser: " . $_SERVER["HTTP_USER_AGENT"]; ?> </body> </html>

  18. Server Variables output: User's IP address: 123.4.56.111 Referer: Browser: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12

  19. Form Handling <html> <body> <form action="welcome.php" method="POST"> <p>Enter your name: <input type="text" name="name" /> <br> <p>Enter your age: <input type="text" name="age" /> <br> <p><input type="submit" /> <input type="reset" /> </form> </body> </html> USER clicks the SUBMIT: FORM data goes to welcome.php. POST:Collect values from the FORM, GET: Collect values but make it public. Get is not good for passing PW, for example <html> <body> Welcome <?php echo $_POST["name"]. ". "; ?><br> You are <?php echo $_POST["age"]; ?> years old! </body> </html> welcome.php

  20. Form Handling

  21. PHP with MySQL Connect to the database server and login $conn = mysqli_connect("host","username","password"); Choose the database mysqli_select_db($conn, "database"); Submit SQL queries to insert/delete/update data mysqli_query( $conn, "query"); Close the connection to the database server mysqli_close($conn);

  22. PHP with MySQL $conn = mysqli_connect("host","user","pwd“, “dbname"); $result=mysqli_query($conn, "SQL query"); $num=mysqli_num_rows($result); $columns=$result->fetch_fields(); $row=mysqli_fetch_row($result); // returns an array $row=mysqli_fetch_assoc($result); // returns an associative array mysqli_close($conn);

  23. Guestbook Example <html><head><title>My Guestbook</title></head> <body><h1>Welcome to my Guestbook</h1> <h2>Enter your comments below:</h2> <form action="<? echo "$PHP_SELF"?>" method="POST"> <textarea cols=40 rows=5 name="note" wrap=virtual></textarea> <p><input type="submit" value=" Submit "> </form> <? //PHP code goes here ?> <h2>The entries so far:</h2> <? //More PHP code goes here ?> </body></html>

  24. Guestbook Example <html><head><title>My Guestbook</title></head> <body><h1>Welcome to my Guestbook</h1> <h2>Enter your comments below:</h2> <form action="<? echo "$PHP_SELF"?>" method="POST"> <textarea cols=40 rows=5 name="note" wrap=virtual></textarea> <p><input type="submit" value=" Submit "> </form> <? $link = mysqli_connect('mysql-user','username','password', 'dbname'); $note = $_POST["note"]; if(isset($note)) { $ts = date("Y-m-d H:i:s"); $query = sprintf("insert into comments values('%s', '%s')", mysqli_real_escape_string($link, $note), $ts); $result = mysqli_query($link, $query); } mysqli_close($link); ?> <h2>The entries so far:</h2> <? $link = mysqli_connect('mysql-user','username','password', 'dbname'); $result = mysqli_query($link, "select * from comments"); while($row = mysqli_fetch_row($result)) { echo $row[1] ." Message: " . $row[0] . "<br>\n"; } mysqli_close($link); ?> </body></html>

  25. Guestbook Example

  26. ANY SQL Injection Attacks!

  27. What is a SQL Injection Attack? • Wikipedia: A code injection technique that exploits a security vulnerability occurring in the database layer of an application. • There are many web applications that take user input from a form • A SQL injection attack involves placing SQL statements in the user input to compromise the database system “All input is evil until proven otherwise.”Howard & LeBlanc

  28. Example Incorrect password; so no rows will be returned

  29. Example Oops! all rows will be returned because ‘x’ =‘x’ is always true SQL injection attacks try to exploit this type of vulnerability

  30. Authorization Bypass • Simplest SQL injection technique is bypassing login forms • Example: Let’s say a user fills out the logon form like this: Login: ' OR ' ' = ' Password: ' OR ' ' = ' • PHP File: $user = $_POST[“login”]; $password = $_POST[“password”] SELECT Username FROM UsersWHERE Username = '$user' AND Password = '$password'; BECOMES SELECT Username FROM Users WHERE Username = ' ' OR ' ' = ' ' AND Password = ' ' OR ' ' = ' ' i.e, Username equals empty OR empty=empty AND Password=empty OR empty=empty

  31. Another Example $SQLQuery = “SELECT * FROM users WHERE username = ‘” + user + “' AND password = ‘” + password + “';” http://www.target.com/login.asp?user=admin&password='%20OR%20‘x'=‘x $SQLquery becomes “SELECT * FROM users WHERE username = 'admin' AND password = '' OR ‘x' = ‘x';” Not a safe query for a Web-based application! You should restrict admins to have access only from a certain machine

  32. Another Example Suppose your code has the following SQL statement $query = “SELECT patient_info FROM patients WHERE SSN = ‘” . $_POST[‘user_input_patient_SSN’] . “’”; Patient SSN: This creates the following SQL: SELECT patient_info FROM patients WHERE SSN = ‘999‘ OR ‘x’ = ‘x’ Attacker has now successfully caused the entire database to be returned. 999‘ OR ‘x’ = ‘x

  33. A More Malicious Example What if the attacker had instead entered:Patient SSN: 999‘; DROP TABLE patients; - - Results in the following SQL: SELECT patient_info FROM patients WHERE SSN = ‘999’; DROP TABLE patients; --’ Note how comment (--) to deal with the final quote This will cause the entire database to be deleted Depends on knowledge of table name, which is sometimes exposed in debug code called during a database error Use non-obvious table names, and never expose them to user Usually data destruction is not your worst fear, as there is low economic motivation

  34. Other injection possibilities • Using SQL injections, attackers can: • Add new data to the database • Could be embarrassing to find yourself selling politically incorrect items on an eCommerce site • Perform an INSERT in the injected SQL • Modify data currently in the database • Could be very costly to have an expensive item suddenly be deeply ‘discounted’ • Perform an UPDATE in the injected SQL • Often can gain access to other user’s system capabilities by obtaining their password

  35. Example

  36. Example

  37. XKCD

  38. Defenses Use provided functions for escaping strings Many attacks can be thwarted by simply using the SQL string escaping mechanism '  \ ' "  \ " Example: mysqli_real_escape_string($conn, $string) or addslashes ($string) Not a silver bullet! Consider: SELECT fields FROM table WHERE id = 23 OR 1=1 No quotes here!

  39. More Defenses Check syntax of input for validity Have length limits on input Many SQL injection attacks depend on entering long strings Scan query string for undesirable word combinations that indicate SQL statements INSERT, DROP, etc. Limit database permissions and segregate users Configure database error reporting Default error reporting often gives away information that is valuable for attackers (table name, field name, etc.) Configure so that this information is never exposed to a user

More Related