Skip to main content

Security Architecture & Configuration Guide

This document defines the comprehensive security architecture for the LLM Platform, including DOD Level 5 compliance requirements, zero-trust implementation, and deployment in classified environments.

Environment Variables​

Metrics Authentication​

# Enable/disable metrics endpoint authentication (default: true)
METRICS_AUTH_ENABLED=true

# API key for metrics endpoint access
METRICS_API_KEY=your-secure-api-key-here

# Optional: Custom header name for API key (default: x-metrics-api-key)
METRICS_API_HEADER=x-metrics-api-key

CSRF Protection​

# Enable/disable CSRF protection (default: true)
CSRF_ENABLED=true

# CSRF token cookie name (default: XSRF-TOKEN)
CSRF_COOKIE_NAME=XSRF-TOKEN

# CSRF token header name (default: X-XSRF-TOKEN)
CSRF_HEADER_NAME=X-XSRF-TOKEN

# Cookie security settings
NODE_ENV=production # Enables secure cookies

Rate Limiting​

# Redis URL for distributed rate limiting
REDIS_URL=redis://localhost:6379

# Rate limit window in milliseconds (default: 900000 = 15 minutes)
RATE_LIMIT_WINDOW=900000

# Maximum requests per window (default: 1000)
RATE_LIMIT_MAX=1000

General Security​

# Node environment (production enables stricter security)
NODE_ENV=production

# Allowed CORS origins (comma-separated)
CORS_ORIGINS=https://app.example.com,https://admin.example.com

# IP whitelist (comma-separated, optional)
IP_WHITELIST=192.168.1.0/24,10.0.0.0/8

# IP blacklist (comma-separated, optional)
IP_BLACKLIST=192.168.1.100,10.0.0.50

Implementation Details​

1. Shell Command Injection Protection​

All shell command executions are now protected with:

  • Command whitelist validation
  • Argument escaping
  • Path traversal prevention
  • Use of Node.js native APIs where possible

Location:

  • /CommonNPM/tddai/src/utils/security.ts
  • /CommonNPM/llmcli/src/utils/security.ts

2. CSRF Protection​

Implemented double-submit cookie pattern:

  • Automatic token generation on GET requests
  • Token validation on state-changing operations
  • Excluded paths for public endpoints
  • Timing-safe token comparison

Location:

  • /CommonNPM/llm-gateway/src-legacy/middleware/csrf.ts
  • /CommonNPM/llmcli/src/api/middleware/csrf.ts

3. Metrics Endpoint Protection​

API key authentication for sensitive metrics:

  • Optional authentication (configurable)
  • Timing-safe API key comparison
  • Custom header support

Location:

  • /CommonNPM/llm-gateway/src/middleware/metricsAuth.js

4. Input Sanitization​

Comprehensive input sanitization:

  • SQL injection prevention
  • XSS protection
  • Path traversal blocking
  • Prototype pollution prevention

Location:

  • /CommonNPM/llm-gateway/src-legacy/middleware/security.ts

Usage Examples​

Accessing Protected Metrics​

# With authentication enabled
curl -H "X-Metrics-API-Key: your-secure-api-key-here" http://localhost:8080/metrics

# Without proper authentication (returns 401)
curl http://localhost:8080/metrics

Making CSRF-Protected Requests​

// 1. Get CSRF token
const tokenResponse = await fetch('/api/v1/csrf-token', {
credentials: 'include'
});
const { token } = await tokenResponse.json();

// 2. Make protected request
const response = await fetch('/api/v1/ai/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token
},
credentials: 'include',
body: JSON.stringify({ prompt: 'Hello' })
});

Secure Command Execution​

import { safeExec, validatePath } from './utils/security.js';

// Safe command execution
const result = await safeExec('npm', ['install', packageName]);

// Path validation
const safePath = validatePath(userProvidedPath, {
allowedPaths: ['/safe/directory']
});

Security Best Practices​

  1. Always use environment variables for sensitive configuration
  2. Enable all security features in production environments
  3. Regularly update API keys and tokens
  4. Monitor security logs for suspicious activity
  5. Keep dependencies updated to patch vulnerabilities
  6. Use HTTPS in production for secure cookie transmission
  7. Implement proper logging for security events

Testing Security Features​

# Test CSRF protection
npm test -- --grep "CSRF"

# Test input validation
npm test -- --grep "security"

# Test rate limiting
npm test -- --grep "rate limit"

Troubleshooting​

CSRF Token Errors​

  • Ensure cookies are enabled in the client
  • Check that credentials are included in fetch requests
  • Verify the correct header name is used

Metrics Access Denied​

  • Confirm the API key is set in environment variables
  • Check the header name matches configuration
  • Ensure the API key is included in requests

Command Execution Failures​

  • Verify the command is in the allowed list
  • Check for special characters in arguments
  • Use Node.js native APIs when possible

DOD Level 5 Security Architecture​

Security Classification Support​

Classification Levels:
Unclassified (U):
- Public citizen services
- Published government data

Controlled Unclassified (CUI):
- Law enforcement sensitive
- Privacy Act protected data

Secret (S):
- National security information
- Defense-related data

Top Secret (TS):
- Compartmented information
- Special access programs

Zero-Trust Implementation​

// Zero-trust security service
class ZeroTrustSecurityService {

// No implicit trust - verify everything
public function verifyAccess($user, $resource, $context) {
// Continuous verification
$this->verifyIdentity($user);
$this->checkDeviceCompliance($context);
$this->validateLocation($context);
$this->enforceTimeRestrictions($context);

// Least privilege access
return $this->calculateMinimumPermissions($user, $resource);
}
}

DISA STIG Compliance​

class DrupalSTIGCompliance {

// V-235751: Disable unnecessary modules
public function hardenModules() {
$prohibited = ['php', 'devel', 'views_ui', 'field_ui'];
foreach ($prohibited as $module) {
if (\Drupal::moduleHandler()->moduleExists($module)) {
\Drupal::service('module_installer')->uninstall([$module]);
}
}
}

// V-235752: Enforce secure sessions
public function hardenSessions() {
ini_set('session.cookie_secure', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.gc_maxlifetime', 900); // 15 min for classified
}
}

FIPS 140-2 Level 3 Encryption​

Encryption Requirements:
Algorithms:
- AES-256-GCM (data at rest)
- TLS 1.3 (data in transit)
- SHA-384 (hashing)

Key Management:
- Hardware Security Module (HSM)
- Automated key rotation (90 days)
- Split key custody
- Secure key destruction

CAC/PIV Authentication​

class CACAuthenticationProvider {

public function authenticate($certificate) {
// Validate DOD certificate
$this->validateCertificateChain($certificate);
$this->checkCertificateRevocation($certificate);
$this->extractUserAttributes($certificate);

// Map to Drupal user
return $this->mapToLocalAccount($certificate);
}
}

AI-Specific Security Controls​

Model Security & Isolation​

class AIModelSecurity {

// Prevent cross-classification contamination
public function enforceModelIsolation($model, $classification) {
// Separate models per classification level
$allowedData = $this->getDataByClassification($classification);

// Prevent higher classification data access
if ($model->getClassification() < $classification) {
throw new SecurityException('Model lacks required clearance');
}
}

// Prompt injection prevention
public function sanitizePrompt($prompt, $userClearance) {
// Remove injection patterns
$prompt = $this->removeInjectionVectors($prompt);

// Check for classified keywords
$this->scanForClassifiedTerms($prompt, $userClearance);

return $prompt;
}
}

Data Loss Prevention (DLP)​

DLP Configuration:
Patterns:
- SSN: '\d{3}-\d{2}-\d{4}'
- Classification: '(TOP SECRET|SECRET|CONFIDENTIAL)'
- Credit Cards: Luhn algorithm check

Actions:
- Block: Prevent transmission
- Quarantine: Hold for review
- Alert: Notify security team
- Log: Full audit trail

Continuous Security Monitoring​

Security Operations Center (SOC) Integration​

Monitoring Stack:
SIEM: Splunk Enterprise Security

Data Sources:
- Drupal watchdog logs
- Apache/Nginx access logs
- System authentication logs
- Database query logs
- AI model usage logs

Alerts:
- Failed authentication attempts > 3
- Privilege escalation attempts
- Data exfiltration patterns
- Anomalous AI usage
- Compliance violations

Incident Response Automation​

class IncidentResponseService {

public function handleSecurityIncident($incident) {
// Immediate containment
$this->isolateAffectedSystems($incident);
$this->preserveForensicEvidence($incident);

// Notification
$this->notifySecurityTeam($incident);
$this->createIncidentTicket($incident);

// Automated response
if ($incident->getSeverity() >= 'CRITICAL') {
$this->initiateEmergencyProtocol($incident);
}
}
}

Deployment Security Checklist​

Pre-Deployment​

  • STIG compliance scan passed
  • Vulnerability assessment completed
  • Penetration test passed
  • Security documentation reviewed
  • ATO package submitted

Deployment​

  • Secure baseline configuration applied
  • Audit logging enabled
  • Monitoring agents installed
  • Backup encryption verified
  • Access controls configured

Post-Deployment​

  • Security validation completed
  • Compliance scanning scheduled
  • Incident response tested
  • Security metrics baseline established
  • Continuous monitoring active

Air-Gap Deployment Support​

#!/bin/bash
# Secure offline deployment script

# Create offline package
drush package:export --security-hardened

# Generate integrity checks
find . -type f -exec sha256sum {} \; > checksums.txt
gpg --armor --detach-sign checksums.txt

# Prepare transfer media
dd if=/dev/zero of=/dev/sdX bs=4M # Wipe media
dd if=package.tar.gz.gpg of=/dev/sdX bs=4M

Security Contacts & Escalation​

Security Team:
24/7 SOC: 1-800-SEC-TEAM
Email: security@llm-platform.gov

Escalation Matrix:
Level 1: SOC Analyst (0-15 min)
Level 2: Security Engineer (15-30 min)
Level 3: CISO (30-60 min)
Level 4: Agency Leadership (60+ min)