Skip to content

fix: harden auth, SSH, plugin, Electron, database, and Docker security - #1998

Open
ZacharyZcR wants to merge 1 commit into
Termix-SSH:dev-26.11.4from
ZacharyZcR:fix/security-and-stability-hardening
Open

ZacharyZcR wants to merge 1 commit into
Termix-SSH:dev-26.11.4from
ZacharyZcR:fix/security-and-stability-hardening

Conversation

@ZacharyZcR

Copy link
Copy Markdown
Member

Summary

This PR addresses a set of security, concurrency, and stability issues across authentication, SSH/credentials, plugin runtime/SDK, Electron/frontend, database repositories, and Docker/build scripts.

Authentication & Access Control

  • Prevent 2FA temp_token replay & policy bypass (src/backend/auth/login-pipeline.ts): Reject readPendingLogin() when no matching in-memory pending login exists instead of falling back to pending: null, and atomically consume pending logins upon verification.
  • Bind step-up state to session & clear on logout (src/backend/auth/step-up.ts, src/backend/database/routes/step-up-routes.ts, src/backend/utils/auth-manager.ts): Scope step-up verification to sessionId with TTL cleanup, clear on logoutUser(), normalize auth paths (session-access.ts, auth-manager.ts) to prevent case/encoding bypasses, touch sessions in createAdminMiddleware(), and propagate sessionRepository.create() errors in generateJWTToken().
  • Prevent open redirect via X-Forwarded-Prefix (src/backend/utils/request-origin.ts): Reject protocol-relative (//...) and backslash-containing base paths in normalizeBasePath().
  • Fix IPv6 bracket stripping in SSRF DNS hook (src/backend/utils/safe-outbound-fetch.ts): Fix unescaped character class /^[|]$/g to /^\[|\]$/g.
  • Guard audit-log pagination against NaN (src/backend/database/routes/audit-log-routes.ts).

SSH, Credentials & Operations

  • Encrypt & strip socks5ProxyChain passwords end-to-end (src/backend/utils/field-crypto.ts, src/backend/utils/lazy-field-encryption.ts, src/backend/database/routes/host-normalizers.ts, src/backend/hosts/import/host-export.ts, src/backend/hosts/credential-storage.ts): Encrypt proxy chain field at rest, strip nested passwords from API responses, shared exports, and credential-storage-disabled writes.
  • Prevent cross-user/cross-route SSH connection pool collisions (src/backend/hosts/connect/connect-host.ts): Key connections by acting user plus socks5ProxyChain, jumpHosts, authType, and credentialId, and clean up timer/jump client on synchronous connect() errors.
  • Fix SSH relay & jump-host resource leaks and races (src/backend/hosts/ssh-relay.ts, src/backend/hosts/jump-host-chain.ts, src/backend/hosts/host-key-verifier.ts): Fix MAX_RELAYS_PER_USER TOCTOU and disconnect-before-connect socket/jumpClient leak; destroy unbound proxySocket and late forwardOut streams; handle WebSocket close and DB errors cleanly in host-key verification.
  • Verify ownership before deleting host access (src/backend/database/repositories/host-repository.ts): Check findByIdForUser() before calling deleteAccessForHost().
  • Harden operations gate & resource cache (src/backend/operations/gate.ts, src/backend/operations/resources.ts): Check API key scopes against effectiveRisk, enforce admin/registration checks in decideOperationApproval(), redact undoInput, include serialized input in resource cache keys, and align default hostAccess with gate.ts.
  • Fix encryption init validation & export cleanup (src/backend/database/database.ts): Use real validateJWTSecret() instead of hardcoded true, and ensure temporary export SQLite files are removed if opening/initializing fails.

Plugin Runtime & SDK

  • Enforce DB capability grant for ctx.asUser (src/backend/plugins/ctx.ts): Require assertCapability(..., "users:impersonate") instead of manifest-only check.
  • Harden plugin SQL migration DDL validator (packages/plugin-sdk/src/ddl.ts): Check refused functions and setval across all DML statements (INSERT/REPLACE/UPDATE/DELETE, not only SELECT), and unwrap quoted identifiers so "pg_read_file"(...) cannot bypass checks.
  • Harden plugin process, audit & desktop-local helpers (src/backend/plugins/ctx-process.ts, ctx-audit.ts, ctx-desktop-local.ts): Block ./.. binary names, enforce download size limit and cancel redirected response bodies, guard async audit subscriptions against disposal race, and block #/encoded traversal in pluginFetch.

Electron & Frontend

  • Fix path traversal in create-temp-folder IPC (electron/main.cjs): Reject ./.. path segments and verify resolved target paths stay within the temp folder.
  • Fix isPrivateNetworkHost false positives on fc*/fd* domains (electron/main.cjs): Strip IPv6 brackets and require : before matching fc/fd ULA prefixes.
  • Prevent PID-reuse process kills on startup (electron/backend-process.cjs, electron/main.cjs): Verify the recorded PID belongs to a Termix backend process before killing it.
  • Bind external-login callback to 127.0.0.1 & case-insensitive SameSite header check (electron/main.cjs).
  • Validate external plugin URLs (http:/https: only) (src/ui/plugins/plugin-model.ts, PluginDetail.tsx, PluginReleaseNotes.tsx).
  • Clear cached currentUser on logout & clean up drag listeners (src/ui/plugin-host/bridge.ts, loader.ts, src/ui/shell/controller/use-regions.ts, CompanionFrame.tsx, CardGridCanvas.tsx).

Database, Docker & Build Scripts

  • Fix first-user admin race & NULL-scope duplicate settings (src/backend/database/repositories/user-repository.ts, plugin-settings-repository.ts): Add .limit(1) and PG/MySQL locking in createCheckingIfFirst(), and wrap PluginSettingsRepository.set() in a transaction with lock/deduplication for scope_id IS NULL.
  • Fix folder LIKE escaping, Unicode SUBSTR, and transactions (src/backend/database/repositories/host-folder-repository.ts, folder-access-repository.ts).
  • Close remote DB pools on shutdown & guard SQLite table rebuilds (src/backend/database/db/connect.ts, index.ts, src/backend/starter.ts): Close PG/MySQL pools on shutdown and wrap table rebuilds in transactions that restore PRAGMA foreign_keys = ON in finally.
  • Harden Docker image & entrypoint (docker/Dockerfile, docker/entrypoint.sh): Build only frontend assets into /app/html (no longer exposing dist/backend or dist/plugins via Nginx), apply patch-ssh2-sk.cjs in Docker builds, remove redundant npm rebuild bcryptjs, include Nginx in HEALTHCHECK, parse DATA_DIR/.env safely without source, and respect SSL_CERT_PATH/SSL_KEY_PATH.
  • Fail loudly on mismatched postinstall patches & align V8 macro (scripts/patch-app-builder-lib.cjs, patch-better-sqlite3.cjs, patch-nan.cjs, patch-node-pty.cjs).

Verification

  • npm run type-check: passed
  • npm run lint: passed (0 errors)
  • npm run test: verified across backend, frontend, and scripts test suites (including added regression tests in data.test.ts, capabilities.test.ts, actor.test.ts, and ssh-relay.test.ts)

@termix-triage-bot

Copy link
Copy Markdown

AI review | Looks safe to merge

This PR hardens authentication, SSH connections, plugin runtime, Electron IPC, database operations, and Docker builds against multiple security and stability issues. It fixes real vulnerabilities including 2FA token replay, path traversal, PID reuse attacks, SSRF bypasses, and connection pool collisions, while addressing concurrency races and resource leaks without introducing any malicious code or rule violations.

Reviewed 475b193. AI can be wrong, a maintainer still decides. Comment /termix review to run it again.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Open PRs

Development

Successfully merging this pull request may close these issues.

1 participant