#!/usr/bin/env python3
"""Log every exec, and the exit of every exec'd process, as JSON lines (kernel proc connector).

Needs root. Nothing is attached to the traced processes. Usage: exec-trace [seconds]
"""
import json
import os
import socket
import struct
import sys
import time

NETLINK_CONNECTOR, CN_IDX_PROC, CN_VAL_PROC = 11, 1, 1
PROC_CN_MCAST_LISTEN, PROC_EVENT_EXEC, PROC_EVENT_EXIT = 1, 0x2, 0x80000000


def read(pid, name):
    try:
        with open(f"/proc/{pid}/{name}", "rb") as f:
            return f.read()
    except OSError:
        return b""


def cmdline(pid):
    return read(pid, "cmdline").replace(b"\0", b" ").decode(errors="replace").strip()


def emit(**fields):
    print(json.dumps({"time": time.strftime("%T"), **fields}), flush=True)


sock = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, NETLINK_CONNECTOR)
sock.bind((os.getpid(), CN_IDX_PROC))
op = struct.pack("=I", PROC_CN_MCAST_LISTEN)
cn = struct.pack("=4I2H", CN_IDX_PROC, CN_VAL_PROC, 0, 0, len(op), 0) + op
sock.send(struct.pack("=IHHII", 16 + len(cn), 3, 0, 0, os.getpid()) + cn)

deadline = time.monotonic() + float(sys.argv[1]) if len(sys.argv) > 1 else None
seen = {}
while deadline is None or time.monotonic() < deadline:
    sock.settimeout(None if deadline is None else max(0.1, deadline - time.monotonic()))
    try:
        data = sock.recv(65536)
    except socket.timeout:
        break
    what = struct.unpack_from("=I", data, 36)[0]
    if what == PROC_EVENT_EXEC:
        tgid = struct.unpack_from("=ii", data, 52)[1]
        status = dict(l.split(":\t", 1) for l in read(tgid, "status").decode(errors="replace").splitlines() if ":\t" in l)
        ppid = status.get("PPid", "").strip()
        seen[tgid] = cmdline(tgid)
        emit(event="exec", pid=tgid, ppid=ppid, uid=status.get("Uid", "").split()[:2],
             exe=os.path.realpath(f"/proc/{tgid}/exe") if os.path.exists(f"/proc/{tgid}/exe") else "",
             cmd=seen[tgid], parent=cmdline(ppid)[:200] if ppid.isdigit() else "")
    elif what == PROC_EVENT_EXIT:
        pid, tgid, code, sig = struct.unpack_from("=iiII", data, 52)
        if pid == tgid and tgid in seen:
            emit(event="exit", pid=tgid, cmd=seen.pop(tgid)[:120],
                 status=(code >> 8) if code & 0x7f == 0 else f"signal {code & 0x7f}")
