KHAGAN AYDIN

OWASP 2017 A5: Broken Access Control

Every request asks one question. Most breaches happen when nobody answers it.

· 11 min read

Broken Access Control is a security vulnerability in which an application lets a logged-in person read, change or do something they are not allowed to. It is number five on the 2017 OWASP Top 10. It is the only item on the list made by joining two from 2013: A4, Insecure Direct Object References, and A7, Missing Function Level Access Control. The name itself is older than either; it was number two on the 2004 list.

Access control is the part of an application that decides what a logged-in person may do: which records they may read, which they may change, which actions they may take. When it breaks, the attacker needs no exploit and no special tool. Each case below needed only a browser, at most a free account, and one changed value in a request. Together they exposed hundreds of millions of documents.

Why two items became one

The 2013 list split the problem by what the attacker changes. Change the object, and you have a direct object reference: GET /invoice?id=10234 becomes id=10235, and you see someone else’s invoice. Change the function, and you have missing function level control: a normal user calls POST /admin/deleteUser because the server only hid the button. The essays on direct object references and function level control covered each one separately.

The 2017 release notes record the merge without arguing for it, but the reason is obvious the first time you test an application programming interface (API). Look at this request:

DELETE /api/accounts/200/users/42 HTTP/1.1

Is that a bad object or a bad function? Both arrive on the same line. The server must answer one question every time: may this user perform this action on this object? Two categories let teams fix half of it and feel finished.

OWASP rates the new item 2 out of 3 for how common it is, how easy it is to find and how easy it is to exploit, and 3 out of 3 for impact. Its entry also admits that scanners can spot an absent check but cannot tell whether a present one actually works. A scanner does not know that invoice 777 belongs to someone else. Only a test that knows who owns what can find this bug.

Why APIs made it bigger

In an older server-rendered application, a record that appeared on no page was hard to find, and that accident hid many missing checks. A single page app or mobile app talks to the API directly. Every record is a URL with an ID in it, and every action is a method on that URL: GET reads, PUT and PATCH change, DELETE removes. The interface shows users their own data; the API answers whatever it is asked. Three patterns recur:

  • Reads are checked, writes are not. GET /api/orders/777 refuses, but PUT /api/orders/777 with a new delivery address succeeds.
  • The body carries fields it should not. A user sends PATCH /api/users/me with {"role": "admin"} or {"account_id": 200}, and the handler saves every field it was given.
  • Search and export endpoints. A list or search call skips the filter that the single-record call applies, or accepts a wildcard and returns everyone.

Panera Bread, April 2018

On April 2, 2018, it was reported that panerabread.com had been serving customer records in plain text to anyone who knew the address, with no login. The records held names, email and home addresses, birthdays, phone numbers, loyalty numbers and the last four digits of saved cards. Account IDs were sequential numbers, so one record led to the next. A researcher had reported the problem to the company on August 2, 2017. It stayed open for eight months, until a journalist asked about it. The company said fewer than 10,000 accounts were affected; data a security firm shared later put the exposure above 37 million records.

Root cause: an endpoint that returned customer data checked neither who was asking nor whose record it was.

The US Postal Service, November 2018

On November 21, 2018, it was reported that an API behind the Postal Service’s Informed Visibility program, which gives bulk mailers tracking data, let any logged-in usps.com user look up other users’ email address, username, account number, street address and phone number. About 60 million users were exposed. Many fields accepted wildcards, so one search could return a whole data set, and the API accepted requests to change other people’s account details, though some changes needed the owner’s confirmation. A researcher had reported the flaw more than a year earlier and heard nothing back. The Postal Service fixed it after a journalist asked, and said it had no sign the flaw had been abused.

Root cause: the API checked that the caller was logged in, and stopped there. Authentication (proving who you are) was mistaken for authorization (deciding what you may see).

First American Financial, May 2019

On May 24, 2019, it was reported that First American Financial, a large title insurance company, had about 885 million documents reachable on its website, dating back to 2003. They included bank account numbers and statements, mortgage and tax records, Social Security numbers, wire transfer receipts and images of driver’s licenses. The company emailed document links to the parties in a real estate deal, and the number in each link was nine digits that appeared to be issued in sequence. Change one digit and you saw someone else’s records. No login was required. The company disabled the site that afternoon and blamed a design flaw in one application.

Root cause: the link itself was the only permission. Whoever held a document number could open the document.

The code

The vulnerable handler looks normal, which is why it ships: it requires login, uses a parameterized query and handles missing records.

Vulnerable code

// Node.js (Express): requireLogin sets req.user from the session
app.get('/api/invoices/:id', requireLogin, async (req, res) => {
  const { rows } = await pool.query(
    'SELECT id, account_id, amount, status FROM invoices WHERE id = $1',
    [req.params.id]);
  if (rows.length === 0) {
    return res.status(404).end();
  }
  res.json(rows[0]);
});

Nothing ties the invoice to the person asking. The fix puts the owner into the query, so other people’s records are never loaded.

Fixed code

app.get('/api/invoices/:id', requireLogin, async (req, res) => {
  const { rows } = await pool.query(
    'SELECT id, amount, status FROM invoices WHERE id = $1 AND account_id = $2',
    [req.params.id, req.user.accountId]);
  if (rows.length === 0) {
    return res.status(404).end(); // missing and not yours look the same
  }
  res.json(rows[0]);
});

The account comes from the session, never from the request. The response is 404 whether the invoice is missing or someone else’s, so an attacker cannot map which IDs are real. The same pair in Python with Flask:

Vulnerable code

@app.route('/api/invoices/<int:invoice_id>')
@login_required
def get_invoice(invoice_id):
    invoice = Invoice.query.get_or_404(invoice_id)
    return jsonify(invoice.to_dict())

Fixed code

@app.route('/api/invoices/<int:invoice_id>')
@login_required
def get_invoice(invoice_id):
    invoice = Invoice.query.filter_by(
        id=invoice_id, account_id=current_user.account_id).first_or_404()
    return jsonify(invoice.to_dict())

Write the rules once, deny by default

Fixing one handler at a time is how the next one gets missed. OWASP’s advice is to deny by default and implement the checks once, then reuse them. In practice: one file holds every rule, and no route exists without one.

// policy.js: every access rule in the application lives here.
const rules = {
  'invoice:read': (user, invoice) => invoice.account_id === user.accountId,
  'invoice:refund': (user, invoice) =>
    invoice.account_id === user.accountId && user.role === 'billing_admin',
  'user:delete': (user) => user.role === 'support_admin'
};

function can(user, action, resource) {
  const rule = rules[action];
  if (!user || !rule) {
    return false; // unknown action or no user: deny
  }
  return rule(user, resource) === true;
}

// Express middleware: load the object, check the rule, or stop.
function authorize(action, load) {
  return async (req, res, next) => {
    try {
      const resource = load ? await load(req) : null;
      if (load && !resource) {
        return res.status(404).end();
      }
      if (!can(req.user, action, resource)) {
        console.warn('access denied', req.user && req.user.id, action, req.originalUrl);
        return res.status(resource ? 404 : 403).end();
      }
      req.resource = resource;
      next();
    } catch (err) {
      next(err);
    }
  };
}

module.exports = { can, authorize };

Then make the rule part of declaring a route, so forgetting it fails at startup instead of in production:

// The only way to add a route. No rule, no route.
function route(method, path, action, load, handler) {
  if (typeof action !== 'string') {
    throw new Error('No access rule for ' + method.toUpperCase() + ' ' + path);
  }
  app[method](path, requireLogin, authorize(action, load), handler);
}

route('post', '/api/invoices/:id/refund', 'invoice:refund', loadInvoice, refund);

An action with no rule is refused, so a new feature stays closed until someone writes its rule. Every refusal is logged, because a burst from one account is someone walking through IDs. And the rules are plain functions, testable for every role without a server:

// people: one fixture user per role; invoice belongs to the member's account
const expected = {
  'invoice:read':   ['member', 'billingAdmin'],
  'invoice:refund': ['billingAdmin'],
  'user:delete':    ['supportAdmin']
};

Object.keys(expected).forEach((action) => {
  Object.keys(people).forEach((name) => {
    const allowed = expected[action].includes(name);
    it(name + (allowed ? ' may ' : ' may not ') + action, () => {
      assert.strictEqual(can(people[name], action, invoice), allowed);
    });
  });
});

The expected table is your access matrix, readable by a reviewer, and the test fails the day code and table disagree. Include a user from another account with the same role: that row catches most bugs.

Two newer ways to break it

The 2017 entry also names two failures that belong to the API era.

Cross-Origin Resource Sharing (CORS). Browsers stop one site from reading another site’s responses unless the second allows it with CORS headers. The common mistake is allowing everyone, with cookies:

app.use(cors({ origin: true, credentials: true }));

With the cors package for Express, origin: true copies back whatever origin the request names, including the null origin that sandboxed frames send. Any web page your logged-in user visits can now call your API with their cookies and read the answer. Name the exact origins instead:

app.use(cors({
  origin: ['https://app.example.com', 'https://admin.example.com'],
  credentials: true
}));

JSON Web Tokens (JWT). A JWT is a signed token that carries claims such as the user’s ID and role. If the server reads the claims without checking the signature, the user writes their own role:

Vulnerable code

const claims = jwt.decode(req.get('Authorization').slice(7)); // no signature check
if (claims.role === 'support_admin') { /* ... */ }

Fixed code

const claims = jwt.verify(req.get('Authorization').slice(7), publicKey, {
  algorithms: ['RS256']
});

Pin the algorithm. In 2015 several JWT libraries were found to accept tokens marked none, with no signature at all, or to accept a token marked as signed with a shared secret and use the server’s public key as that secret, so anyone could forge one. Current versions of the Node.js jsonwebtoken library refuse both, but naming the algorithm states the server’s intent instead of trusting the token’s. A role inside a token is also a snapshot: a user demoted this morning keeps their admin token until it expires. Keep lifetimes short, invalidate tokens on the server at logout, and look up the current role for sensitive actions.

Why the usual fixes fail

Random IDs. Unguessable identifiers slow down someone counting upward and are worth using, but they do not decide who may see a record. IDs leak through email, as at First American, and through browser history, logs, screenshots and the Referer header browsers send to other sites. An ID is a name, not a key.

Requiring a login. The Postal Service lesson: a login tells you who is asking, not whether they may have what they asked for.

Checking at the gateway. An API gateway knows the user. It does not know that invoice 777 belongs to account 200. Object checks have to live where the data does.

Hiding things in the interface. Any check the browser or mobile app performs, the attacker can skip.

How to test your own application

Automate the attack. Create two accounts in your test data, log in as user A, and ask for user B’s things, for every route and every method:

const assert = require('assert');
const request = require('supertest');
const app = require('./app');

const userA = { token: 'token-1' };                 // account 100
const userB = { token: 'token-2', invoiceId: 777 }; // account 200

describe('cross-account access', () => {
  const attempts = [
    ['get', '/api/invoices/' + userB.invoiceId],
    ['post', '/api/invoices/' + userB.invoiceId + '/refund'],
    ['delete', '/api/users/2']
  ];

  attempts.forEach(([method, path]) => {
    it('user A cannot ' + method.toUpperCase() + ' ' + path, async () => {
      const res = await request(app)[method](path)
        .set('Authorization', 'Bearer ' + userA.token);
      assert.ok([403, 404].includes(res.status),
        'expected 403 or 404, got ' + res.status);
    });
  });

  it('user B can still read their own invoice', async () => {
    const res = await request(app).get('/api/invoices/' + userB.invoiceId)
      .set('Authorization', 'Bearer ' + userB.token);
    assert.strictEqual(res.status, 200);
  });
});

The last test matters: a rule that refuses everyone passes every refusal test.

By hand, I keep two browsers logged in as users from different accounts. I record every request the more privileged user can make, then replay each one in Burp Suite’s Repeater with the other user’s session, then with none. I change every ID in the path, query and body, try every method on each URL, and add fields the form never sends, like role and account_id. Any response that returns or changes the other user’s data is a finding.

Checklist

  • Take the user and account from the session or a verified token, never from the request.
  • Put the owner into the query.
  • Deny by default: no rule, no route.
  • Keep every rule in one place and test it per role, including the same role in another account.
  • Check writes, searches and exports, not only single reads.
  • List exact CORS origins. Pin the JWT algorithm.
  • Log refusals and alert on bursts.
  • Run the cross-account test on every build.

The 2013 list asked two questions; the 2017 list asks one. Panera, the Postal Service and First American each failed the simplest check there is, for months or years, while their sites worked perfectly for every honest user. That is the nature of this bug: honest users never trip it, so nobody notices until someone dishonest does. Ask the question in one place, on the server, on every request, and test it as the user who should be refused.