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_subs.py — sau khi login vao portal.azure.com: bat ARM Bearer token tu traffic cua portal
|
| 3 |
+
# roi goi thang API management.azure.com/subscriptions -> lay day du: ten, ID, state (Enabled/
|
| 4 |
+
# Disabled/Warned/PastDue), offer/quota, spending limit, tenant, role. Tra (list[(head,body)], status).
|
| 5 |
+
import json, time, base64, urllib.request, urllib.error
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _tid(t):
|
| 9 |
+
"""Doc tenant id (tid) tu JWT ARM token (khong verify, chi de phan biet tenant)."""
|
| 10 |
+
try:
|
| 11 |
+
p = t.split(".")[1]; p += "=" * (-len(p) % 4)
|
| 12 |
+
return json.loads(base64.urlsafe_b64decode(p)).get("tid", "?")
|
| 13 |
+
except Exception:
|
| 14 |
+
return "?"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _grab_token(page, secs=55):
|
| 18 |
+
"""Bat 'Authorization: Bearer <JWT>' tu request DAU TIEN toi management.azure.com."""
|
| 19 |
+
tok = {"v": None}
|
| 20 |
+
|
| 21 |
+
def on_req(req):
|
| 22 |
+
if tok["v"]:
|
| 23 |
+
return
|
| 24 |
+
try:
|
| 25 |
+
if "management.azure.com" in req.url:
|
| 26 |
+
a = ""
|
| 27 |
+
try:
|
| 28 |
+
a = req.headers.get("authorization") or ""
|
| 29 |
+
except Exception:
|
| 30 |
+
pass
|
| 31 |
+
if not a.lower().startswith("bearer "):
|
| 32 |
+
try:
|
| 33 |
+
a = (req.all_headers() or {}).get("authorization", "") or ""
|
| 34 |
+
except Exception:
|
| 35 |
+
a = ""
|
| 36 |
+
if a.lower().startswith("bearer "):
|
| 37 |
+
tok["v"] = a.split(" ", 1)[1]
|
| 38 |
+
except Exception:
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
page.on("request", on_req)
|
| 42 |
+
try:
|
| 43 |
+
# mo blade Subscriptions -> BUOC portal goi ARM (chac chan co token)
|
| 44 |
+
try:
|
| 45 |
+
page.goto("https://portal.azure.com/#view/Microsoft_Azure_Billing/SubscriptionsBladeV2",
|
| 46 |
+
timeout=60000)
|
| 47 |
+
except Exception:
|
| 48 |
+
pass
|
| 49 |
+
dl = time.time() + secs
|
| 50 |
+
while time.time() < dl and not tok["v"]:
|
| 51 |
+
page.wait_for_timeout(700)
|
| 52 |
+
finally:
|
| 53 |
+
try:
|
| 54 |
+
page.remove_listener("request", on_req)
|
| 55 |
+
except Exception:
|
| 56 |
+
pass
|
| 57 |
+
return tok["v"]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _arm(token, path):
|
| 61 |
+
r = urllib.request.Request("https://management.azure.com" + path,
|
| 62 |
+
headers={"Authorization": "Bearer " + token})
|
| 63 |
+
return json.loads(urllib.request.urlopen(r, timeout=30).read().decode("utf-8", "ignore"))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def portal_login(page, cfg, get_code=None, secs=140):
|
| 67 |
+
"""Da co phien MSA (dang o inbox). Mo portal.azure.com, xu ly trang AAD
|
| 68 |
+
'Sign in to continue to Microsoft Azure': dien email -> SSO qua MSA (khong can code)
|
| 69 |
+
-> portal load -> sniffer o run_login bat ARM token. Tra True neu co token."""
|
| 70 |
+
email = cfg.get("email", "") or ""
|
| 71 |
+
dbg = bool(cfg.get("_debug_shots"))
|
| 72 |
+
try:
|
| 73 |
+
page.goto("https://portal.azure.com/", timeout=60000)
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
dl = time.time() + secs
|
| 77 |
+
did_email = 0
|
| 78 |
+
did_code = 0
|
| 79 |
+
forced_blade = False
|
| 80 |
+
signin_retry = 0
|
| 81 |
+
while time.time() < dl:
|
| 82 |
+
if cfg.get("_arm_token"):
|
| 83 |
+
return True
|
| 84 |
+
page.wait_for_timeout(1500)
|
| 85 |
+
url = page.url or ""
|
| 86 |
+
try:
|
| 87 |
+
txt = page.inner_text("body") or ""
|
| 88 |
+
except Exception:
|
| 89 |
+
txt = ""
|
| 90 |
+
low = txt.lower()
|
| 91 |
+
if dbg:
|
| 92 |
+
print(" [portal] url=%s | txt=%r" % (url[:68], txt[:70]))
|
| 93 |
+
if cfg.get("_arm_token"):
|
| 94 |
+
return True
|
| 95 |
+
|
| 96 |
+
# post_request_failed / sign-in failed (form_post cross-site) -> retry lai portal (hay transient)
|
| 97 |
+
if "signinfailed" in url.lower() or "post_request_failed" in low or "sign-in failed" in low:
|
| 98 |
+
if signin_retry < 3:
|
| 99 |
+
signin_retry += 1
|
| 100 |
+
did_email = 0; forced_blade = False
|
| 101 |
+
if dbg:
|
| 102 |
+
print(" [portal] SigninFailed -> retry portal lan", signin_retry)
|
| 103 |
+
try:
|
| 104 |
+
page.goto("https://portal.azure.com/", timeout=60000)
|
| 105 |
+
except Exception:
|
| 106 |
+
pass
|
| 107 |
+
page.wait_for_timeout(3000); continue
|
| 108 |
+
else:
|
| 109 |
+
if dbg:
|
| 110 |
+
print(" [portal] SigninFailed qua %d lan -> bo cuoc" % signin_retry)
|
| 111 |
+
return False
|
| 112 |
+
|
| 113 |
+
on_aad = "login.microsoftonline.com" in url or "login.live.com" in url or "login.microsoft.com" in url
|
| 114 |
+
|
| 115 |
+
# 1) tile "chon tai khoan" co san email -> click
|
| 116 |
+
if on_aad:
|
| 117 |
+
try:
|
| 118 |
+
for sel in ("[data-test-id='%s']" % email, "[title='%s']" % email,
|
| 119 |
+
"div.table[role='button']", "div[role='button'] small"):
|
| 120 |
+
el = page.query_selector(sel)
|
| 121 |
+
if el and email.lower() in ((el.inner_text() or "").lower() + (el.get_attribute("title") or "").lower()):
|
| 122 |
+
el.click(); page.wait_for_timeout(2500); break
|
| 123 |
+
except Exception:
|
| 124 |
+
pass
|
| 125 |
+
|
| 126 |
+
# 2) o nhap email (loginfmt) -> Next
|
| 127 |
+
if on_aad and did_email < 3:
|
| 128 |
+
try:
|
| 129 |
+
inp = page.query_selector("input[type=email], input[name=loginfmt]")
|
| 130 |
+
if inp and inp.is_visible():
|
| 131 |
+
inp.fill(email); page.wait_for_timeout(400)
|
| 132 |
+
nx = page.query_selector("#idSIButton9, input[type=submit], button[type=submit]")
|
| 133 |
+
if nx:
|
| 134 |
+
nx.click()
|
| 135 |
+
did_email += 1
|
| 136 |
+
if dbg:
|
| 137 |
+
print(" [portal] -> dien email lan", did_email)
|
| 138 |
+
page.wait_for_timeout(3000); continue
|
| 139 |
+
except Exception:
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
# 3) KMSI 'stay signed in?' -> Yes. Nhan dien KHONG phu thuoc ngon ngu: co #KmsiCheckboxField.
|
| 143 |
+
if on_aad:
|
| 144 |
+
try:
|
| 145 |
+
is_kmsi = ("signed in?" in low or "stay signed" in low or "kmsi" in url.lower()
|
| 146 |
+
or page.query_selector("#KmsiCheckboxField") is not None)
|
| 147 |
+
if is_kmsi:
|
| 148 |
+
y = page.query_selector("#idSIButton9, input[value='Yes'], button[type=submit]")
|
| 149 |
+
if y:
|
| 150 |
+
y.click()
|
| 151 |
+
if dbg:
|
| 152 |
+
print(" [portal] KMSI -> Yes")
|
| 153 |
+
page.wait_for_timeout(2500); continue
|
| 154 |
+
except Exception:
|
| 155 |
+
pass
|
| 156 |
+
|
| 157 |
+
# 4) hiem: doi nhap code (thuong SSO khong can vi da co phien MSA)
|
| 158 |
+
if on_aad and get_code and did_code < 2 and ("enter code" in low or "verification code" in low or "security code" in low or "code we" in low):
|
| 159 |
+
try:
|
| 160 |
+
c = get_code(page, cfg)
|
| 161 |
+
if c:
|
| 162 |
+
inp = page.query_selector("input[name=otc], input[type=tel], input[inputmode='numeric'], input[type=text]")
|
| 163 |
+
if inp:
|
| 164 |
+
inp.fill(c); page.wait_for_timeout(300)
|
| 165 |
+
nx = page.query_selector("#idSIButton9, input[type=submit], button[type=submit]")
|
| 166 |
+
if nx:
|
| 167 |
+
nx.click()
|
| 168 |
+
did_code += 1; page.wait_for_timeout(3000); continue
|
| 169 |
+
except Exception:
|
| 170 |
+
pass
|
| 171 |
+
|
| 172 |
+
# 5) da o portal nhung chua co token -> ep mo blade Subscriptions cho portal goi ARM
|
| 173 |
+
if url.startswith("https://portal.azure.com") and not forced_blade:
|
| 174 |
+
forced_blade = True
|
| 175 |
+
try:
|
| 176 |
+
page.goto("https://portal.azure.com/#view/Microsoft_Azure_Billing/SubscriptionsBladeV2", timeout=45000)
|
| 177 |
+
except Exception:
|
| 178 |
+
pass
|
| 179 |
+
page.wait_for_timeout(3500)
|
| 180 |
+
return bool(cfg.get("_arm_token"))
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _clean_text(raw, maxlines=45):
|
| 184 |
+
"""Bo icon (private-use U+E000..U+F8FF), dong ngan/rac -> giu dong co nghia (moi ngon ngu)."""
|
| 185 |
+
out = []
|
| 186 |
+
for ln in (raw or "").splitlines():
|
| 187 |
+
s = ln.strip()
|
| 188 |
+
if len(s) < 3:
|
| 189 |
+
continue
|
| 190 |
+
# bo dong toan ky tu icon
|
| 191 |
+
letters = [c for c in s if not (0xE000 <= ord(c) <= 0xF8FF)]
|
| 192 |
+
if len("".join(letters).strip()) < 3:
|
| 193 |
+
continue
|
| 194 |
+
s = "".join(letters).strip()
|
| 195 |
+
if s not in out:
|
| 196 |
+
out.append(s)
|
| 197 |
+
if len(out) >= maxlines:
|
| 198 |
+
break
|
| 199 |
+
return "\n".join(out)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _portal_notice(page, cfg):
|
| 203 |
+
"""KHONG vao duoc ben trong portal (acc cu / sub bi xoa) -> chup thong bao NGOAI + phan loai.
|
| 204 |
+
Tra (head, body, short_status)."""
|
| 205 |
+
url_now = ""
|
| 206 |
+
notice = ""
|
| 207 |
+
try:
|
| 208 |
+
url_now = page.url or ""
|
| 209 |
+
except Exception:
|
| 210 |
+
pass
|
| 211 |
+
try:
|
| 212 |
+
notice = _clean_text(page.inner_text("body") or "")
|
| 213 |
+
except Exception:
|
| 214 |
+
pass
|
| 215 |
+
low = (notice + " " + url_now).lower()
|
| 216 |
+
# phan loai KHONG phu thuoc ngon ngu: uu tien dau hieu URL + tu khoa pho bien
|
| 217 |
+
if "signinfailed" in low or "post_request" in low or "ue_" in low.replace("/", "_"):
|
| 218 |
+
reason = "KHONG dang nhap duoc portal Azure (sign-in failed / token bi chan)"
|
| 219 |
+
elif "aad.portal" in url_now or "login.microsoftonline" in url_now or "login.live.com" in url_now:
|
| 220 |
+
reason = "KET o trang dang nhap Azure — acc khong co directory/subscription de vao portal"
|
| 221 |
+
elif "no subscription" in low or "don't have any sub" in low or "no active sub" in low or "reactivate" in low:
|
| 222 |
+
reason = "Portal bao KHONG co subscription (co the sub da bi xoa / inactive)"
|
| 223 |
+
else:
|
| 224 |
+
reason = "KHONG vao duoc ben trong portal (acc cu / sub bi xoa — chi hien thong bao ngoai)"
|
| 225 |
+
head = "========== PORTAL: KHONG doc duoc subscription =========="
|
| 226 |
+
body = ("Ly do : %s\nURL : %s\narm req da thay: %s\n\n"
|
| 227 |
+
"--- Noi dung trang portal luc do (thong bao ngoai, giup xac dinh trang thai) ---\n%s") % (
|
| 228 |
+
reason, url_now[:130], cfg.get("_arm_req_count", 0), notice or "(trang trong)")
|
| 229 |
+
return head, body, reason
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def read_azure_subscriptions(page, cfg):
|
| 233 |
+
"""Tra (mails, status). mails = list[(head, body)] de export_result ghi txt.
|
| 234 |
+
- [] -> vao portal OK nhung 0 subscription.
|
| 235 |
+
- [...] -> co subscription (day du) HOAC 1 muc thong bao ngoai (acc cu/khong vao duoc).
|
| 236 |
+
Doc subscription qua API JSON (management.azure.com) nen KHONG phu thuoc ngon ngu."""
|
| 237 |
+
token = cfg.get("_arm_token")
|
| 238 |
+
if not token:
|
| 239 |
+
# chua bat duoc luc login -> mo blade Subscriptions + reload de EP portal goi ARM (sniffer o run_login bat)
|
| 240 |
+
try:
|
| 241 |
+
page.goto("https://portal.azure.com/#view/Microsoft_Azure_Billing/SubscriptionsBladeV2", timeout=60000)
|
| 242 |
+
except Exception:
|
| 243 |
+
pass
|
| 244 |
+
dl = time.time() + 55
|
| 245 |
+
did = False
|
| 246 |
+
while time.time() < dl and not cfg.get("_arm_token"):
|
| 247 |
+
page.wait_for_timeout(1000)
|
| 248 |
+
if not cfg.get("_arm_token") and not did and (dl - time.time()) < 32:
|
| 249 |
+
did = True
|
| 250 |
+
try:
|
| 251 |
+
page.reload()
|
| 252 |
+
except Exception:
|
| 253 |
+
pass
|
| 254 |
+
token = cfg.get("_arm_token")
|
| 255 |
+
if not token:
|
| 256 |
+
# KHONG bat duoc token -> khong vao duoc ben trong portal. Chup thong bao ngoai (acc cu / sub xoa).
|
| 257 |
+
head, body, reason = _portal_notice(page, cfg)
|
| 258 |
+
print(" [azure] KHONG vao duoc portal:", reason)
|
| 259 |
+
return [(head, body)], "PORTAL: " + reason
|
| 260 |
+
# DWELL: cho portal liet ke het cac directory/tenant — moi tenant portal lay 1 token ARM RIENG.
|
| 261 |
+
# Gom het token roi query /subscriptions tung cai -> khong bo sot sub o tenant khac (fix "0 sub" sai).
|
| 262 |
+
try:
|
| 263 |
+
page.goto("https://portal.azure.com/#view/Microsoft_Azure_Billing/SubscriptionsBladeV2", timeout=45000)
|
| 264 |
+
except Exception:
|
| 265 |
+
pass
|
| 266 |
+
for _ in range(9):
|
| 267 |
+
page.wait_for_timeout(1300)
|
| 268 |
+
|
| 269 |
+
tokens = list(cfg.get("_arm_tokens") or [])
|
| 270 |
+
if token not in tokens:
|
| 271 |
+
tokens.insert(0, token)
|
| 272 |
+
# moi tenant chi giu 1 token (token moi nhat cua tenant do)
|
| 273 |
+
by_tenant = {}
|
| 274 |
+
for t in tokens:
|
| 275 |
+
by_tenant[_tid(t)] = t
|
| 276 |
+
|
| 277 |
+
seen = {}
|
| 278 |
+
http_errs = []
|
| 279 |
+
for t in by_tenant.values():
|
| 280 |
+
try:
|
| 281 |
+
for s in _arm(t, "/subscriptions?api-version=2020-01-01").get("value", []) or []:
|
| 282 |
+
sid = s.get("subscriptionId")
|
| 283 |
+
if sid and sid not in seen:
|
| 284 |
+
seen[sid] = s
|
| 285 |
+
except urllib.error.HTTPError as e:
|
| 286 |
+
http_errs.append(str(e.code))
|
| 287 |
+
except Exception:
|
| 288 |
+
pass
|
| 289 |
+
subs = list(seen.values())
|
| 290 |
+
|
| 291 |
+
# dem tenant (tu token + /tenants)
|
| 292 |
+
tenset = set(k for k in by_tenant.keys() if k and k != "?")
|
| 293 |
+
try:
|
| 294 |
+
for tn in _arm(token, "/tenants?api-version=2022-12-01").get("value", []) or []:
|
| 295 |
+
if tn.get("tenantId"):
|
| 296 |
+
tenset.add(tn.get("tenantId"))
|
| 297 |
+
except Exception:
|
| 298 |
+
pass
|
| 299 |
+
|
| 300 |
+
if not subs:
|
| 301 |
+
extra = (" | ARM loi HTTP %s" % ",".join(sorted(set(http_errs)))) if http_errs else ""
|
| 302 |
+
return [], ("PORTAL OK — 0 SUBSCRIPTION (quet %d tenant / %d token)%s" % (len(tenset), len(by_tenant), extra))
|
| 303 |
+
|
| 304 |
+
en = sum(1 for s in subs if s.get("state") == "Enabled")
|
| 305 |
+
out = []
|
| 306 |
+
for s in subs:
|
| 307 |
+
st = s.get("state", "?")
|
| 308 |
+
pol = s.get("subscriptionPolicies", {}) or {}
|
| 309 |
+
head = "%s [%s]" % (s.get("displayName", "(khong ten)"), st)
|
| 310 |
+
body = ("Subscription ID : %s\n"
|
| 311 |
+
"Trang thai : %s\n"
|
| 312 |
+
"Offer / Quota : %s\n"
|
| 313 |
+
"Spending limit : %s\n"
|
| 314 |
+
"Tenant ID : %s\n"
|
| 315 |
+
"Authorization : %s") % (
|
| 316 |
+
s.get("subscriptionId", "?"), st, pol.get("quotaId", "?"),
|
| 317 |
+
pol.get("spendingLimit", "?"), s.get("tenantId", "?"), s.get("authorizationSource", "?"))
|
| 318 |
+
out.append((head, body))
|
| 319 |
+
status = "PORTAL OK — %d SUBSCRIPTION (%d Enabled | %d khac)" % (len(subs), en, len(subs) - en)
|
| 320 |
+
return out, status
|