Skip to content

Health Software Common Practices

HSCP-T-006 · open test

Inventory of encryption and keys: complete fields, no key value, one decision per gap

Serves HSCP-G-042, HSCP-G-001 · Recipe: HSCP-R-019

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 the inventory of encryption, one line per use (JSON Lines), following the data model of the recipe. Every line carries:

Field Required Meaning
donnee yes the protected data
classe yes its security-need class, from the data classification
sante no true for health data
couche yes circulation-externe (external transit), circulation-interne (internal transit), stockage (storage), sauvegarde (backup) or applicatif (application level)
sens no for transit: entrant (incoming, the product receives the connection) or sortant (outgoing, the product opens it to a third party)
mecanisme yes protocol or algorithm, key size, library and version
cle yes identifier of the key, never its value
client for health data at rest, with --multi-clients customer the key belongs to
emplacements_cle yes list of every place where the key is held
acces yes who or which service can use the key
rotation yes derniere (last) and echeance (due), or detruite_le (destroyed on)
confidentialite_jusqu_a no year until which the data must stay confidential, taken from its class (for example 2040)
besoin yes encryption expected for the data class
ecart yes aucun (none), manque (missing), faiblesse (weakness) or exces (excess)
decision for every gap action (corriger fix, accepter accept, retirer remove), date, motif (reason), and echeance (due date) for a fix
point no for an exposed endpoint: host:port
protocoles with point protocols allowed on that endpoint, for example TLSv1.2, TLSv1.3

The test rejects:

  • an unreadable line, a missing required field, a layer, direction or gap outside the vocabulary, an unreadable confidentiality year;
  • a line that contains, in any field, what looks like a key or a secret: PEM block, JWK key, age key, long hexadecimal string, long base64 string;
  • an unreadable or future date, an overdue rotation on a key that has not been destroyed;
  • a gap without a decision, a decision without a date or without a real reason, a fix without a due date or past its due date.

With --multi-clients, when the product serves several customers, it also rejects health data at rest whose key has no customer, and the same key attached to two customers.

With --releve, it compares a configuration scan of the exposed endpoints with the inventory, produced by testssl.sh (free software) with --jsonfile or --jsonfile-pretty. It rejects a scanned endpoint missing from the inventory, and a protocol offered by an endpoint but not allowed by its line. An endpoint of the inventory missing from the scan gives a note, not a rejection.

Running the test

python3 verifier.py inventaire.jsonl --date 2026-12-01 --multi-clients --releve releve.json

Without --date, the test uses the current day. --json gives the same answer as JSON. Exit code: 0 evidence accepted, 1 evidence rejected, 2 incorrect call. Python 3.10 or later, no dependency, no network access.

Producing the evidence

The inventory is written by hand or exported from the key manager and the configuration, one line per use of encryption. The scan of the exposed endpoints is produced with testssl.sh:

testssl.sh --jsonfile releve.json portail.exemple.test:443

Examples

  • exemples/valide/: seven uses for a product that serves several customers. One key per customer for storage, a backup with a shared key and its decision to fix it, a double encryption to remove, an incoming exposed endpoint on TLS 1.2 and 1.3 matching the scan, a key destroyed at the end of a contract, an outgoing connection to an AI model, confidential until 2040, without hybrid key exchange, accepted with its reason. Accepted on 01/12/2026.
  • exemples/refuse/: a key shared by two customers, an attachment key without a customer, overdue and without a decision, a secret value in a line, a layer outside the vocabulary, a decision without a date or reason, a direction inconnu and an unreadable confidentiality year. The scan shows TLS 1.0 offered and an exposed endpoint missing from the inventory. Rejected.

What the test does not say

  • It does not say whether the chosen encryption is the right one, nor whether the need of each class is right: that is the review of the recipe.
  • It does not say whether the inventory is complete. The scan only sees exposed endpoints; encryption at rest and copies of keys are checked by review, by comparing the inventory with the key manager's list.
  • The search for key values relies on their shape. A certificate fingerprint in hexadecimal is rejected like a key: name the key by its identifier. A short secret or one written in words can pass.
  • It does not read the cipher suites or the certificate expiry in the scan: only the endpoints and the protocols.

Code

Download the test (zip archive: program, examples, README, licence) (18 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-006 : inventaire du chiffrement et des clés, une ligne par usage, sans valeur de clé, une décision par écart.

    python3 verifier.py <inventaire.jsonl> [--date AAAA-MM-JJ] [--multi-clients] [--releve <relevé.json>] [--json]

Une ligne JSON par usage du chiffrement :
  donnee            la donnée protégée
  classe            sa classe de besoin de sécurité (celle du classement des données)
  sante             true si la donnée est une donnée de santé
  couche            circulation-externe | circulation-interne | stockage | sauvegarde | applicatif
  sens              facultatif, pour la circulation : entrant (le produit reçoit la connexion) | sortant (il l'ouvre)
  mecanisme         protocole ou algorithme, taille de clé, bibliothèque et version
  cle               identifiant de la clé (jamais sa valeur)
  client            client rattaché à la clé (obligatoire avec --multi-clients pour une donnée de santé au repos)
  emplacements_cle  liste des endroits où se trouve la clé (gestionnaire, séquestre, réplicas, environnements, postes)
  acces             qui ou quel service peut utiliser la clé
  rotation          {"derniere": date, "echeance": date} ou {"detruite_le": date}
  confidentialite_jusqu_a  facultatif : année jusqu'à laquelle la donnée doit rester confidentielle (2040)
  besoin            chiffrement attendu par la classe de la donnée
  ecart             aucun | manque | faiblesse | exces
  decision          pour un écart : {"action": corriger | accepter | retirer, "date": date, "motif": texte,
                    "echeance": date (pour corriger)}
  point             pour la couche circulation-externe : hôte:port du point exposé
  protocoles        pour un point exposé : protocoles admis (TLSv1.2, TLSv1.3…)

Refus : ligne illisible, champ obligatoire absent ou vide, couche, sens ou écart hors vocabulaire, année de
confidentialité illisible, valeur qui ressemble à une
clé ou à un secret (bloc PEM, clé JWK, longue suite hexadécimale ou base64) dans n'importe quel champ, date illisible
ou postérieure à --date, rotation échue sans destruction, écart sans décision (ou décision sans date, sans motif, ou
correction échue), et avec --multi-clients : donnée de santé au repos sans client, ou même clé pour deux clients.
Avec --releve (sortie JSON de testssl.sh, --jsonfile ou --jsonfile-pretty) : point relevé absent de l'inventaire, ou
protocole offert par le point et non admis par l'inventaire.
Il ne dit pas si le chiffrement choisi est le bon ni si l'inventaire est complet : il vérifie la forme de la pièce.

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-006"
COUCHES = ("circulation-externe", "circulation-interne", "stockage", "sauvegarde", "applicatif")
AU_REPOS = ("stockage", "sauvegarde", "applicatif")
ECARTS = ("aucun", "manque", "faiblesse", "exces")
SENS = ("entrant", "sortant")
ANNEES = (2000, 2200)
ACTIONS = ("corriger", "accepter", "retirer")
OBLIGATOIRES = ("donnee", "classe", "couche", "mecanisme", "cle", "emplacements_cle", "acces", "rotation", "besoin", "ecart")
MOTIF_MIN = 10
# Ce qui ressemble à une clé ou à un secret : la pièce nomme les clés, elle n'en contient aucune.
FORMES_DE_CLE = [(re.compile(r"-----BEGIN [A-Z ]*(PRIVATE KEY|KEY|CERTIFICATE)-----"), "bloc PEM"),
          (re.compile(r"\b[0-9a-fA-F]{32,}\b"), "longue suite hexadécimale"),
          (re.compile(r"\bAGE-SECRET-KEY-1[0-9A-Z]+"), "clé age")]
CHAMPS_JWK = {"d", "k", "p", "q", "dp", "dq", "qi"}
PROTOCOLES = {"SSLv2": "SSLv2", "SSLv3": "SSLv3", "TLS1": "TLSv1.0", "TLS1_1": "TLSv1.1", "TLS1_2": "TLSv1.2",
              "TLS1_3": "TLSv1.3"}


def jour(texte):
    s = str(texte or "").strip()
    try:
        return dt.date.fromisoformat(s[:10])
    except ValueError:
        return None


def chaines(valeur, chemin=""):
    """(chemin, chaîne) de toutes les chaînes d'une valeur JSON, et les clés d'objet."""
    if isinstance(valeur, str):
        yield chemin, valeur
    elif isinstance(valeur, list):
        for i, v in enumerate(valeur):
            yield from chaines(v, f"{chemin}[{i}]")
    elif isinstance(valeur, dict):
        for k, v in valeur.items():
            yield from chaines(v, f"{chemin}.{k}" if chemin else str(k))


def jwk(valeur):
    if isinstance(valeur, dict):
        if "kty" in valeur and CHAMPS_JWK & set(valeur):
            return True
        return any(jwk(v) for v in valeur.values())
    if isinstance(valeur, list):
        return any(jwk(v) for v in valeur)
    return False


def base64(s):
    """Une suite d'au moins 40 caractères base64 qui mêle majuscules, minuscules et chiffres : une valeur, pas un nom
    (un identifiant de clé, même long, s'écrit en mots : « kms/clinique-nord/sante-stockage-2026 »)."""
    for m in re.finditer(r"[A-Za-z0-9+/_=-]{40,}", s):
        x = m.group(0)
        if re.search(r"[A-Z]", x) and re.search(r"[a-z]", x) and re.search(r"[0-9]", x) \
                and max(len(seg) for seg in re.split(r"[/_-]", x)) >= 24:
            return True
    return False


def annee(v):
    """Année lisible (nombre ou texte de quatre chiffres, entre 2000 et 2200), sinon None."""
    if isinstance(v, bool):
        return None
    if isinstance(v, int):
        a = v
    elif isinstance(v, str) and re.fullmatch(r"\s*\d{4}\s*", v):
        a = int(v)
    else:
        return None
    return a if ANNEES[0] <= a <= ANNEES[1] else None


def vide(v):
    return v is None or (isinstance(v, (str, list, dict)) and not (v.strip() if isinstance(v, str) else v))


def date_passee(refus, ici, nom, valeur, aujourd_hui):
    """Date lisible et pas dans le futur ; None si absente."""
    if vide(valeur):
        return None
    d = jour(valeur)
    if not d:
        refus.append(f"{ici} : {nom} illisible « {valeur} »")
    elif d > aujourd_hui:
        refus.append(f"{ici} : {nom} du {d}, postérieure au {aujourd_hui}")
    return d


def releve_testssl(chemin):
    """{(hôte, port): {protocoles offerts}} depuis la sortie JSON de testssl.sh (plate ou « pretty »)."""
    d = json.load(open(chemin, encoding="utf-8"))
    lignes = []
    if isinstance(d, list):
        lignes = d
    elif isinstance(d, dict):
        for s in d.get("scanResult", []):
            base = {"ip": f"{s.get('targetHost', '')}/{s.get('ip', '')}", "port": s.get("port", "")}
            for section in s.values():
                if isinstance(section, list):
                    lignes += [{**base, **x} for x in section if isinstance(x, dict)]
    points = {}
    for x in lignes:
        hote = str(x.get("ip", "")).split("/")[0].strip().lower()
        port = str(x.get("port", "")).strip()
        if not hote or not port:
            continue
        offerts = points.setdefault((hote, port), set())
        proto = PROTOCOLES.get(str(x.get("id", "")))
        trouve = str(x.get("finding", "")).lower()
        if proto and "offered" in trouve and "not offered" not in trouve:
            offerts.add(proto)
    return points


def verifier(chemin, aujourd_hui, multi_clients=False, releve=None):
    refus, notes, n = [], [], 0
    comptes = dict.fromkeys(ECARTS, 0)
    clients_de_cle, points = {}, {}
    try:
        lignes = open(chemin, encoding="utf-8").read().splitlines()
    except OSError as e:
        return {"refus": [f"fichier illisible : {e.strerror}"], "notes": []}
    for num, texte in enumerate(lignes, 1):
        if not texte.strip():
            continue
        n += 1
        ici = f"ligne {num}"
        try:
            d = json.loads(texte)
        except ValueError as e:
            refus.append(f"{ici} : JSON illisible ({e})")
            continue
        if not isinstance(d, dict):
            refus.append(f"{ici} : pas un objet JSON")
            continue
        ici = f"ligne {num} ({d.get('donnee') or '?'}, {d.get('couche') or '?'})"
        for champ in OBLIGATOIRES:
            if vide(d.get(champ)):
                refus.append(f"{ici} : champ « {champ} » absent ou vide")
        # Aucune valeur de clé, nulle part dans la ligne.
        if jwk(d):
            refus.append(f"{ici} : contient une clé au format JWK : l'inventaire nomme les clés, il n'en contient aucune")
        for ou, s in chaines(d):
            for motif, quoi in FORMES_DE_CLE + [(None, "longue suite base64")]:
                if (motif.search(s) if motif else base64(s)):
                    refus.append(f"{ici} : « {ou} » contient ce qui ressemble à une valeur de clé ({quoi}) : "
                                 "l'inventaire nomme les clés, il n'en contient aucune")
                    break
        couche = d.get("couche")
        if couche and couche not in COUCHES:
            refus.append(f"{ici} : couche « {couche} » hors vocabulaire ({', '.join(COUCHES)})")
        sens = d.get("sens")
        if not vide(sens) and sens not in SENS:
            refus.append(f"{ici} : sens « {sens} » hors vocabulaire ({', '.join(SENS)})")
        conf = d.get("confidentialite_jusqu_a")
        if conf is not None and annee(conf) is None:
            refus.append(f"{ici} : confidentialite_jusqu_a illisible « {conf} » (une année, par exemple 2040)")
        if not vide(d.get("emplacements_cle")) and not isinstance(d.get("emplacements_cle"), list):
            refus.append(f"{ici} : « emplacements_cle » doit être une liste (tous les endroits où se trouve la clé)")
        rot = d.get("rotation")
        if not vide(rot):
            if not isinstance(rot, dict):
                refus.append(f"{ici} : « rotation » doit porter « echeance » (et « derniere ») ou « detruite_le »")
            else:
                date_passee(refus, ici, "rotation.derniere", rot.get("derniere"), aujourd_hui)
                detruite = date_passee(refus, ici, "rotation.detruite_le", rot.get("detruite_le"), aujourd_hui)
                if not detruite:
                    ech = jour(rot.get("echeance"))
                    if vide(rot.get("echeance")):
                        refus.append(f"{ici} : rotation sans « echeance » (ni « detruite_le »)")
                    elif not ech:
                        refus.append(f"{ici} : rotation.echeance illisible « {rot.get('echeance')} »")
                    elif ech < aujourd_hui:
                        refus.append(f"{ici} : rotation échue le {ech} : la clé est à faire tourner, ou l'écart à décider")
        ecart = d.get("ecart")
        if ecart and ecart not in ECARTS:
            refus.append(f"{ici} : écart « {ecart} » hors vocabulaire ({', '.join(ECARTS)})")
        elif ecart:
            comptes[ecart] += 1
        if ecart in ("manque", "faiblesse", "exces"):
            dec = d.get("decision")
            if vide(dec) or not isinstance(dec, dict):
                refus.append(f"{ici} : écart « {ecart} » sans décision (corriger, accepter ou retirer, datée)")
            else:
                action = dec.get("action")
                if action not in ACTIONS:
                    refus.append(f"{ici} : décision « {action} » hors vocabulaire ({', '.join(ACTIONS)})")
                quand = date_passee(refus, ici, "decision.date", dec.get("date"), aujourd_hui)
                if vide(dec.get("date")):
                    refus.append(f"{ici} : décision sans date")
                motif = str(dec.get("motif") or "").strip()
                if len(motif) < MOTIF_MIN:
                    refus.append(f"{ici} : décision sans vrai motif (« {motif} »)")
                if action == "corriger":
                    ech = jour(dec.get("echeance"))
                    if not ech:
                        refus.append(f"{ici} : correction sans échéance lisible")
                    elif quand and ech < quand:
                        refus.append(f"{ici} : échéance de correction ({ech}) antérieure à la décision ({quand})")
                    elif ech < aujourd_hui:
                        refus.append(f"{ici} : correction échue le {ech} : la décision est à réexaminer")
        # Une clé par client pour les données de santé au repos, quand le produit sert plusieurs clients.
        cle = str(d.get("cle") or "").strip()
        client = str(d.get("client") or "").strip()
        if cle and client:
            clients_de_cle.setdefault(cle, {}).setdefault(client, num)
        if multi_clients and d.get("sante") is True and couche in AU_REPOS and not client:
            refus.append(f"{ici} : donnée de santé au repos sans client rattaché à sa clé (produit multi-clients)")
        if couche == "circulation-externe" and not vide(d.get("point")):
            point = str(d["point"]).strip().lower()
            hote, _, port = point.rpartition(":")
            if not hote or not port.isdigit():
                refus.append(f"{ici} : point « {d['point']} » attendu sous la forme hôte:port")
            else:
                admis = d.get("protocoles") or []
                if not isinstance(admis, list) or not admis:
                    refus.append(f"{ici} : point exposé sans liste « protocoles » admis")
                    admis = []
                points.setdefault((hote, port), set()).update(admis)
    if multi_clients:
        for cle, clients in clients_de_cle.items():
            if len(clients) > 1:
                refus.append(f"clé « {cle} » rattachée à plusieurs clients ({', '.join(sorted(clients))}, lignes "
                             f"{', '.join(str(x) for x in sorted(clients.values()))}) : une clé par client")
    if releve:
        try:
            vus = releve_testssl(releve)
        except (OSError, ValueError) as e:
            refus.append(f"relevé illisible : {e}")
            vus = {}
        for (hote, port), offerts in sorted(vus.items()):
            if (hote, port) not in points:
                refus.append(f"relevé : point exposé {hote}:{port} absent de l'inventaire")
                continue
            hors = sorted(offerts - points[(hote, port)])
            if hors:
                refus.append(f"relevé : {hote}:{port} offre {', '.join(hors)}, non admis par l'inventaire "
                             f"({', '.join(sorted(points[(hote, port)]))})")
        for hote, port in sorted(set(points) - set(vus)):
            notes.append(f"point {hote}:{port} de l'inventaire absent du relevé (non relevé ou retiré)")
        notes.append(f"relevé : {len(vus)} point(s) exposé(s) comparé(s) à l'inventaire")
    if not n:
        refus.append("inventaire vide")
    notes.append(f"{n} usage(s) du chiffrement : " + ", ".join(f"écart {k} {v}" for k, v in comptes.items()))
    return {"refus": refus, "notes": notes}


def main(argv=None):
    analyseur = argparse.ArgumentParser(description=__doc__.split("\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
    analyseur.add_argument("inventaire", help="fichier JSON Lines, un usage du chiffrement par ligne")
    analyseur.add_argument("--date", help="date de la vérification (défaut : aujourd'hui), AAAA-MM-JJ")
    analyseur.add_argument("--multi-clients", action="store_true",
                           help="le produit sert plusieurs clients : une clé par client pour les données de santé au repos")
    analyseur.add_argument("--releve", help="relevé de configuration des points exposés (JSON de testssl.sh)")
    analyseur.add_argument("--json", action="store_true", help="sortie JSON")
    a = analyseur.parse_args(argv)
    aujourd_hui = jour(a.date) if a.date else dt.date.today()
    if not aujourd_hui:
        analyseur.error(f"--date illisible : {a.date}")
    r = verifier(a.inventaire, aujourd_hui, a.multi_clients, a.releve)
    r.update(test=ID, piece=a.inventaire, date=str(aujourd_hui), accepte=not r["refus"])
    if a.json:
        print(json.dumps(r, ensure_ascii=False, indent=1))
    else:
        print(f"{ID} inventaire du chiffrement et des clés : {a.inventaire} (au {aujourd_hui})")
        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