KHAGAN AYDIN

OWASP 2017 A1: Injection

The bug kept its crown and changed its shape.

· 10 min read

Injection is a security vulnerability in which an application passes untrusted data to an interpreter, such as a database or a shell, and the interpreter runs part of that data as a command. On November 20, 2017, OWASP published the new edition of its Top 10, the list of the ten web application risks most worth your attention, and Injection is still number one. It held that spot in 2010, in 2013, and now in 2017, which makes it the only item never to move.

That alone is not interesting. What changed underneath the ranking is. In 2013 the single word “injection” still meant SQL injection to most developers, and the fix was understood: use parameterized queries and stop building queries out of strings. I wrote about that fix in my 2013 essay on SQL injection, and it holds today. But while teams were finally learning it, the ground moved. The database under a typical application is often no longer a relational one you query in SQL. The server runs JavaScript. The query is built by an object mapper, or sits inside a template, or is really a shell command. Injection did not go away. It spread into every place where your code hands attacker-controlled data to something that interprets it.

The 2017 text makes the spread official. Where the 2013 page named SQL, LDAP (the directory protocol many companies use to store staff accounts) and a handful of others, the 2017 page lists SQL, NoSQL, operating system command, Object Relational Mapping (ORM) search parameters, LDAP, Expression Language (EL) and Object Graph Navigation Library (OGNL). Same root cause, more interpreters. This essay walks the ones that catch people who thought prepared statements had closed the whole chapter.

The one idea behind all of it

Injection is one mistake wearing different clothes. Your program builds a command for some interpreter (a database, a shell, an XML parser, a template engine) by mixing a fixed instruction with data you received from the outside. The interpreter cannot tell which part you meant as instruction and which part arrived from a stranger. So the stranger writes instructions too.

The cure is always the same shape: keep the data out of the instruction. Send the command and the values on separate rails so the interpreter never parses one as the other. Everything below is that single idea applied to a different interpreter.

NoSQL: an object where you expected a string

MongoDB is the common case. A login handler in Node.js looks it up like this:

Vulnerable code

// Node.js, Express, the MongoDB driver
app.post('/login', async (req, res) => {
  const user = await db.collection('users').findOne({
    username: req.body.username,
    password: req.body.password
  });
  if (user) {
    req.session.userId = user._id;
    return res.json({ ok: true });
  }
  res.status(401).json({ ok: false });
});

There is no SQL here, no string glued together, nothing a SQL scanner would flag. The author assumed req.body.username is a string. It does not have to be. The client sets the Content-Type to application/json and sends this body:

{ "username": { "$gt": "" }, "password": { "$gt": "" } }

Now req.body.password is not the string the code expected, it is the object { "$gt": "" }. MongoDB reads $gt as the “greater than” operator, so the query becomes “find a user whose username is greater than empty and whose password is greater than empty.” That matches the first user in the collection, usually an administrator, and the login succeeds with no password at all. { "$ne": null } does the same job: “not equal to null” matches any record where the field exists.

The attacker does not even need JSON. Express’s default body parser turns a form field named password[$ne]= into the nested object { password: { $ne: '' } }, so a plain urlencoded post reaches the same place.

Fixed code

app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  if (typeof username !== 'string' || typeof password !== 'string') {
    return res.status(400).json({ ok: false });
  }
  const user = await db.collection('users').findOne({ username: username });
  if (user && await bcrypt.compare(password, user.passwordHash)) {
    req.session.userId = user._id;
    return res.json({ ok: true });
  }
  res.status(401).json({ ok: false });
});

Two changes, both load-bearing. First, reject anything that is not a string before it reaches the query, so an operator object can never arrive. Second, look the user up by username alone and check the password in your own code against a stored hash, so the password value never touches the query at all. The second change matters even if you forget the first, because an operator object compared by bcrypt.compare is simply false.

OS command injection: the shell reads your punctuation

When your code shells out, the interpreter is the shell, and the shell treats ;, |, &, $() and backticks as instructions.

Vulnerable code

const { exec } = require('child_process');
app.get('/ping', (req, res) => {
  exec('ping -c 1 ' + req.query.host, (err, stdout) => {
    res.type('text').send(stdout);
  });
});

A request for ?host=example.com;cat%20/etc/passwd runs the ping and then reads the password file. exec hands the whole string to /bin/sh, which happily runs both commands.

Fixed code

const { execFile } = require('child_process');
app.get('/ping', (req, res) => {
  const host = req.query.host;
  // Must start with a letter or digit, so a leading dash can never reach ping as an option.
  if (typeof host !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9.-]*$/.test(host)) {
    return res.status(400).send('invalid host');
  }
  execFile('ping', ['-c', '1', host], (err, stdout) => {
    res.type('text').send(stdout);
  });
});

execFile runs the program directly with an argument list and no shell, so ; and $() are just characters in a single argument. This is the right default: pass arguments as a list, never as one glued string, in any language. Python has subprocess.run([...]) instead of shell=True, Ruby has the array form of system, and so on.

Here is the part most write-ups skip. Dropping the shell is necessary but not sufficient. If the attacker controls an argument that the program itself reads as an option, they can still change what the program does without any shell metacharacter. In August 2017 this exact class was patched across common tools: a crafted address could make the version control client treat a host name beginning with a dash as a command-line option and run a program of the attacker’s choosing (tracked as CVE-2017-1000117 for one of them, with sibling fixes in two others). The lesson for your own code: an argument list stops the shell, and an allowlist that forbids a leading dash stops argument injection. The regular expression above does both: it allows only letters, digits, dots and hyphens, and it requires the first character to be a letter or digit, so a leading dash is refused.

The cost of getting this wrong is not abstract. In May 2016 a flaw in a widely used image processing library, nicknamed ImageTragick and assigned CVE-2016-3714, let an attacker run commands on a server just by uploading a booby-trapped image. The library passed file names into a shell command for its external helper tools without stripping shell characters, so a file whose name carried a command ran that command during conversion. It was reported on May 3 and seen in real attacks within a day, because countless sites resize user uploads and almost none expected their image resizer to be a shell.

ORM: the raw escape hatch

Object mappers are sold as the end of SQL injection, and for their normal methods they are. The trouble is the escape hatch every mapper provides for raw queries, used exactly where the mapper’s own methods feel too limited, which is where the interesting data usually lives.

Vulnerable code

// Sequelize, a Node.js ORM
const rows = await sequelize.query(
  "SELECT id, title FROM articles WHERE author = '" + req.query.author + "'"
);

The project uses an ORM, so a reviewer scrolls past it. But sequelize.query with a concatenated string is ordinary SQL injection wearing an ORM’s name. The same trap exists in every mapper: raw SQL in one, and the object query languages that mappers ship, such as Hibernate Query Language in the Java world, which is just as injectable when you build it from strings.

Fixed code

const { QueryTypes } = require('sequelize');
const rows = await sequelize.query(
  'SELECT id, title FROM articles WHERE author = :author',
  { replacements: { author: req.query.author }, type: QueryTypes.SELECT }
);

The named placeholder :author is bound by the driver, so the value cannot become part of the query. The 2017 list adds one more ORM-specific trap worth naming: feeding attacker data into the mapper’s own search parameters to widen a result set, pulling back rows the user should never see. An allowlist for any field a user is allowed to filter or sort by closes that one, because table names, column names and sort directions can never be bound as parameters.

EL, OGNL and templates: injecting into the server’s own language

The newest members of the family inject into an expression or template language that the server evaluates. This is how the largest breach of the year happened.

In March 2017 a remote code execution flaw was found in a popular Java web framework, Apache Struts, and assigned CVE-2017-5638. The framework’s file-upload parser took the request’s Content-Type header, and when that header was not a valid type it built an error message out of it. Building that message ran it through an evaluator that treated text inside a certain marker as an OGNL expression, the framework’s own object language, and executed it. So an attacker who put an OGNL expression in the Content-Type header ran operating system commands on the server. No login, no form field, just a header. A fixed version shipped on March 7, and working exploits were in the wild within two days.

One large credit bureau did not apply that fix. Over the summer of 2017, attackers used the Struts flaw to enter a public dispute portal. The company’s own statements place the unauthorized access from May 13 to July 30, 2017, with staff first noticing suspicious traffic on July 29. By October 2 the count stood at about 145.5 million people, with names, dates of birth and government identifiers taken. The root cause was two failures stacked: a public framework with a known, patched injection flaw left unpatched for months, and an internal application reachable from the internet that trusted a request header. There is nothing exotic in it, which is the point.

For your own code, the defense against template and expression injection is to keep user input out of the template, never in it. User data is a value you pass to an already-compiled template, not text you concatenate into template source. Research presented in 2015 named this whole class, server-side template injection, and showed it in several popular engines; the fix in every one is the same separation of data from code.

The fix, in short

One rule, applied to each interpreter: keep the data out of the instruction.

  • Database queries. Bind every value as a parameter, and check that input is a string before it reaches the query.
  • Shell commands. Run the program with an argument list, never one glued string, and refuse a leading dash.
  • Object mappers. Treat the raw query method as raw SQL, and allowlist any column or sort order a user may choose.
  • Templates and expressions. Pass user data to the template as a value. Never build it into the template text.

What changed from 2013, in one line

The item did not move and its definition barely grew. What grew is the number of interpreters in a normal application, so the same mistake now has more places to happen. In 2013 a team could “handle injection” by auditing SQL. In 2017 that audit misses the login that trusts a JSON object, the resize that trusts a file name, the raw ORM query, and the header that reaches an expression engine.

How to test your own application

Go interpreter by interpreter, not scanner by scanner.

  • For every database call, find the ones that build a query or command from a string. In Node.js search for .query( and exec( with a + or a backtick template nearby. In Java, Statement instead of PreparedStatement, and any string-built Hibernate query. In any ORM, grep for the raw-query method by name.
  • At every login and search endpoint, send a value that is an object, not a string: the JSON body {"username": {"$ne": null}, "password": {"$ne": null}}, and the urlencoded password[$ne]=. A different response means the parameter reached the query as an operator.
  • At any endpoint that runs a command, resizes an image, or renders a document, send a value carrying ;id, $(id), a leading -, and a template probe such as {{7*7}}. If 49 comes back, or a dash changes the behavior, you have found expression injection or argument injection.
  • Keep an inventory of your frameworks and their versions, and read their security advisories. The Struts breach did not need a new technique, only an unread bulletin.

The point

Injection stayed at number one for the third list running because the cure is simple to state and tedious to apply everywhere, and “everywhere” now includes interpreters that did not exist in your stack last time you checked. You do not win this by escaping harder. You win it by making the safe call the default in each place: bound parameters for every query, an argument list for every command, a value passed to a template instead of text built into one, and a type check before any of it, so an object can never slip in where you expected a string.

Checklist

  • Reject non-string input before it reaches a query. An operator object is a login bypass.
  • Look users up by identifier, compare secrets in your own code against a stored hash.
  • Run external programs with an argument list, never a shell string, and forbid a leading dash.
  • Treat an ORM’s raw-query method as raw SQL. Bind every value.
  • Allowlist any column or sort a user may choose. Names cannot be parameters.
  • Pass user data to a template as a value, never concatenate it into template source.
  • Patch your frameworks and read their advisories. An unpatched injection flaw is an open door.