# Injection Analysis Report (SQLi & Command Injection)

## 1. Executive Summary

- **Analysis Status:** Complete
- **Key Outcome:** One critical path traversal vulnerability and one high-severity email header injection vulnerability were identified through comprehensive source code analysis. The path traversal vulnerability has been passed to the exploitation phase via the machine-readable queue at `deliverables/injection_exploitation_queue.json`. All other injection vectors (SQL injection, SSTI, command injection, unsafe deserialization) were analyzed and confirmed secure.
- **Purpose of this Document:** This report provides the strategic context, vulnerability patterns, and environmental intelligence necessary to effectively exploit the path traversal vulnerability listed in the queue. It documents both vulnerable and secure code paths to prevent re-testing and demonstrates complete coverage of all injection sources identified in reconnaissance.

## 2. Dominant Vulnerability Patterns

### Pattern 1: Sanitization Applied to Wrong Variable
- **Description:** The application applies defensive sanitization functions (filepath.Base()) to isolate filename components, but applies this sanitization to a display variable (fileName) while storing and later using a completely unsanitized variable (relPath) in security-critical file operations.
- **Implication:** This represents a logic error where security controls exist but are bypassed due to variable confusion. The developer's intent was clear (sanitize paths), but the implementation split the data flow into two variables and only sanitized one branch.
- **Representative:** INJ-VULN-01 (Path Traversal in file upload processing)

### Pattern 2: Post-Sanitization Data Flow Reconstruction
- **Description:** User input is sanitized at the entry point, then stored in an encrypted database field. When retrieved later for processing, the sanitized state is lost because the original unsanitized value was what got stored. The application trusts database-stored values without re-validating.
- **Implication:** Defense-in-depth failure. Sanitization at input is ineffective if the unsanitized value is persisted and later retrieved for use in dangerous operations. This pattern is especially dangerous in async/multi-step workflows.
- **Representative:** INJ-VULN-01 (relPath stored at line 222, retrieved unsanitized at line 451)

## 3. Strategic Intelligence for Exploitation

### Database Technology & Architecture
- **Database:** SQLite with AES-256-GCM encryption at rest
- **File Storage:** Local filesystem at `/tank/inou/uploads/` with encrypted files
- **Temp Directory:** Processing uses `os.MkdirTemp("", "dicom-import-*)` creating directories in `/tmp/`
- **Process Permissions:** Application runs with permissions to write to `/tank/inou/` and `/tmp/` directories
- **File Permissions:** Written files use `0644` (world-readable, owner-writable)

### Authentication & Access Requirements
- **Path Traversal (INJ-VULN-01):** Requires authenticated user with PermWrite on any dossier (can use attacker's own dossier)
- **Multi-Step Attack:** Upload endpoint is separate from processing endpoint - two requests required
- **No Rate Limiting:** No observed throttling on upload or processing endpoints

### Defensive Measures Observed
- **SQL Injection:** Comprehensive parameterized query usage throughout codebase - all queries use `?` placeholders for user values
- **Command Injection:** Go's `exec.Command()` uses array-based execution preventing shell metacharacter interpretation
- **SSTI:** Templates pre-loaded from disk at startup, user data passed as structured objects with auto-escaping
- **CSRF Protection:** Not observed in file upload endpoints (potential chaining opportunity)

### Exploitation Recommendations
- **Path Traversal Target:** Focus on writing to `/etc/cron.d/` for persistent access, or `/tmp/` for proof-of-concept
- **Authentication Bypass:** Use standard email-based passwordless login (6-digit code sent to email)
- **Backdoor Code:** Testing backdoor code `250365` exists and always validates (CRITICAL: authentication bypass)
- **Payload Delivery:** Use two-step process: (1) POST to `/dossier/{id}/upload` with `path` parameter, (2) POST to `/dossier/{id}/process-imaging` to trigger file write

## 4. Vectors Analyzed and Confirmed Secure

These input vectors were traced through complete source-to-sink analysis and confirmed to have robust, context-appropriate defenses. They are **low-priority** for further testing.

| **Source (Parameter/Key)** | **Endpoint/File Location** | **Defense Mechanism Implemented** | **Verdict** |
|----------------------------|----------------------------|-----------------------------------|-------------|
| All database query parameters | All SQL queries in `/repos/inou-portal/lib/db_queries.go`, `/repos/inou-portal/lib/dbcore.go` | Parameterized queries with `?` placeholders - 100% coverage | SAFE |
| Template page selection | `.Page` field in all template renders | Validated against whitelist, only hardcoded template names used | SAFE |
| JSON deserialization | All API endpoints using `json.NewDecoder().Decode()` | Go's `encoding/json` package - no code execution possible | SAFE |
| DICOM processor targetID | `/repos/inou-portal/portal/upload.go:472` in `exec.Command()` | Array-based execution prevents shell interpretation (no shell=True) | SAFE |
| OAuth parameters | `/oauth/authorize` and `/oauth/token` endpoints | PKCE validation, whitelist for client_id and redirect_uri | SAFE |
| Email address (SMTP envelope) | `client.Rcpt(toEmail)` at `/repos/inou-portal/portal/main.go:331` | SMTP protocol-level validation by net/smtp library | SAFE |
| Integer/Boolean filters | `Limit`, `Category`, `Status` in query filters | Type safety - integers cannot contain injection payloads | SAFE |

### SQL Injection - Comprehensive Analysis

**Total SQL Operations Analyzed:** 40+ across all database files

**Key Findings:**
- **Parameterization Coverage:** 100% - Every user-controlled value uses `?` placeholders
- **Dynamic SQL Construction:** Limited to table/column names from struct tags (compile-time constants), never from user input
- **LIMIT Clauses:** Use `fmt.Sprintf` with integer type (type-safe, no injection risk)
- **ORDER BY Clauses:** All hardcoded literals (`ORDER BY Timestamp, Ordinal`)
- **Encryption Layer:** Sensitive data encrypted via `Pack()` function before parameterization

**Representative Safe Pattern:**
```go
q := "SELECT ... FROM entries WHERE DossierID = ?"
args := []any{dossierID}
if f.Type != "" {
    q += " AND Type = ?"
    args = append(args, Pack([]byte(f.Type)))
}
rows, err := db.Query(q, args...)
```

**Verdict:** NOT VULNERABLE - Excellent security practices throughout

### Server-Side Template Injection - Comprehensive Analysis

**Template Loading Mechanism:**
- Templates loaded once at startup: `template.Must(template.New("").Funcs(funcs).ParseGlob(filepath.Join(tmplDir, "*.tmpl")))`
- Template directory: Hardcoded constant `"templates"`
- No dynamic template parsing from user input

**Template Execution:**
- Template name always hardcoded: `templates.ExecuteTemplate(w, "base.tmpl", data)`
- User data passed as structured `PageData` structs, never as template source
- Page selection via `.Page` field validated against whitelist

**Auto-Escaping:**
- Uses `html/template` package (not `text/template`)
- Context-aware automatic escaping for HTML, JS, CSS, URL contexts
- Custom template functions (`hex`, `sexT`, `dict`) perform only safe formatting

**Verdict:** NOT VULNERABLE - Static templates with proper escaping

### Command Injection - Detailed Analysis

**Sink Location:** `/repos/inou-portal/portal/upload.go:472`
```go
cmd := exec.Command("/tank/inou/bin/import-dicom", targetID, tempDir)
```

**Why Safe from Classic Command Injection:**
- Go's `exec.Command()` uses array-based execution (equivalent to `shell=False` in Python)
- Arguments passed directly to binary via `execve()` syscall
- Shell metacharacters (`;`, `|`, `&`, `$()`, `` ` ``) treated as literal strings
- No shell invocation (`/bin/sh`) occurs

**Remaining Risk (Low):**
- Argument injection: Attacker controls first argument to external binary
- Missing validation: No check that `targetID` is valid 16-character hex
- Mitigation: Authorization check prevents using arbitrary IDs (must have PermWrite on dossier)

**Recommendation:** Add format validation as defense-in-depth:
```go
if lib.ParseID(targetID) == 0 {
    http.Error(w, "Invalid dossier ID", http.StatusBadRequest)
    return
}
```

**Verdict:** NOT VULNERABLE to command injection (defense-in-depth improvement recommended)

### Unsafe Deserialization - Comprehensive Analysis

**Serialization Formats Used:**
- JSON only: Go's `encoding/json` package (safe)
- No binary formats: No gob, protobuf, msgpack, pickle, YAML

**JSON Unmarshaling Pattern:**
- All endpoints: `json.NewDecoder(r.Body).Decode(&structType)`
- Target types: Always concrete structs, never arbitrary `interface{}`
- Custom UnmarshalJSON: Only in `/repos/inou-portal/api/llm_types.go:76` for backward compatibility

**Custom UnmarshalJSON Analysis:**
```go
func (e *ExtractionResult) UnmarshalJSON(data []byte) error {
    // Uses type alias pattern to prevent recursion
    // Only performs type assertions and re-marshaling
    // No code execution or reflection-based attacks possible
}
```

**Why Safe:**
- Go's JSON unmarshaler cannot execute code during unmarshaling
- Type system prevents instantiation of arbitrary types
- No equivalent to Python's `__reduce__` or Java's gadget chains

**Verdict:** NOT VULNERABLE - Language-level protection

## 5. Analysis Constraints and Blind Spots

### External Binary Behavior
- **Component:** `/tank/inou/bin/import-dicom` binary
- **Issue:** Source code not available for analysis
- **Risk:** Cannot verify how binary handles `targetID` argument
- **Potential Concerns:**
  - If binary uses `targetID` in file paths without validation → Path traversal
  - If binary uses `targetID` in SQL queries → SQL injection
  - If binary accepts special flags (e.g., `--config`) → Argument injection
- **Mitigation:** Authorization check limits `targetID` to dossiers with PermWrite
- **Recommendation:** Audit external binary or add strict hex format validation

### Email Header Injection (Out of Scope for Exploitation Queue)
- **Finding:** Critical email header injection vulnerability discovered in `/repos/inou-portal/portal/main.go:334`
- **Affected Functions:** `sendEmail()`, `sendCodeEmail()`, `sendEmailWithFrom()`
- **Root Cause:** Unsafe string concatenation to construct email headers without CRLF sanitization
- **Attack Vectors:**
  1. Email address field in verification codes: `To:` header injection
  2. User name field in dossier creation: `From:` header injection in share emails
  3. Subject construction from user names: Subject override
- **Impact:** BCC injection, header spoofing, phishing, account hijacking
- **Status:** Not included in injection exploitation queue (queue is for SQLi/Command/Path/SSTI/Deser only)
- **Recommendation:** Pass to separate email security testing phase or web vulnerability assessment

### Async Genome Processing
- **Component:** Genome CSV parsing triggered by `category=genetics` in file upload
- **Location:** `/repos/inou-portal/portal/genome.go`
- **Issue:** Async goroutine processing user-uploaded CSV without full input validation
- **Analysis Coverage:** Partial - CSV parsing uses `strings.Split()` but no injection sinks identified
- **Blind Spot:** Cannot rule out injection if CSV data is later used in SQL queries or shell commands
- **Mitigation:** CSV data stored as encrypted entries in database, retrieved via parameterized queries

### Rate Limiting & DoS
- **Observation:** No rate limiting observed on critical endpoints
- **Affected Endpoints:**
  - File upload: No size limits enforced in code (max 10GB configured but not validated)
  - JSON parsing: No depth limits on nested JSON structures
  - Authentication: No throttling on verification code attempts
- **Impact:** Resource exhaustion attacks possible
- **Scope:** DoS is out of scope for injection analysis but noted for completeness

### Multi-Step Workflow State
- **File Upload → Processing Flow:** Two separate endpoints with database as intermediary
- **Assumption:** Analysis assumes attacker completes both steps (upload + trigger processing)
- **Potential Issue:** If processing can be triggered by different user, impact changes
- **Analysis:** Code review shows processing checks same permissions as upload (PermWrite required)

