Pages

Wednesday 27 April 2011

Web Space Management System - File Upload - Part 1

This blog post will be the first part of a series of blog posts through which I will share my experience while working on the course work for my second semester – a web space management system.

I will be splitting up the course work into the following parts
  • User authentication – User registration and login functionality
  • File upload – File upload functionality
  • File management – create/delete directories, move/delete files.

This first post will focus on the file upload functionality; we will only be working on 2 files, the index.html which will contain the file input form where the user selects the files to upload and the uploadFile.php which contains the backend PHP code to handle the actual file upload.

Index.html



 The index page contains a simple html form as used in the previous blog post. Since the form will be handling files the enctpye attribute has been set to multipart/form-data and the input field type attribute has been set to file, this will allow the user to select files located on the local machine to be uploaded. The above script will post the form to the uploadFile.php page.

On chrome the above html page will be rendered as follows

 When the user clicks the choose file button an explorer window is opened for selection.

uploadFile.php


 This script takes care of the file upload process, it moved the uploaded file to the uploads/ directory and prompts the user when successful


The example above simple demonstrates the functionality that PHP offers to handle file uploads and although it works should not be used without further validations and restrictions.

Some vulnerability with this setup




  •  Users can execute PHP code on the server by uploading .php files and loading them from the browser as explained below.

  1. Upload hack.php file containing the following text <?php echo "PHP code executed on server... " ?>
  2. Load http://localhost/phpFileUpload/uploads/hack.php


As you can se from the above screenshot, the PHP code was executed.


In the next blog post I will go though the authentication system as well as how to secure the application against malicious attacks such as the one shown above.

Wednesday 13 April 2011

PHP & MySQL - Simple Guestbook

Now that we have our environment set up and ready to go, I decided it would be a good time to start experimenting with PHP, but before we go any further let's first stick to the hello, world tradition.


<?php
echo "hello, world";
?>



Ok now that the "hello, world" example is done let's start working on the real task at hand i.e. a PHP/MySQL powered guestbook.

The entire project is made up of the following 5 files.



I will go through each of the above files throughout this post.

index.php

Index.php is the main page and is the only page the user will interact with, it lists all existing guestbook entries as well as provide the user with a form to input additional entries.



Although this entire PHP application could have easily been implemented in just a single index.php file, it is considered bad practice to mix page markup with PHP code, I have therefore segregated all PHP code to separate files residing in the /include directory each of which is called whenever required using the include() or include_once() function, it is important to use the include_once() function on files which should only be executed once e.g. the MySQL connection include file, you only need the connection to be established once.

PHP includes

Line 9 - inc_mysql_conn.php is included, this assigns a database connection to the $db_conn variable which would then be available throughout the script.

Line 10 - submit_entry.php is included, this script is triggered only when the submit button is pressed and after validating the entry will insert the entry into the database.

Line 14 - list_all_entries.php is included, this script outputs all entries in the guestbook to the browser in an HTML table.

I will go through the PHP code on each of the above included files later in the post.

Input Form

The above html form submits data back to the index.php page using the post method (line 18), although for this application the get method would have been fine, I usually prefer using post over get just to keep the URL clear from any query string clutter.

There are 3 visible text fields, name, email and comment and one hidden field. Since the form is posting to itself the hidden field will be used later by submit_entry.php which will read it's value to check whether the submit button has been pressed and therefore data needs to be inserted in the database.


inc_mysql_conn.php

This php file opens a mySQL connection with the database which can later be used in any part of the application.


This script opens a connection to a MySQL server logging in with the credentials defined in the par_db.php script. Once this script is included it makes the $db_conn connection available throughout the execution which is the main reason why this is usually one of the first included script in any project. It is considered good practice to unset any variables which are no longer required.

par_db.php

This php file is used to define the mySQL connection parameters, the primary reason why this data is contained within a separate file is simply to prevent modifying files which contains functional logic whenever these parameters need to be altered.
The above script simply defines the credentials used to login to the MySQL database.

list_all_entries.php

This code will output all guestbook entries in an HTML table, this page

This script will retrieve all guest book entries from the database and iterates through each record to output an HTML table to the browser, this script is included whenever the guestbook entries are to be listed.

submit_entry.php


The above script is responsible for validating and inserting guest book entries into the database. It first checks if the form has been submitted or not, since we are posting to the same page we would only want to execute the insert statement when the submit button has actually been pressed, the most common way of doing this is by placing a hidden field on the form and then checking if the variable has been set or not using the isset() function.

I am then validating the inputs to verify that all fields have been populated and when valid inserting the values into the database by executing an insert statement.

The above code is considered safe against SQL injection attacks, as all user inputs are passed through the mysql_real_escape_string() function which escapes special characters, it is still vulnerable to other injection attacks such as cross site scripting.


Seeing it in action

The first time the page is loaded the user is only presented with the input form.


The user is now able to input guestbook entries simply by populating all fields and pressing the submit button. The data is validated prior to being inserted in the database and as you can see below, the submission was rejected because both the email address and comments field were left blank.

In the example below, all fields where populated and the comment was inserted in the database, "Comment added..." success message and the actual comment are immediately shown on screen as the form submits to itself so no refresh is required.


The below screenshot shows how multiple comments would be displayed.


I have attached all sources mentioned above in the attachment below for anyone interested.
PHPsimpleGuestBook.rar

Sunday 10 April 2011

Setting up the Environment

For this semester we will mainly be focusing on the server side scripting language PHP. This blog post will go through the entire process of setting up everything that is required before we can start hacking into the PHP language itself.

Setting up XAMP

Up until a couple years ago, if you wanted to configure a local development environment where you can deploy and test PHP applications, you would have to spend hours reading through contradicting documentation from various vendors to install and get Apache, PHP and mySQL to work.

Fortunately, that is now a thing of the part thanks to XAMPP. XAMPP is a pre-configured packaged solution which primarily contains the Apache web-server, the mySQL database server and the PHP interpreter. After XAMPP has been fully installed all services can by controlled from the XAMPP control panel.





Common issues when trying to start Apache

The most common reason why Apache may fail to start is that some other program is already listening on port 80 or 443 which are the default http/https ports.

To check what program is listening on these ports type the following command in cmd.

netstat -o -n -a | findstr 0.0:80 and netstat -o -n -a | findstr 0.0:443

If any of these commands return anything it means that those ports are already in use. The last number in the returned string is the pid (process id) and you can see what process it listening on that port by using the following command

Tasklist | findstr <pid>


As you can se from the above screenshot, VisualSVNServer.exe is already listening on port 443; you can either stop the process and retry starting apache or chose another port for apache.
SSH listen port can be configured from the following file xampp\apache\conf\extrahttpd-ssl.conf to 444 (after verifying that that port is currently not used)

Experimenting with XAMPP

Loading the main XAMPP page

By default the homepage on the installed apache server is the XAMP web interface, it provides the user with various tools vital to ensuring that the installation has been set-up properly and that the various services are running as expected.



Status Report

This page displays the same information as the desktop Control Panel, it shows the status of the various services installed through XAMPP.


In the above screenshot all services except Tomcat are activated.

Security Report

This report performs various security checks on the various services running through XAMPP, the below screenshot shows the security report for a freshly installed un-secured setup, the various checks also include details as to how to rectify the security issues. For e.g. changing the default ftp password.


phpinfo()

By seeing this page one can be sure that PHP has been installed and correctly loaded by the web server, this page lists the full details about the current PHP installation configuration as well as all modules/libraries loaded. This is usually the first place to look when certain functionality within an application is not working as expected on a server. This page can be easily generated from a simple PHP file by calling the phpinfo(); function directly.


Phone Book sample application

This sample application shows some simple PHP in action, it allows the user to create/remove entries from the phone book.

FTP Access

I used the winSCP ftp client to log in to the ftp server by setting the host to localhost, port to 21 (the port the ftp server was configured to listen on) with user 'newuser'.



Upon logging in, I had access to the ftp directory where I could create, edit and even upload files to the server, I created a test file in this directory to verify I had write access.


XAMPP also provides a shortcut to the FileZilla Server terminal (Available by clicking the admin button in the XAMPP control panel). The terminal outputs all activity going through the server as well as lists users currently connected to the ftp server.

This terminal also provides the admin with all functionality required to maintain the server, such as user account maintenance and directory permissions.


Friday 1 April 2011

An introduction to XML

XML (Extensible Markup Language) is another markup language (like HTML), but unlike HTML it is not styled, and solely used to store and transport data.

Although there are various standards based on XML e.g. RSS which come with their own set of tags/rules, XML on its own allows the developer to invent/come up with his own tags, as long as the basic ‘tree’ structure is preserved.

All XML documents must follow the node structure as explain below, where everything is contained within a single root element, the root element may contain any number of branches and leaves and where every inner branch may contain more branches and leaves. As long as this structure is maintained the resulting XML document will be valid.

<root>
          <branch>
                    <leaf>content</leaf>
          </branch>
</root>

 As you can see XML is a very flexible yet efficient way of storing any data structure, I’ve created a simple XML document describing a list of customers, each holding one or more accounts.



I have also validated the XML document at http://validator.w3.org/

XML in the real world

The use of XML is so widespread that it’s actually hard to draw a line and just discuss a few every day uses.

1. Web services

A clear example of extensive use of XML are web services, web services allow any system irrelevant of what language or platform it runs on to interact with any other system which supports web services through the HTTP protocol. The interaction between both systems is done entirely through XML.

  • Starting with the wsdl (Webservice Definition Language)– an XML document which describes the service’s endpoints. It simply lists all method calls available through the webservice as well as the inputs and outputs of each endpoint.
  • Request/Response – All communication done to and from the webservice is contained within XML.

Had it not been for XML we wouldn’t have any of the flexibility offered through web services.

2. Object serialisation

Any POJO (plain old java object) can be serialised directly into XML, which can then be later stored in a database, text file etc… It is also highly effective when used in conjunction with web services, because if you can marshal an object directly into XML you can actually forward the entire serialised object through the webservice just like you would with any other method.

3. RSS

RSS (Really Simply Syndication) is also extensively used now with all this craze going on around blogs, every blogging platform I know of supports RSS natively, it is an XML standard used to publish articles, it comes with a standard set of XML tags such as date, author, title and post. This enabled the content to be picked up by crawlers and robots to be syndicated over the internet. RSS is one of the main contributors to the fast response to news event we see online.

Although XML can be seen everywhere, I still believe that it’s still in its infancy with innovations cropping up every other day, we still have to yet realise the true potential of this simple but efficient way of storing and forwarding data between systems.