"""Explainable red-flag checks for a single URL, shared by training (Python) and the Space (space/urlflags.js). Everything here is deliberately hand-rolled (no urllib, no public-suffix library) so the JavaScript port can match it exactly. The lists (brands, TLDs, hosting providers...) live in url_spec.json, which both ports read. analyze(url) -> {"url": normalized url, "parts": {...}, "flags": [{id, label, severity, why, spans}]} Spans are [start, end) offsets into the normalized url, for highlighting. """ import json import os import re SPEC = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "url_spec.json"), encoding="utf-8")) FLAG_IDS = [f["id"] for f in SPEC["flags"]] META = {f["id"]: f for f in SPEC["flags"]} SECOND = set(SPEC["second_level"]) HOSTING = sorted(SPEC["hosting_suffixes"], key=lambda s: -s.count(".")) FREE, DDNS, SHORT = SPEC["free_hosting"], SPEC["dynamic_dns"], set(SPEC["shorteners"]) RISKY = set(SPEC["risky_tlds"]) EXEC, ARCH = set(SPEC["exec_ext"]), set(SPEC["archive_ext"]) DBL = re.compile(r"\.(%s)\.(%s)$" % ("|".join(SPEC["doc_ext"]), "|".join(SPEC["dbl_exec_ext"]))) SENS = set(SPEC["sensitive_words"]) CMS = SPEC["cms_paths"] LEET = SPEC["leet"] BRANDS = SPEC["brands"] WORD_BRANDS = set(SPEC.get("word_brands", [])) CONFUSABLE = SPEC["confusables"] OFFICIAL = sorted({d for ds in BRANDS.values() for d in ds}) EMBED = re.compile(r"(?:^|/)((?:www\.)?[a-z0-9\-]{2,}\.(?:%s)(?:\.[a-z]{2})?)(?=/|$)" % "|".join(SPEC["common_tlds"])) EMAIL = re.compile(r"[a-z0-9._+\-]+(?:@|%40)[a-z0-9.\-]+\.[a-z]{2,}") TOKEN = re.compile(r"[a-z0-9]+") PCT = re.compile(r"%[0-9a-f]{2}", re.I) SCHEME = re.compile(r"^([a-zA-Z][a-zA-Z0-9+.\-]*):") IPV4 = re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}$") PORT = re.compile(r":(\d*)$") REDIR = re.compile(r"^(?:https?:)?//([^/?#&:@]+)|^www\.([^/?#&:@]+)") def refang(s): """Undo common defanging (hxxp, [.], (dot), [:]) and drop whitespace.""" s = re.sub(r"\s+", "", s) s = re.sub(r"hxxp", "http", s, flags=re.I) s = re.sub(r"\[\.\]|\(\.\)|\{\.\}|\[dot\]|\(dot\)", ".", s, flags=re.I) s = s.replace("[://]", "://").replace("[:]", ":") s = re.sub(r"\[@\]|\[at\]", "@", s, flags=re.I) return s def parse(u): r = {"scheme": "", "special": False, "auth_start": 0, "userinfo": "", "host": "", "host_start": 0, "port": "", "path": "", "path_start": 0, "query": "", "query_start": 0, "fragment": "", "frag_start": 0} m = SCHEME.match(u) i = 0 if m and m.group(1).lower() in ("data", "javascript", "vbscript"): r["scheme"], r["special"] = m.group(1).lower(), True r["path"], r["path_start"] = u[m.end():], m.end() return r if m and u[m.end():m.end() + 2] == "//": r["scheme"], i = m.group(1).lower(), m.end() + 2 elif u[:2] == "//": i = 2 r["auth_start"] = i j = i while j < len(u) and u[j] not in "/?#\\": j += 1 auth = u[i:j] at = auth.rfind("@") hs = i if at >= 0: r["userinfo"] = auth[:at] hs = i + at + 1 hp = u[hs:j] pm = PORT.search(hp) host = hp if pm: r["port"] = pm.group(1) host = hp[:pm.start()] r["host"], r["host_start"] = host.lower(), hs k = j while k < len(u) and u[k] not in "?#": k += 1 r["path"], r["path_start"] = u[j:k], j if k < len(u) and u[k] == "?": q = k + 1 while k < len(u) and u[k] != "#": k += 1 r["query"], r["query_start"] = u[q:k], q if k < len(u) and u[k] == "#": r["fragment"], r["frag_start"] = u[k + 1:], k + 1 return r def labels_of(host): return [x for x in host.split(".") if x] def ip_kind(host): """'' (not an IP), 'private', 'public' or 'obfuscated' (decimal / hex / octal forms).""" if IPV4.match(host): o = [int(x) for x in host.split(".")] if any(x > 255 for x in o): return "obfuscated" if o[0] in (10, 127, 0) or (o[0] == 192 and o[1] == 168) or (o[0] == 172 and 16 <= o[1] <= 31) or \ (o[0] == 169 and o[1] == 254): return "private" return "public" if re.match(r"^\d{8,10}$", host) or re.match(r"^0x[0-9a-f]{6,8}$", host): return "obfuscated" parts = host.split(".") if len(parts) == 4 and all(re.match(r"^(0x[0-9a-f]+|\d+)$", p) for p in parts) and \ any(p.startswith("0x") or (len(p) > 1 and p[0] == "0") for p in parts): return "obfuscated" return "" def split_host(host): """-> (registrable domain, public suffix, subdomain labels).""" labels = labels_of(host) if not labels: return "", "", [] if len(labels) >= 3 and ".".join(labels[-2:]) in SECOND: suffix = ".".join(labels[-2:]) else: suffix = labels[-1] n = suffix.count(".") + 1 for h in HOSTING: # private suffixes: each customer gets their own "registrable" name if host == h: return host, suffix, [] if host.endswith("." + h): n = h.count(".") + 1 break reg = ".".join(labels[-(n + 1):]) if len(labels) > n else ".".join(labels) sub = labels[:-(n + 1)] if len(labels) > n + 1 else [] return reg, suffix, sub def registrable(host): return split_host(host.lower())[0] def is_official(host): return any(host == d or host.endswith("." + d) for d in OFFICIAL) def deleet(s): s = "".join(LEET.get(c, c) for c in s) return s.replace("rn", "m").replace("vv", "w").replace("-", "") def lev1(a, b): """True when a and b differ by exactly one edit (insert, delete, substitute or adjacent swap).""" if a == b or abs(len(a) - len(b)) > 1: return False if len(a) == len(b): d = [i for i in range(len(a)) if a[i] != b[i]] return len(d) == 1 or (len(d) == 2 and d[1] == d[0] + 1 and a[d[0]] == b[d[1]] and a[d[1]] == b[d[0]]) if len(a) > len(b): a, b = b, a i = 0 while i < len(a) and a[i] == b[i]: i += 1 return a[i:] == b[i + 1:] def puny_decode(label): """RFC 3492 decode of the part after xn--; None when invalid.""" base, tmin, tmax, skew, damp = 36, 1, 26, 38, 700 inp = label d = inp.rfind("-") out = list(inp[:d]) if d > 0 else [] if any(ord(c) > 127 for c in out): return None i, n, bias, pos = 0, 128, 72, d + 1 if d > 0 else 0 while pos < len(inp): oldi, w, k = i, 1, base while True: if pos >= len(inp): return None c = inp[pos] pos += 1 cp = ord(c) digit = cp - 48 + 26 if 48 <= cp <= 57 else cp - 97 if 97 <= cp <= 122 else cp - 65 if 65 <= cp <= 90 else -1 if digit < 0: return None i += digit * w t = tmin if k <= bias else tmax if k >= bias + tmax else k - bias if digit < t: break w *= base - t k += base if i > 0x10FFFF * 40: return None delta = (i - oldi) // (damp if oldi == 0 else 2) delta += delta // (len(out) + 1) k = 0 while delta > ((base - tmin) * tmax) // 2: delta //= base - tmin k += base bias = k + (base - tmin + 1) * delta // (delta + skew) n += i // (len(out) + 1) i %= len(out) + 1 if n > 0x10FFFF: return None out.insert(i, chr(n)) i += 1 return "".join(out) def skeleton(host): """Decode xn-- labels and map lookalike letters to Latin, e.g. xn--ntoso-... -> contoso.""" labs = [] for lab in host.split("."): if lab.startswith("xn--"): dec = puny_decode(lab[4:]) lab = dec if dec is not None else lab labs.append(lab) return "".join(CONFUSABLE.get(c, c) for c in ".".join(labs)) def brand_in(text, tokens, b): if len(b) >= 5 and b not in WORD_BRANDS: return b in text return b in tokens def analyze(raw): url = refang(raw) p = parse(url) flags = {} def add(fid, s, e): flags.setdefault(fid, []).append([s, e]) n = len(url) if p["special"]: add("data_or_js_scheme", 0, len(p["scheme"]) + 1) host, hs = p["host"], p["host_start"] he = hs + len(host) reg, suffix, sub = split_host(host) ipk = ip_kind(host) labels = labels_of(host) parts = {"scheme": p["scheme"], "userinfo": p["userinfo"], "host": host, "port": p["port"], "path": p["path"], "query": p["query"], "fragment": p["fragment"], "registrable": reg, "suffix": suffix, "subdomain": ".".join(sub), "ip": ipk} if host and not p["special"]: if ipk in ("public", "obfuscated"): add("ip_host", hs, he) if p["userinfo"]: add("at_symbol", p["auth_start"], hs - 1) if any(ord(c) > 127 for c in host): add("non_ascii_host", hs, he) pos = 0 for lab in host.split("."): if lab.startswith("xn--"): add("punycode", hs + pos, hs + pos + len(lab)) pos += len(lab) + 1 reg_s = he - len(reg) if host.endswith(reg) else hs sub_s, sub_e = hs, max(hs, reg_s - 1) regname = labels_of(reg)[0] if reg else "" official = is_official(host) if not ipk and not official and regname: rn_tokens = regname.split("-") rn_flat = regname.replace("-", "") sub_str = ".".join(sub) sub_tokens = [t for x in sub for t in x.split("-")] dl = deleet(regname) ptoks = TOKEN.findall(p["path"].lower()) sk_name = "" if any(ord(c) > 127 for c in host) or "xn--" in host: sk_reg = split_host(skeleton(host))[0] sk_name = labels_of(sk_reg)[0].replace("-", "") if sk_reg else "" for b in BRANDS: if brand_in(rn_flat, rn_tokens, b): add("brand_domain_misuse", reg_s, reg_s + len(regname)) elif (len(b) >= 5 and b not in WORD_BRANDS and b in dl) or (len(b) >= 6 and lev1(rn_flat, b)) or \ any(t != b and deleet(t) == b for t in rn_tokens): add("brand_lookalike", reg_s, reg_s + len(regname)) if sub and brand_in(sub_str, sub_tokens, b): add("brand_in_subdomain", sub_s, sub_e) if sk_name and sk_name != rn_flat and brand_in(sk_name, sk_name.split("-"), b): add("brand_lookalike", reg_s, reg_s + len(regname)) if b in ptoks: i = p["path"].lower().find(b) add("brand_in_path", p["path_start"] + i, p["path_start"] + i + len(b)) hl = host[:len(host) - len(suffix)] for m in TOKEN.finditer(hl): if m.group(0) in SENS: add("sensitive_words_host", hs + m.start(), hs + m.end()) if p["path"]: for m in TOKEN.finditer(p["path"].lower()): if m.group(0) in SENS: add("sensitive_words_path", p["path_start"] + m.start(), p["path_start"] + m.end()) if not ipk and labels and labels[-1] in RISKY: add("risky_tld", he - len(labels[-1]), he) for d in FREE: if host == d or host.endswith("." + d): add("free_hosting", he - len(d), he) break for d in DDNS: if host == d or host.endswith("." + d): add("dynamic_dns", he - len(d), he) break if (host[4:] if host.startswith("www.") else host) in SHORT: add("shortener", hs, he) if len(sub) >= 3: add("many_subdomains", sub_s, sub_e) if not ipk: pos = 0 for lab in host.split(".")[:max(0, len(labels) - (suffix.count(".") + 1))]: off = 0 for piece in lab.split("-"): if not lab.startswith("xn--") and len(piece) >= 8 and re.match(r"^[a-z0-9]+$", piece): vow = sum(c in "aeiou" for c in piece) dig = sum(c.isdigit() for c in piece) let = len(piece) - dig if vow / len(piece) < 0.2 or (dig >= 3 and let >= 3) or re.match(r"^[0-9a-f]{12,}$", piece): add("random_host", hs + pos + off, hs + pos + off + len(piece)) off += len(piece) + 1 pos += len(lab) + 1 if host.count("-") - 2 * host.count("xn--") >= 3: add("hyphen_heavy", hs, he) if len(host) > 35: add("long_host", hs, he) if p["port"] and p["port"] not in ("80", "443"): add("nonstandard_port", he, he + 1 + len(p["port"])) path_l = p["path"].lower() if p["path"] and not p["special"]: ls = path_l.rfind("/") seg = path_l[ls + 1:] seg_s = p["path_start"] + ls + 1 if "." in seg: ext = seg[seg.rfind(".") + 1:] if DBL.search(seg): add("double_extension", seg_s, seg_s + len(seg)) if ext in EXEC: add("exe_download", seg_s, seg_s + len(seg)) elif ext in ARCH: add("archive_download", seg_s, seg_s + len(seg)) for m in EMBED.finditer(path_l): add("embedded_domain_path", p["path_start"] + m.start(1), p["path_start"] + m.end(1)) i = path_l.find("//") if i >= 0: add("double_slash_path", p["path_start"] + i, p["path_start"] + i + 2) for c in CMS: i = path_l.find(c) if i >= 0: add("cms_path", p["path_start"] + i, p["path_start"] + i + len(c)) break if p["query"]: pos = 0 for kv in p["query"].split("&"): eq = kv.find("=") if eq > 0: v = kv[eq + 1:].lower().replace("%25", "%").replace("%3a", ":").replace("%2f", "/") m = REDIR.match(v) if m: t = m.group(1) or m.group(2) if registrable(t) != reg: s = p["query_start"] + pos + eq + 1 add("redirect_param", s, s + len(kv) - eq - 1) pos += len(kv) + 1 for part, start in ((p["query"], p["query_start"]), (p["fragment"], p["frag_start"])): for m in EMAIL.finditer(part.lower()): add("email_in_url", start + m.start(), start + m.end()) enc = len(PCT.findall(p["path"] + p["query"])) if enc >= 6 or (host and PCT.search(host)): add("encoded_chars", p["path_start"], n) if n > 120: add("long_url", 0, n) if p["scheme"] == "http": add("no_https", 0, 4) out = [] for fid in FLAG_IDS: if fid in flags: meta = META[fid] out.append({"id": fid, "label": meta["label"], "severity": meta["severity"], "why": meta["why"], "spans": flags[fid]}) return {"url": url, "parts": parts, "flags": out} def flag_vector(raw): got = {f["id"] for f in analyze(raw)["flags"]} return [1 if fid in got else 0 for fid in FLAG_IDS] def _tok(prefix, t): if t.isdigit(): return prefix + "" if len(t) >= 20: return prefix + "" return prefix + t def unpct(s): """Turn %xx escapes into separators so encoded URLs tokenize into words (https%3A%2F%2Fx -> https x).""" return PCT.sub(" ", s.replace("%25", "%")) def model_docs(raw): """-> (char_doc, token_doc), the two strings the TF-IDF blocks see.""" url = refang(raw) p = parse(url) char_doc = url if p["special"] else url[p["auth_start"]:] char_doc = char_doc[:300] toks = ["s:" + (p["scheme"] or "none")] if p["special"]: toks += [_tok("p:", t) for t in TOKEN.findall(p["path"].lower())[:30]] return char_doc, " ".join(toks) host = p["host"] reg, suffix, sub = split_host(host) if ip_kind(host): toks.append("h:") else: toks.append("tld:" + suffix) for t in TOKEN.findall(host[:max(0, len(host) - len(suffix))]): toks.append(_tok("h:", t)) if p["userinfo"]: toks.append("user:") toks += [_tok("u:", t) for t in TOKEN.findall(p["userinfo"].lower())[:10]] if p["port"]: toks.append("port:" + p["port"]) path_l = p["path"].lower() for t in TOKEN.findall(unpct(path_l)): toks.append(_tok("p:", t)) seg = path_l[path_l.rfind("/") + 1:] if "." in seg: toks.append("ext:" + _tok("", "".join(TOKEN.findall(seg[seg.rfind(".") + 1:]))[:10])) for kv in p["query"].split("&") if p["query"] else []: eq = kv.find("=") key = kv[:eq] if eq >= 0 else kv val = kv[eq + 1:] if eq >= 0 else "" kt = "".join(TOKEN.findall(key.lower())) if kt: toks.append(_tok("qk:", kt)) for t in TOKEN.findall(unpct(val.lower())): toks.append(_tok("q:", t)) if p["fragment"]: toks.append("frag:") return char_doc, " ".join(toks[:200])