Posts Tagged

php

Zero Day Twig PHP template engine

Twig is a modern template engine for PHP, its flexible, fast, and secure template engine for PHP.If you have any exposure to other text-based template languages, such as Smarty, Django, or Jinja, you should feel right at home with Twig. It’s both designer and developer friendly by sticking to PHP’s principles and adding functionality useful for templating environments.

ExploitDB link:

https://www.exploit-db.com/exploits/44102

Well, Twig {Latest version} is affected to Server-Side Template Injection and {{Command execution}}.

Exploit:

Twig <=2.4.4 contain SSTI vulnerability which allow attackers to execute commands within the Parameters, by just using {{COMAND TO EXECUTE}} instead of using the expected values “Normal integer or normal string”, depends on the vulnerable application, which takes deferent params by GET or POST.

1.POC:

Example: by injecting this in a search param http://localhost/search?search_key={{4*4}} >        Output: 16

2. POC:

http://localhost/search?search_key={{4*4}}

http://localhost/search?search_key={{ls}}

OUTPUT: list of files/directories etc….

See the screenshot bellow how its executing the command and printing out the results, this could be also {{ rm * }} which will delete the entire application 🙂

PHP and MySQL: Secure coding

php mysql secure coding

With all the languages out there used by websites, one of the most dynamic ones is PHP, mostly used in websites such as Amazon, Wikipedia, and Facebook.

PHP is very popular to use, generally because it is easy to learn, easy to install and does not require the user to write code.

Yet, in spite of PHP’s popularity, security is not a very popular issue among its users.

For this reason, in order to make your PHP apps more secure, I will be explaining how you can do that.

One of the solutions is creating a PHP web app that connects to a MySQL back end database.

This will create a layered security structure.

There is no definite method of blocking attacks, but using the layered security concept, we can limit our exposure to them.

Two of the attacks we will lessen are SQL Injection (SQLi) and Cross Site Scripting (XSS). Both of these attacks are performed by taking advantage of applications that do not properly handle user input.

 

XSS happens when an application sends the users browser back input that has not been checked for code. If an attacker were to enter something similar to the text below in a form field, it would cause the browser to execute the code and create a pop up on the screen displaying the text “XSS”.

”&gt;&lt;script&gt;alert(‘XSS’)&lt;/script&gt;

Similarly SQLi is caused by an attacker running unplanned SQL code against the database. An example would be if an attacker were to enter the following in a form, the browser would display all the data in the user table:

;select * from users;

I will use PHP built-in methods such as htmlspecialchars(), mysqli_real_escape_strings() and use prepared statements to help prevent the attacks mentioned above.

In this training contact  list app example , the database will store the following fields:

  • First Name
  • Last Name
  • email address

securecodingexample1

 

As a privileged user I ran the following code to create the database.it is attached at the end of this post as createdb.sql.

mysql -uroot -p -h 127.0.0.1 mysql

CREATE DATABASE `contactsSchema` ;
USE contactsSchema;
CREATE TABLE `contactsTable` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `first` VARCHAR(40) DEFAULT NULL,
    `last` VARCHAR(64) DEFAULT NULL,
    `email` VARCHAR(256) DEFAULT NULL
    PRIMARY KEY (`id`)
) ENGINE=InnoDB; 
CREATE USER 'contactsUser'@'localhost' identified by 'superSecretPassword';
GRANT SELECT, INSERT, UPDATE, DELETE
    ON contactsSchema.contactsTable TO 'contactsUser'@'localhost';

INSERT INTO contactsTable (id, first, last, email)
values(null, 'Alexander', 'Bell', 'alexander@bell.com');

For the application, I will drop the authenticated login functionality that will be discussed in a later post .

In the PHP page, which is attached at the bottom as index.php, you will see some  PHP code that makes this contacts app more secure.

1. strip_tags()

#User passed in vars
isset ( $_REQUEST['i'] ) ? $i = strip_tags($_REQUEST['i']) : $i = "";
isset ( $_REQUEST['s'] ) ? $s = strip_tags($_REQUEST['s']) : $s = "";

I am only allowing variables from the user that I am specifying. Next I am running strip_tags() on them to remove any html tags in the text. This however does not get all extra characters.

2. mysqli_real_escape_string()

$first=mysqli_real_escape_string($db, $first);

In the above code snippet, the mysqli_real_escape_string() method is used to escape any special characters.
This is used as the variable is provided by the user. Anything the user enters should be sanitized.
However mysqli_real_escape_string() does not protect against all threats.

3. Prepared Statement

if ($stmt = mysqli_prepare($db,
 "INSERT INTO contactsTable SET first=?, last=?, email=?, id=''")) {

               mysqli_stmt_bind_param($stmt, "sss", $first, $last, $email);
               mysqli_stmt_execute($stmt);
               mysqli_stmt_close($stmt);
}

In this code we are using prepared statements to limit the functionality of the query.
In this example, I am only passing in variables to execute in this query,
it prevents nested queries, which are a common SQLi attack.

 

4. htmlspecialchars()

function displayResults($first, $last, $email) {

       echo "&lt;tr&gt; &lt;td&gt;" . htmlspecialchars($first)  . "&lt;/td&gt;";
       echo "&lt;td&gt;" . htmlspecialchars($last)  . "&lt;/td&gt;";
       echo "&lt;td&gt;" . htmlspecialchars($email)  . "&lt;/td&gt;&lt;/tr&gt;";
}

In the above example, I am disabling code that may be stored in the database or passed in by the end user from being rendered as executable html in the browser. The command htmlspecialchars() replaces characters like < with markup equivalent such as &LT;.

Conclusion

In this example application, I have applied multiple layers of security to prevent attacks such as cross site scripting and SQL injection. Clearly this is a simple application, but the code is reusable and you can build on it when you create your own applications.

Code Examples Used in Writeup:

createdb.sql

CREATE DATABASE `contactsSchema` ;
USE contactsSchema;
CREATE TABLE `contactsTable` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `first` VARCHAR(40) DEFAULT NULL,
    `last` VARCHAR(64) DEFAULT NULL,
    `email` VARCHAR(256) DEFAULT NULL
    PRIMARY KEY (`id`)
) ENGINE=InnoDB; 
CREATE USER 'contactsUser'@'localhost' identified by 'superSecretPassword';
GRANT SELECT, INSERT, UPDATE, DELETE
    ON contactsSchema.contactsTable TO 'contactsUser'@'localhost';

INSERT INTO contactsTable (id, first, last, email)
values(null, 'Alexander', 'Bell', 'alexander@bell.com');

Index.php

&lt;?php
//file: index.php 
//purpose: example contact list
//version: 1.0 
//date: 2012/08/30
#User passed in var run strip tags on input
isset ( $_REQUEST['i'] ) ? $i = strip_tags($_REQUEST['i']) : $i = "";
isset ( $_REQUEST['s'] ) ? $s = strip_tags($_REQUEST['s']) : $s = "";
isset ( $_REQUEST['st'] ) ? $st = strip_tags($_REQUEST['st']) : $st = "";
isset ( $_REQUEST['first'] ) ? $first = strip_tags($_REQUEST['first']) : $first = "";
isset ( $_REQUEST['last'] ) ? $last = strip_tags($_REQUEST['last']) : $last = "";
isset ( $_REQUEST['email'] ) ? $email = strip_tags($_REQUEST['email']) : $email = "";

#Database Connection 
function connectDB(&amp;$db){
 $db_host='localhost';
 $db_user='contactsUser';
 $db_pass='superSecretPassword';
 $db_name='contactsSchema';
 $db = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
 if (mysqli_connect_errno()) {
 print "&lt;br&gt; Houston we have a problem! &lt;br&gt;
 There seems to be an error connecting to the MySQL Database. 
 &lt;br&gt; The error we hit was: &lt;br&gt; " . htmlspecialchars(mysqli_connect_error()) .
 "&lt;br&gt; error code " . htmlspecialchars(mysql_errno());
 exit;
 }
}
//Add new entries to DB
function addContact($db, $first, $last, $email) { 
 $first=mysqli_real_escape_string($db, $first);
 $last=mysqli_real_escape_string($db, $last);
 $email=mysqli_real_escape_string($db, $email);
 if ($stmt = mysqli_prepare($db, "INSERT INTO contactsTable SET first=?, last=?, email=?, id=''")) {
 mysqli_stmt_bind_param($stmt, "sss", $first, $last, $email); 
 mysqli_stmt_execute($stmt); 
 mysqli_stmt_close($stmt);
 } else {
 echo "Error Adding Contact";
 }
}
//Table Header 
function resultTableHeader() {
 echo "&lt;table width=60%&gt;
 &lt;tr&gt; &lt;td bgcolor=#D8D8D8 width=30%&gt; &lt;b&gt;&lt;u&gt; First &lt;/b&gt; &lt;/u&gt; &lt;/td&gt;
 &lt;td bgcolor=#D8D8D8 width=30%&gt; &lt;b&gt;&lt;u&gt; Last &lt;/b&gt; &lt;/u&gt; &lt;/td&gt; 
 &lt;td bgcolor=#D8D8D8 width=40%&gt; &lt;b&gt;&lt;u&gt; eMail &lt;/b&gt; &lt;/u&gt; &lt;/td&gt; &lt;/tr&gt;";
}
//Results Display
function displayResults($first, $last, $email) {
 echo "&lt;tr&gt; &lt;td&gt;" . htmlspecialchars($first) . "&lt;/td&gt;";
 echo "&lt;td&gt;" . htmlspecialchars($last) . "&lt;/td&gt;";
 echo "&lt;td&gt;" . htmlspecialchars($email) . "&lt;/td&gt;&lt;/tr&gt;";
}
//Coonect to the DB to begin
connectDB($db);
echo "
&lt;html&gt;
&lt;head&gt;
&lt;title&gt; Contacts &lt;/title&gt; 
&lt;/head&gt;
&lt;body&gt; 
&lt;center&gt;
&lt;h3&gt; Contact List &lt;/h3&gt;
&lt;table width=60%&gt; 
&lt;tr&gt;
 &lt;td bgcolor=#D8D8D8 width=30%&gt; &lt;a href=index.php?s=1&gt;Add New &lt;/a&gt; &lt;/td&gt;
 &lt;td bgcolor=#D8D8D8 width=30%&gt; &lt;a href=index.php?s=2&gt;Search&lt;/a&gt; &lt;/td&gt;
 &lt;td bgcolor=#D8D8D8 width=40%&gt; &lt;a href=index.php&gt;Back&lt;/a&gt; &lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
";
if ($s == Null) { //If no options, just query the whole table
 resultTableHeader();
 $query="SELECT first, last, email FROM contactsTable"; 
 $result=mysqli_query($db, $query); 
 while($row=mysqli_fetch_row($result)) {
 displayResults($row[0], $row[1], $row[2]);
 }
 echo "&lt;/table&gt;";
}elseif ($s == 1) { //Add new entry
 if ($first == Null) { //If we don't have user input yet
 echo "&lt;form method=post action="index.php"&gt; ";
 resultTableHeader();
 echo " 
 &lt;td&gt; &lt;input type=text name="first" value=""&gt;&lt;/input&gt; &lt;/td&gt; 
 &lt;td&gt; &lt;input type=text name="last" value=""&gt;&lt;/input&gt; &lt;/td&gt; 
 &lt;td&gt; &lt;input type=text name="email" value=""&gt;&lt;/input&gt; &lt;/td&gt; 
 &lt;tr&gt; &lt;td colspan=3 align=center&gt;&lt;input type=hidden name="s" value="1"&gt;
 &lt;input type=submit name="Submit" value="Submit"&gt; &lt;/td &lt;/tr&gt;
 &lt;/table&gt;";

 } elseif ($first != Null) {
 addContact($db, $first, $last, $email) ;
 echo "Added new Entry &lt;br&gt;" . 
 htmlspecialchars($first) . "&lt;br&gt;" .
 htmlspecialchars($last) . "&lt;br&gt;" . 
 htmlspecialchars($email) . "&lt;br&gt;";
 }
}elseif( $s == 2) {
 if ($st == Null) { 
 echo "Enter Search Term: 
 &lt;form method=post action="index.php"&gt;
 &lt;input type=text name="st" value=""&gt; 
 &lt;input type=hidden name="s" value="2"&gt;
 &lt;input type=submit value="Submit" name="Submit"&gt; 
 &lt;/form&gt;" ;
 } else { 
 $st=mysqli_real_escape_string($db, $st);
 resultTableHeader();
 if ($stmt = mysqli_prepare($db, "SELECT first, last, email FROM contactsTable WHERE 
 first LIKE CONCAT('%', ? ,'%') or
 last LIKE CONCAT('%', ? ,'%') or
 email LIKE CONCAT('%', ? ,'%')")){
 mysqli_stmt_bind_param($stmt, "sss", $st, $st, $st); 
 mysqli_stmt_execute($stmt); 
 mysqli_stmt_bind_result($stmt, $first, $last, $email);
 while(mysqli_stmt_fetch($stmt)) {
 displayResults($first, $last, $email);
 }
 mysqli_stmt_close($stmt);
 }
 echo "&lt;/table&gt; ";
 } 
}
echo " 
 &lt;/center&gt;
 &lt;/body&gt;
&lt;/html&gt;";
?&gt;