docs/SSH_SECURITY.md

SSH key security and connection lifecycle (current)

This supersedes the prototype protection/migration contract. Current validation and artifact provenance are in KEY_SECURITY_REVISION.md. The Material 3 / Material You theme, activities and navigation remain the base.

Discretionary local unlock

Creating or importing prepares an in-memory candidate only. Before an atomic save, choose one of:

  • Biometrics, primary and preselected when strong biometrics are available and enrolled. Uses an authentication-bound Android Keystore AES-256 GCM key with a real BiometricPrompt.CryptoObject, per-operation authorization and enrollment invalidation. API 30+ specifies AUTH_BIOMETRIC_STRONG; API 26–29 uses the per-operation validity setting. Device PIN or a preceding UI boolean is not a substitute. Cancellation/failure never saves or silently changes modes.
  • Local PIN / passphrase, recommended when biometrics are unavailable. Any nonempty matching value is accepted: no minimum length, strength mandate or repeated warning. The local secret is not stored. PBKDF2-HMAC-SHA256 (600000 iterations, random 16-byte salt) derives AES-256 GCM protection. A local PIN alone does not authenticate SSH: the private key must also be possessed/used. An extracted passphrase-protected envelope permits offline guesses; this is not hardware-backed guessing protection.
  • Skip additional unlock protection, an explicit supported choice with no extra confirmation/nag. A non-user-auth Android Keystore AES-256 GCM key wraps the identity. The copy stays in app-private no-backup storage, but connecting does not require per-use local authorization. It is not plaintext storage, an export mode or a way to persist SSH account passwords. Keystore availability failure fails the save rather than falling back to plaintext.

One current envelope (EZK2, mode PIN/passphrase, biometric or Skip) contains public key, salt, IV and authenticated ciphertext. Header/public key are AAD. The saved public key can be read without unlocking, but authentication fails if its authenticated header is changed. The private envelope is size bounded. A synced temporary file is moved atomically with no non-atomic fallback, so a failed save keeps the previous snapshot. Temporary mutable key/import/secret buffers are wiped on exit; JVM/library/IME internals are not claimed perfectly zeroizable. Only an accepted, completed candidate reaches the save operation. Backgrounding/cancelling an unfinished chooser discards its pending key.

Import, nonexportability and recovery

The GUI never reveals, copies, shares or exports a saved private key, whether plaintext or encrypted, in any mode. Copy/share controls use only the public line; there is no private-key export action. Explicit private-key paste and file picker import remain confined to the key screen; ordinary composer paste is unchanged. The current public identity and protection are primary, with explicit public-key Copy/Share labels. Import existing key is a visible deliberate secondary flow, not hidden behind key generation. Both generation and import over a saved identity require explicit Replace consent tied to the observed saved identity; stale ownership or stopping/recreation does not authorize a later overwrite. The previous identity remains until a successful, consented atomic save. Keys can come from existing phone/Termux files. Standard OpenSSH, PEM and PuTTY SSH formats are interoperability, not old app storage support. The import boundary is deliberately stricter than JSch's permissive prefix loader.

Imports accept exactly up to 65536 bytes, detect overflow with a bounded extra read, close provider streams, and fail safely on read/close/format errors. The original encrypted key passphrase is used transiently to decode; the user then chooses app-local protection separately. No source file is changed/deleted, and no persistent URI permission or source-path assumption is needed after the bytes are consumed. Cancel/failure preserves the current saved key and source.

Provider open/read runs outside the serialized credential worker, with one process-wide import slot and no provider backlog. A 30-second UI deadline or leaving the key screen abandons delivery, requests cancellation, and closes the owned stream off-main. A provider that ignores interrupt/cancel/close can still occupy that single import slot; further imports fail fast, but key generation, unlock and deletion remain independent. Cancellation/close work is bounded too. Credential jobs have lifecycle-scoped, bounded queuing: abandoned queued secrets are wiped immediately; running workers retain exclusive ownership and perform their own cleanup. Late undelivered identities/import results are disposed, not shown or reused after the screen stops.

Exactly one private identity; public data is derived

StrictKeyImport consumes the whole input, not the first parsed prefix. It rejects concatenated same/different private-key blocks, non-whitespace before/after a container, public-only input, trailing DER/SSH fields, OpenSSH key counts other than one, and extra private records hidden in a container. Ordinary blank lines around an armored key are allowed. PuTTY's length-counted sections and MAC are checked; its CBC padding is bounded and MAC-covered. OpenSSH checkints and all padding bytes are checked after decoding/decryption. PKCS#1 multi-prime RSA is explicitly unsupported rather than partially imported.

No supplied public field or JSch public getter establishes identity. RSA modulus and exponent are recomputed from validated private factors/exponent (CRT values must agree); DSA uses g^x mod p; named-curve EC uses scalar multiplication; Ed25519/Ed448 use the private seed. Redundant public fields must agree, including the OpenSSH outer blob, the inner EdDSA public field and the public half embedded beside its seed, SEC1/PKCS8 optional public fields, and PuTTY's public section. Only fresh, validated private records are passed to JSch for internal serialization: a full derived PKCS#1 record for RSA (JSch's agent loader omits CRT exponents required by its PEM writer), and canonical agent records for the other algorithms. Imported comments are discarded, not sanitized into trusted data. Public output is freshly formed from that same derived identity with the fixed one-line app comment EzAgent; fingerprint and copy read the same public blob. Generation also uses that safe fixed comment. Private serialization remains an internal pending/protection/authentication operation, never an export facility.

The implemented format paths are unencrypted OpenSSH; bcrypt-encrypted OpenSSH with AES-128/192/256 CTR/CBC or 3DES-CBC; traditional RSA/DSA/EC PEM (unencrypted or OpenSSL AES-CBC/3DES-CBC encryption); PKCS8 with supported RSA/DSA/named EC/EdDSA algorithms (unencrypted or PBES2 AES-CBC/3DES-CBC with PBKDF2 or scrypt); and PuTTY v2/v3 (unencrypted or AES-256-CBC, with v3 Argon2d/i/id). A complete single private SSH agent record is also validated. Named EC curves are nistp256/384/521. DSA is specifically the SSH ssh-dss 1024-bit p / 160-bit q profile; other DSA parameter sizes are rejected instead of emitting an unusable ssh-dss identity. Unsupported algorithms, curves, encryption schemes and out-of-bound KDF work fail explicitly; there is no fallback to trusting supplied public data or the old prefix parser. This is not a claim to accept every cipher/extension that JSch can recognize. In particular OpenSSH AEAD/Blowfish variants and old SSH2/F-Secure armor are not implemented by this strict boundary. No app storage compatibility/migration path or destructive reset is introduced.

Before every untrusted ASN.1 decoding entry point, including DER contained in PKCS8's private octet string, an iterative DER preflight enforces the 65536-byte bound, definite/minimal lengths, one complete root, at most 16 levels (including the primitive leaf), and at most 4096 nodes. No recursive BC decoding or DER re-encoding occurs before this check. Raw PBES2, PBKDF2/scrypt and all nested KDF, cipher and PRF AlgorithmIdentifiers are checked for exact cardinality and field types; BC convenience readers are not allowed to ignore extra nested identities. Opaque PKCS8 attributes are explicitly unsupported/rejected rather than accepting unknown metadata schemas capable of embedding another private identity. Optional PKCS8 public fields remain supported and cryptographically checked.

Unauthenticated import KDF parameters are bounded before invocation/allocation by ImportKdfBudget. These are conservative implementation budgets, not measured latency guarantees or a guarantee against all Android heap exhaustion:

  • Estimated KDF working memory ceiling: 32 MiB, leaving heap for the app.
  • scrypt: N <= 262144, r <= 32, p <= 16, N*r*p <= 1048576, and estimated peak 128*r*N + 256*r*p + 1024*r + 1 MiB <= 32 MiB. This includes BC's retained byte/int parallelization buffers, not just V; N=2,r=1,p=1000000 is rejected.
  • Argon2: at most 16384 KiB, 8 passes, 4 lanes, at least 8 KiB per lane, and memoryKiB*passes <= 65536. Peak estimate budgets 1152 bytes per 1-KiB block plus 1 MiB for overhead/scratch, accounting for BC block arrays/objects.
  • OpenSSH bcrypt: at most 64 rounds (derived material is at most 48 bytes).
  • Import PBKDF2: at most 1000000 total HMAC iterations across derived output blocks (so SHA1 producing 32 bytes permits at most 500000 iterations).
  • Salts are bounded to 1024 bytes; Argon2 needs at least 8 bytes, other KDFs a nonempty salt. Existing saved-envelope protection policy is unchanged.

Keys exceeding these supported budgets fail explicitly; there is no weaker KDF, public-field trust, partial parse or protection fallback.

Public-only reads of saved envelopes validate one complete, bounded public line, canonical base64, matching algorithm/blob structure and supported public fields. An ordinary final LF/CRLF is accepted; embedded controls, additional lines and trailing blob fields fail closed. A malformed saved line is reported without resetting or rewriting the snapshot. Reading a locked public header is not proof of GCM authentication; private unlock still authenticates the envelope as before.

Regression coverage is in KeyVaultTest, StrictKeyImportTest, ImportBoundaryTest and ImportInteroperabilityTest, using only synthetic keys and isolated temporary storage. New tests cover comment injection, multiple/private-only boundaries, redundant-field mismatches, encrypted/plain containers, independently verified Ed25519/RSA signatures, fingerprint/blob identity, malformed saved public output and failed/cancelled replacement/source preservation. Boundary tests include nested same/different identities inside each encryption schema, over-depth outer and private-octet-contained DER, node/length bounds, resource-limit boundary checks without running the expensive KDFs, and malicious encoded parameters rejected before derivation.

The integrated offline gate freshly passed 1,010 app, 118 library and 27 Android-JSON test executions, plus normal APK assembly and lint (0 errors, 65 warnings). It includes the correction for JSch's RSA agent-loader/PEM-writer CRT mismatch and all import/ownership regressions. No real saved keys were used or replaced. Synthetic encrypted fixtures cover OpenSSH AES-256-CTR/bcrypt, classic JSch 3DES PEM, PKCS8 AES-256-CBC/PBKDF2-HMAC-SHA256, and PuTTY v2/v3 AES-256-CBC (v3 Argon2id).

New checked-in resources in app/src/test/resources/ssh-import-fixtures/ were generated solely for this test by OpenSSH 10.5p1 / OpenSSL 3.6.4. Each expected public blob was captured before any import. RSA-2048, Ed25519 and all three NIST EC curves have plain/encrypted ssh-keygen OpenSSH fixtures. RSA and EC also have plain/encrypted traditional PEM and OpenSSL PKCS8 fixtures. OpenSSL generated standard DSA-1024/160 with plain/encrypted traditional PEM and PKCS8; its independent public SPKI was converted to the RFC4253 public blob before import. This host's ssh-keygen does not support DSA generation. The import passphrase for these test-only keys is fixture-import-secret. The tests compare exact expected blobs/fingerprints and verify serialized-private challenge signatures against those independent expected public components using BC, not JSch public getters or importer output. An additional OpenSSL PKCS8 scrypt fixture (N=16384, r=8, p=1) also passes independent RSA identity/signature and save/unlock checks within the Android resource budget. These regressions passed in the integrated gate; the fixture keys are public test data and must never be authorized on a server.

External PuTTY interoperability is not established; PuTTY coverage remains synthetic. Other implemented cipher/KDF variants and Ed448 are not independently exercised. Mutable application-owned parse/decrypt/serialization copies are wiped; BigInteger, ASN.1 and crypto-library internal copies are not claimed zeroizable.

There is no generated-key backup/export workflow. If a generated saved key is lost or cannot unlock, recovery requires enrolling a replacement using another account-access method. An imported key may instead be restored from its original backup if one exists. No backup is assumed. Device reset, lost local secret, Keystore loss or biometric enrollment changes can make a saved copy unusable. An invalidated biometric alias is deliberately not replaced during candidate preparation: doing so would destroy the old identity's wrapping key before a replacement commits. In-place biometric alias renewal is not implemented; explicitly choose local PIN/passphrase or Skip for a replacement/restored original, or use another account access method to enroll a replacement. Do not silently delete a saved key to repair a biometric alias.

No pre-release compatibility paths

There is no old app-format detection, unwrap reader, migration API/button or migration test. Unknown/unsupported/unreadable key envelopes get a bounded error; bytes remain intact until the user explicitly replaces, re-imports or deletes. The current key screen exposes those controls even when the snapshot is unreadable. No automatic conversion or deletion happens. Standard SSH import remains supported. The unrelated bootstrap single-profile preference importer was also removed: ConnectionStore reads only the current connections preferences. Old prototype preferences/files/aliases are not scanned, converted or erased by this revision. No test reset of the real Waydroid package is authorized or required.

Direct connection and secret ownership

Normal Connect goes straight to the key's selected mechanism: Skip unwraps on a worker with no dialog; PIN/passphrase opens local unlock directly; biometric starts the real CryptoObject operation. There is no generic “Authorize connection” chooser. An explicit Connect with account password connection-item menu action is available regardless of saved mode (also from local unlock). Account passwords are one-attempt, never saved, distinct from both local and import passphrases.

AttemptCredentials owns queued credentials. A synchronized claim transfers the lease exactly once to the connection worker. Cancellation wipes only an unclaimed lease. For active attempts the UI cancels/closes SshLink.Attempt transport; only the worker/SshLink may wipe its buffers, on authentication completion or exit. There is no simultaneous UI wipe of arrays JSch is consuming. Generation fences prevent queued/late results from resurrecting a cancelled/replaced connection. No retry callback captures credential buffers, only the chosen auth-kind boolean.

Host trust is exact, atomic and fail-closed for changed keys, including key-type changes. Each SSH attempt has its own TrustedHosts.Verification snapshot, not a mutable repository-wide last-presented key. Unknown-host credentials are disposed before the prompt. After independent fingerprint verification and trust, a fresh attempt uses the selected mode: new local/biometric unlock, fresh account password if explicitly chosen, or no invented authorization secret for Skip. Forgetting a changed key does not trust the replacement or retry automatically. Trust write failure does not mutate live trust. Raw transport/server errors are not exposed.

The only app transport is SSH direct-streamlocal@openssh.com to the configured Unix-domain socket. The app never opens an exec channel, runs Python, or launches a remote proxy. Forwarding failures are reported with socket-path/access and server/key-policy checks; they never trigger a second transport. Custom socket paths are supported. Container socket exposure or a dedicated external relay is an operator/deployment concern, not client behavior.

restrict,port-forwarding is a useful authorized_keys option, not server confinement: it still permits exec and account access even though this app does not use exec. Server/key policy must permit Unix-socket forwarding, and the SSH account must be able to reach the configured socket.

Lifecycle and remaining limits

The intended lifecycle is Termux-like: Android screen lock, backgrounding, Home/Back/activity recreation and task removal do not deliberately disconnect an established connection. There is no app-specific lock action. The foreground service has an ongoing notification with Disconnect. Notification/in-app Disconnect and explicit connection replacement share a process-owned graceful drain: finish native work, retire owned temporary helpers, then close transport and stop the non-restarting service. There is no outer elapsed deadline that turns slow connected cleanup into failure. Actual cleanup failures retain a sanitized incomplete-cleanup warning. SSH connection-establishment and transport liveness timeouts remain distinct from deadline-free JSONL startup, writes and RPC/owner waits; see request waiting policy. Replacement credentials are a fresh one-attempt lease, canceled/wiped if replacement is canceled; they are not retained for reconnect. Transport loss or service failure uses immediate emergency closure instead of waiting for cleanup RPCs. Notification permission/channel availability is required by the current foreground-service UX, not by SSH itself; a foreground-only fallback is not part of the chosen design.

If transport or process loss ends the connection, nothing silently reconnects or retains unlocked credentials for reuse. Reconnecting requests biometric or local PIN/passphrase unlock only when the saved key uses that protection. Skip adds no unlock prompt. SSH account-password authentication requires fresh entry. Android may still terminate the process or network connection; background persistence is not a guarantee against OS eviction. This lifecycle contract is not a claim that every screen-lock or device-specific power-management case has been tested. Secret dialog windows and the key activity retain FLAG_SECURE, mutable field clearing, disabled saved secret state/autofill, and bounded safe error categories.

Real-hardware biometric enforcement, enrollment and invalidation testing is explicitly user-deferred. Sensor-less Waydroid and JVM tests are not claimed as hardware verification. See the revision record for exact tests, GUI evidence, coverage limitations and fixture cleanup.

Attempt-scoped connection feedback

Connection UI uses explicit sanitized failure categories, not raw exception messages or string-matched repair suggestions. Feedback names the profile and stays near it until dismissed, superseded by a new attempt, or invalidated by editing/deletion. Retention is UI/process scoped, not a cross-launch error log; it contains no password, unlock secret, private key or transient trust prompt.

Available actions depend on the category: fresh explicit Retry, Edit, SSH key or Android notification settings where appropriate. Cancellation is not reported as a repairable connection failure. A changed host key remains a verification block, not a generic retry/repair path. These affordances do not silently change the selected authentication mode, preserve unlocked credentials, accept new trust, replay previous actions or bypass the foreground-service notification boundary. Secret fields name their purpose: Local PIN / passphrase, Original key passphrase or SSH account password. Secure-window, no-saved-state/autofill, ownership and wiping rules remain unchanged.