// Synthetic negative controls for an allocation/EL0 subproof, not a VM run. import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; import {checkNativeOwnership} from '../../scripts/os-acceptance/features/k2155-native-ownership-check.mjs'; import {NATIVE_STAGES,nativeStageOrder,collectNativePhysical} from '../../scripts/os-acceptance/features/k2155-native-capture.mjs'; import {ledger,released} from '../../scripts/os-acceptance/features/k2155-dma-authority-check.mjs'; const candidate=JSON.parse(readFileSync(process.argv[2])),image=readFileSync(candidate.artifacts.image.path),symbols={}; for(const line of readFileSync(candidate.artifacts.nm.path,'utf8').split('\n')){const m=line.match(/^([a-f0-9]{16}) (?:([a-f0-9]{16}) )?[A-Za-z] (\S+)$/);if(m)symbols[m[3]]={address:parseInt(m[1],16),size:m[2]?parseInt(m[2],16):0};} const key='OS_K1000_AUTHORITY_LAYOUT_EXPECTED',symbol=symbols[key],at=symbol.address-candidate.imageSpan.start,compiled={[key]:image.subarray(at,at+symbol.size)}; const W=b=>Array.from({length:b.length/8},(_,i)=>b.readBigUInt64LE(i*8)),l=W(compiled[key]).map(Number); const words=values=>{const b=Buffer.alloc(values.length*8);values.forEach((v,i)=>b.writeBigUInt64LE(BigInt(v),i*8));return b;}; const programs=['driver','pid1'].map(n=>readFileSync(candidate.sources['k2155-native-'+n+'.bin'].path)); const bootId='1122334455667788',root=0x41000000n,start=0x48000000n,pages=Array.from({length:34},(_,i)=>start+BigInt(i)*4096n); const before=Buffer.alloc(l[0]),held=Buffer.alloc(l[0]); before.writeBigUInt64LE(1n,l[1]+l[3]);before.writeBigUInt64LE(start,l[1]+l[2]+l[21]);before.writeBigUInt64LE(start+64n*4096n,l[1]+l[2]+l[22]); before.writeBigUInt64LE(root,l[5]+l[7]);before.writeBigUInt64LE(1n,l[5]+l[8]);before[l[5]+l[9]]=1;before.writeBigUInt64LE(100n,l[17]);before.writeBigUInt64LE(0x1234n,l[18]); before.copy(held);held.writeBigUInt64LE(start+34n*4096n,l[1]+l[2]+l[21]);held.writeBigUInt64LE(134n,l[17]); for(const [i,address]of pages.entries()){const at=l[5]+(i+1)*l[6];held.writeBigUInt64LE(address,at+l[7]);held.writeBigUInt64LE(BigInt(101+i),at+l[8]);held[at+l[9]]=1;} const initial=ledger(held,l),afterWorkers=released(held,l,initial,pages.slice(12,22)),afterDma=released(held,l,initial,pages.slice(12)),afterAll=released(held,l,initial,pages); const kernel=Buffer.alloc(4096);kernel.writeBigUInt64LE(0x41001003n,8); const userBuffers={},users=[],guards=[],devices=Array(128).fill(0n); for(let i=0;i<2;i++){ const [r,l2,l3,c,d,s]=pages.slice(i*6,i*6+6),prefix='user-'+i+'-'; users.push(r,c,d,s,0x80000000n,0x80001000n,0x80002000n,0x80003000n); const a=Buffer.from(kernel),b=Buffer.alloc(4096),e=Buffer.alloc(4096);a.writeBigUInt64LE(l2|3n,16);b.writeBigUInt64LE(l3|3n,0); words([c|0x0020000000000fc3n,d|0x0060000000000f43n,0n,s|0x0060000000000f43n]).copy(e); for(const[label,value]of [['root',a],['l2',b],['l3',e],['code',Buffer.alloc(4096)],['data',Buffer.alloc(4096)],['stack',Buffer.alloc(4096)]])userBuffers[prefix+label]=value; programs[i].copy(userBuffers[prefix+'code']);const guard=pages[12+i*5];guards.push(guard,0x41002000n+(guard>>12n&511n)*8n,guard|0x0060000000000703n,guard+4096n,guard+20472n,guard+4096n); } let frame=22;for(let d=0;d<2;d++)for(let q=0;q<(d===0?1:2);q++)for(let p=0;p<4;p++)devices[d*64+12+q*20+p]=pages[frame++]; const stackLow=BigInt(symbols.OS_K900_STACK.address)+4096n,stackTop=stackLow+65536n-16n,frameAddress=stackTop-4096n; const normalSp=stackTop-8192n,requests=[],pcs=programs.map(p=>{const a=[];for(let i=0;i+4<=p.length;i+=4)if(p.readUInt32LE(i)===0xd4000001)a.push(0x80000000n+BigInt(i+4));assert.ok(a.length);return a;}); const REFUSED=1n<<63n,GEN=0x21550001n; for(const id of [[9n,0x21550009n],[1n,GEN-1n]])for(const [call,args,result]of [[16n,[0n,0n,0n],REFUSED|1n],[16n,[1n,GEN,0xffffffffffffffffn],REFUSED|1n],[17n,[0n,0n,0n],0n],[1n,[0x2159n,0n,0n],0x2159n]])requests.push([...id,call,...args,result,0n]); requests.push([1n,GEN,16n,1n,0n,0n,REFUSED|22n,0n],[1n,GEN,17n,0n,0n,0n,0n,0n],[1n,GEN,16n,0n,0n,0n,0x215500acn,1n]); function fixture(first=100,tco=0n){ const stages=[...NATIVE_STAGES];stages.splice(4,4,first,first+1,first===100?110:100,first===100?111:101);nativeStageOrder(stages); const rows=Buffer.alloc(1536),frames=Buffer.alloc(2496); requests.forEach((r,i)=>words([...r,pcs[i<8?0:1][0],0x80004000n,0x3c0n|tco,0x56000000n,8n,i+1,i===10?1n:0n,frameAddress]).copy(rows,i*128)); for(let i=0;i<3;i++){const row=rows.subarray([0,4,10][i]*128),b=frames.subarray(i*832,(i+1)*832);row.copy(b,0,24,48);b.writeBigUInt64LE(16n,64);for(const[at,index]of [[248,9],[256,8],[264,10],[272,11],[816,12]])b.writeBigUInt64LE(row.readBigUInt64LE(index*8),at);} let calls=0,count=0;const snapshots=[]; stages.forEach((stage,step)=>{ if(stage===330){calls=1;count=1;}if(stage===300)calls=4;if(stage===331){calls=5;count=2;}if(stage===301)calls=8;if(stage===332){calls=11;count=3;} const e=Array(64).fill(0n);e[0]=0x4b32313535494e54n;e[1]=BigInt(stage);e[2]=64n;e[4]=BigInt('0x'+bootId); if(stage!==0){e[5]=users[0];e[6]=users[8];e[7]=root;}if(step>=10)e[10]=4n;if(step>=12)e[11]=4n;if(step>=14){e[12]=3n;e[13]=11n;e[14]=1n;}if(stage===70){e[3]=64n;e[15]=22n;e[16]=52n;e[17]=1n;} const svc=[330,331,332].includes(stage),cpu=[svc?users[stage===332?8:0]:root,svc?symbols.__os_fx_vectors.address:[100,101,110,111].includes(stage)?symbols.__os_k2155_irq_vectors.address:0x40080000,0x3c0,normalSp,0x80000000,step+1,24000000,4]; if([210,211,220,221].includes(stage))cpu[3]=guards[(stage%10)*6]+8192n; const context=Buffer.alloc(192);context.writeBigUInt64LE(stackTop-1024n,96);context.writeBigUInt64LE(root,104);context.writeBigUInt64LE(0x40080000n,112);context.writeBigUInt64LE(0x3c0n,120); const s={OS_K2155_EVIDENCE:words(e),OS_K2155_CPU_STATE:words(cpu),OS_K2155_DMA_AUTHORITY:words([0x41010000,l[0],symbol.address,192]),[key]:Buffer.from(compiled[key]), OS_K2155_USER_SPACES:stage===0?Buffer.alloc(128):words(users),OS_K2155_DMA_DEVICES:words(devices),OS_K2155_THREAD_GUARDS:words(guards), authority:Buffer.from(stage===0?before:stage===230?afterWorkers:stage===60?afterDma:stage===70?afterAll:held),'root-page':Buffer.from(kernel),'el0-kernel-context':context, OS_K2155_EL0_REQUESTS:Buffer.alloc(1536),OS_K2155_EL0_FRAMES:Buffer.alloc(2496)}; rows.copy(s.OS_K2155_EL0_REQUESTS,0,0,calls*128);frames.copy(s.OS_K2155_EL0_FRAMES,0,0,count*832); if(stage!==0)for(const[k,b]of Object.entries(userBuffers))s[k]=stage===70?Buffer.alloc(4096):Buffer.from(b); if(svc)s['el0-frame']=Buffer.from(frames.subarray((stage-330)*832,(stage-330)*832+824));snapshots.push(s); });return {snapshots,compiled,symbols,memoryMiB:256,bootId,programs}; } const rejected=[]; for(const first of [100,110])for(const tco of [0n,1n<<25n]){ const input=fixture(first,tco);assert.equal(checkNativeOwnership(input).ownedPages,34); const mutations=[ ['kernel-root-reclaimed',70,'authority',l[5]+l[9]],['unrelated-owner',210,'authority',l[18]],['fake-compiler-layout',1,key,0], ['missing-preallocation-baseline',0,'authority',l[17]],['changed-existing-generation',1,'authority',l[5]+l[8]], ['wrong-user-permission',1,'user-0-l3',6],['mapped-user-guard',1,'user-0-l3',16],['extra-user-l2-mapping',1,'user-0-l2',8], ['wrong-user-code',1,'user-0-code',0],['user-data-contaminated',1,'user-0-data',0],['user-root-shares-wrong-kernel',1,'user-0-root',8], ['wrong-user-root-register',330,'OS_K2155_CPU_STATE',0],['private-root-during-teardown',30,'OS_K2155_CPU_STATE',0], ['wrong-vector',332,'OS_K2155_CPU_STATE',8],['irq-unmasked',220,'OS_K2155_CPU_STATE',16],['wrong-cpu',2,'OS_K2155_CPU_STATE',32], ['wrong-frequency',302,'OS_K2155_CPU_STATE',48],['wrong-el',60,'OS_K2155_CPU_STATE',56],['invalid-worker-sp',210,'OS_K2155_CPU_STATE',24], ['wrong-live-svc',330,'el0-frame',64],['wrong-live-spsr',331,'el0-frame',264],['wrong-live-slot',332,'el0-frame',816], ['wrong-saved-root',331,'el0-kernel-context',104],['wrong-saved-vbar',332,'el0-kernel-context',112], ['fabricated-unwritten-request',0,'OS_K2155_EL0_REQUESTS',0],['early-receipt',302,'OS_K2155_EVIDENCE',120], ['early-clean-marker',50,'OS_K2155_EVIDENCE',136],['wrong-final-page-count',70,'OS_K2155_EVIDENCE',128], ['unreleased-user-data',70,'user-1-data',0],['unreleased-user-table',70,'user-1-l3',0], ['early-worker-release',30,'authority',l[5]+13*l[6]+l[9]],['early-dma-release',50,'authority',l[5]+23*l[6]+l[9]], ['raw-padding-fabricated',332,'OS_K2155_EL0_FRAMES',2*832+824], ]; for(const[name,stage,key,at]of mutations){const snapshots=input.snapshots.map(s=>({...s})),index=snapshots.findIndex(s=>Number(s.OS_K2155_EVIDENCE.readBigUInt64LE(8))===stage);snapshots[index][key]=Buffer.from(snapshots[index][key]);snapshots[index][key][at]^=key==='OS_K2155_CPU_STATE'&&at===16?0x80:1;assert.throws(()=>checkNativeOwnership({...input,snapshots}),name);rejected.push(first+':'+tco+':'+name);} // Coupled alterations modify every copy of a request, to ensure rejection // comes from authorization/instruction semantics rather than copy mismatch. for(const[name,field,delta]of [['forged-caller-generation',1,1n],['forged-refusal-result',6,1n],['el1-origin',10,5n],['not-svc',11,1n<<26n],['forged-pending',14,1n],['non-svc-return-pc',8,1n]]){ const snapshots=input.snapshots.map(s=>Object.fromEntries(Object.entries(s).map(([k,b])=>[k,Buffer.from(b)]))); for(const s of snapshots){if(s.OS_K2155_EL0_REQUESTS.readBigUInt64LE(0)!==0n)s.OS_K2155_EL0_REQUESTS.writeBigUInt64LE(s.OS_K2155_EL0_REQUESTS.readBigUInt64LE(field*8)^delta,field*8);} assert.throws(()=>checkNativeOwnership({...input,snapshots}),name);rejected.push(first+':'+tco+':'+name); } } const input=fixture(),plan={},captured=[]; await collectNativePhysical({stage:0,data:input.snapshots[0],symbols,plan,take:async(name,address,size,mmio)=>{captured.push([name,address,size,mmio]);return input.snapshots[0][name];}}); assert.deepEqual(captured.map(x=>x[0]),['authority','root-page','el0-kernel-context']);assert.equal(plan.kernelRoot,root); // Replay every collector gate with physical address assertions. In particular // user tables are erased at 70: the collector must retain their old addresses // and must not dereference the already-consumed native IRQ owner's stack slot. const physicalPlan={},ilSymbol=symbols.OS_K2155_IRQ_LAYOUT,ilBytes=image.subarray(ilSymbol.address-candidate.imageSpan.start,ilSymbol.address-candidate.imageSpan.start+ilSymbol.size),il=W(ilBytes); const tlSymbol=symbols.OS_K2155_THREAD_LAYOUT,tlBytes=image.subarray(tlSymbol.address-candidate.imageSpan.start,tlSymbol.address-candidate.imageSpan.start+tlSymbol.size),tl=W(tlBytes); let physicalSpans=0; for(const s of input.snapshots){ const stage=Number(s.OS_K2155_EVIDENCE.readBigUInt64LE(8)),state=Array(32).fill(0n),events=Array(128).fill(0n),rawTable=stackLow+12288n; state[0]=0x8000000n;state[5]=79n;state[8]=78n;state[23]=BigInt(symbols.OS_K2155_IRQ_CONTEXT.address)+16n; state[25]=stackLow+16384n;state[26]=il[0];state[27]=BigInt(symbols.OS_K2155_IRQ_CONTEXT.address); if([100,101,110,111].includes(stage)){state[10]=1n;if(stage>=110)state[12]=1n;events[(stage>=110?1:0)*16+3]=frameAddress;} s.OS_K2155_IRQ_STATE=words(state);s.OS_K2155_IRQ_EVENTS=words(events);s.OS_K2155_IRQ_LAYOUT=ilBytes; s.OS_K2155_THREAD_TABLE=words([[60,70].includes(stage)?0n:rawTable,tl[0],2,2,0x41010000,l[0],symbol.address,root,tlSymbol.address,128]); s.OS_K2155_DMA_DEVICES.writeBigUInt64LE(0xa003e00n,0);s.OS_K2155_DMA_DEVICES.writeBigUInt64LE(0xa003c00n,512); const actual=new Map(),put=(name,address,buffer)=>actual.set(name,{address:Number(address),buffer}); put('authority',0x41010000,s.authority);put('root-page',root,s['root-page']);put('el0-kernel-context',symbols.__os_fx_kernel_context.address,s['el0-kernel-context']); for(let i=0;i<2;i++)for(const[j,label]of ['root','l2','l3','code','data','stack'].entries())if(stage!==0)put('user-'+i+'-'+label,pages[i*6+j],s['user-'+i+'-'+label]); put('thread-table',rawTable,Buffer.alloc(Number(tl[0]))); const l2=Buffer.alloc(4096),l3=Buffer.alloc(4096);l2.writeBigUInt64LE(0x41002003n,64*8);put('l2-41001000',0x41001000,l2);put('l3-41002000',0x41002000,l3); for(let i=0;i<2;i++){ put('guard-'+i,guards[i*6+1],Buffer.alloc(8));put('stack-'+i,guards[i*6],Buffer.alloc(20480)); put('low-canary-'+i,guards[i*6+3],Buffer.alloc(8));put('high-canary-'+i,guards[i*6+4],Buffer.alloc(8)); } for(let d=0;d<2;d++){ const base=d===0?0xa003e00:0xa003c00; for(const[name,off]of [['magic',0],['version',4],['device',8],['vendor',12],['ready',0x44],['interrupt',0x60],['status',0x70]])put(`mmio-${d}-${name}`,base+off,Buffer.alloc(4)); for(let q=0;q<(d===0?1:2);q++)for(let p=0;p<4;p++)put(`dma-${d}-${q}-${p}`,pages[22+(d===0?0:4+q*4)+p],Buffer.alloc(4096)); const id=d===0?79:78,word=4*Math.floor(id/32); for(const[name,offset,size]of [['enable',0x100+word,4],['active',0x300+word,4],['pending',0x200+word,4],['config',0xc00+4*Math.floor(id/16),4],['group',0x80+word,4],['priority',0x400+id,1],['route',0x6000+id*8,8]])put(`gic-${d}-${name}`,0x8000000+offset,Buffer.alloc(size)); } for(const[name,address,size]of [['irq-owner',state[25],Number(il[0])],['irq-active',state[23],4],['irq-context',state[27],8],['gic-control',0x8000000,4],['gic-typer',0x8000004,4],['irq-frame',frameAddress,848]])put(name,address,Buffer.alloc(size)); if(s['el0-frame'])put('el0-frame',frameAddress,s['el0-frame']); await collectNativePhysical({stage,data:s,symbols,plan:physicalPlan,take:async(name,address,size)=>{ assert.ok(!(stage===70&&name==='irq-owner'),'consumed IRQ owner cannot be read');const expected=actual.get(name);assert.ok(expected,name);assert.equal(address,expected.address,name);assert.equal(size,expected.buffer.length,name);physicalSpans++;return expected.buffer; }}); } assert.throws(()=>nativeStageOrder(NATIVE_STAGES.filter(n=>n!==230)));assert.throws(()=>nativeStageOrder([...NATIVE_STAGES].reverse())); console.log(JSON.stringify({status:'NATIVE_OWNERSHIP_HOST_TESTS_PASSED',syntheticFixture:true,positiveFixtures:4,collectorGates:25,physicalSpans,rejected,guestAccepted:false,productAccepted:false,fullNativeShutdownVerified:false}));