Application Security

Secure Coding Practices Every Backend Developer Should Know

The OWASP Top 10 was updated last month for the first time since 2017, and broken access control is now the number one risk. This practical guide covers the secure coding practices that matter most for backend developers, mapped to the 2021 list, with examples of what to do and what to avoid.

By EthicalHat Research · · 3 min read
Infographic: The OWASP Top 10 2021, and what's new

On 24 September, OWASP published the 2021 edition of its Top 10, the most widely used list of critical web application security risks. The biggest change: broken access control moved from fifth place to first. Three new categories appeared: insecure design, software and data integrity failures, and server-side request forgery (SSRF).

For backend developers, the list is a practical checklist of where things go wrong. Here are the practices that address it, with examples.

1. Enforce access control on every request (A01)

Authentication tells you who the user is. Authorisation decides what they may do. Most access control bugs come from checking the first and forgetting the second.

python
# Vulnerable: any logged-in user can fetch any document by ID
@app.get("/documents/<int:doc_id>")
@login_required
def get_document(doc_id):
    return jsonify(Document.query.get_or_404(doc_id).to_dict())

# Secure: the query is scoped to documents the current user may access
@app.get("/documents/<int:doc_id>")
@login_required
def get_document(doc_id):
    doc = Document.query.filter_by(id=doc_id, owner_id=current_user.id).first_or_404()
    return jsonify(doc.to_dict())
  • Deny by default.
  • Enforce checks server-side, centrally where possible, not in the UI.
  • Test authorisation: for every endpoint, try it as a different user and as a lower-privileged role.

2. Use cryptography properly (A02)

  • Use TLS everywhere, including between internal services.
  • Hash passwords with a slow, salted algorithm such as bcrypt, scrypt or Argon2, never MD5, SHA-1 or unsalted SHA-256.
  • Use vetted libraries and authenticated encryption modes; never invent your own crypto.
  • Keep keys in a key management service or vault, not in code.

3. Prevent injection (A03)

Never build queries or commands by concatenating user input.

javascript
// Vulnerable
db.query(`SELECT * FROM users WHERE email = '${req.body.email}'`);

// Secure: parameterised query
db.query("SELECT * FROM users WHERE email = $1", [req.body.email]);

The same principle applies to OS commands (pass arguments as arrays, avoid the shell), LDAP, NoSQL queries and templating. Cross-site scripting is now included in this category: encode output for the context it is rendered in, and prefer frameworks that do it automatically.

4. Design for security (A04)

Some flaws cannot be fixed by better code, because the design is wrong: password reset flows that leak whether an account exists, business logic that lets a discount be applied repeatedly, or rate-limit-free endpoints for expensive operations. Threat-model features before building them.

5. Configure securely (A05)

  • Disable debug modes and verbose error pages in production.
  • Remove default accounts and sample applications.
  • Set security headers and restrictive CORS policies.
  • Apply least privilege to service accounts and database users.

6. Keep components current (A06)

Know what libraries you use, monitor them for vulnerabilities and update promptly. Automated dependency update tools make this routine rather than a crisis.

7. Get authentication right (A07)

  • Use a proven authentication framework or identity provider rather than rolling your own.
  • Support MFA, and require it for privileged accounts.
  • Protect against credential stuffing with rate limiting and breached-password checks.
  • Regenerate session IDs at login, and set cookies with Secure, HttpOnly and SameSite.

8. Protect software and data integrity (A08)

  • Verify the integrity of dependencies and updates (lock files, checksums, signatures).
  • Do not deserialise untrusted data with unsafe mechanisms such as Java native serialisation, Python pickle or YAML's unsafe loaders.
python
import yaml
config = yaml.safe_load(untrusted_text)   # never yaml.load() on untrusted input

9. Log and monitor security events (A09)

Log authentication events, access control failures, input validation failures and administrative actions, with enough context (user, IP address, resource) to investigate. Never log secrets, passwords or full payment details. Make sure someone, or something, watches the logs.

10. Prevent server-side request forgery (A10)

If your application fetches URLs supplied by users, such as webhooks, URL previews or file imports, an attacker may make it request internal services or cloud metadata endpoints.

python
import ipaddress, socket
from urllib.parse import urlparse

ALLOWED_SCHEMES = {"https"}

def is_safe_url(url: str) -> bool:
    parsed = urlparse(url)
    if parsed.scheme not in ALLOWED_SCHEMES or not parsed.hostname:
        return False
    for info in socket.getaddrinfo(parsed.hostname, 443):
        ip = ipaddress.ip_address(info[4][0])
        if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved:
            return False            # blocks internal ranges and 169.254.169.254
    return True

Resolve and check the address at connection time, not just at validation time, to avoid DNS-rebinding tricks, and use an allow-list of destinations wherever possible.

Make it stick

  • Add these checks to code review templates.
  • Use linters and SAST rules that catch the common patterns.
  • Write security unit tests for authorisation and input handling.
  • Train with examples from your own codebase.

The bottom line

The 2021 OWASP Top 10 is a reminder that the most damaging vulnerabilities are often the most basic: a missing authorisation check, a concatenated query, an unsafe deserialiser. Backend developers who make these practices habits, and teams that back them with shared libraries and automated checks, eliminate the majority of real-world web application risk.

Our security training teaches these practices hands-on in your team's languages, and our application penetration testing verifies them in your applications.

EthicalHat Research

The EthicalHat research team: penetration testers, SOC analysts and engineers writing about security, software engineering and AI.

Want an expert opinion on your own systems?

Email info@ethicalhat.com or call +1-844-838-4422. Our security engineers are happy to talk it through.