Skip to main content
Ethical Hacking
CHAPTER 10

Secure Web Development Practices

Updated: May 15, 2026
20 min read

# CHAPTER 10

Secure Web Development Practices

1. Introduction

Fixing SQL Injection and XSS is critical, but a truly secure web application requires a "Defense in Depth" approach. Security cannot be an afterthought bolted onto the end of the development cycle; it must be woven into the architecture from day one. This involves securing data in transit, configuring HTTP headers to protect the browser, and preventing attackers from forcing users to perform unintended actions. In this chapter, we will explore HTTPS, CSRF protection, secure cookie flags, and essential Security Headers.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the necessity of HTTPS and TLS encryption.
  • Define Cross-Site Request Forgery (CSRF).
  • Implement CSRF Tokens as a defense mechanism.
  • Understand Secure and HttpOnly cookie flags.
  • Identify critical HTTP Security Headers (HSTS, X-Frame-Options).

3. Beginner-Friendly Explanation

Imagine sending a postcard through the mail.
  • HTTP (Unencrypted): Anyone who handles the postcard—the postman, the sorting facility, your neighbor—can flip it over and read your secrets.
  • HTTPS (Encrypted): You place the postcard inside a titanium, locked briefcase. You give the briefcase to the postman. Only the intended recipient has the key to open the briefcase. Anyone else looking at it just sees a metal box.

If you are logging into an application over standard HTTP, the hacker sitting in the coffee shop sniffing the Wi-Fi can see your password in plain text.

4. Cross-Site Request Forgery (CSRF)

CSRF is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated.
  • The Setup: You log into your bank (bank.com). Your browser receives a Session Cookie.
  • The Trap: Without logging out, you open a new tab and visit a hacker's website (evil.com).
  • The Exploit: The hacker's website has a hidden script that automatically sends a request to bank.com/transfer?amount=1000&to=HackerAccount.
  • The Result: Because your browser automatically attaches your bank.com cookie to that request, the bank thinks *you* made the request, and transfers the money.

5. CSRF Defense: Anti-CSRF Tokens

To stop CSRF, the server must be able to distinguish between a legitimate request originating from its own website, and a forged request originating from evil.com. The Fix: When the user loads the legitimate transfer form, the server generates a random, cryptographically secure string (a CSRF Token) and embeds it as a hidden field in the form. When the form is submitted, the server verifies the token. Because evil.com cannot read the hidden token generated on bank.com (due to browser security rules), the forged request will not include the token, and the server will reject it.

6. Securing Session Cookies

If an attacker steals a Session Cookie via XSS or network sniffing, it's game over. You must harden your cookies using flags:
  • Secure Flag: Tells the browser: "Only send this cookie over an encrypted HTTPS connection. Never send it over HTTP." This prevents network sniffing.
  • HttpOnly Flag: Tells the browser: "Do not allow JavaScript to access this cookie." This prevents XSS attacks from reading document.cookie and stealing the session!

7. Mini Project: Harden a Demo Application

Let's look at how to implement these architectural defenses in code.

Setting Secure Cookies in PHP:

php
12345678910
// The parameters: Name, Value, Expiry, Path, Domain, SECURE, HTTPONLY
session_set_cookie_params([
    'lifetime' => 3600,
    'path' => '/',
    'domain' => 'example.com',
    'secure' => true,      // Must be HTTPS
    'httponly' => true,    // JS cannot read it
    'samesite' => 'Strict' // Prevents CSRF by stopping cross-site sending
]);
session_start();

Essential HTTP Security Headers: A web server should send these headers with every response to instruct the browser on how to behave securely:

  • Strict-Transport-Security (HSTS): Forces the browser to *always* use HTTPS, even if the user types http://.
  • X-Frame-Options: DENY: Prevents other websites from embedding your site in an <iframe>, preventing "Clickjacking" attacks.

8. Real-World Scenarios

A popular home router interface had a CSRF vulnerability. Users would log into their router's web portal to change settings, leaving the session active. Hackers created malicious advertisements and deployed them on popular websites. If a user browsed the web while their router session was active, the malicious ad silently sent a CSRF request to the router's local IP address (192.168.1.1/change_dns). The router, seeing a valid session cookie, changed the DNS settings. The hacker successfully rerouted all of the user's internet traffic through malicious servers.

9. Best Practices

  • SameSite Cookie Attribute: Modern browsers support the SameSite cookie attribute. Setting it to Lax or Strict prevents the browser from sending the session cookie along with cross-site requests (requests originating from a different domain). This is a highly effective, built-in defense against CSRF attacks.
As a defensive security professional, your job is not just to point out flaws, but to provide actionable, code-level remediation advice to developers. Telling a developer "You have CSRF" is useless; telling them "Implement Anti-CSRF tokens and the SameSite cookie attribute" adds immense value.

11. Exercises

  1. 1. Explain the mechanics of a Cross-Site Request Forgery (CSRF) attack. Why does the victim's browser automatically aid the attacker?
  1. 2. What is the specific security benefit of applying the HttpOnly flag to a Session Cookie? Which attack vector does it mitigate?

12. FAQs

Q: If I use HTTPS, does that mean my website is safe from hacking? A: No! HTTPS only encrypts the traffic *in transit* between the user and the server. It stops someone in a coffee shop from reading the data. It does absolutely nothing to prevent SQL Injection, XSS, or logic flaws on the server itself.

13. Interview Questions

  • Q: Describe the "Defense in Depth" principle. How would you apply it to secure a user's session from initiation to termination?
  • Q: A developer has implemented an Anti-CSRF token mechanism, but it is failing security audits. Upon inspection, the token is being generated via MD5(username). Identify the critical flaw in this implementation and propose a secure alternative.

14. Summary

In Chapter 10, we elevated our security posture from fixing individual bugs to implementing architectural Defense in Depth. We mandated HTTPS to protect data in transit. We analyzed the mechanics of CSRF attacks and implemented cryptographic tokens to verify request authenticity. Finally, we hardened the browser's handling of session data by enforcing the Secure and HttpOnly cookie flags, and deployed HTTP Security Headers to establish strict operational boundaries.

15. Next Chapter Recommendation

We know how to build a secure application. But how do we check if an existing network is secure before the hackers do? Proceed to Chapter 11: Vulnerability Scanning Basics.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·