Sovereignty: Let's Build the cloud agent infrastructure
In the previous article I explained why my cloud needs agents. Some information is only available on the host itself, but I want to collect it in one place. Public clouds use agents too, so why not mine? 😄
Time to build a small version. The agent is written in Go and reports the filesystems mounted on a host. A collector asks several agents for this information over HTTPS. The certificates come from a local Smallstep Certificate Authority (CA), and each host gets its own token. The collector does not need SSH access.
One operation. Known hosts. Explicit trust.
The setup
These are example addresses. Replace them with the private addresses of your own machines throughout the example:
| Role | Address |
|---|---|
| CA and collector on Calculon | 192.168.3.54 |
| Calculon agent | 192.168.3.54:9443 |
| DiskStation agent | 192.168.3.200:9443 |
| Local CA | 192.168.3.54:9000 |
The CA runs in a container. The agents run directly on the Linux hosts, so they can see the host’s mounts instead of the mounts inside a container. The collector runs on Calculon. If you run it in a container, the agents may see a different source address.
You need Linux hosts, Docker Compose on the CA host and Go on your build machine. You also need the Smallstep CLI and OpenSSL on the machine you use for administration. Run the CA setup commands as root; the agents themselves do not need root.
Before starting, configure the firewalls. Allow port 9443 on the agents only from the collector, and port 9000 on the CA only from the machines used for administration and renewal. Do not expose these ports publicly. Docker can bypass ordinary UFW rules, so check the firewall rules for your Docker setup.
Initialize the CA once
On the CA host, create a new protected directory, such as /srv/mount-demo, and run these commands from there. Do not use an existing CA directory:
umask 077
mkdir -p bootstrap root-private ca-state/config ca-state/certs ca-state/secrets ca-state/db
openssl rand -hex 32 > bootstrap/root-password
openssl rand -hex 32 > bootstrap/intermediate-password
openssl rand -hex 32 > bootstrap/provisioner-password
chown -R 1000:1000 bootstrap root-private ca-state
chmod 0700 bootstrap root-private ca-state
Store the three CA passwords in your password manager. Keep this directory out of Git and file shares. The setup container runs as UID 1000. After setup, we will make the root-key and bootstrap directories owned by root again.
Create .env with the CA’s private IP address:
CA_BIND_ADDRESS=192.168.3.54
Create compose.yaml:
x-step-image: &step-image smallstep/step-ca:0.30.2@sha256:a2b17872915c193259b75a5474c398326f41bd199f0842093e52cf4182bc8270
services:
init:
image: *step-image
profiles: [setup]
user: "1000:1000"
environment:
STEPPATH: /home/step
CA_BIND_ADDRESS: ${CA_BIND_ADDRESS:?}
entrypoint: ["/bin/sh", "-ec"]
command:
- |
umask 077
test ! -e /home/step/config/ca.json
test ! -e /root-private/root_ca_key
step certificate create "Mount Demo Root CA" \
/root-private/root_ca.crt /root-private/root_ca_key \
--profile root-ca --not-after 87600h \
--password-file /bootstrap/root-password
step ca init --deployment-type standalone --name "Mount Demo CA" \
--root /root-private/root_ca.crt --key /root-private/root_ca_key \
--key-password-file /bootstrap/root-password \
--password-file /bootstrap/intermediate-password \
--provisioner-password-file /bootstrap/provisioner-password \
--provisioner agents-bootstrap --address :9000 \
--dns ca --dns "$${CA_BIND_ADDRESS}" \
--with-ca-url "https://$${CA_BIND_ADDRESS}:9000"
test ! -e /home/step/secrets/root_ca_key
cp /bootstrap/intermediate-password /home/step/secrets/password
chmod 0600 /home/step/secrets/password
volumes:
- ./ca-state:/home/step
- ./root-private:/root-private
- ./bootstrap:/bootstrap:ro
ca:
image: *step-image
restart: unless-stopped
user: "1000:1000"
entrypoint: ["/usr/local/bin/step-ca"]
command: ["/home/step/config/ca.json", "--password-file", "/home/step/secrets/password"]
environment:
STEPPATH: /home/step
ports:
- "${CA_BIND_ADDRESS:?}:9000:9000"
read_only: true
cap_drop: [ALL]
cap_add: [NET_BIND_SERVICE]
security_opt: ["no-new-privileges:true"]
tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=16m
volumes:
- ./ca-state/config:/home/step/config:ro
- ./ca-state/certs:/home/step/certs:ro
- ./ca-state/secrets:/home/step/secrets:ro
- ./ca-state/db:/home/step/db
The image is pinned to a specific version, so the example uses the same image each time. Check for newer releases before using it. The container needs NET_BIND_SERVICE because of a capability set on the executable.
Run the setup and only continue if it succeeds:
docker compose --profile setup run --rm init
Then protect the setup files and start the CA:
chown -R root:root root-private bootstrap
chmod 0700 root-private bootstrap
docker compose up -d ca
step certificate fingerprint ca-state/certs/root_ca.crt
step ca health --ca-url https://192.168.3.54:9000 --root ca-state/certs/root_ca.crt
Record the root certificate’s fingerprint over a trusted connection. The running CA cannot access the root key through its container mounts, but host and Docker administrators can still access the key on the host. This is not an offline root.
Back up the CA files and encrypted keys, and store the passwords separately. If setup fails, inspect what happened before trying again. Repeating the command until it works is not my favourite CA recovery strategy.
Give each host its own identity
On the CA host, create directories for the certificates and issue one for each host:
umask 077
mkdir -p enroll/calculon enroll/diskstation
step ca certificate calculon enroll/calculon/tls.crt enroll/calculon/tls.key \
--san 192.168.3.54 --ca-url https://192.168.3.54:9000 \
--root ca-state/certs/root_ca.crt --provisioner agents-bootstrap \
--provisioner-password-file bootstrap/provisioner-password
step ca certificate diskstation enroll/diskstation/tls.crt enroll/diskstation/tls.key \
--san 192.168.3.200 --ca-url https://192.168.3.54:9000 \
--root ca-state/certs/root_ca.crt --provisioner agents-bootstrap \
--provisioner-password-file bootstrap/provisioner-password
openssl rand -hex 32 > enroll/calculon/token
openssl rand -hex 32 > enroll/diskstation/token
Each token contains 32 random bytes, written as 64 hexadecimal characters. Each certificate includes its host’s IP address, because that is how the collector connects to it.
Send each host its own certificate, private key and token over a trusted connection. The collector needs the public root certificate and the tokens, not the private keys or CA passwords. Remove the temporary copies afterwards. For a larger setup, you can generate the keys on each host instead.
A tiny shared contract
On the build machine, create a Go module:
mkdir mount-demo
cd mount-demo
go mod init example.net/mount-demo
mkdir -p internal/protocol cmd/agent cmd/collector
Put this in internal/protocol/protocol.go:
package protocol
import (
"encoding/hex"
"errors"
"os"
"strings"
"time"
)
type Mount struct {
MountPoint string `json:"mountPoint"`
Source string `json:"source"`
FileSystem string `json:"fileSystem"`
ReadOnly bool `json:"readOnly"`
}
type Snapshot struct {
SchemaVersion int `json:"schemaVersion"`
ServerID string `json:"serverId"`
Hostname string `json:"hostname"`
CollectedAt time.Time `json:"collectedAt"`
Mounts []Mount `json:"mounts"`
}
func ReadToken(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
token := strings.TrimSpace(string(data))
decoded, err := hex.DecodeString(token)
if err != nil || len(decoded) != 32 {
return "", errors.New("expected a 32-byte hexadecimal token")
}
return token, nil
}
Both programs use this package, so they handle the response and tokens in the same way.
The host agent
Put this in cmd/agent/main.go:
package main
import (
"crypto/sha256"
"crypto/subtle"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"io"
"log"
"net"
"net/http"
"net/netip"
"os"
"runtime"
"strings"
"time"
"example.net/mount-demo/internal/protocol"
)
const maxBytes = 4 << 20
var unescape = strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`)
func readMounts() ([]protocol.Mount, error) {
file, err := os.Open("/proc/self/mountinfo")
if err != nil {
return nil, err
}
defer file.Close()
data, err := io.ReadAll(io.LimitReader(file, maxBytes+1))
if err != nil || len(data) > maxBytes {
return nil, errors.New("mount table unavailable or too large")
}
mounts := []protocol.Mount{}
for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
fields := strings.Fields(line)
separator := -1
for position, field := range fields {
if field == "-" {
separator = position
break
}
}
if separator < 6 || separator+3 >= len(fields) {
return nil, errors.New("invalid mount table")
}
options := "," + fields[5] + "," + fields[separator+3] + ","
mounts = append(mounts, protocol.Mount{
MountPoint: unescape.Replace(fields[4]),
Source: unescape.Replace(fields[separator+2]),
FileSystem: fields[separator+1],
ReadOnly: strings.Contains(options, ",ro,"),
})
}
return mounts, nil
}
func main() {
serverID := flag.String("id", "", "stable server identifier")
listen := flag.String("listen", "", "private IPv4 address and port")
collector := flag.String("collector", "", "allowed collector IPv4 address")
tokenFile := flag.String("token", "/etc/mount-agent/token", "token file")
certFile := flag.String("cert", "/etc/mount-agent/tls.crt", "certificate chain")
keyFile := flag.String("key", "/etc/mount-agent/tls.key", "private key")
flag.Parse()
address, err := netip.ParseAddrPort(*listen)
if err != nil || !address.Addr().Is4() || !address.Addr().IsPrivate() || address.Port() == 0 {
log.Fatal("listen must be a specific private IPv4 address and nonzero port")
}
allowed, err := netip.ParseAddr(*collector)
if err != nil || !allowed.Is4() || !allowed.IsPrivate() {
log.Fatal("collector must be a private IPv4 address")
}
if runtime.GOOS != "linux" || *serverID == "" {
log.Fatal("Linux and a server identifier are required")
}
token, err := protocol.ReadToken(*tokenFile)
if err != nil {
log.Fatal(err)
}
hostname, err := os.Hostname()
if err != nil {
log.Fatal(err)
}
expected := sha256.Sum256([]byte("Bearer " + token))
busy := make(chan struct{}, 1)
handler := http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Cache-Control", "no-store")
writer.Header().Set("X-Content-Type-Options", "nosniff")
host, _, err := net.SplitHostPort(request.RemoteAddr)
source, parseErr := netip.ParseAddr(host)
if err != nil || parseErr != nil || source.Unmap() != allowed {
http.Error(writer, "source not allowed", http.StatusForbidden)
return
}
actual := sha256.Sum256([]byte(request.Header.Get("Authorization")))
if subtle.ConstantTimeCompare(actual[:], expected[:]) != 1 {
writer.Header().Set("WWW-Authenticate", "Bearer")
http.Error(writer, "authentication required", http.StatusUnauthorized)
return
}
if request.URL.Path != "/mounts" || request.URL.RawQuery != "" || request.URL.ForceQuery {
http.NotFound(writer, request)
return
}
if request.Method != http.MethodGet {
writer.Header().Set("Allow", "GET")
http.Error(writer, "method not allowed", http.StatusMethodNotAllowed)
return
}
select {
case busy <- struct{}{}:
defer func() { <-busy }()
default:
http.Error(writer, "collection busy", http.StatusTooManyRequests)
return
}
mounts, err := readMounts()
if err != nil {
log.Printf("mount collection: %v", err)
http.Error(writer, "collection unavailable", http.StatusServiceUnavailable)
return
}
body, err := json.Marshal(protocol.Snapshot{
SchemaVersion: 1, ServerID: *serverID, Hostname: hostname,
CollectedAt: time.Now().UTC(), Mounts: mounts,
})
if err != nil || len(body) > maxBytes {
http.Error(writer, "snapshot unavailable", http.StatusServiceUnavailable)
return
}
writer.Header().Set("Content-Type", "application/json")
_, _ = writer.Write(body)
})
server := &http.Server{
Addr: *listen, Handler: handler,
TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12},
ReadHeaderTimeout: 3 * time.Second, ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second,
MaxHeaderBytes: 8192,
}
log.Fatal(server.ListenAndServeTLS(*certFile, *keyFile))
}
The agent reads the mounts it can see, including virtual filesystems. It returns a few fields without the raw mount options. Before reading the mounts, it checks the token and the address of the caller. It does not accept paths or commands.
Install without giving it root
Build the programs on your Go machine for the target architecture:
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o mount-agent ./cmd/agent
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o mount-collector ./cmd/collector
Run the second command after adding the collector code below. For ARM64, use GOARCH=arm64. Check that your Go version supports the target kernel, especially on older NAS devices.
On each systemd host, create an account for the agent without a login shell or access to Docker. Install the binary as root and do not let the agent account change it. Give the agent read access to its own token, key and certificate:
/usr/local/bin/mount-agent root:root 0755
/etc/mount-agent/ root:mountagent 0750
/etc/mount-agent/token root:mountagent 0640
/etc/mount-agent/tls.crt root:mountagent 0640
/etc/mount-agent/tls.key root:mountagent 0640
Use the certificate, key and token created for each host. Check that the agent account can read /proc/self/mountinfo.
A small mount-agent.service for Calculon:
[Unit]
Description=Read-only mount observer
After=network-online.target
Wants=network-online.target
[Service]
User=mountagent
Group=mountagent
ExecStart=/usr/local/bin/mount-agent -id calculon -listen 192.168.3.54:9443 -collector 192.168.3.54
Restart=on-failure
RestartSec=5
NoNewPrivileges=true
CapabilityBoundingSet=
UMask=0077
[Install]
WantedBy=multi-user.target
After installing the service and configuring the firewall, run systemctl daemon-reload and systemctl enable --now mount-agent as an administrator. Set the ID and listening address for each host. If you add settings that isolate the filesystem, check that the agent still sees the host’s mounts.
On my Synology, I need a different way to start the agent. A systemd service does not magically turn my NAS into a systemd host.
Query several hosts
On the collector machine, store the list of agents and their credentials:
collector/
agents.json
root_ca.crt
credentials/
calculon.token
diskstation.token
Copy the public root certificate over a trusted connection and compare its fingerprint with the one recorded earlier. Only the collector account should have access to the token files.
Put this in agents.json:
[
{
"serverId": "calculon",
"url": "https://192.168.3.54:9443",
"tokenFile": "credentials/calculon.token"
},
{
"serverId": "diskstation",
"url": "https://192.168.3.200:9443",
"tokenFile": "credentials/diskstation.token"
}
]
Put this in cmd/collector/main.go:
package main
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/netip"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"example.net/mount-demo/internal/protocol"
)
type Host struct {
ServerID string `json:"serverId"`
URL string `json:"url"`
TokenFile string `json:"tokenFile"`
}
type Result struct {
ServerID string `json:"serverId"`
Snapshot *protocol.Snapshot `json:"snapshot,omitempty"`
Error string `json:"error,omitempty"`
}
func fetch(client *http.Client, host Host) (*protocol.Snapshot, error) {
endpoint, err := url.Parse(host.URL)
if err != nil {
return nil, errors.New("invalid agent URL")
}
address, err := netip.ParseAddr(endpoint.Hostname())
if err != nil || !address.Is4() || !address.IsPrivate() ||
endpoint.Scheme != "https" || endpoint.Port() != "9443" ||
endpoint.User != nil || endpoint.Path != "" || endpoint.RawQuery != "" ||
endpoint.ForceQuery || endpoint.Fragment != "" {
return nil, errors.New("expected a private HTTPS origin on port 9443")
}
token, err := protocol.ReadToken(host.TokenFile)
if err != nil {
return nil, errors.New("host credential unavailable")
}
request, err := http.NewRequest(http.MethodGet, host.URL+"/mounts", nil)
if err != nil {
return nil, err
}
request.Header.Set("Authorization", "Bearer "+token)
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("agent returned HTTP %d", response.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(response.Body, (4<<20)+1))
if err != nil || len(body) > 4<<20 {
return nil, errors.New("invalid response size or body")
}
var snapshot protocol.Snapshot
if err := json.Unmarshal(body, &snapshot); err != nil {
return nil, errors.New("invalid snapshot JSON")
}
if snapshot.SchemaVersion != 1 || snapshot.ServerID != host.ServerID ||
snapshot.Hostname == "" || snapshot.CollectedAt.IsZero() || len(snapshot.Mounts) == 0 ||
snapshot.CollectedAt.After(time.Now().Add(5*time.Minute)) {
return nil, errors.New("snapshot identity, version or metadata mismatch")
}
for _, mount := range snapshot.Mounts {
if !strings.HasPrefix(mount.MountPoint, "/") || mount.Source == "" || mount.FileSystem == "" {
return nil, errors.New("invalid mount record")
}
}
return &snapshot, nil
}
func main() {
if len(os.Args) != 2 {
log.Fatal("usage: mount-collector /path/to/agents.json")
}
directory := filepath.Dir(os.Args[1])
root, err := os.ReadFile(filepath.Join(directory, "root_ca.crt"))
if err != nil {
log.Fatal(err)
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(root) {
log.Fatal("invalid CA root")
}
data, err := os.ReadFile(os.Args[1])
if err != nil {
log.Fatal(err)
}
var hosts []Host
if err := json.Unmarshal(data, &hosts); err != nil || len(hosts) == 0 || len(hosts) > 64 {
log.Fatal("expected an inventory of 1 to 64 hosts")
}
seen := map[string]bool{}
for _, host := range hosts {
if host.ServerID == "" || host.TokenFile == "" || seen[host.ServerID] {
log.Fatal("missing or duplicate host identity or missing token path")
}
seen[host.ServerID] = true
}
transport := &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12},
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
MaxResponseHeaderBytes: 16 << 10,
}
defer transport.CloseIdleConnections()
client := &http.Client{
Transport: transport, Timeout: 10 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
results := []Result{}
failed := false
for _, host := range hosts {
if !filepath.IsAbs(host.TokenFile) {
host.TokenFile = filepath.Join(directory, host.TokenFile)
}
snapshot, err := fetch(client, host)
result := Result{ServerID: host.ServerID, Snapshot: snapshot}
if err != nil {
result.Error = err.Error()
failed = true
}
results = append(results, result)
}
if err := json.NewEncoder(os.Stdout).Encode(results); err != nil {
log.Fatal(err)
}
if failed {
os.Exit(1)
}
}
The collector checks the certificate, its expiry date and the host’s IP address. It also checks that the returned serverId matches the host it asked. It queries the hosts one at a time, with a ten-second timeout, so one failure does not stop the others.
Run the compiled collector with the inventory path:
./mount-collector ./collector/agents.json
The output contains the mount information or an error for each host. If any host fails, the collector exits with a non-zero code. This version does not save the results. If you add storage, keep the collection time and mark old data when a refresh fails.
Test it
First check that both hosts return their own server ID and list of mounts. Then try a few things that should fail:
- Use a wrong token for one host: that host rejects the request, while the other still returns data.
- Use a trusted certificate with the wrong IP address: the TLS check fails.
- Send a request from an address that is not allowed: the agent or firewall blocks it.
- Stop one agent: its request fails, but the other host still returns data.
- Change a
serverIdin the list: the collector rejects the response.
From the collector host, curl --cacert root_ca.crt https://192.168.3.200:9443/mounts should return HTTP 401 because it has no token. The output shows how your hosts are set up, so keep it private.
Renew the certificate
By default, Smallstep certificates expire after 24 hours, so they need to be renewed in time. This example loads the certificate at startup, so the agent needs a restart after renewal.
step ca renew /etc/mount-agent/tls.crt /etc/mount-agent/tls.key \
--out /etc/mount-agent/tls.next.crt \
--ca-url https://192.168.3.54:9000 --root /etc/mount-agent/root_ca.crt
step certificate verify /etc/mount-agent/tls.next.crt \
--roots /etc/mount-agent/root_ca.crt
install -o root -g mountagent -m 0640 /etc/mount-agent/tls.next.crt /etc/mount-agent/tls.crt
systemctl restart mount-agent
rm /etc/mount-agent/tls.next.crt
Run these commands as an administrator after installing the verified public root certificate. Stop if a command fails. Smallstep uses the agent’s current certificate and private key to approve the renewal. The API token is separate and does not change.
What did we achieve?
The CA signs the certificates, the agents report mounts and the collector checks the answers. This example is smaller than my current setup. I left out things like automatic renewal, but it still lets me ask several machines about their mounts without giving the collector a remote shell.
