sec: fail-closed verification + server-issued enrollment (v1.4.0)
Implements protocol v1.2.0. verifySignature() returned true when no public_key was configured, logging "skipping signature verification". The SSO installer never wrote a public_key, so a default install executed reboot, service_restart, configure_ldap, arbitrary_bash and update_binary UNVERIFIED from anything that could reach its socket. An agent that cannot verify now refuses. Canonicalization also disagreed with the server. Go's encoding/json escapes <, > and & by default; JSON.stringify does not. Any payload containing them hashed differently on each side and failed verification -- for arbitrary_bash that is most real scripts (`>` redirection, `&&`). Now uses json.Encoder with SetEscapeHTML(false), trailing newline trimmed. The SSO now rejects tokens it did not issue. Handles its close codes (4001/4002/4003/4004) and backs off 5 minutes on an enrollment failure instead of retrying every 5s forever. The connect log no longer prints the URL, which carried ?token=. install.sh gains --public-key and warns when none is configured. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,28 @@ All notable changes to the `theta-agent` daemon will be documented in this file.
|
|||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [v1.4.0] - 2026-08-05
|
||||||
|
|
||||||
|
Implements **Protocol v1.2.0**. See `PROTOCOL.md` §1.1, §5.1–5.3.
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- **Fail-closed signature verification.** `verifySignature` returned `true` when no `public_key` was configured, logging "skipping signature verification". Combined with an installer that never wrote a `public_key`, that meant a default install would execute `reboot`, `service_restart`, `configure_ldap`, `arbitrary_bash` and `update_binary` **unverified** from anything that could reach its socket. An agent that cannot verify a high-risk command now refuses it.
|
||||||
|
- **The token must be issued by the server.** The SSO now rejects tokens it did not mint (close code `4001`). Agents carrying a token generated by the old browser-side installer will not connect until re-enrolled.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Canonicalization mismatch broke signatures for most real scripts.** Go's `encoding/json` escapes `<`, `>` and `&` by default; the server's `JSON.stringify` does not. Any payload containing them — an `arbitrary_bash` script using `>` redirection or `&&`, which is most of them — hashed differently on each side and failed verification. `canonicalize()` now uses `json.Encoder` with `SetEscapeHTML(false)` and trims the encoder's trailing newline.
|
||||||
|
- **Auth failures no longer hot-loop.** A rejected credential was retried every 5 seconds forever, flooding the SSO and its audit log. Close codes `4001`/`4003`/`4004` now back off for 5 minutes and log what to do about it.
|
||||||
|
- **The auth token no longer appears in logs.** The connect line logged the full URL, including `?token=...`. It now logs only host + path, and the token is URL-escaped.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Close-code handling for the SSO's enrollment signals: `4001` unauthorized, `4002` superseded, `4003` revoked, `4004` token rotated.
|
||||||
|
- `install.sh --public-key <base64>`, written into the generated `agent.yml`. The installer warns loudly when no public key is configured, since such an agent can report telemetry but will refuse every high-risk command.
|
||||||
|
- Tests: fail-closed with no key, wrong key, payload tampered after signing, shell metacharacters (`>`, `&&`, `<`) round-tripping, and canonical-form equality with the server. `interop_check_test.go` verifies a signature produced by the live SSO against the agent's own verifier (skipped unless `INTEROP_FIXTURE` is set).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Existing tests no longer rely on verification being skipped; high-risk cases now sign with a real test key.
|
||||||
|
- `agent.yml.example`, `README.md`, `INSTALL.md`: enrollment is a prerequisite, and `public_key` is the base64 of the **raw 32-byte** Ed25519 key — not a PEM body. The previous documented example (`MCowBQYDK2VwAyEA...`) decodes to 44 bytes and would have been rejected.
|
||||||
|
|
||||||
## [v1.3.0] - 2026-08-04
|
## [v1.3.0] - 2026-08-04
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|||||||
+14
-1
@@ -2,6 +2,18 @@
|
|||||||
|
|
||||||
Theta Agent is designed for rapid deployment across the fleet. The recommended method is via the "One-Liner" install, which marries the agent to a specific SSO Manager instance.
|
Theta Agent is designed for rapid deployment across the fleet. The recommended method is via the "One-Liner" install, which marries the agent to a specific SSO Manager instance.
|
||||||
|
|
||||||
|
## Prerequisite: enroll the host
|
||||||
|
|
||||||
|
The agent's token is issued by the SSO, not chosen by you. In the SSO open
|
||||||
|
**Directory → Install Agent**, name the host, bind it to a host resource, and
|
||||||
|
press **Enroll & issue token**. You get:
|
||||||
|
|
||||||
|
- the **agent token** — shown once; only its hash is stored
|
||||||
|
- the **SSO public key** — pinned by the agent to verify high-risk commands
|
||||||
|
|
||||||
|
The modal builds the install command below with both already filled in. A token
|
||||||
|
the SSO did not issue is rejected at connect time with close code `4001`.
|
||||||
|
|
||||||
## Quick Start (The One-Liner)
|
## Quick Start (The One-Liner)
|
||||||
|
|
||||||
The SSO Manager provides a pre-generated installation command. Copy and paste it into your terminal as root:
|
The SSO Manager provides a pre-generated installation command. Copy and paste it into your terminal as root:
|
||||||
@@ -15,7 +27,8 @@ curl -fsSL https://sso.example.com/resources/theta-agent/install.sh | sh -s -- "
|
|||||||
### Option B: Minimal Setup
|
### Option B: Minimal Setup
|
||||||
Use this for rapid deployment with basic telemetry:
|
Use this for rapid deployment with basic telemetry:
|
||||||
```bash
|
```bash
|
||||||
curl -fsSL https://sso.example.com/resources/theta-agent/install.sh | sh -s -- --url "https://sso.example.com" --token "your-host-token"
|
curl -fsSL https://sso.example.com/resources/theta-agent/install.sh | sh -s -- \
|
||||||
|
--url "https://sso.example.com" --token "<ISSUED_TOKEN>" --public-key "<BASE64_PUBLIC_KEY>"
|
||||||
```
|
```
|
||||||
|
|
||||||
### What this does:
|
### What this does:
|
||||||
|
|||||||
+71
-4
@@ -1,4 +1,4 @@
|
|||||||
# Theta Agent Protocol Specification (v1.1.0)
|
# Theta Agent Protocol Specification (v1.2.0)
|
||||||
|
|
||||||
This document defines the communication protocol between the `theta-agent` (Client) and the `sso-manager` (Server).
|
This document defines the communication protocol between the `theta-agent` (Client) and the `sso-manager` (Server).
|
||||||
|
|
||||||
@@ -7,8 +7,34 @@ This document defines the communication protocol between the `theta-agent` (Clie
|
|||||||
The agent establishes a persistent outbound WebSocket connection.
|
The agent establishes a persistent outbound WebSocket connection.
|
||||||
|
|
||||||
- **Endpoint**: `wss://<manager-url>/api/agent/ws`
|
- **Endpoint**: `wss://<manager-url>/api/agent/ws`
|
||||||
- **Authentication**: The agent must provide a unique host token as a query parameter:
|
- **Authentication**: The agent must provide its enrollment token as a query parameter:
|
||||||
- `wss://<manager-url>/api/agent/ws?token=<HOST_TOKEN>`
|
- `wss://<manager-url>/api/agent/ws?token=<AGENT_TOKEN>`
|
||||||
|
|
||||||
|
### 1.1 Enrollment (changed in v1.2.0)
|
||||||
|
|
||||||
|
The token **must be issued by the server**. An administrator enrolls the agent in
|
||||||
|
the SSO (Directory → Agents, or `POST /api/agent/enroll`), which mints the token,
|
||||||
|
stores only its SHA-256, and displays the raw value once. That value goes into
|
||||||
|
`auth_token` in `agent.yml`.
|
||||||
|
|
||||||
|
Up to v1.1.0 the token was generated in the browser and never recorded
|
||||||
|
server-side, so the server accepted *any* string: anyone who could reach
|
||||||
|
`/api/agent/ws` could register as a node, publish discovery/telemetry, and
|
||||||
|
receive commands addressed to a token they guessed. Tokens the server did not
|
||||||
|
issue are now rejected.
|
||||||
|
|
||||||
|
The server accepts the WebSocket upgrade before authenticating, so an
|
||||||
|
authentication failure arrives as a **close frame**, not an HTTP status:
|
||||||
|
|
||||||
|
| Code | Meaning | Agent behaviour |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `4001` | Token unknown, or not issued by this server | Back off (5 min); the credential will not fix itself |
|
||||||
|
| `4002` | Superseded — another connection authenticated as this agent | Normal reconnect |
|
||||||
|
| `4003` | Enrollment revoked or deleted by an administrator | Back off (5 min) |
|
||||||
|
| `4004` | Token rotated — `agent.yml` holds the superseded value | Back off (5 min); re-copy the token |
|
||||||
|
|
||||||
|
Revocation and rotation both drop any live socket immediately, so they take
|
||||||
|
effect without waiting for the agent to reconnect.
|
||||||
|
|
||||||
## 2. Message Format
|
## 2. Message Format
|
||||||
|
|
||||||
@@ -97,9 +123,50 @@ These commands **require** an Ed25519 signature in the payload. The agent verifi
|
|||||||
|
|
||||||
To send a high-risk command:
|
To send a high-risk command:
|
||||||
1. Create the payload (e.g., `{"script": "uptime"}`).
|
1. Create the payload (e.g., `{"script": "uptime"}`).
|
||||||
2. Canonicalize the JSON (sort keys alphabetically, remove whitespace).
|
2. Canonicalize the JSON (see 5.1).
|
||||||
3. Sign the canonical bytes using the private Ed25519 key.
|
3. Sign the canonical bytes using the private Ed25519 key.
|
||||||
4. Add the base64 signature to the payload: `{"script": "uptime", "signature": "..."}`.
|
4. Add the base64 signature to the payload: `{"script": "uptime", "signature": "..."}`.
|
||||||
5. Send as a `WSMessage`.
|
5. Send as a `WSMessage`.
|
||||||
|
|
||||||
The agent performs the reverse process to verify authenticity before execution.
|
The agent performs the reverse process to verify authenticity before execution.
|
||||||
|
|
||||||
|
### 5.1 Canonical form
|
||||||
|
|
||||||
|
Both sides must produce **byte-identical** input to sign/verify:
|
||||||
|
|
||||||
|
- keys sorted alphabetically
|
||||||
|
- no insignificant whitespace
|
||||||
|
- the `signature` key omitted
|
||||||
|
- **no HTML escaping** — `<`, `>` and `&` are emitted literally
|
||||||
|
- no trailing newline
|
||||||
|
|
||||||
|
The escaping rule is load-bearing. Go's `encoding/json` escapes those three
|
||||||
|
characters by default while JavaScript's `JSON.stringify` does not, so a payload
|
||||||
|
containing any of them hashed differently on each side and verification failed.
|
||||||
|
For `arbitrary_bash` that is most real scripts (`>` redirection, `&&`). The Go
|
||||||
|
client uses `json.Encoder` with `SetEscapeHTML(false)`.
|
||||||
|
|
||||||
|
Example — payload `{"script": "echo a > b && c", "comment": "x&y"}` canonicalizes to:
|
||||||
|
|
||||||
|
```
|
||||||
|
{"comment":"x&y","script":"echo a > b && c"}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 The server signing key (changed in v1.2.0)
|
||||||
|
|
||||||
|
The server's Ed25519 key pair is **persistent**, stored in OpenBao at
|
||||||
|
`secret/agent/signing-key`. `public_key` in `agent.yml` is the base64-encoded raw
|
||||||
|
32-byte public key, available from the enrollment response or
|
||||||
|
`GET /api/agent/nodes`.
|
||||||
|
|
||||||
|
Previously the pair was generated in memory at process start, so it changed on
|
||||||
|
every restart and no agent could meaningfully pin it. If the server cannot load
|
||||||
|
or persist a key it now **refuses to send high-risk commands** rather than
|
||||||
|
signing with a key no agent has seen.
|
||||||
|
|
||||||
|
### 5.3 Agent-side verification is fail-closed (changed in v1.2.0)
|
||||||
|
|
||||||
|
An agent with no `public_key` configured **rejects** every high-risk command.
|
||||||
|
Until v1.1.0 it logged "skipping signature verification" and executed them,
|
||||||
|
which meant an agent installed without a key would run `reboot`,
|
||||||
|
`configure_ldap` and `arbitrary_bash` from anything that reached its socket.
|
||||||
|
|||||||
@@ -39,6 +39,17 @@ The agent will **only** execute commands that are explicitly enabled in its loca
|
|||||||
### Cryptographic Hardening
|
### Cryptographic Hardening
|
||||||
All high-risk commands require an Ed25519 signature. The agent verifies the signature against the `public_key` provided in the local config. If the signature is missing or invalid, the command is rejected regardless of the capability matrix.
|
All high-risk commands require an Ed25519 signature. The agent verifies the signature against the `public_key` provided in the local config. If the signature is missing or invalid, the command is rejected regardless of the capability matrix.
|
||||||
|
|
||||||
|
Verification is **fail-closed**: an agent with no `public_key` configured rejects
|
||||||
|
every high-risk command. (Before protocol v1.2.0 it logged "skipping signature
|
||||||
|
verification" and executed them, so an agent installed without a key would run
|
||||||
|
`reboot`, `configure_ldap` and `arbitrary_bash` unverified.)
|
||||||
|
|
||||||
|
### Enrollment
|
||||||
|
The agent's token must be **issued by the SSO**. The server stores only its
|
||||||
|
SHA-256 and rejects anything else at the WebSocket handshake, so a token cannot
|
||||||
|
be minted client-side, and an enrollment can be revoked or rotated centrally —
|
||||||
|
either drops the agent's live connection immediately. See `PROTOCOL.md` §1.1.
|
||||||
|
|
||||||
### Capability Matrix
|
### Capability Matrix
|
||||||
|
|
||||||
| Capability | Risk Level | Description | Impact |
|
| Capability | Risk Level | Description | Impact |
|
||||||
@@ -56,7 +67,7 @@ Configuration is stored in YAML format at `/etc/theta42/agent.yml`.
|
|||||||
### Example `agent.yml`
|
### Example `agent.yml`
|
||||||
```yaml
|
```yaml
|
||||||
server_url: "wss://sso.theta42.local"
|
server_url: "wss://sso.theta42.local"
|
||||||
auth_token: "your-unique-host-token"
|
auth_token: "issued-by-the-sso-at-enrollment"
|
||||||
public_key: "base64-encoded-ed25519-public-key"
|
public_key: "base64-encoded-ed25519-public-key"
|
||||||
location: "dc-01-rack-12"
|
location: "dc-01-rack-12"
|
||||||
capabilities:
|
capabilities:
|
||||||
@@ -71,7 +82,12 @@ capabilities:
|
|||||||
|
|
||||||
1. **Build**: Compile for your target architecture (see CI/CD artifacts).
|
1. **Build**: Compile for your target architecture (see CI/CD artifacts).
|
||||||
2. **Deploy**: Place the binary in `/usr/local/bin/theta-agent`.
|
2. **Deploy**: Place the binary in `/usr/local/bin/theta-agent`.
|
||||||
3. **Configure**: Create `/etc/theta42/agent.yml` with the required token and capabilities.
|
3. **Enroll**: In the SSO, open **Directory → Install Agent**, name the host, bind
|
||||||
|
it to a host resource, and press **Enroll & issue token**. The SSO mints the
|
||||||
|
token (shown once) and gives you its public key. Tokens the server did not
|
||||||
|
issue are rejected.
|
||||||
|
4. **Configure**: Create `/etc/theta42/agent.yml` with the issued `auth_token`,
|
||||||
|
the SSO's `public_key`, and your capabilities.
|
||||||
4. **Service**: Set up as a systemd unit (example: `/etc/systemd/system/theta-agent.service`).
|
4. **Service**: Set up as a systemd unit (example: `/etc/systemd/system/theta-agent.service`).
|
||||||
|
|
||||||
For the fastest deployment, use the installation script:
|
For the fastest deployment, use the installation script:
|
||||||
@@ -79,6 +95,14 @@ For the fastest deployment, use the installation script:
|
|||||||
curl -fsSL https://sso.example.com/resources/theta-agent/install.sh | sh -s -- "BASE64_ENCODED_CONFIG"
|
curl -fsSL https://sso.example.com/resources/theta-agent/install.sh | sh -s -- "BASE64_ENCODED_CONFIG"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The **Install Agent** modal generates that command for you after enrollment,
|
||||||
|
with the token and public key already embedded. The equivalent flag form is:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -fsSL https://sso.example.com/resources/theta-agent/install.sh | sh -s -- \
|
||||||
|
--url "https://sso.example.com" --token "<ISSUED_TOKEN>" --public-key "<BASE64_PUBLIC_KEY>"
|
||||||
|
```
|
||||||
|
|
||||||
## Development & Testing
|
## Development & Testing
|
||||||
|
|
||||||
The agent uses a decoupled execution engine for safety and testability.
|
The agent uses a decoupled execution engine for safety and testability.
|
||||||
|
|||||||
+14
-1
@@ -2,7 +2,20 @@
|
|||||||
# Default location: /etc/theta42/agent.yml
|
# Default location: /etc/theta42/agent.yml
|
||||||
|
|
||||||
server_url: "https://sso.example.com"
|
server_url: "https://sso.example.com"
|
||||||
auth_token: "REPLACE_WITH_AGENT_TOKEN"
|
|
||||||
|
# Issued by the SSO when you enroll this host (Directory -> Install Agent, or
|
||||||
|
# POST /api/agent/enroll). The server records only its hash and rejects any
|
||||||
|
# token it did not issue, so a value invented locally will not connect.
|
||||||
|
auth_token: "REPLACE_WITH_ISSUED_AGENT_TOKEN"
|
||||||
|
|
||||||
|
# Base64 of the SSO's RAW 32-byte Ed25519 public key -- the `publicKey` value
|
||||||
|
# from enrollment or GET /api/agent/nodes. This is NOT a PEM body.
|
||||||
|
#
|
||||||
|
# Required for any high-risk command. Without it the agent still reports
|
||||||
|
# telemetry, but REFUSES reboot / service_restart / configure_ldap /
|
||||||
|
# arbitrary_bash / update_binary, because it has no way to verify them.
|
||||||
|
public_key: "REPLACE_WITH_SSO_PUBLIC_KEY"
|
||||||
|
|
||||||
location: "default" # Location identifier (e.g., site, datacenter) for naming
|
location: "default" # Location identifier (e.g., site, datacenter) for naming
|
||||||
|
|
||||||
capabilities:
|
capabilities:
|
||||||
|
|||||||
+23
-1
@@ -50,6 +50,7 @@ install_sssd_deps() {
|
|||||||
# 2. Argument Parsing
|
# 2. Argument Parsing
|
||||||
URL=""
|
URL=""
|
||||||
TOKEN=""
|
TOKEN=""
|
||||||
|
PUBLIC_KEY=""
|
||||||
B64_CONFIG=""
|
B64_CONFIG=""
|
||||||
INSTALL_SSSD=0
|
INSTALL_SSSD=0
|
||||||
|
|
||||||
@@ -63,6 +64,14 @@ while [[ $# -gt 0 ]]; do
|
|||||||
TOKEN="$2"
|
TOKEN="$2"
|
||||||
shift 2
|
shift 2
|
||||||
;;
|
;;
|
||||||
|
# Base64 of the SSO's raw Ed25519 public key. The agent verifies high-risk
|
||||||
|
# commands (reboot, configure_ldap, arbitrary_bash, update_binary) against
|
||||||
|
# it and REFUSES them when it is absent, so an install without this key can
|
||||||
|
# stream telemetry but cannot be acted on.
|
||||||
|
--public-key)
|
||||||
|
PUBLIC_KEY="$2"
|
||||||
|
shift 2
|
||||||
|
;;
|
||||||
--install-sssd|--ldap)
|
--install-sssd|--ldap)
|
||||||
INSTALL_SSSD=1
|
INSTALL_SSSD=1
|
||||||
shift
|
shift
|
||||||
@@ -79,7 +88,10 @@ if [ -z "$B64_CONFIG" ] && [ -z "$URL" ] || [ -z "$B64_CONFIG" ] && [ -z "$TOKEN
|
|||||||
error "Missing required configuration. Either provide a base64 encoded config, or both --url and --token."
|
error "Missing required configuration. Either provide a base64 encoded config, or both --url and --token."
|
||||||
echo "Usage examples:"
|
echo "Usage examples:"
|
||||||
echo " sh install.sh \"BASE64_CONFIG\""
|
echo " sh install.sh \"BASE64_CONFIG\""
|
||||||
echo " sh install.sh --url \"https://sso.local\" --token \"secret-token\" --install-sssd"
|
echo " sh install.sh --url \"https://sso.local\" --token \"ISSUED_TOKEN\" --public-key \"BASE64_KEY\" --install-sssd"
|
||||||
|
echo ""
|
||||||
|
echo "The token must be issued by the SSO (Directory -> Install Agent enrolls"
|
||||||
|
echo "the host and mints it). Tokens the server did not issue are rejected."
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -104,6 +116,7 @@ else
|
|||||||
cat <<EOF > "$CONFIG_FILE"
|
cat <<EOF > "$CONFIG_FILE"
|
||||||
server_url: "$URL"
|
server_url: "$URL"
|
||||||
auth_token: "$TOKEN"
|
auth_token: "$TOKEN"
|
||||||
|
public_key: "$PUBLIC_KEY"
|
||||||
location: "unknown"
|
location: "unknown"
|
||||||
capabilities:
|
capabilities:
|
||||||
telemetry: true
|
telemetry: true
|
||||||
@@ -115,6 +128,15 @@ EOF
|
|||||||
fi
|
fi
|
||||||
chmod 600 "$CONFIG_FILE"
|
chmod 600 "$CONFIG_FILE"
|
||||||
|
|
||||||
|
# An agent with no public_key cannot verify signed commands and will refuse
|
||||||
|
# every one of them. That is the safe default, but it is silent at run time, so
|
||||||
|
# say it plainly here where the operator is watching.
|
||||||
|
if ! grep -qE '^public_key:[[:space:]]*"[^"]+"' "$CONFIG_FILE" 2>/dev/null; then
|
||||||
|
log "WARNING: no public_key configured — this agent will report telemetry but"
|
||||||
|
log " REFUSE reboot / configure_ldap / arbitrary_bash / update_binary."
|
||||||
|
log " Re-run with --public-key \"<base64 key>\" (shown at enrollment)."
|
||||||
|
fi
|
||||||
|
|
||||||
# 4b. Ensure SSSD dependencies are installed if configure_ldap is enabled
|
# 4b. Ensure SSSD dependencies are installed if configure_ldap is enabled
|
||||||
if [ "$INSTALL_SSSD" -eq 1 ] || grep -q -i "configure_ldap:\s*true" "$CONFIG_FILE" 2>/dev/null; then
|
if [ "$INSTALL_SSSD" -eq 1 ] || grep -q -i "configure_ldap:\s*true" "$CONFIG_FILE" 2>/dev/null; then
|
||||||
install_sssd_deps
|
install_sssd_deps
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cross-implementation check: a payload signed by the Node server (utils/
|
||||||
|
// agent_manager.js) must verify with the agent's own verifySignature. Skips
|
||||||
|
// unless the fixture is present, so it never breaks a normal `go test`.
|
||||||
|
func TestInteropWithServerSignature(t *testing.T) {
|
||||||
|
raw, err := os.ReadFile(os.Getenv("INTEROP_FIXTURE"))
|
||||||
|
if err != nil {
|
||||||
|
t.Skip("no INTEROP_FIXTURE provided")
|
||||||
|
}
|
||||||
|
var fx struct {
|
||||||
|
Pub string `json:"pub"`
|
||||||
|
Payload map[string]interface{} `json:"payload"`
|
||||||
|
Sig string `json:"sig"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &fx); err != nil {
|
||||||
|
t.Fatalf("bad fixture: %v", err)
|
||||||
|
}
|
||||||
|
payload := map[string]interface{}{}
|
||||||
|
for k, v := range fx.Payload {
|
||||||
|
payload[k] = v
|
||||||
|
}
|
||||||
|
payload["signature"] = fx.Sig
|
||||||
|
|
||||||
|
cfg := &Config{PublicKey: fx.Pub}
|
||||||
|
if !verifySignature(cfg, WSMessage{Type: "arbitrary_bash", Payload: payload}) {
|
||||||
|
t.Fatal("agent REJECTED a signature produced by the SSO server")
|
||||||
|
}
|
||||||
|
t.Log("agent accepted the server-produced signature")
|
||||||
|
}
|
||||||
+82
-7
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"crypto/ed25519"
|
"crypto/ed25519"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
@@ -23,14 +24,55 @@ type WSMessage struct {
|
|||||||
Payload map[string]interface{} `json:"payload"`
|
Payload map[string]interface{} `json:"payload"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Application close codes the SSO uses to say "your enrollment is the problem"
|
||||||
|
// (PROTOCOL.md §1.1). All three mean retrying quickly is pointless.
|
||||||
|
const (
|
||||||
|
closeUnauthorized = 4001 // token was never issued, or is unknown
|
||||||
|
closeSuperseded = 4002 // another connection took over this enrollment
|
||||||
|
closeRevoked = 4003 // enrollment revoked or deleted by an admin
|
||||||
|
closeTokenRotated = 4004 // token rotated; agent.yml holds the old one
|
||||||
|
)
|
||||||
|
|
||||||
|
// How long to wait before retrying after the server rejects our credential.
|
||||||
|
// Short enough that a re-enrollment is picked up without a restart, long enough
|
||||||
|
// that a decommissioned agent is not a permanent load on the SSO.
|
||||||
|
const authRetryInterval = 5 * time.Minute
|
||||||
|
|
||||||
type MessageWriter interface {
|
type MessageWriter interface {
|
||||||
WriteMessage(messageType int, data []byte) error
|
WriteMessage(messageType int, data []byte) error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// canonicalize produces the exact bytes the server signed (PROTOCOL.md §5):
|
||||||
|
// keys sorted alphabetically, no whitespace, `signature` omitted.
|
||||||
|
//
|
||||||
|
// encoding/json sorts map keys for us, but by default it also escapes <, > and
|
||||||
|
// & as <, > and & -- which Node's JSON.stringify on the server
|
||||||
|
// does not. Any payload containing those characters therefore hashed
|
||||||
|
// differently on each side and the signature failed. For arbitrary_bash that is
|
||||||
|
// most real scripts: `>` redirection and `&&` are everywhere. SetEscapeHTML
|
||||||
|
// (false) is what makes the two encoders agree.
|
||||||
|
//
|
||||||
|
// Encoder.Encode also appends a trailing newline, which must be trimmed or it
|
||||||
|
// is signed-over data the server never produced.
|
||||||
|
func canonicalize(payload map[string]interface{}) ([]byte, error) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
enc := json.NewEncoder(&buf)
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
if err := enc.Encode(payload); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return bytes.TrimRight(buf.Bytes(), "\n"), nil
|
||||||
|
}
|
||||||
|
|
||||||
func verifySignature(cfg *Config, msg WSMessage) bool {
|
func verifySignature(cfg *Config, msg WSMessage) bool {
|
||||||
|
// Fail CLOSED. This used to return true when no public key was configured,
|
||||||
|
// which meant an agent installed without a `public_key` would execute
|
||||||
|
// reboot / configure_ldap / arbitrary_bash from anything that could reach
|
||||||
|
// its socket, with no verification at all -- the exact commands the
|
||||||
|
// signature exists to protect. An agent that cannot verify must not act.
|
||||||
if cfg.PublicKey == "" {
|
if cfg.PublicKey == "" {
|
||||||
log.Println("No public key configured; skipping signature verification")
|
log.Println("Refusing high-risk command: no public_key configured in agent.yml")
|
||||||
return true
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
sigB64, ok := msg.Payload["signature"].(string)
|
sigB64, ok := msg.Payload["signature"].(string)
|
||||||
@@ -52,7 +94,11 @@ func verifySignature(cfg *Config, msg WSMessage) bool {
|
|||||||
payloadCopy[k] = v
|
payloadCopy[k] = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
canonicalPayload, _ := json.Marshal(payloadCopy)
|
canonicalPayload, err := canonicalize(payloadCopy)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Could not canonicalize payload for verification: %v", err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
pubKeyBytes, err := base64.StdEncoding.DecodeString(cfg.PublicKey)
|
pubKeyBytes, err := base64.StdEncoding.DecodeString(cfg.PublicKey)
|
||||||
if err != nil || len(pubKeyBytes) != ed25519.PublicKeySize {
|
if err != nil || len(pubKeyBytes) != ed25519.PublicKeySize {
|
||||||
@@ -75,12 +121,22 @@ func connectWebSocket(cm *ConfigManager, exec Executor) {
|
|||||||
log.Fatalf("Invalid ServerURL: %v", err)
|
log.Fatalf("Invalid ServerURL: %v", err)
|
||||||
}
|
}
|
||||||
u.Path = "/api/agent/ws"
|
u.Path = "/api/agent/ws"
|
||||||
u.RawQuery = "token=" + cfg.AuthToken
|
u.RawQuery = "token=" + url.QueryEscape(cfg.AuthToken)
|
||||||
|
|
||||||
log.Printf("Connecting to %s", u.String())
|
// Never log u.String(): RawQuery carries the auth token, and agent logs
|
||||||
|
// are routinely shipped around and pasted into issues.
|
||||||
|
log.Printf("Connecting to %s%s", u.Host, u.Path)
|
||||||
|
|
||||||
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
|
c, resp, err := websocket.DefaultDialer.Dial(u.String(), nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
// The server now rejects tokens it did not issue. Retrying a bad
|
||||||
|
// credential every 5s just floods the SSO and its audit log
|
||||||
|
// forever, so back off hard and say plainly what is wrong.
|
||||||
|
if resp != nil && (resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden) {
|
||||||
|
log.Printf("Server rejected our token (HTTP %d). Enroll this agent in the SSO Directory and put the issued token in agent.yml. Retrying in %s.", resp.StatusCode, authRetryInterval)
|
||||||
|
time.Sleep(authRetryInterval)
|
||||||
|
continue
|
||||||
|
}
|
||||||
log.Printf("Dial error: %v. Retrying in 5 seconds...", err)
|
log.Printf("Dial error: %v. Retrying in 5 seconds...", err)
|
||||||
time.Sleep(5 * time.Second)
|
time.Sleep(5 * time.Second)
|
||||||
continue
|
continue
|
||||||
@@ -111,11 +167,24 @@ func connectWebSocket(cm *ConfigManager, exec Executor) {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
// Set when the server closes us for an enrollment problem rather than a
|
||||||
|
// transient fault, so the reconnect below can back off instead of
|
||||||
|
// spinning on a credential that will not start working by itself.
|
||||||
|
authRejected := false
|
||||||
|
|
||||||
// Read loop
|
// Read loop
|
||||||
for {
|
for {
|
||||||
_, message, err := c.ReadMessage()
|
_, message, err := c.ReadMessage()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("WebSocket read error:", err)
|
// The SSO accepts the upgrade and only then closes with an
|
||||||
|
// application code, so an auth failure surfaces here rather
|
||||||
|
// than at Dial.
|
||||||
|
if websocket.IsCloseError(err, closeUnauthorized, closeRevoked, closeTokenRotated) {
|
||||||
|
authRejected = true
|
||||||
|
log.Printf("Server closed the connection: %v. This agent's token is not valid for that SSO — re-enroll it and update agent.yml.", err)
|
||||||
|
} else {
|
||||||
|
log.Println("WebSocket read error:", err)
|
||||||
|
}
|
||||||
break // break read loop, reconnect
|
break // break read loop, reconnect
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -132,6 +201,12 @@ func connectWebSocket(cm *ConfigManager, exec Executor) {
|
|||||||
close(stopCh)
|
close(stopCh)
|
||||||
c.Close()
|
c.Close()
|
||||||
|
|
||||||
|
if authRejected {
|
||||||
|
log.Printf("Reconnecting in %s.", authRetryInterval)
|
||||||
|
time.Sleep(authRetryInterval)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
log.Println("WebSocket disconnected. Reconnecting in 5 seconds...")
|
log.Println("WebSocket disconnected. Reconnecting in 5 seconds...")
|
||||||
time.Sleep(5 * time.Second)
|
time.Sleep(5 * time.Second)
|
||||||
}
|
}
|
||||||
|
|||||||
+118
-10
@@ -1,11 +1,42 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/ed25519"
|
||||||
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"os"
|
"os"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// A fixed key pair for the tests, standing in for the SSO's persisted signing
|
||||||
|
// key. High-risk commands must now be genuinely signed: the agent fails closed
|
||||||
|
// when no public_key is configured, so these tests sign the way the server
|
||||||
|
// does instead of relying on verification being skipped.
|
||||||
|
var testPubKey, testPrivKey, _ = ed25519.GenerateKey(nil)
|
||||||
|
|
||||||
|
func testPubKeyB64() string {
|
||||||
|
return base64.StdEncoding.EncodeToString(testPubKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
// sign mirrors the server's canonicalization (sorted keys, no whitespace, no
|
||||||
|
// HTML escaping, `signature` omitted) and adds the signature to the payload.
|
||||||
|
func sign(t *testing.T, payload map[string]interface{}) map[string]interface{} {
|
||||||
|
t.Helper()
|
||||||
|
if payload == nil {
|
||||||
|
payload = map[string]interface{}{}
|
||||||
|
}
|
||||||
|
canonical, err := canonicalize(payload)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("canonicalize: %v", err)
|
||||||
|
}
|
||||||
|
signed := make(map[string]interface{}, len(payload)+1)
|
||||||
|
for k, v := range payload {
|
||||||
|
signed[k] = v
|
||||||
|
}
|
||||||
|
signed["signature"] = base64.StdEncoding.EncodeToString(ed25519.Sign(testPrivKey, canonical))
|
||||||
|
return signed
|
||||||
|
}
|
||||||
|
|
||||||
type MockConn struct {
|
type MockConn struct {
|
||||||
Messages [][]byte
|
Messages [][]byte
|
||||||
}
|
}
|
||||||
@@ -44,13 +75,16 @@ func (m *MockExecutor) ReadFile(path string) ([]byte, error) {
|
|||||||
|
|
||||||
func TestHandleCommand(t *testing.T) {
|
func TestHandleCommand(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
cfg *Config
|
cfg *Config
|
||||||
msg WSMessage
|
msg WSMessage
|
||||||
expectedStatus string
|
expectedStatus string
|
||||||
expectedCmd []string
|
expectedCmd []string
|
||||||
expectedFile string
|
expectedFile string
|
||||||
expectedFileCont string
|
expectedFileCont string
|
||||||
|
// sign the payload with the test key before dispatch, the way the SSO
|
||||||
|
// signs high-risk commands
|
||||||
|
signed bool
|
||||||
// heartbeat_ack (and any fire-and-forget ack) must be silently ignored —
|
// heartbeat_ack (and any fire-and-forget ack) must be silently ignored —
|
||||||
// no response message, no command, no log noise.
|
// no response message, no command, no log noise.
|
||||||
expectedNoResponse bool
|
expectedNoResponse bool
|
||||||
@@ -69,11 +103,13 @@ func TestHandleCommand(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "reboot command allowed",
|
name: "reboot command allowed",
|
||||||
cfg: &Config{
|
cfg: &Config{
|
||||||
|
PublicKey: testPubKeyB64(),
|
||||||
Capabilities: Capabilities{Reboot: true},
|
Capabilities: Capabilities{Reboot: true},
|
||||||
},
|
},
|
||||||
msg: WSMessage{
|
msg: WSMessage{
|
||||||
Type: "reboot",
|
Type: "reboot",
|
||||||
},
|
},
|
||||||
|
signed: true,
|
||||||
expectedStatus: "ok",
|
expectedStatus: "ok",
|
||||||
expectedCmd: []string{"reboot"},
|
expectedCmd: []string{"reboot"},
|
||||||
},
|
},
|
||||||
@@ -123,6 +159,7 @@ func TestHandleCommand(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "configure_ldap allowed",
|
name: "configure_ldap allowed",
|
||||||
cfg: &Config{
|
cfg: &Config{
|
||||||
|
PublicKey: testPubKeyB64(),
|
||||||
Capabilities: Capabilities{ConfigureLDAP: true},
|
Capabilities: Capabilities{ConfigureLDAP: true},
|
||||||
},
|
},
|
||||||
msg: WSMessage{
|
msg: WSMessage{
|
||||||
@@ -131,10 +168,11 @@ func TestHandleCommand(t *testing.T) {
|
|||||||
"config": "domain = theta42.local\nserver = sso.local",
|
"config": "domain = theta42.local\nserver = sso.local",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
expectedStatus: "ok",
|
signed: true,
|
||||||
expectedFile: "/etc/sssd/sssd.conf",
|
expectedStatus: "ok",
|
||||||
|
expectedFile: "/etc/sssd/sssd.conf",
|
||||||
expectedFileCont: "domain = theta42.local\nserver = sso.local",
|
expectedFileCont: "domain = theta42.local\nserver = sso.local",
|
||||||
expectedCmd: []string{"systemctl", "restart", "sssd"},
|
expectedCmd: []string{"systemctl", "restart", "sssd"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "configure_ldap denied",
|
name: "configure_ldap denied",
|
||||||
@@ -153,6 +191,7 @@ func TestHandleCommand(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "arbitrary_bash allowed",
|
name: "arbitrary_bash allowed",
|
||||||
cfg: &Config{
|
cfg: &Config{
|
||||||
|
PublicKey: testPubKeyB64(),
|
||||||
Capabilities: Capabilities{ArbitraryBash: true},
|
Capabilities: Capabilities{ArbitraryBash: true},
|
||||||
},
|
},
|
||||||
msg: WSMessage{
|
msg: WSMessage{
|
||||||
@@ -161,6 +200,7 @@ func TestHandleCommand(t *testing.T) {
|
|||||||
"script": "uptime",
|
"script": "uptime",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
signed: true,
|
||||||
expectedStatus: "ok",
|
expectedStatus: "ok",
|
||||||
expectedCmd: []string{"bash", "-c", "uptime"},
|
expectedCmd: []string{"bash", "-c", "uptime"},
|
||||||
},
|
},
|
||||||
@@ -205,7 +245,11 @@ func TestHandleCommand(t *testing.T) {
|
|||||||
mockConn := &MockConn{}
|
mockConn := &MockConn{}
|
||||||
mockExec := &MockExecutor{}
|
mockExec := &MockExecutor{}
|
||||||
cm := &ConfigManager{current: tc.cfg}
|
cm := &ConfigManager{current: tc.cfg}
|
||||||
handleCommand(cm, tc.msg, mockConn, mockExec)
|
msg := tc.msg
|
||||||
|
if tc.signed {
|
||||||
|
msg.Payload = sign(t, msg.Payload)
|
||||||
|
}
|
||||||
|
handleCommand(cm, msg, mockConn, mockExec)
|
||||||
|
|
||||||
if tc.expectedNoResponse {
|
if tc.expectedNoResponse {
|
||||||
if len(mockConn.Messages) != 0 {
|
if len(mockConn.Messages) != 0 {
|
||||||
@@ -259,3 +303,67 @@ func TestHandleCommand(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The agent must not execute a high-risk command it cannot verify. This used to
|
||||||
|
// return true when no public_key was configured, so an agent installed without
|
||||||
|
// one executed reboot / configure_ldap / arbitrary_bash unverified.
|
||||||
|
func TestVerifySignatureFailsClosedWithoutPublicKey(t *testing.T) {
|
||||||
|
cfg := &Config{} // no PublicKey
|
||||||
|
msg := WSMessage{Type: "arbitrary_bash", Payload: sign(t, map[string]interface{}{"script": "uptime"})}
|
||||||
|
if verifySignature(cfg, msg) {
|
||||||
|
t.Fatal("verifySignature accepted a command with no public_key configured")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifySignatureRejectsWrongKey(t *testing.T) {
|
||||||
|
otherPub, _, _ := ed25519.GenerateKey(nil)
|
||||||
|
cfg := &Config{PublicKey: base64.StdEncoding.EncodeToString(otherPub)}
|
||||||
|
msg := WSMessage{Type: "arbitrary_bash", Payload: sign(t, map[string]interface{}{"script": "uptime"})}
|
||||||
|
if verifySignature(cfg, msg) {
|
||||||
|
t.Fatal("verifySignature accepted a signature from a different key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifySignatureRejectsTamperedPayload(t *testing.T) {
|
||||||
|
cfg := &Config{PublicKey: testPubKeyB64()}
|
||||||
|
payload := sign(t, map[string]interface{}{"script": "uptime"})
|
||||||
|
payload["script"] = "rm -rf /" // swap the script, keep the signature
|
||||||
|
if verifySignature(cfg, WSMessage{Type: "arbitrary_bash", Payload: payload}) {
|
||||||
|
t.Fatal("verifySignature accepted a payload modified after signing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Regression: encoding/json escapes <, > and & by default, but the server's
|
||||||
|
// JSON.stringify does not. Any script using redirection or && therefore
|
||||||
|
// canonicalized differently on each side and failed verification -- which is
|
||||||
|
// most real scripts.
|
||||||
|
func TestVerifySignatureAcceptsShellMetacharacters(t *testing.T) {
|
||||||
|
cfg := &Config{PublicKey: testPubKeyB64()}
|
||||||
|
for _, script := range []string{
|
||||||
|
"echo hi > /tmp//out.log",
|
||||||
|
"systemctl is-active nginx && systemctl reload nginx",
|
||||||
|
"grep -c . < /etc/passwd",
|
||||||
|
"a=1 && b=2 && echo \"$a<$b\" > /dev/null",
|
||||||
|
} {
|
||||||
|
msg := WSMessage{Type: "arbitrary_bash", Payload: sign(t, map[string]interface{}{"script": script})}
|
||||||
|
if !verifySignature(cfg, msg) {
|
||||||
|
t.Errorf("verifySignature rejected a correctly signed script: %q", script)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The canonical form must be byte-identical to the server's: sorted keys, no
|
||||||
|
// whitespace, no HTML escaping, no trailing newline, signature omitted.
|
||||||
|
func TestCanonicalizeMatchesServerForm(t *testing.T) {
|
||||||
|
got, err := canonicalize(map[string]interface{}{
|
||||||
|
"script": "echo a > b && c",
|
||||||
|
"comment": "x&y",
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("canonicalize: %v", err)
|
||||||
|
}
|
||||||
|
want := `{"comment":"x&y","script":"echo a > b && c"}`
|
||||||
|
if string(got) != want {
|
||||||
|
t.Errorf("canonical form mismatch:\n got: %s\nwant: %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user