"""Operator-only archive scan, no Docker socket mounted into the scanner or any app.""" import collections import datetime import json import os from pathlib import Path import socket import subprocess import time import sys ROOT=Path(__file__).resolve().parents[1] SCANNER='aquasec/trivy:0.67.2@sha256:e2b22eac59c02003d8749f5b8d9bd073b62e30fefaef5b7c8371204e0a4b0c08' def compact(raw): findings=[] for group in raw.get('Results',[]): for v in group.get('Vulnerabilities',[]): findings.append({k:v.get(k,'') for k in ['VulnerabilityID','PkgName','InstalledVersion','FixedVersion','Severity']}) return {'artifact':raw.get('ArtifactName'),'artifact_type':raw.get('ArtifactType'), 'severity_counts':dict(collections.Counter(x['Severity'] for x in findings)),'findings':findings} COLUMNS=['VulnerabilityID','PkgName','InstalledVersion','FixedVersion','Severity'] def save(result): result['findings_columns']=COLUMNS for row in result['images']: if row.get('findings') and isinstance(row['findings'][0],dict): row['findings']=[[v.get(k,'') for k in COLUMNS] for v in row['findings']] previous=result.get('previous_image_scans',[]) result['previous_image_scans']=[{k:v for k,v in row.items() if k in ['image','image_id','severity_counts']} for row in previous] old=result.get('before_application') if old and old.get('findings') and isinstance(old['findings'][0],dict): old['findings']=[[v.get(k,'') for k in COLUMNS] for v in old['findings']] path=ROOT/'evidence/image-scans.json' temporary=path.with_suffix('.tmp') temporary.write_text(json.dumps(result,ensure_ascii=False,separators=(',',':'))+'\n') temporary.replace(path) def main(): folder=ROOT/'build/scans';folder.mkdir(parents=True,exist_ok=True) cache=ROOT/'build/trivy-cache';cache.mkdir(exist_ok=True) cfg=json.loads((ROOT/'compose.yaml').read_text()) images=sorted({x['image'] for x in cfg['services'].values()}) result={'scanner':SCANNER,'date_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(), 'method':'Local docker save archives, vuln scanner only, no scanner Docker socket; official GHCR vulnerability DB. Local isolated lab, not a penetration-test certification.','images':[]} existing=ROOT/'evidence/image-scans.json' if '--resume' in sys.argv and existing.exists():result=json.loads(existing.read_text()) obsolete=[r for r in result['images'] if r['image'] not in images] result.setdefault('previous_image_scans',[]).extend(obsolete) result['images']=[r for r in result['images'] if r['image'] in images] before=folder/'before.json' if before.exists():result['before_application']=compact(json.loads(before.read_text())) for index,image in enumerate(images): image_id=subprocess.check_output(['docker','image','inspect',image,'--format','{{.Id}}'],text=True).strip() if any(r['image']==image and r.get('image_id')==image_id for r in result['images']):continue previous=[r for r in result['images'] if r['image']==image] result.setdefault('previous_image_scans',[]).extend(previous) result['images']=[r for r in result['images'] if r['image']!=image] archive=folder/('image-'+str(index)+'.tar') subprocess.run(['docker','save','-o',str(archive),image],check=True) with archive.open('rb') as sync:os.fsync(sync.fileno()) time.sleep(.3) args=['docker','run','--rm','--memory','512m','--cpus','1'] for host in ['ghcr.io','pkg-containers.githubusercontent.com']: args+=['--add-host',host+':'+socket.gethostbyname(host)] args+=['-v',str(folder)+':/scan:ro','-v',str(cache)+':/root/.cache/trivy',SCANNER, 'image','--db-repository','ghcr.io/aquasecurity/trivy-db:2','--scanners','vuln','--input','/scan/'+archive.name,'--format','json'] with open(folder/'current.scan','w') as out,open(folder/'scanner.log','w') as err: subprocess.run(args,stdout=out,stderr=err,check=True) row=compact(json.loads((folder/'current.scan').read_text()));row['image']=image;row['image_id']=image_id result['images'].append(row) save(result) print(image.split('@')[0],row['severity_counts'],flush=True) archive.unlink() save(result) print('PASS: all declared unique runtime images scanned; triage still required.',flush=True) if __name__=='__main__':main()