Étape 2 — Fingerprinting HTTP/2 dans le pipeline ML : - Ajout du dictionnaire dict_browser_h2 (11 familles de navigateurs) dans 05_aggregation_tables.sql - Ajout du CTE h2_agg et 4 features HTTP/2 dans 07_ai_features_view.sql : h2_settings_known, h2_pseudo_order_match, h2_ja4_coherence, h2_settings_rare - Calcul du fingerprint_coherence_score (5 axes pondérés) dans la vue - Ajout du 6e axe axis_h2_coherence dans browser.py (poids rééquilibrés) - browser_h2.csv : 11 fingerprints Akamai → famille navigateur Étape 3 — Pré-filtre de cohérence sur la baseline humaine : - pipeline.py exclut les sessions avec fingerprint_coherence_score < seuil de la baseline d'entraînement - FINGERPRINT_COHERENCE_THRESHOLD configurable via env (défaut 0.25) - Log des sessions exclues pour analyse SOC Étape 4 — Détection de drift améliorée : - scoring.py : passage de 5 à 9 quantiles (p5…p95) - Ajout de la divergence KL en complément du test KS - Détection de drift adversarial (≥80% des features dérivent dans la même direction) - Split temporel strict pour la validation Étape 5 — Graphe bipartite JA4×ASN (§5.2) : - fleet.py : détection de flottes via NetworkX + Louvain (imports optionnels) - enrich_with_fleet_score() : ajout fleet_score + fleet_campaign_flag au DataFrame - cycle.py : appel après preprocess_df avec log du nombre de sessions en flotte - SQL migration 05_fleet_metrics_tables.sql : table fleet_detections (TTL 7j) - Dashboard : /fleet + /api/fleet (communautés détectées) + template fleet.html Étape 6 — Cross-domain Jaccard §5.8 : - 12_thesis_features.sql : CTE jaccard_paths → cross_domain_path_similarity - Signal : même chemins (/admin, /wp-login) sur plusieurs hosts = scanner Étape 7 — ExIFFI + erreurs AE par feature : - scoring.py : compute_exiffi_importance() par permutation, compute_ae_feature_errors() - pipeline.py : calcul ExIFFI sur X_test, mapping index → dict pour anomalies - build_reason() enrichi avec exiffi_top quand SHAP inactif Étape 8 — Méta-learner pour la pondération de l'ensemble : - scoring.py : classe MetaLearner (LogisticRegression, fallback poids fixes <1000 labels) - Collecte des labels depuis le cycle courant (known_bots, légitimes, Anubis) - pipeline.py : remplacement des poids fixes par MetaLearner.predict() Étape 9 — Métriques de performance et monitoring : - metrics.py : record_cycle_metrics() — taux anomalie, drift, corrélation, latence - SQL migration 05_fleet_metrics_tables.sql : table ml_performance_metrics (TTL 90j) - Dashboard : /health + /api/health + template health.html - cycle.py : appel record_cycle_metrics en fin de cycle (Complet + Applicatif) Tests : 36/36 bot-detector tests passent Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
192 lines
8.8 KiB
Python
192 lines
8.8 KiB
Python
"""A9 — Identification multifactorielle des navigateurs.
|
|
|
|
5 axes indépendants combinés pour identifier les navigateurs légitimes.
|
|
Aucun axe ne repose sur le User-Agent (trivalement falsifiable).
|
|
Signaux principaux : JA4 (TLS), Client Hints, Sec-Fetch-*, comportement.
|
|
"""
|
|
import pandas as pd
|
|
import numpy as np
|
|
|
|
# Profils structurels JA4 des navigateurs connus (TCP).
|
|
# Plages de cipher/extension count caractéristiques par famille TLS.
|
|
# Sources : FoxIO ja4plus-mapping.csv, ja4db.com, captures réelles.
|
|
_BROWSER_JA4_PROFILES = {
|
|
'Chromium': {'tls': '13', 'alpn': ('h2', 'h3'),
|
|
'ciphers': range(13, 19), 'exts': range(13, 20)},
|
|
'Firefox': {'tls': '13', 'alpn': ('h2', 'h3'),
|
|
'ciphers': range(15, 20), 'exts': range(13, 18)},
|
|
'Safari': {'tls': '13', 'alpn': ('h2', 'h3'),
|
|
'ciphers': range(17, 25), 'exts': range(11, 17)},
|
|
'Tor_Browser': {'tls': '13', 'alpn': ('h2',),
|
|
'ciphers': range(14, 18), 'exts': range(12, 17)},
|
|
}
|
|
|
|
# Pondération des 6 axes pour le score browser_confidence.
|
|
# Favorise les signaux TLS (difficiles à falsifier) sur HTTP.
|
|
# L'axe H2 complète la cohérence TLS avec les paramètres HTTP/2.
|
|
_AXIS_WEIGHTS = {
|
|
'ja4_known': 0.25, # Axe 1 — Signature JA4 dans dict_browser_ja4 (TLS fingerprint)
|
|
'ja4_struct': 0.15, # Axe 2 — Structure JA4 (TLS1.3, h2, nb ciphers/ext)
|
|
'http_modern': 0.20, # Axe 3 — Client Hints + Sec-Fetch-* (PAS de User-Agent)
|
|
'nav_behavior': 0.15, # Axe 4 — Comportement de navigation (assets, referers)
|
|
'tls_coherence': 0.15, # Axe 5 — Cohérence TLS/TCP (pas de mismatch)
|
|
'h2_coherence': 0.10, # Axe 6 — Cohérence HTTP/2 (SETTINGS↔JA4, pseudo-headers) §2
|
|
}
|
|
|
|
|
|
def _parse_ja4_columns(ja4_series: pd.Series) -> pd.DataFrame:
|
|
"""Parse la partie structurelle du JA4 (10 premiers caractères) vectorisé.
|
|
|
|
Format JA4 : {proto}{tls_ver}{sni}{cipher_cnt}{ext_cnt}{alpn}_hash_hash
|
|
Exemple : t13d1516h2_8daaf6152771_02713d6af862
|
|
|
|
Retourne un DataFrame avec : ja4_tls, ja4_ciphers, ja4_exts, ja4_alpn.
|
|
"""
|
|
s = ja4_series.fillna('').astype(str)
|
|
valid = s.str.len() >= 10
|
|
result = pd.DataFrame(index=ja4_series.index)
|
|
result['ja4_tls'] = s.str[1:3].where(valid, '00')
|
|
result['ja4_ciphers'] = pd.to_numeric(s.str[4:6].where(valid, '0'), errors='coerce').fillna(0).astype(int)
|
|
result['ja4_exts'] = pd.to_numeric(s.str[6:8].where(valid, '0'), errors='coerce').fillna(0).astype(int)
|
|
result['ja4_alpn'] = s.str[8:10].where(valid, '00')
|
|
return result
|
|
|
|
|
|
def _compute_browser_axes(df: pd.DataFrame) -> pd.DataFrame:
|
|
"""Calcule les 5 axes d'identification navigateur pour chaque session.
|
|
|
|
Axe 1 (ja4_known) : JA4 présent dans dict_browser_ja4 (0 ou 1)
|
|
Axe 2 (ja4_struct) : Structure JA4 compatible navigateur (TLS1.3 + h2/h3 + ciphers/exts)
|
|
Axe 3 (http_modern) : Headers HTTP modernes (sec-ch-ua, Accept-Language, Sec-Fetch-*)
|
|
Axe 4 (nav_behavior) : Comportement navigation (cookies, referer, assets, accès direct)
|
|
Axe 5 (tls_coherence) : Cohérence TLS/TCP (pas de mismatch ALPN, window scaling, TLS1.3)
|
|
|
|
Retourne un DataFrame avec les colonnes axis_* et browser_confidence.
|
|
"""
|
|
n = len(df)
|
|
axes = pd.DataFrame(index=df.index)
|
|
|
|
# ── Axe 1 — Signature JA4 connue ──
|
|
bf = df.get('browser_family', pd.Series('', index=df.index)).fillna('').astype(str)
|
|
axes['axis_ja4_known'] = (bf != '').astype(float)
|
|
|
|
# ── Axe 2 — Structure JA4 ──
|
|
ja4_parsed = _parse_ja4_columns(df.get('ja4', pd.Series('', index=df.index)))
|
|
is_tls13 = (ja4_parsed['ja4_tls'] == '13').astype(float)
|
|
is_h2h3 = ja4_parsed['ja4_alpn'].isin(['h2', 'h3']).astype(float)
|
|
# Plage de ciphers et extensions typique d'un navigateur (10-25)
|
|
c = ja4_parsed['ja4_ciphers']
|
|
e = ja4_parsed['ja4_exts']
|
|
ciphers_ok = ((c >= 10) & (c <= 25)).astype(float)
|
|
exts_ok = ((e >= 10) & (e <= 25)).astype(float)
|
|
axes['axis_ja4_struct'] = (
|
|
is_tls13 * 0.35 + is_h2h3 * 0.25 + ciphers_ok * 0.20 + exts_ok * 0.20
|
|
)
|
|
|
|
# ── Axe 3 — Signaux HTTP sans User-Agent ──
|
|
# Client Hints (sec-ch-ua) = signal fort, nécessite un vrai moteur Chromium.
|
|
# Sec-Fetch-* = signal moyen, envoyé automatiquement par les navigateurs modernes.
|
|
# Le User-Agent n'est PAS utilisé (trivalement falsifiable par n'importe quel bot).
|
|
scu = df.get('has_sec_ch_ua', pd.Series(0, index=df.index)).fillna(0)
|
|
hal = df.get('has_accept_language', pd.Series(0, index=df.index)).fillna(0)
|
|
sfa = df.get('sec_fetch_absence_rate', pd.Series(1, index=df.index)).fillna(1)
|
|
gar = df.get('generic_accept_ratio', pd.Series(1, index=df.index)).fillna(1)
|
|
ifn = df.get('is_fake_navigation', pd.Series(0, index=df.index)).fillna(0)
|
|
axes['axis_http_modern'] = (
|
|
(scu > 0).astype(float) * 0.30
|
|
+ (sfa < 0.2).astype(float) * 0.30
|
|
+ (hal > 0).astype(float) * 0.15
|
|
+ (gar < 0.3).astype(float) * 0.15
|
|
+ (ifn == 0).astype(float) * 0.10
|
|
)
|
|
|
|
# ── Axe 4 — Comportement de navigation ──
|
|
hck = df.get('has_cookie', pd.Series(0, index=df.index)).fillna(0)
|
|
hrf = df.get('has_referer', pd.Series(0, index=df.index)).fillna(0)
|
|
asr = df.get('asset_ratio', pd.Series(0, index=df.index)).fillna(0)
|
|
dar = df.get('direct_access_ratio', pd.Series(1, index=df.index)).fillna(1)
|
|
axes['axis_nav_behavior'] = (
|
|
(hck > 0).astype(float) * 0.25
|
|
+ (hrf > 0).astype(float) * 0.25
|
|
+ (asr > 0.15).astype(float) * 0.25
|
|
+ (dar < 0.5).astype(float) * 0.25
|
|
)
|
|
|
|
# ── Axe 5 — Cohérence TLS/TCP ──
|
|
alm = df.get('alpn_http_mismatch', pd.Series(0, index=df.index)).fillna(0)
|
|
nws = df.get('no_window_scale_ratio', pd.Series(0, index=df.index)).fillna(0)
|
|
t12 = df.get('tls12_ratio', pd.Series(0, index=df.index)).fillna(0)
|
|
h10 = df.get('http10_ratio', pd.Series(0, index=df.index)).fillna(0)
|
|
iam = df.get('is_alpn_missing', pd.Series(0, index=df.index)).fillna(0)
|
|
axes['axis_tls_coherence'] = (
|
|
(alm == 0).astype(float) * 0.25
|
|
+ (nws == 0).astype(float) * 0.20
|
|
+ (t12 < 0.1).astype(float) * 0.20
|
|
+ (h10 == 0).astype(float) * 0.15
|
|
+ (iam == 0).astype(float) * 0.20
|
|
)
|
|
|
|
# ── Axe 6 — Cohérence HTTP/2 (§2) ──
|
|
# Signaux : fingerprint SETTINGS connu, cohérence H2↔JA4, pseudo-headers corrects.
|
|
# Quand les données H2 sont absentes (HTTP/1.x), l'axe est neutre (0.5).
|
|
h2k = df.get('h2_settings_known', pd.Series(-1, index=df.index)).fillna(-1)
|
|
h2c = df.get('h2_ja4_coherence', pd.Series(-1, index=df.index)).fillna(-1)
|
|
h2p = df.get('h2_pseudo_order_match', pd.Series(-1, index=df.index)).fillna(-1)
|
|
# Sessions sans données H2 → axe neutre à 0.5 (ne pénalise pas les sites HTTP/1.x)
|
|
h2_present = ((h2k >= 0) | (h2c >= 0)).astype(float)
|
|
h2_score = (
|
|
h2k.clip(0).astype(float) * 0.40
|
|
+ h2c.clip(0).astype(float) * 0.35
|
|
+ h2p.clip(0).astype(float) * 0.25
|
|
)
|
|
axes['axis_h2_coherence'] = h2_present * h2_score + (1 - h2_present) * 0.5
|
|
|
|
# ── Score combiné pondéré ──
|
|
axes['browser_confidence'] = sum(
|
|
axes[f'axis_{k}'] * w for k, w in _AXIS_WEIGHTS.items()
|
|
)
|
|
return axes
|
|
|
|
|
|
def _infer_browser_family(df: pd.DataFrame, ja4_parsed: pd.DataFrame,
|
|
axes: pd.DataFrame) -> pd.Series:
|
|
"""Infère la famille navigateur par analyse structurelle quand dict_browser_ja4 manque.
|
|
|
|
Priorité :
|
|
1. browser_family connu (dict_browser_ja4) → conservé
|
|
2. Profil structurel JA4 (cipher/ext count) → famille probable
|
|
3. Sinon → '' (inconnu)
|
|
|
|
La famille inférée nécessite browser_confidence ≥ 0.45 pour éviter les faux positifs
|
|
(un bot avec un JA4 structurellement similaire mais sans comportement navigateur).
|
|
"""
|
|
bf = df.get('browser_family', pd.Series('', index=df.index)).fillna('').astype(str)
|
|
result = bf.copy()
|
|
unknown_mask = (result == '')
|
|
if not unknown_mask.any():
|
|
return result
|
|
|
|
# Inférence structurelle sur les sessions sans famille connue
|
|
c = ja4_parsed.loc[unknown_mask, 'ja4_ciphers']
|
|
e = ja4_parsed.loc[unknown_mask, 'ja4_exts']
|
|
tls = ja4_parsed.loc[unknown_mask, 'ja4_tls']
|
|
alpn = ja4_parsed.loc[unknown_mask, 'ja4_alpn']
|
|
conf = axes.loc[unknown_mask, 'browser_confidence']
|
|
|
|
# Seuil minimal : le comportement global doit être suffisamment navigateur
|
|
eligible = conf >= 0.45
|
|
|
|
for family, profile in _BROWSER_JA4_PROFILES.items():
|
|
match = (
|
|
eligible
|
|
& (tls == profile['tls'])
|
|
& alpn.isin(profile['alpn'])
|
|
& c.isin(profile['ciphers'])
|
|
& e.isin(profile['exts'])
|
|
)
|
|
# Affecter seulement si pas encore attribué
|
|
match = match & (result.loc[unknown_mask] == '')
|
|
result.loc[match[match].index] = family
|
|
|
|
return result
|