feat: capture gated native logical and physical identity evidence

This commit is contained in:
阿白叔 committed 2026-11-03 11:39:38 +08:00
1 parent ca84bce24f
commit 63f3417f19
2 files changed
+483

No files matched your search

@@ -0,0 +1,331 @@
"""Pinned EE7.9.5 native logical exports plus conservative physical/assets proof.
This contract is not raw iCDB equivalence or a claim of exhaustive arbitrary CES
semantics. It compares the proven hierarchy/flat ASCII and CSV/property exports,
and preserves physical design and all other primary engineering assets exactly.
"""
from dataclasses import dataclass
import hashlib
from pathlib import Path
import re
import subprocess
import time
from .management import source_project, _write_json
from .scoped_manifest import ManifestScope, build_manifest, hash_file
POLICY = 'mentor795-native-content-v1'
COVERAGE = {'logical_connectivity_and_properties': 'native hierarchy/flat ASCII and CSV',
'physical_design_and_primary_assets': 'raw SHA256',
'schematic_graphical_geometry': 'unproven', 'production_acceptance': False}
EXPORTER_PROOF = {
'icdb2ascii.exe': 'e37c87356eaf57c0b97e4183458bc8c5eb6eb0ac497cc7ad40dcd585d8cd213b',
'icdb2csv.exe': '22059f4a432e8eabf30a5326ebcbd463ed6fa6495af21d7aad5ab5d2f892f255',
}
INF_HEADER = (b'Design Name\tSystem Name\tSystem Version\tSystem_Date\tCompany_Name\tDepartment_Name'
b'\tAddress\tAddress1\tCity\tState_Province\tCountry\tZip\tPhone\tPhone_Ext\tFax\tFax_Ext')
CSV_SUFFIXES = ('', '.esf', '.inf', '.npr', '.ppn', '.ppr', '.prm', '.prt', '.pth',
'.sht', '.spn', '.spr', '.sym', '.thn')
_retained_exports = []
_OWNER_NAMES = frozenset({'icdb2ascii.exe', 'icdb2csv.exe', 'icdbnetserver.exe',
'icdbnetlauncher.exe', 'icdbservermanager.exe', 'icdbservermonitor.exe'})
@dataclass(frozen=True)
class IdentityOutcome:
identity: dict | None
safe_to_continue: bool
detail: str
evidence_path: Path
def _digest(data):
return hashlib.sha256(data).hexdigest()
def normalize_ascii(data, top):
"""Only the three observed, position-bound report metadata values vary."""
lines = data.splitlines(keepends=True)
prefixes = {0: b'iCDB Ascii Report Generation Date: ',
4: b'\t iCDB directory: ', 5: b'\t DATE: '}
if (len(lines) < 12 or lines[3].rstrip(b'\r\n') != b'\tReport Criteria:'
or any(not lines[i].startswith(prefix) or not lines[i][len(prefix):].strip()
for i, prefix in prefixes.items())):
raise ValueError('Incomplete or unknown native ASCII report header.')
header = b''.join(lines[:next((i for i, line in enumerate(lines) if line.startswith(b'Block ')), len(lines))])
required = (b'\t REPORT FORMAT: FREEFORM', b'\t MODE: HIER AND FLAT BLOCKS',
b'\t CONNECTION LISTS: ON', b'\t TEXT LISTS: ON')
if any(header.count(value) != 1 for value in required):
raise ValueError('Native ASCII export mode does not match the proven contract.')
top_bytes = top.encode('mbcs')
if (not any(line.rstrip(b'\r\n') == b'Block '+top_bytes+b' \tRoot' for line in lines)
or not any(line.startswith(b'Config ') for line in lines)):
raise ValueError('Native ASCII export lacks the exact root or flat configuration.')
for index, prefix in prefixes.items():
ending = b'\r\n' if lines[index].endswith(b'\r\n') else b'\n'
lines[index] = prefix+b'<REPORT_METADATA>'+ending
return b''.join(lines)
def normalize_inf(data):
lines = data.splitlines(keepends=True)
if len(lines) != 2 or lines[0].rstrip(b'\r\n') != INF_HEADER:
raise ValueError('Unknown native CSV information schema.')
values = lines[1].rstrip(b'\r\n').split(b'\t')
if len(values) != 16 or values[:3] != [b'identity', b'Design Capture', b'VB99.0']:
raise ValueError('Malformed native CSV information row.')
if not re.fullmatch(rb'\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}', values[3]):
raise ValueError('Unknown native CSV System_Date format.')
values[3] = b'<SYSTEM_DATE>'
ending = b'\r\n' if lines[1].endswith(b'\r\n') else b'\n'
return lines[0]+b'\t'.join(values)+ending
def csv_identity(root):
from .scoped_manifest import scan_tree
root = Path(root)
paths = {p.relative_to(root).as_posix(): p for p in scan_tree(root) if p.is_file()}
expected = {'work/identity'+suffix for suffix in CSV_SUFFIXES}
if paths.keys() != expected or any(not p.stat().st_size for p in paths.values()):
raise ValueError('Native CSV export is empty, incomplete or an unsupported snapshot.')
index = paths['work/identity'].read_bytes().splitlines()
expected_index = {b'file:identity'+suffix.encode('ascii') for suffix in CSV_SUFFIXES if suffix}
if len(index) != len(expected_index) or set(index) != expected_index:
raise ValueError('Native CSV index does not bind every exported table.')
return {name: _digest(normalize_inf(path.read_bytes()) if name.endswith('.inf') else path.read_bytes())
for name, path in sorted(paths.items())}
def _project_encoding(data):
if data.startswith((b'\xff\xfe', b'\xfe\xff')): return 'utf-16'
if data.startswith(b'\xef\xbb\xbf'): return 'utf-8-sig'
try: data.decode('utf-8'); return 'utf-8'
except UnicodeDecodeError: return 'mbcs'
def project_library(source):
"""Require one existing approved source library across every project ref."""
from .backup_recovery import _project_text
source, pcb, _ = source_project(source)
libraries = set()
for path in (source, pcb.parent/'pcb.prj'):
values = re.findall(r'^KEY CentralLibrary "([^"\r\n]+)"', _project_text(path), re.M)
if not values: raise ValueError('Project lacks CentralLibrary references.')
for value in values:
target = (path.parent/value).resolve(strict=True)
if target.suffix.casefold() != '.lmc' or not target.is_file():
raise ValueError('CentralLibrary is not an existing LMC.')
libraries.add(target)
if len(libraries) != 1: raise ValueError('Project CentralLibrary references disagree.')
return libraries.pop()
def _normalized_project(path, expected_library):
data = path.read_bytes(); encoding = _project_encoding(data)
text = data.decode(encoding)
refs = re.findall(r'^KEY CentralLibrary "([^"\r\n]*)"', text, re.M)
if not refs or any((path.parent/value).resolve() != expected_library.resolve() for value in refs):
raise ValueError(f'CentralLibrary reference does not resolve to the approved library: {path}')
return re.sub(r'(?m)^(KEY CentralLibrary ")[^"\r\n]*(")',
r'\1<CENTRAL_LIBRARY>\2', text).encode(encoding)
def asset_identity(source, expected_library):
from .backup_recovery import _project_text
source, pcb, top = source_project(source)
expected_library = Path(expected_library)
if not expected_library.is_file(): raise ValueError('Approved CentralLibrary is missing.')
root = source.parent
projects = (source, pcb.parent/'pcb.prj')
databases = []
for project in projects:
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', _project_text(project), re.M)
databases.extend((project.parent/value).resolve() for value in values)
main_database = databases[0]
runtime = [db/'cdbsvr' for db in databases]
files = build_manifest(root, scope=ManifestScope())['files']
assets = {}
for relative, record in files.items():
path = root/relative
if path == main_database/'icdb.dat' or any(path.is_relative_to(p) for p in runtime):
continue
if path in projects:
data = _normalized_project(path, expected_library)
assets[relative] = {'size': len(data), 'sha256': _digest(data)}
else:
assets[relative] = {'size': record['size'], 'sha256': record['sha256']}
return {'policy': POLICY, 'top_level_block': top,
'layout_sha256': hash_file(pcb.parent/'Layout/LayoutDB.lyt'), 'assets': assets}
def check_exporters(mentor_home):
for name, expected in EXPORTER_PROOF.items():
path = Path(mentor_home)/'iCDB/win32/bin'/name
if not path.is_file() or hash_file(path) != expected:
raise ValueError(f'Native identity exporter is not the proven EE7.9.5 binary: {path}')
def validate_export_output(kind, code, report, log):
text = Path(log).read_bytes().decode('mbcs', errors='strict')
if code != 0 or re.search(r'(?im)^\s*(?:#\s*)?(?:error|fatal)\b', text):
raise ValueError('Native identity exporter failed or reported an error.')
if kind == 'ascii':
if (not Path(report).is_file() or not Path(report).stat().st_size
or f'Report generation complete, report file is {report}' not in text):
raise ValueError('Native ASCII export lacks a complete nonempty report.')
elif kind == 'csv':
if 'iCDB to CSV complete' not in [line.strip() for line in text.splitlines()]:
raise ValueError('Native CSV export lacks its completion marker.')
csv_identity(report)
else:
raise ValueError('Unsupported native export kind.')
def _process_snapshot():
import win32com.client
service = win32com.client.GetObject('winmgmts:')
try:
return [{'pid': int(p.ProcessId), 'parent': int(p.ParentProcessId or 0),
'name': str(p.Name), 'executable': str(p.ExecutablePath or '')}
for p in service.ExecQuery('SELECT ProcessId, ParentProcessId, Name, ExecutablePath FROM Win32_Process')]
finally:
service = None
def _database_released(project_root):
"""Exclusive reads plus absent addresses prove the copied native DBs idle."""
import win32file, win32con
from contextlib import ExitStack
root = Path(project_root)
if any(root.rglob('sAddress.adr')):
return False
with ExitStack() as stack:
for path in root.rglob('*'):
if path.is_file() and path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
stack.callback(handle.Close)
return True
def _run_exports(project, root, mentor_home, timeout_seconds):
"""Observe exact exporter/descendant handles; never kill a database owner."""
import win32api, win32con, win32event, pywintypes
root = Path(root)
before = _process_snapshot()
if any(p['name'].casefold() in _OWNER_NAMES for p in before):
return {'success': False, 'safe_to_continue': False, 'detail': 'An existing iCDB owner prevents isolated identity export.'}
if not _database_released(project.parent):
return {'success': False, 'safe_to_continue': False, 'detail': 'Analysis copy has unreleased native addresses or DB handles.'}
commands = [
('ascii', [str(Path(mentor_home)/'iCDB/win32/bin/icdb2ascii.exe'),
f'-project={project}', f'-file={root/"design.rpt"}', f'-clog={root/"ascii.log"}',
'-f', '-h', '-c', '-t', '-nostrip'], root/'design.rpt', root/'ascii.log'),
('csv', [str(Path(mentor_home)/'iCDB/win32/bin/icdb2csv.exe'),
f'-project={project}', '-snap=DxD', '-file=identity', f'-output={root/"tables"}',
f'-clog={root/"csv.log"}', '-properties', '-nostrip'], root/'tables', root/'csv.log'),
]
for kind, command, report, log in commands:
process = None
handles = {}
released = False
record = {'command': command, 'kind': kind, 'success': False, 'safe_to_continue': False}
try:
deadline = time.monotonic()+float(timeout_seconds)
with (root/(kind+'-stdout.txt')).open('wb') as output:
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW)
record['pid'] = process.pid
descendants = {process.pid}
_write_json(root/(kind+'-process.json'), record)
while time.monotonic() < deadline:
snapshot = _process_snapshot()
changed = True
while changed:
previous = len(descendants)
descendants.update(p['pid'] for p in snapshot if p['parent'] in descendants)
changed = len(descendants) != previous
owners = [p for p in snapshot if p['pid'] in descendants or p['name'].casefold() in _OWNER_NAMES]
for owner in owners:
if owner['pid'] not in handles:
try: handles[owner['pid']] = win32api.OpenProcess(win32con.SYNCHRONIZE, False, owner['pid'])
except pywintypes.error as error:
if error.winerror != 87: raise
record['observed_pids'] = sorted(descendants | handles.keys())
if (process.poll() is not None and not owners
and all(win32event.WaitForSingleObject(h, 0) == win32con.WAIT_OBJECT_0 for h in handles.values())):
released = _database_released(project.parent)
if released: break
time.sleep(.1)
record.update(exit_code=process.poll(), safe_to_continue=released)
if not released:
record['detail'] = 'TIMEOUT: native export owner or copied database release remains unconfirmed.'
return record
validate_export_output(kind, process.returncode, report, log)
record.update(success=True, detail='Native export complete and owners released.')
except Exception as error:
record.update(detail=str(error), safe_to_continue=released)
return record
finally:
if process is not None and not released:
_retained_exports.append((process, handles))
else:
for handle in handles.values(): handle.Close()
_write_json(root/(kind+'-process.json'), record)
return {'success': True, 'safe_to_continue': True, 'detail': 'Both native exports completed and released.'}
def capture_identity(source, evidence_root, *, expected_library, owner_library, mentor_home,
timeout_seconds=180):
"""Capture on a fresh project copy while an existing transaction owns its library."""
from .backup_recovery import _align_library
from .library_lock import LibraryLock, owned_snapshot
from .scoped_manifest import copy_verified
import win32event, win32con
source, pcb, top = source_project(source)
root = Path(evidence_root).absolute()
library = Path(owner_library)
lease = LibraryLock(library)
if owned_snapshot(lease.path) is None:
raise ValueError('Native identity capture requires a current-thread transaction library lease.')
if (root.resolve().is_relative_to(source.parent) or source.parent.is_relative_to(root.resolve())
or root.resolve().is_relative_to(library.parent.resolve())):
raise ValueError('Native identity evidence must be independent of source and library.')
check_exporters(mentor_home)
root.mkdir(parents=True, exist_ok=False)
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
owner_safe = True
outcome = IdentityOutcome(None, True, 'Identity capture did not start.', root)
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired: raise RuntimeError('Another CBB operation owns the management mutex.')
with LibraryLock(library, safe_to_release=lambda: owner_safe):
assets = asset_identity(source, Path(expected_library))
original = copy_verified(source.parent, root/'project')
clone = root/'project'/source.name
_, clone_pcb, _ = source_project(clone)
_align_library(clone, clone_pcb, Path(expected_library))
if any((root/'project').rglob('sAddress.adr')):
raise ValueError('Analysis source contains an unresolved database address.')
owner_safe = False
native = _run_exports(clone, root, mentor_home, timeout_seconds)
owner_safe = native.get('safe_to_continue') is True
_write_json(root/'native-outcome.json', native)
if not owner_safe or not native.get('success'):
outcome = IdentityOutcome(None, owner_safe, native.get('detail', 'Native export failed.'), root)
else:
ascii_bytes = normalize_ascii((root/'design.rpt').read_bytes(), top)
csv = csv_identity(root/'tables')
if build_manifest(source.parent) != original:
raise ValueError('Identity input changed while exporting its disposable copy.')
fingerprint = {**assets, 'coverage': COVERAGE, 'ascii_sha256': _digest(ascii_bytes), 'csv': csv}
outcome = IdentityOutcome(fingerprint, True, 'Native logical exports and primary assets captured.', root)
except Exception as error:
outcome = IdentityOutcome(None, owner_safe, str(error), root)
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
_write_json(root/'identity.json', {'identity': outcome.identity, 'safe_to_continue': outcome.safe_to_continue,
'detail': outcome.detail, 'policy': POLICY})
return outcome