Monday, 8 April 2013

Mobile Secure Web Applications With Grails

This article examines security related Grails-specific techniques of web application development for application users of hand-held devices such as mobiles and tablets.
Assumption: The article assumes that the end-users would access these applications using mobile web browsers that can render HTML and HTML5, JavaScript code in the web browser container. Native mobile application interfaces are expected to work equally well when they are designed to access the business logic using server side components in the Grails platform using loosely-coupled interfaces such as end-user views based on REST API calls.
The principles and best practices of secure web application using Grails (please refer to article on web security and Grails) apply regardless of end-users using the application on either desktop or handheld interfaces, or both.
Technical Approaches
When it comes to securing users and users' data in web applications, Grails makes it easier and convenient to design server side business logic using the built-in approaches based on the rapid application development platform.
Controller Interceptors
Controller interceptor are essentially controller class action interceptor closure method that can provide security related safety nets before executing actual controller action bound to the URL. It can also be a map of specific interceptor method reference and conditions such as; which controller action to skip or which action to apply.
For example, if a bookmarked URL is insecurely accessed, either by unauthenticated but valid user, or by an invalid user, the controller behind the URL action can be intercepted to route the user to a login page or register first page.
defbeforeInterceptor = [action: this.&authorize, except: 'login']
private authorize() {
if (!session.user) { redirect(action: 'login') return false }
def login() { // show login view }
Grails Filters
Interceptors are simple to user and works well but is quite unwieldy for large applications as this works on a single controller class basis and also involves adding interceptor code to controller classes. A better approach is to decouple the security filter code in separate classes that applies to controller actions, controller and URLs.
In Grails, filters are defined in filter classes using design by convention technique. These filters can be used for enforcing security in accessing features exposed as controller actions. Filter classes are defined with name that ends with Filters as per Grails convention over code philosophy.
The filter definition is pretty comprehensive and includes other parameters as well that can be optionally defined (Please refer to Grails documentation for more details).
Within the body of the filter, one can also filter types as follows:
Before - Executed before the action. Return false to indicate that the response has been handled that all future filters and the action should not execute, which is handy for business security rules.
After - Executed after an action is executed within a controller
AfterView - Executed after view rendering. Takes an Exception as an argument which will be non-null if an exception occurs during processing.
An example, below is a security filter class that has several filters defined for a finance web application:
classSecureAccessFilters {
def filters = {
 SecurityFilter(controller:'AccountManagement', action:'*') {
before = {
if (!session.user&&!actionName.equals('login')) {
redirect(action: 'login')
return false
Advanced Security Implementation Approaches
The above approaches are for simple security measures which may suffice for many simple applications. If one needs enhanced security measures such as role-based authorization, authentication, data security; Grails allows one to include sophisticated security features using Grails plugins. Spring Security and Apache Shiro are most popular in this space.
They provide similar features and differ only in the ease of implementation and cost of implementation. Spring security Grails plugin has a Core plugin which supports form-based authentication, encrypted/salted passwords, HTTP Basic authentication, etc., and can support secondary dependent plugins that provide alternate functionality such as OpenID authentication, ACL support, single sign-on with Jasig CAS, LDAP authentication, Kerberos authentication, and a plugin providing user interface extensions and security workflows.
We looked at various approaches to securing web applications accessible in desktop computers, mobile devices such as mobile phones, smart phones and tablet PCs.
For the last 8 years, Sigma Infosolutions Grails Development team is using this innovative open source web-application platform that offers new levels of productivity. Sigma Infosolutions' Grails Development team seamlessly integrates with your existing processes and work flows to work with data as non-intrusively as possible. We use agile methodologies and develop high quality, easy to use applications in small time that meets every user's expectations and requirements.
Besides Grails, Sigma Infoslolutions' also has expertise in technologies like Spring, Struts, Hibernate, JSP/Servlets, Java Beans (EJB), AWT/Swing and many more.
Call today at 1-888-861-7360 or write us at to discuss your Application Development requirement.

Monday, 1 April 2013

Secure Web Applications using Grails Framework


As internet and World Wide Web got increasingly popular and powerful in the last 20 years, so have web applications over years. The landscape has evolved from simple CGI and scripting applications to powerful b2b and b2c applications over years, encompassing techniques such as Web 2.0, SaaS, cloud deployed applications and platforms such as mobile phones.

With this evolution also comes increasing risked posed by security threats by human and non-human actors to users of application. Insecure software is already undermining the financial, healthcare, defense, energy, and other critical infrastructures of nations and businesses. The digital infrastructure has become increasingly complex and interconnected, resulting in increased difficulty of ensuring adequate application security.

Secure web application defined simply means that the information exchange between authorized users and the system is handled with utmost care for security concerns. These concerns can be classified at high level in 3 categories:

      1. Confidentiality: Ensure only system permitted authorized users interact and exchange data.

      2. Integrity:  Ensure that data is not compromised by users not authorized to use data.

      3. Availability: Ensure systems are available for use when authorized users need them.

Web Application Security Architecture

The best system architecture designs and detailed design documents contain security discussion in each and every feature, how the risks are going to be mitigated, and what was actually done during coding. Security architecture starts on the day the business requirements are modeled, and never finish until the last copy of your application is decommissioned. 

This article aims at how one can build a rapid web application using Grails rapid application framework on the Java platform. Before we get into how Grails helps in developing secure web application, let us briefly look at the details of common risks to web application security.

Web Application Security Threats

As per Open Web Application Security Project (OWASP) information, there are 10 most important security threats for web applications. This 2010 list enumerates the following most important risk categories:


Injection attacks, such as SQL, OS, and LDAP injection, occur when untrusted data is sent to application backend as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing unauthorized data.

Cross-site Scripting (XSS)

XSS flaws occur whenever an application takes untrusted data and sends it to a web browser without proper validation and escaping for threats such as JavaScript code. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.

Broken Authentication and Session Management

Application functions related to authentication and session management are often not implemented correctly, allowing attackers to steal passwords, keys, session tokens, or exploit other implementation flaws to assume other users’ identities.

Insecure Direct Object References

A direct object reference occurs when a developer exposes a reference to an internal implementation object, such as a file, directory, or database key. Without an access control check or other protection, attackers can manipulate these references to access unauthorized data.

Cross-site Request Forgery (CSRF)

A CSRF attack forces a logged-on victim’s browser to send a forged HTTP request, including the victim’s session cookie and any other automatically included authentication information, to a vulnerable web application. This allows the attacker to force the victim’s browser to generate requests the vulnerable application thinks are legitimate requests from the victim.

Security Misconfiguration

Good security requires having a secure configuration defined and deployed for the application, frameworks, application server, web server, database server, and platform. All these settings should be defined, implemented, and maintained as many are not shipped with secure defaults. This includes keeping all software up to date, including all code libraries used by the application.

Insecure cryptographic storage

Many web applications do not properly protect user sensitive data, such as credit cards, user PINs and authentication credentials, with appropriate encryption or hashing. Attackers may steal or modify such weakly protected data to conduct identity theft, credit card fraud, or other crimes.

Failure to restrict secure URL access

Many web applications check URL access rights before rendering protected links and buttons. However, applications need to perform similar access control checks each time these pages are accessed, or attackers will be able to forge URLs to access these hidden pages anyway.

Insufficient Transport Layer Protection

Applications frequently fail to authenticate, encrypt, and protect the confidentiality and integrity of sensitive network traffic. When they do, they sometimes support weak algorithms, use expired or invalid security certificates, or do not use them correctly.

Invalid URL redirects and forwards

Web applications frequently redirect and forward users to other pages and websites, and use untrusted data to determine the destination pages. Without proper validation, attackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.

Grails Approach to Secure Application Development

As stated earlier in the first section, several non-trivial business web applications these days are developed using modern application frameworks designed for rapid application development using Agile methods and principles such as “Do not repeat yourself” (DRY). These frameworks are available pretty much in all the widely used programming languages and platforms such as .NET, Java/JEE, PHP, Python, Ruby etc. Grails is one such platform designed for those principles using modern approach to Model View Controller architecture. 

Let us look at what Grails offer in securing and building a secure web application.

What does Grails framework provide out of the box?


Grails is no more or less secure than traditional web applications written using Java Servlets as controllers. However Java servlets (and hence Grails) are extremely secure and largely immune to common buffer overrun and malformed URL exploits  due to the default security sandbox provisions of the JVM.

Web security problems typically occur due to developer naivety or mistakes, and there is a little Grails can do to avoid common mistakes and make writing secure applications easier to write.

Default Support

Grails has a few built in safety mechanisms by default for the OWASP top 10 risks listed above. The support gets better with the maturity of grails platform and as adoption grows each day.

Injection Risk

  • All standard database access via GORM (Grails Object Relational Mapping) domain objects is automatically SQL escaped to prevent SQL injection attacks
  • The default scaffolding HTML templates HTML all data fields when displayed.
  • Grails link creating tags support such, g:link, g:form, g:createLink g:createLinkTo and others, all use appropriate escaping mechanisms to prevent code injection risk.
  • Grails provides codecs to allow you to trivially escape data when rendered as HTML, JavaScript and URLs to prevent injection attacks here.
  • Hibernate, which is the technology underlying GORM domain classes, automatically escapes data when committing to database so this is not an issue. However it is still possible to write bad dynamic HQL code that uses unchecked request parameters.

Authentication Risk

Currently Grails does not supply any implementation for this. There are multiple security plugins, including Spring Security, Shiro, and Authentication, and if your needs are very simple you can guard your application with Grails filters.

Cross-site Scripting Risk (XSS)

It is important that your application verifies as much as possible that incoming requests were originated from your application and not from another site. Ticketing and page flow systems can help. Grails has a plug in that supports Spring Web flow component for flow based web applications.

It is also important to ensure that all data values rendered into views are escaped correctly. For example when rendering to HTML or XHTML, on can use Grails controller APIencodeAsHTML() on every object to ensure that people cannot maliciously inject JavaScript or other HTML into data or tags viewed by others. Grails supplies several Dynamic Encoding Methods for this purpose and if a particular output escaping format is not supported, it is easy to write you’re a custom codec.

As a practice, on must also avoid the use of request parameters or data fields for determining the next URL to redirect the user to. If you use a successURL parameter for example to determine where to redirect a user to after a successful login, attackers can imitate your login procedure using your own site, and then redirect the user back to their own site once logged in, potentially allowing JS code to then exploit the logged-in account on the site.

Insecure URL access Risk

This is where bad data is supplied such that when it is later used to create a link in a page, clicking it will not cause the expected behaviour, and may redirect to another site or alter request parameters. A safe bet is to assume that every unprotected URL is publicly accessible one way or another to help think about securing the URL access. HTML/URL injection is easily handled with codecs already built in Grails.

Denial of service

Load balancers, proxy servers and other appliances are more likely to be useful here, but there are also issues relating to excessive queries for example where a link is created by an attacker to set max=1000000 so that a query could exceed the memory limits of the server or slow the system down. The solution here is to always sanitize request parameters before passing them to dynamic finders or other GORM query methods:

Guessable IDs

Many applications use the last part of the URL as an "id" of some object to retrieve from GORM or elsewhere. Especially in the case of GORM these are easily guessable as they are typically sequential integers. Therefore you must assert that the requesting user is authenticated and authorized to view the details before returning the response to the user.

Other risks and application specific Risks

For other security risks explicitly unhandled by Grails, one can use OWASP enterprise security API for Java to handle them. Grails, being a Java compatible language, can easily interoperate with this API. For further reference, please refer the link


In this article, we have looked at the security aspects of web application, the typical risks a web application faces and high level overview of how a modern web development framework on the Java platform, GRAILS, helps you meet the goals of agile development without comprising web security.