12 Security - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: 2.1.0
Table of Contents
12 Security
Grails is no more or less secure than Java Servlets. However, Java servlets (and hence Grails) are extremely secure and largely immune to common buffer overrun and malformed URL exploits due to the nature of the Java Virtual Machine underpinning the code.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.What Grails Automatically Does
Grails has a few built in safety mechanisms by default.- All standard database access via GORM domain objects is automatically SQL escaped to prevent SQL injection attacks
- The default scaffolding templates HTML escape all data fields when displayed
- Grails link creating tags (link, form, createLink, createLinkTo and others) all use appropriate escaping mechanisms to prevent code injection
- Grails provides codecs to let you trivially escape data when rendered as HTML, JavaScript and URLs to prevent injection attacks here.
12.1 Securing Against Attacks
SQL injection
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. For example doing the following is vulnerable to HQL injection attacks:def vulnerable() { def books = Book.find("from Book as b where b.title ='" + params.title + "'") }
def vulnerable() {
def books = Book.find("from Book as b where b.title ='${params.title}'")
}
def safe() {
def books = Book.find("from Book as b where b.title = ?",
[params.title])
}
def safe() {
def books = Book.find("from Book as b where b.title = :title",
[title: params.title])
}
Phishing
This really a public relations issue in terms of avoiding hijacking of your branding and a declared communication policy with your customers. Customers need to know how to identify valid emails.XSS - cross-site scripting injection
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 this and Grails' support for Spring Web Flow includes security like this by default.It is also important to ensure that all data values rendered into views are escaped correctly. For example when rendering to HTML or XHTML you must call encodeAsHTML 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 your output escaping format is not supported you can easily write your own codec.You must also avoid the use of request parameters or data fields for determining the next URL to redirect the user to. If you use asuccessURL
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 JavaScript code to then exploit the logged-in account on the site.Cross-site request forgery
CSRF involves unauthorized commands being transmitted from a user that a website trusts. A typical example would be another website embedding a link to perform an action on your website if the user is still authenticated.The best way to decrease risk against these types of attacks is to use theuseToken
attribute on your forms. See Handling Duplicate Form Submissions for more information on how to use it. An additional measure would be to not use remember-me cookies.HTML/URL injection
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.HTML/URL injection is easily handled with the codecs supplied by Grails, and the tag libraries supplied by Grails all use encodeAsURL where appropriate. If you create your own tags that generate URLs you will need to be mindful of doing this too.Denial of service
Load balancers 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 the maximum value of a result set 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:def safeMax = Math.max(params.max?.toInteger(), 100) // limit to 100 results return Book.list(max:safeMax)
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 allowed to view the object with the requested id before returning the response to the user.Not doing this is "security through obscurity" which is inevitably breached, just like having a default password of "letmein" and so on.You must assume that every unprotected URL is publicly accessible one way or another.12.2 Encoding and Decoding Objects
Grails supports the concept of dynamic encode/decode methods. A set of standard codecs are bundled with Grails. Grails also supports a simple mechanism for developers to contribute their own codecs that will be recognized at runtime.Codec Classes
A Grails codec class is one that may contain an encode closure, a decode closure or both. When a Grails application starts up the Grails framework dynamically loads codecs from thegrails-app/utils/
directory.The framework looks under grails-app/utils/
for class names that end with the convention Codec
. For example one of the standard codecs that ships with Grails is HTMLCodec
.If a codec contains an encode
closure Grails will create a dynamic encode
method and add that method to the Object
class with a name representing the codec that defined the encode closure. For example, the HTMLCodec
class defines an encode
closure, so Grails attaches it with the name encodeAsHTML
.The HTMLCodec
and URLCodec
classes also define a decode
closure, so Grails attaches those with the names decodeHTML
and decodeURL
respectively. Dynamic codec methods may be invoked from anywhere in a Grails application. For example, consider a case where a report contains a property called 'description' which may contain special characters that must be escaped to be presented in an HTML document. One way to deal with that in a GSP is to encode the description property using the dynamic encode method as shown below:${report.description.encodeAsHTML()}
value.decodeHTML()
syntax.Standard Codecs
HTMLCodecThis codec performs HTML escaping and unescaping, so that values can be rendered safely in an HTML page without creating any HTML tags or damaging the page layout. For example, given a value "Don't you know that 2 > 1?" you wouldn't be able to show this safely within an HTML page because the > will look like it closes a tag, which is especially bad if you render this data within an attribute, such as the value attribute of an input field.Example of usage:<input name="comment.message" value="${comment.message.encodeAsHTML()}"/>
Note that the HTML encoding does not re-encode apostrophe/single quote so you must use double quotes on attribute values to avoid text with apostrophes affecting your page.URLCodecURL encoding is required when creating URLs in links or form actions, or any time data is used to create a URL. It prevents illegal characters from getting into the URL and changing its meaning, for example "Apple & Blackberry" is not going to work well as a parameter in a GET request as the ampersand will break parameter parsing.Example of usage:
<a href="/mycontroller/find?searchKey=${lastSearch.encodeAsURL()}">
Repeat last search
</a>
Your registration code is: ${user.registrationCode.encodeAsBase64()}
Element.update('${elementId}',
'${render(template: "/common/message").encodeAsJavaScript()}')
Selected colour: #${[255,127,255].encodeAsHex()}
Your API Key: ${user.uniqueID.encodeAsMD5()}
byte[] passwordHash = params.password.encodeAsMD5Bytes()
Your API Key: ${user.uniqueID.encodeAsSHA1()}
byte[] passwordHash = params.password.encodeAsSHA1Bytes()
Your API Key: ${user.uniqueID.encodeAsSHA256()}
byte[] passwordHash = params.password.encodeAsSHA256Bytes()
Custom Codecs
Applications may define their own codecs and Grails will load them along with the standard codecs. A custom codec class must be defined in thegrails-app/utils/
directory and the class name must end with Codec
. The codec may contain a static
encode
closure, a static
decode
closure or both. The closure must accept a single argument which will be the object that the dynamic method was invoked on. For Example:class PigLatinCodec { static encode = { str -> // convert the string to pig latin and return the result } }
${lastName.encodeAsPigLatin()}
12.3 Authentication
Grails has no default mechanism for authentication as it is possible to implement authentication in many different ways. It is however, easy to implement a simple authentication mechanism using either interceptors or filters. This is sufficient for simple use cases but it's highly preferable to use an established security framework, for example by using the Spring Security or the Shiro plugin.Filters let you apply authentication across all controllers or across a URI space. For example you can create a new set of filters in a class calledgrails-app/conf/SecurityFilters.groovy
by running:grails create-filters security
class SecurityFilters { def filters = { loginCheck(controller: '*', action: '*') { before = { if (!session.user && actionName != "login") { redirect(controller: "user", action: "login") return false } } } } }
loginCheck
filter intercepts execution before all actions except login
are executed, and if there is no user in the session then redirect to the login
action.The login
action itself is simple too:def login() { if (request.get) { return // render the login view } def u = User.findByLogin(params.login) if (u) { if (u.password == params.password) { session.user = u redirect(action: "home") } else { render(view: "login", model: [message: "Password incorrect"]) } } else { render(view: "login", model: [message: "User not found"]) } }
12.4 Security Plugins
If you need more advanced functionality beyond simple authentication such as authorization, roles etc. then you should consider using one of the available security plugins.12.4.1 Spring Security
The Spring Security plugins are built on the Spring Security project which provides a flexible, extensible framework for building all sorts of authentication and authorization schemes. The plugins are modular so you can install just the functionality that you need for your application. The Spring Security plugins are the official security plugins for Grails and are actively maintained and supported.There is a Core plugin which supports form-based authentication, encrypted/salted passwords, HTTP Basic authentication, etc. and secondary dependent plugins 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.See the Core plugin page for basic information and the user guide for detailed information.12.4.2 Shiro
Shiro is a Java POJO-oriented security framework that provides a default domain model that models realms, users, roles and permissions. With Shiro you extend a controller base class called calledJsecAuthBase
in each controller you want secured and then provide an accessControl
block to setup the roles. An example below:class ExampleController extends JsecAuthBase { static accessControl = { // All actions require the 'Observer' role. role(name: 'Observer') // The 'edit' action requires the 'Administrator' role. role(name: 'Administrator', action: 'edit') // Alternatively, several actions can be specified. role(name: 'Administrator', only: [ 'create', 'edit', 'save', 'update' ]) } … }