Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

LLM Firewall 🔒

A lightweight, open-source PII/PHI redaction proxy for any OpenAI-compatible LLM API.

Drop it in front of any LLM — cloud or local — and it automatically strips sensitive data before it reaches the model, then restores real values in the response. Your app never changes. The LLM never sees real data.

Your App  →  [LLM Firewall]  →  OpenAI / Anthropic / Ollama / vLLM / any LLM
                  ↓
         Detects & redacts PII/PHI
         Stores token map (per session)
         De-redacts LLM response  ←

Why This Exists

Use Case Problem How LLM Firewall Helps
Cloud LLMs Customer data leaks to OpenAI/Anthropic Redacts before the API call
Local/Offline LLMs Compliance + audit trail required even on-prem Provides HIPAA-ready audit logs
RAG Pipelines PII lives in retrieved documents, not just user input Scrubs chunks before they hit context window
Fine-tuning Conversation logs contain PII → leaks into model weights Batch sanitize training data
Multi-tenant apps User A's PII can bleed into User B's context Session-scoped token isolation

Features

  • Zero code change — point OPENAI_BASE_URL at the firewall, done
  • De-redaction — LLM responses use real values again, transparently
  • Session-scoped token maps — same value always gets the same token within a session
  • Pluggable providers — regex (default), Presidio, Nightfall, AWS, Azure
  • Fully offline mode — regex + Presidio run with zero network calls
  • Audit log — records PII types + sha256 hash of prompt, never raw text
  • Streaming support — works with stream: true responses
  • Pass-through proxy — forwards all other /v1/* routes (embeddings, models, etc.) transparently

Quickstart

Option 1: Docker (recommended)

# Against OpenAI
docker run -e UPSTREAM=https://api.openai.com \
           -e UPSTREAM_API_KEY=sk-... \
           -p 8080:8080 vamsibvv/llm-firewall

# Against Ollama (fully offline, zero network calls)
docker run -e UPSTREAM=http://host.docker.internal:11434 \
           -p 8080:8080 vamsibvv/llm-firewall

# Against vLLM
docker run -e UPSTREAM=http://host.docker.internal:8000 \
           -p 8080:8080 vamsibvv/llm-firewall

Then change one line in your app:

OPENAI_BASE_URL=http://localhost:8080

That's it. All prompts are now automatically redacted.

Option 2: Docker Compose

git clone https://github.com/vamsibvv/llm-firewall
cd llm-firewall
UPSTREAM=https://api.openai.com UPSTREAM_API_KEY=sk-... docker-compose up

Option 3: From Source

git clone https://github.com/vamsibvv/llm-firewall
cd llm-firewall

# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Run the firewall
UPSTREAM=http://localhost:11434 python3 firewall.py

Configuration

All settings live in config.yaml. Every value can also be set via environment variable.

# config.yaml

upstream:
  # Point at your LLM — any OpenAI-compatible endpoint works
  base_url: https://api.openai.com
  # api_key: your-key-here   ← or use UPSTREAM_API_KEY env var
  timeout: 120  # seconds

# PII/PHI detection provider
# Options: regex (default) | presidio | nightfall | aws | azure
provider: regex

# Provider-specific config (only needed for non-regex providers)
provider_config: {}

# Disable specific patterns (regex provider only)
# Full list: SSN, EMAIL, PHONE, CREDIT_CARD, IPV4, IPV6, URL, MAC_ADDRESS,
#            MRN, NPI, DEA_NUMBER, HEALTH_PLAN_ID, ZIP_CODE, DATE, DOB,
#            AGE, VIN, API_KEY, AWS_KEY, IBAN, ROUTING_NUMBER,
#            PASSPORT, DRIVERS_LICENSE
disabled_patterns: []

# Audit log — records PII types + sha256 hash (never raw text)
audit_log: true
audit_log_file: audit.jsonl

host: 0.0.0.0
port: 8080

Environment Variables

Variable Description Example
UPSTREAM Upstream LLM base URL http://localhost:11434
UPSTREAM_API_KEY API key forwarded to upstream sk-...
PII_PROVIDER Override provider presidio

Environment variables always win over config.yaml.


Supported LLM Servers

Server Config
OpenAI UPSTREAM=https://api.openai.com
Anthropic (via proxy) UPSTREAM=https://api.anthropic.com
Ollama UPSTREAM=http://localhost:11434
vLLM UPSTREAM=http://localhost:8000
LM Studio UPSTREAM=http://localhost:1234
Any OpenAI-compatible Set UPSTREAM to your endpoint

PII/PHI Detection Providers

Provider 1: Regex (default)

Zero dependencies, fully offline, instant startup. Best for structured PII.

provider: regex

No extra install needed. Works out of the box.

Catches: SSN, Email, Phone, Credit Card, IBAN, Routing Number, IPv4/IPv6, MAC Address, URL, MRN, NPI, DEA Number, Health Plan ID, ZIP Code, Date, DOB, Age, VIN, API Keys, AWS Keys, Passport, Driver's License.


Provider 2: Presidio (free, offline NLP)

Microsoft open-source NLP engine. Catches everything regex catches plus names, organizations, and locations. Still fully offline after one-time model download.

pip install presidio-analyzer presidio-anonymizer
python -m spacy download en_core_web_lg
provider: presidio

Catches everything regex catches, plus: Person names, Organization names, Locations, and free-text PHI that regex patterns miss.

Side-by-side comparison:

Input: "Dr. Sarah Johnson from Mayo Clinic called about patient Robert Brown,
        DOB 03/15/1970, MRN: 4492817, reach her at sarah@mayoclinic.org"

Regex output:    "Dr. Sarah Johnson from Mayo Clinic called about patient Robert Brown,
                  DOB [DATE_1], MRN [MRN_1], reach her at [EMAIL_1]"

Presidio output: "Dr. [NAME_1] from [ORG_1] called about patient [NAME_2],
                  DOB [DATE_1], MRN [MRN_1], reach her at [EMAIL_1]"

Presidio also caught: ['NAME', 'ORG']

Provider 3: Nightfall AI

Commercial API with high accuracy across 100+ detectors.

pip install nightfall
provider: nightfall
provider_config:
  nightfall_api_key: your-key-here

Sign up at nightfall.ai. Free trial available.


Provider 4: AWS Comprehend + Comprehend Medical

Uses AWS Comprehend for PII and AWS Comprehend Medical for PHI.

pip install boto3
provider: aws
provider_config:
  aws_region: us-east-1
  aws_access_key: AKIA...      # optional, falls back to ~/.aws/credentials
  aws_secret_key: your-secret

Free tier: 50,000 units/month for 3 months. See AWS pricing.


Provider 5: Azure AI Language

Uses Azure Cognitive Services PII detection.

pip install azure-ai-textanalytics
provider: azure
provider_config:
  azure_endpoint: https://your-resource.cognitiveservices.azure.com
  azure_api_key: your-key-here

Free tier: 5,000 text records/month. See Azure pricing.


Provider Comparison

Regex Presidio Nightfall AWS Azure
Cost Free Free Paid Pay-per-use Pay-per-use
Offline Yes Yes No No No
Structured PII Yes Yes Yes Yes Yes
Person Names No Yes Yes Yes Yes
Organizations No Yes Yes Yes Yes
Locations No Yes Yes Yes Yes
Free-text PHI No Partial Yes Yes Yes
Extra install None ~500MB SDK boto3 Azure SDK
Cold start <1s 5-10s API API API

Recommendation: Start with regex. Add presidio for free NLP-based detection. Use aws or azure for enterprise compliance requirements.


What Gets Redacted

Example 1: Healthcare / PHI — Medical Intake Note

INPUT:
  PATIENT INTAKE NOTE
  Patient: Robert James Caldwell | DOB: 07/23/1962 | MRN: 4492817
  SSN: 542-88-3310 | Insurance ID: BCBS-9921004-TX
  Address: 2847 Pinecrest Drive, Austin, TX 78704
  Phone: (512) 334-7821 | Email: rcaldwell62@gmail.com
  Emergency Contact: Linda Caldwell — (512) 334-9002
  Referring Physician NPI: 1234567890

SENT TO LLM:
  PATIENT INTAKE NOTE
  Patient: Robert James Caldwell | DOB: [DATE_1] | MRN: [MRN_1]
  SSN: [SSN_1] | Insurance ID: BCBS-9921004-TX
  Address: 2847 Pinecrest Drive, Austin, TX [ZIP_CODE_1]
  Phone: [PHONE_1] | Email: [EMAIL_1]
  Emergency Contact: Linda Caldwell — [PHONE_2]
  Referring Physician NPI: [NPI_1]

PII/PHI detected: ['DATE', 'EMAIL', 'MRN', 'NPI', 'PHONE', 'SSN', 'ZIP_CODE']

Example 2: Financial / PCI — Bank Support Ticket

INPUT:
  Customer: Maria Elena Vasquez | DOB: 11/04/1989
  Account: 4111-1111-1111-1111 (Visa Platinum)
  Email: mvasquez89@outlook.com | Phone: 773-902-4415
  Unauthorized charges on 07/28/2026. ATM IP: 10.0.0.45
  Bank routing: 071000013 | IBAN: GB29NWBK60161331926819

SENT TO LLM:
  Customer: Maria Elena Vasquez | DOB: [DATE_1]
  Account: [CREDIT_CARD_1] (Visa Platinum)
  Email: [EMAIL_1] | Phone: [PHONE_1]
  Unauthorized charges on [DATE_2]. ATM IP: [IPV4_1]
  Bank routing: 071000013 | IBAN: [IBAN_1]

PII/PHI detected: ['CREDIT_CARD', 'DATE', 'EMAIL', 'IBAN', 'IPV4', 'PHONE']

Example 3: DevOps / Credential Leak

INPUT:
  DB_HOST=10.0.1.23
  AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
  API_KEY=sk-prod-abc123xyz456def789ghi012jkl345mno678
  Contact: james.wu@company.com | MAC: 00:1A:2B:3C:4D:5E
  VPN: https://vpn.internal.company.com/connect?token=eyJhbGci

SENT TO LLM:
  DB_HOST=[IPV4_1]
  AWS_ACCESS_KEY_ID=[AWS_KEY_1]
  API_KEY=[API_KEY_1]
  Contact: [EMAIL_1] | MAC: [MAC_ADDRESS_1]
  VPN: [URL_1]

PII/PHI detected: ['API_KEY', 'AWS_KEY', 'EMAIL', 'IPV4', 'MAC_ADDRESS', 'URL']

Example 4: Legal / Multi-party PII

INPUT:
  CASE FILE: Henderson vs. Apex Corp
  Plaintiff: Thomas R. Henderson | SSN: 301-55-8821 | DOB: 03/09/1975
  Attorney: Sarah Kim | sarah.kim@legalfirm.com
  Medical records MRN: 7731009 | Injury date: 05/14/2026

SENT TO LLM:
  CASE FILE: Henderson vs. Apex Corp
  Plaintiff: Thomas R. Henderson | SSN: [SSN_1] | DOB: [DATE_1]
  Attorney: Sarah Kim | [EMAIL_1]
  Medical records MRN: [MRN_1] | Injury date: [DATE_2]

PII/PHI detected: ['DATE', 'EMAIL', 'MRN', 'SSN']

Running the Demo

# Clone and set up
git clone https://github.com/vamsibvv/llm-firewall
cd llm-firewall
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt

# Run demo (no LLM needed)
python3 demo.py

To compare regex vs Presidio side by side:

pip install presidio-analyzer presidio-anonymizer
python -m spacy download en_core_web_lg
python3 demo.py   # answer 'y' when asked about Presidio demo

Running Tests

python3 -m pytest tests/ -v

Presidio tests are automatically skipped if not installed:

tests/test_redactor.py::test_email          PASSED
tests/test_redactor.py::test_ssn            PASSED
tests/test_redactor.py::test_deredact_roundtrip  PASSED
...
tests/test_presidio.py  SKIPPED (presidio-analyzer not installed)

Audit Log

Every redacted request appends one line to audit.jsonl. Raw prompt text is never stored — only the sha256 hash and which PII types were detected.

{"ts": "2026-08-07T10:23:11+00:00", "session_id": "abc-123", "pii_types": ["SSN", "EMAIL", "PHONE"], "prompt_hash": "sha256:e3b0c44298fc..."}
{"ts": "2026-08-07T10:24:05+00:00", "session_id": "def-456", "pii_types": ["CREDIT_CARD", "DATE"], "prompt_hash": "sha256:a87ff679a2f3..."}

This is the format compliance auditors (HIPAA, SOC2, PCI-DSS) want to see.

Disable audit logging:

audit_log: false

Using as a Python SDK (in-process)

If you don't want a proxy and prefer to call the redactor directly:

from redactor import Redactor

r = Redactor()

# Redact before sending to LLM
result = r.redact("Patient SSN 123-45-6789, email john@example.com", session_id="session-1")
print(result.redacted_text)   # "Patient SSN [SSN_1], email [EMAIL_1]"
print(result.detections)      # [{"type": "SSN", "token": "[SSN_1]"}, ...]

# De-redact LLM response
llm_response = "Record for [SSN_1] has been updated. Confirmation to [EMAIL_1]."
restored = r.deredact(llm_response, session_id="session-1")
print(restored)  # "Record for 123-45-6789 has been updated. Confirmation to john@example.com."

Or with Presidio:

from providers.presidio import PresidioProvider

p = PresidioProvider()
result = p.redact("Dr. Sarah Johnson from Mayo Clinic called.", session_id="s1")
print(result.redacted_text)  # "Dr. [NAME_1] from [ORG_1] called."

Making it Fully Offline (Air-gapped)

For environments with no internet access:

# 1. One-time: download spaCy model while you have internet
python -m spacy download en_core_web_lg

# 2. Run firewall with --network=none (proves zero outbound connections)
docker run --network=none \
           -e UPSTREAM=http://your-local-ollama:11434 \
           -p 8080:8080 vamsibvv/llm-firewall

The --network=none flag is a strong compliance selling point — you can prove to security teams that no data ever leaves the container.


Project Structure

llm-firewall/
├── firewall.py          # FastAPI proxy — sync, streaming, passthrough routes
├── redactor.py          # Core redact/deredact engine + session token store
├── patterns.py          # 22 PII/PHI regex patterns
├── config.py            # YAML + env var config loader
├── demo.py              # Interactive demo (no LLM needed)
├── providers/
│   ├── __init__.py      # Provider loader (factory)
│   ├── base.py          # Abstract PIIProvider interface
│   ├── regex.py         # Default — wraps core Redactor
│   ├── presidio.py      # Microsoft Presidio (free, offline NLP)
│   ├── nightfall.py     # Nightfall AI API
│   ├── aws.py           # AWS Comprehend + Comprehend Medical
│   └── azure.py         # Azure AI Language
├── tests/
│   ├── conftest.py      # Adds project root to sys.path
│   ├── test_redactor.py # 15 unit tests for core redaction engine
│   ├── test_proxy.py    # 4 integration tests with fake upstream LLM
│   └── test_presidio.py # Presidio tests (auto-skipped if not installed)
├── config.yaml          # Default configuration
├── requirements.txt     # Core deps + optional provider deps
├── Dockerfile           # ~120MB image
└── docker-compose.yml   # One-command deploy

Roadmap

  • Presidio custom recognizers (domain-specific entity types)
  • Web dashboard to visualize audit.jsonl
  • LangChain middleware / LlamaIndex plugin
  • Batch mode for sanitizing fine-tuning datasets
  • Pseudonymization mode (consistent fake names instead of tokens)
  • Metrics endpoint (/metrics) for Prometheus scraping

Contributing

Pull requests welcome. To add a new provider:

  1. Create providers/your_provider.py implementing PIIProvider from providers/base.py
  2. Register it in providers/__init__.py
  3. Add tests in tests/test_your_provider.py
  4. Document it in config.yaml and this README

License

MIT — free to use, modify, and distribute.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages