# Mosis Lua Sandbox Security

**Status**: ✅ Complete (149 security tests passing)
**Goal**: Secure app isolation with defense-in-depth approach.

---

## Overview

Third-party apps run in isolated Lua environments with restricted access to system resources. Each app gets its own `lua_State` with carefully controlled APIs.

```
┌─────────────────────────────────────────────────────────────────────┐
│                         Mosis Kernel                                 │
│  ┌───────────────────────────────────────────────────────────────┐  │
│  │                    LuaSandboxManager                           │  │
│  │  - Creates per-app lua_State with custom allocator             │  │
│  │  - Enforces memory/CPU limits                                  │  │
│  │  - Routes permission-gated API calls                           │  │
│  └───────────────────────────────────────────────────────────────┘  │
│          │                    │                    │                 │
│          ▼                    ▼                    ▼                 │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐          │
│  │ App A State  │    │ App B State  │    │ App C State  │          │
│  │ (isolated)   │    │ (isolated)   │    │ (isolated)   │          │
│  └──────────────┘    └──────────────┘    └──────────────┘          │
│         │                   │                   │                   │
│         └───────────────────┴───────────────────┘                   │
│                             │                                        │
│                    ┌────────▼────────┐                              │
│                    │ Permission Gate │                              │
│                    └────────┬────────┘                              │
│                             │                                        │
│  ┌──────────────────────────▼──────────────────────────────────┐   │
│  │                    System Services                           │   │
│  │  Camera │ Network │ Storage │ Contacts │ Messages │ ...     │   │
│  └─────────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────────┘
```

---

## Threat Model

### Threat Categories

| Category | Threat | Severity | Mitigation |
|----------|--------|----------|------------|
| **Code Execution** | `os.execute()`, `io.popen()` | Critical | Remove globals |
| **File Access** | `io.open()`, `loadfile()` | Critical | Remove globals |
| **Bytecode Injection** | `load()` with binary chunks | Critical | Text-only loading |
| **Memory Exhaustion** | Infinite tables/strings | High | Custom allocator with limits |
| **CPU Exhaustion** | Infinite loops | High | Instruction count hook |
| **Sandbox Escape** | `debug.getregistry()` | Critical | Remove debug library |
| **Global Pollution** | Modifying `_G`, `string` | Medium | Frozen globals |
| **Path Traversal** | `require("../../etc/passwd")` | Critical | Path validation |
| **Data Exfiltration** | Unauthorized network access | High | Permission-gated network |
| **Privilege Escalation** | Access other app's data | High | Per-app storage isolation |
| **Timing Attacks** | High-resolution timers | Low | Limit timer precision |
| **Side Channels** | Memory/CPU usage patterns | Low | Rate limiting |

### Attacker Capabilities

We assume a malicious app developer can:
- Write arbitrary Lua code within the sandbox
- Attempt to exploit any exposed API
- Try to escape the sandbox via Lua language features
- Attempt DoS via resource exhaustion
- Try to access other apps' data
- Attempt to exfiltrate user data

---

## Security Layers

### Layer 1: Dangerous Globals Removal
Remove all dangerous functions before any app code runs: `os`, `io`, `debug`, `package`, `require`, `ffi`, `jit`, `dofile`, `loadfile`, `load`, `loadstring`, `rawget`, `rawset`, `collectgarbage`, `string.dump`.

### Layer 2: Bytecode Prevention
Only allow text chunks (`"t"` mode), reject binary Lua bytecode.

### Layer 3: Memory Limits
Custom allocator tracks and limits memory per app (16 MB default).

### Layer 4: CPU Limits
Instruction count hook interrupts runaway code (10M instructions default).

### Layer 5: Metatable Protection
Freeze `_G` and string metatable to prevent modification.

### Layer 6: Permission System
Three categories: Normal (auto-granted), Dangerous (user prompt), Signature (system only).

### Layer 7: Rate Limiting
Token bucket rate limiting on sensitive operations.

### Layer 8: Audit Logging
All security events logged for forensics.

---

## Implementation

The sandbox is implemented across 20 milestones with 22 modules. See:

- **[SANDBOX_MILESTONES.md](SANDBOX_MILESTONES.md)** - Complete implementation details for all 20 milestones
- **[LUA-SANDBOX.md](LUA-SANDBOX.md)** - API documentation for app developers

### Milestone Overview

| Phase | Milestones | Components |
|-------|------------|------------|
| **Foundation** | 1-4 | Core sandbox, permissions, audit logging, path security |
| **Core APIs** | 5-8 | Timers, JSON, crypto, virtual filesystem, SQLite |
| **Network** | 9-10 | HTTP requests, WebSocket connections |
| **Hardware** | 11-17 | Camera, mic, audio, location, sensors, Bluetooth, contacts |
| **System** | 18-20 | Inter-app messaging, security tests, kernel integration |

### Source Files

All sandbox code is in `src/main/cpp/sandbox/`:

| File | Description |
|------|-------------|
| `sandbox_manager.cpp` | Multi-app orchestrator |
| `lua_sandbox.cpp` | Core Lua sandbox with resource limits |
| `permission_gate.cpp` | Permission system |
| `virtual_fs.cpp` | Per-app virtual filesystem |
| `database_manager.cpp` | SQLite per app |
| `network_manager.cpp` | HTTP request validation |
| `websocket_manager.cpp` | WebSocket connections |
| `timer_manager.cpp` | setTimeout/setInterval |
| `json_api.cpp` | Safe JSON encode/decode |
| `crypto_api.cpp` | SHA256, HMAC, secure random |
| `camera_interface.cpp` | Camera with indicators |
| `microphone_interface.cpp` | Microphone with indicators |
| `audio_output.cpp` | Audio playback |
| `location_interface.cpp` | GPS with precision control |
| `sensor_interface.cpp` | Accelerometer, gyroscope, etc. |
| `bluetooth_interface.cpp` | Bluetooth device access |
| `contacts_interface.cpp` | Contacts read/write |
| `message_bus.cpp` | Inter-app communication |

---

## Testing

149 security tests verify sandbox integrity. Run with:

```bash
cd sandbox-test
./run_tests.bat
```

### Test Categories

- Dangerous globals removal
- Bytecode rejection
- Memory limit enforcement
- CPU limit enforcement
- Metatable protection
- Path traversal prevention
- Permission checks
- Rate limiting
- Network security (private IP blocking, HTTPS enforcement)
- Hardware indicator requirements

---

## References

- [Lua 5.4 Manual - Sandboxing](https://www.lua.org/manual/5.4/)
- [OWASP Secure Coding Practices](https://owasp.org/www-project-secure-coding-practices-quick-reference-guide/)
- Android permission model

---

*Last updated: 2026-01-19*
