96 lines
6.6 KiB
Python
96 lines
6.6 KiB
Python
"""Read protected evidence. Export counts/classification only, never captured values."""
|
|
from pathlib import Path
|
|
from datetime import datetime,timezone
|
|
from urllib.parse import urlparse,parse_qs,unquote
|
|
import json,hashlib,re,collections
|
|
OUT=Path(__file__).resolve().parent;ROOT=OUT.parents[1]
|
|
incident=Path(json.loads((OUT/'C132-private-location.json').read_text(encoding='utf-8-sig'))['private_directory'])
|
|
manifest=json.loads((incident/'evidence-manifest-private.json').read_text(encoding='utf-8-sig'))
|
|
metrics=collections.defaultdict(lambda:collections.Counter());times=[];methods=collections.Counter();families=collections.Counter();auth_ids=set();secrets=[];records=0;body_states=collections.Counter();mfa_times=[]
|
|
markers={'[REDACTED]','[UNSERIALIZABLE]','[TRUNCATED]','********','**********','[redacted]'}
|
|
def state(v):
|
|
if v is None or v=='' or v==[] or v=={}:return 'empty'
|
|
if isinstance(v,str) and (v in markers or all(c=='*' for c in v)):return 'redacted'
|
|
if isinstance(v,list) and all(state(x) in ['empty','redacted'] for x in v):return 'redacted'
|
|
return 'unredacted'
|
|
def leaf_values(v):
|
|
if isinstance(v,dict):
|
|
for x in v.values():yield from leaf_values(x)
|
|
elif isinstance(v,list):
|
|
for x in v:yield from leaf_values(x)
|
|
elif isinstance(v,str):yield v
|
|
def walk(v,path=()):
|
|
if isinstance(v,dict):
|
|
for k,x in v.items():yield path+(str(k),),x;yield from walk(x,path+(str(k),))
|
|
elif isinstance(v,list):
|
|
for i,x in enumerate(v):yield from walk(x,path+(str(i),))
|
|
elif isinstance(v,str) and v[:1] in ['{','['] and len(v)<8000000:
|
|
try:decoded=json.loads(v)
|
|
except ValueError:return
|
|
yield from walk(decoded,path+('embedded-json',))
|
|
envsecrets={}
|
|
for line in (ROOT/'.env').read_text(encoding='utf-8-sig').splitlines():
|
|
if '=' not in line or line.lstrip().startswith('#'):continue
|
|
k,v=line.split('=',1);v=v.strip().strip('"').strip("'")
|
|
if re.search(r'(?:PASSWORD|SECRET|TOKEN|PRIVATE_KEY|APP_KEY|API_KEY)$',k.strip()) and len(v)>=8:envsecrets[k.strip()]=v
|
|
config_matches=collections.Counter();headers=['cookie','set-cookie','authorization','proxy-authorization','x-xsrf-token','x-csrf-token']
|
|
for f in manifest['files']:
|
|
p=incident/'diagnostics'/f['name'];raw=p.read_bytes();assert hashlib.sha256(raw).hexdigest()==f['sha256']
|
|
if not re.fullmatch(r'[0-9A-HJKMNP-TV-Z]{26}\.json',f['name']):continue
|
|
d=json.loads(raw);meta=d.get('__meta') or {};records+=1;times.append(meta.get('timestamp'));methods[meta.get('method','unknown')]+=1
|
|
route=urlparse(str(meta.get('url',''))).path
|
|
family=next((family for prefix,family in [('/management','management'),('/perfis','profile_administration'),('/dashboard','dashboard'),('/login','login'),('/two-factor-challenge','MFA_challenge'),('/user/two-factor','MFA_setup'),('/settings','settings'),('/minhas-oportunidades','opportunities')] if route.startswith(prefix)),'other')
|
|
families[family]+=1
|
|
http=d.get('http') or {}
|
|
for bag in ['requestHeaders','responseHeaders']:
|
|
for k,v in (http.get(bag) or {}).items():
|
|
lower=str(k).lower()
|
|
if lower in headers:
|
|
metrics['header:'+lower][state(v)]+=1
|
|
if state(v)=='unredacted':secrets.append({'kind':'header:'+lower,'value':v,'entry_id':meta.get('id'),'timestamp':meta.get('timestamp')})
|
|
for key in ['requestBody','responseBody']:
|
|
if isinstance(http.get(key),dict):body_states[key+':'+str(http[key].get('status','unknown'))]+=1
|
|
# Fortify returns recovery codes as a JSON array, with no sensitive field name to trigger generic key redaction.
|
|
if route=='/user/two-factor-recovery-codes':
|
|
response=http.get('responseBody') or {};value=response.get('value') if isinstance(response,dict) else None
|
|
if isinstance(value,str):
|
|
try:value=json.loads(value)
|
|
except ValueError:pass
|
|
if isinstance(value,list):
|
|
for code in value:
|
|
metrics['MFA_recovery_code'][state(code)]+=1
|
|
if state(code)=='unredacted':secrets.append({'kind':'MFA_recovery_code','value':code,'entry_id':meta.get('id'),'timestamp':meta.get('timestamp')})
|
|
props=d.get('propValues') or {}
|
|
user=(props.get('auth') or {}).get('user') if isinstance(props,dict) and isinstance(props.get('auth'),dict) else None
|
|
if isinstance(user,dict) and isinstance(user.get('id'),int):auth_ids.add(user['id'])
|
|
for path,v in walk(d):
|
|
last=path[-1].lower().replace('-','_')
|
|
key=last.replace('_','')
|
|
kind=None
|
|
if key in ['password','passwordconfirmation','currentpassword']:kind='password'
|
|
elif key in ['token','accesstoken','refreshtoken','_token','apikey','clientsecret']:kind='token_or_secret'
|
|
elif key in ['secret','secretkey','twofactorsecret','totpsecret','mfasecret']:kind='MFA_or_other_secret'
|
|
elif key in ['recoverycode','recoverycodes','twofactorrecoverycodes']:kind='MFA_recovery_code'
|
|
elif last=='code' and family=='MFA_challenge' and 'requestBody' in path:kind='MFA_one_time_code'
|
|
if kind:
|
|
metrics[kind][state(v)]+=1
|
|
if state(v)=='unredacted':
|
|
secrets.append({'kind':kind,'value':v,'entry_id':meta.get('id'),'timestamp':meta.get('timestamp')})
|
|
if kind=='MFA_one_time_code':mfa_times.append(meta.get('timestamp'))
|
|
if isinstance(v,str) and 'otpauth://' in v:
|
|
metrics['otpauth_URI']['unredacted']+=1;secrets.append({'kind':'otpauth_URI','value':v,'entry_id':meta.get('id'),'timestamp':meta.get('timestamp')})
|
|
strings=list(leaf_values(d))
|
|
for name,value in envsecrets.items():
|
|
if any(value in s or json.dumps(value)[1:-1] in s for s in strings):config_matches[name]+=1
|
|
times=sorted(t for t in times if isinstance(t,str));mfa_times=sorted(t for t in mfa_times if isinstance(t,str))
|
|
# Potential values remain solely in the already restricted incident directory for usability assessment.
|
|
(incident/'secret-candidates-private.json').write_text(json.dumps(secrets,ensure_ascii=False),encoding='utf-8')
|
|
summary={'at':datetime.now(timezone.utc).isoformat(),'case':'C132','diagnostic_records_examined':records,'preserved_files':len(manifest['files']),
|
|
'retained_first_timestamp':times[0] if times else None,'retained_last_timestamp':times[-1] if times else None,
|
|
'retained_window_not_full_exposure_period':True,'methods':dict(methods),'route_families':dict(families),'authenticated_user_ids_in_retained_props':sorted(auth_ids),
|
|
'sensitive_field_classification':{k:dict(v) for k,v in sorted(metrics.items())},'body_capture_states':dict(body_states),
|
|
'active_config_secret_exact_matches':dict(config_matches),'MFA_code_first_timestamp':mfa_times[0] if mfa_times else None,'MFA_code_last_timestamp':mfa_times[-1] if mfa_times else None,
|
|
'unredacted_candidate_occurrences':len(secrets),'values_exported':False,'candidate_values_retained_only_in_restricted_evidence':True,
|
|
'usability_assessment_pending':bool(secrets)}
|
|
(OUT/'C132-local-analysis.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf-8');print(json.dumps(summary,ensure_ascii=True))
|