Skip to content

Health Software Common Practices

HSCP-T-025 · open test

Scan of the hybrid key exchange: every connection scanned, a dated decision for every refusal of hybrid

Serves HSCP-G-042 · Recipe: HSCP-R-040

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 scan of the negotiated key exchange, one line per connection (JSON Lines), incoming and outgoing. Every line carries:

Field Required Meaning
connexion yes the connection: host:port of the exposed endpoint, or the name of its line in the inventory of encryption
sens yes entrant (incoming, the product receives the connection) or sortant (outgoing, the product opens it to a third party)
autre_bout yes who holds the other end: browsers, partners, model provider, sector authority
hybride yes oui (yes) if the hybrid key exchange was negotiated, otherwise non (no)
decision for non date, motif (reason), and an optional action: mettre-a-jour (update), demander-une-date (ask for a date) or accepter (accept)
groupe no negotiated key exchange group, for example X25519MLKEM768

The test rejects:

  • an unreadable line, a missing required field, a direction, a hybride value or an action outside the vocabulary;
  • a non without a decision, a decision without a readable date, dated after the day of the check, or without a real reason.

With --inventaire, it also reads the inventory of encryption from recipe HSCP-R-019 (evidence item of test HSCP-T-006) and rejects a transit connection of the inventory (layer circulation-externe or circulation-interne) missing from the scan. The connection is matched by its point if it has one, otherwise by its donnee. A different direction between the two items is rejected too. A scanned connection that is not in the inventory is not rejected here: the inventory must carry it.

Running the test

python3 verifier.py releve.jsonl --inventaire inventaire.jsonl --date 2026-12-05

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 test reads a scan produced elsewhere; it connects to nothing. For each connection, a command from a free software tool, with OpenSSL 3.5 or later, succeeds only if the other end accepts the hybrid key exchange:

openssl s_client -connect portail.exemple.test:443 -groups X25519MLKEM768 </dev/null

Run from outside towards an exposed endpoint, it gives the incoming side; run from the product's environment towards a third party, the outgoing side. The result for each connection is written as one line of the scan.

Examples

  • exemples/valide/: four connections. The portal negotiates hybrid; the partner interface, the AI model and a national service do not, each with its dated decision (update, date asked of the provider, authority's schedule accepted). The three transit connections of the inventory are scanned. Accepted on 05/12/2026.
  • exemples/refuse/: a non without a decision, a peut-être (maybe) value, a decision without a readable date or a real reason, and the outgoing connection to the AI model, present in the inventory, missing from the scan. Rejected.

What the test does not say

  • It does not say whether the scan is accurate: it does not reconnect. An outgoing scan made from a workstation is not worth one made from the product's environment.
  • It does not say whether a decision is the right one, nor whether the migration plan is in the right order: that is the review of the recipe.
  • It does not see an intermediary that decrypts and re-encrypts: each segment is a connection to scan.

Code

Download the test (zip archive: program, examples, README, licence) (14 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-025 : relevé de l'échange de clés hybride, une ligne par connexion, une décision datée pour chaque « non ».

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

Une ligne JSON par connexion relevée :
  connexion   la connexion : hôte:port du point exposé, ou nom de la ligne de l'inventaire (sa « donnee »)
  sens        entrant (le produit reçoit la connexion) | sortant (le produit l'ouvre vers un tiers)
  autre_bout  qui tient l'autre bout (navigateurs, partenaires, fournisseur du modèle, autorité du secteur…)
  hybride     oui | non : l'échange de clés hybride a été négocié
  decision    pour « non » : {"date": date, "motif": texte, "action": mettre-a-jour | demander-une-date | accepter}
              (action facultative)
  groupe      facultatif : groupe d'échange de clés négocié (X25519MLKEM768…)

Refus : ligne illisible, champ obligatoire absent ou vide, sens, hybride ou action hors vocabulaire, « non » sans
décision, décision sans date lisible (ou datée après --date) ou sans vrai motif.
Avec --inventaire (pièce de HSCP-T-006, JSON Lines) : une ligne de circulation de l'inventaire (couche
circulation-externe ou circulation-interne) absente du relevé est refusée. Elle est retrouvée par son « point »
(hôte:port) s'il existe, sinon par sa « donnee » ; un sens différent entre les deux pièces est refusé aussi.
Le test lit un relevé produit ailleurs : il ne se connecte à rien.

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 sys

ID = "HSCP-T-025"
SENS = ("entrant", "sortant")
HYBRIDE = ("oui", "non")
ACTIONS = ("mettre-a-jour", "demander-une-date", "accepter")
OBLIGATOIRES = ("connexion", "sens", "autre_bout", "hybride")
CIRCULATION = ("circulation-externe", "circulation-interne")
MOTIF_MIN = 10


def jour(texte):
    s = str(texte or "").strip()
    try:
        return dt.date.fromisoformat(s[:10])
    except ValueError:
        return 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 cle(texte):
    return " ".join(str(texte or "").split()).lower()


def lire_jsonl(chemin, refus, quoi):
    try:
        lignes = open(chemin, encoding="utf-8").read().splitlines()
    except OSError as e:
        refus.append(f"{quoi} illisible : {e.strerror}")
        return []
    out = []
    for num, texte in enumerate(lignes, 1):
        if not texte.strip():
            continue
        try:
            d = json.loads(texte)
        except ValueError as e:
            refus.append(f"{quoi}, ligne {num} : JSON illisible ({e})")
            continue
        if not isinstance(d, dict):
            refus.append(f"{quoi}, ligne {num} : pas un objet JSON")
            continue
        out.append((num, d))
    return out


def verifier(chemin, aujourd_hui, inventaire=None):
    refus, notes = [], []
    releve = lire_jsonl(chemin, refus, "relevé")
    vues, comptes = {}, {"oui": 0, "non": 0}
    for num, d in releve:
        ici = f"ligne {num} ({d.get('connexion') or '?'})"
        for champ in OBLIGATOIRES:
            if vide(d.get(champ)):
                refus.append(f"{ici} : champ « {champ} » absent ou vide")
        sens = d.get("sens")
        if not vide(sens) and sens not in SENS:
            refus.append(f"{ici} : sens « {sens} » hors vocabulaire ({', '.join(SENS)})")
        hybride = d.get("hybride")
        if not vide(hybride) and hybride not in HYBRIDE:
            refus.append(f"{ici} : hybride « {hybride} » hors vocabulaire ({', '.join(HYBRIDE)})")
        elif hybride in HYBRIDE:
            comptes[hybride] += 1
        if hybride == "non":
            dec = d.get("decision")
            if vide(dec) or not isinstance(dec, dict):
                refus.append(f"{ici} : échange non hybride sans décision datée et motivée "
                             "(mettre à jour, demander une date au tiers, accepter avec sa raison)")
            else:
                quand = jour(dec.get("date"))
                if vide(dec.get("date")):
                    refus.append(f"{ici} : décision sans date")
                elif not quand:
                    refus.append(f"{ici} : decision.date illisible « {dec.get('date')} »")
                elif quand > aujourd_hui:
                    refus.append(f"{ici} : décision du {quand}, postérieure au {aujourd_hui}")
                motif = str(dec.get("motif") or "").strip()
                if len(motif) < MOTIF_MIN:
                    refus.append(f"{ici} : décision sans vrai motif (« {motif} »)")
                action = dec.get("action")
                if not vide(action) and action not in ACTIONS:
                    refus.append(f"{ici} : action « {action} » hors vocabulaire ({', '.join(ACTIONS)})")
        if not vide(d.get("connexion")):
            vues.setdefault(cle(d["connexion"]), (num, sens))
    if not releve and not refus:
        refus.append("relevé vide")
    if inventaire:
        lignes = lire_jsonl(inventaire, refus, "inventaire")
        attendues = 0
        for num, d in lignes:
            if d.get("couche") not in CIRCULATION:
                continue
            attendues += 1
            nom = d.get("point") if not vide(d.get("point")) else d.get("donnee")
            if vide(nom):
                refus.append(f"inventaire, ligne {num} : ligne de circulation sans « point » ni « donnee »")
                continue
            trouve = vues.get(cle(nom))
            if not trouve:
                refus.append(f"inventaire, ligne {num} : connexion « {nom} » ({d.get('couche')}"
                             f"{', ' + d['sens'] if d.get('sens') else ''}) absente du relevé")
            elif d.get("sens") in SENS and trouve[1] in SENS and d["sens"] != trouve[1]:
                refus.append(f"connexion « {nom} » : sens « {trouve[1]} » au relevé (ligne {trouve[0]}), "
                             f"« {d['sens']} » à l'inventaire (ligne {num})")
        notes.append(f"inventaire : {attendues} connexion(s) de circulation comparée(s) au relevé")
    notes.append(f"{len(releve)} connexion(s) relevée(s) : hybride oui {comptes['oui']}, non {comptes['non']}")
    return {"refus": refus, "notes": notes}


def main(argv=None):
    analyseur = argparse.ArgumentParser(description=__doc__.split("\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
    analyseur.add_argument("releve", help="fichier JSON Lines, une connexion relevée par ligne")
    analyseur.add_argument("--inventaire", help="inventaire du chiffrement (pièce de HSCP-T-006, JSON Lines)")
    analyseur.add_argument("--date", help="date de la vérification (défaut : aujourd'hui), AAAA-MM-JJ")
    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.releve, aujourd_hui, a.inventaire)
    r.update(test=ID, piece=a.releve, date=str(aujourd_hui), accepte=not r["refus"])
    if a.json:
        print(json.dumps(r, ensure_ascii=False, indent=1))
    else:
        print(f"{ID} relevé de l'échange de clés hybride : {a.releve} (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