diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..0a9c8cb --- /dev/null +++ b/.dockerignore @@ -0,0 +1,19 @@ +# Keep the Docker build context to what the package build needs. +# Never send credentials, identities, local notes or build output. +.git +.github +.claude +dist/ +.deb-staging/ +ziti-ssh +ziti-scp +ziti-ssh-ca +ziti-ssh-host +*.jwt +*.json +*.pem +*.key +*.log +SECURITY_FINDINGS.md +ziti-ssh-security-review.md +suites/ diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d8b446e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,22 @@ +version: 2 +updates: + - package-ecosystem: gomod + directory: / + schedule: + interval: weekly + groups: + go-minor-patch: + update-types: [minor, patch] + + - package-ecosystem: docker + directory: /scripts + schedule: + interval: weekly + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + actions-minor-patch: + update-types: [minor, patch] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d9a9afb..a5d3d3a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,8 +6,8 @@ on: push: branches: [main] -env: - FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true +permissions: + contents: read jobs: test: @@ -15,9 +15,9 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@v5 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod cache: true @@ -31,5 +31,15 @@ jobs: - name: Build run: go build ./... + # Scan with the Go toolchain that builds release binaries (go.mod's + # toolchain directive, installed by setup-go above). govulncheck-action + # is not used: its bundled setup-go reads only the go directive (1.26.0) + # or defaults to "stable", so it never scanned the release toolchain. + # The pinned version is verified against the Go checksum database; + # bump it by hand (Dependabot does not track go run versions). - name: Vulnerability scan - uses: golang/govulncheck-action@v1 + env: + GOVULNCHECK_VERSION: v1.9.0 + run: | + go version + go run "golang.org/x/vuln/cmd/govulncheck@${GOVULNCHECK_VERSION}" ./... diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 2da6208..a857bb8 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -8,8 +8,8 @@ on: env: NF_DEB_TEST_REPO: ${{ vars.NF_DEB_TEST_REPO || 'nfpax-netfoundry-deb-test' }} NF_RPM_TEST_REPO: ${{ vars.NF_RPM_TEST_REPO || 'nfpax-netfoundry-rpm-test' }} - JFROG_CLI_VERSION: ${{ vars.JFROG_CLI_VERSION || '2.78.2' }} - NFPM_VERSION: ${{ vars.NFPM_VERSION || '2.38.0' }} + JFROG_CLI_VERSION: ${{ vars.JFROG_CLI_VERSION || '2.133.0' }} + NFPM_VERSION: ${{ vars.NFPM_VERSION || '2.49.0' }} jobs: build_and_publish: @@ -18,23 +18,30 @@ jobs: permissions: contents: write id-token: write + attestations: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@v5 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod cache: true - name: Install nfpm run: | - curl -sfL \ - "https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_Linux_x86_64.tar.gz" \ - | tar -xz -C /usr/local/bin nfpm + set -euo pipefail + tarball="nfpm_${NFPM_VERSION}_Linux_x86_64.tar.gz" + base="https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}" + tmp="$(mktemp -d)" + curl -sfL -o "${tmp}/${tarball}" "${base}/${tarball}" + curl -sfL -o "${tmp}/checksums.txt" "${base}/checksums.txt" + (cd "${tmp}" && grep " ${tarball}\$" checksums.txt | sha256sum -c -) + tar -xzf "${tmp}/${tarball}" -C /usr/local/bin nfpm + nfpm --version - name: Configure jFrog CLI - uses: jfrog/setup-jfrog-cli@v4 + uses: jfrog/setup-jfrog-cli@4c2f06da03095113100534a16d58d8a252680949 # v5.3.5 with: version: ${{ env.JFROG_CLI_VERSION }} oidc-provider-name: nf-github-actions-setup-jfrog-cli @@ -45,6 +52,20 @@ jobs: run: | VERSION=${GITHUB_REF_NAME#v} ARCHS=amd64,arm64 ./scripts/build-packages.sh + - name: Generate checksums + run: | + set -euo pipefail + cd dist + sha256sum -- *.deb *.rpm > SHA256SUMS + cat SHA256SUMS + + - name: Attest build provenance + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: | + dist/*.deb + dist/*.rpm + - name: Upload DEBs to test repo run: | VERSION=${GITHUB_REF_NAME#v} @@ -74,7 +95,8 @@ jobs: done - name: Create GitHub prerelease - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4 with: generate_release_notes: true prerelease: true + files: dist/SHA256SUMS diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml index 55e6905..ea56c9f 100644 --- a/.github/workflows/promote.yml +++ b/.github/workflows/promote.yml @@ -9,6 +9,10 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref_name }} cancel-in-progress: true +# Least privilege by default; promote_artifactory adds id-token: write. +permissions: + contents: read + jobs: enforce_stable_semver: name: Require Stable Release Semver @@ -54,10 +58,10 @@ jobs: NF_RPM_TEST_REPO: ${{ vars.NF_RPM_TEST_REPO || 'nfpax-netfoundry-rpm-test' }} NF_DEB_STABLE_REPO: ${{ vars.NF_DEB_STABLE_REPO || 'nfpax-netfoundry-deb-stable' }} NF_RPM_STABLE_REPO: ${{ vars.NF_RPM_STABLE_REPO || 'nfpax-netfoundry-rpm-stable' }} - JFROG_CLI_VERSION: ${{ vars.JFROG_CLI_VERSION || '2.78.2' }} + JFROG_CLI_VERSION: ${{ vars.JFROG_CLI_VERSION || '2.133.0' }} steps: - name: Configure jFrog CLI - uses: jfrog/setup-jfrog-cli@v4 + uses: jfrog/setup-jfrog-cli@4c2f06da03095113100534a16d58d8a252680949 # v5.3.5 with: version: ${{ env.JFROG_CLI_VERSION }} oidc-provider-name: nf-github-actions-setup-jfrog-cli diff --git a/.github/workflows/ziti-test.yml b/.github/workflows/ziti-test.yml index 7a6b2ec..b8aa2b4 100644 --- a/.github/workflows/ziti-test.yml +++ b/.github/workflows/ziti-test.yml @@ -9,10 +9,13 @@ name: Integration Test # ZTS_CHECKOUT_TOKEN — fine-grained PAT with read access to # netfoundry/ziti-test-suite # -# The topology is defined in suites/ziti-ssh/suite.yml: -# • 1 Ziti controller — runs ziti-ssh-ca -# • 2 edge routers — each runs ziti-ssh-host (proxies Ziti → local sshd) -# • 1 client VM — runs ziti-ssh and ziti-scp +# Two suites, same topology (1 controller running ziti-ssh-ca, 2 edge routers +# each running ziti-ssh-host, 1 client VM running ziti-ssh and ziti-scp): +# • suites/ziti-ssh/suite.yml — shared mode +# • suites/ziti-ssh-per-identity/suite.yml — per-identity mode (accounts, +# grant policy, config reload, revocation) +# Each suite gets its own stack (run_id_override). The called workflow's +# concurrency group may run them one after the other. on: workflow_dispatch: @@ -26,37 +29,51 @@ on: - 'false' - 'true' -env: - FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true +# Least privilege by default; jobs below widen only what they need. +permissions: + contents: read jobs: build-debs: name: Build Debian Packages runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/setup-go@v5 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod cache: true - name: Build .deb packages - run: VERSION=0.0.0 ./scripts/build-deb.sh + run: VERSION=0.0.0 FORMAT=deb ARCHS=amd64 ./scripts/build-packages.sh - name: Upload packages - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: ziti-ssh-debs path: dist/*.deb retention-days: 1 integration-test: - name: Integration Test + name: Integration Test (${{ matrix.suite }}) needs: build-debs - uses: netfoundry/ziti-test-suite/.github/workflows/ziti-network.yml@main + strategy: + fail-fast: false + matrix: + suite: [ziti-ssh, ziti-ssh-per-identity] + # The reusable workflow and the suite code it checks out are pinned to the + # same commit (ziti-test-suite main, 2026-04-24). ziti-test-suite is private: + # bump both SHAs together by hand unless Dependabot has been granted access. + # id-token: write is the maximum the called workflow requests (AWS OIDC). + permissions: + contents: read + id-token: write + uses: netfoundry/ziti-test-suite/.github/workflows/ziti-network.yml@fdba452ba30e016a7cc8bbb051784606efe35c55 # main 2026-04-24 with: - topology_file: suites/ziti-ssh/suite.yml + topology_file: suites/${{ matrix.suite }}/suite.yml + run_id_override: run${{ github.run_number }}-${{ matrix.suite }} + ziti_test_suite_ref: fdba452ba30e016a7cc8bbb051784606efe35c55 artifacts: ziti-ssh-debs keep_on_failure: ${{ inputs.keep_on_failure || 'false' }} secrets: diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index f32320e..dcc23e3 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -46,22 +46,22 @@ Entry points: `cmd/ziti-ssh-ca/main.go` (service and root) and `cmd/ziti-ssh-ca/ **Service startup sequence:** 1. Resolve configuration (flags > env vars > defaults) via `config.EnvOrFlag`. -2. Load the Ed25519 CA private key from disk with `ca.LoadKey` — fail fast if the file is missing or unparseable. +2. Load the controller's intermediate CA private key (RSA, ECDSA or Ed25519) from disk with `ca.LoadKey` — fail fast if the file is missing or unparseable. 3. Initialize a Ziti context from the identity file with `ziti.NewContextFromFile`, then call `zitiCtx.Authenticate()`. 4. Call `zitiCtx.Listen(serviceName)` to bind the named Ziti service and receive an `edge.Listener`. 5. Build a per-identity token-bucket rate limiter (`ratelimit.New`) and start its eviction goroutine. -6. Loop: `listener.Accept()` → `go handleConn(...)`. +6. Loop: `listener.Accept()` → `dispatch(...)`: if one of `--max-connections` slots (default 64) is free, run `handleConn` in a goroutine and release the slot when it returns; otherwise close the connection immediately. Each connection handler (`handleConn`): -1. Type-asserts the `net.Conn` to `edge.Conn` to call `GetDialerIdentityName()` — the Ziti-verified identity name of the caller. -2. Reads one newline-terminated line from the connection. -3. Resolves the effective principal from the configured mode (see [Mode: shared vs per-identity](#mode-shared-vs-per-identity)). -4. Enforces the per-identity rate limit for cert-signing requests (CA public key requests are not rate-limited). -5. Dispatches on line content: empty → write CA public key; non-empty → parse as SSH public key, sign, write certificate. +1. Calls `GetDialerIdentityName()` on the connection — the router-verified identity name of the caller (see [§6](#6-ziti-identity-flow)). Rejects the connection if it is empty. +2. Resolves the effective principal from the configured mode (see [Mode: shared vs per-identity](#mode-shared-vs-per-identity)). +3. Sets a 10-second deadline on the connection. +4. Enforces the per-identity rate limit **before reading anything**, for every request type (CA public key requests included); a limited caller receives `error: rate limit exceeded`. +5. Reads one newline-terminated line (at most 4 KiB) and dispatches on its content (a key that fails `ca.ValidateClientKey` — certificate, DSA, RSA < 3072 bits, unsupported type, or the CA's own key — gets an `error:` reply): empty → write CA public key; non-empty → parse as SSH public key, sign, write certificate. 6. Logs every outcome with the identity name as a structured field. -The CA signer (`ssh.Signer`) is initialized once and passed to every handler. `ssh.Signer` wraps a Go `crypto.Signer` — the standard library's Ed25519 implementation is safe for concurrent use, so no mutex is required. +The CA signer (`ssh.Signer`) is initialized once and passed to every handler. `ssh.Signer` wraps a Go `crypto.Signer` — the standard library's RSA, ECDSA and Ed25519 implementations are safe for concurrent use, so no mutex is required. **`config` subcommand** (`cmd/ziti-ssh-ca/config.go`): @@ -86,7 +86,7 @@ Three subcommands share persistent flags (`--identity`, `--ca-service`, `--ziti- 3. Marshal the resulting config to JSON and write it to `/etc/ziti-ssh-host/identity.json` (mode 0600, parent dir mode 0700). 4. Call `intermediateCAPublicKey(cfg)` to extract the intermediate CA public key from the enrollment response (see below). No network call to `ssh-ca` is required. 5. Call `host.WriteSSHConfig` to write `/etc/ssh/ziti_ca.pub` and `/etc/ssh/sshd_config.d/ziti-ssh.conf`. -6. Call `host.ReloadSSHD` (`systemctl reload ssh`) to make sshd pick up the new config. +6. Call `host.ReloadSSHD` to make sshd pick up the new config: validate with `sshd -t`, `systemctl reload ssh.service` if it is running (including when `ssh.socket` with `Accept=no` has started it, the Ubuntu 22.10+ default), and send SIGHUP to any leftover top-level sshd listeners (PPID 1) — skipped only for an `Accept=yes` socket, where every connection's sshd has PPID 1. **Intermediate CA extraction:** @@ -110,10 +110,10 @@ After enrollment, `cfg.ID.CA` contains the PEM chain (root CA + intermediate CA) b. Call `zitiCtx.GetService(svcName)` and `zitiEdge.ParseServiceConfig` to load and parse the `ziti-ssh-host.v1` config into a `*host.PermissionsConfig` (nil if no config attached). c. Store the config in a `serviceState` (RWMutex-protected pointer) for atomic live reload. 5. If `mode == "per-identity"`: - a. Create a single shared `host.UserManager` backed by `/var/lib/ziti-ssh-host/managed-users`. - b. Call `manager.CleanupOrphans()` to remove users left over from a previous crash. + a. Create a single shared `host.UserManager` backed by `/var/lib/ziti-ssh-host/managed-users` (active sessions) and `/var/lib/ziti-ssh-host/owned-users.json` (ownership registry). + b. Call `manager.CleanupOrphans()` to remove registered users left over from a previous crash. c. For each service, build a `host.ProxyHooks` struct that closes over that service's `serviceState`: - - `OnConnect`: calls `ca.DeriveUsername(identity)`, resolves `host.IdentityPermissions` from the service's `PermissionsConfig` (falling back to global env vars), then calls `manager.EnsureUser(username, perms)`. + - `OnConnect`: calls `ca.DeriveUsername(identity)`, resolves `host.IdentityPermissions` from the service's `PermissionsConfig` (falling back to global env vars), then calls `manager.EnsureUser(identity, username, perms)`. - `OnDisconnect`: calls `manager.ReleaseUser(username)`. 6. For each service, launch `host.Proxy(listener, "127.0.0.1:22", hooks, &connWg)` in a goroutine. All services share one `connWg` for graceful drain. 7. Subscribe to service-changed events via `zitiCtx.Events().AddServiceChangedListener`. When a changed event arrives for a bound service, reload its `ziti-ssh-host.v1` config and swap the `serviceState` pointer atomically. @@ -134,10 +134,10 @@ The client binary. It provides five subcommands (and a root shorthand for `conne **`connect [user@]`** (also the root default when a target argument is given): 1. Resolve the SSH private key (auto-detect from `~/.ssh/` or use `--key`). -2. Call `client.CertNeedsRefresh(certPath)` — if the cert is missing or will expire within 5 minutes, run the sign flow automatically before opening the session. +2. Call `client.CertNeedsRefresh(certPath)` — if the cert is missing or less than 20% of its lifetime remains (between 30 s and 5 min — 1 minute for the default 5-minute certificate), run the sign flow automatically before opening the session. 3. Call `client.NewCertSigner(privKeyPath)` to load the private key and, if a `-cert.pub` file is present, wrap it in an `ssh.CertSigner`. If the key is passphrase-protected, fall back to the SSH agent (`SSH_AUTH_SOCK`). 4. Authenticate to Ziti and dial the `ssh` service, specifying the target identity name as the terminator address via `ziti.DialOptions{Identity: terminatorAddr}`. If the target matches a known Ziti service name directly, it is dialled without a terminator. -5. Call `client.RunSession(conn, username, host, signer, forwardAgent)` to run an interactive PTY session over the Ziti connection. Pass `forwardAgent=true` when `-A` is set to forward the local SSH agent. +5. Build the host-key check (`client.NewHostKeyCallback(service, terminator)`, trust on first use) and call `client.RunSession(conn, username, host, signer, forwardAgent, hostKeyCallback)` to run an interactive PTY session over the Ziti connection. Pass `forwardAgent=true` when `-A` is set to forward the local SSH agent. **`sign`**: dials the `ssh-ca` Ziti service, sends the user's SSH public key, receives the signed certificate, writes it to `~/.ssh/-cert.pub`, and displays certificate details via `ssh-keygen -L`. @@ -164,7 +164,7 @@ The CA places the operator-configured `--principal` (default: `ziggy`) in `Valid The CA calls `ca.DeriveUsername(callerIdentity)` to produce a Linux-safe username and places it in `ValidPrincipals`. `ziti-ssh-host run` uses `host.UserManager` to create and destroy Linux accounts on demand. **`ca.DeriveUsername` rules:** -1. Lowercase the entire identity name. +1. Lowercase ASCII letters (`A`–`Z`); other characters are not case-folded, so non-ASCII lookalikes such as the Kelvin sign `K` never become ASCII letters. 2. Replace any character outside `[a-z0-9_-]` with `_`. 3. If the result starts with a digit, prefix it with `z`. 4. Truncate to 32 characters. @@ -189,26 +189,35 @@ type IdentityPermissions struct { Safe on a nil receiver — returns the global fallbacks when no config is attached. -**`host.NewUserManager(stateFile string, cleanupOnDisconnect bool)`** returns a concurrent-safe reference counter. It no longer accepts a global `sudoersRule` — permissions are passed per-call instead, enabling each service to supply different values through the same shared manager. +**`host.NewUserManager(stateFile string, cleanupOnDisconnect bool) (*UserManager, error)`** returns a concurrent-safe session counter and account manager. Account ownership is persisted in a `host.OwnerRegistry` at `owned-users.json` next to `stateFile`; the constructor fails (and `run` exits) if that file exists but cannot be parsed, so accounts are never managed without it. -**`host.UserManager`** tracks how many sessions are open for each derived username: +**`host.UserManager`** tracks how many sessions are open for each derived username and decides which accounts may be touched: -- `EnsureUser(username string, perms IdentityPermissions) error` — increments the session count. If the count was 0: runs `useradd -m -s /bin/bash ` (exit code 9 treated as success); if `perms.Groups` is non-empty, runs `usermod -aG ` (failure is non-fatal, logged); if `perms.SudoersRule` is non-empty, writes and validates a sudoers file at `/etc/sudoers.d/` via `visudo -c`. The username is appended to the state file. -- `ReleaseUser(username string) error` — decrements the session count. If the count reaches 0 and `cleanupOnDisconnect` is true, calls `deleteUser(username)` and removes the username from the state file. If `cleanupOnDisconnect` is false, the account is kept but the sudoers file is still removed (group membership is implicitly removed when the account is eventually deleted). -- `CleanupOrphans()` — reads the state file and calls `deleteUser` on each entry. Called once at startup before accepting connections. +- `EnsureUser(zitiIdentity, username string, perms IdentityPermissions) error` — rejects reserved names, names starting with `-`, and names outside `[a-z0-9_-]` (`ValidateManagedUsername`). Under a per-user lock it then looks the account up with `getent passwd`: + - **absent** → `useradd -m -s /bin/bash -- `, verify the assigned UID is ≥ `MinManagedUID` (1000), record `{identity, uid}` in the registry; + - **present** → proceed only if the registry records it for the same identity with the same UID and the UID is ≥ 1000; otherwise reject without touching it (pre-existing system or admin account, identity collision, or replaced account). `useradd` exit 9 (created concurrently by someone else) is a rejection, not success. + + It then (`applyPermissions`) sets supplementary groups with `usermod -G -- `, removes a legacy `/etc/sudoers.d/` only if it holds the single line this tool used to write, and writes or removes `/etc/sudoers.d/ziti-ssh-host-`. Any failure rejects the connection; a failed sudoers install first removes the existing file. The session is counted only after this succeeds. +- `ReleaseUser(username string) error` — decrements the session count. At zero it re-checks the count after taking the per-user lock (a new session may have started), then acts only on a registered account whose UID still matches: removes the sudoers file, or — with `cleanupOnDisconnect` — deletes the account and its registry record. +- `CleanupOrphans()` — reads the state file at startup. With cleanup enabled, deletes each listed account that is still registered with a matching UID; otherwise removes their leftover sudoers files. Unregistered accounts are skipped. + +**`ziti-ssh-host users list|claim`** read and extend the registry. `claim` is the migration path for accounts created before the registry existed; see [operations.md](docs/operations.md#managing-account-ownership). **Global fallback env vars** (per-identity mode only): - `ZITI_SUDOERS_RULE` — sudoers rule fragment applied to any identity not matched by a `ziti-ssh-host.v1` config entry. - `ZITI_SSH_GROUPS` — comma-separated Linux group names applied to any identity not matched by a config entry. - `ZITI_USER_CLEANUP` — set to `true` to delete Linux accounts after the last session closes (default: `false`). +- `ZITI_TERMINATE_ON_DISCONNECT` — set to `true` to end a kept account's processes when its last session closes (default: `false`). -**`host.deleteUser(username)`** — the internal cleanup sequence: +**`host.deleteUser(username, uid)`** — the internal cleanup sequence, called only for registered accounts with a verified UID (it also refuses any UID below 1000): -1. Remove `/etc/sudoers.d/` if present. -2. Run `loginctl terminate-user ` to drain the systemd user session (errors are logged but ignored — the session may already be gone). -3. Poll with `pgrep -u ` until no processes remain or a 5-second timeout elapses. -4. Run `userdel -r ` to remove the account and home directory. +1. Remove `/etc/sudoers.d/ziti-ssh-host-` if present. +2. `terminateUserProcesses`: run `loginctl disable-linger -- ` and `loginctl terminate-user -- ` (errors logged but ignored — the session may already be gone), then poll with `pgrep -u ` until no processes remain (5 s), then `pkill -TERM -u ` (10 s), then `pkill -KILL -u ` (5 s). +3. `removeOwnedFiles`: delete entries owned by the UID in `/tmp`, `/var/tmp` and `/dev/shm` (files and symlinks themselves, then directories left empty; never following links, never removing other users' files), so they cannot pass to the next account given the same UID. +4. Run `userdel -r -- ` to remove the account and home directory. + +With `ZITI_TERMINATE_ON_DISCONNECT=true` and cleanup off, `ReleaseUser` (and `CleanupOrphans` after a crash) calls `terminateUserProcesses` via `accountOps.TerminateProcesses` after dropping privileges, without deleting the account. **`host.ProxyHooks`** wires `UserManager` into the proxy loop: @@ -221,7 +230,7 @@ type ProxyHooks struct { `proxyConn` extracts the caller's Ziti identity name via the `dialerNamer` interface (same pattern as `ziti-ssh-ca`), then calls `OnConnect` before proxying and `OnDisconnect` in a deferred call after the connection closes. If `OnConnect` returns an error, the connection is closed without proxying. -In `per-identity` mode, the `OnConnect` closure for each service: (1) derives the Linux username with `ca.DeriveUsername`; (2) calls `serviceState.get()` to read the current `*PermissionsConfig` under a read lock; (3) calls `config.Resolve(identity, globalGroups, globalSudoersRule)` to obtain the `IdentityPermissions` for this connection; (4) calls `manager.EnsureUser(username, perms)`. The `serviceState` pointer may be swapped by the service-changed listener at any time; the read lock ensures a consistent view per connection. +In `per-identity` mode, the `OnConnect` closure for each service: (1) derives the Linux username with `ca.DeriveUsername`; (2) calls `serviceState.get()` to read the current `*PermissionsConfig` under a read lock; (3) calls `config.Resolve(identity, globalGroups, globalSudoersRule)` to obtain the `IdentityPermissions` for this connection; (4) calls `manager.EnsureUser(identity, username, perms)`. The `serviceState` pointer may be swapped by the service-changed listener at any time; the read lock ensures a consistent view per connection. **Multi-service binding:** all services share one `UserManager`. If the same Ziti identity connects through two different services simultaneously, the Linux user is created once on the first connection (with that service's permissions) and the second connection reuses the existing account. This first-connection-wins behaviour is logged at info level. @@ -246,8 +255,10 @@ Client ziti-ssh-ca - Non-empty line: treated as an SSH public key in authorized_keys format (`ssh-ed25519 AAAA...`). **Response encoding:** A single line in authorized_keys format, terminated by `\n`. -- CA public key response: `ssh-ed25519 AAAA... \n` +- CA public key response: ` AAAA... \n` — the type of the controller's intermediate CA key, typically `ssh-rsa` - Signed certificate response: `ssh-ed25519-cert-v01@openssh.com AAAA...\n` +- Refusal: `error: \n` (e.g. `error: rate limit exceeded`). Every request, including a CA public key request, counts against the caller's rate limit. +- When `--max-connections` concurrent connections are already open, a new connection is closed without a response. Both are produced by `ssh.MarshalAuthorizedKey` from `golang.org/x/crypto/ssh`. @@ -257,29 +268,58 @@ The connection is closed by the server after each response. There is no persiste ## 6. Ziti Identity Flow -The Ziti network provides mutual TLS for all connections. Every Ziti identity has a certificate issued by the Ziti controller. When a client dials a service, the edge router verifies the client's certificate and forwards the verified identity name to the listener side. +The Ziti network provides mutual TLS for all connections. Every Ziti identity has a certificate issued by the Ziti controller. When a client dials a service, the client's edge router (which authenticated the client) attaches the dialer's identity name to the connection it delivers to the hosting side. + +Two identity values arrive with every accepted connection, and only one is trustworthy: + +| Accessor | Wire header | Set by | Trusted | +|---|---|---|---| +| `GetDialerIdentityName()` | `DialerIdentityName` | The dialer's edge router, from its own record of the authenticated identity (OpenZiti **v2.0.0+**) | **Yes** | +| `SourceIdentifier()` | `CallerId` | The dialing SDK; copied through the router unchanged | **No** — a modified client can send any value | + +```mermaid +sequenceDiagram + participant C as Client (ziti-ssh) + participant R as Edge router (v2.0.0+) + participant S as ziti-ssh-ca / ziti-ssh-host + C->>R: Dial (CallerId = any value the client chooses) + Note over R: Resolves the authenticated identity ID
in its router data model + R->>S: CallerId (passed through, untrusted)
DialerIdentityName (router-set, trusted) + alt DialerIdentityName present + S->>S: Use it for principal, Key ID, rate limit, permissions + S-->>S: Warn if CallerId differs (possible spoofing attempt) + else DialerIdentityName absent + S--xC: Close connection (fail closed) + end +``` ### Extraction -In `cmd/ziti-ssh-ca/main.go`, `callerIdentity` performs the extraction: +In `cmd/ziti-ssh-ca/main.go`, `callerIdentity` performs the extraction (`host.callerName` in `host/host.go` is equivalent): ```go func callerIdentity(conn net.Conn) string { - if ec, ok := conn.(zitiEdge.Conn); ok { - return ec.GetDialerIdentityName() - } - // Fallback narrow interface for flexibility type dialerNamer interface { GetDialerIdentityName() string } - if dn, ok := conn.(dialerNamer); ok { - return dn.GetDialerIdentityName() + dn, ok := conn.(dialerNamer) + if !ok { + return "" } - return "" + name := dn.GetDialerIdentityName() + // SourceIdentifier() is compared only to log a mismatch warning. + ... + return name } ``` -`zitiEdge.Conn` is from `github.com/openziti/sdk-golang/ziti/edge`. The `edge.Listener.Accept()` returns values that implement this interface. If the assertion fails (e.g. in unit tests using a plain `net.Conn`), the function returns `""` and the connection is rejected. +If the router did not supply a dialer identity — a router older than v2.0.0, or a router that could not resolve the dialing identity — the function returns `""`. `ziti-ssh-ca` then closes the connection, and `ziti-ssh-host` in `per-identity` mode closes it without creating a user or proxying to sshd. In both cases the log line is: + +``` +rejected connection: edge router did not supply a dialer identity (OpenZiti v2.0.0+ routers required) +``` + +A compile-time assertion in both `cmd/ziti-ssh-ca/main.go` and `cmd/ziti-ssh-host/main.go` ensures `edge.Conn` still provides `GetDialerIdentityName()` after SDK upgrades. ### Identity as SSH Certificate Key ID @@ -299,6 +339,8 @@ On the host side, `ziti-ssh-host run` uses `BindUsingEdgeIdentity: true`. This c ## 7. Addressable Terminators for Host Routing +> **Limitation:** a terminator name is an address chosen by the binding identity, not an authenticated identity. OpenZiti only prevents two *different* identities from holding the same name at the same time, and the dialer is not told which identity answered. An identity with Bind on the service can therefore answer for an offline host's name. Access control is per service; per-host services give a per-host guarantee. See [operations.md](docs/operations.md#host-identity-terminator-names). + Each Ziti service that `ziti-ssh-host` binds has multiple terminators — one per enrolled host. Each `ziti-ssh-host run` instance adds a terminator with its identity name as the address using `BindUsingEdgeIdentity: true`: ``` @@ -320,6 +362,8 @@ ssh-ops: alice → [sudo, adm] ← ops team reach db-primary with OS permissi ssh-db: carol → [mysql] ← DBA team reach db-primary with DB permissions ``` +The `sudo` grant on `ssh-ops` requires the host owner's opt-in for that service (`ZITI_ALLOW_GROUPS=ssh-ops:sudo`); the `ssh-db` config cannot grant it. + This design means: - No SSH jump hosts or bastion servers. - No DNS entries needed for SSH targets. @@ -353,7 +397,7 @@ The key written to `ziti_ca.pub` is the **controller's intermediate CA public ke - Which Ziti identity the user holds. - Whether the user's Ziti identity is still valid. -Both of these are enforced by the Ziti network before the connection ever reaches `sshd`. The certificate TTL (default 8 hours, configurable via `--cert-ttl` / `ZITI_CERT_TTL` on `ziti-ssh-ca`) provides a backstop: a revoked or expired Ziti identity loses access once any outstanding certificate expires, without any changes on SSH hosts. +Both of these are enforced by the Ziti network before the connection ever reaches `sshd`. The certificate TTL (default 5 minutes, configurable via `--cert-ttl` / `ZITI_CERT_TTL` on `ziti-ssh-ca`) provides a backstop: a revoked or expired Ziti identity loses access once any outstanding certificate expires, without any changes on SSH hosts. --- @@ -369,15 +413,15 @@ Certificates are issued on demand and are ephemeral. There is no certificate sto | `Key` | Client's submitted public key | Wire protocol request | | `KeyId` | `ziti:` | Extracted from Ziti connection | | `ValidPrincipals` | `[]string{principal}` | shared mode: `--principal` flag (default: `ziggy`); per-identity mode: `ca.DeriveUsername(callerIdentity)` | -| `ValidAfter` | `time.Now().Unix()` | Signing time | +| `Serial` | random non-zero `uint64` | `crypto/rand`; logged by the CA (`issued SSH certificate … serial=N`) and by sshd on login (`serial N`) | +| `ValidAfter` | `time.Now().Add(-ca.ClockSkewAllowance).Unix()` | Signing time − 60 s, so hosts whose clock is slightly behind the CA's accept new certificates | | `ValidBefore` | `time.Now().Add(ttl).Unix()` | Signing time + TTL (default 5m, configurable via `--cert-ttl` / `ZITI_CERT_TTL`) | -| `Extensions["permit-pty"]` | `""` | Hardcoded | -| `Extensions["permit-port-forwarding"]` | `""` | Hardcoded | -| `Extensions["permit-agent-forwarding"]` | `""` | Hardcoded | +| `Extensions` | `permit-pty`, `permit-port-forwarding` | `--cert-extensions` / `ZITI_CERT_EXTENSIONS` (`ca.ParseExtensions`); agent forwarding not granted by default | +| `CriticalOptions["source-address"]` | `127.0.0.1/32,::1/128` | `--cert-source-address` / `ZITI_CERT_SOURCE_ADDRESS`; omitted when set to `none` | ### TTL and Revocation -The TTL defaults to 8 hours and is configurable via `--cert-ttl` (flag) or `ZITI_CERT_TTL` (environment variable) on `ziti-ssh-ca`. Any positive `time.Duration` string is accepted (e.g. `4h`, `12h`, `24h`). There is no revocation mechanism. Access control is handled upstream: +The TTL defaults to 5 minutes and is configurable via `--cert-ttl` (flag) or `ZITI_CERT_TTL` (environment variable) on `ziti-ssh-ca`. Any positive `time.Duration` string is accepted (e.g. `4h`, `12h`, `24h`). There is no revocation mechanism (no KRL); with a 5-minute default TTL this is accepted. Access control is handled upstream: - **While TTL is active:** A user whose Ziti identity is revoked at the controller can no longer dial the `ssh` service — they cannot open new SSH sessions. Any existing SSH session (TCP connection already established) continues until it closes naturally. - **After TTL expires:** The certificate is no longer accepted by `sshd`. The user must obtain a new certificate, which requires a live Ziti identity. @@ -391,22 +435,23 @@ For most operational scenarios this is sufficient. If immediate hard revocation cert := &ssh.Certificate{ CertType: ssh.UserCert, Key: pubKey, + Serial: serial, // random, non-zero KeyId: "ziti:" + identity, ValidPrincipals: []string{principal}, - ValidAfter: uint64(now.Unix()), + ValidAfter: uint64(now.Add(-ca.ClockSkewAllowance).Unix()), // 60 s backdate ValidBefore: uint64(now.Add(ttl).Unix()), Permissions: ssh.Permissions{ - Extensions: map[string]string{ - "permit-pty": "", - "permit-port-forwarding": "", - "permit-agent-forwarding": "", - }, + // From --cert-extensions; default "permit-pty,permit-port-forwarding". + Extensions: map[string]string{"permit-pty": "", "permit-port-forwarding": ""}, }, } +if sourceAddress != "" { // --cert-source-address, default "127.0.0.1/32,::1/128" + cert.Permissions.CriticalOptions = map[string]string{"source-address": sourceAddress} +} cert.SignCert(rand.Reader, signer) ``` -`ssh.Certificate.SignCert` serializes the certificate in OpenSSH wire format, signs the serialized bytes with the CA key using Ed25519, and attaches the signature. The result is marshaled to authorized_keys format by `ssh.MarshalAuthorizedKey`. +`ssh.Certificate.SignCert` serializes the certificate in OpenSSH wire format, signs the serialized bytes with the CA key (with an RSA CA key the signature algorithm is `rsa-sha2-256`, as `ssh-keygen -L` reports for issued certificates — accepted by OpenSSH's default `CASignatureAlgorithms`), and attaches the signature. The result is marshaled to authorized_keys format by `ssh.MarshalAuthorizedKey`. --- @@ -519,6 +564,8 @@ conn, err := zitiCtx.Dial(caService) import zitiEdge "github.com/openziti/sdk-golang/ziti/edge" if ec, ok := conn.(zitiEdge.Conn); ok { + // Router-verified (OpenZiti v2.0.0+). Never use ec.SourceIdentifier() + // for authorization: it is client-supplied. identityName := ec.GetDialerIdentityName() } ``` @@ -610,12 +657,20 @@ This is possible because `ziti-ssh-ca` runs on the same host as the Ziti control **CA private key exposure:** The CA private key is loaded once at startup and held in memory as an `ssh.Signer`. It is never written to a log or returned over the wire. The key file must be owned by the service user with mode 0600. -**Identity validation:** `callerIdentity` returns `""` for any connection where the Ziti identity cannot be asserted. `handleConn` rejects such connections immediately before reading any data from them. +**Identity validation:** `callerIdentity` trusts only the router-set `DialerIdentityName` header (`GetDialerIdentityName()`), never the client-set `CallerId` header (`SourceIdentifier()`). It returns `""` when the router supplied no dialer identity, and `handleConn` rejects such connections before reading any data from them. `ziti-ssh-host` applies the same rule in `per-identity` mode. This requires every edge router to run OpenZiti v2.0.0 or later. -**Principal derivation:** In `shared` mode, `ValidPrincipals` is set from the operator-configured `--principal` flag — a client cannot influence which Linux user they get. In `per-identity` mode, the principal is derived deterministically from the Ziti-verified identity name via `ca.DeriveUsername`. The identity name is attested by the Ziti network's mutual TLS and cannot be spoofed by the client. The derivation function (lowercase, replace non-`[a-z0-9_-]` with `_`, prefix `z` if digit-leading, truncate to 32) is purely defensive — it sanitizes the identity name for use as a POSIX username and is not a security boundary. +**Principal derivation:** In `shared` mode, `ValidPrincipals` is set from the operator-configured `--principal` flag — a client cannot influence which Linux user they get. In `per-identity` mode, the principal is derived deterministically from the router-verified identity name via `ca.DeriveUsername`. The name comes from the dialer's edge router, which authenticated the client over mTLS, so the client cannot substitute another name. The derivation function (lowercase, replace non-`[a-z0-9_-]` with `_`, prefix `z` if digit-leading, truncate to 32) is purely defensive — it sanitizes the identity name for use as a POSIX username and is not a security boundary. Because it is lossy (`Alice` and `alice`, or `a.b` and `a_b`, derive the same name), `ziti-ssh-host` binds each account to the first identity that created it in its ownership registry and rejects any other identity deriving the same username. `ziti-ssh-ca` refuses to sign a per-identity certificate whose derived principal is a reserved account name (`ca.IsReservedUsername`: `root`, system accounts, `ubuntu`, `admin`, …) or starts with `-`; the host uses the same list. + +**Certificate-only login for managed accounts:** the sshd drop-in written by `ziti-ssh-host` adds `Match Group ziti-ssh-managed` with `AuthorizedKeysFile none` and `AuthorizedKeysCommand none`. Per-identity accounts are always in that group, and administrators add the shared account in shared mode. A key a user adds to their own `authorized_keys` therefore cannot outlive their certificate or the revocation of their identity. Other accounts (administrators, cloud default users) are unaffected. + +**Certificates are bound to the Ziti path:** every certificate carries the `source-address` critical option (default `127.0.0.1/32,::1/128`). Each host's sshd only ever receives legitimate logins from that host's own `ziti-ssh-host` proxy over loopback, so the same certificate works on every host the caller's Ziti policies allow, while sshd rejects it on any connection that reaches port 22 directly (a security group, LAN or VPN path that bypasses Ziti). A local user on the SSH host itself who also holds the private key can still use it via loopback until it expires. **Ziti as the authorization boundary:** Any identity that can dial `ssh-ca` receives a certificate. Any identity that can dial `ssh` with a given terminator address reaches that host. Access control is managed entirely in Ziti service policies (dial policies, service policies). This is intentional — the CA is a dumb signing service; the access control lives in Ziti. **No credentials on hosts:** The only file written to each SSH host is the CA public key (`/etc/ssh/ziti_ca.pub`). This is not a credential. An attacker who reads it gains nothing — it is the CA's public key and is not secret. -**Per-identity permissions trust boundary:** The `ziti-ssh-host.v1` config is fetched from the Ziti controller over the same mTLS-authenticated data plane channel used for service subscription. The hosting identity must have a config policy granting it access to the `ziti-ssh-host.v1` config type — config data is not delivered to arbitrary identities. Permission entries are keyed by exact Ziti identity name; the identity name is attested by Ziti's mTLS and cannot be spoofed by the connecting client. Linux groups referenced in a config entry must already exist on the host — `ziti-ssh-host` does not create groups. A missing group causes `usermod` to fail for that group; the failure is non-fatal (logged, session continues) so a misconfigured group name silently reduces the permissions applied rather than blocking access. Operators should use `ziti-ssh-host inspect` to verify the effective permissions before and after config changes. +**Account ownership boundary (per-identity mode):** `ziti-ssh-host` runs as root and creates, modifies, and deletes Linux accounts, so it must never act on an account it does not own. It manages an account only if it is recorded in `/var/lib/ziti-ssh-host/owned-users.json` for the connecting identity with the account's current UID, and the UID is at least 1000. Accounts that already exist but are not registered — `root`, the distribution's default user, administrator accounts — are refused before any `usermod`, sudoers write, process signal, or `userdel`. A short list of reserved names is refused even if absent. Sudoers files are written under a `ziti-ssh-host-` prefix so they cannot overwrite administrator files in `/etc/sudoers.d`. Accounts created by earlier releases are adopted only through an explicit `ziti-ssh-host users claim`. + +**Host grant policy:** a `ziti-ssh-host.v1` config is written by whoever can edit configs on the controller, so `ziti-ssh-host` does not apply it unconditionally. Per service, the host owner opts in to `sudoers_rule` (`ZITI_ALLOW_SUDOERS`) and to privileged groups (`ZITI_ALLOW_GROUPS`; `root`, `sudo`, `admin`, `wheel`, `docker`, `lxd`, `disk`, `shadow`, `libvirt` are refused otherwise), optionally restricting all grantable groups (`ZITI_RESTRICT_GROUPS`). Entries exceeding the policy reject the connection. Controller config access alone therefore cannot grant root on a host; it takes the host owner's opt-in for that service as well. The host's own env fallbacks are outside the policy. + +**Per-identity permissions trust boundary:** The `ziti-ssh-host.v1` config is fetched from the Ziti controller over the same mTLS-authenticated data plane channel used for service subscription. The hosting identity must have a config policy granting it access to the `ziti-ssh-host.v1` config type — config data is not delivered to arbitrary identities. Permission entries are keyed by Ziti identity name; the name used for lookup is the router-verified dialer identity (see [§6](#6-ziti-identity-flow)), so the connecting client cannot substitute another identity's entry. Linux groups referenced in a config entry must already exist on the host — `ziti-ssh-host` does not create groups. A missing group makes `usermod -G` fail, and the connection is then rejected (fail closed) rather than proceeding with the account's previous groups — a misconfigured entry blocks that identity until the config is fixed. The same applies to sudoers write or removal failures. Operators should use `ziti-ssh-host inspect` to verify the effective permissions before and after config changes. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c38d19..a16db58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,272 @@ All notable changes to this project will be documented in this file. +## [0.3.0] - 2026-11-20 + +### Security: upgrade required + +This release fixes security issues in how the CA and the host daemon identify callers, in per-identity account +handling, in certificate scope and in the clients. All deployments should upgrade. Before upgrading: + +- **OpenZiti routers v2.0.0 or later are required.** The caller's identity is taken only from the router-set dialer + identity; connections without it are refused. +- **Upgrade `ziti-ssh-ca` and `ziti-ssh-host` together.** Certificates are now valid only through the local + `ziti-ssh-host` proxy (`source-address`), and derived usernames fold only ASCII case. +- **Breaking changes:** a `ziti-ssh-host.v1` config may grant privileged groups or a `sudoers_rule` only where the + host opts the service in (`ZITI_ALLOW_GROUPS`, `ZITI_ALLOW_SUDOERS`); certificates no longer grant agent forwarding + by default, and `ziti-ssh -A` needs `--forward-agent-unverified`; permission keys match `*` and `?` only (`[` and + `\` are literal). +- **Per-identity hosts:** accounts created by earlier releases are not managed until claimed with + `ziti-ssh-host users claim --username --identity ` (`ziti-ssh-host users list` shows them). +- **Shared mode:** add the shared account to the `ziti-ssh-managed` group (`usermod -aG ziti-ssh-managed ziggy`) so it + can only log in with a CA certificate. +- **Revocation:** by default a disconnected (or revoked) user's background processes and scheduled jobs keep + running. Set `ZITI_TERMINATE_ON_DISCONNECT=true` or `ZITI_USER_CLEANUP=true` on hosts where that is not acceptable. + +Details of each change follow. + +#### Certificates restricted to the Ziti path (`source-address`) + +`ziti-ssh-ca` now adds the OpenSSH `source-address` critical option to every certificate, defaulting to `127.0.0.1/32,::1/128`. sshd accepts a certificate only from those addresses; `ziti-ssh-host` always proxies to `127.0.0.1:22`, so the same certificate keeps working on every host the caller's Ziti policies allow, but is rejected on any connection that reaches port 22 directly. + +- New flag `--cert-source-address` / `ZITI_CERT_SOURCE_ADDRESS` (comma-separated IPs or CIDRs, or `none` to omit the option). Invalid values stop the CA at startup. +- If something other than the local `ziti-ssh-host` delivers connections to sshd, set this accordingly. + +#### Host grant policy for `ziti-ssh-host.v1` configs (BREAKING) + +- `ziti-ssh-host` now limits, per Ziti service, what a `ziti-ssh-host.v1` config may grant: `sudoers_rule` only from services listed in `ZITI_ALLOW_SUDOERS` (default: none); privileged groups (`root`, `sudo`, `admin`, `wheel`, `docker`, `lxd`, `disk`, `shadow`, `libvirt`) only when opted in via `ZITI_ALLOW_GROUPS` (`:` or `*:`); optionally only listed groups (`ZITI_RESTRICT_GROUPS=true`). The host's own `ZITI_SSH_GROUPS` / `ZITI_SUDOERS_RULE` fallbacks are unaffected. +- An entry exceeding the policy rejects the connection (`rejecting connection: permissions refused by host grant policy`); violations are logged at config load/reload; `ziti-ssh-host inspect` shows the policy and refused entries. Invalid policy settings stop `run` in per-identity mode. +- **Action:** configs that grant `sudoers_rule` or privileged groups are refused until each host opts the service in. Run `ziti-ssh-host inspect --service ` before upgrading. + +#### Host keys checked on every connection (trust on first use) + +- `ziti-ssh` and `ziti-scp` no longer accept any SSH host key. They remember the key(s) seen for each Ziti address in `$XDG_CONFIG_HOME/ziti-ssh/known_hosts` (0600). A host dialed by name (`@`) with a changed key is refused; for a service dialed directly, where any bound host may answer, the user is asked before an additional key is trusted (refused without a terminal). OpenZiti does not tell the dialer which identity answered, so this detects impersonation after the first connection. +- New `ziti-ssh known-hosts list|remove
`. +- Dialing a service directly now prints `Dialing service "…" directly: any host bound to it may answer.` (`ziti-ssh`, `ziti-scp`, `ziti-ssh proxy`). +- **Action:** after rebuilding a host, users run `ziti-ssh known-hosts remove @`. + +#### Certificate-only login for Ziti-managed accounts + +- The sshd drop-in now contains `Match Group ziti-ssh-managed` with `AuthorizedKeysFile none` and `AuthorizedKeysCommand none`, so members of that group can only log in with a CA certificate; a key added to their own `authorized_keys` can no longer outlive their certificate or identity. Other accounts are unaffected. +- The group is created by the `ziti-ssh-host` package, `enroll` and `run`; `run` rewrites an outdated drop-in at startup and reloads sshd. Per-identity accounts are always kept in the group. +- **Action (shared mode):** add the shared account to the group — `usermod -aG ziti-ssh-managed `. `run` warns at startup if the group is empty. + +#### Agent forwarding off by default (BREAKING) + +- `ziti-ssh-ca` grants certificate extensions from `--cert-extensions` / `ZITI_CERT_EXTENSIONS`, default `permit-pty,permit-port-forwarding` — **agent forwarding is no longer granted by default**. +- `ziti-ssh connect -A` is refused unless `--forward-agent-unverified` is also given: clients cannot yet verify which host answered on a terminator address (an OpenZiti limitation), and a forwarded agent can be used by that host while connected. +- **Action:** to keep agent forwarding, add `permit-agent-forwarding` to `ZITI_CERT_EXTENSIONS` on the CA and use `-A --forward-agent-unverified`. + +#### Documentation: host identity and access scope + +- Docs no longer present the terminator name as a per-host access boundary: access control is per Ziti service, and a terminator name is an address chosen by the binding identity. New section in `docs/operations.md` (host identity / terminator names) describing the limitation, Bind-policy guidance, and one-service-per-host for hosts needing a strong identity guarantee. + +#### Temporary files removed with deleted accounts + +- With `ZITI_USER_CLEANUP=true`, files a deleted user owned in `/tmp`, `/var/tmp` and `/dev/shm` are removed before `userdel` (symlinks are removed, never followed; directories only when empty), so they do not pass to the next account given the same UID. + +#### Controller CA key tracking + +- `ziti-ssh-host` takes each controller's intermediate CA from the TLS chain verified against the enrollment root CA (`VerifiedChains`) instead of the certificates the server presented, which could include an extra CA certificate that would have become an SSH trust anchor. +- If a controller does not answer during a CA key refresh, currently trusted keys are kept (previously its key was dropped from `TrustedUserCAKeys`, breaking logins during a transient outage). Keys are removed only when every controller answered. +- The event-driven and periodic refreshes are serialised; empty controller URL lists are ignored and never persisted to the identity file (applies to all binaries via `config.PersistZtAPIs`). + +#### Permission configs that fail to load now fail closed + +- If a service's `ziti-ssh-host.v1` config cannot be fetched or parsed at startup, per-identity connections on that service are rejected instead of falling back to the global defaults. A failed live reload marks the service unavailable instead of keeping the previous config. A config that is simply not attached still uses the global fallbacks. + +#### `ziti-scp` download hardening + +- Refuses to write through an existing local symlink at a download destination. +- Downloaded files take the remote file's permission bits reduced by the local umask (previously always 0644); with `-p` the mode is applied exactly except that files are never made world-writable. setuid/setgid/sticky are never applied. +- Recursive copies stop at 64 directory levels (the remote host controls download depth). +- Control characters in server-supplied file names are replaced before being printed in progress output. + +#### `ziti-ssh proxy` never prompts + +- In `ProxyCommand` mode, `ziti-ssh proxy` no longer offers to generate an SSH key when none is found (the prompt was written into the SSH data stream on stdout); it exits with an error asking for a key or `--key`. + +#### CA key-type allowlist + +- `ziti-ssh-ca` only certifies ed25519, ECDSA (P-256/384/521), the `sk-` security-key variants, and RSA keys of at least 3072 bits. Certificates, DSA keys, shorter RSA keys, and the CA's own key are refused with an `error: …` reply (shown by clients as `CA refused the request: …`). Malformed requests now also get an `error:` reply instead of a silent close. +- **Action:** users with RSA keys shorter than 3072 bits must generate a new key (e.g. `ssh-keygen -t ed25519`). + +#### CA connection limits + +- `ziti-ssh-ca` caps concurrent connections (`--max-connections` / `ZITI_MAX_CONNECTIONS`, default 64); connections beyond the cap are closed immediately. +- The per-identity rate limit is now checked before the request is read and applies to CA public key requests as well as certificate requests. A limited caller receives `error: rate limit exceeded`. +- The per-connection deadline is reduced from 30 s to 10 s. + +#### Optional termination of a user's processes on disconnect + +- New `ziti-ssh-host` setting `ZITI_TERMINATE_ON_DISCONNECT` (default `false`, per-identity mode with `ZITI_USER_CLEANUP=false`). When `true`, everything the account can run is stopped when its last session closes — the account is expired (`usermod -e 1`; re-enabled on the identity's next authorized connection, which is rejected if that fails), its crontab and `at` jobs are removed, lingering is disabled, `loginctl terminate-user`, then SIGTERM/SIGKILL to the account's UID — while the account and home directory are kept. With `ZITI_USER_CLEANUP=true` the same sequence runs before deletion. Also applied at startup to accounts that still had sessions open when the daemon stopped. +- With both settings at their defaults, background processes survive disconnect and identity revocation; the daemon now logs a warning at startup in that configuration. +- `docs/operations.md` revocation section now tabulates the behaviour of each combination. + +#### Per-identity permissions are applied fail-closed (behaviour change) + +- If `ziti-ssh-host` cannot set an account's supplementary groups, remove a legacy sudoers file, or write/remove its sudoers file, the connection is now **rejected** instead of continuing with the account's previous groups and sudoers rule. If a new sudoers rule cannot be installed, the existing file is removed first. Log line: `rejecting connection: could not apply permissions`. +- **Action:** a group named in a `ziti-ssh-host.v1` entry or `ZITI_SSH_GROUPS` that does not exist on the host now blocks that identity's logins on that host. Verify configs with `ziti-ssh-host inspect`. +- When the last session closes with `ZITI_USER_CLEANUP=false`, supplementary groups are cleared as well as the sudoers file (also after a restart following a crash). + +#### OIDC callback server listens on loopback only and refuses an occupied port + +- The temporary OIDC callback server now binds only `127.0.0.1` and `::1` (previously all interfaces), and claims the port before contacting the identity provider. If either address is already in use the flow stops with an error instead of opening the browser. The redirect URI (`http://localhost:/auth/callback`) and default port are unchanged; no identity-provider changes are needed. +- The login URL is printed to stderr before the browser is opened, and failing to launch a browser is no longer fatal (previously `ziti-ssh` exited on headless machines without showing the URL). +- Only the first authorization callback is used; the callback server has a read-header timeout. + +#### Caller identity taken from the edge router (BREAKING) + +`ziti-ssh-ca` and `ziti-ssh-host` now identify each caller only by the dialer identity name that the caller's edge router attaches to the connection (`GetDialerIdentityName()`). The client-supplied caller ID header is no longer used for any decision; if it differs, a warning is logged (`client-supplied caller id does not match router-verified dialer identity`). + +- Connections without a router-supplied dialer identity are rejected (`rejected connection: edge router did not supply a dialer identity (OpenZiti v2.0.0+ routers required)`). In `per-identity` mode, `ziti-ssh-host` closes such connections without proxying them to sshd. +- **Breaking:** the controller and all edge routers must run **OpenZiti v2.0.0 or later**. +- Integration suite (`suites/ziti-ssh/suite.yml`) now runs against OpenZiti v2.0.8. + +**Updated docs:** `ARCHITECTURE.md` §6 (identity flow, with diagram) and §12; `README.md` prerequisites; `docs/provisioning.md` version requirement; `docs/operations.md` new "Caller identity verification" section. + +#### Per-identity account ownership registry + +`ziti-ssh-host` now records the Linux accounts it creates in `/var/lib/ziti-ssh-host/owned-users.json` (username → Ziti identity, UID; mode 0600) and only creates, modifies, or deletes accounts recorded there for the connecting identity with a matching UID ≥ 1000. + +- Existing accounts that `ziti-ssh-host` did not create are not managed; connections deriving their names are rejected. A corrupt registry stops `run` in per-identity mode. +- Two identities that derive the same username are detected across disconnects and restarts. +- Reserved names (`root`, common system accounts, `ubuntu`, `admin`, `ziti`) and names starting with `-` are refused. +- Sudoers files moved to `/etc/sudoers.d/ziti-ssh-host-`; a legacy `/etc/sudoers.d/` is removed only if it contains the single line `ziti-ssh-host` wrote. +- The session count is re-checked before account cleanup when a session is released. +- With cleanup disabled, sudoers files left by sessions open during a crash are removed on restart. +- `ziti-ssh-ca` refuses to sign a per-identity certificate whose derived principal is a reserved account name (the same list the host refuses) or starts with `-`. +- New `ziti-ssh-host users list` and `ziti-ssh-host users claim --username --identity ` (root). + +**Upgrade action required (per-identity hosts with persistent accounts):** accounts created by earlier releases are not in the registry, so their identities are rejected (`refusing to manage pre-existing account`) until claimed with `sudo ziti-ssh-host users claim --username --identity `. This mainly affects hosts with `ZITI_USER_CLEANUP=false` (the default), where accounts persist. With cleanup enabled, accounts are normally deleted at disconnect; an account whose session was still open during the upgrade is left in place (not deleted, since it is unregistered) and must be claimed or removed with `userdel -r` by an administrator. + +**Updated docs:** `docs/operations.md` (account ownership flow diagram, lifecycle, new "Managing account ownership" section, files-written table), `docs/configuration.md` (`users` subcommands, sudoers path), `ARCHITECTURE.md` (`UserManager`, `deleteUser`, §12 account ownership boundary), `CLAUDE.md`. + +### Fixed +#### Permission config changes apply within 30 seconds + +- `ziti-ssh-host run` checks the controller for service changes every 30 s (`ZITI_SERVICE_REFRESH`, minimum 5 s); previously it used the SDK default of 5 minutes, so a changed or reduced `ziti-ssh-host.v1` config could take up to 5 minutes to reach a host although the docs said "within seconds". Each check is a small "anything changed?" request. + +#### Host connection limit and cross-service permission conflicts + +- `ziti-ssh-host run --max-connections` / `ZITI_MAX_CONNECTIONS` (default 128) caps concurrent connections per service; further connections are closed immediately and logged at most every 10 s. Previously accepts were unbounded. +- Per-identity mode: a Linux account has one set of groups and one sudoers file. While an identity has sessions open through one service, a connection through a different service that resolves to different permissions is now **rejected** instead of replacing the permissions of the open sessions (the previous docs incorrectly said the first connection's permissions were kept). The same service always applies the current config; a different service with identical permissions is allowed. + +#### Controller URL lists validated + +- Controller URL lists pushed by the controller are filtered before use: entries must be `https` with a host and no user info, query or fragment; others are logged and dropped, and duplicates removed. This applies before `ziti-ssh-host` fetches CA keys and before any binary saves the list to its identity file. +- The identity file is no longer rewritten when the controller list has not changed. + +#### Certificate serials and clock-skew tolerance + +- Each certificate carries a random 64-bit serial (was always 0). `ziti-ssh-ca` logs it when issuing (`serial=`) and sshd logs it at login, so a login can be traced to its issuance. +- Certificates are valid from 60 seconds before signing, so an SSH host whose clock is slightly behind the CA's accepts a new certificate. Expiry is unchanged (signing time + `--cert-ttl`). + +#### Derived usernames fold ASCII case only (behaviour change) + +- `ca.DeriveUsername` lowercases only `A`–`Z`; every other non-`[a-z0-9_-]` character becomes `_`. Previously Unicode case folding mapped some non-ASCII letters to ASCII (the Kelvin sign to `k`, `İ` to `i`), so a lookalike identity name could derive another identity's username. Only identity names containing such characters derive a different name; upgrade `ziti-ssh-ca` and `ziti-ssh-host` together. + +#### Permission key matching (behaviour change) + +- `ziti-ssh-host.v1` permission keys are matched by `host.MatchPattern`: `*` matches any run of characters including `/`, `?` one character, everything else literally. Previously `path.Match` was used, where `*` stopped at `/` (so `"*"` did not match identity names containing `/`), `[…]` was a character class and `\` an escape. Keys containing `[` or `\` are flagged in the log and by `inspect`. +- Patterns of equal specificity are now ordered by the pattern string, so which entry applies no longer depends on map iteration order. + +#### Client key and file checks + +- When `ziti-ssh` generates a key it no longer passes an empty passphrase: `ssh-keygen` asks for one (Enter for none). +- A passphrase-protected key that no SSH agent holds is unlocked by asking for the passphrase on the terminal, instead of failing (`client.NewCertSignerPrompt`). +- `config.yaml` and the Ziti `known_hosts` file are refused if writable by others, writable by a shared group, or owned by another user (`config.CheckUserFile`), as OpenSSH does for its client config. Group write is accepted when the group is the owner's private group (Debian/Ubuntu default umask 002). + +#### MFA codes asked for by every client command + +- `ziti-ssh connect/sign/proxy/list` and `ziti-scp` now ask for an MFA TOTP code when the controller requires one; previously only the `mfa` subcommands did, so other commands could not authenticate an MFA-enrolled identity. Codes are read from the terminal (`/dev/tty`) without echo — never from stdin — and authentication stops after three wrong codes or at end of input (the `mfa` prompt previously looped forever on closed stdin). Shared code in `internal/mfa`. + +#### SOCKS5 proxy method negotiation + +- `ziti-ssh -D` replies "no acceptable methods" (`0xFF`) and closes when a SOCKS5 client does not offer the no-authentication method, as RFC 1928 requires; previously it always selected no-authentication. + +#### Client target parsing + +- `ziti-ssh` and `ziti-scp` split `[user@]target` at the last `@` (as OpenSSH does); previously `a@b@web1` targeted `b@web1`. +- Without `user@`, `ziti-ssh connect` and `ziti-scp` use the certificate's principal as the SSH user when it has exactly one (in per-identity mode, the identity's derived Linux username), instead of the local user name. Per-identity users can run `ziti-ssh web1`; an explicit user must be the derived name (`alice_corp_com`), not the identity name. +- `ziti-scp` treats an argument as remote only if it contains `:` with no `/` before it, matching `scp`. Previously `/data/a:b`, `./a:b` and `dir/a:b` were taken as remote host specifications. +- `ziti-ssh -L/-R/-D` accept bracketed IPv6 addresses (`-L [::1]:8080:[2001:db8::1]:80`) and reject ports outside 1–65535; previously IPv6 specs were mis-split on `:`. A warning is printed when a `-L` or `-D` listener binds to a non-loopback address, since the listener has no authentication of its own. +- `ziti-scp --service ` (as in `ziti-ssh`) treats the remote host as a terminator address on `` even when the host name is also a service name. + + +#### `ziti-ssh-host` did not reload a running sshd on socket-activated systems + +`host.ReloadSSHD` (used by `enroll` and by `run` when the CA key set changes) treated an active `ssh.socket` as "each connection starts a fresh sshd" and skipped both `systemctl reload ssh` and the SIGHUP to leftover sshd listeners. On Ubuntu 22.10+ `ssh.socket` uses `Accept=no`: the first connection starts a long-running `ssh.service`, which then serves all connections with the configuration it started with. On any host where sshd was already running when `enroll` wrote `TrustedUserCAKeys` — for example after an administrator had logged in — certificate logins failed until sshd was restarted. + +- `ReloadSSHD` now reloads `ssh.service` whenever it is active and sends SIGHUP to top-level sshd listeners (PPID 1) unless `ssh.socket` uses `Accept=yes` (where per-connection sshd processes also have PPID 1). The decision is unit-tested (`planSSHDReload`). +- Integration suite: `install-ca.sh` no longer reports `ziti-ssh-ca` as running when its first start fails because the `ssh-ca` service has not been created yet; systemd restarts it until the service exists. +- Integration suite: `install-host.sh` no longer fails provisioning when `ziti-ssh-host` first exits with `service 'ssh' not found` (the service is created only after all edge routers are online); systemd restarts it until the service exists. Any other startup failure is still fatal. + +#### Clients re-signed a certificate on every invocation and saved CA error replies as certificates + +`ziti-ssh` and `ziti-scp` refreshed a certificate when fewer than 5 minutes of validity remained — which, with the CA's default 5-minute TTL, was always true. Every invocation requested a new certificate, so a fourth call within a few seconds exceeded the CA's default rate limit (5/min, burst 3). The CA's `error: rate limit exceeded` reply was then written to `-cert.pub` as if it were a certificate, overwriting a valid one, and the login failed with `unable to authenticate`. + +- A certificate is now refreshed when less than 20% of its lifetime remains, between 30 seconds and 5 minutes (1 minute for a 5-minute certificate; unchanged for certificates of 25 minutes or longer). +- The CA reply is read with a 16 KiB limit and validated before it is written: an `error: …` reply is reported as `CA refused the request: `, and anything other than a user certificate for the caller's own public key is rejected. The existing certificate file is left untouched on failure. +- Docs no longer state an 8-hour default TTL (`ARCHITECTURE.md`, `docs/usage.md`, `docs/operations.md`). + +#### Per-identity hardening follow-ups + +- `ziti-ssh-host`: a connection rejected by the ownership check (e.g. two identities deriving the same username) is no longer counted as a session while it is being checked; previously it could make the owner's final disconnect skip sudoers removal and account cleanup. +- `ziti-ssh-host`: `sudoers_rule` (and `ZITI_SUDOERS_RULE`) values starting with `,` — which would add users to the rule, e.g. `, ALL ALL=(ALL) NOPASSWD: ALL` — are rejected, as are values containing NUL bytes or lacking `=`. +- `ziti-ssh-host run`: at startup, legacy `/etc/sudoers.d/` files are removed for registered accounts; legacy-format files for unregistered accounts are reported (log warning and `ziti-ssh-host users list`) but never removed automatically. +- `docs/operations.md`: revocation section corrected — with `ZITI_USER_CLEANUP=false` (default) the account and its processes are kept after the last session closes. + +#### `ziti-ssh-ca` package runs as the controller's service user + +- The postinstall script detects the Ziti controller's service user (from `ziti-controller.service`, otherwise the owner of a running `ziti controller run` process) and writes the systemd drop-in `/etc/systemd/system/ziti-ssh-ca.service.d/10-controller-user.conf`. The `openziti-controller` v2 package runs the controller as `ziti-controller`, so the unit's fixed `User=ziti` left the CA unable to read the intermediate key there. Administrator overrides that set `User=` are left unchanged; if no controller is detected, instructions are printed. +- `/etc/ziti-ssh-ca` is now owned by the service user (mode 0750) so controller URL updates can be saved to the identity file. + +### Changed + +#### `ziti-ssh-ca config`: controller trust and password handling + +- Controller TLS trust works like `ziti edge login`: if the system CAs do not trust the controller, its CA bundle is fetched from `/.well-known/est/cacerts`, the controller's certificate is verified against it, the CAs are shown and the user is asked to trust them (`--yes` for scripts). The bundle is saved under `$XDG_CONFIG_HOME/ziti-ssh/controllers/` and reused. A changed CA is refused unless confirmed interactively (`--yes` never replaces it). `--insecure` remains but warns. +- The admin password can come from `--password-file `, `ZITI_CTRL_PASSWORD_FILE`, `ZITI_CTRL_PASSWORD`, or a hidden prompt. `--password` still works but warns that it is visible in the process list and shell history. + +#### Packages install to `/usr/bin`; remove/purge scripts (behaviour change) + +- All four packages install their binary to `/usr/bin` instead of `/usr/local/bin` (reserved for locally installed software); the systemd units are updated. Upgrades move the binary automatically; update any scripts or custom units that hard-code `/usr/local/bin/ziti-ssh*`. +- `ziti-ssh-ca` and `ziti-ssh-host` stop and disable their service on removal (not on upgrade). +- `apt purge ziti-ssh-host` removes the sshd drop-in and `/etc/ssh/ziti_ca.pub` and reloads sshd, so the host stops trusting the CA; identities, env files, the ownership registry and Linux accounts are kept. `apt purge ziti-ssh-ca` removes its managed systemd drop-in. rpm has no purge — see `docs/provisioning.md` (Uninstalling). + +#### Release checksums and build provenance + +- Tagged releases attach `SHA256SUMS` (every `.deb` and `.rpm`) to the GitHub release and publish a GitHub build provenance attestation for each package (`actions/attest-build-provenance`). Verify with `sha256sum --check` or `gh attestation verify --repo netfoundry/ziti-ssh`; see `docs/building.md` (Verifying packages). Repository installs are unchanged (signed repository index). + +#### Docker package build + +- Added `.dockerignore` so the build context excludes `.git`, `dist/`, local binaries, `*.jwt`, `*.json` (identity files), key material and local security notes (previously `COPY . .` could copy an enrollment JWT into the image). +- `scripts/Dockerfile.packages` pins `golang:1.26-bookworm` by digest; Dependabot now also tracks the Docker base image. +- `scripts/build-packages.sh` no longer installs nfpm with `go install` (nfpm v2.49.0 needs Go ≥ 1.27.4, so the Docker build and machines without nfpm failed); when nfpm is not on `PATH` it downloads the pinned release binary, verifies it against the release checksums, and uses it for that run only — as the release workflow does. + +#### Documentation and cleanup + +- The CA key is described correctly as the controller's intermediate CA key (RSA, ECDSA or Ed25519; RSA on stock controllers), not "Ed25519". +- Removed the unused `scripts/build-deb.sh`; packages are built with `scripts/build-packages.sh` (nfpm). + +#### Dependency, toolchain, and CI refresh + +- `github.com/openziti/sdk-golang` moved from v1.9.0 to **v1.8.4**. v1.9.0 was retracted upstream ("published from main before the module moved to `github.com/openziti/sdk-golang/v2`; the supported v1 line is 1.8.x"). +- Direct dependencies updated: `edge-api` v0.36.1, `go-openapi/runtime` v0.33.5, `go-openapi/strfmt` v0.27.4, `pkg/sftp` v1.13.12, `zitadel/oidc/v3` v3.52.0, `go.yaml.in/yaml/v3` v3.0.6, `x/crypto` v0.59.0, `x/term` v0.48.0, `x/time` v0.16.0. +- `go.mod` now declares `go 1.26.0` (required by sdk-golang) and `toolchain go1.26.11`. `actions/setup-go` v6+ honours the `toolchain` directive, so release binaries are built with a patched standard library; previously `setup-go@v5` installed exactly the `go` directive version (1.25.0). +- CI vulnerability scan runs `govulncheck` (pinned, `go run golang.org/x/vuln/cmd/govulncheck@v1.9.0`) with the release toolchain from `go.mod` instead of `govulncheck-action`, whose bundled setup-go scanned with `stable` or the `go` directive (1.26.0) rather than the toolchain that builds releases. +- GitHub Actions updated and pinned to commit SHAs: `checkout` v7.0.1, `setup-go` v7.1.0, `upload-artifact` v7.0.2, `setup-jfrog-cli` v5.3.5, `action-gh-release` v3.0.4. `FORCE_JAVASCRIPT_ACTIONS_TO_NODE24` removed (all actions now run on Node 24 natively). +- `ci.yml`, `ziti-test.yml` and `promote.yml` declare `permissions: contents: read` at the top level; jobs add only what they need (`id-token: write` for AWS / Artifactory OIDC, `attestations: write` for provenance). +- `ziti-test.yml` runs two suites (matrix): `suites/ziti-ssh` (shared mode) and the new `suites/ziti-ssh-per-identity` (per-identity accounts, grant policy, config reload, revocation), each on its own stack. +- `ziti-test.yml` calls the `ziti-test-suite` reusable workflow at a pinned commit and checks out the suite code at the same commit (was `@main`). +- Default tool versions: nfpm 2.49.0 (prerelease download now verified against the release `checksums.txt`; `build-packages.sh` fallback pinned instead of `@latest`), jfrog-cli 2.133.0. +- `ziti-test.yml` builds packages with `build-packages.sh` (same nfpm path as releases) instead of `build-deb.sh`; `suites/ziti-ssh/suite.yml` paths updated to the nfpm filenames (`_0.0.0-1_amd64.deb`). +- `scripts/Dockerfile.packages` base image moved to `golang:1.26-bookworm`. +- Added `.github/dependabot.yml` (weekly `gomod` and `github-actions` updates, minor/patch grouped). + +--- + ## [Unreleased] - 2026-04-14 ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 527e74c..01e5f18 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,7 +18,7 @@ Four cooperating binaries: 2. **`ziti-ssh-host`** — a host daemon that enrolls the host into a Ziti network, configures sshd to trust the CA, and proxies Ziti connections to the local sshd. In `per-identity` mode, creates ephemeral Linux users and applies per-identity permissions (groups, sudoers rules) sourced from a `ziti-ssh-host.v1` config attached to the Ziti service. A single instance can bind to multiple Ziti services simultaneously, each with independent permissions. -3. **`ziti-ssh`** — a full SSH client over OpenZiti. Subcommands: `connect` (default), `sign`, `enroll`, `list`, `mfa`. Obtains and caches SSH certificates from the CA; auto-refreshes when fewer than 5 minutes of validity remain. +3. **`ziti-ssh`** — a full SSH client over OpenZiti. Subcommands: `connect` (default), `sign`, `enroll`, `list`, `mfa`. Obtains and caches SSH certificates from the CA; auto-refreshes when less than 20% of its lifetime remains (between 30 s and 5 min — 1 minute for the default 5-minute certificate); validates the CA reply (rejects `error:` replies and certs for another key) before writing it. 4. **`ziti-scp`** — a file copy tool over OpenZiti. Uses the SFTP subsystem over the same Ziti overlay. Mirrors `scp(1)` behaviour: upload, download, recursive directory copy, preserve mode. Shares the same identity, certificate, config infrastructure, and cert auto-refresh logic as `ziti-ssh`. @@ -65,6 +65,8 @@ The Ziti network proves the caller's identity through mutual TLS. The same Ziti - Authorizes host access (dial policy on the per-host `ssh` service) - Is embedded in the cert Key ID for audit trail +The caller's name is read **only** from `GetDialerIdentityName()` (set by the dialer's edge router; requires OpenZiti v2.0.0+). Never use `SourceIdentifier()` (the client-supplied `CallerId` header) for any authorization decision — a modified client can set it to anything. Connections with no dialer identity are rejected. + ### Ziti service policy IS the access control Any Ziti identity that can dial the `ssh-ca` service is authorized to receive a cert. Any Ziti identity that can dial the `ssh` service terminator for a given host is authorized to reach that host. Access control is managed entirely through Ziti service policies. @@ -72,12 +74,12 @@ Any Ziti identity that can dial the `ssh-ca` service is authorized to receive a Per-identity Linux permissions (groups, sudoers rules) are stored as a `ziti-ssh-host.v1` config attached to the Ziti service. The service boundary is therefore the permission scope boundary — the same boundary already used for access control. Different services can carry different permission sets, enabling role-tiered deployments where, for example, DB admins and ops teams can both reach a database host but with different Linux permissions. ### Short-lived certificates (5m TTL) -Certificates expire after 8 hours. No revocation infrastructure needed — compromised or removed identities lose access at expiry without any intervention on SSH hosts. +Certificates expire after 5 minutes by default (`--cert-ttl`). No revocation infrastructure needed — compromised or removed identities lose access at expiry without any intervention on SSH hosts. ### `ziti-ssh` and `ziti-scp` as client tools `ziti-ssh` is the interactive client. It handles Ziti dialing, SSH certificate management, and interactive SSH sessions. The `sign` subcommand fetches certs from the CA; the `connect` subcommand (default) auto-refreshes the cert if needed and then opens an SSH session. The `enroll`, `list`, and `mfa` subcommands cover the full Ziti identity lifecycle on user machines. -`ziti-scp` is the file copy companion. It uses the same identity, cert, and config infrastructure as `ziti-ssh` but opens an SFTP subsystem session instead of an interactive shell. The same cert auto-refresh logic applies (30-minute threshold), and the same Ziti service resolution (direct service name vs. terminator address on `--ssh-service`) is used. +`ziti-scp` is the file copy companion. It uses the same identity, cert, and config infrastructure as `ziti-ssh` but opens an SFTP subsystem session instead of an interactive shell. The same cert auto-refresh logic applies (`client.CertNeedsRefresh`), and the same Ziti service resolution (direct service name vs. terminator address on `--ssh-service`) is used. ### Addressable terminators for host routing Each `ziti-ssh-host` instance listens on a Ziti service with its identity name as the terminator address. `ziti-ssh` dials the service specifying the target identity name — no hostname resolution, no config file required. @@ -89,21 +91,21 @@ Each `ziti-ssh-host` instance listens on a Ziti service with its identity name a Seven subcommands: **`connect [user@]`** (also the default when a bare argument is given): -- Auto-refreshes the SSH cert if missing or expiring within 5 min. +- Auto-refreshes the SSH cert if missing or less than 20% of its lifetime remains (between 30 s and 5 min — 1 minute for the default 5-minute certificate). - Resolves whether the target is a direct Ziti service name or a terminator address on `--ssh-service`. - Uses `ziti.DialOptions{Identity: terminatorAddr}` when dialling via a terminator. - Wraps the private key and cert into an `ssh.CertSigner` via `client.NewCertSigner`. Falls back to `SSH_AUTH_SOCK` if the private key is passphrase-protected. - Runs a full interactive PTY session via `client.RunSession` (no forwards) or via `client.NewSSHClient` + `runSSHClientSession` when `-L`/`-R`/`-D` forwards are active. -- `-A` / `--forward-agent` — forward the local SSH agent to the remote session; calls `client.ForwardAgent(sshClient, session)` before `session.Shell()`; non-fatal if `SSH_AUTH_SOCK` is unset or agent unreachable. +- `-A` / `--forward-agent` — forward the local SSH agent to the remote session; refused unless `--forward-agent-unverified` is also given (`checkAgentForwarding`: hosts cannot yet be verified, see H8) and the CA grants `permit-agent-forwarding`; calls `client.ForwardAgent(sshClient, session)` before `session.Shell()`; non-fatal if `SSH_AUTH_SOCK` is unset or agent unreachable. - Accepts a trailing command (after `--`) for non-interactive execution via `client.RunCommand`; the remote exit code is propagated. -- `-L [bind:]localport:remotehost:remoteport` — local port forward; may be repeated; calls `client.RunLocalForward` in a goroutine. +- `-L [bind:]localport:remotehost:remoteport` — local port forward; may be repeated; calls `client.RunLocalForward` in a goroutine. Specs are split by `splitForwardSpec` (bracketed IPv6, ports 1–65535); non-loopback `-L`/`-D` binds print a warning (`warnNonLoopbackBind`). - `-R [bind:]remoteport:localhost:localport` — remote port forward; calls `client.RunRemoteForward` in a goroutine. - `-D [bind:]port` — dynamic SOCKS5 proxy; calls `client.RunDynamicProxy` in a goroutine. - `-N` / `--no-shell` — block without opening a shell; only runs the requested forwards until SIGINT/SIGTERM. - When any forward is present: all forwards + (optionally) the shell session run concurrently under a shared `context.Context`; SIGINT/SIGTERM cancels the context and tears everything down. **`proxy [user@]`**: -- Auto-refreshes the SSH cert (same 5-minute threshold as `connect`). +- Auto-refreshes the SSH cert (same threshold as `connect`). - Dials the Ziti service raw — no SSH handshake performed by `ziti-ssh`. - Bridges `os.Stdin` ↔ conn and conn → `os.Stdout` via `io.Copy` in two goroutines; returns when either direction closes. - Intended as a `ProxyCommand` in `~/.ssh/config` so that standard tools (`ssh`, `git`, `rsync`, VS Code Remote) work through the Ziti overlay without modification. @@ -115,29 +117,36 @@ Seven subcommands: **`list`**: Calls `ctx.GetServices()` and prints each service name and permissions. +**`known-hosts list|remove
`**: shows or forgets remembered SSH host keys (`client.KnownHosts`). + **`mfa enable/verify/remove`**: Uses `zitiCtx.EnrollZitiMfa`, `VerifyZitiMfa`, `RemoveZitiMfa` with `AddMfaTotpCodeListener` / `AddAuthenticationStateFullListener` event hooks. -**OIDC authentication**: When `--oidc-issuer` is set (or `oidc.issuer` in the config file), `connect`, `sign`, and `proxy` perform a browser-based OIDC authorization code flow (PKCE when no client secret) before authenticating with Ziti. The resulting JWT is added to the Ziti context via `AddJWT()`, satisfying ext-jwt-signer policies on the controller. Flow times out after 2 minutes. Implemented in `cmd/ziti-ssh/oidc.go` and `internal/oidc/oidc.go`. +**MFA during authentication** (`internal/mfa`): every authenticating command (`connect`, `sign`, `proxy`, `list`, `ziti-scp`) calls `mfa.RegisterTTY` before `Authenticate`, so `EventMfaTotpCode` is answered from `/dev/tty` (hidden; never stdin; 3 attempts; stops at EOF). The SDK emits it synchronously, so typing counts against `--ziti-timeout`. The `mfa` subcommands read stdin via `mfa.NewReader`. + +**OIDC authentication**: When `--oidc-issuer` is set (or `oidc.issuer` in the config file), `connect`, `sign`, and `proxy` perform a browser-based OIDC authorization code flow (PKCE when no client secret) before authenticating with Ziti. The resulting JWT is added to the Ziti context via `AddJWT()`, satisfying ext-jwt-signer policies on the controller. Flow times out after 2 minutes. The callback port is claimed on loopback only (`127.0.0.1` and `::1`) before the IdP is contacted, and the flow aborts if either address is already in use (`listenLoopback`); the login URL is printed to stderr before a non-fatal browser launch. Implemented in `cmd/ziti-ssh/oidc.go` and `internal/oidc/oidc.go`. Config file at `~/.config/ziti-ssh/config.yaml` (XDG_CONFIG_HOME respected). Fields: `identity`, `ca_service`, `ssh_service`, `ssh_key_path`, `mode`, `oidc.*`. Three-tier precedence: CLI flag > config file > default. ### SSH Session / SFTP Library (`client/ssh.go`, `client/sftp.go`) -- `NewCertSigner(keyPath string) (ssh.Signer, error)` — loads key and cert; returns `ssh.CertSigner` if cert present. -- `CertNeedsRefresh(certPath string) bool` — true if cert absent or expires within 5 min. -- `NewSSHClient(conn net.Conn, user, host string, signer ssh.Signer) (*ssh.Client, error)` — performs the SSH handshake and returns a raw `*ssh.Client` for forwarding use cases. -- `RunSession(conn net.Conn, user, host string, signer ssh.Signer, forwardAgent bool) error` — PTY SSH session over an existing `net.Conn`; when `forwardAgent` is true, calls `ForwardAgent` before `session.Shell()`. +- `NewCertSigner(keyPath string) (ssh.Signer, error)` — loads key and cert; returns `ssh.CertSigner` if cert present. `NewCertSignerPrompt(keyPath, prompt)` additionally asks for the passphrase (`TTYPassphrasePrompt`, `/dev/tty`) when the key is encrypted and no agent holds it; `connect` and `ziti-scp` use it. +- `config.CheckUserFile(path)` — refuses `config.yaml` / `known_hosts` that are world-writable, group-writable by a shared group (the owner's private group — Debian/Ubuntu umask 002 — is accepted, as in OpenSSH), or owned by another user. +- `CertNeedsRefresh(certPath string) bool` — true if cert absent or less than 20% of its lifetime remains (between 30 s and 5 min — 1 minute for the default 5-minute certificate). +- `ReadCAResponse(r) (string, error)` / `ValidateSignedCert(line, pubKeyLine) ([]byte, error)` (`client/certs.go`) — bounded read of the CA reply; returns `*CARejectedError` for `error: …` replies and rejects anything but a user cert for the caller's key, so a bad reply never overwrites a valid cert. +- `NewSSHClient(conn net.Conn, user, host string, signer ssh.Signer, hostKeyCallback ssh.HostKeyCallback) (*ssh.Client, error)` — performs the SSH handshake and returns a raw `*ssh.Client` for forwarding use cases. +- `RunSession(conn net.Conn, user, host string, signer ssh.Signer, forwardAgent bool, hostKeyCallback ssh.HostKeyCallback) error` — PTY SSH session over an existing `net.Conn`; when `forwardAgent` is true, calls `ForwardAgent` before `session.Shell()`. - `ForwardAgent(sshClient *ssh.Client, session *ssh.Session) error` — connects to `SSH_AUTH_SOCK`, calls `agent.ForwardToAgent` on the client and `agent.RequestAgentForwarding` on the session; returns an error (non-fatal by convention) if `SSH_AUTH_SOCK` is unset or agent is unreachable. -- `RunCommand(conn net.Conn, user, host, cmd string, signer ssh.Signer) error` — non-interactive command execution; propagates remote exit code via `os.Exit`. +- `RunCommand(conn net.Conn, user, host, cmd string, signer ssh.Signer, hostKeyCallback ssh.HostKeyCallback) error` — non-interactive command execution; propagates remote exit code via `os.Exit`. - `RunLocalForward(ctx, sshClient, LocalForwardSpec) error` — local port forward (-L); listens locally, tunnels via `direct-tcpip`; runs until ctx cancelled. - `RunRemoteForward(ctx, sshClient, RemoteForwardSpec) error` — remote port forward (-R); uses `sshClient.Listen`; runs until ctx cancelled. - `RunDynamicProxy(ctx, sshClient, DynamicForwardSpec) error` — SOCKS5 proxy (-D); implements RFC 1928 CONNECT with no-auth; runs until ctx cancelled. -- `RunSFTP(conn, user, host, signer, isUpload, localPaths, remotePath, recursive, preserve, quiet) error` — SFTP file copy over an existing `net.Conn`; uses `github.com/pkg/sftp`. +- `NewHostKeyCallback(service, terminator string) (ssh.HostKeyCallback, error)` (`client/hostkeys.go`) — trust-on-first-use host keys in `~/.config/ziti-ssh/known_hosts`, keyed by Ziti address (`@`, or `` for a direct service dial). Terminator address: a changed key is refused. Direct service dial (any bound host may answer): the user is asked to trust an additional key (refused without a terminal). Replaces `InsecureIgnoreHostKey`; OpenZiti cannot tell the dialer which identity answered (H8). +- `RunSFTP(conn, user, host, signer, isUpload, localPaths, remotePath, recursive, preserve, quiet, hostKeyCallback) error` — SFTP file copy over an existing `net.Conn`; uses `github.com/pkg/sftp`. ### File Copy Tool (`ziti-scp`) -- Parses `[user@]host:path` remote specs and bare local paths from positional arguments (last arg is destination). -- Same cert auto-refresh (5-minute threshold) and Ziti dial logic as `ziti-ssh`. +- Parses `[user@]host:path` remote specs and bare local paths from positional arguments (last arg is destination). Remote only if a `:` has no `/` before it (scp semantics); user split at the last `@` (also `ziti-ssh`'s `parseTarget`). `--service ` forces terminator addressing (as in `ziti-ssh`). +- Same cert auto-refresh threshold and Ziti dial logic as `ziti-ssh`. - Flags: `-r` (recursive), `-p` (preserve timestamps/permissions), `-q` (quiet). - `enroll` subcommand for identity enrollment (mirrors `ziti-ssh enroll`). - Shared config file: `~/.config/ziti-ssh/config.yaml`. @@ -156,7 +165,9 @@ Three modes of operation: a long-running service, a one-shot `enroll` command, a - If the request body is empty, returns the CA public key instead (used by hosts during enrollment) - Embeds the Ziti identity name as the certificate Key ID (for audit logging) - Issues certs with a configurable principal (default: `ziggy`) and 5m validity -- Enforces a per-identity token-bucket rate limit (default: 5 req/min, burst 3) +- Enforces a per-identity token-bucket rate limit (default: 5 req/min, burst 3) on every request, checked before the request is read +- Caps concurrent connections (`--max-connections`, default 64); further connections are closed immediately +- Only certifies ed25519, ECDSA (P-256/384/521), `sk-` security-key variants, and RSA ≥ 3072 bits (`ca.ValidateClientKey`); refuses certificates, DSA, short RSA and its own key with an `error:` reply **`enroll` subcommand** — enrolls the CA server's Ziti identity from a one-time JWT file. Writes the identity JSON to `/etc/ziti-ssh-ca/identity.json` (mode 0600) by default; `--out` overrides the path. No CA-specific post-enrollment steps needed. @@ -166,11 +177,11 @@ Three modes of operation: a long-running service, a one-shot `enroll` command, a - `config apply` — idempotent install-or-update of the `ziti-ssh-host.v1` config type: checks whether it exists, then creates or replaces it. - `config remove` — removes the `ziti-ssh-host.v1` config type if present. -Flags: `--controller ` (default port 443), `--username`, `--password`, `--insecure` (skip TLS verify), `--controller-ca ` (trust a specific CA cert). All have env var equivalents (`ZITI_CTRL_ADDRESS`, `ZITI_CTRL_USERNAME`, `ZITI_CTRL_PASSWORD`, `ZITI_CTRL_INSECURE`, `ZITI_CTRL_CA`). `--insecure` and `--controller-ca` are mutually exclusive. +Flags: `--controller ` (default port 443), `--username`, `--password` (warns; prefer `--password-file`, env, or the hidden prompt), `--password-file `, `--yes`, `--insecure` (skip TLS verify; warns), `--controller-ca ` (trust a specific CA cert). Controller TLS trust (`cmd/ziti-ssh-ca/ctrltrust.go`) mirrors `ziti edge login`: `--controller-ca` → saved bundle (`$XDG_CONFIG_HOME/ziti-ssh/controllers/_.pem`) → system roots → fetch `/.well-known/est/cacerts`, verify the server against it, confirm (or `--yes`) and save; a changed CA is refused unless confirmed interactively (`--yes` never replaces). All have env var equivalents (`ZITI_CTRL_ADDRESS`, `ZITI_CTRL_USERNAME`, `ZITI_CTRL_PASSWORD`, `ZITI_CTRL_INSECURE`, `ZITI_CTRL_CA`). `--insecure` and `--controller-ca` are mutually exclusive. ### Host Daemon (`ziti-ssh-host`) -Three subcommands: +Four subcommands: **`enroll --jwt `:** 1. Enrolls the host Ziti identity from a JWT token @@ -181,12 +192,12 @@ Three subcommands: **`run`:** 1. Initializes Ziti context from the identity file; declares `ziti-ssh-host.v1` as a requested config type so the controller delivers it with the service detail -2. Subscribes to `EventControllerUrlsUpdated` before authenticating; when the controller cluster membership changes: (a) persists the updated controller URL list to the identity JSON via `config.PersistZtAPIs`, and (b) fetches CA public keys from the new set of controllers and rewrites `TrustedUserCAKeys` + reloads sshd if the set changed. All four binaries call `PersistZtAPIs` on this event so the identity file always reflects the live cluster membership. +2. Subscribes to `EventControllerUrlsUpdated` before authenticating; when the controller cluster membership changes: (a) persists the updated controller URL list to the identity JSON via `config.PersistZtAPIs`, and (b) fetches CA public keys from the new set of controllers and rewrites `TrustedUserCAKeys` + reloads sshd if the set changed. All four binaries call `PersistZtAPIs` on this event so the identity file always reflects the live cluster membership. Entries must pass `config.CheckControllerURL` (https, host, no userinfo/query/fragment); `FilterControllerURLs` drops the rest (also before CA-key refresh), dedupes, and an unchanged list is not rewritten. 3. Accepts one or more `--ssh-service` values (flag may be repeated; `ZITI_SSH_SERVICE` accepts comma-separated list; defaults to `ssh`) 4. For each service: opens a separate Ziti listener, loads and parses the `ziti-ssh-host.v1` config, builds independent `ProxyHooks` carrying that service's permission map 5. Proxies incoming connections to `127.0.0.1:22` -6. In `per-identity` mode: on connect, creates an ephemeral Linux user and applies the resolved permissions (groups via `usermod -aG`, sudoers rule via `/etc/sudoers.d/`); on disconnect, decrements the session ref-count and deletes the user when the last session closes -7. Subscribes to service-changed events and reloads each service's `ziti-ssh-host.v1` config atomically when it changes — no restart needed +6. In `per-identity` mode: on connect, creates an ephemeral Linux user and applies the resolved permissions (groups via `usermod -G`, sudoers rule via `/etc/sudoers.d/ziti-ssh-host-`); only accounts in the ownership registry are ever touched; on disconnect, decrements the session ref-count and deletes the user when the last session closes +7. Subscribes to service-changed events and reloads each service's `ziti-ssh-host.v1` config atomically when it changes — no restart needed; if a config cannot be loaded or parsed (at startup or on reload), per-identity connections on that service are rejected until a valid config loads (`serviceState.update/current`) **`inspect [--service ]...`:** - Authenticates with the host identity; no listeners opened @@ -194,6 +205,10 @@ Three subcommands: - Also prints the global fallback values (`ZITI_SSH_GROUPS`, `ZITI_SUDOERS_RULE`) alongside each service block - Useful for verifying configuration before putting a host into service or after a config change +**`users list` / `users claim --username --identity `** (root; no Ziti connection): +- `list` prints the per-identity account ownership registry with each account's current status +- `claim` registers an existing account (UID ≥ 1000, username == `ca.DeriveUsername(identity)`) as owned by an identity — the migration path for accounts created before the registry existed + ## Per-Identity Permissions (`ziti-ssh-host.v1`) In `per-identity` mode, Linux permissions for each connecting identity are resolved from two sources in order: @@ -211,11 +226,13 @@ In `per-identity` mode, Linux permissions for each connecting identity are resol } ``` + The `docker` group and the `sudoers_rule` entries above are applied only if the host opts the service in (`ZITI_ALLOW_GROUPS=:docker`, `ZITI_ALLOW_SUDOERS=`); see **Host grant policy** below. + 2. **Global fallbacks** (apply when no config is attached, or when no config key matches the identity): - `ZITI_SSH_GROUPS` — comma-separated Linux group names - `ZITI_SUDOERS_RULE` — sudoers rule fragment -**Resolution order:** (1) exact key match; (2) most-specific glob pattern (longest literal prefix before the first wildcard wins); (3) `"*"` catch-all; (4) global fallbacks. Any matched config entry is the complete permission specification — global fallbacks are not merged in. The `"*"` catch-all is preferred over env var fallbacks because it lives in the Ziti config and propagates live without restarting hosts. +**Resolution order:** (1) exact key match; (2) most-specific glob pattern (longest literal prefix before the first wildcard wins, then most literals, then lexically smallest pattern); (3) `"*"` catch-all; (4) global fallbacks. Patterns use `host.MatchPattern`: `*` any run (incl. `/`), `?` one character, all else literal (`[`/`\` keys flagged by `PermissionsConfig.PatternWarnings`). Any matched config entry is the complete permission specification — global fallbacks are not merged in. The `"*"` catch-all is preferred over env var fallbacks because it lives in the Ziti config and propagates live without restarting hosts. **Scope:** the `ziti-ssh-host.v1` config is attached to a specific Ziti service. Because a host can bind to multiple services simultaneously, different permission sets can apply to the same physical host depending on which service a caller dials. This enables role-tiered deployments: @@ -224,15 +241,20 @@ DB server running: ziti-ssh-host run --ssh-service ssh-ops --ssh-service ssh-db ssh-ops config: ops-alice → [sudo, adm] ← ops team, OS-level access ssh-db config: dba-carol → [mysql] ← DBA team, database-level access + +host env: ZITI_ALLOW_GROUPS=ssh-ops:sudo ← host owner lets only ssh-ops grant sudo ``` -**Config type registration:** `ziti-ssh-ca config apply` registers the `ziti-ssh-host.v1` schema on the controller as a one-time setup step. Subsequent `ziti edge update config` commands update individual permission configs; changes propagate live to all running `ziti-ssh-host` instances within seconds. +**Host grant policy (`host.GrantPolicy`, `host/grant.go`):** the host owner limits, per service, what a config may grant: `ZITI_ALLOW_SUDOERS` (services whose config may set `sudoers_rule`; default none), `ZITI_ALLOW_GROUPS` (`:` opt-ins for privileged groups `root`, `sudo`, `admin`, `wheel`, `docker`, `lxd`, `disk`, `shadow`, `libvirt`; any other group is allowed by default), `ZITI_RESTRICT_GROUPS=true` (only listed groups). Refused entries reject the connection (`GrantPolicy.Enforce` in the connect hook), are logged at config load/reload, and are flagged by `inspect`. The host's own fallbacks (`ZITI_SSH_GROUPS`, `ZITI_SUDOERS_RULE`) are not subject to it (`ResolveWithSource`). Controller config write access alone therefore cannot grant root. + +**Config type registration:** `ziti-ssh-ca config apply` registers the `ziti-ssh-host.v1` schema on the controller as a one-time setup step. Subsequent `ziti edge update config` commands update individual permission configs; changes reach running `ziti-ssh-host` instances at their next service refresh (`ZITI_SERVICE_REFRESH`, default 30 s; the SDK default would be 5 min — `newZitiContextWithConfigTypes` sets `Options.RefreshInterval`). ## Wire Protocol Over a raw Ziti connection to `ssh-ca`: - **Fetch CA public key:** send empty line (`\n`) → receive CA public key in authorized_keys format - **Sign cert:** send SSH public key in authorized_keys format → receive signed cert in authorized_keys format +- **Refusal:** `error: ` line (e.g. `error: rate limit exceeded`). Both request types count against the per-identity rate limit, which is checked before the request is read. Connections beyond `--max-connections` are closed without a reply; each connection has a 10 s deadline and a 4 KiB request cap. No HTTP, no framing beyond the newline. @@ -242,8 +264,10 @@ No HTTP, no framing beyond the newline. |---|---| | Principal | Configurable (default: `ziggy`); derived from identity name in `per-identity` mode | | Key ID | `ziti:` | -| Validity | 8 hours from signing time (configurable via `--cert-ttl`) | -| Extensions | `permit-pty`, `permit-port-forwarding`, `permit-agent-forwarding` | +| Serial | Random non-zero 64-bit value; logged by the CA at issue and by sshd at login | +| Validity | From 60 s before signing (`ca.ClockSkewAllowance`, clock-skew tolerance) until 5 minutes after signing by default (configurable via `--cert-ttl`) | +| Extensions | `permit-pty`, `permit-port-forwarding` by default (`--cert-extensions`; agent forwarding only if configured) | +| Critical options | `source-address=127.0.0.1/32,::1/128` (`--cert-source-address`): sshd accepts the cert only from loopback, i.e. via the local `ziti-ssh-host` proxy, so a cert cannot be used by connecting to port 22 directly | The Key ID appears in `/var/log/auth.log` on every SSH host, providing a per-identity audit trail even though all users share the same account in `shared` mode. @@ -256,13 +280,16 @@ All binaries accept configuration via flags and environment variables (flags tak | Flag | Env var | Default | Description | |---|---|---|---| | `--identity` | `ZITI_IDENTITY` | — | Path to Ziti identity file | -| `--ca-key` | `ZITI_CA_KEY` | — | Path to CA private key (Ed25519) | +| `--ca-key` | `ZITI_CA_KEY` | — | Path to the controller's intermediate CA private key (RSA, ECDSA or Ed25519; typically RSA) | | `--service` | `ZITI_CA_SERVICE` | `ssh-ca` | Ziti service name to bind | | `--principal` | `ZITI_SSH_PRINCIPAL` | `ziggy` | SSH certificate principal (shared mode only) | | `--mode` | `ZITI_SSH_MODE` | `shared` | Principal mode: `shared` or `per-identity` | | `--cert-ttl` | `ZITI_CERT_TTL` | `5m` | Certificate validity duration (e.g. `4h`, `12h`, `24h`); must be > 0 | -| `--rate-limit` | `ZITI_RATE_LIMIT` | `5` | Max cert signing requests per minute per identity | +| `--cert-extensions` | `ZITI_CERT_EXTENSIONS` | `permit-pty,permit-port-forwarding` | Certificate extensions to grant, or `none` | +| `--cert-source-address` | `ZITI_CERT_SOURCE_ADDRESS` | `127.0.0.1/32,::1/128` | Comma-separated IPs/CIDRs written to each certificate's `source-address` critical option; sshd accepts the certificate only from those addresses. The default (loopback) means certificates work only through `ziti-ssh-host`'s local proxy. `none` disables it. | +| `--rate-limit` | `ZITI_RATE_LIMIT` | `5` | Max requests (cert signing and CA public key) per minute per identity | | `--rate-burst` | `ZITI_RATE_BURST` | `3` | Burst allowance for the per-identity rate limiter | +| `--max-connections` | `ZITI_MAX_CONNECTIONS` | `64` | Maximum concurrent CA connections; further connections are closed immediately | | `--ziti-timeout` | `ZITI_TIMEOUT` | `30s` | Timeout for blocking Ziti network operations | `config apply` / `config remove` additional flags: @@ -271,7 +298,9 @@ All binaries accept configuration via flags and environment variables (flags tak |---|---|---|---| | `--controller` | `ZITI_CTRL_ADDRESS` | — | Controller host, optionally with port (default port: 443) | | `--username` | `ZITI_CTRL_USERNAME` | — | Controller admin username | -| `--password` | `ZITI_CTRL_PASSWORD` | — | Controller admin password | +| `--password` | `ZITI_CTRL_PASSWORD` | — | Controller admin password (flag warns: visible in process list) | +| `--password-file` | `ZITI_CTRL_PASSWORD_FILE` | — | Password from a file (`-` = stdin) | +| `--yes` | — | false | Trust the controller CA bundle on first use without asking | | `--insecure` | `ZITI_CTRL_INSECURE` | false | Skip TLS certificate verification | | `--controller-ca` | `ZITI_CTRL_CA` | — | Path to PEM CA cert to trust for controller TLS | @@ -290,9 +319,15 @@ Persistent flags (accepted by all subcommands): |---|---|---|---| | `--ssh-service` | `ZITI_SSH_SERVICE` | `ssh` | Ziti service(s) to proxy; flag may be repeated, env var accepts comma-separated list | | `--mode` | `ZITI_SSH_MODE` | `shared` | Principal mode: `shared` or `per-identity` | +| `--max-connections` | `ZITI_MAX_CONNECTIONS` | `128` | Max concurrent connections per service (`host.ProxyLimited`); excess closed immediately | | — | `ZITI_SUDOERS_RULE` | — | Global fallback sudoers rule (per-identity mode only) | | — | `ZITI_SSH_GROUPS` | — | Global fallback Linux groups, comma-separated (per-identity mode only) | | — | `ZITI_USER_CLEANUP` | `false` | Set to `true` to delete Linux accounts after the last session closes | +| — | `ZITI_ALLOW_SUDOERS` | — | Services (comma-separated, or `*`) whose config may set `sudoers_rule`; others are refused (connection rejected) | +| — | `ZITI_ALLOW_GROUPS` | — | `:` / `*:` list of privileged groups (`root`, `sudo`, `admin`, `wheel`, `docker`, `lxd`, `disk`, `shadow`, `libvirt`) a service's config may grant | +| — | `ZITI_RESTRICT_GROUPS` | `false` | `true`: config may grant only groups listed in `ZITI_ALLOW_GROUPS` | +| — | `ZITI_SERVICE_REFRESH` | `30s` | How often `run` checks the controller for service changes (minimum `5s`); a changed `ziti-ssh-host.v1` config applies within this interval | +| — | `ZITI_TERMINATE_ON_DISCONNECT` | `false` | With cleanup off: set to `true` to end everything the account can run when the last session closes (account expired with `usermod -e 1`, crontab and `at` jobs removed, lingering disabled, `loginctl terminate-user`, SIGTERM/SIGKILL by UID), keeping the account; `accountOps.ReactivateAccount` (`usermod -e ""`) re-enables it on the next authorized connect (fail closed). Needed for revoked identities to lose background processes. | **Important:** `--mode` must be set consistently on both `ziti-ssh-ca` and `ziti-ssh-host run`. If the CA issues certs with per-identity principals but the host is in shared mode (or vice versa), SSH authentication will fail. @@ -307,36 +342,44 @@ All connections authenticate as a single shared Linux user (e.g. `ziggy`). The C The CA derives a Linux username from each caller's Ziti identity name using `ca.DeriveUsername` and uses it as the certificate principal. `ziti-ssh-host run` creates the Linux user on first connection and deletes it (including home directory) when the last session for that identity closes. **Username sanitization rules** (applied by `ca.DeriveUsername`): -1. Lowercase the entire identity name. +1. Lowercase ASCII letters (`A`–`Z`); other characters are not case-folded, so non-ASCII lookalikes such as the Kelvin sign `K` never become ASCII letters. 2. Replace any character outside `[a-z0-9_-]` with `_`. 3. If the result starts with a digit, prefix it with `z`. 4. Truncate to 32 characters. Example: `Alice` → `alice`, `dba-Alice` → `dba-alice`, `123bot` → `z123bot` +**Account ownership (security boundary):** `ziti-ssh-host` only creates, modifies, or deletes accounts recorded in `/var/lib/ziti-ssh-host/owned-users.json` (`host.OwnerRegistry`: username → identity, UID) for the connecting identity with a matching UID ≥ 1000. Never adopt a pre-existing account: `useradd` exit 9 is a rejection, not success. Reserved names (`root`, system accounts, `ubuntu`, …) and names starting with `-` are refused. Accounts from releases before the registry are adopted only via `ziti-ssh-host users claim --username --identity `; `users list` shows the registry. OS calls go through the `accountOps` interface (`host/accounts.go`) so this logic is unit-tested with a fake. + **Ephemeral user lifecycle:** -- `ziti-ssh-host run` creates the user with `useradd -m -s /bin/bash ` on the first connection from that identity. -- Permissions are resolved (config entry → global fallback) and applied: `usermod -aG ` for group membership, `/etc/sudoers.d/` for sudoers (validated with `visudo -c` before installation). Group failures are non-fatal and logged. -- A reference count tracks concurrent sessions for the same identity. -- When the last session closes, the cleanup sequence runs: `loginctl terminate-user`, process poll (up to 5 s), `userdel -r`. The sudoers file is removed unconditionally at this point; group membership is removed implicitly by account deletion. -- The set of active managed usernames is persisted to `/var/lib/ziti-ssh-host/managed-users` (one username per line). On startup, `CleanupOrphans` reads this file and deletes any users still listed there (they had active sessions when the process was killed). This prevents accumulation of stale accounts after crashes. -- By default the Linux account is kept after disconnect. Set `ZITI_USER_CLEANUP=true` to delete the account when the last session closes (useful when ephemeral-only accounts are required). The sudoers file is still removed on disconnect. +- `ziti-ssh-host run` creates the user with `useradd -m -s /bin/bash -- ` on the first connection from that identity and records it in the ownership registry. +- Permissions are resolved (config entry → global fallback) and applied on every connect: `usermod -G ` (replaces supplementary groups) for group membership, `/etc/sudoers.d/ziti-ssh-host-` for sudoers (validated with `visudo -c` before installation). If setting the groups, writing or removing the sudoers file, or removing a legacy sudoers file fails, the connection is **rejected** (fail closed); if a new sudoers rule cannot be installed, any existing sudoers file is removed first so an older rule cannot stay in force. The session is counted only after permissions are applied. +- A reference count tracks concurrent sessions for the same identity. One account means one permission set: while it has sessions open through one service, a connection through a different service with different resolved permissions is rejected (`UserManager.EnsureUserForService`, `ErrPermissionConflict`); same service always applies the current config. +- When the last session closes, the sudoers file is removed and supplementary groups are cleared; with `ZITI_USER_CLEANUP=true` the cleanup sequence then runs: `loginctl terminate-user`, process poll by UID with SIGTERM/SIGKILL escalation, `userdel -r`, and the registry record is removed. +- The set of usernames with active sessions is persisted to `/var/lib/ziti-ssh-host/managed-users` (one username per line). On startup, `CleanupOrphans` reads this file and, in cleanup mode, deletes listed accounts that are still registered (they had active sessions when the process was killed). +- By default the Linux account — and any background processes the user left running — is kept after disconnect (the daemon logs a startup warning). Set `ZITI_TERMINATE_ON_DISCONNECT=true` to end the account's processes at last disconnect while keeping the account (`UserManager.SetTerminateOnDisconnect`, `accountOps.TerminateProcesses`), or `ZITI_USER_CLEANUP=true` to delete the account (useful when ephemeral-only accounts are required). The sudoers file is removed and groups are cleared on disconnect in all cases. **Connecting in per-identity mode:** ```sh -ziti-ssh dba-alice@web-server-prod +ziti-ssh web-server-prod ``` -The username before `@` is the Ziti identity name (which is also the derived Linux username when it contains only lowercase letters, digits, hyphens, and underscores). +With no `user@`, `ziti-ssh` and `ziti-scp` use the certificate's principal — in per-identity mode the CA issues it for the identity's derived Linux username (`client.CertPrincipal`). An explicit user must be that derived name, not the Ziti identity name: identity `Alice@Corp.com` logs in as `alice_corp_com` (`ziti-ssh alice_corp_com@web-server-prod`); `alice@corp.com@web-server-prod` is refused by sshd because it does not match the certificate. ## SSH Host Configuration -Written by `ziti-ssh-host enroll` to `/etc/ssh/sshd_config.d/ziti-ssh.conf`: +Written by `ziti-ssh-host enroll` to `/etc/ssh/sshd_config.d/ziti-ssh.conf` (and refreshed by `run` at startup if it differs, e.g. after an upgrade — `host.EnsureSSHDDropIn`): ``` +# Managed by ziti-ssh-host. TrustedUserCAKeys /etc/ssh/ziti_ca.pub + +# Accounts managed through Ziti may only log in with a CA certificate. +Match Group ziti-ssh-managed + AuthorizedKeysFile none + AuthorizedKeysCommand none ``` -No other changes required. No SSSD, no NSS, no PAM modifications, no custom sshd. +Members of `ziti-ssh-managed` (`host.ManagedGroup`) can only log in with a CA certificate: a key a user adds to their own authorized_keys cannot outlive their certificate or identity. Per-identity accounts are always kept in the group; in shared mode the administrator adds the shared account (`usermod -aG ziti-ssh-managed ziggy`), and `run` warns at startup if the group is empty. The group is created by the package postinstall, `enroll` and `run`. Verified on Ubuntu 24.04: the `Match` block ends with the included file (`sshd -t` passes; main-config settings stay global). No SSSD, no NSS, no PAM modifications, no custom sshd. ## PKI Hierarchy @@ -354,7 +397,7 @@ The root CA private key is kept offline and is not used at runtime. The controll The `--ca-key` argument to `ziti-ssh-ca` is the **controller's intermediate CA private key** — not the root CA key. This is the key that signs Ziti identity certificates, and it is therefore the key sshd must trust via `TrustedUserCAKeys`. -In production, `ziti-ssh-ca` runs on the same machine as the Ziti controller, as the same OS user (typically `ziti`). This gives it direct filesystem access to the controller's PKI. The intermediate CA key path is typically: +In production, `ziti-ssh-ca` runs on the same machine as the Ziti controller, as the same OS user as the controller (`ziti-controller` with the `openziti-controller` v2 package, `ziti` in other deployments). The package postinstall detects that user and writes the drop-in `/etc/systemd/system/ziti-ssh-ca.service.d/10-controller-user.conf`; the unit's default is `User=ziti`. This gives it direct filesystem access to the controller's PKI. The intermediate CA key path is typically: ``` /var/lib/ziti-controller/pki/intermediate-ca/keys/intermediate-ca.key @@ -368,7 +411,7 @@ The key file should remain mode 0600 and owned by the controller service user. ` - **Language:** Go - **Target OS:** Ubuntu 24.04+ (also the upcoming 26.04) -- **CA key type:** Ed25519 +- **CA key type:** whatever the controller's intermediate CA uses (RSA on stock controllers; ECDSA and Ed25519 also supported) - **Shared Linux user:** `ziggy` (default, configurable) ## Project Structure @@ -377,35 +420,56 @@ The key file should remain mode 0600 and owned by the controller service user. ` ziti-ssh/ ├── cmd/ │ ├── ziti-ssh/ -│ │ ├── main.go # Full SSH client (connect, sign, enroll, list, mfa) -│ │ └── oidc.go # Browser-based OIDC auth flow (browser launch, callback server) +│ │ ├── main.go # Full SSH client (connect, proxy, sign, enroll, list, mfa, known-hosts) +│ │ ├── oidc.go # Browser-based OIDC auth flow wiring +│ │ └── main_test.go # Target/forward parsing, agent-forwarding gate, proxy never prompts │ ├── ziti-scp/ -│ │ └── main.go # SCP-style file copy tool (upload, download, recursive, enroll) +│ │ ├── main.go # SCP-style file copy tool (upload, download, recursive, enroll) +│ │ └── main_test.go # scp argument parsing │ ├── ziti-ssh-ca/ │ │ ├── main.go # CA service entry point, run loop, enroll subcommand -│ │ └── config.go # config subcommand (print, apply, remove) +│ │ ├── config.go # config subcommand (print, apply, remove) +│ │ ├── ctrltrust.go # Controller TLS trust for config (cacerts fetch, TOFU, saved bundles) +│ │ └── *_test.go │ └── ziti-ssh-host/ -│ └── main.go # enroll, run (multi-service), inspect subcommands +│ ├── main.go # enroll, run (multi-service), inspect subcommands +│ ├── users.go # users list / claim (ownership registry admin) +│ └── main_test.go ├── ca/ -│ ├── ca.go # CA key loading, cert signing, DeriveUsername -│ └── ca_test.go # Unit tests for DeriveUsername +│ ├── ca.go # CA key loading, cert signing (serial, source-address), DeriveUsername, key allowlist +│ └── ca_test.go ├── client/ -│ ├── ssh.go # NewCertSigner, CertNeedsRefresh, RunSession, RunCommand -│ └── sftp.go # RunSFTP — SFTP file copy over net.Conn +│ ├── ssh.go # NewCertSigner(Prompt), CertNeedsRefresh, RunSession, RunCommand, forwards, SOCKS5 +│ ├── certs.go # CA reply validation, refresh threshold, CertPrincipal +│ ├── hostkeys.go # Trust-on-first-use host keys (KnownHosts, NewHostKeyCallback) +│ ├── sftp.go # RunSFTP — SFTP file copy over net.Conn +│ └── *_test.go # incl. forward_test.go (in-process SSH server), sftp_copy_test.go ├── host/ -│ ├── host.go # ProxyHooks, Proxy, UserManager, PermissionsConfig, sshd config -│ └── host_test.go # Unit tests for PermissionsConfig.Resolve and UserManager +│ ├── host.go # ProxyHooks, Proxy(Limited), UserManager, PermissionsConfig, MatchPattern, sshd config +│ ├── accounts.go # accountOps (useradd/usermod/userdel/getent…), termination, deleteUser +│ ├── registry.go # OwnerRegistry — persistent account ownership (owned-users.json) +│ ├── claim.go # ClaimAccount — adopt pre-registry accounts +│ ├── grant.go # GrantPolicy — host-side limits on what configs may grant +│ └── *_test.go # accounts (fake accountOps), caller, grant, match, sessions, sshd ├── config/ │ ├── config.go # Shared configuration (flags + env vars) -│ └── ztapis.go # Controller URL persistence (PersistZtAPIs, EventControllerUrlsUpdated) +│ ├── atomic.go # AtomicWriteFile +│ ├── ztapis.go # Controller URL persistence (PersistZtAPIs) +│ ├── ctrlurls.go # Controller URL validation (CheckControllerURL, FilterControllerURLs) +│ └── perms*.go # CheckUserFile — refuse files another user could have written ├── internal/ -│ ├── oidc/ -│ │ └── oidc.go # OIDC authorization code flow (PKCE, token exchange) -│ └── ratelimit/ -│ ├── ratelimit.go # Per-identity token-bucket rate limiter -│ └── ratelimit_test.go +│ ├── mfa/ # MFA TOTP prompt (terminal, hidden, bounded attempts) +│ ├── oidc/ # OIDC authorization code flow (PKCE, loopback callback); flow_test.go: fake IdP +│ └── ratelimit/ # Per-identity token-bucket rate limiter +├── packaging/ # nfpm configs, postinstall/preremove/postremove scripts, systemd units ├── scripts/ -│ └── build-packages.sh # Builds deb and/or rpm packages into dist/ (FORMAT=deb,rpm ARCHS=amd64,arm64) +│ ├── build-packages.sh # Builds deb and/or rpm packages into dist/ (FORMAT=deb,rpm ARCHS=amd64,arm64) +│ ├── docker-build-packages.sh +│ └── Dockerfile.packages +├── suites/ # ziti-test-suite integration suites (AWS) +│ ├── ziti-ssh/ # shared mode; install scripts shared by both suites +│ └── ziti-ssh-per-identity/ # per-identity mode (accounts, grant policy, reload, revocation) +├── docs/ # building, configuration, operations, provisioning, usage ├── go.mod ├── go.sum ├── ARCHITECTURE.md # High-level architecture narrative diff --git a/README.md b/README.md index 65f3c4e..2f46f43 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ The Ziti network enforces who can reach which machines; `sshd` on each machine o ## Prerequisites -- An operational OpenZiti network (controller + at least one edge router). See the [OpenZiti quickstart](https://openziti.io/docs/learn/quickstarts/) if you do not have one yet. +- An operational OpenZiti network (controller + at least one edge router), running **OpenZiti v2.0.0 or later** on the controller and all edge routers. See the [OpenZiti quickstart](https://openziti.io/docs/learn/quickstarts/) if you do not have one yet. - **On user machines:** `ziti-ssh` installed - **On the controller:** `ziti-ssh-ca` installed - **On each SSH target host:** `ziti-ssh-host` installed — Ubuntu 22.04 or later (or any distro with OpenSSH 8.2+ and systemd) diff --git a/ca/ca.go b/ca/ca.go index 8d1357e..c5b9422 100644 --- a/ca/ca.go +++ b/ca/ca.go @@ -14,24 +14,30 @@ limitations under the License. */ -// Package ca provides SSH certificate authority operations: loading Ed25519 CA -// keys and signing short-lived SSH user certificates bound to Ziti identities. +// Package ca provides SSH certificate authority operations: loading the CA key +// (the Ziti controller's intermediate CA private key — RSA, ECDSA or Ed25519) +// and signing short-lived SSH user certificates bound to Ziti identities. package ca import ( + "bytes" "crypto/rand" + "crypto/rsa" + "encoding/binary" "fmt" + "net" "os" "strings" "time" - "unicode" "golang.org/x/crypto/ssh" ) -// LoadKey reads an Ed25519 private key from path and returns an ssh.Signer -// and the corresponding ssh.PublicKey. The key must be stored in PEM format -// (as produced by ssh-keygen -t ed25519). +// LoadKey reads the CA private key from path and returns an ssh.Signer and the +// corresponding ssh.PublicKey. It accepts any key ssh.ParsePrivateKey does — +// PEM-encoded RSA, ECDSA or Ed25519 (PKCS#1, PKCS#8, SEC 1 or OpenSSH format). +// In production this is the Ziti controller's intermediate CA key (never the +// offline root CA key); on stock controllers it is typically RSA. func LoadKey(path string) (ssh.Signer, ssh.PublicKey, error) { data, err := os.ReadFile(path) if err != nil { @@ -49,11 +55,15 @@ func LoadKey(path string) (ssh.Signer, ssh.PublicKey, error) { // SignCert signs a short-lived SSH user certificate for the given public key. // identity is the Ziti identity name of the caller (embedded in the Key ID for // audit purposes). principal is the Linux username the cert grants access to. -// ttl controls validity duration — pass 8*time.Hour for standard production use. +// ttl controls validity duration (the CA defaults to 5 minutes). +// sourceAddress, when non-empty, is set as the "source-address" critical +// option (see ParseSourceAddress and DefaultSourceAddress); "" omits it. +// extensions are the certificate extensions (permissions) to grant, as +// returned by ParseExtensions. // // The returned bytes are in authorized_keys format, ready to write to a // ~/.ssh/-cert.pub file. -func SignCert(signer ssh.Signer, pubKey ssh.PublicKey, identity, principal string, ttl time.Duration) ([]byte, error) { +func SignCert(signer ssh.Signer, pubKey ssh.PublicKey, identity, principal string, ttl time.Duration, sourceAddress string, extensions []string) ([]byte, error) { if identity == "" { return nil, fmt.Errorf("identity must not be empty") } @@ -61,22 +71,34 @@ func SignCert(signer ssh.Signer, pubKey ssh.PublicKey, identity, principal strin return nil, fmt.Errorf("principal must not be empty") } + serial, err := randomSerial() + if err != nil { + return nil, err + } now := time.Now() cert := &ssh.Certificate{ CertType: ssh.UserCert, Key: pubKey, + Serial: serial, KeyId: "ziti:" + identity, ValidPrincipals: []string{principal}, - ValidAfter: uint64(now.Unix()), - ValidBefore: uint64(now.Add(ttl).Unix()), + // Backdated so an SSH host whose clock is slightly behind the CA's + // still accepts a freshly issued certificate. + ValidAfter: uint64(now.Add(-ClockSkewAllowance).Unix()), + ValidBefore: uint64(now.Add(ttl).Unix()), Permissions: ssh.Permissions{ - Extensions: map[string]string{ - "permit-pty": "", - "permit-port-forwarding": "", - "permit-agent-forwarding": "", - }, + Extensions: map[string]string{}, }, } + for _, e := range extensions { + cert.Permissions.Extensions[e] = "" + } + if sourceAddress != "" { + // sshd accepts the certificate only from these addresses. Every + // legitimate login reaches sshd from the host's own ziti-ssh-host + // proxy over loopback, so this confines certificates to the Ziti path. + cert.Permissions.CriticalOptions = map[string]string{"source-address": sourceAddress} + } if err := cert.SignCert(rand.Reader, signer); err != nil { return nil, fmt.Errorf("sign certificate: %w", err) @@ -90,19 +112,47 @@ func PublicKeyBytes(pub ssh.PublicKey) []byte { return ssh.MarshalAuthorizedKey(pub) } +// ClockSkewAllowance is how far before the signing time a certificate's +// validity starts, so hosts with a clock slightly behind the CA's accept it. +const ClockSkewAllowance = 60 * time.Second + +// randomSerial returns a random non-zero 64-bit certificate serial. sshd logs +// it with every certificate login ("ID ziti: (serial N)"), and the +// CA logs it when issuing, so a login can be matched to its issuance. +func randomSerial() (uint64, error) { + var b [8]byte + for { + if _, err := rand.Read(b[:]); err != nil { + return 0, fmt.Errorf("generate certificate serial: %w", err) + } + if v := binary.BigEndian.Uint64(b[:]); v != 0 { + return v, nil + } + } +} + // DeriveUsername maps a Ziti identity name to a valid Linux username. // // Rules applied in order: -// 1. Lowercase the entire string. +// 1. Lowercase ASCII letters (A–Z only). // 2. Replace any character outside [a-z0-9_-] with '_'. +// +// Only ASCII is case-folded: unicode.ToLower maps some non-ASCII letters to +// ASCII ones (U+212A KELVIN SIGN → 'k', U+0130 'İ' → 'i'), which would let a +// lookalike identity name derive the same username as another identity. // 3. If the result starts with a digit, prefix with 'z'. // 4. Truncate to 32 characters. // // The result is guaranteed to be non-empty as long as identity is non-empty, // because every character is either kept or replaced with '_'. func DeriveUsername(identity string) string { - // Step 1: lowercase. - s := strings.Map(unicode.ToLower, identity) + // Step 1: lowercase ASCII letters only. + s := strings.Map(func(r rune) rune { + if r >= 'A' && r <= 'Z' { + return r + ('a' - 'A') + } + return r + }, identity) // Step 2: replace characters outside [a-z0-9_-] with '_'. var b strings.Builder @@ -128,3 +178,172 @@ func DeriveUsername(identity string) string { return result } + +// reservedUsernames are Linux account names that must never be issued as a +// per-identity certificate principal by ziti-ssh-ca, nor managed by +// ziti-ssh-host: root, common Debian/Ubuntu system accounts, the default +// cloud-image user, and generic administrator names. ziti-ssh-host's ownership +// registry is the primary control; this list is defence in depth on both sides. +var reservedUsernames = map[string]bool{ + "root": true, "daemon": true, "bin": true, "sys": true, "sync": true, + "games": true, "man": true, "lp": true, "mail": true, "news": true, + "uucp": true, "proxy": true, "www-data": true, "backup": true, "list": true, + "irc": true, "gnats": true, "nobody": true, "systemd-network": true, + "systemd-resolve": true, "systemd-timesync": true, "messagebus": true, + "syslog": true, "sshd": true, "ubuntu": true, "admin": true, "ziti": true, +} + +// IsReservedUsername reports whether username is on the reserved list. +func IsReservedUsername(username string) bool { + return reservedUsernames[username] +} + +// ValidatePerIdentityPrincipal rejects derived per-identity principals that +// must never appear in a certificate: empty, reserved names (see +// IsReservedUsername, including "root"), or names starting with '-' (which +// command-line tools would parse as an option). A certificate for a reserved +// name would be accepted by sshd on any host trusting the CA where that +// account exists, independent of ziti-ssh-host's own checks. +func ValidatePerIdentityPrincipal(principal string) error { + switch { + case principal == "": + return fmt.Errorf("derived principal is empty") + case IsReservedUsername(principal): + return fmt.Errorf("derived principal %q is a reserved account name", principal) + case strings.HasPrefix(principal, "-"): + return fmt.Errorf("derived principal %q must not start with '-'", principal) + } + return nil +} + +// DefaultSourceAddress is the default "source-address" critical option: the +// loopback addresses from which ziti-ssh-host proxies connections to sshd. +const DefaultSourceAddress = "127.0.0.1/32,::1/128" + +// ParseSourceAddress validates and normalises a value for the certificate +// "source-address" critical option: a comma-separated list of IP addresses or +// CIDR blocks. A bare IP becomes a /32 (IPv4) or /128 (IPv6). CIDRs with host +// bits set are rejected to avoid silently widening the range. The value +// "none" disables the option and returns "". +func ParseSourceAddress(v string) (string, error) { + v = strings.TrimSpace(v) + if strings.EqualFold(v, "none") { + return "", nil + } + if v == "" { + return "", fmt.Errorf("source address list is empty (use \"none\" to disable)") + } + var out []string + for _, item := range strings.Split(v, ",") { + item = strings.TrimSpace(item) + if item == "" { + return "", fmt.Errorf("source address list %q has an empty entry", v) + } + if strings.Contains(item, "/") { + ip, ipnet, err := net.ParseCIDR(item) + if err != nil { + return "", fmt.Errorf("invalid CIDR %q: %w", item, err) + } + if !ip.Equal(ipnet.IP) { + return "", fmt.Errorf("CIDR %q has host bits set (did you mean %s?)", item, ipnet.String()) + } + out = append(out, ipnet.String()) + continue + } + ip := net.ParseIP(item) + if ip == nil { + return "", fmt.Errorf("invalid IP address %q", item) + } + if ip.To4() != nil { + out = append(out, ip.To4().String()+"/32") + } else { + out = append(out, ip.String()+"/128") + } + } + return strings.Join(out, ","), nil +} + +// MinRSABits is the smallest RSA client key the CA will certify. +const MinRSABits = 3072 + +// allowedClientKeyTypes are the SSH public key algorithms the CA certifies. +var allowedClientKeyTypes = map[string]bool{ + ssh.KeyAlgoED25519: true, + ssh.KeyAlgoSKED25519: true, + ssh.KeyAlgoECDSA256: true, + ssh.KeyAlgoECDSA384: true, + ssh.KeyAlgoECDSA521: true, + ssh.KeyAlgoSKECDSA256: true, + ssh.KeyAlgoRSA: true, +} + +// ValidateClientKey rejects keys the CA must not certify: certificates, +// DSA and other unsupported algorithms, RSA keys shorter than MinRSABits, and +// the CA's own public key. +func ValidateClientKey(key, caKey ssh.PublicKey) error { + if _, isCert := key.(*ssh.Certificate); isCert { + return fmt.Errorf("a certificate was submitted; send the plain public key") + } + if !allowedClientKeyTypes[key.Type()] { + return fmt.Errorf("key type %s is not supported (use ed25519, ecdsa, or rsa >= %d bits)", key.Type(), MinRSABits) + } + if key.Type() == ssh.KeyAlgoRSA { + cpk, ok := key.(ssh.CryptoPublicKey) + if !ok { + return fmt.Errorf("cannot inspect RSA key") + } + rk, ok := cpk.CryptoPublicKey().(*rsa.PublicKey) + if !ok || rk.N.BitLen() < MinRSABits { + bits := 0 + if ok { + bits = rk.N.BitLen() + } + return fmt.Errorf("RSA key is %d bits; at least %d required", bits, MinRSABits) + } + } + if caKey != nil && bytes.Equal(key.Marshal(), caKey.Marshal()) { + return fmt.Errorf("refusing to certify the CA's own key") + } + return nil +} + +// DefaultExtensions are the certificate extensions granted by default: +// interactive terminals and port forwarding (ziti-ssh -L/-R/-D). Agent +// forwarding is not granted by default: clients cannot yet verify which host +// they reached (see the H8 notes in docs/operations.md). +const DefaultExtensions = "permit-pty,permit-port-forwarding" + +// knownExtensions are the OpenSSH user-certificate extensions. +var knownExtensions = map[string]bool{ + "permit-pty": true, + "permit-port-forwarding": true, + "permit-agent-forwarding": true, + "permit-X11-forwarding": true, + "permit-user-rc": true, + "no-touch-required": true, +} + +// ParseExtensions validates a comma-separated list of certificate extensions. +// "none" grants no extensions (no PTY, no forwarding). +func ParseExtensions(v string) ([]string, error) { + v = strings.TrimSpace(v) + if strings.EqualFold(v, "none") { + return []string{}, nil + } + if v == "" { + return nil, fmt.Errorf("extension list is empty (use \"none\" to grant no extensions)") + } + seen := map[string]bool{} + var out []string + for _, e := range strings.Split(v, ",") { + e = strings.TrimSpace(e) + if !knownExtensions[e] { + return nil, fmt.Errorf("unknown certificate extension %q", e) + } + if !seen[e] { + seen[e] = true + out = append(out, e) + } + } + return out, nil +} diff --git a/ca/ca_test.go b/ca/ca_test.go index 2430dd0..8df07c2 100644 --- a/ca/ca_test.go +++ b/ca/ca_test.go @@ -17,8 +17,11 @@ package ca_test import ( + "crypto/ecdsa" "crypto/ed25519" + "crypto/elliptic" "crypto/rand" + "crypto/rsa" "strings" "testing" "time" @@ -67,7 +70,7 @@ func TestSignCert(t *testing.T) { const ttl = 5 * time.Minute before := time.Now() - certBytes, err := ca.SignCert(caSigner, clientPub, identity, principal, ttl) + certBytes, err := ca.SignCert(caSigner, clientPub, identity, principal, ttl, ca.DefaultSourceAddress, mustExtensions(t, ca.DefaultExtensions)) after := time.Now() if err != nil { @@ -100,6 +103,16 @@ func TestSignCert(t *testing.T) { } }) + t.Run("SourceAddress", func(t *testing.T) { + got := cert.CriticalOptions["source-address"] + if got != ca.DefaultSourceAddress { + t.Errorf("source-address = %q, want %q", got, ca.DefaultSourceAddress) + } + if len(cert.CriticalOptions) != 1 { + t.Errorf("CriticalOptions = %v, want only source-address", cert.CriticalOptions) + } + }) + t.Run("Principals", func(t *testing.T) { if len(cert.ValidPrincipals) != 1 { t.Fatalf("len(ValidPrincipals) = %d, want 1", len(cert.ValidPrincipals)) @@ -113,13 +126,13 @@ func TestSignCert(t *testing.T) { validAfter := time.Unix(int64(cert.ValidAfter), 0) validBefore := time.Unix(int64(cert.ValidBefore), 0) - // ValidAfter must be at or after our before-timestamp (with 1s slack for clock granularity). - if validAfter.Before(before.Add(-time.Second)) { - t.Errorf("ValidAfter %v is before test start %v", validAfter, before) + // ValidAfter is backdated by ClockSkewAllowance (1s slack for + // clock granularity) so hosts slightly behind the CA accept it. + if validAfter.Before(before.Add(-ca.ClockSkewAllowance - time.Second)) { + t.Errorf("ValidAfter %v is more than %v before test start %v", validAfter, ca.ClockSkewAllowance, before) } - // ValidAfter must not be in the future relative to after. - if validAfter.After(after.Add(time.Second)) { - t.Errorf("ValidAfter %v is after test end %v", validAfter, after) + if validAfter.After(after.Add(-ca.ClockSkewAllowance + time.Second)) { + t.Errorf("ValidAfter %v is not backdated by %v (test end %v)", validAfter, ca.ClockSkewAllowance, after) } // ValidBefore must be approximately now+5m (within 5 seconds). @@ -131,16 +144,18 @@ func TestSignCert(t *testing.T) { }) t.Run("Extensions", func(t *testing.T) { - required := []string{ - "permit-pty", - "permit-port-forwarding", - "permit-agent-forwarding", - } - for _, ext := range required { + // Default: terminals and port forwarding, but no agent forwarding. + for _, ext := range []string{"permit-pty", "permit-port-forwarding"} { if _, ok := cert.Extensions[ext]; !ok { t.Errorf("missing extension %q", ext) } } + if _, ok := cert.Extensions["permit-agent-forwarding"]; ok { + t.Error("agent forwarding granted by default") + } + if len(cert.Extensions) != 2 { + t.Errorf("unexpected extensions: %v", cert.Extensions) + } }) } @@ -148,7 +163,7 @@ func TestSignCert_EmptyIdentityRejected(t *testing.T) { caSigner, _ := generateTestCA(t) clientPub := generateTestClientKey(t) - _, err := ca.SignCert(caSigner, clientPub, "", "ziggy", 8*time.Hour) + _, err := ca.SignCert(caSigner, clientPub, "", "ziggy", 8*time.Hour, "", nil) if err == nil { t.Fatal("expected error for empty identity, got nil") } @@ -158,7 +173,7 @@ func TestSignCert_EmptyPrincipalRejected(t *testing.T) { caSigner, _ := generateTestCA(t) clientPub := generateTestClientKey(t) - _, err := ca.SignCert(caSigner, clientPub, "alice", "", 8*time.Hour) + _, err := ca.SignCert(caSigner, clientPub, "alice", "", 8*time.Hour, "", nil) if err == nil { t.Fatal("expected error for empty principal, got nil") } @@ -277,3 +292,158 @@ func TestPublicKeyBytes(t *testing.T) { t.Errorf("PublicKeyBytes = %q, want prefix %q", string(b), "ssh-ed25519 ") } } + +func TestValidatePerIdentityPrincipal(t *testing.T) { + for _, p := range []string{"", "root", "-ou0", "ubuntu", "admin", "sshd", "ziti"} { + if err := ca.ValidatePerIdentityPrincipal(p); err == nil { + t.Errorf("ValidatePerIdentityPrincipal(%q) = nil, want error", p) + } + } + for _, p := range []string{"alice", "dba-alice", "z123bot"} { + if err := ca.ValidatePerIdentityPrincipal(p); err != nil { + t.Errorf("ValidatePerIdentityPrincipal(%q) = %v, want nil", p, err) + } + } +} + +func TestSignCert_NoSourceAddress(t *testing.T) { + caSigner, _ := generateTestCA(t) + certBytes, err := ca.SignCert(caSigner, generateTestClientKey(t), "alice", "ziggy", 5*time.Minute, "", nil) + if err != nil { + t.Fatal(err) + } + pub, _, _, _, err := ssh.ParseAuthorizedKey(certBytes) + if err != nil { + t.Fatal(err) + } + if opts := pub.(*ssh.Certificate).CriticalOptions; len(opts) != 0 { + t.Errorf("CriticalOptions = %v, want none", opts) + } +} + +func TestParseSourceAddress(t *testing.T) { + valid := map[string]string{ + ca.DefaultSourceAddress: "127.0.0.1/32,::1/128", + "127.0.0.1": "127.0.0.1/32", + " 10.0.0.0/8 , ::1 ": "10.0.0.0/8,::1/128", + "192.168.1.0/24,fd00::/8": "192.168.1.0/24,fd00::/8", + "none": "", + "NONE": "", + } + for in, want := range valid { + got, err := ca.ParseSourceAddress(in) + if err != nil || got != want { + t.Errorf("ParseSourceAddress(%q) = %q, %v; want %q", in, got, err, want) + } + } + for _, in := range []string{"", "localhost", "127.0.0.1/33", "10.0.0.5/24", "127.0.0.1,,::1", "1.2.3"} { + if got, err := ca.ParseSourceAddress(in); err == nil { + t.Errorf("ParseSourceAddress(%q) = %q, want error", in, got) + } + } +} + +func TestValidateClientKey(t *testing.T) { + caSigner, caPub := generateTestCA(t) + sshPub := func(k interface{}) ssh.PublicKey { + p, err := ssh.NewPublicKey(k) + if err != nil { + t.Fatal(err) + } + return p + } + + edPub, _, _ := ed25519.GenerateKey(rand.Reader) + ec, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + rsa3072, _ := rsa.GenerateKey(rand.Reader, 3072) + rsa2048, _ := rsa.GenerateKey(rand.Reader, 2048) + + for name, k := range map[string]ssh.PublicKey{ + "ed25519": sshPub(edPub), + "ecdsa": sshPub(&ec.PublicKey), + "rsa-3072": sshPub(&rsa3072.PublicKey), + } { + if err := ca.ValidateClientKey(k, caPub); err != nil { + t.Errorf("%s rejected: %v", name, err) + } + } + + cert := &ssh.Certificate{Key: sshPub(edPub), CertType: ssh.UserCert, ValidPrincipals: []string{"ziggy"}, ValidBefore: ssh.CertTimeInfinity} + if err := cert.SignCert(rand.Reader, caSigner); err != nil { + t.Fatal(err) + } + for name, k := range map[string]ssh.PublicKey{ + "rsa-2048": sshPub(&rsa2048.PublicKey), + "certificate": cert, + "CA's own key": caPub, + } { + if err := ca.ValidateClientKey(k, caPub); err == nil { + t.Errorf("%s accepted", name) + } + } +} + +func mustExtensions(t *testing.T, v string) []string { + t.Helper() + e, err := ca.ParseExtensions(v) + if err != nil { + t.Fatal(err) + } + return e +} + +func TestParseExtensions(t *testing.T) { + if got := mustExtensions(t, " permit-pty , permit-agent-forwarding,permit-pty"); strings.Join(got, ",") != "permit-pty,permit-agent-forwarding" { + t.Errorf("got %v", got) + } + if got := mustExtensions(t, "none"); len(got) != 0 { + t.Errorf("none: got %v", got) + } + for _, bad := range []string{"", "permit-everything", "permit-pty,,permit-user-rc"} { + if _, err := ca.ParseExtensions(bad); err == nil { + t.Errorf("ParseExtensions(%q) accepted", bad) + } + } +} + +func TestDeriveUsername_NoNonASCIICaseFolding(t *testing.T) { + // Lookalike identity names must not derive the same username as the + // ASCII name they imitate. + cases := map[string]string{ + "admİn": "adm_n", // LATIN CAPITAL LETTER I WITH DOT ABOVE + "Karen": "_aren", // KELVIN SIGN + "ALICE": "alice", // ASCII still folded + "Ünïcode-User": "_n_code-user", + } + for in, want := range cases { + if got := ca.DeriveUsername(in); got != want { + t.Errorf("DeriveUsername(%q) = %q, want %q", in, got, want) + } + } +} + +func TestSignCert_RandomSerial(t *testing.T) { + _, caPriv, _ := ed25519.GenerateKey(rand.Reader) + signer, err := ssh.NewSignerFromKey(caPriv) + if err != nil { + t.Fatal(err) + } + userPub, _, _ := ed25519.GenerateKey(rand.Reader) + pub, _ := ssh.NewPublicKey(userPub) + seen := map[uint64]bool{} + for i := 0; i < 20; i++ { + b, err := ca.SignCert(signer, pub, "alice", "ziggy", 5*time.Minute, ca.DefaultSourceAddress, []string{"permit-pty"}) + if err != nil { + t.Fatal(err) + } + pk, _, _, _, err := ssh.ParseAuthorizedKey(b) + if err != nil { + t.Fatal(err) + } + s := pk.(*ssh.Certificate).Serial + if s == 0 || seen[s] { + t.Fatalf("serial %d is zero or repeated", s) + } + seen[s] = true + } +} diff --git a/client/certs.go b/client/certs.go new file mode 100644 index 0000000..9ea0955 --- /dev/null +++ b/client/certs.go @@ -0,0 +1,154 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package client + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "os" + "strings" + "time" + + "golang.org/x/crypto/ssh" +) + +// MaxCAResponseBytes bounds the single line read from ziti-ssh-ca. A signed +// certificate in authorized_keys format is a few kilobytes at most. +const MaxCAResponseBytes = 16 * 1024 + +// CARejectedError is returned when ziti-ssh-ca answers with an +// "error: " line instead of a certificate (e.g. rate limiting). +type CARejectedError struct { + Reason string +} + +func (e *CARejectedError) Error() string { + return "CA refused the request: " + e.Reason +} + +// ReadCAResponse reads one newline-terminated line from the CA, refusing +// responses longer than MaxCAResponseBytes. +func ReadCAResponse(r io.Reader) (string, error) { + br := bufio.NewReader(io.LimitReader(r, MaxCAResponseBytes+1)) + line, err := br.ReadString('\n') + if len(line) > MaxCAResponseBytes { + return "", fmt.Errorf("CA response exceeds %d bytes", MaxCAResponseBytes) + } + if err != nil && !(errors.Is(err, io.EOF) && line != "") { + return "", fmt.Errorf("read certificate from CA: %w", err) + } + return strings.TrimSpace(line), nil +} + +// ValidateSignedCert checks the CA's response line before it is written to +// disk. It returns the certificate re-encoded in authorized_keys format. +// +// It fails with *CARejectedError for an "error: ..." reply, and with a plain +// error unless the line is a user certificate for exactly pubKeyLine's key. +// Callers must not overwrite an existing certificate when this fails. +func ValidateSignedCert(line, pubKeyLine string) ([]byte, error) { + line = strings.TrimSpace(line) + if line == "" { + return nil, errors.New("CA returned no certificate") + } + if rest, ok := strings.CutPrefix(line, "error:"); ok { + return nil, &CARejectedError{Reason: strings.TrimSpace(rest)} + } + + ourKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pubKeyLine)) + if err != nil { + return nil, fmt.Errorf("parse local public key: %w", err) + } + pub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(line)) + if err != nil { + return nil, fmt.Errorf("CA response is not a valid certificate: %w", err) + } + cert, ok := pub.(*ssh.Certificate) + if !ok { + return nil, fmt.Errorf("CA response is a %s key, not a certificate", pub.Type()) + } + if cert.CertType != ssh.UserCert { + return nil, fmt.Errorf("CA returned a host certificate, not a user certificate") + } + if !bytes.Equal(cert.Key.Marshal(), ourKey.Marshal()) { + return nil, errors.New("CA returned a certificate for a different public key") + } + return ssh.MarshalAuthorizedKey(cert), nil +} + +// Refresh threshold bounds: a certificate is refreshed when its remaining +// validity drops below 20% of its total lifetime, capped at maxRefreshWindow +// and never below minRefreshWindow. +const ( + maxRefreshWindow = 5 * time.Minute + minRefreshWindow = 30 * time.Second +) + +// certRefreshThreshold returns how much remaining validity triggers a refresh. +// With the default 5-minute certificates this is 1 minute, so a certificate is +// reused for about 4 minutes instead of being re-signed on every invocation; +// certificates of 25 minutes or longer keep the 5-minute window. +func certRefreshThreshold(cert *ssh.Certificate) time.Duration { + if cert.ValidAfter == 0 || cert.ValidBefore <= cert.ValidAfter { + return maxRefreshWindow + } + lifetime := time.Duration(cert.ValidBefore-cert.ValidAfter) * time.Second + t := lifetime / 5 + if t > maxRefreshWindow { + t = maxRefreshWindow + } + if t < minRefreshWindow { + t = minRefreshWindow + } + return t +} + +// certNeedsRefreshAt reports whether cert should be replaced at time now. +func certNeedsRefreshAt(cert *ssh.Certificate, now time.Time) bool { + // ValidBefore of 0 or CertTimeInfinity means "forever"; this CA never + // issues such certificates, but treat them as not needing refresh. + if cert.ValidBefore == 0 || cert.ValidBefore == ssh.CertTimeInfinity { + return false + } + expiry := time.Unix(int64(cert.ValidBefore), 0) + return expiry.Sub(now) < certRefreshThreshold(cert) +} + +// CertPrincipal returns the only principal of the SSH certificate at +// certPath. ok is false if the file is missing, is not a certificate, or the +// certificate has zero or several principals. Clients use it as the default +// SSH user when none is given: in per-identity mode the CA issues each +// identity a certificate for its derived Linux username, so the user does not +// have to work that name out. +func CertPrincipal(certPath string) (principal string, ok bool) { + data, err := os.ReadFile(certPath) + if err != nil { + return "", false + } + pub, _, _, _, err := ssh.ParseAuthorizedKey(data) + if err != nil { + return "", false + } + cert, isCert := pub.(*ssh.Certificate) + if !isCert || len(cert.ValidPrincipals) != 1 || cert.ValidPrincipals[0] == "" { + return "", false + } + return cert.ValidPrincipals[0], true +} diff --git a/client/certs_test.go b/client/certs_test.go new file mode 100644 index 0000000..ead2301 --- /dev/null +++ b/client/certs_test.go @@ -0,0 +1,182 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package client + +import ( + "crypto/ed25519" + "crypto/rand" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "golang.org/x/crypto/ssh" +) + +func newKey(t *testing.T) ssh.Signer { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + s, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatal(err) + } + return s +} + +func signCert(t *testing.T, ca ssh.Signer, key ssh.PublicKey, certType uint32, lifetime time.Duration) *ssh.Certificate { + t.Helper() + now := time.Now() + c := &ssh.Certificate{ + Key: key, + CertType: certType, + KeyId: "ziti:test", + ValidPrincipals: []string{"ziggy"}, + ValidAfter: uint64(now.Unix()), + ValidBefore: uint64(now.Add(lifetime).Unix()), + } + if err := c.SignCert(rand.Reader, ca); err != nil { + t.Fatal(err) + } + return c +} + +func authLine(k ssh.PublicKey) string { return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(k))) } + +func TestValidateSignedCert(t *testing.T) { + ca, user, other := newKey(t), newKey(t), newKey(t) + ourPub := authLine(user.PublicKey()) + + good := authLine(signCert(t, ca, user.PublicKey(), ssh.UserCert, 5*time.Minute)) + if out, err := ValidateSignedCert(good, ourPub); err != nil || !strings.HasPrefix(string(out), "ssh-ed25519-cert-v01@openssh.com ") { + t.Fatalf("valid cert rejected: out=%q err=%v", out, err) + } + + cases := []struct { + name string + line string + }{ + {"empty", ""}, + {"junk", "not a certificate"}, + {"plain public key", ourPub}, + {"certificate for another key", authLine(signCert(t, ca, other.PublicKey(), ssh.UserCert, 5*time.Minute))}, + {"host certificate", authLine(signCert(t, ca, user.PublicKey(), ssh.HostCert, 5*time.Minute))}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if _, err := ValidateSignedCert(tc.line, ourPub); err == nil { + t.Fatal("accepted, want error") + } + }) + } + + _, err := ValidateSignedCert("error: rate limit exceeded", ourPub) + var rej *CARejectedError + if !errors.As(err, &rej) || rej.Reason != "rate limit exceeded" { + t.Fatalf("error reply: got %v, want CARejectedError(rate limit exceeded)", err) + } +} + +func TestReadCAResponse(t *testing.T) { + if got, err := ReadCAResponse(strings.NewReader("ssh-ed25519-cert AAAA\nextra")); err != nil || got != "ssh-ed25519-cert AAAA" { + t.Errorf("newline-terminated: got %q, %v", got, err) + } + if got, err := ReadCAResponse(strings.NewReader("error: rate limit exceeded")); err != nil || got != "error: rate limit exceeded" { + t.Errorf("EOF without newline: got %q, %v", got, err) + } + if _, err := ReadCAResponse(strings.NewReader("")); err == nil { + t.Error("empty response accepted") + } + if _, err := ReadCAResponse(strings.NewReader(strings.Repeat("A", MaxCAResponseBytes+10) + "\n")); err == nil { + t.Error("oversized response accepted") + } +} + +func TestCertNeedsRefreshAt(t *testing.T) { + ca, user := newKey(t), newKey(t) + now := time.Now() + + fiveMin := signCert(t, ca, user.PublicKey(), ssh.UserCert, 5*time.Minute) + if got := certRefreshThreshold(fiveMin); got != time.Minute { + t.Errorf("5m cert threshold = %v, want 1m", got) + } + // Regression: a fresh 5-minute cert must not be refreshed immediately. + if certNeedsRefreshAt(fiveMin, now) { + t.Error("fresh 5-minute certificate needs refresh (re-sign on every call)") + } + if certNeedsRefreshAt(fiveMin, now.Add(3*time.Minute)) { + t.Error("5-minute certificate with 2m left needs refresh") + } + if !certNeedsRefreshAt(fiveMin, now.Add(4*time.Minute+30*time.Second)) { + t.Error("5-minute certificate with 30s left does not need refresh") + } + if !certNeedsRefreshAt(fiveMin, now.Add(6*time.Minute)) { + t.Error("expired certificate does not need refresh") + } + + eightHour := signCert(t, ca, user.PublicKey(), ssh.UserCert, 8*time.Hour) + if got := certRefreshThreshold(eightHour); got != 5*time.Minute { + t.Errorf("8h cert threshold = %v, want 5m (unchanged behaviour)", got) + } + + oneMin := signCert(t, ca, user.PublicKey(), ssh.UserCert, time.Minute) + if got := certRefreshThreshold(oneMin); got != 30*time.Second { + t.Errorf("1m cert threshold = %v, want 30s floor", got) + } + + forever := &ssh.Certificate{ValidBefore: ssh.CertTimeInfinity} + if certNeedsRefreshAt(forever, now) { + t.Error("non-expiring certificate needs refresh") + } +} + +func TestCertPrincipal(t *testing.T) { + dir := t.TempDir() + ca, user := newKey(t), newKey(t) + write := func(name string, principals ...string) string { + c := signCert(t, ca, user.PublicKey(), ssh.UserCert, 5*time.Minute) + c.ValidPrincipals = principals + if err := c.SignCert(rand.Reader, ca); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, name) + if err := os.WriteFile(p, ssh.MarshalAuthorizedKey(c), 0o644); err != nil { + t.Fatal(err) + } + return p + } + if p, ok := CertPrincipal(write("one", "alice_corp_com")); !ok || p != "alice_corp_com" { + t.Errorf("single principal: %q, %v", p, ok) + } + if _, ok := CertPrincipal(write("two", "a", "b")); ok { + t.Error("two principals: want no default") + } + if _, ok := CertPrincipal(filepath.Join(dir, "missing")); ok { + t.Error("missing file: want no default") + } + plain := filepath.Join(dir, "plain.pub") + if err := os.WriteFile(plain, ssh.MarshalAuthorizedKey(user.PublicKey()), 0o644); err != nil { + t.Fatal(err) + } + if _, ok := CertPrincipal(plain); ok { + t.Error("plain public key: want no default") + } +} diff --git a/client/forward_test.go b/client/forward_test.go new file mode 100644 index 0000000..9721a14 --- /dev/null +++ b/client/forward_test.go @@ -0,0 +1,398 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package client + +import ( + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "encoding/binary" + "io" + "net" + "strconv" + "sync" + "testing" + "time" + + "golang.org/x/crypto/ssh" +) + +// echoServer accepts connections on network/addr and echoes everything back. +func echoServer(t *testing.T, network, addr string) string { + t.Helper() + ln, err := net.Listen(network, addr) + if err != nil { + t.Skipf("listen %s %s: %v", network, addr, err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func() { defer c.Close(); _, _ = io.Copy(c, c) }() + } + }() + return ln.Addr().String() +} + +func freePort(t *testing.T) string { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer ln.Close() + _, port, _ := net.SplitHostPort(ln.Addr().String()) + return port +} + +func pipeChannel(ch ssh.Channel, c net.Conn) { + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); _, _ = io.Copy(ch, c); _ = ch.CloseWrite() }() + go func() { defer wg.Done(); _, _ = io.Copy(c, ch) }() + wg.Wait() + ch.Close() + c.Close() +} + +// testSSHClient starts an in-process SSH server that implements direct-tcpip +// (for -L / -D) and tcpip-forward (for -R), and returns a client for it. +func testSSHClient(t *testing.T) *ssh.Client { + t.Helper() + _, hostPriv, _ := ed25519.GenerateKey(rand.Reader) + hostSigner, err := ssh.NewSignerFromKey(hostPriv) + if err != nil { + t.Fatal(err) + } + cfg := &ssh.ServerConfig{NoClientAuth: true} + cfg.AddHostKey(hostSigner) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + nc, err := ln.Accept() + if err != nil { + return + } + go serveSSH(nc, cfg) + } + }() + + client, err := ssh.Dial("tcp", ln.Addr().String(), &ssh.ClientConfig{ + User: "test", + HostKeyCallback: ssh.InsecureIgnoreHostKey(), //nolint:gosec // in-process test server + Timeout: 5 * time.Second, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { client.Close() }) + return client +} + +func serveSSH(nc net.Conn, cfg *ssh.ServerConfig) { + sconn, chans, reqs, err := ssh.NewServerConn(nc, cfg) + if err != nil { + return + } + go func() { + for req := range reqs { + if req.Type != "tcpip-forward" { + _ = req.Reply(false, nil) + continue + } + var fwd struct { + Addr string + Port uint32 + } + if ssh.Unmarshal(req.Payload, &fwd) != nil { + _ = req.Reply(false, nil) + continue + } + rl, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(fwd.Port)))) + if err != nil { + _ = req.Reply(false, nil) + continue + } + _ = req.Reply(true, nil) + go func() { + defer rl.Close() + for { + c, err := rl.Accept() + if err != nil { + return + } + payload := ssh.Marshal(struct { + Addr string + Port uint32 + OrigAddr string + OrigPort uint32 + }{fwd.Addr, fwd.Port, "127.0.0.1", uint32(c.RemoteAddr().(*net.TCPAddr).Port)}) + ch, chReqs, err := sconn.OpenChannel("forwarded-tcpip", payload) + if err != nil { + c.Close() + continue + } + go ssh.DiscardRequests(chReqs) + go pipeChannel(ch, c) + } + }() + go func() { _ = sconn.Wait(); rl.Close() }() + } + }() + for nch := range chans { + if nch.ChannelType() != "direct-tcpip" { + _ = nch.Reject(ssh.UnknownChannelType, "unsupported") + continue + } + var d struct { + Host string + Port uint32 + OrigHost string + OrigPort uint32 + } + if ssh.Unmarshal(nch.ExtraData(), &d) != nil { + _ = nch.Reject(ssh.ConnectionFailed, "bad payload") + continue + } + c, err := net.Dial("tcp", net.JoinHostPort(d.Host, strconv.Itoa(int(d.Port)))) + if err != nil { + _ = nch.Reject(ssh.ConnectionFailed, err.Error()) + continue + } + ch, chReqs, err := nch.Accept() + if err != nil { + c.Close() + continue + } + go ssh.DiscardRequests(chReqs) + go pipeChannel(ch, c) + } +} + +// dialRetry dials addr until it is accepted (the forward starts listening +// asynchronously). +func dialRetry(t *testing.T, addr string) net.Conn { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + c, err := net.Dial("tcp", addr) + if err == nil { + return c + } + if time.Now().After(deadline) { + t.Fatalf("dial %s: %v", addr, err) + } + time.Sleep(20 * time.Millisecond) + } +} + +func assertEcho(t *testing.T, c net.Conn, msg string) { + t.Helper() + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) + if _, err := c.Write([]byte(msg)); err != nil { + t.Fatal(err) + } + buf := make([]byte, len(msg)) + if _, err := io.ReadFull(c, buf); err != nil { + t.Fatal(err) + } + if string(buf) != msg { + t.Fatalf("echo = %q, want %q", buf, msg) + } +} + +func TestRunLocalForward(t *testing.T) { + client := testSSHClient(t) + echoHost, echoPort, _ := net.SplitHostPort(echoServer(t, "tcp", "127.0.0.1:0")) + port := freePort(t) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { + done <- RunLocalForward(ctx, client, LocalForwardSpec{Bind: "127.0.0.1", LocalPort: port, RemoteHost: echoHost, RemotePort: echoPort}) + }() + c := dialRetry(t, net.JoinHostPort("127.0.0.1", port)) + assertEcho(t, c, "hello through -L") + c.Close() + + cancel() + select { + case err := <-done: + if err != nil { + t.Errorf("RunLocalForward after cancel: %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("RunLocalForward did not stop on cancel") + } +} + +func TestRunRemoteForward(t *testing.T) { + client := testSSHClient(t) + echoHost, echoPort, _ := net.SplitHostPort(echoServer(t, "tcp", "127.0.0.1:0")) + port := freePort(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + _ = RunRemoteForward(ctx, client, RemoteForwardSpec{Bind: "127.0.0.1", RemotePort: port, LocalHost: echoHost, LocalPort: echoPort}) + }() + // The test server listens on the requested port on the "remote" side as + // soon as it accepts the request; the client registers the forward only + // after the reply, so an early connection can be rejected. Retry until a + // round trip succeeds. + addr := net.JoinHostPort("127.0.0.1", port) + deadline := time.Now().Add(5 * time.Second) + for { + c := dialRetry(t, addr) + _ = c.SetDeadline(time.Now().Add(2 * time.Second)) + msg := "hello through -R" + _, werr := c.Write([]byte(msg)) + buf := make([]byte, len(msg)) + _, rerr := io.ReadFull(c, buf) + c.Close() + if werr == nil && rerr == nil && string(buf) == msg { + return + } + if time.Now().After(deadline) { + t.Fatalf("no echo through -R: write %v, read %v, got %q", werr, rerr, buf) + } + time.Sleep(50 * time.Millisecond) + } +} + +// socks5 opens a connection to the proxy and performs the greeting with the +// given methods, returning the connection and the server's method choice. +func socks5(t *testing.T, proxy string, methods ...byte) (net.Conn, []byte) { + t.Helper() + c := dialRetry(t, proxy) + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) + if _, err := c.Write(append([]byte{0x05, byte(len(methods))}, methods...)); err != nil { + t.Fatal(err) + } + reply := make([]byte, 2) + if _, err := io.ReadFull(c, reply); err != nil { + t.Fatalf("greeting reply: %v", err) + } + return c, reply +} + +func socks5Connect(t *testing.T, c net.Conn, cmd, atyp byte, addr []byte, port uint16) byte { + t.Helper() + req := append([]byte{0x05, cmd, 0x00, atyp}, addr...) + req = binary.BigEndian.AppendUint16(req, port) + if _, err := c.Write(req); err != nil { + t.Fatal(err) + } + reply := make([]byte, 10) + if _, err := io.ReadFull(c, reply); err != nil { + t.Fatalf("connect reply: %v", err) + } + return reply[1] +} + +func TestRunDynamicProxy_SOCKS5(t *testing.T) { + client := testSSHClient(t) + _, echoPortStr, _ := net.SplitHostPort(echoServer(t, "tcp", "127.0.0.1:0")) + echoPort, _ := strconv.Atoi(echoPortStr) + port := freePort(t) + proxy := net.JoinHostPort("127.0.0.1", port) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { _ = RunDynamicProxy(ctx, client, DynamicForwardSpec{Bind: "127.0.0.1", LocalPort: port}) }() + + t.Run("IPv4", func(t *testing.T) { + c, m := socks5(t, proxy, 0x00) + defer c.Close() + if !bytes.Equal(m, []byte{0x05, 0x00}) { + t.Fatalf("method reply %v", m) + } + if st := socks5Connect(t, c, 0x01, 0x01, net.ParseIP("127.0.0.1").To4(), uint16(echoPort)); st != 0x00 { + t.Fatalf("status %#x", st) + } + assertEcho(t, c, "ipv4") + }) + t.Run("DomainName", func(t *testing.T) { + c, _ := socks5(t, proxy, 0x02, 0x00) + defer c.Close() + name := []byte("localhost") + if st := socks5Connect(t, c, 0x01, 0x03, append([]byte{byte(len(name))}, name...), uint16(echoPort)); st != 0x00 { + t.Skipf("localhost did not resolve to the IPv4 echo server (status %#x)", st) + } + assertEcho(t, c, "domain") + }) + t.Run("IPv6", func(t *testing.T) { + _, p6, _ := net.SplitHostPort(echoServer(t, "tcp6", "[::1]:0")) + port6, _ := strconv.Atoi(p6) + c, _ := socks5(t, proxy, 0x00) + defer c.Close() + if st := socks5Connect(t, c, 0x01, 0x04, net.ParseIP("::1").To16(), uint16(port6)); st != 0x00 { + t.Fatalf("status %#x", st) + } + assertEcho(t, c, "ipv6") + }) + t.Run("UnsupportedCommand", func(t *testing.T) { + c, _ := socks5(t, proxy, 0x00) + defer c.Close() + if st := socks5Connect(t, c, 0x02 /* BIND */, 0x01, net.ParseIP("127.0.0.1").To4(), uint16(echoPort)); st != 0x07 { + t.Fatalf("BIND status %#x, want 0x07", st) + } + }) + t.Run("UnsupportedAddressType", func(t *testing.T) { + c, _ := socks5(t, proxy, 0x00) + defer c.Close() + if _, err := c.Write([]byte{0x05, 0x01, 0x00, 0x09}); err != nil { + t.Fatal(err) + } + reply := make([]byte, 10) + if _, err := io.ReadFull(c, reply); err != nil || reply[1] != 0x08 { + t.Fatalf("reply %v, %v; want status 0x08", reply, err) + } + }) + t.Run("RefusesWithoutNoAuthMethod", func(t *testing.T) { + c, m := socks5(t, proxy, 0x02) // username/password only + defer c.Close() + if !bytes.Equal(m, []byte{0x05, 0xFF}) { + t.Fatalf("method reply %v, want [5 255]", m) + } + }) + t.Run("RefusesSOCKS4", func(t *testing.T) { + c := dialRetry(t, proxy) + defer c.Close() + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) + _, _ = c.Write([]byte{0x04, 0x01, 0x00, 0x50, 127, 0, 0, 1, 0}) + // Closed without a reply (EOF, or a reset because the request was + // left unread). + if n, err := c.Read(make([]byte, 1)); n != 0 || err == nil { + t.Fatalf("SOCKS4 not refused: read %d bytes, %v", n, err) + } + }) + t.Run("ConnectionRefusedStatus", func(t *testing.T) { + c, _ := socks5(t, proxy, 0x00) + defer c.Close() + closed, _ := strconv.Atoi(freePort(t)) + if st := socks5Connect(t, c, 0x01, 0x01, net.ParseIP("127.0.0.1").To4(), uint16(closed)); st != 0x05 { + t.Fatalf("status %#x, want 0x05", st) + } + }) +} diff --git a/client/hostkeys.go b/client/hostkeys.go new file mode 100644 index 0000000..b3ba749 --- /dev/null +++ b/client/hostkeys.go @@ -0,0 +1,319 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package client + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/netfoundry/ziti-ssh/config" + "golang.org/x/crypto/ssh" + "golang.org/x/term" +) + +// Host key trust on first use. +// +// OpenZiti does not tell a dialer which identity answered on a terminator +// address, so ziti-ssh cannot verify a host's identity. Instead it remembers +// the SSH host key(s) seen for each Ziti address and detects changes: +// +// - address dialed by terminator name ("@"), i.e. one +// host: an unknown address is trusted and saved; a different key is +// refused (remove the entry with "ziti-ssh known-hosts remove" after a +// legitimate rebuild). +// - service dialed by name (""), where any host bound to the +// service may answer: an unknown address is trusted and saved; a +// different key is shown with a warning and, if the user agrees, saved as +// an additional key for that service. Without a terminal it is refused. + +// KnownHostsAddress returns the address under which host keys are recorded: +// "@" for a terminator dial, or "" when the +// service is dialed directly (any host bound to it may answer). +func KnownHostsAddress(service, terminator string) string { + if terminator == "" { + return service + } + return terminator + "@" + service +} + +// DefaultKnownHostsPath returns $XDG_CONFIG_HOME/ziti-ssh/known_hosts +// (default ~/.config/ziti-ssh/known_hosts). +func DefaultKnownHostsPath() (string, error) { + base := os.Getenv("XDG_CONFIG_HOME") + if base == "" { + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("resolve home directory: %w", err) + } + base = filepath.Join(home, ".config") + } + return filepath.Join(base, "ziti-ssh", "known_hosts"), nil +} + +// KnownHosts is a file of "
" lines (the +// OpenSSH known_hosts line format, with Ziti addresses instead of hostnames). +type KnownHosts struct { + Path string +} + +type knownHostEntry struct { + addr string + key ssh.PublicKey +} + +func (k KnownHosts) read() ([]knownHostEntry, error) { + // Host keys decide which servers are trusted: refuse a file that another + // user could have written. + if err := config.CheckUserFile(k.Path); err != nil { + return nil, err + } + data, err := os.ReadFile(k.Path) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("read %s: %w", k.Path, err) + } + var out []knownHostEntry + sc := bufio.NewScanner(bytes.NewReader(data)) + for n := 1; sc.Scan(); n++ { + line := strings.TrimSpace(sc.Text()) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + addr, rest, ok := strings.Cut(line, " ") + if !ok { + return nil, fmt.Errorf("%s:%d: malformed entry", k.Path, n) + } + key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(strings.TrimSpace(rest))) + if err != nil { + return nil, fmt.Errorf("%s:%d: %w", k.Path, n, err) + } + out = append(out, knownHostEntry{addr: addr, key: key}) + } + return out, sc.Err() +} + +func (k KnownHosts) write(entries []knownHostEntry) error { + var b strings.Builder + b.WriteString("# ziti-ssh known host keys: \n") + for _, e := range entries { + b.WriteString(e.addr) + b.WriteByte(' ') + b.Write(bytes.TrimSpace(ssh.MarshalAuthorizedKey(e.key))) + b.WriteByte('\n') + } + dir := filepath.Dir(k.Path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("create %s: %w", dir, err) + } + tmp, err := os.CreateTemp(dir, ".known_hosts-*") + if err != nil { + return fmt.Errorf("create temp file: %w", err) + } + tmpPath := tmp.Name() + if _, err := tmp.WriteString(b.String()); err != nil { + tmp.Close() + os.Remove(tmpPath) + return fmt.Errorf("write %s: %w", tmpPath, err) + } + if err := tmp.Chmod(0o600); err != nil { + tmp.Close() + os.Remove(tmpPath) + return err + } + if err := tmp.Close(); err != nil { + os.Remove(tmpPath) + return err + } + // Atomic replace. Concurrent ziti-ssh processes may race; the worst case + // is a lost entry, which is re-learned on the next connection. + if err := os.Rename(tmpPath, k.Path); err != nil { + os.Remove(tmpPath) + return fmt.Errorf("replace %s: %w", k.Path, err) + } + return nil +} + +// Keys returns the keys recorded for addr. +func (k KnownHosts) Keys(addr string) ([]ssh.PublicKey, error) { + entries, err := k.read() + if err != nil { + return nil, err + } + var out []ssh.PublicKey + for _, e := range entries { + if e.addr == addr { + out = append(out, e.key) + } + } + return out, nil +} + +// Add records key for addr (no-op if already present). +func (k KnownHosts) Add(addr string, key ssh.PublicKey) error { + entries, err := k.read() + if err != nil { + return err + } + for _, e := range entries { + if e.addr == addr && bytes.Equal(e.key.Marshal(), key.Marshal()) { + return nil + } + } + return k.write(append(entries, knownHostEntry{addr: addr, key: key})) +} + +// Remove deletes every key recorded for addr and returns how many it removed. +func (k KnownHosts) Remove(addr string) (int, error) { + entries, err := k.read() + if err != nil { + return 0, err + } + kept := entries[:0] + removed := 0 + for _, e := range entries { + if e.addr == addr { + removed++ + continue + } + kept = append(kept, e) + } + if removed == 0 { + return 0, nil + } + return removed, k.write(kept) +} + +// List writes "
" for every entry, +// sorted by address. +func (k KnownHosts) List(w io.Writer) error { + entries, err := k.read() + if err != nil { + return err + } + sort.SliceStable(entries, func(i, j int) bool { return entries[i].addr < entries[j].addr }) + for _, e := range entries { + fmt.Fprintf(w, "%s %s %s\n", e.addr, e.key.Type(), ssh.FingerprintSHA256(e.key)) + } + return nil +} + +// HostKeyPolicy configures HostKeyCallback. +type HostKeyPolicy struct { + Store KnownHosts + // Address is the Ziti address dialed (see KnownHostsAddress). + Address string + // MultiHost is true when the service was dialed directly, so any host + // bound to it may answer and several keys may be legitimate. + MultiHost bool + // Confirm asks the user a yes/no question; nil means non-interactive. + Confirm func(question string) bool + // Notify receives informational and warning messages (normally stderr). + Notify io.Writer +} + +// HostKeyCallback returns an ssh.HostKeyCallback implementing trust on first +// use for p.Address (see the package comment above). +func HostKeyCallback(p HostKeyPolicy) ssh.HostKeyCallback { + notify := p.Notify + if notify == nil { + notify = io.Discard + } + return func(_ string, _ net.Addr, key ssh.PublicKey) error { + known, err := p.Store.Keys(p.Address) + if err != nil { + return fmt.Errorf("known hosts: %w", err) + } + for _, k := range known { + if bytes.Equal(k.Marshal(), key.Marshal()) { + return nil + } + } + fp := ssh.FingerprintSHA256(key) + if len(known) == 0 { + if err := p.Store.Add(p.Address, key); err != nil { + return fmt.Errorf("known hosts: %w", err) + } + fmt.Fprintf(notify, "Permanently added host key for %s (%s %s) to %s\n", p.Address, key.Type(), fp, p.Store.Path) + return nil + } + + var prints []string + for _, k := range known { + prints = append(prints, k.Type()+" "+ssh.FingerprintSHA256(k)) + } + if !p.MultiHost { + fmt.Fprintf(notify, "@@@ WARNING: HOST KEY FOR %s HAS CHANGED @@@\n"+ + "Someone could be impersonating this host, or it may have been rebuilt.\n"+ + " known: %s\n received: %s %s\n"+ + "If the change is expected, run: ziti-ssh known-hosts remove %s\n", + p.Address, strings.Join(prints, ", "), key.Type(), fp, p.Address) + return fmt.Errorf("host key for %s has changed; refusing to connect", p.Address) + } + + msg := fmt.Sprintf("WARNING: service %s answered with a host key not seen before.\n"+ + "Any host bound to the service may answer, so this may be another member of the pool,\n"+ + "or someone impersonating one.\n known: %s\n received: %s %s\n", + p.Address, strings.Join(prints, ", "), key.Type(), fp) + fmt.Fprint(notify, msg) + if p.Confirm == nil { + return fmt.Errorf("new host key for service %s; run ziti-ssh interactively once to review and accept it", p.Address) + } + if !p.Confirm(fmt.Sprintf("Trust this additional key for %s? [y/N] ", p.Address)) { + return fmt.Errorf("host key for service %s not accepted", p.Address) + } + if err := p.Store.Add(p.Address, key); err != nil { + return fmt.Errorf("known hosts: %w", err) + } + fmt.Fprintf(notify, "Added additional host key for %s (%s %s)\n", p.Address, key.Type(), fp) + return nil + } +} + +// NewHostKeyCallback returns the host-key check for a connection to service +// (and terminator, empty for a direct service dial), using the default known +// hosts file. It asks on the terminal before trusting an additional key for a +// directly dialed service, and only when stdin and stderr are terminals. +func NewHostKeyCallback(service, terminator string) (ssh.HostKeyCallback, error) { + path, err := DefaultKnownHostsPath() + if err != nil { + return nil, err + } + p := HostKeyPolicy{ + Store: KnownHosts{Path: path}, + Address: KnownHostsAddress(service, terminator), + MultiHost: terminator == "", + Notify: os.Stderr, + } + if term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stderr.Fd())) { + p.Confirm = func(question string) bool { + fmt.Fprint(os.Stderr, question) + line, _ := bufio.NewReader(os.Stdin).ReadString('\n') + return strings.EqualFold(strings.TrimSpace(line), "y") || strings.EqualFold(strings.TrimSpace(line), "yes") + } + } + return HostKeyCallback(p), nil +} diff --git a/client/hostkeys_test.go b/client/hostkeys_test.go new file mode 100644 index 0000000..c9d6b82 --- /dev/null +++ b/client/hostkeys_test.go @@ -0,0 +1,186 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package client + +import ( + "bytes" + "os" + "path/filepath" + "strings" + "testing" + + "golang.org/x/crypto/ssh" +) + +func hostKey(t *testing.T) ssh.PublicKey { + t.Helper() + return newKey(t).PublicKey() +} + +func store(t *testing.T) KnownHosts { + return KnownHosts{Path: filepath.Join(t.TempDir(), "ziti-ssh", "known_hosts")} +} + +func TestKnownHostsAddress(t *testing.T) { + if got := KnownHostsAddress("ssh", "web-server-prod"); got != "web-server-prod@ssh" { + t.Errorf("terminator dial: %q", got) + } + if got := KnownHostsAddress("ssh-db-pool", ""); got != "ssh-db-pool" { + t.Errorf("service dial: %q", got) + } +} + +func TestHostKeyCallback_TrustOnFirstUse(t *testing.T) { + kh := store(t) + var out bytes.Buffer + cb := HostKeyCallback(HostKeyPolicy{Store: kh, Address: "web@ssh", Notify: &out}) + k := hostKey(t) + + if err := cb("web", nil, k); err != nil { + t.Fatalf("first use refused: %v", err) + } + if !strings.Contains(out.String(), "Permanently added host key for web@ssh") { + t.Errorf("no notice on first use: %q", out.String()) + } + if err := cb("web", nil, k); err != nil { + t.Fatalf("known key refused: %v", err) + } + fi, err := os.Stat(kh.Path) + if err != nil { + t.Fatal(err) + } + if fi.Mode().Perm() != 0o600 { + t.Errorf("known_hosts mode %o, want 600", fi.Mode().Perm()) + } +} + +func TestHostKeyCallback_TerminatorAddressRefusesChange(t *testing.T) { + kh := store(t) + var out bytes.Buffer + asked := false + cb := HostKeyCallback(HostKeyPolicy{Store: kh, Address: "web@ssh", Notify: &out, + Confirm: func(string) bool { asked = true; return true }}) + if err := cb("web", nil, hostKey(t)); err != nil { + t.Fatal(err) + } + impostor := hostKey(t) + err := cb("web", nil, impostor) + if err == nil || !strings.Contains(err.Error(), "has changed") { + t.Fatalf("changed key accepted: %v", err) + } + if asked { + t.Error("user was asked to accept a changed key for a single-host address") + } + if !strings.Contains(out.String(), "ziti-ssh known-hosts remove web@ssh") { + t.Errorf("warning lacks remediation: %q", out.String()) + } + if keys, _ := kh.Keys("web@ssh"); len(keys) != 1 { + t.Errorf("changed key was saved: %d keys", len(keys)) + } +} + +func TestHostKeyCallback_ServiceAddressAsksForAdditionalKey(t *testing.T) { + first, second := hostKey(t), hostKey(t) + + t.Run("accepted", func(t *testing.T) { + kh := store(t) + cb := HostKeyCallback(HostKeyPolicy{Store: kh, Address: "pool", MultiHost: true, + Confirm: func(string) bool { return true }}) + if err := cb("pool", nil, first); err != nil { + t.Fatal(err) + } + if err := cb("pool", nil, second); err != nil { + t.Fatalf("accepted additional key refused: %v", err) + } + if keys, _ := kh.Keys("pool"); len(keys) != 2 { + t.Fatalf("want both keys remembered, got %d", len(keys)) + } + // Both members now connect without asking. + silent := HostKeyCallback(HostKeyPolicy{Store: kh, Address: "pool", MultiHost: true}) + for _, k := range []ssh.PublicKey{first, second} { + if err := silent("pool", nil, k); err != nil { + t.Errorf("remembered pool member refused: %v", err) + } + } + }) + + t.Run("declined", func(t *testing.T) { + kh := store(t) + cb := HostKeyCallback(HostKeyPolicy{Store: kh, Address: "pool", MultiHost: true, + Confirm: func(string) bool { return false }}) + _ = cb("pool", nil, first) + if err := cb("pool", nil, second); err == nil { + t.Fatal("declined key accepted") + } + if keys, _ := kh.Keys("pool"); len(keys) != 1 { + t.Errorf("declined key saved") + } + }) + + t.Run("non-interactive", func(t *testing.T) { + kh := store(t) + cb := HostKeyCallback(HostKeyPolicy{Store: kh, Address: "pool", MultiHost: true}) + _ = cb("pool", nil, first) + if err := cb("pool", nil, second); err == nil || !strings.Contains(err.Error(), "interactively") { + t.Fatalf("new key accepted without a terminal: %v", err) + } + }) +} + +func TestKnownHosts_ListAndRemove(t *testing.T) { + kh := store(t) + a, b := hostKey(t), hostKey(t) + for _, e := range []struct { + addr string + k ssh.PublicKey + }{{"web@ssh", a}, {"pool", a}, {"pool", b}} { + if err := kh.Add(e.addr, e.k); err != nil { + t.Fatal(err) + } + } + if err := kh.Add("pool", b); err != nil { // duplicate: no-op + t.Fatal(err) + } + var out bytes.Buffer + if err := kh.List(&out); err != nil { + t.Fatal(err) + } + if lines := strings.Count(out.String(), "\n"); lines != 3 { + t.Errorf("list has %d lines, want 3:\n%s", lines, out.String()) + } + n, err := kh.Remove("pool") + if err != nil || n != 2 { + t.Fatalf("remove pool: n=%d err=%v", n, err) + } + if keys, _ := kh.Keys("web@ssh"); len(keys) != 1 { + t.Error("unrelated entry removed") + } +} + +func TestKnownHosts_MalformedFileFailsClosed(t *testing.T) { + kh := store(t) + if err := os.MkdirAll(filepath.Dir(kh.Path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(kh.Path, []byte("web@ssh not-a-key\n"), 0o600); err != nil { + t.Fatal(err) + } + cb := HostKeyCallback(HostKeyPolicy{Store: kh, Address: "web@ssh"}) + if err := cb("web", nil, hostKey(t)); err == nil { + t.Fatal("connection allowed with an unreadable known_hosts file") + } +} diff --git a/client/passphrase_test.go b/client/passphrase_test.go new file mode 100644 index 0000000..8166f37 --- /dev/null +++ b/client/passphrase_test.go @@ -0,0 +1,98 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package client + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/pem" + "os" + "path/filepath" + "testing" + + "golang.org/x/crypto/ssh" +) + +func writeEncryptedKey(t *testing.T, pass string) (string, ssh.PublicKey) { + t.Helper() + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + block, err := ssh.MarshalPrivateKeyWithPassphrase(priv, "", []byte(pass)) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "id_ed25519") + if err := os.WriteFile(path, pem.EncodeToMemory(block), 0o600); err != nil { + t.Fatal(err) + } + sshPub, err := ssh.NewPublicKey(pub) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path+".pub", ssh.MarshalAuthorizedKey(sshPub), 0o644); err != nil { + t.Fatal(err) + } + return path, sshPub +} + +func TestNewCertSignerPrompt_AsksForPassphraseWithoutAgent(t *testing.T) { + t.Setenv("SSH_AUTH_SOCK", "") + path, pub := writeEncryptedKey(t, "s3cret") + + // Without a prompt the old behaviour stays: an error naming the agent. + if _, err := NewCertSigner(path); err == nil { + t.Fatal("encrypted key loaded without agent or passphrase") + } + + asked := 0 + signer, err := NewCertSignerPrompt(path, func() ([]byte, error) { + asked++ + return []byte("s3cret"), nil + }) + if err != nil { + t.Fatalf("NewCertSignerPrompt: %v", err) + } + if asked != 1 { + t.Errorf("prompt called %d times", asked) + } + if string(signer.PublicKey().Marshal()) != string(pub.Marshal()) { + t.Error("signer has the wrong public key") + } + + if _, err := NewCertSignerPrompt(path, func() ([]byte, error) { return []byte("wrong"), nil }); err == nil { + t.Error("wrong passphrase accepted") + } +} + +func TestKnownHosts_RefusesWritableByOthers(t *testing.T) { + path := filepath.Join(t.TempDir(), "known_hosts") + if err := os.WriteFile(path, nil, 0o600); err != nil { + t.Fatal(err) + } + kh := KnownHosts{Path: path} + if _, err := kh.read(); err != nil { + t.Fatalf("0600 refused: %v", err) + } + if err := os.Chmod(path, 0o666); err != nil { + t.Fatal(err) + } + if _, err := kh.read(); err == nil { + t.Fatal("world-writable known_hosts accepted") + } +} diff --git a/client/sftp.go b/client/sftp.go index 7b83c44..c029337 100644 --- a/client/sftp.go +++ b/client/sftp.go @@ -61,16 +61,14 @@ func RunSFTP( recursive bool, preserve bool, quiet bool, + hostKeyCallback ssh.HostKeyCallback, ) error { cfg := &ssh.ClientConfig{ - User: user, - Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)}, - // Host key verification is intentionally skipped. The connection arrives - // over a Ziti overlay that enforces mutual TLS using the controller's - // PKI — the host's Ziti identity is cryptographically proven before any - // SSH bytes are exchanged. A traditional known-hosts check would be - // redundant and weaker than the guarantee Ziti already provides. - HostKeyCallback: ssh.InsecureIgnoreHostKey(), //nolint:gosec + User: user, + Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)}, + // OpenZiti does not tell the dialer which identity answered, so the + // host key is checked against keys seen before (see HostKeyCallback). + HostKeyCallback: hostKeyCallback, } clientConn, chans, reqs, err := ssh.NewClientConn(conn, host, cfg) @@ -124,7 +122,7 @@ func uploadAll(client *sftp.Client, localPaths []string, remoteDst string, recur } else { dstDir = remoteDst } - if err := uploadDir(client, localPath, dstDir, preserve, quiet); err != nil { + if err := uploadDir(client, localPath, dstDir, preserve, quiet, 0); err != nil { return err } } else { @@ -142,7 +140,10 @@ func uploadAll(client *sftp.Client, localPaths []string, remoteDst string, recur return nil } -func uploadDir(client *sftp.Client, localDir, remoteDir string, preserve, quiet bool) error { +func uploadDir(client *sftp.Client, localDir, remoteDir string, preserve, quiet bool, depth int) error { + if depth > maxRecursionDepth { + return fmt.Errorf("local directory %q exceeds the maximum depth of %d", localDir, maxRecursionDepth) + } if err := client.MkdirAll(remoteDir); err != nil { return fmt.Errorf("mkdir remote %q: %w", remoteDir, err) } @@ -156,7 +157,7 @@ func uploadDir(client *sftp.Client, localDir, remoteDir string, preserve, quiet localPath := filepath.Join(localDir, entry.Name()) remotePath := path.Join(remoteDir, entry.Name()) if entry.IsDir() { - if err := uploadDir(client, localPath, remotePath, preserve, quiet); err != nil { + if err := uploadDir(client, localPath, remotePath, preserve, quiet, depth+1); err != nil { return err } } else { @@ -256,7 +257,7 @@ func downloadAll(client *sftp.Client, remotePaths []string, localDst string, rec } else { localDir = localDst } - if err := downloadDir(client, remotePath, localDir, preserve, quiet); err != nil { + if err := downloadDir(client, remotePath, localDir, preserve, quiet, 0); err != nil { return err } } else { @@ -274,7 +275,13 @@ func downloadAll(client *sftp.Client, remotePaths []string, localDst string, rec return nil } -func downloadDir(client *sftp.Client, remoteDir, localDir string, preserve, quiet bool) error { +func downloadDir(client *sftp.Client, remoteDir, localDir string, preserve, quiet bool, depth int) error { + if depth > maxRecursionDepth { + return fmt.Errorf("remote directory %q exceeds the maximum depth of %d", remoteDir, maxRecursionDepth) + } + if err := refuseLocalSymlink(localDir); err != nil { + return err + } fi, err := client.Stat(remoteDir) if err != nil { return fmt.Errorf("stat remote dir %q: %w", remoteDir, err) @@ -300,7 +307,7 @@ func downloadDir(client *sftp.Client, remoteDir, localDir string, preserve, quie rPath := path.Join(remoteDir, entry.Name()) lPath := filepath.Join(localDir, entry.Name()) if entry.IsDir() { - if err := downloadDir(client, rPath, lPath, preserve, quiet); err != nil { + if err := downloadDir(client, rPath, lPath, preserve, quiet, depth+1); err != nil { return err } } else { @@ -328,20 +335,29 @@ func downloadFile(client *sftp.Client, remotePath, localPath string, preserve, q return fmt.Errorf("stat remote file %q: %w", remotePath, err) } - var perm os.FileMode = 0644 - if preserve { - perm = fi.Mode().Perm() - } + // New files take the remote file's permission bits, reduced by the local + // umask (as scp does). Perm() never includes setuid/setgid/sticky. + perm := downloadMode(fi.Mode(), preserve) if err := os.MkdirAll(filepath.Dir(localPath), 0755); err != nil { return fmt.Errorf("create local parent dir for %q: %w", localPath, err) } + if err := refuseLocalSymlink(localPath); err != nil { + return err + } dst, err := os.OpenFile(localPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) //nolint:gosec if err != nil { return fmt.Errorf("open local file %q for writing: %w", localPath, err) } defer dst.Close() + if preserve { + // -p: apply the mode exactly (not reduced by umask), except that a + // server can never make a local file world-writable. + if err := dst.Chmod(perm); err != nil { + slog.Debug("chmod local file failed (non-fatal)", "path", localPath, "err", err) + } + } var w io.Writer = dst if !quiet { @@ -427,7 +443,7 @@ func (pw *progressWriter) printProgress(now time.Time) { } eta := time.Duration(etaSec) * time.Second - name := pw.name + name := terminalSafe(pw.name) if len(name) > 30 { name = "..." + name[len(name)-27:] } @@ -442,6 +458,7 @@ func (pw *progressWriter) printProgress(now time.Time) { } func printFinalProgress(name string, total int64) { + name = terminalSafe(name) if len(name) > 30 { name = "..." + name[len(name)-27:] } @@ -480,3 +497,44 @@ func formatDuration(d time.Duration) string { } return fmt.Sprintf("%d:%02d", m, s) } + +// maxRecursionDepth bounds recursive copies; on downloads the remote server +// controls the directory structure. +const maxRecursionDepth = 64 + +// refuseLocalSymlink fails if localPath already exists as a symbolic link, so +// a download can never write through a link to a file elsewhere (for example +// a link in the target directory pointing at a shell startup file). +func refuseLocalSymlink(localPath string) error { + fi, err := os.Lstat(localPath) + if err != nil { + return nil // does not exist (or cannot be inspected; open will report it) + } + if fi.Mode()&os.ModeSymlink != 0 { + return fmt.Errorf("refusing to write through local symlink %q", localPath) + } + return nil +} + +// downloadMode returns the permission bits for a downloaded file. Only the +// 0777 bits are ever used; with preserve (-p) the world-writable bit is also +// dropped so a server cannot make a local file writable by every user. +func downloadMode(remote os.FileMode, preserve bool) os.FileMode { + perm := remote.Perm() + if preserve { + perm &^= 0o002 + } + return perm +} + +// terminalSafe replaces control characters (including ESC and C1 controls) +// in server-supplied names before they are written to the terminal, so a +// host cannot inject terminal escape sequences. +func terminalSafe(s string) string { + return strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f || (r >= 0x80 && r <= 0x9f) { + return '?' + } + return r + }, s) +} diff --git a/client/sftp_copy_test.go b/client/sftp_copy_test.go new file mode 100644 index 0000000..cab0575 --- /dev/null +++ b/client/sftp_copy_test.go @@ -0,0 +1,221 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package client + +import ( + "net" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/pkg/sftp" +) + +func writeLocal(t *testing.T, p, content string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } +} + +func readLocal(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func TestUpload_FileAndRecursiveDir(t *testing.T) { + c := memSFTP(t) + src := t.TempDir() + writeLocal(t, filepath.Join(src, "one.txt"), "one") + writeLocal(t, filepath.Join(src, "tree", "a.txt"), "a") + writeLocal(t, filepath.Join(src, "tree", "sub", "b.txt"), "b") + if err := c.Mkdir("/dst"); err != nil { + t.Fatal(err) + } + + // Single file into an existing directory. + if err := uploadAll(c, []string{filepath.Join(src, "one.txt")}, "/dst", false, false, true); err != nil { + t.Fatal(err) + } + // Directory without -r is refused. + if err := uploadAll(c, []string{filepath.Join(src, "tree")}, "/dst", false, false, true); err == nil || + !strings.Contains(err.Error(), "use -r") { + t.Fatalf("directory without -r: %v", err) + } + // Recursive directory. + if err := uploadAll(c, []string{filepath.Join(src, "tree")}, "/dst", true, false, true); err != nil { + t.Fatal(err) + } + for p, want := range map[string]string{"/dst/one.txt": "one", "/dst/tree/a.txt": "a", "/dst/tree/sub/b.txt": "b"} { + f, err := c.Open(p) + if err != nil { + t.Fatalf("%s: %v", p, err) + } + b := make([]byte, 16) + n, _ := f.Read(b) + f.Close() + if string(b[:n]) != want { + t.Errorf("%s = %q, want %q", p, b[:n], want) + } + } +} + +func TestUpload_MultipleSourcesNeedDirectory(t *testing.T) { + c := memSFTP(t) + src := t.TempDir() + writeLocal(t, filepath.Join(src, "a"), "a") + writeLocal(t, filepath.Join(src, "b"), "b") + srcs := []string{filepath.Join(src, "a"), filepath.Join(src, "b")} + if err := uploadAll(c, srcs, "/not-a-dir", false, false, true); err == nil || + !strings.Contains(err.Error(), "must be a directory") { + t.Fatalf("multiple sources to a file: %v", err) + } + if err := c.Mkdir("/d"); err != nil { + t.Fatal(err) + } + if err := uploadAll(c, srcs, "/d", false, false, true); err != nil { + t.Fatal(err) + } + for _, p := range []string{"/d/a", "/d/b"} { + if _, err := c.Stat(p); err != nil { + t.Errorf("%s missing: %v", p, err) + } + } +} + +func TestDownload_FileDirAndErrors(t *testing.T) { + c := memSFTP(t) + if err := c.MkdirAll("/r/tree/sub"); err != nil { + t.Fatal(err) + } + writeRemote(t, c, "/r/file.txt", "file") + writeRemote(t, c, "/r/tree/a.txt", "a") + writeRemote(t, c, "/r/tree/sub/b.txt", "b") + dst := t.TempDir() + + if err := downloadAll(c, []string{"/r/file.txt"}, dst, false, false, true); err != nil { + t.Fatal(err) + } + if got := readLocal(t, filepath.Join(dst, "file.txt")); got != "file" { + t.Errorf("file.txt = %q", got) + } + // Single file to an explicit new file name. + if err := downloadAll(c, []string{"/r/file.txt"}, filepath.Join(dst, "renamed"), false, false, true); err != nil { + t.Fatal(err) + } + if got := readLocal(t, filepath.Join(dst, "renamed")); got != "file" { + t.Errorf("renamed = %q", got) + } + if err := downloadAll(c, []string{"/r/tree"}, dst, false, false, true); err == nil || + !strings.Contains(err.Error(), "use -r") { + t.Fatalf("remote directory without -r: %v", err) + } + if err := downloadAll(c, []string{"/r/tree"}, dst, true, false, true); err != nil { + t.Fatal(err) + } + if got := readLocal(t, filepath.Join(dst, "tree", "sub", "b.txt")); got != "b" { + t.Errorf("tree/sub/b.txt = %q", got) + } + if err := downloadAll(c, []string{"/r/missing"}, dst, false, false, true); err == nil { + t.Fatal("missing remote path accepted") + } + if err := downloadAll(c, []string{"/r/file.txt", "/r/tree/a.txt"}, filepath.Join(dst, "renamed"), false, false, true); err == nil || + !strings.Contains(err.Error(), "must be a directory") { + t.Fatalf("multiple sources to a file: %v", err) + } +} + +// fsSFTP returns a client for an SFTP server backed by the real filesystem +// (the in-memory server does not keep timestamps). +func fsSFTP(t *testing.T) *sftp.Client { + t.Helper() + srvConn, cliConn := net.Pipe() + server, err := sftp.NewServer(srvConn) + if err != nil { + t.Fatal(err) + } + go func() { _ = server.Serve() }() + c, err := sftp.NewClientPipe(cliConn, cliConn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + c.Close() + server.Close() + }) + return c +} + +func TestPreserveTimes_UploadAndDownload(t *testing.T) { + c := fsSFTP(t) + when := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC) + dir := t.TempDir() + + // Upload with -p: the remote file gets the local mtime. + src := filepath.Join(dir, "src") + writeLocal(t, src, "x") + if err := os.Chtimes(src, when, when); err != nil { + t.Fatal(err) + } + remote := filepath.Join(dir, "remote") + if err := uploadAll(c, []string{src}, remote, false, true, true); err != nil { + t.Fatal(err) + } + if st, err := os.Stat(remote); err != nil || !st.ModTime().Equal(when) { + t.Errorf("upload -p: mtime %v, %v; want %v", st.ModTime(), err, when) + } + + // Download with -p: the local file gets the remote mtime. + local := filepath.Join(dir, "local") + if err := downloadAll(c, []string{remote}, local, false, true, true); err != nil { + t.Fatal(err) + } + if st, err := os.Stat(local); err != nil || !st.ModTime().Equal(when) { + t.Errorf("download -p: mtime %v, %v; want %v", st.ModTime(), err, when) + } + + // Without -p the time is not copied. + plain := filepath.Join(dir, "plain") + if err := downloadAll(c, []string{remote}, plain, false, false, true); err != nil { + t.Fatal(err) + } + if st, _ := os.Stat(plain); st.ModTime().Equal(when) { + t.Error("mtime copied without -p") + } +} + +func TestSafeName(t *testing.T) { + for _, ok := range []string{"a", "file.txt", ".hidden", "a..b"} { + if err := safeName(ok); err != nil { + t.Errorf("safeName(%q) = %v", ok, err) + } + } + for _, bad := range []string{"", ".", "..", "a/b", `a\b`, "../x", "/abs"} { + if err := safeName(bad); err == nil { + t.Errorf("safeName(%q) accepted", bad) + } + } +} diff --git a/client/sftp_test.go b/client/sftp_test.go new file mode 100644 index 0000000..4bac5df --- /dev/null +++ b/client/sftp_test.go @@ -0,0 +1,127 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package client + +import ( + "net" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/pkg/sftp" +) + +// memSFTP returns a client connected to an in-memory SFTP server. +func memSFTP(t *testing.T) *sftp.Client { + t.Helper() + srvConn, cliConn := net.Pipe() + server := sftp.NewRequestServer(srvConn, sftp.InMemHandler()) + go func() { _ = server.Serve() }() + c, err := sftp.NewClientPipe(cliConn, cliConn) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + c.Close() + server.Close() + }) + return c +} + +func writeRemote(t *testing.T, c *sftp.Client, p, content string) { + t.Helper() + f, err := c.Create(p) + if err != nil { + t.Fatal(err) + } + if _, err := f.Write([]byte(content)); err != nil { + t.Fatal(err) + } + f.Close() +} + +func TestDownload_RefusesToWriteThroughLocalSymlink(t *testing.T) { + c := memSFTP(t) + if err := c.Mkdir("/d"); err != nil { + t.Fatal(err) + } + writeRemote(t, c, "/d/notes", "from the server") + + local := t.TempDir() + victim := filepath.Join(local, "startup-file") + if err := os.WriteFile(victim, []byte("original"), 0600); err != nil { + t.Fatal(err) + } + dst := filepath.Join(local, "d") + if err := os.Mkdir(dst, 0755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(victim, filepath.Join(dst, "notes")); err != nil { + t.Fatal(err) + } + + err := downloadDir(c, "/d", dst, false, true, 0) + if err == nil || !strings.Contains(err.Error(), "symlink") { + t.Fatalf("want symlink refusal, got %v", err) + } + if b, _ := os.ReadFile(victim); string(b) != "original" { + t.Fatalf("file behind the symlink was overwritten: %q", b) + } +} + +func TestDownload_DepthLimit(t *testing.T) { + c := memSFTP(t) + if err := c.Mkdir("/d"); err != nil { + t.Fatal(err) + } + err := downloadDir(c, "/d", filepath.Join(t.TempDir(), "d"), false, true, maxRecursionDepth+1) + if err == nil || !strings.Contains(err.Error(), "maximum depth") { + t.Fatalf("want depth limit error, got %v", err) + } +} + +// File modes are tested through downloadMode: the in-memory SFTP server used +// here always reports files as 0644, so it cannot exercise remote modes. +func TestDownloadMode(t *testing.T) { + cases := []struct { + remote os.FileMode + preserve bool + want os.FileMode + }{ + {0o600, false, 0o600}, + {0o777, false, 0o777}, // reduced by umask when the file is created + {0o777, true, 0o775}, // -p: never world-writable + {os.ModeSetuid | os.ModeSticky | 0o755, true, 0o755}, + } + for _, c := range cases { + if got := downloadMode(c.remote, c.preserve); got != c.want { + t.Errorf("downloadMode(%v, %v) = %o, want %o", c.remote, c.preserve, got, c.want) + } + } +} + +func TestTerminalSafe(t *testing.T) { + in := "report\x1b]0;pwned\x07\x9b2J.txt" + got := terminalSafe(in) + if strings.ContainsAny(got, "\x1b\x07") || strings.ContainsRune(got, 0x9b) { + t.Errorf("control characters survived: %q", got) + } + if !strings.HasPrefix(got, "report") || !strings.HasSuffix(got, ".txt") { + t.Errorf("printable text altered: %q", got) + } +} diff --git a/client/ssh.go b/client/ssh.go index 3f2da81..29f12aa 100644 --- a/client/ssh.go +++ b/client/ssh.go @@ -83,6 +83,13 @@ import ( // If the cert file is absent or cannot be parsed the raw signer is returned // without error — the caller can still authenticate with the bare key. func NewCertSigner(keyPath string) (ssh.Signer, error) { + return NewCertSignerPrompt(keyPath, nil) +} + +// NewCertSignerPrompt is NewCertSigner, except that when the key is +// passphrase-protected and no SSH agent holds it, the passphrase is asked for +// with prompt (if non-nil) instead of failing. +func NewCertSignerPrompt(keyPath string, prompt func() ([]byte, error)) (ssh.Signer, error) { keyBytes, err := os.ReadFile(keyPath) if err != nil { return nil, fmt.Errorf("read SSH key %q: %w", keyPath, err) @@ -96,12 +103,42 @@ func NewCertSigner(keyPath string) (ssh.Signer, error) { return nil, fmt.Errorf("parse SSH key %q: %w", keyPath, parseErr) } - return newSignerFromAgent(keyPath) + agentSigner, agentErr := newSignerFromAgent(keyPath) + if agentErr == nil || prompt == nil { + return agentSigner, agentErr + } + slog.Debug("SSH agent unavailable for key; asking for passphrase", "key", keyPath, "err", agentErr) + pass, err := prompt() + if err != nil { + return nil, fmt.Errorf("SSH key %q is passphrase-protected (%v) and the passphrase could not be read: %w", keyPath, agentErr, err) + } + signer, err = ssh.ParsePrivateKeyWithPassphrase(keyBytes, pass) + clear(pass) + if err != nil { + return nil, fmt.Errorf("decrypt SSH key %q: %w", keyPath, err) + } } return wrapWithCert(signer, keyPath) } +// TTYPassphrasePrompt returns a prompt for NewCertSignerPrompt that asks for +// the key's passphrase on the controlling terminal (/dev/tty) without echo, +// so stdin is never consumed. +func TTYPassphrasePrompt(keyPath string) func() ([]byte, error) { + return func() ([]byte, error) { + tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0) + if err != nil { + return nil, fmt.Errorf("no terminal: %w", err) + } + defer tty.Close() + fmt.Fprintf(tty, "Enter passphrase for key '%s': ", keyPath) + pass, err := term.ReadPassword(int(tty.Fd())) + fmt.Fprintln(tty) + return pass, err + } +} + // newSignerFromAgent resolves a signer for keyPath from the SSH agent and, // if a valid cert file is present, wraps it in an ssh.CertSigner. func newSignerFromAgent(keyPath string) (ssh.Signer, error) { @@ -212,9 +249,10 @@ func wrapWithCert(signer ssh.Signer, keyPath string) (ssh.Signer, error) { } // CertNeedsRefresh returns true when the certificate file at certPath is -// either absent or will expire within 5 minutes of the time this function is -// called. It returns false if the file is present and has more than 5 minutes -// of validity remaining. +// absent, unparseable, or close to expiry. "Close" is 20% of the +// certificate's lifetime, between 30 seconds and 5 minutes (see +// certRefreshThreshold): a default 5-minute certificate is refreshed when +// less than 1 minute remains. func CertNeedsRefresh(certPath string) bool { data, err := os.ReadFile(certPath) if err != nil { @@ -231,15 +269,7 @@ func CertNeedsRefresh(certPath string) bool { if !ok { return true } - - // ValidBefore is a uint64 Unix timestamp. Zero means "forever", but that - // is not issued by this CA — treat it as always-valid just in case. - if cert.ValidBefore == 0 || cert.ValidBefore == ssh.CertTimeInfinity { - return false - } - - expiry := time.Unix(int64(cert.ValidBefore), 0) - return time.Until(expiry) < 5*time.Minute + return certNeedsRefreshAt(cert, time.Now()) } // RunSession opens an interactive SSH shell session over conn. @@ -259,15 +289,14 @@ func CertNeedsRefresh(certPath string) bool { // restored on return (even on error). // // Host key verification is intentionally skipped. The connection arrives over -// a Ziti overlay that enforces mutual TLS using the controller's PKI — the -// host's Ziti identity is cryptographically proven before any SSH bytes are -// exchanged. A traditional known-hosts check would be redundant and weaker -// than the guarantee Ziti already provides. -func RunSession(conn net.Conn, user, host string, signer ssh.Signer, forwardAgent bool) error { +// a Ziti overlay, but OpenZiti does not tell the dialer which identity +// answered, so hostKeyCallback (normally HostKeyCallback) checks the host key +// against keys seen before for that Ziti address. +func RunSession(conn net.Conn, user, host string, signer ssh.Signer, forwardAgent bool, hostKeyCallback ssh.HostKeyCallback) error { cfg := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)}, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), //nolint:gosec + HostKeyCallback: hostKeyCallback, } clientConn, chans, reqs, err := ssh.NewClientConn(conn, host, cfg) @@ -406,14 +435,12 @@ func ForwardAgent(sshClient *ssh.Client, session *ssh.Session) error { // behaviour of standard ssh(1). Other errors (handshake failure, session // open failure, etc.) are returned normally so the caller can log them. // -// Host key verification is intentionally skipped for the same reason as -// RunSession — the Ziti overlay enforces mutual TLS before any SSH bytes are -// exchanged. -func RunCommand(conn net.Conn, user, host, command string, signer ssh.Signer) error { +// The host key is checked by hostKeyCallback (see RunSession). +func RunCommand(conn net.Conn, user, host, command string, signer ssh.Signer, hostKeyCallback ssh.HostKeyCallback) error { cfg := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)}, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), //nolint:gosec + HostKeyCallback: hostKeyCallback, } clientConn, chans, reqs, err := ssh.NewClientConn(conn, host, cfg) @@ -451,12 +478,12 @@ func RunCommand(conn net.Conn, user, host, command string, signer ssh.Signer) er // port forwards independently. The caller is responsible for calling // client.Close() when done. // -// Host key verification is intentionally skipped (see RunSession for rationale). -func NewSSHClient(conn net.Conn, user, host string, signer ssh.Signer) (*ssh.Client, error) { +// The host key is checked by hostKeyCallback (see RunSession). +func NewSSHClient(conn net.Conn, user, host string, signer ssh.Signer, hostKeyCallback ssh.HostKeyCallback) (*ssh.Client, error) { cfg := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)}, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), //nolint:gosec + HostKeyCallback: hostKeyCallback, } clientConn, chans, reqs, err := ssh.NewClientConn(conn, host, cfg) if err != nil { @@ -666,6 +693,13 @@ func handleSocks5Conn(ctx context.Context, sshClient *ssh.Client, conn net.Conn) slog.Debug("socks5: read methods failed", "err", err) return } + // Only "no authentication" (0x00) is supported; RFC 1928 §3 requires + // replying 0xFF and closing when the client did not offer it. + if !bytes.Contains(methods, []byte{0x00}) { + slog.Debug("socks5: client offered no acceptable auth method", "methods", methods) + _, _ = conn.Write([]byte{0x05, 0xFF}) + return + } // Respond: VER=5, METHOD=0 (no auth). if _, err := conn.Write([]byte{0x05, 0x00}); err != nil { slog.Debug("socks5: write auth response failed", "err", err) diff --git a/cmd/ziti-scp/main.go b/cmd/ziti-scp/main.go index 0ecc93a..42775da 100644 --- a/cmd/ziti-scp/main.go +++ b/cmd/ziti-scp/main.go @@ -38,7 +38,6 @@ package main import ( - "bufio" "context" "encoding/json" "fmt" @@ -58,6 +57,7 @@ import ( "github.com/netfoundry/ziti-ssh/client" "github.com/netfoundry/ziti-ssh/config" + "github.com/netfoundry/ziti-ssh/internal/mfa" zitioidc "github.com/netfoundry/ziti-ssh/internal/oidc" ) @@ -86,6 +86,11 @@ type OIDCConfig struct { // loadConfig reads the YAML config file at cfgPath. If the file does not exist // an empty Config is returned without error. func loadConfig(cfgPath string) (*Config, error) { + // The config chooses the identity, CA service and key: refuse one that + // another user could have written. + if err := config.CheckUserFile(cfgPath); err != nil { + return nil, err + } data, err := os.ReadFile(cfgPath) if os.IsNotExist(err) { return &Config{}, nil @@ -131,12 +136,15 @@ type remoteSpec struct { } // parseArg parses a single scp-style argument. It returns (isRemote, remoteSpec, localPath). -// A remote specification is any argument containing ":" that is not an absolute or -// relative path (i.e. does not start with "/" or "."). +// As with scp(1), an argument is remote ("[user@]host:path") only if it has a +// ':' with no '/' before it; anything else — including "/a:b", "./a:b" and +// "dir/a:b" — is a local path. A single-letter host part is treated as a +// Windows drive letter ("C:\x"), i.e. local. func parseArg(arg string) (isRemote bool, remote remoteSpec, localPath string) { - // Detect "host:path" — the colon must appear before any "/" to avoid - // treating absolute paths like "/foo/bar" as remote specs. colonIdx := strings.Index(arg, ":") + if slashIdx := strings.Index(arg, "/"); slashIdx >= 0 && slashIdx < colonIdx { + return false, remoteSpec{}, arg + } if colonIdx > 0 { hostPart := arg[:colonIdx] // Make sure the host part does not look like a Windows absolute path @@ -150,17 +158,28 @@ func parseArg(arg string) (isRemote bool, remote remoteSpec, localPath string) { return false, remoteSpec{}, arg } -// splitUserHost splits "user@host" into (user, host). If no "@" is present the -// current OS username is used. +// splitUserHost splits "user@host" into (user, host) at the last "@" (as +// OpenSSH does). If no "@" is present, u is empty and runSCP picks the +// default user (defaultUser) once the certificate is known. func splitUserHost(hostPart string) (u, h string) { - if idx := strings.IndexByte(hostPart, '@'); idx >= 0 { + if idx := strings.LastIndexByte(hostPart, '@'); idx >= 0 { return hostPart[:idx], hostPart[idx+1:] } + return "", hostPart +} + +// defaultUser is the SSH user when the remote spec names none: the +// certificate's single principal if there is one (in per-identity mode, the +// identity's derived Linux username), otherwise the current OS user. +func defaultUser(certPath string) (string, error) { + if p, ok := client.CertPrincipal(certPath); ok { + return p, nil + } cur, err := user.Current() - if err == nil { - return cur.Username, hostPart + if err != nil { + return "", fmt.Errorf("determine current user: %w", err) } - return "", hostPart + return cur.Username, nil } // --------------------------------------------------------------------------- @@ -257,6 +276,7 @@ func runSign(p signParams) error { defer zitiCtx.Close() registerZtAPIsPersist(zitiCtx, p.identityFile) + defer mfa.RegisterTTY(zitiCtx)() if err := zitioidc.AddCredentials(zitiCtx, p.oidc); err != nil { return err @@ -282,18 +302,19 @@ func runSign(p signParams) error { return fmt.Errorf("send public key to CA: %w", err) } - reader := bufio.NewReader(conn) - certLine, err := reader.ReadString('\n') + certLine, err := client.ReadCAResponse(conn) if err != nil { - return fmt.Errorf("read certificate from CA: %w", err) + return err } - certLine = strings.TrimSpace(certLine) - if certLine == "" { - return fmt.Errorf("CA returned no certificate") + // Validate before writing so a CA error reply or a certificate for the + // wrong key never overwrites an existing valid certificate. + certBytes, err := client.ValidateSignedCert(certLine, pubKeyLine) + if err != nil { + return err } certPath := deriveCertPath(privKeyPath) - if err := config.AtomicWriteFile(certPath, []byte(certLine+"\n"), 0644); err != nil { + if err := config.AtomicWriteFile(certPath, certBytes, 0644); err != nil { return fmt.Errorf("write certificate to %q: %w", certPath, err) } @@ -367,6 +388,7 @@ type scpParams struct { identityFile string caService string sshService string + service string // --service: dial this service with the host as terminator keyFile string oidc zitioidc.FlowParams recursive bool @@ -446,7 +468,13 @@ func runSCP(p scpParams) error { } } - signer, err := client.NewCertSigner(privKeyPath) + if remoteUser == "" { + if remoteUser, err = defaultUser(certPath); err != nil { + return err + } + } + + signer, err := client.NewCertSignerPrompt(privKeyPath, client.TTYPassphrasePrompt(privKeyPath)) if err != nil { return fmt.Errorf("load SSH key: %w", err) } @@ -459,6 +487,7 @@ func runSCP(p scpParams) error { defer zitiCtx.Close() registerZtAPIsPersist(zitiCtx, p.identityFile) + defer mfa.RegisterTTY(zitiCtx)() if err := zitioidc.AddCredentials(zitiCtx, p.oidc); err != nil { return err @@ -472,9 +501,19 @@ func runSCP(p scpParams) error { dialService := p.sshService terminatorAddr := remoteHost - if _, ok := zitiCtx.GetService(remoteHost); ok { + if p.service != "" { + // Explicit --service: always address the host as a terminator on it, + // even if the host name is also a service name. + dialService = p.service + } else if _, ok := zitiCtx.GetService(remoteHost); ok { dialService = remoteHost terminatorAddr = "" + fmt.Fprintf(os.Stderr, "Dialing service %q directly: any host bound to it may answer.\n", dialService) + } + + hostKeyCallback, err := client.NewHostKeyCallback(dialService, terminatorAddr) + if err != nil { + return err } dialCtx, dialCancel := context.WithTimeout(context.Background(), p.zitiTimeout) @@ -508,7 +547,7 @@ func runSCP(p scpParams) error { slog.Info("uploading", "user", remoteUser, "host", remoteHost, "remote_path", dstRemote.path, "local_paths", localPaths) return client.RunSFTP(netConn, remoteUser, remoteHost, signer, true, localPaths, dstRemote.path, - p.recursive, p.preserve, p.quiet) + p.recursive, p.preserve, p.quiet, hostKeyCallback) } // Download: srcs are remote, dst is local. @@ -519,7 +558,7 @@ func runSCP(p scpParams) error { slog.Info("downloading", "user", remoteUser, "host", remoteHost, "remote_paths", remotePaths, "local_dst", dstLocal) return client.RunSFTP(netConn, remoteUser, remoteHost, signer, false, remotePaths, dstLocal, - p.recursive, p.preserve, p.quiet) + p.recursive, p.preserve, p.quiet, hostKeyCallback) } // version is set at build time via -ldflags "-X main.version=". @@ -550,8 +589,13 @@ overlay — port 22 is never exposed externally. At least one of or must be a remote specification of the form: [user@]host:path -If the remote hostname matches a Ziti service name it is dialled directly. -Otherwise it is used as a terminator address on --ssh-service (default: "ssh"). +If the remote hostname matches a Ziti service name it is dialled directly +(any host bound to that service may answer; a notice is printed). Otherwise it +is used as a terminator address on --ssh-service (default: "ssh"). Use +--service to always treat the hostname as a terminator address on . + +An argument is remote only if it contains ':' with no '/' before it; use +./name:with:colons for local files whose names contain ':'. Examples: @@ -634,6 +678,7 @@ of validity remain.`, identityFile: identityFile, caService: caService, sshService: sshService, + service: serviceFlag, keyFile: resolvedKey, oidc: oidcParams, recursive: recursiveFlag, @@ -653,6 +698,7 @@ of validity remain.`, root.Flags().StringVar(&caServiceFlag, "ca-service", "", "CA service name (or ZITI_CA_SERVICE, default: ssh-ca)") root.Flags().StringVar(&sshServiceFlag, "ssh-service", "", "SSH service name (or ZITI_SSH_SERVICE, default: ssh)") + root.Flags().StringVar(&serviceFlag, "service", "", "Dial this service with the remote host as terminator address, even if the host name is also a service name") root.Flags().StringVar(&keyFlag, "key", "", "SSH private key path (default: auto-detect from ~/.ssh/)") root.Flags().StringVar(&oidcIssuerFlag, "oidc-issuer", "", "OIDC issuer URL; triggers browser-based OIDC auth before connecting (or set oidc.issuer in config)") root.Flags().BoolVarP(&recursiveFlag, "recursive", "r", false, "Recursively copy entire directories") @@ -707,6 +753,7 @@ Example: var ( caServiceFlag string sshServiceFlag string + serviceFlag string keyFlag string oidcIssuerFlag string recursiveFlag bool diff --git a/cmd/ziti-scp/main_test.go b/cmd/ziti-scp/main_test.go new file mode 100644 index 0000000..b3b6838 --- /dev/null +++ b/cmd/ziti-scp/main_test.go @@ -0,0 +1,56 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package main + +import "testing" + +func TestParseArg(t *testing.T) { + cases := []struct { + arg string + remote bool + user, host, path string + local string + }{ + {arg: "web1:/tmp/x", remote: true, host: "web1", path: "/tmp/x"}, + {arg: "bob@web1:/tmp/x", remote: true, user: "bob", host: "web1", path: "/tmp/x"}, + // Identity names may contain '@': split at the last one. + {arg: "alice@corp.com@web1:f", remote: true, user: "alice@corp.com", host: "web1", path: "f"}, + // A '/' before the first ':' makes it a local path (scp semantics). + {arg: "/data/a:b", local: "/data/a:b"}, + {arg: "./a:b", local: "./a:b"}, + {arg: "../a:b", local: "../a:b"}, + {arg: "dir/a:b", local: "dir/a:b"}, + {arg: "plain", local: "plain"}, + {arg: `C:\file`, local: `C:\file`}, + } + for _, c := range cases { + isRemote, r, local := parseArg(c.arg) + if isRemote != c.remote { + t.Errorf("%q: remote=%v, want %v", c.arg, isRemote, c.remote) + continue + } + if !c.remote { + if local != c.local { + t.Errorf("%q: local=%q, want %q", c.arg, local, c.local) + } + continue + } + if r.host != c.host || r.path != c.path || (c.user != "" && r.user != c.user) { + t.Errorf("%q: got user=%q host=%q path=%q, want %q %q %q", c.arg, r.user, r.host, r.path, c.user, c.host, c.path) + } + } +} diff --git a/cmd/ziti-ssh-ca/config.go b/cmd/ziti-ssh-ca/config.go index ed856e9..8b079f2 100644 --- a/cmd/ziti-ssh-ca/config.go +++ b/cmd/ziti-ssh-ca/config.go @@ -17,18 +17,18 @@ package main import ( - "crypto/tls" - "crypto/x509" "encoding/json" "fmt" "net" "net/http" "net/url" "os" + "strings" httptransport "github.com/go-openapi/runtime/client" "github.com/go-openapi/strfmt" "github.com/spf13/cobra" + "golang.org/x/term" management "github.com/openziti/edge-api/rest_management_api_client" "github.com/openziti/edge-api/rest_management_api_client/authentication" @@ -60,7 +60,7 @@ const configTypeSchema = `{ }, "sudoers_rule": { "type": "string", - "description": "Rule fragment written after the username in /etc/sudoers.d/" + "description": "Rule fragment written after the username in /etc/sudoers.d/ziti-ssh-host-" } } } @@ -85,7 +85,7 @@ Fields: sudoers_rule (string) Rule fragment appended after the username in - /etc/sudoers.d/. Example: "ALL=(ALL) NOPASSWD: /usr/bin/apt" + /etc/sudoers.d/ziti-ssh-host-. Example: "ALL=(ALL) NOPASSWD: /usr/bin/apt" Example config value: { @@ -111,8 +111,10 @@ func buildConfigCmd() *cobra.Command { controllerFlag string usernameFlag string passwordFlag string + passwordFileFlag string insecureFlag bool controllerCAFlag string + yesFlag bool ) parent := &cobra.Command{ @@ -126,9 +128,13 @@ func buildConfigCmd() *cobra.Command { parent.PersistentFlags().StringVar(&usernameFlag, "username", "", "Controller admin username (or set ZITI_CTRL_USERNAME)") parent.PersistentFlags().StringVar(&passwordFlag, "password", "", - "Controller admin password (or set ZITI_CTRL_PASSWORD)") + "Controller admin password (visible in the process list; prefer --password-file, ZITI_CTRL_PASSWORD, or the prompt)") + parent.PersistentFlags().StringVar(&passwordFileFlag, "password-file", "", + "Read the controller admin password from a file, or \"-\" for stdin (or set ZITI_CTRL_PASSWORD_FILE)") + parent.PersistentFlags().BoolVarP(&yesFlag, "yes", "y", false, + "Trust the controller's certificate authority on first use without asking (never replaces a changed one)") parent.PersistentFlags().BoolVar(&insecureFlag, "insecure", false, - "Skip TLS certificate verification (or set ZITI_CTRL_INSECURE)") + "Skip TLS certificate verification — sends the admin password unverified; last resort (or set ZITI_CTRL_INSECURE)") parent.PersistentFlags().StringVar(&controllerCAFlag, "controller-ca", "", "Path to PEM CA certificate to trust for the controller's TLS (or set ZITI_CTRL_CA)") @@ -146,16 +152,11 @@ func buildConfigCmd() *cobra.Command { Use: "apply", Short: "Idempotent install-or-update of the ziti-ssh-host.v1 config type on the controller", RunE: func(cmd *cobra.Command, args []string) error { - ctrl := config.EnvOrFlag(controllerFlag, "ZITI_CTRL_ADDRESS", "") - user := config.EnvOrFlag(usernameFlag, "ZITI_CTRL_USERNAME", "") - pass := config.EnvOrFlag(passwordFlag, "ZITI_CTRL_PASSWORD", "") - insecure := insecureFlag || os.Getenv("ZITI_CTRL_INSECURE") == "true" - caPath := config.EnvOrFlag(controllerCAFlag, "ZITI_CTRL_CA", "") - - if err := validateControllerFlags(ctrl, user, pass, insecure, caPath); err != nil { + opts, err := resolveControllerOptions(controllerFlag, usernameFlag, passwordFlag, passwordFileFlag, controllerCAFlag, insecureFlag, yesFlag) + if err != nil { return err } - return runConfigApply(ctrl, user, pass, insecure, caPath) + return runConfigApply(opts) }, } @@ -164,16 +165,11 @@ func buildConfigCmd() *cobra.Command { Use: "remove", Short: "Remove the ziti-ssh-host.v1 config type from the controller", RunE: func(cmd *cobra.Command, args []string) error { - ctrl := config.EnvOrFlag(controllerFlag, "ZITI_CTRL_ADDRESS", "") - user := config.EnvOrFlag(usernameFlag, "ZITI_CTRL_USERNAME", "") - pass := config.EnvOrFlag(passwordFlag, "ZITI_CTRL_PASSWORD", "") - insecure := insecureFlag || os.Getenv("ZITI_CTRL_INSECURE") == "true" - caPath := config.EnvOrFlag(controllerCAFlag, "ZITI_CTRL_CA", "") - - if err := validateControllerFlags(ctrl, user, pass, insecure, caPath); err != nil { + opts, err := resolveControllerOptions(controllerFlag, usernameFlag, passwordFlag, passwordFileFlag, controllerCAFlag, insecureFlag, yesFlag) + if err != nil { return err } - return runConfigRemove(ctrl, user, pass, insecure, caPath) + return runConfigRemove(opts) }, } @@ -183,22 +179,84 @@ func buildConfigCmd() *cobra.Command { return parent } -// validateControllerFlags returns an error if any required flag is missing or -// if --insecure and --controller-ca are both set. -func validateControllerFlags(ctrl, user, pass string, insecure bool, caPath string) error { - if ctrl == "" { - return fmt.Errorf("--controller (or ZITI_CTRL_ADDRESS) is required") +// controllerOptions are the resolved settings for a management API session. +type controllerOptions struct { + ctrl, user, pass string + caPath string + insecure, yes bool + caCacheDir string + confirm trustPrompt +} + +// resolveControllerOptions applies flag/env precedence, reads the password +// (flag, ZITI_CTRL_PASSWORD, --password-file / ZITI_CTRL_PASSWORD_FILE, or a +// hidden prompt), and validates the combination. +func resolveControllerOptions(ctrlFlag, userFlag, passFlag, passFileFlag, caFlag string, insecureFlag, yes bool) (controllerOptions, error) { + o := controllerOptions{ + ctrl: config.EnvOrFlag(ctrlFlag, "ZITI_CTRL_ADDRESS", ""), + user: config.EnvOrFlag(userFlag, "ZITI_CTRL_USERNAME", ""), + caPath: config.EnvOrFlag(caFlag, "ZITI_CTRL_CA", ""), + insecure: insecureFlag || os.Getenv("ZITI_CTRL_INSECURE") == "true", + yes: yes, } - if user == "" { - return fmt.Errorf("--username (or ZITI_CTRL_USERNAME) is required") + if o.ctrl == "" { + return o, fmt.Errorf("--controller (or ZITI_CTRL_ADDRESS) is required") } - if pass == "" { - return fmt.Errorf("--password (or ZITI_CTRL_PASSWORD) is required") + if o.user == "" { + return o, fmt.Errorf("--username (or ZITI_CTRL_USERNAME) is required") } - if insecure && caPath != "" { - return fmt.Errorf("--insecure and --controller-ca are mutually exclusive") + if o.insecure && o.caPath != "" { + return o, fmt.Errorf("--insecure and --controller-ca are mutually exclusive") } - return nil + + interactive := term.IsTerminal(int(os.Stdin.Fd())) && term.IsTerminal(int(os.Stderr.Fd())) + passFile := config.EnvOrFlag(passFileFlag, "ZITI_CTRL_PASSWORD_FILE", "") + switch { + case passFlag != "": + fmt.Fprintln(os.Stderr, "WARNING: --password is visible to other users in the process list and saved in shell history; prefer --password-file, ZITI_CTRL_PASSWORD, or the interactive prompt.") + o.pass = passFlag + case os.Getenv("ZITI_CTRL_PASSWORD") != "": + o.pass = os.Getenv("ZITI_CTRL_PASSWORD") + case passFile == "-": + p, err := lineReader(os.Stdin) + if err != nil { + return o, fmt.Errorf("read password from stdin: %w", err) + } + o.pass = p + interactive = false // stdin is consumed + case passFile != "": + b, err := os.ReadFile(passFile) + if err != nil { + return o, fmt.Errorf("read password file: %w", err) + } + o.pass = strings.TrimRight(strings.SplitN(string(b), "\n", 2)[0], "\r") + case interactive: + fmt.Fprintf(os.Stderr, "Password for %s: ", o.user) + b, err := term.ReadPassword(int(os.Stdin.Fd())) + fmt.Fprintln(os.Stderr) + if err != nil { + return o, fmt.Errorf("read password: %w", err) + } + o.pass = string(b) + } + if o.pass == "" { + return o, fmt.Errorf("a controller admin password is required (--password-file, ZITI_CTRL_PASSWORD, or run interactively)") + } + + dir, err := defaultControllerCADir() + if err != nil { + return o, err + } + o.caCacheDir = dir + if interactive { + o.confirm = func(question string) bool { + fmt.Fprint(os.Stderr, question) + answer, _ := lineReader(os.Stdin) + answer = strings.TrimSpace(answer) + return strings.EqualFold(answer, "y") || strings.EqualFold(answer, "yes") + } + } + return o, nil } // resolveControllerHost strips any scheme prefix and appends the default port 443 @@ -216,22 +274,21 @@ func resolveControllerHost(raw string) string { // buildMgmtClient constructs a Ziti management API client and authenticates it. // On success the returned *httptransport.Runtime has DefaultAuthentication set to // the bearer token, so callers can pass nil as the auth info to each API call. -func buildMgmtClient(ctrl, user, pass string, insecure bool, caPath string) (*management.ZitiEdgeManagement, error) { - host := resolveControllerHost(ctrl) - - tlsCfg := &tls.Config{} //nolint:gosec - if insecure { - tlsCfg.InsecureSkipVerify = true //nolint:gosec // operator-explicit flag - } else if caPath != "" { - pemBytes, err := os.ReadFile(caPath) - if err != nil { - return nil, fmt.Errorf("read controller CA file %q: %w", caPath, err) - } - pool := x509.NewCertPool() - if !pool.AppendCertsFromPEM(pemBytes) { - return nil, fmt.Errorf("no valid PEM certificates found in %q", caPath) - } - tlsCfg.RootCAs = pool +func buildMgmtClient(o controllerOptions) (*management.ZitiEdgeManagement, error) { + host := resolveControllerHost(o.ctrl) + user, pass := o.user, o.pass + + tlsCfg, err := controllerTLSConfig(controllerTrustOptions{ + host: host, + caPath: o.caPath, + insecure: o.insecure, + yes: o.yes, + cacheDir: o.caCacheDir, + confirm: o.confirm, + out: os.Stderr, + }) + if err != nil { + return nil, err } transport := httptransport.New(host, "/edge/management/v1", []string{"https"}) @@ -284,8 +341,8 @@ func runConfigPrint() error { } // runConfigApply idempotently creates or updates the ziti-ssh-host.v1 config type. -func runConfigApply(ctrl, user, pass string, insecure bool, caPath string) error { - mgmtClient, err := buildMgmtClient(ctrl, user, pass, insecure, caPath) +func runConfigApply(o controllerOptions) error { + mgmtClient, err := buildMgmtClient(o) if err != nil { return err } @@ -335,8 +392,8 @@ func runConfigApply(ctrl, user, pass string, insecure bool, caPath string) error } // runConfigRemove removes the ziti-ssh-host.v1 config type if it exists. -func runConfigRemove(ctrl, user, pass string, insecure bool, caPath string) error { - mgmtClient, err := buildMgmtClient(ctrl, user, pass, insecure, caPath) +func runConfigRemove(o controllerOptions) error { + mgmtClient, err := buildMgmtClient(o) if err != nil { return err } diff --git a/cmd/ziti-ssh-ca/ctrltrust.go b/cmd/ziti-ssh-ca/ctrltrust.go new file mode 100644 index 0000000..3a5bb07 --- /dev/null +++ b/cmd/ziti-ssh-ca/ctrltrust.go @@ -0,0 +1,256 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package main + +import ( + "bufio" + "bytes" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/pem" + "errors" + "fmt" + "io" + "net" + "net/http" + "os" + "path/filepath" + "strings" + "time" + + "github.com/fullsailor/pkcs7" +) + +// Controller TLS trust for "ziti-ssh-ca config apply|remove". +// +// Resolution order (mirrors "ziti edge login"): +// 1. --controller-ca +// 2. a bundle saved earlier for this controller +// 3. the system CA pool, if it already trusts the controller +// 4. the controller's own CA bundle from /.well-known/est/cacerts, checked +// against the server's TLS chain, shown to the user and saved after +// confirmation (or --yes) +// +// A saved bundle that no longer matches the server is a warning sign: it is +// only replaced after interactive confirmation, never by --yes alone. +// --insecure skips verification entirely and prints a warning. + +// trustPrompt asks a yes/no question; nil means non-interactive. +type trustPrompt func(question string) bool + +type controllerTrustOptions struct { + host string // host:port + caPath string // --controller-ca + insecure bool // --insecure + yes bool // --yes: accept a first-seen controller CA without asking + cacheDir string // where accepted bundles are saved + confirm trustPrompt + out io.Writer // messages (stderr) +} + +// defaultControllerCADir returns $XDG_CONFIG_HOME/ziti-ssh/controllers. +func defaultControllerCADir() (string, error) { + base := os.Getenv("XDG_CONFIG_HOME") + if base == "" { + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + base = filepath.Join(home, ".config") + } + return filepath.Join(base, "ziti-ssh", "controllers"), nil +} + +func cachedBundlePath(dir, host string) string { + return filepath.Join(dir, strings.NewReplacer(":", "_", "/", "_").Replace(host)+".pem") +} + +// controllerTLSConfig returns the TLS configuration for talking to the +// controller's management API. +func controllerTLSConfig(o controllerTrustOptions) (*tls.Config, error) { + serverName, _, err := net.SplitHostPort(o.host) + if err != nil { + return nil, fmt.Errorf("controller address %q: %w", o.host, err) + } + out := o.out + if out == nil { + out = io.Discard + } + + if o.insecure { + fmt.Fprintln(out, "WARNING: --insecure: the controller's TLS certificate is NOT verified; the admin password is sent to whoever answers.") + return &tls.Config{InsecureSkipVerify: true}, nil //nolint:gosec // operator-explicit flag + } + + if o.caPath != "" { + pool, err := loadPEMPool(o.caPath) + if err != nil { + return nil, err + } + return &tls.Config{RootCAs: pool, ServerName: serverName}, nil + } + + cache := cachedBundlePath(o.cacheDir, o.host) + if _, err := os.Stat(cache); err == nil { + pool, err := loadPEMPool(cache) + if err != nil { + return nil, err + } + if probeErr := probeTLS(o.host, serverName, pool); probeErr == nil { + return &tls.Config{RootCAs: pool, ServerName: serverName}, nil + } else if !isVerificationError(probeErr) { + return nil, fmt.Errorf("connect to controller %s: %w", o.host, probeErr) + } + // The controller no longer chains to the saved bundle. + bundle, certs, err := fetchControllerBundle(o.host, serverName) + if err != nil { + return nil, fmt.Errorf("controller %s does not match its saved CA bundle %s, and its current bundle could not be fetched: %w", o.host, cache, err) + } + fmt.Fprintf(out, "WARNING: controller %s presents a certificate authority that does NOT match the saved bundle %s.\n"+ + "This is expected only if the controller's PKI was replaced. Server-provided certificate authorities:\n", o.host, cache) + describeCerts(out, certs) + if o.confirm == nil || !o.confirm("Replace the saved certificate authority? [y/N] ") { + return nil, fmt.Errorf("controller CA for %s changed; not replacing %s (use --controller-ca, or confirm interactively)", o.host, cache) + } + return saveAndUse(o, cache, serverName, bundle, out) + } + + if probeTLS(o.host, serverName, nil) == nil { + return &tls.Config{ServerName: serverName}, nil // trusted by the system pool + } + + bundle, certs, err := fetchControllerBundle(o.host, serverName) + if err != nil { + return nil, fmt.Errorf("controller %s is not trusted by the system CAs, and its CA bundle could not be fetched: %w (use --controller-ca)", o.host, err) + } + fmt.Fprintf(out, "Untrusted certificate authority retrieved from controller %s.\n"+ + "Verified that the controller's TLS certificate is issued by it. Server-provided certificate authorities:\n", o.host) + describeCerts(out, certs) + accept := o.yes + if !accept && o.confirm != nil { + accept = o.confirm("Trust this controller certificate authority? [y/N] ") + } + if !accept { + return nil, fmt.Errorf("controller CA for %s not trusted (re-run interactively, add --yes, or use --controller-ca)", o.host) + } + return saveAndUse(o, cache, serverName, bundle, out) +} + +func saveAndUse(o controllerTrustOptions, cache, serverName string, bundle []byte, out io.Writer) (*tls.Config, error) { + if err := os.MkdirAll(filepath.Dir(cache), 0o700); err != nil { + return nil, err + } + if err := os.WriteFile(cache, bundle, 0o600); err != nil { + return nil, fmt.Errorf("save controller CA bundle: %w", err) + } + fmt.Fprintf(out, "Saved controller certificate authority to %s\n", cache) + pool, err := loadPEMPool(cache) + if err != nil { + return nil, err + } + return &tls.Config{RootCAs: pool, ServerName: serverName}, nil +} + +// fetchControllerBundle downloads the controller's CA bundle (base64 PKCS#7 +// from /.well-known/est/cacerts) without verification, then requires the +// controller's TLS certificate to chain to it. It returns the bundle as PEM. +func fetchControllerBundle(host, serverName string) ([]byte, []*x509.Certificate, error) { + client := &http.Client{ + Timeout: 15 * time.Second, + Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}, //nolint:gosec // bootstrap; verified below + } + resp, err := client.Get("https://" + host + "/.well-known/est/cacerts") + if err != nil { + return nil, nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, nil, fmt.Errorf("GET /.well-known/est/cacerts: %s", resp.Status) + } + encoded, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if err != nil { + return nil, nil, err + } + der, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(encoded))) + if err != nil { + return nil, nil, fmt.Errorf("decode CA bundle: %w", err) + } + p7, err := pkcs7.Parse(der) + if err != nil { + return nil, nil, fmt.Errorf("parse CA bundle: %w", err) + } + if len(p7.Certificates) == 0 { + return nil, nil, errors.New("CA bundle is empty") + } + var buf bytes.Buffer + pool := x509.NewCertPool() + for _, c := range p7.Certificates { + pool.AddCert(c) + _ = pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: c.Raw}) + } + if err := probeTLS(host, serverName, pool); err != nil { + return nil, nil, fmt.Errorf("controller's TLS certificate is not issued by its own CA bundle: %w", err) + } + return buf.Bytes(), p7.Certificates, nil +} + +func describeCerts(out io.Writer, certs []*x509.Certificate) { + for _, c := range certs { + sum := sha256.Sum256(c.Raw) + fmt.Fprintf(out, " subject: %s\n SHA-256: %X\n", c.Subject.String(), sum[:]) + } +} + +// probeTLS performs a TLS handshake verifying the server against pool (the +// system pool when nil). +func probeTLS(host, serverName string, pool *x509.CertPool) error { + d := &net.Dialer{Timeout: 15 * time.Second} + conn, err := tls.DialWithDialer(d, "tcp", host, &tls.Config{RootCAs: pool, ServerName: serverName}) + if err != nil { + return err + } + return conn.Close() +} + +func isVerificationError(err error) bool { + var cv *tls.CertificateVerificationError + var ua x509.UnknownAuthorityError + return errors.As(err, &cv) || errors.As(err, &ua) +} + +func loadPEMPool(path string) (*x509.CertPool, error) { + b, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("read CA file %q: %w", path, err) + } + pool := x509.NewCertPool() + if !pool.AppendCertsFromPEM(b) { + return nil, fmt.Errorf("no valid PEM certificates found in %q", path) + } + return pool, nil +} + +// lineReader reads one line from r with the trailing newline removed. +func lineReader(r io.Reader) (string, error) { + line, err := bufio.NewReader(r).ReadString('\n') + if err != nil && !(errors.Is(err, io.EOF) && line != "") { + return "", err + } + return strings.TrimRight(line, "\r\n"), nil +} diff --git a/cmd/ziti-ssh-ca/ctrltrust_test.go b/cmd/ziti-ssh-ca/ctrltrust_test.go new file mode 100644 index 0000000..454bf6a --- /dev/null +++ b/cmd/ziti-ssh-ca/ctrltrust_test.go @@ -0,0 +1,233 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package main + +import ( + "bytes" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/pem" + "math/big" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/fullsailor/pkcs7" +) + +type testCert struct { + cert *x509.Certificate + key *ecdsa.PrivateKey +} + +func newCert(t *testing.T, cn string, parent *testCert, isCA bool) *testCert { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: cn}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + IsCA: isCA, BasicConstraintsValid: true, + } + if isCA { + tmpl.KeyUsage = x509.KeyUsageCertSign + } else { + tmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} + tmpl.IPAddresses = []net.IP{net.IPv4(127, 0, 0, 1)} + } + signer, signerKey := tmpl, key + if parent != nil { + signer, signerKey = parent.cert, parent.key + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, signer, &key.PublicKey, signerKey) + if err != nil { + t.Fatal(err) + } + c, _ := x509.ParseCertificate(der) + return &testCert{cert: c, key: key} +} + +// controllerServer is a TLS server whose certificate is issued by serverCA and +// whose /.well-known/est/cacerts advertises bundleCA. +func controllerServer(t *testing.T, serverCA, bundleCA *testCert) string { + t.Helper() + leaf := newCert(t, "controller", serverCA, false) + p7, err := pkcs7.DegenerateCertificate(bundleCA.cert.Raw) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/.well-known/est/cacerts" { + _, _ = w.Write([]byte(base64.StdEncoding.EncodeToString(p7))) + return + } + http.NotFound(w, r) + })) + srv.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{leaf.cert.Raw}, PrivateKey: leaf.key}}} + srv.StartTLS() + t.Cleanup(srv.Close) + return strings.TrimPrefix(srv.URL, "https://") +} + +func opts(t *testing.T, host string) controllerTrustOptions { + return controllerTrustOptions{host: host, cacheDir: t.TempDir(), out: &bytes.Buffer{}} +} + +func TestControllerTrust_FirstUse(t *testing.T) { + ca := newCert(t, "ziti-root", nil, true) + host := controllerServer(t, ca, ca) + + t.Run("non-interactive without --yes refuses", func(t *testing.T) { + o := opts(t, host) + if _, err := controllerTLSConfig(o); err == nil { + t.Fatal("untrusted controller accepted silently") + } + if _, err := os.Stat(cachedBundlePath(o.cacheDir, host)); err == nil { + t.Error("bundle saved without consent") + } + }) + + t.Run("--yes saves and trusts; next run uses the saved bundle", func(t *testing.T) { + o := opts(t, host) + o.yes = true + cfg, err := controllerTLSConfig(o) + if err != nil || cfg.RootCAs == nil { + t.Fatalf("cfg=%v err=%v", cfg, err) + } + fi, err := os.Stat(cachedBundlePath(o.cacheDir, host)) + if err != nil || fi.Mode().Perm() != 0o600 { + t.Fatalf("saved bundle: %v %v", fi, err) + } + o.yes = false + if _, err := controllerTLSConfig(o); err != nil { + t.Errorf("saved bundle not used: %v", err) + } + }) + + t.Run("interactive yes", func(t *testing.T) { + o := opts(t, host) + asked := "" + o.confirm = func(q string) bool { asked = q; return true } + if _, err := controllerTLSConfig(o); err != nil || !strings.Contains(asked, "Trust") { + t.Fatalf("asked=%q err=%v", asked, err) + } + }) +} + +func TestControllerTrust_ChangedCARequiresConfirmation(t *testing.T) { + newCA := newCert(t, "new-root", nil, true) + host := controllerServer(t, newCA, newCA) + oldCA := newCert(t, "old-root", nil, true) + + setup := func(t *testing.T) controllerTrustOptions { + o := opts(t, host) + if err := os.MkdirAll(o.cacheDir, 0o700); err != nil { + t.Fatal(err) + } + pemOld := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: oldCA.cert.Raw}) + if err := os.WriteFile(cachedBundlePath(o.cacheDir, host), pemOld, 0o600); err != nil { + t.Fatal(err) + } + return o + } + + t.Run("--yes does not replace", func(t *testing.T) { + o := setup(t) + o.yes = true + if _, err := controllerTLSConfig(o); err == nil { + t.Fatal("changed CA replaced by --yes") + } + if !strings.Contains(o.out.(*bytes.Buffer).String(), "does NOT match") { + t.Error("no mismatch warning") + } + }) + + t.Run("interactive confirmation replaces", func(t *testing.T) { + o := setup(t) + o.confirm = func(string) bool { return true } + if _, err := controllerTLSConfig(o); err != nil { + t.Fatalf("confirmed replacement failed: %v", err) + } + b, _ := os.ReadFile(cachedBundlePath(o.cacheDir, host)) + blk, _ := pem.Decode(b) + if blk == nil || !bytes.Equal(blk.Bytes, newCA.cert.Raw) { + t.Error("saved bundle not replaced with the controller's current CA") + } + }) +} + +func TestControllerTrust_BundleMustIssueServerCert(t *testing.T) { + realCA := newCert(t, "real", nil, true) + otherCA := newCert(t, "other", nil, true) + host := controllerServer(t, realCA, otherCA) // advertises a CA that did not issue its cert + o := opts(t, host) + o.yes = true + if _, err := controllerTLSConfig(o); err == nil { + t.Fatal("bundle that does not issue the server certificate was trusted") + } +} + +func TestControllerTrust_InsecureWarns(t *testing.T) { + o := opts(t, "127.0.0.1:1") + o.insecure = true + cfg, err := controllerTLSConfig(o) + if err != nil || !cfg.InsecureSkipVerify { + t.Fatalf("cfg=%v err=%v", cfg, err) + } + if !strings.Contains(o.out.(*bytes.Buffer).String(), "NOT verified") { + t.Error("no warning for --insecure") + } +} + +func TestResolveControllerOptions_PasswordSources(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("ZITI_CTRL_PASSWORD", "") + t.Setenv("ZITI_CTRL_PASSWORD_FILE", "") + + f := t.TempDir() + "/admin-secret" + if err := os.WriteFile(f, []byte("test-value\n"), 0o600); err != nil { + t.Fatal(err) + } + o, err := resolveControllerOptions("ctrl", "admin", "", f, "", false, false) + if err != nil || o.pass != "test-value" { + t.Fatalf("--password-file: pass=%q err=%v", o.pass, err) + } + + t.Setenv("ZITI_CTRL_PASSWORD", "from-env") + if o, err = resolveControllerOptions("ctrl", "admin", "", "", "", false, false); err != nil || o.pass != "from-env" { + t.Fatalf("env: pass=%q err=%v", o.pass, err) + } + + t.Setenv("ZITI_CTRL_PASSWORD", "") + if _, err := resolveControllerOptions("ctrl", "admin", "", "", "", false, false); err == nil { + t.Fatal("missing password accepted (tests run without a terminal, so no prompt)") + } + if _, err := resolveControllerOptions("ctrl", "admin", "x", "", "ca.pem", true, false); err == nil { + t.Fatal("--insecure with --controller-ca accepted") + } +} diff --git a/cmd/ziti-ssh-ca/main.go b/cmd/ziti-ssh-ca/main.go index a9268ba..e9e4762 100644 --- a/cmd/ziti-ssh-ca/main.go +++ b/cmd/ziti-ssh-ca/main.go @@ -67,6 +67,9 @@ func main() { certTTLFlag string rateLimitFlag string rateBurstFlag string + sourceAddrFlag string + maxConnsFlag string + extensionsFlag string zitiTimeoutFlag string versionFlag bool ) @@ -91,6 +94,9 @@ func main() { rateLimitStr := config.EnvOrFlag(rateLimitFlag, "ZITI_RATE_LIMIT", "5") rateBurstStr := config.EnvOrFlag(rateBurstFlag, "ZITI_RATE_BURST", "3") zitiTimeoutStr := config.EnvOrFlag(zitiTimeoutFlag, "ZITI_TIMEOUT", "30s") + sourceAddrStr := config.EnvOrFlag(sourceAddrFlag, "ZITI_CERT_SOURCE_ADDRESS", ca.DefaultSourceAddress) + maxConnsStr := config.EnvOrFlag(maxConnsFlag, "ZITI_MAX_CONNECTIONS", strconv.Itoa(defaultMaxConnections)) + extensionsStr := config.EnvOrFlag(extensionsFlag, "ZITI_CERT_EXTENSIONS", ca.DefaultExtensions) if identityFile == "" { return fmt.Errorf("--identity (or ZITI_IDENTITY) is required") @@ -128,17 +134,35 @@ func main() { return fmt.Errorf("--rate-burst (or ZITI_RATE_BURST): must be a positive integer, got %q", rateBurstStr) } - return run(identityFile, caKeyFile, serviceName, principal, mode, certTTL, rateLimit, rateBurst, zitiTimeout) + sourceAddress, err := ca.ParseSourceAddress(sourceAddrStr) + if err != nil { + return fmt.Errorf("--cert-source-address (or ZITI_CERT_SOURCE_ADDRESS): %w", err) + } + + maxConns, err := strconv.Atoi(maxConnsStr) + if err != nil || maxConns < 1 { + return fmt.Errorf("--max-connections (or ZITI_MAX_CONNECTIONS): must be a positive integer, got %q", maxConnsStr) + } + + extensions, err := ca.ParseExtensions(extensionsStr) + if err != nil { + return fmt.Errorf("--cert-extensions (or ZITI_CERT_EXTENSIONS): %w", err) + } + + return run(identityFile, caKeyFile, serviceName, principal, mode, certTTL, sourceAddress, extensions, rateLimit, rateBurst, maxConns, zitiTimeout) }, } root.Flags().StringVar(&identityFlag, "identity", "", "Path to Ziti identity file (or set ZITI_IDENTITY)") - root.Flags().StringVar(&caKeyFlag, "ca-key", "", "Path to CA private key (Ed25519) (or set ZITI_CA_KEY)") + root.Flags().StringVar(&caKeyFlag, "ca-key", "", "Path to the controller intermediate CA private key (RSA, ECDSA or Ed25519) (or set ZITI_CA_KEY)") root.Flags().StringVar(&serviceFlag, "service", "", "Ziti service name to bind (or set ZITI_CA_SERVICE, default: ssh-ca)") root.Flags().StringVar(&principalFlag, "principal", "", "SSH certificate principal in shared mode (or set ZITI_SSH_PRINCIPAL, default: ziggy)") root.Flags().StringVar(&modeFlag, "mode", "", "Principal mode: \"shared\" (default) or \"per-identity\" (or set ZITI_SSH_MODE)") root.Flags().StringVar(&certTTLFlag, "cert-ttl", "", "Certificate validity duration (or set ZITI_CERT_TTL, default: 5m)") root.Flags().StringVar(&rateLimitFlag, "rate-limit", "", "Max cert signing requests per minute per identity (or set ZITI_RATE_LIMIT, default: 5)") + root.Flags().StringVar(&sourceAddrFlag, "cert-source-address", "", "Comma-separated IPs/CIDRs set as the certificate source-address option, or \"none\" (or set ZITI_CERT_SOURCE_ADDRESS, default: "+ca.DefaultSourceAddress+")") + root.Flags().StringVar(&extensionsFlag, "cert-extensions", "", "Comma-separated certificate extensions to grant, or \"none\" (or set ZITI_CERT_EXTENSIONS, default: "+ca.DefaultExtensions+")") + root.Flags().StringVar(&maxConnsFlag, "max-connections", "", "Maximum concurrent CA connections; further connections are closed (or set ZITI_MAX_CONNECTIONS, default: "+strconv.Itoa(defaultMaxConnections)+")") root.Flags().StringVar(&rateBurstFlag, "rate-burst", "", "Burst allowance for per-identity rate limiter (or set ZITI_RATE_BURST, default: 3)") root.PersistentFlags().StringVar(&zitiTimeoutFlag, "ziti-timeout", "", "Timeout for Ziti network operations (or set ZITI_TIMEOUT, default: 30s)") root.PersistentFlags().BoolVarP(&versionFlag, "version", "V", false, "Print version and exit") @@ -238,14 +262,15 @@ const drainTimeout = 30 * time.Second // burst window. const idleLimiterTTL = 10 * time.Minute -func run(identityFile, caKeyFile, serviceName, principal, mode string, certTTL time.Duration, ratePerMinute float64, rateBurst int, zitiTimeout time.Duration) error { +func run(identityFile, caKeyFile, serviceName, principal, mode string, certTTL time.Duration, sourceAddress string, extensions []string, ratePerMinute float64, rateBurst int, maxConns int, zitiTimeout time.Duration) error { // Load CA key. signer, caPub, err := ca.LoadKey(caKeyFile) if err != nil { return fmt.Errorf("load CA key: %w", err) } slog.Info("CA key loaded", "service", serviceName, "mode", mode, "principal", principal, - "rate_limit_per_min", ratePerMinute, "rate_burst", rateBurst) + "cert_ttl", certTTL, "cert_source_address", sourceAddressForLog(sourceAddress), "cert_extensions", extensions, + "rate_limit_per_min", ratePerMinute, "rate_burst", rateBurst, "max_connections", maxConns) caPubBytes := ca.PublicKeyBytes(caPub) @@ -327,6 +352,7 @@ func run(identityFile, caKeyFile, serviceName, principal, mode string, certTTL t }() // Accept loop. + slots := make(chan struct{}, maxConns) for { conn, err := listener.Accept() if err != nil { @@ -335,11 +361,9 @@ func run(identityFile, caKeyFile, serviceName, principal, mode string, certTTL t slog.Info("listener closed, draining in-flight connections") break } - wg.Add(1) - go func(c net.Conn) { - defer wg.Done() - handleConn(c, signer, caPubBytes, principal, mode, certTTL, limiter) - }(conn) + dispatch(conn, slots, &wg, func(c net.Conn) { + handleConn(c, signer, caPubBytes, principal, mode, certTTL, sourceAddress, extensions, limiter) + }) } // Stop the limiter eviction goroutine now that we're shutting down. @@ -365,21 +389,19 @@ func run(identityFile, caKeyFile, serviceName, principal, mode string, certTTL t // handleConn serves a single incoming Ziti connection. // It reads one line from the client: -// - empty line → send CA public key (not rate-limited) +// - empty line → send CA public key // - public key → sign and return certificate (rate-limited per identity) // // In "shared" mode the principal comes from the operator-configured flag. // In "per-identity" mode the principal is derived from the caller's Ziti identity // name via ca.DeriveUsername. -func handleConn(conn net.Conn, signer ssh.Signer, caPubBytes []byte, principal, mode string, certTTL time.Duration, limiter *ratelimit.Map) { +func handleConn(conn net.Conn, signer ssh.Signer, caPubBytes []byte, principal, mode string, certTTL time.Duration, sourceAddress string, extensions []string, limiter *ratelimit.Map) { defer conn.Close() - // Extract caller identity. The Ziti listener returns edge.Conn values via - // AcceptEdge; plain Accept returns a net.Conn wrapper. We type-assert to get - // the identity name. + // Extract the router-verified caller identity. Fail closed if absent. identity := callerIdentity(conn) if identity == "" { - slog.Error("rejected connection: empty Ziti identity") + slog.Error("rejected connection: edge router did not supply a dialer identity (OpenZiti v2.0.0+ routers required)") return } @@ -389,20 +411,30 @@ func handleConn(conn net.Conn, signer ssh.Signer, caPubBytes []byte, principal, effectivePrincipal := principal if mode == "per-identity" { effectivePrincipal = ca.DeriveUsername(identity) - if effectivePrincipal == "" { - log.Error("rejected connection: derived username is empty", "identity", identity) + if err := ca.ValidatePerIdentityPrincipal(effectivePrincipal); err != nil { + log.Error("rejected connection: invalid per-identity principal", "identity", identity, "err", err) return } log = log.With("derived_principal", effectivePrincipal) } - // Bound the connection lifetime: 30 s is generous for a single-line request. - // The size cap (4 KiB) is well above any real SSH public key but prevents a - // slow-sender from holding the connection indefinitely. - if err := conn.SetDeadline(time.Now().Add(30 * time.Second)); err != nil { + // Bound the connection lifetime: the request is a single line sent right + // after dialing. The size cap (4 KiB) is well above any real SSH public key. + if err := conn.SetDeadline(time.Now().Add(connDeadline)); err != nil { log.Error("set deadline", "err", err) return } + + // Enforce the per-identity rate limit before reading anything, for every + // request type (certificate and CA public key alike). + if !limiter.Allow(identity) { + log.Warn("rate limit exceeded, rejecting request", "identity", identity) + if _, err := conn.Write([]byte("error: rate limit exceeded\n")); err != nil { + log.Error("write rate limit error", "err", err) + } + return + } + const maxRequestBytes = 4096 reader := bufio.NewReader(io.LimitReader(conn, maxRequestBytes)) line, err := reader.ReadString('\n') @@ -413,7 +445,7 @@ func handleConn(conn net.Conn, signer ssh.Signer, caPubBytes []byte, principal, line = strings.TrimSpace(line) if line == "" { - // Client requested the CA public key — not subject to rate limiting. + // Client requested the CA public key. if _, err := conn.Write(caPubBytes); err != nil { log.Error("write CA public key", "err", err) } else { @@ -422,23 +454,20 @@ func handleConn(conn net.Conn, signer ssh.Signer, caPubBytes []byte, principal, return } - // Cert signing request — enforce per-identity rate limit. - if !limiter.Allow(identity) { - log.Warn("rate limit exceeded, rejecting cert signing request", "identity", identity) - if _, err := conn.Write([]byte("error: rate limit exceeded\n")); err != nil { - log.Error("write rate limit error", "err", err) - } - return - } - // Client sent a public key — parse it and return a signed certificate. pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(line)) if err != nil { log.Error("parse client public key", "err", err) + writeRefusal(conn, log, "request is not an SSH public key in authorized_keys format") + return + } + if err := ca.ValidateClientKey(pubKey, signer.PublicKey()); err != nil { + log.Warn("rejected client key", "type", pubKey.Type(), "err", err) + writeRefusal(conn, log, err.Error()) return } - certBytes, err := ca.SignCert(signer, pubKey, identity, effectivePrincipal, certTTL) + certBytes, err := ca.SignCert(signer, pubKey, identity, effectivePrincipal, certTTL, sourceAddress, extensions) if err != nil { log.Error("sign certificate", "err", err) return @@ -449,32 +478,94 @@ func handleConn(conn net.Conn, signer ssh.Signer, caPubBytes []byte, principal, return } - log.Info("issued SSH certificate", "principal", effectivePrincipal, "ttl", certTTL) + // The serial appears in sshd's log for every login with this certificate. + var serial uint64 + if pk, _, _, _, err := ssh.ParseAuthorizedKey(certBytes); err == nil { + if c, ok := pk.(*ssh.Certificate); ok { + serial = c.Serial + } + } + log.Info("issued SSH certificate", "principal", effectivePrincipal, "ttl", certTTL, "serial", serial) } -// callerIdentity extracts the Ziti identity name from a net.Conn. +// Compile-time assertion: SDK connections must expose the router-verified +// dialer identity that callerIdentity relies on. +var _ interface{ GetDialerIdentityName() string } = (zitiEdge.Conn)(nil) + +// callerIdentity returns the authenticated Ziti identity name of the dialer. // -// The SDK sets CallerIdHeader to the dialer's identity name on every dial -// (ziti.go: edgeDialOptions.CallerId = GetCurrentApiSession().GetIdentityName()). -// This is exposed via SourceIdentifier() on edge.Conn. +// Only GetDialerIdentityName() is trusted. That header is set by the dialer's +// edge router (OpenZiti v2.0.0+) from the router's own record of the +// authenticated identity and cannot be influenced by the client. // -// GetDialerIdentityName() reads a separate header injected by the fabric layer -// that is not always present — SourceIdentifier() is the reliable source. +// SourceIdentifier() (the CallerId header) is NOT trusted: it is written by the +// dialing SDK and copied through the router unchanged, so a modified client can +// claim any identity name. It is used only to log a warning on mismatch. // -// Returns "" only for plain net.Conn values (e.g. in unit tests). +// Returns "" when the router did not supply a dialer identity (router older +// than v2.0.0, or the router could not resolve the identity); callers must +// reject the connection in that case. func callerIdentity(conn net.Conn) string { - if ec, ok := conn.(zitiEdge.Conn); ok { - if name := ec.SourceIdentifier(); name != "" { - return name - } - return ec.GetDialerIdentityName() + type dialerNamer interface { + GetDialerIdentityName() string } - // Fallback: structural interface for tests/mocks that don't import edge. + dn, ok := conn.(dialerNamer) + if !ok { + return "" + } + name := dn.GetDialerIdentityName() + type sourceIdentifier interface { SourceIdentifier() string } if si, ok := conn.(sourceIdentifier); ok { - return si.SourceIdentifier() + if claimed := si.SourceIdentifier(); claimed != "" && name != "" && claimed != name { + slog.Warn("client-supplied caller id does not match router-verified dialer identity; using router-verified identity", + "dialer_identity", name, "claimed_caller_id", claimed) + } + } + return name +} + +// sourceAddressForLog renders the configured source-address restriction. +func sourceAddressForLog(sourceAddress string) string { + if sourceAddress == "" { + return "none (certificates accepted from any address)" + } + return sourceAddress +} + +const ( + // defaultMaxConnections bounds concurrent CA connections. + defaultMaxConnections = 64 + // connDeadline bounds each connection's lifetime. + connDeadline = 10 * time.Second +) + +// dispatch runs handle(conn) in a new goroutine if a connection slot is free, +// and returns true. If all slots are in use it closes conn immediately and +// returns false. The slot is released when handle returns. +func dispatch(conn net.Conn, slots chan struct{}, wg *sync.WaitGroup, handle func(net.Conn)) bool { + select { + case slots <- struct{}{}: + default: + slog.Warn("connection limit reached; closing new connection", "max_connections", cap(slots)) + _ = conn.Close() + return false + } + wg.Add(1) + go func() { + defer wg.Done() + defer func() { <-slots }() + handle(conn) + }() + return true +} + +// writeRefusal sends an "error: " line, which clients report as a CA +// refusal instead of a generic read failure. +func writeRefusal(conn net.Conn, log *slog.Logger, reason string) { + if _, err := conn.Write([]byte("error: " + reason + "\n")); err != nil { + log.Error("write refusal", "err", err) } - return "" } diff --git a/cmd/ziti-ssh-ca/main_test.go b/cmd/ziti-ssh-ca/main_test.go new file mode 100644 index 0000000..e077b39 --- /dev/null +++ b/cmd/ziti-ssh-ca/main_test.go @@ -0,0 +1,195 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package main + +import ( + "bufio" + "crypto/ed25519" + "crypto/rand" + "errors" + "io" + "net" + "strings" + "sync" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "github.com/netfoundry/ziti-ssh/ca" + "github.com/netfoundry/ziti-ssh/internal/ratelimit" +) + +// zitiLikeConn mimics an SDK edge connection: SourceIdentifier() is the +// client-supplied CallerId header, GetDialerIdentityName() is the +// router-verified dialer identity. +type zitiLikeConn struct { + net.Conn + callerID string + dialerName string +} + +func (c *zitiLikeConn) SourceIdentifier() string { return c.callerID } +func (c *zitiLikeConn) GetDialerIdentityName() string { return c.dialerName } + +func TestCallerIdentity_TrustsOnlyRouterVerifiedIdentity(t *testing.T) { + cases := []struct { + name string + callerID string + dialerName string + want string + }{ + {"mismatched caller id, no router identity", "root", "", ""}, + {"mismatched caller id, router identity present", "root", "alice", "alice"}, + {"matching values", "alice", "alice", "alice"}, + {"router identity only", "", "alice", "alice"}, + {"neither", "", "", ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := callerIdentity(&zitiLikeConn{callerID: tc.callerID, dialerName: tc.dialerName}) + if got != tc.want { + t.Fatalf("callerIdentity() = %q, want %q", got, tc.want) + } + }) + } +} + +// sourceOnlyConn exposes only the client-supplied CallerId, which was +// previously trusted and must now be ignored. +type sourceOnlyConn struct { + net.Conn + callerID string +} + +func (c *sourceOnlyConn) SourceIdentifier() string { return c.callerID } + +func TestCallerIdentity_SourceIdentifierOnlyConnIsRejected(t *testing.T) { + if got := callerIdentity(&sourceOnlyConn{callerID: "root"}); got != "" { + t.Fatalf("callerIdentity() = %q, want empty", got) + } +} + +func testCASigner(t *testing.T) (ssh.Signer, []byte) { + t.Helper() + _, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + signer, err := ssh.NewSignerFromKey(priv) + if err != nil { + t.Fatal(err) + } + return signer, ca.PublicKeyBytes(signer.PublicKey()) +} + +// serve runs handleConn on the server end of a pipe whose caller identity is +// "alice", and returns the client end. +func serve(t *testing.T, signer ssh.Signer, caPub []byte, limiter *ratelimit.Map) net.Conn { + t.Helper() + client, server := net.Pipe() + go handleConn(&zitiLikeConn{Conn: server, dialerName: "alice"}, signer, caPub, "ziggy", "shared", + 5*time.Minute, ca.DefaultSourceAddress, []string{"permit-pty"}, limiter) + t.Cleanup(func() { client.Close() }) + return client +} + +func readLine(t *testing.T, c net.Conn) string { + t.Helper() + _ = c.SetReadDeadline(time.Now().Add(2 * time.Second)) + line, err := bufio.NewReader(c).ReadString('\n') + if err != nil && line == "" { + t.Fatalf("no reply from CA within 2s: %v", err) + } + return strings.TrimSpace(line) +} + +func TestHandleConn_RateLimitCheckedBeforeReading(t *testing.T) { + stop := make(chan struct{}) + defer close(stop) + limiter := ratelimit.New(1.0/3600, 1, time.Hour, stop) // one request, then limited + signer, caPub := testCASigner(t) + + // First request: a CA public-key request. It must be served — and count + // against the identity's rate limit. + c1 := serve(t, signer, caPub, limiter) + if _, err := c1.Write([]byte("\n")); err != nil { + t.Fatal(err) + } + if got := readLine(t, c1); got != strings.TrimSpace(string(caPub)) { + t.Fatalf("CA public key request: got %q", got) + } + + // Second request: the client sends nothing. The CA must reply with the + // rate-limit error without waiting to read a request line. + c2 := serve(t, signer, caPub, limiter) + if got := readLine(t, c2); got != "error: rate limit exceeded" { + t.Fatalf("want rate-limit error before any request is read, got %q", got) + } +} + +func TestDispatch_ConnectionCap(t *testing.T) { + slots := make(chan struct{}, 1) + var wg sync.WaitGroup + release := make(chan struct{}) + var mu sync.Mutex + handled := map[string]bool{} + handler := func(name string) func(net.Conn) { + return func(c net.Conn) { + mu.Lock() + handled[name] = true + mu.Unlock() + <-release + c.Close() + } + } + + aClient, aServer := net.Pipe() + defer aClient.Close() + if !dispatch(aServer, slots, &wg, handler("a")) { + t.Fatal("first connection rejected with a free slot") + } + + bClient, bServer := net.Pipe() + defer bClient.Close() + if dispatch(bServer, slots, &wg, handler("b")) { + t.Fatal("connection accepted beyond the cap") + } + _ = bClient.SetReadDeadline(time.Now().Add(2 * time.Second)) + if _, err := bClient.Read(make([]byte, 1)); err != io.EOF && !errors.Is(err, io.ErrClosedPipe) { + t.Errorf("over-cap connection not closed: %v", err) + } + + close(release) // finish "a"; its slot must be returned + wg.Wait() + + cClient, cServer := net.Pipe() + defer cClient.Close() + if !dispatch(cServer, slots, &wg, handler("c")) { + t.Fatal("slot not released after the handler returned") + } + wg.Wait() + + mu.Lock() + defer mu.Unlock() + if handled["b"] { + t.Error("handler ran for the rejected connection") + } + if !handled["a"] || !handled["c"] { + t.Errorf("handlers not run for admitted connections: %v", handled) + } +} diff --git a/cmd/ziti-ssh-host/main.go b/cmd/ziti-ssh-host/main.go index 52ebd53..11684c2 100644 --- a/cmd/ziti-ssh-host/main.go +++ b/cmd/ziti-ssh-host/main.go @@ -26,6 +26,9 @@ // // inspect Show the resolved ziti-ssh-host.v1 config for one or // more services. Exits without opening any listeners. +// +// users list|claim Show or extend the per-identity account ownership +// registry (/var/lib/ziti-ssh-host/owned-users.json). package main import ( @@ -39,6 +42,7 @@ import ( "os" "os/signal" "path/filepath" + "strconv" "strings" "sync" "syscall" @@ -114,7 +118,7 @@ func main() { _ = enrollCmd.MarkFlagRequired("jwt") // --------------------------------------------------------------------- run - var modeFlag string + var modeFlag, maxConnsFlag string runCmd := &cobra.Command{ Use: "run", Short: "Listen on the Ziti ssh service and proxy to local sshd", @@ -133,10 +137,16 @@ func main() { if zitiTimeout <= 0 { return fmt.Errorf("--ziti-timeout (or ZITI_TIMEOUT) must be greater than zero, got %q", zitiTimeoutStr) } - return runProxy(identityFile, sshServices, mode, zitiTimeout) + maxConnsStr := config.EnvOrFlag(maxConnsFlag, "ZITI_MAX_CONNECTIONS", strconv.Itoa(host.DefaultMaxConnections)) + maxConns, err := strconv.Atoi(maxConnsStr) + if err != nil || maxConns < 1 { + return fmt.Errorf("--max-connections (or ZITI_MAX_CONNECTIONS) must be a positive integer, got %q", maxConnsStr) + } + return runProxy(identityFile, sshServices, mode, zitiTimeout, maxConns) }, } runCmd.Flags().StringVar(&modeFlag, "mode", "", "Principal mode: \"shared\" (default) or \"per-identity\" (or set ZITI_SSH_MODE)") + runCmd.Flags().StringVar(&maxConnsFlag, "max-connections", "", fmt.Sprintf("Maximum concurrent connections per service; further connections are closed immediately (or ZITI_MAX_CONNECTIONS, default: %d)", host.DefaultMaxConnections)) // ----------------------------------------------------------------- inspect var inspectServicesFlag []string @@ -169,7 +179,7 @@ func main() { }, } - root.AddCommand(enrollCmd, runCmd, inspectCmd, versionCmd) + root.AddCommand(enrollCmd, runCmd, inspectCmd, newUsersCmd(), versionCmd) if err := root.Execute(); err != nil { os.Exit(1) @@ -218,13 +228,45 @@ func parseGlobalGroups() []string { // appends configType to the context's declared config types before the first // Authenticate call. This is required for the SDK to deliver service config // data of that type. -func newZitiContextWithConfigTypes(identityFile string, configTypes ...string) (ziti.Context, error) { +// +// serviceRefresh sets how often the SDK checks the controller for service +// changes — and so how quickly a changed ziti-ssh-host.v1 config reaches this +// host (0 = SDK default, 5 minutes). Each check is a small "anything +// changed?" request; services are only re-fetched when something changed. +func newZitiContextWithConfigTypes(identityFile string, serviceRefresh time.Duration, configTypes ...string) (ziti.Context, error) { cfg, err := ziti.NewConfigFromFile(identityFile) if err != nil { return nil, fmt.Errorf("load Ziti config from %q: %w", identityFile, err) } cfg.ConfigTypes = append(cfg.ConfigTypes, configTypes...) - return ziti.NewContext(cfg) + opts := *ziti.DefaultOptions + if serviceRefresh > 0 { + opts.RefreshInterval = serviceRefresh + } + return ziti.NewContextWithOpts(cfg, &opts) +} + +// Service refresh interval for ziti-ssh-host run (ZITI_SERVICE_REFRESH). +const ( + defaultServiceRefresh = 30 * time.Second + minServiceRefresh = 5 * time.Second +) + +// serviceRefreshFromEnv parses ZITI_SERVICE_REFRESH (a duration, at least +// minServiceRefresh), defaulting to defaultServiceRefresh. +func serviceRefreshFromEnv() (time.Duration, error) { + v := os.Getenv("ZITI_SERVICE_REFRESH") + if v == "" { + return defaultServiceRefresh, nil + } + d, err := time.ParseDuration(v) + if err != nil { + return 0, fmt.Errorf("ZITI_SERVICE_REFRESH: invalid duration %q: %w", v, err) + } + if d < minServiceRefresh { + return 0, fmt.Errorf("ZITI_SERVICE_REFRESH must be at least %s, got %s", minServiceRefresh, d) + } + return d, nil } // runEnroll enrolls this host with the Ziti network, fetches the intermediate @@ -295,7 +337,12 @@ func runEnroll(jwtPath, identityFile string) error { } caPubBytes := clusterCAsToBytes(clusterCAs) - // 6. Write sshd configuration. + // 6. Write sshd configuration. The drop-in refers to the managed group, so + // create it first (an unknown group in "Match Group" simply never matches). + if err := host.EnsureManagedGroup(); err != nil { + slog.Warn("could not create managed group; Ziti-managed accounts keep authorized_keys login until it exists", + "group", host.ManagedGroup, "err", err) + } if err := host.WriteSSHConfig(caPubBytes, sshdConfFile, sshdCAPubKeyFile); err != nil { return fmt.Errorf("write sshd config: %w", err) } @@ -377,6 +424,14 @@ type clusterCA struct { // per unique intermediate CA (deduplicated by actual public key bytes, not // SubjectKeyId which is unreliable across HA nodes). func collectClusterCAs(urlRoots []string, rootPool *x509.CertPool) ([]clusterCA, error) { + cas, _, err := collectClusterCAsDetailed(urlRoots, rootPool) + return cas, err +} + +// collectClusterCAsDetailed is collectClusterCAs, also reporting how many +// controllers could not be queried. +func collectClusterCAsDetailed(urlRoots []string, rootPool *x509.CertPool) ([]clusterCA, int, error) { + failed := 0 seen := make(map[string]bool) var out []clusterCA @@ -384,6 +439,7 @@ func collectClusterCAs(urlRoots []string, rootPool *x509.CertPool) ([]clusterCA, cert, err := intCAFromController(urlRoot, rootPool) if err != nil { slog.Warn("could not get intermediate CA from controller", "url", urlRoot, "err", err) + failed++ continue } @@ -416,9 +472,9 @@ func collectClusterCAs(urlRoots []string, rootPool *x509.CertPool) ([]clusterCA, } if len(out) == 0 { - return nil, fmt.Errorf("no intermediate CA public keys found across %d controller(s)", len(urlRoots)) + return nil, failed, fmt.Errorf("no intermediate CA public keys found across %d controller(s)", len(urlRoots)) } - return out, nil + return out, failed, nil } // clusterCAsToBytes concatenates all authorized_key lines from cas into a @@ -473,21 +529,32 @@ func intCAFromController(controllerURL string, rootPool *x509.CertPool) (*x509.C "selfSigned", cert.Subject.String() == cert.Issuer.String()) } - if len(state.PeerCertificates) == 0 { + // Use the chain Go verified against rootPool, not the certificates the + // server sent: a server could append an extra CA certificate to + // PeerCertificates, which would then become an SSH trust anchor. Only the + // enrollment bootstrap (no root pool yet) falls back to PeerCertificates. + chain := state.PeerCertificates + if rootPool != nil { + if len(state.VerifiedChains) == 0 || len(state.VerifiedChains[0]) < 2 { + return nil, fmt.Errorf("no verified certificate chain from %q", host) + } + chain = state.VerifiedChains[0] + } + if len(chain) == 0 { return nil, fmt.Errorf("no certificates in TLS chain from %q", host) } - leaf := state.PeerCertificates[0] + leaf := chain[0] // Walk the chain and pick the cert whose Subject matches the leaf's Issuer // field. Raw-bytes comparison avoids encoding differences that string // formatting can obscure, and correctly identifies the signing intermediate // even when the chain contains cross-signed or multiple intermediate certs. - for _, cert := range state.PeerCertificates[1:] { + for _, cert := range chain[1:] { if cert.IsCA && bytes.Equal(cert.RawSubject, leaf.RawIssuer) { return cert, nil } } // Fallback to the original heuristic for unusual chain orderings. - for _, cert := range state.PeerCertificates { + for _, cert := range chain { if cert.IsCA && !bytes.Equal(cert.RawSubject, cert.RawIssuer) { return cert, nil } @@ -500,6 +567,16 @@ func intCAFromController(controllerURL string, rootPool *x509.CertPool) (*x509.C // sshd if the set has changed. Logs only when the set changes (additions // with controller URL, removals by count). func refreshTrustedCAs(urls []*url.URL, rootPool *x509.CertPool) error { + // Called from both the controller-URL event handler and the periodic + // poller; serialise so two refreshes cannot interleave their read/write. + trustRefreshMu.Lock() + defer trustRefreshMu.Unlock() + + // Only fetch CA keys from well-formed https controller URLs. + urls, rejected := config.FilterControllerURLs(urls) + for _, r := range rejected { + slog.Warn("ignoring controller URL", "reason", r) + } if len(urls) == 0 { return nil } @@ -508,17 +585,26 @@ func refreshTrustedCAs(urls []*url.URL, rootPool *x509.CertPool) error { urlStrs[i] = u.String() } - newCAs, err := collectClusterCAs(urlStrs, rootPool) + newCAs, failed, err := collectClusterCAsDetailed(urlStrs, rootPool) if err != nil { return fmt.Errorf("collect CA public keys: %w", err) } - newKeyBytes := clusterCAsToBytes(newCAs) current, err := os.ReadFile(sshdCAPubKeyFile) if err != nil && !os.IsNotExist(err) { return fmt.Errorf("read %q: %w", sshdCAPubKeyFile, err) } + // If any controller did not answer, keep every currently trusted key: an + // unreachable controller's CA must not be dropped (that would break + // logins for certificates it signed). Keys are only removed when all + // controllers in the cluster list answered and none presented them. + if failed > 0 { + slog.Warn("some controllers did not answer; keeping currently trusted CA keys", "failed", failed, "controllers", len(urls)) + newCAs = mergeTrustedKeys(current, newCAs) + } + newKeyBytes := clusterCAsToBytes(newCAs) + if sshPubKeySetsEqual(current, newKeyBytes) { slog.Debug("trusted CA keys unchanged", "controllers", len(urls)) return nil @@ -657,20 +743,33 @@ func nonEmptyLines(s string) []string { type serviceState struct { mu sync.RWMutex config *host.PermissionsConfig // nil if no ziti-ssh-host.v1 config is attached + // loadErr is set when the service's config could not be loaded or parsed. + // Per-identity connections on the service are then rejected (fail closed) + // rather than falling back to the global defaults or a stale config. + loadErr error } -func (s *serviceState) get() *host.PermissionsConfig { +// current returns the config, or an error if the last load failed. +func (s *serviceState) current() (*host.PermissionsConfig, error) { s.mu.RLock() defer s.mu.RUnlock() - return s.config + return s.config, s.loadErr } -func (s *serviceState) set(pc *host.PermissionsConfig) { +// update records the result of loading the service's config: on success the +// new config (nil = none attached) replaces the old one; on failure the +// service is marked unavailable and the old config is discarded. +func (s *serviceState) update(pc *host.PermissionsConfig, err error) { s.mu.Lock() defer s.mu.Unlock() - s.config = pc + if err != nil { + s.config, s.loadErr = nil, err + return + } + s.config, s.loadErr = pc, nil } + // loadPermissionsConfig fetches and parses the ziti-ssh-host.v1 config from // serviceName via zitiCtx. Returns nil when no such config is attached. func loadPermissionsConfig(zitiCtx ziti.Context, serviceName string) (*host.PermissionsConfig, error) { @@ -739,6 +838,9 @@ func loadPermissionsConfig(zitiCtx ziti.Context, serviceName string) (*host.Perm serviceName, strings.Join(collisions, "; ")) } + for _, w := range pc.PatternWarnings() { + slog.Warn("ziti-ssh-host.v1 config: pattern meaning changed", "service", serviceName, "detail", w) + } slog.Info("loaded ziti-ssh-host.v1 config", "service", serviceName, "identities", len(pc.Permissions)) return pc, nil } @@ -751,7 +853,7 @@ func loadPermissionsConfig(zitiCtx ziti.Context, serviceName string) (*host.Perm // startup, and ProxyHooks are wired to create/delete Linux users as sessions // open and close. Each service gets its own ProxyHooks that resolve permissions // from that service's ziti-ssh-host.v1 config. -func runProxy(identityFile string, sshServices []string, mode string, zitiTimeout time.Duration) error { +func runProxy(identityFile string, sshServices []string, mode string, zitiTimeout time.Duration, maxConns int) error { // Load the Ziti config to build the CA pool used when refreshing trusted // CA keys after a controller cluster membership change. cfg, err := ziti.NewConfigFromFile(identityFile) @@ -765,10 +867,15 @@ func runProxy(identityFile string, sshServices []string, mode string, zitiTimeou // Use NewConfigFromFile + NewContext so we can inject ConfigTypes before // the first Authenticate call. - zitiCtx, err := newZitiContextWithConfigTypes(identityFile, zitiSSHHostConfigType) + serviceRefresh, err := serviceRefreshFromEnv() + if err != nil { + return err + } + zitiCtx, err := newZitiContextWithConfigTypes(identityFile, serviceRefresh, zitiSSHHostConfigType) if err != nil { return fmt.Errorf("init Ziti context from %q: %w", identityFile, err) } + slog.Info("service refresh interval (config changes reach this host within it)", "interval", serviceRefresh) defer zitiCtx.Close() // cachedCtrlURLs holds the most-recently-seen controller URL list so the @@ -794,6 +901,14 @@ func runProxy(identityFile string, sshServices []string, mode string, zitiTimeou if !ok { return } + if len(urls) == 0 { + slog.Warn("ignoring empty controller URL list from controller") + return + } + if valid, _ := config.FilterControllerURLs(urls); len(valid) == 0 { + slog.Warn("ignoring controller URL list with no acceptable https URLs", "count", len(urls)) + return + } cachedMu.Lock() cachedCtrlURLs = urls cachedMu.Unlock() @@ -852,6 +967,18 @@ func runProxy(identityFile string, sshServices []string, mode string, zitiTimeou globalSudoersRule := os.Getenv("ZITI_SUDOERS_RULE") globalGroups := parseGlobalGroups() cleanupOnDisconnect := os.Getenv("ZITI_USER_CLEANUP") == "true" + terminateOnDisconnect := os.Getenv("ZITI_TERMINATE_ON_DISCONNECT") == "true" + grantPolicy, err := grantPolicyFromEnv() + if err != nil && mode == "per-identity" { + return fmt.Errorf("per-identity mode: %w", err) + } + + // Accounts managed through Ziti may only log in with a CA certificate: + // make sure the managed group exists and the sshd drop-in (which may + // predate this release) disables authorized_keys for its members. + if err := ensureSSHDLockdown(mode); err != nil { + return err + } listenOpts := &ziti.ListenOptions{ BindUsingEdgeIdentity: true, @@ -887,10 +1014,12 @@ func runProxy(identityFile string, sshServices []string, mode string, zitiTimeou if mode == "per-identity" { pc, err := loadPermissionsConfig(zitiCtx, svcName) if err != nil { - slog.Warn("could not load permissions config, using global fallbacks only", + slog.Error("could not load permissions config; per-identity connections on this service will be rejected until it loads", "service", svcName, "err", err) } - state.set(pc) + slog.Info("host grant policy", "service", svcName, "policy", grantPolicy.Describe(svcName)) + warnPolicyViolations(svcName, pc, grantPolicy) + state.update(pc, err) } entries = append(entries, serviceEntry{ @@ -924,13 +1053,28 @@ func runProxy(identityFile string, sshServices []string, mode string, zitiTimeou ) if mode == "per-identity" { - mgr = host.NewUserManager(userManagerStateFile, cleanupOnDisconnect) + var err error + mgr, err = host.NewUserManager(userManagerStateFile, cleanupOnDisconnect) + if err != nil { + return fmt.Errorf("per-identity mode: %w", err) + } + mgr.SetTerminateOnDisconnect(terminateOnDisconnect) + switch { + case cleanupOnDisconnect: + slog.Info("per-identity: accounts deleted (and their processes ended) when the last session closes") + case terminateOnDisconnect: + slog.Info("per-identity: accounts kept; their processes are ended when the last session closes") + default: + slog.Warn("per-identity: accounts and their background processes are kept after the last session closes; " + + "set ZITI_TERMINATE_ON_DISCONNECT=true or ZITI_USER_CLEANUP=true so revoked identities lose running processes") + } slog.Info("running orphan user cleanup") if err := mgr.CleanupOrphans(); err != nil { // Log but do not abort — a cleanup failure is not fatal to startup. slog.Error("orphan cleanup failed", "err", err) } + mgr.ReconcileLegacySudoers() } // Subscribe to service-changed events so we can hot-reload permissions. @@ -953,10 +1097,13 @@ func runProxy(identityFile string, sshServices []string, mode string, zitiTimeou slog.Info("service-changed event received, reloading permissions config", "service", svcName) pc, err := loadPermissionsConfig(zitiCtx, svcName) if err != nil { - slog.Error("failed to reload permissions config", "service", svcName, "err", err) + slog.Error("failed to reload permissions config; per-identity connections on this service will be rejected until it loads", + "service", svcName, "err", err) + st.update(nil, err) return } - st.set(pc) + warnPolicyViolations(svcName, pc, grantPolicy) + st.update(pc, nil) slog.Info("permissions config reloaded", "service", svcName) }) defer removeListener() @@ -975,14 +1122,27 @@ func runProxy(identityFile string, sshServices []string, mode string, zitiTimeou if username == "" { return fmt.Errorf("derived empty username from identity %q", zitiIdentity) } - perms := st.get().Resolve(zitiIdentity, globalGroups, globalSudoersRule) + pc, loadErr := st.current() + if loadErr != nil { + slog.Error("rejecting connection: permissions config for this service could not be loaded", + "service", svcName, "identity", zitiIdentity, "err", loadErr) + return fmt.Errorf("service %q: permissions config unavailable: %w", svcName, loadErr) + } + perms, fromConfig := pc.ResolveWithSource(zitiIdentity, globalGroups, globalSudoersRule) + // The host owner's per-service limit on what the + // controller-side config may grant (fail closed). + if err := grantPolicy.Enforce(svcName, perms, fromConfig); err != nil { + slog.Error("rejecting connection: permissions refused by host grant policy", + "service", svcName, "identity", zitiIdentity, "err", err) + return fmt.Errorf("identity %q on service %q: %w", zitiIdentity, svcName, err) + } slog.Info("per-identity connect", "service", svcName, "identity", zitiIdentity, "username", username, "groups", perms.Groups, "has_sudoers", perms.SudoersRule != "") - return mgr.EnsureUser(zitiIdentity, username, perms) + return mgr.EnsureUserForService(zitiIdentity, username, svcName, perms) }, OnDisconnect: func(zitiIdentity string) { username := ca.DeriveUsername(zitiIdentity) @@ -1004,7 +1164,7 @@ func runProxy(identityFile string, sshServices []string, mode string, zitiTimeou wg.Add(1) go func() { defer wg.Done() - host.Proxy(e.listener, defaultSSHTarget, hooks, &connWg) + host.ProxyLimited(e.listener, defaultSSHTarget, hooks, &connWg, maxConns) }() } @@ -1058,7 +1218,7 @@ func runProxy(identityFile string, sshServices []string, mode string, zitiTimeou // ziti-ssh-host.v1 config for each requested service, and prints a formatted // permissions table. Exits without opening any listeners. func runInspect(identityFile string, serviceNames []string, zitiTimeout time.Duration) error { - zitiCtx, err := newZitiContextWithConfigTypes(identityFile, zitiSSHHostConfigType) + zitiCtx, err := newZitiContextWithConfigTypes(identityFile, 0, zitiSSHHostConfigType) if err != nil { return fmt.Errorf("init Ziti context from %q: %w", identityFile, err) } @@ -1070,6 +1230,10 @@ func runInspect(identityFile string, serviceNames []string, zitiTimeout time.Dur globalSudoersRule := os.Getenv("ZITI_SUDOERS_RULE") globalGroups := parseGlobalGroups() + policy, policyErr := grantPolicyFromEnv() + if policyErr != nil { + fmt.Printf("WARNING: invalid host grant policy (ziti-ssh-host run would refuse to start in per-identity mode): %v\n\n", policyErr) + } for _, svcName := range serviceNames { _, ok := zitiCtx.GetService(svcName) @@ -1088,8 +1252,18 @@ func runInspect(identityFile string, serviceNames []string, zitiTimeout time.Dur if pc == nil { fmt.Printf(" Config type %s: not attached\n\n", zitiSSHHostConfigType) } else { - fmt.Printf(" Config type %s: present\n\n", zitiSSHHostConfigType) + fmt.Printf(" Config type %s: present\n", zitiSSHHostConfigType) + if policyErr == nil { + fmt.Printf(" Host grant policy: %s\n", policy.Describe(svcName)) + } + fmt.Println() printPermissionsTable(pc) + for _, w := range pc.PatternWarnings() { + fmt.Printf(" WARNING: %s\n", w) + } + if policyErr == nil { + printPolicyRefusals(svcName, pc, policy) + } } printGlobalFallbacks(globalGroups, globalSudoersRule) fmt.Println() @@ -1184,3 +1358,111 @@ func sortStrings(ss []string) { // interface that host.proxyConn uses to extract the caller's Ziti identity // name. This keeps the zitiEdge import live and verifies SDK compatibility. var _ interface{ GetDialerIdentityName() string } = (zitiEdge.Conn)(nil) + +// grantPolicyFromEnv reads the host grant policy settings. +func grantPolicyFromEnv() (host.GrantPolicy, error) { + return host.ParseGrantPolicy( + os.Getenv("ZITI_ALLOW_SUDOERS"), + os.Getenv("ZITI_ALLOW_GROUPS"), + os.Getenv("ZITI_RESTRICT_GROUPS"), + ) +} + +// warnPolicyViolations logs every entry of pc that the host grant policy +// would refuse for service, so operators see the problem when a config is +// loaded rather than only when the identity connects. +func warnPolicyViolations(service string, pc *host.PermissionsConfig, policy host.GrantPolicy) { + if pc == nil { + return + } + for key, perms := range pc.Permissions { + if err := policy.Check(service, perms); err != nil { + slog.Warn("ziti-ssh-host.v1 entry will be refused by host grant policy", + "service", service, "entry", key, "err", err) + } + } +} + +// printPolicyRefusals lists config entries the host grant policy refuses. +func printPolicyRefusals(service string, pc *host.PermissionsConfig, policy host.GrantPolicy) { + keys := make([]string, 0, len(pc.Permissions)) + for k := range pc.Permissions { + keys = append(keys, k) + } + sortStrings(keys) + refused := 0 + for _, k := range keys { + if err := policy.Check(service, pc.Permissions[k]); err != nil { + if refused == 0 { + fmt.Println(" Entries REFUSED by host policy (these identities cannot connect via this service):") + } + refused++ + fmt.Printf(" %s: %v\n", k, err) + } + } + if refused > 0 { + fmt.Println() + } +} + +// ensureSSHDLockdown creates host.ManagedGroup and brings the sshd drop-in up +// to date (reloading sshd if it changed). In per-identity mode a failure to +// create the group is fatal, because accounts would then keep authorized_keys +// login; in shared mode it is logged. In shared mode it also warns when no +// account is in the group, since the administrator must add the shared account. +func ensureSSHDLockdown(mode string) error { + if err := host.EnsureManagedGroup(); err != nil { + if mode == "per-identity" { + return fmt.Errorf("per-identity mode: %w", err) + } + slog.Warn("could not create managed group", "group", host.ManagedGroup, "err", err) + } + if _, err := os.Stat(sshdCAPubKeyFile); err == nil { + changed, err := host.EnsureSSHDDropIn(sshdConfFile, sshdCAPubKeyFile) + if err != nil { + return fmt.Errorf("update sshd drop-in: %w", err) + } + if changed { + slog.Info("updated sshd drop-in", "file", sshdConfFile) + if err := host.ReloadSSHD(); err != nil { + return fmt.Errorf("reload sshd after updating drop-in: %w", err) + } + } + } else { + slog.Warn("CA key file missing; run 'ziti-ssh-host enroll' first", "file", sshdCAPubKeyFile) + } + if mode != "per-identity" { + members, err := host.ManagedGroupMembers() + switch { + case err != nil: + slog.Warn("could not read managed group members", "group", host.ManagedGroup, "err", err) + case len(members) == 0: + slog.Warn("shared mode: no account is in the managed group, so the shared account's own authorized_keys stays active; "+ + "add it with: usermod -aG "+host.ManagedGroup+" ", "group", host.ManagedGroup) + default: + slog.Info("shared mode: accounts restricted to certificate login", "group", host.ManagedGroup, "members", members) + } + } + return nil +} + +// trustRefreshMu serialises refreshTrustedCAs. +var trustRefreshMu sync.Mutex + +// mergeTrustedKeys returns collected plus every key in the current +// TrustedUserCAKeys content that collected does not already contain. +func mergeTrustedKeys(current []byte, collected []clusterCA) []clusterCA { + have := make(map[string]bool) + for _, ca := range collected { + have[normalizeSSHKey(strings.TrimSpace(string(ca.AuthorizedKey)))] = true + } + out := append([]clusterCA(nil), collected...) + for _, line := range nonEmptyLines(string(current)) { + k := normalizeSSHKey(line) + if !have[k] { + have[k] = true + out = append(out, clusterCA{ControllerURL: "(kept: controller unreachable)", AuthorizedKey: []byte(strings.TrimSpace(line) + "\n")}) + } + } + return out +} diff --git a/cmd/ziti-ssh-host/main_test.go b/cmd/ziti-ssh-host/main_test.go new file mode 100644 index 0000000..f65b3ba --- /dev/null +++ b/cmd/ziti-ssh-host/main_test.go @@ -0,0 +1,191 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package main + +import ( + "bytes" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "errors" + "math/big" + "net" + "strings" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "github.com/netfoundry/ziti-ssh/host" +) + +func TestServiceState_FailsClosedOnLoadErrors(t *testing.T) { + var st serviceState + good := &host.PermissionsConfig{Permissions: map[string]host.IdentityPermissions{"alice": {Groups: []string{"dev"}}}} + + // Startup load failure: unavailable, not "fall back to globals". + st.update(nil, errors.New("parse error")) + if _, err := st.current(); err == nil { + t.Fatal("failed initial load not reported") + } + + // A good load makes the service available. + st.update(good, nil) + if pc, err := st.current(); err != nil || pc != good { + t.Fatalf("good load: pc=%v err=%v", pc, err) + } + + // A failed reload must not keep the previous (possibly broader) config. + st.update(nil, errors.New("bad entry")) + if pc, err := st.current(); err == nil || pc != nil { + t.Fatalf("failed reload kept old config: pc=%v err=%v", pc, err) + } + + // No config attached is not an error: global fallbacks apply. + st.update(nil, nil) + if pc, err := st.current(); err != nil || pc != nil { + t.Fatalf("no config attached: pc=%v err=%v", pc, err) + } +} + +type testCA struct { + cert *x509.Certificate + key *ecdsa.PrivateKey +} + +func makeCert(t *testing.T, subject string, isCA bool, parent *testCA, ip net.IP) *testCA { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(time.Now().UnixNano()), + Subject: pkix.Name{CommonName: subject}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + IsCA: isCA, + BasicConstraintsValid: true, + } + if isCA { + tmpl.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature + } else { + tmpl.KeyUsage = x509.KeyUsageDigitalSignature + tmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} + tmpl.IPAddresses = []net.IP{ip} + } + signerCert, signerKey := tmpl, key + if parent != nil { + signerCert, signerKey = parent.cert, parent.key + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, signerCert, &key.PublicKey, signerKey) + if err != nil { + t.Fatal(err) + } + c, err := x509.ParseCertificate(der) + if err != nil { + t.Fatal(err) + } + return &testCA{cert: c, key: key} +} + +// A controller endpoint presenting [leaf, rogue CA, real intermediate]. The +// rogue cert has the intermediate's subject but its own key; Go still +// verifies the chain via the real intermediate. +func TestIntCAFromController_UsesVerifiedChain(t *testing.T) { + root := makeCert(t, "root", true, nil, nil) + inter := makeCert(t, "intermediate", true, root, nil) + rogue := makeCert(t, "intermediate", true, nil, nil) // same subject, self-signed, different key + leaf := makeCert(t, "controller", false, inter, net.IPv4(127, 0, 0, 1)) + + ln, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{ + Certificates: []tls.Certificate{{ + Certificate: [][]byte{leaf.cert.Raw, rogue.cert.Raw, inter.cert.Raw}, + PrivateKey: leaf.key, + }}, + }) + if err != nil { + t.Fatal(err) + } + defer ln.Close() + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + _ = c.(*tls.Conn).Handshake() + c.Close() + } + }() + + pool := x509.NewCertPool() + pool.AddCert(root.cert) + got, err := intCAFromController("https://"+ln.Addr().String(), pool) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got.Raw, inter.cert.Raw) { + t.Fatalf("picked %q (rogue=%v) instead of the verified intermediate", got.Subject.CommonName, bytes.Equal(got.Raw, rogue.cert.Raw)) + } +} + +func authorizedKey(t *testing.T) string { + t.Helper() + k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + p, err := ssh.NewPublicKey(&k.PublicKey) + if err != nil { + t.Fatal(err) + } + return strings.TrimSpace(string(ssh.MarshalAuthorizedKey(p))) +} + +func TestMergeTrustedKeys_KeepsKeysOfUnreachableControllers(t *testing.T) { + a, b, c := authorizedKey(t), authorizedKey(t), authorizedKey(t) + current := []byte(a + "\n" + b + "\n") + collected := []clusterCA{{ControllerURL: "x", AuthorizedKey: []byte(a + "\n")}, {ControllerURL: "y", AuthorizedKey: []byte(c + "\n")}} + + got := string(clusterCAsToBytes(mergeTrustedKeys(current, collected))) + for _, k := range []string{a, b, c} { + if strings.Count(got, k) != 1 { + t.Errorf("key missing or duplicated in merged set:\n%s", got) + } + } +} + +func TestServiceRefreshFromEnv(t *testing.T) { + t.Setenv("ZITI_SERVICE_REFRESH", "") + if d, err := serviceRefreshFromEnv(); err != nil || d != defaultServiceRefresh { + t.Errorf("default: %v, %v", d, err) + } + t.Setenv("ZITI_SERVICE_REFRESH", "10s") + if d, err := serviceRefreshFromEnv(); err != nil || d != 10*time.Second { + t.Errorf("10s: %v, %v", d, err) + } + for _, bad := range []string{"1s", "0", "-5s", "soon"} { + t.Setenv("ZITI_SERVICE_REFRESH", bad) + if _, err := serviceRefreshFromEnv(); err == nil { + t.Errorf("%q accepted", bad) + } + } +} diff --git a/cmd/ziti-ssh-host/users.go b/cmd/ziti-ssh-host/users.go new file mode 100644 index 0000000..62b84b6 --- /dev/null +++ b/cmd/ziti-ssh-host/users.go @@ -0,0 +1,144 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package main + +import ( + "fmt" + "os" + "path/filepath" + "text/tabwriter" + "time" + + "github.com/spf13/cobra" + + "github.com/netfoundry/ziti-ssh/ca" + "github.com/netfoundry/ziti-ssh/host" +) + +// ownerRegistry returns the registry used by "run" in per-identity mode. +func ownerRegistry() *host.OwnerRegistry { + return host.NewOwnerRegistry(filepath.Join(filepath.Dir(userManagerStateFile), host.OwnedUsersFileName)) +} + +// newUsersCmd builds the "users" subcommand group for administering the +// per-identity account ownership registry. +func newUsersCmd() *cobra.Command { + usersCmd := &cobra.Command{ + Use: "users", + Short: "Administer per-identity Linux accounts managed by ziti-ssh-host", + } + + listCmd := &cobra.Command{ + Use: "list", + Short: "List accounts in the ownership registry (requires root)", + Args: cobra.NoArgs, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + reg := ownerRegistry() + names, entries, err := reg.List() + if err != nil { + return err + } + defer printLegacySudoers(entries) + if len(names) == 0 { + fmt.Printf("No accounts registered in %s\n", reg.Path()) + return nil + } + w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) + fmt.Fprintln(w, "USERNAME\tZITI IDENTITY\tUID\tCREATED\tSOURCE\tSTATUS") + for _, n := range names { + rec := entries[n] + source := "created" + if rec.Claimed { + source = "claimed" + } + status := "ok" + uid, exists, err := host.LookupAccountUID(n) + switch { + case err != nil: + status = "lookup error: " + err.Error() + case !exists: + status = "account missing (record removed on next disconnect or recreated on connect)" + case uid != rec.UID: + status = fmt.Sprintf("UID MISMATCH (now %d): account will not be managed", uid) + } + fmt.Fprintf(w, "%s\t%s\t%d\t%s\t%s\t%s\n", n, rec.Identity, rec.UID, rec.Created.Format(time.RFC3339), source, status) + } + return w.Flush() + }, + } + + var claimUsername, claimIdentity string + claimCmd := &cobra.Command{ + Use: "claim", + Short: "Register an existing account as owned by a Ziti identity (requires root)", + Long: `Register an existing Linux account in the ownership registry so that +ziti-ssh-host manages it for the given Ziti identity. + +ziti-ssh-host only creates, modifies, or deletes accounts recorded in its +ownership registry. Accounts created by releases before the registry existed +are therefore refused until claimed. --username must be the username derived +from --identity, and the account must have a UID of at least 1000.`, + Args: cobra.NoArgs, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + if claimUsername == "" || claimIdentity == "" { + return fmt.Errorf("--username and --identity are required") + } + if derived := ca.DeriveUsername(claimIdentity); derived != claimUsername { + return fmt.Errorf("identity %q derives username %q, not %q", claimIdentity, derived, claimUsername) + } + rec, err := host.ClaimAccount(ownerRegistry(), claimUsername, claimIdentity) + if err != nil { + return err + } + fmt.Printf("Registered %s (uid %d) to Ziti identity %q\n", claimUsername, rec.UID, rec.Identity) + return nil + }, + } + claimCmd.Flags().StringVar(&claimUsername, "username", "", "Existing Linux username to claim") + claimCmd.Flags().StringVar(&claimIdentity, "identity", "", "Ziti identity name that owns the account") + + usersCmd.AddCommand(listCmd, claimCmd) + return usersCmd +} + +// printLegacySudoers lists legacy-format files in /etc/sudoers.d for accounts +// that are not in the registry. They may be administrator files, or files +// written by a release before the registry that still grant sudo. +func printLegacySudoers(registered map[string]host.OwnerRecord) { + names, err := host.LegacySudoersCandidates() + if err != nil { + fmt.Fprintf(os.Stderr, "warning: scanning /etc/sudoers.d: %v\n", err) + return + } + var unmanaged []string + for _, n := range names { + if _, ok := registered[n]; !ok { + unmanaged = append(unmanaged, n) + } + } + if len(unmanaged) == 0 { + return + } + fmt.Println() + fmt.Println("Legacy-format sudoers files for accounts not in the registry (review each;") + fmt.Println("remove it if an earlier ziti-ssh-host wrote it, or claim the account):") + for _, n := range unmanaged { + fmt.Printf(" /etc/sudoers.d/%s\n", n) + } +} diff --git a/cmd/ziti-ssh/main.go b/cmd/ziti-ssh/main.go index 4a39a98..0638603 100644 --- a/cmd/ziti-ssh/main.go +++ b/cmd/ziti-ssh/main.go @@ -31,7 +31,6 @@ package main import ( - "bufio" "context" "encoding/json" "errors" @@ -45,12 +44,12 @@ import ( "os/signal" "os/user" "path/filepath" + "strconv" "strings" "sync" "syscall" "time" - "github.com/openziti/edge-api/rest_model" edgeapis "github.com/openziti/sdk-golang/edge-apis" ziti "github.com/openziti/sdk-golang/ziti" "github.com/openziti/sdk-golang/ziti/enroll" @@ -61,6 +60,7 @@ import ( "github.com/netfoundry/ziti-ssh/client" "github.com/netfoundry/ziti-ssh/config" + "github.com/netfoundry/ziti-ssh/internal/mfa" ) // --------------------------------------------------------------------------- @@ -87,6 +87,11 @@ type OIDCConfig struct { // loadConfig reads the YAML config file at cfgPath. If the file does not exist // an empty Config is returned without error. func loadConfig(cfgPath string) (*Config, error) { + // The config chooses the identity, CA service and key: refuse one that + // another user could have written. + if err := config.CheckUserFile(cfgPath); err != nil { + return nil, err + } data, err := os.ReadFile(cfgPath) if os.IsNotExist(err) { return &Config{}, nil @@ -124,78 +129,149 @@ func orDefault(val, fallback string) string { // Port-forward spec parsing // --------------------------------------------------------------------------- +// splitForwardSpec splits a forwarding spec on ':' like ssh(1), except that +// an IPv6 address may be written in brackets ("[::1]", "[2001:db8::1]"); the +// brackets are removed from the returned field. +func splitForwardSpec(s string) ([]string, error) { + var fields []string + for { + var field string + if strings.HasPrefix(s, "[") { + end := strings.IndexByte(s, ']') + if end < 0 { + return nil, fmt.Errorf("unterminated '[' in %q", s) + } + field, s = s[1:end], s[end+1:] + if s != "" && s[0] != ':' { + return nil, fmt.Errorf("expected ':' after ']' in %q", s) + } + } else if i := strings.IndexByte(s, ':'); i >= 0 { + field, s = s[:i], s[i:] + } else { + field, s = s, "" + } + fields = append(fields, field) + if s == "" { + return fields, nil + } + s = s[1:] // skip ':' + } +} + +// validPort reports whether p is a TCP port number 1–65535. +func validPort(p string) error { + n, err := strconv.Atoi(p) + if err != nil || n < 1 || n > 65535 { + return fmt.Errorf("invalid port %q", p) + } + return nil +} + +// isLoopbackBind reports whether a local bind address only accepts +// connections from this machine. +func isLoopbackBind(bind string) bool { + if bind == "" || bind == "localhost" { + return true + } + ip := net.ParseIP(bind) + return ip != nil && ip.IsLoopback() +} + +// warnNonLoopbackBind prints a warning when a local forward or SOCKS listener +// is reachable from other machines: it has no authentication of its own. +func warnNonLoopbackBind(flag, bind string) { + if !isLoopbackBind(bind) { + fmt.Fprintf(os.Stderr, "Warning: %s listener on %q is reachable from other machines and has no authentication;\n"+ + "anyone who can connect to it can use your session.\n", flag, bind) + } +} + // parseLocalForward parses a -L spec of the form: // // [bind:]localport:remotehost:remoteport // // A bare 3-part form (localport:remotehost:remoteport) binds to 127.0.0.1. +// IPv6 addresses are written in brackets: [::1]:8080:[2001:db8::1]:80. func parseLocalForward(s string) (client.LocalForwardSpec, error) { - parts := strings.Split(s, ":") + usage := fmt.Errorf("invalid -L spec %q: expected [bind:]localport:remotehost:remoteport", s) + parts, err := splitForwardSpec(s) + if err != nil { + return client.LocalForwardSpec{}, fmt.Errorf("invalid -L spec: %w", err) + } + var spec client.LocalForwardSpec switch len(parts) { case 3: - // localport:remotehost:remoteport - return client.LocalForwardSpec{ - Bind: "127.0.0.1", - LocalPort: parts[0], - RemoteHost: parts[1], - RemotePort: parts[2], - }, nil + spec = client.LocalForwardSpec{Bind: "127.0.0.1", LocalPort: parts[0], RemoteHost: parts[1], RemotePort: parts[2]} case 4: - // bind:localport:remotehost:remoteport - return client.LocalForwardSpec{ - Bind: parts[0], - LocalPort: parts[1], - RemoteHost: parts[2], - RemotePort: parts[3], - }, nil + spec = client.LocalForwardSpec{Bind: parts[0], LocalPort: parts[1], RemoteHost: parts[2], RemotePort: parts[3]} default: - return client.LocalForwardSpec{}, fmt.Errorf( - "invalid -L spec %q: expected [bind:]localport:remotehost:remoteport", s) + return client.LocalForwardSpec{}, usage + } + if spec.RemoteHost == "" { + return client.LocalForwardSpec{}, usage } + for _, p := range []string{spec.LocalPort, spec.RemotePort} { + if err := validPort(p); err != nil { + return client.LocalForwardSpec{}, fmt.Errorf("invalid -L spec %q: %w", s, err) + } + } + return spec, nil } // parseRemoteForward parses a -R spec of the form: // // [bind:]remoteport:localhost:localport +// +// IPv6 addresses are written in brackets. func parseRemoteForward(s string) (client.RemoteForwardSpec, error) { - parts := strings.Split(s, ":") + usage := fmt.Errorf("invalid -R spec %q: expected [bind:]remoteport:localhost:localport", s) + parts, err := splitForwardSpec(s) + if err != nil { + return client.RemoteForwardSpec{}, fmt.Errorf("invalid -R spec: %w", err) + } + var spec client.RemoteForwardSpec switch len(parts) { case 3: - // remoteport:localhost:localport - return client.RemoteForwardSpec{ - Bind: "", - RemotePort: parts[0], - LocalHost: parts[1], - LocalPort: parts[2], - }, nil + spec = client.RemoteForwardSpec{RemotePort: parts[0], LocalHost: parts[1], LocalPort: parts[2]} case 4: - // bind:remoteport:localhost:localport - return client.RemoteForwardSpec{ - Bind: parts[0], - RemotePort: parts[1], - LocalHost: parts[2], - LocalPort: parts[3], - }, nil + spec = client.RemoteForwardSpec{Bind: parts[0], RemotePort: parts[1], LocalHost: parts[2], LocalPort: parts[3]} default: - return client.RemoteForwardSpec{}, fmt.Errorf( - "invalid -R spec %q: expected [bind:]remoteport:localhost:localport", s) + return client.RemoteForwardSpec{}, usage } + if spec.LocalHost == "" { + return client.RemoteForwardSpec{}, usage + } + for _, p := range []string{spec.RemotePort, spec.LocalPort} { + if err := validPort(p); err != nil { + return client.RemoteForwardSpec{}, fmt.Errorf("invalid -R spec %q: %w", s, err) + } + } + return spec, nil } // parseDynamicForward parses a -D spec of the form: // // [bind:]port +// +// IPv6 bind addresses are written in brackets: [::1]:1080. func parseDynamicForward(s string) (client.DynamicForwardSpec, error) { - parts := strings.Split(s, ":") + parts, err := splitForwardSpec(s) + if err != nil { + return client.DynamicForwardSpec{}, fmt.Errorf("invalid -D spec: %w", err) + } + var spec client.DynamicForwardSpec switch len(parts) { case 1: - return client.DynamicForwardSpec{Bind: "127.0.0.1", LocalPort: parts[0]}, nil + spec = client.DynamicForwardSpec{Bind: "127.0.0.1", LocalPort: parts[0]} case 2: - return client.DynamicForwardSpec{Bind: parts[0], LocalPort: parts[1]}, nil + spec = client.DynamicForwardSpec{Bind: parts[0], LocalPort: parts[1]} default: - return client.DynamicForwardSpec{}, fmt.Errorf( - "invalid -D spec %q: expected [bind:]port", s) + return client.DynamicForwardSpec{}, fmt.Errorf("invalid -D spec %q: expected [bind:]port", s) + } + if err := validPort(spec.LocalPort); err != nil { + return client.DynamicForwardSpec{}, fmt.Errorf("invalid -D spec %q: %w", s, err) } + return spec, nil } // --------------------------------------------------------------------------- @@ -208,7 +284,12 @@ var candidateKeys = []string{"id_ed25519", "id_ecdsa", "id_rsa"} // resolveKey returns the absolute path to the SSH private key to use. // If keyFile is non-empty it is used directly. Otherwise ~/.ssh/ is searched // in candidateKeys order. If no key exists the user is prompted to generate one. -func resolveKey(keyFile string) (string, error) { +// resolveKey returns the SSH private key to use: keyFile if given, otherwise +// the first of candidateKeys found in the user's SSH directory. If none exists +// and interactive is true, it offers to generate one; when interactive is +// false (proxy mode, where stdin/stdout carry the SSH stream) it returns an +// error instead of prompting. +func resolveKey(keyFile string, interactive bool) (string, error) { if keyFile != "" { if _, err := os.Stat(keyFile); err != nil { return "", fmt.Errorf("key file %q not found: %w", keyFile, err) @@ -230,6 +311,10 @@ func resolveKey(keyFile string) (string, error) { } } + if !interactive { + return "", fmt.Errorf("no SSH key found; create one first (ssh-keygen -t ed25519) or pass --key") + } + // No key found — offer to generate one. fmt.Print("No SSH key found. Generate one now? [y/N] ") var answer string @@ -246,7 +331,9 @@ func resolveKey(keyFile string) (string, error) { } slog.Info("generating SSH key", "path", keyPath) //nolint:gosec // arguments are constant or path-derived; no user-controlled shell injection. - cmd := exec.Command("ssh-keygen", "-t", "ed25519", "-f", keyPath, "-N", "") + // No -N: ssh-keygen asks for a passphrase (Enter for none). + cmd := exec.Command("ssh-keygen", "-t", "ed25519", "-f", keyPath) + cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { @@ -313,7 +400,7 @@ func registerZtAPIsPersist(zitiCtx ziti.Context, identityFile string) { // runSign obtains a signed SSH certificate from the CA and writes it to disk. // It is used both by the `sign` subcommand and by runConnect for auto-sign. func runSign(p signParams) error { - privKeyPath, err := resolveKey(p.keyFile) + privKeyPath, err := resolveKey(p.keyFile, true) if err != nil { return err } @@ -341,6 +428,7 @@ func runSign(p signParams) error { } registerZtAPIsPersist(zitiCtx, p.identityFile) + defer mfa.RegisterTTY(zitiCtx)() if err := config.RunWithTimeout(p.zitiTimeout, "authenticate", zitiCtx.Authenticate); err != nil { return err @@ -362,18 +450,19 @@ func runSign(p signParams) error { return fmt.Errorf("send public key to CA: %w", err) } - reader := bufio.NewReader(conn) - certLine, err := reader.ReadString('\n') + certLine, err := client.ReadCAResponse(conn) if err != nil { - return fmt.Errorf("read certificate from CA: %w", err) + return err } - certLine = strings.TrimSpace(certLine) - if certLine == "" { - return fmt.Errorf("CA returned no certificate") + // Validate before writing so a CA error reply or a certificate for the + // wrong key never overwrites an existing valid certificate. + certBytes, err := client.ValidateSignedCert(certLine, pubKeyLine) + if err != nil { + return err } certPath := deriveCertPath(privKeyPath) - if err := config.AtomicWriteFile(certPath, []byte(certLine+"\n"), 0644); err != nil { + if err := config.AtomicWriteFile(certPath, certBytes, 0644); err != nil { return fmt.Errorf("write certificate to %q: %w", certPath, err) } @@ -388,36 +477,65 @@ func runSign(p signParams) error { // connect subcommand logic // --------------------------------------------------------------------------- -// parseTarget splits "[user@]target" into (user, target). If no "@" is -// present the current OS user is returned as the default username. +// parseTarget splits "[user@]target" into (user, target) at the last "@" (as +// OpenSSH does). If no "@" is present +// the current OS user is returned as the default username (proxy mode, +// where the user is not used; connect uses splitTarget and defaultUser). func parseTarget(arg string) (username, target string, err error) { - if idx := strings.IndexByte(arg, '@'); idx >= 0 { - return arg[:idx], arg[idx+1:], nil + username, target, explicit := splitTarget(arg) + if explicit { + return username, target, nil } cur, err := user.Current() if err != nil { return "", "", fmt.Errorf("determine current user: %w", err) } - return cur.Username, arg, nil + return cur.Username, target, nil +} + +// splitTarget splits "[user@]target" at the last "@"; explicit reports +// whether a user was given. +func splitTarget(arg string) (username, target string, explicit bool) { + if idx := strings.LastIndexByte(arg, '@'); idx >= 0 { + return arg[:idx], arg[idx+1:], true + } + return "", arg, false +} + +// defaultUser is the SSH user when the target names none: the certificate's +// single principal if there is one (in per-identity mode, the identity's +// derived Linux username), otherwise the current OS user. +func defaultUser(certPath string) (string, error) { + if p, ok := client.CertPrincipal(certPath); ok { + return p, nil + } + cur, err := user.Current() + if err != nil { + return "", fmt.Errorf("determine current user: %w", err) + } + return cur.Username, nil } // connectParams holds all resolved settings for the connect command. type connectParams struct { - identityFile string - caService string - sshService string - service string // explicit override (--service) - keyFile string - oidc oidcFlowParams - zitiTimeout time.Duration - target string // raw "[user@]target" argument - command string // optional remote command; empty means interactive shell - verbose bool - noShell bool // -N: do not open a shell, only run forwards - forwardAgent bool // -A: forward local SSH agent to remote session - localForwards []client.LocalForwardSpec // -L specs - remoteForwards []client.RemoteForwardSpec // -R specs - dynamicProxies []client.DynamicForwardSpec // -D specs + identityFile string + caService string + sshService string + service string // explicit override (--service) + keyFile string + oidc oidcFlowParams + zitiTimeout time.Duration + target string // raw "[user@]target" argument + command string // optional remote command; empty means interactive shell + verbose bool + noShell bool // -N: do not open a shell, only run forwards + forwardAgent bool // -A: forward local SSH agent to remote session + // forwardAgentUnverified acknowledges that the host cannot be verified + // (see checkAgentForwarding) and allows -A anyway. + forwardAgentUnverified bool + localForwards []client.LocalForwardSpec // -L specs + remoteForwards []client.RemoteForwardSpec // -R specs + dynamicProxies []client.DynamicForwardSpec // -D specs } // certTimeRemaining parses the certificate at certPath and returns the time @@ -450,14 +568,14 @@ func certTimeRemaining(certPath string) (string, bool) { } func runConnect(p connectParams) error { - username, host, err := parseTarget(p.target) - if err != nil { + if err := checkAgentForwarding(p.forwardAgent, p.forwardAgentUnverified); err != nil { return err } + username, host, explicitUser := splitTarget(p.target) // Resolve SSH key path before touching the network so we can check cert // freshness without authenticating twice. - privKeyPath, err := resolveKey(p.keyFile) + privKeyPath, err := resolveKey(p.keyFile, true) if err != nil { return err } @@ -500,8 +618,14 @@ func runConnect(p connectParams) error { } } + if !explicitUser { + if username, err = defaultUser(certPath); err != nil { + return err + } + } + // Load signer (private key + cert). - signer, err := client.NewCertSigner(privKeyPath) + signer, err := client.NewCertSignerPrompt(privKeyPath, client.TTYPassphrasePrompt(privKeyPath)) if err != nil { return fmt.Errorf("load SSH key: %w", err) } @@ -518,6 +642,7 @@ func runConnect(p connectParams) error { } registerZtAPIsPersist(zitiCtx, p.identityFile) + defer mfa.RegisterTTY(zitiCtx)() if err := config.RunWithTimeout(p.zitiTimeout, "authenticate", zitiCtx.Authenticate); err != nil { return err @@ -535,12 +660,18 @@ func runConnect(p connectParams) error { // Target matches a known service name: dial it directly. dialService = host terminatorAddr = "" + fmt.Fprintf(os.Stderr, "Dialing service %q directly: any host bound to it may answer.\n", dialService) } if p.verbose { fmt.Fprintf(os.Stderr, "%-12s %s @ %s\n", "Connecting:", username, host) } + hostKeyCallback, err := client.NewHostKeyCallback(dialService, terminatorAddr) + if err != nil { + return err + } + dialCtx, dialCancel := context.WithTimeout(context.Background(), p.zitiTimeout) defer dialCancel() @@ -570,14 +701,14 @@ func runConnect(p connectParams) error { if !hasForwards { if p.command != "" { slog.Debug("running remote command", "user", username, "host", host, "command", p.command) - return client.RunCommand(netConn, username, host, p.command, signer) + return client.RunCommand(netConn, username, host, p.command, signer, hostKeyCallback) } slog.Debug("SSH session starting", "user", username, "host", host) - return client.RunSession(netConn, username, host, signer, p.forwardAgent) + return client.RunSession(netConn, username, host, signer, p.forwardAgent, hostKeyCallback) } // Build an *ssh.Client for forwarding (and optionally a shell session). - sshClient, err := client.NewSSHClient(netConn, username, host, signer) + sshClient, err := client.NewSSHClient(netConn, username, host, signer, hostKeyCallback) if err != nil { return err } @@ -775,7 +906,7 @@ func runProxy(p proxyParams) error { } // Resolve SSH key for cert refresh — same logic as connect. - privKeyPath, err := resolveKey(p.keyFile) + privKeyPath, err := resolveKey(p.keyFile, false) // never prompt: stdin/stdout are the SSH stream if err != nil { return err } @@ -811,6 +942,10 @@ func runProxy(p proxyParams) error { registerZtAPIsPersist(zitiCtx, p.identityFile) + // MFA codes are read from the terminal, never stdin (here it carries the + // SSH stream). + defer mfa.RegisterTTY(zitiCtx)() + if err := config.RunWithTimeout(p.zitiTimeout, "authenticate", zitiCtx.Authenticate); err != nil { return err } @@ -824,6 +959,7 @@ func runProxy(p proxyParams) error { } else if _, ok := zitiCtx.GetService(host); ok { dialService = host terminatorAddr = "" + fmt.Fprintf(os.Stderr, "Dialing service %q directly: any host bound to it may answer.\n", dialService) } dialCtx, dialCancel := context.WithTimeout(context.Background(), p.zitiTimeout) @@ -930,6 +1066,7 @@ func runList(identityFile string, zitiTimeout time.Duration) error { return fmt.Errorf("init Ziti context from %q: %w", identityFile, err) } defer zitiCtx.Close() + defer mfa.RegisterTTY(zitiCtx)() if err := config.RunWithTimeout(zitiTimeout, "authenticate", zitiCtx.Authenticate); err != nil { return err @@ -966,31 +1103,8 @@ func runList(identityFile string, zitiTimeout time.Duration) error { // MFA helpers // --------------------------------------------------------------------------- -func readMFACode(allowEmpty bool) string { - reader := bufio.NewReader(os.Stdin) - for { - fmt.Print("MFA TOTP code: ") - code, _ := reader.ReadString('\n') - code = strings.TrimSpace(code) - if code != "" || allowEmpty { - return code - } - } -} - -// mfaTotpListener returns a listener function compatible with -// ziti.Events().AddMfaTotpCodeListener. -func mfaTotpListener(_ ziti.Context, _ *rest_model.AuthQueryDetail, response ziti.MfaCodeResponse) { - for { - fmt.Println("MFA TOTP required to fully authenticate.") - code := readMFACode(false) - if err := response(code); err != nil { - fmt.Println("error verifying MFA TOTP:", err) - continue - } - break - } -} +// mfaStdin reads MFA codes for the mfa subcommands (hidden on a terminal). +var mfaStdin = mfa.NewReader(os.Stdin) func runMFAEnable(identityFile string, showQR bool, zitiTimeout time.Duration) error { zitiCtx, err := ziti.NewContextFromFile(identityFile) @@ -1000,7 +1114,7 @@ func runMFAEnable(identityFile string, showQR bool, zitiTimeout time.Duration) e defer zitiCtx.Close() // Register MFA listener before authenticating in case it fires during auth. - zitiCtx.Events().AddMfaTotpCodeListener(mfaTotpListener) + zitiCtx.Events().AddMfaTotpCodeListener(mfa.Listener(mfaStdin, os.Stderr)) if err := config.RunWithTimeout(zitiTimeout, "authenticate", zitiCtx.Authenticate); err != nil { return err @@ -1031,7 +1145,10 @@ func runMFAEnable(identityFile string, showQR bool, zitiTimeout time.Duration) e } fmt.Println() - code := readMFACode(false) + code, err := mfa.ReadCode(mfaStdin, os.Stderr, false) + if err != nil { + return err + } if err := zitiCtx.VerifyZitiMfa(code); err != nil { return fmt.Errorf("verify MFA code: %w", err) } @@ -1064,7 +1181,7 @@ func runMFAVerify(identityFile string, zitiTimeout time.Duration) error { } defer zitiCtx.Close() - zitiCtx.Events().AddMfaTotpCodeListener(mfaTotpListener) + zitiCtx.Events().AddMfaTotpCodeListener(mfa.Listener(mfaStdin, os.Stderr)) if err := config.RunWithTimeout(zitiTimeout, "authenticate", zitiCtx.Authenticate); err != nil { return err @@ -1089,7 +1206,11 @@ func runMFARemove(identityFile string, zitiTimeout time.Duration) error { fmt.Println("If MFA TOTP is enrolled, enter a valid code or recovery code.") fmt.Println("Otherwise, enter any value to continue.") fmt.Println() - code := readMFACode(true) + code, err := mfa.ReadCode(mfaStdin, os.Stderr, true) + if err != nil { + done <- err + return + } if err := c.RemoveZitiMfa(code); err != nil { done <- fmt.Errorf("remove MFA: %w", err) return @@ -1205,16 +1326,17 @@ Usage: // ---------------------------------------------------------------- connect var ( - caServiceFlag string - sshServiceFlag string - serviceFlag string - keyFlag string - oidcIssuerFlag string - noShellFlag bool - forwardAgentFlag bool - localFwdFlags []string - remoteFwdFlags []string - dynamicFwdFlags []string + caServiceFlag string + sshServiceFlag string + serviceFlag string + keyFlag string + oidcIssuerFlag string + noShellFlag bool + forwardAgentFlag bool + forwardAgentUnverifiedFlag bool + localFwdFlags []string + remoteFwdFlags []string + dynamicFwdFlags []string ) connectCmd = &cobra.Command{ Use: "connect [user@] [-- [args...]]", @@ -1229,7 +1351,8 @@ automatically refreshed via the ziti-ssh-ca service before connecting. The target may be given as: user@identity-name — SSH as to the host with Ziti identity - identity-name — SSH as the current OS user + identity-name — SSH as the certificate's principal (per-identity mode: + your derived Linux username), else the current OS user If the target exactly matches a Ziti service name it is dialled directly. Otherwise it is used as a terminator address on the --ssh-service. @@ -1274,6 +1397,7 @@ Examples: if err != nil { return err } + warnNonLoopbackBind("-L", spec.Bind) localFwds = append(localFwds, spec) } var remoteFwds []client.RemoteForwardSpec @@ -1290,6 +1414,7 @@ Examples: if err != nil { return err } + warnNonLoopbackBind("-D", spec.Bind) dynFwds = append(dynFwds, spec) } @@ -1305,15 +1430,16 @@ Examples: ClientSecret: cfg.OIDC.ClientSecret, CallbackPort: oidcCallbackPort, }, - zitiTimeout: zitiTimeout, - target: args[0], - command: remoteCommand, - verbose: verbose, - noShell: noShellFlag, - forwardAgent: forwardAgentFlag, - localForwards: localFwds, - remoteForwards: remoteFwds, - dynamicProxies: dynFwds, + zitiTimeout: zitiTimeout, + target: args[0], + command: remoteCommand, + verbose: verbose, + noShell: noShellFlag, + forwardAgent: forwardAgentFlag, + forwardAgentUnverified: forwardAgentUnverifiedFlag, + localForwards: localFwds, + remoteForwards: remoteFwds, + dynamicProxies: dynFwds, }) }, } @@ -1323,7 +1449,8 @@ Examples: connectCmd.Flags().StringVar(&keyFlag, "key", "", "SSH private key path (default: auto-detect from ~/.ssh/)") connectCmd.Flags().StringVar(&oidcIssuerFlag, "oidc-issuer", "", "OIDC issuer URL; triggers browser-based OIDC auth before connecting (or set oidc.issuer in config)") connectCmd.Flags().BoolVarP(&noShellFlag, "no-shell", "N", false, "Do not open a shell; only forward ports (requires at least one -L, -R, or -D)") - connectCmd.Flags().BoolVarP(&forwardAgentFlag, "forward-agent", "A", false, "Forward local SSH agent to the remote session (requires SSH_AUTH_SOCK)") + connectCmd.Flags().BoolVarP(&forwardAgentFlag, "forward-agent", "A", false, "Forward local SSH agent to the remote session (requires SSH_AUTH_SOCK and --forward-agent-unverified)") + connectCmd.Flags().BoolVar(&forwardAgentUnverifiedFlag, "forward-agent-unverified", false, "Allow -A although the host's identity cannot be verified (the host can use your agent while connected)") connectCmd.Flags().StringArrayVarP(&localFwdFlags, "local-forward", "L", nil, "Local port forward: [bind:]localport:remotehost:remoteport (may be repeated)") connectCmd.Flags().StringArrayVarP(&remoteFwdFlags, "remote-forward", "R", nil, "Remote port forward: [bind:]remoteport:localhost:localport (may be repeated)") connectCmd.Flags().StringArrayVarP(&dynamicFwdFlags, "dynamic", "D", nil, "Dynamic SOCKS5 proxy: [bind:]port (may be repeated)") @@ -1547,6 +1674,7 @@ Example: }, } root.AddCommand(versionCmd) + root.AddCommand(newKnownHostsCmd()) if err := root.Execute(); err != nil { os.Exit(1) @@ -1555,3 +1683,69 @@ Example: // Compile-time assertion: confirm the time package is referenced. var _ = time.Now + +// checkAgentForwarding refuses -A unless the user explicitly accepts that the +// host cannot be verified. ziti-ssh cannot yet confirm which identity answered +// on a terminator address, so a host impersonating another could use the +// forwarded agent to authenticate as the user elsewhere while connected. +func checkAgentForwarding(forward, unverified bool) error { + if forward && !unverified { + return fmt.Errorf("-A/--forward-agent is disabled: ziti-ssh cannot yet verify which host answered, " + + "and a forwarded agent can be used by that host while you are connected. " + + "To forward anyway, add --forward-agent-unverified (the CA must also grant permit-agent-forwarding)") + } + return nil +} + +// newKnownHostsCmd builds "ziti-ssh known-hosts list|remove". +func newKnownHostsCmd() *cobra.Command { + store := func() (client.KnownHosts, error) { + path, err := client.DefaultKnownHostsPath() + return client.KnownHosts{Path: path}, err + } + khCmd := &cobra.Command{ + Use: "known-hosts", + Short: "Show or remove remembered SSH host keys", + Long: `ziti-ssh remembers the SSH host key(s) seen for each Ziti address and refuses +a changed key ("@" addresses) or asks before trusting an +additional key (services dialed directly, where any bound host may answer). + +Addresses are "@" for hosts dialed by name, or "" for +services dialed directly.`, + } + khCmd.AddCommand(&cobra.Command{ + Use: "list", + Short: "List remembered host keys", + Args: cobra.NoArgs, + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + kh, err := store() + if err != nil { + return err + } + return kh.List(os.Stdout) + }, + }) + khCmd.AddCommand(&cobra.Command{ + Use: "remove
", + Short: "Forget the host key(s) for an address, e.g. after a host was rebuilt", + Args: cobra.ExactArgs(1), + SilenceUsage: true, + RunE: func(cmd *cobra.Command, args []string) error { + kh, err := store() + if err != nil { + return err + } + n, err := kh.Remove(args[0]) + if err != nil { + return err + } + if n == 0 { + return fmt.Errorf("no host keys remembered for %q (see: ziti-ssh known-hosts list)", args[0]) + } + fmt.Printf("Removed %d host key(s) for %s\n", n, args[0]) + return nil + }, + }) + return khCmd +} diff --git a/cmd/ziti-ssh/main_test.go b/cmd/ziti-ssh/main_test.go new file mode 100644 index 0000000..a7027a0 --- /dev/null +++ b/cmd/ziti-ssh/main_test.go @@ -0,0 +1,137 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package main + +import ( + "io" + "os" + "testing" +) + +func TestCheckAgentForwarding(t *testing.T) { + if err := checkAgentForwarding(false, false); err != nil { + t.Errorf("no -A: %v", err) + } + if err := checkAgentForwarding(true, false); err == nil { + t.Error("-A allowed without --forward-agent-unverified") + } + if err := checkAgentForwarding(true, true); err != nil { + t.Errorf("-A with --forward-agent-unverified refused: %v", err) + } +} + +func TestResolveKey_NonInteractiveNeverPrompts(t *testing.T) { + t.Setenv("HOME", t.TempDir()) // no SSH keys + + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + stdout := os.Stdout + os.Stdout = w + _, resolveErr := resolveKey("", false) + os.Stdout = stdout + w.Close() + out, _ := io.ReadAll(r) + + if resolveErr == nil { + t.Fatal("want an error when no key exists in non-interactive mode") + } + if len(out) != 0 { + t.Fatalf("non-interactive resolveKey wrote to stdout (would corrupt the proxied SSH stream): %q", out) + } +} + +func TestParseTarget_SplitsAtLastAt(t *testing.T) { + cases := map[string][2]string{ + "bob@web1": {"bob", "web1"}, + "alice@corp.com@web1": {"alice@corp.com", "web1"}, + } + for in, want := range cases { + u, h, err := parseTarget(in) + if err != nil || u != want[0] || h != want[1] { + t.Errorf("parseTarget(%q) = %q, %q, %v; want %q, %q", in, u, h, err, want[0], want[1]) + } + } + if _, h, err := parseTarget("web1"); err != nil || h != "web1" { + t.Errorf("parseTarget(web1) = %q, %v", h, err) + } +} + +func TestParseForwardSpecs(t *testing.T) { + l, err := parseLocalForward("[::1]:8080:[2001:db8::1]:80") + if err != nil || l.Bind != "::1" || l.LocalPort != "8080" || l.RemoteHost != "2001:db8::1" || l.RemotePort != "80" { + t.Errorf("IPv6 -L: %+v, %v", l, err) + } + l, err = parseLocalForward("8080:db:5432") + if err != nil || l.Bind != "127.0.0.1" || l.RemoteHost != "db" { + t.Errorf("3-part -L: %+v, %v", l, err) + } + r, err := parseRemoteForward("[::]:9000:localhost:3000") + if err != nil || r.Bind != "::" || r.RemotePort != "9000" || r.LocalHost != "localhost" || r.LocalPort != "3000" { + t.Errorf("IPv6 -R: %+v, %v", r, err) + } + d, err := parseDynamicForward("[::1]:1080") + if err != nil || d.Bind != "::1" || d.LocalPort != "1080" { + t.Errorf("IPv6 -D: %+v, %v", d, err) + } + for _, bad := range []string{"0:db:80", "8080:db:65536", "x:db:80", "8080::80", "[::1:8080:db:80", "[::1]x:8080:db:80"} { + if _, err := parseLocalForward(bad); err == nil { + t.Errorf("-L %q accepted", bad) + } + } + if _, err := parseDynamicForward("99999"); err == nil { + t.Error("-D 99999 accepted") + } +} + +func TestIsLoopbackBind(t *testing.T) { + for _, b := range []string{"", "localhost", "127.0.0.1", "127.0.0.2", "::1"} { + if !isLoopbackBind(b) { + t.Errorf("%q not loopback", b) + } + } + for _, b := range []string{"0.0.0.0", "::", "*", "192.168.1.5", "example.com"} { + if isLoopbackBind(b) { + t.Errorf("%q treated as loopback", b) + } + } +} + +func TestSplitTarget(t *testing.T) { + cases := map[string]struct { + user, target string + explicit bool + }{ + "web1": {"", "web1", false}, + "bob@web1": {"bob", "web1", true}, + "alice@corp.com@web1": {"alice@corp.com", "web1", true}, + } + for in, want := range cases { + u, h, ex := splitTarget(in) + if u != want.user || h != want.target || ex != want.explicit { + t.Errorf("splitTarget(%q) = %q, %q, %v; want %+v", in, u, h, ex, want) + } + } +} + +func TestDefaultUser_FallsBackToOSUser(t *testing.T) { + u, err := defaultUser(t.TempDir() + "/missing-cert.pub") + if err != nil || u == "" { + t.Fatalf("defaultUser without a certificate: %q, %v", u, err) + } +} diff --git a/config/ctrlurls.go b/config/ctrlurls.go new file mode 100644 index 0000000..677df46 --- /dev/null +++ b/config/ctrlurls.go @@ -0,0 +1,79 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package config + +import ( + "fmt" + "net/url" +) + +// CheckControllerURL reports why u is not an acceptable controller API URL: +// it must be https with a host, and carry no user info, query or fragment. +func CheckControllerURL(u *url.URL) error { + switch { + case u == nil: + return fmt.Errorf("empty URL") + case u.Scheme != "https": + return fmt.Errorf("%q: scheme must be https", u.Redacted()) + case u.Hostname() == "": + return fmt.Errorf("%q: no host", u.Redacted()) + case u.User != nil: + return fmt.Errorf("%q: user info not allowed", u.Redacted()) + case u.RawQuery != "" || u.ForceQuery || u.Fragment != "": + return fmt.Errorf("%q: query or fragment not allowed", u.Redacted()) + } + return nil +} + +// FilterControllerURLs returns the acceptable URLs from a controller-supplied +// list (see CheckControllerURL), without duplicates and in their original +// order, plus one problem description per rejected entry. +func FilterControllerURLs(urls []*url.URL) (valid []*url.URL, rejected []string) { + seen := make(map[string]bool, len(urls)) + for _, u := range urls { + if err := CheckControllerURL(u); err != nil { + rejected = append(rejected, err.Error()) + continue + } + key := u.String() + if seen[key] { + continue + } + seen[key] = true + valid = append(valid, u) + } + return valid, rejected +} + +// FilterControllerURLStrings is FilterControllerURLs for string URLs; an +// entry that does not parse is rejected. +func FilterControllerURLStrings(urls []string) (valid []string, rejected []string) { + parsed := make([]*url.URL, 0, len(urls)) + for _, s := range urls { + u, err := url.Parse(s) + if err != nil { + rejected = append(rejected, fmt.Sprintf("unparseable URL: %v", err)) + continue + } + parsed = append(parsed, u) + } + ok, bad := FilterControllerURLs(parsed) + for _, u := range ok { + valid = append(valid, u.String()) + } + return valid, append(rejected, bad...) +} diff --git a/config/perms.go b/config/perms.go new file mode 100644 index 0000000..cec8ebd --- /dev/null +++ b/config/perms.go @@ -0,0 +1,48 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package config + +import ( + "errors" + "fmt" + "os" +) + +// CheckUserFile refuses a file that another user could have written, as +// OpenSSH does for its per-user client config ("Bad owner or permissions"): +// it must be owned by the current user (or root), not writable by others, +// and not writable by its group unless that group is the owner's private +// group (Debian/Ubuntu default umask 002). A missing file is not an error. +func CheckUserFile(path string) error { + fi, err := os.Stat(path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + // Group write is accepted only for the owner's private group (see + // privateGroup), as OpenSSH does; world write never. + if perm := fi.Mode().Perm(); perm&0o002 != 0 || (perm&0o020 != 0 && !privateGroup(fi)) { + return fmt.Errorf("bad permissions on %s (%04o): it must not be writable by others or by a shared group (chmod go-w %s)", + path, perm, path) + } + if uid, ok := fileOwner(fi); ok && uid != 0 && uid != os.Getuid() { + return fmt.Errorf("bad owner of %s (uid %d): it must be owned by you or root", path, uid) + } + return nil +} diff --git a/config/perms_other.go b/config/perms_other.go new file mode 100644 index 0000000..57b3d88 --- /dev/null +++ b/config/perms_other.go @@ -0,0 +1,25 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +//go:build !unix + +package config + +import "os" + +func fileOwner(os.FileInfo) (int, bool) { return 0, false } + +func privateGroup(os.FileInfo) bool { return false } diff --git a/config/perms_test.go b/config/perms_test.go new file mode 100644 index 0000000..6992b01 --- /dev/null +++ b/config/perms_test.go @@ -0,0 +1,109 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +//go:build unix + +package config + +import ( + "fmt" + "os" + "os/user" + "path/filepath" + "testing" +) + +func writeMode(t *testing.T, f string, mode os.FileMode) { + t.Helper() + if err := os.Chmod(f, mode); err != nil { + t.Fatal(err) + } +} + +func TestCheckUserFile(t *testing.T) { + dir := t.TempDir() + if err := CheckUserFile(filepath.Join(dir, "missing")); err != nil { + t.Errorf("missing file: %v", err) + } + f := filepath.Join(dir, "config.yaml") + if err := os.WriteFile(f, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + + // No group file entry: group write is never accepted. + old := groupFile + t.Cleanup(func() { groupFile = old }) + groupFile = filepath.Join(dir, "no-such-group-file") + + for _, mode := range []os.FileMode{0o600, 0o644, 0o640, 0o400} { + writeMode(t, f, mode) + if err := CheckUserFile(f); err != nil { + t.Errorf("mode %04o refused: %v", mode, err) + } + } + for _, mode := range []os.FileMode{0o664, 0o666, 0o602, 0o620} { + writeMode(t, f, mode) + if err := CheckUserFile(f); err == nil { + t.Errorf("mode %04o accepted without a private group", mode) + } + } +} + +// Debian/Ubuntu give each user a private group and a umask of 002, so files +// are created 0664. That must be accepted, as OpenSSH does — but only while +// the group has no other members. +func TestCheckUserFile_UserPrivateGroup(t *testing.T) { + me, err := user.Current() + if err != nil { + t.Skip(err) + } + grp, err := user.LookupGroupId(me.Gid) + if err != nil || grp.Name != me.Username { + t.Skipf("primary group of %q is not a private group (%v)", me.Username, err) + } + dir := t.TempDir() + f := filepath.Join(dir, "config.yaml") + if err := os.WriteFile(f, []byte("x"), 0o664); err != nil { + t.Fatal(err) + } + writeMode(t, f, 0o664) + + old := groupFile + t.Cleanup(func() { groupFile = old }) + gf := filepath.Join(dir, "group") + + for _, members := range []string{"", me.Username} { + if err := os.WriteFile(gf, []byte(fmt.Sprintf("%s:x:%s:%s\n", grp.Name, me.Gid, members)), 0o644); err != nil { + t.Fatal(err) + } + groupFile = gf + if err := CheckUserFile(f); err != nil { + t.Errorf("private group (members %q): 0664 refused: %v", members, err) + } + } + + if err := os.WriteFile(gf, []byte(fmt.Sprintf("%s:x:%s:%s,mallory\n", grp.Name, me.Gid, me.Username)), 0o644); err != nil { + t.Fatal(err) + } + if err := CheckUserFile(f); err == nil { + t.Error("0664 accepted although the group has another member") + } + + writeMode(t, f, 0o666) + if err := CheckUserFile(f); err == nil { + t.Error("world-writable file accepted") + } +} diff --git a/config/perms_unix.go b/config/perms_unix.go new file mode 100644 index 0000000..d50dbf1 --- /dev/null +++ b/config/perms_unix.go @@ -0,0 +1,94 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +//go:build unix + +package config + +import ( + "bufio" + "os" + "os/user" + "strconv" + "strings" + "syscall" +) + +func fileOwner(fi os.FileInfo) (int, bool) { + st, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + return 0, false + } + return int(st.Uid), true +} + +// groupFile is the group database read by privateGroup (a variable for tests). +var groupFile = "/etc/group" + +// privateGroup reports whether fi's group is its owner's private group (the +// "user private group" scheme used by Debian/Ubuntu, where the default umask +// is 002): the owner's primary group, named after the owner, with no members +// other than the owner. A group-writable file in such a group is writable +// only by its owner, so OpenSSH accepts it too. +func privateGroup(fi os.FileInfo) bool { + st, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + return false + } + owner, err := user.LookupId(strconv.FormatUint(uint64(st.Uid), 10)) + if err != nil || owner.Gid != strconv.FormatUint(uint64(st.Gid), 10) { + return false + } + members, found := groupMembers(owner.Gid) + if !found { + return false + } + grp, err := user.LookupGroupId(owner.Gid) + if err != nil || grp.Name != owner.Username { + return false + } + for _, m := range members { + if m != owner.Username { + return false + } + } + return true +} + +// groupMembers returns the explicit member list of gid from groupFile. +// found is false if the group is not listed there (e.g. a directory-service +// group), in which case its members cannot be checked. +func groupMembers(gid string) (members []string, found bool) { + f, err := os.Open(groupFile) + if err != nil { + return nil, false + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + fields := strings.Split(sc.Text(), ":") + if len(fields) != 4 || fields[2] != gid { + continue + } + for _, m := range strings.Split(fields[3], ",") { + if m = strings.TrimSpace(m); m != "" { + members = append(members, m) + } + } + return members, true + } + return nil, false +} diff --git a/config/ztapis.go b/config/ztapis.go index 28491d8..ab85826 100644 --- a/config/ztapis.go +++ b/config/ztapis.go @@ -19,7 +19,10 @@ package config import ( "encoding/json" "fmt" + "log/slog" "os" + "slices" + "strings" ) // PersistZtAPIs atomically overwrites the ztAPIs field in the given Ziti @@ -31,7 +34,26 @@ import ( // this, the identity file only ever contains the originally enrolled // controller URL, meaning a process restart fails if that specific controller // is offline (even if other cluster members are healthy). +// +// Entries that are not acceptable controller URLs (CheckControllerURL: https, +// a host, no user info/query/fragment) are dropped and logged, duplicates are +// removed, and a list with no acceptable entry is refused. The file is not +// rewritten when the stored list is already the same. +// +// There is no cross-process lock: only ztAPIs changes, every writer derives it +// from the same controller and the write is an atomic rename, so concurrent +// writers can only race to store equivalent lists. func PersistZtAPIs(identityFile string, urls []string) error { + if len(urls) == 0 { + return fmt.Errorf("refusing to persist an empty controller URL list") + } + urls, rejected := FilterControllerURLStrings(urls) + for _, r := range rejected { + slog.Warn("ignoring controller URL", "reason", r) + } + if len(urls) == 0 { + return fmt.Errorf("refusing to persist controller URL list: no acceptable entries (%s)", strings.Join(rejected, "; ")) + } data, err := os.ReadFile(identityFile) if err != nil { return fmt.Errorf("read identity file: %w", err) @@ -44,6 +66,13 @@ func PersistZtAPIs(identityFile string, urls []string) error { return fmt.Errorf("parse identity file: %w", err) } + if stored, ok := raw["ztAPIs"]; ok { + var current []string + if json.Unmarshal(stored, ¤t) == nil && slices.Equal(current, urls) { + return nil // unchanged: no rewrite + } + } + encoded, err := json.Marshal(urls) if err != nil { return fmt.Errorf("marshal ztAPIs: %w", err) diff --git a/config/ztapis_test.go b/config/ztapis_test.go new file mode 100644 index 0000000..00f41f5 --- /dev/null +++ b/config/ztapis_test.go @@ -0,0 +1,78 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestPersistZtAPIs_RefusesEmptyList(t *testing.T) { + f := filepath.Join(t.TempDir(), "identity.json") + orig := `{"ztAPI":"https://ctrl:443","ztAPIs":["https://ctrl:443"]}` + if err := os.WriteFile(f, []byte(orig), 0600); err != nil { + t.Fatal(err) + } + if err := PersistZtAPIs(f, nil); err == nil { + t.Fatal("empty controller list accepted") + } + if b, _ := os.ReadFile(f); string(b) != orig { + t.Fatalf("identity file modified: %s", b) + } +} + +func TestPersistZtAPIs_FiltersAndSkipsUnchanged(t *testing.T) { + f := filepath.Join(t.TempDir(), "identity.json") + orig := `{"ztAPI":"https://ctrl:443","ztAPIs":["https://ctrl:443"]}` + if err := os.WriteFile(f, []byte(orig), 0600); err != nil { + t.Fatal(err) + } + + // Only unacceptable entries: refused, file untouched. + bad := []string{"http://ctrl:80", "https://user:pw@ctrl:443", "https://ctrl:443/?x=1", "https://:443", "::"} + if err := PersistZtAPIs(f, bad); err == nil { + t.Fatal("list with no acceptable URL accepted") + } + if b, _ := os.ReadFile(f); string(b) != orig { + t.Fatalf("identity file modified: %s", b) + } + + // Same list as stored (after dedupe/filter): no rewrite. + before, _ := os.Stat(f) + if err := PersistZtAPIs(f, []string{"https://ctrl:443", "http://evil", "https://ctrl:443"}); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(f); string(b) != orig { + t.Fatalf("unchanged list rewrote the file: %s", b) + } + after, _ := os.Stat(f) + if !before.ModTime().Equal(after.ModTime()) { + t.Error("file rewritten for an unchanged list") + } + + // New list: invalid entries dropped, duplicates removed. + if err := PersistZtAPIs(f, []string{"https://a:443", "ftp://b", "https://a:443", "https://c:1280"}); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(f) + if !strings.Contains(string(b), `"https://a:443",`) || !strings.Contains(string(b), `"https://c:1280"`) || + strings.Contains(string(b), "ftp://") || strings.Count(string(b), "https://a:443") != 1 { + t.Fatalf("unexpected ztAPIs: %s", b) + } +} diff --git a/docs/building.md b/docs/building.md index a69d573..6785b34 100644 --- a/docs/building.md +++ b/docs/building.md @@ -24,6 +24,25 @@ curl -sSL https://get.netfoundry.io/linux-install.bash | sudo bash -s ziti-scp The install script configures the repository and installs the latest stable package. Subsequent upgrades are handled by the system package manager (`apt upgrade` / `yum update`). +### Verifying packages + +Packages from the repository are verified automatically by `apt` / `dnf`: the repository index is GPG-signed and lists each package's checksum. The packages themselves are not individually signed. + +Each release built from a tag also publishes: + +- **`SHA256SUMS`** — attached to the GitHub release; the checksums of every `.deb` and `.rpm` the release workflow built. +- **Build provenance attestations** — signed by GitHub Actions, linking each package to the commit and workflow run that built it. + +To check a package file (for example one fetched with `apt-get download ziti-ssh` or `dnf download ziti-ssh`): + +```sh +# Checksum (run in the directory holding the package and SHA256SUMS) +sha256sum --check --ignore-missing SHA256SUMS + +# Provenance (needs a GitHub CLI that has the `attestation` command) +gh attestation verify ziti-ssh_-1_amd64.deb --repo netfoundry/ziti-ssh +``` + --- ## Build packages locally diff --git a/docs/configuration.md b/docs/configuration.md index cf86707..9bbb630 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -21,11 +21,12 @@ All binaries resolve each setting in the same order: CLI flag > environment vari |---|---|---|---| | `--ca-service` | `ZITI_CA_SERVICE` | `ssh-ca` | CA service name | | `--ssh-service` | `ZITI_SSH_SERVICE` | `ssh` | SSH service name | -| `--service` | — | — | SSH service name to dial (alias for `--ssh-service`) | +| `--service` | — | — | Dial this service with the target as terminator address, even if the target is also a service name (otherwise like `--ssh-service`) | | `--key` | — | auto-detect | SSH private key path | | `--oidc-issuer` | — | — | OIDC issuer URL; triggers browser-based OIDC auth (overrides `oidc.issuer` in config) | | `-N` / `--no-shell` | — | false | Do not open a shell; only run port forwards. Requires at least one `-L`, `-R`, or `-D`. | -| `-A` / `--forward-agent` | — | false | Forward the local SSH agent to the remote session. Requires `SSH_AUTH_SOCK`. Non-fatal if the agent is unreachable — session continues without forwarding. | +| `-A` / `--forward-agent` | — | false | Forward the local SSH agent to the remote session. Refused unless `--forward-agent-unverified` is also given (the host cannot yet be verified), and the CA must grant `permit-agent-forwarding`. Requires `SSH_AUTH_SOCK`. Non-fatal if the agent is unreachable — session continues without forwarding. | +| `--forward-agent-unverified` | — | false | Allow `-A` although the host's identity cannot be verified. The remote host can use your agent while you are connected. | | `-L` / `--local-forward` | — | — | Local port forward: `[bind:]localport:remotehost:remoteport`. May be repeated. | | `-R` / `--remote-forward` | — | — | Remote port forward: `[bind:]remoteport:localhost:localport`. May be repeated. | | `-D` / `--dynamic` | — | — | Dynamic SOCKS5 proxy: `[bind:]port`. May be repeated. | @@ -36,7 +37,7 @@ All binaries resolve each setting in the same order: CLI flag > environment vari |---|---|---|---| | `--ca-service` | `ZITI_CA_SERVICE` | `ssh-ca` | CA service name (for cert auto-refresh) | | `--ssh-service` | `ZITI_SSH_SERVICE` | `ssh` | SSH service name | -| `--service` | — | — | SSH service name to dial (alias for `--ssh-service`) | +| `--service` | — | — | Dial this service with the target as terminator address, even if the target is also a service name (otherwise like `--ssh-service`) | | `--key` | — | auto-detect | SSH private key path (used for cert refresh check) | | `--oidc-issuer` | — | — | OIDC issuer URL; triggers browser-based OIDC auth before dialling | @@ -64,6 +65,15 @@ All binaries resolve each setting in the same order: CLI flag > environment vari --- +### `ziti-ssh known-hosts` + +| Subcommand | Description | +|---|---| +| `list` | List remembered host keys: Ziti address, key type, SHA256 fingerprint | +| `remove
` | Forget the key(s) for an address (`@` or ``), e.g. after a host was rebuilt | + +Host keys are stored in `$XDG_CONFIG_HOME/ziti-ssh/known_hosts` (default under `~/.config/ziti-ssh/`). See [usage.md](usage.md#host-keys-trust-on-first-use). + ## `ziti-ssh-ca` | Flag | Environment variable | Default | Required | Description | @@ -74,8 +84,11 @@ All binaries resolve each setting in the same order: CLI flag > environment vari | `--principal` | `ZITI_SSH_PRINCIPAL` | `ziggy` | No | Linux username placed in `ValidPrincipals` (shared mode only) | | `--mode` | `ZITI_SSH_MODE` | `shared` | No | Principal mode: `shared` or `per-identity` | | `--cert-ttl` | `ZITI_CERT_TTL` | `5m` | No | Certificate validity duration (e.g. `4h`, `12h`, `24h`); must be > 0 | -| `--rate-limit` | `ZITI_RATE_LIMIT` | `5` | No | Maximum cert signing requests per minute per identity (decimal values accepted for sub-minute rates) | +| `--cert-extensions` | `ZITI_CERT_EXTENSIONS` | `permit-pty,permit-port-forwarding` | No | Certificate extensions (permissions) to grant, comma-separated, or `none`. Valid: `permit-pty`, `permit-port-forwarding`, `permit-agent-forwarding`, `permit-X11-forwarding`, `permit-user-rc`, `no-touch-required`. Agent forwarding is not granted by default. | +| `--cert-source-address` | `ZITI_CERT_SOURCE_ADDRESS` | `127.0.0.1/32,::1/128` | No | Comma-separated IPs/CIDRs written to each certificate's `source-address` critical option; sshd accepts the certificate only from those addresses. The default (loopback) means certificates work only through `ziti-ssh-host`'s local proxy. `none` disables it. | +| `--rate-limit` | `ZITI_RATE_LIMIT` | `5` | No | Maximum requests (cert signing and CA public key) per minute per identity (decimal values accepted for sub-minute rates) | | `--rate-burst` | `ZITI_RATE_BURST` | `3` | No | Burst allowance for the per-identity token-bucket rate limiter | +| `--max-connections` | `ZITI_MAX_CONNECTIONS` | `64` | No | Maximum concurrent CA connections; further connections are closed immediately. Each connection has a 10 s deadline. | | `--ziti-timeout` | `ZITI_TIMEOUT` | `30s` | No | Timeout for blocking Ziti network operations (authenticate, listen). Accepts any `time.Duration` string, e.g. `30s`, `1m`. | ### `ziti-ssh-ca enroll` subcommand @@ -103,8 +116,10 @@ The `config` subcommand manages the `ziti-ssh-host.v1` config type on the Ziti c |---|---|---|---| | `--controller` | `ZITI_CTRL_ADDRESS` | — | Controller hostname, optionally with port (default port: 443). Do not include `https://`. | | `--username` | `ZITI_CTRL_USERNAME` | — | Controller admin username | -| `--password` | `ZITI_CTRL_PASSWORD` | — | Controller admin password | -| `--insecure` | `ZITI_CTRL_INSECURE` | false | Skip TLS certificate verification. Mutually exclusive with `--controller-ca`. | +| `--password` | `ZITI_CTRL_PASSWORD` | — | Controller admin password. The flag is visible in the process list and prints a warning; prefer the environment variable, `--password-file`, or the interactive prompt (used when none is given and a terminal is attached). | +| `--password-file` | `ZITI_CTRL_PASSWORD_FILE` | — | Read the password from the first line of a file; `-` reads stdin | +| `--yes` / `-y` | — | false | Trust the controller's CA bundle on first use without asking. Never replaces a saved bundle that no longer matches. | +| `--insecure` | `ZITI_CTRL_INSECURE` | false | Skip TLS certificate verification (last resort; prints a warning — the admin password is sent unverified). Normally the controller's own CA bundle is fetched, confirmed and saved instead (see provisioning). Mutually exclusive with `--controller-ca`. | | `--controller-ca` | `ZITI_CTRL_CA` | — | Path to PEM CA certificate to trust for the controller TLS connection. Mutually exclusive with `--insecure`. | See [Configuring per-identity permissions](provisioning.md#configuring-per-identity-permissions-ziti-ssh-hostv1) in the provisioning guide for usage examples. @@ -126,9 +141,15 @@ The `run` subcommand also accepts: | Flag | Environment variable | Default | Description | |---|---|---|---| | `--mode` | `ZITI_SSH_MODE` | `shared` | Principal mode: `shared` or `per-identity` | -| — | `ZITI_SSH_GROUPS` | — | Comma-separated Linux groups applied (via `usermod -aG`) to users not matched by a `ziti-ssh-host.v1` config entry. Global fallback; per-identity mode only. Groups must already exist on the host. | -| — | `ZITI_SUDOERS_RULE` | — | If set, a sudoers rule ` ` is written to `/etc/sudoers.d/` on first connect. Global fallback applied to users not matched by a `ziti-ssh-host.v1` config entry; per-identity mode only. | +| `--max-connections` | `ZITI_MAX_CONNECTIONS` | `128` | Maximum concurrent connections per service; further connections are closed immediately (logged at most every 10 s) | +| — | `ZITI_SSH_GROUPS` | — | Comma-separated Linux groups set as the user's supplementary groups (via `usermod -G`, replacing existing membership) for users not matched by a `ziti-ssh-host.v1` config entry. Global fallback; per-identity mode only. Groups must already exist on the host; if setting them fails, the connection is rejected. | +| — | `ZITI_SUDOERS_RULE` | — | If set, a sudoers rule ` ` is written to `/etc/sudoers.d/ziti-ssh-host-` on connect. Global fallback applied to users not matched by a `ziti-ssh-host.v1` config entry; per-identity mode only. | | — | `ZITI_USER_CLEANUP` | `false` | Set to `true` to delete the Linux account after the last session closes via `userdel -r` (per-identity mode only) | +| — | `ZITI_ALLOW_SUDOERS` | — | Services whose `ziti-ssh-host.v1` config may set `sudoers_rule`: comma-separated service names, or `*` for all. A config `sudoers_rule` from any other service is refused and the connection rejected. Does not affect `ZITI_SUDOERS_RULE`. | +| — | `ZITI_ALLOW_GROUPS` | — | Privileged groups a service's config may grant, as `:` (or `*:` for all services), comma-separated. By default a config may grant any group except `root`, `sudo`, `admin`, `wheel`, `docker`, `lxd`, `disk`, `shadow`, `libvirt`. | +| — | `ZITI_RESTRICT_GROUPS` | `false` | `true`: a config may grant **only** groups listed in `ZITI_ALLOW_GROUPS` (for hosts where custom groups carry sudo rights). Does not affect `ZITI_SSH_GROUPS`. | +| — | `ZITI_SERVICE_REFRESH` | `30s` | How often `ziti-ssh-host run` checks the controller for service changes (a duration, minimum `5s`). A changed `ziti-ssh-host.v1` config — including a removed grant — applies to new connections within this interval. Each check is a small request; services are re-fetched only when something changed. | +| — | `ZITI_TERMINATE_ON_DISCONNECT` | `false` | Set to `true` to end all of the account's processes, remove its crontab and `at` jobs, and expire the account (re-enabled on the identity's next authorized connection) when the last session closes, keeping the account and home directory (per-identity mode with `ZITI_USER_CLEANUP=false`; no effect when cleanup is on, which already ends them). Without it, background processes (`nohup`, `tmux`, systemd user services) survive disconnect and revocation. | `enroll` also requires `--jwt ` (no environment variable equivalent). @@ -140,6 +161,19 @@ The `run` subcommand also accepts: Uses the same `--identity` flag (and `ZITI_IDENTITY` env var) as the other subcommands. See [Inspecting per-identity permissions](operations.md#inspecting-per-identity-permissions) in the operations guide for details and example output. +### `ziti-ssh-host users list` / `users claim` + +Administer the per-identity account ownership registry (`/var/lib/ziti-ssh-host/owned-users.json`). Both must run as root; neither connects to the Ziti network. + +`users list` takes no flags. `users claim` flags: + +| Flag | Environment variable | Default | Description | +|---|---|---|---| +| `--username` | — | — | Existing Linux username to register. Must equal the username derived from `--identity`. Required. | +| `--identity` | — | — | Ziti identity name that owns the account. Required. | + +See [Managing account ownership](operations.md#managing-account-ownership) for when and how to use them. + --- ## `ziti-scp` @@ -158,9 +192,10 @@ Uses the same `--identity` flag (and `ZITI_IDENTITY` env var) as the other subco |---|---|---|---| | `--ca-service` | `ZITI_CA_SERVICE` | `ssh-ca` | CA service name | | `--ssh-service` | `ZITI_SSH_SERVICE` | `ssh` | SSH service name | +| `--service` | — | — | Dial this service with the remote host as terminator address, even if the host name is also a service name | | `--key` | — | auto-detect | SSH private key path | | `-r` / `--recursive` | — | false | Recursively copy entire directories | -| `-p` / `--preserve` | — | false | Preserve file timestamps and permissions | +| `-p` / `--preserve` | — | false | Preserve file timestamps and permissions (on download, never world-writable) | | `-q` / `--quiet` | — | false | Suppress per-file progress output | ### `ziti-scp enroll` @@ -194,8 +229,8 @@ This config is only consulted in `per-identity` mode. It has no effect in `share | Field | Type | Required | Description | |---|---|---|---| | `permissions` | object | yes | Map of Ziti identity name (or pattern) → permission entry. Keys may be exact identity names, glob patterns (using `*` and `?`), or the `"*"` catch-all. All matches are case-sensitive. | -| `permissions..groups` | array of strings | no | Linux groups to add the ephemeral user to via `usermod -aG` after account creation. Groups must already exist on the host. | -| `permissions..sudoers_rule` | string | no | The rule fragment placed after the username in `/etc/sudoers.d/`. Validated with `visudo -c` before installation. Omit to grant no sudo access. | +| `permissions..groups` | array of strings | no | The user's exact supplementary Linux groups, set via `usermod -G` on every connect. Groups must already exist on the host; if setting them fails, the connection is rejected. Privileged groups (`root`, `sudo`, `admin`, `wheel`, `docker`, `lxd`, `disk`, `shadow`, `libvirt`) are refused unless the host allows them for this service (`ZITI_ALLOW_GROUPS`). | +| `permissions..sudoers_rule` | string | no | The rule fragment placed after the username in `/etc/sudoers.d/ziti-ssh-host-`. Validated with `visudo -c` before installation. Omit to grant no sudo access. Refused unless the host lists this service in `ZITI_ALLOW_SUDOERS`. | ### Example @@ -210,11 +245,13 @@ This config is only consulted in `per-identity` mode. It has no effect in `share } ``` +> **Host opt-in required:** the `docker` group and `sudoers_rule` entries in this example are only applied on hosts that allow them for this service — e.g. `ZITI_ALLOW_SUDOERS=ssh` and `ZITI_ALLOW_GROUPS=ssh:docker` in `/etc/ziti-ssh-host/env`. Otherwise those identities are refused. See [Host grant policy](operations.md#host-grant-policy). + Identity keys are the **Ziti identity names** as they appear in the controller — not the derived Linux usernames. `ziti-ssh-host` applies `DeriveUsername` internally to obtain the Linux username for `useradd`, `usermod`, and the sudoers filename. Keys may be: - **Exact identity names** — matched literally (case-sensitive). -- **Glob patterns** — keys containing `*` or `?` are matched via `path.Match`. The most specific match wins (longest literal prefix before the first wildcard). +- **Glob patterns** — keys containing `*` or `?` are patterns: `*` matches any run of characters (including none, and including `/`), `?` matches exactly one character, and every other character — including `[`, `]` and `\` — matches itself. The most specific match wins: longest literal prefix before the first wildcard, then most literal characters overall; remaining ties go to the pattern that sorts first, so the result never depends on ordering. Keys containing `[` or `\` are flagged at load (log warning and `inspect`), because earlier releases treated them as character classes / escapes. - **`"*"` catch-all** — matches any identity not covered by an exact key or more-specific pattern. This is the preferred alternative to `ZITI_SSH_GROUPS`/`ZITI_SUDOERS_RULE` for setting a default permission set, because it lives in the config and propagates live without a host restart. ### Interaction with global fallbacks @@ -264,8 +301,24 @@ OIDC authentication is entirely optional. When no issuer is configured the behav When an OIDC issuer is configured: -1. Before dialling any Ziti service, `ziti-ssh connect` (and `ziti-ssh sign`) starts a temporary HTTP server on `localhost:` and opens your browser to the authorization URL. -2. You log in through your identity provider's normal web UI. +```mermaid +sequenceDiagram + participant C as ziti-ssh / ziti-scp + participant B as Browser + participant I as Identity provider + participant Z as Ziti controller + C->>C: Bind callback port on 127.0.0.1 and ::1
(abort if either is already in use) + C->>B: Print login URL, then open browser + B->>I: Sign in + I->>B: Redirect to localhost:/auth/callback?code=… + B->>C: Authorization code + C->>I: Exchange code (PKCE when no client secret) + I-->>C: Access token + C->>Z: Authenticate (mTLS identity + JWT) +``` + +1. Before dialling any Ziti service, `ziti-ssh connect` (and `sign`, `proxy`, and `ziti-scp`) claims the callback port on the loopback addresses `127.0.0.1` and `::1` (or `127.0.0.1` only on hosts without IPv6). It never listens on a network-facing address. If either loopback address is already in use, it **refuses to continue** — another process holding the port, for example another user on a shared machine, would otherwise receive your login — and tells you to stop that process or choose another `callback_port`. +2. It prints the login URL to stderr and tries to open it in your browser. On a headless machine, or if no browser can be launched, open the printed URL yourself (for example on a machine that can reach this one's `localhost`, via SSH port forwarding). Then log in through your identity provider's normal web UI. 3. The provider redirects to the local callback server with an authorization code. 4. `ziti-ssh` exchanges the code for an access token and adds it to the Ziti context via `GetCredentials().AddJWT()` before calling `Authenticate()`. 5. The Ziti controller validates the JWT against the configured ext-jwt-signer. If the JWT is accepted, the controller grants the session additional permissions beyond what the mTLS identity alone would receive. @@ -297,7 +350,7 @@ ziti edge update identity alice --auth-policy ssh-oidc-policy Consult the [OpenZiti ext-jwt-signer documentation](https://openziti.io/docs/reference/configuration/conventions#external-jwt-signers) for the full list of options. -Your OIDC provider must have `http://localhost:/auth/callback` registered as an allowed redirect URI. The default callback port is `63275`. +Your OIDC provider must have `http://localhost:/auth/callback` registered as an allowed redirect URI. The default callback port is `63275`. If you change `callback_port` (for example because another user on a shared machine holds the default), register the new URI too. ### Configuring `ziti-ssh` to use OIDC diff --git a/docs/operations.md b/docs/operations.md index 244b5a5..753e110 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -27,27 +27,47 @@ ziti-ssh ziggy@web-server-prod The CA derives a Linux username from each caller's Ziti identity name and places it in the certificate's `ValidPrincipals`. `ziti-ssh-host` creates the Linux user on the first connection from that identity and deletes it (including home directory) when the last session closes. **Username derivation rules** (`ca.DeriveUsername`): -1. Lowercase the entire identity name. +1. Lowercase ASCII letters (`A`–`Z`); other characters are not case-folded, so non-ASCII lookalikes such as the Kelvin sign `K` never become ASCII letters. 2. Replace any character outside `[a-z0-9_-]` with `_`. 3. If the result starts with a digit, prefix it with `z`. 4. Truncate to 32 characters. Examples: `Alice` → `alice`, `dba-Alice` → `dba-alice`, `123bot` → `z123bot` +**Account ownership:** `ziti-ssh-host` only creates, modifies, or deletes Linux accounts that it created itself (or that an administrator has explicitly claimed, see [Managing account ownership](#managing-account-ownership)). Ownership is recorded in `/var/lib/ziti-ssh-host/owned-users.json` (username → Ziti identity and UID). On each connection: + +```mermaid +flowchart TD + A[Connection from identity] --> B{Username valid?
not reserved, no leading '-'} + B -- no --> X[Reject] + B -- yes --> C{Account exists?
getent passwd} + C -- no --> D["useradd -m -s /bin/bash -- <username>"] + D --> E{UID >= 1000?} + E -- no --> X + E -- yes --> F[Record in owned-users.json] + F --> G[Apply groups and sudoers] + C -- yes --> H{Registered to this identity
with the same UID, UID >= 1000?} + H -- no --> X + H -- yes --> G +``` + +The connection is rejected — and the account left untouched — when the account already exists but was not created by `ziti-ssh-host` (for example `ubuntu` or an administrator account), when it is registered to a different Ziti identity (two identities deriving the same username), when it was deleted and recreated with a different UID, or when its UID is below 1000. Reserved names (`root`, common system accounts, `ubuntu`, `admin`, `ziti`) are always refused. `ziti-ssh-ca` refuses to sign a per-identity certificate for the same reserved names or for a principal starting with `-`. + **Ephemeral user lifecycle:** -- On first connection from an identity, `useradd -m -s /bin/bash ` runs. -- If `ZITI_SSH_GROUPS` is set, `usermod -aG ` is run immediately after account creation. Groups must already exist on the host; failure is non-fatal and logged. -- If `ZITI_SUDOERS_RULE` is set, a sudoers file is written to `/etc/sudoers.d/` (validated with `visudo -c` before installation). +- On first connection from an identity, `useradd -m -s /bin/bash -- ` runs and the account is recorded in the ownership registry. +- On every connection, supplementary groups are set to exactly the resolved list with `usermod -G -- ` (from the `ziti-ssh-host.v1` config entry, or `ZITI_SSH_GROUPS`). Groups must already exist on the host. **If this fails — for example because a group does not exist — the connection is rejected.** +- If a sudoers rule is resolved (config entry or `ZITI_SUDOERS_RULE`), it is written to `/etc/sudoers.d/ziti-ssh-host-` (validated with `visudo -c` before installation); otherwise any existing file is removed. If the rule cannot be installed, the existing file is removed and the connection is rejected; if an existing file cannot be removed, the connection is rejected. +- Every managed account is a member of the `ziti-ssh-managed` group (in addition to its configured groups, and also after its privileges are dropped). sshd ignores `authorized_keys` and any `AuthorizedKeysCommand` for this group, so users can only log in with a CA certificate. - Concurrent sessions from the same identity are reference-counted — `useradd` is only called once. -- When the last session from an identity closes, the cleanup sequence runs: `loginctl terminate-user ` drains the systemd session, the process list is polled until the user's processes exit (up to 5 seconds), and then `userdel -r ` removes the account and home directory. The sudoers file is removed unconditionally at this point (group membership is implicit in account deletion). -- By default the Linux account is kept after disconnect. Set `ZITI_USER_CLEANUP=true` to delete the account when the last session closes. The sudoers file is removed on disconnect regardless of this setting. -- Active managed usernames are persisted to `/var/lib/ziti-ssh-host/managed-users`. On startup, `CleanupOrphans` reads this file and deletes any listed users (they had sessions open when the process was last killed), preventing accumulation of stale accounts after crashes. +- When the last session from an identity closes, the sudoers file is removed and the account's supplementary groups are cleared. With `ZITI_USER_CLEANUP=true`, the cleanup sequence then runs: `loginctl terminate-user` drains the systemd session, the user's processes (matched by UID) are polled until they exit, escalating to SIGTERM and then SIGKILL, and `userdel -r` removes the account and home directory and its ownership record. Accounts not in the registry with a matching UID are never touched. +- By default the Linux account is kept after disconnect, together with any background processes the user started. Set `ZITI_TERMINATE_ON_DISCONNECT=true` to end those processes and remove the account's crontab and `at` jobs when the last session closes (the account and home directory are kept; the account is expired until its identity's next authorized connection), or `ZITI_USER_CLEANUP=true` to delete the account when the last session closes. +- Usernames with active sessions are persisted to `/var/lib/ziti-ssh-host/managed-users`. On startup, `CleanupOrphans` reads this file: with `ZITI_USER_CLEANUP=true` it deletes each listed account that is still registered (they had sessions open when the process was last killed); otherwise it removes their leftover sudoers files, clears their supplementary groups, and keeps the accounts. **Connecting in per-identity mode:** ```sh -ziti-ssh dba-alice@web-server-prod +ziti-ssh web-server-prod ``` -The username before `@` is the Ziti identity name (which is also the derived Linux username when it contains only lowercase letters, digits, hyphens, and underscores). +With no `user@`, `ziti-ssh` and `ziti-scp` use the certificate's principal — in per-identity mode the CA issues it for the identity's derived Linux username. An explicit user must be that derived name, not the Ziti identity name: identity `Alice@Corp.com` logs in as `alice_corp_com` (`ziti-ssh alice_corp_com@web-server-prod`); `alice@corp.com@web-server-prod` is refused by sshd because it does not match the certificate. > **Important:** `--mode` must be set consistently on both `ziti-ssh-ca` and `ziti-ssh-host run`. If the CA issues certs with per-identity principals but the host is in shared mode (or vice versa), SSH authentication will fail. @@ -63,7 +83,7 @@ For each connecting identity, `ziti-ssh-host` resolves permissions as follows: 1. **Exact match** — if the config has an entry whose key is the exact Ziti identity name, that entry is used. Global fallbacks are ignored. -2. **Most-specific glob match** — if no exact key exists, all glob patterns in the config (keys containing `*` or `?`) are tested via `path.Match`. The pattern with the longest literal prefix before the first wildcard wins. Global fallbacks are ignored for the matched identity. +2. **Most-specific glob match** — if no exact key exists, all glob patterns in the config (keys containing `*` or `?`) are tested: `*` matches any run of characters (including none, and including `/`), `?` matches exactly one character, and every other character — including `[`, `]` and `\` — matches itself. The pattern with the longest literal prefix before the first wildcard wins, then the one with the most literal characters; any remaining tie goes to the pattern that sorts first. Global fallbacks are ignored for the matched identity. 3. **`"*"` catch-all** — if neither an exact key nor a more-specific glob matches, a key of `"*"` in the config is used. This is the preferred way to define a default permission set, because the config propagates live to all running `ziti-ssh-host` instances without requiring an env file edit or service restart. @@ -75,7 +95,32 @@ An entry that omits a field means that field gets nothing — globals are not me #### Live config reload -When a `ziti-ssh-host.v1` config is updated in the Ziti controller, the change propagates to all running `ziti-ssh-host` instances bound to that service within seconds via the service-changed event. Already-open sessions are not affected — the updated permissions apply only to connections established after the reload. No restart of `ziti-ssh-host` is required. +When a `ziti-ssh-host.v1` config is updated in the Ziti controller, the change reaches all running `ziti-ssh-host` instances bound to that service at their next service refresh — within 30 seconds by default (`ZITI_SERVICE_REFRESH`) — via the service-changed event. Until then a host keeps applying the previous config, so removing a grant (for example `sudo`) takes effect for new connections only after that interval. Already-open sessions are not affected — the updated permissions apply only to connections established after the reload. No restart of `ziti-ssh-host` is required. + +### Host grant policy + +A `ziti-ssh-host.v1` config is written on the Ziti controller, by whoever can edit configs there. Each host's owner decides, **per service**, what such a config is allowed to grant on that host. Without an opt-in, a config cannot grant root. + +| Setting (`/etc/ziti-ssh-host/env`) | Default | Effect | +|---|---|---| +| `ZITI_ALLOW_SUDOERS` | none | Services (comma-separated, or `*`) whose config may set `sudoers_rule`. | +| `ZITI_ALLOW_GROUPS` | none | Privileged groups a service's config may grant: `:`, or `*:` for every service. Privileged groups are `root`, `sudo`, `admin`, `wheel`, `docker`, `lxd`, `disk`, `shadow`, `libvirt`; any other group may be granted by default. | +| `ZITI_RESTRICT_GROUPS` | `false` | `true`: a config may grant only groups listed in `ZITI_ALLOW_GROUPS` — use this if custom groups on the host carry sudo rights the built-in list cannot know about. | + +A config entry that asks for more than the policy allows **rejects the connection** for that identity on that service (log: `rejecting connection: permissions refused by host grant policy`). Violations are also logged when the config is loaded or reloaded, and `ziti-ssh-host inspect` prints the policy and lists refused entries. The host's own fallbacks (`ZITI_SSH_GROUPS`, `ZITI_SUDOERS_RULE`) are set by the host owner and are never refused. + +**Granting root deliberately** — the role-tier example below, where only the ops service may grant root: + +```sh +# /etc/ziti-ssh-host/env on the DB server +ZITI_SSH_SERVICE=ssh-ops,ssh-db +ZITI_ALLOW_SUDOERS=ssh-ops +ZITI_ALLOW_GROUPS=ssh-ops:sudo,ssh-ops:docker +``` + +The `ssh-ops` config can now give `ops-alice` the `sudo` group or a `sudoers_rule`; nothing in the `ssh-db` config can, even on the same host. + +**Upgrading:** entries that already grant `sudoers_rule` or a privileged group are refused until the host opts in. Run `ziti-ssh-host inspect --service ` before upgrading to list them. ### Multi-service binding @@ -89,7 +134,7 @@ ziti-ssh-host run --ssh-service ssh-ops --ssh-service ssh-db Ops identities are granted dial access to `ssh-ops` in Ziti service policy; DBA identities are granted dial access to `ssh-db`. An identity granted access to both gets whichever permission set corresponds to the service it dialled. -> **Note:** If the same Ziti identity connects through two different services to the same host at the same time, the Linux user is created once on the first connection and the permissions from that first connection are used for the lifetime of the account. The second service's config is not applied retroactively. This is a known limitation and is logged at info level. +> **Note:** A Linux account has one set of groups and one sudoers file shared by all its sessions. So while an identity has sessions open through one service, a connection through a **different** service that resolves to **different** permissions is **rejected** (`rejecting connection: account has open sessions through another service with different permissions`); close the open sessions first. A second service with the same permissions is allowed, and a new connection through the same service always applies the current config. ### Deployment patterns @@ -106,14 +151,111 @@ Each host has its own service (e.g., `ssh-web-01`, `ssh-web-02`) with a fully in ### Constraints -- **Groups must exist on the host.** `ziti-ssh-host` does not create Linux groups. If a config entry references a group that does not exist, `usermod -aG` will fail. The failure is logged and the session proceeds with the user account created but without the requested group membership. -- **First-connection-wins for concurrent cross-service sessions.** If the same identity connects through two services simultaneously, the Linux account is created once with the permissions from the first connection. The second service's config is not applied retroactively. +- **Groups must exist on the host.** `ziti-ssh-host` does not create Linux groups. If a config entry references a group that does not exist, `usermod -G` fails and **the connection is rejected** (`rejecting connection: could not apply permissions`). The identity cannot log in to that host until the config is fixed or the group is created. Check with `ziti-ssh-host inspect` after every config change. +- **No concurrent sessions with different permissions through different services.** A Linux account has one set of groups and one sudoers file shared by all its sessions. So while an identity has sessions open through one service, a connection through a **different** service that resolves to **different** permissions is **rejected** (`rejecting connection: account has open sessions through another service with different permissions`); close the open sessions first. A second service with the same permissions is allowed, and a new connection through the same service always applies the current config. - **Any matched config entry suppresses global fallbacks entirely.** An identity matched by an exact key, a glob pattern, or the `"*"` catch-all receives only what that entry specifies — globals are not merged in. - **No config attached is not an error.** `ziti-ssh-host` logs a debug message and uses global fallbacks. +- **A config that cannot be loaded fails closed.** If a service's `ziti-ssh-host.v1` config cannot be fetched or parsed (for example an invalid `sudoers_rule` or a username collision anywhere in it), per-identity connections on that service are **rejected** (`rejecting connection: permissions config for this service could not be loaded`) until a valid config loads. A failed live reload also discards the previously loaded config rather than keeping it. Fix the config and the next service-changed event reloads it. - **`shared` mode is unaffected.** The `ziti-ssh-host.v1` config is consulted only in `per-identity` mode. --- +## Managing account ownership + +In `per-identity` mode, `ziti-ssh-host` manages only accounts recorded in its ownership registry, `/var/lib/ziti-ssh-host/owned-users.json`. Two admin subcommands read and extend it; both must run as root. + +### `ziti-ssh-host users list` + +Lists every registered account with its Ziti identity, UID, creation time, source (`created` by `ziti-ssh-host` or `claimed` by an administrator), and current status. A `UID MISMATCH` status means the account was deleted and recreated outside `ziti-ssh-host`; it will not be managed until the situation is resolved by an administrator. + +### `ziti-ssh-host users claim --username --identity ` + +Registers an existing account as owned by a Ziti identity. This is the **upgrade path** for accounts created by releases before the registry existed: those accounts are not in the registry, so connections from their identities are rejected with + +``` +refusing to manage pre-existing account "" (identity ""): it was not created by ziti-ssh-host; if it should be, run "ziti-ssh-host users claim" +``` + +until claimed. The command refuses unless: + +- `--username` equals the username derived from `--identity` (same rules as `ca.DeriveUsername`); +- the account exists and has a UID of at least 1000; +- the name is not reserved; and +- the account is not already registered to a different identity. + +Example, after upgrading a host whose identity `dba-alice` already has an account: + +```sh +sudo ziti-ssh-host users claim --username dba-alice --identity dba-alice +sudo ziti-ssh-host users list +``` + +Claims take effect on the next connection; no restart is needed. Only claim accounts you know were created for that identity — claiming hands the account, including its home directory and any sudoers rule the identity's config grants, to that identity. + +### Legacy sudoers files + +Earlier releases wrote sudoers rules to `/etc/sudoers.d/`; they are now written to `/etc/sudoers.d/ziti-ssh-host-`. For a **registered** account, the old file is removed at daemon startup and on the account's next connection if — and only if — it contains the single ` ` line that `ziti-ssh-host` wrote. + +For accounts that are **not** registered, a file of that shape is never removed automatically, because administrators often write their own sudoers files the same way. Instead, `ziti-ssh-host run` logs a warning at startup (`legacy-format sudoers file for an account ziti-ssh-host does not manage`) and `ziti-ssh-host users list` lists the files. Review each one: if an earlier `ziti-ssh-host` release wrote it, either delete it or claim the account (`users claim`) so it is migrated. Until then, such a file still grants sudo to that account. + +### Rejection log lines + +| Log message (prefix) | Meaning | +|---|---| +| `rejecting connection: could not apply permissions` (`step` field) | Setting groups or writing/removing the sudoers file failed — usually a group in the config that does not exist on the host, or a sudoers rule `visudo` rejects. Fix the `ziti-ssh-host.v1` entry (or `ZITI_SSH_GROUPS` / `ZITI_SUDOERS_RULE`) or create the group. | +| `refusing to manage pre-existing account` | Account exists but is not registered. Claim it if it belongs to that identity; otherwise rename or remove the Ziti identity. | +| `username "" (derived from "") is already in use by Ziti identity` | Two identities derive the same username. Rename one of the identities. | +| `does not match registered uid` | Account was replaced outside `ziti-ssh-host`. | +| `account has open sessions through another service with different permissions` | The identity is logged in through another service whose config grants different groups/sudoers. Close those sessions, or give both services the same entry for the identity. | +| `connection limit reached; closing new connections` | The service already has `--max-connections` (`ZITI_MAX_CONNECTIONS`, default 128) connections open; further ones are closed immediately. Logged at most every 10 s with a count. | +| `is reserved and will not be managed` / `must not start with '-'` | The identity's derived username is not allowed. Rename the identity. | +| `rejected connection: invalid per-identity principal` (`ziti-ssh-ca`) | The CA refused to sign for a reserved derived principal (`root`, system accounts, `ubuntu`, `admin`, `ziti`) or one starting with `-`. Rename the identity. | + +--- + +## Host identity (terminator names) + +`ziti-ssh connect web-server-prod` asks the Ziti network for the terminator **named** `web-server-prod` on the `ssh` service. In OpenZiti, a terminator name is an address chosen by whoever binds the service (`ziti-ssh-host` uses its own identity name), not a verified identity. The controller only ensures that, at any moment, all terminators with one name belong to the same identity. When the real host is offline, **any identity with Bind on the service** can register that name — OpenZiti does not tell the dialer which identity answered. `ziti-ssh` and `ziti-scp` mitigate this by remembering each address's SSH host key on first use and refusing a changed key (or, for a service dialed directly, asking before trusting an additional pool member's key) — see [Host keys](usage.md#host-keys-trust-on-first-use). That detects impersonation after a first connection, not on it. + +What this means in practice: + +- **Access control is per service, not per host.** Dial on `ssh` reaches every host bound to `ssh`; Bind on `ssh` lets an identity answer for any host name that is not currently taken. Grant Bind only to host identities (`#ssh-hosts`). +- **A compromised or misconfigured host identity can impersonate other hosts while they are offline**, receiving what the user types (including `sudo` passwords) and any forwarded agent. This is why `-A` is refused unless `--forward-agent-unverified` is given, and why the CA does not grant `permit-agent-forwarding` by default. +- **For hosts that need a strong identity guarantee, use one service per host** (or per small group of equally trusted hosts) with a Bind policy naming only that host's identity, and dial the service by name (`ziti-ssh ziggy@ssh-web-server-prod` when `ssh-web-server-prod` is a service). The Ziti policy then enforces who can answer. + +Verifiable host identity at the dialer is being pursued upstream (openziti/ziti#4172, a controller-signed circuit token naming the terminating identity; openziti/sdk-golang#980, SDK verification). `ziti-ssh` will verify the host against it once available. + +--- + +## Caller identity verification + +`ziti-ssh-ca` (all modes) and `ziti-ssh-host` (`per-identity` mode) identify each caller by the **dialer identity name that the caller's edge router attaches to the connection**. The router derives it from the identity it authenticated, so the client cannot influence it. The separate client-supplied caller ID header is ignored for all decisions. If it differs from the router-supplied name, a warning is logged: + +``` +client-supplied caller id does not match router-verified dialer identity; using router-verified identity +``` + +The log line includes `dialer_identity` and `claimed_caller_id` fields. A stock `ziti-ssh` client always sends its own identity name, so a mismatch indicates a modified client and is worth investigating. + +### Requirement + +Every edge router that clients connect through must run **OpenZiti v2.0.0 or later**. Older routers do not attach the dialer identity. + +### Symptom: connections rejected + +If the router does not supply a dialer identity, the connection is closed (fail closed) and the service logs: + +``` +rejected connection: edge router did not supply a dialer identity (OpenZiti v2.0.0+ routers required) +``` + +On `ziti-ssh-ca` the client receives no certificate; on `ziti-ssh-host` in `per-identity` mode no Linux user is created and the connection never reaches sshd. Check, in order: + +1. **Router version.** Run `ziti edge list edge-routers -j` (full JSON output) and confirm that `versionInfo.version` is v2.0.0 or later for the router the client is connected through. (The default table output does not include versions.) +2. **Recently created identity.** The router resolves the dialer identity from its local copy of the controller's data model. Retry after a short wait; if the rejection persists for an established identity, collect the edge router's logs for the time of the connection. + +--- + ## Inspecting per-identity permissions The `ziti-ssh-host inspect` subcommand is a diagnostic tool for operators verifying their `ziti-ssh-host.v1` config before deploying or after a change. @@ -219,11 +361,23 @@ ziti edge update identity alice@corp.com --role-attributes 'ssh-staging-clients' ### What happens on the host (per-identity mode) -When the connection closes, `ziti-ssh-host` sees EOF on the proxied `net.Conn`, decrements the session ref-count for the identity, and runs the normal cleanup sequence when the last session ends: the sudoers file is removed, `loginctl terminate-user` drains the systemd session, and `userdel -r` removes the account and home directory. No special handling is required — revocation flows through the same path as a normal disconnect. +Revoking an identity does not end SSH sessions that are already open; they continue until they disconnect. When the last session for the identity closes, `ziti-ssh-host` sees EOF on the proxied `net.Conn`, decrements the session ref-count, and removes the identity's sudoers file. + +In every mode the account's supplementary groups are cleared at that point. What happens next depends on `ZITI_USER_CLEANUP` and `ZITI_TERMINATE_ON_DISCONNECT`: + +| `ZITI_USER_CLEANUP` | `ZITI_TERMINATE_ON_DISCONNECT` | Account and home | Background processes (`nohup`, `tmux`, systemd user services) | +|---|---|---|---| +| `false` (default) | `false` (default) | Kept | **Kept running** — a revoked identity's processes, crontab and `at` jobs continue. The daemon logs a startup warning in this configuration. | +| `false` | `true` | Kept (expired until the next authorized connection) | Ended: the account is expired (`usermod -e 1`, so neither sshd nor cron accepts it until the identity's next authorized connection re-enables it), its crontab and `at` jobs are removed, lingering is disabled, `loginctl terminate-user`, then SIGTERM and SIGKILL to the account's UID | +| `true` | any | Deleted (`userdel -r`), and the user's files in `/tmp`, `/var/tmp` and `/dev/shm` removed | Ended (same sequence, before deletion) | + +The host cannot distinguish a revocation from an ordinary disconnect — it only sees the last session close — so for revocation to also stop running processes, enable `ZITI_TERMINATE_ON_DISCONNECT=true` or `ZITI_USER_CLEANUP=true`. Users then lose background jobs whenever their last session closes. Otherwise an administrator must end them manually on each host (`loginctl terminate-user `, and `userdel -r ` to remove the account). ### Outstanding SSH certificates -Revoking Ziti access does not invalidate the user's SSH certificate — it may still have up to 8 hours of validity remaining. However, the certificate is useless without a live Ziti connection to reach any SSH host, so this is not a practical concern in normal operation. The certificate cannot be used to connect directly to port 22 because that port is firewalled; it can only be used through the Ziti overlay. +Revoking Ziti access does not invalidate the user's SSH certificate — it may still have up to the CA's certificate TTL of validity remaining (default 5 minutes, `--cert-ttl`). However, the certificate is useless without a live Ziti connection to reach any SSH host. Each certificate carries the `source-address` critical option (default `127.0.0.1/32,::1/128`, `--cert-source-address` on `ziti-ssh-ca`), so sshd accepts it only from loopback — that is, only when the connection arrives through the host's own `ziti-ssh-host` proxy. Even if port 22 is reachable directly (security group, LAN, VPN), sshd rejects the certificate there and logs the source-address mismatch. + +Change `--cert-source-address` only if something other than `ziti-ssh-host` on the same machine delivers connections to sshd; `none` removes the restriction and should be paired with a firewall that keeps port 22 unreachable. If the CA itself needs to be rotated (for example, after a credential compromise), see [CA key rotation](#ca-key-rotation) below. @@ -257,7 +411,7 @@ Once running, `ziti-ssh-host run` continues to track the controller cluster memb **Event-driven updates:** Before authenticating, `ziti-ssh-host run` subscribes to the `EventControllerUrlsUpdated` event. This event fires at startup (during `Authenticate`) and again at each hourly session renewal. When it fires, the daemon: 1. Persists the full controller URL list to the identity JSON file (`ztAPIs` field) via `config.PersistZtAPIs`. This atomic write (write-then-rename) ensures the identity file always reflects the live cluster membership so that a process restart can bootstrap from any cluster member, not just the one originally enrolled against. -2. Fetches the current intermediate CA public keys from the updated controller set and compares them (order-independent) against the contents of `/etc/ssh/ziti_ca.pub`. If the set has changed, the file is rewritten and sshd is reloaded. Additions are logged with the controller URL; removals are logged by count. +2. Fetches the current intermediate CA public keys from the updated controller set and compares them (order-independent) against the contents of `/etc/ssh/ziti_ca.pub`. If the set has changed, the file is rewritten and sshd is reloaded. Additions are logged with the controller URL; removals are logged by count. **A controller that does not answer never causes a key to be removed:** if any controller in the list cannot be reached, the newly collected keys are merged with the currently trusted ones, so a brief outage does not break logins for certificates its CA signed. A key is removed only when every controller in the cluster list answered and none presented it. An empty controller list is ignored and never persisted. Controller URLs must be `https` with a host and no user info, query or fragment; other entries are logged (`ignoring controller URL`) and dropped before CA keys are fetched or the list is saved, duplicates are removed, and the identity file is only rewritten when the list actually changes. Each controller's CA key is taken from the TLS chain verified against the enrollment root CA, never from extra certificates the server appends. Refreshes from the event and the poller are serialised. **Periodic poll:** Because `EventControllerUrlsUpdated` only fires at `Authenticate` and the hourly session renewal, the daemon also polls the controller's `/controllers` API endpoint every **5 minutes**. This means a newly added cluster node is trusted within 5 minutes of joining, without waiting up to an hour for the next session renewal. @@ -344,10 +498,13 @@ See [provisioning.md](provisioning.md) for the full systemd unit file examples f |---|---|---| | `/etc/ziti-ssh-host/identity.json` | 0600 | Enrolled Ziti identity (private key material) | | `/etc/ssh/ziti_ca.pub` | 0644 | CA public key in authorized_keys format | -| `/etc/ssh/sshd_config.d/ziti-ssh.conf` | 0644 | `TrustedUserCAKeys /etc/ssh/ziti_ca.pub` | +| `/etc/ssh/sshd_config.d/ziti-ssh.conf` | 0644 | `TrustedUserCAKeys /etc/ssh/ziti_ca.pub`, plus a `Match Group ziti-ssh-managed` block setting `AuthorizedKeysFile none` and `AuthorizedKeysCommand none`. Rewritten by `run` at startup if it differs. | ### `run` (per-identity mode only) | Path | Mode | Contents | |---|---|---| -| `/var/lib/ziti-ssh-host/managed-users` | 0644 | One derived username per line — the set of Linux users currently managed by the daemon. Used for orphan cleanup on restart. | +| `/var/lib/ziti-ssh-host/managed-users` | 0600 | One derived username per line — the Linux users with active sessions. Used for orphan cleanup on restart. | +| `/var/lib/ziti-ssh-host/owned-users.json` | 0600 | Ownership registry: username → Ziti identity, UID, creation time, and whether it was claimed. The only authority for which accounts `ziti-ssh-host` may modify or delete. Never cleared on restart. | +| `/var/lib/ziti-ssh-host/owned-users.json.lock` | 0600 | Lock file serialising registry access between the daemon and `ziti-ssh-host users`. | +| `/etc/sudoers.d/ziti-ssh-host-` | 0440 | Sudoers rule for a managed user, when one is resolved. Removed when the last session closes. | diff --git a/docs/provisioning.md b/docs/provisioning.md index d8556a8..f6f5a98 100644 --- a/docs/provisioning.md +++ b/docs/provisioning.md @@ -33,6 +33,8 @@ In simple deployments a single `ssh` service is sufficient. Fleets using per-ide ## Provisioning the Ziti network +**Version requirement:** the controller and every edge router that clients connect through must run **OpenZiti v2.0.0 or later**. `ziti-ssh-ca` and `ziti-ssh-host` (in `per-identity` mode) identify callers only by the dialer identity that the edge router attaches to each connection, a header that v2.0.0+ routers provide. Connections arriving through older routers are rejected. See [Caller identity verification](operations.md#caller-identity-verification). + The commands in this section assume `ziti edge login` has already been run against your controller. All commands use the `ziti` CLI. ### 1. Create the two services @@ -62,7 +64,8 @@ ziti edge create service-policy dial-ssh-ca Dial \ --service-roles "@ssh-ca" \ --identity-roles "#ssh-clients" -# hosts bind ssh (one terminator per host, addressed by identity name) +# hosts bind ssh (one terminator per host, addressed by identity name; +# grant Bind only to host identities — see the Access scope note below) ziti edge create service-policy bind-ssh Bind \ --service-roles "@ssh" \ --identity-roles "#ssh-hosts" @@ -121,6 +124,8 @@ Copy the JWT to the user's machine. Enrollment is covered in [Setting up a clien The identity name chosen for each host (`web-server-prod` above) is the address users pass to `ziti-ssh` — choose it carefully, as it is also the terminator address on the `ssh` service. +> **Access scope:** Dial on the `ssh` service reaches every host bound to it, and the terminator name is an address, not a verified identity — any identity with Bind on `ssh` can answer for a host name that is not currently in use. Grant Bind only to host identities. For hosts that need per-host access control or a strong host identity, give each its own service with a Bind policy naming only that host. See [Host identity (terminator names)](operations.md#host-identity-terminator-names). + --- ## Setting up `ziti-ssh-ca` @@ -139,7 +144,20 @@ Or install from a locally built package: dpkg -i ziti-ssh-ca_-1_.deb ``` -The postinstall script creates `/etc/ziti-ssh-ca/env` (mode 0640) with all variables commented out, and runs `systemctl daemon-reload`. +The postinstall script creates `/etc/ziti-ssh-ca/env` (mode 0640) with all variables commented out, sets the service user (below), and runs `systemctl daemon-reload`. + +**Service user.** `ziti-ssh-ca` must run as the same OS user as the Ziti controller, because it reads the controller's intermediate CA key (mode 0600, owned by that user). That user varies: the `openziti-controller` package (v2.0+) runs the controller as `ziti-controller`; other deployments use e.g. `ziti`. The postinstall script detects it — from `User=` in `ziti-controller.service`, otherwise from the owner of a running `ziti controller run` process — and writes `/etc/systemd/system/ziti-ssh-ca.service.d/10-controller-user.conf` with that `User=`/`Group=`, and makes that user the owner of `/etc/ziti-ssh-ca` (mode 0750) so the service can save controller URL updates to its identity file. An existing administrator override that sets `User=` is never changed, and the managed drop-in is left alone once edited by hand (delete its first line to take ownership). + +If no controller is detected (for example the package is installed before the controller), the unit keeps its default `User=ziti` and the postinstall prints instructions. Check and fix with: + +```sh +systemctl show -p User,Group ziti-ssh-ca # what the CA will run as +systemctl show -p User ziti-controller # what the controller runs as +sudo systemctl edit ziti-ssh-ca # [Service] User= Group= +sudo chown : /etc/ziti-ssh-ca /etc/ziti-ssh-ca/identity.json +``` + +Re-running the package's postinstall (reinstalling the package) after the controller is installed also performs the detection. ### 2. Locate the Ziti controller intermediate CA private key @@ -153,7 +171,7 @@ Root CA (offline) `ziti-ssh-ca` uses the **controller's intermediate CA private key** — the key that signs Ziti identity certificates. Do not use the root CA key; the root CA private key is kept offline and never used at runtime. -In production, `ziti-ssh-ca` runs on the same machine as the Ziti controller, as the same OS user (typically `ziti`). This gives it direct filesystem access to the controller's PKI without any credential distribution. +In production, `ziti-ssh-ca` runs on the same machine as the Ziti controller, as the same OS user (`ziti-controller` with the `openziti-controller` v2 package; `ziti` in some other deployments — see **Service user** above). This gives it direct filesystem access to the controller's PKI without any credential distribution. The intermediate CA private key is typically found at a path like: @@ -251,13 +269,15 @@ Repeat these steps on every machine you want to make reachable over Ziti. > **Skip this step if using `per-identity` mode.** In `per-identity` mode, `ziti-ssh-host` creates and removes Linux accounts automatically on each connection. No manual account setup is needed. -In `shared` mode, all SSH sessions authenticate as a single Linux user. Create it if it does not already exist: +In `shared` mode, all SSH sessions authenticate as a single Linux user. Create it if it does not already exist, and add it to the `ziti-ssh-managed` group so it can only log in with a CA certificate (a key someone adds to its authorized_keys would otherwise keep working after their certificate expires or their identity is revoked): ```sh -useradd --create-home --shell /bin/bash ziggy +groupadd -f --system ziti-ssh-managed # also created by the ziti-ssh-host package +useradd --create-home --shell /bin/bash -G ziti-ssh-managed ziggy +# existing account: usermod -aG ziti-ssh-managed ziggy ``` -Use any existing account — just set `--principal` on the CA to match. +Use any existing account — just set `--principal` on the CA to match, and add it to `ziti-ssh-managed`. `ziti-ssh-host run` logs a warning at startup in shared mode if no account is in the group. ### 2. Install the package @@ -311,6 +331,9 @@ ZITI_SSH_MODE=shared # ZITI_SSH_GROUPS=adm,systemd-journal # per-identity mode only; global fallback groups # ZITI_SUDOERS_RULE=ALL=(ALL) NOPASSWD:ALL # per-identity mode only; global fallback sudoers # ZITI_USER_CLEANUP=true # per-identity mode only; set to true to delete accounts on disconnect +# ZITI_TERMINATE_ON_DISCONNECT=true # per-identity mode only; end a kept account's processes on disconnect +# ZITI_ALLOW_SUDOERS=ssh-ops # per-identity mode only; services whose config may set sudoers_rule +# ZITI_ALLOW_GROUPS=ssh-ops:sudo # per-identity mode only; privileged groups a service's config may grant ``` `ZITI_SSH_MODE` must match the value set on `ziti-ssh-ca`. See [Modes](operations.md#modes) for a full explanation. @@ -373,8 +396,8 @@ Register the `ziti-ssh-host.v1` config type in the Ziti controller. This step is ```sh ziti-ssh-ca config apply \ --controller ctrl.example.com \ - --username admin \ - --password + --username admin +# prompts for the password; for scripts use --password-file or ZITI_CTRL_PASSWORD ``` This creates the config type if it does not exist, or updates it to the current schema if it does. To preview the schema that will be registered without connecting to the controller: @@ -383,7 +406,9 @@ This creates the config type if it does not exist, or updates it to the current ziti-ssh-ca config print ``` -> **TLS note:** If your controller uses a self-signed certificate, add `--insecure` to skip verification, or `--controller-ca /path/to/ca.pem` to trust a specific CA. All flags can also be set via environment variables (`ZITI_CTRL_ADDRESS`, `ZITI_CTRL_USERNAME`, `ZITI_CTRL_PASSWORD`, `ZITI_CTRL_INSECURE`, `ZITI_CTRL_CA`) — useful for scripted provisioning. +> **Controller TLS trust:** like `ziti edge login`, the first connection to a controller whose certificate the system does not trust downloads the controller's own CA bundle (`/.well-known/est/cacerts`), checks that the controller's certificate is issued by it, prints each CA's subject and SHA-256 fingerprint, and asks `Trust this controller certificate authority? [y/N]` (`--yes` accepts without asking — for scripts). The bundle is saved under `$XDG_CONFIG_HOME/ziti-ssh/controllers/` and used from then on. If the controller later presents a different CA, the command refuses with a warning and only replaces the saved bundle after interactive confirmation — `--yes` never does. Alternatively pass `--controller-ca /path/to/ca.pem`. `--insecure` (no verification; sends the admin password to whoever answers) remains as a last resort and prints a warning. +> +> **Password:** prompted for (hidden) when run in a terminal; otherwise use `--password-file ` (`-` = stdin) / `ZITI_CTRL_PASSWORD_FILE`, or `ZITI_CTRL_PASSWORD`. `--password` still works but warns, because it is visible in the process list and shell history. Other settings have environment variables too (`ZITI_CTRL_ADDRESS`, `ZITI_CTRL_USERNAME`, `ZITI_CTRL_CA`, `ZITI_CTRL_INSECURE`). ### 2. Create a config for a service @@ -418,13 +443,15 @@ The `ziti-ssh-host` identity must have access to the `ziti-ssh-host.v1` config t ### 4. Update a config -Edit the config object in the controller to add, change, or remove identity entries. Changes propagate to all running `ziti-ssh-host` instances bound to that service within seconds — no restart required. +Edit the config object in the controller to add, change, or remove identity entries. Changes reach all running `ziti-ssh-host` instances bound to that service within their service refresh interval — 30 seconds by default, `ZITI_SERVICE_REFRESH` — with no restart required. ```sh ziti edge update config ssh-permissions \ '{"permissions":{"*":{"groups":["developers"]},"ops-*":{"groups":["developers","docker"]},"ops-alice":{"groups":["sudo","developers"]},"ops-automation":{"sudoers_rule":"ALL=(ALL) NOPASSWD: ALL"}}}' ``` +> **Host opt-in required:** the `docker` group and `sudoers_rule` entries in this example are only applied on hosts that allow them for this service — e.g. `ZITI_ALLOW_SUDOERS=ssh` and `ZITI_ALLOW_GROUPS=ssh:docker` in `/etc/ziti-ssh-host/env`. Otherwise those identities are refused. See [Host grant policy](operations.md#host-grant-policy). + Run `ziti-ssh-host inspect --service ssh` on the host to confirm what the running daemon sees after the update. See [Inspecting per-identity permissions](operations.md#inspecting-per-identity-permissions) in the operations guide for details. --- @@ -484,3 +511,18 @@ go build -o /usr/local/bin/ziti-scp ./cmd/ziti-scp ``` + +--- + +## Uninstalling + +Packages install binaries to `/usr/bin` (earlier releases used `/usr/local/bin`; upgrading moves them automatically). + +| Action | `ziti-ssh-host` | `ziti-ssh-ca` | `ziti-ssh`, `ziti-scp` | +|---|---|---|---| +| `apt remove` / `rpm -e` | Service stopped and disabled. Configuration, identity, sshd trust and Linux accounts are kept. | Service stopped and disabled. Configuration and identity are kept. | Binary removed. | +| `apt purge` (deb only) | Additionally removes `/etc/ssh/sshd_config.d/ziti-ssh.conf` and `/etc/ssh/ziti_ca.pub` and reloads sshd, so the host **stops trusting the Ziti CA**. `/etc/ziti-ssh-host/` (identity, env), the account ownership registry and Linux accounts are kept. | Additionally removes the managed systemd drop-in `ziti-ssh-ca.service.d/10-controller-user.conf` (unless edited by hand). `/etc/ziti-ssh-ca/` is kept. | — | + +**rpm has no purge.** After `rpm -e ziti-ssh-host`, delete `/etc/ssh/sshd_config.d/ziti-ssh.conf` and `/etc/ssh/ziti_ca.pub` and reload sshd (`systemctl reload sshd`) if the host should no longer accept Ziti certificates. + +Delete Ziti identities (`/etc/ziti-ssh-host/identity.json`, `/etc/ziti-ssh-ca/identity.json`) and per-identity Linux accounts yourself if they are no longer needed; the packages never remove them. diff --git a/docs/usage.md b/docs/usage.md index cedbc75..ebb91e3 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -54,9 +54,13 @@ ziti-ssh connect ziggy@web-server-prod `web-server-prod` is the Ziti identity name of the target host. `ziti-ssh` resolves this as a Ziti service terminator address on the `ssh` service — no DNS, no IP address required. -If a certificate is missing or will expire within 5 minutes, `ziti-ssh connect` automatically obtains a fresh one from the CA before opening the session. On first use it auto-detects your SSH key in `~/.ssh/` (tries `id_ed25519`, `id_ecdsa`, `id_rsa` in that order). If no key exists it offers to run `ssh-keygen -t ed25519` for you. +Without a `user@`, the SSH user is the principal of your certificate when it has exactly one — in per-identity mode that is your derived Linux username, so `ziti-ssh web-server-prod` is enough — and otherwise your local user name. The target is split at the **last** `@`, as with OpenSSH. In per-identity mode an explicit user must be the derived Linux username (identity `alice@corp.com` → `alice_corp_com`), not the identity name. If the target name is also a Ziti service name, that service is dialed directly (see the host key table below); `--service ` always treats the target as a terminator address on ``. -If the SSH private key is passphrase-protected, `ziti-ssh connect` falls back to the SSH agent (`SSH_AUTH_SOCK`). It locates the matching key in the agent and, if a certificate is present on disk, wraps it as an `ssh.CertSigner` so the certificate is offered during authentication. The passphrase is never exposed to this process. If the key is passphrase-protected and `SSH_AUTH_SOCK` is not set (or the key has not been added with `ssh-add`), `ziti-ssh connect` exits with an actionable error. +If a certificate is missing or less than 20% of its lifetime remains (between 30 s and 5 min — 1 minute for the default 5-minute certificate), `ziti-ssh connect` automatically obtains a fresh one from the CA before opening the session. On first use it auto-detects your SSH key in `~/.ssh/` (tries `id_ed25519`, `id_ecdsa`, `id_rsa` in that order). If no key exists it offers to run `ssh-keygen -t ed25519` for you; `ssh-keygen` asks for a passphrase (recommended; press Enter for none). + +If the SSH private key is passphrase-protected, `ziti-ssh connect` falls back to the SSH agent (`SSH_AUTH_SOCK`). It locates the matching key in the agent and, if a certificate is present on disk, wraps it as an `ssh.CertSigner` so the certificate is offered during authentication. With the agent the passphrase is never exposed to this process. If no agent holds the key (`SSH_AUTH_SOCK` unset, or the key not added with `ssh-add`), `ziti-ssh connect` and `ziti-scp` ask for the passphrase on the terminal (`Enter passphrase for key '…':`, not echoed); without a terminal they exit with an error. + +`ziti-ssh` and `ziti-scp` refuse to use `config.yaml` or the Ziti `known_hosts` file if it is writable by others, writable by a group other than your own private group (on Debian/Ubuntu each user has one, and files are created group-writable by default — that is accepted), or owned by another user (as OpenSSH does for its own config): another user could otherwise point you at a different identity, key or host. Fix with `chmod go-w `. ### Non-interactive command execution @@ -83,10 +87,34 @@ The remote process exit code is propagated: if the remote command exits non-zero --- +### Host keys (trust on first use) + +OpenZiti does not tell `ziti-ssh` which identity answered on a host's address, so `ziti-ssh` and `ziti-scp` remember the SSH host key(s) they have seen for each Ziti address in `$XDG_CONFIG_HOME/ziti-ssh/known_hosts` (default under `~/.config/ziti-ssh/`, mode 0600) and check them on every connection: + +| You connect to | First connection | Same key later | Different key later | +|---|---|---|---| +| A host by name (`ziggy@web-server-prod`; address `web-server-prod@ssh`) | Key saved; `Permanently added host key …` printed | Connects | **Refused** with a warning showing both fingerprints | +| A service directly (`ziggy@ssh-db-pool`, when `ssh-db-pool` is a service; address `ssh-db-pool`) — any host bound to it may answer | Key saved | Connects | Warning, then **asked** `Trust this additional key for ssh-db-pool? [y/N]`. Yes adds it, so each member of a pool is accepted once. Without a terminal (scripts, pipes) it is refused — connect interactively once. | + +When a target is a service name, `ziti-ssh` prints `Dialing service "…" directly: any host bound to it may answer.` + +After a host was legitimately rebuilt (new host key): + +```sh +ziti-ssh known-hosts list # address, key type, SHA256 fingerprint +ziti-ssh known-hosts remove web-server-prod@ssh # then reconnect to save the new key +``` + +This catches a host being impersonated **after** you have connected to it once; it cannot verify the very first connection. `ziti-ssh proxy` (OpenSSH `ProxyCommand`) is not affected: OpenSSH applies its own known_hosts checks, keyed by the `Host` name. + ## Port forwarding `ziti-ssh connect` supports the same `-L`, `-R`, and `-D` forwarding flags as `ssh(1)`. All forwards run over the Ziti overlay — no port 22 exposure required. +Write IPv6 addresses in brackets, as with `ssh`: `-L [::1]:8080:[2001:db8::1]:80`, `-D [::1]:1080`. Ports must be 1–65535. + +Local listeners (`-L`, `-D`) bind to `127.0.0.1` by default. They have no authentication of their own: when you bind them to any other address, `ziti-ssh` prints a warning, because anyone who can reach that address can use your session. + ### Local port forward (`-L`) Listens on a local port and forwards each connection to a remote host:port through the SSH tunnel. @@ -95,7 +123,8 @@ Listens on a local port and forwards each connection to a remote host:port throu # Forward localhost:8080 → db.internal:5432 on the remote network ziti-ssh connect ziggy@web-server-prod -L 8080:db.internal:5432 -# Bind on all interfaces (e.g. for container-to-host forwarding) +# Bind on all interfaces (e.g. for container-to-host forwarding) — prints a warning: +# anyone who can reach this machine on port 8080 can use the tunnel ziti-ssh connect ziggy@web-server-prod -L 0.0.0.0:8080:db.internal:5432 ``` @@ -157,8 +186,13 @@ ziti-ssh connect ziggy@web-server-prod -L 8080:db.internal:5432 The `-A` / `--forward-agent` flag forwards your local SSH agent to the remote session. This lets processes running on the remote host use keys held by your local agent — for example, to make onward SSH hops to other machines without copying private keys to the remote host. +**Agent forwarding is off by default and needs two opt-ins**, because `ziti-ssh` cannot yet verify which host answered on a terminator address (an OpenZiti limitation, see [operations.md](operations.md#host-identity-terminator-names)), and a forwarded agent can be used by the remote host for as long as you are connected: + +1. The CA must grant the `permit-agent-forwarding` extension (`--cert-extensions` / `ZITI_CERT_EXTENSIONS` on `ziti-ssh-ca`; the default grants only `permit-pty,permit-port-forwarding`). +2. You must pass `--forward-agent-unverified` together with `-A`; `-A` alone is refused with an explanation. + ```sh -ziti-ssh connect -A ziggy@web-server-prod +ziti-ssh connect -A --forward-agent-unverified ziggy@web-server-prod ``` Agent forwarding requires `SSH_AUTH_SOCK` to be set in your environment (i.e. a running SSH agent). If it is not set, or the agent cannot be reached, `ziti-ssh` logs a warning and opens the session normally without forwarding — the connection is not aborted. @@ -169,7 +203,7 @@ eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519 # Now connect with agent forwarding -ziti-ssh connect -A ziggy@web-server-prod +ziti-ssh connect -A --forward-agent-unverified ziggy@web-server-prod # On the remote host you can SSH onward using your local agent keys: # ssh another-internal-host @@ -178,11 +212,9 @@ ziti-ssh connect -A ziggy@web-server-prod Agent forwarding can be combined with port forwarding flags: ```sh -ziti-ssh connect -A -L 5432:db.internal:5432 ziggy@web-server-prod +ziti-ssh connect -A --forward-agent-unverified -L 5432:db.internal:5432 ziggy@web-server-prod ``` -The SSH certificates issued by `ziti-ssh-ca` already include the `permit-agent-forwarding` extension, so no CA or sshd configuration changes are needed. - --- ## Using `ziti-ssh` as a ProxyCommand @@ -238,7 +270,7 @@ Host prod-*.internal ### Identity and certificate -`ziti-ssh proxy` uses the same `--identity` flag, `ZITI_IDENTITY` environment variable, and `~/.config/ziti-ssh/config.yaml` as the `connect` subcommand. It auto-refreshes the SSH certificate if it is missing or will expire within 5 minutes — so the `ssh` process that reads `ProxyCommand` output will find a valid cert in `~/.ssh/-cert.pub`. +`ziti-ssh proxy` uses the same `--identity` flag, `ZITI_IDENTITY` environment variable, and `~/.config/ziti-ssh/config.yaml` as the `connect` subcommand. It auto-refreshes the SSH certificate if it is missing or less than 20% of its lifetime remains (between 30 s and 5 min — 1 minute for the default 5-minute certificate) — so the `ssh` process that reads `ProxyCommand` output will find a valid cert in `~/.ssh/-cert.pub`. The user@ part in `ProxyCommand ziti-ssh proxy %h` is accepted for syntax compatibility but is not used by `ziti-ssh proxy` — the connection happens at the TCP level below SSH authentication. @@ -272,18 +304,17 @@ The certificate is written to `~/.ssh/-cert.pub` and its details are printe Public key: ED25519-CERT SHA256:... Signing CA: ED25519 SHA256:... (using ssh-ed25519) Key ID: "ziti:alice" - Serial: 0 + Serial: 7294018234810342811 Valid: from 2026-03-30T09:00:00 to 2026-03-30T17:00:00 Principals: ziggy Critical Options: (none) Extensions: - permit-agent-forwarding permit-port-forwarding permit-pty ``` -The certificate expires after the TTL configured on the CA (default: 8 hours). `ziti-ssh connect` auto-renews when fewer than 5 minutes of validity remain. +The certificate expires after the TTL configured on the CA (default: 5 minutes). `ziti-ssh connect` auto-renews when less than 20% of its lifetime remains (between 30 s and 5 min — 1 minute for the default 5-minute certificate). If the CA refuses a request (for example `CA refused the request: rate limit exceeded`), the existing certificate file is left untouched. --- @@ -291,7 +322,7 @@ The certificate expires after the TTL configured on the CA (default: 8 hours). ` `ziti-scp` copies files to and from remote hosts over the same Ziti overlay, using the SFTP subsystem. It mirrors `scp(1)` behaviour. The same identity, SSH certificate, and `~/.config/ziti-ssh/config.yaml` config file are shared with `ziti-ssh` — no additional enrollment is needed. -Remote specifications use the same `[user@]host:path` format as `scp`. The host name is resolved the same way `ziti-ssh` resolves it: first checked against the Ziti service list for a direct match, then used as a terminator address on `--ssh-service` (default: `ssh`). +Remote specifications use the same `[user@]host:path` format as `scp`. The host name is resolved the same way `ziti-ssh` resolves it: first checked against the Ziti service list for a direct match, then used as a terminator address on `--ssh-service` (default: `ssh`); `--service ` skips the service-name check. As with `scp`, an argument is remote only if it contains `:` with no `/` before it — `/data/a:b`, `./a:b` and `dir/a:b` are local paths. The user part is split at the last `@`; without one, the certificate's principal (or your local user name) is used, as in `ziti-ssh`. ### Upload (local to remote) @@ -321,15 +352,18 @@ ziti-scp -r ziggy@web-server-prod:/remote/dir /local/dir/ | Flag | Short | Default | Description | |---|---|---|---| | `--recursive` | `-r` | false | Recursively copy entire directories | -| `--preserve` | `-p` | false | Preserve file timestamps and permissions | +| `--preserve` | `-p` | false | Preserve file timestamps and permissions (on download, never world-writable) | | `--quiet` | `-q` | false | Suppress progress output | | `--identity` | — | `ZITI_IDENTITY` | Ziti identity file path | | `--key` | — | auto-detect | SSH private key path | | `--ca-service` | — | `ssh-ca` | CA service name | | `--ssh-service` | — | `ssh` | SSH service name | +| `--service` | — | — | Treat the remote host as a terminator address on this service, even if it is also a service name | | `--config` | — | `~/.config/ziti-ssh/config.yaml` | Config file path | -If the certificate is missing or will expire within 5 minutes, `ziti-scp` automatically obtains a fresh certificate from the CA before connecting — the same auto-refresh behaviour as `ziti-ssh connect`. +**Downloads are defensive about what the remote host sends:** a downloaded file takes the remote file's permission bits reduced by your umask (never setuid, setgid or sticky; with `-p`, never world-writable); `ziti-scp` refuses to write through an existing local symlink at the destination; remote entry names containing `/`, `\` or `..` are rejected; recursion stops at 64 directory levels; and control characters in file names are replaced before being printed. + +If the certificate is missing or less than 20% of its lifetime remains (between 30 s and 5 min — 1 minute for the default 5-minute certificate), `ziti-scp` automatically obtains a fresh certificate from the CA before connecting — the same auto-refresh behaviour as `ziti-ssh connect`. ### Enroll a Ziti identity @@ -368,6 +402,8 @@ ziti-ssh mfa verify --identity ~/.config/ziti-ssh/alice.json ziti-ssh mfa remove --identity ~/.config/ziti-ssh/alice.json ``` +Once MFA is enabled, every command that authenticates — `connect`, `sign`, `proxy`, `list` and `ziti-scp` — asks for a code when the controller requires one (`MFA TOTP code:`). The code is read from your terminal (`/dev/tty`) without echo, never from stdin, so piped input and `proxy`'s SSH stream are left alone. Three wrong codes, or no terminal, end authentication. Entering the code counts against `--ziti-timeout` (default 30s). The `mfa` subcommands read codes from stdin (hidden when it is a terminal). + --- ## Config file usage diff --git a/go.mod b/go.mod index a0a6077..f3471c3 100644 --- a/go.mod +++ b/go.mod @@ -1,55 +1,57 @@ module github.com/netfoundry/ziti-ssh -go 1.25.0 +go 1.26.0 + +toolchain go1.26.11 require ( github.com/coreos/go-systemd/v22 v22.7.0 - github.com/go-openapi/runtime v0.32.3 - github.com/go-openapi/strfmt v0.26.3 + github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa + github.com/go-jose/go-jose/v4 v4.1.9 + github.com/go-openapi/runtime v0.33.5 + github.com/go-openapi/strfmt v0.27.4 github.com/gorilla/securecookie v1.1.2 - github.com/openziti/edge-api v0.32.0 - github.com/openziti/sdk-golang v1.9.0 - github.com/pkg/sftp v1.13.10 + github.com/openziti/edge-api v0.36.1 + github.com/openziti/sdk-golang v1.8.4 + github.com/pkg/sftp v1.13.12 github.com/spf13/cobra v1.10.2 - github.com/zitadel/oidc/v3 v3.47.5 - go.yaml.in/yaml/v3 v3.0.4 - golang.org/x/crypto v0.53.0 - golang.org/x/term v0.44.0 - golang.org/x/time v0.12.0 + github.com/zitadel/oidc/v3 v3.52.0 + go.yaml.in/yaml/v3 v3.0.6 + golang.org/x/crypto v0.59.0 + golang.org/x/term v0.48.0 + golang.org/x/time v0.16.0 ) require ( github.com/Jeffail/gabs v1.4.0 // indirect github.com/cenkalti/backoff/v4 v4.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/ebitengine/purego v0.10.1 // indirect + github.com/ebitengine/purego v0.11.3 // indirect github.com/emirpasic/gods v1.18.1 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect - github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa // indirect - github.com/go-jose/go-jose/v4 v4.1.4 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.3.0 // indirect - github.com/go-openapi/analysis v0.25.2 // indirect - github.com/go-openapi/errors v0.22.8 // indirect - github.com/go-openapi/jsonpointer v0.23.1 // indirect - github.com/go-openapi/jsonreference v0.21.6 // indirect - github.com/go-openapi/loads v0.24.0 // indirect - github.com/go-openapi/runtime/server-middleware v0.32.3 // indirect - github.com/go-openapi/spec v0.22.5 // indirect - github.com/go-openapi/swag v0.26.1 // indirect - github.com/go-openapi/swag/cmdutils v0.26.1 // indirect - github.com/go-openapi/swag/conv v0.26.1 // indirect - github.com/go-openapi/swag/fileutils v0.26.1 // indirect - github.com/go-openapi/swag/jsonname v0.26.1 // indirect - github.com/go-openapi/swag/jsonutils v0.26.1 // indirect - github.com/go-openapi/swag/loading v0.26.1 // indirect - github.com/go-openapi/swag/mangling v0.26.1 // indirect - github.com/go-openapi/swag/netutils v0.26.1 // indirect - github.com/go-openapi/swag/stringutils v0.26.1 // indirect - github.com/go-openapi/swag/typeutils v0.26.1 // indirect - github.com/go-openapi/swag/yamlutils v0.26.1 // indirect - github.com/go-openapi/validate v0.26.0 // indirect + github.com/go-openapi/analysis v1.0.1 // indirect + github.com/go-openapi/errors v0.22.9 // indirect + github.com/go-openapi/jsonpointer v1.0.2 // indirect + github.com/go-openapi/jsonreference v1.0.3 // indirect + github.com/go-openapi/loads v0.25.3 // indirect + github.com/go-openapi/runtime/server-middleware v0.33.5 // indirect + github.com/go-openapi/spec v1.0.1 // indirect + github.com/go-openapi/swag v0.29.2 // indirect + github.com/go-openapi/swag/cmdutils v0.29.2 // indirect + github.com/go-openapi/swag/conv v0.29.2 // indirect + github.com/go-openapi/swag/fileutils v0.29.2 // indirect + github.com/go-openapi/swag/jsonutils v0.29.2 // indirect + github.com/go-openapi/swag/loading v0.29.2 // indirect + github.com/go-openapi/swag/mangling v0.29.2 // indirect + github.com/go-openapi/swag/netutils v0.29.2 // indirect + github.com/go-openapi/swag/pools v0.29.2 // indirect + github.com/go-openapi/swag/stringutils v0.29.2 // indirect + github.com/go-openapi/swag/typeutils v0.29.2 // indirect + github.com/go-openapi/swag/yamlutils v0.29.2 // indirect + github.com/go-openapi/validate v1.0.1 // indirect github.com/go-resty/resty/v2 v2.17.2 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/golang-jwt/jwt/v5 v5.3.1 // indirect @@ -59,45 +61,45 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/kataras/go-events v0.0.3 // indirect github.com/kr/fs v0.1.0 // indirect - github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect - github.com/mattn/go-colorable v0.1.15 // indirect - github.com/mattn/go-isatty v0.0.22 // indirect + github.com/lufia/plan9stats v0.0.0-20261101121723-be84dd9509a0 // indirect + github.com/mattn/go-colorable v0.1.16 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect github.com/michaelquigley/pfxlog v0.6.10 // indirect github.com/miekg/pkcs11 v1.1.2 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/muhlemmer/gu v0.3.1 // indirect - github.com/oklog/ulid/v2 v2.1.1 // indirect - github.com/openziti/channel/v5 v5.0.10 // indirect - github.com/openziti/foundation/v2 v2.0.95 // indirect - github.com/openziti/identity v1.0.133 // indirect + github.com/oklog/ulid/v2 v2.1.2 // indirect + github.com/openziti/channel/v4 v4.3.15 // indirect + github.com/openziti/foundation/v2 v2.0.106 // indirect + github.com/openziti/identity v1.0.145 // indirect github.com/openziti/metrics v1.4.5 // indirect - github.com/openziti/secretstream v0.1.51 // indirect - github.com/openziti/transport/v2 v2.0.216 // indirect + github.com/openziti/secretstream v0.1.53 // indirect + github.com/openziti/transport/v2 v2.0.229 // indirect github.com/orcaman/concurrent-map/v2 v2.0.1 // indirect github.com/parallaxsecond/parsec-client-go v0.0.0-20221025095442-f0a77d263cf9 // indirect github.com/pkg/errors v0.9.1 // indirect - github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect + github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect - github.com/shirou/gopsutil/v4 v4.26.5 // indirect - github.com/sirupsen/logrus v1.9.4 // indirect + github.com/shirou/gopsutil/v4 v4.26.10 // indirect + github.com/sirupsen/logrus v1.10.2 // indirect github.com/speps/go-hashids v2.0.0+incompatible // indirect github.com/spf13/pflag v1.0.9 // indirect github.com/tklauser/go-sysconf v0.4.0 // indirect github.com/tklauser/numcpus v0.12.0 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect - github.com/zitadel/logging v0.7.0 // indirect github.com/zitadel/schema v1.3.2 // indirect - go.mozilla.org/pkcs7 v0.9.0 // indirect + go.mozilla.org/pkcs7 v0.10.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/otel v1.44.0 // indirect - go.opentelemetry.io/otel/metric v1.44.0 // indirect - go.opentelemetry.io/otel/trace v1.44.0 // indirect - golang.org/x/net v0.56.0 // indirect - golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sync v0.21.0 // indirect - golang.org/x/sys v0.46.0 // indirect - golang.org/x/text v0.38.0 // indirect - google.golang.org/protobuf v1.36.11 // indirect + go.opentelemetry.io/otel v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/otel/metric v1.47.0 // indirect + go.opentelemetry.io/otel/trace v1.47.0 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/oauth2 v0.38.0 // indirect + golang.org/x/sync v0.25.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/text v0.44.0 // indirect + google.golang.org/protobuf v1.36.12 // indirect nhooyr.io/websocket v1.8.17 // indirect ) diff --git a/go.sum b/go.sum index ce35fa3..8b89438 100644 --- a/go.sum +++ b/go.sum @@ -47,8 +47,8 @@ github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmV github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM= -github.com/bmatcuk/doublestar/v4 v4.10.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs= -github.com/bmatcuk/doublestar/v4 v4.10.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= +github.com/bmatcuk/doublestar/v4 v4.10.4 h1:oTKkRmRuOsKMqFe1AQazd9gGBFNEpOmgKp/xzB97dnA= +github.com/bmatcuk/doublestar/v4 v4.10.4/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= @@ -68,10 +68,9 @@ github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7 github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= -github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= +github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg= +github.com/ebitengine/purego v0.11.3/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -89,71 +88,71 @@ github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxv github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa h1:RDBNVkRviHZtvDvId8XSGPu3rmpmSe+wKRcEWNgsfWU= github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa/go.mod h1:KnogPXtdwXqoenmZCw6S+25EAm2MkxbG0deNDu4cbSA= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= -github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= +github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg= +github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= -github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.9 h1:pKfeQkig1NmgK4hJrZYXLEYURXfoJB61Larw0uIW4gY= +github.com/go-jose/go-jose/v4 v4.1.9/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= -github.com/go-openapi/analysis v0.25.2 h1:I0vy4n3alz+DHTiN1PRhCb7QZxkK6g5YmswZKv2TKuw= -github.com/go-openapi/analysis v0.25.2/go.mod h1:Uhs1t/2XR10EnwONYILGEzw8gcfGIG5Xk5K2AxnhqDo= -github.com/go-openapi/errors v0.22.8 h1:oP7sW7TWc3wFFjrzzj0nI83H2qMBkNjNfSd+XRejk/I= -github.com/go-openapi/errors v0.22.8/go.mod h1:BuUoHcYrU6E7V9gfj1I5wLQqgtIHnup/alXZ8KdgQ0w= -github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= -github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= -github.com/go-openapi/jsonreference v0.21.6 h1:NZ5nGfnaM1n4I43Xjm1e5/M2GjOwQwndQz22uhxwD+Y= -github.com/go-openapi/jsonreference v0.21.6/go.mod h1:xzbgtQ3ZbWxvET3AxdzCJlJt6vkovbf+IfSPJjD0tUY= -github.com/go-openapi/loads v0.24.0 h1:4LLorXRPTzIN9V6ngMUZbAscsBOUBk3Oa8cClu/bFrQ= -github.com/go-openapi/loads v0.24.0/go.mod h1:xQMgX+hw5xRAhGrcDXxeMw78IFqUpIzhleu3HqPhyF4= -github.com/go-openapi/runtime v0.32.3 h1:J7Ycy5DJmhhP1By3NifhRUjnkXTrk21qbeqSULjwX8U= -github.com/go-openapi/runtime v0.32.3/go.mod h1:/WTQi0fa5DiGnnCXQKsTkSm15OzJp8Uz3H2t+67TBr4= -github.com/go-openapi/runtime/server-middleware v0.32.3 h1:Y/6h9ix9NCoMG04XazRwX6eA3alh4+JZ6qXdar5yd24= -github.com/go-openapi/runtime/server-middleware v0.32.3/go.mod h1:fYPep4GdTwg/XqZUjR40uIM/8C12Ba5M+MrGCiwpTHo= -github.com/go-openapi/spec v0.22.5 h1:KhO7RBlKQfonUWX2WzQCoLIXVA6AcNqDGZ3a1Dutdlo= -github.com/go-openapi/spec v0.22.5/go.mod h1:vxpOtMya5TXtENXKE5bKqv5NjocVhyhxHrlZfvKnZ74= -github.com/go-openapi/strfmt v0.26.3 h1:rzmslHarJgBbf2qfGge+X3htclQfmXqBZMm0Too0HhU= -github.com/go-openapi/strfmt v0.26.3/go.mod h1:a5nsUw0oRpQzZeOwx8bi6cKbzFZslpbCKt1LEot+KnQ= -github.com/go-openapi/swag v0.26.1 h1:l5sVEyVpwj+DDYeZyo7wQI/Ebn/mKYIyGB/pFwAfGoQ= -github.com/go-openapi/swag v0.26.1/go.mod h1:yNY38BbIVthxbkDtq1UHBCGasBqjakW3lCR6ANzdBEw= -github.com/go-openapi/swag/cmdutils v0.26.1 h1:f2iE1ijYaJ3nuu5PaEMx3zpEhzhZFgivCJObWEObLIQ= -github.com/go-openapi/swag/cmdutils v0.26.1/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= -github.com/go-openapi/swag/conv v0.26.1 h1:slr5FVkg9Wc3Y5zcwenD8Sd/PQ94b2I/QJI7N7KTBpg= -github.com/go-openapi/swag/conv v0.26.1/go.mod h1:mvQXgPptZk9GTrFgGwWvT4q+dN+zQej9JfmGwnipz1A= -github.com/go-openapi/swag/fileutils v0.26.1 h1:K1XCM2CGhfNsc6YDt6v7Q5+1e59rftYWdcu/isZhvFw= -github.com/go-openapi/swag/fileutils v0.26.1/go.mod h1:mYUgxQAKX4ShS3qvvySx+/9yrlUnDhjiD1CalaQl8lQ= -github.com/go-openapi/swag/jsonname v0.26.1 h1:VReupaV6WxlAsCn0e4DUfgV6bPmINnPpyJDLqSfNPcE= -github.com/go-openapi/swag/jsonname v0.26.1/go.mod h1:OvdW6BoWoj33pTfi7x9vFrgmT+fk7aw0BRwvCE0YOuc= -github.com/go-openapi/swag/jsonutils v0.26.1 h1:2hdBfFkHg+7Wrz2VsCbeyR6hzkRDs7AztnMR2u84yOY= -github.com/go-openapi/swag/jsonutils v0.26.1/go.mod h1:U+RMJH3wa+6BRiphuRtIyI8fW9HPFqFQ4sHk2oRx0UQ= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.1 h1:1CD7NiLLb/TXl3tOnFYU4b+mNfb5rtgHkaA+q7RMYYQ= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.1/go.mod h1:ZWafc8nMdYzTE3uYY6W86f0n46+IF0g4uUyRhJw/kXc= -github.com/go-openapi/swag/loading v0.26.1 h1:E9K4wqXeROlhjFQ13K9zMz6ojFGXIggGe+ad1odrK9w= -github.com/go-openapi/swag/loading v0.26.1/go.mod h1:3qvRIlWzWdq1HvmldwmuJ2ohpcAryN6xVt2OTKd0/7E= -github.com/go-openapi/swag/mangling v0.26.1 h1:gpYI4WuPKFJJVjV5cDLGlDVJhFIxYjQc7yN5eEb4CqM= -github.com/go-openapi/swag/mangling v0.26.1/go.mod h1:POETDH01hqAdASXfw7ISEd9bCOE6xBHOt8NHmGZRmYM= -github.com/go-openapi/swag/netutils v0.26.1 h1:BNctoc39WTAUMxyAs355fExOPzMZtPbZ0ZZ1Am2FR5M= -github.com/go-openapi/swag/netutils v0.26.1/go.mod h1:y02vByhZhQPAVwOX+0KipXFZ/hUbk6G/Enhf5rGaOkQ= -github.com/go-openapi/swag/stringutils v0.26.1 h1:f88uYyTso7TnHrKM/bUBsQ5e2wKf37cpgo6pvbzd9yU= -github.com/go-openapi/swag/stringutils v0.26.1/go.mod h1:Sc6d3bU8fgk5AyZR8/8jEQ+Is/Ald+TD/IIggPN8UJk= -github.com/go-openapi/swag/typeutils v0.26.1 h1:yg42FgMzRR6PVQ3M3qHz1s+Y6/P4HoJ3cBarXa3OVnU= -github.com/go-openapi/swag/typeutils v0.26.1/go.mod h1:VfnV+oUtSP2vCSCn2aJgnr8OevUYemyIzzS1VOzS10o= -github.com/go-openapi/swag/yamlutils v0.26.1 h1:0TSLK+lXs9vfIhAWzBeI/lOzEnIoot6WTCO1aAeWFTk= -github.com/go-openapi/swag/yamlutils v0.26.1/go.mod h1:7W5b7PRX9MxwL7TjeG7H8HkyBGRsIDRObhyMWFgBI2M= -github.com/go-openapi/testify/enable/yaml/v2 v2.5.1 h1:q9NtHwK4qHF7yZziBPvZyv7zWAIk8ok88Gh2mR6Jpc8= -github.com/go-openapi/testify/enable/yaml/v2 v2.5.1/go.mod h1:JW0MXIotCYps/XsgJnG3a8Q7rE5xAiBwoOD5OfaIQBk= -github.com/go-openapi/testify/v2 v2.5.1 h1:TMdhCaw8fUNraVSf3Omoob1dO/AzBfhtFAPW0an6sBo= -github.com/go-openapi/testify/v2 v2.5.1/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= -github.com/go-openapi/validate v0.26.0 h1:dxWzQ3F+vb1SajqUxHjwb5T4mTpSHmdrtv5Bi7+ZNhw= -github.com/go-openapi/validate v0.26.0/go.mod h1:b4o00uq7fJeJA+wWhVFCJpKTctzeFwzZImGGmHsl2JA= +github.com/go-openapi/analysis v1.0.1 h1:JTEyujgl4GyFj8pbMUY2yZx5ak1Ozt/DaqzQjQBnBWM= +github.com/go-openapi/analysis v1.0.1/go.mod h1:f3gYbXmnXSQIZB02DqE4f8JX969PdOEnaY7gDBLeJjI= +github.com/go-openapi/errors v0.22.9 h1:HI9+SyVYiRzyeBQGv0CbWbQa+u2S0nny7G7AhY+UMiM= +github.com/go-openapi/errors v0.22.9/go.mod h1:R73q66sXP2smzAGgFOI4nqtusRK2xN5pYCjsij+KX58= +github.com/go-openapi/jsonpointer v1.0.2 h1:NbW7xT2b+l7x+JefiPGDsZWsrLk1ogrz4AHK1TTzMt8= +github.com/go-openapi/jsonpointer v1.0.2/go.mod h1:N0rI4MbNKD7xAFTiHtB+5Nhrg2j/wwYg7m7Fmb4/jk8= +github.com/go-openapi/jsonreference v1.0.3 h1:5rDbq+JsjCv6/nUDDJt83nLZoADI4w03uvHXer+4aYQ= +github.com/go-openapi/jsonreference v1.0.3/go.mod h1:OJSlMXHysgH272D9z2tiy2MGe5A9vQLHaCPb6KbYdE4= +github.com/go-openapi/loads v0.25.3 h1:V+jKy/thXWdLJUuYC8sZX2dICyAa8M3DokF70jj34P0= +github.com/go-openapi/loads v0.25.3/go.mod h1:LgLyCSOLBL2Qnj0Ps1oo2YH8jZoEKsMeVZCc+ALIxFo= +github.com/go-openapi/runtime v0.33.5 h1:+75EEOU6yv55alsXrkK7BV+vfiQg2ZJb9lAfXx8NW4w= +github.com/go-openapi/runtime v0.33.5/go.mod h1:cvmwmMVxhBn/wzfz/VAeUEbe/E1jSCQ9HoNMwDmd+qs= +github.com/go-openapi/runtime/server-middleware v0.33.5 h1:Kw2mZgKrLrqrq80yP35WPrQMT2oT3zytJRICqprMagY= +github.com/go-openapi/runtime/server-middleware v0.33.5/go.mod h1:f/7HY8zgRWGpXO+aYTCXBtTTuhB+HUjY8L++uqoS5WU= +github.com/go-openapi/spec v1.0.1 h1:lj2vdGpNDcVgwRc6qXdw6qt/KQpCtSa9tnUH6vpDPDk= +github.com/go-openapi/spec v1.0.1/go.mod h1:M//GWQGtDUAjnP37gE6fInLgaczB+FatoipV3H1fYw8= +github.com/go-openapi/strfmt v0.27.4 h1:E1xsvHb8R9vsuYru4TP2PVVTv9AIgSFAUACUZrFQfCI= +github.com/go-openapi/strfmt v0.27.4/go.mod h1:SCOff81PPhU26acBiW96jHaFycEbT2nkQRvojM+V2z0= +github.com/go-openapi/swag v0.29.2 h1:9n8frkcsuQRA0INU31VbxNxt1zBaHxrHYGEf5BUjFi4= +github.com/go-openapi/swag v0.29.2/go.mod h1:RkCiX1gCVXWgLOavDXE3ALJrQ/VO2ziiIzOUs3z10xo= +github.com/go-openapi/swag/cmdutils v0.29.2 h1:cXEzX/nWCODon251f+1HgL75/R4XXML5IZxgLCWMoro= +github.com/go-openapi/swag/cmdutils v0.29.2/go.mod h1:XziaSVzYqkDvpWXzASfWajw2YvJrLscq610O2XiyqJw= +github.com/go-openapi/swag/conv v0.29.2 h1:8c9shoB8l0QRSR6ymq1llHdBWDqpIgJfjTGHx3Vuhm0= +github.com/go-openapi/swag/conv v0.29.2/go.mod h1:AZS0YigTNf8qNtD6WqJz/N4RUNmpr76SyjFGkq4+p6Q= +github.com/go-openapi/swag/fileutils v0.29.2 h1:mdUL+Vw5ah1fO1AvFCoHeIyv7YZsCz2MN3KNqd/lLVI= +github.com/go-openapi/swag/fileutils v0.29.2/go.mod h1:7QKmmodjAebaq61lGVJa8ldLdGeMF4DSgYv8tXOGGo0= +github.com/go-openapi/swag/jsonutils v0.29.2 h1:uZNSD2/rJDYAfvsLYkykTzXuyxM3QpDKV9jhRHrMu6k= +github.com/go-openapi/swag/jsonutils v0.29.2/go.mod h1:ONTdNvj3Y+IXRzfa17E+Rgt2ns/qiSOYjIo2K7v2yDs= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2 h1:w+Fd6EBOMGlC74GYGHqCLGyb3Bpams8TtNrgM/SG4jo= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2/go.mod h1:HC2egPORFzbj/gf05Zrfgz8Mgplx3oW7hgGi7pjZVhM= +github.com/go-openapi/swag/loading v0.29.2 h1:QU1ry24e6r6Shoxe380Nx0X5iKkpRO+hJffsyJ2dVlY= +github.com/go-openapi/swag/loading v0.29.2/go.mod h1:DqilDjuiJKETecsS4TRopWG1acUDsfqN39ZmQhPu6uI= +github.com/go-openapi/swag/mangling v0.29.2 h1:ltdo3K0tTP4P6zWhVVWDU9D37/YYBuMJRdZxiS2Dtog= +github.com/go-openapi/swag/mangling v0.29.2/go.mod h1:RjDi4TnItAenS3cgCXSpIl1kKbjG7il6pnmQVl/8bp8= +github.com/go-openapi/swag/netutils v0.29.2 h1:dBli6jyUa93sDS/XYWShJzf4+nnVfFKfvY9SLUaUzB8= +github.com/go-openapi/swag/netutils v0.29.2/go.mod h1:1pM6Xg/Um8E1eps3umWl8Hme3ByWXOtHsvFC0CULHUE= +github.com/go-openapi/swag/pools v0.29.2 h1:PlGoDRF8WtSyXkedZZkpW3f9wDhFf3u8KtaBcmgmh8c= +github.com/go-openapi/swag/pools v0.29.2/go.mod h1:V3lhxVT4qDYRqc2MRSSbLsTYIYV/2HlHafhyEkmzLIc= +github.com/go-openapi/swag/stringutils v0.29.2 h1:lcnBxwAaysT3bMUVBfn9V/PkfVqkurpqufKU6rTUMGk= +github.com/go-openapi/swag/stringutils v0.29.2/go.mod h1:i9cdh7sGaa0nm3CqIvH5IM5h2QClk1wns2ktKeILvRI= +github.com/go-openapi/swag/typeutils v0.29.2 h1:O7aVvkTs3pXwikgtrPLenigEMdQFgONKRooQA9pgf2I= +github.com/go-openapi/swag/typeutils v0.29.2/go.mod h1:7+GDG+uz9Ke+eVt4rClZg7wklSDp8hT/mKNh/pC26TE= +github.com/go-openapi/swag/yamlutils v0.29.2 h1:IFKFFeDnuIwzfsuWRQU+rI8iL3g4XyAYjV/RlnlxPLM= +github.com/go-openapi/swag/yamlutils v0.29.2/go.mod h1:7MGqtcrK73sxQ4ceiyIf8qiXS/s09JLMdR5esK5euYQ= +github.com/go-openapi/testify/enable/yaml/v2 v2.8.1 h1:BIMg/qqur4MXPPHLE3nftDfHdXrw5GwZEsNEw7zraYA= +github.com/go-openapi/testify/enable/yaml/v2 v2.8.1/go.mod h1:74sM7nseyEwJFZ9yRNI77kCQAM5h8nZ4TmXI86voDHs= +github.com/go-openapi/testify/v2 v2.8.1 h1:zk3S6KaDY1iQW91vsOJc25Ql1xm5bhPrZKdnL930bRQ= +github.com/go-openapi/testify/v2 v2.8.1/go.mod h1:4gUN8jC+RqOE2qjW/vDmfyTvl5BCht4qL7oca0odrak= +github.com/go-openapi/validate v1.0.1 h1:Z337eNvBb5KhZiKtjBKfpk2ZHPI8otENKyp/I60XVos= +github.com/go-openapi/validate v1.0.1/go.mod h1:2ZKOLz7jBYipFCn3IDGwppZwtbUHlQTMuKfSWTO7Nqk= github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk= github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA= github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= @@ -276,24 +275,20 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak= -github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= +github.com/lufia/plan9stats v0.0.0-20261101121723-be84dd9509a0 h1:bGmNmV0W+HWMJyDOXmbY2InjV33LK59X9ClO7AU/8e8= +github.com/lufia/plan9stats v0.0.0-20261101121723-be84dd9509a0/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= -github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= -github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A= +github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4= -github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI= github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= @@ -323,8 +318,8 @@ github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLA github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= -github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s= -github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= +github.com/oklog/ulid/v2 v2.1.2 h1:IEclFb9JNvzYA6MW2SCxbLzcHTVsfqm3PrqGQJH5zec= +github.com/oklog/ulid/v2 v2.1.2/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= github.com/onsi/ginkgo v1.15.0/go.mod h1:hF8qUzuuC8DJGygJH3726JnCZX4MYbRB8yFfISqnKUg= @@ -335,22 +330,22 @@ github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1y github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= github.com/onsi/gomega v1.13.0 h1:7lLHu94wT9Ij0o6EWWclhu0aOh32VxhkwEJvzuWPeak= github.com/onsi/gomega v1.13.0/go.mod h1:lRk9szgn8TxENtWd0Tp4c3wjlRfMTMH27I+3Je41yGY= -github.com/openziti/channel/v5 v5.0.10 h1:5KxHL8FcsdA2xhHQjtZ4nL3h2F0FegPklvr5Oa6I6r8= -github.com/openziti/channel/v5 v5.0.10/go.mod h1:zvmzkCYBnzK3hosc/v9xrri781L2E8uxeGnLXlfDhAM= -github.com/openziti/edge-api v0.32.0 h1:+hnr0kzk5/jUzMPWl0TViyROUahccKnDyxlFCkAJqfM= -github.com/openziti/edge-api v0.32.0/go.mod h1:wFExSB9pO7yEwVVuz4AatZeU++dgcjy9pkzeCFLXeno= -github.com/openziti/foundation/v2 v2.0.95 h1:ZB6AeclGCfuI2l3c3PN7stKLp6Ck+P0wBuokY4pp7qo= -github.com/openziti/foundation/v2 v2.0.95/go.mod h1:yhdRzmEzrHxqG8frg2fMmSpR5+iZI1tL/teeaAoWl7U= -github.com/openziti/identity v1.0.133 h1:rOFsV+sQVpy3FJqtShF7NYQxR+678FDQfFUS3ziGNeo= -github.com/openziti/identity v1.0.133/go.mod h1:mZKgg92/dHxGytk8eRCSg2wmEFUp/ajy4KhoArP+g94= +github.com/openziti/channel/v4 v4.3.15 h1:9FatbmEnfbKZGOwmuKUN5k1L9Jyu3ja8XMWLISzMPsU= +github.com/openziti/channel/v4 v4.3.15/go.mod h1:WZpOeuPliA7mJ3m7Pal8WdYu74eHMzkM/1Z9AMLmUAg= +github.com/openziti/edge-api v0.36.1 h1:f6ncmo7KjzSC0rEY0cxig+BQVI0B8896tfeNF2fMo1w= +github.com/openziti/edge-api v0.36.1/go.mod h1:58bsD0bYzI9IoP75aiwI5hQmaLtHdhB6eA2V/2/H07g= +github.com/openziti/foundation/v2 v2.0.106 h1:ZvPLHFV61H8f1WkvjoxQjAYm9M/MaJnDRgu1MGgdW2I= +github.com/openziti/foundation/v2 v2.0.106/go.mod h1:3EyQT6VRe3q14qTUwBYiTZlunyaGsQD7Em+IuC9B4hc= +github.com/openziti/identity v1.0.145 h1:jDFXcwSUF1L5SZ1CaU0w7PslOIT6ZVAdH2Bll05Huww= +github.com/openziti/identity v1.0.145/go.mod h1:YqaG84NCZO8l3so2vXf2xDBLLlTwe9IFh70oVC6oenA= github.com/openziti/metrics v1.4.5 h1:p51HYSQyqaDafizPWluhYjU/rVfY52snER8/BHpfPrU= github.com/openziti/metrics v1.4.5/go.mod h1:MOLcoTxhPNla6+NWUCMVTnl1PNqTU40qrbKVa/lVVgg= -github.com/openziti/sdk-golang v1.9.0 h1:cIhebAKnqyusUJlBXxPXzppTkEbnmG4MT31LTdExbPE= -github.com/openziti/sdk-golang v1.9.0/go.mod h1:MsLGTLG2K6QSKfuZuAulf/ao7IQ05A4V9Zs3E7RoXHA= -github.com/openziti/secretstream v0.1.51 h1:j/rMfIzBNqZD5a1EKV8J4Z5QeaoSK56s/zxvvB08eSA= -github.com/openziti/secretstream v0.1.51/go.mod h1:YapZv2c/SyZyohn6Q0MJkl8SUuBbs9Q6XWSiboBc1jA= -github.com/openziti/transport/v2 v2.0.216 h1:/2ALqUaeDzOfvZwzGSPNtWqMu8srgA1AERF3Nk94nDQ= -github.com/openziti/transport/v2 v2.0.216/go.mod h1:Kh4dP6FtAUbiJvTmRcMJvLVCBmpQOpvUT1jMUCLDxQg= +github.com/openziti/sdk-golang v1.8.4 h1:/sV/p94JZnVcModx60gnBpzZ9oHxXAEhEB9zXeqzehk= +github.com/openziti/sdk-golang v1.8.4/go.mod h1:iQgTkt7p0MltrGuLqSy6w+cBQq7g3bHA9zzaorW6NJo= +github.com/openziti/secretstream v0.1.53 h1:UHkuk71U24vdzTC0wXq+DTwPOQnFApfRvOA9mat0L4c= +github.com/openziti/secretstream v0.1.53/go.mod h1:gk8JnDEKR/YNwWfHaQXsUSdSn3w7+mmw9O/Cgqox1II= +github.com/openziti/transport/v2 v2.0.229 h1:NYe1NpUgv2zHPsY6/BB3dABNtA+UKpeIXfeMP3bqpfQ= +github.com/openziti/transport/v2 v2.0.229/go.mod h1:S77UkTfd331FlJRtq2sHa9beFhcIpoeBSmsGsj2ni18= github.com/orcaman/concurrent-map/v2 v2.0.1 h1:jOJ5Pg2w1oeB6PeDurIYf6k9PQ+aTITr/6lP/L/zp6c= github.com/orcaman/concurrent-map/v2 v2.0.1/go.mod h1:9Eq3TG2oBe5FirmYWQfYO5iH1q0Jv47PLaNK++uCdOM= github.com/parallaxsecond/parsec-client-go v0.0.0-20221025095442-f0a77d263cf9 h1:mOvehYivJ4Aqu2CPe3D3lv8jhqOI9/1o0THxJHBE0qw= @@ -362,32 +357,29 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= -github.com/pkg/sftp v1.13.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU= -github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pkg/sftp v1.13.12 h1:Myhzy/ZzLPnCtE2F2WtDHsgs8RfgMnH2gfbHuCJhkMU= +github.com/pkg/sftp v1.13.12/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= -github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= +github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 h1:XA01Vk/wv9YikCi1V51yRzIHPMT5of9+cMpZoZvDn/M= +github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg= github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= -github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA= github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/shirou/gopsutil/v4 v4.26.5 h1:RPcBXkpz7kOj9PqGFQOlBPZHsyaPvPVQc098y9RmCNM= -github.com/shirou/gopsutil/v4 v4.26.5/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ= +github.com/shirou/gopsutil/v4 v4.26.10 h1:MJN6euesJx53MVEjscYeyRSRcrdIcy3sz5k9nosjldg= +github.com/shirou/gopsutil/v4 v4.26.10/go.mod h1:XpkIrcUMQhwte/dGxu57KtnMMFsbKelI7PP23zweKBk= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= -github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo= +github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/speps/go-hashids v2.0.0+incompatible h1:kSfxGfESueJKTx0mpER9Y/1XHl+FVQjtCqRyYcviFbw= @@ -409,8 +401,8 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= @@ -424,17 +416,15 @@ github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1 github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0= github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= -github.com/zitadel/logging v0.7.0 h1:eugftwMM95Wgqwftsvj81isL0JK/hoScVqp/7iA2adQ= -github.com/zitadel/logging v0.7.0/go.mod h1:9A6h9feBF/3u0IhA4uffdzSDY7mBaf7RE78H5sFMINQ= -github.com/zitadel/oidc/v3 v3.47.5 h1:cR2z0oqa5XZkwpXQiPCUGqKtndrjHgEXb81y3oXocK4= -github.com/zitadel/oidc/v3 v3.47.5/go.mod h1:XxFh0666HRXycyrKmono+3gY0RACpYJLgy4r/+kliKY= +github.com/zitadel/oidc/v3 v3.52.0 h1:UWIDloHmoi8wFM6oLW94OlxQmf/CYQU2tZxTQhxQWQU= +github.com/zitadel/oidc/v3 v3.52.0/go.mod h1:jLFGXtanUQnh7H6GTrmqbMTooFfkBM+Nt8yUveFbsGs= github.com/zitadel/schema v1.3.2 h1:gfJvt7dOMfTmxzhscZ9KkapKo3Nei3B6cAxjav+lyjI= github.com/zitadel/schema v1.3.2/go.mod h1:IZmdfF9Wu62Zu6tJJTH3UsArevs3Y4smfJIj3L8fzxw= go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs= go.etcd.io/etcd/client/pkg/v3 v3.5.0/go.mod h1:IJHfcCEKxYu1Os13ZdwCwIUTUVGYTSAM3YSwc9/Ac1g= go.etcd.io/etcd/client/v2 v2.305.0/go.mod h1:h9puh54ZTgAKtEbut2oe9P4L/oqKCVB6xsXlzd7alYQ= -go.mozilla.org/pkcs7 v0.9.0 h1:yM4/HS9dYv7ri2biPtxt8ikvB37a980dg69/pKmS+eI= -go.mozilla.org/pkcs7 v0.9.0/go.mod h1:SNgMg+EgDFwmvSmLRTNKC5fegJjB7v23qTQ0XLGUNHk= +go.mozilla.org/pkcs7 v0.10.0 h1:jmljzDzNYFzaP1dFlgmCiQml9e+iEMmv8/NNs4evQbg= +go.mozilla.org/pkcs7 v0.10.0/go.mod h1:SNgMg+EgDFwmvSmLRTNKC5fegJjB7v23qTQ0XLGUNHk= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= @@ -444,19 +434,22 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= -go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= -go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= -go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= -go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= -go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= -go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= -go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= +go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -466,8 +459,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= -golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= -golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -545,8 +538,8 @@ golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLd golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= -golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= -golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -559,8 +552,8 @@ golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210402161424-2e8d93401602/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= -golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI= +golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -573,8 +566,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= -golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= +golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -628,13 +621,13 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= -golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= -golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= +golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -644,13 +637,13 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= -golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= -golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -810,13 +803,11 @@ google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGj google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= -google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= diff --git a/host/accounts.go b/host/accounts.go new file mode 100644 index 0000000..34f9031 --- /dev/null +++ b/host/accounts.go @@ -0,0 +1,507 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import ( + "errors" + "fmt" + "io/fs" + "log/slog" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" + + "github.com/netfoundry/ziti-ssh/ca" +) + +// MinManagedUID is the lowest UID ziti-ssh-host will ever create, modify, or +// delete. Accounts below it (root and system accounts) are never touched. +const MinManagedUID = 1000 + +// ValidateManagedUsername rejects usernames ziti-ssh-host must never manage: +// empty names, names starting with '-' (would be parsed as command options), +// names containing characters outside [a-z0-9_-], and reserved system names. +func ValidateManagedUsername(username string) error { + if username == "" { + return fmt.Errorf("username is empty") + } + if strings.HasPrefix(username, "-") { + return fmt.Errorf("username %q must not start with '-'", username) + } + for _, r := range username { + if !((r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '_' || r == '-') { + return fmt.Errorf("username %q contains invalid character %q", username, r) + } + } + if ca.IsReservedUsername(username) { + return fmt.Errorf("username %q is reserved and will not be managed", username) + } + return nil +} + +// errUserExists is returned by accountOps.CreateUser when useradd reports +// that the account already exists (exit code 9). +var errUserExists = errors.New("user already exists") + +// accountOps is the set of OS operations UserManager performs. The production +// implementation (osAccountOps) shells out to the standard tools; tests +// substitute a fake so ownership logic can be verified without root. +type accountOps interface { + // LookupUID returns the account's UID via NSS (getent), and whether it exists. + LookupUID(username string) (uid int, exists bool, err error) + // CreateUser creates the account with a home directory. Returns + // errUserExists if it already exists. + CreateUser(username string) error + // SetGroups replaces the account's supplementary groups. + SetGroups(username string, groups []string) error + // InstallSudoers writes the validated sudoers file for username. + InstallSudoers(username, rule string) error + // RemoveSudoers removes the sudoers file for username, if present. + RemoveSudoers(username string) error + // RemoveLegacySudoers removes a pre-rename /etc/sudoers.d/ file, + // but only if its content is in the format ziti-ssh-host wrote. + RemoveLegacySudoers(username string) error + // TerminateProcesses ends every process owned by the account (disabling + // lingering first) but keeps the account. uid must be the verified UID. + TerminateProcesses(username string, uid int) error + // ReactivateAccount removes an account expiry set by TerminateProcesses. + ReactivateAccount(username string) error + // DeleteUser terminates the account's processes and removes it with its + // home directory. uid must be the verified UID of the account. + DeleteUser(username string, uid int) error +} + +// osAccountOps is the production accountOps implementation. +type osAccountOps struct{} + +func (osAccountOps) LookupUID(username string) (int, bool, error) { + cmd := exec.Command("getent", "passwd", "--", username) + cmd.Env = childEnv() + out, err := cmd.Output() + if err != nil { + // getent exits 2 when the key is not found. + if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 2 { + return 0, false, nil + } + return 0, false, fmt.Errorf("getent passwd %q: %w", username, err) + } + line := strings.TrimSpace(strings.SplitN(string(out), "\n", 2)[0]) + fields := strings.Split(line, ":") + if len(fields) < 3 || fields[0] != username { + return 0, false, fmt.Errorf("getent passwd %q: unexpected output %q", username, line) + } + uid, err := strconv.Atoi(fields[2]) + if err != nil { + return 0, false, fmt.Errorf("getent passwd %q: invalid uid %q", username, fields[2]) + } + return uid, true, nil +} + +func (osAccountOps) CreateUser(username string) error { + cmd := exec.Command("useradd", "-m", "-s", "/bin/bash", "--", username) + cmd.Env = childEnv() + out, err := cmd.CombinedOutput() + if err != nil { + if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 9 { + return errUserExists + } + return fmt.Errorf("useradd %q: %w (output: %s)", username, err, strings.TrimSpace(string(out))) + } + return nil +} + +func (osAccountOps) SetGroups(username string, groups []string) error { + cmd := exec.Command("usermod", "-G", strings.Join(groups, ","), "--", username) + cmd.Env = childEnv() + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("usermod -G %q: %w (output: %s)", username, err, strings.TrimSpace(string(out))) + } + return nil +} + +func (osAccountOps) InstallSudoers(username, rule string) error { return createSudoers(username, rule) } +func (osAccountOps) RemoveSudoers(username string) error { return removeSudoers(username) } + +func (osAccountOps) RemoveLegacySudoers(username string) error { + return removeLegacySudoersFile(legacySudoersPath(username), username) +} + +// removeLegacySudoersFile removes path only if it contains exactly the single +// " " line that ziti-ssh-host used to write there. +func removeLegacySudoersFile(path, username string) error { + data, err := os.ReadFile(path) + if os.IsNotExist(err) { + return nil + } + if err != nil { + return fmt.Errorf("read legacy sudoers file %q: %w", path, err) + } + // ziti-ssh-host wrote exactly one line: " \n". Anything + // else was written by someone else and is left alone. + content := string(data) + if !strings.HasPrefix(content, username+" ") || strings.Count(content, "\n") > 1 { + slog.Warn("leaving legacy sudoers file in place: content not written by ziti-ssh-host", "path", path) + return nil + } + if err := os.Remove(path); err != nil && !os.IsNotExist(err) { + return fmt.Errorf("remove legacy sudoers file %q: %w", path, err) + } + slog.Info("removed legacy sudoers file", "path", path) + return nil +} + +func (osAccountOps) TerminateProcesses(username string, uid int) error { + return terminateUserProcesses(username, uid) +} + +func (osAccountOps) ReactivateAccount(username string) error { return reactivateAccount(username) } + +func (osAccountOps) DeleteUser(username string, uid int) error { + return deleteUser(username, uid) +} + +// userProcessesGone polls pgrep until no processes owned by uid remain or the +// timeout elapses. Returns true when the user has no remaining processes. +func userProcessesGone(uid int, timeout time.Duration) bool { + const pollInterval = 200 * time.Millisecond + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + pgrep := exec.Command("pgrep", "-u", strconv.Itoa(uid)) + pgrep.Env = childEnv() + err := pgrep.Run() + if err != nil { + // pgrep exits 1 when no processes match — user is clear. + if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 { + return true + } + slog.Warn("pgrep error while waiting for user processes to exit", "uid", uid, "err", err) + return false + } + time.Sleep(pollInterval) + } + return false +} + +// terminateUserProcesses ends everything the account can still run: it +// first expires the account (so neither sshd nor cron accepts it until the +// identity's next authorized connection, see reactivateAccount), removes its +// crontab and at jobs, disables lingering (so systemd user services are not +// restarted), asks loginctl to terminate the user's sessions, waits up to +// 5 s, then escalates to SIGTERM (10 s) and SIGKILL (5 s). Processes are +// matched by the verified UID, never by name. The UID floor is re-checked as +// a last guard. A failure to expire the account is returned; the rest +// continues regardless. +func terminateUserProcesses(username string, uid int) error { + if uid < MinManagedUID { + return fmt.Errorf("refusing to terminate processes of %q: uid %d is below %d", username, uid, MinManagedUID) + } + + var expireErr error + if out, err := runChild("usermod", "-e", "1", "--", username); err != nil { + expireErr = fmt.Errorf("expire account %q: %w (%s)", username, err, out) + slog.Error("could not expire account; cron jobs may still run", "username", username, "err", expireErr) + } + removeScheduledJobs(username) + + linger := exec.Command("loginctl", "disable-linger", "--", username) + linger.Env = childEnv() + if out, err := linger.CombinedOutput(); err != nil { + slog.Info("loginctl disable-linger returned non-zero (ignored)", + "username", username, "err", err, "output", strings.TrimSpace(string(out))) + } + + loginctl := exec.Command("loginctl", "terminate-user", "--", username) + loginctl.Env = childEnv() + if out, err := loginctl.CombinedOutput(); err != nil { + slog.Info("loginctl terminate-user returned non-zero (ignored)", + "username", username, "err", err, "output", strings.TrimSpace(string(out))) + } + + uidStr := strconv.Itoa(uid) + if userProcessesGone(uid, 5*time.Second) { + return nil + } + slog.Info("user processes still running after loginctl; sending SIGTERM", "username", username, "uid", uid) + pkillTerm := exec.Command("pkill", "-TERM", "-u", uidStr) + pkillTerm.Env = childEnv() + if out, err := pkillTerm.CombinedOutput(); err != nil { + slog.Info("pkill -TERM returned non-zero (ignored)", + "username", username, "err", err, "output", strings.TrimSpace(string(out))) + } + if userProcessesGone(uid, 10*time.Second) { + return nil + } + slog.Warn("user processes still running after SIGTERM; sending SIGKILL", "username", username, "uid", uid) + pkillKill := exec.Command("pkill", "-KILL", "-u", uidStr) + pkillKill.Env = childEnv() + if out, err := pkillKill.CombinedOutput(); err != nil { + slog.Info("pkill -KILL returned non-zero (ignored)", + "username", username, "err", err, "output", strings.TrimSpace(string(out))) + } + if !userProcessesGone(uid, 5*time.Second) { + return errors.Join(expireErr, fmt.Errorf("processes of %q (uid %d) still running after SIGKILL", username, uid)) + } + return expireErr +} + +// runChild runs a command with the sanitised child environment and returns +// its trimmed combined output. +func runChild(name string, args ...string) (string, error) { + cmd := exec.Command(name, args...) + cmd.Env = childEnv() + out, err := cmd.CombinedOutput() + return strings.TrimSpace(string(out)), err +} + +// removeScheduledJobs removes the account's crontab and its at jobs, so +// nothing the user scheduled runs after their access ends. Missing tools or +// "no crontab" are not errors. +func removeScheduledJobs(username string) { + if out, err := runChild("crontab", "-u", username, "-r"); err != nil { + slog.Debug("crontab -r (ignored)", "username", username, "err", err, "output", out) + } else { + slog.Info("removed user's crontab", "username", username) + } + out, err := runChild("atq") + if err != nil { + slog.Debug("atq unavailable (ignored)", "err", err, "output", out) + return + } + if ids := atJobsOf(out, username); len(ids) > 0 { + if out, err := runChild("atrm", ids...); err != nil { + slog.Warn("atrm failed", "username", username, "jobs", ids, "err", err, "output", out) + } else { + slog.Info("removed user's at jobs", "username", username, "jobs", ids) + } + } +} + +// atJobsOf returns the job numbers in atq output (as root: "\t +// ") that belong to username. +func atJobsOf(atq, username string) []string { + var ids []string + for _, line := range strings.Split(atq, "\n") { + f := strings.Fields(line) + if len(f) >= 2 && f[len(f)-1] == username { + if _, err := strconv.Atoi(f[0]); err == nil { + ids = append(ids, f[0]) + } + } + } + return ids +} + +// reactivateAccount removes the expiry set by terminateUserProcesses, so the +// account can log in again. Called on every authorized connection of an +// owned account; usermod -e "" is a no-op for an account that never expired. +func reactivateAccount(username string) error { + if out, err := runChild("usermod", "-e", "", "--", username); err != nil { + return fmt.Errorf("re-enable account %q: %w (%s)", username, err, out) + } + return nil +} + +// deleteUser removes the sudoers file, terminates the user's processes (see +// terminateUserProcesses), then removes the user and home directory with +// userdel -r. Callers must have verified ownership and that +// uid >= MinManagedUID; the floor is re-checked as a last guard. +func deleteUser(username string, uid int) error { + if uid < MinManagedUID { + return fmt.Errorf("refusing to delete %q: uid %d is below %d", username, uid, MinManagedUID) + } + if err := removeSudoers(username); err != nil { + slog.Error("failed to remove sudoers file during deleteUser", "username", username, "err", err) + } + if err := terminateUserProcesses(username, uid); err != nil { + slog.Warn("proceeding with userdel", "username", username, "err", err) + } + // userdel -r removes only the home directory and mail spool. Files the + // user left in shared temporary directories would otherwise pass to the + // next account that is given the same UID. + if n := removeOwnedFiles(sharedTempDirs, uid); n > 0 { + slog.Info("removed user's files from shared temporary directories", "username", username, "uid", uid, "count", n) + } + + cmd := exec.Command("userdel", "-r", "--", username) + cmd.Env = childEnv() + out, err := cmd.CombinedOutput() + if err != nil { + if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 8 { + return fmt.Errorf("userdel %q: user still has running processes; account not deleted (exit 8): %s", + username, strings.TrimSpace(string(out))) + } + return fmt.Errorf("userdel -r %q: %w (output: %s)", username, err, out) + } + slog.Info("deleted Linux user", "username", username) + return nil +} + +// legacySudoersDir is where releases before the ownership registry wrote +// sudoers files, named after the bare username. +const legacySudoersDir = "/etc/sudoers.d" + +// findLegacySudoersFiles returns the usernames of files in dir that have the +// exact shape older ziti-ssh-host releases wrote: a regular file named after a +// valid, non-reserved username containing a single " " line. +// Administrators often write files of the same shape, so a match is only a +// candidate, not proof of ownership. +func findLegacySudoersFiles(dir string) ([]string, error) { + entries, err := os.ReadDir(dir) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, fmt.Errorf("read %q: %w", dir, err) + } + var out []string + for _, e := range entries { + name := e.Name() + if !e.Type().IsRegular() || strings.HasPrefix(name, "ziti-ssh-host-") || ValidateManagedUsername(name) != nil { + continue + } + data, err := os.ReadFile(filepath.Join(dir, name)) + if err != nil { + continue + } + content := string(data) + if strings.HasPrefix(content, name+" ") && strings.Count(content, "\n") <= 1 { + out = append(out, name) + } + } + return out, nil +} + +// LegacySudoersCandidates lists usernames with a legacy-format file in +// /etc/sudoers.d (see findLegacySudoersFiles). +func LegacySudoersCandidates() ([]string, error) { + return findLegacySudoersFiles(legacySudoersDir) +} + +// ReconcileLegacySudoers handles sudoers files left by releases before the +// ownership registry. For accounts in the registry with a verified UID the +// legacy file is removed (it is known to be ziti-ssh-host's). For any other +// candidate a warning is logged and the file is left in place: it may belong +// to an administrator, but if it was written by an old ziti-ssh-host it still +// grants sudo to an account that is no longer managed. Run at startup. +func (m *UserManager) ReconcileLegacySudoers() { + m.reconcileLegacySudoersIn(legacySudoersDir) +} + +func (m *UserManager) reconcileLegacySudoersIn(dir string) { + names, err := findLegacySudoersFiles(dir) + if err != nil { + slog.Error("scanning for legacy sudoers files failed", "err", err) + return + } + for _, u := range names { + if _, registered, _ := m.registry.Get(u); registered { + if _, owned := m.verifiedOwnedUID(u); !owned { + continue // verifiedOwnedUID logged why + } + if err := m.ops.RemoveLegacySudoers(u); err != nil { + slog.Error("failed to remove legacy sudoers file", "username", u, "err", err) + } + continue + } + slog.Warn("legacy-format sudoers file for an account ziti-ssh-host does not manage; review it: "+ + "if an earlier ziti-ssh-host release wrote it, remove it or run \"ziti-ssh-host users claim\"", + "path", filepath.Join(dir, u)) + } +} + +// EnsureManagedGroup creates ManagedGroup as a system group if it does not +// exist. +func EnsureManagedGroup() error { + if err := exec.Command("getent", "group", "--", ManagedGroup).Run(); err == nil { + return nil + } + cmd := exec.Command("groupadd", "--system", "--", ManagedGroup) + cmd.Env = childEnv() + if out, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("groupadd %s: %w (output: %s)", ManagedGroup, err, strings.TrimSpace(string(out))) + } + slog.Info("created group", "group", ManagedGroup) + return nil +} + +// ManagedGroupMembers returns the supplementary members of ManagedGroup. +func ManagedGroupMembers() ([]string, error) { + out, err := exec.Command("getent", "group", "--", ManagedGroup).Output() + if err != nil { + return nil, fmt.Errorf("getent group %s: %w", ManagedGroup, err) + } + fields := strings.Split(strings.TrimSpace(string(out)), ":") + if len(fields) < 4 || fields[3] == "" { + return nil, nil + } + return strings.Split(fields[3], ","), nil +} + +// sharedTempDirs are world-writable directories cleaned of a deleted user's +// files before userdel. +var sharedTempDirs = []string{"/tmp", "/var/tmp", "/dev/shm"} + +// removeOwnedFiles deletes, under each root, every entry owned by uid: +// regular files, symlinks themselves (never their targets) and other +// non-directories, then directories owned by uid that are empty afterwards. +// It never follows symlinks, never removes a root itself, and leaves any +// directory that still contains other users' files. Errors are logged and +// skipped. It returns the number of entries removed. +func removeOwnedFiles(roots []string, uid int) int { + removed := 0 + for _, root := range roots { + var dirs []string + _ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return nil // unreadable entry: skip it, keep walking + } + if p == root { + return nil + } + info, err := os.Lstat(p) + if err != nil { + return nil + } + st, ok := info.Sys().(*syscall.Stat_t) + if !ok || int(st.Uid) != uid { + return nil + } + if d.IsDir() { + dirs = append(dirs, p) // remove after its contents, if empty + return nil + } + if err := os.Remove(p); err != nil { + slog.Debug("could not remove file", "path", p, "err", err) + return nil + } + removed++ + return nil + }) + // Deepest first, so emptied parents can be removed too. os.Remove + // fails on non-empty directories, which keeps other users' files. + for i := len(dirs) - 1; i >= 0; i-- { + if err := os.Remove(dirs[i]); err == nil { + removed++ + } + } + } + return removed +} diff --git a/host/accounts_test.go b/host/accounts_test.go new file mode 100644 index 0000000..71090f7 --- /dev/null +++ b/host/accounts_test.go @@ -0,0 +1,988 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import ( + "errors" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// fakeOps is an in-memory accountOps that records every mutating call. +type fakeOps struct { + mu sync.Mutex + users map[string]int // username → uid + nextUID int + createErr error + fail map[string]error // op ("groups", "sudoers", "rmsudoers", "rmlegacy") → error to return + calls []string +} + +func (f *fakeOps) failure(op string) error { + f.mu.Lock() + defer f.mu.Unlock() + return f.fail[op] +} + +func newFakeOps() *fakeOps { + return &fakeOps{users: map[string]int{}, nextUID: 1001, fail: map[string]error{}} +} + +func (f *fakeOps) record(call string) { + f.mu.Lock() + f.calls = append(f.calls, call) + f.mu.Unlock() +} + +func (f *fakeOps) called(prefix string) bool { + f.mu.Lock() + defer f.mu.Unlock() + for _, c := range f.calls { + if strings.HasPrefix(c, prefix) { + return true + } + } + return false +} + +func (f *fakeOps) LookupUID(u string) (int, bool, error) { + f.mu.Lock() + defer f.mu.Unlock() + uid, ok := f.users[u] + return uid, ok, nil +} + +func (f *fakeOps) CreateUser(u string) error { + f.record("create:" + u) + if f.createErr != nil { + return f.createErr + } + f.mu.Lock() + f.users[u] = f.nextUID + f.nextUID++ + f.mu.Unlock() + return nil +} + +func (f *fakeOps) SetGroups(u string, g []string) error { + f.record("groups:" + u + ":" + strings.Join(g, ",")) + return f.failure("groups") +} +func (f *fakeOps) InstallSudoers(u, r string) error { + f.record("sudoers:" + u) + return f.failure("sudoers") +} +func (f *fakeOps) RemoveSudoers(u string) error { + f.record("rmsudoers:" + u) + return f.failure("rmsudoers") +} +func (f *fakeOps) RemoveLegacySudoers(u string) error { + f.record("rmlegacy:" + u) + return f.failure("rmlegacy") +} +func (f *fakeOps) ReactivateAccount(u string) error { + f.record("reactivate:" + u) + return f.failure("reactivate") +} + +func (f *fakeOps) TerminateProcesses(u string, uid int) error { + f.record("terminate:" + u) + return nil +} +func (f *fakeOps) DeleteUser(u string, uid int) error { + f.record("delete:" + u) + f.mu.Lock() + delete(f.users, u) + f.mu.Unlock() + return nil +} + +func testManager(t *testing.T, dir string, ops *fakeOps, cleanup bool) *UserManager { + t.Helper() + reg := NewOwnerRegistry(filepath.Join(dir, OwnedUsersFileName)) + return newUserManager(filepath.Join(dir, "managed-users"), reg, ops, cleanup) +} + +var adminPerms = IdentityPermissions{Groups: []string{"sudo"}, SudoersRule: "ALL=(ALL) NOPASSWD: ALL"} + +// ---- pre-existing accounts ---------------------------------------------------- + +func TestEnsureUser_PreExistingAccountNotAdopted(t *testing.T) { + ops := newFakeOps() + ops.users["alice"] = 1000 // e.g. an administrator's own account + m := testManager(t, t.TempDir(), ops, true) + + err := m.EnsureUser("alice", "alice", adminPerms) + if err == nil || !strings.Contains(err.Error(), "pre-existing account") { + t.Fatalf("expected pre-existing account rejection, got %v", err) + } + for _, c := range []string{"create:", "groups:", "sudoers:", "rmsudoers:", "rmlegacy:", "delete:"} { + if ops.called(c) { + t.Errorf("unexpected OS call %q on a pre-existing account", c) + } + } + if n := m.sessions["alice"]; n != 0 { + t.Errorf("session count = %d after rejection, want 0", n) + } +} + +func TestEnsureUser_ReservedAndInvalidNamesRejected(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, true) + for _, u := range []string{"root", "ubuntu", "sshd", "-ou0", "", "a.b"} { + if err := m.EnsureUser("x", u, IdentityPermissions{}); err == nil { + t.Errorf("EnsureUser(%q) succeeded, want rejection", u) + } + } + if len(ops.calls) != 0 { + t.Errorf("OS calls made for rejected names: %v", ops.calls) + } +} + +func TestEnsureUser_CreatesAndRegisters(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + m := testManager(t, dir, ops, false) + + if err := m.EnsureUser("alice@corp", "alice_corp", adminPerms); err != nil { + t.Fatalf("EnsureUser: %v", err) + } + rec, ok, err := m.registry.Get("alice_corp") + if err != nil || !ok { + t.Fatalf("registry record missing: ok=%v err=%v", ok, err) + } + if rec.Identity != "alice@corp" || rec.UID != 1001 || rec.Claimed { + t.Errorf("unexpected record %+v", rec) + } + if !ops.called("groups:alice_corp:sudo") || !ops.called("sudoers:alice_corp") { + t.Errorf("permissions not applied: %v", ops.calls) + } +} + +func TestEnsureUser_OwnershipSurvivesRestart(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + m := testManager(t, dir, ops, false) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + + // Restart: new manager, same registry file. + m2 := testManager(t, dir, ops, false) + ops.calls = nil + if err := m2.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatalf("owner reconnect after restart rejected: %v", err) + } + if ops.called("create:") { + t.Error("account recreated instead of reused") + } +} + +func TestEnsureUser_CollisionRejectedAcrossRestart(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + m := testManager(t, dir, ops, false) + // "alice.corp" and "alice_corp" both derive "alice_corp". + if err := m.EnsureUser("alice.corp", "alice_corp", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if err := m.ReleaseUser("alice_corp"); err != nil { + t.Fatal(err) + } + + m2 := testManager(t, dir, ops, false) + err := m2.EnsureUser("alice_corp", "alice_corp", adminPerms) + if err == nil || !strings.Contains(err.Error(), "already in use") { + t.Fatalf("expected collision rejection after restart, got %v", err) + } +} + +func TestEnsureUser_ReplacedAccountRejected(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + m := testManager(t, dir, ops, true) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + // Account deleted and recreated outside ziti-ssh-host with a new UID. + ops.users["alice"] = 1500 + + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err == nil || + !strings.Contains(err.Error(), "does not match registered uid") { + t.Fatalf("expected UID mismatch rejection, got %v", err) + } + // Releasing the original session must not delete the replacement account. + ops.calls = nil + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + if ops.called("delete:") || ops.called("rmsudoers:") { + t.Errorf("replacement account was modified on release: %v", ops.calls) + } +} + +func TestEnsureUser_LowUIDNeverManaged(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + m := testManager(t, dir, ops, true) + // Even a registry record cannot authorize a low-UID account. + ops.users["svc"] = 999 + if err := m.registry.Put("svc", OwnerRecord{Identity: "svc", UID: 999}); err != nil { + t.Fatal(err) + } + if err := m.EnsureUser("svc", "svc", adminPerms); err == nil { + t.Fatal("low-UID account was managed") + } + + // useradd assigning a low UID is rejected and the account is not registered. + ops.nextUID = 500 + if err := m.EnsureUser("bob", "bob", adminPerms); err == nil { + t.Fatal("account with low assigned UID accepted") + } + if _, ok, _ := m.registry.Get("bob"); ok { + t.Error("low-UID account was registered") + } + if ops.called("groups:") || ops.called("sudoers:") { + t.Errorf("permissions applied to low-UID account: %v", ops.calls) + } +} + +func TestEnsureUser_ConcurrentOutsideCreationRejected(t *testing.T) { + ops := newFakeOps() + ops.createErr = errUserExists + m := testManager(t, t.TempDir(), ops, true) + if err := m.EnsureUser("alice", "alice", adminPerms); err == nil { + t.Fatal("useradd exit 9 treated as success") + } + if _, ok, _ := m.registry.Get("alice"); ok { + t.Error("account registered after useradd reported it already existed") + } + if ops.called("groups:") || ops.called("sudoers:") { + t.Errorf("permissions applied: %v", ops.calls) + } +} + +func TestEnsureUser_RemovesLegacySudoersForOwnedAccount(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, true) + if err := m.EnsureUser("alice", "alice", adminPerms); err != nil { + t.Fatal(err) + } + if !ops.called("rmlegacy:alice") { + t.Error("legacy sudoers file not migrated for owned account") + } +} + +// ---- release / cleanup -------------------------------------------------------- + +func TestReleaseUser_DeletesOnlyOwnedAccount(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + m := testManager(t, dir, ops, true) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + if !ops.called("delete:alice") { + t.Error("owned account not deleted in cleanup mode") + } + if _, ok, _ := m.registry.Get("alice"); ok { + t.Error("registry record kept after deletion") + } + + // A session whose registry record disappears must not lead to deletion. + if err := m.EnsureUser("bob", "bob", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if err := m.registry.Remove("bob"); err != nil { + t.Fatal(err) + } + ops.calls = nil + if err := m.ReleaseUser("bob"); err != nil { + t.Fatal(err) + } + if ops.called("delete:") { + t.Error("unregistered account deleted") + } +} + +func TestReleaseUser_NewSessionDuringReleaseKeepsAccount(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, true) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + + ops.mu.Lock() + ops.calls = nil + ops.mu.Unlock() + + // Hold the per-user lock so ReleaseUser blocks after phase 1. + ul := m.userLocks["alice"] + ul.Lock() + done := make(chan error, 1) + go func() { done <- m.ReleaseUser("alice") }() + + // Wait for phase 1 to drop the session count to zero. + deadline := time.Now().Add(2 * time.Second) + for { + m.mu.Lock() + _, present := m.sessions["alice"] + m.mu.Unlock() + if !present { + break + } + if time.Now().After(deadline) { + t.Fatal("ReleaseUser phase 1 did not run") + } + time.Sleep(5 * time.Millisecond) + } + // A new session arrives (EnsureUser phase 1) before release takes the lock. + m.mu.Lock() + m.sessions["alice"]++ + m.mu.Unlock() + ul.Unlock() + + if err := <-done; err != nil { + t.Fatal(err) + } + if ops.called("delete:") || ops.called("rmsudoers:") { + t.Errorf("account torn down under a live session: %v", ops.calls) + } +} + +func TestReleaseUser_RejectedCollisionDoesNotBlockTeardown(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, true) + // "alice.corp" owns alice_corp; "alice_corp" derives the same username. + if err := m.EnsureUser("alice.corp", "alice_corp", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + ops.mu.Lock() + ops.calls = nil + ops.mu.Unlock() + + ul := m.userLocks["alice_corp"] + ul.Lock() + + // The colliding identity connects while the owner's last session ends. + collider := make(chan error, 1) + go func() { collider <- m.EnsureUser("alice_corp", "alice_corp", IdentityPermissions{}) }() + time.Sleep(50 * time.Millisecond) // let it reach the per-user lock + + release := make(chan error, 1) + go func() { release <- m.ReleaseUser("alice_corp") }() + + // The owner's release must see zero sessions: the rejected attempt must + // not have been counted. + deadline := time.Now().Add(2 * time.Second) + for { + m.mu.Lock() + _, present := m.sessions["alice_corp"] + m.mu.Unlock() + if !present { + break + } + if time.Now().After(deadline) { + ul.Unlock() + <-collider + <-release + t.Fatal("owner's release saw an open session counted for a not-yet-verified connection") + } + time.Sleep(5 * time.Millisecond) + } + ul.Unlock() + + // Either order is correct once the lock is released: if the collider runs + // first it is rejected (owned by alice.corp); if the release runs first the + // owner's account and record are deleted, and the collider then gets a + // fresh account of its own. In both cases the owner's teardown happens. + collErr := <-collider + if err := <-release; err != nil { + t.Fatal(err) + } + if !ops.called("delete:alice_corp") { + t.Errorf("owner's account was not torn down: %v", ops.calls) + } + if collErr == nil { + rec, ok, _ := m.registry.Get("alice_corp") + if !ok || rec.Identity != "alice_corp" { + t.Errorf("collider accepted without a fresh account of its own: %+v", rec) + } + } else if !strings.Contains(collErr.Error(), "already in use") { + t.Errorf("unexpected collider error: %v", collErr) + } +} + +func TestCleanupOrphans_SkipsUnownedAccounts(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + m := testManager(t, dir, ops, true) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + // State file also lists an account ziti-ssh-host never created. + ops.users["carol"] = 1000 + if err := os.WriteFile(m.stateFile, []byte("alice\ncarol\n"), 0600); err != nil { + t.Fatal(err) + } + + m2 := testManager(t, dir, ops, true) + ops.calls = nil + if err := m2.CleanupOrphans(); err != nil { + t.Fatal(err) + } + if !ops.called("delete:alice") { + t.Error("owned orphan not deleted") + } + if ops.called("delete:carol") { + t.Error("unowned account deleted by orphan cleanup") + } + data, _ := os.ReadFile(m.stateFile) + if strings.TrimSpace(string(data)) != "" { + t.Errorf("state file not cleared: %q", data) + } +} + +// ---- claim / registry --------------------------------------------------------- + +func TestClaimAccount(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + ops.users["alice"] = 1002 + ops.users["svc"] = 999 + reg := NewOwnerRegistry(filepath.Join(dir, OwnedUsersFileName)) + + if _, err := claimAccount(reg, ops, "svc", "svc"); err == nil { + t.Error("low-UID account claimed") + } + if _, err := claimAccount(reg, ops, "nobody-here", "nobody-here"); err == nil { + t.Error("missing account claimed") + } + if _, err := claimAccount(reg, ops, "root", "root"); err == nil { + t.Error("reserved account claimed") + } + + rec, err := claimAccount(reg, ops, "alice", "alice") + if err != nil { + t.Fatalf("claim: %v", err) + } + if !rec.Claimed || rec.UID != 1002 { + t.Errorf("unexpected record %+v", rec) + } + if _, err := claimAccount(reg, ops, "alice", "alice"); err != nil { + t.Errorf("re-claim by same identity should be a no-op: %v", err) + } + if _, err := claimAccount(reg, ops, "alice", "Alice"); err == nil { + t.Error("claim by a different identity succeeded") + } + + // The claimed account is now usable by its identity. + m := newUserManager(filepath.Join(dir, "managed-users"), reg, ops, false) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatalf("EnsureUser after claim: %v", err) + } +} + +func TestOwnerRegistry_CorruptFileFailsClosed(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, OwnedUsersFileName) + if err := os.WriteFile(path, []byte("{not json"), 0600); err != nil { + t.Fatal(err) + } + if _, err := NewUserManager(filepath.Join(dir, "managed-users"), true); err == nil { + t.Fatal("NewUserManager accepted a corrupt registry") + } + ops := newFakeOps() + m := newUserManager(filepath.Join(dir, "managed-users"), NewOwnerRegistry(path), ops, true) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err == nil { + t.Fatal("EnsureUser succeeded with a corrupt registry") + } + if len(ops.calls) != 0 { + t.Errorf("OS calls made with corrupt registry: %v", ops.calls) + } +} + +func TestOwnerRegistry_FileMode(t *testing.T) { + path := filepath.Join(t.TempDir(), OwnedUsersFileName) + reg := NewOwnerRegistry(path) + if err := reg.Put("alice", OwnerRecord{Identity: "alice", UID: 1001}); err != nil { + t.Fatal(err) + } + st, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if st.Mode().Perm() != 0600 { + t.Errorf("registry mode = %o, want 600", st.Mode().Perm()) + } +} + +// ---- legacy sudoers migration ------------------------------------------------- + +func TestRemoveLegacySudoersFile(t *testing.T) { + dir := t.TempDir() + cases := []struct { + name, content string + wantRemoved bool + }{ + {"written by ziti-ssh-host", "alice ALL=(ALL) NOPASSWD: ALL\n", true}, + {"admin file, other user", "bob ALL=(ALL) ALL\n", false}, + {"admin file, multiple lines", "alice ALL=(ALL) ALL\nDefaults:alice !requiretty\n", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := filepath.Join(dir, "alice") + if err := os.WriteFile(p, []byte(tc.content), 0440); err != nil { + t.Fatal(err) + } + if err := removeLegacySudoersFile(p, "alice"); err != nil { + t.Fatal(err) + } + _, err := os.Stat(p) + removed := os.IsNotExist(err) + if removed != tc.wantRemoved { + t.Errorf("removed = %v, want %v", removed, tc.wantRemoved) + } + os.Remove(p) + }) + } +} + +func TestSudoersPath_Prefixed(t *testing.T) { + if got := SudoersPath("admins"); got != "/etc/sudoers.d/ziti-ssh-host-admins" { + t.Errorf("SudoersPath = %q", got) + } +} + +func TestLegacySudoers_FindAndReconcile(t *testing.T) { + dir := t.TempDir() + write := func(name, content string) { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0440); err != nil { + t.Fatal(err) + } + } + write("alice", "alice ALL=(ALL) NOPASSWD: ALL\n") // owned below → removed + write("bob", "bob ALL=(ALL) ALL\n") // not registered → warn only + write("carol", "carol ALL=(ALL) ALL\nDefaults:carol !requiretty\n") // multi-line → not a candidate + write("README", "dave ALL=(ALL) ALL\n") // invalid username → ignored + write("root", "root ALL=(ALL) ALL\n") // reserved → ignored + write("ziti-ssh-host-erin", "erin ALL=(ALL) ALL\n") // current format → ignored + + got, err := findLegacySudoersFiles(dir) + if err != nil { + t.Fatal(err) + } + if strings.Join(got, ",") != "alice,bob" { + t.Fatalf("candidates = %v, want [alice bob]", got) + } + + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + ops.users["bob"] = 1000 // exists, never registered + ops.calls = nil + + m.reconcileLegacySudoersIn(dir) + if !ops.called("rmlegacy:alice") { + t.Error("legacy file for registered account not removed") + } + if ops.called("rmlegacy:bob") { + t.Error("legacy-format file for unregistered account was removed") + } +} + +// ---- H5: fail closed when permissions cannot be applied -------------------- + +func TestEnsureUser_PermissionFailuresRejectConnection(t *testing.T) { + boom := errors.New("boom") + cases := []struct { + name string + failOp string + perms IdentityPermissions + wantCalls []string // must have been attempted + notCalls []string // must not have been attempted + }{ + {"groups fail", "groups", adminPerms, nil, []string{"sudoers:"}}, + {"legacy sudoers removal fails", "rmlegacy", adminPerms, nil, []string{"sudoers:"}}, + // A failed install must also remove any existing file so an older rule + // cannot stay in force. + {"sudoers install fails", "sudoers", adminPerms, []string{"rmsudoers:alice"}, nil}, + {"sudoers removal fails (no rule configured)", "rmsudoers", IdentityPermissions{Groups: []string{"dev"}}, nil, nil}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + ops.fail[tc.failOp] = boom + + err := m.EnsureUser("alice", "alice", tc.perms) + if err == nil || !errors.Is(err, boom) { + t.Fatalf("want rejection wrapping the failure, got %v", err) + } + if n := m.sessions["alice"]; n != 0 { + t.Errorf("rejected connection counted as a session (count %d)", n) + } + for _, c := range tc.wantCalls { + if !ops.called(c) { + t.Errorf("expected call %q; calls: %v", c, ops.calls) + } + } + for _, c := range tc.notCalls { + if ops.called(c) { + t.Errorf("unexpected call %q after failure; calls: %v", c, ops.calls) + } + } + }) + } +} + +func TestEnsureUser_RecoversAfterConfigFixed(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + ops.fail["groups"] = errors.New("group 'dokcer' does not exist") + if err := m.EnsureUser("alice", "alice", adminPerms); err == nil { + t.Fatal("want rejection while config is broken") + } + delete(ops.fail, "groups") + if err := m.EnsureUser("alice", "alice", adminPerms); err != nil { + t.Fatalf("connection still rejected after config fixed: %v", err) + } + if m.sessions["alice"] != 1 { + t.Errorf("session count = %d, want 1", m.sessions["alice"]) + } +} + +func TestReleaseUser_ClearsGroupsAndSudoersWhenKeepingAccount(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) // cleanup off: account kept + if err := m.EnsureUser("alice", "alice", adminPerms); err != nil { + t.Fatal(err) + } + ops.calls = nil + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + if !ops.called("groups:alice:") || ops.called("groups:alice:sudo") { + t.Errorf("supplementary groups not cleared on last release: %v", ops.calls) + } + if !ops.called("rmsudoers:alice") { + t.Errorf("sudoers not removed on last release: %v", ops.calls) + } + if ops.called("delete:") { + t.Errorf("account deleted with cleanup disabled: %v", ops.calls) + } +} + +func TestCleanupOrphans_ClearsGroupsWhenKeepingAccounts(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + m := testManager(t, dir, ops, false) + if err := m.EnsureUser("alice", "alice", adminPerms); err != nil { + t.Fatal(err) + } + // Simulate a crash: state file still lists alice; a new manager starts. + m2 := testManager(t, dir, ops, false) + ops.calls = nil + if err := m2.CleanupOrphans(); err != nil { + t.Fatal(err) + } + if !ops.called("groups:alice:") || !ops.called("rmsudoers:alice") { + t.Errorf("orphan privileges not dropped after restart: %v", ops.calls) + } +} + +// ---- H12: opt-in termination of a kept account's processes ---------------- + +func TestReleaseUser_TerminateOnDisconnect(t *testing.T) { + t.Run("on: privileges dropped, then processes ended, account kept", func(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + m.SetTerminateOnDisconnect(true) + if err := m.EnsureUser("alice", "alice", adminPerms); err != nil { + t.Fatal(err) + } + ops.calls = nil + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + idx := func(prefix string) int { + for i, c := range ops.calls { + if strings.HasPrefix(c, prefix) { + return i + } + } + return -1 + } + term, groups, sudo := idx("terminate:alice"), idx("groups:alice:"), idx("rmsudoers:alice") + if term < 0 { + t.Fatalf("processes not terminated: %v", ops.calls) + } + if groups < 0 || sudo < 0 || groups > term || sudo > term { + t.Errorf("privileges must be dropped before termination: %v", ops.calls) + } + if ops.called("delete:") { + t.Errorf("account deleted although cleanup is off: %v", ops.calls) + } + }) + + t.Run("off (default): processes left running", func(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + if ops.called("terminate:") { + t.Errorf("processes terminated with the setting off: %v", ops.calls) + } + }) + + t.Run("not while other sessions remain", func(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + m.SetTerminateOnDisconnect(true) + for i := 0; i < 2; i++ { + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + } + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + if ops.called("terminate:") { + t.Errorf("processes terminated while a session is still open: %v", ops.calls) + } + }) + + t.Run("never for unregistered or replaced accounts", func(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + m.SetTerminateOnDisconnect(true) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + ops.users["alice"] = 1500 // replaced outside ziti-ssh-host + if err := m.EnsureUser("bob", "bob", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if err := m.registry.Remove("bob"); err != nil { // no longer registered + t.Fatal(err) + } + ops.calls = nil + _ = m.ReleaseUser("alice") + _ = m.ReleaseUser("bob") + if ops.called("terminate:") { + t.Errorf("terminated processes of an account not verifiably owned: %v", ops.calls) + } + }) +} + +func TestCleanupOrphans_TerminateOnDisconnect(t *testing.T) { + dir := t.TempDir() + ops := newFakeOps() + m := testManager(t, dir, ops, false) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + // Crash, then restart with the setting on. + m2 := testManager(t, dir, ops, false) + m2.SetTerminateOnDisconnect(true) + ops.calls = nil + if err := m2.CleanupOrphans(); err != nil { + t.Fatal(err) + } + if !ops.called("terminate:alice") || ops.called("delete:") { + t.Errorf("want processes of the orphaned account ended and the account kept: %v", ops.calls) + } +} + +// ---- M10: managed accounts are restricted to certificate login -------------- + +func TestSSHDDropIn_DisablesKeyFilesForManagedGroup(t *testing.T) { + got := SSHDDropIn("/etc/ssh/ziti_ca.pub") + for _, want := range []string{ + "TrustedUserCAKeys /etc/ssh/ziti_ca.pub\n", + "Match Group " + ManagedGroup + "\n", + " AuthorizedKeysFile none\n", + " AuthorizedKeysCommand none\n", + } { + if !strings.Contains(got, want) { + t.Errorf("drop-in missing %q:\n%s", want, got) + } + } + // TrustedUserCAKeys must come before the Match block (global scope). + if strings.Index(got, "TrustedUserCAKeys") > strings.Index(got, "Match Group") { + t.Error("TrustedUserCAKeys must precede the Match block") + } +} + +func TestEnsureSSHDDropIn_RewritesOnlyWhenDifferent(t *testing.T) { + conf := filepath.Join(t.TempDir(), "ziti-ssh.conf") + // A drop-in from an earlier release. + if err := os.WriteFile(conf, []byte("TrustedUserCAKeys /etc/ssh/ziti_ca.pub\n"), 0644); err != nil { + t.Fatal(err) + } + changed, err := EnsureSSHDDropIn(conf, "/etc/ssh/ziti_ca.pub") + if err != nil || !changed { + t.Fatalf("old drop-in not upgraded: changed=%v err=%v", changed, err) + } + changed, err = EnsureSSHDDropIn(conf, "/etc/ssh/ziti_ca.pub") + if err != nil || changed { + t.Fatalf("up-to-date drop-in rewritten: changed=%v err=%v", changed, err) + } +} + +func TestEnsureUser_AlwaysInManagedGroup(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{Groups: []string{"dev", ManagedGroup}}); err != nil { + t.Fatal(err) + } + if !ops.called("groups:alice:dev," + ManagedGroup) { + t.Errorf("managed group not added exactly once: %v", ops.calls) + } + ops.calls = nil + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if !ops.called("groups:alice:" + ManagedGroup) { + t.Errorf("account with no configured groups not kept in managed group: %v", ops.calls) + } + ops.calls = nil + _ = m.ReleaseUser("alice") + _ = m.ReleaseUser("alice") + if !ops.called("groups:alice:"+ManagedGroup) || ops.called("groups:alice:dev") { + t.Errorf("release must drop configured groups but keep the managed group: %v", ops.calls) + } +} + +// ---- G3: files left in shared temporary directories ------------------------ + +func TestRemoveOwnedFiles(t *testing.T) { + root := t.TempDir() + outside := filepath.Join(t.TempDir(), "keep-me") + if err := os.WriteFile(outside, []byte("x"), 0600); err != nil { + t.Fatal(err) + } + mustWrite := func(p string) { + if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte("x"), 0600); err != nil { + t.Fatal(err) + } + } + mustWrite(filepath.Join(root, "a.txt")) + mustWrite(filepath.Join(root, "sub", "deep", "b.txt")) + if err := os.Symlink(outside, filepath.Join(root, "link")); err != nil { + t.Fatal(err) + } + + // A different UID owns nothing here: nothing may be removed. + if n := removeOwnedFiles([]string{root}, os.Getuid()+1); n != 0 { + t.Fatalf("removed %d entries owned by another uid", n) + } + + n := removeOwnedFiles([]string{root}, os.Getuid()) + // a.txt, b.txt, link, deep/, sub/ + if n != 5 { + t.Errorf("removed %d entries, want 5", n) + } + entries, _ := os.ReadDir(root) + if len(entries) != 0 { + t.Errorf("entries left in root: %v", entries) + } + if _, err := os.Stat(root); err != nil { + t.Error("root directory itself was removed") + } + if _, err := os.Stat(outside); err != nil { + t.Error("symlink target outside the root was removed") + } +} + +// ---- revocation: scheduled jobs and account expiry (H12) ------------------ + +func TestAtJobsOf(t *testing.T) { + atq := "12\tThu Nov 20 10:00:00 2026 a alice\n" + + "13\tThu Nov 20 11:00:00 2026 b bob\n" + + "14\tFri Nov 21 09:30:00 2026 a alice\n" + + "garbage line alice\n" + got := atJobsOf(atq, "alice") + if len(got) != 2 || got[0] != "12" || got[1] != "14" { + t.Fatalf("atJobsOf = %v, want [12 14]", got) + } + if got := atJobsOf(atq, "carol"); len(got) != 0 { + t.Fatalf("carol: %v", got) + } +} + +func TestEnsureUser_ReactivatesOwnedAccount(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + // First connection creates the account: nothing to re-enable. + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if ops.called("reactivate:") { + t.Error("new account re-enabled") + } + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + // Reconnection to the kept account re-enables it (it may have been + // expired by TerminateProcesses at the last disconnect). + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if !ops.called("reactivate:alice") { + t.Error("existing account not re-enabled on connect") + } +} + +func TestEnsureUser_ReactivateFailureRejects(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + if err := m.EnsureUser("alice", "alice", IdentityPermissions{}); err != nil { + t.Fatal(err) + } + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + ops.mu.Lock() + ops.fail["reactivate"] = errors.New("usermod failed") + ops.mu.Unlock() + if err := m.EnsureUser("alice", "alice", adminPerms); err == nil { + t.Fatal("connection accepted although the account could not be re-enabled") + } + if ops.called("sudoers:alice") || ops.called("groups:alice:sudo") { + t.Error("permissions applied to an account that could not be re-enabled") + } +} diff --git a/host/caller_test.go b/host/caller_test.go new file mode 100644 index 0000000..79204d9 --- /dev/null +++ b/host/caller_test.go @@ -0,0 +1,185 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import ( + "net" + "testing" + "time" +) + +// zitiLikeConn mimics an SDK edge connection: SourceIdentifier() is the +// client-supplied CallerId header, GetDialerIdentityName() is the +// router-verified dialer identity. +type zitiLikeConn struct { + net.Conn + callerID string + dialerName string +} + +func (c *zitiLikeConn) SourceIdentifier() string { return c.callerID } +func (c *zitiLikeConn) GetDialerIdentityName() string { return c.dialerName } + +func TestCallerName_TrustsOnlyRouterVerifiedIdentity(t *testing.T) { + cases := []struct { + name string + callerID string + dialerName string + want string + }{ + {"mismatched caller id, no router identity", "root", "", ""}, + {"mismatched caller id, router identity present", "root", "alice", "alice"}, + {"matching values", "alice", "alice", "alice"}, + {"router identity only", "", "alice", "alice"}, + {"neither", "", "", ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := callerName(&zitiLikeConn{callerID: tc.callerID, dialerName: tc.dialerName}) + if got != tc.want { + t.Fatalf("callerName() = %q, want %q", got, tc.want) + } + }) + } +} + +// sourceOnlyConn exposes only the client-supplied CallerId, which was +// previously trusted and must now be ignored. +type sourceOnlyConn struct { + net.Conn + callerID string +} + +func (c *sourceOnlyConn) SourceIdentifier() string { return c.callerID } + +func TestCallerName_SourceIdentifierOnlyConnIsRejected(t *testing.T) { + if got := callerName(&sourceOnlyConn{callerID: "root"}); got != "" { + t.Fatalf("callerName() = %q, want empty", got) + } +} + +// targetListener starts a TCP listener standing in for sshd and returns its +// address and a channel that receives each accepted connection. +func targetListener(t *testing.T) (string, <-chan net.Conn) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + t.Cleanup(func() { ln.Close() }) + accepted := make(chan net.Conn, 4) + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + accepted <- c + } + }() + return ln.Addr().String(), accepted +} + +func TestProxyConn_HooksWithoutRouterIdentity_FailsClosed(t *testing.T) { + target, accepted := targetListener(t) + + client, server := net.Pipe() + defer client.Close() + + connectCalled := false + hooks := &ProxyHooks{ + OnConnect: func(string) error { connectCalled = true; return nil }, + OnDisconnect: func(string) {}, + } + + // Client-supplied CallerId only, no router-verified identity. Run in a goroutine so a + // regression (proxying instead of rejecting) fails rather than hangs. + done := make(chan struct{}) + go func() { + proxyConn(&zitiLikeConn{Conn: server, callerID: "root"}, target, hooks) + close(done) + }() + + select { + case c := <-accepted: + c.Close() + client.Close() + <-done + t.Fatal("connection was proxied to the target without a router-verified identity") + case <-done: + case <-time.After(2 * time.Second): + client.Close() + <-done + t.Fatal("proxyConn did not return promptly for a connection without a router-verified identity") + } + if connectCalled { + t.Fatal("OnConnect was called for a connection without a router-verified identity") + } +} + +func TestProxyConn_HooksReceiveRouterIdentityNotCallerID(t *testing.T) { + target, accepted := targetListener(t) + + client, server := net.Pipe() + + var gotIdentity string + hooks := &ProxyHooks{ + OnConnect: func(id string) error { gotIdentity = id; return nil }, + OnDisconnect: func(string) {}, + } + + done := make(chan struct{}) + go func() { + proxyConn(&zitiLikeConn{Conn: server, callerID: "root", dialerName: "alice"}, target, hooks) + close(done) + }() + + select { + case c := <-accepted: + c.Close() + case <-time.After(2 * time.Second): + t.Fatal("connection with a router-verified identity was not proxied") + } + client.Close() + <-done + + if gotIdentity != "alice" { + t.Fatalf("OnConnect received %q, want router-verified %q", gotIdentity, "alice") + } +} + +func TestProxyConn_NoHooks_SharedModeStillProxies(t *testing.T) { + target, accepted := targetListener(t) + + client, server := net.Pipe() + + done := make(chan struct{}) + go func() { + // Shared mode: no hooks, no identity needed on the host side. + proxyConn(&zitiLikeConn{Conn: server}, target, nil) + close(done) + }() + + select { + case c := <-accepted: + c.Close() + case <-time.After(2 * time.Second): + t.Fatal("shared-mode connection was not proxied") + } + client.Close() + <-done +} diff --git a/host/claim.go b/host/claim.go new file mode 100644 index 0000000..fdaebab --- /dev/null +++ b/host/claim.go @@ -0,0 +1,76 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import ( + "fmt" + "time" +) + +// ClaimAccount records an existing Linux account as owned by zitiIdentity in +// reg, so ziti-ssh-host will manage it on that identity's next connection. +// It is the migration path for accounts created by releases that predate the +// ownership registry. +// +// The account must exist, have a valid non-reserved name, and have a UID of at +// least MinManagedUID. Claiming an account already registered to the same +// identity and UID is a no-op; one registered to a different identity, or +// with a different UID, is an error. +// +// The caller is responsible for checking that username is the username derived +// from zitiIdentity. +func ClaimAccount(reg *OwnerRegistry, username, zitiIdentity string) (OwnerRecord, error) { + return claimAccount(reg, osAccountOps{}, username, zitiIdentity) +} + +func claimAccount(reg *OwnerRegistry, ops accountOps, username, zitiIdentity string) (OwnerRecord, error) { + if zitiIdentity == "" { + return OwnerRecord{}, fmt.Errorf("identity is empty") + } + if err := ValidateManagedUsername(username); err != nil { + return OwnerRecord{}, err + } + uid, exists, err := ops.LookupUID(username) + if err != nil { + return OwnerRecord{}, err + } + if !exists { + return OwnerRecord{}, fmt.Errorf("account %q does not exist (nothing to claim; it will be created on first connect)", username) + } + if uid < MinManagedUID { + return OwnerRecord{}, fmt.Errorf("account %q has uid %d, below %d: system accounts cannot be claimed", username, uid, MinManagedUID) + } + if rec, ok, err := reg.Get(username); err != nil { + return OwnerRecord{}, err + } else if ok { + if rec.Identity == zitiIdentity && rec.UID == uid { + return rec, nil + } + return OwnerRecord{}, fmt.Errorf("account %q is already registered to identity %q with uid %d", username, rec.Identity, rec.UID) + } + rec := OwnerRecord{Identity: zitiIdentity, UID: uid, Created: time.Now().UTC(), Claimed: true} + if err := reg.Put(username, rec); err != nil { + return OwnerRecord{}, err + } + return rec, nil +} + +// LookupAccountUID returns the UID of username via NSS (getent) and whether +// the account exists. +func LookupAccountUID(username string) (int, bool, error) { + return osAccountOps{}.LookupUID(username) +} diff --git a/host/grant.go b/host/grant.go new file mode 100644 index 0000000..362c2c4 --- /dev/null +++ b/host/grant.go @@ -0,0 +1,188 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import ( + "fmt" + "sort" + "strings" +) + +// PrivilegedGroups are Linux groups that are root-equivalent (or nearly so) on +// common distributions. A ziti-ssh-host.v1 config may grant them only for +// services the host owner has opted in via ZITI_ALLOW_GROUPS. +var PrivilegedGroups = []string{"root", "sudo", "admin", "wheel", "docker", "lxd", "disk", "shadow", "libvirt"} + +// GrantPolicy is the host owner's limit on what a ziti-ssh-host.v1 config — +// written by whoever can edit configs on the Ziti controller — may grant on +// this host, per Ziti service. It does not apply to the host's own fallbacks +// (ZITI_SSH_GROUPS, ZITI_SUDOERS_RULE). +// +// The zero value is the default policy: no service may set sudoers_rule, and +// any group except PrivilegedGroups may be granted. +type GrantPolicy struct { + sudoersAll bool + sudoersServices map[string]bool + groupsAll map[string]bool // "*:" + groupsByService map[string]map[string]bool // ":" + restrictGroups bool +} + +// ParseGrantPolicy builds a GrantPolicy from the host settings: +// +// allowSudoers ZITI_ALLOW_SUDOERS "svc1,svc2" or "*"; empty = none +// allowGroups ZITI_ALLOW_GROUPS "svc:group,*:group,..."; empty = none +// restrict ZITI_RESTRICT_GROUPS "true"/"false"; empty = false +func ParseGrantPolicy(allowSudoers, allowGroups, restrict string) (GrantPolicy, error) { + p := GrantPolicy{ + sudoersServices: map[string]bool{}, + groupsAll: map[string]bool{}, + groupsByService: map[string]map[string]bool{}, + } + + for _, svc := range splitList(allowSudoers) { + if svc == "*" { + p.sudoersAll = true + continue + } + if err := validateToken(svc); err != nil { + return GrantPolicy{}, fmt.Errorf("ZITI_ALLOW_SUDOERS: service %q: %w", svc, err) + } + p.sudoersServices[svc] = true + } + + for _, item := range splitList(allowGroups) { + svc, group, ok := strings.Cut(item, ":") + if !ok { + return GrantPolicy{}, fmt.Errorf("ZITI_ALLOW_GROUPS: entry %q must be : (use *: for all services)", item) + } + svc, group = strings.TrimSpace(svc), strings.TrimSpace(group) + if err := validateToken(group); err != nil { + return GrantPolicy{}, fmt.Errorf("ZITI_ALLOW_GROUPS: entry %q: group: %w", item, err) + } + if svc == "*" { + p.groupsAll[group] = true + continue + } + if err := validateToken(svc); err != nil { + return GrantPolicy{}, fmt.Errorf("ZITI_ALLOW_GROUPS: entry %q: service: %w", item, err) + } + if p.groupsByService[svc] == nil { + p.groupsByService[svc] = map[string]bool{} + } + p.groupsByService[svc][group] = true + } + + switch strings.ToLower(strings.TrimSpace(restrict)) { + case "", "false": + case "true": + p.restrictGroups = true + default: + return GrantPolicy{}, fmt.Errorf("ZITI_RESTRICT_GROUPS: must be true or false, got %q", restrict) + } + return p, nil +} + +// Check reports whether a config entry resolved for service may be applied. +// It returns an error describing the first refused grant. +func (p GrantPolicy) Check(service string, perms IdentityPermissions) error { + if perms.SudoersRule != "" && !p.sudoersAllowed(service) { + return fmt.Errorf("sudoers_rule is not permitted from service %q (host setting ZITI_ALLOW_SUDOERS)", service) + } + for _, g := range perms.Groups { + explicit := p.groupsAll[g] || p.groupsByService[service][g] + switch { + case p.restrictGroups && !explicit: + return fmt.Errorf("group %q is not permitted from service %q (ZITI_RESTRICT_GROUPS=true and not listed in ZITI_ALLOW_GROUPS)", g, service) + case !explicit && isPrivilegedGroup(g): + return fmt.Errorf("privileged group %q is not permitted from service %q (host setting ZITI_ALLOW_GROUPS, e.g. %s:%s)", g, service, service, g) + } + } + return nil +} + +// Enforce applies Check to permissions that came from a ziti-ssh-host.v1 +// config entry (fromConfig, from ResolveWithSource). The host's own fallbacks +// (ZITI_SSH_GROUPS, ZITI_SUDOERS_RULE) are set by the host owner and are never +// refused. +func (p GrantPolicy) Enforce(service string, perms IdentityPermissions, fromConfig bool) error { + if !fromConfig { + return nil + } + return p.Check(service, perms) +} + +// Describe summarises the policy for service, for logs and inspect output. +func (p GrantPolicy) Describe(service string) string { + sudoers := "refused" + if p.sudoersAllowed(service) { + sudoers = "allowed" + } + var extra []string + for g := range p.groupsAll { + extra = append(extra, g) + } + for g := range p.groupsByService[service] { + if !p.groupsAll[g] { + extra = append(extra, g) + } + } + sort.Strings(extra) + groups := "any except " + strings.Join(PrivilegedGroups, ", ") + if p.restrictGroups { + groups = "only listed" + } + if len(extra) > 0 { + groups += "; explicitly allowed: " + strings.Join(extra, ", ") + } else if p.restrictGroups { + groups += " (none listed)" + } + return fmt.Sprintf("sudoers_rule %s; groups: %s", sudoers, groups) +} + +func (p GrantPolicy) sudoersAllowed(service string) bool { + return p.sudoersAll || p.sudoersServices[service] +} + +func isPrivilegedGroup(g string) bool { + for _, pg := range PrivilegedGroups { + if g == pg { + return true + } + } + return false +} + +func splitList(v string) []string { + var out []string + for _, s := range strings.Split(v, ",") { + if s = strings.TrimSpace(s); s != "" { + out = append(out, s) + } + } + return out +} + +func validateToken(s string) error { + if s == "" { + return fmt.Errorf("is empty") + } + if strings.ContainsAny(s, " \t:,*") { + return fmt.Errorf("%q contains whitespace, ':', ',' or '*'", s) + } + return nil +} diff --git a/host/grant_test.go b/host/grant_test.go new file mode 100644 index 0000000..564871b --- /dev/null +++ b/host/grant_test.go @@ -0,0 +1,158 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import ( + "strings" + "testing" +) + +func mustPolicy(t *testing.T, sudoers, groups, restrict string) GrantPolicy { + t.Helper() + p, err := ParseGrantPolicy(sudoers, groups, restrict) + if err != nil { + t.Fatalf("ParseGrantPolicy(%q, %q, %q): %v", sudoers, groups, restrict, err) + } + return p +} + +func TestParseGrantPolicy_Invalid(t *testing.T) { + cases := []struct{ sudoers, groups, restrict string }{ + {"ssh ops", "", ""}, // whitespace in service name + {"ssh:ops", "", ""}, // ':' in service name + {"", "sudo", ""}, // group without service + {"", "ssh-ops:", ""}, // empty group + {"", ":sudo", ""}, // empty service + {"", "ssh-ops:su do", ""}, // whitespace in group + {"", "ssh-*:sudo", ""}, // wildcard inside a service name + {"", "", "yes"}, // not true/false + } + for _, c := range cases { + if _, err := ParseGrantPolicy(c.sudoers, c.groups, c.restrict); err == nil { + t.Errorf("ParseGrantPolicy(%q, %q, %q) accepted invalid input", c.sudoers, c.groups, c.restrict) + } + } +} + +func TestGrantPolicy_DefaultPolicy(t *testing.T) { + p := mustPolicy(t, "", "", "") + + if err := p.Check("ssh", IdentityPermissions{Groups: []string{"developers", "mysql"}}); err != nil { + t.Errorf("ordinary groups refused by default: %v", err) + } + if err := p.Check("ssh", IdentityPermissions{}); err != nil { + t.Errorf("empty permissions refused: %v", err) + } + for _, g := range PrivilegedGroups { + if err := p.Check("ssh", IdentityPermissions{Groups: []string{"developers", g}}); err == nil { + t.Errorf("privileged group %q allowed by default", g) + } + } + err := p.Check("ssh", IdentityPermissions{SudoersRule: "ALL=(ALL) NOPASSWD: ALL"}) + if err == nil || !strings.Contains(err.Error(), "ZITI_ALLOW_SUDOERS") { + t.Errorf("sudoers_rule allowed by default: %v", err) + } +} + +func TestGrantPolicy_PerServiceOptIn(t *testing.T) { + // The role-tier example: ssh-ops may grant root, ssh-db may not. + p := mustPolicy(t, "ssh-ops", "ssh-ops:sudo, ssh-ops:docker", "") + + root := IdentityPermissions{Groups: []string{"sudo", "docker"}, SudoersRule: "ALL=(ALL) NOPASSWD: ALL"} + if err := p.Check("ssh-ops", root); err != nil { + t.Errorf("opted-in service refused: %v", err) + } + if err := p.Check("ssh-db", IdentityPermissions{SudoersRule: "ALL=(ALL) ALL"}); err == nil { + t.Error("sudoers_rule allowed from a service that was not opted in") + } + if err := p.Check("ssh-db", IdentityPermissions{Groups: []string{"sudo"}}); err == nil { + t.Error("privileged group allowed from a service that was not opted in") + } + if err := p.Check("ssh-db", IdentityPermissions{Groups: []string{"mysql"}}); err != nil { + t.Errorf("ordinary group refused on other service: %v", err) + } +} + +func TestGrantPolicy_Wildcards(t *testing.T) { + p := mustPolicy(t, "*", "*:docker", "") + if err := p.Check("anything", IdentityPermissions{Groups: []string{"docker"}, SudoersRule: "ALL=(ALL) ALL"}); err != nil { + t.Errorf("wildcard opt-in not applied: %v", err) + } + if err := p.Check("anything", IdentityPermissions{Groups: []string{"sudo"}}); err == nil { + t.Error("*:docker must not allow other privileged groups") + } +} + +func TestGrantPolicy_RestrictGroups(t *testing.T) { + p := mustPolicy(t, "", "*:developers,ssh-ops:ops", "true") + if err := p.Check("ssh-ops", IdentityPermissions{Groups: []string{"developers", "ops"}}); err != nil { + t.Errorf("listed groups refused in strict mode: %v", err) + } + // A custom group that may carry sudo rights in the host's own sudoers. + if err := p.Check("ssh-db", IdentityPermissions{Groups: []string{"ops"}}); err == nil { + t.Error("group listed for another service allowed in strict mode") + } + if err := p.Check("ssh-ops", IdentityPermissions{Groups: []string{"mysql"}}); err == nil { + t.Error("unlisted ordinary group allowed in strict mode") + } +} + +func TestGrantPolicy_Describe(t *testing.T) { + p := mustPolicy(t, "ssh-ops", "ssh-ops:sudo", "") + if d := p.Describe("ssh-ops"); !strings.Contains(d, "sudoers_rule allowed") || !strings.Contains(d, "explicitly allowed: sudo") { + t.Errorf("Describe(ssh-ops) = %q", d) + } + if d := p.Describe("ssh-db"); !strings.Contains(d, "sudoers_rule refused") || strings.Contains(d, "explicitly allowed") { + t.Errorf("Describe(ssh-db) = %q", d) + } +} + +func TestResolveWithSource(t *testing.T) { + pc := &PermissionsConfig{Permissions: map[string]IdentityPermissions{ + "alice": {Groups: []string{"a"}}, + "dba-*": {Groups: []string{"b"}}, + "*": {Groups: []string{"c"}}, + }} + for _, id := range []string{"alice", "dba-carol", "someone-else"} { + if _, fromConfig := pc.ResolveWithSource(id, []string{"fallback"}, "ALL=(ALL) ALL"); !fromConfig { + t.Errorf("%q: config match reported as fallback", id) + } + } + + // Without a catch-all, unmatched identities use the host's fallbacks, + // which are not subject to the grant policy. + noCatchAll := &PermissionsConfig{Permissions: map[string]IdentityPermissions{"alice": {}}} + perms, fromConfig := noCatchAll.ResolveWithSource("bob", []string{"sudo"}, "ALL=(ALL) ALL") + if fromConfig || perms.SudoersRule == "" { + t.Errorf("fallback reported as config (fromConfig=%v, perms=%+v)", fromConfig, perms) + } + var nilConfig *PermissionsConfig + if _, fromConfig := nilConfig.ResolveWithSource("bob", nil, ""); fromConfig { + t.Error("no config attached reported as config") + } +} + +func TestGrantPolicy_EnforceSkipsHostFallbacks(t *testing.T) { + p := mustPolicy(t, "", "", "") + root := IdentityPermissions{Groups: []string{"sudo"}, SudoersRule: "ALL=(ALL) NOPASSWD: ALL"} + if err := p.Enforce("ssh", root, false); err != nil { + t.Errorf("host-owned fallback refused: %v", err) + } + if err := p.Enforce("ssh", root, true); err == nil { + t.Error("the same grant from a config entry was not refused") + } +} diff --git a/host/host.go b/host/host.go index 4a938b6..7993ce1 100644 --- a/host/host.go +++ b/host/host.go @@ -21,14 +21,16 @@ package host import ( "bufio" + "errors" "fmt" "io" "log/slog" "net" "os" "os/exec" - "path" "path/filepath" + "slices" + "sort" "strings" "sync" "time" @@ -37,13 +39,13 @@ import ( // IdentityPermissions holds the resolved Linux permissions for a single // connecting Ziti identity on a specific service. type IdentityPermissions struct { - // Groups is a list of existing Linux groups to add the ephemeral user to - // via "usermod -aG" after account creation. Groups must already exist on - // the host; a missing group causes a non-fatal logged error. + // Groups is the exact list of supplementary Linux groups for the user, set + // via "usermod -G" on every connect. Groups must already exist on the host; + // a missing group causes a non-fatal logged error. Groups []string // SudoersRule is the rule fragment written after the username in - // /etc/sudoers.d/. An empty string means no sudoers file is + // SudoersPath(username). An empty string means no sudoers file is // created for this user. SudoersRule string } @@ -60,51 +62,60 @@ type PermissionsConfig struct { // Resolution order: // 1. Exact key match — zitiIdentity found as a literal key in the map. // 2. Most specific glob pattern — among all map keys containing '*' or '?' -// that match zitiIdentity (via path.Match), the winner is determined by +// that match zitiIdentity (via MatchPattern: '*' any run of characters, +// including '/'; '?' one character; everything else literal), the +// winner is determined by // a two-field score: (prefixLen, totalLiterals) compared lexicographically // descending. prefixLen is the count of literal characters before the first // wildcard; totalLiterals is the count of all non-wildcard characters in // the pattern. This correctly ranks "*@dba" (0, 4) above "*" (0, 0). +// Patterns with equal scores are ordered by the pattern string (the +// lexically smaller wins), so the result never depends on map order. // 3. Env var fallback — globalGroups / globalSudoersRule (unchanged). // // In all matching cases the matched entry is returned as-is; global // fallbacks are not merged in. func (pc *PermissionsConfig) Resolve(zitiIdentity string, globalGroups []string, globalSudoersRule string) IdentityPermissions { + perms, _ := pc.ResolveWithSource(zitiIdentity, globalGroups, globalSudoersRule) + return perms +} + +// ResolveWithSource is Resolve, also reporting whether the result came from a +// ziti-ssh-host.v1 config entry (true) or from the host's own global fallbacks +// (false). Only config entries are subject to the host's GrantPolicy. +func (pc *PermissionsConfig) ResolveWithSource(zitiIdentity string, globalGroups []string, globalSudoersRule string) (IdentityPermissions, bool) { if pc != nil { // Step 1: exact match. if entry, ok := pc.Permissions[zitiIdentity]; ok { - return entry + return entry, true } // Step 2: glob match — find the most specific pattern that matches. bestPrefixLen := -1 bestTotalLiterals := 0 + bestPattern := "" var bestEntry IdentityPermissions for pattern, entry := range pc.Permissions { if !strings.ContainsAny(pattern, "*?") { // Pure literal key that didn't match exactly — skip. continue } - matched, err := path.Match(pattern, zitiIdentity) - if err != nil { - // path.Match only errors on malformed patterns (unclosed '['). - // Log and skip rather than crashing. - slog.Warn("invalid glob pattern in permissions config, skipping", - "pattern", pattern, "err", err) - continue - } - if !matched { + if !MatchPattern(pattern, zitiIdentity) { continue } pl, tl := patternSpecificity(pattern) - if pl > bestPrefixLen || (pl == bestPrefixLen && tl > bestTotalLiterals) { + better := pl > bestPrefixLen || + (pl == bestPrefixLen && tl > bestTotalLiterals) || + (pl == bestPrefixLen && tl == bestTotalLiterals && pattern < bestPattern) + if better { bestPrefixLen = pl bestTotalLiterals = tl + bestPattern = pattern bestEntry = entry } } if bestPrefixLen >= 0 { - return bestEntry + return bestEntry, true } } @@ -112,7 +123,56 @@ func (pc *PermissionsConfig) Resolve(zitiIdentity string, globalGroups []string, return IdentityPermissions{ Groups: globalGroups, SudoersRule: globalSudoersRule, + }, false +} + +// MatchPattern reports whether a ziti-ssh-host.v1 permissions key matches a +// Ziti identity name. '*' matches any run of characters (including none and +// including '/'), '?' matches exactly one character, and every other +// character — including '[', ']' and '\' — matches itself. (Earlier +// releases used path.Match, where '*' stopped at '/', '[…]' was a character +// class and '\' an escape.) +func MatchPattern(pattern, name string) bool { + p, n := []rune(pattern), []rune(name) + // Iterative wildcard match with single-star backtracking. + pi, ni, starP, starN := 0, 0, -1, 0 + for ni < len(n) { + switch { + case pi < len(p) && (p[pi] == '?' || p[pi] == n[ni]): + pi++ + ni++ + case pi < len(p) && p[pi] == '*': + starP, starN = pi, ni + pi++ + case starP >= 0: + pi = starP + 1 + starN++ + ni = starN + default: + return false + } } + for pi < len(p) && p[pi] == '*' { + pi++ + } + return pi == len(p) +} + +// PatternWarnings lists permissions keys whose meaning changed when matching +// moved from path.Match to MatchPattern: keys containing '[' or '\' (now +// literal characters). +func (pc *PermissionsConfig) PatternWarnings() []string { + if pc == nil { + return nil + } + var out []string + for key := range pc.Permissions { + if strings.ContainsAny(key, "[\\") { + out = append(out, fmt.Sprintf("key %q: '[' and '\\' are matched literally (only '*' and '?' are wildcards)", key)) + } + } + sort.Strings(out) + return out } // patternSpecificity returns two counts for a glob pattern: @@ -169,15 +229,32 @@ type ProxyHooks struct { // // hooks is optional. When non-nil and its fields are non-nil, OnConnect is // called before proxying and OnDisconnect is called after. The username -// passed to the hooks is extracted from the connection via SourceIdentifier() -// (preferred) or GetDialerIdentityName() (fallback); if neither is available -// the hooks are skipped. +// passed to the hooks is the router-verified dialer identity +// (GetDialerIdentityName()); if it is unavailable while hooks are configured, +// the connection is closed without proxying. // // wg is optional. When non-nil, each accepted connection increments wg before // starting and decrements it when the connection closes. Pass a WaitGroup to // enable graceful drain: after Proxy returns, call wg.Wait() (with a timeout // of your choice) to block until all in-flight connections have finished. func Proxy(listener net.Listener, target string, hooks *ProxyHooks, wg *sync.WaitGroup) { + ProxyLimited(listener, target, hooks, wg, 0) +} + +// DefaultMaxConnections is the default per-service cap on concurrent proxied +// connections (ziti-ssh-host run --max-connections / ZITI_MAX_CONNECTIONS). +const DefaultMaxConnections = 128 + +// ProxyLimited is Proxy with at most maxConns connections in flight +// (0 = unlimited). A connection accepted while the limit is reached is closed +// immediately, before any hook runs; refusals are logged at most every 10 s. +func ProxyLimited(listener net.Listener, target string, hooks *ProxyHooks, wg *sync.WaitGroup, maxConns int) { + var slots chan struct{} + if maxConns > 0 { + slots = make(chan struct{}, maxConns) + } + var lastWarn time.Time + refused := 0 for { conn, err := listener.Accept() if err != nil { @@ -185,6 +262,20 @@ func Proxy(listener net.Listener, target string, hooks *ProxyHooks, wg *sync.Wai slog.Info("proxy listener closed", "err", err) return } + if slots != nil { + select { + case slots <- struct{}{}: + default: + _ = conn.Close() + refused++ + if time.Since(lastWarn) >= 10*time.Second { + slog.Warn("connection limit reached; closing new connections", + "max_connections", maxConns, "refused_since_last_warning", refused) + lastWarn, refused = time.Now(), 0 + } + continue + } + } if wg != nil { wg.Add(1) } @@ -192,36 +283,46 @@ func Proxy(listener net.Listener, target string, hooks *ProxyHooks, wg *sync.Wai if wg != nil { defer wg.Done() } + if slots != nil { + defer func() { <-slots }() + } proxyConn(c, target, hooks) }(conn) } } -// callerName returns the Ziti identity name for the connection. +// callerName returns the router-verified Ziti identity name of the dialer. +// +// Only GetDialerIdentityName() is trusted. That header is set by the dialer's +// edge router (OpenZiti v2.0.0+) from the router's own record of the +// authenticated identity. SourceIdentifier() (the CallerId header) is written +// by the dialing SDK and copied through the router unchanged, so a modified +// client can claim any name; it is used only to log a warning on mismatch. // -// The SDK sets CallerIdHeader to the dialer's identity name on every dial and -// exposes it via SourceIdentifier(). GetDialerIdentityName() reads a separate -// header injected by the fabric layer that may not be present. We prefer -// SourceIdentifier() and fall back to GetDialerIdentityName(). +// Returns "" when the router did not supply a dialer identity. // // Defined via structural interfaces so host has no import dependency on the // Ziti SDK. func callerName(conn net.Conn) string { + type dialerNamer interface { + GetDialerIdentityName() string + } + dn, ok := conn.(dialerNamer) + if !ok { + return "" + } + name := dn.GetDialerIdentityName() + type sourceIdentifier interface { SourceIdentifier() string } if si, ok := conn.(sourceIdentifier); ok { - if name := si.SourceIdentifier(); name != "" { - return name + if claimed := si.SourceIdentifier(); claimed != "" && name != "" && claimed != name { + slog.Warn("client-supplied caller id does not match router-verified dialer identity; using router-verified identity", + "dialer_identity", name, "claimed_caller_id", claimed) } } - type dialerNamer interface { - GetDialerIdentityName() string - } - if dn, ok := conn.(dialerNamer); ok { - return dn.GetDialerIdentityName() - } - return "" + return name } func proxyConn(src net.Conn, target string, hooks *ProxyHooks) { @@ -231,6 +332,12 @@ func proxyConn(src net.Conn, target string, hooks *ProxyHooks) { var username string if hooks != nil && (hooks.OnConnect != nil || hooks.OnDisconnect != nil) { username = callerName(src) + // Fail closed: with hooks configured (per-identity mode) a connection + // must never reach sshd without a router-verified identity. + if username == "" { + slog.Error("rejected connection: edge router did not supply a dialer identity (OpenZiti v2.0.0+ routers required)") + return + } } // OnConnect lifecycle — must succeed before we proxy anything. @@ -266,6 +373,44 @@ func proxyConn(src net.Conn, target string, hooks *ProxyHooks) { <-done } +// ManagedGroup is the Linux group whose members' own authorized_keys (and any +// AuthorizedKeysCommand) sshd ignores, so they can only log in with a CA +// certificate. ziti-ssh-host adds every per-identity account to it; in shared +// mode the administrator adds the shared account. +const ManagedGroup = "ziti-ssh-managed" + +// SSHDDropIn returns the sshd_config.d drop-in content: trust the CA keys in +// keyFile, and disable key files and key commands for ManagedGroup members. +// A user could otherwise add a key to their own authorized_keys file that +// keeps working after their certificate expires or their identity is revoked. +func SSHDDropIn(keyFile string) string { + return fmt.Sprintf(`# Managed by ziti-ssh-host. +TrustedUserCAKeys %s + +# Accounts managed through Ziti may only log in with a CA certificate. +Match Group %s + AuthorizedKeysFile none + AuthorizedKeysCommand none +`, keyFile, ManagedGroup) +} + +// EnsureSSHDDropIn rewrites confFile with SSHDDropIn(keyFile) if its content +// differs (e.g. after an upgrade) and reports whether it changed. The caller +// must reload sshd when it did. +func EnsureSSHDDropIn(confFile, keyFile string) (bool, error) { + want := SSHDDropIn(keyFile) + if cur, err := os.ReadFile(confFile); err == nil && string(cur) == want { + return false, nil + } + if err := os.MkdirAll(filepath.Dir(confFile), 0755); err != nil { + return false, fmt.Errorf("create dir for %q: %w", confFile, err) + } + if err := atomicWriteFile(confFile, []byte(want), 0644); err != nil { + return false, fmt.Errorf("write sshd config to %q: %w", confFile, err) + } + return true, nil +} + // WriteSSHConfig writes the CA public key to keyFile (mode 0644) and writes // a sshd_config.d snippet referencing it to confFile (mode 0644). Parent // directories are created as needed. @@ -288,7 +433,7 @@ func WriteSSHConfig(caPubKey []byte, confFile, keyFile string) error { if err := os.MkdirAll(filepath.Dir(confFile), 0755); err != nil { return fmt.Errorf("create dir for %q: %w", confFile, err) } - conf := fmt.Sprintf("TrustedUserCAKeys %s\n", keyFile) + conf := SSHDDropIn(keyFile) if err := atomicWriteFile(confFile, []byte(conf), 0644); err != nil { return fmt.Errorf("write sshd config to %q: %w", confFile, err) } @@ -345,19 +490,44 @@ func atomicWriteFile(dest string, data []byte, mode os.FileMode) error { return nil } -// ReloadSSHD signals sshd to reload its configuration. -// -// Ubuntu 24.04 defaults to socket-activated sshd (ssh.socket + ssh@.service): -// each incoming connection spawns a fresh sshd that re-reads sshd_config at -// fork, so no daemon reload is required — the next connection automatically -// picks up TrustedUserCAKeys. When the traditional long-running ssh.service is -// active instead, SIGHUP is delivered via "systemctl reload ssh". +// sshdState describes how sshd is running under systemd. +type sshdState struct { + ServiceActive bool // ssh.service is active (a long-running sshd daemon) + SocketActive bool // ssh.socket is active + SocketPerConn bool // ssh.socket has Accept=yes (one sshd per connection) +} + +// sshdReloadPlan is what ReloadSSHD does for a given sshdState. +type sshdReloadPlan struct { + ReloadService bool // run "systemctl reload ssh" + HUPOrphans bool // SIGHUP top-level sshd processes (PPID 1) +} + +// planSSHDReload decides how to make sshd pick up a changed configuration. // -// In both cases pkill broadcasts SIGHUP to any top-level sshd listener -// processes (PPID=1) that may be co-listening via SO_REUSEPORT alongside the -// managed instance. This covers orphaned sshd parents left by service restarts -// during provisioning. Per-connection children call signal(SIGHUP, SIG_IGN) -// after privilege separation (OpenSSH 8.x+) and are unaffected. +// - A running ssh.service is a long-lived daemon that only re-reads its +// configuration on SIGHUP, so it is always reloaded — including on Ubuntu +// 22.10+ where ssh.socket (Accept=no) starts ssh.service on the first +// connection and that daemon then serves all later connections. +// - Top-level sshd listeners (PPID 1) left over from earlier service +// restarts can co-listen on port 22 via SO_REUSEPORT with a stale config; +// they are sent SIGHUP too. Their per-connection children have the +// listener as parent, not PID 1, so live sessions are unaffected. +// - The exception is ssh.socket with Accept=yes, where every connection's +// sshd has PPID 1: signalling them would disconnect live sessions, and no +// signal is needed because each instance reads the configuration at start. +// - When neither ssh.service is running nor an Accept=yes socket is in use, +// the next sshd started reads the new configuration; there is nothing to +// reload. +func planSSHDReload(st sshdState) sshdReloadPlan { + return sshdReloadPlan{ + ReloadService: st.ServiceActive, + HUPOrphans: !(st.SocketActive && st.SocketPerConn), + } +} + +// ReloadSSHD validates the sshd configuration and makes running sshd +// processes pick it up (see planSSHDReload). func ReloadSSHD() error { // Validate configuration before reloading. sshd -t reads the full config // tree (including sshd_config.d drop-ins) and checks that referenced files @@ -367,30 +537,35 @@ func ReloadSSHD() error { return fmt.Errorf("sshd config validation failed (not reloading): %w\n%s", err, strings.TrimSpace(string(out))) } - // Detect socket-activated sshd (Ubuntu 24.04 default). Under socket - // activation, ssh.service is typically masked and "systemctl reload ssh" - // would fail — but no reload is needed because each sshd instance reads - // its config at fork time. - socketActive := exec.Command("systemctl", "is-active", "--quiet", "ssh.socket").Run() == nil - if socketActive { - slog.Info("sshd is socket-activated; new connections will pick up TrustedUserCAKeys automatically") - } else { - cmd := exec.Command("systemctl", "reload", "ssh") + st := sshdState{ + ServiceActive: exec.Command("systemctl", "is-active", "--quiet", "ssh.service").Run() == nil, + SocketActive: exec.Command("systemctl", "is-active", "--quiet", "ssh.socket").Run() == nil, + } + if st.SocketActive { + out, err := exec.Command("systemctl", "show", "ssh.socket", "-p", "Accept", "--value").Output() + // If the mode cannot be determined, assume per-connection (Accept=yes) + // so live sessions are never signalled. + st.SocketPerConn = err != nil || strings.TrimSpace(string(out)) != "no" + } + plan := planSSHDReload(st) + slog.Info("reloading sshd", "service_active", st.ServiceActive, "socket_active", st.SocketActive, + "socket_per_connection", st.SocketPerConn, "reload_service", plan.ReloadService, "hup_orphans", plan.HUPOrphans) + + if plan.ReloadService { + cmd := exec.Command("systemctl", "reload", "ssh.service") cmd.Env = childEnv() if out, err := cmd.CombinedOutput(); err != nil { - return fmt.Errorf("systemctl reload ssh: %w (output: %s)", err, out) + return fmt.Errorf("systemctl reload ssh.service: %w (output: %s)", err, out) } } - - // Under ssh.service (non-socket), also signal any top-level sshd listener - // that may have been spawned outside systemd. Skip this under socket - // activation: per-connection sshd children have PPID 1 there too, and - // sending SIGHUP to an active connection sshd disconnects the session. - if !socketActive { + if plan.HUPOrphans { if err := exec.Command("pkill", "-HUP", "-P", "1", "-x", "sshd").Run(); err != nil { slog.Debug("pkill sshd: no additional listener processes to signal", "err", err) } } + if !plan.ReloadService && !plan.HUPOrphans { + slog.Info("sshd is socket-activated per connection; new connections will read the updated configuration") + } slog.Info("sshd reloaded") return nil @@ -410,71 +585,142 @@ func childEnv() []string { return filtered } -// UserManager tracks reference counts for per-identity Linux users and -// persists the set of managed usernames to a state file so that orphaned -// users created before a crash can be cleaned up on the next startup. +// UserManager tracks reference counts for per-identity Linux users and decides +// which accounts ziti-ssh-host is allowed to create, modify, and delete. +// +// Ownership is recorded in a persistent OwnerRegistry (owned-users.json, next +// to the state file). An account is managed only if it is in the registry for +// the connecting Ziti identity with a matching UID. Pre-existing accounts that +// ziti-ssh-host did not create — root, the distribution's default user, any +// administrator account — are never adopted, modified, or deleted. +// +// The managed-users state file separately lists accounts with active sessions +// so that CleanupOrphans can delete them after a crash (cleanup mode only). // // All exported methods are safe for concurrent use. type UserManager struct { mu sync.Mutex - sessions map[string]int // username → active session count - owners map[string]string // username → Ziti identity that created the account + sessions map[string]int // username → active session count + // activeService / activePerms record which service, and which resolved + // permissions, the account's open sessions were admitted with (M2: one + // Linux account per identity, so permissions are per account). + activeService map[string]string + activePerms map[string]IdentityPermissions userLocks map[string]*sync.Mutex // username → per-user lock for slow OS ops stateFile string - cleanupOnDisconnect bool // if false, skip deleteUser on ReleaseUser + registry *OwnerRegistry + ops accountOps + cleanupOnDisconnect bool // if false, keep the account on ReleaseUser + + // terminateOnDisconnect ends all of a kept account's processes when its + // last session closes (see SetTerminateOnDisconnect). + terminateOnDisconnect bool } -// NewUserManager returns a UserManager that persists state to stateFile. -// The state file and its parent directories are created on first write. +// SetTerminateOnDisconnect controls whether, with cleanup disabled, all +// processes of an account are ended when its last session closes (and for +// accounts that still had sessions open after a crash). The account and its +// home directory are kept. Without it, background processes started by a +// user (nohup, tmux, systemd user services) survive disconnect — and +// revocation of the user's Ziti identity. Call before accepting connections. +func (m *UserManager) SetTerminateOnDisconnect(on bool) { + m.mu.Lock() + m.terminateOnDisconnect = on + m.mu.Unlock() +} + +// keepAccountOnLastRelease drops an owned account's privileges and, if +// configured, ends its processes. Used when cleanup (deletion) is disabled. +func (m *UserManager) keepAccountOnLastRelease(username string, uid int) { + m.dropPrivileges(username) + m.mu.Lock() + terminate := m.terminateOnDisconnect + m.mu.Unlock() + if !terminate { + return + } + slog.Info("ending all processes of user (ZITI_TERMINATE_ON_DISCONNECT)", "username", username, "uid", uid) + if err := m.ops.TerminateProcesses(username, uid); err != nil { + slog.Error("failed to terminate user processes", "username", username, "uid", uid, "err", err) + } +} + +// NewUserManager returns a UserManager that persists active sessions to +// stateFile and account ownership to OwnedUsersFileName in the same directory. // // cleanupOnDisconnect controls whether the Linux user is deleted when the last // session closes. When false, the account persists across disconnects; the // sudoers file is still removed if one was written. -func NewUserManager(stateFile string, cleanupOnDisconnect bool) *UserManager { +// +// It returns an error if the ownership registry exists but cannot be read, so +// the daemon fails closed rather than managing accounts without it. +func NewUserManager(stateFile string, cleanupOnDisconnect bool) (*UserManager, error) { + reg := NewOwnerRegistry(filepath.Join(filepath.Dir(stateFile), OwnedUsersFileName)) + if _, _, err := reg.List(); err != nil { + return nil, err + } + return newUserManager(stateFile, reg, osAccountOps{}, cleanupOnDisconnect), nil +} + +func newUserManager(stateFile string, reg *OwnerRegistry, ops accountOps, cleanupOnDisconnect bool) *UserManager { return &UserManager{ sessions: make(map[string]int), - owners: make(map[string]string), + activeService: make(map[string]string), + activePerms: make(map[string]IdentityPermissions), userLocks: make(map[string]*sync.Mutex), stateFile: stateFile, + registry: reg, + ops: ops, cleanupOnDisconnect: cleanupOnDisconnect, } } -// EnsureUser creates the Linux user if this is the first session for that -// username. zitiIdentity is the caller's Ziti identity name; username is its -// derived Linux username (from ca.DeriveUsername). The pair is recorded so -// that if a different Ziti identity later derives the same Linux username the -// connection is rejected rather than silently inheriting the first caller's -// permissions. +// Registry returns the manager's ownership registry. +func (m *UserManager) Registry() *OwnerRegistry { return m.registry } + +// EnsureUser prepares the Linux account for a new session of zitiIdentity, +// whose derived Linux username is username, and applies perms. // -// useradd is called with "-m -s /bin/bash ". If useradd reports -// that the user already exists (exit code 9) the error is ignored so that -// concurrent connections that race to create the same user are handled -// gracefully. +// The account is used only if one of the following holds: +// - it does not exist: it is created with useradd, its UID is verified to be +// >= MinManagedUID, and ownership is recorded in the registry; or +// - it exists and the registry records it as owned by zitiIdentity with the +// same UID. // -// perms carries the resolved per-identity permissions for this connection. -// Groups and sudoers are only applied on the first session for a username -// (when the account is actually created). Subsequent sessions for the same -// username log a message and return immediately. +// Every other case is rejected without touching the account: a pre-existing +// account not created by ziti-ssh-host, an account owned by a different Ziti +// identity (derived-username collision), an account deleted and recreated +// with a different UID, a UID below MinManagedUID, or a reserved/invalid name. // -// The username is recorded in the state file so that CleanupOrphans can -// remove it after a crash. +// Supplementary groups are then set to exactly perms.Groups and the sudoers +// file is written (or removed if perms.SudoersRule is empty); if any of that +// fails the connection is rejected. The +// session is counted (only after ownership is verified) and the username +// recorded in the state file. func (m *UserManager) EnsureUser(zitiIdentity, username string, perms IdentityPermissions) error { - // Phase 1 (global lock, fast): ownership check, session bookkeeping, and - // per-user lock acquisition. No blocking OS calls are made here. + return m.EnsureUserForService(zitiIdentity, username, "", perms) +} + +// ErrPermissionConflict is returned (wrapped) by EnsureUserForService when an +// account already has sessions open through another service with different +// permissions. +var ErrPermissionConflict = errors.New("account has open sessions through another service with different permissions") + +// EnsureUserForService is EnsureUser for a connection that arrived on service. +// A Linux account has one set of groups and one sudoers file, shared by all +// of its sessions; so while the account has open sessions admitted through +// one service, a connection through a different service that resolves to +// different permissions is rejected (ErrPermissionConflict) instead of +// silently changing the permissions of the sessions already open. A +// connection through the same service always applies the current +// permissions, so config changes take effect. service "" skips the check. +func (m *UserManager) EnsureUserForService(zitiIdentity, username, service string, perms IdentityPermissions) error { + if err := ValidateManagedUsername(username); err != nil { + return fmt.Errorf("identity %q: %w", zitiIdentity, err) + } + + // Phase 1 (global lock, fast): obtain the per-user lock. m.mu.Lock() - if owner, owned := m.owners[username]; owned && owner != zitiIdentity { - m.mu.Unlock() - return fmt.Errorf("username %q (derived from %q) is already in use by Ziti identity %q: connection rejected to prevent privilege collision", - username, zitiIdentity, owner) - } - m.sessions[username]++ - isFirst := m.sessions[username] == 1 - if isFirst { - // Record ownership atomically with the session increment so there is no - // window where the account exists without a recorded owner. - m.owners[username] = zitiIdentity - } ul, ok := m.userLocks[username] if !ok { ul = &sync.Mutex{} @@ -482,107 +728,213 @@ func (m *UserManager) EnsureUser(zitiIdentity, username string, perms IdentityPe } m.mu.Unlock() - if !isFirst { - // Acquire the per-user lock to: - // (a) wait for the first caller to finish useradd before proceeding - // (H5 barrier — prevents SSH login before /etc/passwd is written), and - // (b) re-apply permissions idempotently, so a config change takes effect - // on the next concurrent session without waiting for all sessions to - // close (C2 fix — "regardless of session count"). - // - // Invariant: by the time EnsureUser returns nil, the Linux user exists in - // /etc/passwd (or useradd reported it already existed). - ul.Lock() - defer ul.Unlock() + // Phase 2 (per-user lock): ownership verification and OS operations. + // ReleaseUser takes the same lock before tearing anything down, so the + // account cannot be deleted between the ownership check and the session + // being counted. + ul.Lock() + defer ul.Unlock() - slog.Info("user already exists, re-applying permissions", "username", username, "sessions", m.sessions[username]) + if err := m.checkPermissionConflict(username, service, perms); err != nil { + return fmt.Errorf("identity %q on service %q: %w", zitiIdentity, service, err) + } - groupList := strings.Join(perms.Groups, ",") - slog.Info("setting user supplementary groups", "username", username, "groups", groupList) - usermod := exec.Command("usermod", "-G", groupList, username) - usermod.Env = childEnv() - if out, err := usermod.CombinedOutput(); err != nil { - slog.Error("usermod -G failed", "username", username, "groups", groupList, "err", err, "output", strings.TrimSpace(string(out))) - } + if err := m.ensureOwnedAccount(zitiIdentity, username); err != nil { + return err + } - if perms.SudoersRule != "" { - if err := createSudoers(username, perms.SudoersRule); err != nil { - slog.Error("failed to update sudoers file", "username", username, "err", err) - } - } else { - // Config no longer specifies a sudoers rule — remove any stale file. - if err := removeSudoers(username); err != nil { - slog.Error("failed to remove stale sudoers file", "username", username, "err", err) - } + // Apply the resolved permissions. Any failure rejects the connection + // (fail closed): continuing would leave the account with whatever groups + // or sudoers rule it had before, which may be more than the current + // config grants. + if err := m.applyPermissions(zitiIdentity, username, perms); err != nil { + return err + } + + // Count the session only once ownership is verified and permissions are + // applied. Counting earlier would let a rejected attempt make the owner's + // final ReleaseUser believe a session is still open and skip teardown. + m.mu.Lock() + m.sessions[username]++ + isFirst := m.sessions[username] == 1 + if service != "" { + m.activeService[username] = service + m.activePerms[username] = perms + } + m.mu.Unlock() + + if isFirst { + if err := m.syncStateFile(); err != nil { + slog.Error("failed to write state file", "username", username, "err", err) } + } + return nil +} +// checkPermissionConflict implements the cross-service rule of +// EnsureUserForService. Must be called with the per-user lock. +func (m *UserManager) checkPermissionConflict(username, service string, perms IdentityPermissions) error { + if service == "" { + return nil + } + m.mu.Lock() + defer m.mu.Unlock() + if m.sessions[username] == 0 { return nil } + prev, ok := m.activeService[username] + if !ok || prev == service || samePermissions(m.activePerms[username], perms) { + return nil + } + slog.Error("rejecting connection: account has open sessions through another service with different permissions", + "username", username, "service", service, "active_service", prev, "sessions", m.sessions[username]) + return fmt.Errorf("%w (%q); close those sessions first", ErrPermissionConflict, prev) +} - // Phase 2 (per-user lock only): slow OS operations. The global lock is not - // held here, so other usernames proceed concurrently. - ul.Lock() - defer ul.Unlock() +// samePermissions reports whether a and b grant the same groups (in any +// order, duplicates ignored) and the same sudoers rule. +func samePermissions(a, b IdentityPermissions) bool { + if a.SudoersRule != b.SudoersRule { + return false + } + set := func(g []string) []string { + out := slices.Clone(g) + slices.Sort(out) + return slices.Compact(out) + } + return slices.Equal(set(a.Groups), set(b.Groups)) +} - slog.Info("creating Linux user", "username", username) - cmd := exec.Command("useradd", "-m", "-s", "/bin/bash", username) - cmd.Env = childEnv() - out, err := cmd.CombinedOutput() - if err != nil { - // useradd exits with code 9 when the user already exists. - if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 9 { - slog.Info("user already exists, treating as success", "username", username, "ziti_identity", zitiIdentity) - } else { - // Rollback: undo the session increment and ownership record. - m.mu.Lock() - m.sessions[username]-- - if m.sessions[username] == 0 { - delete(m.sessions, username) - delete(m.owners, username) +// applyPermissions sets the account's supplementary groups to exactly +// perms.Groups and installs or removes its sudoers file. It returns an error +// (and the caller rejects the connection) if any step fails. If a new sudoers +// rule cannot be installed, any existing sudoers file is removed first so an +// older rule cannot remain in force. Must be called with the per-user lock. +func (m *UserManager) applyPermissions(zitiIdentity, username string, perms IdentityPermissions) error { + reject := func(what string, err error) error { + slog.Error("rejecting connection: could not apply permissions", + "identity", zitiIdentity, "username", username, "step", what, "err", err) + return fmt.Errorf("identity %q: %s for %q: %w", zitiIdentity, what, username, err) + } + groups := withManagedGroup(perms.Groups) + if err := m.ops.SetGroups(username, groups); err != nil { + return reject(fmt.Sprintf("setting supplementary groups %v", groups), err) + } + if err := m.ops.RemoveLegacySudoers(username); err != nil { + return reject("removing legacy sudoers file", err) + } + if perms.SudoersRule != "" { + if err := m.ops.InstallSudoers(username, perms.SudoersRule); err != nil { + if rmErr := m.ops.RemoveSudoers(username); rmErr != nil { + slog.Error("could not remove existing sudoers file after failed update", + "username", username, "err", rmErr) } - m.mu.Unlock() - return fmt.Errorf("useradd %q: %w (output: %s)", username, err, out) + return reject("writing sudoers file", err) } + } else if err := m.ops.RemoveSudoers(username); err != nil { + return reject("removing sudoers file", err) } + return nil +} - // Set the user's supplementary groups to exactly the configured list. - // -G replaces the full supplementary group membership rather than - // appending (-aG), so revocations take effect on the next reconnect - // without needing to delete and recreate the account. An empty list - // clears all supplementary groups. - groupList := strings.Join(perms.Groups, ",") - slog.Info("setting user supplementary groups", "username", username, "groups", groupList) - usermod := exec.Command("usermod", "-G", groupList, username) - usermod.Env = childEnv() - if out, err := usermod.CombinedOutput(); err != nil { - // Non-fatal: the user was created successfully; group membership - // failure (e.g. group does not exist) is logged but does not abort - // the session. - slog.Error("usermod -G failed", "username", username, "groups", groupList, "err", err, "output", strings.TrimSpace(string(out))) +// dropPrivileges clears supplementary groups and removes the sudoers file of +// an owned account with no open sessions. Failures are logged; the next +// connection re-applies (or rejects) permissions in any case. +func (m *UserManager) dropPrivileges(username string) { + if err := m.ops.RemoveSudoers(username); err != nil { + slog.Error("failed to remove sudoers file", "username", username, "err", err) + } + if err := m.ops.SetGroups(username, []string{ManagedGroup}); err != nil { + slog.Error("failed to clear supplementary groups", "username", username, "err", err) } +} - // Write sudoers file if a rule is configured. - if perms.SudoersRule != "" { - if err := createSudoers(username, perms.SudoersRule); err != nil { - // Non-fatal: the user was created successfully; sudoers failure - // should not block the session, but it must be visible in logs. - slog.Error("failed to create sudoers file", "username", username, "err", err) +// withManagedGroup returns groups plus ManagedGroup (once). Managed accounts +// always stay in it so sshd never accepts their own authorized_keys. +func withManagedGroup(groups []string) []string { + out := make([]string, 0, len(groups)+1) + for _, g := range groups { + if g != ManagedGroup { + out = append(out, g) } } + return append(out, ManagedGroup) +} - // Persist the username so orphan cleanup can find it after a restart. - if err := m.syncStateFile(); err != nil { - slog.Error("failed to write state file", "username", username, "err", err) - // Non-fatal: the user was created; orphan cleanup may miss it after a - // crash, but the session ref-count is correct for this run. +// ensureOwnedAccount verifies or establishes ownership of username for +// zitiIdentity. Must be called with the per-user lock held. +func (m *UserManager) ensureOwnedAccount(zitiIdentity, username string) error { + rec, owned, err := m.registry.Get(username) + if err != nil { + return fmt.Errorf("ownership registry: %w", err) + } + if owned && rec.Identity != zitiIdentity { + return fmt.Errorf("username %q (derived from %q) is already in use by Ziti identity %q: connection rejected to prevent privilege collision", + username, zitiIdentity, rec.Identity) } + uid, exists, err := m.ops.LookupUID(username) + if err != nil { + return err + } + + if exists { + if !owned { + return fmt.Errorf("refusing to manage pre-existing account %q (identity %q): it was not created by ziti-ssh-host; if it should be, run \"ziti-ssh-host users claim\"", + username, zitiIdentity) + } + if uid != rec.UID { + return fmt.Errorf("refusing to manage account %q: uid %d does not match registered uid %d (account was replaced outside ziti-ssh-host)", + username, uid, rec.UID) + } + if uid < MinManagedUID { + return fmt.Errorf("refusing to manage account %q: uid %d is below %d", username, uid, MinManagedUID) + } + // The account may have been expired when its last session ended + // (TerminateProcesses); this authorized connection re-enables it. + // Fail closed: an expired account would be refused by sshd anyway. + if err := m.ops.ReactivateAccount(username); err != nil { + return err + } + return nil + } + + // Account does not exist. A registry record for it is stale (the account + // was deleted outside ziti-ssh-host); it is replaced below. + slog.Info("creating Linux user", "username", username, "ziti_identity", zitiIdentity) + if err := m.ops.CreateUser(username); err != nil { + if errors.Is(err, errUserExists) { + // Created by someone else between lookup and useradd. + return fmt.Errorf("refusing to manage account %q: it was created concurrently outside ziti-ssh-host", username) + } + return err + } + uid, exists, err = m.ops.LookupUID(username) + if err != nil || !exists { + return fmt.Errorf("account %q not found after useradd (err: %v)", username, err) + } + if uid < MinManagedUID { + // Not registered, so it will never be used or modified. Left for the + // administrator to remove: deleteUser refuses UIDs below the floor. + slog.Error("useradd assigned a uid below the managed floor; account not registered and will not be used", + "username", username, "uid", uid) + return fmt.Errorf("useradd assigned uid %d below %d to %q; check UID_MIN in /etc/login.defs", uid, MinManagedUID, username) + } + if owned { + if err := m.registry.Remove(username); err != nil { + return fmt.Errorf("ownership registry: %w", err) + } + } + if err := m.registry.Put(username, OwnerRecord{Identity: zitiIdentity, UID: uid, Created: time.Now().UTC()}); err != nil { + return fmt.Errorf("ownership registry: %w", err) + } return nil } // ReleaseUser decrements the session count for username. When the count -// reaches zero, the Linux user is deleted with "userdel -r " and -// the username is removed from the state file. +// reaches zero, the sudoers file is removed and — in cleanup mode — the Linux +// user is deleted. Nothing is done to an account that is not in the registry +// with a matching UID. func (m *UserManager) ReleaseUser(username string) error { // Phase 1 (global lock, fast): session bookkeeping only. m.mu.Lock() @@ -598,24 +950,35 @@ func (m *UserManager) ReleaseUser(username string) error { return nil } delete(m.sessions, username) - delete(m.owners, username) + delete(m.activeService, username) + delete(m.activePerms, username) ul := m.userLocks[username] m.mu.Unlock() - // Phase 2 (per-user lock only): slow OS operations. The global lock is not - // held here, so other usernames proceed concurrently. + // Phase 2 (per-user lock): slow OS operations. if ul != nil { ul.Lock() defer ul.Unlock() } + // A new session may have started between phase 1 and acquiring the + // per-user lock; it now owns the account, so do not tear anything down. + m.mu.Lock() + reacquired := m.sessions[username] > 0 + m.mu.Unlock() + if reacquired { + slog.Info("new session started during release; keeping user", "username", username) + return nil + } + + uid, ok := m.verifiedOwnedUID(username) + if !ok { + return m.syncStateFile() + } + if !m.cleanupOnDisconnect { - slog.Info("last session closed, cleanup disabled — keeping Linux user", "username", username) - // Always attempt to remove the sudoers file (it may or may not exist). - // removeSudoers is a no-op if the file is absent. - if err := removeSudoers(username); err != nil { - slog.Error("failed to remove sudoers file", "username", username, "err", err) - } + slog.Info("last session closed, cleanup disabled — keeping Linux user without supplementary groups or sudoers", "username", username) + m.keepAccountOnLastRelease(username, uid) if err := m.syncStateFile(); err != nil { slog.Error("failed to update state file", "username", username, "err", err) } @@ -623,31 +986,63 @@ func (m *UserManager) ReleaseUser(username string) error { } slog.Info("last session closed, deleting Linux user", "username", username) - if err := deleteUser(username); err != nil { + if err := m.ops.DeleteUser(username, uid); err != nil { return err } - + if err := m.registry.Remove(username); err != nil { + slog.Error("failed to remove ownership record after deletion", "username", username, "err", err) + } if err := m.syncStateFile(); err != nil { slog.Error("failed to update state file after deletion", "username", username, "err", err) - // Non-fatal. } - return nil } -// CleanupOrphans reads the state file and calls userdel -r on each listed -// username. It is intended to be called at startup, before accepting any -// connections, to remove users that were not cleaned up after a crash. +// verifiedOwnedUID returns the account's UID if it is in the registry, still +// exists with the registered UID, and is at or above MinManagedUID. Any other +// state is logged and reported as not owned. A registry record whose account +// no longer exists is removed. +func (m *UserManager) verifiedOwnedUID(username string) (int, bool) { + rec, owned, err := m.registry.Get(username) + if err != nil { + slog.Error("ownership registry unreadable; not touching account", "username", username, "err", err) + return 0, false + } + if !owned { + slog.Warn("account not in ownership registry; not touching it", "username", username) + return 0, false + } + uid, exists, err := m.ops.LookupUID(username) + if err != nil { + slog.Error("account lookup failed; not touching it", "username", username, "err", err) + return 0, false + } + if !exists { + slog.Info("registered account no longer exists; removing ownership record", "username", username) + if err := m.registry.Remove(username); err != nil { + slog.Error("failed to remove stale ownership record", "username", username, "err", err) + } + return 0, false + } + if uid != rec.UID || uid < MinManagedUID { + slog.Warn("account uid does not match ownership record or is below floor; not touching it", + "username", username, "uid", uid, "registered_uid", rec.UID) + return 0, false + } + return uid, true +} + +// CleanupOrphans reads the state file and, in cleanup mode, deletes each +// listed account that is still owned per the registry. It is intended to be +// called at startup, before accepting any connections, to remove users that +// were not cleaned up after a crash. Unowned accounts are dropped from the +// state file without being touched. // // Errors deleting individual users are logged but do not stop cleanup of the // remaining users. func (m *UserManager) CleanupOrphans() error { - m.mu.Lock() - defer m.mu.Unlock() - data, err := os.ReadFile(m.stateFile) if os.IsNotExist(err) { - // No state file — nothing to clean up. return nil } if err != nil { @@ -663,29 +1058,35 @@ func (m *UserManager) CleanupOrphans() error { continue } if !m.cleanupOnDisconnect { - // Users are intentionally persistent; do not delete them on - // restart. Clear the state file so they are no longer tracked - // by this process instance — they will not be cleaned up on the - // next restart either, which is the correct behaviour. - slog.Info("cleanup disabled; skipping orphan user deletion on restart", "username", username) + // Accounts are intentionally persistent. Remove any sudoers file + // left by a crash, but keep the account. + slog.Info("cleanup disabled; keeping account after restart", "username", username) + if uid, ok := m.verifiedOwnedUID(username); ok { + m.keepAccountOnLastRelease(username, uid) + } + continue + } + uid, ok := m.verifiedOwnedUID(username) + if !ok { continue } slog.Info("cleaning up orphan user", "username", username) - if err := deleteUser(username); err != nil { + if err := m.ops.DeleteUser(username, uid); err != nil { slog.Error("failed to delete orphan user", "username", username, "err", err) - // Keep in remaining so we try again on the next restart. remaining = append(remaining, username) + continue + } + if err := m.registry.Remove(username); err != nil { + slog.Error("failed to remove ownership record after orphan deletion", "username", username, "err", err) } } - if err := scanner.Err(); err != nil { return fmt.Errorf("scan state file: %w", err) } - - // Rewrite the state file with only the users we failed to delete. return m.writeStateFile(remaining) } + // ValidateSudoersRule checks that rule is safe to embed in a sudoers file as // the fragment following a username: // @@ -703,10 +1104,23 @@ func ValidateSudoersRule(rule string) error { if strings.ContainsAny(rule, "\n\r") { return fmt.Errorf("sudoers_rule must not contain newlines") } + if strings.ContainsRune(rule, 0) { + return fmt.Errorf("sudoers_rule must not contain NUL bytes") + } trimmed := strings.TrimSpace(rule) if strings.HasPrefix(trimmed, "#") { return fmt.Errorf("sudoers_rule must not start with '#'") } + // The file line is " ". A rule starting with ',' would + // extend the User_List, e.g. ", ALL ALL=(ALL) NOPASSWD: ALL" grants root + // to every user on the host. + if strings.HasPrefix(trimmed, ",") { + return fmt.Errorf("sudoers_rule must not start with ',' (it would add users to the rule)") + } + // Every user specification has the form "Host_List = Cmnd_Spec_List". + if trimmed != "" && !strings.Contains(trimmed, "=") { + return fmt.Errorf("sudoers_rule must have the form \"=\", e.g. \"ALL=(ALL) NOPASSWD: /usr/bin/systemctl status *\"") + } for _, kw := range []string{"@include", "Defaults", "Cmnd_Alias", "Host_Alias", "User_Alias", "Runas_Alias"} { if strings.HasPrefix(trimmed, kw) { return fmt.Errorf("sudoers_rule must not start with %q", kw) @@ -722,7 +1136,20 @@ func ValidateSudoersRule(rule string) error { // /etc/sudoers.d guarantees the final os.Rename is atomic (same filesystem). const sudoersStagingDir = "/etc/sudoers.d/.ziti-ssh-host-staging" -// createSudoers writes a validated sudoers file to /etc/sudoers.d/. +// SudoersPath returns the sudoers file ziti-ssh-host manages for username: +// /etc/sudoers.d/ziti-ssh-host-. The prefix keeps it from colliding +// with administrator-created files. Usernames are limited to [a-z0-9_-], so +// the name never contains '.' or ends in '~' (which sudo's #includedir skips). +func SudoersPath(username string) string { + return "/etc/sudoers.d/ziti-ssh-host-" + username +} + +// legacySudoersPath is the pre-rename location, /etc/sudoers.d/. +func legacySudoersPath(username string) string { + return "/etc/sudoers.d/" + username +} + +// createSudoers writes a validated sudoers file to SudoersPath(username). // // The file content is " \n". It is staged in sudoersStagingDir // (a hidden subdirectory of /etc/sudoers.d that sudo ignores), validated with @@ -765,7 +1192,7 @@ func createSudoers(username, rule string) error { } // Atomic rename — same filesystem as the staging dir. - dest := "/etc/sudoers.d/" + username + dest := SudoersPath(username) if err := os.Rename(tmpPath, dest); err != nil { os.Remove(tmpPath) return fmt.Errorf("install sudoers file to %q: %w", dest, err) @@ -775,115 +1202,19 @@ func createSudoers(username, rule string) error { return nil } -// removeSudoers removes /etc/sudoers.d/ if it exists. +// removeSudoers removes SudoersPath(username) if it exists. // A missing file is not treated as an error. func removeSudoers(username string) error { - path := "/etc/sudoers.d/" + username + path := SudoersPath(username) if err := os.Remove(path); err != nil && !os.IsNotExist(err) { return fmt.Errorf("remove sudoers file %q: %w", path, err) } return nil } -// deleteUser drains the user's systemd session, waits for all owned processes -// to exit, then removes the user and their home directory with userdel -r. -// userProcessesGone polls pgrep until no processes owned by username remain or -// the timeout elapses. Returns true when the user has no remaining processes. -func userProcessesGone(username string, timeout time.Duration) bool { - const pollInterval = 200 * time.Millisecond - deadline := time.Now().Add(timeout) - for time.Now().Before(deadline) { - pgrep := exec.Command("pgrep", "-u", username) - pgrep.Env = childEnv() - err := pgrep.Run() - if err != nil { - // pgrep exits 1 when no processes match — user is clear. - if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 1 { - return true - } - // Unexpected pgrep error (e.g. command not found) — stop polling. - slog.Warn("pgrep error while waiting for user processes to exit", - "username", username, "err", err) - return false - } - time.Sleep(pollInterval) - } - return false -} - -func deleteUser(username string) error { - // Remove the sudoers file before tearing down the account. - if err := removeSudoers(username); err != nil { - slog.Error("failed to remove sudoers file during deleteUser", "username", username, "err", err) - // Non-fatal: proceed with userdel regardless. - } - - // Step 1: ask loginctl to terminate the user session (systemd --user, - // sd-pam, etc.). Ignore errors — the session may already be gone. - loginctl := exec.Command("loginctl", "terminate-user", username) - loginctl.Env = childEnv() - if out, err := loginctl.CombinedOutput(); err != nil { - slog.Info("loginctl terminate-user returned non-zero (ignored)", - "username", username, "err", err, "output", strings.TrimSpace(string(out))) - } - - // Step 2: wait up to 5 s for session processes to exit naturally. - if !userProcessesGone(username, 5*time.Second) { - // Step 3: escalate to SIGTERM for detached processes (nohup, screen, - // tmux) that loginctl does not reach. - slog.Info("user processes still running after loginctl; sending SIGTERM", "username", username) - pkillTerm := exec.Command("pkill", "-TERM", "-u", username) - pkillTerm.Env = childEnv() - if out, err := pkillTerm.CombinedOutput(); err != nil { - slog.Info("pkill -TERM returned non-zero (ignored)", - "username", username, "err", err, "output", strings.TrimSpace(string(out))) - } - - // Step 4: wait up to 10 s for SIGTERM to take effect. - if !userProcessesGone(username, 10*time.Second) { - // Step 5: escalate to SIGKILL — cannot be caught or ignored. - slog.Warn("user processes still running after SIGTERM; sending SIGKILL", "username", username) - pkillKill := exec.Command("pkill", "-KILL", "-u", username) - pkillKill.Env = childEnv() - if out, err := pkillKill.CombinedOutput(); err != nil { - slog.Info("pkill -KILL returned non-zero (ignored)", - "username", username, "err", err, "output", strings.TrimSpace(string(out))) - } - - // Step 6: wait up to 5 s for the kernel to reap SIGKILL'd processes. - if !userProcessesGone(username, 5*time.Second) { - slog.Warn("user processes still running after SIGKILL; proceeding with userdel", - "username", username) - } - } - } - - // Step 7: remove the user and their home directory. - cmd := exec.Command("userdel", "-r", username) - cmd.Env = childEnv() - out, err := cmd.CombinedOutput() - if err != nil { - if exitErr, ok := err.(*exec.ExitError); ok && exitErr.ExitCode() == 8 { - // Exit code 8: user still has running processes. The account and - // home directory were NOT deleted. The caller should retry after - // the processes exit. - return fmt.Errorf("userdel %q: user still has running processes; account not deleted (exit 8): %s", - username, strings.TrimSpace(string(out))) - } - return fmt.Errorf("userdel -r %q: %w (output: %s)", username, err, out) - } - slog.Info("deleted Linux user", "username", username) - return nil -} - // syncStateFile atomically rewrites the state file from the current contents // of m.sessions. It briefly acquires m.mu to take a consistent snapshot, then // releases it before performing file I/O — so callers must not hold m.mu. -// -// This replaces both the old addToStateFile (append) and removeFromStateFile -// (read-filter-rewrite) with a single always-correct snapshot: the in-memory -// sessions map is the source of truth, so there is no need to read the file -// and no risk of divergence between the file and the map. func (m *UserManager) syncStateFile() error { m.mu.Lock() lines := make([]string, 0, len(m.sessions)) @@ -895,50 +1226,10 @@ func (m *UserManager) syncStateFile() error { } // writeStateFile atomically replaces the state file with lines. -// It writes to a temp file in the same directory, fsyncs, renames, then -// fsyncs the parent directory — so a crash at any point leaves either the old -// or the new file fully intact, never a zero-length or partially-written file. func (m *UserManager) writeStateFile(lines []string) error { - dir := filepath.Dir(m.stateFile) - if err := os.MkdirAll(dir, 0700); err != nil { - return fmt.Errorf("create state file dir: %w", err) - } content := strings.Join(lines, "\n") if len(lines) > 0 { content += "\n" } - tmp, err := os.CreateTemp(dir, ".managed-users-tmp-*") - if err != nil { - return fmt.Errorf("create state file temp: %w", err) - } - tmpPath := tmp.Name() - if _, err := tmp.WriteString(content); err != nil { - tmp.Close() - os.Remove(tmpPath) - return fmt.Errorf("write state file temp: %w", err) - } - if err := tmp.Sync(); err != nil { - tmp.Close() - os.Remove(tmpPath) - return fmt.Errorf("sync state file temp: %w", err) - } - if err := tmp.Chmod(0600); err != nil { - tmp.Close() - os.Remove(tmpPath) - return fmt.Errorf("chmod state file temp: %w", err) - } - if err := tmp.Close(); err != nil { - os.Remove(tmpPath) - return fmt.Errorf("close state file temp: %w", err) - } - if err := os.Rename(tmpPath, m.stateFile); err != nil { - os.Remove(tmpPath) - return fmt.Errorf("rename state file: %w", err) - } - // Fsync the parent directory to make the rename durable across power loss. - if dirF, err := os.Open(dir); err == nil { - _ = dirF.Sync() - dirF.Close() - } - return nil + return writeFileAtomic(m.stateFile, []byte(content), 0600) } diff --git a/host/host_test.go b/host/host_test.go index 5f90590..c1cef30 100644 --- a/host/host_test.go +++ b/host/host_test.go @@ -389,7 +389,7 @@ func TestEnsureUser_AcceptsIdentityPermissions(t *testing.T) { dir := t.TempDir() stateFile := filepath.Join(dir, "state") - mgr := host.NewUserManager(stateFile, true) + mgr := mustUserManager(t, stateFile, true) // Use a deliberately short unique name unlikely to clash with system users. username := "ztestperm01" @@ -430,7 +430,7 @@ func TestEnsureUser_RefCounting(t *testing.T) { dir := t.TempDir() stateFile := filepath.Join(dir, "state") - mgr := host.NewUserManager(stateFile, true) + mgr := mustUserManager(t, stateFile, true) username := "ztestrefcnt1" perms := host.IdentityPermissions{} @@ -473,7 +473,7 @@ func TestNewUserManager_Signature(t *testing.T) { // Verify that NewUserManager's signature no longer includes sudoersRule. // This is a compile-time check embedded as a runtime test. dir := t.TempDir() - mgr := host.NewUserManager(filepath.Join(dir, "state"), true) + mgr := mustUserManager(t, filepath.Join(dir, "state"), true) if mgr == nil { t.Fatal("NewUserManager returned nil") } @@ -510,6 +510,10 @@ func TestValidateSudoersRule(t *testing.T) { {"Host_Alias ALL = *", "Host_Alias keyword"}, {"User_Alias ADMINS = root", "User_Alias keyword"}, {"Runas_Alias ROOT = root", "Runas_Alias keyword"}, + {", ALL ALL=(ALL) NOPASSWD: ALL", "leading comma extends the user list"}, + {" ,ALL ALL=(ALL) NOPASSWD: ALL", "leading comma after whitespace"}, + {"ALL=(ALL) NOPASSWD: /bin/ls\x00", "NUL byte"}, + {"NOPASSWD: ALL", "missing '=' (not a user specification)"}, } for _, tc := range invalid { if err := host.ValidateSudoersRule(tc.rule); err == nil { @@ -524,7 +528,7 @@ func TestEnsureUser_CollisionRejected(t *testing.T) { } dir := t.TempDir() - mgr := host.NewUserManager(filepath.Join(dir, "state"), true) + mgr := mustUserManager(t, filepath.Join(dir, "state"), true) // "alice.corp" and "alice_corp" are different Ziti identities that both // derive to the Linux username "alice_corp" (period → underscore). @@ -548,3 +552,13 @@ func TestEnsureUser_CollisionRejected(t *testing.T) { t.Errorf("expected 'already in use' in error, got: %v", err) } } + +// mustUserManager constructs a UserManager or fails the test. +func mustUserManager(t *testing.T, stateFile string, cleanup bool) *host.UserManager { + t.Helper() + mgr, err := host.NewUserManager(stateFile, cleanup) + if err != nil { + t.Fatalf("NewUserManager: %v", err) + } + return mgr +} diff --git a/host/match_test.go b/host/match_test.go new file mode 100644 index 0000000..df7147c --- /dev/null +++ b/host/match_test.go @@ -0,0 +1,83 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import ( + "strings" + "testing" +) + +func TestMatchPattern(t *testing.T) { + cases := []struct { + pattern, name string + want bool + }{ + {"*", "alice", true}, + {"*", "", true}, + {"*", "team/alice", true}, // path.Match: '*' stopped at '/' + {"dba-*", "dba-carol", true}, + {"dba-*", "ops-carol", false}, + {"*@corp.com", "alice@corp.com", true}, + {"*@corp.com", "alice@corp.com.evil", false}, + {"a?c", "abc", true}, + {"a?c", "ac", false}, + {"a*b*c", "aXXbYYc", true}, + {"a*b*c", "aXXbYY", false}, + {"[ab]*", "a-team", false}, // path.Match: character class + {"[ab]*", "[ab]-team", true}, + {`dev\*`, `dev\anything`, true}, // path.Match: escaped '*' + {"é*", "éclair", true}, + } + for _, c := range cases { + if got := MatchPattern(c.pattern, c.name); got != c.want { + t.Errorf("MatchPattern(%q, %q) = %v, want %v", c.pattern, c.name, got, c.want) + } + } +} + +func TestResolve_EqualSpecificityIsDeterministic(t *testing.T) { + // "*a*" and "*b*" both match "ab" with equal specificity (0, 1); the + // lexically smaller pattern must win every time, regardless of map order. + pc := &PermissionsConfig{Permissions: map[string]IdentityPermissions{ + "*-ops": {Groups: []string{"ops"}}, + "*-dba": {Groups: []string{"dba"}}, + "*-x": {Groups: []string{"x"}}, + "x-*": {Groups: []string{"prefix"}}, + }} + pc2 := &PermissionsConfig{Permissions: map[string]IdentityPermissions{ + "*b*": {Groups: []string{"b"}}, + "*a*": {Groups: []string{"a"}}, + }} + for i := 0; i < 200; i++ { + if got := pc2.Resolve("ab", nil, ""); len(got.Groups) != 1 || got.Groups[0] != "a" { + t.Fatalf("iteration %d: got %v, want [a]", i, got.Groups) + } + if got := pc.Resolve("x-ops", nil, ""); got.Groups[0] != "prefix" { + t.Fatalf("prefix should win: %v", got.Groups) + } + } +} + +func TestPatternWarnings(t *testing.T) { + pc := &PermissionsConfig{Permissions: map[string]IdentityPermissions{ + "[ab]*": {}, `dev\*`: {}, "dba-*": {}, "alice": {}, + }} + w := pc.PatternWarnings() + if len(w) != 2 || !strings.Contains(w[0]+w[1], "[ab]*") || !strings.Contains(w[0]+w[1], `dev\\*`) { + t.Errorf("warnings: %v", w) + } +} diff --git a/host/registry.go b/host/registry.go new file mode 100644 index 0000000..388265a --- /dev/null +++ b/host/registry.go @@ -0,0 +1,200 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "syscall" + "time" +) + +// OwnedUsersFileName is the name of the ownership registry file, stored in the +// same directory as the managed-users state file. +const OwnedUsersFileName = "owned-users.json" + +// OwnerRecord records that ziti-ssh-host created a Linux account for a Ziti +// identity. The registry is the sole authority for modifying or deleting an +// account: accounts without a matching record are never touched. +type OwnerRecord struct { + Identity string `json:"identity"` + UID int `json:"uid"` + Created time.Time `json:"created"` + // Claimed is true when the record was added by "ziti-ssh-host users claim" + // rather than by ziti-ssh-host creating the account. + Claimed bool `json:"claimed,omitempty"` +} + +// OwnerRegistry is a persistent username → OwnerRecord map stored as JSON. +// +// Every operation re-reads the file under an exclusive flock on a sibling lock +// file and writes it back atomically, so the running daemon and the +// "ziti-ssh-host users" admin commands can safely operate concurrently. +// +// Unlike the managed-users state file, the registry is never cleared on +// startup; a record is removed only after its account has been deleted. +type OwnerRegistry struct { + path string +} + +// NewOwnerRegistry returns a registry backed by path. The file is created on +// first write. A missing file is an empty registry; an unreadable or corrupt +// file is an error on every operation (fail closed). +func NewOwnerRegistry(path string) *OwnerRegistry { + return &OwnerRegistry{path: path} +} + +// Path returns the registry file path. +func (r *OwnerRegistry) Path() string { return r.path } + +// Get returns the record for username, if any. +func (r *OwnerRegistry) Get(username string) (OwnerRecord, bool, error) { + var rec OwnerRecord + var found bool + err := r.withLock(func(entries map[string]OwnerRecord) (bool, error) { + rec, found = entries[username] + return false, nil + }) + return rec, found, err +} + +// List returns all records keyed by username, sorted by username. +func (r *OwnerRegistry) List() ([]string, map[string]OwnerRecord, error) { + var out map[string]OwnerRecord + err := r.withLock(func(entries map[string]OwnerRecord) (bool, error) { + out = entries + return false, nil + }) + names := make([]string, 0, len(out)) + for n := range out { + names = append(names, n) + } + sort.Strings(names) + return names, out, err +} + +// Put records ownership of username. If a record already exists for a +// different identity, Put returns an error and leaves it unchanged. +func (r *OwnerRegistry) Put(username string, rec OwnerRecord) error { + return r.withLock(func(entries map[string]OwnerRecord) (bool, error) { + if existing, ok := entries[username]; ok && existing.Identity != rec.Identity { + return false, fmt.Errorf("username %q is already registered to Ziti identity %q", username, existing.Identity) + } + entries[username] = rec + return true, nil + }) +} + +// Remove deletes the record for username. Removing an absent record is not an +// error. +func (r *OwnerRegistry) Remove(username string) error { + return r.withLock(func(entries map[string]OwnerRecord) (bool, error) { + if _, ok := entries[username]; !ok { + return false, nil + } + delete(entries, username) + return true, nil + }) +} + +// withLock loads the registry under an exclusive flock, calls fn, and writes +// the registry back if fn reports a modification. +func (r *OwnerRegistry) withLock(fn func(entries map[string]OwnerRecord) (bool, error)) error { + dir := filepath.Dir(r.path) + if err := os.MkdirAll(dir, 0700); err != nil { + return fmt.Errorf("create registry dir: %w", err) + } + lockPath := r.path + ".lock" + lf, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return fmt.Errorf("open registry lock %q: %w", lockPath, err) + } + defer lf.Close() + if err := syscall.Flock(int(lf.Fd()), syscall.LOCK_EX); err != nil { + return fmt.Errorf("lock registry %q: %w", lockPath, err) + } + defer func() { _ = syscall.Flock(int(lf.Fd()), syscall.LOCK_UN) }() + + entries := make(map[string]OwnerRecord) + data, err := os.ReadFile(r.path) + switch { + case os.IsNotExist(err): + // Empty registry. + case err != nil: + return fmt.Errorf("read registry %q: %w", r.path, err) + case len(data) > 0: + if err := json.Unmarshal(data, &entries); err != nil { + return fmt.Errorf("parse registry %q: %w (refusing to manage accounts until the file is repaired)", r.path, err) + } + } + + modified, err := fn(entries) + if err != nil || !modified { + return err + } + + out, err := json.MarshalIndent(entries, "", " ") + if err != nil { + return fmt.Errorf("encode registry: %w", err) + } + return writeFileAtomic(r.path, append(out, '\n'), 0600) +} + +// writeFileAtomic replaces path with data. It writes to a temp file in the same +// directory, fsyncs, renames, then fsyncs the parent directory — so a crash at +// any point leaves either the old or the new file fully intact. +func writeFileAtomic(path string, data []byte, mode os.FileMode) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0700); err != nil { + return fmt.Errorf("create dir %q: %w", dir, err) + } + tmp, err := os.CreateTemp(dir, "."+filepath.Base(path)+"-tmp-*") + if err != nil { + return fmt.Errorf("create temp file: %w", err) + } + tmpPath := tmp.Name() + fail := func(step string, err error) error { + tmp.Close() + os.Remove(tmpPath) + return fmt.Errorf("%s %q: %w", step, path, err) + } + if _, err := tmp.Write(data); err != nil { + return fail("write", err) + } + if err := tmp.Sync(); err != nil { + return fail("sync", err) + } + if err := tmp.Chmod(mode); err != nil { + return fail("chmod", err) + } + if err := tmp.Close(); err != nil { + os.Remove(tmpPath) + return fmt.Errorf("close temp for %q: %w", path, err) + } + if err := os.Rename(tmpPath, path); err != nil { + os.Remove(tmpPath) + return fmt.Errorf("rename into %q: %w", path, err) + } + if dirF, err := os.Open(dir); err == nil { + _ = dirF.Sync() + dirF.Close() + } + return nil +} diff --git a/host/sessions_test.go b/host/sessions_test.go new file mode 100644 index 0000000..80eeaac --- /dev/null +++ b/host/sessions_test.go @@ -0,0 +1,121 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import ( + "errors" + "io" + "net" + "sync" + "testing" + "time" +) + +func TestEnsureUserForService_CrossServiceConflictRejected(t *testing.T) { + ops := newFakeOps() + m := testManager(t, t.TempDir(), ops, false) + ops2 := IdentityPermissions{Groups: []string{"adm", "sudo"}} + db := IdentityPermissions{Groups: []string{"mysql"}} + + if err := m.EnsureUserForService("alice", "alice", "ssh-ops", ops2); err != nil { + t.Fatal(err) + } + // Different service, different permissions, while ssh-ops is open: reject. + err := m.EnsureUserForService("alice", "alice", "ssh-db", db) + if !errors.Is(err, ErrPermissionConflict) { + t.Fatalf("want ErrPermissionConflict, got %v", err) + } + if ops.called("groups:alice:mysql") { + t.Error("conflicting connection changed the account's groups") + } + // Different service, same permissions (order/duplicates ignored): allowed. + if err := m.EnsureUserForService("alice", "alice", "ssh-other", IdentityPermissions{Groups: []string{"sudo", "adm", "sudo"}}); err != nil { + t.Fatalf("same permissions via another service: %v", err) + } + // Same service as the latest admission with changed config: applied. + if err := m.EnsureUserForService("alice", "alice", "ssh-other", IdentityPermissions{Groups: []string{"adm"}}); err != nil { + t.Fatalf("same service, new config: %v", err) + } + // Once every session is closed, another service is fine. + for i := 0; i < 3; i++ { + if err := m.ReleaseUser("alice"); err != nil { + t.Fatal(err) + } + } + if err := m.EnsureUserForService("alice", "alice", "ssh-db", db); err != nil { + t.Fatalf("after all sessions closed: %v", err) + } +} + +func TestProxyLimited_ClosesExcessConnections(t *testing.T) { + // Target that holds every connection open. + target, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer target.Close() + var held []net.Conn + var mu sync.Mutex + go func() { + for { + c, err := target.Accept() + if err != nil { + return + } + mu.Lock() + held = append(held, c) + mu.Unlock() + } + }() + + front, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + go ProxyLimited(front, target.Addr().String(), nil, nil, 1) + defer front.Close() + + first, err := net.Dial("tcp", front.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer first.Close() + // Wait until the first connection is proxied (holds the only slot). + deadline := time.Now().Add(2 * time.Second) + for { + mu.Lock() + n := len(held) + mu.Unlock() + if n == 1 { + break + } + if time.Now().After(deadline) { + t.Fatal("first connection never reached the target") + } + time.Sleep(10 * time.Millisecond) + } + + second, err := net.Dial("tcp", front.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer second.Close() + _ = second.SetReadDeadline(time.Now().Add(2 * time.Second)) + if _, err := second.Read(make([]byte, 1)); err != io.EOF { + t.Fatalf("second connection not closed by the limit: %v", err) + } +} diff --git a/host/sshd_test.go b/host/sshd_test.go new file mode 100644 index 0000000..21f9800 --- /dev/null +++ b/host/sshd_test.go @@ -0,0 +1,64 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package host + +import "testing" + +func TestPlanSSHDReload(t *testing.T) { + cases := []struct { + name string + st sshdState + want sshdReloadPlan + }{ + { + // Ubuntu 24.04 after any SSH login: ssh.socket (Accept=no) has + // started a long-running ssh.service. Previously skipped entirely, + // so the running sshd never loaded TrustedUserCAKeys. + name: "socket Accept=no with running service", + st: sshdState{ServiceActive: true, SocketActive: true, SocketPerConn: false}, + want: sshdReloadPlan{ReloadService: true, HUPOrphans: true}, + }, + { + name: "socket Accept=no, service not yet started", + st: sshdState{ServiceActive: false, SocketActive: true, SocketPerConn: false}, + want: sshdReloadPlan{ReloadService: false, HUPOrphans: true}, + }, + { + name: "traditional ssh.service only", + st: sshdState{ServiceActive: true, SocketActive: false}, + want: sshdReloadPlan{ReloadService: true, HUPOrphans: true}, + }, + { + // Every connection's sshd has PPID 1: never signal them. + name: "socket Accept=yes (per-connection sshd)", + st: sshdState{ServiceActive: false, SocketActive: true, SocketPerConn: true}, + want: sshdReloadPlan{ReloadService: false, HUPOrphans: false}, + }, + { + name: "sshd not managed by systemd units", + st: sshdState{}, + want: sshdReloadPlan{ReloadService: false, HUPOrphans: true}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := planSSHDReload(tc.st); got != tc.want { + t.Errorf("planSSHDReload(%+v) = %+v, want %+v", tc.st, got, tc.want) + } + }) + } +} diff --git a/internal/mfa/mfa.go b/internal/mfa/mfa.go new file mode 100644 index 0000000..c131aac --- /dev/null +++ b/internal/mfa/mfa.go @@ -0,0 +1,137 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +// Package mfa prompts for Ziti MFA TOTP codes during authentication. +// +// The SDK emits ziti.EventMfaTotpCode from Authenticate when an identity has +// MFA enrolled; without a listener nothing answers and authentication cannot +// complete. Codes are read without echo when the input is a terminal. +package mfa + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "strings" + + "github.com/openziti/edge-api/rest_model" + "github.com/openziti/sdk-golang/ziti" + "golang.org/x/term" +) + +// MaxAttempts is the number of codes accepted before giving up. +const MaxAttempts = 3 + +// ReadFunc reads one code (without the prompt). +type ReadFunc func() (string, error) + +// NewReader returns a ReadFunc for f: hidden input when f is a terminal, +// otherwise one line at a time. +func NewReader(f *os.File) ReadFunc { + fd := int(f.Fd()) + if term.IsTerminal(fd) { + return func() (string, error) { + b, err := term.ReadPassword(fd) + fmt.Fprintln(os.Stderr) + return string(b), err + } + } + return LineReader(f) +} + +// LineReader returns a ReadFunc reading newline-terminated lines from r. +// io.EOF is returned once r is exhausted. +func LineReader(r io.Reader) ReadFunc { + br := bufio.NewReader(r) + return func() (string, error) { + line, err := br.ReadString('\n') + if err != nil && (line == "" || !errors.Is(err, io.EOF)) { + return "", err + } + return line, nil + } +} + +// ReadCode prompts on out and reads a code. Empty input is re-prompted (up to +// MaxAttempts times) unless allowEmpty. A read error (e.g. EOF) is returned +// instead of looping. +func ReadCode(read ReadFunc, out io.Writer, allowEmpty bool) (string, error) { + for i := 0; i < MaxAttempts; i++ { + fmt.Fprint(out, "MFA TOTP code: ") + code, err := read() + if err != nil { + fmt.Fprintln(out) + return "", fmt.Errorf("read MFA code: %w", err) + } + code = strings.TrimSpace(code) + if code != "" || allowEmpty { + return code, nil + } + } + return "", errors.New("no MFA code entered") +} + +// Listener returns an EventMfaTotpCode listener that reads codes with read +// and reports on out. It gives up after MaxAttempts rejected codes or on a +// read error. If read is nil (no terminal available) it only explains why +// authentication cannot complete. +func Listener(read ReadFunc, out io.Writer) func(ziti.Context, *rest_model.AuthQueryDetail, ziti.MfaCodeResponse) { + return func(_ ziti.Context, _ *rest_model.AuthQueryDetail, response ziti.MfaCodeResponse) { + if read == nil { + fmt.Fprintln(out, "This identity requires an MFA TOTP code, but no terminal is available to ask for it.") + return + } + fmt.Fprintln(out, "MFA TOTP required to fully authenticate.") + for i := 0; i < MaxAttempts; i++ { + code, err := ReadCode(read, out, false) + if err != nil { + fmt.Fprintln(out, "MFA aborted:", err) + return + } + if err := response(code); err != nil { + fmt.Fprintln(out, "error verifying MFA TOTP:", err) + continue + } + return + } + fmt.Fprintln(out, "MFA aborted: too many failed attempts") + } +} + +// RegisterTTY registers a listener that prompts and reads codes on the +// controlling terminal (/dev/tty), as ssh(1) does for passwords, so piped +// stdin (or the SSH stream in ProxyCommand mode) is never consumed. Without a +// terminal the listener explains why authentication cannot complete. The +// returned function closes the terminal. +func RegisterTTY(ctx ziti.Context) (closeFn func()) { + tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0) + if err != nil { + ctx.Events().AddMfaTotpCodeListener(Listener(nil, os.Stderr)) + return func() {} + } + read := func() (string, error) { + b, err := term.ReadPassword(int(tty.Fd())) + fmt.Fprintln(tty) + return string(b), err + } + if !term.IsTerminal(int(tty.Fd())) { + read = LineReader(tty) + } + ctx.Events().AddMfaTotpCodeListener(Listener(read, tty)) + return func() { _ = tty.Close() } +} diff --git a/internal/mfa/mfa_test.go b/internal/mfa/mfa_test.go new file mode 100644 index 0000000..afa56d9 --- /dev/null +++ b/internal/mfa/mfa_test.go @@ -0,0 +1,83 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package mfa + +import ( + "bytes" + "errors" + "strings" + "testing" +) + +func TestReadCode_EOFStops(t *testing.T) { + // Previously an exhausted stdin made the prompt loop forever. + var out bytes.Buffer + if _, err := ReadCode(LineReader(strings.NewReader("")), &out, false); err == nil { + t.Fatal("EOF accepted") + } +} + +func TestReadCode_RetriesEmptyThenGivesUp(t *testing.T) { + var out bytes.Buffer + code, err := ReadCode(LineReader(strings.NewReader("\n \n123456\n")), &out, false) + if err != nil || code != "123456" { + t.Fatalf("got %q, %v", code, err) + } + if _, err := ReadCode(LineReader(strings.NewReader("\n\n\n\n")), &out, false); err == nil { + t.Fatal("empty input accepted") + } + if code, err := ReadCode(LineReader(strings.NewReader("\n")), &out, true); err != nil || code != "" { + t.Fatalf("allowEmpty: %q, %v", code, err) + } +} + +func TestListener_StopsAfterMaxAttempts(t *testing.T) { + var out bytes.Buffer + calls := 0 + respond := func(code string) error { calls++; return errors.New("invalid") } + Listener(LineReader(strings.NewReader("1\n2\n3\n4\n5\n")), &out)(nil, nil, respond) + if calls != MaxAttempts { + t.Fatalf("response called %d times, want %d", calls, MaxAttempts) + } + if !strings.Contains(out.String(), "too many failed attempts") { + t.Errorf("output: %q", out.String()) + } +} + +func TestListener_AcceptsValidCode(t *testing.T) { + var out bytes.Buffer + var got []string + respond := func(code string) error { + got = append(got, code) + if code == "222222" { + return nil + } + return errors.New("invalid") + } + Listener(LineReader(strings.NewReader("111111\n222222\n333333\n")), &out)(nil, nil, respond) + if len(got) != 2 || got[1] != "222222" { + t.Fatalf("codes sent: %v", got) + } +} + +func TestListener_NoTerminalExplains(t *testing.T) { + var out bytes.Buffer + Listener(nil, &out)(nil, nil, func(string) error { t.Fatal("response called"); return nil }) + if !strings.Contains(out.String(), "no terminal") { + t.Errorf("output: %q", out.String()) + } +} diff --git a/internal/oidc/flow_test.go b/internal/oidc/flow_test.go new file mode 100644 index 0000000..b787475 --- /dev/null +++ b/internal/oidc/flow_test.go @@ -0,0 +1,221 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package oidc + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + jose "github.com/go-jose/go-jose/v4" +) + +// fakeIdP is a minimal OpenID provider: discovery, an authorize endpoint +// that redirects straight back with a code, a token endpoint and its keys. +type fakeIdP struct { + t *testing.T + srv *httptest.Server + pub *rsa.PublicKey // published in the JWKS + + mu sync.Mutex + signer *rsa.PrivateKey // signs ID tokens (normally matches pub) + tokenIssuer string // "iss" in the ID token (normally srv.URL) + tamperState bool + challenge string + challengeMeth string + verifierOK bool + secretSeen string +} + +func newFakeIdP(t *testing.T) *fakeIdP { + t.Helper() + k, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + f := &fakeIdP{t: t, pub: &k.PublicKey, signer: k} + mux := http.NewServeMux() + mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{ + "issuer": f.srv.URL, + "authorization_endpoint": f.srv.URL + "/authorize", + "token_endpoint": f.srv.URL + "/token", + "jwks_uri": f.srv.URL + "/jwks", + "response_types_supported": []string{"code"}, + "subject_types_supported": []string{"public"}, + "id_token_signing_alg_values_supported": []string{"RS256"}, + "code_challenge_methods_supported": []string{"S256"}, + }) + }) + mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + f.mu.Lock() + f.challenge, f.challengeMeth = q.Get("code_challenge"), q.Get("code_challenge_method") + state := q.Get("state") + if f.tamperState { + state += "x" + } + f.mu.Unlock() + http.Redirect(w, r, q.Get("redirect_uri")+"?code=c1&state="+url.QueryEscape(state), http.StatusFound) + }) + mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + f.mu.Lock() + defer f.mu.Unlock() + if v := r.PostForm.Get("code_verifier"); v != "" { + sum := sha256.Sum256([]byte(v)) + f.verifierOK = base64.RawURLEncoding.EncodeToString(sum[:]) == f.challenge + } + if _, secret, ok := r.BasicAuth(); ok { + f.secretSeen = secret + } else if s := r.PostForm.Get("client_secret"); s != "" { + f.secretSeen = s + } + iss := f.tokenIssuer + if iss == "" { + iss = f.srv.URL + } + now := time.Now() + claims, _ := json.Marshal(map[string]any{ + "iss": iss, "sub": "alice", "aud": []string{"ziti-ssh"}, + "iat": now.Unix(), "exp": now.Add(time.Hour).Unix(), + }) + signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, + Key: jose.JSONWebKey{Key: f.signer, KeyID: "k1"}}, (&jose.SignerOptions{}).WithType("JWT")) + if err != nil { + f.t.Error(err) + return + } + jws, err := signer.Sign(claims) + if err != nil { + f.t.Error(err) + return + } + idToken, _ := jws.CompactSerialize() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "access_token": "access-token-1", "token_type": "Bearer", + "expires_in": 3600, "id_token": idToken, + }) + }) + mux.HandleFunc("/jwks", func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{ + {Key: f.pub, KeyID: "k1", Algorithm: "RS256", Use: "sig"}, + }}) + }) + f.srv = httptest.NewServer(mux) + t.Cleanup(f.srv.Close) + return f +} + +// runWithBrowser runs runFlow, driving the login with an HTTP client that +// keeps cookies and follows redirects. It returns the token, the flow error +// and the HTTP status the "browser" saw on the callback page. +func runWithBrowser(t *testing.T, p FlowParams, timeout time.Duration) (string, error, int) { + t.Helper() + oldBrowse, oldTimeout := browse, flowTimeout + t.Cleanup(func() { browse, flowTimeout = oldBrowse, oldTimeout }) + flowTimeout = timeout + + status := make(chan int, 1) + browse = func(u string) { + go func() { + jar, _ := cookiejar.New(nil) + resp, err := (&http.Client{Jar: jar, Timeout: 10 * time.Second}).Get(u) + if err != nil { + status <- -1 + return + } + resp.Body.Close() + status <- resp.StatusCode + }() + } + token, err := runFlow(context.Background(), p) + select { + case s := <-status: + return token, err, s + case <-time.After(5 * time.Second): + return token, err, 0 + } +} + +func TestRunFlow_PKCESuccess(t *testing.T) { + idp := newFakeIdP(t) + token, err, status := runWithBrowser(t, FlowParams{Issuer: idp.srv.URL, ClientID: "ziti-ssh", CallbackPort: freePort(t)}, 20*time.Second) + if err != nil || token != "access-token-1" { + t.Fatalf("token %q, err %v (callback status %d)", token, err, status) + } + idp.mu.Lock() + defer idp.mu.Unlock() + if idp.challengeMeth != "S256" || !idp.verifierOK { + t.Errorf("PKCE not used correctly: method %q, verifier ok %v", idp.challengeMeth, idp.verifierOK) + } +} + +func TestRunFlow_ClientSecretSuccess(t *testing.T) { + idp := newFakeIdP(t) + token, err, _ := runWithBrowser(t, FlowParams{Issuer: idp.srv.URL, ClientID: "ziti-ssh", ClientSecret: "s3cret", CallbackPort: freePort(t)}, 20*time.Second) + if err != nil || token != "access-token-1" { + t.Fatalf("token %q, err %v", token, err) + } + idp.mu.Lock() + defer idp.mu.Unlock() + if idp.secretSeen != "s3cret" || idp.challenge != "" { + t.Errorf("secret %q, challenge %q", idp.secretSeen, idp.challenge) + } +} + +// A rejected callback must not yield a token; the flow keeps waiting (so a +// forged callback cannot end a real login) until it times out. +func TestRunFlow_RejectedCallbacks(t *testing.T) { + other, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal(err) + } + cases := map[string]func(f *fakeIdP){ + "tampered state": func(f *fakeIdP) { f.tamperState = true }, + "bad signature": func(f *fakeIdP) { f.signer = other }, + "wrong issuer": func(f *fakeIdP) { f.tokenIssuer = "https://evil.example" }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + idp := newFakeIdP(t) + mutate(idp) + token, err, status := runWithBrowser(t, FlowParams{Issuer: idp.srv.URL, ClientID: "ziti-ssh", CallbackPort: freePort(t)}, 3*time.Second) + if err == nil || token != "" { + t.Fatalf("accepted: token %q, err %v", token, err) + } + if !strings.Contains(err.Error(), "timed out") { + t.Errorf("err = %v, want timeout", err) + } + if status == http.StatusOK { + t.Errorf("callback page returned 200") + } + }) + } +} diff --git a/internal/oidc/oidc.go b/internal/oidc/oidc.go index e3d595f..e289b05 100644 --- a/internal/oidc/oidc.go +++ b/internal/oidc/oidc.go @@ -18,8 +18,10 @@ // by ziti-ssh and ziti-scp to satisfy ext-jwt-signer policies on a Ziti // controller. // -// When an OIDC issuer is configured, the flow opens a temporary localhost HTTP -// server, opens the browser to the authorization URL, and waits for the +// When an OIDC issuer is configured, the flow first claims the callback port on +// both loopback addresses (127.0.0.1 and ::1) — refusing to continue if +// another process already holds it, since that process would receive the +// login — then opens the browser to the authorization URL and waits for the // identity provider to redirect back with an authorization code. The code is // exchanged for an access token which is added to the Ziti context credentials // before Authenticate() is called. @@ -32,15 +34,19 @@ import ( "crypto/rand" "errors" "fmt" + "io" "log/slog" + "net" "net/http" + "os" + "os/exec" + "runtime" "strings" "time" "github.com/gorilla/securecookie" ziti "github.com/openziti/sdk-golang/ziti" "github.com/zitadel/oidc/v3/pkg/client/rp" - "github.com/zitadel/oidc/v3/pkg/client/rp/cli" httphelper "github.com/zitadel/oidc/v3/pkg/http" "github.com/zitadel/oidc/v3/pkg/oidc" ) @@ -52,9 +58,17 @@ const ( callbackPath = "/auth/callback" defaultAuthScopes = "openid profile email" - flowTimeout = 2 * time.Minute ) +// flowTimeout bounds the whole browser flow. A callback that fails (bad state, +// bad token) does not end the flow early, so a forged request from another +// local process cannot abort a legitimate login. (A variable for tests.) +var flowTimeout = 2 * time.Minute + +// browse opens the login URL for the user (a variable so tests can drive the +// flow with an HTTP client instead of a browser). +var browse = func(url string) { openBrowser(url, os.Stderr, startCommand) } + // FlowParams holds all parameters required to run the OIDC browser flow. type FlowParams struct { Issuer string @@ -102,6 +116,19 @@ func runFlow(ctx context.Context, p FlowParams) (string, error) { p.CallbackPort = DefaultCallbackPort } + // Claim the callback port before contacting the identity provider or + // opening the browser. If another process (e.g. another local user) held + // it, the browser would deliver the login to that process. + listeners, err := listenLoopback(p.CallbackPort) + if err != nil { + return "", err + } + defer func() { + for _, l := range listeners { + _ = l.Close() + } + }() + redirectURL := fmt.Sprintf("http://localhost:%s%s", p.CallbackPort, callbackPath) cookieHandler := httphelper.NewCookieHandler( @@ -144,7 +171,8 @@ func runFlow(ctx context.Context, p FlowParams) (string, error) { state string, party rp.RelyingParty, ) { - tokenChan <- tokens + // Only the first callback is used; later ones must not block. + offer(tokenChan, tokens) _, _ = w.Write([]byte( "" + "" + @@ -156,24 +184,22 @@ func runFlow(ctx context.Context, p FlowParams) (string, error) { mux := http.NewServeMux() mux.Handle("/login", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - rp.AuthURLHandler(func() string { - b := make([]byte, 16) - _, _ = rand.Read(b) - return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) - }, relyingParty)(w, r) + rp.AuthURLHandler(rand.Text, relyingParty)(w, r) })) mux.Handle(callbackPath, rp.CodeExchangeHandler(callback, relyingParty)) server := &http.Server{ - Addr: ":" + p.CallbackPort, - Handler: mux, + Handler: mux, + ReadHeaderTimeout: 10 * time.Second, } - go func() { - if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { - slog.Error("OIDC callback server error", "err", err) - } - }() + for _, l := range listeners { + go func(l net.Listener) { + if err := server.Serve(l); err != nil && !errors.Is(err, http.ErrServerClosed) { + slog.Error("OIDC callback server error", "addr", l.Addr(), "err", err) + } + }(l) + } go func() { <-flowCtx.Done() @@ -189,7 +215,7 @@ func runFlow(ctx context.Context, p FlowParams) (string, error) { "callback_port", p.CallbackPort, "timeout", flowTimeout, ) - cli.OpenBrowser("http://localhost:" + p.CallbackPort + "/login") + browse("http://localhost:" + p.CallbackPort + "/login") select { case tokens := <-tokenChan: @@ -199,3 +225,83 @@ func runFlow(ctx context.Context, p FlowParams) (string, error) { return "", fmt.Errorf("OIDC authentication timed out after %s", flowTimeout) } } + +// listenLoopback binds the callback port on 127.0.0.1 and, when the host has +// an IPv6 loopback, on ::1. Browsers may resolve "localhost" to either, so +// both must be held by this process. It fails if either address is already in +// use. It never binds a non-loopback address. +func listenLoopback(port string) ([]net.Listener, error) { + l4, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", port)) + if err != nil { + return nil, callbackPortError(port, "127.0.0.1", err) + } + if !ipv6LoopbackAvailable() { + slog.Debug("IPv6 loopback unavailable; OIDC callback listening on 127.0.0.1 only") + return []net.Listener{l4}, nil + } + l6, err := net.Listen("tcp6", net.JoinHostPort("::1", port)) + if err != nil { + _ = l4.Close() + return nil, callbackPortError(port, "::1", err) + } + return []net.Listener{l4, l6}, nil +} + +// ipv6LoopbackAvailable reports whether ::1 can be bound at all. If it cannot, +// no other process can bind it either, so listening on IPv4 only is safe. +func ipv6LoopbackAvailable() bool { + l, err := net.Listen("tcp6", "[::1]:0") + if err != nil { + return false + } + _ = l.Close() + return true +} + +func callbackPortError(port, addr string, err error) error { + return fmt.Errorf("OIDC callback port %s on %s is unavailable (%v); refusing to continue because "+ + "another process holding it would receive the login. Stop that process or set a different "+ + "callback port (oidc.callback_port) that is also registered with the identity provider", port, addr, err) +} + +// startCommand starts an external program without waiting for it to finish. +func startCommand(name string, args ...string) error { + cmd := exec.Command(name, args...) + if err := cmd.Start(); err != nil { + return err + } + go func() { _ = cmd.Wait() }() + return nil +} + +// openBrowser prints the login URL to w first, so it is always available on +// headless machines, then tries to open it in the user's browser. Failure to +// launch a browser is reported but is not fatal. +func openBrowser(url string, w io.Writer, start func(name string, args ...string) error) { + _, _ = fmt.Fprintf(w, "To sign in, open this URL in a browser (attempting to open it for you):\n %s\n", url) + + var err error + switch runtime.GOOS { + case "linux", "freebsd", "openbsd", "netbsd": + err = start("xdg-open", url) + case "darwin": + err = start("open", url) + case "windows": + err = start("rundll32", "url.dll,FileProtocolHandler", url) + default: + err = fmt.Errorf("unsupported platform %s", runtime.GOOS) + } + if err != nil { + _, _ = fmt.Fprintf(w, "Could not open a browser (%v); open the URL above manually.\n", err) + } +} + +// offer sends v on ch without blocking and reports whether it was delivered. +func offer[T any](ch chan T, v T) bool { + select { + case ch <- v: + return true + default: + return false + } +} diff --git a/internal/oidc/oidc_test.go b/internal/oidc/oidc_test.go new file mode 100644 index 0000000..e46e6ea --- /dev/null +++ b/internal/oidc/oidc_test.go @@ -0,0 +1,183 @@ +/* + Copyright NetFoundry Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package oidc + +import ( + "bytes" + "context" + "errors" + "net" + "strconv" + "strings" + "testing" +) + +// freePort returns a TCP port that is currently free on 127.0.0.1. +func freePort(t *testing.T) string { + t.Helper() + l, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer l.Close() + return strconv.Itoa(l.Addr().(*net.TCPAddr).Port) +} + +func closeAll(ls []net.Listener) { + for _, l := range ls { + l.Close() + } +} + +func TestListenLoopback_BindsOnlyLoopback(t *testing.T) { + ls, err := listenLoopback(freePort(t)) + if err != nil { + t.Fatal(err) + } + defer closeAll(ls) + + want := 1 + if ipv6LoopbackAvailable() { + want = 2 + } + if len(ls) != want { + t.Fatalf("got %d listeners, want %d", len(ls), want) + } + for _, l := range ls { + ip := l.Addr().(*net.TCPAddr).IP + if !ip.IsLoopback() { + t.Errorf("listener on non-loopback address %v", l.Addr()) + } + } +} + +func TestListenLoopback_RefusesWhenIPv4Taken(t *testing.T) { + port := freePort(t) + squatter, err := net.Listen("tcp4", "127.0.0.1:"+port) + if err != nil { + t.Fatal(err) + } + defer squatter.Close() + + ls, err := listenLoopback(port) + if err == nil { + closeAll(ls) + t.Fatal("listenLoopback succeeded although 127.0.0.1 port is held by another listener") + } + if !strings.Contains(err.Error(), "refusing to continue") { + t.Errorf("unexpected error: %v", err) + } +} + +func TestListenLoopback_RefusesWhenIPv6Taken(t *testing.T) { + if !ipv6LoopbackAvailable() { + t.Skip("no IPv6 loopback on this host") + } + port := freePort(t) + squatter, err := net.Listen("tcp6", "[::1]:"+port) + if err != nil { + t.Skipf("cannot bind [::1]:%s for the test: %v", port, err) + } + defer squatter.Close() + + ls, err := listenLoopback(port) + if err == nil { + closeAll(ls) + t.Fatal("listenLoopback succeeded although ::1 port is held by another listener") + } + // The IPv4 listener must have been released on failure. + l, err := net.Listen("tcp4", "127.0.0.1:"+port) + if err != nil { + t.Fatalf("127.0.0.1:%s not released after failure: %v", port, err) + } + l.Close() +} + +func TestOpenBrowser_PrintsURLAndSurvivesFailure(t *testing.T) { + var out bytes.Buffer + const url = "http://localhost:63275/login" + openBrowser(url, &out, func(string, ...string) error { return errors.New("no display") }) + + got := out.String() + urlAt := strings.Index(got, url) + failAt := strings.Index(got, "open the URL above manually") + if urlAt < 0 || failAt < 0 || urlAt > failAt { + t.Fatalf("URL must be printed before the failure notice; output:\n%s", got) + } +} + +func TestOpenBrowser_Success(t *testing.T) { + var out bytes.Buffer + var called string + openBrowser("http://localhost:1/login", &out, func(name string, _ ...string) error { called = name; return nil }) + if called == "" { + t.Error("browser launcher not called") + } + if strings.Contains(out.String(), "manually") { + t.Errorf("failure notice printed on success:\n%s", out.String()) + } +} + +func TestOffer_DoesNotBlock(t *testing.T) { + ch := make(chan int, 1) + if !offer(ch, 1) { + t.Fatal("first value not delivered") + } + if offer(ch, 2) { + t.Fatal("second value delivered into a full channel") + } + if v := <-ch; v != 1 { + t.Fatalf("got %d, want the first value", v) + } +} + +func TestRunFlow_RefusesBeforeContactingIssuerWhenPortTaken(t *testing.T) { + port := freePort(t) + squatter, err := net.Listen("tcp4", "127.0.0.1:"+port) + if err != nil { + t.Fatal(err) + } + defer squatter.Close() + + // example.invalid can never resolve (RFC 2606). If the flow contacted the + // issuer first, the error would be about discovery/DNS instead. + _, err = runFlow(context.Background(), FlowParams{ + Issuer: "https://example.invalid", + ClientID: "test", + CallbackPort: port, + }) + if err == nil || !strings.Contains(err.Error(), "refusing to continue") { + t.Fatalf("want callback-port refusal before issuer discovery, got: %v", err) + } +} + +func TestRunFlow_ReleasesPortWhenIssuerFails(t *testing.T) { + port := freePort(t) + _, err := runFlow(context.Background(), FlowParams{ + Issuer: "https://example.invalid", + ClientID: "test", + CallbackPort: port, + }) + if err == nil || strings.Contains(err.Error(), "refusing to continue") { + t.Fatalf("want an issuer discovery error, got: %v", err) + } + l, err := net.Listen("tcp4", "127.0.0.1:"+port) + if err != nil { + t.Fatalf("callback port not released after a failed flow: %v", err) + } + l.Close() +} diff --git a/packaging/nfpm-ziti-scp.yaml b/packaging/nfpm-ziti-scp.yaml index 9d91225..b03ad71 100644 --- a/packaging/nfpm-ziti-scp.yaml +++ b/packaging/nfpm-ziti-scp.yaml @@ -19,7 +19,7 @@ depends: contents: - src: "dist/binaries/ziti-scp" - dst: /usr/local/bin/ziti-scp + dst: /usr/bin/ziti-scp file_info: mode: 0755 diff --git a/packaging/nfpm-ziti-ssh-ca.yaml b/packaging/nfpm-ziti-ssh-ca.yaml index 24865d4..3b338e9 100644 --- a/packaging/nfpm-ziti-ssh-ca.yaml +++ b/packaging/nfpm-ziti-ssh-ca.yaml @@ -18,7 +18,7 @@ depends: contents: - src: "dist/binaries/ziti-ssh-ca" - dst: /usr/local/bin/ziti-ssh-ca + dst: /usr/bin/ziti-ssh-ca file_info: mode: 0755 - src: packaging/systemd/ziti-ssh-ca.service @@ -32,3 +32,5 @@ contents: scripts: postinstall: packaging/scripts/postinstall-ziti-ssh-ca.sh + preremove: packaging/scripts/preremove-ziti-ssh-ca.sh + postremove: packaging/scripts/postremove-ziti-ssh-ca.sh diff --git a/packaging/nfpm-ziti-ssh-host.yaml b/packaging/nfpm-ziti-ssh-host.yaml index 6b14792..48c92a7 100644 --- a/packaging/nfpm-ziti-ssh-host.yaml +++ b/packaging/nfpm-ziti-ssh-host.yaml @@ -20,7 +20,7 @@ depends: contents: - src: "dist/binaries/ziti-ssh-host" - dst: /usr/local/bin/ziti-ssh-host + dst: /usr/bin/ziti-ssh-host file_info: mode: 0755 - src: packaging/systemd/ziti-ssh-host.service @@ -34,3 +34,5 @@ contents: scripts: postinstall: packaging/scripts/postinstall-ziti-ssh-host.sh + preremove: packaging/scripts/preremove-ziti-ssh-host.sh + postremove: packaging/scripts/postremove-ziti-ssh-host.sh diff --git a/packaging/nfpm-ziti-ssh.yaml b/packaging/nfpm-ziti-ssh.yaml index 25fd68e..003b698 100644 --- a/packaging/nfpm-ziti-ssh.yaml +++ b/packaging/nfpm-ziti-ssh.yaml @@ -18,7 +18,7 @@ depends: contents: - src: "dist/binaries/ziti-ssh" - dst: /usr/local/bin/ziti-ssh + dst: /usr/bin/ziti-ssh file_info: mode: 0755 diff --git a/packaging/scripts/postinstall-ziti-ssh-ca.sh b/packaging/scripts/postinstall-ziti-ssh-ca.sh index 1265273..8a3ea1c 100755 --- a/packaging/scripts/postinstall-ziti-ssh-ca.sh +++ b/packaging/scripts/postinstall-ziti-ssh-ca.sh @@ -1,8 +1,14 @@ #!/bin/sh set -e -if [ ! -f /etc/ziti-ssh-ca/env ]; then - cat > /etc/ziti-ssh-ca/env <<'ENVEOF' +# Paths (overridable only to allow testing this script outside a real install). +CONF_DIR="${ZITI_SSH_CA_CONF_DIR:-/etc/ziti-ssh-ca}" +DROPIN_DIR="${ZITI_SSH_CA_DROPIN_DIR:-/etc/systemd/system/ziti-ssh-ca.service.d}" +DROPIN_FILE="${DROPIN_DIR}/10-controller-user.conf" +DROPIN_MARKER="# Managed by the ziti-ssh-ca package" + +if [ ! -f "${CONF_DIR}/env" ]; then + cat > "${CONF_DIR}/env" <<'ENVEOF' # ziti-ssh-ca environment configuration # Uncomment and set these variables before starting the service. #ZITI_IDENTITY=/etc/ziti-ssh-ca/identity.json @@ -25,7 +31,104 @@ if [ ! -f /etc/ziti-ssh-ca/env ]; then # Certificate validity duration (default 5m). Examples: 5m, 15m, 1h. #ZITI_CERT_TTL=5m ENVEOF - chmod 640 /etc/ziti-ssh-ca/env + chmod 640 "${CONF_DIR}/env" +fi + +# --------------------------------------------------------------------------- +# Run as the Ziti controller's service user. +# +# ziti-ssh-ca reads the controller's intermediate CA key, which is owned by the +# controller's service user with mode 0600, so it must run as that same user. +# That user differs between installs: the openziti-controller package (v2+) +# uses "ziti-controller", other deployments use e.g. "ziti". Detect it and +# write a systemd drop-in that overrides the unit's default (User=ziti). +# --------------------------------------------------------------------------- + +controller_user() { + # 1) The controller's systemd unit, if it names a static user. + if command -v systemctl >/dev/null 2>&1; then + u=$(systemctl show -p User --value ziti-controller.service 2>/dev/null || true) + if [ -n "${u}" ]; then + echo "${u}" + return 0 + fi + fi + # 2) The owner of a running "ziti controller run" process. + if command -v pgrep >/dev/null 2>&1; then + pid=$(pgrep -f -o 'ziti controller run' 2>/dev/null || true) + if [ -n "${pid}" ]; then + # Resolve by UID: "ps -o user=" truncates long names + # (e.g. "ziti-controller" becomes "ziti-co+"). + uid=$(ps -o uid= -p "${pid}" 2>/dev/null | tr -d ' ' || true) + u="" + if [ -n "${uid}" ]; then + u=$(getent passwd "${uid}" 2>/dev/null | cut -d: -f1 || true) + fi + if [ -n "${u}" ]; then + echo "${u}" + return 0 + fi + fi + fi + return 1 +} + +# An administrator's own override (e.g. "systemctl edit ziti-ssh-ca") wins: +# any drop-in other than ours that sets User= is left alone. +admin_override() { + for f in "${DROPIN_DIR}"/*.conf; do + [ -f "${f}" ] || continue + [ "${f}" = "${DROPIN_FILE}" ] && continue + if grep -q '^[[:space:]]*User=' "${f}"; then + echo "${f}" + return 0 + fi + done + return 1 +} + +if override=$(admin_override); then + echo "ziti-ssh-ca: keeping existing service user override in ${override}" >&2 +elif [ -f "${DROPIN_FILE}" ] && ! grep -q "^${DROPIN_MARKER}" "${DROPIN_FILE}"; then + echo "ziti-ssh-ca: ${DROPIN_FILE} was edited locally; leaving it unchanged" >&2 +elif svc_user=$(controller_user) && getent passwd "${svc_user}" >/dev/null 2>&1; then + svc_group=$(id -gn "${svc_user}") + mkdir -p "${DROPIN_DIR}" + cat > "${DROPIN_FILE}" <&2 + fi + echo "ziti-ssh-ca: will run as the Ziti controller's user '${svc_user}' (${DROPIN_FILE})" >&2 +else + cat >&2 < + Group= + + sudo chown : ${CONF_DIR} +EOF fi if [ -d /run/systemd/system ]; then diff --git a/packaging/scripts/postinstall-ziti-ssh-host.sh b/packaging/scripts/postinstall-ziti-ssh-host.sh index 9c488c4..8ad0b7b 100755 --- a/packaging/scripts/postinstall-ziti-ssh-host.sh +++ b/packaging/scripts/postinstall-ziti-ssh-host.sh @@ -26,7 +26,8 @@ if [ ! -f /etc/ziti-ssh-host/env ]; then # SUDOERS — optional sudo rule granted to per-identity users on connect. # Only applies when ZITI_SSH_MODE=per-identity. -# Leave unset for no sudo access. The rule is written to /etc/sudoers.d/. +# Leave unset for no sudo access. The rule is written to +# /etc/sudoers.d/ziti-ssh-host-. # Example (full passwordless sudo): #ZITI_SUDOERS_RULE=ALL=(ALL) NOPASSWD:ALL @@ -34,10 +35,41 @@ if [ ! -f /etc/ziti-ssh-host/env ]; then # false (default): persistent users — account remains after disconnect. # true: ephemeral users — account removed when last session closes. #ZITI_USER_CLEANUP=false + +# TERMINATE_ON_DISCONNECT — with USER_CLEANUP=false, end all of the user's +# processes (nohup, tmux, systemd user services), remove their crontab and at +# jobs, and expire the account until its next authorized connection when the +# last session closes, keeping the account and home directory. Needed for revoked identities to lose +# running processes. No effect when USER_CLEANUP=true (deletion already ends them). +#ZITI_TERMINATE_ON_DISCONNECT=false + +# How often to check the controller for service/config changes (default 30s, +# minimum 5s); a changed ziti-ssh-host.v1 config applies within this interval. +#ZITI_SERVICE_REFRESH=30s + +# Maximum concurrent connections per service (default 128); further +# connections are closed immediately. +#ZITI_MAX_CONNECTIONS=128 + +# Host grant policy — what each service's ziti-ssh-host.v1 config may grant here. +# ALLOW_SUDOERS: services whose config may set sudoers_rule (comma list, or *). +#ZITI_ALLOW_SUDOERS=ssh-ops +# ALLOW_GROUPS: privileged groups (root, sudo, admin, wheel, docker, lxd, disk, +# shadow, libvirt) a service's config may grant, as : or *:. +#ZITI_ALLOW_GROUPS=ssh-ops:sudo +# RESTRICT_GROUPS: true = config may grant only groups listed in ALLOW_GROUPS. +#ZITI_RESTRICT_GROUPS=false ENVEOF chmod 640 /etc/ziti-ssh-host/env fi +# Accounts in this group may only log in with a CA certificate (the sshd +# drop-in written by "ziti-ssh-host enroll" disables authorized_keys for them). +# Add the shared account to it in shared mode: usermod -aG ziti-ssh-managed +if command -v groupadd >/dev/null 2>&1; then + groupadd -f --system ziti-ssh-managed +fi + if [ -d /run/systemd/system ]; then systemctl daemon-reload || true fi diff --git a/packaging/scripts/postremove-ziti-ssh-ca.sh b/packaging/scripts/postremove-ziti-ssh-ca.sh new file mode 100644 index 0000000..3c29928 --- /dev/null +++ b/packaging/scripts/postremove-ziti-ssh-ca.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Post-remove for ziti-ssh-ca. +# +# purge (deb): remove the systemd drop-in the postinstall wrote to run the CA +# as the controller's user — only if it still carries the package's marker +# (a hand-edited drop-in is left alone). /etc/ziti-ssh-ca (identity, env) +# is kept. +set -e + +DROPIN_DIR=/etc/systemd/system/ziti-ssh-ca.service.d +DROPIN_FILE="$DROPIN_DIR/10-controller-user.conf" + +if [ "$1" = "purge" ]; then + if [ -f "$DROPIN_FILE" ] && grep -q '^# Managed by the ziti-ssh-ca package' "$DROPIN_FILE"; then + rm -f "$DROPIN_FILE" + rmdir "$DROPIN_DIR" 2>/dev/null || true + fi +fi + +if [ -d /run/systemd/system ]; then + systemctl daemon-reload || true +fi diff --git a/packaging/scripts/postremove-ziti-ssh-host.sh b/packaging/scripts/postremove-ziti-ssh-host.sh new file mode 100644 index 0000000..78858f3 --- /dev/null +++ b/packaging/scripts/postremove-ziti-ssh-host.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# Post-remove for ziti-ssh-host. +# +# purge (deb): stop sshd trusting the Ziti CA by removing the two files +# ziti-ssh-host writes (the sshd drop-in and the CA public key) and +# reloading sshd. Identity files, /etc/ziti-ssh-host/env, the account +# ownership registry and any Linux accounts are kept. +# rpm has no purge: after "rpm -e", remove those two files manually if the +# host should stop trusting the CA (see docs/provisioning.md). +set -e + +SSHD_DROPIN=/etc/ssh/sshd_config.d/ziti-ssh.conf +CA_PUBKEY=/etc/ssh/ziti_ca.pub + +if [ "$1" = "purge" ]; then + rm -f "$SSHD_DROPIN" "$CA_PUBKEY" + if [ -d /run/systemd/system ]; then + if systemctl is-active --quiet ssh.service; then + systemctl reload ssh.service || true + elif systemctl is-active --quiet sshd.service; then + systemctl reload sshd.service || true + fi + fi + # Leftover top-level sshd listeners (see host.ReloadSSHD). + pkill -HUP -P 1 -x sshd 2>/dev/null || true +fi + +if [ -d /run/systemd/system ]; then + systemctl daemon-reload || true +fi diff --git a/packaging/scripts/preremove-ziti-ssh-ca.sh b/packaging/scripts/preremove-ziti-ssh-ca.sh new file mode 100644 index 0000000..69bafe7 --- /dev/null +++ b/packaging/scripts/preremove-ziti-ssh-ca.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Pre-remove for ziti-ssh-ca: stop and disable the service when the package is +# removed (deb "remove", rpm "0"). Upgrades leave the service as it is. +set -e + +case "$1" in + remove|0) + if [ -d /run/systemd/system ]; then + systemctl disable --now ziti-ssh-ca.service >/dev/null 2>&1 || true + fi + ;; +esac diff --git a/packaging/scripts/preremove-ziti-ssh-host.sh b/packaging/scripts/preremove-ziti-ssh-host.sh new file mode 100644 index 0000000..c548af2 --- /dev/null +++ b/packaging/scripts/preremove-ziti-ssh-host.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Pre-remove for ziti-ssh-host: stop and disable the service when the package is +# removed (deb "remove", rpm "0"). Upgrades leave the service as it is. +set -e + +case "$1" in + remove|0) + if [ -d /run/systemd/system ]; then + systemctl disable --now ziti-ssh-host.service >/dev/null 2>&1 || true + fi + ;; +esac diff --git a/packaging/systemd/ziti-ssh-ca.service b/packaging/systemd/ziti-ssh-ca.service index bdf5e81..9d96dea 100644 --- a/packaging/systemd/ziti-ssh-ca.service +++ b/packaging/systemd/ziti-ssh-ca.service @@ -8,7 +8,7 @@ Wants=network-online.target Type=notify User=ziti EnvironmentFile=/etc/ziti-ssh-ca/env -ExecStart=/usr/local/bin/ziti-ssh-ca +ExecStart=/usr/bin/ziti-ssh-ca Restart=on-failure RestartSec=5 diff --git a/packaging/systemd/ziti-ssh-host.service b/packaging/systemd/ziti-ssh-host.service index 44826c9..d750a3f 100644 --- a/packaging/systemd/ziti-ssh-host.service +++ b/packaging/systemd/ziti-ssh-host.service @@ -11,7 +11,7 @@ Type=notify # (mode 0700) and is only readable by root. User=root EnvironmentFile=-/etc/ziti-ssh-host/env -ExecStart=/usr/local/bin/ziti-ssh-host run +ExecStart=/usr/bin/ziti-ssh-host run Restart=on-failure RestartSec=5 diff --git a/scripts/Dockerfile.packages b/scripts/Dockerfile.packages index 21e9de0..bd83e86 100644 --- a/scripts/Dockerfile.packages +++ b/scripts/Dockerfile.packages @@ -1,4 +1,5 @@ -FROM golang:1.25-bookworm +# Pinned by digest (multi-arch index); Dependabot (docker ecosystem) updates it. +FROM golang:1.26-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 ARG VERSION=0.1.0 ARG FORMAT=deb,rpm diff --git a/scripts/build-deb.sh b/scripts/build-deb.sh deleted file mode 100755 index c2c409b..0000000 --- a/scripts/build-deb.sh +++ /dev/null @@ -1,411 +0,0 @@ -#!/usr/bin/env bash -# build-deb.sh — build .deb packages for ziti-ssh-ca, ziti-ssh-host, ziti-ssh, and ziti-scp -# -# Usage: -# ./scripts/build-deb.sh -# VERSION=1.2.3 ./scripts/build-deb.sh -# -# Requires: go, dpkg-deb -# Produces: dist/ziti-ssh-ca__amd64.deb -# dist/ziti-ssh-host__amd64.deb -# dist/ziti-ssh__amd64.deb -# dist/ziti-scp__amd64.deb - -set -euo pipefail - -VERSION="${VERSION:-0.0.0}" -ARCH="amd64" -MAINTAINER="Edward Moscardini[edward.moscardini@netfoundry.io]" -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" -DIST_DIR="${REPO_ROOT}/dist" -STAGING_DIR="${REPO_ROOT}/.deb-staging" - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - -log() { printf '[build-deb] %s\n' "$*"; } - -require_cmd() { - if ! command -v "$1" >/dev/null 2>&1; then - printf 'error: %s is required but not found in PATH\n' "$1" >&2 - exit 1 - fi -} - -require_cmd go -require_cmd dpkg-deb - -# --------------------------------------------------------------------------- -# Preparation -# --------------------------------------------------------------------------- - -log "Version: ${VERSION}" -log "Output: ${DIST_DIR}/" - -rm -rf "${STAGING_DIR}" -mkdir -p "${DIST_DIR}" - -# --------------------------------------------------------------------------- -# Build Go binaries -# --------------------------------------------------------------------------- - -log "Building ziti-ssh-ca..." -GOARCH=amd64 GOOS=linux CGO_ENABLED=0 go build \ - -trimpath -ldflags "-s -w -X main.version=${VERSION}" \ - -o "${STAGING_DIR}/binaries/ziti-ssh-ca" \ - "${REPO_ROOT}/cmd/ziti-ssh-ca" - -log "Building ziti-ssh-host..." -GOARCH=amd64 GOOS=linux CGO_ENABLED=0 go build \ - -trimpath -ldflags "-s -w -X main.version=${VERSION}" \ - -o "${STAGING_DIR}/binaries/ziti-ssh-host" \ - "${REPO_ROOT}/cmd/ziti-ssh-host" - -log "Building ziti-ssh..." -GOARCH=amd64 GOOS=linux CGO_ENABLED=0 go build \ - -trimpath -ldflags "-s -w -X main.version=${VERSION}" \ - -o "${STAGING_DIR}/binaries/ziti-ssh" \ - "${REPO_ROOT}/cmd/ziti-ssh" - -log "Building ziti-scp..." -GOARCH=amd64 GOOS=linux CGO_ENABLED=0 go build \ - -trimpath -ldflags "-s -w -X main.version=${VERSION}" \ - -o "${STAGING_DIR}/binaries/ziti-scp" \ - "${REPO_ROOT}/cmd/ziti-scp" - -# --------------------------------------------------------------------------- -# Package: ziti-ssh-ca -# --------------------------------------------------------------------------- - -log "Packaging ziti-ssh-ca..." - -PKG="ziti-ssh-ca" -PKG_DIR="${STAGING_DIR}/${PKG}" - -# Binary -install -D -m 0755 \ - "${STAGING_DIR}/binaries/ziti-ssh-ca" \ - "${PKG_DIR}/usr/local/bin/ziti-ssh-ca" - -# Config directory (empty placeholder so dpkg tracks it) -install -d -m 0755 "${PKG_DIR}/etc/ziti-ssh-ca" - -# Systemd service file -install -D -m 0644 /dev/stdin \ - "${PKG_DIR}/lib/systemd/system/ziti-ssh-ca.service" <<'EOF' -[Unit] -Description=Ziti SSH Certificate Authority -Documentation=https://github.com/netfoundry/ziti-ssh -After=network-online.target -Wants=network-online.target - -[Service] -Type=notify -User=ziti -EnvironmentFile=/etc/ziti-ssh-ca/env -ExecStart=/usr/local/bin/ziti-ssh-ca -Restart=on-failure -RestartSec=5 -# The CA key is the Ziti controller's own PKI root CA private key. -# ziti-ssh-ca must run on the same host as the controller (same user) -# so it can read the key via the shared filesystem. - -[Install] -WantedBy=multi-user.target -EOF - -# Debian control file -install -d "${PKG_DIR}/DEBIAN" -cat > "${PKG_DIR}/DEBIAN/control" < "${PKG_DIR}/DEBIAN/postinst" <<'EOF' -#!/bin/sh -set -e - -if [ ! -f /etc/ziti-ssh-ca/env ]; then - cat > /etc/ziti-ssh-ca/env <<'ENVEOF' -# ziti-ssh-ca environment configuration -# Uncomment and set these variables before starting the service. -#ZITI_IDENTITY=/etc/ziti-ssh-ca/identity.json -#ZITI_CA_KEY=/var/lib/ziti-controller/pki/intermediate-ca/keys/intermediate-ca.key - -# MODE controls how SSH certificates are issued: -# -# shared (default): all users authenticate as a single shared Linux account. -# Set ZITI_SSH_PRINCIPAL to the shared account name (e.g. ziggy). -# Leave ZITI_SSH_MODE unset or set to "shared". -# -# per-identity: each Ziti identity gets its own Linux account on the target -# host (created automatically by ziti-ssh-host). Do not set -# ZITI_SSH_PRINCIPAL — the username is derived from the identity name. -# Set ZITI_SSH_MODE=per-identity on both ziti-ssh-ca AND ziti-ssh-host. -# -#ZITI_SSH_MODE=shared -#ZITI_SSH_PRINCIPAL=ziggy - -# Certificate validity duration (default 5m). Examples: 5m, 15m, 1h. -#ZITI_CERT_TTL=5m -ENVEOF - chmod 640 /etc/ziti-ssh-ca/env -fi - -if [ -d /run/systemd/system ]; then - systemctl daemon-reload || true -fi -EOF -chmod 0755 "${PKG_DIR}/DEBIAN/postinst" - -dpkg-deb --build --root-owner-group "${PKG_DIR}" \ - "${DIST_DIR}/${PKG}_${VERSION}_${ARCH}.deb" - -log "Created ${DIST_DIR}/${PKG}_${VERSION}_${ARCH}.deb" - -# --------------------------------------------------------------------------- -# Package: ziti-ssh-host -# --------------------------------------------------------------------------- - -log "Packaging ziti-ssh-host..." - -PKG="ziti-ssh-host" -PKG_DIR="${STAGING_DIR}/${PKG}" - -# Binary -install -D -m 0755 \ - "${STAGING_DIR}/binaries/ziti-ssh-host" \ - "${PKG_DIR}/usr/local/bin/ziti-ssh-host" - -# Config directory — mode 0700 because it will contain the identity JSON -# (private key material) after enrollment. -install -d -m 0700 "${PKG_DIR}/etc/ziti-ssh-host" - -# Systemd service file -install -D -m 0644 /dev/stdin \ - "${PKG_DIR}/lib/systemd/system/ziti-ssh-host.service" <<'EOF' -[Unit] -Description=Ziti SSH Host Proxy -Documentation=https://github.com/netfoundry/ziti-ssh -After=network-online.target -Wants=network-online.target - -[Service] -Type=notify -# Runs as root: writes /etc/ssh/ during enrollment and proxies connections -# to the local sshd. The identity file is stored in /etc/ziti-ssh-host/ -# (mode 0700) and is only readable by root. -User=root -EnvironmentFile=-/etc/ziti-ssh-host/env -ExecStart=/usr/local/bin/ziti-ssh-host run -Restart=on-failure -RestartSec=5 - -[Install] -WantedBy=multi-user.target -EOF - -# Debian control file -install -d "${PKG_DIR}/DEBIAN" -cat > "${PKG_DIR}/DEBIAN/control" <" once, then start the - service. -EOF - -# postinst: create env file placeholder if absent, reload systemd -cat > "${PKG_DIR}/DEBIAN/postinst" <<'EOF' -#!/bin/sh -set -e - -if [ ! -f /etc/ziti-ssh-host/env ]; then - cat > /etc/ziti-ssh-host/env <<\ENVEOF -# ziti-ssh-host environment configuration -# Uncomment and set these variables before starting the service. - -# Path to the enrolled Ziti identity file (written by: ziti-ssh-host enroll --jwt) -#ZITI_IDENTITY=/etc/ziti-ssh-host/identity.json - -# Ziti service name to bind as SSH host (must match the service created on the controller) -#ZITI_SSH_SERVICE=ssh - -# MODE controls how SSH connections are handled: -# -# shared (default): all connections authenticate as a single shared Linux account. -# The account (e.g. ziggy) must already exist on this host. -# Set ZITI_SSH_MODE=shared (or leave unset). -# -# per-identity: each connecting Ziti identity gets its own ephemeral Linux account, -# created automatically on first connection and removed when the last session closes. -# Set ZITI_SSH_MODE=per-identity on BOTH ziti-ssh-host AND ziti-ssh-ca. -# -#ZITI_SSH_MODE=shared - -# SUDOERS — optional sudo rule granted to per-identity users on connect. -# Only applies when ZITI_SSH_MODE=per-identity. -# Leave unset for no sudo access. The rule is written to /etc/sudoers.d/. -# Example (full passwordless sudo): -#ZITI_SUDOERS_RULE=ALL=(ALL) NOPASSWD:ALL - -# USER_CLEANUP — whether to delete the Linux user and sudoers file on disconnect. -# false (default): persistent users — account remains after disconnect. -# true: ephemeral users — account removed when last session closes. -#ZITI_USER_CLEANUP=false -ENVEOF - chmod 640 /etc/ziti-ssh-host/env -fi - -if [ -d /run/systemd/system ]; then - systemctl daemon-reload || true -fi -EOF -chmod 0755 "${PKG_DIR}/DEBIAN/postinst" - -dpkg-deb --build --root-owner-group "${PKG_DIR}" \ - "${DIST_DIR}/${PKG}_${VERSION}_${ARCH}.deb" - -log "Created ${DIST_DIR}/${PKG}_${VERSION}_${ARCH}.deb" - -# --------------------------------------------------------------------------- -# Package: ziti-ssh -# --------------------------------------------------------------------------- - -log "Packaging ziti-ssh..." - -PKG="ziti-ssh" -PKG_DIR="${STAGING_DIR}/${PKG}" - -# Binary -install -D -m 0755 \ - "${STAGING_DIR}/binaries/ziti-ssh" \ - "${PKG_DIR}/usr/local/bin/ziti-ssh" - -# Debian control file -install -d "${PKG_DIR}/DEBIAN" -cat > "${PKG_DIR}/DEBIAN/control" <-cert.pub. - They are refreshed automatically when fewer than 5 minutes of validity - remain. - . - Subcommands: connect (default), sign, enroll, list, mfa. - . - Configuration is read from ~/.config/ziti-ssh/config.yaml (XDG_CONFIG_HOME - is respected). No long-lived credentials are stored on SSH hosts. -EOF - -# postinst: no systemd service for a CLI tool. The config directory cannot be -# created here reliably (we do not know the target user). Document it instead. -cat > "${PKG_DIR}/DEBIAN/postinst" <<'EOF' -#!/bin/sh -set -e - -# ziti-ssh stores its config in ~/.config/ziti-ssh/config.yaml. -# Create that directory the first time you run ziti-ssh, or manually: -# mkdir -p ~/.config/ziti-ssh -EOF -chmod 0755 "${PKG_DIR}/DEBIAN/postinst" - -dpkg-deb --build --root-owner-group "${PKG_DIR}" \ - "${DIST_DIR}/${PKG}_${VERSION}_${ARCH}.deb" - -log "Created ${DIST_DIR}/${PKG}_${VERSION}_${ARCH}.deb" - -# --------------------------------------------------------------------------- -# Package: ziti-scp -# --------------------------------------------------------------------------- - -log "Packaging ziti-scp..." - -PKG="ziti-scp" -PKG_DIR="${STAGING_DIR}/${PKG}" - -# Binary -install -D -m 0755 \ - "${STAGING_DIR}/binaries/ziti-scp" \ - "${PKG_DIR}/usr/local/bin/ziti-scp" - -# Debian control file -install -d "${PKG_DIR}/DEBIAN" -cat > "${PKG_DIR}/DEBIAN/control" <... - . - Configuration is read from ~/.config/ziti-ssh/config.yaml (XDG_CONFIG_HOME - is respected). No long-lived credentials are stored on SSH hosts. -EOF - -# postinst: no systemd service for a CLI tool. -cat > "${PKG_DIR}/DEBIAN/postinst" <<'EOF' -#!/bin/sh -set -e - -# ziti-scp shares its config with ziti-ssh at ~/.config/ziti-ssh/config.yaml. -# Create that directory the first time you run ziti-ssh or ziti-scp, or manually: -# mkdir -p ~/.config/ziti-ssh -EOF -chmod 0755 "${PKG_DIR}/DEBIAN/postinst" - -dpkg-deb --build --root-owner-group "${PKG_DIR}" \ - "${DIST_DIR}/${PKG}_${VERSION}_${ARCH}.deb" - -log "Created ${DIST_DIR}/${PKG}_${VERSION}_${ARCH}.deb" - -# --------------------------------------------------------------------------- -# Copy binaries to repo root for local testing -# --------------------------------------------------------------------------- - -log "Copying binaries to repo root for local testing..." -cp "${STAGING_DIR}/binaries/ziti-ssh-ca" "${REPO_ROOT}/ziti-ssh-ca" -cp "${STAGING_DIR}/binaries/ziti-ssh-host" "${REPO_ROOT}/ziti-ssh-host" -cp "${STAGING_DIR}/binaries/ziti-ssh" "${REPO_ROOT}/ziti-ssh" -cp "${STAGING_DIR}/binaries/ziti-scp" "${REPO_ROOT}/ziti-scp" - -# --------------------------------------------------------------------------- -# Cleanup and summary -# --------------------------------------------------------------------------- - -rm -rf "${STAGING_DIR}" - -log "Done." -log "" -log "Packages:" -ls -lh "${DIST_DIR}/"*_"${VERSION}"_"${ARCH}".deb -log "" -log "Binaries (repo root):" -ls -lh "${REPO_ROOT}/ziti-ssh-ca" "${REPO_ROOT}/ziti-ssh-host" "${REPO_ROOT}/ziti-ssh" "${REPO_ROOT}/ziti-scp" diff --git a/scripts/build-packages.sh b/scripts/build-packages.sh index 4e2a91e..be1147c 100755 --- a/scripts/build-packages.sh +++ b/scripts/build-packages.sh @@ -12,7 +12,7 @@ # FORMAT — comma-separated list of package formats: deb, rpm, or deb,rpm (default: deb,rpm) # ARCHS — comma-separated list of Go architectures to build (default: native arch) # -# Requires: go, nfpm +# Requires: go; nfpm (downloaded and checksum-verified for this run if not on PATH; Linux) set -euo pipefail @@ -36,10 +36,35 @@ if ! command -v go >/dev/null 2>&1; then printf 'error: go is required but not found in PATH\n' >&2 exit 1 fi +# nfpm: use the one on PATH, otherwise download the pinned release binary and +# verify it against the release checksums (as prerelease.yml does). It is put +# in a temporary directory for this run only. "go install" is not used: recent +# nfpm releases need a newer Go than this module's toolchain. if ! command -v nfpm >/dev/null 2>&1; then - log "nfpm not found — installing via go install..." - go install github.com/goreleaser/nfpm/v2/cmd/nfpm@latest - export PATH="${PATH}:$(go env GOPATH)/bin" + NFPM_VERSION="${NFPM_VERSION:-2.49.0}" + if [[ "$(uname -s)" != "Linux" ]]; then + printf 'error: nfpm not found; install nfpm v%s (https://nfpm.goreleaser.com/install/)\n' "${NFPM_VERSION}" >&2 + exit 1 + fi + case "$(uname -m)" in + x86_64|amd64) NFPM_ARCH_NAME=x86_64 ;; + aarch64|arm64) NFPM_ARCH_NAME=arm64 ;; + *) printf 'error: nfpm not found and no release binary for %s; install nfpm v%s\n' "$(uname -m)" "${NFPM_VERSION}" >&2 + exit 1 ;; + esac + for tool in curl tar sha256sum; do + command -v "${tool}" >/dev/null 2>&1 || { printf 'error: %s is required to download nfpm\n' "${tool}" >&2; exit 1; } + done + NFPM_TMP="$(mktemp -d)" + trap 'rm -rf "${NFPM_TMP}"' EXIT + tarball="nfpm_${NFPM_VERSION}_Linux_${NFPM_ARCH_NAME}.tar.gz" + base="https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}" + log "nfpm not found — downloading v${NFPM_VERSION} (${tarball}) and verifying its checksum" + curl -sfL -o "${NFPM_TMP}/${tarball}" "${base}/${tarball}" + curl -sfL -o "${NFPM_TMP}/checksums.txt" "${base}/checksums.txt" + (cd "${NFPM_TMP}" && grep " ${tarball}\$" checksums.txt | sha256sum -c -) + tar -xzf "${NFPM_TMP}/${tarball}" -C "${NFPM_TMP}" nfpm + export PATH="${NFPM_TMP}:${PATH}" fi IFS=',' read -ra FORMAT_LIST <<< "${FORMAT}" diff --git a/suites/ziti-ssh-per-identity/network.yaml b/suites/ziti-ssh-per-identity/network.yaml new file mode 100644 index 0000000..34f1ccf --- /dev/null +++ b/suites/ziti-ssh-per-identity/network.yaml @@ -0,0 +1,80 @@ +# suites/ziti-ssh-per-identity/network.yaml +# +# As suites/ziti-ssh/network.yaml, plus a second SSH service "ssh-ops" with +# the same "ssh" role attribute, so the existing bind/dial/router policies +# cover it. Tests attach ziti-ssh-host.v1 configs to both services. +# +# Declarative Ziti network resources for the ziti-ssh integration test suite. +# Applied via ``ziti ops import`` after all edge routers are online and before +# any client post_install scripts run. +# +# Defines: +# • ssh-ca service — CA signs short-lived SSH certificates +# • ssh service — Ziti-tunneled SSH sessions to the ER hosts +# +# Identities are NOT declared here; each post_install script creates its own +# identity via the management REST API so that each VM can enroll itself. +# +# Policy model: +# #ssh-ca-servers BIND ssh-ca (the CA on ctrl-0) +# #ssh-clients DIAL ssh-ca (the client VM requesting certs) +# #ssh-hosts BIND ssh (each ER running ziti-ssh-host) +# #ssh-clients DIAL ssh (the client VM opening SSH sessions) + +services: + - name: ssh-ca + encryptionRequired: true + roleAttributes: + - ssh-ca + + - name: ssh + encryptionRequired: true + roleAttributes: + - ssh + + - name: ssh-ops + encryptionRequired: true + roleAttributes: + - ssh + +servicePolicies: + - name: bind-ssh-ca + type: Bind + serviceRoles: ['#ssh-ca'] + identityRoles: ['#ssh-ca-servers'] + semantic: AnyOf + + - name: dial-ssh-ca + type: Dial + serviceRoles: ['#ssh-ca'] + identityRoles: ['#ssh-clients'] + semantic: AnyOf + + - name: bind-ssh + type: Bind + serviceRoles: ['#ssh'] + identityRoles: ['#ssh-hosts'] + semantic: AnyOf + + - name: dial-ssh + type: Dial + serviceRoles: ['#ssh'] + identityRoles: ['#ssh-clients'] + semantic: AnyOf + +edgeRouterPolicies: + - name: erp-ziti-ssh + identityRoles: ['#ssh-ca-servers', '#ssh-hosts', '#ssh-clients'] + edgeRouterRoles: ['#all'] + semantic: AnyOf + +serviceEdgeRouterPolicies: + - name: serp-ssh-ca + serviceRoles: ['#ssh-ca'] + edgeRouterRoles: ['#all'] + semantic: AnyOf + + - name: serp-ssh + serviceRoles: ['#ssh'] + edgeRouterRoles: ['#all'] + semantic: AnyOf diff --git a/suites/ziti-ssh-per-identity/suite.yml b/suites/ziti-ssh-per-identity/suite.yml new file mode 100644 index 0000000..f7a36e8 --- /dev/null +++ b/suites/ziti-ssh-per-identity/suite.yml @@ -0,0 +1,86 @@ +# suites/ziti-ssh-per-identity/suite.yml +# +# Per-identity mode integration test for netfoundry/ziti-ssh. Same topology +# and install scripts as suites/ziti-ssh; the suite vars below switch the CA +# and hosts to per-identity mode, bind a second service (ssh-ops) and opt +# ssh-ops in to granting the privileged "sudo" group. +# +# Topology: +# • 1 controller (t3.medium) — runs ziti-ssh-ca +# • 2 edge routers (t3.small) — each runs ziti-ssh-host +# • 1 client VM (t3.micro) — runs ziti-ssh + ziti-scp + +meta: + name: "ziti-ssh-per-identity" + description: "ziti-ssh per-identity mode end-to-end integration test" + +# Injected into every post_install script and test as environment variables. +vars: + ZSSH_MODE: "per-identity" + ZSSH_SERVICES: "ssh,ssh-ops" + ZSSH_ALLOW_GROUPS: "ssh-ops:sudo" + # Config changes reach hosts within this interval (default 30s). + ZSSH_SERVICE_REFRESH: "10s" + +ziti: + version: "2.0.8" + apt_channel: "test" + network_name: "ziti-ssh-pi-test" + + # Declarative network resources applied after all ERs are online and before + # any client post_install runs. Defines the ssh-ca and ssh services plus + # all bind/dial policies. + resources_file: "suites/ziti-ssh-per-identity/network.yaml" + + controllers: + - count: 1 + instance_type: "t3.medium" + files: + - local: "dist/ziti-ssh-ca_0.0.0-1_amd64.deb" + remote: "/tmp/ziti-ssh-ca.deb" + post_install: + - script: "suites/ziti-ssh/scripts/install-ca.sh" + args: [] + + edge_routers: + - name: "er" + type: "edge" + count: 2 + instance_type: "t3.small" + listener_port: 3022 + public: true + files: + - local: "dist/ziti-ssh-host_0.0.0-1_amd64.deb" + remote: "/tmp/ziti-ssh-host.deb" + post_install: + - script: "suites/ziti-ssh/scripts/install-host.sh" + args: [] + +clients: + - name: "client" + type: "custom" + count: 1 + instance_type: "t3.micro" + files: + - local: "dist/ziti-ssh_0.0.0-1_amd64.deb" + remote: "/tmp/ziti-ssh.deb" + - local: "dist/ziti-scp_0.0.0-1_amd64.deb" + remote: "/tmp/ziti-scp.deb" + post_install: + - script: "suites/ziti-ssh/scripts/install-client.sh" + args: [] + +provider: + type: "aws" + region: "us-east-2" + networking: + isolated_vpc: false + +tests: + - script: "suites/ziti-ssh-per-identity/tests/test.sh" + args: [] + target: "client" + +behavior: + keep_on_failure: false + teardown_timeout_minutes: 60 diff --git a/suites/ziti-ssh-per-identity/tests/test.sh b/suites/ziti-ssh-per-identity/tests/test.sh new file mode 100755 index 0000000..5f81822 --- /dev/null +++ b/suites/ziti-ssh-per-identity/tests/test.sh @@ -0,0 +1,271 @@ +#!/usr/bin/env bash +# suites/ziti-ssh-per-identity/tests/test.sh +# +# End-to-end tests for ziti-ssh per-identity mode. Runs on the test runner; +# drives the client VM and both SSH hosts (edge routers) over SSH, and manages +# ziti-ssh-host.v1 configs through the controller's management API. +# +# The client identity is "ssh-client-vm"; its derived Linux username (the +# certificate principal) is the same string. +# +# Covered: +# 1. Account creation: registry entry, ziti-ssh-managed, configured groups, +# authorized_keys disabled; default SSH user = certificate principal. +# 2. A user name other than the principal is refused by sshd. +# 3. Pre-existing local account with the derived name is not adopted (H3). +# 4. Host grant policy: "sudo" refused via "ssh", allowed via "ssh-ops" +# (ZITI_ALLOW_GROUPS=ssh-ops:sudo); sudoers_rule refused (no opt-in). +# 5. Live reload: changed config applies on the next connection. +# 6. Config that fails to load fails closed. +# 7. Cross-service permission conflict rejected while a session is open (M2). +# 8. Disconnect clears groups and sudoers; account kept by default. +# 9. ZITI_TERMINATE_ON_DISCONNECT=true removes the crontab, ends background +# processes and expires the account; the next connection re-enables it. +# 10. ZITI_USER_CLEANUP=true deletes the account on disconnect. +# +# Environment (from ziti-test-suite): +# ZTS_TEST_TARGET_IP, ZTS_SSH_PRIVATE_KEY, ZTS_SSH_USER, +# ZTS_CONTROLLER_URLS, ZTS_CONTROLLER_ADMIN_PASSWORD, ZTS_EDGE_ROUTER_IPS +# +# Exit codes: 0 = all tests passed; 1 = one or more tests failed. + +set -euo pipefail + +log() { printf '[%s] [test] %s\n' "$(date -u '+%Y-%m-%d %H:%M:%S')" "$*" >&2; } +pass() { log " PASS: $*"; } +fail() { log " FAIL: $*"; FAILED=1; } +FAILED=0 + +: "${ZTS_TEST_TARGET_IP:?ZTS_TEST_TARGET_IP is required (target: client)}" +: "${ZTS_SSH_PRIVATE_KEY:?ZTS_SSH_PRIVATE_KEY is required}" +: "${ZTS_CONTROLLER_URLS:?ZTS_CONTROLLER_URLS is required}" +: "${ZTS_CONTROLLER_ADMIN_PASSWORD:?ZTS_CONTROLLER_ADMIN_PASSWORD is required}" +: "${ZTS_EDGE_ROUTER_IPS:?ZTS_EDGE_ROUTER_IPS is required}" +: "${ZTS_SSH_USER:=ubuntu}" + +CLIENT_IP="${ZTS_TEST_TARGET_IP}" +U="ssh-client-vm" # client identity name == derived username +SSH_KEY=$(mktemp) +printf '%s' "${ZTS_SSH_PRIVATE_KEY}" > "${SSH_KEY}" +chmod 600 "${SSH_KEY}" +trap 'rm -f "${SSH_KEY}"' EXIT +SSH_OPTS=(-i "${SSH_KEY}" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null + -o LogLevel=ERROR -o ConnectTimeout=30) + +on() { local ip=$1; shift; ssh "${SSH_OPTS[@]}" "${ZTS_SSH_USER}@${ip}" "$@"; } +on_client() { on "${CLIENT_IP}" "$@"; } + +# --------------------------------------------------------------------------- +# Management API helpers (curl --insecure: test network with a private CA) +# --------------------------------------------------------------------------- +CTRL=$(python3 -c 'import json,os;print(json.loads(os.environ["ZTS_CONTROLLER_URLS"])[0])') +API="${CTRL}/edge/management/v1" +TOKEN=$(curl -sf --insecure -H 'Content-Type: application/json' \ + --data "$(python3 -c 'import json,os;print(json.dumps({"username":"admin","password":os.environ["ZTS_CONTROLLER_ADMIN_PASSWORD"]}))')" \ + "${API}/authenticate?method=password" | python3 -c 'import json,sys;print(json.load(sys.stdin)["data"]["token"])') +api() { # method path [json] + curl -sf --insecure -X "$1" -H "zt-session: ${TOKEN}" -H 'Content-Type: application/json' \ + ${3:+--data "$3"} "${API}$2" +} +id_by_name() { # collection name + api GET "/$1?filter=$(python3 -c 'import sys,urllib.parse;print(urllib.parse.quote("name=\""+sys.argv[1]+"\""))' "$2")" | + python3 -c 'import json,sys;d=json.load(sys.stdin)["data"];print(d[0]["id"] if d else "")' +} +CFG_TYPE=$(id_by_name config-types ziti-ssh-host.v1) +[[ -n "${CFG_TYPE}" ]] || { log "ERROR: config type ziti-ssh-host.v1 not registered"; exit 1; } + +declare -A CFG_ID +# set_perms SERVICE PERMISSIONS_JSON — create or replace the service's config. +set_perms() { + local svc=$1 perms=$2 body + body=$(python3 -c 'import json,sys;print(json.dumps({"name":"zssh-"+sys.argv[1],"configTypeId":sys.argv[2],"data":{"permissions":json.loads(sys.argv[3])}}))' "${svc}" "${CFG_TYPE}" "${perms}") + if [[ -z "${CFG_ID[$svc]:-}" ]]; then + CFG_ID[$svc]=$(api POST /configs "${body}" | python3 -c 'import json,sys;print(json.load(sys.stdin)["data"]["id"])') + api PATCH "/services/$(id_by_name services "${svc}")" "{\"configs\":[\"${CFG_ID[$svc]}\"]}" >/dev/null + else + api PATCH "/configs/${CFG_ID[$svc]}" "$(python3 -c 'import json,sys;print(json.dumps({"data":{"permissions":json.loads(sys.argv[1])}}))' "${perms}")" >/dev/null + fi +} + +# --------------------------------------------------------------------------- +# Hosts: map each edge router IP to its terminator (identity) name. +# --------------------------------------------------------------------------- +mapfile -t ER_IPS < <(python3 -c 'import json,os;print("\n".join(json.loads(os.environ["ZTS_EDGE_ROUTER_IPS"])["er"]))') +H1_IP=${ER_IPS[0]}; H2_IP=${ER_IPS[1]} +H1="ssh-host-$(on "${H1_IP}" hostname -s)"; H2="ssh-host-$(on "${H2_IP}" hostname -s)" +log "Hosts: ${H1} (${H1_IP}), ${H2} (${H2_IP}); client ${CLIENT_IP}" + +host_log() { on "$1" "sudo journalctl -u ziti-ssh-host --no-pager -o cat --since '-${2:-2min}'"; } + +# zssh SERVICE HOST 'CMD' — connect as the default user (cert principal) and +# run CMD on the SSH host. CMD is single-quoted so a ';' runs remotely, not on +# the client VM. (CMD must not contain single quotes.) +# On failure the client's last error lines are logged. +zssh() { + local svc=$1 host=$2 rc=0; shift 2 + on_client "timeout 60 ziti-ssh connect --service ${svc} ${host} -- '$*' 2>/tmp/zssh.err" || rc=$? + if (( rc != 0 )); then on_client 'tail -2 /tmp/zssh.err' 2>/dev/null | sed 's/^/ [client] /' >&2 || true; fi + return "${rc}" +} + +# until_ok SECONDS CMD... — retry until the command succeeds. +until_ok() { + local deadline=$((SECONDS + $1)); shift + until "$@"; do (( SECONDS < deadline )) || return 1; sleep 5; done +} + +# --------------------------------------------------------------------------- +# Readiness: both services visible to the client, both hosts running. +# --------------------------------------------------------------------------- +log "Waiting for services ssh, ssh-ops and ssh-ca (up to 5 min)..." +services_ready() { local l; l=$(on_client 'ziti-ssh list 2>/dev/null' || true) + grep -q '^ssh-ca' <<< "$l" && grep -q '^ssh-ops' <<< "$l" && grep -qE '^ssh +' <<< "$l"; } +until_ok 300 services_ready || { log "ERROR: services not visible"; exit 1; } +for ip in "${H1_IP}" "${H2_IP}"; do + until_ok 120 on "${ip}" 'systemctl is-active --quiet ziti-ssh-host' || + { log "ERROR: ziti-ssh-host not active on ${ip}"; exit 1; } +done + +# Baseline configs (attached before the first connection). +set_perms ssh '{"*": {"groups": ["zt-dev"]}}' +set_perms ssh-ops '{"*": {"groups": ["zt-ops", "sudo"]}}' +sleep 20 # hosts refresh services every 10s (ZSSH_SERVICE_REFRESH) + +# --------------------------------------------------------------------------- +# 3. Pre-existing account on H2 is not adopted (before any connection to H2). +# --------------------------------------------------------------------------- +log "Test 3: pre-existing account with the derived name is refused (${H2})" +on "${H2_IP}" "sudo useradd -m ${U}" +if zssh ssh "${H2}" true 2>/dev/null; then + fail "connected to a pre-existing account on ${H2}" +elif host_log "${H2_IP}" | grep -q 'refusing to manage pre-existing account'; then + pass "pre-existing account refused (host log)" +else + fail "connection failed but no 'pre-existing account' log on ${H2}" +fi + +# --------------------------------------------------------------------------- +# 1. Account creation and default user. +# --------------------------------------------------------------------------- +log "Test 1: first connection creates and registers the account (${H1})" +has_dev() { zssh ssh "${H1}" 'id -Gn' 2>/dev/null | grep -qw zt-dev; } +until_ok 60 has_dev || true +OUT=$(zssh ssh "${H1}" 'id -un; id -Gn' 2>/dev/null || true) +if [[ "$(head -1 <<< "${OUT}")" == "${U}" ]]; then pass "default user is the certificate principal (${U})" +else fail "unexpected user: ${OUT}"; fi +if grep -qw zt-dev <<< "${OUT}" && grep -qw ziti-ssh-managed <<< "${OUT}"; then pass "groups: $(tail -1 <<< "${OUT}")" +else fail "groups missing (want zt-dev, ziti-ssh-managed): ${OUT}"; fi +if on "${H1_IP}" "sudo ziti-ssh-host users list" | grep -q "${U}"; then pass "account in ownership registry" +else fail "account not in ownership registry"; fi +AKF=$(on "${H1_IP}" "sudo sshd -T -C user=${U},host=localhost,addr=127.0.0.1 | grep -i '^authorizedkeysfile'") +if [[ "${AKF,,}" == "authorizedkeysfile none" ]]; then pass "authorized_keys disabled for ${U}" +else fail "authorizedkeysfile for ${U}: ${AKF}"; fi + +# --------------------------------------------------------------------------- +# 2. A user other than the principal is refused. +# --------------------------------------------------------------------------- +log "Test 2: explicit user other than the principal is refused" +if on_client "timeout 60 ziti-ssh connect --service ssh ubuntu@${H1} -- true" 2>/dev/null; then + fail "logged in as ubuntu with a ${U} certificate" +else pass "ubuntu@${H1} refused"; fi + +# --------------------------------------------------------------------------- +# 4. Host grant policy. +# --------------------------------------------------------------------------- +log "Test 4: host grant policy" +OUT=$(zssh ssh-ops "${H1}" 'id -Gn' 2>/dev/null || true) +if grep -qw sudo <<< "${OUT}"; then pass "sudo granted via ssh-ops (opted in): ${OUT}" +else fail "sudo not granted via ssh-ops: ${OUT}"; fi +set_perms ssh '{"*": {"groups": ["sudo"]}}' +refused_sudo() { ! zssh ssh "${H1}" true 2>/dev/null && host_log "${H1_IP}" 1min | grep -q 'rejecting connection: permissions refused by host grant policy'; } +if until_ok 60 refused_sudo; then pass "sudo via ssh refused by the host grant policy" +else fail "sudo via ssh not refused"; fi +set_perms ssh '{"*": {"groups": ["zt-dev"], "sudoers_rule": "ALL=(ALL) NOPASSWD: /usr/bin/true"}}' +refused_rule() { ! zssh ssh "${H1}" true 2>/dev/null && host_log "${H1_IP}" 1min | grep -q 'rejecting connection: permissions refused by host grant policy'; } +if until_ok 60 refused_rule; then pass "sudoers_rule refused without ZITI_ALLOW_SUDOERS" +else fail "sudoers_rule not refused"; fi + +# --------------------------------------------------------------------------- +# 5. Live reload. +# --------------------------------------------------------------------------- +log "Test 5: config change applies on the next connection" +set_perms ssh '{"*": {"groups": ["zt-dev", "zt-ops"]}}' +reloaded() { zssh ssh "${H1}" 'id -Gn' 2>/dev/null | grep -qw zt-ops; } +if until_ok 90 reloaded; then pass "new groups applied after config update" +else fail "config update not applied within 90s"; fi + +# --------------------------------------------------------------------------- +# 6. Config that fails to load fails closed. +# --------------------------------------------------------------------------- +log "Test 6: invalid config fails closed" +set_perms ssh '{"*": {"groups": ["zt-dev"], "sudoers_rule": "ALL=(ALL) ALL\nDefaults !authenticate"}}' +closed() { ! zssh ssh "${H1}" true 2>/dev/null && host_log "${H1_IP}" 1min | grep -q 'could not be loaded'; } +if until_ok 90 closed; then pass "connections rejected while the config is invalid" +else fail "invalid config did not fail closed"; fi +set_perms ssh '{"*": {"groups": ["zt-dev"]}}' +until_ok 90 zssh ssh "${H1}" true 2>/dev/null && pass "connections accepted again after fixing the config" || + fail "connections still rejected after fixing the config" + +# --------------------------------------------------------------------------- +# 7. Cross-service permission conflict (M2). +# --------------------------------------------------------------------------- +log "Test 7: different permissions via another service while a session is open" +on_client "nohup timeout 90 ziti-ssh connect --service ssh ${H1} -- sleep 40 /tmp/hold.log 2>&1 &" +sleep 15 +if zssh ssh-ops "${H1}" true 2>/dev/null; then + fail "ssh-ops connection allowed while an ssh session with different permissions was open" +elif host_log "${H1_IP}" 1min | grep -q 'open sessions through another service'; then + pass "ssh-ops connection rejected (permission conflict)" +else fail "ssh-ops connection failed without a conflict log"; fi +sleep 35 +until_ok 60 zssh ssh-ops "${H1}" true 2>/dev/null && pass "ssh-ops allowed after the ssh session closed" || + fail "ssh-ops still rejected after the ssh session closed" + +# --------------------------------------------------------------------------- +# 8. Disconnect clears privileges, keeps the account. +# --------------------------------------------------------------------------- +log "Test 8: last disconnect clears groups and sudoers" +sleep 5 +G=$(on "${H1_IP}" "id -Gn ${U}" || true) +if grep -qw sudo <<< "${G}" || grep -qw zt-ops <<< "${G}" || grep -qw zt-dev <<< "${G}"; then + fail "groups not cleared after disconnect: ${G}" +else pass "groups after disconnect: ${G}"; fi +if on "${H1_IP}" "sudo test -e /etc/sudoers.d/ziti-ssh-host-${U}"; then fail "sudoers file left behind" +else pass "no sudoers file"; fi +if on "${H1_IP}" "id ${U}" >/dev/null 2>&1; then pass "account kept (ZITI_USER_CLEANUP unset)" +else fail "account deleted although cleanup is off"; fi + +# --------------------------------------------------------------------------- +# 9. ZITI_TERMINATE_ON_DISCONNECT=true: cron, processes, expiry. +# --------------------------------------------------------------------------- +log "Test 9: ZITI_TERMINATE_ON_DISCONNECT=true ends what the account can run" +on "${H1_IP}" "echo ZITI_TERMINATE_ON_DISCONNECT=true | sudo tee -a /etc/ziti-ssh-host/env >/dev/null && sudo systemctl restart ziti-ssh-host" +until_ok 120 on "${H1_IP}" 'systemctl is-active --quiet ziti-ssh-host' +sleep 10 +until_ok 60 zssh ssh "${H1}" 'echo "* * * * * true" | crontab - && (setsid nohup sleep 600 /dev/null 2>&1 &) && crontab -l' >/dev/null || + fail "could not set up crontab / background process" +sleep 15 +if on "${H1_IP}" "sudo crontab -u ${U} -l" >/dev/null 2>&1; then fail "crontab still present after disconnect" +else pass "crontab removed"; fi +if on "${H1_IP}" "pgrep -u ${U}" >/dev/null 2>&1; then fail "processes still running: $(on "${H1_IP}" "pgrep -a -u ${U}" || true)" +else pass "background processes ended"; fi +EXP=$(on "${H1_IP}" "sudo chage -l ${U} | grep -i '^account expires'" || true) +if grep -qi 'never' <<< "${EXP}"; then fail "account not expired: ${EXP}" +else pass "account expired after disconnect: ${EXP}"; fi +until_ok 60 zssh ssh "${H1}" true && pass "next authorized connection re-enables the account" || + fail "account not re-enabled on the next connection" + +# --------------------------------------------------------------------------- +# 10. ZITI_USER_CLEANUP=true deletes the account. +# --------------------------------------------------------------------------- +log "Test 10: ZITI_USER_CLEANUP=true deletes the account on disconnect" +on "${H1_IP}" "echo ZITI_USER_CLEANUP=true | sudo tee -a /etc/ziti-ssh-host/env >/dev/null && sudo systemctl restart ziti-ssh-host" +until_ok 120 on "${H1_IP}" 'systemctl is-active --quiet ziti-ssh-host' +sleep 10 +until_ok 60 zssh ssh "${H1}" true 2>/dev/null || fail "connect with cleanup on failed" +gone() { ! on "${H1_IP}" "id ${U}" >/dev/null 2>&1; } +if until_ok 30 gone; then pass "account deleted after the last session closed" +else fail "account still present with cleanup on"; fi + +if [[ ${FAILED} -eq 0 ]]; then log "All tests PASSED"; exit 0; fi +log "One or more tests FAILED"; exit 1 diff --git a/suites/ziti-ssh/scripts/install-ca.sh b/suites/ziti-ssh/scripts/install-ca.sh index 1c81e46..b13b083 100755 --- a/suites/ziti-ssh/scripts/install-ca.sh +++ b/suites/ziti-ssh/scripts/install-ca.sh @@ -14,6 +14,7 @@ # Environment variables (injected by ziti-test-suite): # ZITI_CTRL_URL — controller management API URL (https://host:port) # ZITI_ADMIN_PASSWORD — controller admin password +# ZSSH_MODE — optional suite var: shared (default) or per-identity # # Exit codes: 0 on success; non-zero on any failure (set -euo pipefail). @@ -137,7 +138,7 @@ sudo tee /etc/ziti-ssh-ca/env > /dev/null </dev/null 2>&1; then sudo useradd --create-home --shell /bin/bash ziggy fi +# Restrict the shared account to CA-certificate login (the ziti-ssh-host sshd +# drop-in disables authorized_keys for members of ziti-ssh-managed). +sudo groupadd -f --system ziti-ssh-managed +sudo usermod -aG ziti-ssh-managed ziggy # --------------------------------------------------------------------------- # 3) Install the ziti-ssh-host package staged by the suite runner. @@ -133,12 +137,26 @@ sudo ziti-ssh-host enroll \ # whether certificates carry a shared principal ("ziggy") or a per-identity # derived username. # --------------------------------------------------------------------------- -log "Writing ziti-ssh-host environment + systemd unit" -sudo tee /etc/ziti-ssh-host/env > /dev/null <<'ENVEOF' +# Suite vars (optional): ZSSH_MODE=per-identity switches the host to +# per-identity mode, binds ZSSH_SERVICES (default "ssh") and applies the +# grant policy ZSSH_ALLOW_GROUPS; it also creates the test groups. +ZSSH_MODE="${ZSSH_MODE:-shared}" +ZSSH_SERVICES="${ZSSH_SERVICES:-ssh}" +if [[ "${ZSSH_MODE}" == "per-identity" ]]; then + for g in zt-dev zt-ops; do sudo groupadd -f "${g}"; done +fi +log "Writing ziti-ssh-host environment + systemd unit (mode ${ZSSH_MODE}, services ${ZSSH_SERVICES})" +sudo tee /etc/ziti-ssh-host/env > /dev/null < /dev/null +fi +if [[ -n "${ZSSH_SERVICE_REFRESH:-}" ]]; then + echo "ZITI_SERVICE_REFRESH=${ZSSH_SERVICE_REFRESH}" | sudo tee -a /etc/ziti-ssh-host/env > /dev/null +fi sudo tee /etc/systemd/system/ziti-ssh-host.service > /dev/null <<'UNITEOF' [Unit] @@ -149,7 +167,7 @@ Wants=network-online.target [Service] Type=notify EnvironmentFile=-/etc/ziti-ssh-host/env -ExecStart=/usr/local/bin/ziti-ssh-host run +ExecStart=/usr/bin/ziti-ssh-host run Restart=on-failure RestartSec=5 @@ -158,13 +176,27 @@ WantedBy=multi-user.target UNITEOF sudo systemctl daemon-reload -sudo systemctl enable --now ziti-ssh-host +sudo systemctl enable --now ziti-ssh-host || true # With Type=notify, systemd waits for READY=1 before reporting active, so # is-active here confirms the daemon fully initialised and opened its listener. +# +# One startup failure is expected: the "ssh" Ziti service is created by the +# suite's network resources, which are applied only after ALL edge routers are +# online. If this ER finishes first, ziti-ssh-host exits with +# "service 'ssh' not found" and systemd restarts it (Restart=on-failure, +# RestartSec=5) until the service exists. Any other failure is fatal. if ! sudo systemctl is-active --quiet ziti-ssh-host; then + # Capture before matching: piping journalctl into "grep -q" can SIGPIPE + # journalctl and fail the pipeline under "set -o pipefail". + JOURNAL=$(sudo journalctl -u ziti-ssh-host --no-pager -n 50 || true) + if grep -qE "service '[^']+' not found" <<< "${JOURNAL}"; then + log "install-host.sh complete — ziti-ssh-host enabled as ${IDENTITY_NAME};" \ + "waiting for the 'ssh' service to be created (systemd will restart it)" + exit 0 + fi log "ziti-ssh-host failed to start — recent journal output:" - sudo journalctl -u ziti-ssh-host --no-pager -n 50 >&2 + printf '%s\n' "${JOURNAL}" >&2 exit 1 fi diff --git a/suites/ziti-ssh/suite.yml b/suites/ziti-ssh/suite.yml index 11908ed..8f1c90a 100644 --- a/suites/ziti-ssh/suite.yml +++ b/suites/ziti-ssh/suite.yml @@ -12,7 +12,7 @@ meta: description: "ziti-ssh end-to-end integration test" ziti: - version: "2.0.0-pre10" + version: "2.0.8" apt_channel: "test" network_name: "ziti-ssh-test" @@ -25,7 +25,7 @@ ziti: - count: 1 instance_type: "t3.medium" files: - - local: "dist/ziti-ssh-ca_0.0.0_amd64.deb" + - local: "dist/ziti-ssh-ca_0.0.0-1_amd64.deb" remote: "/tmp/ziti-ssh-ca.deb" post_install: - script: "suites/ziti-ssh/scripts/install-ca.sh" @@ -39,7 +39,7 @@ ziti: listener_port: 3022 public: true files: - - local: "dist/ziti-ssh-host_0.0.0_amd64.deb" + - local: "dist/ziti-ssh-host_0.0.0-1_amd64.deb" remote: "/tmp/ziti-ssh-host.deb" post_install: - script: "suites/ziti-ssh/scripts/install-host.sh" @@ -51,9 +51,9 @@ clients: count: 1 instance_type: "t3.micro" files: - - local: "dist/ziti-ssh_0.0.0_amd64.deb" + - local: "dist/ziti-ssh_0.0.0-1_amd64.deb" remote: "/tmp/ziti-ssh.deb" - - local: "dist/ziti-scp_0.0.0_amd64.deb" + - local: "dist/ziti-scp_0.0.0-1_amd64.deb" remote: "/tmp/ziti-scp.deb" post_install: - script: "suites/ziti-ssh/scripts/install-client.sh"