"""Bounded, resumable copies of explicitly hash-bound evidence. Never delete sources.""" import argparse import contextlib import fcntl import hashlib import json import os from pathlib import Path import re import stat import uuid CHUNK=1024*1024 MAX_FILES=4096 MAX_FILE_BYTES=16*1024**3 MAX_TOTAL_BYTES=64*1024**3 MAX_JSON=8*1024**2 PREFIX='turkos-evidence-archives' HEX=re.compile(r'^[0-9a-f]{64}$') def encode(value):return (json.dumps(value,ensure_ascii=False,sort_keys=True,indent=2)+'\n').encode() def digest(data):return hashlib.sha256(data).hexdigest() def parts(path): if not isinstance(path,str) or '\x00' in path or '\\' in path:raise ValueError('invalid relative path') items=path.split('/') if any(p in ('','.','..')for p in items):raise ValueError('normal relative path required') return items def unique_pairs(pairs): result={} for key,value in pairs: if key in result:raise ValueError('duplicate JSON key') result[key]=value return result def decode(data): if len(data)>MAX_JSON:raise ValueError('JSON exceeds batch limit') return json.loads(data,object_pairs_hook=unique_pairs) def identity(s):return (s.st_dev,s.st_ino,s.st_size,s.st_mtime_ns,s.st_ctime_ns,s.st_mode) def write_all(fd,data): view=memoryview(data) while view: count=os.write(fd,view) if count<=0:raise OSError('short write') view=view[count:] class Tree: """An open root and O_NOFOLLOW walks, including every intermediate directory.""" def __init__(self,root): path=Path(root) if path.is_symlink():raise ValueError('symlink root') self.path=path.resolve(strict=True) self.fd=os.open(self.path,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW|os.O_CLOEXEC) self.device=os.fstat(self.fd).st_dev def __enter__(self):return self def __exit__(self,*_):os.close(self.fd) def directory(self,names,create=False): fd=os.dup(self.fd) try: for name in names: if create: try:os.mkdir(name,0o700,dir_fd=fd) except FileExistsError:pass other=os.open(name,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW|os.O_CLOEXEC,dir_fd=fd) try: if os.fstat(other).st_dev!=self.device:raise ValueError('nested filesystem') except BaseException:os.close(other);raise os.close(fd);fd=other return fd except BaseException:os.close(fd);raise def mkdir(self,path): fd=self.directory(parts(path),True);os.close(fd) def open(self,path,flags=os.O_RDONLY,mode=0o600,parents=False): names=parts(path);parent=self.directory(names[:-1],parents) try:fd=os.open(names[-1],flags|os.O_NOFOLLOW|os.O_CLOEXEC|os.O_NONBLOCK,mode,dir_fd=parent) finally:os.close(parent) info=os.fstat(fd) if not stat.S_ISREG(info.st_mode) or info.st_dev!=self.device: os.close(fd);raise ValueError('regular file in the selected filesystem required') return fd def read(self,path,limit=MAX_JSON): fd=self.open(path) try: before=os.fstat(fd) if before.st_size>limit:raise ValueError('read limit') chunks=[];count=0 while True: data=os.read(fd,min(CHUNK,limit-count+1)) if not data:break chunks.append(data);count+=len(data) if count>limit:raise ValueError('read limit') if identity(before)!=identity(os.fstat(fd)):raise RuntimeError('file changed while reading') return b''.join(chunks) finally:os.close(fd) def exists(self,path): try:fd=self.open(path) except FileNotFoundError:return False else:os.close(fd);return True def publish(self,path,data,mode=0o400): names=parts(path);parent=self.directory(names[:-1],True);temporary='.write-'+uuid.uuid4().hex+'.tmp' fd=None try: fd=os.open(temporary,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW|os.O_CLOEXEC,0o600,dir_fd=parent) write_all(fd,data);os.fchmod(fd,mode);os.fsync(fd);os.close(fd);fd=None try:os.link(temporary,names[-1],src_dir_fd=parent,dst_dir_fd=parent,follow_symlinks=False) except FileExistsError: if self.read(path,max(len(data),MAX_JSON))!=data:raise ValueError('immutable destination conflict: '+path) os.fsync(parent) finally: if fd is not None:os.close(fd) try:os.unlink(temporary,dir_fd=parent) except FileNotFoundError:pass os.close(parent) @contextlib.contextmanager def lock(self,path): fd=self.open(path,os.O_RDWR|os.O_CREAT,parents=True) try: try:fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB) except BlockingIOError:raise RuntimeError('another writer owns this batch') yield finally:os.close(fd) def inspect(tree,path,expected=None): fd=tree.open(path) try: before=os.fstat(fd) if before.st_size>MAX_FILE_BYTES:raise ValueError('file exceeds batch limit') if stat.S_IMODE(before.st_mode)&~0o777:raise ValueError('special permission bits unsupported') value=hashlib.sha256() remaining=before.st_size while True: data=os.read(fd,min(CHUNK,remaining+1)) if not data:break remaining-=len(data) if remaining<0:raise RuntimeError('file grew while hashing') value.update(data) if identity(before)!=identity(os.fstat(fd)):raise RuntimeError('source changed while hashing') row=dict(path=path,sha256=value.hexdigest(),bytes=before.st_size,mode=stat.S_IMODE(before.st_mode)) if expected is not None and any(row[k]!=expected[k]for k in ['sha256','bytes','mode']):raise ValueError('changed bytes or permissions: '+path) return row finally:os.close(fd) def selection_plan(tree,selection): if set(selection)!=set(['schema','storageClass','files']):raise ValueError('selection fields') if selection['schema']!='turkos-archive-selection/v1' or selection['storageClass']!='sealed-evidence':raise ValueError('sealed evidence selection required') files=selection['files'] if not isinstance(files,list)or not 1<=len(files)<=MAX_FILES:raise ValueError('bounded nonempty batch required') paths=set();rows=[];total=0 for item in files: if not isinstance(item,dict)or set(item)!=set(['path','sha256']):raise ValueError('selection file fields') path=item['path'];parts(path) if path.split('/')[0].startswith('.turkos-restore'):raise ValueError('reserved restore path') if path in paths:raise ValueError('duplicate source path') if not isinstance(item['sha256'],str)or not HEX.fullmatch(item['sha256']):raise ValueError('SHA-256 required') paths.add(path);row=inspect(tree,path) if not row['mode']&0o400:raise ValueError('owner-readable source permission required') if row['sha256']!=item['sha256']:raise ValueError('selection hash mismatch: '+path) total+=row['bytes'] if total>MAX_TOTAL_BYTES:raise ValueError('batch bytes exceeded') rows.append(row) return dict(schema='turkos-evidence-archive/v1',storageClass='sealed-evidence',files=sorted(rows,key=lambda r:r['path']),totalBytes=total,permissionMask=0o777,sourceFilesystem=tree.device) def copy_partial(source,path,target,partial,expected,fault=None): """Verify the existing prefix; append without truncating either file.""" source_fd=source.open(path);target_fd=None try: before=os.fstat(source_fd) if before.st_size!=expected['bytes']:raise ValueError('changed source size') try:existing=target.open(partial) except FileNotFoundError:pass else: try: info=os.fstat(existing) if info.st_uid!=os.getuid()or info.st_nlink!=1:raise ValueError('partial copy ownership') if stat.S_IMODE(info.st_mode)not in (0o600,0o400,expected['mode']):raise ValueError('partial permission mismatch') os.fchmod(existing,0o600) finally:os.close(existing) target_fd=target.open(partial,os.O_RDWR|os.O_CREAT,parents=True) opened=os.fstat(target_fd) if opened.st_uid!=os.getuid()or opened.st_nlink!=1 or stat.S_IMODE(opened.st_mode)!=0o600:raise ValueError('private partial file required') size=opened.st_size if size>expected['bytes']:raise ValueError('oversized partial copy') h=hashlib.sha256();left=size while left: a=os.read(source_fd,min(CHUNK,left));b=os.read(target_fd,len(a)) if not a or a!=b:raise ValueError('corrupt partial copy') h.update(a);left-=len(a) copied=0 remaining=expected['bytes']-size while True: data=os.read(source_fd,min(CHUNK,remaining+1)) if not data:break remaining-=len(data) if remaining<0:raise RuntimeError('source grew during copy') write_all(target_fd,data);h.update(data);copied+=len(data) if fault:fault('chunk',path,size+copied) if identity(before)!=identity(os.fstat(source_fd)):raise RuntimeError('source changed during copy') if h.hexdigest()!=expected['sha256'] or size+copied!=expected['bytes']:raise ValueError('copy hash mismatch') os.fsync(target_fd) return dict(resumedBytes=size,copiedBytes=copied) finally: if target_fd is not None:os.close(target_fd) os.close(source_fd) def promote(tree,partial,final,mode,fault=None): fd=tree.open(partial,os.O_RDWR) try:os.fchmod(fd,mode);os.fsync(fd) finally:os.close(fd) if fault:fault('after-mode',partial,0) source_names=parts(partial);target_names=parts(final) a=tree.directory(source_names[:-1]);b=tree.directory(target_names[:-1],True) try: os.link(source_names[-1],target_names[-1],src_dir_fd=a,dst_dir_fd=b,follow_symlinks=False);os.fsync(b) os.unlink(source_names[-1],dir_fd=a);os.fsync(a) finally:os.close(a);os.close(b) def backup(root,selection,destination,*,require_external=True,_fault=None): with Tree(root)as source,Tree(destination)as target: if target.path==source.path or source.path in target.path.parents:raise ValueError('archive must be outside the source tree') separate=source.device!=target.device if require_external and not separate:raise ValueError('a different destination filesystem is required') plan=selection_plan(source,selection);data=encode(plan);archive_id=digest(data);base=PREFIX+'/'+archive_id target.mkdir(base);target.mkdir(base+'/objects');target.mkdir(base+'/partial') with target.lock(base+'/.lock'): target.publish(base+'/plan.json',data) copied=0;resumed=0;reused=0 for row in plan['files']: final=base+'/objects/'+row['sha256'];partial=base+'/partial/'+row['sha256'] if target.exists(final): inspect(target,final,dict(row,mode=0o400));reused+=1;continue result=copy_partial(source,row['path'],target,partial,row,_fault) inspect(target,partial,dict(row,mode=0o600));promote(target,partial,final,0o400,_fault) copied+=result['copiedBytes'];resumed+=result['resumedBytes'] if _fault:_fault('before-seal','',0) for row in plan['files']: inspect(source,row['path'],row);inspect(target,base+'/objects/'+row['sha256'],dict(row,mode=0o400)) complete=dict(schema='turkos-evidence-archive-complete/v1',archiveId=archive_id,planSha256=archive_id,files=len(plan['files']),totalBytes=plan['totalBytes'],sourceFilesystem=source.device,archiveFilesystem=target.device,externalStorageVerified=separate) if target.exists(base+'/complete.json'):archive_plan(target,archive_id) else:target.publish(base+'/complete.json',encode(complete)) return dict(status='ARCHIVE_COPY_VERIFIED',archiveId=archive_id,completionSha256=digest(target.read(base+'/complete.json')),destination=str(target.path),files=len(plan['files']),totalBytes=plan['totalBytes'],copiedBytes=copied,resumedBytes=resumed,reusedFiles=reused,externalStorageVerified=separate,sourceDeletionImplemented=False) def archive_plan(tree,archive_id,completion_sha256=None): if not isinstance(archive_id,str)or not HEX.fullmatch(archive_id):raise ValueError('archive identity') base=PREFIX+'/'+archive_id;data=tree.read(base+'/plan.json');plan=decode(data) if digest(data)!=archive_id or encode(plan)!=data:raise ValueError('archive plan hash or encoding') if set(plan)!=set(['schema','storageClass','files','totalBytes','permissionMask','sourceFilesystem']):raise ValueError('archive plan fields') if plan['schema']!='turkos-evidence-archive/v1'or plan['storageClass']!='sealed-evidence'or plan['permissionMask']!=0o777:raise ValueError('archive schema') if not isinstance(plan['files'],list)or not 1<=len(plan['files'])<=MAX_FILES:raise ValueError('archive batch size') seen=set();total=0 for row in plan['files']: if set(row)!=set(['path','sha256','bytes','mode']):raise ValueError('archive row fields') parts(row['path']) if row['path'] in seen or row['path'].split('/')[0].startswith('.turkos-restore'):raise ValueError('duplicate or reserved restore path') if not isinstance(row['sha256'],str)or not HEX.fullmatch(row['sha256']):raise ValueError('archive object hash') if type(row['bytes'])is not int or not 0<=row['bytes']<=MAX_FILE_BYTES:raise ValueError('archive file size') if type(row['mode'])is not int or not 0<=row['mode']<=0o777 or not row['mode']&0o400:raise ValueError('archive permission mask') seen.add(row['path']);total+=row['bytes'] if total>MAX_TOTAL_BYTES:raise ValueError('archive bytes exceeded') if total!=plan['totalBytes']:raise ValueError('archive size accounting') if type(plan['sourceFilesystem'])is not int or plan['sourceFilesystem']<0:raise ValueError('source filesystem identity') completion=tree.read(base+'/complete.json') if completion_sha256 is not None: if not isinstance(completion_sha256,str)or not HEX.fullmatch(completion_sha256)or digest(completion)!=completion_sha256:raise ValueError('completion record hash') complete=decode(completion) original=complete.get('archiveFilesystem') if type(original)is not int or original<0:raise ValueError('original archive filesystem identity') expected=dict(schema='turkos-evidence-archive-complete/v1',archiveId=archive_id,planSha256=archive_id,files=len(plan['files']),totalBytes=total,sourceFilesystem=plan['sourceFilesystem'],archiveFilesystem=original,externalStorageVerified=plan['sourceFilesystem']!=original) if complete!=expected:raise ValueError('archive completion binding') for row in plan['files']:inspect(tree,base+'/objects/'+row['sha256'],dict(row,mode=0o400)) return plan,base def restore(destination,archive_id,output,*,completion_sha256,require_external=True,_fault=None): with Tree(destination)as archive: if not isinstance(completion_sha256,str)or not HEX.fullmatch(completion_sha256):raise ValueError('completion SHA-256 required') plan,base=archive_plan(archive,archive_id,completion_sha256) output=Path(output);parent=output.parent.resolve(strict=True);output=parent/output.name if output==archive.path or archive.path in output.parents:raise ValueError('restore must be outside the archive root') if require_external and os.stat(parent).st_dev==archive.device:raise ValueError('restore must cross filesystems') new=False try:os.mkdir(output,0o700);new=True except FileExistsError:pass with Tree(output)as target: separate=target.device!=archive.device if require_external and not separate:raise ValueError('restore must cross filesystems') marker=encode(dict(schema='turkos-evidence-restore/v1',archiveId=archive_id,completionSha256=completion_sha256)) if not new and target.read('.turkos-restore.json')!=marker:raise ValueError('existing output is not this restore job') target.publish('.turkos-restore.json',marker) with target.lock('.turkos-restore.lock'): copied=0;resumed=0;reused=0 for i,row in enumerate(plan['files']): path=row['path'];partial='.turkos-restore-work/'+str(i)+'-'+row['sha256'] if target.exists(path):inspect(target,path,row);reused+=1;continue result=copy_partial(archive,base+'/objects/'+row['sha256'],target,partial,row,_fault) inspect(target,partial,dict(row,mode=0o600));promote(target,partial,path,row['mode'],_fault) copied+=result['copiedBytes'];resumed+=result['resumedBytes'] for row in plan['files']:inspect(target,row['path'],row) result=dict(status='ARCHIVE_RESTORE_VERIFIED',archiveId=archive_id,completionSha256=completion_sha256,files=len(plan['files']),totalBytes=plan['totalBytes'],restoredAcrossFilesystems=separate,sourceDeletionImplemented=False) target.publish('.turkos-restore-complete.json',encode(result)) return dict(result,output=str(target.path),copiedBytes=copied,resumedBytes=resumed,reusedFiles=reused) def main(): p=argparse.ArgumentParser(description=__doc__);sub=p.add_subparsers(dest='command',required=True) q=sub.add_parser('plan');q.add_argument('--root',type=Path,required=True);q.add_argument('--selection',type=Path,required=True) q=sub.add_parser('backup');q.add_argument('--root',type=Path,required=True);q.add_argument('--selection',type=Path,required=True);q.add_argument('--destination',type=Path,required=True) q=sub.add_parser('restore');q.add_argument('--destination',type=Path,required=True);q.add_argument('--archive-id',required=True);q.add_argument('--completion-sha256',required=True);q.add_argument('--output',type=Path,required=True) a=p.parse_args() if a.command=='restore':result=restore(a.destination,a.archive_id,a.output,completion_sha256=a.completion_sha256) else: with Tree(a.selection.parent)as selected:selection=decode(selected.read(a.selection.name)) if a.command=='backup':result=backup(a.root,selection,a.destination) else: with Tree(a.root)as source:plan=selection_plan(source,selection) result=dict(status='ARCHIVE_PLAN_VERIFIED',archiveId=digest(encode(plan)),plan=plan,externalStorageVerified=False) print(json.dumps(result,ensure_ascii=False)) if __name__=='__main__':main()