Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions docs/adr/0018-fix-text-comes-from-the-rules.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# 0018. Fix text comes from the rules, not from a host; no shell commands in rules

- Status: Accepted
- Date: 2026-11-24

## Context

The remediation page (v0.47) shows how to fix a failing control next to the hosts that fail it. The next step proposed was
per-distribution fix commands: an optional `fix:` map in a check (`debian`, `rhel`) of shell commands, shown in `explain`,
the reports, the dashboard and the result document, proven by an e2e run that applies them to a stock container of each
supported distribution and scans it again.

A review against the proposal found it unsafe as written:

- **The trust path.** A result carries its fix text (`remediation`, `remediationKo`), the server stores it after checking
only its length and that it is text, and the dashboard's evidence view shows it as it came. A host that is compromised,
or anyone with its ingest token, can therefore put any text there, and the dashboard presents it as the project's
guidance. Prose that misleads does little harm; a command that an administrator copies and runs as root on many hosts
turns a compromised host into a compromised fleet, through a person. That is the outcome VISION principle 3 rules out.
Policy packs are trusted like `vmsctl.yaml` (ADR 0012), not reviewed by the project.
- **The proof proves too little.** In a container, sysctl, service and kernel checks are NOT_APPLICABLE, so their commands
pass untested. One run does not show that a command is idempotent (`sed -i '1i …'` adds a line every time), that it
works alone, or that the host stays usable (`PasswordAuthentication no` without keys, a PAM stack rewritten by
`authselect --force`, which drops sssd or MFA on a real host). `e2e/harden.sh` says it is not a hardening guide.
- **A family is not a platform.** CentOS 7, EL 9 and 10, and Amazon Linux 2023 already need different PAM steps; commands
would grow shell conditions inside rules, which every rule reviewer would then have to review as code.
- **Parameters.** Checks with `params` take values from the profile and `vmsctl.yaml`; a command with a fixed value
contradicts the policy the user set.
- **The non-goal.** VISION allows fix hints and rules out remediation. Commands grouped per family are a script in all but
name; "copy all", "export" and "let the agent run it" follow.

## Decision

1. **No shell commands in rules.** The fix stays prose (`remediation`, `remediation_ko`), which names the setting, the file
and the value, with short commands in backticks where one is exact (`chmod go-w`), as today.
2. **The dashboard shows the fix text of a built-in check from the server's own rules, never from the result.** The
evidence view asks the server for the control's rules (`GET /api/v1/controls/PROFILE/ID/info`) and shows their fix
text. When the server knows the control, only its rules speak: a check the rule does not list (one a host slipped in)
shows no fix at all. Only a control the server has no rules for (a policy pack's: 404) shows the text of the scan,
labelled as what the scan reported; any other failure to get the rules shows no fix. The CSV of a scan that the
dashboard offers is made the same way. The stored result itself (`GET /api/v1/scans/ID`) stays as the host sent it:
it is the host's document, the evidence.
3. If structured fixes come later, they must be: declarative (a target state such as a drop-in file, a key and a value,
a file mode) that vmsctl turns into text, so that parameters are respected and rules hold no shell; shown only from
the renderer's own rules, never carried in or read from a result; not allowed in policy packs; labelled with the
distributions they were tested on; each proven in a fresh container, applied twice, with only PASS counting; shown one
at a time under the prose, with no bulk copy, no script export and no execution by the agent. That needs a new ADR.

## Consequences

- A host cannot put words in the project's mouth on the dashboard: for built-in checks the fix text is the server's.
- The evidence view makes one more request the first time a control is opened (the control's rules, small; the page keeps
them while it is open, since they do not change while the server runs).
- The reports (`vmsctl report`, Markdown and HTML) still render the fix text of the results they are given; they are made
by the person who holds the results. Taking the built-in text there too is a follow-up.
- Per-distribution commands are not built. Configuration management (ComplianceAsCode, ansible-lockdown) remains the
answer for applying a baseline in bulk.
1 change: 1 addition & 0 deletions docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ Consequences. Don't edit an accepted ADR to change a decision — add a new ADR
| [0015](0015-dashboard-sign-in.md) | Signing in to the dashboard: roles with the first writing feature, an authenticating proxy for OIDC (accepted) |
| [0016](0016-images-and-packs-in-the-fleet-server.md) | Images and policy-pack results in the fleet server (accepted) |
| [0017](0017-rename-to-vmsctl.md) | The project is renamed from hostlint to vmsctl: what changes, what keeps the old name, what is accepted both ways (accepted) |
| [0018](0018-fix-text-comes-from-the-rules.md) | Fix text comes from the rules, not from a host; no shell commands in rules (accepted) |
4 changes: 2 additions & 2 deletions docs/fleet.ko.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<!-- translated from docs/fleet.md @ 5eb28a0 -->
<!-- translated from docs/fleet.md @ 1ef4873 -->
# 서버로 모아 보기

> 설계는 [ADR 0010](adr/0010-fleet-server-and-dashboard.md)에 있습니다. 호스트가 결과를 보내고, 서버가 저장해 두었다가 조회
Expand Down Expand Up @@ -303,7 +303,7 @@ curl --cacert tls.crt -H "Authorization: Bearer hlt_api_..." https://vmsctl.exam
| `GET /api/v1/trend` | 전체 호스트의 최근 추이를 하루에 한 점씩, 오래된 날부터: 호스트 수, 실패한 점검 항목이 있는 호스트 수, 그날 기준의 상태별 개수와 통과율, 그리고 그날 받은 스캔에서 각 호스트의 직전 스캔보다 악화된 항목 수(`worse`)와 해결된 항목 수(`fixed`)(`?days=30`, 1~90). 저장된 스캔으로 계산하므로 `server prune`을 하면 볼 수 있는 날짜가 달라지고, 같은 답을 30초 동안 재사용합니다 |
| `GET /api/v1/overview` | 호스트 수, 실패한 점검 항목이 있는 호스트 수, 오래 보고하지 않은 호스트 수, 상태별 개수, 심각도와 호스트 수로 정렬한 실패 점검 항목(각각 고치면 오르는 통과율 `gain`, %p 단위), 최근 악화와 최근 해결(`?staleDays=7`) |
| `GET /api/v1/hosts` | 호스트 목록과 각 호스트의 최신 스캔 개수·통과율(`?q=`, `?status=failing\|stale`, `?sort=name\|score\|last`, `?limit=`, `?offset=`, `?format=csv`, 이미지를 보려면 `?kind=image`, 레이블이 있는 호스트만 보려면 `?label=env%3Dprod`. 대시보드에서는 레이블을 눌러 거릅니다). 호스트마다 `os`, `labels`(최신 결과가 알려 준 값이고 개수에 상한이 있습니다), `agentOnline`, 최근 스캔의 통과율 `trend`도 들어 있습니다 |
| `GET /api/v1/controls`, `GET /api/v1/controls/PROFILE/ID` | 점검 항목 전체와 최신 스캔의 상태별 개수(기본 제공 프로파일이면 `area`도). 점검 항목 하나의 경우 해당 호스트(호스트마다 최신 스캔 `scanId`, 실패한 호스트는 실패가 이어지기 시작한 스캔 시각 `failingSince`), 무엇을 점검하는지, 어떻게 고치는지 |
| `GET /api/v1/controls`, `GET /api/v1/controls/PROFILE/ID` | 점검 항목 전체와 최신 스캔의 상태별 개수(기본 제공 프로파일이면 `area`도). 점검 항목 하나의 경우 해당 호스트(호스트마다 최신 스캔 `scanId`, 실패한 호스트는 실패가 이어지기 시작한 스캔 시각 `failingSince`), 무엇을 점검하는지, 어떻게 고치는지. `GET /api/v1/controls/PROFILE/ID/info`는 마지막 부분만 줍니다(서버에 규칙이 없는 점검 항목은 404). 대시보드는 기본 제공 점검의 조치 방법을 호스트가 보낸 결과가 아니라 여기서 가져오므로, 호스트가 대시보드의 조치 안내를 바꿀 수 없습니다([ADR 0018](adr/0018-fix-text-comes-from-the-rules.md)) |
| `GET /api/v1/matrix` | 모든 호스트의 모든 점검 항목의 최신 상태. 가장 많이 실패한 호스트가 먼저 나옵니다. `?format=csv`를 붙이면 스프레드시트용 표(호스트마다 한 행, 점검 항목마다 한 열, `?lang=ko`로 열 제목을 한국어로)로 받으며, 대시보드의 매트릭스 화면에서 내려받을 수 있습니다 |
| `GET /api/v1/hosts/ID` | 호스트 하나의 최신 점검 항목과 이력 |
| `GET /api/v1/scans/ID` | 저장된 결과를 받은 그대로. `?format=csv`를 붙이면 `vmsctl scan --format csv`와 같은 스프레드시트용 CSV 보고서(대시보드의 호스트 이력 화면에서 내려받을 수 있습니다) |
Expand Down
2 changes: 1 addition & 1 deletion docs/fleet.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ curl --cacert tls.crt -H "Authorization: Bearer hlt_api_..." https://vmsctl.exam
| `GET /api/v1/trend` | The fleet over the last days, one point a day, oldest first: hosts, hosts with a failing control, counts and pass rate as of that day, and `worse` and `fixed`: the controls that got worse or were fixed in the scans received that day, each against its host's previous scan (`?days=30`, 1 to 90). It is computed from the scans that are stored, so `server prune` changes the days it covers, and is served again for 30 seconds |
| `GET /api/v1/overview` | Hosts, hosts with a failing control, stale hosts, counts, the failing controls ranked by severity times hosts with the `gain` in pass rate (percentage points) of fixing each, recent regressions and recent fixes (`?staleDays=7`) |
| `GET /api/v1/hosts` | The hosts with the counts and score of their latest scan (`?q=`, `?status=failing\|stale`, `?sort=name\|score\|last`, `?limit=`, `?offset=`, `?format=csv`, `?kind=image` for the images, `?label=env%3Dprod` for the hosts with a label; the dashboard filters by a clicked label); each host also has its `os`, `labels` (what its latest result says, bounded), `agentOnline` and a `trend` of the pass rate of its latest scans |
| `GET /api/v1/controls`, `GET /api/v1/controls/PROFILE/ID` | Every control with the status counts of the latest scans (and its `area`, for a built-in profile); one control with its hosts (each with its latest scan, `scanId`, and for a failing host `failingSince`, the first scan of the run of scans that fail it), and what it checks and how to fix it |
| `GET /api/v1/controls`, `GET /api/v1/controls/PROFILE/ID` | Every control with the status counts of the latest scans (and its `area`, for a built-in profile); one control with its hosts (each with its latest scan, `scanId`, and for a failing host `failingSince`, the first scan of the run of scans that fail it), and what it checks and how to fix it; `GET /api/v1/controls/PROFILE/ID/info` is the last part alone (404 for a control the server has no rules for). The dashboard shows the fix of a built-in check from these, never from a host's result, so a host cannot change what the dashboard tells people to do ([ADR 0018](adr/0018-fix-text-comes-from-the-rules.md)) |
| `GET /api/v1/matrix` | The latest status of every control on every host, hosts that fail most first; with `?format=csv`, a sheet for a spreadsheet (a row per host, a column per control, `?lang=ko` for Korean column titles; the dashboard offers it on the matrix page) |
| `GET /api/v1/hosts/ID` | One host: its latest controls and its history |
| `GET /api/v1/scans/ID` | A stored result, exactly as received; with `?format=csv`, the CSV report of `vmsctl scan --format csv` for a spreadsheet (the dashboard offers it in the history of a host) |
Expand Down
49 changes: 49 additions & 0 deletions internal/server/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"fmt"
"net/http"
"regexp"
"slices"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -73,6 +74,7 @@ func (s *Server) routesRead(mux *http.ServeMux) {
mux.HandleFunc("GET /api/v1/matrix", s.readAPI(s.handleMatrix))
mux.HandleFunc("GET /api/v1/controls", s.readAPI(s.handleControls))
mux.HandleFunc("GET /api/v1/controls/{profile}/{id}", s.readAPI(s.handleControl))
mux.HandleFunc("GET /api/v1/controls/{profile}/{id}/info", s.readAPI(s.handleControlInfo))
mux.HandleFunc("GET /api/v1/hosts/{id}", s.readAPI(s.handleHost))
mux.HandleFunc("GET /api/v1/hosts/{id}/agent", s.readAPI(s.handleHostAgent))
mux.HandleFunc("GET /api/v1/scans/{id}", s.readAPI(s.handleScan))
Expand Down Expand Up @@ -337,6 +339,7 @@ func (s *Server) handleScan(w http.ResponseWriter, r *http.Request) {
res.Controls[i].TitleKo = s.titleKo(res.Controls[i].Profile, res.Controls[i].ID)
}
}
s.trustFixes(res)
var buf bytes.Buffer
if err := output.Write(&buf, res, "csv", output.Options{}); err != nil {
s.fail(w, err)
Expand Down Expand Up @@ -625,6 +628,52 @@ func (s *Server) controlInfo(profile, id string) *ControlInfo {
return nil
}

// trustFixes replaces, in a stored result about to be shown, the fix text of the checks of built-in controls with the server's own
// (ADR 0018). A check that the rule's control does not list gets none: a host cannot slip its own text in under a built-in control.
// The controls of a policy pack's profile keep the text of the scan (the server has no rules for them).
func (s *Server) trustFixes(res *engine.Result) {
if s.cfg.Content == nil {
return
}
byRef := map[string]*engine.CheckResult{}
for i := range res.Checks {
byRef[res.Checks[i].Ref] = &res.Checks[i]
}
for _, c := range res.Controls {
ctl := s.builtinControl(c.Profile, c.ID)
if ctl == nil {
continue
}
for _, ref := range c.Checks {
ck := byRef[ref]
if ck == nil {
continue
}
rule := s.cfg.Content.Checks[ck.ID]
if rule == nil || !slices.Contains(ctl.Checks, ck.ID) {
ck.Remediation, ck.RemediationKo = "", ""
continue
}
ck.Remediation, ck.RemediationKo = strings.TrimSpace(rule.Remediation), strings.TrimSpace(rule.RemediationKo)
}
}
}

// handleControlInfo is what a control of a built-in profile checks and how to fix it, from the server's own rules (ADR 0018): the
// fix text the dashboard shows, which a host cannot change. 404 for a control the server does not know (a policy pack's).
func (s *Server) handleControlInfo(w http.ResponseWriter, r *http.Request) {
if s.cfg.Content == nil { // not "unknown control": the dashboard would show the hosts' text for every control
writeError(w, http.StatusServiceUnavailable, "the server has no rules")
return
}
info := s.controlInfo(r.PathValue("profile"), r.PathValue("id"))
if info == nil {
writeError(w, http.StatusNotFound, "the server has no rules for this control")
return
}
writeJSON(w, http.StatusOK, info)
}

func (s *Server) handleControl(w http.ResponseWriter, r *http.Request) {
after, err := staleAfter(r)
if err != nil {
Expand Down
104 changes: 104 additions & 0 deletions internal/server/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1172,3 +1172,107 @@ func TestControlFailingSince(t *testing.T) {
t.Errorf("failing again: since %s, want %s (the last scan)", h.FailingSince, want)
}
}

// The fix text the dashboard shows for a built-in control is the server's own (ADR 0018); a control it does not know has none.
func TestControlInfo(t *testing.T) {
f := newAPIFixture(t)
content, err := engine.Load(rules.FS, profiles.FS)
if err != nil {
t.Fatal(err)
}
srv := New(Config{Store: f.store, Rate: 100000, Now: func() time.Time { return f.clock }, Content: content})
get := func(path string) (int, []byte) {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Header.Set("Authorization", "Bearer "+f.api)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.Bytes()
}
code, body := get("/api/v1/controls/kisa-2026/U-01/info")
var info ControlInfo
if err := json.Unmarshal(body, &info); code != http.StatusOK || err != nil || len(info.Checks) == 0 {
t.Fatalf("%d %s", code, body)
}
want := strings.TrimSpace(content.Checks[info.Checks[0].ID].Remediation)
if want == "" || info.Checks[0].Remediation != want {
t.Errorf("remediation %q, want the rule's %q", info.Checks[0].Remediation, want)
}
if code, _ := get("/api/v1/controls/x-acme/A-01/info"); code != http.StatusNotFound {
t.Errorf("a pack's control: %d", code)
}
// a read endpoint: not without a token
req := httptest.NewRequest(http.MethodGet, "/api/v1/controls/kisa-2026/U-01/info", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("without a token: %d", rec.Code)
}
}

// A host cannot put its own fix text in what the server shows (ADR 0018): the CSV of a scan takes the fix of a built-in check from
// the server's rules, and a check that a built-in control does not list (slipped in by the host) gets none.
func TestScanCSVFixFromRules(t *testing.T) {
f := newAPIFixture(t)
content, err := engine.Load(rules.FS, profiles.FS)
if err != nil {
t.Fatal(err)
}
srv := New(Config{Store: f.store, Rate: 100000, Now: func() time.Time { return f.clock }, Content: content})
var doc map[string]any
if err := json.Unmarshal(fixture(t, "web-01.json"), &doc); err != nil {
t.Fatal(err)
}
doc["scan"].(map[string]any)["id"] = "web-01-planted"
for _, c := range doc["checks"].([]any) {
if c.(map[string]any)["status"] == "FAIL" {
c.(map[string]any)["remediation"] = "PLANTED run this"
}
}
// a check of the host's own under the built-in control U-01, failing with its own "fix"
doc["checks"] = append(doc["checks"].([]any), map[string]any{"ref": "x-evil.fix", "id": "x-evil.fix", "title": "x", "severity": "high", "status": "FAIL", "statusSource": "observed", "remediation": "PLANTED too"})
for _, c := range doc["controls"].([]any) {
if c.(map[string]any)["id"] == "U-01" {
c.(map[string]any)["checks"] = append([]any{"x-evil.fix"}, c.(map[string]any)["checks"].([]any)...)
c.(map[string]any)["status"] = "FAIL"
}
}
raw, err := json.Marshal(doc)
if err != nil {
t.Fatal(err)
}
f.clock = f.clock.Add(time.Hour)
if code, out := post(t, f.srv, token(t, f.store, ScopeIngest, ""), raw); code != http.StatusCreated {
t.Fatalf("not stored: %d %v", code, out)
}
var scans struct {
Scans []ScanRow `json:"scans"`
}
var hosts struct {
Hosts []struct{ ID int64 } `json:"hosts"`
}
f.json(t, "/api/v1/hosts?q=web-01", &hosts)
f.json(t, "/api/v1/hosts/"+itoa(hosts.Hosts[0].ID), &scans)
req := httptest.NewRequest(http.MethodGet, "/api/v1/scans/"+itoa(scans.Scans[0].ID)+"?format=csv", nil)
req.Header.Set("Authorization", "Bearer "+f.api)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
body := rec.Body.String()
if strings.Contains(body, "PLANTED") {
t.Errorf("the host's fix text is in the CSV:\n%s", body)
}
if want := strings.Fields(strings.TrimSpace(content.Checks["ssh.permit-root-login"].Remediation))[0]; !strings.Contains(body, want) {
t.Errorf("the rule's fix is not in the CSV")
}
// a server without rules does not answer "unknown control", which would send the dashboard to the hosts' text
bare := New(Config{Store: f.store, Rate: 100000, Now: func() time.Time { return f.clock }})
req = httptest.NewRequest(http.MethodGet, "/api/v1/controls/kisa-2026/U-01/info", nil)
req.Header.Set("Authorization", "Bearer "+f.api)
rec = httptest.NewRecorder()
bare.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Errorf("without rules: %d", rec.Code)
}
}
2 changes: 2 additions & 0 deletions web/scripts/record-demo.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ for (const pair of pairs) {
for (const id of latest) await record(`/api/v1/scans/${id}`);
for (const c of controls.values()) {
await record(`/api/v1/controls/${encodeURIComponent(c.profile)}/${encodeURIComponent(c.id)}?staleDays=${STALE}`);
// the fix text of the evidence view comes from the server's rules (ADR 0018)
await record(`/api/v1/controls/${encodeURIComponent(c.profile)}/${encodeURIComponent(c.id)}/info`, { optional: true });
}

// When it was recorded: the demo moves every time forward by the age of the file, so "41 minutes ago" stays that.
Expand Down
Loading