Back to posts
Post

Detecting Anomalous sudo Session Duration with LLM and iptables Automation

Use LLMs to analyze syslog for unusual sudo session lengths and automatically block IPs via iptables—practical steps for Linux admins.

Yapay ZekasudoLLMiptableslog analysis

I’ve been experimenting with lightweight LLM integrations for log analysis lately, especially around privilege escalation patterns. One recurring signal in sudo logs is session duration—legitimate admin tasks usually finish within minutes, but compromised accounts or scripts sometimes leave sudo sessions open for hours. In my environment, I started by enriching sudo session logs with start and end timestamps, then feeding sliding windows of that data into a small local LLM to flag outliers. The goal isn’t to replace tools like auditd or fail2ban, but to add a behavioral layer that catches slow, low-volume abuse that threshold-based rules miss.

First, I needed reliable sudo session data. By default, sudo logs only show command execution, not session boundaries. I patched this using pam_exec and a simple wrapper script that logs session start/end to syslog with a custom tag. Here’s the core of that wrapper:

#!/bin/bash
# /usr/local/lib/sudo-session-logger
SESSION_START=$(date +%s)
logger -t sudo-session "START uid=$(id -u) user=$USER pid=$$"
"$@"
SESSION_END=$(date +%s)
DURATION=$((SESSION_END - SESSION_START))
logger -t sudo-session "END uid=$(id -u) user=$USER duration=$DURATION"

I made it executable and referenced it in /etc/pam.d/sudo via:

session    optional     pam_exec.so /usr/local/lib/sudo-session-logger

Now every sudo session produces two syslog lines: one at start, one at end with duration in seconds. I collect these via rsyslog into a dedicated file (/var/log/sudo-session.log) for easier processing.

Next, the LLM part. I used a quantized Llama 3 8B model running locally with Ollama—no API calls, no external dependencies. I wrote a Python script that reads the last hour of sudo-session logs, groups entries by user and source IP (from PAM’s RHOST), and calculates session duration. Instead of hardcoding thresholds, I prompt the LLM with a JSON array of recent sessions and ask it to identify which ones feel anomalous based on context: time of day, user behavior, duration outliers. The prompt looks like this:

Analyze these sudo session durations (in seconds) for user alice from 10.0.0.45:
[320, 180, 210, 4800, 190]
Which session(s) are likely anomalous and why? Respond in JSON: {"anomalous": [indices], "reason": "short explanation"}

The model correctly flagged the 4800-second session (80 minutes) as unusual given the history. I parse the response and trigger action if confidence is high.

For automation, I integrated with iptables via ipset. When the LLM flags a session as anomalous, I extract the source IP and add it to an ipset called sudo_abusers, which is referenced by a DROP rule in the INPUT chain:

# Setup (run once)
ipset create sudo_abusers hash:ip timeout 3600
iptables -I INPUT -m set --match-set sudo_abusers src -j DROP

The Python script then does:

ipset add sudo_abusers $IP

I set a one-hour timeout so blocks expire unless renewed—prevents lockouts from false positives while still disrupting ongoing abuse. I also log every addition to /var/log/sudo-llm-block.log with the LLM’s reasoning for audit.

This approach isn’t about perfection; it’s about signal amplification. The LLM doesn’t need to understand Linux internals—it just needs to spot that a 90-minute sudo session from a service account at 3 AM doesn’t fit the pattern of the last 20 sessions from that IP. Combined with the speed of iptables ipset updates, it creates a responsive feedback loop.

As I mentioned before in my post on Fail2ban + LLM for SSH (https://furkanikkan.com/urun/fail2ban-llm-ssh-brute-force-saldirilarina-akilli-mudahale-136), the key is keeping the model local and the integration simple. Here, Ollama + a 200-line Python script does the job without introducing latency or external risk. If you’re already collecting sudo logs, adding session boundaries and LLM-based anomaly detection is a low-overhead way to catch slow-moving privilege misuse that signature-based tools overlook.


Cover image: ₡ґǘșϯγ Ɗᶏ Ⱪᶅṏⱳդ · CC0 (Openverse / kamu malı) · https://www.flickr.com/photos/148598741@N02/51973552248