Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-forge/blob/main/research/tests/decode.sh # interplane-forge INTERPLANE Forge Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `interplane-forge / research / tests / decode.sh` 400 lines ยท 20633 bytes Raw Blame History 1 #!/bin/sh 2 # Offline host containment test. Compiles an independent synthetic adversary, not 3 # product code. The real normal and expansion PDFs are public-domain fixtures 4 # generated for this test: Courier text, Flate stream and exact xref offsets. 5 # Expansion: 2100 pages reuse a compressed 5000-character stream. No network, 6 # node, model, credential, unit file or persistent manager setting is used. 7 set -eu 8 cd "$(dirname "$0")/../.." 9 export LC_ALL=C 10 umask 077 11 T=$(mktemp -d) 12 fixture_unit=; fixture_invocation=; fixture_pid= 13 stop_fixture() { 14 # Even fixture teardown must not mistake an unrelated unit for our own. 15 [ -n "$fixture_invocation" ] || return 0 16 current=$(systemctl --user show "$fixture_unit" -p InvocationID --value 2>/dev/null || :) 17 if [ "$current" = "$fixture_invocation" ]; then systemctl --user stop "$fixture_unit" >/dev/null 2>&1 || :; fi 18 if [ -n "$fixture_pid" ]; then wait "$fixture_pid" 2>/dev/null || :; fi 19 fixture_unit=; fixture_invocation=; fixture_pid= 20 } 21 trap 'stop_fixture; rm -rf "$T"' EXIT 22 trap 'exit 1' HUP INT TERM 23 pass=0; fail=0 24 ok() { pass=$((pass+1)); echo "PASS decode $*"; } 25 bad() { fail=$((fail+1)); echo "FAIL decode $*"; } 26 for tool in cc python3 systemctl systemd-run journalctl bwrap pdftotext; do 27 command -v "$tool" >/dev/null || { echo "BLOCKED decode missing $tool"; exit 1; } 28 done 29 # Every call uses a distinct wrapper-owned unit. Record only this test's units; 30 # never stop or assert about another concurrently running extraction. 31 observe() { 32 log=$1; pid=$2; evidence=$3; name=$4 33 released=0; baseline=; baseline_kill= 34 while kill -0 "$pid" 2>/dev/null; do 35 unit=$(sed -n 's/^research decode: scope=\([^ ]*\).*/\1/p' "$log" | head -n1) 36 if [ -n "$unit" ]; then 37 cg=$(systemctl --user show "$unit" -p ControlGroup --value 2>/dev/null || :) 38 case "$cg" in 39 /user.slice/*) 40 if [ "$name" = memory ] && [ -r "/sys/fs/cgroup$cg/memory.events" ]; then 41 events=/sys/fs/cgroup$cg/memory.events 42 if [ "$released" = 0 ]; then 43 # Arm the oracle before the adversary may allocate. This gate is 44 # a read-only test mount, never a writable host sandbox path. 45 baseline=$(awk '$1=="oom" {print $2}' "$events") 46 baseline_kill=$(awk '$1=="oom_kill" {print $2}' "$events") 47 printf '1' > "$T/gate" 48 released=1 49 else 50 current=$(awk '$1=="oom" {print $2}' "$events" 2>/dev/null || :) 51 current_kill=$(awk '$1=="oom_kill" {print $2}' "$events" 2>/dev/null || :) 52 if [ -n "$current" ] && [ -n "$current_kill" ] && 53 [ "$current" -gt "$baseline" ] && [ "$current_kill" -gt "$baseline_kill" ]; then 54 printf 'KERNEL_OOM before=%s after=%s kill_before=%s kill_after=%s\n' \ 55 "$baseline" "$current" "$baseline_kill" "$current_kill" >> "$evidence" 56 # Parent fixture holds the cgroup alive until the independent 57 # host observer has read actual kernel oom AND oom_kill deltas. 58 printf '2' > "$T/gate" 59 fi 60 fi 61 fi 62 for field in memory.peak memory.events pids.peak pids.events; do 63 if [ -r "/sys/fs/cgroup$cg/$field" ]; then 64 { printf '%s ' "$field"; tr '\n' ';' < "/sys/fs/cgroup$cg/$field"; echo; } >> "$evidence" 2>/dev/null || : 65 fi 66 done ;; 67 esac 68 systemctl --user show "$unit" -p MemoryPeak -p MemoryMax -p MemorySwapMax -p TasksMax -p KillMode >> "$evidence" 2>/dev/null || : 69 fi 70 sleep 0.1 71 done 72 } 73 run() { 74 wrapper=$1; input=$2; name=$3 75 : > "$T/$name.evidence" 76 if [ "$name" = memory ]; then printf '0' > "$T/gate"; else printf '2' > "$T/gate"; fi 77 sh "$wrapper" "$input" "$T/$name.text" > "$T/$name.stdout" 2> "$T/$name.log" & 78 pid=$! 79 observe "$T/$name.log" "$pid" "$T/$name.evidence" "$name" & observer=$! 80 rc=0; wait "$pid" || rc=$? 81 wait "$observer" || : 82 printf '%s\n' "$rc" > "$T/$name.rc" 83 unit=$(sed -n 's/^research decode: scope=\([^ ]*\).*/\1/p' "$T/$name.log" | head -n1) 84 if [ "$name" = memory ] && [ -n "$unit" ]; then 85 # DefaultOOMPolicy=stop terminates the whole scope with SIGTERM (143), 86 # including any fixture-side reporter. Cgroup counters may disappear before 87 # a sampler runs. The manager's authenticated structured kernel-OOM receipt 88 # survives --collect. Never accept a decoder string or an exit code instead. 89 n=0 90 while :; do 91 journalctl --user --unit="$unit" --no-pager -o json > "$T/$name.journal" 92 if python3 -I - "$T/$name.journal" "$unit" > "$T/$name.receipt" <<'RECEIPT' 93 import json,os,sys 94 rows=[json.loads(line) for line in open(sys.argv[1]) if line.strip()] 95 rows=[r for r in rows if r.get('USER_UNIT')==sys.argv[2] 96 and r.get('_EXE')=='/usr/lib/systemd/systemd' 97 and r.get('_UID')==str(os.getuid()) and r.get('_TRANSPORT')=='journal'] 98 oom={r.get('USER_INVOCATION_ID') for r in rows 99 if r.get('MESSAGE_ID')=='`fe6faa94e7774663a0da52717891d8ef`' 100 and r.get('CODE_FUNC')=='unit_check_oom'} 101 failed={r.get('USER_INVOCATION_ID') for r in rows 102 if r.get('MESSAGE_ID')=='`d9b373ed55a64feb8242e02dbe79a49c`' 103 and r.get('CODE_FUNC')=='unit_log_failure' and r.get('UNIT_RESULT')=='oom-kill'} 104 invocations=(oom & failed)-{None,''} 105 if len(invocations)!=1: sys.exit(1) 106 print('KERNEL_OOM_RECEIPT unit='+sys.argv[2]+' invocation='+next(iter(invocations))+ 107 ' result=oom-kill source=systemd-unit_check_oom') 108 RECEIPT 109 then cat "$T/$name.receipt" >> "$T/$name.evidence"; break; fi 110 n=$((n+1)); [ "$n" -lt 30 ] || break 111 sleep 0.1 112 done 113 fi 114 if [ -n "$unit" ]; then 115 # Manager GC can lag briefly, but an active descendant is never acceptable. 116 n=0 117 while :; do 118 if ! systemctl --user list-units --type=scope --all --no-legend --plain "$unit" > "$T/$name.units"; then 119 bad "$name cannot enumerate leftover scope"; break 120 fi 121 [ ! -s "$T/$name.units" ] && break 122 n=$((n+1)); [ "$n" -lt 30 ] || { bad "$name leftover scope $unit"; cat "$T/$name.units"; break; } 123 sleep 0.1 124 done 125 fi 126 if find "$T" -maxdepth 1 -name '.interplane-research-pdf.*' | grep -q .; then bad "$name staging directory left behind"; fi 127 # Resource observations are measurements, not predicted limits. Manager/kernel 128 # versions without a peak field are explicitly labelled, not filled in. 129 if grep -qE 'memory.peak |MemoryPeak=[0-9]+' "$T/$name.evidence"; then 130 echo "OBSERVED decode $name $(grep -E 'memory.peak |MemoryPeak=[0-9]+' "$T/$name.evidence" | tail -n1)" 131 else echo "NOT_EXPOSED decode $name peak memory"; fi 132 if [ "$name" = memory ]; then grep '^KERNEL_OOM_RECEIPT ' "$T/$name.evidence" | tail -n1 || :; fi 133 } 134 refused() { 135 name=$1; reason=$2 136 if [ "$(cat "$T/$name.rc")" != 0 ] && [ ! -e "$T/$name.text" ] && grep -qE "$reason" "$T/$name.log"; then 137 ok "$name rejects for $reason without installed text" 138 else bad "$name refusal oracle"; cat "$T/$name.log"; fi 139 } 140 run research/decode.sh research/tests/fixtures/decode-normal.pdf normal 141 if [ "$(cat "$T/normal.rc")" != 0 ]; then 142 cat "$T/normal.log" 143 echo 'BLOCKED decode normal real PDF failed; scope/property errors above are not bypassed' 144 exit 1 145 fi 146 grep -q 'Interplane PDF containment normal fixture' "$T/normal.text" && ok 'real normal PDF extracted' || bad 'real normal PDF text' 147 printf '%%PDF-malformed\n' > "$T/malformed.pdf" 148 run research/decode.sh "$T/malformed.pdf" malformed 149 refused malformed 'decoder/scope failed' 150 run research/decode.sh research/tests/fixtures/decode-expansion.pdf expansion 151 refused expansion 'output limit exceeded|decoder/scope failed status=(137|9)' 152 # The compiled adversary replaces only pdftotext in a private COPY of the actual 153 # wrapper. It is mounted read-only over that binary inside the same bwrap/scope; 154 # production decode.sh has no decoder path override or bypass environment knob. 155 cat > "$T/adversary.c" <<'C' 156 #define _GNU_SOURCE 157 #include 158 #include 159 #include 160 #include 161 #include 162 #include 163 #include 164 #include 165 #include 166 #include 167 extern char **environ; 168 static int emit(size_t n) { 169 char bytes[4096]; memset(bytes, 'X', sizeof bytes); 170 while(n) { size_t want=n=target)return 1; 179 usleep(10000); 180 } 181 return 0; 182 } 183 static void ram(void) { 184 // Raising our own score requires no privilege. The allocating children, not 185 // bwrap/timeout/fixture parent, must be the OOM victims so evidence survives. 186 int score=open("/proc/self/oom_score_adj",O_WRONLY); 187 if(score<0||write(score,"1000",4)!=4)_exit(78); 188 close(score); 189 size_t n=80u*1024u*1024u; 190 volatile char *p=malloc(n); if(!p)_exit(77); 191 for(size_t i=0;i0) { if(WIFSIGNALED(st)&&WTERMSIG(st)==SIGKILL)oom=1; else if(!WIFEXITED(st)||WEXITSTATUS(st))return 25; } 203 if(!gate('2'))return 80; 204 if(oom){fputs("OOM_SIGNAL\n",stderr);return 137;} 205 return emit(1); 206 } 207 if(!strncmp(mode,"tasks",5)) { 208 pid_t children[32]; int n=0,limited=0; 209 while(n<32){pid_t p=fork();if(p<0){limited=errno==EAGAIN;break;}if(!p){sleep(5);_exit(0);}children[n++]=p;} 210 sleep(1); 211 for(int i=0;i0){} 213 if(limited){fputs("TASKS_LIMIT\n",stderr);return 42;} 214 return emit(1); 215 } 216 if(!strncmp(mode,"timeout",7)){sleep(60);return 0;} 217 if(!strncmp(mode,"failure",7)){emit(100);return 23;} 218 if(!strncmp(mode,"overflow",8))return emit(`8388608`); 219 if(!strncmp(mode,"boundary",8))return emit(`8388607`); 220 if(!strncmp(mode,"empty",5))return 0; 221 if(!strncmp(mode,"sandbox",7)){ 222 for(char **e=environ;*e;e++)if(strncmp(*e,"PATH=",5)&&strncmp(*e,"LC_ALL=",7)&&strcmp(*e,"PWD=/"))return 31; 223 fd=open("/usr/bin/pdftotext",O_WRONLY);if(fd>=0)return 32; 224 fd=open("/paper.pdf",O_WRONLY);if(fd>=0)return 33; 225 if(access("/run/user",F_OK)==0||access("/root",F_OK)==0)return 34; 226 return emit(1); 227 } 228 return 26; 229 } 230 C 231 cc -O2 -Wall -Wextra -Werror "$T/adversary.c" -o "$T/adversary" 232 # The launch shim is INSIDE the unchanged aggregate-limited scope. Only test 233 # fixtures see the gate; production decode.sh remains untouched. 234 cat > "$T/stage.sh" < "$T/$mode.input" 264 run "$T/controlled.sh" "$T/$mode.input" "$mode" 265 done 266 [ "$(cat "$T/sandbox.rc")" = 0 ] && ok 'sandbox read-only files and clean environment' || { bad 'sandbox boundary'; cat "$T/sandbox.log"; } 267 [ "$(cat "$T/boundary.rc")" = 0 ] && [ "$(wc -c < "$T/boundary.text")" = `8388607` ] && ok 'exact output boundary installs all bytes' || bad 'exact output boundary' 268 refused overflow 'output limit exceeded .*staged_bytes=`8388607`' 269 refused failure 'decoder/scope failed status=23' 270 refused empty 'decoder produced no text' 271 if [ "$(cat "$T/memory.rc")" != 0 ] && [ ! -e "$T/memory.text" ] && 272 grep -q '^KERNEL_OOM_RECEIPT ' "$T/memory.evidence"; then 273 ok 'memory rejected with authenticated kernel aggregate OOM receipt' 274 else bad 'memory kernel OOM oracle'; cat "$T/memory.log"; fi 275 refused tasks 'TASKS_LIMIT' 276 refused timeout 'decoder/scope failed status=124' 277 run "$T/no-manager.sh" "$T/sandbox.input" no-manager 278 refused no-manager 'user scope unavailable' 279 # The SAME resource oracle must reject the unbounded execution specifically for 280 # successful over-limit work. An error (including compilation/namespace errors) 281 # is a failed negative control, never containment evidence. 282 resource_oracle() { 283 name=$1 284 if [ "$(cat "$T/$name.rc")" = 0 ] && [ -s "$T/$name.text" ]; then echo UNBOUNDED; return 1; fi 285 if [ ! -e "$T/$name.text" ]; then 286 case "$name" in 287 memory) if grep -q '^KERNEL_OOM_RECEIPT ' "$T/$name.evidence"; then echo CONTAINED; return 0; fi ;; 288 tasks) if grep -q TASKS_LIMIT "$T/$name.log"; then echo CONTAINED; return 0; fi ;; 289 esac 290 fi 291 echo INVALID; return 2 292 } 293 for mode in memory tasks; do 294 got=$(resource_oracle "$mode") || { bad "$mode aggregate resource oracle invalid: $got"; continue; } 295 [ "$got" = CONTAINED ] || bad "$mode containment result" 296 run "$T/unbounded.sh" "$T/$mode.input" "unbounded-$mode" 297 neg=0; got=$(resource_oracle "unbounded-$mode") || neg=$? 298 [ "$neg" = 1 ] && [ "$got" = UNBOUNDED ] && ok "NEG removed scope is specifically UNBOUNDED for $mode" || { bad "NEG scope removal invalid: rc=$neg result=$got"; cat "$T/unbounded-$mode.log"; } 299 done 300 # Force an actual creation collision in a private source copy, not via any 301 # production override or preflight is-active check. The only preexisting unit 302 # touched here is this test's own fresh transient scope; no existing service or 303 # unit property is changed. The fixture has no public/metadata/input paths. 304 fixture_snapshot() { 305 systemctl --user show "$fixture_unit" \ 306 -p Id -p Description -p InvocationID -p ControlGroup -p ActiveState \ 307 -p MemoryMax -p MemorySwapMax -p TasksMax -p KillMode 308 } 309 start_fixture() { 310 fixture_nonce=$(cat /proc/sys/kernel/random/uuid) 311 fixture_unit=interplane-research-pdf-test-$fixture_nonce.scope 312 systemd-run --user --scope --collect --quiet --unit="$fixture_unit" \ 313 --description="interplane decoder collision fixture $fixture_nonce" \ 314 /bin/sh -c 'printf "%s\n" "$$" > "$1"; exec /usr/bin/sleep 120' fixture "$T/fixture.pid" \ 315 > "$T/fixture.stdout" 2> "$T/fixture.log" & 316 fixture_pid=$! 317 n=0 318 while :; do 319 candidate=$(systemctl --user show "$fixture_unit" -p InvocationID --value 2>/dev/null || :) 320 if [ -n "$candidate" ] && [ -s "$T/fixture.pid" ] && 321 [ "$(cat "$T/fixture.pid")" = "$fixture_pid" ] && 322 [ "$(systemctl --user show "$fixture_unit" -p Description --value)" = "interplane decoder collision fixture $fixture_nonce" ] && 323 [ "$(sed -n 's/^0:://p' "/proc/$fixture_pid/cgroup")" = "$(systemctl --user show "$fixture_unit" -p ControlGroup --value)" ] && 324 systemctl --user is-active --quiet "$fixture_unit"; then fixture_invocation=$candidate; break; fi 325 n=$((n+1)); [ "$n" -lt 100 ] || { cat "$T/fixture.log"; bad 'fixture creation failed'; return 1; } 326 sleep 0.1 327 done 328 fixture_snapshot > "$T/fixture.before" 329 } 330 # Same oracle for the real wrapper and unconditional-cleanup mutant. In 331 # particular launch errors cannot masquerade as the caught collateral stop. 332 collision_oracle() { 333 if ! kill -0 "$fixture_pid" 2>/dev/null || ! systemctl --user is-active --quiet "$fixture_unit"; then 334 echo COLLATERAL_STOP; return 1 335 fi 336 fixture_snapshot > "$T/fixture.after" 337 if ! cmp -s "$T/fixture.before" "$T/fixture.after"; then echo CHANGED_IDENTITY_OR_PROPERTIES; return 2; fi 338 if [ "$collision_rc" = 0 ] || [ -e "$T/collision.text" ] || [ -s "$T/stop.calls" ] || 339 find "$T" -maxdepth 1 -name '.interplane-research-pdf.*' | grep -q .; then echo INVALID_REFUSAL; return 2; fi 340 case "$collision_mode" in 341 source-failure) reason='injected source preparation failure' ;; 342 *) reason='was not proven created by this invocation' ;; 343 esac 344 if ! grep -q "$reason" "$T/collision.log"; then echo WRONG_REFUSAL; return 2; fi 345 echo PRESERVED 346 } 347 for collision_mode in collision source-failure unconditional-cleanup; do 348 rm -f "$T/fixture.pid" "$T/collision.text" "$T/stop.calls" 349 start_fixture || exit 1 350 python3 -I - "$T" "$fixture_unit" "$collision_mode" <<'OWNERSHIP' 351 import pathlib,sys 352 p=pathlib.Path(sys.argv[1]); unit=sys.argv[2]; mode=sys.argv[3] 353 s=pathlib.Path('research/decode.sh').read_text() 354 needle='unit=interplane-research-pdf-${work##*.}.scope' 355 assert s.count(needle)==1 356 s=s.replace(needle,'unit='+unit) 357 # Log every attempted stop, then execute the real manager client. The shim is 358 # private and only substitutes this call in the source copy; not PATH injection. 359 stop='/usr/bin/systemctl --user stop "$unit"' 360 assert s.count(stop)==1 361 shim=p/'stop.sh' 362 shim.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> "'+str(p/'stop.calls')+'"\nexec /usr/bin/systemctl "$@"\n') 363 s=s.replace(stop,'/bin/sh "'+str(shim)+'" --user stop "$unit"') 364 if mode=='source-failure': 365 needle='mkfifo "$work/stdout" "$work/stderr" "$work/claim" "$work/release"' 366 assert s.count(needle)==1 367 s=s.replace(needle,"refuse 'injected source preparation failure'\n"+needle) 368 if mode=='unconditional-cleanup': 369 needle=' owns_scope || return 0\n' 370 assert s.count(needle)==1 371 s=s.replace(needle,'') 372 (p/'collision.sh').write_text(s) 373 OWNERSHIP 374 collision_rc=0 375 sh "$T/collision.sh" research/tests/fixtures/decode-normal.pdf "$T/collision.text" \ 376 > "$T/collision.stdout" 2> "$T/collision.log" || collision_rc=$? 377 oracle_rc=0; got=$(collision_oracle) || oracle_rc=$? 378 if [ "$collision_mode" = unconditional-cleanup ]; then 379 if [ "$oracle_rc" = 1 ] && [ "$got" = COLLATERAL_STOP ] && [ -s "$T/stop.calls" ] && 380 [ "$collision_rc" != 0 ] && [ ! -e "$T/collision.text" ] && 381 grep -q 'was not proven created by this invocation' "$T/collision.log"; then 382 ok 'NEG unconditional cleanup caught specifically for stopping collision fixture' 383 else bad "NEG collision cleanup oracle rc=$oracle_rc result=$got"; cat "$T/collision.log"; fi 384 else 385 if [ "$oracle_rc" = 0 ] && [ "$got" = PRESERVED ]; then 386 ok "$collision_mode refuses without output/manager stop; same fixture PID, invocation and properties preserved" 387 else bad "$collision_mode ownership oracle rc=$oracle_rc result=$got"; cat "$T/collision.log"; fi 388 fi 389 stop_fixture 390 done 391 # Atomic non-overwrite and symlink refusal, including a dangling destination. 392 printf 'preserve\n' > "$T/existing" 393 if sh research/decode.sh research/tests/fixtures/decode-normal.pdf "$T/existing" 2> "$T/existing.log"; then bad 'existing destination overwritten'; 394 else [ "$(cat "$T/existing")" = preserve ] && ok 'existing destination preserved' || bad 'existing destination changed'; fi 395 ln -s "$T/missing" "$T/link" 396 if sh research/decode.sh research/tests/fixtures/decode-normal.pdf "$T/link" 2> "$T/link.log"; then bad 'dangling output symlink accepted'; else [ ! -e "$T/missing" ] && ok 'dangling destination rejected' || bad 'symlink target written'; fi 397 ln -s "$T/malformed.pdf" "$T/input-link" 398 if sh research/decode.sh "$T/input-link" "$T/symlink.text" 2> "$T/symlink.log"; then bad 'input symlink accepted'; else [ ! -e "$T/symlink.text" ] && ok 'input symlink rejected' || bad 'input symlink installed text'; fi 399 printf 'DECODE_RESULT pass=%s fail=%s\n' "$pass" "$fail" 400 [ "$fail" = 0 ]