Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples of vulnerable PHP code? [closed]

Tags:

Ok so me and a friend are doing a mini presentation on PHP security (I'm not really into PHP though) and he asked me to find some examples of vulnerable PHP code (one that is prone to SQL injections and all other types of attacks). I was wondering are there any websites with both good and bad pieces of code showing how you should and shouldn't code?

Basically I will put them into our website and he will try to hack it, then we will show the "proper" website and he will try to hack it again.

like image 357
Mateusz Dymczyk Avatar asked Nov 23 '09 13:11

Mateusz Dymczyk


People also ask

What is vulnerability give small example?

Vulnerability is a weakness or some area where you are exposed or at risk. If you are running for political office and you don't want anyone to find out about a scandal in your past, the scandal is an example of a vulnerability.

Is PHP a security risk?

PHP is as secure as any other major language. PHP is as secure as any major server-side language. With the new PHP frameworks and tools introduced over the last few years, it is now easier than ever to manage top-notch security.


2 Answers

A really common beginner's mistake is forget to terminate script execution after a redirect.

<?php
if ($_SESSION['user_logged_in'] !== true) {
    header('Location: /login.php');
}

omg_important_private_functionality_here();

The solution:

if ($_SESSION['user_logged_in'] !== true) {
    header('Location: /login.php');
    exit();
}

This can be missed when testing in a normal browser, because browsers usually follow the Location header without rendering any of the output of the script.

like image 35
Ben James Avatar answered Sep 23 '22 15:09

Ben James


SQL injection is easy:

$var = $_POST['var'];
mysql_query("SELECT * FROM sometable WHERE id = $var");

This is easily solved by:

$var = mysql_real_escape_string($_POST['var']);

The other common one is XSS (cross site scripting):

$var = $_POST['var'];
echo "<div>$var</div>\n";

allows you to inject Javascript that is run from your site. There are several ways of dealing with this, for example:

$var = strip_tags($_POST['var']);

and

$var = filter_var($_POST['var'], FILTER_SANITIZE_STRING);
like image 76
cletus Avatar answered Sep 23 '22 15:09

cletus