📄 03-data-handling.md
⬇ Download Raw

Data Handling, File I/O, Privacy & Encryption Audit

Audit Date: 2026-04-28 Codebase: scorpiox/clang Scope: 222 source files (124,371 LOC), excluding vendor libraries Auditor: Security Audit Agent

Executive Summary

The scorpiox codebase has a broad data handling footprint spanning configuration management, conversation persistence, multi-provider API credential handling, email services with TLS/DKIM, traffic capture, and session logging. Three critical findings were identified: (1) hardcoded API keys compiled into the WASM binary, (2) unsalted SHA-256 password hashing for email authentication, and (3) predictable temporary file paths creating symlink attack surfaces. The codebase demonstrates good practices in some areas (TLS via mbedTLS, redacted API key logging, session data isolation) but has significant gaps in credential management and temporary file security.

Overall Risk Rating: HIGH

1. Data Flow Summary

┌──────────────────────────────────────────────────────────────────────┐

│ DATA FLOW DIAGRAM │

├──────────────────────────────────────────────────────────────────────┤

│ │

│ User Input ──► sx.c (TUI) ──► Provider (API) ──► AI Response │

│ │ │ │ │ │

│ ▼ ▼ ▼ ▼ │

│ Bash exec Conversation HTTP Request Display │

│ (sx_exec) .json save (credentials) (sxui_*) │

│ │ │ │ │ │

│ ▼ ▼ ▼ ▼ │

│ /tmp files .scorpiox/ Traffic capture Session log │

│ sessions/ .scorpiox/traffics/ events.jsonl │

│ │

│ Config cascade: │

│ defaults → exe_dir/scorpiox-env.txt → ~/.claude/scorpiox-env.txt │

│ → CWD/.scorpiox/scorpiox-env.txt │

│ │

│ Email subsystem: │

│ SMTP/IMAP ──► sxmail_auth (SHA256) ──► maildir storage │

│ ──► TLS (mbedTLS) ──► DKIM (RSA-SHA256) │

└──────────────────────────────────────────────────────────────────────┘


2. File I/O Inventory

2.1 Configuration Files

File PathOperationModulePurposeSensitivity
exe_dir/scorpiox-env.txtReadsx_config.cGlobal configurationHIGH — contains API keys, SSH passwords
~/.claude/scorpiox-env.txtReadsx_config.cUser-level config overrideHIGH — contains API keys
.scorpiox/scorpiox-env.txtRead/Writesx_config.cProject-level configHIGH — contains API keys
accounts.txt (email)Readsxmail_auth.cUser:hash credential pairsHIGH — password hashes
filter.txt (email)Readsxmail_filter.cEmail routing rulesLOW

2.2 Session & Conversation Storage

File PathOperationModulePurposeSensitivity
.scorpiox/sessions//conversation.jsonRead/Writesx_conversation.cFull conversation historyHIGH — user messages, tool inputs/outputs
.scorpiox/sessions//session.logAppendsx_log.cDebug/info/error logMEDIUM — may contain keys at DEBUG level
.scorpiox/sessions//events.jsonlAppendsx_session.cStructured event streamMEDIUM
.scorpiox/sessions//trace.jsonlAppendsx_trace.cData flow trace with tool inputsHIGH — tool_input includes bash commands
.scorpiox/sessions//config-snapshot.txtWritesx_session.cFrozen config at session startHIGH — full config dump
.scorpiox/sessions//meta.jsonWritesx_session.cSession metadata & summaryLOW
.scorpiox/sessions//traffic/Writescorpiox-traffic.cMITM traffic captureCRITICAL — full HTTP request/response bodies
.scorpiox/conversations/.jsonRead/Writesx_conversation.cLegacy conversation formatHIGH

2.3 Temporary Files

File PathOperationModulePurposeSecurity
/tmp/sxmux/sxmux-.sockCreatesxmux_session.cUnix domain socketDir created with 0700 ✓
/tmp/sxmux/sxmux-.pidRead/Writesxmux_session.cSession PID trackingPredictable name ⚠
/tmp/sx_emit__.txtWritesx.cEvent emission temp filePredictable name ⚠
/tmp/sx_voice.wavWritescorpiox-voice.cVoice recordingFixed path — race condition
/tmp/sx_voice_result.txtRead/Writescorpiox-voice.cVoice transcription resultFixed path — race condition
/tmp/sx_voice_.oggWritescorpiox-whatsapp.cWhatsApp voice msgPredictable (timestamp) ⚠
/tmp/sx_post__.txtWritescorpiox-server.cHTTP POST body tempPredictable ⚠
/tmp/sx_mcp_.jsonWritesx_mcp.cMCP config tempPredictable ⚠
/tmp/sx_slirp_.sockCreatescorpiox-unshare.cSlirp4netns socketPredictable ⚠
/tmp/sx_builtin_.shWritesx_slashcmd.cBuilt-in command scriptPredictable ⚠
/tmp/vault-XXXXXXCreatescorpiox-vault-git.cBackup temp dirUses mkdtemp()
/sx-edit-.txtWritesx.cEditor temp fileUses TMPDIR, PID-based

2.4 Email Subsystem Files

File PathOperationModulePurposeSensitivity
Maildir tmp/ subdirectoryWrite→Renamesxmail_maildir.cAtomic mail deliveryContains email content
Maildir new/ subdirectoryRead/Renamesxmail_maildir.cNew message storageContains email content
Maildir cur/ subdirectoryReadsxmail_maildir.cRead message storageContains email content
~/.scorpiox/server-email.logAppendscorpiox-server-email.cEmail server logMEDIUM
TLS cert fileReadsxmail_tls.cServer certificateHIGH
TLS key fileReadsxmail_tls.cPrivate keyCRITICAL
DKIM key fileReadsxmail_dkim.cDKIM signing keyCRITICAL

2.5 Logging Destinations

File PathOperationModulePurpose
.scorpiox/logs/scorpiox-tmux.logAppendscorpiox-tmux.cTmux manager log
.scorpiox/traffics//proxy.logWritescorpiox-traffic.cMITM proxy log
.scorpiox/traffics//traffic.logWritescorpiox-traffic.cTraffic capture log
/var/log/scorpiox-dns/Writescorpiox-dns.cDNS audit log

3. PII Assessment

3.1 PII Data Handled

PII TypeLocationContextRisk
Email addressessxmail_smtp.c, sxmail_imap.cSMTP MAIL FROM/RCPT TO, IMAP mailboxStored in mail queue, logged in server
Email contentsxmail_maildir.c, sxmail_queue.cFull message bodiesStored on disk in plaintext
User credentialssxmail_auth.cUsername + SHA256 hashStored in accounts file
Conversation contentsx_conversation.cAll user messages and AI responsesStored in JSON on disk
Bash command outputsx_conversation.c, sx_trace.cTool results stored as conversation messagesMay contain arbitrary file contents, env vars
JWT claimsscorpiox-server.cuser_id, email from JWTLogged at INFO level
Usernamescorpiox-usage.c, scorpiox-unshare.cUSER, USERNAME env varsUsed for container setup

3.2 PII Logging Risks


4. Credential Management

4.1 Credential Types & Storage

CredentialStorage MethodRisk Level
ANTHROPIC_API_KEYConfig file (scorpiox-env.txt) / env varMEDIUM — plaintext in file
ANTHROPIC_ANTIGRAVITY_KEYHardcoded in sx_config_embedded.cCRITICALsk-6088a10dc3c1473cac567069b0e557f6
ANTHROPIC_ZAI_KEYHardcoded in sx_config_embedded.cCRITICAL9c6fba5db3f84613aaf8700b05990835.ue19jY48d9GmddqX
GEMINI_API_KEYHardcoded in sx_config_embedded.cCRITICALAIzaSyDsvlLnCdMFXnlCLxurMaAO5RKI8IQHVA8
OPENAI_API_KEYConfig file / env varMEDIUM — plaintext in file
CLAUDE_CODE_SSH_PASSHardcoded in sx_config_embedded.cCRITICALxboxone
CODEX_SSH_PASSConfig fileMEDIUM — plaintext in file
SMTP_PASSConfig fileMEDIUM — plaintext in file
SERVER_JWT_SECRETConfig file / env varHIGH — HMAC signing key
HTTP_RELAY_KEYConfig file / env varMEDIUM
TCP_API_KEYConfig fileMEDIUM
TLS private keyFile on disk (path in config)HIGH — must be file-permission protected
DKIM private keyFile on disk (path in config)HIGH — must be file-permission protected
Git PAT tokensInjected into URLs at runtimeHIGH — appear in https://PAT@host/ URLs

4.2 Critical Finding: Hardcoded Secrets in WASM Binary

File: libsxutil/sx_config_embedded.c (auto-generated, compiled into WASM)
{"ANTHROPIC_ANTIGRAVITY_KEY", "sk-6088a10dc3c1473cac567069b0e557f6"},

{"ANTHROPIC_ZAI_KEY", "9c6fba5db3f84613aaf8700b05990835.ue19jY48d9GmddqX"},

{"GEMINI_API_KEY", "AIzaSyDsvlLnCdMFXnlCLxurMaAO5RKI8IQHVA8"},

{"CLAUDE_CODE_SSH_PASS", "xboxone"},

These secrets are baked into the compiled binary and can be trivially extracted. The WASM binary is distributed to end users, making this a secret exposure vulnerability.

4.3 Credential Logging Practices

Good: API keys are redacted in log output: Bad:

4.4 Credential Flow

scorpiox-env.txt ──► sx_config_init() ──► in-memory g_cfg struct

│ │

▼ ▼

Environment vars ──► getenv() ──────────► Provider data->api_key[256]

setenv() before exec

(child process inherits)

HTTP headers:

"x-api-key: <key>"

"Authorization: Bearer <key>"


5. Encryption Usage

5.1 Cryptographic Operations

AlgorithmLibraryModulePurposeAssessment
TLS 1.2/1.3mbedTLSsxmail_tls.cEmail transport encryption✓ Proper implementation
RSA-SHA256mbedTLSsxmail_dkim.cDKIM email signing✓ RFC 6376 compliant
SHA-256mbedTLSsxmail_auth.cPassword hashing⚠ UNSALTED — weak
HMAC-SHA256Custom (scorpiox-server.c)JWT verification✓ Standard JWT validation
SHA-256Custom (scorpiox-server.c:149)JWT HMAC component✓ RFC 6234
CTR-DRBGmbedTLSsxmail_tls.c, sxmail_dkim.cCryptographic RNG✓ Proper seeding from entropy
Base64mbedTLS + customsxmail_dkim.c, sxmail_auth.cEncoding (not encryption)N/A

5.2 Critical Finding: Unsalted SHA-256 Password Hashing

File: sxmail_auth.c:121-130
int sxmail_auth_hash_password(const char pass, char out, size_t out_sz) {

if (!pass || !out || out_sz < 65) return -1;

unsigned char digest[32];

mbedtls_sha256((const unsigned char *)pass, strlen(pass), digest, 0);

for (int i = 0; i < 32; i++)

snprintf(out + i * 2, 3, "%02x", digest[i]);

out[64] = '\0';

return 0;

}

Issues:
  • No salt — identical passwords produce identical hashes, enabling rainbow table attacks
  • No iteration/stretching — single SHA-256 pass, trivially brute-forced (~billions/sec on GPU)
  • Should use bcrypt, scrypt, or Argon2id with per-user salt and adequate work factor
  • 5.3 TLS Configuration

    The TLS implementation in sxmail_tls.c uses mbedTLS correctly:

    5.4 Data at Rest Encryption

    No data at rest encryption is implemented. All persistent data is stored in plaintext:

    6. Temporary File Security

    6.1 Findings

    PatternCountSecurity
    mkdtemp()1 (scorpiox-vault-git.c)✓ Secure
    mkstemp()0— Not used anywhere
    Predictable /tmp/sx_* paths8+ locations⚠ Insecure
    Fixed /tmp/sx_voice.wav1⚠ Race condition / symlink attack

    6.2 Specific Vulnerabilities

    Symlink attack vectors: Positive:

    6.3 Temp File Cleanup


    7. Logging Analysis

    7.1 Logging Infrastructure

    7.2 Sensitive Data in Logs

    RiskLocationDetail
    HIGHscorpiox-agent.c:817SX_INFO(" [VAR] %s=%s", key, value) — logs ALL env vars unfiltered
    HIGHsx_config.c:640SX_INFO("config: wrote %s=%s ...") — logs config writes including API keys
    MEDIUMsx_provider_openai.c:426SX_DEBUG("openai: found OPENAI_API_KEY len=%zu", strlen(v)) — leaks key length
    MEDIUMsx_session.c config-snapshotFull config dump at session start may include secrets
    LOWsx_provider_.cAPI key presence logged as or (set) — properly redacted
    LOW**sxmail_dkim.c:324Logs key file path (not key contents)

    7.3 Log File Locations

    LogPathContains
    Session log.scorpiox/sessions//session.logAll SX_LOG output for session
    Events log.scorpiox/sessions//events.jsonlStructured events
    Trace log.scorpiox/sessions//trace.jsonlTool inputs, data flow
    Email log~/.scorpiox/server-email.logSMTP/IMAP operations
    Tmux log.scorpiox/logs/scorpiox-tmux.logSession manager operations
    Traffic log.scorpiox/traffics//traffic.logFull HTTP capture
    DNS audit/var/log/scorpiox-dns/DNS query log

    8. Data Retention

    8.1 Persistence Model

    Data TypeLocationRetentionEncryption
    Conversations.scorpiox/sessions//conversation.jsonIndefiniteNone
    Session logs.scorpiox/sessions//session.logIndefiniteNone
    Traffic captures.scorpiox/traffics//Until --clearNone
    Email messagesMaildir hierarchyIndefiniteNone
    Config snapshots.scorpiox/sessions//config-snapshot.txtIndefiniteNone
    DNS audit logs/var/log/scorpiox-dns/IndefiniteNone

    8.2 Observations


    9. Environment Variable Usage

    9.1 Sensitive Environment Variables (133 getenv() calls)

    VariableModuleSensitivityPurpose
    OPENAI_API_KEYsx_provider_openai.cHIGHOpenAI API authentication
    GEMINI_API_KEYsx_provider_gemini.cHIGHGoogle Gemini API authentication
    AGENTS_PATscorpiox-agent.cHIGHGit Personal Access Token
    SCORPIOX_HOMEMultipleMEDIUMInstallation directory
    HOME / USERPROFILEMultiple (19 calls)LOWUser home directory
    EDITOR / VISUALsx.cLOWText editor preference
    SHELLsxmux_pane.c, sx_pty.cLOWDefault shell
    USER / USERNAMEscorpiox-usage.cLOWCurrent username
    CURL_CA_BUNDLEsx_platform.cLOWCA certificate path
    TZsx_systemprompt.cLOWTimezone
    TERMscorpiox-unshare.cLOWTerminal type
    PATHsx_platform.c, scorpiox-unshare.cLOWExecutable search path
    IMAGE_BASE_URLscorpiox-wsl.c, scorpiox-unshare.cLOWContainer image source
    SXMUX_INIT_CMDsxmux_pane.cLOWInitial mux command

    9.2 Environment Variable Injection


    10. Risk Assessment

    10.1 Critical Risks

    #RiskSeverityLocationRecommendation
    C1Hardcoded API keys in WASM binaryCRITICALsx_config_embedded.cRemove all secrets from compiled code; use runtime-only config or secure vault
    C2Hardcoded SSH password in WASM binaryCRITICALsx_config_embedded.c"xboxone" — rotate immediately, remove from source
    C3Unsalted SHA-256 password hashingCRITICALsxmail_auth.c:121Migrate to Argon2id or bcrypt with per-user salt

    10.2 High Risks

    #RiskSeverityLocationRecommendation
    H1Plaintext API keys in config filesHIGHsx_config.c, scorpiox-env.txtEncrypt sensitive config values or use OS keychain
    H2Unfiltered env var loggingHIGHscorpiox-agent.c:817Filter sensitive keys (API_KEY, PASS, SECRET, TOKEN) from log output
    H3Config snapshot may contain secretsHIGHsx_session.cRedact sensitive keys in config-snapshot.txt
    H4Traffic capture stores full HTTP bodiesHIGHscorpiox-traffic.cWarn users; auto-redact Authorization headers
    H5No data-at-rest encryptionHIGHAll persistenceEncrypt conversation.json, session logs, and config at rest
    H6Conversation stores all tool outputsHIGHsx_conversation.cConsider content filtering/redaction for sensitive outputs

    10.3 Medium Risks

    #RiskSeverityLocationRecommendation
    M1Predictable temp file pathsMEDIUM8+ locationsUse mkstemp()/mkdtemp() instead of predictable names
    M2Fixed temp file paths (voice)MEDIUMscorpiox-voice.cRace condition / symlink attack — use mkstemp()
    M3Git PAT in URL visible to psMEDIUMscorpiox-agent.c, scorpiox-server.cUse credential helper or git-credential-store
    M4No session retention enforcementMEDIUMsx_session.cImplement automatic cleanup per SESSION_RETENTION_DAYS
    M5Config value logged on writeMEDIUMsx_config.c:640Redact values for keys matching sensitive patterns
    M6Builtin script written to predictable /tmp pathMEDIUMsx_slashcmd.c:567/tmp/sx_builtin_.sh could be pre-planted — use mkstemp()

    10.4 Low Risks

    #RiskSeverityLocationRecommendation
    L1Debug log reveals API key lengthLOWsx_provider_openai.c:426Minor info leak; consider removing
    L2Email log in fallback /tmp pathLOWscorpiox-server-email.c:486Falls back to /tmp if HOME unset
    L3JWT claims logged at INFOLOWscorpiox-server.c:502user_id/email in logs — acceptable for audit

    11. Recommendations Summary

    Immediate Actions (Critical)

  • Rotate all hardcoded credentials in sx_config_embedded.c — they are compromised
  • Remove secrets from compiled binaries — use runtime configuration or encrypted config vault
  • Replace SHA-256 password hashing with Argon2id (preferred) or bcrypt with salt
  • Short-term Actions (High)

  • Add sensitive-key filtering to all log output (match patterns: KEY, PASS, SECRET, TOKEN)
  • Redact sensitive values in config-snapshot.txt
  • Implement data-at-rest encryption for conversation and session data
  • Medium-term Actions

  • Replace all predictable /tmp/sx_* paths with mkstemp()/mkdtemp()
  • Implement automatic session data cleanup per SESSION_RETENTION_DAYS
  • Add content filtering/redaction for tool outputs in conversation storage
  • Use OS keychain (macOS Keychain, Linux Secret Service) for API key storage

  • Report generated by Security Audit Agent — 2026-04-28