Skip to content

Health Software Common Practices

HSCP-T-004 · open test

security.txt file compliant with RFC 9116 and not expired

Serves HSCP-G-145 · Recipe: HSCP-R-013

Code under the licence Apache 2.0 · Python 3.10 or later, standard library only, no network access

What the test checks

The evidence item is a copy of the /.well-known/security.txt file served by the product. The test accepts it if:

  • every line is empty, a comment or a Name: value field;
  • it carries at least one Contact, as a mailto:, https:// or tel: address;
  • it carries a single Expires, a date and time with a time zone, not past;
  • every web address (Contact, Canonical, Encryption, Acknowledgments, Policy, Hiring, CSAF) starts with https://;
  • Preferred-Languages appears at most once and lists language tags;
  • if --url is given and the file declares Canonical fields, the address is one of them.

It reports without refusing an expiry more than a year away (the RFC advises against it), a missing Canonical, and an OpenPGP signature (which it does not verify).

Running the test

The test does not access the network. First fetch the served file, then check the copy:

curl -fsS https://example.org/.well-known/security.txt -o security.txt
python3 verifier.py security.txt --url https://example.org/.well-known/security.txt

--date sets the instant of the check, --json gives the answer in JSON. Exit code: 0 evidence accepted, 1 evidence refused, 2 incorrect call. Python 3.10 or later, no dependency.

Run every day, the test refuses the file as soon as it expires: that is the monitoring needed, earlier if a margin is added to --date.

Examples

  • exemples/valide/: two contacts, an expiry six months away, the policy and the canonical address. Accepted.
  • exemples/refuse/: a contact without mailto:, a past expiry, a policy over http://, a canonical address that is not the one the copy comes from, a line of free text. Refused.

What the test does not say

  • It does not say that the contact answers, nor that the announced policy is applied.
  • It does not say that the file is served at the right place: the fetch command shows that.
  • It does not verify the OpenPGP signature.

Code

Download the test (zip archive: program, examples, README, licence) (11 KB) · verifier.py

The code and its messages are not translated (French).

#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 les contributeurs des Gestes communs du logiciel de santé
"""HSCP-T-004 : fichier security.txt conforme à la RFC 9116 et non expiré.

    python3 verifier.py <security.txt> [--url https://example.org/.well-known/security.txt] [--date ISO 8601] [--json]

Lit une copie du fichier (le test n'accède pas au réseau : récupérez d'abord le fichier servi, voir le LISEZ-MOI).
Refus : ligne qui n'est ni vide, ni commentaire, ni « Champ: valeur » ; Contact absent ; Contact qui n'est pas une
adresse mailto:, https: ou tel: ; Expires absent, répété, illisible ou dépassé à --date ; Preferred-Languages répété ;
adresse web en http:// au lieu de https:// (Contact, Canonical, Encryption, Acknowledgments, Policy, Hiring, CSAF) ;
--url absente des Canonical quand le fichier en déclare.
Note seulement : Expires à plus d'un an (la RFC le déconseille), Canonical absent, signature OpenPGP présente (elle
n'est pas vérifiée).
Il ne dit pas que le contact répond, ni que la politique annoncée est appliquée.

Codes de retour : 0 pièce acceptée, 1 pièce refusée, 2 appel incorrect.
Bibliothèque standard seulement, aucun accès réseau.
"""
import argparse
import datetime as dt
import json
import re
import sys

ID = "HSCP-T-004"
WEB = ("contact", "canonical", "encryption", "acknowledgments", "policy", "hiring", "csaf")
UNIQUES = ("expires", "preferred-languages")
CHAMP = re.compile(r"^([A-Za-z0-9-]+):[ \t]*(.*?)[ \t]*$")
LANGUE = re.compile(r"^[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*$")


def instant(texte):
    s = str(texte or "").strip()
    if "T" not in s:
        return None
    try:
        d = dt.datetime.fromisoformat(s.replace("Z", "+00:00"))
    except ValueError:
        return None
    return d if d.tzinfo else None   # la RFC 9116 exige un fuseau (format de la RFC 3339)


def corps(lignes, notes):
    """Retire l'enveloppe OpenPGP en clair (RFC 4880 § 7) s'il y en a une ; la signature n'est pas vérifiée."""
    if not lignes or lignes[0].strip() != "-----BEGIN PGP SIGNED MESSAGE-----":
        return list(enumerate(lignes, 1))
    notes.append("signature OpenPGP présente : non vérifiée par ce test")
    sortie, i = [], 1
    while i < len(lignes) and lignes[i].strip():   # en-têtes Hash: jusqu'à la ligne vide
        i += 1
    for num, l in enumerate(lignes[i + 1:], i + 2):
        if l.strip() == "-----BEGIN PGP SIGNATURE-----":
            break
        sortie.append((num, l[2:] if l.startswith("- ") else l))
    return sortie


def verifier(chemin, maintenant, url):
    refus, notes = [], []
    try:
        texte = open(chemin, encoding="utf-8").read()
    except OSError as e:
        return {"refus": [f"fichier illisible : {e.strerror}"], "notes": []}
    except UnicodeDecodeError:
        return {"refus": ["fichier qui n'est pas en UTF-8"], "notes": []}
    champs = {}
    for num, l in corps(texte.splitlines(), notes):
        if not l.strip() or l.lstrip().startswith("#"):
            continue
        m = CHAMP.match(l)
        if not m:
            refus.append(f"ligne {num} : ni commentaire ni « Champ: valeur »")
            continue
        champs.setdefault(m.group(1).lower(), []).append((num, m.group(2)))
    contacts = champs.get("contact", [])
    if not contacts:
        refus.append("Contact absent (au moins un est obligatoire)")
    for num, v in contacts:
        if not re.match(r"^(mailto:[^@\s]+@[^@\s]+|https://\S+|tel:\+?[0-9 ()./-]+)$", v):
            refus.append(f"ligne {num} : Contact « {v} » n'est pas une adresse mailto:, https:// ou tel:")
    for nom in WEB:
        for num, v in champs.get(nom, []):
            if v.lower().startswith("http://"):
                refus.append(f"ligne {num} : {nom} en http:// ; une adresse web doit commencer par https://")
    for nom in UNIQUES:
        if len(champs.get(nom, [])) > 1:
            refus.append(f"{nom} présent {len(champs[nom])} fois (une seule fois au plus)")
    exp = champs.get("expires", [])
    if not exp:
        refus.append("Expires absent (obligatoire)")
    else:
        num, v = exp[0]
        d = instant(v)
        if not d:
            refus.append(f"ligne {num} : Expires « {v} » illisible (date et heure avec fuseau, ex. 2027-06-30T23:00:00Z)")
        elif d <= maintenant:
            refus.append(f"ligne {num} : Expires dépassé ({v})")
        else:
            reste = (d - maintenant).days
            notes.append(f"expire le {d.date()}, dans {reste} jour(s)")
            if reste > 366:
                notes.append("Expires à plus d'un an : la RFC 9116 recommande moins d'un an")
    for num, v in champs.get("preferred-languages", []):
        if not all(LANGUE.match(x.strip()) for x in v.split(",")):
            refus.append(f"ligne {num} : Preferred-Languages « {v} » n'est pas une liste d'étiquettes de langue")
    canon = [v for _, v in champs.get("canonical", [])]
    if not canon:
        notes.append("Canonical absent : recommandé, surtout pour un fichier signé")
    elif url and url not in canon:
        refus.append(f"{url} absente des Canonical déclarés ({', '.join(canon)})")
    notes.insert(0, f"{len(contacts)} contact(s), champs : {', '.join(sorted(champs)) or 'aucun'}")
    return {"refus": refus, "notes": notes}


def main(argv=None):
    analyseur = argparse.ArgumentParser(description=__doc__.split("\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
    analyseur.add_argument("fichier", help="copie du security.txt servi")
    analyseur.add_argument("--url", help="adresse d'où vient la copie, comparée aux champs Canonical")
    analyseur.add_argument("--date", help="instant de la vérification (défaut : maintenant), ISO 8601 avec fuseau")
    analyseur.add_argument("--json", action="store_true", help="sortie JSON")
    a = analyseur.parse_args(argv)
    maintenant = instant(a.date) if a.date else dt.datetime.now(dt.timezone.utc)
    if not maintenant:
        analyseur.error(f"--date illisible (date et heure avec fuseau) : {a.date}")
    if a.url and not a.url.startswith("https://"):
        analyseur.error("--url doit commencer par https://")
    r = verifier(a.fichier, maintenant, a.url)
    r.update(test=ID, piece=a.fichier, date=maintenant.isoformat(), accepte=not r["refus"])
    if a.json:
        print(json.dumps(r, ensure_ascii=False, indent=1))
    else:
        print(f"{ID} security.txt : {a.fichier} (au {maintenant.isoformat()})")
        for x in r["refus"]:
            print(f"  REFUS  {x}")
        for x in r["notes"]:
            print(f"  NOTE   {x}")
        print("Résultat : " + ("pièce acceptée" if r["accepte"] else f"pièce refusée ({len(r['refus'])} refus)"))
    return 0 if r["accepte"] else 1


if __name__ == "__main__":
    sys.exit(main())

Files of the test