Totally Communications Ltd

Websites. Software. Consulting

Totally Communications specialise in professional web design, software development and online marketing, working with SME's, charities and large corporates. more >>

Call to Discuss Your Project

Form Injection

By Jamie Frankel

Added Friday 07/08/2009

Ever created a web form, tested it, concluded it works perfectly and pushed it live, without really thinking about how secure it is? Well until now, I have. Obviously my major concern with web forms has always been SQL Injection, however most programming languages have a function to escape any harmful characters.

But have you ever thought about a JavaScript injection. Well, a colleague pointed it out to me a couple of week's back, so I thought I should share that knowledge so others can avoid the same mistakes.
Consider a basic contact form. On submit, you do some server-side validation (like checking the email address is valid), and if this fails, you redisplay the form with the posted values filled into the input fields.
This is common practise for most forms, as many forms are quite long and users would definitely not appreciate having to retype everything if they'd typed one thing incorrectly.
As an example, I am going to use a form created in PHP:

< input type="text" name="emailAddress" value="< ? php echo $_POST['emailAddress']; ?>" />

This is a standard way of implementing a text input element.
Now consider your user typed in:

" >< script>alert(123) < / script>

Obviously your form validation would fail because it is NOT a valid email address. But have you thought what would now display when your form comes back:

< input type="text" name="emailAddress" value="" >
< script>alert(123) " / >


Although this script isn't harmful (an alert box will appear saying 123 in it), it does demonstrate how just echo-ing the posted value can cause an injection script to run.

The Solution

To solve this problem, simply add the htmlentities method to your echo, which will convert all those nasty characters into safe HTML.

< input type="text" name="emailAddress" value="
< ? php echo htmlentities($_POST['emailAddress'],ENT_QUOTES); ?>" />


This will render the following code on your website:

< input type="text" name="emailAddress" value="
">< script>alert(123)< /script>" />


Hope this provides some more ways of keeping hackers away from your websites.


Bookmark and Share

Comments

There are no comments at this time.

Toby Mason - Google Certified Professional Certification IMA Award Winner SEO Expert Rating Professional Valid XHTML 1.0 Transitional E-Consultancy Internet Advertising Bureau

Totally Communications 2010
Software Developers London |

SEO Company London | PPC Company London | Search Marketing Company London