Survey Form with Validation

Posted on

Form is one of the key elements of a web application. It enables the communication and interaction between the users and a website. However, it is also a major channel of attacking a web site as I mentioned in my earlier blog post Web Application Security. Although it is not enough to secure a website by validating and sanitizing user input in the front-end, validation for a form can detect unintentional human mistakes and reduce invalid calls to the server. In this blog post, I will explain a few form validation methods using dojo form widgets.

The most common web forms are for managing a user account, leaving a message or conducting a survey. In this post, we will use a survey form for example. Let’s take a look at the form below and spend a few minutes to think about how you can validate the user input in different specific fields.

a blank form

Since a valid name only include letters, spaces, and sometimes dash, the validation can be done by a simple regexp expression and specify it with the regExp property of the ValidationTextBox. ValidationTextBox checks user input as they type and show error message if needed.

// code for name input field
<label for="name">Name*: </label>
  <input id="name" type="text" name="name" 
         data-dojo-type="dijit.form.ValidationTextBox"
         data-dojo-props="regExp:'^[- A-Za-z]+$',
         required:true, trim:'true', maxlength:64"/>

Age input field is a drop down menu which is good for security as well as usability. It provides options for user to choose from and the options can be only those interested ones. Since the value for each option is set, nothing much needs to be done in the front-end. The value of form does not contain most of the advanced form widgets and this rating widgets is one of them, thus you will need to get the values for those fields individually and mix in with the rest of the form data when submitting the form.

Besides using regexp to validate the input, you can take advantage of the predefined validate functions in dojox/validate.

// code for email input field
<label for="email">Email*: </label>
<input id="email" type="text" name="email" data-dojo-attach-point="email" 
    data-dojo-type="dijit.form.ValidationTextBox"
    data-dojo-props="required:true, invalidMessage:'Invalid Email address', 
    trim:'true', maxLength:32"/>

The rating field is one of dojox form widgets where you can specify number of stars and default value. Same with other textbox input, I used a customized regexp to validate the reference # field. SimpleTextArea widget lets you specify the rows and cols for the text area while TextArea widget will display a text box and change the size as the user types in more data.

// set validator for reference # field
_setValidator: function _setValidator(){
    this.refNum.validator = function(value){
        return value== "" || /^[s-zS-Z][a-hA-H][0-9]{6}$/.test(value);
    };
}

// strip off invalid characters in textarea
_cleanString: function _cleanString(text){
    return text.match(/[^<>\\]?/g).join("");
}

Last but not least, connecting events with the submit button.

on(this.submitBtn, "click", lang.hitch(this, function(){
    var rating = this.rating.get("value"),
	    commentText = this._cleanString(this.comment.value);

    if(this.form.validate() && rating !== 0){
        response = "Form data in json format:<br/>";
        response += json.stringify(lang.mixin(this.form.get("value"), 
            {comment:commentText, rating:rating}));
    }
    else{
        response = "Form can not be submitted.<br/>";
        response += "Please fill in all required field and verify the data 
            you have entered.";
    }
    this.formDataDiv.innerHTML = response;
}));

Check out the Demo.


Web Application Security

Posted on

A Web application is a software which runs on a web server and can be access with an identified URL. There is common misconception that the security is provided by the host web server or application server. While a web server or an application server can protect the environment for the web application from malware or virus, it does not block the hackers from sending malicious software through legitimated channels which includes the publicly accessible web applications that are running on top of it.

Failure to secure your web application will enable the hacker to take over the control of your web application and perform malicious actions which can cause sensitive information to be lost or/and financial loss for your users and the web application will no longer be trustworthy.

The Open Web Application Security Project(OWASP) is a non-profit global organization that is dedicated to improve software security. Below are the Top 10 Web Application Security Risks for 2010:

1. Injection
Hackers try to inject some malicious command to the interpreter, such as database, LDAP, and OS. SQL injection is the most popular one for form-based web applications.

2. Cross-Site Scripting (XSS)
Hackers insert a script as part of the input and send it to the web application. The script will be executed on the web site as the user input is evaluated as dynamic content on the page. The hacker will be able to retrieve any information of the user with script, including the session id.

3. Broken Authentication and Session Management
HTTP is stateless so the server needs to maintain state with session id. The session id is generated by the server but kept in the client browser. If the session id is reusable and the hacker can steel it from the url or the network, the hacker can then log in as a legitimate user.

4. Insecure Direct Object References
It is common that documents organized in the web server in a specific way, for example, http://yourwebsite.com/pages/194. The hacker can try out other numbers to access unauthorized content if the backend does not have the access control enforced.

5. Cross-Site Request Forgery (CSRF)
CSRF is when the attackers embed action request in the link to the legitimate website. If the user click the link and log in to the website, the hidden action will be performed on the website.

6. Security Misconfiguration
Security misconfiguration is caused by blindly applying the third party framework. When you use the third party framework, make sure you check what are included in the package and the configuration for the features provided.

7. Insecure Cryptographic Storage
If Sensitive information is not encrypted by strong encryption methods, then applications are subject to this security issue.

8. Failure to Restrict URL Access
This is similar to Insecure Direct Object References mentioned above. A security website should prohibit access to pages that the user is not authorized to access. Backend checking needs to be enforced.

9. Insufficient Transport Layer Protection
It’s recommended to use SSL transfer data between the user and the server over the Internet.

10. Invalidated Redirects and Forwards
Some websites use a parameter in the url to redirect to other pages. The hacker may be able to put his or her page or script in the url and take over the control.

Above are just the top 10 risks listed by OWASP and there are many more of the vulnerabilities that are specific to a web application. Keeping those potential risks in mind can help noticing the security issues during the software development. Here is a simple check list to improve the security of your web application.

1. Validate the user input on the front-end
Only allow legitimate characters since there are too many to be excluded. This will also protect you from the unknown attacks. The benefit for validating user input in the front end is that the user will get immediate response and save one invalid request to the server.

2. Validate user input on the server side
This is a must for security because the server is within your own environment.

3. Avoid exposing application structure or database structure
An application should catch any possible exceptions so user won’t see a page of error output on the page. Error output can expose the application or database infrastructure to hackers. Customized error messages need be on a need-to-know basis.

4. Do not trust your encryption
Encryption was a big hit and most types of encryption have been broken and the information is easy to find online. As Dr. Mark Stamp once said, it’s better not to encrypt than to use bad encryption. Use secure encryption method such as SHA-256.

6. Maintain Secure Session
Use new unique token with limited time period for each request. Clear session state information as the session expires.

7. Use post over get
Hacker may change parameters in the url to exploit other pages. It’s more secure to keep the information in the request body with post request.

8. Send information using secure protocol
Use TSL(SSL) protocol to transfer sensitive information.

9. Limit user input by giving only valid options
It’s better to give users valid options than letting users to put in the open-ended answers from both usability and security aspects.