Exploit databaseDownload repository ZIP
GH-dc9f3bf19a1fadec9492bc498d07cfab
mahdi13830510/cve-2026-31431-mitigation-suite
Sources for CVE-2026-31431
166 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files2
mahdi13830510/cve-2026-31431-mitigation-suiteRevision d47c072dc94e
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
ebpf/af_alg_tracer.py
Python · 6,863 bytes#!/usr/bin/env python3
"""
af_alg_tracer.py - Runtime observability for AF_ALG socket creation.
Hooks the kernel's `security_socket_create` LSM hook via kprobe and emits
a structured event whenever a process attempts to create a socket in the
AF_ALG (38) address family. AF_ALG is the userspace interface to the
kernel crypto API; legitimate use is rare in modern userland and the
subsystem has a long history of CVEs (e.g. CVE-2019-8912, CVE-2017-13215),
so any creation event is a high-signal indicator for SOC review.
Output is line-delimited JSON on stdout, suitable for shipping to
Fluent Bit, Vector, or a sidecar collector.
Requires: bcc >= 0.25, Linux >= 4.18 (for security_socket_create kprobe),
CAP_BPF or root.
Usage:
sudo ./af_alg_tracer.py [--pretty] [--allowlist /etc/af-alg-defense/allow.list]
"""
from __future__ import annotations
import argparse
import json
import os
import signal
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
try:
from bcc import BPF
except ImportError:
sys.stderr.write(
"ERROR: python3-bcc is not installed. "
"On Debian/Ubuntu: apt install bpfcc-tools python3-bpfcc\n"
)
sys.exit(2)
# AF_ALG is family 38 on Linux. Defined in <linux/socket.h>.
AF_ALG = 38
BPF_PROGRAM = r"""
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
struct event_t {
u64 ts_ns;
u32 pid;
u32 tgid;
u32 uid;
u32 gid;
s32 family;
s32 type;
s32 protocol;
char comm[TASK_COMM_LEN];
};
BPF_PERF_OUTPUT(events);
/*
* security_socket_create(int family, int type, int protocol, int kern)
*
* The LSM hook fires before the socket structure is allocated, so we
* observe the *intent* to create the socket rather than the result.
* This is exactly what we want for behavioral monitoring: even a denied
* attempt is forensically interesting.
*/
int kprobe__security_socket_create(struct pt_regs *ctx,
int family, int type, int protocol, int kern)
{
if (family != FILTER_FAMILY)
return 0;
/* kern == 1 means kernel-internal socket; we only care about userspace */
if (kern)
return 0;
struct event_t evt = {};
u64 id = bpf_get_current_pid_tgid();
u64 ugid = bpf_get_current_uid_gid();
evt.ts_ns = bpf_ktime_get_ns();
evt.pid = (u32)id;
evt.tgid = id >> 32;
evt.uid = (u32)ugid;
evt.gid = ugid >> 32;
evt.family = family;
evt.type = type;
evt.protocol = protocol;
bpf_get_current_comm(&evt.comm, sizeof(evt.comm));
events.perf_submit(ctx, &evt, sizeof(evt));
return 0;
}
"""
def load_allowlist(path: Path | None) -> set[str]:
"""Read newline-separated comm names that should be suppressed.
The allowlist exists to silence known-good crypto consumers (e.g. cryptsetup
during boot) without losing the ability to detect deviations. Lines starting
with '#' and blank lines are ignored.
"""
if path is None or not path.exists():
return set()
out: set[str] = set()
for line in path.read_text().splitlines():
line = line.strip()
if line and not line.startswith("#"):
out.add(line)
return out
def boot_time_epoch() -> float:
"""Return the system boot time as a UNIX epoch.
bpf_ktime_get_ns() is monotonic-since-boot; we add boot_time to convert
to wall-clock for the JSON timestamp. /proc/stat's `btime` is preferred
over CLOCK_BOOTTIME math because it survives suspend correctly.
"""
with open("/proc/stat") as f:
for line in f:
if line.startswith("btime"):
return float(line.split()[1])
# Fallback - imprecise but better than crashing
return time.time() - time.monotonic()
def build_emitter(pretty: bool, allowlist: set[str]):
btime = boot_time_epoch()
def emit(cpu, data, size): # noqa: ARG001 - BCC callback signature
evt = b["events"].event(data)
comm = evt.comm.decode("utf-8", errors="replace")
if comm in allowlist:
return
record = {
"@timestamp": datetime.fromtimestamp(
btime + evt.ts_ns / 1e9, tz=timezone.utc
).isoformat(),
"event": {
"category": "kernel",
"action": "af_alg_socket_create",
"severity": "high",
},
"process": {
"pid": evt.pid,
"tgid": evt.tgid,
"comm": comm,
},
"user": {
"uid": evt.uid,
"gid": evt.gid,
},
"socket": {
"family": evt.family,
"family_name": "AF_ALG",
"type": evt.type,
"protocol": evt.protocol,
},
"host": {
"name": os.uname().nodename,
},
}
if pretty:
print(json.dumps(record, indent=2), flush=True)
else:
print(json.dumps(record, separators=(",", ":")), flush=True)
return emit
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--pretty",
action="store_true",
help="Pretty-print JSON (default: line-delimited JSON for log shippers)",
)
parser.add_argument(
"--allowlist",
type=Path,
default=Path("/etc/af-alg-defense/allow.list"),
help="Path to comm-name allowlist (one name per line)",
)
args = parser.parse_args()
if os.geteuid() != 0:
sys.stderr.write("ERROR: root or CAP_BPF required to load eBPF programs.\n")
return 1
allowlist = load_allowlist(args.allowlist)
# Inject the family filter at compile-time so the verifier sees a constant
# and can prune the branch entirely. Avoids a per-event map lookup.
program = BPF_PROGRAM.replace("FILTER_FAMILY", str(AF_ALG))
global b # used by the perf callback
b = BPF(text=program)
# Print a startup banner to stderr so it doesn't pollute the JSON stream
sys.stderr.write(
f"[af-alg-tracer] attached to security_socket_create; "
f"family={AF_ALG} (AF_ALG); allowlist={len(allowlist)} entries\n"
)
b["events"].open_perf_buffer(build_emitter(args.pretty, allowlist), page_cnt=64)
stop = {"flag": False}
def handle_signal(signum, frame): # noqa: ARG001
stop["flag"] = True
signal.signal(signal.SIGINT, handle_signal)
signal.signal(signal.SIGTERM, handle_signal)
while not stop["flag"]:
try:
b.perf_buffer_poll(timeout=500)
except KeyboardInterrupt:
break
sys.stderr.write("[af-alg-tracer] shutting down\n")
return 0
if __name__ == "__main__":
sys.exit(main())