EthicsComputerCourses
Join training +91 90532 10052

HTML Security Testing

HTML · Lesson 210 of 234 Advanced 12 min read Updated

By the end of this lesson you will be able to test your own website's security in a repeatable way: check headers from the command line, evaluate a Content Security Policy, test output escaping with a harmless marker, audit forms, mixed content and Subresource Integrity, check dependencies with npm audit and run a passive ZAP baseline scan. You will also know how to report a problem on someone else's site.

What you should know first: Advanced HTML Security Architecture (which headers to send and why), Content Security Policy Advanced, Clickjacking Protection, Subresource Integrity (SRI), Secure Form Handling and HTML Injection & DOM-Based XSS. Those lessons build the defences; this one checks that they are really there.

Test only what you own

Security testing means sending requests designed to find weaknesses. On your own site, or with written permission from the owner, that is responsible engineering. On anyone else's site it can be a crime. In India, the IT Act 2000 treats accessing or damaging a computer system without the owner's permission as an offence with civil and criminal penalties. "I was only testing" is not a defence. This is general information, not legal advice.

Good habits:

  • Test a local copy or a staging server, not production, unless the owner agrees in writing.
  • Write down the scope: which hostnames, which tests, which dates, who approved.
  • Use only passive checks and harmless markers. Never try to read other people's data.

A fire inspector in Pune may test the alarms of the office that hired her, not the building next door.

Step 1: check the response headers

Headers come first: one missing config line removes a protection from every page. curl -sI sends a HEAD request and prints only the headers. Here is a PHP 8.4 test site for a Rohtak cycle shop, first with PHP's defaults:

Terminal
php -S 127.0.0.1:8211 -t site
curl -sI http://127.0.0.1:8211/index.php
Output
HTTP/1.1 200 OK
Host: 127.0.0.1:8211
Date: Sun, 15 Nov 2026 16:34:25 GMT
Connection: close
X-Powered-By: PHP/8.4.27
Set-Cookie: PHPSESSID=9d1d043812376acbd3e0f8acaecb15ad; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-type: text/html; charset=UTF-8

No CSP, no nosniff, a session cookie without Secure, HttpOnly or SameSite, and the exact PHP version advertised. Then the same site, started with a headers.php file that runs before every page (php -d auto_prepend_file=headers.php -S ...):

Output
HTTP/1.1 200 OK
Host: 127.0.0.1:8211
Date: Sun, 15 Nov 2026 16:34:37 GMT
Connection: close
Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Set-Cookie: PHPSESSID=a3c9f7ad38029e4963172a1e4b36e471; path=/; secure; HttpOnly; SameSite=Lax
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-type: text/html; charset=UTF-8

Strict-Transport-Security (HSTS) is missing on purpose: browsers ignore it over plain HTTP, so check it on the live HTTPS site, together with the redirect from http:// to https://. To grade a set of headers, paste them into the checker in Advanced HTML Security Architecture.

You can also check from inside the page. Run this in the DevTools Console on your own site:

JavaScript
(async () => {
  const res = await fetch(location.href, { method: "HEAD", cache: "no-store" });
  const wanted = ["content-security-policy", "strict-transport-security", "x-content-type-options",
                  "referrer-policy", "permissions-policy", "cross-origin-opener-policy"];
  for (const name of wanted) {
    const value = res.headers.get(name);
    console.log(`${value ? "OK     " : "MISSING"} ${name}${value ? ": " + value.slice(0, 50) : ""}`);
  }
  console.log(`Leaks version: ${res.headers.get("server") ?? res.headers.get("x-powered-by") ?? "no"}`);
})();
Output
OK      content-security-policy: default-src 'self'; object-src 'none'; base-uri 'n
MISSING strict-transport-security
OK      x-content-type-options: nosniff
OK      referrer-policy: strict-origin-when-cross-origin
OK      permissions-policy: camera=(), microphone=(), geolocation=()
MISSING cross-origin-opener-policy
Leaks version: no

Scripts can never read Set-Cookie, so check cookie flags with curl or the DevTools Application panel.

Step 2: evaluate the CSP

Having a CSP is not the same as having a useful one. Google's open-source csp_evaluator library (also behind the CSP Evaluator website and Lighthouse's "Ensure CSP is effective against XSS attacks" check) reads a policy and lists weaknesses. A small Node script, using version 1.1.8:

JavaScript
// csp-check.mjs: node csp-check.mjs "<policy>"
import { CspParser } from "csp_evaluator/dist/parser.js";
import { CspEvaluator } from "csp_evaluator/dist/evaluator.js";
import { Severity } from "csp_evaluator/dist/finding.js";

const csp = new CspParser(process.argv[2]).csp;
const findings = new CspEvaluator(csp).evaluate();
const name = (n) => Object.keys(Severity).find((k) => Severity[k] === n);

for (const f of findings.sort((a, b) => a.severity - b.severity)) {
  console.log(`${name(f.severity).padEnd(12)} ${f.directive.padEnd(12)} ${f.description}`);
}
if (!findings.length) console.log("No findings");
Terminal
node csp-check.mjs "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net"
node csp-check.mjs "script-src 'nonce-KY0rTlP6WP8NMjjXPnCRNQ==' 'strict-dynamic'; object-src 'none'; base-uri 'none'"
Output
HIGH         script-src   'unsafe-inline' allows the execution of unsafe in-page scripts and event handlers.
HIGH         script-src   cdn.jsdelivr.net is known to host JSONP endpoints and Angular libraries which allow to bypass this CSP.
MEDIUM_MAYBE script-src   'self' can be problematic if you host JSONP, AngularJS or user uploaded files.
No findings

The first policy looks strict but allows inline scripts and a whole public CDN. The second, a nonce-based strict policy as built in Content Security Policy Advanced, has no findings. A nonce shorter than 8 characters would be flagged too.

Step 3: test output escaping with a harmless marker

Cross-site scripting (XSS) happens when text from a user is placed into a page as markup instead of text. You can test for the root cause without any attack code. Send a unique marker: a made-up word plus the four characters that matter in HTML, such as zx81"'<>. Then look at how it comes back. If the characters return unchanged, the page is not escaping output in that spot.

The test site has an old search page that prints the query directly, and a fixed one that uses htmlspecialchars():

Terminal
curl -s "http://127.0.0.1:8211/search-old.php?q=zx81%22%27%3C%3E"
curl -s "http://127.0.0.1:8211/search.php?q=zx81%22%27%3C%3E"
Output
<!DOCTYPE html><html lang="en"><title>Search</title><p>Results for zx81"'<></p></html>
<!DOCTYPE html><html lang="en"><title>Search</title><p>Results for zx81&quot;&#039;&lt;&gt;</p></html>

The old page returned < and > as they are, so a visitor's text could become HTML. The fixed page returned entities, so it stays text. Repeat the test for each place a value is printed: inside an attribute, inside a <script> block and inside a URL. Each needs its own encoding, as explained in Cross-Site Scripting (XSS) Prevention.

The same idea works for DOM-based problems, where JavaScript writes text into the page. Here the marker contains a harmless <i data-canary> element. If that element appears in the DOM, the renderer turned text into markup.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en-IN">
<head>
  <meta charset="utf-8">
  <title>Canary test for DOM sinks</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    .box { border: 1px solid #b0bec5; padding: 8px; margin-block: 8px; }
    .bad { color: #b00020; font-weight: bold; } .good { color: #1b5e20; font-weight: bold; }
  </style>
</head>
<body>
  <h1>Search renderer test</h1>
  <label for="q">Marker</label>
  <input id="q" size="40" value='zx81"<i data-canary>zx81</i>'>
  <button type="button" id="test">Test both renderers</button>

  <h2>Old renderer (innerHTML)</h2>
  <div class="box" id="old"></div>
  <p id="old-result"></p>
  <h2>New renderer (textContent)</h2>
  <div class="box" id="new"></div>
  <p id="new-result"></p>

  <script>
    function renderOld(q) {
      document.querySelector("#old").innerHTML = `<p>Results for ${q}</p>`;
    }
    function renderNew(q) {
      const p = document.createElement("p");
      p.textContent = `Results for ${q}`;
      document.querySelector("#new").replaceChildren(p);
    }
    function check(id) {
      const unsafe = document.querySelector(`#${id} [data-canary]`) !== null;
      const result = document.querySelector(`#${id}-result`);
      result.textContent = unsafe ? "UNSAFE: the marker became an element" : "SAFE: the marker stayed text";
      result.className = unsafe ? "bad" : "good";
    }
    document.querySelector("#test").addEventListener("click", () => {
      const q = document.querySelector("#q").value;
      renderOld(q);
      renderNew(q);
      check("old");
      check("new");
    });
    document.querySelector("#test").click();
  </script>
</body>
</html>

The old renderer shows "zx81" in italics and reports UNSAFE; the new one prints the marker as plain text. In a real project, search your code for innerHTML, outerHTML, insertAdjacentHTML and document.write, and run this marker through every one you find.

Step 4: forms, mixed content and SRI in the markup

Many problems are visible in the HTML itself. The checker below parses HTML you paste (parsing with DOMParser loads nothing) and checks it. Paste the checkMarkup function into the Console and call checkMarkup(document) to check a live page of your own.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en-IN">
<head>
  <meta charset="utf-8">
  <title>Markup security checklist</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    textarea { inline-size: 100%; block-size: 11rem; font-family: monospace; font-size: 0.85rem; }
    .FAIL { color: #b00020; } .WARN { color: #e65100; } .INFO { color: #455a64; }
  </style>
</head>
<body>
  <h1>Markup security checklist</h1>
  <label for="src">HTML of a page (served over HTTPS)</label>
  <textarea id="src"><head>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
  <link rel="stylesheet" href="https://cdn.example.net/slider.css" integrity="sha384-abc">
  <img src="http://img.example.in/cycle.jpg" alt="Hero cycle">
</head>
<body>
  <form action="/login" method="get">
    <input name="mobile" autocomplete="username">
    <input type="password" name="password" autocomplete="off">
  </form>
  <form action="http://pay.example.in/charge" method="post"><input name="amount"></form>
  <a href="javascript:void(0)" onclick="openMenu()">Menu</a>
  <iframe src="https://maps.example.com/rohtak"></iframe>
</body></textarea>
  <button type="button" id="go">Check</button>
  <ul id="out"></ul>

  <script>
    function checkMarkup(doc) {
      const out = [];
      const add = (level, text) => out.push([level, text]);
      const pageOrigin = "https://www.example.in";

      for (const el of doc.querySelectorAll("script[src], link[rel~='stylesheet'][href]")) {
        const url = new URL(el.getAttribute("src") ?? el.getAttribute("href"), pageOrigin);
        if (url.origin === pageOrigin) continue;
        if (!el.hasAttribute("integrity")) add("WARN", `No SRI on cross-origin file ${url.href}`);
        else if (!el.hasAttribute("crossorigin")) add("FAIL", `SRI without crossorigin (file will be blocked): ${url.href}`);
      }
      for (const el of doc.querySelectorAll("[src], link[href], form[action]")) {
        const value = el.getAttribute("src") ?? el.getAttribute("href") ?? el.getAttribute("action");
        if (value.startsWith("http:")) add("FAIL", `Mixed content: <${el.localName}> uses ${value}`);
      }
      for (const form of doc.querySelectorAll("form")) {
        const method = (form.getAttribute("method") ?? "get").toLowerCase();
        const hasPassword = form.querySelector("input[type=password]");
        if (hasPassword && method !== "post") add("FAIL", "Password form uses GET: the password ends up in the URL and logs");
        if (method === "post" && !form.querySelector("input[type=hidden][name*=csrf i], input[type=hidden][name*=token i]")) {
          add("WARN", `POST form to ${form.getAttribute("action")} has no CSRF token field`);
        }
      }
      for (const input of doc.querySelectorAll("input[type=password]")) {
        const ac = input.getAttribute("autocomplete");
        if (!ac || ac === "off") add("WARN", `Password field autocomplete is "${ac ?? "missing"}"; use current-password or new-password`);
      }
      const handlers = [...doc.querySelectorAll("*")].filter((el) => [...el.attributes].some((a) => a.name.startsWith("on")));
      if (handlers.length) add("WARN", `${handlers.length} element(s) with inline event handlers; a strict CSP blocks them`);
      for (const a of doc.querySelectorAll("a[href^='javascript:' i]")) add("FAIL", `javascript: URL in link "${a.textContent.trim()}"`);
      for (const frame of doc.querySelectorAll("iframe:not([sandbox])")) add("INFO", `iframe without sandbox: ${frame.getAttribute("src")}`);
      if (!doc.querySelector("meta[http-equiv='Content-Security-Policy' i]")) add("INFO", "No CSP meta tag (fine if the server sends the header)");
      return out;
    }

    function run() {
      const doc = new DOMParser().parseFromString(document.querySelector("#src").value, "text/html");
      const results = checkMarkup(doc);
      document.querySelector("#out").replaceChildren(...results.map(([level, text]) => {
        const li = document.createElement("li");
        li.className = level;
        li.textContent = `${level}: ${text}`;
        return li;
      }));
    }
    document.querySelector("#go").addEventListener("click", run);
    run();
  </script>
</body>
</html>

It reports eleven findings: jQuery from a CDN without SRI, a stylesheet with integrity but no crossorigin, an http: image and form (mixed content, which browsers upgrade or block on HTTPS pages), a password form sent with GET, a payment form without a CSRF token, autocomplete="off" on the password, an inline onclick, a javascript: link, an unsandboxed iframe and no CSP meta tag. A missing token field is a warning, not proof: some sites send the token in a header instead, so confirm on the server side. See Secure Form Handling and Secure Iframes & Sandbox Attributes for the fixes.

Step 5: dependencies and a ZAP baseline scan

Perfect HTML does not help if a library you load has a known hole. npm audit compares your lock file with the public advisory database. For a project pinned to jQuery 3.4.1 and lodash 4.17.20 (npm 10.9):

Output
# npm audit report

jquery  <=3.4.1
Severity: moderate
Potential XSS vulnerability in jQuery - https://github.com/advisories/GHSA-jpcq-cgw6-v4j6
Potential XSS vulnerability in jQuery - https://github.com/advisories/GHSA-gxr4-xjj5-5px2
fix available via `npm audit fix --force`
Will install jquery@3.7.1, which is outside the stated dependency range
node_modules/jquery

lodash  <=4.17.23
Severity: high
Command Injection in lodash - https://github.com/advisories/GHSA-35jh-r3h4-6jhm
Regular Expression Denial of Service (ReDoS) in lodash - https://github.com/advisories/GHSA-29mw-wpgm-hmr9
lodash vulnerable to Code Injection via `_.template` imports key names - https://github.com/advisories/GHSA-r5fr-rjxr-66jc
Lodash has Prototype Pollution Vulnerability in `_.unset`, `_.omit`, and `_.pullAt` functions - https://github.com/advisories/GHSA-xxjr-mmjv-4gpg
fix available via `npm audit fix --force`
Will install lodash@4.18.1, which is outside the stated dependency range
node_modules/lodash

2 vulnerabilities (1 moderate, 1 high)

To address all issues, run:
  npm audit fix --force

The command exits with code 1 when it finds problems, so CI fails. npm audit --audit-level=high fails only for high or critical issues. "Outside the stated dependency range" means a major or pinned-version change: upgrade, then retest. Libraries loaded from a CDN with a <script> tag are not in package.json, so keep a list of them and their versions and check those by hand.

ZAP (Zed Attack Proxy) is a free, open-source web scanner. It began as an OWASP project; in 2023 it left OWASP, and since September 2024 its core team works at Checkmarx, so the project now calls itself "ZAP by Checkmarx". Its baseline scan spiders a site for one minute and then reports only what it can see passively, such as missing headers and cookie flags. It sends no attacks. With Docker installed, against your own staging site:

Terminal
docker run -v "$(pwd):/zap/wrk/:rw" -t ghcr.io/zaproxy/zaproxy:stable \
  zap-baseline.py -t https://staging.example.in -r zap-report.html

-t is the target and -r writes an HTML report. The script exits with 0 when everything passes, 1 when a rule is set to FAIL, 2 for warnings only and 3 for other errors, which CI can use. A config file passed with -c sets each rule to IGNORE, WARN or FAIL, so you can tune it to your site. The full active scan does send attack traffic and needs explicit permission.

For a quick public check of a live site's headers, Mozilla's HTTP Observatory now lives on MDN at developer.mozilla.org/en-US/observatory. It grades HTTP headers and redirects. Scan results are public, so use it only on sites you own.

When you find a problem on someone else's site

Stop. Do not test further, do not download data and do not post about it. Look for the site's /.well-known/security.txt file, a standard file (RFC 9116) that names a security contact, and report privately with the URL, what you saw and the time. If there is no contact, or the problem affects an Indian product or organisation, CERT-In runs a Responsible Vulnerability Disclosure and Coordination Policy and accepts reports at vdisclose@cert-in.org.in. Read the current process on cert-in.org.in first. Give the owner reasonable time to fix it before saying anything publicly.

Common mistakes

  • Testing a site you do not own "just to see". Get written permission first.
  • Checking headers on one page only. Error pages, uploads and API responses often miss them.
  • Trusting a CSP because it exists. Evaluate it; 'unsafe-inline' or a whole CDN can make it useless.
  • Using real attack strings when a marker would do. The marker shows the same root cause safely.
  • Running npm audit fix --force blindly. It can install breaking major versions; review and retest.

Interview questions

1. How would you check a site's security headers quickly?

Run curl -sI https://site/ and read the headers, or use the DevTools Network panel. Look for CSP, HSTS, X-Content-Type-Options: nosniff, Referrer-Policy, framing protection, and cookie flags Secure, HttpOnly and SameSite. Check several page types, not just the home page.

2. How can you test for XSS without using attack payloads?

Send a unique marker containing "'<> and see how it comes back in each output context. If the characters return unencoded, that spot does not escape output and must be fixed. For DOM sinks, a harmless element in the marker, such as <i data-canary>, shows whether text became markup.

3. What does csp_evaluator check?

It parses a policy and reports weaknesses such as 'unsafe-inline', allowed hosts known to serve JSONP or old Angular, missing object-src or base-uri, and short nonces. A nonce-based policy with 'strict-dynamic' usually has no findings.

4. What is the difference between a ZAP baseline scan and an active scan?

The baseline scan spiders the site briefly and only reports what it observes passively, so it is safe for staging and CI. An active scan sends attack requests to find vulnerabilities and needs explicit permission and a test environment.

5. You notice a vulnerability on another company's website. What do you do?

Stop testing, do not access data, and report privately through the contact in their security.txt or a published disclosure programme. In India, CERT-In also coordinates vulnerability reports. Testing further without permission can break the IT Act 2000.

Key points

  • Test only your own sites or with written permission; the IT Act 2000 penalises unauthorised access.
  • curl -sI and a Console fetch show headers; check HSTS and redirects on the live HTTPS site.
  • csp_evaluator finds weak policies; a nonce-based 'strict-dynamic' policy is the target.
  • A harmless marker such as zx81"'<> reveals missing output escaping without attack code.
  • Markup checks catch missing SRI, mixed content, GET password forms, missing CSRF fields and inline handlers.
  • npm audit and a passive ZAP baseline scan can run in CI; report others' bugs privately via security.txt or CERT-In.

Exercise

Run a security test of your own Level 2 business website on your computer. Serve it with php -S (or XAMPP), record the headers with curl -sI, and add the missing ones. Evaluate your CSP with the csp-check script. Send the marker zx81"'<> to every page that prints user input and record whether it comes back encoded. Run checkMarkup(document) in the Console on each page. Write a one-page report listing each finding, its severity and the fix.

Show solution

A sample report:

Text
Scope: local copy of the business website, http://127.0.0.1:8080, tested by Priya on 20 Nov
1. HIGH   contact.php prints the name back without escaping: marker returned as zx81"'<>
          Fix: htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); retest showed zx81&quot;&#039;&lt;&gt;
2. HIGH   No Content-Security-Policy header
          Fix: nonce-based policy from includes/security-headers.php; csp-check: "No findings"
3. MEDIUM Contact form (POST) has no CSRF token field
          Fix: session token in a hidden input, checked with hash_equals() on submit
4. MEDIUM Session cookie missing HttpOnly and SameSite
          Fix: session_set_cookie_params() before session_start()
5. LOW    X-Powered-By: PHP/8.4.27 shown
          Fix: header_remove('X-Powered-By') or expose_php = Off
6. INFO   Google Maps iframe without sandbox; accepted, map needs scripts
Not tested: HSTS and HTTPS redirect (local server has no HTTPS), to check on staging

Every finding has evidence, a fix and a retest, and the report says clearly what was not tested.

Quick Quiz

1. Which curl option prints only the response headers?

2. A marker zx81"'<> comes back in the page as zx81"'<>. What does that show?

3. What does a ZAP baseline scan do?

4. You find a bug on another company's website. What should you do first?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call