Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions PROJECTS/beginner/linux-ebpf-security-tracer/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
docs/
__pycache__/
*.pyc
.env
.venv/
*.o
*.so
.mypy_cache/
.ruff_cache/
.pytest_cache/
dist/
build/
*.egg-info/
3 changes: 3 additions & 0 deletions PROJECTS/beginner/linux-ebpf-security-tracer/.style.yapf
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[style]
based_on_style = pep8
column_limit = 75
185 changes: 185 additions & 0 deletions PROJECTS/beginner/linux-ebpf-security-tracer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
# Linux eBPF Security Tracer

Real-time syscall tracing tool using eBPF for security observability. Monitors process execution, file access, network connections, privilege changes, and system operations to detect suspicious behavior patterns.

## Features

- Real-time syscall monitoring via eBPF tracepoints
- 10 built-in detection rules mapped to MITRE ATT&CK techniques
- Correlated event analysis (reverse shell detection, privilege escalation)
- Multiple output formats: live color-coded stream, JSON, table summary
- Configurable severity filtering (LOW, MEDIUM, HIGH, CRITICAL)
- Process, file, network, privilege, and system event categories
- Event enrichment from /proc filesystem
- Clean signal handling and eBPF program cleanup

## Prerequisites

- Linux kernel 5.8+ (ring buffer support)
- Root privileges (required for eBPF)
- Python 3.10+
- BCC (BPF Compiler Collection) with Python bindings

## Quick Start

```bash
# Install system dependencies and Python packages
./install.sh

# Start tracing all syscalls
sudo uv run ebpf-tracer

# JSON output, only MEDIUM+ severity
sudo uv run ebpf-tracer -f json -s MEDIUM

# Only network events
sudo uv run ebpf-tracer -t network

# Only show detection alerts
sudo uv run ebpf-tracer --detections

# Filter by process name
sudo uv run ebpf-tracer -c nginx

# Write events to file while streaming
sudo uv run ebpf-tracer -o events.jsonl
```

## Usage

```
ebpf-tracer [OPTIONS]

Options:
-f, --format Output format: json, table, live [default: live]
-s, --severity Minimum severity: LOW, MEDIUM, [default: LOW]
HIGH, CRITICAL
-p, --pid Filter by specific PID
-c, --comm Filter by process name
-t, --type Event category: process, file, [default: all]
network, privilege, system, all
--no-enrich Disable /proc enrichment
-o, --output Also write events to file
--detections Show only detection alerts
--version Show version
--help Show help
```

## Detection Rules

| ID | Name | Severity | MITRE ATT&CK | Trigger |
|----|------|----------|--------------|---------|
| D001 | Privilege Escalation | CRITICAL | T1548 | setuid(0) by non-root |
| D002 | Sensitive File Read | MEDIUM | T1003.008 | /etc/shadow access by non-root |
| D003 | SSH Key Access | MEDIUM | T1552.004 | SSH key file access |
| D004 | Process Injection | MEDIUM | T1055.008 | ptrace ATTACH/SEIZE |
| D005 | Kernel Module Load | HIGH | T1547.006 | init_module syscall |
| D006 | Reverse Shell | CRITICAL | T1059.004 | connect + shell execve sequence |
| D007 | Persistence via Cron | MEDIUM | T1053.003 | Write to cron directories |
| D008 | Persistence via Systemd | MEDIUM | T1543.002 | Write to systemd unit dirs |
| D009 | Log Tampering | MEDIUM | T1070.002 | Log file deletion/truncation |
| D010 | Suspicious Mount | HIGH | T1611 | mount syscall |

## Architecture

```
User Space
┌─────────┐ ┌──────────────┐ ┌─────────────────┐
│ CLI │──▶│ Event Engine │──▶│ Output Renderer │
│ (Typer) │ │ (Processor + │ │ (JSON / Table / │
│ │ │ Detector) │ │ Live Stream) │
└─────────┘ └──────┬───────┘ └─────────────────┘
┌──────┴───────┐
│ BPF Loader │
│ (BCC/Python)│
└──────┬───────┘
─────────────────────┼──────────────────────────────
Kernel Space │
┌──────┴───────┐
│ Ring Buffer │
└──────┬───────┘
┌───────────────┼───────────────────┐
│ eBPF C Tracepoint Programs │
│ ┌─────────┐┌────────┐┌─────────┐ │
│ │ Process ││ File ││ Network │ │
│ └─────────┘└────────┘└─────────┘ │
│ ┌──────────┐┌────────┐ │
│ │Privilege ││ System │ │
│ └──────────┘└────────┘ │
└───────────────────────────────────┘
```

## Monitored Syscalls

| Category | Syscalls | Purpose |
|----------|----------|---------|
| Process | execve, clone | New process creation |
| File | openat, unlinkat, renameat2 | File access and manipulation |
| Network | connect, accept4, bind, listen | Network activity |
| Privilege | setuid, setgid | Privilege changes |
| System | ptrace, mount, init_module | System-level operations |

## Project Structure

```
src/
├── main.py # CLI entrypoint (Typer)
├── config.py # Constants, event types, detection rules
├── loader.py # BCC program loader and ring buffer setup
├── processor.py # Event parsing, enrichment, filtering
├── detector.py # Detection engine with stateless and stateful rules
├── renderer.py # Output formatters (JSON, live, table)
└── ebpf/
├── process_tracer.c # execve, clone tracepoints
├── file_tracer.c # openat, unlinkat, renameat2 tracepoints
├── network_tracer.c # connect, accept4, bind, listen tracepoints
├── privilege_tracer.c # setuid, setgid tracepoints
└── system_tracer.c # ptrace, mount, init_module tracepoints
```

## Example Output

### Live Mode (default)

```
[14:30:01] LOW execve pid=1234 comm=bash /usr/bin/curl
[14:30:01] CRITICAL connect pid=1234 comm=nc 10.0.0.1:4444 [Reverse Shell]
[14:30:02] MEDIUM openat pid=5678 comm=python3 /etc/shadow [Sensitive File Read]
[14:30:03] HIGH init_module pid=9012 comm=insmod [Kernel Module Load]
```

### JSON Mode

```json
{"timestamp":"2026-04-08T14:30:01+00:00","event_type":"connect","pid":1234,"comm":"nc","severity":"CRITICAL","detection":"Reverse Shell","mitre_id":"T1059.004","dest_ip":"10.0.0.1","dest_port":4444}
```

## Development

```bash
# Install dev dependencies
uv sync

# Run unit tests
just test

# Lint
just lint

# Format
just format
```

## How It Works

1. **eBPF C programs** attach to kernel tracepoints for specific syscalls
2. When a traced syscall fires, the eBPF program captures event data (PID, UID, filename, etc.) and pushes it to a shared ring buffer
3. **Python (BCC)** polls the ring buffer and deserializes events via ctypes
4. The **processor** enriches events with data from /proc (parent process, username)
5. The **detection engine** evaluates each event against stateless rules (single-event patterns) and stateful rules (correlated event sequences)
6. The **renderer** outputs events in the selected format with severity-based color coding

## License

MIT
135 changes: 135 additions & 0 deletions PROJECTS/beginner/linux-ebpf-security-tracer/install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
#!/usr/bin/env bash
# ©AngelaMos | 2026
# install.sh

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info() { echo -e "${GREEN}[+]${NC} $1"; }
warn() { echo -e "${YELLOW}[!]${NC} $1"; }
fail() { echo -e "${RED}[-]${NC} $1"; exit 1; }

check_root() {
if [[ $EUID -ne 0 ]]; then
warn "Some steps require root. You may be prompted for sudo."
fi
}

check_kernel() {
local version
version=$(uname -r | cut -d. -f1-2)
local major minor
major=$(echo "$version" | cut -d. -f1)
minor=$(echo "$version" | cut -d. -f2)

if [[ $major -lt 5 ]] || { [[ $major -eq 5 ]] && [[ $minor -lt 8 ]]; }; then
fail "Kernel $version detected. Requires Linux 5.8+ for ring buffer support."
fi
info "Kernel version $(uname -r) meets requirements (5.8+)"
}

detect_distro() {
if [[ -f /etc/os-release ]]; then
. /etc/os-release
echo "$ID"
else
echo "unknown"
fi
}

install_system_deps() {
local distro
distro=$(detect_distro)

case "$distro" in
ubuntu|debian|pop|linuxmint|kali)
info "Detected Debian-based system ($distro)"
sudo apt-get update -qq
sudo apt-get install -y -qq \
bpfcc-tools \
python3-bpfcc \
libbpfcc-dev \
linux-headers-"$(uname -r)" \
2>/dev/null || true
;;
fedora)
info "Detected Fedora"
sudo dnf install -y \
bcc-tools \
python3-bcc \
bcc-devel \
kernel-headers \
kernel-devel \
2>/dev/null || true
;;
rhel|centos|rocky|alma)
info "Detected RHEL-based system ($distro)"
sudo yum install -y \
bcc-tools \
python3-bcc \
bcc-devel \
kernel-headers \
kernel-devel \
2>/dev/null || true
;;
arch|manjaro|endeavouros)
info "Detected Arch-based system ($distro)"
sudo pacman -Sy --noconfirm \
bcc \
bcc-tools \
python-bcc \
linux-headers \
2>/dev/null || true
;;
*)
warn "Unknown distro: $distro"
warn "Install manually: bcc-tools, python3-bcc, linux-headers"
;;
esac
}

install_python_deps() {
if ! command -v uv &>/dev/null; then
info "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
fi

info "Installing Python dependencies with uv..."
uv sync
}

verify_install() {
info "Verifying installation..."

if python3 -c "import bcc" 2>/dev/null; then
info "BCC Python bindings: OK"
else
warn "BCC Python bindings not found in system Python"
warn "Make sure python3-bpfcc (Debian) or python3-bcc (Fedora/Arch) is installed"
fi

if [[ -d /sys/kernel/debug/tracing ]]; then
info "Tracing filesystem: OK"
else
warn "Tracing filesystem not mounted. Try: sudo mount -t debugfs debugfs /sys/kernel/debug"
fi
}

main() {
info "eBPF Security Tracer - Installation"
echo ""
check_root
check_kernel
install_system_deps
install_python_deps
verify_install
echo ""
info "Installation complete. Run with: sudo uv run ebpf-tracer"
}

main "$@"
27 changes: 27 additions & 0 deletions PROJECTS/beginner/linux-ebpf-security-tracer/justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# ©AngelaMos | 2026
# justfile

default:
@just --list

lint:
uv run ruff check .
uv run mypy src/

format:
uv run yapf -r -i src/ tests/

check-format:
uv run yapf -r -d src/ tests/

test:
uv run pytest tests/ -m "not integration"

test-all:
sudo uv run pytest tests/

run *ARGS:
sudo uv run ebpf-tracer {{ARGS}}

install:
./install.sh
Loading
Loading