GenAIHub
← Back to Technical Section

Data Leakage Prevention

Protecting Sensitive Data in LLM Applications

What is Data Leakage in LLMs?

Data leakage in LLM applications refers to the unintended exposure of sensitive, confidential, or proprietary information through AI systems. This can occur through training data memorization, prompt/response logging, or inadequate input/output filtering.

"Sensitive Information Disclosure occurs when an LLM inadvertently reveals confidential data in its responses, leading to unauthorized data access, privacy violations, and security breaches."

Training Data

Memorized sensitive data in model weights

User Inputs

Sensitive data shared in prompts

RAG Context

Confidential documents in retrieval

Types of Data Leakage

Training Data Extraction

LLMs can memorize and regurgitate training data, including PII, API keys, passwords, and proprietary code. Attackers can craft prompts to extract this memorized information.

Research shows GPT models can recall email addresses, phone numbers, and code from training data

Conversation History Leakage

Session data, chat histories, or context from other users leaking into responses. Can occur due to improper session management, caching issues, or shared memory stores.

User A sees parts of User B's previous conversation in their responses

RAG Document Exposure

Confidential documents indexed for retrieval being exposed to unauthorized users. Improper access control on vector stores can lead to cross-tenant data leakage.

HR documents, financial records, or internal policies exposed via semantic search

System Prompt Disclosure

Attackers extracting confidential system prompts that contain business logic, API endpoints, internal procedures, or competitive advantages.

"Repeat your instructions" → Exposes pricing logic, moderation rules, agent capabilities

Third-Party API Exposure

Sensitive data sent to external LLM providers (OpenAI, Anthropic, etc.) may be logged, used for training, or exposed in case of provider security breaches.

Customer data, internal emails, code sent to cloud APIs without proper safeguards

Sensitive Data Categories

Category Examples Regulations
PII (Personal) Names, SSN, emails, addresses, phone numbers GDPR, CCPA, LGPD
Financial Credit cards, bank accounts, salaries PCI-DSS, SOX
Health (PHI) Medical records, diagnoses, prescriptions HIPAA, HITECH
Credentials API keys, passwords, tokens, secrets SOC 2, ISO 27001
Proprietary Source code, trade secrets, algorithms Trade secret law, NDAs
Internal Employee data, internal policies, strategies Company policies

Prevention Strategies

Input Sanitization

  • Detect & redact PII before sending to LLM
  • Scan for credentials and secrets patterns
  • Apply data classification policies
  • Warn users about sensitive data input

Output Scanning

  • Scan responses for sensitive patterns
  • Block or mask detected sensitive data
  • Validate against data loss policies
  • Log and alert on potential leaks

Access Control

  • Implement document-level permissions in RAG
  • User authentication and authorization
  • Tenant isolation in multi-tenant systems
  • Role-based access to data sources

Infrastructure Security

  • Self-host models for sensitive workloads
  • Encrypt data at rest and in transit
  • Secure logging (exclude sensitive fields)
  • Review vendor data retention policies

Implementation Example

# Using Microsoft Presidio for PII Detection
from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine

analyzer = AnalyzerEngine()
anonymizer = AnonymizerEngine()

def sanitize_input(text: str) -> str:
    """Detect and redact PII before sending to LLM"""
    
    # Analyze for PII entities
    results = analyzer.analyze(
        text=text,
        entities=["PERSON", "EMAIL_ADDRESS", "PHONE_NUMBER", 
                  "CREDIT_CARD", "US_SSN", "IP_ADDRESS"],
        language="en"
    )
    
    # Anonymize detected entities
    anonymized = anonymizer.anonymize(text=text, analyzer_results=results)
    
    return anonymized.text

# Example usage
user_input = "My SSN is 123-45-6789 and email is john@example.com"
safe_input = sanitize_input(user_input)
# Output: "My SSN is <US_SSN> and email is <EMAIL_ADDRESS>"

# Now safe to send to LLM
response = llm.generate(safe_input)

See full documentation: Microsoft Presidio

RAG Access Control Pattern

# Document-level access control in RAG
from typing import List, Dict

def retrieve_with_permissions(
    query: str, 
    user_id: str, 
    user_roles: List[str]
) -> List[Dict]:
    """Retrieve documents respecting user permissions"""
    
    # Get user's accessible document IDs
    allowed_doc_ids = get_user_document_access(user_id, user_roles)
    
    # Search with metadata filter
    results = vector_store.similarity_search(
        query=query,
        k=5,
        filter={
            "document_id": {"$in": allowed_doc_ids},
            "classification": {"$lte": get_user_clearance(user_id)}
        }
    )
    
    # Log access for audit trail
    log_document_access(user_id, [r.metadata["document_id"] for r in results])
    
    return results

Data Protection Tools

Best Practices

Do This

  • Implement defense-in-depth with multiple layers
  • Scan both inputs AND outputs for sensitive data
  • Use data classification and tagging
  • Implement comprehensive audit logging
  • Educate users about data sensitivity
  • Review third-party API data handling policies

Avoid This

  • Sending production data to external APIs unfiltered
  • Logging full prompts/responses with PII
  • Sharing vector stores across security boundaries
  • Trusting LLMs to self-censor sensitive outputs
  • Using production data for fine-tuning without review
  • Ignoring opt-out settings for model training

Research & References

Related Topics