1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
package treeaudit
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
"strings"
"github.com/johnandersen777/socialweb-computer-kcp/internal/hostsvc"
"github.com/johnandersen777/socialweb-computer-kcp/internal/kit/sha256sum"
"github.com/johnandersen777/socialweb-computer-kcp/internal/versions"
)
const (
VMPrefix = hostsvc.NamePrefix + "vm-"
MarketNetworkPrefix = hostsvc.NamePrefix + "market-network-"
MarketNetworkVMPart = "-vm-"
EnvUnit = "SWC_UNIT"
EnvInvoc = "INVOCATION_ID"
)
var VMAssets = []string{"firecracker", "pasta"}
type Proc struct {
PID int `json:"pid"`
Exe string `json:"exe,omitempty"`
SHA256 string `json:"sha256,omitempty"`
Err string `json:"err,omitempty"`
}
type Unit struct {
Name string `json:"name"`
State hostsvc.ActiveState `json:"state"`
MainPID int `json:"mainPID"`
Procs []Proc `json:"procs"`
Err string `json:"err,omitempty"`
}
type Finding struct {
Unit string `json:"unit"`
PID int `json:"pid,omitempty"`
Exe string `json:"exe,omitempty"`
SHA256 string `json:"sha256,omitempty"`
Why string `json:"why"`
}
type Report struct {
Backend hostsvc.Backend `json:"backend"`
Units []Unit `json:"units"`
Findings []Finding `json:"findings"`
}
func (r Report) Pass() bool { return len(r.Findings) == 0 }
func IsVMUnit(name string) bool {
if strings.HasPrefix(name, VMPrefix) {
return true
}
return strings.HasPrefix(name, MarketNetworkPrefix) && strings.Contains(strings.TrimPrefix(name, MarketNetworkPrefix), MarketNetworkVMPart)
}
func Judge(units []Unit, pinned map[string]string) []Finding {
var out []Finding
for _, u := range units {
switch {
case u.Err != "":
out = append(out, Finding{Unit: u.Name, Why: "its process tree could not be read: " + u.Err})
continue
case u.State != hostsvc.Active:
out = append(out, Finding{Unit: u.Name, Why: fmt.Sprintf("the unit is %s, not active: a VM unit passes only once it runs nothing but pinned assets", u.State)})
continue
case len(u.Procs) == 0:
out = append(out, Finding{Unit: u.Name, Why: "the active unit has no process"})
continue
}
for _, p := range u.Procs {
switch {
case p.Err != "":
out = append(out, Finding{Unit: u.Name, PID: p.PID, Exe: p.Exe, Why: "the executable could not be hashed: " + p.Err})
case pinned[p.SHA256] == "":
out = append(out, Finding{Unit: u.Name, PID: p.PID, Exe: p.Exe, SHA256: p.SHA256,
Why: "not a pinned VM-unit asset (" + strings.Join(VMAssets, ", ") + "): no socialweb-computer code, vmexec or trampoline shell may stay in a running VM's tree"})
}
}
}
return out
}
type Host struct {
ProcRoot string
CgroupRoot string
}
func (h Host) proc() string {
if h.ProcRoot == "" {
return "/proc"
}
return h.ProcRoot
}
func (h Host) cgroup() string {
if h.CgroupRoot == "" {
return "/sys/fs/cgroup"
}
return h.CgroupRoot
}
func (h Host) CgroupMembers(mainPID int, unit string) ([]int, error) {
if mainPID <= 0 {
return nil, fmt.Errorf("%s has no main pid", unit)
}
b, err := os.ReadFile(filepath.Join(h.proc(), strconv.Itoa(mainPID), "cgroup"))
if err != nil {
return nil, err
}
var path string
for line := range strings.SplitSeq(string(b), "\n") {
if rest, ok := strings.CutPrefix(line, "0::"); ok {
path = rest
}
}
if path == "" {
return nil, fmt.Errorf("pid %d has no cgroup v2 path", mainPID)
}
for filepath.Base(path) != unit {
if path == "/" || path == "." {
return nil, fmt.Errorf("the main pid %d of %s is not inside the unit's cgroup", mainPID, unit)
}
path = filepath.Dir(path)
}
var pids []int
err = filepath.WalkDir(filepath.Join(h.cgroup(), path), func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || d.Name() != "cgroup.procs" {
return nil
}
raw, err := os.ReadFile(p)
if err != nil {
return err
}
for f := range strings.FieldsSeq(string(raw)) {
if n, err := strconv.Atoi(f); err == nil {
pids = append(pids, n)
}
}
return nil
})
sort.Ints(pids)
return pids, err
}
func statPGID(b []byte) (int, bool) {
i := bytes.LastIndexByte(b, ')')
if i < 0 {
return 0, false
}
f := strings.Fields(string(b[i+1:]))
if len(f) < 3 || f[0] == "Z" || f[0] == "X" {
return 0, false
}
n, err := strconv.Atoi(f[2])
return n, err == nil
}
func environ(b []byte) map[string]string {
out := map[string]string{}
for kv := range bytes.SplitSeq(b, []byte{0}) {
k, v, ok := strings.Cut(string(kv), "=")
if ok {
out[k] = v
}
}
return out
}
func (h Host) ProcMembers(leader int, unit, invocation string, devsup int) ([]int, error) {
entries, err := os.ReadDir(h.proc())
if err != nil {
return nil, err
}
var pids []int
for _, e := range entries {
pid, err := strconv.Atoi(e.Name())
if err != nil || pid == devsup {
continue
}
stat, err := os.ReadFile(filepath.Join(h.proc(), e.Name(), "stat"))
if err != nil {
continue
}
pgid, alive := statPGID(stat)
if !alive {
continue
}
if leader > 0 && pgid == leader {
pids = append(pids, pid)
continue
}
raw, err := os.ReadFile(filepath.Join(h.proc(), e.Name(), "environ"))
if err != nil {
continue
}
env := environ(raw)
if env[EnvUnit] == unit && (invocation == "" || env[EnvInvoc] == invocation) {
pids = append(pids, pid)
}
}
sort.Ints(pids)
return pids, nil
}
func (h Host) Hash(pid int) Proc {
p := Proc{PID: pid}
link := filepath.Join(h.proc(), strconv.Itoa(pid), "exe")
if target, err := os.Readlink(link); err == nil {
p.Exe = target
}
f, err := os.Open(link)
if err != nil {
p.Err = err.Error()
return p
}
defer f.Close()
sum := sha256.New()
if _, err := io.Copy(sum, f); err != nil {
p.Err = err.Error()
return p
}
p.SHA256 = hex.EncodeToString(sum.Sum(nil))
return p
}
type Lister interface {
List(ctx context.Context, prefix string) ([]hostsvc.UnitStatus, error)
Capabilities() hostsvc.Capabilities
}
func Collect(ctx context.Context, m Lister, h Host, devsup int) (Report, error) {
r := Report{Backend: m.Capabilities().Backend}
var statuses []hostsvc.UnitStatus
for _, prefix := range []string{VMPrefix, MarketNetworkPrefix} {
st, err := m.List(ctx, prefix)
if err != nil {
return r, err
}
statuses = append(statuses, st...)
}
sort.Slice(statuses, func(i, j int) bool { return statuses[i].Name < statuses[j].Name })
for _, st := range statuses {
if !IsVMUnit(st.Name) {
continue
}
u := Unit{Name: st.Name, State: st.State, MainPID: st.MainPID}
var pids []int
var err error
switch r.Backend {
case hostsvc.BackendSystemdUser:
pids, err = h.CgroupMembers(st.MainPID, st.Name)
case hostsvc.BackendProc:
pids, err = h.ProcMembers(st.MainPID, st.Name, st.InvocationID, devsup)
default:
err = fmt.Errorf("no tree audit for backend %q", r.Backend)
}
if err != nil && st.State == hostsvc.Active {
u.Err = err.Error()
}
for _, pid := range pids {
u.Procs = append(u.Procs, h.Hash(pid))
}
r.Units = append(r.Units, u)
}
return r, nil
}
func Audit(ctx context.Context, m Lister, h Host, devsup int, pinned map[string]string) (Report, error) {
r, err := Collect(ctx, m, h, devsup)
if err != nil {
return r, err
}
r.Findings = Judge(r.Units, pinned)
return r, nil
}
var digestDir = regexp.MustCompile(`^[0-9a-f]{64}$`)
type TreeDigest func(dir string) (string, error)
func Pinned(runtimeRoot string, pins []versions.Pin, digest TreeDigest) (map[string]string, []string) {
out := map[string]string{}
var notes []string
execNames := map[string]string{}
trees := map[string]string{}
for _, p := range pins {
if !isVMAsset(p.Name) {
continue
}
for _, rel := range p.Executables {
execNames[rel] = p.Name
}
if p.TreeSHA256 != "" {
trees[p.TreeSHA256] = p.Name
}
}
entries, err := os.ReadDir(runtimeRoot)
if err != nil {
return out, []string{"no runtime set under " + runtimeRoot + ": " + err.Error()}
}
for _, e := range entries {
if !e.IsDir() || !digestDir.MatchString(e.Name()) {
continue
}
dir := filepath.Join(runtimeRoot, e.Name())
var found []string
for rel := range execNames {
if _, err := os.Stat(filepath.Join(dir, rel)); err == nil {
found = append(found, rel)
}
}
if len(found) == 0 {
continue
}
if got, err := digest(dir); err != nil || got != e.Name() {
notes = append(notes, fmt.Sprintf("%s does not verify against its name (%v); its executables are not pinned", dir, err))
continue
}
asset, whole := trees[e.Name()]
if !whole {
for _, rel := range found {
sum, err := sha256sum.File(filepath.Join(dir, rel))
if err != nil {
notes = append(notes, err.Error())
continue
}
out[sum] = execNames[rel] + " " + filepath.Join(dir, rel)
}
continue
}
werr := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
if err != nil || !d.Type().IsRegular() {
return err
}
info, err := d.Info()
if err != nil || info.Mode().Perm()&0o111 == 0 {
return err
}
sum, err := sha256sum.File(p)
if err != nil {
return err
}
out[sum] = asset + " " + p
return nil
})
if werr != nil {
notes = append(notes, werr.Error())
}
}
return out, notes
}
func isVMAsset(name string) bool {
return slices.Contains(VMAssets, name)
}
func Write(w io.Writer, r Report) {
fmt.Fprintf(w, "backend %s: %d VM unit(s)\n", r.Backend, len(r.Units))
for _, u := range r.Units {
fmt.Fprintf(w, " %s %s main pid %d, %d process(es)\n", u.Name, u.State, u.MainPID, len(u.Procs))
}
for _, f := range r.Findings {
fmt.Fprintf(w, "FAIL %s pid %d exe %s: %s\n", f.Unit, f.PID, f.Exe, f.Why)
}
}