DaveyD347's picture
Add malicious URL classifier
84f95cd verified
|
Raw History Blame Contribute Delete
13.3 kB
---
license: apache-2.0
language:
- en
library_name: sklearn
pipeline_tag: text-classification
tags:
- cybersecurity
- security
- phishing
- malware
- malicious-url
- url-classification
- explainable-ai
- tfidf
- logistic-regression
- skops
metrics:
- accuracy
- f1
- precision
- recall
- roc_auc
model-index:
- name: malicious-url-classifier
results:
- task:
type: text-classification
name: Malicious URL detection
dataset:
name: Synthetic defanged URLs (template-disjoint test split)
type: DaveyD347/malicious-url-classifier
split: test
metrics:
- type: accuracy
value: 0.962
- type: f1
name: Macro F1
value: 0.962
- type: precision
value: 0.973
- type: recall
value: 0.949
- type: roc_auc
value: 0.989
- task:
type: text-classification
name: Malicious URL detection
dataset:
name: Hand-written challenge set (real benign URLs, real-brand impersonation)
type: DaveyD347/malicious-url-classifier
config: challenge
split: test
metrics:
- type: accuracy
value: 0.983
- type: f1
name: Macro F1
value: 0.983
---
# Malicious URL Classifier (TF-IDF + explainable red flags)
A small, explainable classifier that scores a single URL as **benign or malicious** (phishing, malware delivery or
scam) from the text of the URL alone, and tells you **why**: a lookalike or impersonated brand, a raw IP, an `@`
trick, punycode, an abused TLD, free hosting or dynamic DNS, an executable download, an open redirect, a prefilled
victim email, and more.
It's a logistic regression over three feature blocks, small enough (about 0.8 MB of weights as JSON) to run
**entirely in the browser**. Try it in the
[Malicious URL Detector Space](https://huggingface.co/spaces/DaveyD347/malicious-url-detector), which also takes
defanged input (`hxxps://example[.]com`) and batches of up to 2,000 URLs.
| block | features |
|---|---|
| characters | TF-IDF of character 3-5-grams of the URL without its scheme (30k terms): catches `c0ntoso`, `-secure-`, `.top`, `/wp-content/` |
| tokens | TF-IDF of part-tagged tokens (2.9k terms): `h:login` is "login" in the hostname, `p:login` is "login" in the path, plus `tld:`, `ext:`, `qk:` (query keys), `port:` ... |
| red flags | 31 binary, rule-based checks on the parsed URL ([list below](#red-flags)) |
## Quick start
```python
from huggingface_hub import hf_hub_download
from skops.io import load, get_untrusted_types
import sys, os
repo = "DaveyD347/malicious-url-classifier"
files = ["model.skops", "src/urlflags.py", "src/url_spec.json", "src/train.py"]
paths = [hf_hub_download(repo, f) for f in files]
sys.path.insert(0, os.path.dirname(paths[1]))
from train import featurize # the same preprocessing used in training
from urlflags import analyze
m = load(paths[0], trusted=get_untrusted_types(file=paths[0]))
urls = ["hxxps://paypal[.]com[.]account-verify[.]top/signin", # defanged input is fine
"https://github.com/scikit-learn/scikit-learn"]
p = m["clf"].predict_proba(featurize(m["char"], m["toks"], urls, m["flag_scale"]))[:, 1]
for u, pp in zip(urls, p):
print(f"{pp:.3f} {'malicious' if pp >= m['threshold'] else 'benign'} {u}")
for f in analyze(u)["flags"]:
print(" -", f["label"])
```
Check what `get_untrusted_types` returns before loading any `.skops` file you didn't create. For JavaScript,
`model.json` holds the same weights, and `model.js` + `urlflags.js` in the Space reproduce the whole pipeline with no
dependencies. A parity test checks JS and Python agree on 4,579 URLs: identical flags, highlight spans and token
streams, probabilities within 3e-6.
## Evaluation
Trained on the train + validation splits of the synthetic dataset in [`data/`](data). Every URL comes from one of
168 templates in 53 families (e.g. "brand in subdomain", "executable download", "blog post"). The **test split uses
templates the model never saw**, its hosts come from separate pools (different fictional brands, popular sites and
generated names), and four whole families (crypto-wallet scams, tech-support scams, media links, API endpoints)
appear **only** in test. The challenge set is 60 URLs written by hand.
| set | accuracy | precision | recall | macro F1 | ROC AUC | false-positive rate |
|---|---:|---:|---:|---:|---:|---:|
| test (12,400, unseen templates) | 0.962 | 0.973 | 0.949 | 0.962 | 0.989 | 2.6% |
| test, families never seen in training (3,840) | 0.995 | 0.996 | 0.994 | 0.995 | 1.000 | 0.4% |
| test, new templates of seen families (8,560) | 0.947 | 0.962 | 0.929 | 0.947 | 0.981 | 3.6% |
| challenge (60, hand-written) | 0.983 | 1.000 | 0.967 | 0.983 | 1.000 | 0% |
All at the default threshold of 0.5 (chosen by cross-validation; it was also the best threshold out of fold).
![Confusion matrix](eval/confusion_matrix.png)
**Ablations** (same data and settings): red flags alone reach 0.933 accuracy on test (6.0% false positives), TF-IDF
alone 0.869 (7.8%). Combined, 0.962 (2.6%). The flags carry most of the signal; the text features mostly cut false
positives.
**Where it struggles** on the test split:
- typosquatted *software* sites (`fileziilla.org/download/...-setup.exe`): 62%. The brand checks only know the brand
list, not every software name.
- CloudFront-style CDN hosts (`d1a2b3c4d5e6f7.cloudfront.net/...`): 63% correct. Random-looking hostnames are a
strong malicious signal, and these look random.
- DGA-style random domains with an unseen path shape: 78%. Document-share lures on new templates: 88%.
On the challenge set the miss is `arnazon-orders.net` (scored 0.42, "suspicious" in the Space): an `rn`→`m` lookalike
of a brand that's also a dictionary word. Real benign URLs that look risky score low: Google and Microsoft sign-in
with long redirect parameters (2% and 9%), PayPal sign-in (7%), the Python and Git installers (`.exe`, 9%),
`xn--mnchen-3ya.de` (5%), a router admin page on `192.168.1.1` (4%). A bare `bit.ly` link scores 29%, which the Space
shows as "suspicious": a shortener hides its destination.
The challenge set was written by the same person who wrote the checks, so treat it as a sanity check rather than an
independent benchmark.
### How it was trained
- `C` (inverse regularization) and the red-flag weight were picked by **5-fold grouped cross-validation over
templates** (each fold scores templates left out of training): `C=0.3`, `flag_scale=0.5`, macro F1
0.926 ± 0.016 across folds. Lower `flag_scale` won: the flags are strong, and over-weighting them made the model
brittle on templates where a flag fired on benign URLs.
- Class-balanced logistic regression (scikit-learn `lbfgs`), refit on all 38,456 train + validation URLs.
32,887 features. CPU only; the whole grid search takes about 2 minutes on a few CPU cores.
## Red flags
| id | severity | what it checks |
|---|---|---|
| `data_or_js_scheme` | high | `data:` or `javascript:` URL |
| `ip_host` | high | public IPv4 host, or a decimal / hex / octal encoded IP (private ranges don't count) |
| `at_symbol` | high | userinfo before `@` (`trusted.com@evil.site`) |
| `non_ascii_host` | high | non-Latin characters in the host (homograph) |
| `punycode` | medium | an `xn--` label |
| `brand_lookalike` | high | registered name is one edit, a digit swap (`paypa1`), `rn`→`m`, or a homoglyph away from a known brand |
| `brand_domain_misuse` | high | a brand name is part of a registered domain the brand doesn't own (`brand-login.com`, `brand.top`) |
| `brand_in_subdomain` | high | brand to the left of the registered domain (`brand.com.evil.site`) |
| `brand_in_path` | medium | brand in the path of a domain the brand doesn't own |
| `sensitive_words_host` | medium | login / verify / secure / wallet / billing ... in the hostname |
| `sensitive_words_path` | low | the same words in the path |
| `exe_download` | high | `.exe .scr .msi .apk .ps1 .vbs .jar .hta .iso ...` |
| `double_extension` | high | `invoice.pdf.exe` |
| `archive_download` | low | `.zip .rar .7z ...` |
| `risky_tld` | medium | TLDs over-represented in abuse (`.top .xyz .click .icu .tk ...`) |
| `free_hosting` | medium | free hosting or public cloud storage (`web.app`, `pages.dev`, `storage.googleapis.com`, `ipfs.io` ...) |
| `dynamic_dns` | medium | `duckdns.org`, `ddns.net`, `hopto.org` ... |
| `shortener` | low | `bit.ly`, `tinyurl.com` ... |
| `redirect_param` | medium | a query value that sends you to a different registered domain (open redirect) |
| `email_in_url` | medium | an email address in the query or fragment (prefilled victim) |
| `embedded_domain_path` | medium | another domain inside the path (`evil.top/brand.com/login`) |
| `many_subdomains` | medium | 3+ subdomain labels |
| `random_host` | medium | machine-generated label (low vowel ratio, mixed digits, long hex) |
| `hyphen_heavy` | low | 3+ hyphens in the host |
| `long_host` | low | host longer than 35 characters |
| `nonstandard_port` | medium | explicit port other than 80 / 443 |
| `cms_path` | low | `/wp-content/`, `/wp-includes/`, `/wp-admin/` ... (compromised sites) |
| `encoded_chars` | low | 6+ percent-escapes, or any in the host |
| `double_slash_path` | low | `//` inside the path |
| `long_url` | low | longer than 120 characters |
| `no_https` | low | plain `http://` |
The brand list in `src/url_spec.json` has the 60 fictional brands used in the data plus about 60 real brands that are
commonly impersonated, each with the domains it actually uses. The real brands are never in the training data;
the model learns what a brand flag means from the fictional ones, and the same flag then fires for real brands. A
registrable domain is computed with a small built-in suffix list (e.g. `co.uk`, plus hosting suffixes like
`web.app` where each customer gets their own name), not the full Public Suffix List.
## Training data
51,000 synthetic URLs (`data/train|validation|test.parquet`) plus the 60-URL challenge set, generated by
[`src/generate_dataset.py`](src/generate_dataset.py) and [`src/challenge_set.py`](src/challenge_set.py).
| split | URLs | benign | malicious | templates |
|---|---:|---:|---:|---:|
| train | 31,864 | 16,936 | 14,928 | 109 |
| validation | 6,592 | 3,680 | 2,912 | 22 |
| test | 12,400 | 6,240 | 6,160 | 37 |
| challenge | 60 | 30 | 30 | hand-written |
Columns: `id`, `url` (defanged), `label` (0 benign / 1 malicious), `label_name`, `category` (benign, phishing,
malware, scam), `family`, `variant_id` (the template). Benign URLs include deliberately hard cases: official sign-in
pages with long redirect parameters, legitimate `.exe` / `.msi` downloads, private-IP admin pages, `github.io` and
`netlify.app` sites, SharePoint / Drive / Dropbox share links, newsletter tracking links, hyphen-heavy business
domains, punycode (IDN) domains, and reviews that mention a brand in the path.
**Safety.** No URL comes from a threat feed. Malicious examples impersonate fictional brands on generated domains,
and **every URL is stored defanged** (`hxxp://`, `[.]` in the host and query), so none is clickable. The model
refangs input before scoring (`refang()` in `urlflags.py`). Generated names can collide with real registered domains
by chance; that doesn't make those domains malicious. Benign examples also use 176 real, well-known domains
(Wikipedia, GitHub, BBC ...), split between train and test so test domains are unseen.
Brand names in `url_spec.json` belong to their owners and appear only so the checks can recognize impersonation.
This project isn't affiliated with any of them.
## Intended use and limits
Good for: learning and teaching what malicious URLs look like, explaining a verdict to a user, quick triage of a
list of URLs, and as a cheap, transparent baseline to compare bigger models against.
Not good for: being your only control. It reads **only the URL string**. It can't see domain age, WHOIS, DNS,
reputation, TLS certificates, redirects, or the page itself, so a phishing page on a clean-looking compromised
domain (`https://some-real-bakery.com/menu`) looks benign, and plenty of odd but legitimate URLs look suspicious.
It was trained on synthetic data, so real-world accuracy will be lower than the numbers above, and it has never
seen live malicious URLs. Use it alongside reputation feeds, sandboxing and user reporting.
## Files
| file | what |
|---|---|
| `model.skops` | scikit-learn vectorizers + logistic regression (load with `skops.io.load`) |
| `config.json` | hyper-parameters, cross-validation grid and feature list |
| `model.json` | the same weights for JavaScript (`url-tfidf-logreg-v1` format) |
| `src/urlflags.py`, `src/url_spec.json` | URL parser, refang, the 31 red flags and their lists |
| `src/generate_dataset.py`, `src/challenge_set.py` | the synthetic dataset and challenge set |
| `src/train.py`, `src/evaluate.py`, `src/export_js.py` | training, evaluation and JS export |
| `data/` | train / validation / test / challenge parquet (defanged) and the template-to-split map |
| `eval/` | metrics (per family, ablations, challenge scores) and the confusion matrix |
Reproduce: `python src/generate_dataset.py && python src/challenge_set.py && python src/train.py && python src/evaluate.py`.
## License
Apache-2.0 for the code, the weights and the synthetic data.