import json,re,base64,urllib.parse,subprocess,hashlib,os,tempfile
from lxml import etree
D=json.load(open('work/scratch/saml-all.json')); seen={}
for x in D:
 req=next((b['message'] for b in x['blobs'] if b['kind']=='request'),''); body=req.split('\r\n\r\n',1)[-1]; q=urllib.parse.parse_qs(body,keep_blank_values=True)
 try:xml=base64.b64decode(q.get('SAMLResponse',[''])[0]+'==='); r=etree.fromstring(xml)
 except:continue
 certs=r.xpath('//*[local-name()="X509Certificate"]/text()')
 for c in certs:
  try:
   der=base64.b64decode(''.join(c.split())); h=hashlib.sha256(der).hexdigest()[:12]
   if h in seen:continue
   open('/tmp/c.der','wb').write(der); z=subprocess.check_output(['openssl','x509','-inform','DER','-in','/tmp/c.der','-noout','-subject','-issuer','-serial'],stderr=subprocess.DEVNULL,text=True).strip().replace('\n',' | ')
   seen[h]=(x['exchange_id'],x['agent'],z)
  except:pass
for h,v in seen.items(): print(h,*v,sep='\t')
