KHAGAN AYDIN

OWASP 2013 A4: Insecure Direct Object References

The attack is editing a number. The fix is one clause in a query.

· 11 min read

Insecure Direct Object References, usually shortened to IDOR, is a security vulnerability in which an application takes an identifier from the request, an account number, an order ID, a file name, and hands over the matching record without checking that it belongs to the person asking. It is number four on the 2013 OWASP Top 10.

It matters for three reasons. It needs no skill: anyone who can edit an address bar can try it. It scales: once one number works, a ten-line script tries the next million. And it hides from the tools teams rely on. A vulnerability scanner sees a request that returned 200 with real data and records a success, because it has no idea the invoice belonged to someone else. Only a person, or a test, that knows who owns what can find it.

What the bug is, in plain words

An object is anything your application stores: a statement, an order, a message, an uploaded file. A direct reference is that object’s real key, exposed in the request. The reference is insecure when the server treats “the request named it” as “the user may have it”.

Here is the whole bug in one request. You log in and open your invoice:

GET /invoice?id=88123 HTTP/1.1
Cookie: SESSION=8f3a1c...

You change the number:

GET /invoice?id=88124 HTTP/1.1
Cookie: SESSION=8f3a1c...

If the second request returns someone else’s invoice, you have found it. The login worked perfectly. The session is valid. The server simply never asked whether invoice 88124 is yours.

This item sits next to A7 on the same list, Missing Function Level Access Control. The difference is useful in practice. A7 is about which functions a user may call: can a customer reach the admin page at all? A4 is about which records a user may touch inside a function they are allowed to use: can a customer view an invoice, yes, but which ones?

Where references hide

The address bar is the obvious place. In real applications, I find more of these bugs in places nobody looks at in a browser:

  • Hidden form fields: <input type="hidden" name="account_id" value="10442">.
  • JSON (JavaScript Object Notation) bodies sent by the page’s own JavaScript or by a mobile app: {"orderId": 5012, "status": "cancelled"}.
  • Path segments: /api/users/731/messages.
  • Cookies and custom headers that carry a user or account number.
  • File names: /download?file=statement_10442_2013-12.pdf.

Once one reference works, automation is trivial:

for i in $(seq 88000 88999); do
  curl -s -b "SESSION=8f3a1c..." "https://shop.example.com/invoice?id=$i" -o "invoice-$i.html"
done

Two cases

Citigroup, 2011. Attackers logged in to Citigroup’s Account Online site for credit card customers using valid credentials, then changed the account number in the browser’s address bar to reach other customers’ accounts. A script repeated this tens of thousands of times. Citigroup found the breach in a routine check on May 10, 2011, fixed the flaw for good on May 27, and began notifying customers on June 3. It first put the count at about 210,000 accounts, then revised it to 360,083. Names, account numbers and email addresses were taken; Social Security numbers, birth dates, expiration dates and card security codes were not. The company reissued cards to 217,657 customers. In August 2013, Connecticut’s attorney general announced a $55,000 settlement after a joint investigation with California, which found the weakness was known to the company at the time of the breach and may have existed since 2008. Root cause: the server returned any account whose number appeared in the URL, as long as someone was logged in.

AT&T and the iPad, 2010. To speed up sign-in, AT&T’s login page for iPad 3G data accounts filled in the customer’s email address automatically. It found the address using the device’s ICC-ID (integrated circuit card identifier, the number printed on the iPad’s SIM, or subscriber identity module, card) sent in the request. The page answered only requests that looked as if they came from an iPad, and that look was nothing more than a User-Agent header, which any client can set. A group wrote a PHP script that walked through ICC-IDs, starting from known ones and counting upward, and collected 114,067 email addresses. AT&T switched the feature off within a day of being alerted, in June 2010. One of the people involved was convicted in November 2012 of conspiracy to access a computer without authorization and of identity fraud, was sentenced in March 2013 to 41 months in prison, and has appealed. Root cause: the server returned personal data for any identifier it received, with no check that the requester owned the device, and the identifiers were sequential and not secret.

Notice what neither case needed: no injection, no stolen passwords for the victims, no malware. In the Citigroup case the attackers were fully authenticated. Authentication answered “who are you?” correctly. Nobody asked the second question.

Vulnerable and fixed code

Vulnerable code

<?php
session_start();
$stmt = $pdo->prepare('SELECT id, total, status FROM invoices WHERE id = ?');
$stmt->execute(array($_GET['id']));
$invoice = $stmt->fetch();
if (!$invoice) {
    http_response_code(404);
    exit;
}

Look closely: this uses a prepared statement. It is safe from SQL injection and wide open anyway. Preventing injection, the subject of the A1 essay, tells you nothing about authorization.

Fixed code

<?php
session_start();
if (!isset($_SESSION['customer_id'])) {
    http_response_code(401);
    exit;
}
$stmt = $pdo->prepare('SELECT id, total, status FROM invoices WHERE id = ? AND customer_id = ?');
$stmt->execute(array($_GET['id'], $_SESSION['customer_id']));
$invoice = $stmt->fetch();
if (!$invoice) {
    http_response_code(404);   // same answer for "does not exist" and "not yours"
    exit;
}

The owner comes from the server-side session, set at login, never from the request. The check lives inside the query, so there is no window where the record has been loaded but not yet checked, and no code path that forgets the second step.

The same handler in Java:

Vulnerable code

@WebServlet("/invoice")
public class InvoiceServlet extends HttpServlet {
    @Resource(name = "jdbc/shop")
    private DataSource ds;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        long id = Long.parseLong(req.getParameter("id"));
        String sql = "SELECT id, total, status FROM invoices WHERE id = ?";
        try (Connection c = ds.getConnection();
             PreparedStatement ps = c.prepareStatement(sql)) {
            ps.setLong(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                if (!rs.next()) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
                req.setAttribute("total", rs.getBigDecimal("total"));
                req.setAttribute("status", rs.getString("status"));
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
        req.getRequestDispatcher("/WEB-INF/invoice.jsp").forward(req, resp);
    }
}

Fixed code

        HttpSession session = req.getSession(false);
        Long customerId = (session == null) ? null : (Long) session.getAttribute("customerId");
        if (customerId == null) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        long id;
        try {
            id = Long.parseLong(req.getParameter("id"));
        } catch (NumberFormatException e) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String sql = "SELECT id, total, status FROM invoices WHERE id = ? AND customer_id = ?";
        try (Connection c = ds.getConnection();
             PreparedStatement ps = c.prepareStatement(sql)) {
            ps.setLong(1, id);
            ps.setLong(2, customerId);
            // the rest is unchanged

Writes need the same clause. Changing or deleting someone else’s data is often worse than reading it. This update lets any logged-in user rewrite any address:

$stmt = $pdo->prepare('UPDATE addresses SET line1 = ?, city = ? WHERE id = ?');
$stmt->execute(array($_POST['line1'], $_POST['city'], $_POST['address_id']));

Add AND user_id = ? with the session’s user ID, and someone else’s row can never change. If you want to tell the user the update failed, look the row up first with the same owner condition. Do not lean on rowCount() alone: on MySQL it counts rows that changed, not rows that matched, so an owner saving unchanged values gets zero and looks like an attacker. And never accept an owner field such as user_id from the request body on create or update; set it from the session.

Child records are where the check usually goes missing. Take this route:

GET /orders/5012/attachments/77

The code checks that order 5012 belongs to the user, then loads attachment 77 by its own ID. The attacker supplies their own order number with someone else’s attachment number, passes the first check, and gets the file. Check the whole chain in one query:

SELECT a.file_path
FROM attachments a
JOIN orders o ON o.id = a.order_id
WHERE a.id = ? AND a.order_id = ? AND o.customer_id = ?

File names are references too. readfile('/var/app/statements/' . $_GET['file']) is both IDOR and path traversal. Look up the stored path by ID and owner in the database, and never build a path from the request.

Why hiding the ID does not fix it

The most common response to a finding like this is to make the ID harder to read. None of these change who the server will serve.

Encoding. Base64 or hex is one click to decode in any proxy tool and one click to re-encode with a new value.

Hashing. md5(88124) looks random. An attacker hashes every number from one to ten million in seconds and has your whole ID space.

Random IDs. Long random IDs, such as globally unique identifiers (GUIDs), make guessing impractical, and that is worth having as an extra layer. But IDs do not stay secret. They appear in emails, shared links, browser history, server logs, the Referer header (which tells a site which page linked to it), and other responses from your own application: the list endpoint, the comment that shows its author’s ID, the export file. A user who was shown a document once, then removed from it, still has its ID. The AT&T identifiers were printed on the card and could be found by counting upward from a known one.

POST, hidden fields and JavaScript checks. Moving the ID out of the URL into a POST body or a hidden field changes nothing. Every byte of the request is under the client’s control, and an intercepting proxy such as Burp Suite edits a POST body as easily as a URL. Greyed-out buttons and client-side checks protect only users who were never going to attack you.

Indirect reference maps. A sounder idea: the page shows references 1, 2 and 3, and the session maps them to real IDs. This works, but only because the map holds just the objects this user was allowed to see. It is an access check, done once when the map is built, and every code path that builds a map must get that check right. A check in the query is simpler and covers every caller.

The defense that ends it

Every request that touches a user-owned record proves ownership on the server, using the identity from the session, inside the data access itself.

Make the safe call the only one that exists. If your data layer offers findInvoice(id), someone will call it with a request parameter. Offer findInvoiceForCustomer(id, customerId) instead, and delete the other one. A code review rule that works: any query on a user-owned table without the owner column in its WHERE clause is a finding until proven otherwise. In multi-tenant software, every table carries a tenant ID and every query filters on it.

Where ownership is not one column, such as team members, shared folders or support staff acting for customers, write the rule once, in one function such as canView(user, invoice), and call it on every path. Scattered if statements drift apart over time; one function can be tested.

Return 404 for “not yours”, not 403. A different answer for “exists but forbidden” tells the attacker which IDs are real.

Layers around it

These reduce the damage when one check is missed. They do not replace it.

  • Watch for enumeration. One session requesting hundreds of different account numbers, or a run of 404s on neighboring IDs, is not normal use. The Citigroup script made tens of thousands of requests from logged-in sessions. A per-session count of distinct records viewed, with an alert, catches that pattern.
  • Use random IDs for anything exposed. Not as the fix, as a speed bump that turns a loop into guesswork.
  • Return less. An endpoint that sends only what the screen needs leaks less when its check fails.

How to test your own application

Scanners will not do this for you. You need two accounts and a proxy.

  1. Create two ordinary users, A and B. For multi-tenant software, put them in different organizations too.
  2. Log in as A with Burp Suite or a similar proxy running. Use every feature: create, view, edit, delete, download, export, share. Make sure A owns at least one of every kind of record.
  3. In the proxy history, find every request that carries an identifier: path, query string, form body, JSON, cookies, headers.
  4. Log in as B in another browser and copy B’s session cookie.
  5. Replay each of A’s requests with B’s cookie. In Burp’s Repeater, change only the Cookie header and send. Every response should be a 404. Anything showing A’s data, or a success on a change, is a finding.
  6. Repeat with no cookie at all.
  7. For nested routes, combine B’s parent ID with A’s child ID.
  8. Check every verb, not just reads. The edit and delete paths are tested least and fail most.
  9. Test the application programming interface (API) that the mobile app or the page’s JavaScript calls, not just the pages. Those endpoints are often built later, by a different team, with less review.

Then read the code: search for queries that filter by id alone on tables holding user data, and for data access calls fed directly from request parameters.

Checklist

  • Owner or tenant from the session, in the WHERE clause, on every read and write.
  • Data access methods that require the current user; no “find by ID” on user data.
  • Child records checked through the whole chain to the owner.
  • File paths looked up, never built from the request.
  • No owner fields accepted from the client.
  • 404 for records that exist but are not yours.
  • Random IDs and enumeration alerts as layers, not as the fix.
  • Two-account tests for every endpoint that takes an ID.

Every one of these bugs is a missing question. The server knows who is asking, because the session tells it. It knows what is being asked for, because the request names it. It just never puts the two together. Put them together in the query, on every request, and this whole category disappears from your application.