Building a File Integrity Monitoring (FIM) System with Osquery

In enterprise security and compliance auditing, tracking unauthorized modifications to critical system binaries, configuration files, and registry keys is paramount for detecting rootkits and indicators of compromise early.

By combining Osquery (which exposes operating system internals as a relational SQLite database) with automated Python scripts, security engineers can build a lightweight and robust File Integrity Monitoring (FIM) pipeline.

Core Mechanics of Osquery-Based FIM Pipelines

Osquery transforms the operating system into a high-performance relational database, allowing security tooling to inspect filesystem state efficiently:

  • Filesystem Event Tables: Leverages Osquery's built-in file integrity monitoring capabilities (via kernel APIs like inotify on Linux or FSEvents on macOS) to track file hashes, permissions, and modification timestamps.
  • SQLite Query Interface: Executes standard SQL queries against system tables (e.g., file_events and hash) to discover real-time changes across sensitive paths.
  • Automated Python Log Parsing: Continuously polls or consumes Osquery result logs, evaluating differential changes and triggering alerts when unauthorized file modifications occur.

Traditional File Integrity Tools vs. Osquery FIM

Evaluation PillarTraditional FIM DaemonsOsquery + Python FIM Pipeline
Query FlexibilityRigid configuration files and proprietary rule syntaxStandard SQL queries across cross-platform OS telemetry tables
Resource FootprintHeavy background scanners that consume disk I/O and CPULightweight, event-driven kernel integration with minimal overhead
Best Suited ForLegacy compliance reporting and basic integrity hashingCloud-native fleet visibility, SIEM integration, and automated threat hunting

Python Osquery Log Parsing & Alert Blueprint

Here is how to write a Python script that parses Osquery JSON log output to detect file modification events and trigger security alerts:

Python
Parsing Osquery JSON logs to detect unauthorized file modifications in Python
import json

def process_osquery_fim_log(log_line):
    try:
        # 1. Parse incoming JSON event from Osquery
        event = json.loads(log_line)
        
        columns = event.get("columns", {})
        action = event.get("action", "")
        
        # 2. Inspect file integrity events (e.g., updates, additions, deletions)
        if action in ["UPDATED", "ADDED"]:
            target_path = columns.get("target_path")
            sha256_hash = columns.get("sha256", "N/A")
            actor_id = columns.get("uid", "unknown")
            
            print(f"[SECURITY ALERT] File {action}: {target_path}")
            print(f"  - SHA256 Hash: {sha256_hash}")
            print(f"  - User ID: {actor_id}")
            return True
            
        return False
    except Exception as e:
        print(f"[ERROR] Failed to parse log line: {e}")
        return False

# Execution test
if __name__ == "__main__":
    mock_osquery_log = json.dumps({
        "action": "UPDATED",
        "columns": {
            "target_path": "/etc/shadow",
            "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            "uid": "0"
        }
    })
    
    process_osquery_fim_log(mock_osquery_log)

File Integrity Monitoring Best Practices

When deploying Osquery-based FIM pipelines across production Linux and cloud servers, follow these guidelines:

  • Scope Monitored Paths Carefully: Limit your Osquery file packs to critical system directories (e.g., /etc/, /bin/, /usr/bin/) to avoid excessive disk I/O and log noise.
  • Secure Osquery Configurations: Lock down configuration files and prevent unprivileged local users from modifying Osquery daemon parameters or disabling packs.
  • Ship Logs to a SIEM: Forward FIM event logs instantly to a centralized SIEM or data lake (such as Elasticsearch or Splunk) for real-time alerting and incident correlation.