Introduction
In this tip, I am going to add one more security layer to a web form submission.
Normally, when naming form elements, we choose static/fixed name for each element.
In my technique, I am going to hash the names of the form elements using dynamic salted values, so that a name of an element varies from a user to another!
Namely, I choose a concatenation of the “IP address, the user agent, beside a fixed string” as a salt to hash the name of a form element.
This way, we greatly reduce the risk of playing with our form!
Using the Code
Here is a PHP function that hashes a name of a form
element using SHA1 and a dynamically salted string
:
function HashedFieldName($field){
$salt='hawom169';
$fullSalt=$_SERVER['HTTP_USER_AGENT'].getRealIpAddr().$salt.$field.$salt;
return 'A'. substr(sha1($fullSalt),0,20);
}
The function getRealIpAddr()
is used to get the user IP address, I took it from https://gist.github.com/owcall/2928583.
Then, the function HashedFieldName($field)
is used to name a form
element like this:
<?php $namefield='username';?>
<input type="text" id="txtname" name="<?php echo(HashedFieldName($namefield)) ?>">
Looking carefully to the code, we will see that I used a fixed value for the ID
property of the text
element; this way, we can easily access that element via JavaScript at the client side:
var obj=document.getElementById('txtname');
if(obj.value==''){
window.alert('You must enter your name');
obj.focus();
return false;
}
To expose the form submitted data at the server side, we may use a code like this:
echo("Thank you " . $_POST[HashedFieldName($namefield)].",Your registration is completed successfully!");
What is Next?
In my next article, I am going to provide a complete solution that uses my technique: Preventing Resending by Refresh and Reducing the Need of Captcha.
Points of Interest
- The example is provided in PHP, it is obvious that it can be used by any other technology such as .NET or Java.
- The same technique can also be used for dynamically naming cookies (session cookies), which reduces the risk of cookie theft.