| 1 | package cli |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "os" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | |
| 12 | "github.com/sylvinus/agent-vm/internal/guard" |
| 13 | "github.com/sylvinus/agent-vm/internal/netguard" |
| 14 | "github.com/sylvinus/agent-vm/internal/state" |
| 15 | ) |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | func quiet() bool { return os.Getenv("AGENT_VM_QUIET") == "1" } |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | func policyFingerprint(st state.Dir) string { |
| 30 | var parts []string |
| 31 | if pol, err := netguard.Load(string(st)); err == nil { |
| 32 | parts = append(parts, fmt.Sprintf("open=%t", pol.Open)) |
| 33 | for _, r := range pol.Allow { |
| 34 | parts = append(parts, fmt.Sprintf("allow %v %d", r.Net, r.Port)) |
| 35 | } |
| 36 | for _, d := range pol.Domains { |
| 37 | parts = append(parts, "domain "+d) |
| 38 | } |
| 39 | } else { |
| 40 | parts = append(parts, "network: "+err.Error()) |
| 41 | } |
| 42 | if g, err := guard.Load(string(st), ""); err == nil { |
| 43 | for p := range g.Paths { |
| 44 | parts = append(parts, "guard "+p) |
| 45 | } |
| 46 | } else { |
| 47 | parts = append(parts, "guarded: "+err.Error()) |
| 48 | } |
| 49 | parts = append(parts, fmt.Sprintf("deny=%t", os.Getenv("AGENT_VM_GUARDED_WRITES") == "deny")) |
| 50 | slices.Sort(parts) |
| 51 | sum := sha256.Sum256([]byte(strings.Join(parts, "\n"))) |
| 52 | return hex.EncodeToString(sum[:]) |
| 53 | } |
| 54 | |
| 55 | |
| 56 | func (s *start) recordPolicy() { |
| 57 | if err := s.state.Write(state.PolicyOf+s.name, []byte(policyFingerprint(s.state)+"\n")); err != nil { |
| 58 | s.warnf("Warning: could not record the network and guarded-files policies VM '%s' booted with: %v", s.name, err) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | func (s *start) notePolicyChange() { |
| 66 | booted := s.state.ReadMarker(state.PolicyOf, s.name) |
| 67 | if booted == "" || booted == policyFingerprint(s.state) { |
| 68 | return |
| 69 | } |
| 70 | s.warnf("Note: VM '%s' booted with other network or guarded-files settings than now (%s, %s, AGENT_VM_UNSAFE_OPEN_NETWORK, AGENT_VM_GUARDED_WRITES). The running VM keeps the old ones: 'agent-vm stop', then run again to apply them.", |
| 71 | s.name, netguard.FileName, guard.FileName) |
| 72 | } |
| 73 | |
| 74 | |
| 75 | |
| 76 | func warnDomains(st state.Dir, w io.Writer) { |
| 77 | if quiet() { |
| 78 | return |
| 79 | } |
| 80 | if pol, err := netguard.Load(string(st)); err == nil && len(pol.Domains) > 0 { |
| 81 | fmt.Fprintf(w, "Warning: the 'domain' lines in %s are experimental: do not rely on them alone to confine a VM. AGENT_VM_QUIET=1 hides this.\n", st.Path(netguard.FileName)) |
| 82 | } |
| 83 | } |