Web Security
My personal learning notes on web security
By Noman
Hi there! This is my learning journal where I document everything I learn about web security. I am not an expert. I am just someone who wants to understand how web security works, step by step.
I started this because I believe the best way to learn something is to write it down in your own words. So this is me, learning out loud. If you are also learning web security, maybe this can help you too.
Web security can feel overwhelming at first. There are so many terms, so many attack types, so many things to worry about. But when you break it down one topic at a time, it starts to make sense. That is what I am trying to do here.
I am learning by doing. Reading articles, watching tutorials, practicing in labs, and writing down what I understand. Some chapters will be detailed, some will be short. It all depends on how deep I went into that topic.
If you find something wrong or missing, that is probably because I am still learning. Feel free to suggest improvements. We are all learning together.
Foreword
The internet is everywhere. We use it for banking, shopping, chatting, learning, and so much more. Almost everything we do online runs through web applications. And that means there is a lot of sensitive data flowing around. Personal info, passwords, credit cards, medical records. All of it needs to be protected.
That is where web security comes in.
Every single day, someone somewhere is trying to break into a website, steal data, or trick users into giving up their information. New vulnerabilities are found all the time. New attack methods show up. New defenses are built. It never stops.
When I first started looking into web security, I felt lost. There were so many resources out there, but most of them assumed I already knew a lot. They jumped straight into advanced stuff. They used terms I did not understand. They showed attacks without explaining why they work. I kept thinking, where do I even start?
That is why I started writing this. I wanted to create something that starts from the very beginning. Something that explains things in plain language. Something that shows not just how attacks work, but also how to defend against them. Something practical, not just theoretical.
I am not claiming this is the ultimate web security resource. It is just my attempt to learn and document things in a way that makes sense to me. If it helps you too, that is awesome.
Let us learn together.
Introduction
Welcome to my web security notes! If you are here, chances are you also want to understand how web security actually works. Maybe you are a developer who wants to write safer code. Maybe you are curious about how hackers think. Or maybe you just want to protect yourself online. Whatever your reason, you are in the right place.
Who Is This For?
Let me be honest. I am not writing this as an expert teaching you from a high tower. I am writing this as a learner sharing what I have figured out so far. That said, I think these notes can help you if you are:
- A developer who wants to stop writing vulnerable code and start building secure applications
- A beginner who is curious about cybersecurity but does not know where to start
- A student looking for a structured path through the chaos of web security topics
- A DevOps person who needs to secure deployments and infrastructure
- Anyone who just wants to understand what all these security words actually mean
You do not need any security background to follow along. If you know basic web stuff like HTML, HTTP, and JavaScript, that is great. If not, we will cover the basics anyway.
How This Is Organized
I tried to organize things in a way that actually makes sense. We start from the very basics, like how the web even works. Then we move into common attacks, how to defend against them, and eventually get into more advanced topics.
If you are completely new, I would say read it in order. Each chapter builds on the previous one. If you already know some stuff, feel free to jump around to whatever interests you.
Every chapter generally follows this pattern:
- What is it? We understand the concept first, no rush
- How does the attack work? We see it in action, safely of course
- How do we defend? We learn how to protect against it
- Practice We try it out ourselves because reading is not enough
Important: The attack techniques I describe here are for learning only. Never test them on systems you do not own or do not have permission to test. Unauthorized access is illegal and unethical. Period.
A Quick Note on Formatting
Just so you know what to expect:
- Code looks like
thiswhen it is inline - File names and paths look like this
- Important stuff shows up in blockquotes like the one above
- Terminal commands start with
$
One More Thing About Ethics
This is important so I want to say it clearly.
The things you learn here are powerful. With that power comes responsibility. Use what you learn to:
- Protect systems you are responsible for
- Test only systems you own or have written permission to test
- Practice in safe lab environments
- Help make the internet a safer place
Do not use this knowledge to harm anyone, steal data, or break into systems you are not supposed to. That is not cool. That is not what this is about.
The security community runs on trust and ethics. Let us keep it that way.
Alright, enough talking. Let us get started.
Getting Started with Web Security
Before we jump into specific attacks and defenses, let us take a step back and understand the big picture. Why does web security even matter? How do we practice safely? What does the security landscape look like right now?
This chapter is all about setting the foundation. Think of it as warming up before the real workout. We will talk about real world breaches and why they matter, how to set up a safe lab so you can practice without getting into trouble, and what the current threat landscape looks like.
But here is the thing I really want you to take away from this chapter. Web security is not just about memorizing a list of vulnerabilities. It is about developing a security mindset. That means always asking questions like:
- What could go wrong here?
- How could someone misuse this feature?
- What am I assuming that might not be true?
- If I were an attacker, what would I target?
Once you start thinking this way, you will notice security issues everywhere. Not just in code, but in everyday life. That is when you know the mindset is kicking in. And that is honestly more valuable than knowing any specific attack technique.
So let us start from the beginning. Why should you even care about web security?
Why Web Security Matters
Let me paint a picture for you. Every single day, billions of people use web applications. They log into their bank accounts. They enter their credit card details. They share personal photos and messages. They store medical records and tax documents. All of that data is floating around on the internet.
Now imagine someone gets access to all of that. Your passwords. Your money. Your private conversations. That is not a hypothetical scenario. It happens. A lot.
The Real Cost of Getting Hacked
When people think about security breaches, they often think about the technical details. Which vulnerability was exploited. What code was vulnerable. But the real impact is human.
People lose money. When a payment system gets compromised, real people lose real money. Sometimes life savings.
People lose their identity. When personal data gets stolen, attackers can open accounts in your name, take loans, and ruin your credit. Fixing that can take years.
People lose trust. When a company gets breached, users stop trusting them. And once trust is gone, it is really hard to get back.
People lose access to services. DDoS attacks can take down hospitals, banks, government services. Real people suffer when these systems go offline.
Some Real World Examples
I am not going to list a hundred breaches, but here are a few that show how serious this gets:
- Equifax (2017): 147 million people had their personal data exposed. Social security numbers, addresses, dates of birth. All because of an unpatched vulnerability.
- Yahoo (2013-2014): Every single Yahoo account was affected. That is 3 billion accounts. The breach was not even discovered until years later.
- Capital One (2019): 100 million credit card applications were exposed. A misconfigured firewall was the root cause.
These are not small incidents. These changed people's lives.
Why It Is Getting Worse
You might think that as technology improves, security would get better too. But the reality is more complicated. Here is why things are actually getting harder:
Applications are more complex. A modern web app is not just one server anymore. It is microservices, APIs, third party integrations, cloud services. More moving parts means more places for things to go wrong.
More data is online. We are putting more and more sensitive data into web applications. That makes them bigger targets.
Attacks are automated. Attackers do not sit there manually trying things anymore. They use bots that scan the entire internet for vulnerabilities automatically.
Cybercrime is professional. This is not just hobbyists in hoodies anymore. There are organized criminal enterprises with budgets, teams, and customer support for their hacking tools.
The attack surface keeps growing. Every new API, every new feature, every new integration is a potential entry point for an attacker.
What This Means For You
If you are building web applications, security is your responsibility. Not someday. Not after launch. Right now.
If you are learning web development, learning security alongside it will make you a much better developer. Secure code is good code.
If you are just curious, understanding web security helps you protect yourself online. You will spot phishing attempts. You will understand why certain settings matter. You will make better decisions about your own digital life.
The bottom line is this: web security matters because real people are affected by it. Every vulnerability you learn to prevent could be protecting someone's data, someone's money, someone's privacy.
That is why we are doing this. So let us keep going.
Setting Up Your Security Lab
Before you can practice web security, you need a safe place to do it. You cannot just go around testing attacks on random websites. That is illegal and you could get into serious trouble. What you need is your own lab environment where you can break things, learn from it, and not worry about consequences.
Why Do You Need a Lab?
Think of it like learning to drive. You do not start on a busy highway. You start in an empty parking lot where it is safe to make mistakes. A security lab is your empty parking lot.
A lab gives you:
- Legal safety. You own the systems. You can test whatever you want.
- Control. You can set up specific vulnerabilities and practice against them.
- Freedom to fail. You can break things without affecting anyone.
- Repeatability. You can reset and try again as many times as you need.
The Tools You Will Need
Let me walk you through the essential tools. Do not worry about getting everything at once. Start with the basics and add more as you go.
A Good Web Browser
You already have one. But for security work, you want to use it with some extra tools:
- Firefox with extensions like FoxyProxy, Cookie Manager, and Wappalyzer
- Chrome works too, but Firefox is more popular in the security community
An Intercepting Proxy
This is probably the most important tool. It lets you see and modify every request between your browser and the server.
- Burp Suite Community Edition is the most widely used. It is free and powerful.
- OWASP ZAP is a great free alternative. Open source and beginner friendly.
- mitmproxy is for people who prefer the command line.
Vulnerable Practice Applications
These are applications intentionally made vulnerable so you can practice safely. Think of them as punching bags for security training.
- DVWA (Damn Vulnerable Web Application) is a classic. Simple PHP app with different difficulty levels.
- Juice Shop by OWASP is a modern Angular application. It looks like a real app but is full of vulnerabilities.
- WebGoat is another OWASP project. More structured lessons.
Network Tools
These help you understand what is happening at the network level:
- Nmap for scanning ports and services
- Wireshark for analyzing network traffic
- curl for making HTTP requests from the terminal
Other Useful Tools
- SQLMap for automating SQL injection testing
- dirb or gobuster for discovering hidden directories
- hashcat or John the Ripper for password cracking practice
The Easiest Way: Docker
If Docker is installed on your machine, you can spin up vulnerable applications in seconds. No complicated setup needed.
# Start DVWA
docker run -d -p 80:80 vulnerables/web-dvwa
# Start Juice Shop
docker run -d -p 3000:3000 bkimminich/juice-shop
# Start WebGoat
docker run -d -p 8080:8080 -p 9090:9090 webgoat/webgoat
That is it. Open your browser and you are ready to practice. When you are done, just stop the container. No mess, no cleanup.
Online Practice Platforms
If you do not want to set anything up locally, there are online options too:
- HackTheBox has machines you can hack into. Great for practicing real world scenarios.
- TryHackMe is more beginner friendly with guided paths.
- PortSwigger Web Security Academy is free and created by the makers of Burp Suite. Highly recommended.
A Word of Advice
Start simple. Do not try to set up every tool at once. Get Burp Suite or ZAP, pick one vulnerable app, and start playing around. You will learn more by doing than by reading about tools.
And I cannot stress this enough: only practice on systems you own or have permission to test. Everything in this section is about setting up your own safe environment. Never test on production systems without authorization.
Alright, your lab is ready. Let us look at what the security landscape looks like right now.
The Web Security Landscape
Web security is a huge field and it keeps changing all the time. New vulnerabilities show up. New attack techniques emerge. New tools and defenses are built. It can feel overwhelming when you look at it all at once.
But do not worry. Once you understand the main categories, everything starts to fall into place. Let me break it down for you.
The Big Categories
Web security is not one single thing. It is a bunch of different areas that all connect together. Here are the main ones:
Application Security
This is about vulnerabilities in the application itself. Things like SQL injection, broken authentication, cross site scripting. These are the bugs in your code that attackers can exploit. This is what most people think of when they hear "web security" and it is also where the OWASP Top 10 lives.
Transport Security
This is about protecting data while it moves between the client and the server. Think HTTPS, TLS, SSL certificates. If your data is traveling over plain HTTP, anyone on the network can read it. Transport security makes sure that does not happen.
Client Side Security
This happens inside the browser. The Same Origin Policy, Content Security Policy, cross origin restrictions. These are the rules browsers enforce to keep websites from interfering with each other. When these rules are bypassed, that is when you get attacks like XSS and clickjacking.
Server Side Security
This is about protecting the server itself. Operating system hardening, proper configuration, file permissions, patching. If the server is not secure, nothing running on it is secure either.
API Security
APIs are everywhere now. Every modern web app has them. And they have their own set of security concerns. Authentication, authorization, rate limiting, input validation. APIs are often an afterthought when it comes to security, which makes them attractive targets.
Defense in Depth
Here is a concept you will hear a lot: defense in depth. The idea is simple. No single security measure is enough on its own. You need multiple layers of defense so that if one layer fails, the next one catches the attack.
Think of it like a castle. You have the moat, the outer wall, the inner wall, the keep. An attacker has to get through all of them. If they get past the moat, the wall is still there. If they breach the wall, the inner wall is still there.
In web security, your layers might look like this:
- Prevention. Stop attacks before they happen. Input validation, authentication, access control.
- Detection. Notice when something is wrong. Logging, monitoring, intrusion detection.
- Response. React to incidents. Incident response plans, forensics.
- Recovery. Get back to normal. Backups, disaster recovery.
The more layers you have, the harder it is for an attacker to get through.
Staying Current
Web security moves fast. What was a best practice two years ago might be outdated today. Here are some ways to keep up:
Follow security blogs and newsletters. Krebs on Security, The Hacker News, PortSwigger Blog, and Troy Hunt's blog are all great.
Monitor vulnerability databases. CVE and NVD track known vulnerabilities. Subscribe to alerts for technologies you use.
Practice on CTF platforms. Capture The Flag challenges are a fun way to learn and stay sharp. CTFtime.org lists upcoming events.
Join the community. Reddit's r/netsec, Twitter/X security community, local OWASP chapters. There are smart people sharing knowledge every day.
Read breach reports. When companies get breached, there is usually a postmortem. Read them. Learn from other people's mistakes.
You Do Not Need to Know Everything
Here is something I wish someone told me when I started: you do not need to be an expert in everything. Web security is too broad for any one person to master completely.
Pick an area that interests you and go deep. Maybe you love finding injection vulnerabilities. Maybe API security is your thing. Maybe you are into cryptography. Start somewhere, get good at it, and expand from there.
The important thing is to keep learning and keep practicing. That is what this whole journey is about.
Alright, now that we have the big picture, let us start getting into the details. Next up: understanding how the web actually works, because you cannot secure what you do not understand.
How the Web Works
You cannot secure something you do not understand. That is just a fact. Before we can talk about web vulnerabilities and how to defend against them, we need to understand how the web actually works under the hood.
I know what you are thinking. "I already know how the web works. I build websites." But trust me, most web vulnerabilities exist because developers do not fully understand the underlying protocols. There is a gap between how we think the web works and how it actually works. Attackers exploit that gap.
So let us close that gap. We are going to look at how HTTP and HTTPS work, how DNS resolves domain names, how browsers enforce security boundaries, and how cookies and sessions keep us logged in. Each of these topics has security implications that we will revisit throughout the rest of the book.
This chapter might feel like a refresher if you have been developing for a while. But I promise, looking at these fundamentals through a security lens will change how you think about them. Let us get into it.
HTTP and HTTPS Fundamentals
HTTP is the language of the web. Every time you visit a website, click a link, or submit a form, your browser is speaking HTTP to a server. If you want to understand web security, you need to understand HTTP first. Period.
The Basics: Request and Response
HTTP is simple at its core. Your browser sends a request, and the server sends back a response. That is the whole model.
A request looks like this:
GET /profile HTTP/1.1
Host: example.com
Cookie: session=abc123
And a response looks like this:
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: session=abc123; Secure; HttpOnly
<html>Hello there</html>
Every request and response has three parts:
- The start line. For requests, this is the method, URL, and version. For responses, this is the status code.
- The headers. These are key value pairs that carry metadata. Things like what type of content is being sent, who is authenticated, what cookies to set.
- The body. This is the actual data being sent. Not all requests and responses have a body.
HTTP Methods
Methods tell the server what kind of action you want to perform. The most common ones:
- GET means "give me this resource." You use it when you visit a URL or click a link. It should not change anything on the server.
- POST means "here is some data, process it." You use it when submitting a form or creating something.
- PUT means "replace this entire resource with what I am giving you."
- PATCH means "update part of this resource."
- DELETE means "remove this resource."
From a security perspective, here is the important part: some applications only protect POST endpoints but forget about GET, PUT, or DELETE. Always make sure access controls are applied consistently across all methods.
Status Codes
The server tells you what happened using status codes. Here are the ones you will see most often:
- 200 OK means everything worked
- 301 Moved Permanently means the resource has a new URL
- 302 Found means temporary redirect
- 400 Bad Request means you sent something invalid
- 401 Unauthorized means you need to log in
- 403 Forbidden means you are logged in but not allowed to do this
- 404 Not Found means the resource does not exist
- 500 Internal Server Error means something broke on the server
Security tip: sometimes applications leak information through error messages. A 500 error that shows a stack trace is telling the attacker way too much about your system.
Headers You Should Know
Headers carry a lot of important information. Here are the ones that matter most for security:
- Authorization carries authentication credentials
- Cookie sends stored cookies to the server
- Set-Cookie tells the browser to store a cookie
- Content-Type says what kind of data is in the body
- Referer tells the server which page you came from
- Origin indicates where the request originated from, used for CORS
Attackers love headers. They can manipulate headers to bypass security controls, steal information, or trick servers into doing unexpected things.
HTTPS: HTTP with Encryption
Plain HTTP sends everything in readable text. If someone is on the same network as you, they can read every request and response. Your passwords, your cookies, your data. All visible.
HTTPS fixes this by adding TLS encryption on top of HTTP. This gives you three things:
- Confidentiality. Nobody can read your data in transit.
- Integrity. Nobody can modify your data without you knowing.
- Authentication. You can verify you are talking to the real server, not an impostor.
Without HTTPS, an attacker on the same WiFi network as you can intercept and modify your web traffic. This is called a man in the middle attack and it is surprisingly easy to pull off.
The TLS Handshake
When you connect to an HTTPS site, this is roughly what happens:
- Your browser says hello and tells the server what encryption methods it supports
- The server responds with its certificate and chosen encryption method
- Your browser verifies the certificate is valid and trusted
- Both sides generate session keys
- Encrypted communication begins
All of this happens in a fraction of a second. You do not even notice it.
Common HTTPS Mistakes
Just having HTTPS is not enough. You have to configure it properly:
- Using old TLS versions. TLS 1.0 and 1.1 are broken. Only use TLS 1.2 or 1.3.
- Weak cipher suites. Not all encryption methods are equal. Some are broken and should be disabled.
- Mixed content. If your HTTPS page loads resources over HTTP, attackers can modify those resources. Everything should be HTTPS.
- Missing HSTS. Without the Strict Transport Security header, browsers might still try HTTP first before upgrading to HTTPS. That first HTTP connection is vulnerable.
- Self signed certificates. These might encrypt traffic but they do not prove identity. Anyone can create one. Only use them for development, never in production.
Key Takeaways
- HTTP is the foundation of all web communication. Understand it well.
- Every request and response has a method, headers, and optionally a body.
- HTTPS is not optional anymore. It is required for any serious application.
- Misconfigured HTTPS is almost as bad as no HTTPS at all.
- Headers are a rich attack surface. We will come back to them many times.
Now that we understand how data moves between clients and servers, let us look at how domain names get resolved and why that matters for security.
DNS and Domain Security
DNS stands for Domain Name System. You can think of it as the phonebook of the internet. When you type example.com into your browser, DNS is what translates that into an IP address like 93.184.216.34 that computers can actually use.
Most people never think about DNS. It just works in the background. But from a security perspective, DNS is incredibly important. If an attacker can manipulate DNS, they can redirect your traffic to a fake server without you ever knowing.
How DNS Resolution Works
Let me walk you through what happens when you type a URL:
- Your browser checks its own cache first. Has it looked up this domain recently?
- If not, it asks your operating system's DNS resolver.
- The resolver checks its cache. Still nothing? It asks your ISP's recursive DNS server.
- The recursive server checks its cache. If it does not know either, it starts walking up the DNS hierarchy.
- It asks the root server, which points it to the TLD server (like
.com). - The TLD server points it to the authoritative server for that domain.
- The authoritative server gives the actual IP address.
- The result gets cached at every level along the way.
This whole process usually takes milliseconds. But there are security risks at every step.
DNS Security Threats
DNS Spoofing (Cache Poisoning)
This is when an attacker corrupts a DNS cache so that a domain name points to the wrong IP address. Instead of going to your bank's website, you go to a fake site that looks identical. The attacker steals your credentials and you never realize it.
DNS Amplification Attacks
Attackers can use open DNS resolvers to launch massive DDoS attacks. They send small DNS queries with the victim's IP as the source address. The DNS server sends large responses to the victim, overwhelming their network.
Domain Hijacking
If an attacker gains control of your domain registration account, they can change the DNS records to point to their own servers. This is devastating. Your entire online presence is now under their control.
Subdomain Takeover
This one is sneaky. Say you have a subdomain like blog.example.com that points to a service like WordPress or AWS. If you stop using that service but forget to remove the DNS record, an attacker might be able to claim that subdomain on the service provider. Now blog.example.com serves their content, not yours.
How to Defend Against DNS Attacks
DNSSEC
DNSSEC adds cryptographic signatures to DNS records. This way, your browser can verify that the DNS response actually came from the legitimate domain owner and has not been tampered with. It does not encrypt DNS queries, but it ensures integrity.
DNS over HTTPS (DoH) and DNS over TLS (DoT)
These protocols encrypt your DNS queries so that nobody on your network can see which domains you are visiting. DoH sends queries over HTTPS port 443, which makes them blend in with regular web traffic. DoT uses a dedicated port 853.
Monitor Your DNS
Keep an eye on your DNS records. Set up alerts for any changes. If someone modifies your records, you want to know immediately, not weeks later.
Secure Your Registrar Account
Use a strong, unique password. Enable multi factor authentication. Keep your contact information up to date. Your domain registrar account is as important as your bank account.
Key Takeaways
- DNS translates domain names to IP addresses. It is critical infrastructure.
- DNS attacks can redirect users to fake sites without any visible signs.
- DNS spoofing, amplification attacks, domain hijacking, and subdomain takeover are the main threats.
- DNSSEC, DoH, and DoT help protect DNS queries.
- Always secure your domain registrar account with MFA.
Next, let us look at the browser itself and how it enforces security boundaries.
Browser Security Model
Your browser does a lot more than just render web pages. It is actually a security gatekeeper. It enforces rules about what code on one website can and cannot do with data from another website. These rules are what keep you safe when you have your bank open in one tab and a sketchy website in another.
Understanding the browser security model is crucial because many attacks happen when these rules are bypassed or misunderstood.
The Same Origin Policy (SOP)
This is the big one. The Same Origin Policy is the most important security boundary in the browser. It says that a web page can only access data from the same origin. It cannot access data from a different origin.
So what counts as the same origin? Two URLs have the same origin if they share the same protocol, host, and port.
Let me show you some examples. Let us say our base URL is https://example.com/page:
| URL | Same Origin? | Why |
|---|---|---|
https://example.com/other | Yes | Same protocol, host, port |
http://example.com/page | No | Different protocol (http vs https) |
https://api.example.com/page | No | Different host |
https://example.com:8080/page | No | Different port |
Why does this matter? Because without the Same Origin Policy, any website you visit could read your data from any other website you have open. A malicious site could read your bank balance, your emails, your private messages. The SOP prevents that.
What SOP Restricts
The Same Origin Policy blocks:
- Reading DOM of a different origin. Your JavaScript cannot read the content of an iframe from another site.
- Reading responses from fetch or XMLHttpRequest to a different origin.
- Accessing cookies and storage from a different origin.
What SOP Does NOT Restrict
This is where it gets interesting. The SOP does allow some cross origin interactions:
- Embedding resources. You can load images, scripts, and stylesheets from any origin. That is why CDNs work.
- Submitting forms. You can submit a form to a different origin. This is actually how CSRF attacks work.
- Navigation. You can link to and navigate to any origin.
These exceptions exist because the web would not work without them. But they also create attack opportunities, which we will explore in later chapters.
Cross Origin Mechanisms
The browser provides controlled ways to do cross origin things safely:
CORS (Cross Origin Resource Sharing)
CORS is a way for servers to explicitly allow cross origin requests. The server sends headers like Access-Control-Allow-Origin to tell the browser "yes, this origin is allowed to read my data." We will dive deep into CORS in Chapter 14.
postMessage
The window.postMessage API allows two windows from different origins to communicate. The receiving window can check the origin of the message and decide whether to trust it.
JSONP
This is an older technique that is mostly obsolete now. It works by dynamically creating script tags that call a callback function. It is insecure and should not be used in new projects. I am only mentioning it because you might see it in older codebases.
Browser Storage
Browsers give you several ways to store data, and each has different security properties:
Cookies
Cookies are sent with every HTTP request to the matching domain. They can be protected with:
- Secure flag: only sent over HTTPS
- HttpOnly flag: not accessible via JavaScript
- SameSite flag: controls cross site behavior
If you do not set these flags, cookies are vulnerable to theft and misuse.
localStorage and sessionStorage
These are key value stores that are not sent with requests. They are scoped to the origin and accessible via JavaScript. That means XSS attacks can steal data from them. Never store sensitive data like tokens in localStorage if you can avoid it.
IndexedDB
A full database in the browser. Same origin scoped. Same XSS risk as localStorage.
Cache API
Used by service workers to cache responses. Same origin scoped.
The Sandbox
Browsers run web code in a sandbox. This means JavaScript cannot:
- Access your filesystem directly
- Make arbitrary network connections
- Access hardware without permission
- Interact with other applications on your computer
The sandbox is not perfect, and browser vulnerabilities do get discovered. But it is a strong baseline of protection.
Key Takeaways
- The Same Origin Policy is the most important browser security boundary.
- Same origin means same protocol, host, and port.
- SOP restricts reading data across origins but allows embedding and form submission.
- CORS, postMessage, and JSONP are mechanisms for controlled cross origin interaction.
- Browser storage has different security properties. Choose wisely based on what you are storing.
- The browser sandbox prevents web code from accessing your system directly.
Now let us look at cookies, sessions, and tokens, which are how web applications remember who you are.
Cookies, Sessions, and Tokens
The web was designed to be stateless. That means every request is independent and the server does not remember you from one request to the next. But modern web applications need to remember things. They need to know you are logged in. They need to remember what is in your shopping cart. They need to know your preferences.
That is where cookies, sessions, and tokens come in. They are the mechanisms that add state to the stateless web. And because they are so central to how applications work, they are also a major target for attackers.
Cookies
Cookies are small pieces of data that the server sends to your browser, and your browser sends back with every request to that domain. They were invented in 1994 to solve the "how do I remember this user" problem, and they are still the primary mechanism for maintaining state.
How Cookies Work
- You visit a website and log in
- The server creates a session and sends a
Set-Cookieheader in the response - Your browser stores the cookie
- Every future request to that domain includes the cookie in a
Cookieheader - The server reads the cookie and knows who you are
Cookie Attributes That Matter
A cookie is not just a name and value. It has important security attributes:
Secure. When set, the cookie is only sent over HTTPS connections. This prevents someone on the same network from stealing it. Always use this for sensitive cookies.
HttpOnly. When set, JavaScript cannot access the cookie. This protects against XSS attacks that try to steal cookies with document.cookie. Always use this for session cookies.
SameSite. Controls when the cookie is sent with cross site requests. There are three values:
- Strict: Never sent with cross site requests. Strongest protection but can break user experience, like following a link to your site from an email.
- Lax: Sent with top level navigation but not with cross site POST requests or iframe loads. This is the default in modern browsers and is a good balance.
- None: Always sent with cross site requests. Requires the Secure flag. Use this only if you really need cross site cookies.
Domain. Controls which domains receive the cookie. Be careful here. Setting it too broadly can expose the cookie to subdomains it should not reach.
Path. Controls which URL paths receive the cookie.
Expires / Max-Age. How long the cookie lasts. Session cookies without an expiry date are deleted when the browser closes. Persistent cookies stick around until they expire.
Best Practices for Cookies
Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Lax; Path=/
This is what a well configured session cookie looks like. Use this as your baseline.
Sessions
Sessions are server side storage for user data. The idea is simple: instead of storing everything in the cookie, you store just a session ID in the cookie and keep all the actual data on the server.
How Sessions Work
- You log in
- The server creates a session object in its storage (memory, database, Redis, etc.)
- The server sends you a cookie with the session ID
- On future requests, the server looks up the session data using that ID
Security Concerns with Sessions
Session hijacking. If someone steals your session ID, they can impersonate you. This can happen through network sniffing, XSS, or predictable session IDs.
Session fixation. An attacker forces you to use a session ID they already know. After you log in, they use that same ID to access your account.
Session prediction. If session IDs are not random enough, an attacker might be able to guess valid ones.
Session Best Practices
- Use cryptographically random session IDs (128 bits minimum)
- Regenerate the session ID after login to prevent fixation
- Set a session timeout so inactive sessions expire
- Store session data server side, never trust client side data
- Invalidate sessions on the server when users log out, not just on the client
Tokens (JWT)
JSON Web Tokens, or JWTs, are a different approach. Instead of storing session data on the server, everything is stored in the token itself. The server does not need to look anything up. It just verifies the token signature and trusts the data inside.
JWT Structure
A JWT has three parts separated by dots:
header.payload.signature
The header says what algorithm was used. The payload contains the actual data (called claims). The signature proves the token has not been tampered with.
Here is what a decoded JWT looks like:
// Header
{
"alg": "HS256",
"typ": "JWT"
}
// Payload
{
"sub": "1234567890",
"name": "Noman",
"iat": 1516239022,
"exp": 1516242622
}
Where JWTs Go Wrong
JWTs are powerful but they have some common pitfalls:
The "none" algorithm attack. If the server accepts tokens with the algorithm set to "none", anyone can create a valid token with any claims they want. Always validate the algorithm.
Algorithm confusion. Some implementations accept either HMAC or RSA algorithms. An attacker who knows the public key can sign a token using HMAC with the public key as the secret. The server might verify it incorrectly.
Weak secrets. If you use HMAC and your secret is weak or common, an attacker can brute force it and sign their own tokens.
No revocation. JWTs are stateless. Once issued, they are valid until they expire. There is no easy way to revoke a JWT. If a token is stolen, the attacker can use it until it expires.
Storing sensitive data. The payload is just base64 encoded, not encrypted. Anyone who gets the token can read the data. Never put passwords or secrets in a JWT payload.
JWT Best Practices
- Use strong secrets (32+ characters, random) or better yet, use asymmetric algorithms like RS256 or ES256
- Set short expiration times (15 minutes for access tokens)
- Use refresh tokens for longer sessions
- Never store sensitive data in the payload
- Store tokens in HttpOnly cookies, not localStorage, to protect against XSS
- Implement a token blacklist if you need revocation
Cookies vs Sessions vs Tokens: When to Use What
There is no single right answer. Here is a simple way to think about it:
-
Cookies + Server Sessions are great for traditional web applications. The server controls everything and can easily invalidate sessions.
-
JWTs are great for APIs and microservices where you want stateless authentication. But you need to handle expiration and revocation carefully.
-
Cookies with JWTs inside can give you the best of both worlds. The cookie is HttpOnly (safe from XSS) and the JWT inside means the server can verify without a database lookup.
Key Takeaways
- Cookies, sessions, and tokens are how the web remembers who you are.
- Always set Secure, HttpOnly, and SameSite flags on cookies.
- Sessions store data server side. Tokens store data client side.
- JWTs are not encrypted. Never put secrets in the payload.
- Store tokens in HttpOnly cookies, not localStorage.
- There is no perfect solution. Choose based on your application's needs.
Now that we understand the fundamentals, we are ready to dive into actual attacks. Next up: injection attacks, one of the most common and dangerous classes of web vulnerabilities.
Injection Attacks
Injection attacks occur when untrusted data is sent to an interpreter as part of a command or query. The attacker's hostile data tricks the interpreter into executing unintended commands or accessing unauthorized data. Injection flaws are among the most common and dangerous web vulnerabilities, consistently ranking at the top of the OWASP Top 10.
This chapter covers the various types of injection attacks that target web applications. You will learn how each type of injection works, how to identify vulnerable code, and how to defend against these attacks using parameterized queries, input validation, and other proven techniques.
Injection attacks are particularly dangerous because they can lead to complete system compromise. A successful SQL injection, for example, can allow an attacker to read, modify, or delete the entire database. Command injection can give attackers shell access to the server. Understanding these attacks is essential for any web developer or security professional.
SQL Injection
SQL Injection (SQLi) is one of the most well-known and impactful web vulnerabilities. It occurs when user input is incorporated into SQL queries without proper sanitization or parameterization, allowing attackers to manipulate the query's logic.
How SQL Injection Works
Consider a login query like:
SELECT * FROM users WHERE username = '{username}' AND password = '{password}'
If an attacker enters ' OR '1'='1 as the username, the query becomes:
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = ''
Since '1'='1' is always true, the query returns all users, bypassing authentication.
Types of SQL Injection
In-Band SQL Injection
The attacker uses the same communication channel to launch the attack and gather results. This includes error-based and union-based SQLi.
Blind SQL Injection
The attacker asks the database true/false questions and observes the application's response to infer data. This includes boolean-based and time-based blind SQLi.
Out-of-Band SQL Injection
The attacker uses different channels to launch the attack and gather results, such as making the database send data to an external server.
Prevention
- Use parameterized queries (prepared statements) - This is the most effective defense
- Use ORMs - Most ORMs automatically parameterize queries
- Input validation - Validate and sanitize all user input
- Least privilege - Database accounts should have minimal necessary permissions
- Web Application Firewall - Can detect and block SQL injection attempts
NoSQL Injection
As NoSQL databases like MongoDB, CouchDB, and Redis have gained popularity, a new class of injection attacks has emerged. NoSQL injection exploits the differences in query syntax and evaluation mechanisms specific to NoSQL databases.
MongoDB Injection
MongoDB queries use JavaScript-like object syntax. An attacker can exploit this by injecting query operators. For example, a login query:
db.users.find({ username: username, password: password })
If the attacker sends { "$ne": "" } as the password, the query matches any user where the password is not empty, bypassing authentication.
Prevention
- Validate and sanitize input types (ensure strings, not objects)
- Use MongoDB's query language carefully
- Apply the principle of least privilege to database accounts
- Use middleware to filter input before it reaches the database
Command Injection
Command injection occurs when an application passes user input to a system shell command. If the input is not properly sanitized, an attacker can inject additional commands that are executed with the privileges of the application.
Example
Consider a web application that pings a user-provided IP address:
import os
ip = request.getParameter('ip')
os.system('ping -c 4 ' + ip)
An attacker could provide input like 8.8.8.8; cat /etc/passwd, which would execute both the ping command and the cat /etc/passwd command.
Prevention
- Avoid shell commands - Use language-native libraries instead of shell commands
- Input validation - Use whitelist validation (e.g., only allow IP address format)
- Parameterized execution - Use execvp or similar functions that don't invoke a shell
- Least privilege - Run the application with minimal necessary permissions
LDAP Injection
LDAP injection attacks exploit applications that construct LDAP queries from user input. Similar to SQL injection, LDAP injection allows attackers to modify the logic of LDAP queries to bypass authentication, access unauthorized data, or modify LDAP directory entries.
Example
A login query might look like: (& (uid={username})(userPassword={password})). An attacker entering *)(|(& as the username could bypass authentication.
Prevention
- Use parameterized LDAP queries
- Encode and escape LDAP special characters
- Validate input against expected patterns
- Apply least privilege to LDAP service accounts
Server-Side Template Injection (SSTI)
Server-Side Template Injection occurs when user input is embedded directly into a server-side template engine (like Jinja2, Twig, or Freemarker) rather than being passed as data. This allows attackers to inject template directives that can execute arbitrary code on the server.
Detection
Try injecting template syntax like {{7*7}} and observe if the output contains 49. If it does, the application may be vulnerable to SSTI.
Prevention
- Never embed user input directly in templates
- Pass user input as data parameters to the template
- Use sandboxed template environments
- Keep template engines updated
Cross-Site Scripting (XSS)
Cross-Site Scripting (XSS) is one of the most prevalent web vulnerabilities. It occurs when an application includes untrusted data in a web page without proper validation or escaping, allowing attackers to execute malicious scripts in the victim's browser.
XSS attacks can steal session tokens, redirect users to malicious sites, deface websites, and perform actions on behalf of the victim. Understanding XSS is essential because it is both common and impactful, affecting millions of websites worldwide.
This chapter covers the three main types of XSS attacks, how they work, and comprehensive strategies for preventing them.
Reflected XSS
Reflected XSS occurs when malicious input is included in the immediate response from the web application. The attack is reflected off the web server. This typically happens through URL parameters or form inputs that are displayed back to the user without proper encoding.
How It Works
- An attacker crafts a URL containing malicious JavaScript
- The victim clicks the link (often through phishing)
- The server includes the malicious input in the response
- The victim's browser executes the script
Example
A search page that reflects the query parameter: https://example.com/search?q=<script>alert('XSS')</script>
If the search term is displayed without encoding, the script executes.
Prevention
- Encode output based on context (HTML, JavaScript, URL, CSS)
- Use Content Security Policy headers
- Validate and sanitize input
- Use modern framework auto-escaping features
Stored XSS
Stored XSS (also known as persistent XSS) occurs when malicious input is stored on the server and later displayed to other users without proper encoding. This is the most dangerous form of XSS because it affects all users who view the compromised content.
How It Works
- An attacker submits malicious content (e.g., in a comment or profile field)
- The server stores the content without sanitization
- Other users view the page containing the malicious content
- Their browsers execute the injected script
Prevention
- Sanitize and encode all user-generated content on output
- Use HTML sanitization libraries (DOMPurify, bleach)
- Implement Content Security Policy
- Use HTTP-only cookies for session identifiers
DOM-Based XSS
DOM-based XSS is a variant where the vulnerability exists entirely in the client-side code. The malicious payload is executed as a result of modifying the DOM environment in the victim's browser, without the payload ever being sent to the server.
Example
const name = new URLSearchParams(window.location.search).get('name');
document.getElementById('greeting').innerHTML = 'Hello, ' + name + '!';
An attacker could craft: ?name=<img src=x onerror=alert(1)>
Prevention
- Avoid using dangerous sinks like innerHTML, eval, document.write
- Use textContent instead of innerHTML when possible
- Sanitize data before passing to sinks
- Use DOMPurify for HTML content
XSS Prevention and Mitigation
Preventing XSS requires a multi-layered approach that addresses both input handling and output encoding.
Output Encoding
Context-sensitive output encoding is the most important defense:
- HTML body: Encode special characters
- HTML attributes: Encode all special characters
- JavaScript: Use JavaScript encoding for data in script blocks
- URL: Encode data in URL parameters
- CSS: Encode data in style blocks
Content Security Policy (CSP)
CSP restricts which scripts can execute on a page:
Content-Security-Policy: default-src 'self'; script-src 'self'
Framework Protections
Modern frameworks provide built-in XSS protections:
- React automatically escapes JSX expressions
- Angular sanitizes values bound to the DOM
- Vue.js escapes HTML interpolation
- Django templates auto-escape by default
Cross-Site Request Forgery (CSRF)
Cross-Site Request Forgery (CSRF) is an attack that forces an authenticated user to execute unwanted actions on a web application where they are currently authenticated. CSRF exploits the trust that a web application has in the user's browser.
CSRF attacks can change account details, make purchases, transfer funds, or perform any action the authenticated user is authorized to do. Because the attack uses the victim's own authentication, the server cannot distinguish between a legitimate request and a forged one without proper protections.
Understanding CSRF Attacks
CSRF works by exploiting the way browsers handle cookies and authentication tokens. When a user is authenticated, their browser automatically includes session cookies with every request to that domain.
Attack Example
A user is logged into their bank at bank.com. They visit a malicious site that contains an image tag pointing to a transfer URL. The browser sends the request with the user's session cookie, and the bank processes the transfer because the request appears legitimate.
Prevention
- Use anti-CSRF tokens in forms
- Verify Origin and Referer headers
- Set SameSite attribute on cookies
- Require re-authentication for sensitive actions
CSRF Prevention Techniques
Several effective techniques exist for preventing CSRF attacks.
Anti-CSRF Tokens
A unique, unpredictable token is generated for each session or form and included as a hidden field. The server validates the token before processing the request.
Double Submit Cookie
The CSRF token is sent both as a cookie and as a request parameter. The server verifies they match. This is stateless and easier to implement.
Additional Measures
- Verify the Origin and Referer headers
- Require re-authentication for sensitive actions
- Use custom request headers (X-Requested-With)
- Implement rate limiting on sensitive endpoints
SameSite Cookie Attribute
The SameSite cookie attribute provides built-in CSRF protection at the browser level.
SameSite Values
- Strict: Cookies only sent with same-site requests
- Lax: Cookies sent with same-site requests and top-level navigations (default in modern browsers)
- None: Cookies sent with all requests (requires Secure flag)
Implementation
Set-Cookie: session=abc123; SameSite=Lax; Secure; HttpOnly
Authentication and Authorization
Authentication and authorization are the cornerstones of web application security. Authentication verifies who a user is, while authorization determines what they are allowed to do.
This chapter covers the fundamentals of authentication and authorization, common vulnerabilities, and best practices for implementing secure access control in web applications.
Authentication Fundamentals
Authentication is the process of verifying the identity of a user. In web applications, authentication typically involves verifying that users are who they claim to be.
Authentication Factors
- Something you know - Password, PIN, security questions
- Something you have - Phone, hardware token, smart card
- Something you are - Fingerprint, face recognition, iris scan
Multi-factor authentication (MFA) combines two or more factors for stronger security.
Password Security
Passwords remain the most common form of authentication, making password security a critical concern.
Password Storage
Never store passwords in plaintext. Use adaptive hashing algorithms:
- bcrypt - Designed for password hashing with built-in salt
- scrypt - Memory-hard function resistant to GPU attacks
- Argon2 - Winner of the Password Hashing Competition
Password Policies
- Minimum length of 12+ characters
- Check against commonly used passwords
- Implement rate limiting on login attempts
- Use haveibeenpwned API to check for breached passwords
Multi-Factor Authentication (MFA)
Multi-Factor Authentication requires users to provide two or more verification factors, significantly reducing the risk of unauthorized access.
Types of MFA
- SMS OTP - One-time code via text message
- Authenticator apps - TOTP codes (Google Authenticator, Authy)
- Hardware tokens - YubiKey, FIDO2/WebAuthn
- Push notifications - Mobile app approval
- Biometrics - Fingerprint, face recognition
WebAuthn/FIDO2
WebAuthn is the modern standard for passwordless, phishing-resistant authentication using public-key cryptography and hardware authenticators.
OAuth 2.0 and OpenID Connect
OAuth 2.0 is an authorization framework that allows third-party applications to obtain limited access to user accounts. OpenID Connect (OIDC) adds an identity layer on top of OAuth 2.0.
OAuth 2.0 Flows
- Authorization Code Flow - Most secure, recommended for server-side apps
- Authorization Code Flow with PKCE - For public clients (SPAs, mobile)
- Client Credentials Flow - For server-to-server communication
Common OAuth Vulnerabilities
- Redirect URI validation bypass
- CSRF during authorization flow
- Token leakage via referrer headers
- Weak client secrets
JSON Web Tokens (JWT)
JSON Web Tokens are a compact, URL-safe way to represent claims between two parties, widely used for authentication.
Security Considerations
- Algorithm confusion - Attackers may change the algorithm to 'none'
- Weak secrets - JWTs signed with weak secrets can be cracked
- Token theft - Stolen tokens can be used until expiration
- No built-in revocation - JWTs are stateless and cannot be easily revoked
Best Practices
- Use strong, unique signing keys
- Prefer asymmetric algorithms (RS256, ES256)
- Set short expiration times
- Implement token rotation and refresh tokens
Authorization Patterns
Authorization determines what actions an authenticated user is allowed to perform.
Authorization Models
- RBAC - Role-Based Access Control
- ABAC - Attribute-Based Access Control
- ACL - Access Control Lists
- ReBAC - Relationship-Based Access Control
Common Vulnerabilities
- Broken access control
- Privilege escalation
- Insecure direct object references (IDOR)
- Missing function-level access control
Best Practices
- Deny by default
- Implement access control at every layer
- Use centralized authorization logic
- Log and monitor access control decisions
Session Management
Session management is a critical aspect of web application security. Sessions allow web applications to maintain state across multiple HTTP requests, enabling features like user authentication, shopping carts, and personalized content. However, insecure session management can lead to session hijacking, fixation, and other attacks that compromise user accounts.
This chapter covers the session lifecycle, common session attacks, and best practices for implementing secure session management.
Session Lifecycle
A web session has a well-defined lifecycle: creation, maintenance, and destruction. Understanding each phase is essential for implementing secure sessions.
Session Creation
Sessions are typically created when a user authenticates. The server generates a unique session identifier and stores it as a cookie in the user's browser. The session ID must be unpredictable and sufficiently long to resist brute-force attacks.
Session Maintenance
During an active session, the server must validate the session ID with each request. Best practices include regenerating the session ID after privilege level changes (such as login) and implementing session timeouts.
Session Destruction
Sessions should be properly destroyed on logout, including invalidating the session ID on the server side and clearing the session cookie. Simply clearing the client-side cookie is not sufficient.
Session Hijacking
Session hijacking occurs when an attacker steals a valid session ID and uses it to impersonate the legitimate user. This can be achieved through various means:
- Network sniffing - Intercepting unencrypted session cookies on the network
- XSS attacks - Stealing cookies via JavaScript (if HttpOnly is not set)
- Predictable session IDs - Guessing session IDs if they are not sufficiently random
- Session fixation - Forcing a user to use a known session ID
Prevention
- Always use HTTPS with Secure cookies
- Set the HttpOnly flag on session cookies
- Use strong, random session ID generators
- Regenerate session IDs after authentication
- Implement IP binding or user-agent checking as additional verification
Session Fixation
Session fixation is an attack where the attacker forces a user to use a session ID known to the attacker. After the user authenticates, the attacker can use the known session ID to access the user's account.
Attack Methods
- URL-based session IDs - Attacker sends a link with the session ID in the URL
- Cookie injection - Attacker sets a cookie via XSS or other means
- Cross-subdomain cookie - Attacker exploits cookie scope across subdomains
Prevention
- Regenerate the session ID after login
- Do not accept session IDs from URLs
- Set proper cookie domain and path attributes
- Use the SameSite cookie attribute
Secure Session Practices
Implementing secure sessions requires attention to detail at every stage of the session lifecycle.
Session ID Generation
- Use cryptographically secure random number generators
- Ensure sufficient entropy (128 bits minimum)
- Never use predictable patterns
Cookie Configuration
Set-Cookie: session_id=random128bitValue; Secure; HttpOnly; SameSite=Lax; Path=/
Session Storage
- Store session data server-side, not in cookies
- Encrypt sensitive session data at rest
- Implement proper session cleanup for expired sessions
Monitoring
- Log session creation, destruction, and anomalies
- Alert on suspicious patterns (simultaneous sessions, rapid IP changes)
- Track failed authentication attempts
API Security
APIs (Application Programming Interfaces) are the backbone of modern web applications, enabling communication between different software components and services. As APIs handle increasingly sensitive data and critical operations, API security has become a vital concern. This chapter covers security considerations for REST and GraphQL APIs, authentication patterns, rate limiting, and API gateway security.
REST API Security
REST (Representational State Transfer) APIs are the most common type of web API. Securing REST APIs involves protecting endpoints, validating inputs, and ensuring proper authentication and authorization.
Common REST API Vulnerabilities
- Broken object-level authorization (BOLA)
- Broken authentication
- Excessive data exposure
- Lack of rate limiting
- Mass assignment
Security Best Practices
- Implement proper authentication on all endpoints
- Use consistent authorization checks
- Validate and sanitize all input data
- Implement rate limiting
- Use HTTPS exclusively
- Return appropriate HTTP status codes
- Filter response data to return only what is needed
GraphQL Security
GraphQL provides a powerful query language for APIs, but its flexibility introduces unique security challenges.
GraphQL-Specific Attacks
- Query depth attacks - Deeply nested queries that exhaust server resources
- Batch queries - Multiple queries in a single request
- Introspection leakage - Schema information exposure
- Field suggestion - Information leakage through error messages
Prevention
- Implement query depth limiting
- Set query complexity limits
- Disable introspection in production
- Implement rate limiting based on query complexity
- Use persisted queries
API Authentication and Rate Limiting
API authentication and rate limiting are essential for protecting APIs from abuse and unauthorized access.
API Authentication Methods
- API keys
- OAuth 2.0 Bearer tokens
- Mutual TLS (mTLS)
- HMAC signatures
Rate Limiting Strategies
- Fixed window rate limiting
- Sliding window rate limiting
- Token bucket algorithm
- Leaky bucket algorithm
Implementation
Use HTTP headers to communicate rate limit status:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640000000
API Gateway Security
An API gateway acts as a single entry point for all API calls, providing a centralized location for implementing security policies.
Gateway Security Functions
- Authentication and authorization
- Rate limiting and throttling
- Request validation and transformation
- TLS termination
- Logging and monitoring
- IP allowlisting/blocklisting
Popular API Gateways
- Kong
- AWS API Gateway
- Nginx
- Traefik
- Envoy
Server-Side Security
Server-side security encompasses the measures taken to protect the server, its operating system, and the applications running on it from attacks. This chapter covers input validation, file upload vulnerabilities, path traversal, insecure deserialization, and Server-Side Request Forgery (SSRF).
Input Validation and Sanitization
Input validation is the first line of defense against many web attacks. All data from the client should be considered untrusted until validated.
Validation Strategies
- Whitelist validation - Only allow known-good input patterns
- Blacklist validation - Block known-bad patterns (less effective)
- Type checking - Ensure data matches expected types
- Length limits - Enforce minimum and maximum lengths
- Range checks - Validate numeric ranges
Where to Validate
- Client-side (for UX only, never trust it)
- Server-side (mandatory, the real defense)
- Database constraints (as a safety net)
Sanitization vs Validation
Validation checks if input is acceptable; sanitization cleans input to make it acceptable. Use both: validate first, then sanitize as needed.
File Upload Vulnerabilities
File upload functionality is common in web applications but introduces significant security risks if not implemented correctly.
Attack Vectors
- Remote code execution - Uploading executable files (PHP, JSP, etc.)
- Path traversal - Overwriting critical files via filename manipulation
- XSS via file content - Uploading HTML/SVG files with embedded scripts
- Denial of service - Uploading extremely large files
- MIME type confusion - Bypassing type checks via content-type spoofing
Prevention
- Validate file type by content (magic bytes), not just extension
- Store uploaded files outside the web root
- Use randomly generated filenames
- Set proper file permissions
- Implement file size limits
- Scan uploads for malware
Path Traversal
Path traversal (also known as directory traversal) allows attackers to access files and directories outside the intended directory by using sequences like ../ in file paths.
Attack Example
https://example.com/download?file=../../../etc/passwd
Prevention
- Validate and sanitize all file path inputs
- Use chroot jails or restrict base directories
- Normalize paths before validation
- Never pass user input directly to filesystem operations
- Use allowlists of permitted files or directories
Insecure Deserialization
Insecure deserialization occurs when an application deserializes untrusted data without proper validation, potentially allowing attackers to manipulate objects and execute arbitrary code.
Affected Technologies
- Java (ObjectInputStream)
- PHP (unserialize)
- Python (pickle)
- .NET (BinaryFormatter)
Prevention
- Never deserialize untrusted data
- Use simple data formats (JSON) instead of object serialization
- Implement integrity checks (digital signatures) on serialized data
- Use type-safe deserialization
- Run deserialization in a sandbox
Server-Side Request Forgery (SSRF)
SSRF occurs when an attacker can cause a server to make requests to unintended locations. This can be used to access internal services, scan internal networks, and exfiltrate data.
Attack Scenarios
- Accessing internal APIs (e.g., cloud metadata endpoints)
- Scanning internal network ports
- Reading local files via file:// protocol
- Bypassing firewalls and access controls
Prevention
- Validate and sanitize all URLs before making server-side requests
- Use allowlists of permitted domains and IP ranges
- Block requests to private IP ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
- Block cloud metadata endpoints (169.254.169.254)
- Implement network segmentation
Client-Side Security
Client-side security focuses on protecting users and their browsers from attacks that execute within the browser. As web applications increasingly rely on JavaScript and client-side frameworks, client-side security has become more important than ever. This chapter covers Content Security Policy, Subresource Integrity, postMessage security, clickjacking, and Web Workers security.
Content Security Policy (CSP)
Content Security Policy is a powerful security mechanism that helps prevent XSS and other injection attacks by specifying which sources of content are allowed to be loaded and executed.
CSP Directives
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com
Key Directives
default-src- Fallback for other directivesscript-src- Controls JavaScript sourcesstyle-src- Controls CSS sourcesimg-src- Controls image sourcesconnect-src- Controls fetch, XHR, WebSocket destinationsframe-src- Controls iframe sources
Reporting
CSP can report violations:
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-reports
Subresource Integrity
Subresource Integrity (SRI) allows browsers to verify that external resources (scripts, stylesheets) have not been tampered with by checking a cryptographic hash.
Implementation
<script src="https://cdn.example.com/library.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous"></script>
When to Use SRI
- Always for third-party CDNs
- For any external resource you don't control
- As part of a defense-in-depth strategy
PostMessage Security
The postMessage API allows cross-origin communication between windows and iframes. While it provides a safe mechanism when used correctly, improper implementation can lead to security vulnerabilities.
Security Best Practices
- Always verify the
originof incoming messages - Specify the target origin when sending messages (not
*) - Validate message data structure and content
- Never trust message data without validation
- Consider using structured clone algorithm limitations for defense
Clickjacking
Clickjacking (UI redressing) tricks users into clicking on something different from what they perceive. An attacker loads the target site in a transparent iframe and overlays it with deceptive UI elements.
Prevention
- Use
X-Frame-Options: DENYorX-Frame-Options: SAMEORIGIN - Use CSP
frame-ancestorsdirective - Implement frame-busting JavaScript (less reliable)
- Use the
sandboxattribute on iframes you control
Web Workers Security
Web Workers run JavaScript in background threads, providing performance benefits but also introducing security considerations.
Security Considerations
- Workers operate under the same origin policy
- Dedicated workers can only be created from the same origin
- Shared workers and service workers have broader scope
- Workers can make network requests subject to CORS
- Service workers can intercept and modify requests
Service Worker Security
- Service workers can only be registered over HTTPS
- They have a scoped impact based on their registration path
- Cache poisoning through service workers is a concern
- Always validate and sanitize data in service worker responses
Cryptography for the Web
Cryptography is the backbone of web security, providing the tools to protect data confidentiality, integrity, and authenticity. This chapter covers the cryptographic concepts and algorithms that every web developer and security professional should understand, from symmetric and asymmetric encryption to TLS and certificate management.
Symmetric and Asymmetric Encryption
Encryption transforms readable data into an unreadable format, protecting it from unauthorized access. There are two fundamental types of encryption: symmetric and asymmetric.
Symmetric Encryption
Uses the same key for encryption and decryption. Fast and efficient for large amounts of data.
- AES - The gold standard for symmetric encryption
- ChaCha20 - A modern stream cipher
Asymmetric Encryption
Uses a pair of keys: a public key for encryption and a private key for decryption. Essential for key exchange and digital signatures.
- RSA - Widely used for key exchange and signatures
- ECC - More efficient than RSA with equivalent security
Hybrid Encryption
In practice, web security uses both: asymmetric encryption to exchange a symmetric key, then symmetric encryption for the actual data. This is how TLS works.
Hashing and Salting
Hashing is a one-way function that converts data into a fixed-size digest. It is fundamental to password storage, data integrity verification, and digital signatures.
Cryptographic Hash Functions
- SHA-256/SHA-3 - Standard hash functions
- bcrypt/scrypt/Argon2 - Password hashing algorithms (include salt and work factor)
Why Salt?
Salting adds random data before hashing, preventing rainbow table attacks and ensuring that identical passwords produce different hashes.
Password Hashing Best Practices
- Use bcrypt, scrypt, or Argon2 (not SHA-256 directly)
- Use a unique salt per password
- Use an appropriate work factor/cost parameter
- Never use MD5 or SHA-1 for passwords
TLS/SSL Deep Dive
Transport Layer Security (TLS) is the protocol that secures HTTP traffic, creating HTTPS. Understanding TLS is essential for web security.
TLS 1.3 Handshake
- Client sends supported cipher suites and key share
- Server responds with cipher suite, certificate, and key share
- Both derive shared keys
- Encrypted communication begins
Key Concepts
- Cipher suites - Combinations of key exchange, authentication, encryption, and MAC algorithms
- Certificate chains - Hierarchical trust model
- Perfect forward secrecy - Compromising long-term keys doesn't compromise past sessions
- ALPN - Application-Layer Protocol Negotiation for HTTP/2
Certificate Management
SSL/TLS certificates are digital documents that bind a public key to an identity. Proper certificate management is crucial for maintaining secure HTTPS connections.
Certificate Types
- DV (Domain Validated) - Basic verification
- OV (Organization Validated) - Organization identity verified
- EV (Extended Validation) - Highest level of verification
Certificate Lifecycle
- Generation of key pair and CSR
- Validation by Certificate Authority
- Installation on server
- Monitoring and renewal before expiration
- Revocation if compromised
Automated Management
Let's Encrypt and ACME protocol provide free, automated certificate management.
Key Management Best Practices
Key management encompasses the generation, storage, distribution, rotation, and destruction of cryptographic keys. Poor key management can undermine even the strongest encryption.
Key Generation
- Use cryptographically secure random number generators
- Generate keys with sufficient length
- Use well-vetted libraries and algorithms
Key Storage
- Never hardcode keys in source code
- Use environment variables or dedicated secret managers
- Consider Hardware Security Modules (HSMs) for high-value keys
- Encrypt keys at rest
Key Rotation
- Rotate keys regularly
- Implement key versioning
- Plan for emergency rotation in case of compromise
Web Application Firewalls and Defenses
Web Application Firewalls (WAFs) and defense mechanisms protect web applications from common attacks by filtering and monitoring HTTP traffic. This chapter covers WAFs, rate limiting, bot protection, and DDoS mitigation.
Web Application Firewalls
A WAF sits between the web application and the internet, analyzing HTTP traffic to detect and block malicious requests.
How WAFs Work
- Signature-based detection - Matches known attack patterns
- Anomaly-based detection - Identifies deviations from normal traffic
- Behavioral analysis - Detects suspicious patterns over time
Popular WAF Solutions
- Cloudflare WAF
- AWS WAF
- ModSecurity (open source)
- Akamai Kona Site Defender
Limitations
- WAFs can be bypassed with encoding and obfuscation
- False positives can block legitimate traffic
- Not a substitute for secure coding practices
Rate Limiting and Throttling
Rate limiting controls the number of requests a user can make within a time period, protecting against abuse and denial of service.
Algorithms
- Fixed window - Simple but allows bursts at window boundaries
- Sliding window - Smoother than fixed window
- Token bucket - Allows controlled bursts
- Leaky bucket - Smooths request rate
Implementation
Rate limits should be applied at multiple levels:
- Per IP address
- Per user/account
- Per API endpoint
- Globally
Bot Protection
Bots account for a significant portion of web traffic. While some bots are legitimate (search engines), malicious bots perform credential stuffing, content scraping, and DDoS attacks.
Bot Detection Methods
- CAPTCHA challenges
- Browser fingerprinting
- Behavioral analysis
- IP reputation checks
- JavaScript challenges
Protection Solutions
- reCAPTCHA / hCaptcha
- Cloudflare Bot Management
- Akamai Bot Manager
- Custom challenge-response systems
DDoS Mitigation
Distributed Denial of Service (DDoS) attacks overwhelm a target with traffic from multiple sources, making the service unavailable to legitimate users.
Types of DDoS Attacks
- Volumetric - Overwhelm bandwidth (UDP floods, amplification attacks)
- Protocol - Exploit protocol weaknesses (SYN floods, Ping of Death)
- Application layer - Target web application logic (HTTP floods, Slowloris)
Mitigation Strategies
- Use CDN and DDoS protection services (Cloudflare, AWS Shield)
- Implement rate limiting
- Use Anycast networking
- Scale infrastructure automatically
- Have an incident response plan for DDoS events
Security Headers
HTTP security headers instruct browsers to enable built-in security mechanisms. Properly configured security headers provide a powerful defense-in-depth layer against many common web attacks. This chapter covers the most important security headers and how to configure them.
HTTP Security Headers Overview
Security headers are HTTP response headers that tell browsers how to behave when handling your site's content.
Essential Security Headers
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
Content-Security-Policy: default-src 'self'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 0
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Resource-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Testing
Use security header scanners like securityheaders.com or the observatory by Mozilla to check your headers.
HSTS and Certificate Pinning
HTTP Strict Transport Security (HSTS) forces browsers to only use HTTPS connections to your site, preventing protocol downgrade and cookie hijacking attacks.
HSTS Configuration
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
HSTS Preload
Submitting your domain to the HSTS preload list ensures browsers will only connect via HTTPS even on the first visit.
Certificate Pinning
Certificate pinning associates a specific certificate or public key with a server, preventing man-in-the-middle attacks even with a compromised CA. While HTTP pinning (HPKP) has been deprecated, pinning can still be implemented in native mobile applications.
X-Frame-Options and CORP
The X-Frame-Options header prevents clickjacking by controlling whether a page can be embedded in an iframe.
X-Frame-Options Values
DENY- Page cannot be framed at allSAMEORIGIN- Page can only be framed by same-origin pages
Cross-Origin Resource Policy (CORP)
CORP controls who can embed a resource cross-origin:
same-origin- Only same-origin can embedsame-site- Only same-site can embedcross-origin- Any origin can embed
These headers work together with COEP and COOP to provide comprehensive cross-origin isolation.
Permissions Policy
The Permissions Policy header (formerly Feature-Policy) controls which browser features and APIs can be used in the page and its iframes.
Common Permissions
Permissions-Policy: camera=(), microphone=(), geolocation=(self "https://trusted.example.com"), payment=(self)
This example disables camera and microphone, allows geolocation only from the same origin and a trusted domain, and allows payments only from the same origin.
CORS and Same-Origin Policy
The Same-Origin Policy (SOP) and Cross-Origin Resource Sharing (CORS) are fundamental browser security mechanisms that control how web applications interact across origins. Understanding these mechanisms is essential for both building secure applications and diagnosing cross-origin issues.
Same-Origin Policy Explained
The Same-Origin Policy is the most important security boundary in the browser. It prevents a malicious website from reading data from another website.
What Is an Origin?
An origin is defined by the combination of protocol, host, and port:
https://example.com:443andhttps://example.com:443- Same originhttps://example.comandhttp://example.com- Different (protocol)https://example.comandhttps://api.example.com- Different (host)
What SOP Restricts
- DOM access across origins
- XMLHttpRequest and fetch responses
- Cookie and storage access
What SOP Does NOT Restrict
- Embedding images, scripts, stylesheets
- Form submissions
- Navigating the top-level window
Cross-Origin Resource Sharing
CORS is a mechanism that allows servers to relax the Same-Origin Policy in a controlled way, permitting specific cross-origin requests while blocking others.
Simple Requests vs Preflight
Simple requests (GET, POST with certain content types) are sent directly. Non-simple requests trigger a preflight OPTIONS request first.
CORS Headers
Access-Control-Allow-Origin: https://trusted.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Security Considerations
- Never use
Access-Control-Allow-Origin: *with credentials - Validate the Origin header against an allowlist
- Be specific about allowed methods and headers
CORS Misconfigurations
CORS misconfigurations are a common security issue that can lead to cross-origin data theft and other attacks.
Common Misconfigurations
- Reflecting Origin header - Setting ACAO to the request Origin without validation
- Using null origin - Allowing
nullas a valid origin - Subdomain trust - Allowing all subdomains when only specific ones should be trusted
- Wildcard with credentials - Combining
ACAO: *withAllow-Credentials: true
Testing for CORS Misconfigurations
- Send a request with a different Origin header
- Check if the response includes permissive CORS headers
- Try various Origin values (subdomains, null, etc.)
OWASP Top 10
The OWASP Top 10 is a standard awareness document representing the most critical security risks to web applications. It is updated periodically to reflect the evolving threat landscape. This chapter revisits many of the vulnerabilities covered earlier in the book, now organized according to the OWASP Top 10 framework, providing additional context and depth.
Broken Access Control
Broken access control is the #1 risk in the OWASP Top 10 (2021). It occurs when users can act outside their intended permissions.
Common Issues
- IDOR (Insecure Direct Object Reference)
- Privilege escalation (vertical and horizontal)
- Missing access controls on API endpoints
- Forced browsing to unauthorized pages
- JWT manipulation
Prevention
- Deny by default
- Implement access control mechanisms once, reuse throughout the application
- Enforce record ownership rather than just accepting user-provided IDs
- Disable directory listing
- Log and alert on access control failures
Cryptographic Failures
Previously known as 'Sensitive Data Exposure', cryptographic failures occur when applications fail to properly protect data through encryption.
Common Issues
- Transmitting data in cleartext (HTTP instead of HTTPS)
- Using weak or deprecated algorithms
- Improper key management
- Storing passwords without proper hashing
- Not enforcing encryption (e.g., missing HSTS)
Prevention
- Classify data and apply appropriate encryption
- Use strong, up-to-date algorithms
- Encrypt data in transit (TLS 1.2+) and at rest
- Use proper key management
- Hash passwords with bcrypt/Argon2
Injection (Revisited)
Injection remains a top risk, encompassing SQL injection, NoSQL injection, OS command injection, and LDAP injection.
Why Injection Persists
Despite being well-understood, injection vulnerabilities continue to appear because:
- Developers still concatenate user input into queries
- Legacy code contains vulnerable patterns
- ORMs can be misused
- New technologies introduce new injection surfaces
Comprehensive Prevention
- Use parameterized queries consistently
- Validate all input
- Escape output based on context
- Use ORMs correctly
- Implement WAF as additional protection
Insecure Design
Insecure design refers to fundamental design flaws rather than implementation bugs. It represents a category of weaknesses expressed as missing or ineffective control design.
Examples
- No rate limiting on authentication endpoints
- Security questions that can be easily guessed
- Insecure password recovery flows
- Missing business logic validation
Prevention
- Use threat modeling during design
- Establish secure development lifecycle
- Use secure design patterns
- Write abuse case stories alongside user stories
- Implement security requirements from the start
Security Misconfiguration
Security misconfiguration is the most commonly seen vulnerability category. It includes:
- Unnecessary features enabled
- Default accounts and passwords
- Overly informative error messages
- Missing security headers
- Outdated software
- Unprotected files and directories
Prevention
- Automate the hardening process
- Use minimal platform configurations
- Review and update configurations regularly
- Implement infrastructure as code for consistency
- Run security scanners against configurations
Vulnerable and Outdated Components
Using components with known vulnerabilities is a significant risk, especially given the complexity of modern software supply chains.
Risk Factors
- You don't know all the components you use
- The software is vulnerable or outdated
- You don't scan for vulnerabilities regularly
- You don't fix underlying platforms in a timely fashion
Prevention
- Maintain a software bill of materials (SBOM)
- Remove unused dependencies
- Continuously monitor for vulnerabilities (CVE databases)
- Use automated tools (Dependabot, Snyk, npm audit)
- Only obtain components from official sources
Identification and Authentication Failures
Authentication weaknesses allow attackers to compromise passwords, keys, or session tokens to assume other users' identities.
Common Issues
- Weak password policies
- Credential stuffing
- Improper session management
- Missing multi-factor authentication
- Exposed session IDs in URLs
Prevention
- Implement MFA
- Use strong password policies
- Implement account lockout and rate limiting
- Use secure session management
- Hash passwords with modern algorithms
Software and Data Integrity Failures
This category covers code and infrastructure that does not protect against integrity violations, including using software from untrusted sources and insecure CI/CD pipelines.
Examples
- Insecure deserialization
- Unsigned or unverified code updates
- CI/CD pipeline compromises
- Auto-update functionality without integrity verification
Prevention
- Use digital signatures to verify software integrity
- Verify library dependencies
- Use SRI for CDN resources
- Secure CI/CD pipelines
- Implement code review processes
Security Logging and Monitoring Failures
Without proper logging and monitoring, breaches cannot be detected and responded to effectively.
What to Log
- Authentication events (success and failure)
- Access control failures
- Input validation failures
- Server-side errors
- API usage patterns
Best Practices
- Log sufficient context for forensics
- Ensure logs are tamper-resistant
- Implement real-time alerting
- Use centralized log management
- Regularly review and test monitoring systems
Server-Side Request Forgery
SSRF occurs when a web application fetches a remote resource without validating the user-supplied URL. It allows an attacker to coerce the application to send a crafted request to an unexpected destination.
Impact
- Access to internal services and metadata APIs
- Internal port scanning
- Remote code execution in some cases
- Data exfiltration
Prevention
- Validate and sanitize all user-supplied URLs
- Use allowlists for permitted domains
- Block requests to private/reserved IP ranges
- Disable unnecessary URL schemes
- Implement network segmentation
Secure Development Practices
Building secure applications requires security to be integrated throughout the development lifecycle, not bolted on as an afterthought. This chapter covers threat modeling, secure SDLC, code review for security, static and dynamic analysis, and dependency security.
Threat Modeling
Threat modeling is a systematic approach to identifying and prioritizing potential security threats to an application. It should be performed early in the design phase and revisited throughout development.
STRIDE Model
- Spoofing - Pretending to be another user
- Tampering - Modifying data or code
- Repudiation - Denying an action
- Information disclosure - Exposing data
- Denial of service - Making a service unavailable
- Elevation of privilege - Gaining unauthorized access
Process
- Identify assets and entry points
- Create architecture diagrams
- Identify threats using STRIDE or similar frameworks
- Rate threats by risk (likelihood x impact)
- Plan mitigations
- Validate and iterate
Secure SDLC
A Secure Software Development Lifecycle (SSDLC) integrates security practices at every stage of development.
Stages
- Requirements - Define security requirements alongside functional requirements
- Design - Perform threat modeling, use secure design patterns
- Implementation - Follow secure coding guidelines, use secure libraries
- Testing - Perform security testing (SAST, DAST, penetration testing)
- Deployment - Harden configurations, implement monitoring
- Maintenance - Apply patches, monitor for vulnerabilities
Code Review for Security
Security-focused code review is a critical practice for catching vulnerabilities before they reach production.
What to Look For
- Input validation and output encoding
- Authentication and authorization logic
- Cryptographic implementation
- Error handling and logging
- Database query construction
- File operations
- Session management
Tips
- Use checklists based on OWASP guidelines
- Review with security-specific tools alongside normal code review
- Focus on data flow from input to output
- Pay special attention to authentication and authorization code
Static and Dynamic Analysis
Security testing tools automate the detection of vulnerabilities in your code and running applications.
Static Application Security Testing (SAST)
Analyzes source code without executing it. Catches issues early in development.
- SonarQube, Semgrep, Checkmarx, CodeQL
Dynamic Application Security Testing (DAST)
Tests running applications by sending crafted inputs and observing responses.
- OWASP ZAP, Burp Suite, Nuclei
Interactive Application Security Testing (IAST)
Combines elements of SAST and DAST by instrumenting the application from within.
Software Composition Analysis (SCA)
Identifies known vulnerabilities in third-party libraries and dependencies.
Dependency Security
Modern applications rely heavily on third-party libraries and frameworks, making dependency security a critical concern.
Risks
- Known vulnerabilities in dependencies
- Typosquatting (malicious packages with similar names)
- Dependency confusion attacks
- Supply chain compromises
Best Practices
- Maintain a Software Bill of Materials (SBOM)
- Use lock files to pin dependency versions
- Regularly audit dependencies for vulnerabilities
- Use private registries and namespaces
- Verify package integrity with checksums
- Automate dependency updates (Dependabot, Renovate)
Container and Cloud Security
As applications move to containerized and cloud-native architectures, new security challenges emerge. This chapter covers Docker security, Kubernetes security, cloud security best practices, and serverless security.
Docker Security
Docker containers provide isolation, but they are not inherently secure by default. Proper configuration and best practices are essential.
Best Practices
- Use minimal base images (distroless, Alpine)
- Run containers as non-root users
- Use multi-stage builds
- Scan images for vulnerabilities
- Use read-only filesystems where possible
- Limit container capabilities
- Use resource limits
- Never store secrets in images
Kubernetes Security
Kubernetes is a complex system with many security-relevant configuration points.
Security Areas
- Cluster security - API server authentication, RBAC, network policies
- Pod security - Security contexts, pod security policies/standards
- Secret management - Using external secret managers
- Network security - Network policies, service mesh
- Supply chain - Image verification, admission controllers
Cloud Security Best Practices
Cloud environments introduce shared responsibility models and new security considerations.
Key Principles
- Implement least privilege IAM policies
- Encrypt data at rest and in transit
- Use VPCs and security groups for network isolation
- Enable logging and monitoring (CloudTrail, etc.)
- Use infrastructure as code for consistency
- Regularly audit configurations
Cloud-Native Security Tools
- AWS Security Hub, Azure Security Center, GCP Security Command Center
- CSPM (Cloud Security Posture Management) tools
- CNAPP (Cloud-Native Application Protection Platform) solutions
Serverless Security
Serverless architectures remove server management but introduce new security considerations.
Security Concerns
- Function-level access control
- Event injection via triggers
- Dependency vulnerabilities in function packages
- Inadequate logging and monitoring
- Cold start implications for security checks
Best Practices
- Validate all event input
- Use least-privilege execution roles
- Keep function dependencies minimal and updated
- Implement function-level authentication
- Monitor function execution and anomalies
Penetration Testing
Penetration testing (pentesting) simulates real-world attacks to identify vulnerabilities before malicious actors do. This chapter covers the methodology, tools, and techniques for conducting effective penetration tests on web applications.
Planning and Reconnaissance
The first phase of penetration testing involves planning the engagement and gathering information about the target.
Planning
- Define scope and rules of engagement
- Identify target systems and applications
- Determine testing methodology
- Obtain written authorization
Reconnaissance
- Passive - WHOIS, DNS, search engines, social media
- Active - Port scanning, service enumeration, banner grabbing
- OSINT - Open Source Intelligence gathering
Tools
- Nmap, Shodan, theHarvester, Maltego
Vulnerability Scanning
Vulnerability scanning automates the process of identifying known vulnerabilities in web applications and infrastructure.
Types of Scanners
- Network scanners - Nmap, Nessus, OpenVAS
- Web application scanners - OWASP ZAP, Burp Suite, Nuclei
- Specialized scanners - SQLMap, XSStrike, Nikto
Best Practices
- Scan regularly and after changes
- Verify findings manually (reduce false positives)
- Combine automated scanning with manual testing
- Document all findings with severity ratings
Exploitation
Exploitation involves attempting to actually exploit discovered vulnerabilities to demonstrate their impact.
Common Exploitation Techniques
- SQL injection exploitation with SQLMap
- XSS payload crafting and delivery
- CSRF proof-of-concept creation
- Authentication bypass techniques
- Privilege escalation
Important Guidelines
- Only exploit within the agreed scope
- Minimize impact on the target system
- Document every step carefully
- Clean up after exploitation
- Report all findings responsibly
Reporting and Remediation
The final and most important phase of penetration testing is communicating findings and helping the organization remediate vulnerabilities.
Report Structure
- Executive summary
- Scope and methodology
- Findings with severity ratings
- Detailed vulnerability descriptions
- Proof of concept
- Remediation recommendations
- Risk ratings and priorities
Remediation Priorities
- Critical and high-severity issues first
- Issues that are easily exploitable
- Issues affecting sensitive data
- Lower severity issues
- Hardening recommendations
Incident Response
No security system is perfect. When a security incident occurs, having a well-practiced incident response plan can mean the difference between a minor disruption and a catastrophic breach. This chapter covers incident response planning, detection, containment, and post-incident activities.
Incident Response Planning
An incident response plan defines the processes, procedures, and team structures for handling security incidents.
Key Components
- Incident response team and roles
- Communication plan
- Escalation procedures
- Incident classification system
- Tools and resources
- Legal and regulatory requirements
NIST Framework
- Preparation
- Detection and Analysis
- Containment, Eradication, and Recovery
- Post-Incident Activity
Detection and Analysis
Detecting security incidents quickly and analyzing them accurately is crucial for effective response.
Detection Sources
- Security monitoring tools (SIEM, IDS/IPS)
- Log analysis
- User reports
- External notifications
- Threat intelligence feeds
Analysis Techniques
- Correlate events across multiple sources
- Identify attack patterns and indicators of compromise
- Determine scope and impact
- Classify the incident by severity
- Document findings thoroughly
Containment, Eradication, and Recovery
Once an incident is detected, the immediate priority is containing the damage, removing the threat, and restoring normal operations.
Containment
- Isolate affected systems
- Block malicious IPs and domains
- Disable compromised accounts
- Preserve evidence for forensics
Eradication
- Remove malware and backdoors
- Patch vulnerabilities that were exploited
- Reset compromised credentials
- Verify system integrity
Recovery
- Restore systems from verified backups
- Monitor for re-infection
- Gradually restore services
- Validate that the threat is eliminated
Post-Incident Activities
After an incident is resolved, conducting a thorough post-incident review is essential for improving security and preventing similar incidents.
Post-Incident Review
- What happened and why?
- What was the impact?
- How was the incident detected?
- How effective was the response?
- What can be improved?
Lessons Learned
- Update the incident response plan
- Improve detection capabilities
- Address root causes
- Implement additional controls
- Share findings (anonymized) with the community
Privacy and Compliance
Web security is closely tied to data privacy and regulatory compliance. Organizations must protect personal data and comply with various regulations depending on their industry and geography. This chapter covers data privacy principles, GDPR compliance, PCI DSS, and security audits.
Data Privacy Principles
Data privacy is about giving individuals control over how their personal data is collected, used, and shared.
Key Principles
- Lawfulness, fairness, and transparency
- Purpose limitation - Data collected for specific purposes
- Data minimization - Collect only what is necessary
- Accuracy - Keep data up to date
- Storage limitation - Don't keep data longer than needed
- Integrity and confidentiality - Secure data appropriately
Privacy by Design
Incorporate privacy considerations into system design from the beginning, not as an afterthought.
GDPR Compliance
The General Data Protection Regulation (GDPR) is a comprehensive data protection law that applies to any organization processing personal data of EU residents.
Key Requirements
- Obtain explicit consent for data processing
- Provide data subject rights (access, rectification, erasure, portability)
- Implement data protection by design and by default
- Conduct Data Protection Impact Assessments
- Report data breaches within 72 hours
- Appoint a Data Protection Officer if required
Security Implications
- Encrypt personal data at rest and in transit
- Implement access controls
- Maintain processing records
- Ensure third-party compliance
PCI DSS
The Payment Card Industry Data Security Standard (PCI DSS) applies to any organization that stores, processes, or transmits cardholder data.
Key Requirements
- Maintain a secure network
- Protect cardholder data
- Maintain a vulnerability management program
- Implement strong access control measures
- Regularly monitor and test networks
- Maintain an information security policy
Web Security Implications
- Never store full card numbers unless necessary
- Use tokenization for payment processing
- Encrypt transmission of card data
- Implement strong authentication
Security Audits
Security audits provide independent assessment of an organization's security posture and compliance with standards.
Types of Audits
- Internal audits - Conducted by the organization's own team
- External audits - Performed by third-party auditors
- Compliance audits - Focused on regulatory requirements
- Penetration testing audits - Focused on technical vulnerabilities
Preparing for Audits
- Maintain up-to-date documentation
- Implement and follow security policies
- Regularly conduct self-assessments
- Keep evidence of security controls
- Train staff on security awareness
Final Project: Building a Secure Web Application
Throughout this book, you have learned about various web security threats and defenses. This final chapter brings everything together by walking through the process of building a secure web application from scratch. You will apply threat modeling, implement authentication and authorization, harden the application, and perform security testing before deployment.
Project Setup and Threat Model
Before writing any code, we start with planning and threat modeling.
Application Overview
We will build a secure task management application with user accounts, task management, and API access.
Technology Stack
- Backend: Node.js with Express
- Frontend: React
- Database: PostgreSQL
- Authentication: OAuth 2.0 + JWT
Threat Model
Using the STRIDE framework, we identify:
- Spoofing: Implement strong authentication with MFA
- Tampering: Validate all inputs, use parameterized queries
- Repudiation: Implement audit logging
- Information disclosure: Encrypt sensitive data, use HTTPS
- Denial of service: Implement rate limiting
- Elevation of privilege: Implement proper authorization
Implementing Authentication and Authorization
This section covers implementing secure authentication and authorization for our task management application.
Authentication Implementation
- Password hashing with bcrypt
- JWT-based session management
- OAuth 2.0 integration
- MFA with TOTP
Authorization Implementation
- Role-based access control
- Resource ownership validation
- API endpoint authorization
Security Headers
Implement all recommended security headers, CSP, and CORS configuration.
Hardening the Application
Application hardening involves applying defense-in-depth measures to make the application more resistant to attacks.
Input Validation
- Server-side validation for all inputs
- Parameterized queries for all database operations
- Output encoding based on context
Security Headers
- HSTS, CSP, X-Frame-Options, etc.
Cookie Security
- Secure, HttpOnly, SameSite attributes
Logging and Monitoring
- Security event logging
- Error handling without information leakage
- Audit trail for sensitive operations
Security Testing and Deployment
Before deploying, we thoroughly test the application's security and then deploy with secure configurations.
Security Testing
- SAST with Semgrep or SonarQube
- DAST with OWASP ZAP
- Dependency scanning
- Manual penetration testing
Secure Deployment
- Use HTTPS with strong TLS configuration
- Implement infrastructure as code
- Set up monitoring and alerting
- Configure automated backups
- Implement CI/CD security checks
Ongoing Security
- Regular vulnerability scanning
- Dependency updates
- Security monitoring
- Incident response plan
Appendix
The appendices provide quick reference materials, tool guides, and additional resources to support your web security journey.
Security Tools Reference
A comprehensive reference of security tools organized by category.
Proxies and Intercepting Tools
- Burp Suite (Community/Professional)
- OWASP ZAP
- mitmproxy
Scanning Tools
- Nmap
- Nikto
- Nessus
- OpenVAS
Exploitation Tools
- SQLMap
- Metasploit
- BeEF
Forensics and Analysis
- Wireshark
- Volatility
- Autopsy
Password Cracking
- Hashcat
- John the Ripper
Common Ports and Services
Reference table of commonly encountered ports and their associated services, important for network security assessments.
| Port | Service | Security Notes |
|---|---|---|
| 20/21 | FTP | Unencrypted, avoid |
| 22 | SSH | Secure if configured properly |
| 23 | Telnet | Unencrypted, never use |
| 25 | SMTP | Often misconfigured |
| 53 | DNS | Vulnerable to amplification attacks |
| 80 | HTTP | Redirect to HTTPS |
| 443 | HTTPS | Preferred |
| 3306 | MySQL | Should not be exposed |
| 5432 | PostgreSQL | Should not be exposed |
| 8080 | HTTP Proxy | Often exposed accidentally |
Cheat Sheets
Quick reference cheat sheets for common web security tasks.
XSS Prevention Cheat Sheet
- Encode output for the correct context
- Use CSP
- Use HttpOnly cookies
- Use modern frameworks with auto-escaping
SQL Injection Prevention Cheat Sheet
- Use parameterized queries
- Use stored procedures
- Validate input types
- Apply least privilege
Authentication Cheat Sheet
- Implement MFA
- Use strong password hashing
- Implement account lockout
- Use secure session management
Vulnerability Databases
Essential vulnerability databases and resources for staying current with security threats.
Primary Databases
- CVE (Common Vulnerabilities and Exposures) - cve.org
- NVD (National Vulnerability Database) - nvd.nist.gov
- CWE (Common Weakness Enumeration) - cwe.mitre.org
Vendor Databases
- Microsoft Security Response Center
- Apple Security Updates
- Google Chrome Releases
Community Resources
- Exploit Database (exploit-db.com)
- Packet Storm Security
- Full Disclosure mailing list
Further Reading and Resources
Curated list of books, websites, and courses for continued learning in web security.
Books
- The Web Application Hacker's Handbook - Stuttard & Pinto
- OWASP Testing Guide - OWASP Foundation
- Web Security for Developers - Malcolm McDonald
- Black Hat Python - Justin Seitz
Online Resources
- PortSwigger Web Security Academy (free)
- OWASP Cheat Sheet Series
- HackerOne Hacktivity
- Bugcrowd University
Certifications
- CompTIA Security+
- CEH (Certified Ethical Hacker)
- OSCP (Offensive Security Certified Professional)
- GWAPT (GIAC Web Application Penetration Tester)
Practice Platforms
- HackTheBox
- TryHackMe
- DVWA
- OWASP Juice Shop
- CTFtime.org