# Network Security Monitor

## Overview

The Network Security Monitor is a comprehensive system for tracking and logging all outbound network connections made by your M1 ERP application. It provides real-time visibility into network traffic, automatically blocks external connections, and helps verify that your AI and other services are running 100% locally with no external data leakage.

## Key Features

### 🔒 Security Features
- **Automatic External Blocking**: Any connection attempt to non-local hosts is automatically blocked and logged
- **Local Host Whitelist**: Pre-configured list of safe local addresses (127.0.0.1, localhost, ::1, private IP ranges)
- **Real-Time Alerts**: Visual indicators when blocked connections are detected
- **Detailed Logging**: Every connection attempt is logged with full context and metadata

### 📊 Monitoring Capabilities
- **Top Bar Status Icon**: Always-visible shield icon showing current security status
- **Real-Time Feed**: Live stream of connection attempts (updates every 2 seconds)
- **Connection Log**: Searchable table of all network activity with filtering
- **Statistics Dashboard**: Aggregated metrics across different time periods
- **Connection Testing**: Test any URL to see if it would be allowed or blocked

### 🎯 AI Integration
- **Automatic AI Tracking**: All AI (Ollama) requests are automatically logged
- **Context Awareness**: Logs include AI model, endpoint, payload size, and token counts
- **Performance Metrics**: Track response times and data volumes
- **Zero External Calls**: Verifies AI remains 100% local

## Architecture

### Core Components

1. **NetworkMonitor Class** (`core/NetworkMonitor.php`)
   - Singleton pattern for global access
   - Session-based statistics
   - Database persistence for long-term logs
   - Automatic local/external detection

2. **NetworkMonitorController** (`controllers/NetworkMonitorController.php`)
   - Dashboard interface
   - REST API endpoints for AJAX
   - Permission-based access control

3. **Database Table** (`network_monitor_logs`)
   - Stores all connection attempts
   - Indexed for fast queries
   - Foreign key to users table

4. **UI Components**
   - Top bar status icon with dropdown
   - Full dashboard page
   - Real-time JavaScript updates
   - Bootstrap 5 styling

## Installation

### 1. Database Migration
Already completed - table `network_monitor_logs` created with migration `030_network_monitor.sql`.

### 2. Permissions
Two permissions created:
- `network_monitor.view` - View dashboard (granted to admins)
- `network_monitor.manage` - Manage settings (granted to admins)

### 3. Menu Item
Added to app grid in top navigation bar.

### 4. Routes
All routes added to `public/index.php`:
```php
GET  /network-monitor              - Dashboard
GET  /network-monitor/status       - Current status (AJAX)
GET  /network-monitor/logs         - Connection logs (AJAX)
GET  /network-monitor/feed         - Real-time feed (AJAX)
GET  /network-monitor/log-detail   - Single log details
POST /network-monitor/test-connection - Test URL blocking
POST /network-monitor/add-host     - Add allowed host
POST /network-monitor/clear-logs   - Clear old logs
```

## Usage

### Viewing Network Status

#### Top Bar Icon
- **Green Shield** = Secure (no blocked attempts this session)
- **Yellow Shield** = Warning (blocked attempts detected)
- **Red Badge** = Number of blocked connection attempts
- Click icon to see dropdown with statistics

#### Dashboard
Access via:
- App grid menu (shield icon)
- Direct URL: `/network-monitor`
- Top bar dropdown → "View Full Monitor"

### Dashboard Features

#### Statistics Cards
- **Total Attempts**: All connection attempts this session
- **Allowed (Local)**: Connections to localhost/local IPs
- **Blocked (External)**: Attempted connections to external hosts
- **Session Started**: When tracking began

#### Real-Time Feed
- Shows last 10 connection attempts
- Updates every 2 seconds
- Green checkmark = allowed, Red X = blocked
- "Live" indicator shows feed status

#### Connection Log Table
Filter options:
- **All**: Show everything
- **Local Only**: Only local connections
- **Blocked Only**: Only external/blocked attempts

Each row shows:
- Timestamp
- Host and port
- Context (what triggered the connection)
- HTTP method
- Status (success, blocked, failed)
- Type (Local or External)
- Actions (view details)

#### Allowed Hosts Panel
- Lists all whitelisted hosts
- Default: localhost, 127.0.0.1, ::1, private IPs
- Add custom hosts if needed (use with caution)

#### Connection Test Tool
Test any URL to see if it would be:
- ✅ Allowed (local address)
- ❌ Blocked (external address)

### Log Details
Click the eye icon on any log entry to see:
- Full URL
- Request payload (for AI calls: model, size)
- Response data (for AI calls: token count, response size)
- User who made the request
- IP address
- User agent
- Full timestamp

## Integration with AI

The NetworkMonitor is automatically integrated into the AI class. Every AI API call to Ollama is logged with:

```php
// Example log entry for AI chat
{
  "url": "http://localhost:11434/api/chat",
  "host": "localhost",
  "port": 11434,
  "method": "POST",
  "context": "AI Chat",
  "is_local": 1,
  "status": "success",
  "request_data": {
    "model": "llama3.2:3b",
    "endpoint": "/chat",
    "payload_size": 234
  },
  "response_data": {
    "status": "success",
    "response_size": 567,
    "tokens": 45
  }
}
```

## API Reference

### Get Current Status
```javascript
fetch('/network-monitor/status')
  .then(res => res.json())
  .then(data => {
    // data.status: 'secure' or 'warning'
    // data.total_attempts: int
    // data.blocked_attempts: int
    // data.allowed_attempts: int
  });
```

### Get Connection Logs
```javascript
fetch('/network-monitor/logs?limit=50&only_blocked=true')
  .then(res => res.json())
  .then(data => {
    // data.logs: array of connection objects
  });
```

### Test Connection
```javascript
fetch('/network-monitor/test-connection', {
  method: 'POST',
  body: 'url=' + encodeURIComponent('https://google.com')
})
.then(res => res.json())
.then(data => {
  // data.allowed: true/false
  // data.message: description
});
```

## Security Considerations

### What Gets Blocked
- Any host not in `127.0.0.1`, `localhost`, `::1`
- Any IP outside private ranges (10.x.x.x, 192.168.x.x, 172.16-31.x.x)
- DNS names that resolve to external IPs

### What Gets Allowed
- `localhost` and `127.0.0.1`
- IPv6 localhost (`::1`)
- Private IP ranges (RFC 1918)
- Custom hosts added via "Add Host" (admin only)

### Important Notes
- **Blocking is detection-only**: The NetworkMonitor logs attempts but doesn't prevent them at the network level. It relies on proper application configuration.
- **Ollama must listen on localhost**: Verify with `lsof -i :11434` that Ollama only binds to 127.0.0.1.
- **No false positives**: If you see blocked attempts, investigate immediately - your application should not be making external calls.

## Verification Process

### Verify 100% Local Operation

1. **Start fresh session** (clear browser cache/cookies)
2. **Use AI features** (chat, data analysis, etc.)
3. **Check Network Monitor**:
   - All connections should show as "Local"
   - No "Blocked" or "External" entries
   - All hosts should be `localhost` or `127.0.0.1`

### Test External Blocking
1. Go to Network Monitor dashboard
2. Use "Test Connection" tool
3. Enter: `https://google.com`
4. Should show "Connection blocked - external host detected"
5. Check logs - will see blocked entry

### System-Level Verification
```bash
# Monitor network while using AI
sudo tcpdump -i any 'not (host 127.0.0.1 or host localhost)' &

# Use AI features in browser
# Press Ctrl+C to stop

# Should see ZERO outbound connections (except your browser to localhost)
```

## Troubleshooting

### Status Icon Not Updating
- Check browser console for JavaScript errors
- Verify route `/network-monitor/status` is accessible
- Session may have expired - refresh page

### No Logs Appearing
- Check database table exists: `DESCRIBE network_monitor_logs`
- Verify NetworkMonitor is being called (check error logs)
- Ensure user has `network_monitor.view` permission

### False Positives (Legitimate Local Calls Blocked)
- Add host to allowed list via dashboard
- Or programmatically: `NetworkMonitor::getInstance()->addAllowedHost('192.168.1.100')`

### Performance Impact
- Logs are written asynchronously
- Database inserts are wrapped in try/catch
- Minimal overhead (~5ms per logged connection)
- Auto-cleanup available (clear logs older than X days)

## Maintenance

### Clear Old Logs
Via dashboard:
- Click "Clear Logs" button
- Specify days to keep (default: 30)

Via code:
```php
NetworkMonitor::getInstance()->clearOldLogs(30); // Keep last 30 days
```

Via database:
```sql
DELETE FROM network_monitor_logs WHERE timestamp < DATE_SUB(NOW(), INTERVAL 30 DAY);
```

### Monitor Database Size
```sql
SELECT 
  COUNT(*) as total_logs,
  ROUND(SUM(LENGTH(request_data) + LENGTH(response_data)) / 1024 / 1024, 2) as size_mb
FROM network_monitor_logs;
```

## Future Enhancements

Potential additions:
- [ ] Email alerts on blocked attempts
- [ ] Rate limiting detection
- [ ] Network topology visualization
- [ ] Integration with system firewall
- [ ] Export logs to CSV/JSON
- [ ] Webhook notifications
- [ ] Pattern analysis (unusual hosts, times)
- [ ] Integration with SIEM tools

## Files

### Core Files
- `core/NetworkMonitor.php` - Main monitoring class
- `core/AI.php` - AI class with integrated monitoring
- `controllers/NetworkMonitorController.php` - Web interface
- `views/network_monitor/index.php` - Dashboard UI
- `views/layouts/app.php` - Top bar icon integration
- `database/migrations/030_network_monitor.sql` - Database schema

### Routes
- All routes defined in `public/index.php` (search "Network Monitor")

### Database
- Table: `network_monitor_logs`
- Permissions: `network_monitor.view`, `network_monitor.manage`
- Menu item: In `menu_items` table

## Support

For issues or questions:
1. Check this documentation
2. Review error logs: `error_log` in PHP
3. Check database for logged attempts
4. Test with simple case (known localhost call)
5. Verify permissions are granted

## Privacy & Compliance

This system helps ensure:
- **GDPR Compliance**: No data leaves your infrastructure
- **SOC 2**: Audit trail of all network activity
- **ISO 27001**: Network security controls
- **HIPAA**: PHI remains on-premises
- **Internal Policies**: Proof of local-only operation

All logs contain sensitive data - ensure appropriate database security and access controls are in place.

---

**Version**: 1.0  
**Created**: 2025-01-19  
**Last Updated**: 2025-01-19
