"""cookie-flags-survey-sp500.py: which cookie flags the S&P 500 companies' homepages actually set. Two steps, the second reproducible from the files the first one saved: collect domains.csv -> responses.jsonl.gz + robots.jsonl.gz. For each company website in domains.csv (the list built for email-auth-survey-sp500.py), one ordinary GET of https:///, following redirects by hand (at most 6 responses per site). Before the first request to any host, that host's robots.txt is read; the request is made only if the file allows "/" (or the redirect target's path) for this script's user agent, for "*", and for every Anthropic agent name. A robots.txt that cannot be read (401, 403, 429, 5xx, a network or certificate error) counts as a refusal; 404 or 410 means no rules. One site at a time per worker, a pause of at least one second (or the host's Crawl-delay) between two requests to one host. Only response headers are kept. Every cookie VALUE is dropped before anything is written: the saved copy keeps the cookie's name, its attributes, the value's length, and two yes/no facts about the value (all hex digits? looks like it carries an e-mail or a user/name field?). No request carries a cookie back. analyse responses.jsonl.gz -> aggregate CSV + printed report. Offline. It runs the article's own header audit (session-tokens-stolen-cookie-flags-rotation.py, same folder) over every saved cookie and counts flags: Secure, HttpOnly, SameSite, the __Host- and __Secure- prefixes, Domain, and lifetime (measured from the moment each response was received, so the numbers do not drift when the script is re-run later). Output is aggregate only: shares of sites and of cookies, by cookie family. It names no company and no site. Homepages are not login pages: most cookies set there belong to bot management, load balancers, consent tools and analytics. The report counts those families separately, and counts the cookies named like a server-side session ID. Cookies a page sets later from JavaScript never appear in a Set-Cookie header and are outside this survey. Run: python cookie-flags-survey-sp500.py collect --domains domains.csv --out run_2026-11-15 python cookie-flags-survey-sp500.py analyse --run run_2026-11-15 --csv out.csv Needs the `requests` package for collect only (tested with requests 2.34.2, Python 3.13); analyse is standard library. """ import argparse import collections import csv import datetime as dt import email.utils import gzip import importlib.util import json import os import re import statistics import sys import threading import time import urllib.parse import urllib.robotparser HERE = os.path.dirname(os.path.abspath(__file__)) _spec = importlib.util.spec_from_file_location("sessaudit", os.path.join(HERE, "session-tokens-stolen-cookie-flags-rotation.py")) A = importlib.util.module_from_spec(_spec) _spec.loader.exec_module(A) UA = "passwordpassword-research/1.0 (public-data snapshot; +https://passwordpassword.com/how-this-site-is-made.html)" ROBOT_NAMES = ["passwordpassword-research", "*", "ClaudeBot", "Claude-User", "Claude-SearchBot", "anthropic-ai"] MAX_HOPS = 6 MIN_GAP = 1.0 # seconds between two requests to one host WORKERS = 8 REDIRECTS = {301, 302, 303, 307, 308} DAY_MIN = 1440 # ------------------------------------------------------------------------------------------ collect --- def _utc(): return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") def redact(line): """One Set-Cookie header -> a record without the value.""" first, _, rest = line.partition(";") name, eq, value = first.partition("=") value = value.strip() if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] return {"name": name.strip(), "has_eq": bool(eq), "value_len": len(value), "value_hex": bool(re.fullmatch(r"[0-9a-fA-F]+", value)), "value_pii": bool("@" in value or re.search(r"(?i)(user|email|name)=", value)), "attrs": rest.strip()} class Collector: def __init__(self, out): import requests self.rq = requests self.out = out self.lock = threading.Lock() self.robots = {} # origin -> (parser or None, status, crawl_delay) self.robot_locks = collections.defaultdict(threading.Lock) self.last_hit = {} # host -> monotonic time of last request self.resp_fh = gzip.open(os.path.join(out, "responses.jsonl.gz"), "wt", encoding="utf-8") self.robots_fh = gzip.open(os.path.join(out, "robots.jsonl.gz"), "wt", encoding="utf-8") self.log_fh = open(os.path.join(out, "run.log"), "a", encoding="utf-8") def log(self, msg): with self.lock: self.log_fh.write(f"{_utc()} {msg}\n") self.log_fh.flush() def _wait(self, host, gap): while True: with self.lock: last = self.last_hit.get(host) now = time.monotonic() if last is None or now - last >= gap: self.last_hit[host] = now return delay = gap - (now - last) time.sleep(delay) def _get(self, url): host = urllib.parse.urlsplit(url).netloc gap = max(MIN_GAP, min(60.0, self.robots.get(_origin(url), (None, 0, 0))[2] or 0)) self._wait(host, gap) t0 = time.monotonic() r = self.rq.get(url, headers={"User-Agent": UA, "Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.8"}, allow_redirects=False, stream=True, timeout=(8, 15)) return r, round((time.monotonic() - t0) * 1000) def robots_for(self, url): origin = _origin(url) with self.robot_locks[origin]: if origin in self.robots: return self.robots[origin] rec = {"origin": origin, "utc": _utc(), "chain": []} target, parser, status, delay = origin + "/robots.txt", None, None, 0 try: for _ in range(5): host = urllib.parse.urlsplit(target).netloc self._wait(host, MIN_GAP) r = self.rq.get(target, headers={"User-Agent": UA, "Accept": "text/plain,*/*;q=0.5"}, allow_redirects=False, timeout=(8, 15)) rec["chain"].append({"url": target, "status": r.status_code}) if r.status_code in REDIRECTS and r.headers.get("Location"): target = urllib.parse.urljoin(target, r.headers["Location"]) continue status = r.status_code if 200 <= status < 300: text = r.content[:500_000].decode("utf-8", "replace") rec["body"] = text parser = urllib.robotparser.RobotFileParser() parser.parse(text.splitlines()) delay = max([parser.crawl_delay(n) or 0 for n in ROBOT_NAMES]) break except Exception as e: # network, TLS, timeout: unreadable = refusal rec["error"] = f"{type(e).__name__}: {str(e)[:200]}" rec["status"] = status if status in (404, 410): verdict = "no-rules" elif parser is not None: verdict = "parsed" else: verdict = "unreadable" rec["verdict"] = verdict with self.lock: self.robots_fh.write(json.dumps(rec) + "\n") self.robots[origin] = (parser if verdict == "parsed" else verdict, status, delay) return self.robots[origin] def allowed(self, url): p, _, _ = self.robots_for(url) if p == "no-rules": return True, "no robots.txt" if p == "unreadable": return False, "robots.txt unreadable" refused = [n for n in ROBOT_NAMES if not p.can_fetch(n, url)] return (not refused), ("refused for " + ",".join(refused) if refused else "allowed") def site(self, row): host = row["host"] url = f"https://{host}/" seen = set() for hop in range(MAX_HOPS): ok, why = self.allowed(url) rec = {"domain": row["domain"], "sector": row["gics_sector"], "hop": hop, "url": url, "robots": why} if not ok: rec["skipped"] = True rec["utc"] = _utc() self._write(rec) return try: r, ms = self._get(url) except Exception as e: rec.update({"utc": _utc(), "error": f"{type(e).__name__}: {str(e)[:200]}"}) self._write(rec) return raw = r.raw.headers cookies = [redact(v) for v in raw.getlist("Set-Cookie")] headers = [[k, v] for k, v in raw.items() if k.lower() != "set-cookie"] rec.update({"utc": _utc(), "status": r.status_code, "ms": ms, "headers": headers, "cookies": cookies}) loc = r.headers.get("Location") r.close() self._write(rec) if r.status_code in REDIRECTS and loc: nxt = urllib.parse.urljoin(url, loc) if nxt in seen or not nxt.startswith(("http://", "https://")): return seen.add(url) url = nxt continue return def _write(self, rec): with self.lock: self.resp_fh.write(json.dumps(rec) + "\n") self.resp_fh.flush() def close(self): self.resp_fh.close() self.robots_fh.close() self.log_fh.close() def _origin(url): p = urllib.parse.urlsplit(url) return f"{p.scheme}://{p.netloc}" def collect(args): from concurrent.futures import ThreadPoolExecutor os.makedirs(args.out, exist_ok=True) rows, seen = [], set() with open(args.domains, encoding="utf-8") as fh: for r in csv.DictReader(fh): if not r["domain"] or r["domain"] in seen: continue seen.add(r["domain"]) w = r["website"] if "//" in r["website"] else "//" + r["website"] r["host"] = urllib.parse.urlsplit(w).netloc.lower() rows.append(r) if args.limit: rows = rows[: args.limit] c = Collector(args.out) c.log(f"start: {len(rows)} sites, UA {UA!r}, workers {WORKERS}, min gap {MIN_GAP}s per host") done = [0] def one(r): try: c.site(r) except Exception as e: c.log(f"site {r['domain']} crashed: {type(e).__name__}: {e}") with c.lock: done[0] += 1 if done[0] % 25 == 0: c.log_fh.write(f"{_utc()} progress {done[0]}/{len(rows)}\n") c.log_fh.flush() with ThreadPoolExecutor(WORKERS) as ex: list(ex.map(one, rows)) c.log(f"done: {done[0]} sites") c.close() # ------------------------------------------------------------------------------------------ analyse --- SESSION_ID = re.compile(r"(?i)^(jsessionid|phpsessid|asp\.net_sessionid|aspsessionid\w*|\.aspnetcore\.session|connect\.sid|" r"sessionid|session|sid|ssessionid\S*|dwsid|laravel_session|ci_session|_session_id|.*_session)$") FAMILIES = [ # (family, regex on cookie name); first match wins. Names are vendor or framework defaults. ("bot management / CDN", r"(?i)^(__cf_bm|_cfuvid|cf_clearance|_abck|bm_\w+|ak_bmsc|aka_a2|akavpau_\w+|incap_ses_\w+|" r"visid_incap_\w+|nlbi_\w+|reese84|datadome|_px\w*|__uzm\w+|ts[0-9a-f]{6,}\w*|f5_\w+|f5avr\w+)$"), ("load balancer / routing", r"(?i)^(awsalb\w*|awselb\w*|bigipserver\S*|arraffinity\w*|applicationgatewayaffinity\w*|" r"affinity|ingresscookie|tipmix|x-ms-routing-name|x-mapping-\S+|akaalb_\S+|route|routeid|" r"serverid|cookiesession1|nsc_\S+|\S*sticky_session\S*|waf-\S+-persist|jrouter)$"), ("consent / privacy", r"(?i)^(optanonconsent|optanonalertboxclosed|eupubconsent\S*|cookieconsent\S*|didomi\S*|" r"truste\S*|notice_\S+|cmapi\S*|usprivacy|osano\S*|cookielawinfo\S*|consent\S*|euconsent\S*|" r"_evidon\S*|cookiebot\S*)$"), ("analytics / monitoring", r"(?i)^(_ga\w*|_gid|_gcl\w*|fpid\w*|_fbp|_uetsid|_uetvid|s_\w+|amcv\S*|amcvs\S*|mbox\S*|" r"at_check|_hj\w*|ajs_\S+|_mkto_trk|_clck|_clsk|__utm\w|dtcookie\w*|tltsid|tltuid|" r"sc_analytics_global_cookie)$"), ("site / language / region", r"(?i)^(\S*#lang|sc_site|sxa_site|geo|geo_country|\S*_geo|x-geo-country|" r"x-(country|region|continent|state)-code|\S*-locale)$"), ("server session ID", SESSION_ID.pattern), ] FAMILIES = [(n, re.compile(p)) for n, p in FAMILIES] def family(name): for n, rx in FAMILIES: if rx.match(name): return n return "other / unknown" def _attrs(s): out = {} for part in s.split(";"): part = part.strip() if not part: continue k, eq, v = part.partition("=") out[k.strip().lower()] = v.strip() if eq else True return out def lifetime_min(attrs, received): """Minutes from the moment the response arrived; None = session cookie. Max-Age wins over Expires.""" ma = attrs.get("max-age") if ma not in (None, True): try: return max(0, int(ma)) / 60.0 except ValueError: pass ex = attrs.get("expires") if ex not in (None, True): txt = re.sub(r"(\d{1,2})-(\w{3})-(\d{2,4})", r"\1 \2 \3", ex) try: when = email.utils.parsedate_to_datetime(txt) except (TypeError, ValueError, IndexError): return None if when.tzinfo is None: when = when.replace(tzinfo=dt.timezone.utc) return max(0.0, (when - received).total_seconds() / 60.0) return None def load(run): recs = [] with gzip.open(os.path.join(run, "responses.jsonl.gz"), "rt", encoding="utf-8") as fh: for ln in fh: recs.append(json.loads(ln)) return recs def analyse(args): recs = load(args.run) by_site = collections.OrderedDict() for r in recs: by_site.setdefault(r["domain"], []).append(r) for chain in by_site.values(): chain.sort(key=lambda r: r["hop"]) outcome = collections.Counter() error_status = collections.Counter() # final status of the sites whose homepage answered 4xx or 5xx cookies = [] # (site, family, parsed dict, findings, lifetime) sites_with_cookie = set() for dom, chain in by_site.items(): last = chain[-1] if last.get("skipped"): outcome["refused by robots.txt" if "refused" in last["robots"] else "robots.txt unreadable"] += 1 elif "error" in last: outcome["no response (network or TLS error)"] += 1 elif 200 <= last["status"] < 300: outcome["homepage answered 2xx"] += 1 elif last["status"] in REDIRECTS: outcome["redirect loop or limit"] += 1 else: outcome[f"homepage answered {last['status'] // 100}xx"] += 1 error_status[str(last["status"])] += 1 latest = collections.OrderedDict() # one cookie per name per site: the last header wins, as in a cookie store for r in chain: for ck in r.get("cookies", []): if ck["has_eq"] and ck["name"]: latest.pop(ck["name"], None) latest[ck["name"]] = (r, ck) for r, ck in latest.values(): got = dt.datetime.strptime(r["utc"], "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=dt.timezone.utc) attrs = _attrs(ck["attrs"]) value = ("a" if ck["value_hex"] else "g") * ck["value_len"] if ck["value_pii"]: value = value[:-1] + "@" if value else "@" parsed = {"name": ck["name"], "value": value, "attrs": attrs} findings = A.audit_cookie(parsed) cookies.append((dom, family(ck["name"]), parsed, findings, lifetime_min(attrs, got), urllib.parse.urlsplit(r["url"]).scheme)) sites_with_cookie.add(dom) def flags(c): a = c[2]["attrs"] ss = a.get("samesite") ss = ss.lower() if isinstance(ss, str) else "" return { "secure": a.get("secure") is True, "httponly": a.get("httponly") is True, "samesite_strict": ss == "strict", "samesite_lax": ss == "lax", "samesite_none": ss == "none", "samesite_absent": ss not in ("strict", "lax", "none"), "none_without_secure": ss == "none" and a.get("secure") is not True, "host_prefix": c[2]["name"].startswith("__Host-"), "secure_prefix": c[2]["name"].startswith("__Secure-"), "domain_attr": isinstance(a.get("domain"), str) and a.get("domain") != "", "persistent": c[4] is not None, "over_30_days": c[4] is not None and c[4] > 30 * DAY_MIN, "over_400_days": c[4] is not None and c[4] > 400 * DAY_MIN, "all_three": a.get("secure") is True and a.get("httponly") is True and ss in ("strict", "lax"), "no_shall_finding": not any(f[0] == "SHALL" for f in c[3]), } keys = list(flags(cookies[0]).keys()) if cookies else [] def tally(group): n = len(group) cnt = {k: sum(flags(c)[k] for c in group) for k in keys} return n, cnt groups = [("all cookies", cookies)] for fam, _ in FAMILIES + [("other / unknown", None)]: groups.append((fam, [c for c in cookies if c[1] == fam])) rows = [] stamp = min(r["utc"] for r in recs)[:10] for label, grp in groups: n, cnt = tally(grp) sites = len({c[0] for c in grp}) row = {"group": label, "sites": sites, "cookies": n} for k in keys: row[k] = cnt[k] row[k + "_pct"] = f"{100 * cnt[k] / n:.1f}" if n else "" row["retrieved"] = stamp rows.append(row) # per-site view: does a site's whole set of header cookies carry the flag? site_rows = collections.defaultdict(list) for c in cookies: site_rows[c[0]].append(c) per_site = { "sites_with_cookie": len(sites_with_cookie), "every_cookie_secure": sum(all(flags(c)["secure"] for c in cs) for cs in site_rows.values()), "every_cookie_httponly": sum(all(flags(c)["httponly"] for c in cs) for cs in site_rows.values()), "any_host_prefix": sum(any(flags(c)["host_prefix"] for c in cs) for cs in site_rows.values()), "any_none_without_secure": sum(any(flags(c)["none_without_secure"] for c in cs) for cs in site_rows.values()), "any_over_400_days": sum(any(flags(c)["over_400_days"] for c in cs) for cs in site_rows.values()), } per_cookie_count = [len(cs) for cs in site_rows.values()] findings = collections.Counter() for c in cookies: for lvl, rule, _, _ in c[3]: findings[(lvl, re.sub(r"Domain=\S+", "Domain=...", rule))] += 1 sess = [c for c in cookies if c[1] == "server session ID"] lifetimes = sorted(c[4] for c in cookies if c[4] is not None) report = { "retrieved": stamp, "sites_in_list": len(by_site), "outcome": dict(outcome.most_common()), "error_status": dict(error_status.most_common()), "requests": sum(1 for r in recs if "status" in r), "responses_with_cookies": sum(1 for r in recs if r.get("cookies")), "cookies": len(cookies), "set_cookie_headers": sum(len(r.get("cookies", [])) for r in recs), "cookies_over_http": sum(1 for c in cookies if c[5] == "http"), "per_site": per_site, "cookies_per_site_median": statistics.median(per_cookie_count) if per_cookie_count else 0, "cookies_per_site_max": max(per_cookie_count) if per_cookie_count else 0, "lifetime_median_days": round(statistics.median(lifetimes) / DAY_MIN, 1) if lifetimes else None, "session_id_names": dict(collections.Counter(c[2]["name"] for c in sess).most_common()), "top_findings": [[lvl, rule, n] for (lvl, rule), n in findings.most_common(12)], "groups": rows, } if args.csv: with open(args.csv, "w", newline="", encoding="utf-8") as fh: w = csv.DictWriter(fh, fieldnames=list(rows[0].keys())) w.writeheader() w.writerows(rows) print(json.dumps(report, indent=1)) return report def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) sub = ap.add_subparsers(dest="cmd", required=True) c = sub.add_parser("collect") c.add_argument("--domains", required=True) c.add_argument("--out", required=True) c.add_argument("--limit", type=int, default=0) a = sub.add_parser("analyse") a.add_argument("--run", required=True) a.add_argument("--csv") args = ap.parse_args() if args.cmd == "collect": collect(args) else: analyse(args) if __name__ == "__main__": sys.exit(main())