Enforce required per-job IPv4 allowlists with leased isolated network broker

This commit is contained in:
omar committed 2026-09-25 00:18:35 +03:00
1 parent b3373373e8
commit 32312548ea
24 files changed
+3030 -141

No files matched your search

+10 -2
View File
@@ -8,7 +8,13 @@ Malformed `{id}` path parameters return HTTP 404 `not_found` before database loo
`POST /uploads` body raw bytes (`application/octet-stream`), filename in `X-Filename` (encodeURIComponent). Response 201 `{id,filename,size,sha256,created_at}`. Original bytes immutable. No multipart. `GET /uploads/{id}/content` authorized attachment.
`POST /jobs` `{upload_id,profile_ids:[UUID],settings:{internet:"offline"|"online",duration_seconds:30|60|90|120|180|300|600|900|1200,filename:"original"|"random",privilege:"user"|"admin",args_mode:"none"|"custom",args: string[],set_zoneid:boolean,dll_mode:"regsvr32"|"rundll32",dll_export:string,architecture:"auto"|"x86"|"x64",wsh_host:"cscript"|"wscript",msi_ui:"full"|"quiet"|"passive"}}` -> 201 Job. Arguments are an explicit JSON string array; only `{sample.path}` and `{sample.name}` expand in guest after path selection. DLL export mandatory with rundll32, never guessed. MSI logs always collected. Defender only; each selected profile creates exactly one Run. Immutable settings, random basename selected once per Job preserving extension.
`POST /jobs` `{upload_id,profile_ids:[UUID],settings:{internet:"offline"|"online",allowed_cidrs?:string[],duration_seconds:30|60|90|120|180|300|600|900|1200,filename:"original"|"random",privilege:"user"|"admin",args_mode:"none"|"custom",args:string[],set_zoneid:boolean,dll_mode:"regsvr32"|"rundll32",dll_export:string,architecture:"auto"|"x86"|"x64",wsh_host:"cscript"|"wscript",msi_ui:"full"|"quiet"|"passive"}}` -> 201 Job. Arguments are an explicit JSON string array; only `{sample.path}` and `{sample.name}` expand in guest after path selection. DLL export mandatory with rundll32, never guessed. MSI logs always collected. Defender only; each selected profile creates exactly one Run. Immutable settings, random basename selected once per Job preserving extension.
**Strict per-job IPv4 destinations:** `online` requires `allowed_cidrs` with 1–128 nonblank IPv4 addresses/CIDRs and at most 8192 aggregate UTF-8 bytes, measured before trimming/deduplication. `offline` requires an absent or empty array; even a blank array entry is invalid. Surrounding whitespace is trimmed; bare IPv4 becomes `/32`; host bits are masked; exact canonical duplicates are removed in first-occurrence order. Overlapping entries are not collapsed. Names, address ranges, ports, IPv6 (including IPv4-mapped IPv6), leading-zero octets/prefix lengths and malformed entries are rejected with HTTP 400 `invalid_settings`. The returned immutable settings contain the normalized list.
`0.0.0.0/0` (also bare `0.0.0.0`) is a **public IPv4 only** flag, never accept-all. CIDR host-bit normalization also applies to `/0`; clients must confirm the normalized wildcard explicitly before submission. Public mode excludes `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10`, `127.0.0.0/8`, `169.254.0.0/16`, `172.16.0.0/12`, `192.0.0.0/24`, `192.0.2.0/24`, `192.88.99.0/24`, `192.168.0.0/16`, `198.18.0.0/15`, `198.51.100.0/24`, `203.0.113.0/24`, `224.0.0.0/4`, and `240.0.0.0/4`, plus operator-protected/site networks. Local destinations require separate explicit prefixes, retained alongside the public flag. Explicit private/lab prefixes must be wholly within one of `10.0.0.0/8`, `100.64.0.0/10`, `172.16.0.0/12`, `192.168.0.0/16`, or `198.18.0.0/15`; non-`/0` prefixes mixing public and private space are rejected. All other excluded ranges are never allowed, and any non-`/0` prefix intersecting them is rejected, including explicit `0.0.0.0/32`.
Effective access is the requested finite destinations (or public-only flag plus explicit local destinations), minus protected infrastructure. Host management, gateway, source/control and sandbox networks configured as protected are **always denied**, even if named explicitly. Guest administrator privileges cannot override enforcement. There is no IPv6 fallback, shared clone LAN, DNS bypass or permissive startup period. DNS `1.1.1.1` is advertised only when the effective destination list permits it; otherwise DHCP advertises no resolver and no implicit system resolver is used. Windows/Defender background traffic uses the same list, with no exemption. Offline behavior remains NIC-free. The worker publishes a private `network-policy.json` artifact for the online allocation; runtime lease expiry closes flows without depending on guest cooperation.
Optional immutable `settings.grub_paths: string[]` adds **Grub** file collection after the observation window, on the selected user/admin token. Omitted/empty means no archive and remains valid for historical Jobs. At most 32 literal absolute local Windows file paths, 1024 UTF-8 bytes each / 8192 aggregate. No environment or `{sample.*}` expansion: percent/braces inside an absolute filename are literal. UNC/device/network paths, ADS, traversal, wildcards and unsafe components are rejected; actual directories, reparse points and hard links are rejected in the guest. Extensionless ordinary files are allowed. Serialized settings (including escaped arguments) must fit 38 KiB; the full worker manifest must fit the existing 40 KiB transport limit before allocation.
@@ -18,6 +24,8 @@ Readable live logs are captured as bounded **best-effort open-length snapshots**
`GET /jobs?page=1&page_size=25&q=&status=` -> `{items:Job[],total,page,page_size,next_page:null|number}`; `GET /jobs/{id}` Job with runs; `POST /jobs/{id}/cancel` -> Job; `POST /jobs/{id}/retry` -> same Job with a new Attempt for every Run (including previously successful Runs), preserving every prior Attempt and original immutable settings/revisions, admission rechecked. Retry returns HTTP 409 `job_active` if the Job is queued/running **or any of its Attempts is unfinished**, even if the stored Job status is terminal. Job `{id,owner_id,upload_id,filename,execution_filename,sha256,size,settings,status,created_at,updated_at,cancel_requested,runs:Run[]}`. Status `queued|running|completed|cancelled|failed`.
Retry also revalidates the stored immutable network policy and current profile online availability without changing either the destination list or source revision. Historical online jobs without `allowed_cidrs` (and any other now-invalid policy) return HTTP 409 `invalid_settings`; submit a new job with explicit destinations. Missing historical destinations mean unavailable/legacy information, not unrestricted access.
Job detail additionally returns `queue_ahead: number|null`: the number of queued, never-claimed Attempts from **other Jobs** created before this Job's earliest queued, never-claimed Attempt. The count includes all owners for both operators and admins; it exposes no other Job/owner IDs. It is null when this Job has no queued, never-claimed Attempt. It counts Attempts, not Jobs, and is not a completion-time estimate.
Run `{id,job_id,profile_id,profile_name,revision_id,antivirus:"defender",status,attempts:Attempt[]}`; status `queued|running|completed|cancelled|failed`. `profile_name` is the fixed full name captured when that Run was created, including any manually entered build text; retries preserve it. Runs are ordered by `profile_name`, then `id` in detail and list/dashboard summaries; detail Attempts are ordered by `created_at` ascending.
@@ -110,7 +118,7 @@ Windows names are entered manually, for example `Windows 11 Pro — build 26200.
Admin: `GET /admin/users`; `POST /admin/users` `{username,password,role}`; `PATCH /admin/users/{id}` `{role?,disabled?,password?}`. User `{id,username,role,disabled,created_at}`.
`GET /admin/profiles`; `POST /admin/profiles` `{name,os,architecture}` -> Profile (maintenance, unqualified). `PATCH /admin/profiles/{id}` `{name?,enabled?}`. `POST /admin/profiles/{id}/maintenance` closes admission, returns profile plus drain status; never powers off live master. `POST /admin/profiles/{id}/publish` `{revision_id}` selects a previously worker-validated stopped source revision; never accepts VMID from browser. Returns HTTP 409 `unqualified_revision` without a passed qualification, `stale_revision` if a newer revision exists for the same source reference (including another profile), or `source_not_drained` while old-revision Attempts await cloning. `POST /admin/profiles/{id}/qualify` queues qualification, returns `{id,status}`. Qualified revision configuration and credentials are worker-only CLI/file-backed, not browser secrets.
`GET /admin/bindings` -> list `{owner_id,pool,iso_storage,disk_storage,node,configured,reason,isolation_expires_at}` (metadata only). `isolation_expires_at` is nullable RFC3339: null means not validated; effective `configured` requires successful worker validation **and** a future expiry at request time. Expired/missing expiry closes dashboard readiness and `POST /jobs` admission even if a stale stored flag was true. Bindings are provisioned by operator CLI with file-backed credentials and genuine probe evidence, no secret edits/browser storage; UI shows actual expiry/prerequisites rather than a fake credential form.
`GET /admin/bindings` -> list `{owner_id,pool,iso_storage,disk_storage,node,configured,reason,isolation_expires_at,online_ready,online_expires_at,online_reason}` (metadata only). Expiries are nullable RFC3339: null means not validated. Effective `configured` requires successful worker validation **and** a future isolation expiry at request time. Expired/missing isolation expiry closes dashboard readiness and job admission even if a stale stored flag was true. Online submit/retry additionally requires `online_ready` **and** future `online_expires_at`, plus the selected profile's `online_available`; missing/expired online proof returns HTTP 409 `admission_closed` with a generic safe reason. The bindings response computes effective `online_ready` at read time rather than exposing a stale true flag. Missing online readiness does not disable offline admission. Bindings are provisioned by operator CLI with file-backed credentials and genuine probe evidence, no secret edits/browser storage; UI shows actual expiry/prerequisites rather than a fake credential form.
`GET /admin/health` -> `{database,worker,last_worker_seen,integration_ready,blockers:string[]}`.
`GET /admin/attempts/held` -> `{items:[{attempt_id,job_id,run_id,profile_name,filename,outcome,cleanup,error,finished_at,release_requested,allocation:{id,node,vmid,state}|null}]}`. Admin-only; finished Attempts with `cleanup:"evidence_held"|"failed"`, newest `finished_at` first (nulls last), capped at 200. Includes entries without an allocation; no PVE URLs, tokens or credentials.
`POST /admin/attempts/{id}/release-evidence` `{confirm:true}` -> HTTP 202 `{release_requested:true}` for retained Attempts with cleanup `evidence_held` or `failed` and an allocation. Explicit irreversible authorized cleanup of owned retained disposable VM/disk only, never master/control.
+26 -13
View File
@@ -59,30 +59,43 @@ For an illustrative `max_video_bytes = 512 MiB`, `max_artifact_bytes = 64 MiB` a
## Optional online policy
Under the owner binding set:
Offline remains the default (`online: null` in the example). Sources must be ordinary stopped VMs without any NIC. There is no inherited online bridge or firewall-hash policy. The privileged host broker attaches `net0` only to an adopted, owned disposable clone; the worker never attaches networking to a source or receives host execution privileges.
To enable online qualification, explicitly configure the owner's private worker/watchdog binding:
```json
{
"online": {
"bridge": "otche-isolated",
"proof_file": "/run/otche/owner-one/online-proof.json"
"endpoint": "https://network-broker.example.invalid:9443",
"ca_file": "/run/otche/network-ca.pem",
"certificate_file": "/run/otche/owner-one/network-client.pem",
"key_file": "/run/otche/owner-one/network-client-key.pem",
"proof_file": "/run/otche/owner-one/online-proof.json",
"qualification_allowed_cidrs": ["1.1.1.1/32"]
}
}
```
The private online proof object has fields:
The qualification destination above is illustrative, not a sufficient Windows/Defender connectivity prescription. Choose and verify the actual operator-approved destinations. Qualification uses this explicit canonical list for both online EICAR and benign controls, with the same Defender baseline comparison as offline. It does not add exclusions or bypass background Windows traffic restrictions. Both actual online controls must pass before `online_available` is set.
- `owner_id`, `node`, `bridge`: exact binding identities.
- `passed`, `management_denied`, `private_networks_denied`, `cloud_consent`: actual operator-qualified boolean results/approval, all required true.
- `expires_at`: RFC3339 UTC expiry.
- `network_sha256`: SHA-256 of canonical JSON (Go encoding/json map-key order) of the actual PVE node network/bridge object, with `digest` removed.
- `firewall_options_sha256`: canonical JSON SHA-256 of VM firewall options without `digest`.
- `firewall_rules_sha256`: canonical JSON SHA-256 of VM firewall rules with per-row `digest` removed.
- `evidence_sha256`: SHA-256 of protected actual network probe evidence.
The broker endpoint is an HTTPS origin without a path, query or embedded credentials. All four file paths are absolute; pin the broker server CA and issue a separate client certificate whose CN maps to this owner in the host configuration. Keep the private key and proof mount exclusive to worker/watchdog, never API, frontend or guest. Redirects, system proxy forwarding, untrusted servers and missing client authentication are rejected.
This is an operator-produced approval artifact, **not an automatic network deployment**. Capture real management/private-network denied egress tests from a disposable clone and approved public connectivity; independently ensure external firewall is active. VM policy_in/policy_out must DROP; exact approved rules permit required online traffic. Source inherits the one approved isolated NIC; clone enables only that NIC with firewall flag. Worker compares live network/rule/options objects and refuses drift. Never alter a cluster firewall automatically to satisfy this prerequisite. Online qualification additionally runs its own EICAR/benign controls; a proof file alone does not mark a profile online_available.
Operator-produced online proof fields are:
Online fingerprints are bound to actual API responses and installed PVE semantics; do not fabricate example hashes. Online network qualification must be performed separately by the deployment operator. Successful PVE token authentication does not establish guest egress isolation; this gate stays closed until valid operator artifacts exist.
- `owner_id`, `node`, `endpoint`: exact owner/broker identities.
- `passed`, `management_denied`, `default_denied`, `ipv6_denied`, `spoofing_denied`, `cross_clone_denied`: all must be true results of real disposable-clone probes.
- `expires_at`: future RFC3339 expiry requiring real revalidation, not manual date extension.
- `evidence_sha256`: lowercase SHA-256 of protected actual probe evidence.
No pre-passed proof is provided. `bindings-sync` independently checks the proof and authenticated broker health, publishes `online_ready`, `online_expires_at` and a bounded `online_reason`, without changing offline readiness. API admission requires current online readiness/proof expiry in addition to profile qualification. Runtime rechecks proof and actual allocation before boot/dispatch and during execution; health alone is not isolation evidence. The obsolete fixed bridge/firewall hashes are not accepted as proof.
Online jobs require `settings.allowed_cidrs`: 1–128 IPv4 addresses/CIDRs, at most 8192 input UTF-8 bytes. Bare addresses become `/32`, hostbits are masked, duplicates removed preserving order. DNS names, ranges, IPv6, blank entries, unusable special prefixes and mixed private/public broad prefixes are rejected. `0.0.0.0` and `0.0.0.0/0` mean **public IPv4 only**, never private/local/special networks. Explicit private/lab CIDRs are separate opt-ins and remain alongside the public wildcard. Protected infrastructure and the broker's sandbox pool always remain denied, even explicitly listed. Offline jobs have no nonempty list; historical online jobs without a list are not silently granted access.
The worker persists the broker request before `/v1/prepare`, using the allocation UUID as durable `lease_id`, then saves the complete validated response under `allocation.metadata.network`. An immutable `network-policy.json` artifact captures the canonical list, digest, address/MAC/bridge assignment and initial broker expiry. It does not contain private keys. Every `/v1/check` must match owner, attempt, VMID, node, lease, policy digest and original topology. The actual clone must have exactly the broker-issued VirtIO MAC, bridge and `firewall=1`, with no extra NIC or VLAN option.
Renewal runs independently of QGA every 10 seconds starting immediately after prepare, through boot, readiness, delivery, observation and collection. A failed renewal cancels execution with an explicit network-policy error, tries immediate revocation and then follows stop/release cleanup. The broker's kernel active-port timeout is 45 seconds: worker/broker failure does not leave established connections authorized. No automatic re-prepare, lease replacement or command redispatch occurs. Stop, watchdog, retained-evidence release and deletion use the recorded identity; they release only after confirmed stopped/absent state, before deletion, and refuse changed/reused identities. Ambiguous prepare responses still have a durable release request.
DNS has no implicit bypass: DHCP advertises `1.1.1.1` only when that address is effectively allowed; otherwise it advertises no resolver. There is no host/system resolver fallback, DNS relay or IPv6 fallback. An allowed destination is not a promise that its service will answer. All user and Windows/Defender background traffic is constrained to the same list, including when the payload runs as guest administrator.
## Optional read-only extractor
+1 -1
View File
@@ -39,7 +39,7 @@ func (s *Server) adminRoutes() {
jsonResponse(w, 200, v)
}))
m.HandleFunc("GET /api/v1/admin/bindings", s.protected(true, func(w http.ResponseWriter, r *http.Request) {
s.list(w, r, `SELECT to_jsonb(b)||jsonb_build_object('configured',configured AND COALESCE(isolation_expires_at>now(),false),'reason',CASE WHEN configured AND NOT COALESCE(isolation_expires_at>now(),false) THEN 'Isolation proof expired or requires revalidation' ELSE reason END) FROM bindings b ORDER BY owner_id`)
s.list(w, r, `SELECT to_jsonb(b)||jsonb_build_object('configured',configured AND COALESCE(isolation_expires_at>now(),false),'reason',CASE WHEN configured AND NOT COALESCE(isolation_expires_at>now(),false) THEN 'Isolation proof expired or requires revalidation' ELSE reason END,'online_ready',online_ready AND COALESCE(online_expires_at>now(),false),'online_reason',CASE WHEN online_ready AND NOT COALESCE(online_expires_at>now(),false) THEN 'Online network proof expired or requires revalidation' ELSE online_reason END) FROM bindings b ORDER BY owner_id`)
}))
m.HandleFunc("GET /api/v1/admin/health", s.protected(true, s.health))
m.HandleFunc("GET /api/v1/admin/attempts/held", s.protected(true, s.heldAttempts))
+1 -1
View File
@@ -58,7 +58,7 @@ func TestJobSummariesIncludeAssignedProfile(t *testing.T) {
if _, err = db.Exec(ctx, `INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest) VALUES($1,$2,'win11','fingerprint','config')`, revision, profile); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO jobs(id,owner_id,upload_id,execution_filename,status,settings) VALUES($1,$2,$3,'panel-bat-smoke.bat','completed','{}')`, job, owner, upload); err != nil {
if _, err = db.Exec(ctx, `INSERT INTO jobs(id,owner_id,upload_id,execution_filename,status,settings) VALUES($1,$2,$3,'panel-bat-smoke.bat','completed','{"internet":"offline"}')`, job, owner, upload); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name,status) SELECT $1,$2,id,$4,name,'completed' FROM profiles WHERE id=$3`, run, job, profile, revision); err != nil {
+28 -7
View File
@@ -17,12 +17,14 @@ import (
"github.com/jackc/pgx/v5"
"otche/internal/grub"
"otche/internal/netpolicy"
"otche/internal/pve"
"otche/internal/store"
)
type Settings struct {
Internet string `json:"internet"`
AllowedCIDRs []string `json:"allowed_cidrs,omitempty"`
Duration int `json:"duration_seconds"`
Filename string `json:"filename"`
Privilege string `json:"privilege"`
@@ -59,9 +61,11 @@ func (v *Settings) validate(filename string) error {
if err := grub.Validate(v.GrubPaths); err != nil {
return err
}
if v.Internet != "online" && v.Internet != "offline" {
return errors.New("internet must be online/offline")
allowed, err := netpolicy.Normalize(v.Internet, v.AllowedCIDRs)
if err != nil {
return err
}
v.AllowedCIDRs = allowed
ok := false
for _, d := range []int{30, 60, 90, 120, 180, 300, 600, 900, 1200} {
if v.Duration == d {
@@ -330,7 +334,7 @@ func (s *Server) createJob(w http.ResponseWriter, r *http.Request) {
fail(w, 400, "invalid_settings", e.Error())
return
}
if e = s.admit(r, tx, a.ID); e != nil {
if e = s.admit(r, tx, a.ID, in.Settings.Internet); e != nil {
fail(w, 409, "admission_closed", e.Error())
return
}
@@ -377,7 +381,7 @@ func (s *Server) createJob(w http.ResponseWriter, r *http.Request) {
}
s.respondJob(w, r, id, 201)
}
func (s *Server) admit(r *http.Request, tx pgx.Tx, owner string) error {
func (s *Server) admit(r *http.Request, tx pgx.Tx, owner, network string) error {
var id string
if e := tx.QueryRow(r.Context(), `SELECT id::text FROM users WHERE id=$1 FOR UPDATE`, owner).Scan(&id); e != nil {
return e
@@ -387,6 +391,13 @@ func (s *Server) admit(r *http.Request, tx pgx.Tx, owner string) error {
if e != nil || !configured {
return errors.New("Owner PVE isolation and credentials are not configured")
}
if network == "online" {
var onlineReady bool
e = tx.QueryRow(r.Context(), `SELECT online_ready AND COALESCE(online_expires_at>now(),false) FROM bindings WHERE owner_id=$1`, owner).Scan(&onlineReady)
if e != nil || !onlineReady {
return errors.New("Owner online network is unavailable or requires revalidation")
}
}
var workerReady bool
e = tx.QueryRow(r.Context(), `SELECT COALESCE(bool_or(ready AND seen_at>now()-interval '45 seconds'),false) FROM heartbeats WHERE name='worker'`).Scan(&workerReady)
if e != nil || !workerReady {
@@ -494,7 +505,8 @@ func (s *Server) retryJob(w http.ResponseWriter, r *http.Request) {
}
defer tx.Rollback(r.Context())
var status, owner string
e = tx.QueryRow(r.Context(), `SELECT status,owner_id::text FROM jobs WHERE id=$1 FOR UPDATE`, id).Scan(&status, &owner)
var rawSettings json.RawMessage
e = tx.QueryRow(r.Context(), `SELECT status,owner_id::text,settings FROM jobs WHERE id=$1 FOR UPDATE`, id).Scan(&status, &owner, &rawSettings)
if e != nil {
s.dbError(w, e)
return
@@ -509,11 +521,20 @@ func (s *Server) retryJob(w http.ResponseWriter, r *http.Request) {
fail(w, 409, "job_active", "An active job cannot be retried")
return
}
if e = s.admit(r, tx, owner); e != nil {
var settings Settings
if e = json.Unmarshal(rawSettings, &settings); e != nil {
fail(w, 409, "invalid_settings", "Stored job settings cannot be decoded; submit a new job")
return
}
if _, e = netpolicy.Normalize(settings.Internet, settings.AllowedCIDRs); e != nil {
fail(w, 409, "invalid_settings", "Stored network settings cannot be retried; submit a new job: "+e.Error())
return
}
if e = s.admit(r, tx, owner, settings.Internet); e != nil {
fail(w, 409, "admission_closed", e.Error())
return
}
rows, e := tx.Query(r.Context(), `SELECT r.id::text,p.enabled AND p.state='published' AND p.qualification='qualified' AND p.current_revision_id=r.revision_id FROM runs r JOIN profiles p ON p.id=r.profile_id WHERE r.job_id=$1 FOR SHARE OF p`, id)
rows, e := tx.Query(r.Context(), `SELECT r.id::text,p.enabled AND p.state='published' AND p.qualification='qualified' AND p.current_revision_id=r.revision_id AND ($2='offline' OR p.online_available) FROM runs r JOIN profiles p ON p.id=r.profile_id WHERE r.job_id=$1 FOR SHARE OF p`, id, settings.Internet)
if e != nil {
s.dbError(w, e)
return
+214
View File
@@ -0,0 +1,214 @@
package api
import (
"context"
"encoding/json"
"net/http/httptest"
"os"
"slices"
"strings"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"otche/internal/store"
)
func TestNetworkSettingsSubmissionAndRetry(t *testing.T) {
url := os.Getenv("OTCHE_TEST_DATABASE_URL")
if url == "" {
t.Skip("OTCHE_TEST_DATABASE_URL required for isolated PostgreSQL regression")
}
ctx := context.Background()
admin, err := pgxpool.New(ctx, url)
if err != nil {
t.Fatal(err)
}
defer admin.Close()
schema := "test_" + strings.ReplaceAll(store.NewID(), "-", "")
if _, err = admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
t.Fatal(err)
}
defer admin.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE")
cfg, err := pgxpool.ParseConfig(url)
if err != nil {
t.Fatal(err)
}
cfg.ConnConfig.RuntimeParams["search_path"] = schema
db, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if err = store.Migrate(ctx, db); err != nil {
t.Fatal(err)
}
owner, err := CreateUser(ctx, db, "network-admin", "Network-regression-password-only", "admin")
if err != nil {
t.Fatal(err)
}
upload, profile, revision := store.NewID(), store.NewID(), store.NewID()
if _, err = db.Exec(ctx, `INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key) VALUES($1,$2,'test.bat',1,$3,$4)`, upload, owner, strings.Repeat("a", 64), upload); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO profiles(id,name,os,architecture,enabled,qualification,state,current_revision_id,online_available) VALUES($1,'Network test','Windows','x64',true,'qualified','published',$2,true)`, profile, revision); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest) VALUES($1,$2,'network-test','fingerprint','config')`, revision, profile); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO bindings(owner_id,pool,iso_storage,disk_storage,node,configured,isolation_expires_at,online_ready,online_expires_at) VALUES($1,'test','test','test','test',true,now()+interval '1 hour',true,now()+interval '1 hour')`, owner); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `INSERT INTO heartbeats(name,seen_at,ready) VALUES('worker',now(),true)`); err != nil {
t.Fatal(err)
}
s, err := New(db, Config{Origin: "http://localhost", ArtifactRoot: t.TempDir(), MaxQueuedJobs: 20})
if err != nil {
t.Fatal(err)
}
login := httptest.NewRequest("POST", "/api/v1/auth/login", strings.NewReader(`{"username":"network-admin","password":"Network-regression-password-only"}`))
login.Header.Set("Origin", "http://localhost")
logged := httptest.NewRecorder()
s.ServeHTTP(logged, login)
if logged.Code != 200 {
t.Fatalf("login: %d %s", logged.Code, logged.Body)
}
var session struct {
CSRF string `json:"csrf_token"`
}
if err = json.Unmarshal(logged.Body.Bytes(), &session); err != nil {
t.Fatal(err)
}
request := func(path string, body any, status int, code string) *httptest.ResponseRecorder {
t.Helper()
encoded, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("POST", path, strings.NewReader(string(encoded)))
req.AddCookie(logged.Result().Cookies()[0])
req.Header.Set("Origin", "http://localhost")
req.Header.Set("X-CSRF-Token", session.CSRF)
res := httptest.NewRecorder()
s.ServeHTTP(res, req)
if res.Code != status {
t.Fatalf("%s: %d %s; want %d", path, res.Code, res.Body, status)
}
if code != "" {
var value struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
if err := json.Unmarshal(res.Body.Bytes(), &value); err != nil || value.Error.Code != code {
t.Fatalf("unexpected error response: %s, %v", res.Body, err)
}
}
return res
}
base := Settings{Internet: "online", Duration: 30, Filename: "original", Privilege: "admin", ArgsMode: "none", Args: []string{}}
for _, tc := range []struct {
name string
mode string
entries []string
}{
{"online missing", "online", nil},
{"online empty", "online", []string{}},
{"malformed", "online", []string{"example.com"}},
{"ipv6", "online", []string{"::ffff:1.1.1.1"}},
{"offline nonempty", "offline", []string{"1.1.1.1"}},
{"protected special", "online", []string{"127.0.0.1"}},
{"wildcard does not suppress rejection", "online", []string{"0.0.0.0/0", "169.254.1.1"}},
} {
t.Run(tc.name, func(t *testing.T) {
settings := base
settings.Internet, settings.AllowedCIDRs = tc.mode, tc.entries
request("/api/v1/jobs", map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": settings}, 400, "invalid_settings")
})
}
var jobs int
if err = db.QueryRow(ctx, `SELECT count(*) FROM jobs`).Scan(&jobs); err != nil || jobs != 0 {
t.Fatalf("invalid submissions persisted jobs: %d, %v", jobs, err)
}
base.AllowedCIDRs = []string{" 1.1.1.1 ", "10.27.8.9/16", "0.0.0.0", "10.27.0.0/16", "1.1.1.1/32"}
created := request("/api/v1/jobs", map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": base}, 201, "")
var job struct {
ID string `json:"id"`
Settings Settings `json:"settings"`
}
if err = json.Unmarshal(created.Body.Bytes(), &job); err != nil {
t.Fatal(err)
}
want := []string{"1.1.1.1/32", "10.27.0.0/16", "0.0.0.0/0"}
if !slices.Equal(job.Settings.AllowedCIDRs, want) {
t.Fatalf("immutable policy not canonical or explicit LAN lost: %v", job.Settings.AllowedCIDRs)
}
if _, err = db.Exec(ctx, `UPDATE attempts SET phase='finished',outcome='error' WHERE run_id IN (SELECT id FROM runs WHERE job_id=$1)`, job.ID); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `UPDATE jobs SET status='failed' WHERE id=$1`, job.ID); err != nil {
t.Fatal(err)
}
// Old online jobs must fail before retry admission and never gain a wildcard.
if _, err = db.Exec(ctx, `UPDATE jobs SET settings=settings-'allowed_cidrs' WHERE id=$1`, job.ID); err != nil {
t.Fatal(err)
}
request("/api/v1/jobs/"+job.ID+"/retry", map[string]any{}, 409, "invalid_settings")
var unfinished int
if err = db.QueryRow(ctx, `SELECT count(*) FROM attempts WHERE phase<>'finished'`).Scan(&unfinished); err != nil || unfinished != 0 {
t.Fatalf("legacy policy retry queued work: %d, %v", unfinished, err)
}
canonical, err := json.Marshal(job.Settings)
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `UPDATE jobs SET settings=$2 WHERE id=$1`, job.ID, canonical); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `UPDATE profiles SET online_available=false WHERE id=$1`, profile); err != nil {
t.Fatal(err)
}
request("/api/v1/jobs/"+job.ID+"/retry", map[string]any{}, 409, "revision_unavailable")
if _, err = db.Exec(ctx, `UPDATE profiles SET online_available=true WHERE id=$1`, profile); err != nil {
t.Fatal(err)
}
for _, expiry := range []string{"now()-interval '1 second'", "NULL"} {
if _, err = db.Exec(ctx, `UPDATE bindings SET online_ready=true,online_expires_at=`+expiry+` WHERE owner_id=$1`, owner); err != nil {
t.Fatal(err)
}
request("/api/v1/jobs/"+job.ID+"/retry", map[string]any{}, 409, "admission_closed")
request("/api/v1/jobs", map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": base}, 409, "admission_closed")
bindingsRequest := httptest.NewRequest("GET", "/api/v1/admin/bindings", nil)
bindingsRequest.AddCookie(logged.Result().Cookies()[0])
bindingsResponse := httptest.NewRecorder()
s.ServeHTTP(bindingsResponse, bindingsRequest)
var bindings struct {
Items []struct {
Configured bool `json:"configured"`
OnlineReady bool `json:"online_ready"`
} `json:"items"`
}
if err = json.Unmarshal(bindingsResponse.Body.Bytes(), &bindings); err != nil || bindingsResponse.Code != 200 || len(bindings.Items) != 1 || bindings.Items[0].OnlineReady || !bindings.Items[0].Configured {
t.Fatalf("stale online proof remained ready or disabled offline: %s, %v", bindingsResponse.Body, err)
}
}
if err = db.QueryRow(ctx, `SELECT count(*) FROM attempts WHERE phase<>'finished'`).Scan(&unfinished); err != nil || unfinished != 0 {
t.Fatalf("expired online proof queued work: %d, %v", unfinished, err)
}
offline := base
offline.Internet, offline.AllowedCIDRs = "offline", nil
request("/api/v1/jobs", map[string]any{"upload_id": upload, "profile_ids": []string{profile}, "settings": offline}, 201, "")
if _, err = db.Exec(ctx, `UPDATE attempts SET phase='finished',outcome='error' WHERE phase<>'finished'`); err != nil {
t.Fatal(err)
}
if _, err = db.Exec(ctx, `UPDATE bindings SET online_expires_at=now()+interval '1 hour' WHERE owner_id=$1`, owner); err != nil {
t.Fatal(err)
}
retried := request("/api/v1/jobs/"+job.ID+"/retry", map[string]any{}, 200, "")
if err = json.Unmarshal(retried.Body.Bytes(), &job); err != nil || !slices.Equal(job.Settings.AllowedCIDRs, want) {
t.Fatalf("retry changed immutable policy: %s, %v", retried.Body, err)
}
if err = db.QueryRow(ctx, `SELECT count(*) FROM attempts WHERE phase<>'finished'`).Scan(&unfinished); err != nil || unfinished != 1 {
t.Fatalf("valid policy retry failed to queue exactly one attempt: %d, %v", unfinished, err)
}
}
+114
View File
@@ -0,0 +1,114 @@
package netpolicy
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"net/netip"
"strings"
)
// NonPublic is the canonical IPv4 exclusion list for public-only mode.
// Callers must treat this exported slice as immutable.
var NonPublic = []string{
"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8",
"169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24",
"192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24",
"203.0.113.0/24", "224.0.0.0/4", "240.0.0.0/4",
}
// NeverAllowed is the canonical IPv4 list rejected even when explicitly named.
// Operator-protected infrastructure is additionally denied by the host gateway.
// Callers must treat this exported slice as immutable.
var NeverAllowed = []string{
"0.0.0.0/8", "127.0.0.0/8", "169.254.0.0/16", "192.0.0.0/24",
"192.0.2.0/24", "192.88.99.0/24", "198.51.100.0/24", "203.0.113.0/24",
"224.0.0.0/4", "240.0.0.0/4",
}
var nonPublicPrefixes = parsePrefixes(NonPublic)
var neverAllowedPrefixes = parsePrefixes(NeverAllowed)
func parsePrefixes(entries []string) []netip.Prefix {
prefixes := make([]netip.Prefix, len(entries))
for i, entry := range entries {
prefixes[i] = netip.MustParsePrefix(entry)
}
return prefixes
}
// Normalize validates a destination policy and returns canonical IPv4 prefixes
// in first-occurrence order. The sole /0 entry is a public-only mode flag, never
// an accept-all route; explicitly allowed private/lab prefixes remain separate.
// Limits apply to the submitted strings before whitespace trimming or deduplication.
func Normalize(mode string, entries []string) ([]string, error) {
if mode != "online" && mode != "offline" {
return nil, errors.New("internet must be online/offline")
}
if mode == "offline" {
if len(entries) != 0 {
return nil, errors.New("allowed_cidrs must be empty when internet is offline")
}
return nil, nil
}
if len(entries) == 0 || len(entries) > 128 {
return nil, errors.New("online allowed_cidrs requires 1 to 128 IPv4 addresses or CIDRs")
}
bytes := 0
for _, entry := range entries {
if len(entry) > 8192-bytes {
return nil, errors.New("allowed_cidrs exceeds 8192 UTF-8 bytes")
}
bytes += len(entry)
}
normalized := make([]string, 0, len(entries))
seen := make(map[string]bool, len(entries))
for i, entry := range entries {
entry = strings.TrimSpace(entry)
var prefix netip.Prefix
if strings.Contains(entry, "/") {
var err error
prefix, err = netip.ParsePrefix(entry)
if err != nil || !prefix.Addr().Is4() {
return nil, fmt.Errorf("allowed_cidrs entry %d must be an IPv4 address or CIDR", i+1)
}
prefix = prefix.Masked()
} else {
address, err := netip.ParseAddr(entry)
if err != nil || !address.Is4() {
return nil, fmt.Errorf("allowed_cidrs entry %d must be an IPv4 address or CIDR", i+1)
}
bits := 32
if address.IsUnspecified() {
bits = 0
}
prefix = netip.PrefixFrom(address, bits)
}
if prefix.Bits() != 0 {
for _, denied := range neverAllowedPrefixes {
if prefix.Overlaps(denied) {
return nil, fmt.Errorf("allowed_cidrs entry %d overlaps never-allowed range %s", i+1, denied)
}
}
for _, private := range nonPublicPrefixes {
if prefix.Overlaps(private) && prefix.Bits() < private.Bits() {
return nil, fmt.Errorf("allowed_cidrs entry %d mixes public and private ranges; use separate explicit CIDRs", i+1)
}
}
}
canonical := prefix.String()
if !seen[canonical] {
normalized = append(normalized, canonical)
seen[canonical] = true
}
}
return normalized, nil
}
// Digest hashes normalized entries in order, separated and terminated by LF.
// Call Normalize first; Digest does not validate or reinterpret its input.
func Digest(entries []string) string {
sum := sha256.Sum256([]byte(strings.Join(entries, "\n") + "\n"))
return hex.EncodeToString(sum[:])
}
+105
View File
@@ -0,0 +1,105 @@
package netpolicy
import (
"crypto/sha256"
"encoding/hex"
"slices"
"strings"
"testing"
)
func TestNormalizeRetainsExplicitPrivateAlongsidePublic(t *testing.T) {
input := []string{" 1.1.1.1 ", "10.23.4.5/16", "0.0.0.0", "10.23.0.0/16", "1.1.1.1/32", "0.0.0.0/0", "192.168.7.9", "100.64.0.0/10", "172.16.0.0/12", "198.18.0.0/15"}
original := slices.Clone(input)
want := []string{"1.1.1.1/32", "10.23.0.0/16", "0.0.0.0/0", "192.168.7.9/32", "100.64.0.0/10", "172.16.0.0/12", "198.18.0.0/15"}
got, err := Normalize("online", input)
if err != nil || !slices.Equal(got, want) {
t.Fatalf("canonical policy = %v, %v; want %v", got, err, want)
}
if !slices.Equal(input, original) {
t.Fatal("normalization mutated the caller's immutable policy")
}
finite, err := Normalize("online", []string{"8.8.8.8/24", "8.8.8.8", "10.0.0.0/8"})
if err != nil || !slices.Equal(finite, []string{"8.8.8.0/24", "8.8.8.8/32", "10.0.0.0/8"}) {
t.Fatalf("finite policy collapsed or broadened: %v, %v", finite, err)
}
wildcard, err := Normalize("online", []string{"8.8.8.8/0"})
if err != nil || !slices.Equal(wildcard, []string{"0.0.0.0/0"}) {
t.Fatalf("hostbits were not masked consistently for /0: %v, %v", wildcard, err)
}
}
func TestNormalizeRejectsInvalidDestinations(t *testing.T) {
for _, entry := range []string{
"", " \t ", "::1", "::ffff:8.8.8.8", "::ffff:8.8.8.8/128", "2001:db8::/32",
"example.com", "1.1.1.1-1.1.1.2", "1.1.1.1:443", "1.1.1.1/33", "1.1.1.1/-1",
"1.1.1.1/024", "01.1.1.1", "1.1.1", "0x01010101", "1.1.1.1/255.255.255.0", "1.1.1.1\n8.8.8.8",
"0.0.0.0/32", "0.1.2.3", "127.0.0.1", "169.254.1.1", "192.0.0.9", "192.0.2.1",
"192.88.99.1", "198.51.100.1", "203.0.113.1", "224.0.0.1", "255.255.255.255",
"126.0.0.0/7", "169.254.0.0/15", "8.0.0.0/6", "100.0.0.0/8", "172.0.0.0/11", "198.16.0.0/14",
} {
t.Run(entry, func(t *testing.T) {
got, err := Normalize("online", []string{entry})
if err == nil || got != nil {
t.Fatalf("invalid destination was admitted: %q => %v, %v", entry, got, err)
}
if _, err := Normalize("online", []string{"0.0.0.0/0", entry}); err == nil {
t.Fatal("public wildcard suppressed invalid explicit destination")
}
})
}
}
func TestNormalizeModeAndInputBounds(t *testing.T) {
for _, entries := range [][]string{nil, {}} {
if got, err := Normalize("offline", entries); err != nil || len(got) != 0 {
t.Fatalf("empty offline policy failed: %v, %v", got, err)
}
if _, err := Normalize("online", entries); err == nil {
t.Fatal("online policy without destinations was accepted")
}
}
for _, entries := range [][]string{{"1.1.1.1"}, {""}} {
if _, err := Normalize("offline", entries); err == nil {
t.Fatal("offline nonempty array was accepted")
}
}
if _, err := Normalize("", []string{"1.1.1.1"}); err == nil {
t.Fatal("missing mode was accepted")
}
entries := make([]string, 128)
for i := range entries {
entries[i] = "1.1.1.1"
}
if got, err := Normalize("online", entries); err != nil || !slices.Equal(got, []string{"1.1.1.1/32"}) {
t.Fatalf("128-entry boundary: %v, %v", got, err)
}
if _, err := Normalize("online", append(entries, "1.1.1.1")); err == nil {
t.Fatal("deduplication bypassed submitted count limit")
}
padded := "1.1.1.1" + strings.Repeat(" ", 8192-len("1.1.1.1"))
if got, err := Normalize("online", []string{padded}); err != nil || !slices.Equal(got, []string{"1.1.1.1/32"}) {
t.Fatalf("8192-byte boundary: %v, %v", got, err)
}
if _, err := Normalize("online", []string{padded, "1.1.1.1"}); err == nil {
t.Fatal("trimming/deduplication bypassed aggregate byte limit")
}
if _, err := Normalize("online", []string{"1.1.1.1" + strings.Repeat("\u2003", 2730)}); err == nil {
t.Fatal("UTF-8 byte limit was counted as characters")
}
}
func TestDigestBindsCanonicalOrderAndTrailingNewline(t *testing.T) {
entries, err := Normalize("online", []string{"1.1.1.1", "10.8.7.6/8", "0.0.0.0"})
if err != nil {
t.Fatal(err)
}
sum := sha256.Sum256([]byte("1.1.1.1/32\n10.0.0.0/8\n0.0.0.0/0\n"))
if got := Digest(entries); got != hex.EncodeToString(sum[:]) {
t.Fatalf("digest does not match broker wire preimage: %s", got)
}
slices.Reverse(entries)
if Digest(entries) == hex.EncodeToString(sum[:]) {
t.Fatal("digest discarded immutable policy order")
}
}
+3
View File
@@ -44,3 +44,6 @@ CREATE INDEX IF NOT EXISTS revisions_source ON revisions(source_ref,created_at D
CREATE INDEX IF NOT EXISTS qualifications_profile ON qualifications(profile_id,created_at DESC);
CREATE INDEX IF NOT EXISTS qualifications_active ON qualifications(created_at) WHERE status IN ('queued','running');
CREATE INDEX IF NOT EXISTS events_orphan ON events(created_at) WHERE job_id IS NULL;
ALTER TABLE bindings ADD COLUMN IF NOT EXISTS online_ready boolean NOT NULL DEFAULT false;
ALTER TABLE bindings ADD COLUMN IF NOT EXISTS online_expires_at timestamptz;
ALTER TABLE bindings ADD COLUMN IF NOT EXISTS online_reason text NOT NULL DEFAULT 'Online network not configured';
+5 -1
View File
@@ -38,7 +38,6 @@ type Source struct {
SealPath string `json:"seal_path"`
CDSlot string `json:"cd_slot"`
MaxDiskBytes int64 `json:"max_disk_bytes"`
AllowedBridges []string `json:"allowed_bridges"`
}
type Binding struct {
Endpoint string `json:"endpoint"`
@@ -167,6 +166,11 @@ func loadConfig(path string) (Config, error) {
if b.MinStorageFreeBytes <= 0 || b.MinMemoryFreeBytes <= 0 || b.MaxOwnedDiskBytes <= 0 {
return c, errors.New("explicit owner resource headroom and disk quota required")
}
if b.Online != nil {
if err := b.Online.validate(); err != nil {
return c, err
}
}
}
for ref, s := range c.Sources {
if !ident.MatchString(ref) || !ident.MatchString(s.Node) || s.VMID < 100 || s.VMID == 7000 || !uuidRE.MatchString(s.OwnerID) || !filepath.IsAbs(s.SealPath) || !regexp.MustCompile(`^(ide|sata|scsi)[0-9]+$`).MatchString(s.CDSlot) || s.MaxDiskBytes <= 0 {
+58 -1
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"os"
"otche/internal/grub"
"otche/internal/netpolicy"
"otche/internal/pve"
"otche/internal/recorder"
"path/filepath"
@@ -156,6 +157,9 @@ func (e *engine) safetyDeadline(ctx context.Context, a attempt, l allocation, de
return err
}
func (e *engine) execute(ctx context.Context, a attempt) (outcome, findings, telemetry, cleanup string, report json.RawMessage, retErr error) {
ctx, cancelNetwork := context.WithCancelCause(ctx)
defer cancelNetwork(nil)
var stopNetwork func()
outcome, findings, telemetry, cleanup = "error", "unknown", "unavailable", "complete"
if a.Phase != "queued" {
cleanup = "evidence_held"
@@ -176,9 +180,19 @@ func (e *engine) execute(ctx context.Context, a attempt) (outcome, findings, tel
if json.Unmarshal(a.Settings, &opts) != nil || json.Unmarshal(a.Settings, &internal) != nil {
return outcome, findings, telemetry, cleanup, nil, errors.New("invalid job settings")
}
if opts.Internet != "offline" && (opts.Internet != "online" || b.Online == nil) {
if a.Phase == "queued" && opts.Internet != "offline" && (opts.Internet != "online" || b.Online == nil) {
return outcome, findings, telemetry, cleanup, nil, errors.New("online execution requires configured qualified isolated policy")
}
if a.Phase == "queued" {
if _, err = netpolicy.Normalize(opts.Internet, opts.AllowedCIDRs); err != nil {
return outcome, findings, telemetry, cleanup, nil, err
}
}
if opts.Internet == "online" && a.Phase == "queued" {
if _, err = b.networkProof(a.OwnerID); err != nil {
return outcome, findings, telemetry, cleanup, nil, err
}
}
if opts.Duration < 30 || opts.Duration > 1200 || (opts.Privilege != "user" && opts.Privilege != "admin") {
return outcome, findings, telemetry, cleanup, nil, errors.New("invalid immutable run limits")
}
@@ -217,6 +231,33 @@ func (e *engine) execute(ctx context.Context, a attempt) (outcome, findings, tel
videoComplete := false
collected := false
defer func() {
if stopNetwork != nil {
stopNetwork()
}
if cause := context.Cause(ctx); cause != nil && !errors.Is(cause, context.Canceled) && !errors.Is(cause, context.DeadlineExceeded) {
retErr = cause
if !collected {
outcome = "interrupted"
}
}
defer func() {
if cause := context.Cause(ctx); cause != nil && !errors.Is(cause, context.Canceled) && !errors.Is(cause, context.DeadlineExceeded) {
retErr = cause
if !collected {
outcome = "interrupted"
}
var fields map[string]json.RawMessage
if len(report) == 0 {
fields = map[string]json.RawMessage{}
} else {
_ = json.Unmarshal(report, &fields)
}
if fields != nil {
fields["network_policy_error"], _ = json.Marshal(cause.Error())
report, _ = json.Marshal(fields)
}
}
}()
finalSeconds := e.cfg.CollectTimeoutSeconds + 120
if e.cfg.Extractor != nil {
finalSeconds += e.cfg.Extractor.TimeoutSeconds
@@ -403,6 +444,15 @@ func (e *engine) execute(ctx context.Context, a attempt) (outcome, findings, tel
if err = e.safetyDeadline(ctx, a, l, time.Now().Add(time.Duration(e.cfg.PrepareTimeoutSeconds)*time.Second)); err != nil {
return outcome, findings, telemetry, cleanup, nil, err
}
if opts.Internet == "online" {
if err = e.prepareNetwork(prep, a, l, b, cs); err != nil {
return outcome, findings, telemetry, cleanup, nil, fmt.Errorf("network policy preparation failed: %w", err)
}
stopNetwork = e.renewNetwork(ctx, a, l, b, cs, cancelNetwork)
if err = e.publishNetwork(prep, a, l, b, dir); err != nil {
return outcome, findings, telemetry, cleanup, nil, err
}
}
if err = e.prepareClone(prep, a, l, b, cs); err != nil {
return outcome, findings, telemetry, cleanup, nil, err
}
@@ -499,6 +549,13 @@ func (e *engine) execute(ctx context.Context, a attempt) (outcome, findings, tel
return outcome, findings, telemetry, cleanup, nil, errors.New("recorder closed before run permit")
default:
}
networkConfig, networkErr := cs.provisioner.Config(delivery, b.Node, l.VMID)
if networkErr == nil {
networkErr = e.checkNetwork(delivery, a, b, l.VMID, networkConfig)
}
if networkErr != nil {
return outcome, findings, telemetry, cleanup, nil, fmt.Errorf("network policy before dispatch failed: %w", networkErr)
}
if err = e.recordAction(ctx, a, l, "dispatch_intent", ""); err != nil {
return outcome, findings, telemetry, cleanup, nil, err
}
+430 -53
View File
@@ -1,111 +1,488 @@
package worker
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/netip"
"net/url"
"os"
"otche/internal/netpolicy"
"otche/internal/pve"
"path/filepath"
"slices"
"strings"
"time"
)
// OnlinePolicy refers to an operator-qualified dedicated routed sandbox. The
// immutable proof must include management/RFC1918 denial tests and explicit
// online/cloud-data consent; NIC firewall flags alone are never isolation proof.
// OnlinePolicy contains private worker-only broker credentials and real probe evidence.
type OnlinePolicy struct {
Bridge string `json:"bridge"`
Endpoint string `json:"endpoint"`
CAFile string `json:"ca_file"`
CertificateFile string `json:"certificate_file"`
KeyFile string `json:"key_file"`
ProofFile string `json:"proof_file"`
QualificationAllowedCIDRs []string `json:"qualification_allowed_cidrs"`
}
type onlineProof struct {
OwnerID string `json:"owner_id"`
Node string `json:"node"`
Bridge string `json:"bridge"`
Endpoint string `json:"endpoint"`
ExpiresAt time.Time `json:"expires_at"`
Passed bool `json:"passed"`
ManagementDenied bool `json:"management_denied"`
PrivateNetworksDenied bool `json:"private_networks_denied"`
CloudConsent bool `json:"cloud_consent"`
NetworkSHA256 string `json:"network_sha256"`
FirewallOptionsSHA256 string `json:"firewall_options_sha256"`
FirewallRulesSHA256 string `json:"firewall_rules_sha256"`
DefaultDenied bool `json:"default_denied"`
IPv6Denied bool `json:"ipv6_denied"`
SpoofingDenied bool `json:"spoofing_denied"`
CrossCloneDenied bool `json:"cross_clone_denied"`
EvidenceSHA256 string `json:"evidence_sha256"`
}
func (e *engine) checkNetwork(ctx context.Context, a attempt, b Binding, c *pve.Client, vmid int, cfg map[string]any) error {
var opts settings
if json.Unmarshal(a.Settings, &opts) != nil {
return errors.New("invalid network settings")
type networkRequest struct {
OwnerID string `json:"owner_id"`
AttemptID string `json:"attempt_id"`
Node string `json:"node"`
VMID int `json:"vmid"`
LeaseID string `json:"lease_id"`
AllowedCIDRs []string `json:"allowed_cidrs"`
}
type networkAllocation struct {
Ready bool `json:"ready"`
OwnerID string `json:"owner_id"`
AttemptID string `json:"attempt_id"`
Node string `json:"node"`
VMID int `json:"vmid"`
LeaseID string `json:"lease_id"`
Bridge string `json:"bridge"`
MAC string `json:"mac"`
GuestIPv4 string `json:"guest_ipv4"`
GatewayIPv4 string `json:"gateway_ipv4"`
PrefixLength int `json:"prefix_length"`
DNSIPv4 []string `json:"dns_ipv4"`
PolicySHA256 string `json:"policy_sha256"`
ExpiresAt time.Time `json:"expires_at"`
}
type networkMetadata struct {
Request *networkRequest `json:"network_request"`
Network *networkAllocation `json:"network"`
Released bool `json:"network_released"`
}
func (p *OnlinePolicy) validate() error {
if p == nil {
return errors.New("online broker is not configured")
}
u, err := url.Parse(p.Endpoint)
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" {
return errors.New("online broker requires an HTTPS origin without path or credentials")
}
for _, path := range []string{p.CAFile, p.CertificateFile, p.KeyFile, p.ProofFile} {
if !filepath.IsAbs(path) {
return errors.New("online broker requires absolute private CA, certificate, key and proof paths")
}
}
_, err = netpolicy.Normalize("online", p.QualificationAllowedCIDRs)
return err
}
func (b Binding) networkProof(owner string) (onlineProof, error) {
var p onlineProof
if err := b.Online.validate(); err != nil {
return p, err
}
raw, err := os.ReadFile(b.Online.ProofFile)
if err != nil || len(raw) > 16384 || json.Unmarshal(raw, &p) != nil {
return p, errors.New("online isolation proof missing or malformed")
}
if !p.Passed || !p.ManagementDenied || !p.DefaultDenied || !p.IPv6Denied || !p.SpoofingDenied || !p.CrossCloneDenied || !p.ExpiresAt.After(time.Now()) || p.OwnerID != owner || p.Node != b.Node || p.Endpoint != b.Online.Endpoint || !shaRE.MatchString(p.EvidenceSHA256) {
return p, errors.New("online isolation proof invalid, expired or identity mismatch")
}
return p, nil
}
type networkBroker struct {
endpoint string
client *http.Client
}
func newNetworkBroker(p *OnlinePolicy) (*networkBroker, error) {
if err := p.validate(); err != nil {
return nil, err
}
ca, err := os.ReadFile(p.CAFile)
if err != nil {
return nil, errors.New("network broker CA unavailable")
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(ca) {
return nil, errors.New("network broker CA invalid")
}
cert, err := tls.LoadX509KeyPair(p.CertificateFile, p.KeyFile)
if err != nil {
return nil, errors.New("network broker client certificate unavailable or invalid")
}
transport := &http.Transport{TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: roots, Certificates: []tls.Certificate{cert}}, DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: 60 * time.Second}
return &networkBroker{p.Endpoint, &http.Client{Transport: transport, Timeout: 60 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("network broker redirects forbidden") }}}, nil
}
func (c *networkBroker) close() { c.client.CloseIdleConnections() }
func (c *networkBroker) call(ctx context.Context, action string, request networkRequest, response any) error {
if action != "prepare" && action != "check" && action != "release" && action != "health" {
return errors.New("invalid network broker action")
}
timeout := 8 * time.Second
if action == "prepare" || action == "release" {
timeout = 60 * time.Second
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var body []byte
var err error
method := http.MethodGet
if action != "health" {
method = http.MethodPost
body, err = json.Marshal(request)
if err != nil {
return err
}
}
req, err := http.NewRequestWithContext(ctx, method, c.endpoint+"/v1/"+action, bytes.NewReader(body))
if err != nil {
return errors.New("invalid network broker request")
}
req.Header.Set("Content-Type", "application/json")
res, err := c.client.Do(req)
if err != nil {
return fmt.Errorf("network policy %s transport failed", action)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("network policy %s refused (HTTP %d)", action, res.StatusCode)
}
raw, err := io.ReadAll(io.LimitReader(res.Body, 16385))
if err != nil || len(raw) > 16384 || json.Unmarshal(raw, response) != nil {
return errors.New("network broker response malformed or oversized")
}
return nil
}
func (r networkAllocation) validate(q networkRequest, previous *networkAllocation) error {
if !r.Ready || r.OwnerID != q.OwnerID || r.AttemptID != q.AttemptID || r.Node != q.Node || r.VMID != q.VMID || r.LeaseID != q.LeaseID || r.PolicySHA256 != netpolicy.Digest(q.AllowedCIDRs) {
return errors.New("network broker allocation identity or policy mismatch")
}
if !ident.MatchString(r.Bridge) || len(r.Bridge) > 15 || r.PrefixLength != 30 || !r.ExpiresAt.After(time.Now()) || r.ExpiresAt.After(time.Now().Add(60*time.Second)) {
return errors.New("network broker allocation topology or expiry invalid")
}
mac, err := net.ParseMAC(r.MAC)
if err != nil || len(mac) != 6 || mac[0]&1 != 0 {
return errors.New("network broker MAC invalid")
}
guest, err := netip.ParseAddr(r.GuestIPv4)
gateway, gatewayErr := netip.ParseAddr(r.GatewayIPv4)
if err != nil || gatewayErr != nil || !guest.Is4() || !gateway.Is4() || guest == gateway || !guest.IsGlobalUnicast() || !gateway.IsGlobalUnicast() {
return errors.New("network broker IPv4 allocation invalid")
}
subnet := netip.PrefixFrom(guest, 30).Masked()
if !subnet.Contains(gateway) || guest == subnet.Addr() || gateway == subnet.Addr() || guest.As4()[3]&3 == 3 || gateway.As4()[3]&3 == 3 {
return errors.New("network broker gateway subnet invalid")
}
if len(r.DNSIPv4) > 1 || len(r.DNSIPv4) == 1 && (r.DNSIPv4[0] != "1.1.1.1" || !allowsResolver(q.AllowedCIDRs)) {
return errors.New("network broker implicit DNS is forbidden")
}
if previous != nil && (r.Bridge != previous.Bridge || !strings.EqualFold(r.MAC, previous.MAC) || r.GuestIPv4 != previous.GuestIPv4 || r.GatewayIPv4 != previous.GatewayIPv4 || r.PrefixLength != previous.PrefixLength || !slices.Equal(r.DNSIPv4, previous.DNSIPv4)) {
return errors.New("network broker allocation changed during execution")
}
return nil
}
func allowsResolver(entries []string) bool {
dns := netip.MustParseAddr("1.1.1.1")
for _, s := range entries {
p, err := netip.ParsePrefix(s)
if err == nil && p.Contains(dns) {
return true
}
}
return false
}
func requestNetwork(a attempt, l allocation, b Binding) (networkRequest, error) {
var s settings
if json.Unmarshal(a.Settings, &s) != nil {
return networkRequest{}, errors.New("invalid network settings")
}
entries, err := netpolicy.Normalize(s.Internet, s.AllowedCIDRs)
if err != nil {
return networkRequest{}, err
}
return networkRequest{a.OwnerID, a.ID, b.Node, l.VMID, l.ID, entries}, nil
}
func recordedNetwork(a attempt, l allocation, b Binding) (networkMetadata, error) {
var m networkMetadata
if json.Unmarshal(l.Metadata, &m) != nil {
return m, errors.New("network allocation metadata invalid")
}
if m.Request == nil {
return m, nil
}
expected, err := requestNetwork(a, l, b)
if err != nil {
return m, err
}
q := m.Request
if q.OwnerID != expected.OwnerID || q.AttemptID != expected.AttemptID || q.Node != expected.Node || q.VMID != expected.VMID || q.LeaseID != expected.LeaseID || !slices.Equal(q.AllowedCIDRs, expected.AllowedCIDRs) {
return m, errors.New("recorded network request identity or policy mismatch")
}
if r := m.Network; r != nil && (!r.Ready || r.OwnerID != q.OwnerID || r.AttemptID != q.AttemptID || r.Node != q.Node || r.VMID != q.VMID || r.LeaseID != q.LeaseID || r.PolicySHA256 != netpolicy.Digest(q.AllowedCIDRs)) {
return m, errors.New("recorded network allocation identity or policy mismatch")
}
return m, nil
}
func (e *engine) storeNetwork(ctx context.Context, a attempt, l allocation, patch any) error {
raw, err := json.Marshal(patch)
if err != nil {
return err
}
tag, err := e.db.Exec(ctx, "UPDATE allocations SET metadata=metadata||$2::jsonb WHERE id=$1 AND attempt_id=$3 AND EXISTS(SELECT 1 FROM attempts WHERE id=$3 AND lease_owner=$4 AND lease_until>now())", l.ID, raw, a.ID, e.id)
if err == nil && tag.RowsAffected() != 1 {
err = errors.New("attempt lease lost while storing network policy")
}
return err
}
func (e *engine) prepareNetwork(ctx context.Context, a attempt, l allocation, b Binding, cs clients) error {
if _, err := b.networkProof(a.OwnerID); err != nil {
return err
}
if err := e.fence(ctx, a); err != nil {
return err
}
if err := cs.provisioner.CheckOwned(ctx, e.own(a, l, b)); err != nil {
return err
}
q, err := requestNetwork(a, l, b)
if err != nil {
return err
}
c, err := newNetworkBroker(b.Online)
if err != nil {
return err
}
defer c.close()
// Journal the exact request before sending: a lost response must still be revocable.
if err = e.storeNetwork(ctx, a, l, map[string]any{"network_request": q}); err != nil {
return err
}
if err = e.fence(ctx, a); err != nil {
return err
}
var r networkAllocation
if err = c.call(ctx, "prepare", q, &r); err != nil {
return err
}
if err = r.validate(q, nil); err != nil {
return err
}
return e.storeNetwork(ctx, a, l, map[string]any{"network": r})
}
func checkNetworkNIC(cfg map[string]any, internet string, r *networkAllocation) error {
nics := 0
for key, value := range cfg {
if !strings.HasPrefix(key, "net") {
continue
}
nics++
if opts.Internet == "offline" {
if internet == "offline" {
return errors.New("offline disposable VM has a NIC")
}
if opts.Internet != "online" || b.Online == nil {
return errors.New("online network has no configured isolation policy")
if internet != "online" || r == nil || key != "net0" {
return errors.New("online NIC has no broker allocation")
}
parts := map[string]string{}
for _, part := range strings.Split(pve.Text(value), ",") {
kv := strings.SplitN(part, "=", 2)
if len(kv) == 2 {
if len(kv) != 2 || parts[kv[0]] != "" {
return errors.New("online NIC configuration malformed")
}
parts[kv[0]] = kv[1]
}
for k := range parts {
if k != "virtio" && k != "bridge" && k != "firewall" {
return errors.New("online NIC contains unapproved options")
}
if parts["bridge"] != b.Online.Bridge || parts["firewall"] != "1" || parts["link_down"] == "1" {
return errors.New("online NIC differs from qualified sandbox")
}
if parts["bridge"] != r.Bridge || parts["firewall"] != "1" || !strings.EqualFold(parts["virtio"], r.MAC) {
return errors.New("online NIC differs from broker allocation")
}
}
if internet == "offline" {
return nil
}
if internet != "online" || nics != 1 {
return errors.New("online requires exactly one broker NIC")
}
return nil
}
func (e *engine) checkNetwork(ctx context.Context, a attempt, b Binding, vmid int, cfg map[string]any) error {
var opts settings
if json.Unmarshal(a.Settings, &opts) != nil {
return errors.New("invalid network settings")
}
if _, err := netpolicy.Normalize(opts.Internet, opts.AllowedCIDRs); err != nil {
return err
}
if opts.Internet == "offline" {
return nil
return checkNetworkNIC(cfg, "offline", nil)
}
if opts.Internet != "online" || nics != 1 || b.Online == nil || !ident.MatchString(b.Online.Bridge) {
return errors.New("online requires exactly one qualified sandbox NIC")
if _, err := b.networkProof(a.OwnerID); err != nil {
return err
}
raw, err := os.ReadFile(b.Online.ProofFile)
if err := e.fence(ctx, a); err != nil {
return err
}
l, err := e.getAllocation(ctx, a)
if err != nil {
return errors.New("online isolation proof missing")
}
var proof onlineProof
if json.Unmarshal(raw, &proof) != nil || !proof.Passed || !proof.ManagementDenied || !proof.PrivateNetworksDenied || !proof.CloudConsent || !proof.ExpiresAt.After(time.Now()) || proof.OwnerID != a.OwnerID || proof.Node != b.Node || proof.Bridge != b.Online.Bridge || !shaRE.MatchString(proof.EvidenceSHA256) {
return errors.New("online isolation proof invalid, expired or not consented")
}
var network, options map[string]any
var rules []map[string]any
if err = c.Do(ctx, "GET", "/nodes/"+b.Node+"/network/"+b.Online.Bridge, nil, &network); err != nil {
return err
}
if pve.Text(network["active"]) != "1" && pve.Text(network["active"]) != "true" {
return errors.New("isolated online bridge inactive")
if l.VMID != vmid {
return errors.New("network VMID differs from allocation")
}
delete(network, "digest")
if digest(network) != proof.NetworkSHA256 {
return errors.New("isolated network topology drift")
}
path := pve.VMPath(b.Node, vmid) + "/firewall"
if err = c.Do(ctx, "GET", path+"/options", nil, &options); err != nil {
m, err := recordedNetwork(a, l, b)
if err != nil {
return err
}
delete(options, "digest")
if pve.Text(options["enable"]) != "1" && pve.Text(options["enable"]) != "true" {
return errors.New("online VM firewall not enabled")
if m.Request == nil || m.Network == nil || m.Released {
return errors.New("network broker allocation missing or released")
}
if pve.Text(options["policy_in"]) != "DROP" || pve.Text(options["policy_out"]) != "DROP" {
return errors.New("online default firewall policies are not deny")
}
if err = c.Do(ctx, "GET", path+"/rules", url.Values{}, &rules); err != nil {
if err = checkNetworkNIC(cfg, "online", m.Network); err != nil {
return err
}
for _, r := range rules {
delete(r, "digest")
broker, err := newNetworkBroker(b.Online)
if err != nil {
return err
}
if digest(options) != proof.FirewallOptionsSHA256 || digest(rules) != proof.FirewallRulesSHA256 {
return errors.New("online firewall differs from qualified enforcement policy")
defer broker.close()
var r networkAllocation
if err = broker.call(ctx, "check", *m.Request, &r); err != nil {
return err
}
return r.validate(*m.Request, m.Network)
}
func (e *engine) releaseNetwork(ctx context.Context, a attempt, l allocation, b Binding) error {
if err := e.leaseAlive(ctx, a); err != nil {
return err
}
current, err := e.getAllocation(ctx, a)
if err != nil {
return err
}
if current.ID != l.ID || current.VMID != l.VMID {
return errors.New("network release allocation changed")
}
m, err := recordedNetwork(a, current, b)
if err != nil {
return err
}
if m.Request == nil || m.Released {
return nil
}
c, err := newNetworkBroker(b.Online)
if err != nil {
return err
}
defer c.close()
var response struct {
Released bool `json:"released"`
}
if err = c.call(ctx, "release", *m.Request, &response); err != nil {
return err
}
if !response.Released {
return errors.New("network broker release was not confirmed")
}
return e.storeNetwork(ctx, a, l, map[string]any{"network_released": true})
}
// Renewal never shares the QGA execution path: even a stuck guest cannot prolong authorization.
func (e *engine) renewNetwork(ctx context.Context, a attempt, l allocation, b Binding, cs clients, cancel context.CancelCauseFunc) func() {
monitor, stop := context.WithCancel(ctx)
done := make(chan struct{})
go func() {
defer close(done)
tick := time.NewTicker(10 * time.Second)
defer tick.Stop()
for {
select {
case <-monitor.Done():
return
case <-tick.C:
probe, end := context.WithTimeout(monitor, 8*time.Second)
cfg, err := cs.provisioner.Config(probe, b.Node, l.VMID)
if err == nil {
err = e.checkNetwork(probe, a, b, l.VMID, cfg)
}
end()
if err != nil {
if monitor.Err() != nil {
return
}
cancel(fmt.Errorf("network policy enforcement lost: %v", err))
// Broker revokes before refusing teardown of a running VM; cleanup stops then releases.
revoke, finish := context.WithTimeout(context.Background(), 8*time.Second)
_ = e.releaseNetwork(revoke, a, l, b)
finish()
return
}
}
}
}()
return func() { stop(); <-done }
}
func (e *engine) publishNetwork(ctx context.Context, a attempt, l allocation, b Binding, dir string) error {
current, err := e.getAllocation(ctx, a)
if err != nil {
return err
}
if current.ID != l.ID || current.VMID != l.VMID {
return errors.New("network evidence allocation changed")
}
m, err := recordedNetwork(a, current, b)
if err != nil {
return err
}
if m.Request == nil || m.Network == nil {
return errors.New("network policy evidence missing")
}
path := filepath.Join(dir, "network-policy.json")
if _, err = os.Stat(path); !os.IsNotExist(err) {
return errors.New("network policy evidence already exists or inaccessible")
}
if err = atomicJSON(path, map[string]any{"allowed_cidrs": m.Request.AllowedCIDRs, "public_only_wildcard": true, "allocation": m.Network}); err != nil {
return err
}
return e.publishFile(ctx, a, "network_policy", "network-policy.json", "application/json", path)
}
func (b Binding) networkReadiness(ctx context.Context, owner string) (time.Time, error) {
proof, err := b.networkProof(owner)
if err != nil {
return time.Time{}, err
}
c, err := newNetworkBroker(b.Online)
if err != nil {
return time.Time{}, err
}
defer c.close()
var health struct {
Ready bool `json:"ready"`
Node string `json:"node"`
LeaseSeconds int `json:"lease_seconds"`
}
if err = c.call(ctx, "health", networkRequest{}, &health); err != nil {
return time.Time{}, err
}
if !health.Ready || health.Node != b.Node || health.LeaseSeconds != 45 {
return time.Time{}, errors.New("network broker health identity or lease policy invalid")
}
return proof.ExpiresAt, nil
}
+388 -37
View File
@@ -2,76 +2,427 @@ package worker
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"math/big"
"net/http"
"net/http/httptest"
"os"
"otche/internal/netpolicy"
"otche/internal/pve"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestNetworkGateRejectsUnprovenOnlineAndOfflineNIC(t *testing.T) {
network := map[string]any{"active": true, "iface": "isolated", "type": "bridge"}
options := map[string]any{"enable": true, "policy_in": "DROP", "policy_out": "DROP"}
rules := []map[string]any{{"type": "out", "action": "ACCEPT", "dest": "198.51.100.1", "enable": 1}}
func brokerFixture(t *testing.T, handler http.HandlerFunc) *OnlinePolicy {
t.Helper()
dir := t.TempDir()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
ca := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "test owner CA"}, NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature}
caDER, err := x509.CreateCertificate(rand.Reader, ca, ca, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
cert := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "fixture-owner"}, NotBefore: time.Now().Add(-time.Minute), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}
certDER, err := x509.CreateCertificate(rand.Reader, cert, ca, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
t.Fatal(err)
}
roots := x509.NewCertPool()
roots.AppendCertsFromPEM(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}))
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(r.TLS.VerifiedChains) == 0 || r.TLS.PeerCertificates[0].Subject.CommonName != "fixture-owner" {
t.Error("unverified broker client")
}
handler(w, r)
}))
server.TLS = &tls.Config{ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: roots, MinVersion: tls.VersionTLS12}
server.StartTLS()
t.Cleanup(server.Close)
p := &OnlinePolicy{Endpoint: server.URL, CAFile: filepath.Join(dir, "ca.pem"), CertificateFile: filepath.Join(dir, "client.pem"), KeyFile: filepath.Join(dir, "key.pem"), ProofFile: filepath.Join(dir, "proof.json"), QualificationAllowedCIDRs: []string{"1.1.1.1/32"}}
for path, data := range map[string][]byte{p.CAFile: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}), p.CertificateFile: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}), p.KeyFile: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})} {
if err = os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
}
return p
}
func fixtureNetwork(q networkRequest) networkAllocation {
return networkAllocation{Ready: true, OwnerID: q.OwnerID, AttemptID: q.AttemptID, Node: q.Node, VMID: q.VMID, LeaseID: q.LeaseID, Bridge: "otchetest0", MAC: "02:12:34:56:78:90", GuestIPv4: "100.96.0.2", GatewayIPv4: "100.96.0.1", PrefixLength: 30, DNSIPv4: []string{"1.1.1.1"}, PolicySHA256: netpolicy.Digest(q.AllowedCIDRs), ExpiresAt: time.Now().Add(45 * time.Second)}
}
func TestBrokerMutualTLSAndBoundedFailures(t *testing.T) {
var mode atomic.Int32
p := brokerFixture(t, func(w http.ResponseWriter, r *http.Request) {
switch mode.Load() {
case 1:
http.Redirect(w, r, "https://example.invalid/", http.StatusTemporaryRedirect)
case 2:
w.Write([]byte(strings.Repeat("x", 16385)))
case 3:
http.Error(w, "secret operator diagnostic", http.StatusForbidden)
default:
var q networkRequest
if err := json.NewDecoder(r.Body).Decode(&q); err != nil {
t.Error(err)
}
json.NewEncoder(w).Encode(fixtureNetwork(q))
}
})
client, err := newNetworkBroker(p)
if err != nil {
t.Fatal(err)
}
defer client.close()
q := networkRequest{newID(), newID(), "node", 8101, newID(), []string{"1.1.1.1/32"}}
var r networkAllocation
if err = client.call(context.Background(), "prepare", q, &r); err != nil {
t.Fatal(err)
}
if err = r.validate(q, nil); err != nil {
t.Fatal(err)
}
for _, m := range []int32{1, 2, 3} {
mode.Store(m)
err = client.call(context.Background(), "check", q, &r)
if err == nil || strings.Contains(err.Error(), "secret operator diagnostic") {
t.Fatalf("unsafe broker failure %d: %v", m, err)
}
}
// Missing client authentication fails the TLS handshake before any request is served.
transport := client.client.Transport.(*http.Transport).Clone()
transport.TLSClientConfig = transport.TLSClientConfig.Clone()
transport.TLSClientConfig.Certificates = nil
unauthenticated := &http.Client{Transport: transport, Timeout: time.Second}
defer unauthenticated.CloseIdleConnections()
if res, err := unauthenticated.Get(p.Endpoint + "/v1/health"); err == nil {
res.Body.Close()
t.Fatal("broker accepted missing client certificate")
}
transport2 := client.client.Transport.(*http.Transport).Clone()
transport2.TLSClientConfig = transport2.TLSClientConfig.Clone()
transport2.TLSClientConfig.RootCAs = x509.NewCertPool()
untrusted := &http.Client{Transport: transport2, Timeout: time.Second}
defer untrusted.CloseIdleConnections()
if res, err := untrusted.Get(p.Endpoint + "/v1/health"); err == nil {
res.Body.Close()
t.Fatal("client accepted untrusted server")
}
}
func TestBrokerResponseRejectsIdentityPolicyAndTopologyDrift(t *testing.T) {
q := networkRequest{newID(), newID(), "node", 8101, newID(), []string{"1.1.1.1/32"}}
original := fixtureNetwork(q)
mutations := map[string]func(*networkAllocation){
"other owner": func(r *networkAllocation) { r.OwnerID = newID() },
"other attempt": func(r *networkAllocation) { r.AttemptID = newID() },
"reused vmid": func(r *networkAllocation) { r.VMID++ },
"other lease": func(r *networkAllocation) { r.LeaseID = newID() },
"different policy": func(r *networkAllocation) { r.PolicySHA256 = netpolicy.Digest([]string{"0.0.0.0/0"}) },
"expired": func(r *networkAllocation) { r.ExpiresAt = time.Now().Add(-time.Second) },
"unbounded lease": func(r *networkAllocation) { r.ExpiresAt = time.Now().Add(time.Hour) },
"different bridge": func(r *networkAllocation) { r.Bridge = "otherbridge" },
"different MAC": func(r *networkAllocation) { r.MAC = "02:00:00:00:00:01" },
"implicit DNS": func(r *networkAllocation) { r.DNSIPv4 = []string{"8.8.8.8"} },
"off subnet gateway": func(r *networkAllocation) { r.GatewayIPv4 = "100.96.1.1" },
"IPv6": func(r *networkAllocation) { r.GuestIPv4 = "2001:db8::1" },
}
for name, change := range mutations {
t.Run(name, func(t *testing.T) {
r := original
change(&r)
if r.validate(q, &original) == nil {
t.Fatal("unsafe network allocation accepted")
}
})
}
q.AllowedCIDRs = []string{"8.8.8.8/32"}
r := fixtureNetwork(q)
if r.validate(q, nil) == nil {
t.Fatal("resolver outside finite allowlist accepted")
}
r.DNSIPv4 = []string{}
if err := r.validate(q, nil); err != nil {
t.Fatal(err)
}
}
func TestNetworkNICOfflineAndOnlineIsolation(t *testing.T) {
q := networkRequest{newID(), newID(), "node", 8101, newID(), []string{"1.1.1.1/32"}}
r := fixtureNetwork(q)
nic := "virtio=" + r.MAC + ",bridge=" + r.Bridge + ",firewall=1"
if err := checkNetworkNIC(map[string]any{}, "offline", nil); err != nil {
t.Fatal(err)
}
if checkNetworkNIC(map[string]any{"net0": nic}, "offline", nil) == nil {
t.Fatal("offline NIC accepted")
}
if err := checkNetworkNIC(map[string]any{"net0": nic}, "online", &r); err != nil {
t.Fatal(err)
}
for _, cfg := range []map[string]any{{}, {"net0": nic + ",tag=100"}, {"net0": nic + ",link_down=1"}, {"net0": nic, "net1": nic}, {"net0": strings.Replace(nic, "firewall=1", "firewall=0", 1)}} {
if checkNetworkNIC(cfg, "online", &r) == nil {
t.Fatal("unapproved NIC accepted")
}
}
}
func TestNetworkProofRequiresAllActualControls(t *testing.T) {
p := brokerFixture(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
owner := newID()
b := Binding{Node: "node", Online: p}
proof := onlineProof{OwnerID: owner, Node: b.Node, Endpoint: p.Endpoint, Passed: true, ManagementDenied: true, DefaultDenied: true, IPv6Denied: true, SpoofingDenied: true, CrossCloneDenied: true, ExpiresAt: time.Now().Add(time.Hour), EvidenceSHA256: strings.Repeat("a", 64)}
if err := atomicJSON(p.ProofFile, proof); err != nil {
t.Fatal(err)
}
if _, err := b.networkProof(owner); err != nil {
t.Fatal(err)
}
for _, modify := range []func(*onlineProof){func(p *onlineProof) { p.SpoofingDenied = false }, func(p *onlineProof) { p.ExpiresAt = time.Now().Add(-time.Second) }, func(p *onlineProof) { p.Endpoint = "https://other.invalid" }} {
bad := proof
modify(&bad)
if err := atomicJSON(p.ProofFile, bad); err != nil {
t.Fatal(err)
}
if _, err := b.networkProof(owner); err == nil {
t.Fatal("unproven online policy accepted")
}
}
}
func TestNetworkReleaseRetainsOriginalIdentityAndFencesWorker(t *testing.T) {
db, ctx := recoveryDatabase(t)
a := recoveryAttempt(t, ctx, db)
a.Settings = json.RawMessage(`{"internet":"online","allowed_cidrs":["1.1.1.1/32"]}`)
var releases atomic.Int32
var expected networkRequest
p := brokerFixture(t, func(w http.ResponseWriter, r *http.Request) {
var q networkRequest
if err := json.NewDecoder(r.Body).Decode(&q); err != nil {
t.Error(err)
}
if r.URL.Path != "/v1/release" || q.LeaseID != expected.LeaseID || q.VMID != expected.VMID || q.AttemptID != expected.AttemptID {
t.Error("release changed recorded identity")
}
releases.Add(1)
json.NewEncoder(w).Encode(map[string]bool{"released": true})
})
b := Binding{Node: "node", Pool: "owned", Online: p}
e := engine{db: db, id: newID(), cfg: Config{Owners: map[string]Binding{a.OwnerID: b}}}
l := allocation{ID: newID(), VMID: 8101, State: "deleted"}
expected, _ = requestNetwork(a, l, b)
l.Metadata, _ = json.Marshal(networkMetadata{Request: &expected})
if _, err := db.Exec(ctx, "UPDATE attempts SET lease_owner=$2,lease_until=now()+interval '1 minute' WHERE id=$1", a.ID, e.id); err != nil {
t.Fatal(err)
}
if _, err := db.Exec(ctx, "INSERT INTO allocations(id,attempt_id,owner_id,node,vmid,pool,state,metadata)VALUES($1,$2,$3,$4,$5,$6,$7,$8)", l.ID, a.ID, a.OwnerID, b.Node, l.VMID, b.Pool, l.State, l.Metadata); err != nil {
t.Fatal(err)
}
// A different caller-supplied VMID must not tear down the recorded allocation.
wrong := l
wrong.VMID++
if e.releaseNetwork(ctx, a, wrong, b) == nil || releases.Load() != 0 {
t.Fatal("wrong allocation was released")
}
if err := e.stopOwned(ctx, a, l, b, clients{}); err != nil {
t.Fatal(err)
}
if err := e.releaseNetwork(ctx, a, l, b); err != nil {
t.Fatal(err)
}
if releases.Load() != 1 {
t.Fatal("released allocation was reissued")
}
// A superseded worker cannot use broker credentials to release a newer generation.
if _, err := db.Exec(ctx, "UPDATE attempts SET lease_owner=$2 WHERE id=$1", a.ID, newID()); err != nil {
t.Fatal(err)
}
if e.releaseNetwork(ctx, a, l, b) == nil {
t.Fatal("superseded worker released network")
}
}
func TestStopReleasesNetworkOnlyAfterConfirmedStop(t *testing.T) {
db, ctx := recoveryDatabase(t)
a := recoveryAttempt(t, ctx, db)
a.Settings = json.RawMessage(`{"internet":"online","allowed_cidrs":["1.1.1.1/32"]}`)
var stopped atomic.Bool
var released atomic.Bool
p := brokerFixture(t, func(w http.ResponseWriter, r *http.Request) {
if !stopped.Load() {
t.Error("released before stop confirmation")
}
released.Store(true)
json.NewEncoder(w).Encode(map[string]bool{"released": true})
})
b := Binding{Node: "node", Pool: "owned", Online: p}
e := engine{db: db, id: newID(), cfg: Config{Owners: map[string]Binding{a.OwnerID: b}}}
l := allocation{ID: newID(), VMID: 8101, State: "running"}
q, _ := requestNetwork(a, l, b)
l.Metadata, _ = json.Marshal(networkMetadata{Request: &q})
if _, err := db.Exec(ctx, "UPDATE attempts SET lease_owner=$2,lease_until=now()+interval '1 minute' WHERE id=$1", a.ID, e.id); err != nil {
t.Fatal(err)
}
if _, err := db.Exec(ctx, "INSERT INTO allocations(id,attempt_id,owner_id,node,vmid,pool,state,metadata)VALUES($1,$2,$3,$4,$5,$6,$7,$8)", l.ID, a.ID, a.OwnerID, b.Node, l.VMID, b.Pool, l.State, l.Metadata); err != nil {
t.Fatal(err)
}
// An already-stopped verified clone exercises the exact stop -> release -> state boundary.
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var result any
switch {
case strings.Contains(r.URL.Path, "/network/"):
result = network
case strings.HasSuffix(r.URL.Path, "/options"):
result = options
case strings.HasSuffix(r.URL.Path, "/rules"):
result = rules
switch r.URL.Path {
case "/api2/json/pools/owned":
result = map[string]any{"members": []map[string]any{{"type": "qemu", "vmid": 8101, "node": "node"}}}
case "/api2/json/nodes/node/qemu/8101/config":
result = map[string]any{"name": "otche-" + a.ID, "tags": "otche;otche-owner-" + a.OwnerID + ";otche-attempt-" + a.ID}
case "/api2/json/nodes/node/qemu/8101/status/current":
stopped.Store(true)
result = map[string]any{"status": "stopped"}
default:
t.Errorf("unexpected %s", r.URL.Path)
t.Errorf("unexpected PVE request %s", r.URL.Path)
http.Error(w, "unexpected", 500)
return
}
json.NewEncoder(w).Encode(map[string]any{"data": result})
}))
defer server.Close()
dir := t.TempDir()
ca := filepath.Join(dir, "ca.pem")
credential := filepath.Join(dir, "credential.json")
ca := filepath.Join(dir, "pve-ca.pem")
creds := filepath.Join(dir, "pve.json")
if err := os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(credential, []byte(`{"token_id":"fixture@pve!test","secret":"test-only"}`), 0600); err != nil {
if err := os.WriteFile(creds, []byte(`{"token_id":"fixture@pve!test","secret":"test-only"}`), 0600); err != nil {
t.Fatal(err)
}
client, err := pve.New(server.URL, ca, credential)
pc, err := pve.New(server.URL, ca, creds)
if err != nil {
t.Fatal(err)
}
defer client.Close()
e := engine{}
a := attempt{OwnerID: newID(), Settings: json.RawMessage(`{"internet":"offline"}`)}
b := Binding{Node: "node"}
nic := map[string]any{"net0": "virtio=12:34:56:78:90:AB,bridge=isolated,firewall=1"}
if e.checkNetwork(context.Background(), a, b, client, 9001, nic) == nil {
t.Fatal("offline NIC was accepted")
}
if err = e.checkNetwork(context.Background(), a, b, client, 9001, map[string]any{}); err != nil {
defer pc.Close()
if err = e.stopOwned(ctx, a, l, b, clients{provisioner: pc}); err != nil {
t.Fatal(err)
}
a.Settings = json.RawMessage(`{"internet":"online"}`)
if e.checkNetwork(context.Background(), a, b, client, 9001, nic) == nil {
t.Fatal("unconfigured online was accepted")
if !released.Load() {
t.Fatal("confirmed stopped clone retained active network")
}
proofPath := filepath.Join(dir, "proof.json")
b.Online = &OnlinePolicy{Bridge: "isolated", ProofFile: proofPath}
proof := onlineProof{OwnerID: a.OwnerID, Node: b.Node, Bridge: "isolated", Passed: true, ExpiresAt: time.Now().Add(time.Hour), ManagementDenied: true, PrivateNetworksDenied: true, CloudConsent: true, NetworkSHA256: digest(network), FirewallOptionsSHA256: digest(options), FirewallRulesSHA256: digest(rules), EvidenceSHA256: strings.Repeat("a", 64)}
if err = atomicJSON(proofPath, proof); err != nil {
}
func TestNetworkRenewalCancelsIndependentlyOfGuestWork(t *testing.T) {
db, parent := recoveryDatabase(t)
a := recoveryAttempt(t, parent, db)
a.Settings = json.RawMessage(`{"internet":"online","allowed_cidrs":["1.1.1.1/32"]}`)
var checked, revoked atomic.Bool
p := brokerFixture(t, func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/check":
checked.Store(true)
http.Error(w, "kernel policy drift", http.StatusConflict)
case "/v1/release":
revoked.Store(true)
http.Error(w, "running clone; revoked, teardown refused", http.StatusConflict)
default:
t.Errorf("unexpected broker action %s", r.URL.Path)
http.Error(w, "unexpected", 500)
}
})
b := Binding{Node: "node", Pool: "owned", Online: p}
e := engine{db: db, id: newID(), cfg: Config{Owners: map[string]Binding{a.OwnerID: b}}}
proof := onlineProof{OwnerID: a.OwnerID, Node: b.Node, Endpoint: p.Endpoint, Passed: true, ManagementDenied: true, DefaultDenied: true, IPv6Denied: true, SpoofingDenied: true, CrossCloneDenied: true, ExpiresAt: time.Now().Add(time.Hour), EvidenceSHA256: strings.Repeat("a", 64)}
if err := atomicJSON(p.ProofFile, proof); err != nil {
t.Fatal(err)
}
if err = e.checkNetwork(context.Background(), a, b, client, 9001, nic); err != nil {
t.Fatalf("matching qualified enforcement rejected: %v", err)
l := allocation{ID: newID(), VMID: 8101, State: "running"}
q, _ := requestNetwork(a, l, b)
n := fixtureNetwork(q)
l.Metadata, _ = json.Marshal(networkMetadata{Request: &q, Network: &n})
if _, err := db.Exec(parent, "UPDATE attempts SET lease_owner=$2,lease_until=now()+interval '1 minute' WHERE id=$1", a.ID, e.id); err != nil {
t.Fatal(err)
}
options["policy_out"] = "ACCEPT"
if e.checkNetwork(context.Background(), a, b, client, 9001, nic) == nil {
t.Fatal("firewall drift to default allow accepted")
if _, err := db.Exec(parent, "INSERT INTO allocations(id,attempt_id,owner_id,node,vmid,pool,state,metadata)VALUES($1,$2,$3,$4,$5,$6,$7,$8)", l.ID, a.ID, a.OwnerID, b.Node, l.VMID, b.Pool, l.State, l.Metadata); err != nil {
t.Fatal(err)
}
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api2/json/nodes/node/qemu/8101/config" {
t.Error("renewal tried guest execution")
}
json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"net0": "virtio=" + n.MAC + ",bridge=" + n.Bridge + ",firewall=1"}})
}))
defer server.Close()
dir := t.TempDir()
ca := filepath.Join(dir, "ca.pem")
creds := filepath.Join(dir, "pve.json")
if err := os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(creds, []byte(`{"token_id":"fixture@pve!test","secret":"test-only"}`), 0600); err != nil {
t.Fatal(err)
}
pc, err := pve.New(server.URL, ca, creds)
if err != nil {
t.Fatal(err)
}
defer pc.Close()
ctx, cancel := context.WithCancelCause(parent)
defer cancel(nil)
stop := e.renewNetwork(ctx, a, l, b, clients{provisioner: pc}, cancel)
defer stop()
// No runtime/QGA client is supplied: the separate renewal task must still fail closed.
select {
case <-ctx.Done():
case <-time.After(20 * time.Second):
t.Fatal("renewal did not cancel stalled guest execution")
}
stop()
if !checked.Load() || !revoked.Load() || !strings.Contains(context.Cause(ctx).Error(), "network policy enforcement lost") {
t.Fatalf("network failure not attributed/revoked: %v", context.Cause(ctx))
}
current, err := e.getAllocation(parent, a)
if err != nil {
t.Fatal(err)
}
var m networkMetadata
if err = json.Unmarshal(current.Metadata, &m); err != nil {
t.Fatal(err)
}
if m.Released {
t.Fatal("failed running-VM teardown marked released")
}
}
func TestNetworkReadinessRequiresBoundBrokerHealth(t *testing.T) {
var wrongNode atomic.Bool
p := brokerFixture(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || r.URL.Path != "/v1/health" {
t.Error("invalid health request")
}
node := "node"
if wrongNode.Load() {
node = "other"
}
json.NewEncoder(w).Encode(map[string]any{"ready": true, "node": node, "lease_seconds": 45})
})
owner := newID()
b := Binding{Node: "node", Online: p}
proof := onlineProof{OwnerID: owner, Node: b.Node, Endpoint: p.Endpoint, Passed: true, ManagementDenied: true, DefaultDenied: true, IPv6Denied: true, SpoofingDenied: true, CrossCloneDenied: true, ExpiresAt: time.Now().Add(time.Hour), EvidenceSHA256: strings.Repeat("a", 64)}
if err := atomicJSON(p.ProofFile, proof); err != nil {
t.Fatal(err)
}
if _, err := b.networkReadiness(context.Background(), owner); err != nil {
t.Fatal(err)
}
wrongNode.Store(true)
if _, err := b.networkReadiness(context.Background(), owner); err == nil {
t.Fatal("wrong broker node authorized online admission")
}
}
+3 -3
View File
@@ -280,7 +280,7 @@ func (e *engine) prepareClone(ctx context.Context, a attempt, l allocation, b Bi
return errors.New("invalid job settings")
}
if opts.Internet == "online" {
if err = e.checkNetwork(ctx, a, b, cs.provisioner, l.VMID, cfg); err != nil {
if err = e.checkNetwork(ctx, a, b, l.VMID, cfg); err != nil {
return err
}
}
@@ -317,7 +317,7 @@ func (e *engine) prepareClone(ctx context.Context, a attempt, l allocation, b Bi
if err != nil {
return err
}
if err = e.checkNetwork(ctx, a, b, cs.provisioner, l.VMID, cfg); err != nil {
if err = e.checkNetwork(ctx, a, b, l.VMID, cfg); err != nil {
return err
}
if !cdromMatches(pve.Text(cfg[slot]), "none") {
@@ -338,7 +338,7 @@ func (e *engine) swapISO(ctx context.Context, a attempt, l allocation, b Binding
if !cdromMatches(pve.Text(cfg[slot]), "none") {
return errors.New("hot media insertion requires the existing empty drive")
}
if err = e.checkNetwork(ctx, a, b, cs.provisioner, l.VMID, cfg); err != nil {
if err = e.checkNetwork(ctx, a, b, l.VMID, cfg); err != nil {
return err
}
upid, err := cs.provisioner.OwnedTask(ctx, o, "POST", "/config", url.Values{slot: {volume + ",media=cdrom"}})
+49 -1
View File
@@ -9,6 +9,7 @@ import (
"github.com/jackc/pgx/v5"
"io"
"os"
"otche/internal/netpolicy"
"path/filepath"
"strings"
)
@@ -81,6 +82,11 @@ func (e *engine) qualify(ctx context.Context) error {
if !shaRE.MatchString(e.cfg.BenignSHA256) || !filepath.IsAbs(e.cfg.BenignFixture) || !strings.EqualFold(filepath.Ext(e.cfg.BenignFixture), ".exe") {
result.Errors = append(result.Errors, "Explicit benign native EXE fixture file and verified SHA-256 required")
}
if b.Online != nil {
if _, err = b.networkProof(owner); err != nil {
result.Errors = append(result.Errors, err.Error())
}
}
if len(result.Errors) == 0 {
networks := []string{"offline"}
if b.Online != nil {
@@ -108,6 +114,18 @@ func (e *engine) qualify(ctx context.Context) error {
return tx.Commit(ctx)
}
func (e *engine) enqueueControl(ctx context.Context, tx pgx.Tx, qid, profile, revision, owner, kind, internet string) (qualificationControl, error) {
var allowed []string
if internet == "online" {
b := e.cfg.Owners[owner]
if _, err := b.networkProof(owner); err != nil {
return qualificationControl{}, err
}
var err error
allowed, err = netpolicy.Normalize("online", b.Online.QualificationAllowedCIDRs)
if err != nil {
return qualificationControl{}, err
}
}
c := qualificationControl{Kind: kind, Internet: internet, JobID: newID(), AttemptID: newID()}
upload, run, command := newID(), newID(), newID()
filename := "otche-benign.exe"
@@ -151,7 +169,7 @@ func (e *engine) enqueueControl(ctx context.Context, tx pgx.Tx, qid, profile, re
if kind == "benign" && hash != e.cfg.BenignSHA256 {
return c, errors.New("benign fixture SHA-256 differs from configured known-safe control")
}
settings, _ := json.Marshal(map[string]any{"internet": internet, "duration_seconds": 30, "filename": "original", "privilege": "user", "args_mode": "none", "args": []string{}, "set_zoneid": false, "dll_mode": "regsvr32", "dll_export": "", "architecture": "auto", "wsh_host": "cscript", "msi_ui": "full", "_qualification": kind})
settings, _ := json.Marshal(map[string]any{"internet": internet, "allowed_cidrs": allowed, "duration_seconds": 30, "filename": "original", "privilege": "user", "args_mode": "none", "args": []string{}, "set_zoneid": false, "dll_mode": "regsvr32", "dll_export": "", "architecture": "auto", "wsh_host": "cscript", "msi_ui": "full", "_qualification": kind})
if _, err = tx.Exec(ctx, "INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key) VALUES($1,$2,$3,$4,$5,$6)", upload, owner, filename, n, hash, key); err != nil {
return c, err
}
@@ -172,11 +190,28 @@ func (e *engine) completeQualification(ctx context.Context, id, profile string,
baseline := ""
var metadata any
onlineControls := map[string]bool{}
seenControls := map[string]bool{}
seenAttempts := map[string]bool{}
for _, control := range result.Controls {
if control.Internet != "offline" && control.Internet != "online" || control.Kind != "eicar" && control.Kind != "benign" {
return errors.New("invalid qualification control identity")
}
key := control.Internet + "/" + control.Kind
if seenControls[key] || seenAttempts[control.AttemptID] {
return errors.New("duplicate qualification control")
}
seenControls[key], seenAttempts[control.AttemptID] = true, true
if control.Internet == "online" {
onlineControls[control.Kind] = true
b := e.cfg.Owners[e.cfg.QualificationOwner]
if _, err := b.networkProof(e.cfg.QualificationOwner); err != nil {
result.Errors = append(result.Errors, err.Error())
}
}
}
if !seenControls["offline/eicar"] || !seenControls["offline/benign"] || onlineControls["eicar"] != onlineControls["benign"] {
return errors.New("qualification requires paired offline and optional online controls")
}
for _, control := range result.Controls {
var phase, outcome, findings, telemetry, cleanup string
var report []byte
@@ -186,6 +221,19 @@ func (e *engine) completeQualification(ctx context.Context, id, profile string,
if phase != "finished" {
return nil
}
if control.Internet == "online" {
var immutable []byte
var evidence bool
if err := e.db.QueryRow(ctx, `SELECT j.settings,EXISTS(SELECT 1 FROM artifacts WHERE attempt_id=a.id AND kind='network_policy') FROM attempts a JOIN runs r ON r.id=a.run_id JOIN jobs j ON j.id=r.job_id WHERE a.id=$1 AND j.id=$2 AND j.owner_id=$3`, control.AttemptID, control.JobID, e.cfg.QualificationOwner).Scan(&immutable, &evidence); err != nil {
return err
}
var opts settings
if json.Unmarshal(immutable, &opts) != nil || opts.Internet != "online" || !evidence {
result.Errors = append(result.Errors, "Online control has no strict broker policy evidence")
} else if _, err := netpolicy.Normalize("online", opts.AllowedCIDRs); err != nil {
result.Errors = append(result.Errors, "Online control has no valid immutable allowlist")
}
}
if telemetry != "complete" || cleanup != "complete" {
result.Errors = append(result.Errors, control.Kind+" control observation/collection/cleanup incomplete")
}
+34 -2
View File
@@ -51,17 +51,28 @@ func (e *engine) stopOwned(ctx context.Context, a attempt, l allocation, b Bindi
}
}
if l.State == "deleted" {
return nil
return e.releaseNetwork(ctx, a, l, b)
}
o := e.own(a, l, b)
if err := cs.provisioner.CheckOwned(ctx, o); err != nil {
absent, lookupErr := vmAbsent(ctx, cs.provisioner, b.Node, l.VMID)
if lookupErr != nil || !absent {
return errors.New("cannot establish pool/tags/name ownership for stop; resources retained")
}
if err = e.releaseNetwork(ctx, a, l, b); err != nil {
return err
}
_, err = e.db.Exec(ctx, "UPDATE allocations SET state='deleted' WHERE id=$1", l.ID)
return err
}
state, err := cs.provisioner.Status(ctx, b.Node, l.VMID)
if err != nil {
return err
}
if state == "stopped" {
if err = e.releaseNetwork(ctx, a, l, b); err != nil {
return err
}
_, err = e.db.Exec(ctx, "UPDATE allocations SET state='stopped' WHERE id=$1", l.ID)
return err
}
@@ -90,12 +101,23 @@ func (e *engine) stopOwned(ctx context.Context, a attempt, l allocation, b Bindi
if state != "stopped" {
return errors.New("PVE stop task did not stop clone")
}
if err = e.releaseNetwork(ctx, a, l, b); err != nil {
return err
}
_, err = e.db.Exec(ctx, "UPDATE allocations SET state='stopped' WHERE id=$1", l.ID)
return err
}
func (e *engine) deleteOwned(ctx context.Context, a attempt, l allocation, b Binding, cs clients) error {
current, err := e.getAllocation(ctx, a)
if err != nil {
return err
}
if current.ID != l.ID || current.VMID != l.VMID {
return errors.New("allocation changed before deletion")
}
l = current
if l.State == "deleted" {
return nil
return e.releaseNetwork(ctx, a, l, b)
}
if err := e.leaseAlive(ctx, a); err != nil {
return err
@@ -114,6 +136,9 @@ func (e *engine) deleteOwned(ctx context.Context, a attempt, l allocation, b Bin
if state != "stopped" {
return errors.New("clone destruction requires confirmed stopped state")
}
if err = e.releaseNetwork(ctx, a, l, b); err != nil {
return err
}
if err = cs.provisioner.NoPending(ctx, b.Node, l.VMID, ""); err != nil {
return err
}
@@ -214,6 +239,10 @@ func (e *engine) releaseAttempt(ctx context.Context, id string) (retErr error) {
var absent bool
absent, err = vmAbsent(ctx, cs.provisioner, b.Node, l.VMID)
if err == nil && absent {
err = e.releaseNetwork(ctx, a, l, b)
if err != nil {
return err
}
_, err = e.db.Exec(ctx, "UPDATE allocations SET state='deleted' WHERE id=$1", l.ID)
l.State = "deleted"
}
@@ -225,6 +254,9 @@ func (e *engine) releaseAttempt(ctx context.Context, id string) (retErr error) {
err = e.deleteOwned(ctx, a, l, b, cs)
}
}
if err == nil && l.State == "deleted" {
err = e.releaseNetwork(ctx, a, l, b)
}
if err == nil {
err = e.removeMedia(ctx, a, b, cs)
}
+13 -17
View File
@@ -89,21 +89,7 @@ func sourceConfig(ctx context.Context, c *pve.Client, s Source) (map[string]any,
return nil, "", 0, errors.New("source has inserted or ambiguous CD media")
}
if strings.HasPrefix(k, "net") {
bridge := ""
for _, part := range strings.Split(str, ",") {
if strings.HasPrefix(part, "bridge=") {
bridge = strings.TrimPrefix(part, "bridge=")
}
}
allowed := false
for _, b := range s.AllowedBridges {
if b == bridge {
allowed = true
}
}
if !allowed {
return nil, "", 0, errors.New("source inherited network is not an approved lab bridge")
}
return nil, "", 0, errors.New("source must have no NIC; online networking is attached only to disposable clones")
}
}
var diskBytes int64
@@ -269,7 +255,7 @@ func SyncBindings(ctx context.Context, db *pgxpool.Pool, configPath string) erro
if err != nil {
return err
}
if _, err = db.Exec(ctx, "UPDATE bindings SET configured=false,reason='Binding requires worker validation'"); err != nil {
if _, err = db.Exec(ctx, "UPDATE bindings SET configured=false,reason='Binding requires worker validation',online_ready=false,online_expires_at=NULL,online_reason='Online network requires worker validation'"); err != nil {
return err
}
for owner, b := range cfg.Owners {
@@ -299,7 +285,17 @@ func SyncBindings(ctx context.Context, db *pgxpool.Pool, configPath string) erro
reason = e.Error()
}
}
_, err = db.Exec(ctx, `INSERT INTO bindings(owner_id,pool,iso_storage,disk_storage,node,configured,reason,isolation_expires_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8) ON CONFLICT(owner_id) DO UPDATE SET pool=excluded.pool,iso_storage=excluded.iso_storage,disk_storage=excluded.disk_storage,node=excluded.node,configured=excluded.configured,reason=excluded.reason,isolation_expires_at=excluded.isolation_expires_at`, owner, b.Pool, b.ISOStorage, b.DiskStorage, b.Node, reason == "", reason, expiresAt)
onlineReason := "Online network not configured"
var onlineExpires *time.Time
if b.Online != nil {
if expiry, onlineErr := b.networkReadiness(ctx, owner); onlineErr != nil {
onlineReason = "Online broker or isolation proof unavailable; operator revalidation required"
} else {
onlineReason = ""
onlineExpires = &expiry
}
}
_, err = db.Exec(ctx, `INSERT INTO bindings(owner_id,pool,iso_storage,disk_storage,node,configured,reason,isolation_expires_at,online_ready,online_expires_at,online_reason) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) ON CONFLICT(owner_id) DO UPDATE SET pool=excluded.pool,iso_storage=excluded.iso_storage,disk_storage=excluded.disk_storage,node=excluded.node,configured=excluded.configured,reason=excluded.reason,isolation_expires_at=excluded.isolation_expires_at,online_ready=excluded.online_ready,online_expires_at=excluded.online_expires_at,online_reason=excluded.online_reason`, owner, b.Pool, b.ISOStorage, b.DiskStorage, b.Node, reason == "", reason, expiresAt, reason == "" && onlineReason == "", onlineExpires, onlineReason)
if err != nil {
return err
}
+4
View File
@@ -25,6 +25,7 @@ type attempt struct {
}
type settings struct {
Internet string `json:"internet"`
AllowedCIDRs []string `json:"allowed_cidrs,omitempty"`
Duration int `json:"duration_seconds"`
Privilege string `json:"privilege"`
GrubPaths []string `json:"grub_paths,omitempty"`
@@ -59,6 +60,9 @@ func Run(ctx context.Context, db *pgxpool.Pool, artifactRoot, configPath string)
if _, err = db.Exec(ctx, "UPDATE bindings SET configured=false,reason='Isolation proof expired or requires revalidation' WHERE configured AND NOT COALESCE(isolation_expires_at>now(),false)"); err != nil {
return err
}
if _, err = db.Exec(ctx, "UPDATE bindings SET online_ready=false,online_reason='Online isolation proof expired or requires revalidation' WHERE online_ready AND NOT COALESCE(online_expires_at>now(),false)"); err != nil {
return err
}
if len(cfg.Owners) == 0 {
blockers = append(blockers, "No file-backed owner bindings configured")
}
+20
View File
@@ -0,0 +1,20 @@
{
"listen_host": "192.0.2.10",
"listen_port": 8445,
"ca_file": "/etc/otche-network/client-ca.pem",
"certificate_file": "/etc/otche-network/server.pem",
"key_file": "/etc/otche-network/server.key",
"node": "pve-example",
"uplink_bridge": "vmbr-example",
"wan_mac": "02:0c:7e:00:00:01",
"sandbox_cidr": "100.96.0.0/16",
"protected_cidrs": ["192.0.2.10/32", "192.0.2.1/32", "203.0.113.10/32"],
"local_cidrs": ["192.0.2.0/24"],
"protected_vmids": [7000, 7001],
"owners": {
"00000000-0000-4000-8000-000000000001": {
"pool": "otche-example-owner",
"client_cn": "otche-example-worker"
}
}
}
+94
View File
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Fixed dhclient hook: configure ONLY otwan inside otche-egress.
No default dhclient hooks, DNS writes, shell, host route changes, classless routes,
NTP hooks or remotely supplied executables. A changed/lost WAN lease atomically
revokes all guest ports BEFORE changing network state. The broker then refuses
renewal until operator restart/reconciliation.
"""
import ipaddress
import json
import os
from pathlib import Path
import stat
import subprocess
import sys
import tempfile
NS = 'otche-egress'
WAN = 'otwan'
STATE = Path('/var/lib/otche-network')
def run(argv, text=None):
result = subprocess.run(argv, input=text, text=True, stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE, timeout=10, check=False,
env={'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C'})
if result.returncode:
raise RuntimeError('DHCP hook system command failed')
def main():
if os.geteuid() != 0 or os.environ.get('interface') != WAN:
raise RuntimeError('unexpected DHCP execution context')
if os.stat('/proc/self/ns/net').st_ino != os.stat('/var/run/netns/' + NS).st_ino:
raise RuntimeError('DHCP hook is not in broker namespace')
info = STATE.lstat()
if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o077:
raise RuntimeError('unsafe DHCP state directory')
reason = os.environ.get('reason', '')
if reason in ('PREINIT', 'MEDIUM', 'ARPCHECK', 'ARPSEND'):
return
if reason in ('EXPIRE', 'FAIL', 'RELEASE', 'STOP', 'TIMEOUT'):
run(['/usr/sbin/nft', '-f', '-'], 'flush set inet otche_filter active\n')
run(['/usr/sbin/ip', '-4', 'route', 'flush', 'dev', WAN])
run(['/usr/sbin/ip', '-4', 'address', 'flush', 'dev', WAN])
return
if reason not in ('BOUND', 'RENEW', 'REBIND', 'REBOOT'):
raise RuntimeError('unsupported DHCP reason')
address = ipaddress.IPv4Address(os.environ['new_ip_address'])
mask = os.environ['new_subnet_mask']
network = ipaddress.IPv4Network(str(address) + '/' + mask, strict=False)
routers = os.environ.get('new_routers', '').split()
if len(routers) != 1:
raise RuntimeError('exactly one DHCP router required')
gateway = ipaddress.IPv4Address(routers[0])
if network.prefixlen == 0 or gateway not in network or address in (network.network_address, network.broadcast_address) or gateway == address:
raise RuntimeError('invalid DHCP WAN network')
lease = {'address': str(address) + '/' + str(network.prefixlen), 'gateway': str(gateway)}
file = STATE / 'wan.json'
previous = None
if file.exists():
info = file.lstat()
if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o077:
raise RuntimeError('unsafe DHCP lease file')
previous = json.loads(file.read_text())
if previous != lease:
run(['/usr/sbin/nft', '-f', '-'], 'flush set inet otche_filter active\n')
# Calls run in the verified namespace; never use dhclient-script or its hooks.
run(['/usr/sbin/ip', '-4', 'address', 'replace', lease['address'], 'dev', WAN])
run(['/usr/sbin/ip', '-4', 'route', 'replace', 'default', 'via', lease['gateway'], 'dev', WAN])
fd, name = tempfile.mkstemp(prefix='.wan-', dir=STATE)
try:
os.fchmod(fd, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(lease, stream, separators=(',', ':'))
stream.flush()
os.fsync(stream.fileno())
os.replace(name, file)
directory = os.open(STATE, os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
finally:
if os.path.exists(name):
os.unlink(name)
if __name__ == '__main__':
try:
main()
except Exception as exc:
print('otche DHCP hook refused: ' + str(exc)[:180], file=sys.stderr)
sys.exit(1)
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
[Unit]
Description=Otche per-clone IPv4 network policy broker
After=network-online.target pve-cluster.service
Wants=network-online.target
Requires=pve-cluster.service
[Service]
Type=simple
User=root
Group=root
UMask=0077
StateDirectory=otche-network
StateDirectoryMode=0700
ExecStart=/usr/bin/python3 /opt/otche-workspace/otche-backend/provisioning/otche-network.py --config /etc/otche-network.json
Restart=on-failure
RestartSec=5s
TimeoutStartSec=90s
TimeoutStopSec=20s
KillMode=control-group
NoNewPrivileges=true
# Network/mount namespaces and /proc/sys writes are intrinsic to this broker.
# Do NOT add PrivateNetwork, PrivateMounts, ProtectKernelTunables or a syscall
# filter denying setns/unshare/mount; ip-netns must remain visible to PVE/root.
RestrictAddressFamilies=AF_UNIX AF_INET AF_NETLINK AF_PACKET
LimitNOFILE=1024
TasksMax=512
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target
+1 -2
View File
@@ -6,8 +6,7 @@
"owner_id": "11111111-1111-4111-8111-111111111111",
"seal_path": "/var/lib/otche/source-seals/win11.json",
"cd_slot": "ide2",
"max_disk_bytes": 108447924224,
"allowed_bridges": []
"max_disk_bytes": 108447924224
}
},
"owners": {
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Pure gateway regressions: python3 -m unittest discover -s provisioning -p test_network_gateway.py.
No PVE, root, nft, network interfaces, certificates or subprocesses required.
Main additionally qualifies generated rules with real Linux packet probes.
"""
import copy
import hashlib
import importlib.util
import ipaddress
import json
from pathlib import Path
import ssl
import unittest
from unittest.mock import patch
SPEC = importlib.util.spec_from_file_location('otche_network', Path(__file__).with_name('otche-network.py'))
gateway = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(gateway)
CONFIG = gateway.validate_config(json.loads(Path(__file__).with_name('network-gateway.example.json').read_text()))
OWNER = next(iter(CONFIG['owners']))
def request(vmid=900001, policy=None):
return {'owner_id': OWNER, 'attempt_id': '00000000-0000-4000-8000-000000000003',
'node': CONFIG['node'], 'vmid': vmid, 'lease_id': '00000000-0000-4000-8000-000000000004',
'allowed_cidrs': policy or ['1.1.1.1/32']}
def record(vmid=900001, policy=None):
value = gateway.make_record(request(vmid, policy), ipaddress.IPv4Network('100.96.0.0/30'))
value.update(phase='ready', dns_ipv4=['1.1.1.1'])
return value
class DestinationTests(unittest.TestCase):
def test_wildcard_keeps_explicit_local_authorization(self):
entries = gateway.normalize([' 0.0.0.0 ', '192.168.5.123/24', '192.168.5.0/24', '1.1.1.1'])
self.assertEqual(entries, ['0.0.0.0/0', '192.168.5.0/24', '1.1.1.1/32'])
self.assertEqual(gateway.policy_digest(entries), hashlib.sha256(('\n'.join(entries) + '\n').encode()).hexdigest())
protected = gateway.networks(['192.168.5.1/32', '100.96.0.0/16', '8.8.8.8/32'])
local = gateway.networks(['9.1.0.0/16'])
allow = lambda ip: gateway.effective_allows(entries, ip, protected, local)
self.assertTrue(allow('192.168.5.20'))
self.assertTrue(allow('1.1.1.1'))
for ip in ('192.168.5.1', '192.168.6.1', '100.96.0.2', '8.8.8.8', '9.1.1.1', '127.0.0.1', '169.254.1.2'):
with self.subTest(ip=ip):
self.assertFalse(allow(ip))
def test_finite_list_does_not_imply_dns_or_other_public_addresses(self):
entries = gateway.normalize(['8.8.4.4'])
self.assertTrue(gateway.effective_allows(entries, '8.8.4.4', [], []))
self.assertFalse(gateway.effective_allows(entries, '1.1.1.1', [], []))
self.assertFalse(gateway.effective_allows(entries, '8.8.8.8', [], []))
def test_rejects_mixed_ranges_and_special_prefixes(self):
for entry in ('::/0', 'localhost', '1.1.1.1-1.1.1.9', '127.0.0.1', '169.254.0.0/16',
'224.0.0.0/4', '240.0.0.0/4', '0.0.0.0/8', '8.0.0.0/6', '100.0.0.0/8',
'192.168.1.1/255.255.255.0', '1.2.3.256', ''):
with self.subTest(entry=entry), self.assertRaises(gateway.Refused):
gateway.normalize([entry])
self.assertEqual(gateway.normalize(['100.64.0.0/10', '198.18.0.0/15']), ['100.64.0.0/10', '198.18.0.0/15'])
def test_list_and_body_boundaries(self):
for values in ([], ['1.1.1.1'] * 129, [1], [' ' * 8193]):
with self.subTest(values=str(values)[:30]), self.assertRaises(gateway.Refused):
gateway.normalize(values)
with self.assertRaises(gateway.Refused):
gateway.strict_json('{"vmid":100,"vmid":101}')
with self.assertRaises(gateway.Refused):
gateway.strict_json('{"vmid":NaN}')
class IdentityTests(unittest.TestCase):
def test_owner_and_command_injection_rejected(self):
for field, value in (('vmid', True), ('vmid', 7001), ('owner_id', 'another-owner'),
('attempt_id', 'x; reboot'), ('node', 'pve-example/../other')):
raw = request()
raw[field] = value
with self.subTest(field=field), self.assertRaises(gateway.Refused):
gateway.validate_request(raw, CONFIG, OWNER)
raw = request()
raw['bridge'] = 'vmbr0'
with self.assertRaises(gateway.Refused):
gateway.validate_request(raw, CONFIG, OWNER)
def test_client_cn_maps_exactly_one_owner(self):
cert = {'subject': ((('commonName', CONFIG['owners'][OWNER]['client_cn']),),)}
self.assertEqual(gateway.certificate_owner(cert, CONFIG), OWNER)
for invalid in ({}, {'subject': ((('commonName', 'unknown'),),)},
{'subject': cert['subject'] + cert['subject']}):
with self.assertRaises(gateway.Refused):
gateway.certificate_owner(invalid, CONFIG)
c = copy.deepcopy(CONFIG)
c['owners']['00000000-0000-4000-8000-000000000005'] = copy.deepcopy(c['owners'][OWNER])
with self.assertRaises(gateway.Refused):
gateway.validate_config(c)
def test_tls_requires_peer_certificate_and_tls12(self):
with patch.object(ssl.SSLContext, 'load_verify_locations'), \
patch.object(ssl.SSLContext, 'load_cert_chain'):
actual = gateway.tls_context(CONFIG)
self.assertEqual(actual.verify_mode, ssl.CERT_REQUIRED)
self.assertEqual(actual.minimum_version, ssl.TLSVersion.TLSv1_2)
def test_nic_rejects_vlan_second_model_and_extra_options(self):
r = record()
valid = f'virtio={r["mac"]},bridge={r["bridge"]},firewall=1'
self.assertTrue(gateway.nic_matches(valid, r))
for text in (valid + ',tag=20', valid + ',trunks=1-4094', valid.replace('firewall=1', 'firewall=0'),
valid.replace(r['bridge'], 'vmbr0'), valid + ',virtio=' + r['mac']):
self.assertFalse(gateway.nic_matches(text, r))
def test_vm_reuse_cannot_release_old_or_other_lease(self):
b = gateway.Broker(CONFIG)
r = record()
b.state = {'records': {'900001': r}}
wrong = request()
wrong['lease_id'] = '00000000-0000-4000-8000-000000000006'
with patch.object(gateway, 'command', side_effect=AssertionError('unexpected system mutation')):
with self.assertRaises(gateway.Refused):
b.release(wrong)
self.assertEqual(b.release(request(900002)), {'released': True})
def test_restart_or_expiry_cannot_reauthorize(self):
b = gateway.Broker(CONFIG)
r = record()
for phase, deadline in (('ready', 0), ('revoked', 200), ('intent', 200)):
r['phase'] = phase
b.deadlines['900001'] = deadline
with patch.object(gateway.time, 'monotonic', return_value=100), self.assertRaises(gateway.Refused):
b.require_live('900001', r)
def test_saved_record_resource_collision_is_rejected(self):
b = gateway.Broker(CONFIG)
r = record()
b.state = {'records': {'900001': r}}
b.validate_state()
r['bridge'] = 'vmbr0'
with self.assertRaises(gateway.Refused):
b.validate_state()
class KernelContractTests(unittest.TestCase):
def test_integrity_ignores_live_counters_but_not_policy_or_spoof_rules(self):
original = {'nftables': [
{'set': {'family': 'inet', 'table': 'otche_filter', 'name': 'active', 'flags': ['timeout'],
'elem': [{'elem': {'val': 'otl123', 'timeout': 45000, 'expires': 33000}}]}},
{'chain': {'name': 'forward', 'policy': 'drop', 'handle': 2}},
{'rule': {'handle': 3, 'expr': [{'counter': {'packets': 1, 'bytes': 64}}, {'drop': None}]}}]}
changed = copy.deepcopy(original)
changed['nftables'][0]['set']['elem'] = []
changed['nftables'][2]['rule']['expr'][0]['counter']['packets'] = 99
self.assertEqual(gateway.semantic_ruleset(original), gateway.semantic_ruleset(changed))
changed['nftables'][1]['chain']['policy'] = 'accept'
self.assertNotEqual(gateway.semantic_ruleset(original), gateway.semantic_ruleset(changed))
self.assertEqual(gateway.active_ports(original), {'otl123'})
self.assertEqual(gateway.active_ports(changed), set())
def test_rules_keep_both_destination_gates_and_ttl_before_established(self):
r = record(policy=['0.0.0.0/0', '192.168.5.0/24'])
rules = gateway.rules_namespace(CONFIG, [r], gateway.networks(['100.96.0.0/16']), 'test')
# Assertions concern the emitted firewall program, not broker source.
prerouting = rules.split(' chain prerouting {', 1)[1].split(' chain input {', 1)[0]
forward = rules.split(' chain forward {', 1)[1].split(' chain postrouting {', 1)[0]
self.assertIn('policy drop;', prerouting)
self.assertNotIn(' return', prerouting)
self.assertIn('jump p' + r['lan'][3:] + 'd', prerouting)
self.assertIn('jump p' + r['lan'][3:] + 'd', forward)
self.assertLess(forward.index('oifname != @active counter drop'), forward.index('ct state established,related accept'))
self.assertLess(forward.index('jump p' + r['lan'][3:] + 's'), forward.index('ct state established,related accept'))
self.assertIn('ether saddr != ' + r['mac'] + ' counter drop', rules)
self.assertIn('ether type != { ip, arp } counter drop', rules)
self.assertIn('meta l4proto != { tcp, udp, icmp } counter drop', forward)
def test_host_input_guard_covers_pve_firewall_bridge_without_touching_sources(self):
rules = gateway.rules_bridge([record()], 'test')
input_chain = rules.split(' chain input {', 1)[1].split(' chain output {', 1)[0]
self.assertIn('fwbr900001i0', input_chain)
self.assertIn(record()['bridge'], input_chain)
self.assertNotIn('fwbr7000', rules)
self.assertNotIn('flush ruleset', rules)
self.assertIn('ether saddr != ' + record()['mac'] + ' counter drop', rules)
def test_rebuild_preserves_unrelated_lease_absolute_deadline(self):
b = gateway.Broker(CONFIG)
r1, r2 = record(), record(900002)
b.state = {'records': {'900001': r1, '900002': r2}}
b.deadlines = {'900001': 105, '900002': 140}
emitted = []
with patch.object(gateway.time, 'monotonic', return_value=100), patch.object(b, 'nft', side_effect=emitted.append):
b.refresh_active()
self.assertIn('"' + r1['lan'] + '" timeout 5000ms', emitted[0])
self.assertIn('"' + r2['lan'] + '" timeout 40000ms', emitted[0])
self.assertEqual(b.deadlines, {'900001': 105, '900002': 140})
if __name__ == '__main__':
unittest.main()