# Security Audit Report - 4Runr OS

**Date:** 2026-02-04  
**Status:** Pre-MVP Development Phase  
**Auditor:** AI Security Review

---

## Executive Summary

This document outlines security vulnerabilities found in the 4Runr OS codebase and their severity. Users should be aware that this is a **pre-MVP project** and should exercise caution when using it.

---

## 🔴 CRITICAL VULNERABILITIES

### 1. **Arbitrary Code Execution via Custom Tools**

**Location:** `packages/os-cli/src/index.ts` (lines 2420-2466)

**Issue:** The `tools test` command allows users to execute arbitrary JavaScript code using Node's `vm` module with access to sensitive modules:

```typescript
const context = {
  console,
  setTimeout,
  setInterval,
  clearTimeout,
  clearInterval,
  Buffer,
  require: (module: string) => {
    // Whitelist safe modules
    const allowed = ['fs', 'path', 'os', 'crypto', 'url', 'http', 'https', 'axios'];
    if (allowed.includes(module)) {
      return require(module);
    }
    throw new Error(`Module '${module}' is not allowed`);
  }
};

const wrappedCode = `
  (async () => {
    ${tool.code}  // USER-PROVIDED CODE EXECUTED HERE
    // ...
  })()
`;

const result = await vm.default.runInNewContext(wrappedCode, context, { timeout: 5000 });
```

**Risk:**
- **File system access:** User code can read/write/delete ANY file the process has access to
- **Network access:** Can make arbitrary HTTP/HTTPS requests
- **Crypto operations:** Can perform cryptographic operations
- **VM escape:** The Node.js `vm` module is NOT a security boundary and can be escaped
- **Stored tools:** Malicious code persists in `~/.4runr/tools.json`

**Severity:** 🔴 **CRITICAL** - Remote Code Execution (RCE)

**Exploitation Scenario:**
```javascript
// A malicious user could create a tool that:
1. Reads SSH keys: fs.readFileSync('~/.ssh/id_rsa')
2. Exfiltrates data: https.request() to send data to attacker server
3. Modifies files: fs.writeFileSync() to corrupt system files
4. Creates backdoors: Writes persistent malicious code
```

**Recommendation:**
- **Remove `vm` execution entirely** or restrict to sandboxed environment
- Use a proper sandboxing solution (Docker, isolated processes)
- Remove `fs`, `http`, `https`, `axios` from allowed modules
- Implement strict input validation and sanitization
- Add code signing/verification for tools

---

### 2. **Command Injection via execSync/spawn**

**Locations:**
- `packages/os-cli/src/index.ts` (line 2888, 2921, 3012)
- `packages/os-cli/src/version-check.ts` (multiple)
- `packages/os-cli/src/system-verify.ts` (multiple)
- `packages/os-cli/src/rust-check.ts` (multiple)
- `packages/os-cli/scripts/setup.js` (multiple)

**Issue:** Multiple uses of `execSync` and `spawn` with potentially user-controlled input or without proper validation.

**Example:**
```typescript
// In version-check.ts - external input from npm registry
const output = execSync(`npm view ${packageName} version`, { encoding: 'utf-8', stdio: 'pipe' });

// In index.ts - spawning cargo with potential path manipulation
const cargoProcess = spawn('cargo', ['build', '--release'], {
  cwd: mk3Dir,
  stdio: 'inherit'
});
```

**Risk:**
- Command injection if `packageName` or paths are manipulated
- Arbitrary command execution with user privileges

**Severity:** 🟠 **HIGH** - Command Injection

**Recommendation:**
- Use parameterized commands (array syntax for spawn - ✅ mostly done)
- Validate all inputs before passing to shell
- Avoid `execSync` with string interpolation
- Use `child_process.spawn` with argument arrays instead

---

## 🟠 HIGH SEVERITY VULNERABILITIES

### 3. **Path Traversal in File Operations**

**Locations:**
- `packages/os-cli/src/index.ts` (lines 189-242)
- `packages/os-cli/src/config.ts` (lines 36-63)
- `packages/os-cli/src/auth.ts` (lines 36-74)

**Issue:** User input (usernames) is used to construct file paths without proper sanitization:

```typescript
function getUserAgentsPath(username: string): string {
  return path.join(getUserConfigDir(username), 'agents.json');
}

function getUserConfigDir(username: string): string {
  const userDir = path.join(getConfigDir(), 'users', username);
  // No validation of username!
  if (!fs.existsSync(userDir)) {
    fs.mkdirSync(userDir, { recursive: true });
  }
  return userDir;
}
```

**Risk:**
- Directory traversal: username like `../../../etc/passwd` could read/write outside intended directory
- File creation in arbitrary locations

**Severity:** 🟠 **HIGH** - Path Traversal

**Exploitation Scenario:**
```bash
# User connects with malicious username
connect ../../.ssh/authorized_keys

# This could potentially:
1. Create directories outside ~/.4runr/
2. Read/write files in unintended locations
3. Overwrite system files if permissions allow
```

**Recommendation:**
- Validate usernames: `if (!/^[a-zA-Z0-9_-]+$/.test(username)) throw new Error()`
- Use `path.resolve()` and verify the result is within expected directory
- Reject any username containing `..`, `/`, or `\`

---

### 4. **Insecure JSON Parsing**

**Locations:**
- Multiple files parsing user-provided JSON without validation

**Issue:** Direct `JSON.parse()` on user files without schema validation:

```typescript
const data = fs.readFileSync(filePath, 'utf-8');
const agents: CustomAgent[] = JSON.parse(data);
// No validation of structure!
agents.forEach(agent => {
  customAgents.set(agent.id, agent);
});
```

**Risk:**
- Prototype pollution
- Type confusion attacks
- Application crashes from malformed data

**Severity:** 🟠 **HIGH** - Data Injection

**Recommendation:**
- Use JSON schema validation (e.g., `ajv`)
- Validate structure before use
- Use safe parsing with try-catch and defaults

---

### 5. **Credential Exposure in Configuration Files**

**Locations:**
- `~/.4runr/session.json` (stores gateway URLs)
- `~/.4runr/config.json` (may store sensitive data)
- Tool and agent files (JSON with potentially sensitive data)

**Issue:** Sensitive data stored in plain text:

```typescript
// session.json structure
{
  "username": "user",
  "loggedInAt": 1234567890,
  "lastActivityAt": 1234567890,
  "expiresAt": 1234567890,
  "gatewayUrl": "http://sensitive-server:3001"  // Exposed!
}
```

**Risk:**
- Credentials readable by any process with file access
- No encryption at rest
- Session tokens stored indefinitely

**Severity:** 🟠 **HIGH** - Credential Exposure

**Recommendation:**
- Encrypt sensitive configuration files
- Use OS keychain/credential manager
- Implement file permissions (chmod 600)
- Clear sessions on exit or timeout

---

## 🟡 MEDIUM SEVERITY VULNERABILITIES

### 6. **Server-Side Request Forgery (SSRF)**

**Location:** `packages/os-cli/src/gateway-client.ts`

**Issue:** Gateway URL is user-controlled and can point to arbitrary hosts:

```typescript
let gatewayUrl = process.env.GATEWAY_URL || '';
// User can set this to ANY URL including:
// - localhost internal services
// - cloud metadata endpoints
// - internal network resources
```

**Risk:**
- SSRF to internal services (e.g., http://localhost:6379 for Redis)
- Cloud metadata access (e.g., http://169.254.169.254 for AWS)
- Port scanning internal network

**Severity:** 🟡 **MEDIUM** - SSRF

**Recommendation:**
- Whitelist allowed gateway domains
- Validate URL format and scheme (only https://)
- Block private IP ranges (127.0.0.0/8, 10.0.0.0/8, 192.168.0.0/16, 169.254.169.254)

---

### 7. **Insecure Automatic Updates**

**Location:** `packages/os-cli/src/version-check.ts`

**Issue:** Automatic npm package updates without integrity checks:

```typescript
execSync(`npm install -g ${packageName}@latest`, { 
  stdio: 'inherit' 
});
```

**Risk:**
- Man-in-the-middle attacks on npm registry
- Malicious package updates
- Supply chain attacks

**Severity:** 🟡 **MEDIUM** - Supply Chain

**Recommendation:**
- Verify package signatures
- Use npm's `--prefer-offline` and lockfiles
- Implement version pinning
- Add user confirmation before updates

---

### 8. **Missing Input Validation on Environment Variables**

**Locations:**
- Multiple files reading unchecked environment variables

**Issue:** Environment variables are trusted without validation:

```typescript
const termProfile = process.env.MK2_SAFE_MARGIN_X;
// No validation - could be negative, huge, or malicious
```

**Risk:**
- Integer overflow
- Resource exhaustion
- Application crashes

**Severity:** 🟡 **MEDIUM** - Input Validation

**Recommendation:**
- Validate all environment variable values
- Set min/max bounds
- Use defaults for invalid values

---

### 9. **Unprotected Temporary File Creation**

**Location:** `packages/os-cli/src/tui_mk1/logger.ts`, layout logs

**Issue:** Writing to predictable paths:

```typescript
fs.appendFileSync('/tmp/mk2_layout.log', log);
```

**Risk:**
- Symlink attacks on Unix systems
- Log injection
- Information disclosure

**Severity:** 🟡 **MEDIUM** - Temporary Files

**Recommendation:**
- Use `fs.mkdtempSync()` for unique temp directories
- Set restrictive permissions (0600)
- Clean up temp files on exit

---

## 🟢 LOW SEVERITY / INFORMATIONAL

### 10. **Verbose Error Messages**

**Issue:** Stack traces and detailed errors may leak internal paths

**Recommendation:** Sanitize error messages in production

---

### 11. **No Rate Limiting**

**Issue:** No protection against brute force or DoS on gateway connections

**Recommendation:** Implement rate limiting on API calls

---

### 12. **Weak Session Management**

**Issue:** Sessions are 2 hours but no refresh mechanism

**Recommendation:** Implement session refresh and shorter timeouts

---

## 🛡️ POSITIVE SECURITY CONTROLS

✅ **Removed hardcoded server IP** (previous audit)  
✅ **Gateway URL requires explicit configuration**  
✅ **No eval() or new Function() usage**  
✅ **Most spawn() calls use array syntax**  
✅ **timeout on vm execution (5 seconds)**  
✅ **Separate user directories for isolation**  

---

## IMMEDIATE ACTION ITEMS

### For Development Team:

1. **🔴 CRITICAL:** Remove or sandbox the `tools test` command
2. **🔴 CRITICAL:** Add path traversal protection for usernames
3. **🟠 HIGH:** Implement JSON schema validation
4. **🟠 HIGH:** Encrypt configuration files
5. **🟡 MEDIUM:** Add SSRF protection for gateway URLs
6. **🟡 MEDIUM:** Implement update integrity checks

### For Users:

⚠️ **WARNINGS:**

- **DO NOT** use this in production environments
- **DO NOT** run as root/administrator
- **DO NOT** connect to untrusted gateways
- **DO NOT** execute untrusted tool code
- **BE AWARE** that custom tools can access your file system
- **BE AWARE** that credentials are stored unencrypted

---

## Testing Recommendations

1. **Penetration Testing:** Engage security researchers
2. **Fuzzing:** Test input validation with malformed data
3. **Static Analysis:** Use tools like Snyk, SonarQube
4. **Dependency Auditing:** Run `npm audit` regularly
5. **Code Review:** Security review before MVP release

---

## Compliance Considerations

- **GDPR:** No PII should be stored without encryption
- **SOC 2:** Requires audit logging and encryption at rest
- **ISO 27001:** Requires risk assessment and mitigation

---

## Conclusion

The 4Runr OS codebase contains **CRITICAL vulnerabilities** that could allow arbitrary code execution and data exfiltration. These MUST be addressed before any production use.

**Recommended Security Posture:**
- ⛔ **NOT SAFE** for production use
- ⚠️ **USE WITH CAUTION** for development/testing
- ✅ **OKAY** for local experimentation (non-sensitive environments)

---

## Version History

- **2026-02-04:** Initial security audit
- **Previous:** Removed hardcoded server IP

---

**Note:** This audit is not exhaustive. A professional security audit by a certified penetration tester is recommended before production release.
