Files
archipelago/connectors/host/host.go
T
sam 2928bdb682
publish / publish (push) Successful in 1m6s
fix(host): confine lookups to each host's configured path roots
Lookups run no guards and the helpers read as root, so an instruction injected
into an event could steer the agent into listing anywhere on the host. Each
host now names the roots its lookups may look under, and any other path is
refused before a command is built.
2026-11-16 00:42:48 +11:00

196 lines
6.6 KiB
Go

package main
import (
"context"
"encoding/json/jsontext"
json "encoding/json/v2"
"errors"
"fmt"
"path"
"strconv"
"strings"
"golang.org/x/crypto/ssh"
"github.com/samcharles93/archipelago/sdk/connector"
connectorv1 "github.com/samcharles93/archipelago/sdk/connector/v1"
)
// Target is one host the connector may reach, from its hosts setting.
type Target struct {
Name string `json:"name"`
Address string `json:"address"`
// HostKey is the host's public key in authorized_keys form, as
// ssh-keyscan prints it. A host presenting any other key is refused.
HostKey string `json:"host_key"`
// Helpers runs the lookups that walk directories through the root-owned
// helpers in target/, so they see what the account alone can't read.
Helpers bool `json:"helpers"`
// Paths are the roots lookups may look under. Lookups run no guards and
// may read as root, so a path outside them is refused: an instruction
// injected into an event can't steer the agent into the rest of the host.
Paths []string `json:"paths"`
key ssh.PublicKey
}
type host struct {
targets map[string]Target
username string
signer ssh.Signer
}
func newHost(cfg connector.Config) (*host, error) {
var targets []Target
if err := json.Unmarshal([]byte(cfg.Settings["hosts"]), &targets); err != nil {
return nil, fmt.Errorf("hosts setting: %w", err)
}
h := &host{targets: map[string]Target{}, username: cfg.Secrets["ssh.username"]}
for _, t := range targets {
key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(t.HostKey))
if err != nil {
return nil, fmt.Errorf("host %q: host_key: %w", t.Name, err)
}
t.key = key
for i, root := range t.Paths {
if !path.IsAbs(root) {
return nil, fmt.Errorf("host %q: path root %q must be absolute", t.Name, root)
}
t.Paths[i] = path.Clean(root)
}
h.targets[t.Name] = t
}
pem, pass := cfg.Secrets["ssh.private_key"], cfg.Secrets["ssh.private_key_passphrase"]
if h.username == "" || pem == "" {
return nil, errNoCredential
}
var err error
if pass != "" {
h.signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(pem), []byte(pass))
} else {
h.signer, err = ssh.ParsePrivateKey([]byte(pem))
}
if err != nil {
return nil, fmt.Errorf("ssh private key: %w", err)
}
return h, nil
}
func (h *host) Describe() connector.Description {
return connector.Description{Lookups: []*connectorv1.LookupType{
{
Name: "filesystem_usage",
Description: "Size, used and available bytes and inode use of the filesystem holding a path on a host.",
InputSchema: []byte(`{"type":"object","required":["host","path"],"additionalProperties":false,"properties":{"host":{"type":"string"},"path":{"type":"string","description":"An absolute path."}}}`),
},
{
Name: "directory_sizes",
Description: "The largest entries directly under a directory on a host, by total size, staying on its filesystem.",
InputSchema: []byte(`{"type":"object","required":["host","path"],"additionalProperties":false,"properties":{"host":{"type":"string"},"path":{"type":"string","description":"An absolute path."},"limit":{"type":"integer","minimum":1,"maximum":50}}}`),
},
{
Name: "old_files",
Description: "The largest files under a directory on a host not modified for at least a number of hours, staying on its filesystem.",
InputSchema: []byte(`{"type":"object","required":["host","path"],"additionalProperties":false,"properties":{"host":{"type":"string"},"path":{"type":"string","description":"An absolute path."},"older_than_hours":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}}}`),
},
}}
}
type lookupInput struct {
Host string `json:"host"`
Path string `json:"path"`
Limit int `json:"limit"`
OlderThanHours *int `json:"older_than_hours"`
}
func (h *host) Lookup(ctx context.Context, name string, raw jsontext.Value) (jsontext.Value, bool, error) {
var in lookupInput
if err := json.Unmarshal(raw, &in); err != nil {
return nil, false, fmt.Errorf("input: %w", err)
}
target, ok := h.targets[in.Host]
if !ok {
return nil, false, fmt.Errorf("host %q isn't configured", in.Host)
}
p, err := checkPath(in.Path, target.Paths)
if err != nil {
return nil, false, err
}
limit := in.Limit
if limit <= 0 {
limit = 20
}
command, parse, err := lookupCommand(name, p, limit, in.OlderThanHours, target.Helpers)
if err != nil {
return nil, false, err
}
out, err := h.run(ctx, target, command)
if err != nil {
return nil, false, err
}
result, err := parse(out)
if err != nil {
return nil, false, fmt.Errorf("%s on %s: %w", name, in.Host, err)
}
encoded, err := json.Marshal(result)
if err != nil {
return nil, false, err
}
return encoded, true, nil
}
// lookupCommand builds the fixed command for a lookup. Every argument from
// the input is shell-quoted, because ssh hands the command to the remote
// shell.
func lookupCommand(name, p string, limit int, olderThan *int, helpers bool) (string, func([]byte) (any, error), error) {
q := quote(p)
n := strconv.Itoa(limit)
switch name {
case "filesystem_usage":
return "LC_ALL=C df -P -B1 -- " + q + " && LC_ALL=C df -P -i -- " + q, parseDF, nil
case "directory_sizes":
if helpers {
return helperDir + "directory-sizes " + q + " " + n, parseDU, nil
}
return "LC_ALL=C du -x -B1 --max-depth=1 -- " + q + " 2>/dev/null | sort -rn | head -n " + n, parseDU, nil
case "old_files":
hours := 24
if olderThan != nil {
hours = *olderThan
}
minutes := strconv.Itoa(hours * 60)
if helpers {
return helperDir + "old-files " + q + " " + minutes + " " + n, parseFind, nil
}
return "LC_ALL=C find " + q + " -xdev -type f -mmin +" + minutes +
" -printf '%s\\t%T@\\t%u\\t%p\\n' 2>/dev/null | sort -rn | head -n " + n, parseFind, nil
}
return "", nil, fmt.Errorf("no lookup named %q", name)
}
// helperDir is where target/install.sh puts the helpers, run through sudo.
const helperDir = "sudo -n /usr/local/libexec/archie/"
// checkPath accepts an absolute path with no control characters that, once
// cleaned, is one of roots or lies under one.
func checkPath(p string, roots []string) (string, error) {
if !path.IsAbs(p) {
return "", fmt.Errorf("path %q must be absolute", p)
}
if strings.ContainsFunc(p, func(r rune) bool { return r < 0x20 || r == 0x7f }) {
return "", errors.New("path contains control characters")
}
clean := path.Clean(p)
for _, root := range roots {
if clean == root || strings.HasPrefix(clean, strings.TrimSuffix(root, "/")+"/") {
return clean, nil
}
}
return "", fmt.Errorf("path %q is outside this host's lookup paths %v", clean, roots)
}
// quote makes s one single-quoted shell word.
func quote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}