Web Security Fundamentals — HTTPS, TLS, CSP, XSS & CSRF Explained
Web security protects websites and web applications from attacks like data theft, session hijacking, and code injection — every developer’s responsibility.
What You’ll Learn
In this tutorial, you’ll learn how HTTPS and TLS protect data in transit, the same-origin policy, Content Security Policy (CSP), how to prevent XSS and CSRF attacks, and how to prevent SQL injection.
Why It Matters
Web security vulnerabilities account for the majority of data breaches. A single XSS or SQL injection flaw can expose millions of user records. Understanding these fundamentals is essential for building trustworthy web applications.
Real-World Use
When you log into your bank’s website, TLS encrypts your credentials, a CSRF token prevents forged requests, Content Security Policy blocks injected scripts, and parameterized queries prevent SQL injection. Doda Browser enforces HTTPS, blocks mixed content, and warns about insecure forms to protect your browsing.
sequenceDiagram participant Client participant Server participant CA Client->>Server: 1. Client Hello (TLS version, cipher suites) Server->>Client: 2. Server Hello + Certificate Client->>CA: 3. Verify Certificate CA-->>Client: Valid Client->>Server: 4. Key Exchange (encrypted pre-master secret) Server->>Client: 5. Finished (encrypted with session key) Client->>Server: 6. Finished (encrypted with session key) Note over Client,Server: Secure Tunnel Established
HTTPS and TLS Handshake
HTTPS is HTTP encrypted with TLS. The TLS handshake establishes a secure connection:
- Client Hello: Browser sends supported TLS versions and cipher suites
- Server Hello: Server chooses version + cipher, sends its certificate
- Certificate Verification: Browser checks the certificate against trusted CAs
- Key Exchange: Client generates a pre-master secret, encrypts it with the server’s public key
- Session Keys: Both sides derive symmetric session keys from the pre-master secret
- Secure Communication: All data encrypted with session keys (AES-256-GCM)
Same-Origin Policy
The same-origin policy (SOP) is a browser security mechanism that restricts scripts from one origin from accessing data from another origin. Two URLs have the same origin only if they share the same protocol, host, and port.
| URL A | URL B | Same Origin? |
|---|---|---|
https://example.com/page1 | https://example.com/page2 | Yes |
https://example.com | http://example.com | No (different protocol) |
https://example.com | https://api.example.com | No (different host) |
https://example.com | https://example.com:8443 | No (different port) |
CORS (Cross-Origin Resource Sharing) relaxes SOP when the server sends Access-Control-Allow-Origin headers.
Content Security Policy (CSP)
CSP prevents XSS and data injection attacks by specifying which content sources are allowed. It’s implemented via the Content-Security-Policy HTTP header.
Content-Security-Policy: default-src 'self'; script-src 'self' https://analytics.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' https: data:; object-src 'none'; base-uri 'none'| Directive | Controls |
|---|---|
default-src | Fallback for all resource types |
script-src | Allowed JavaScript sources |
style-src | Allowed CSS sources |
img-src | Allowed image sources |
connect-src | Allowed fetch/XMLHttpRequest targets |
frame-ancestors | Allowed embedding sites (clickjacking) |
report-uri | Where to send violation reports |
XSS Prevention
Cross-Site Scripting (XSS) injects malicious scripts into web pages. Three types:
| Type | Description | Example |
|---|---|---|
| Stored | Malicious script saved in database | Comment field with <script>alert('xss')</script> |
| Reflected | Script in URL/request reflected in response | ?q=<script>stealCookies()</script> |
| DOM-based | Client-side script uses untrusted input | innerHTML = location.hash |
Prevention
from markupsafe import escape
# BAD: Raw user input in template (XSS vulnerable)
# template.render(user_input)
# GOOD: Escaped output
safe_output = escape(user_input)
print(f"<div>{safe_output}</div>") # <script> becomes harmless
# Python web frameworks auto-escape templates
from flask import Flask
app = Flask(__name__)
@app.route("/search")
def search():
query = escape(request.args.get("q", ""))
return f"<p>Search results for: {query}</p>"CSRF Prevention
Cross-Site Request Forgery (CSRF) tricks users into performing actions they didn’t intend. If a user is logged into their bank, a malicious site can submit a transfer form.
CSRF tokens prevent this: the server embeds a random token in every form. When the form is submitted, the server verifies the token matches.
import secrets
from flask import session, render_template_string
# Generate CSRF token
def generate_csrf_token():
if "_csrf_token" not in session:
session["_csrf_token"] = secrets.token_hex(32)
return session["_csrf_token"]
# Template with CSRF token (simplified)
form_html = '''
<form method="POST" action="/transfer">
<input type="hidden" name="csrf_token" value="{{ csrf_token }}">
<input type="text" name="amount" placeholder="Amount">
<button type="submit">Transfer</button>
</form>
'''
# Verification on server
def verify_csrf(token):
stored = session.get("_csrf_token")
return secrets.compare_digest(stored, token)SQL Injection Prevention
SQL injection occurs when user input is concatenated into SQL queries. Always use parameterized queries.
import sqlite3
# BAD: String concatenation (SQL injection!)
def get_user_bad(username):
conn = sqlite3.connect("users.db")
cursor = conn.execute(f"SELECT * FROM users WHERE username = '{username}'")
# Input: ' OR '1'='1 → SELECT * FROM users WHERE username = '' OR '1'='1'
return cursor.fetchall()
# GOOD: Parameterized query
def get_user_good(username):
conn = sqlite3.connect("users.db")
cursor = conn.execute(
"SELECT * FROM users WHERE username = ?",
(username,)
)
return cursor.fetchall()Common Mistakes
- Only using HTTPS for login pages: Once the user is authenticated, a single HTTP request can leak the session cookie. Enforce HTTPS site-wide.
- Setting
SameSitetoNonewithoutSecure:SameSite=NonerequiresSecure(HTTPS). Without it, the cookie is rejected by modern browsers. - Trusting all CORS origins:
Access-Control-Allow-Origin: *allows any site to read your API responses. Use specific origins for authenticated endpoints. - Not validating CSP reports: CSP generates reports when violations occur. Ignoring these means missing actual attacks.
- Using
innerHTMLinstead oftextContent:innerHTMLparses and renders HTML, enabling DOM-based XSS. UsetextContentfor text.
Practice Questions
What does a TLS handshake accomplish? Authenticates the server (via certificate), negotiates encryption algorithms, and establishes symmetric session keys.
How does CSP prevent XSS? It whitelists allowed script sources. The browser blocks any script not from an allowed source, even if injected into the page.
What is a CSRF token and how does it work? A random value embedded in each form. The server validates it on submission, preventing forged cross-origin requests.
How do parameterized queries prevent SQL injection? User input is treated as data, not executable SQL. The database driver handles escaping and quoting automatically.
What’s the difference between XSS and CSRF? XSS injects malicious scripts into a trusted page. CSRF tricks the user’s browser into making unintended requests to a trusted site.
Challenge
Set up CSP headers for a simple web application. Test with inline scripts blocked. Use report-uri to capture violations. Then add nonce-based script loading to allow specific inline scripts.
Real-World Task
Check your favorite website’s security headers: curl -I https://example.com. Look for Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options, and X-Frame-Options.
Mini Project: Web Security Scanner
Build a Python tool that checks a website’s security headers, tests for basic XSS vulnerabilities (reflected), verifies HTTPS configuration, and generates a security score.
Security angle: Web security is a core competency for Durga Antivirus Pro, which scans websites for threats before you click.
What’s Next
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
What’s Next
Congratulations on completing this Web Security tutorial! Here’s where to go from here:
- Practice daily — Consistency is more important than long study sessions
- Build a project — Apply what you learned by building something real
- Explore related topics — Check out other tutorials in the same category
- Join the community — Discuss with other learners and share your progress
Remember: every expert was once a beginner. Keep coding!
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro