ВиртМашУправ ВиртМашУправVPS Manager
Home / Security

Security

Six layers of defense — from the network perimeter to observability. SSH passwords never leave the device in plaintext at any stage.

1

Defense in Depth — Six Layers

Layer 1 — Network
  • CORS whitelist (http://localhost:3000)
  • Request body limit — 1 MB for REST
  • WebSocket frame limit — 20 MB
Layer 2 — Authentication
  • JWT with a short TTL (60 min access)
  • Refresh token rotation (7 days)
  • JWT for WebSocket via Sec-WebSocket-Protocol (not in the query string)
  • HMAC-SHA256 verification of the VM callback
Layer 3 — Authorization
  • @Auth() guard on all routes except /auth/*
  • Resource-ownership check (userId === resource.userId)
Layer 4 — Credential Security
  • AES-256-GCM encryption on the client (the server is zero-knowledge)
  • Argon2id for key derivation from the vault PIN (resistant to brute force)
  • credentialSalt is shared across all devices, set once at registration
  • Ephemeral SSH tokens — 60s TTL, single-use, HMAC-signed
  • Rate limit — 60 tokens/min per VPS per user
Layer 5 — Command Execution
  • Shell-injection protection (parameter-name whitelist + value escaping)
  • Path-traversal protection in the working directory
  • SSRF protection when downloading scripts by URL
  • Serial SSH command queue (protects against races and Windows OpenSSH crashes)
Layer 6 — Observability
  • SSH_EXEC_DEBUG=false — credentials never end up in logs
  • Swagger disabled in production
  • 5xx errors are masked before being sent to the client
2

On-Device Credential Encryption

flowchart LR
    PIN["Password / PIN"] --> KDF["Argon2id (credentialSalt)"]
    KDF --> KEY["authKey (32 bytes)"]
    CREDS["sshUser + sshPassword"] --> ENC["AES-256-GCM"]
    KEY --> ENC
    ENC --> BLOB["{ iv, ciphertext, tag }"]
    BLOB --> SRV[("Server: stores only ciphertext")]

Argon2id + AES-256-GCM — the server stores only ciphertext

flowchart TB
    P["userPassword / PIN"] --> ARGON["Argon2id
memory=65536 KB, time=3, hashLen=32"]
    SALT["credentialSalt (32 bytes)"] --> ARGON
    ARGON --> KEY["authKey (32 bytes)"]
    IV["iv = randomBytes(12)"] --> ENC["AES-256-GCM"]
    KEY --> ENC
    CREDS["{ sshUser, sshPassword }"] --> ENC
    ENC --> OUT["{ iv, ciphertext, tag }"]

Key derivation parameters and the encrypted blob format

flowchart TB
    REG["Registration / OAuth"] --> GEN["Server generates credentialSalt once (32 bytes)"]
    GEN --> STORE[("Stored in User.credentialSalt, never rotated")]

    MD["Second device"] --> KNOWS["Knows the vault PIN + fetches credentialSalt from the server (GET /profile)"]
    KNOWS --> DERIVE["authKey = Argon2id(PIN, credentialSalt)"]
    DERIVE --> UNLOCK["Unlocks all credentials without exchanging secrets between devices"]

    UNLOCK -.-> NOTE["authKey depends on the vault PIN, not the account password —<br/>an account password change (PATCH /profile/password) does not affect credential encryption"]

    classDef note fill:#fdf6df,stroke:#151718,color:#151718
    class NOTE note

credentialSalt is set once at registration and is never rotated

3

The Ephemeral SSH Token Protocol

sequenceDiagram
    participant C as Client
    participant S as Backend
    participant R as Valkey

    Note over C,S: Session setup (once per app launch)
    C->>S: POST /vps/ssh-session { authKeyB64 }
    S->>R: SETEX ssh-session:{userId} authKey (8h)
    S-->>C: sessionId

    Note over C,S: Getting a token (per operation)
    C->>C: opKey = HKDF(authKey, nonce)
    C->>C: ciphertext = AES-GCM(opKey, creds)
    C->>S: POST /vps/:id/ssh-token { nonceB64, ciphertextB64, tagB64, timestamp, action }
    S->>R: fetch authKey for the session
    S->>S: HKDF → opKey → decrypt creds
    S->>R: SET ssh-token:{id} creds (TTL 60s)
    S-->>C: { tokenId, expiresAt }

    Note over C,S: Consuming the token (headers x-ssh-token, x-ssh-token-ts, x-ssh-sig)
    C->>S: POST /sftp/list { tokenId, tokenTs, tokenSig }
    S->>R: GETDEL ssh-token:{id}
    S->>S: SSH command, then wipe creds from memory

HKDF-derived operation key + HMAC signature, 60-second TTL, single use

flowchart LR
    T["Token created (TTL 60s)"] --> U{"Used within the TTL?"}
    U -- "yes" --> C["GETDEL from Valkey → single use"]
    U -- "TTL expired" --> E["TOKEN_NOT_FOUND"]
    RL["60 requests / user / VM / 60s"] --> LIMIT["Exceeded → 400 Bad Request (no errorCode)"]

Single use and rate limiting

4

Vault State

stateDiagram-v2
    [*] --> Locked: app launch
    Locked --> Biometrics: hasSecureKey == true
    Locked --> PinEntry: hasSecureKey == false
    Biometrics --> Unlocked: success
    Biometrics --> PinEntry: unavailable
    PinEntry --> Unlocked: Argon2id(pin) + auth-tag check
    PinEntry --> Locked: wrong PIN
    Unlocked --> Locked: app backgrounded (30s)
    Unlocked --> [*]: logout

State transitions: lock, biometrics, PIN, logout

5

Sign-In via MAX Bot

sequenceDiagram
    participant U as User
    participant App as App
    participant S as Backend
    participant Bot as MAX Bot

    App->>App: generate a 6-digit code (sessionId)
    App->>Bot: deep link .../bot?start=sessionId
    App->>U: show the code in an overlay (with a "copy" button)
    Note over U,Bot: if the redirect to MAX didn't fire automatically
    U->>Bot: sends the code manually in chat
    Bot->>S: /start <sessionId>
    S->>S: store tokens in Valkey (TTL 60s)
    loop poll every 3s (up to 60s)
        App->>S: GET /auth/max/poll/:sessionId
        S-->>App: 202 (waiting)
    end
    S-->>App: 200 { accessToken, refreshToken }

Deep link into MAX + code as a fallback, long polling — no password on the client side

6

Injection and SSRF Protection

flowchart TB
    URL["scriptUrl"] --> CHECK{"IP in a blocked range?"}
    CHECK -- "127.*, 0.0.0.0, localhost" --> BLOCK["Rejected"]
    CHECK -- "10.*, 172.16-31.*, 192.168.* (RFC1918)" --> BLOCK
    CHECK -- "169.254.* (cloud metadata)" --> BLOCK
    CHECK -- "100.64.* (shared address space)" --> BLOCK
    CHECK -- "::1, fc00::, fd* (IPv6 private)" --> BLOCK
    CHECK -- "public address" --> ALLOW["Download allowed"]

Blocked ranges when downloading scripts by URL

flowchart TB
    NAME["Parameter name"] --> RX{"matches the whitelist pattern?"}
    RX -- "no" --> REJECT["Rejected"]
    RX -- "yes" --> OK1["Allowed"]

    DIR["Working directory"] --> ABS{"matches the whitelist character pattern?"}
    ABS -- "no" --> REJECT
    ABS -- "yes" --> OK2["Allowed"]

    VAL["Parameter value"] --> BASH["shellQuoteSh(): single quotes + escaping"]
    VAL --> PS["shellQuotePs(): single quotes, doubling embedded '"]

Parameter validation and value escaping in commands

7

VM Callback HMAC Verification

flowchart LR
    VM["VM (installer)"] --> CB["PATCH /vps/installed?vpsName=...&installed=... + headers x-vm-ts, x-vm-signature"]
    CB --> CALC["expected = HMAC-SHA256(VM_CALLBACK_SECRET, 'event:vpsName:flag:timestamp')"]
    CALC --> CMP{"signature == expected and
drift within tolerance?"}
    CMP -- "yes" --> ACCEPT["status = RUNNING"]
    CMP -- "no" --> REJECT["Rejected"]

Signature verification and allowed clock drift

8

SSH Host-Key Verification

flowchart LR
    CONN["SSH connection"] --> STRICT{"SSH_STRICT_HOST_KEY?"}
    STRICT -- "true" --> FP{"fingerprint in the allowlist?"}
    FP -- "yes" --> ALLOW["Connection allowed"]
    FP -- "no" --> DENY["Connection rejected"]
    STRICT -- "false (dev only)" --> WARN["Log a warning, allow the connection"]

Host-key pinning by SHA256 fingerprint

9

Error Handling

All exceptions are normalized by the global filter into a single format { statusCode, timestamp, path, message, error, errorCode }. 5xx responses are masked with generic text — the full error is logged only on the server.

errorCodeMeaningClient Action
sudoA sudo password is requiredShow the sudo-password prompt
SUDO_PASSWORD_REQUIREDSame as aboveShow the prompt
SUDO_PASSWORD_INVALIDIncorrect sudo passwordPrompt again
expired_sessionThe refresh token has expiredForce logout
TOKEN_NOT_FOUNDToken already used or expiredRetry the operation