This commit is contained in:
Christopher Tarry
2026-10-25 22:45:01 -04:00
commit 63aed4fab8
1813 changed files with 1013870 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
/target
.env
*.log
# capture-proxy's default CA (with its private key) and capture directories.
/proxy-ca/
/captures/
Generated
+4656
View File
File diff suppressed because it is too large Load Diff
+101
View File
@@ -0,0 +1,101 @@
[package]
name = "cfsolve"
version = "0.1.0"
edition = "2024"
license = "MIT"
default-run = "cfsolve"
# The files in tests/ are modules of one test binary (tests/main.rs), so swc and v8
# are linked once instead of once per file. A new test file needs a `mod` line there.
autotests = false
[[test]]
name = "integration"
path = "tests/main.rs"
# Without default features, the library is the solver alone: `Browser`, `Options`, `Outcome`
# and `Error`. The tools in this repository use the rest.
[features]
default = ["internals"]
# The analysis modules behind the solver (deobfuscation, the VM, payloads, and transport), and
# the capture proxy, which records the challenge payloads a real browser sends.
internals = [
"dep:bytes",
"dep:http-body-util",
"dep:hyper",
"dep:hyper-util",
"dep:rcgen",
"dep:rustls",
"dep:rustls-native-certs",
"dep:tokio-rustls",
]
[dependencies]
anyhow = "1.0.104"
base64 = "0.22.1"
chrono = "0.4.42"
ego-tree = "0.11.0"
getrandom = "0.4.3"
html5ever = "0.39.0"
# Payload fields keep the order the challenge program builds them in.
indexmap = { version = "2", features = ["serde"] }
iana-time-zone = "0.1.64"
# `CLOCK_MONOTONIC`, the time base Chrome's `performance.now()` is derived from.
libc = "0.2.189"
num-bigint = "0.4.6"
# A returned program's payload can hold a capture of `RegExp(...).exec(...)`.
regex = "1.12.2"
ryu-js = "1.0.2"
# Fast hashing for the VM interpreter's identifier and register maps.
rustc-hash = "2.1.1"
# `deterministic` keeps attributes in source order, which the page fingerprint
# reports verbatim.
scraper = { version = "0.27.0", features = ["deterministic"] }
serde = { version = "1.0.228", features = ["derive"] }
# Browser measurements must retain the exact doubles produced by JSON.parse.
serde_json = { version = "1.0.151", features = ["float_roundtrip", "preserve_order"] }
sha2 = "0.10.9"
# No default features: the linter and TypeScript declaration emit are unused.
swc = { version = "52.0.0", default-features = false }
swc_core = { version = "54.0.0", features = ["common", "ecma_ast", "ecma_visit", "ecma_codegen", "ecma_parser"] }
swc_ecma_transforms = "44.0.0"
swc_ecma_utils = "25.0.0"
tokio = { version = "1.53.1", features = ["macros", "net", "rt-multi-thread", "sync", "time", "io-util", "signal"] }
url = "2.5.8"
# `Url` leaves an upstream proxy's credentials percent-encoded.
percent-encoding = "2.3.2"
wreq = { version = "=0.16.1", features = ["cookies", "gzip", "brotli", "deflate", "zstd", "socks"] }
rustls-native-certs = { version = "0.8", optional = true }
wreq-util = { version = "0.2.0", features = ["emulation-serde", "emulation-compression"] }
# The UI audit's keyframe text, spelled as each engine serializes it.
cssparser = "0.37"
flate2 = "1.1.10"
brotli = "8.0.4"
zstd = "0.13.3"
# The capture proxy: TLS interception and HTTP serving on the MITM leg.
hyper = { version = "1", features = ["server", "http1", "http2"], optional = true }
hyper-util = { version = "0.1", default-features = false, features = ["tokio"], optional = true }
bytes = { version = "1", optional = true }
http-body-util = { version = "0.1", optional = true }
rustls = { version = "0.23", default-features = false, features = ["std", "tls12", "logging", "ring"], optional = true }
tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12", "ring"], optional = true }
rcgen = { version = "0.14", features = ["x509-parser"], optional = true }
[dev-dependencies]
# The deobfuscator's differential tests compare its output's behavior in V8.
v8 = "=152.2.0"
# Chrome 154's ClientHello: ML-DSA and GREASE signature algorithms and the
# trust_anchors extension, which the published crates cannot send. See the
# "cfsolve patch" comments in vendor/.
[patch.crates-io]
btls-sys = { path = "vendor/btls-sys" }
wreq = { path = "vendor/wreq" }
http2 = { path = "vendor/http2" }
# Full debug info for swc and v8 dominates link time and target/ size. Line tables
# keep file:line in this crate's backtraces; dependencies get none.
[profile.dev]
debug = "line-tables-only"
[profile.dev.package."*"]
debug = false
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Christopher Tarry
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+207
View File
@@ -0,0 +1,207 @@
# cfsolve
cfsolve is a Rust library and command line tool that solves Cloudflare Turnstile
widgets and challenge pages without a headless browser. It returns a Turnstile
token for widgets or a `cf_clearance` cookie for challenge pages.
Turnstile widgets can be solved using the page URL, the sitekey, and optionally the
page's HTML (this should not be required in most cases). Challenge pages require a direct
fetch or the HTML of the page.
## Browser profiles
cfsolve impersonates a specific browser, described by a profile file. One is
included: `profiles/safari-26-ios.json` (Safari on iPhone).
Each profile references recorded responses to the challenge's browser checks,
stored as JSON in a directory. Keep each profile with its directory when you
copy. Producing these files requires some manual (or AI) effort though it can
be greatly aided by solving challenges in a real web browser with the proxy
set to the address of a running `capture-proxy`, which records the decoded
payloads sent to Cloudflare. Currently only Safari and Chrome(ium) profile
types are supported.
## Building
You need the Rust version pinned in `rust-toolchain.toml`, plus CMake, a C/C++
compiler, and libclang (for BoringSSL).
```sh
cargo build --release --bin challenge
```
## Command line tool
```sh
./target/release/challenge --page 'https://example.com/login' /tmp/solve \
--solve --fingerprint profiles/safari-26-ios.json
```
On success it prints the token (or `cf_clearance=...`) and sends progress
to stderr. The directory argument holds all requests and responses for
debugging, so it must be empty or not exist yet.
By default it solves the first Turnstile widget on the page, or clears
the challenge page. To pick one widget when the page has several, pass its
sitekey, with its action and cData when the site sets them. With `--sitekey`,
it fails on a challenge page.
```sh
./target/release/challenge --page 'https://example.com/login' /tmp/solve \
--solve --fingerprint profiles/safari-26-ios.json \
--sitekey 'SITEKEY' --action 'login' --cdata 'CUSTOM_DATA'
```
If you only have a sitekey, add `--blank-page` and set `--page` to the
site's real URL.
| Option | Description |
| --- | --- |
| `--fingerprint <file>` | Browser profile file to use. Required. |
| `--page <url>` | The page with the widget, or the challenge page. |
| `--solve` | Solve the widget or challenge. Without this, cfsolve stops after the first request. |
| `--sitekey <key>` | Select a widget by sitekey. |
| `--action <value>`, `--cdata <value>` | Override the widget's action and cData. This needs `--sitekey`. |
| `--blank-page` | Skip loading the page. Render the widget on a blank page at the page URL. This needs `--solve` and `--sitekey`. |
| `--proxy <url>` | Send every request through an `http://`, `https://`, `socks5://`, or `socks5h://` proxy. Put credentials in the URL, as in `socks5h://user:password@host:1080`. |
| `-h`, `--help` | Show help. |
## Library
Add cfsolve as a path dependency and copy its `[patch]` section, since
Cargo only reads patches from the top-level `Cargo.toml`:
```toml
[dependencies]
cfsolve = { path = "/path/to/cfsolve", default-features = false }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
[patch.crates-io]
btls-sys = { path = "/path/to/cfsolve/vendor/btls-sys" }
wreq = { path = "/path/to/cfsolve/vendor/wreq" }
http2 = { path = "/path/to/cfsolve/vendor/http2" }
```
`default-features = false` turns off the internal tools so only the solver remains.
Use the Rust version in `rust-toolchain.toml` or newer.
```rust
use cfsolve::{Browser, Options, PageSource, Turnstile};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let browser = Browser::read("/path/to/cfsolve/profiles/safari-26-ios.json")?;
let options = Options::default();
let turnstile = Turnstile {
url: "https://example.com/login".parse()?,
page: PageSource::Navigate,
widget: None,
};
let token = browser.solve_turnstile(turnstile, &options).await?;
println!("{token}");
let cleared = browser.clear(&"https://example.com/".parse()?, &options).await?;
println!("cf_clearance={}", cleared.clearance);
println!("{} cookies; protected page: {}", cleared.cookies.len(), cleared.page.url);
Ok(())
}
```
Load a `Browser` once and share it. Concurrent operations each get their own
connections and cookies.
Send the `cf_clearance` cookie from the same IP address and user agent
as the profile, or Cloudflare will reject it.
### Turnstile with a sitekey or your own HTML
`PageSource::Navigate` fetches the page. With only a URL and sitekey, use
`PageSource::Blank` and specify the widget:
```rust
use cfsolve::{PageSource, Turnstile, Widget};
let turnstile = Turnstile {
url: "https://example.com/login".parse()?,
page: PageSource::Blank,
widget: Some(Widget {
sitekey: "SITEKEY".into(),
action: Some("login".into()),
cdata: None,
}),
};
let token = browser.solve_turnstile(turnstile, &options).await?;
```
Set `action` and `cdata` to the values the site uses, or `None` when the site
doesn't set them. You can also pass a `Widget` with `PageSource::Navigate` to pick
one widget out of several or to supply one the site adds with JavaScript.
For a page you have already loaded, such as one behind a login, pass its URL and
HTML:
```rust
PageSource::Html {
html: std::fs::read_to_string("account.html")?,
referrer_policy: None, // Or the response's Referrer-Policy header.
}
```
The widget runs in a cross-site iframe, so you don't need your login cookies.
With `Html`, `widget: None` solves the first widget on the page, while `Blank`
always needs a `Widget` and renders it on a blank page at the site's URL.
### Challenge pages
`browser.clear(&url, &options)` fetches the page and clears the challenge. The
`Clearance` it returns contains the `cf_clearance` cookie, all cookies for the
page, and the protected page. It fails with `Error::NotChallenged` when there's
no challenge.
If you fetched the challenge page yourself, pass the response as a
`FetchedPage` to `browser.clear_fetched(page, &options)`. Use the same IP and user
agent as the profile.
If you don't know whether a URL shows a widget or a challenge page, use
`browser.solve`, which covers both cases:
```rust
use cfsolve::Outcome;
match browser.solve(&url, &options).await? {
Outcome::Token(token) => println!("{token}"),
Outcome::Cleared(cleared) => println!("cf_clearance={}", cleared.clearance),
}
```
### Options
Set a proxy per operation through `Options`, using HTTP, HTTPS, or SOCKS5:
```rust
let options = cfsolve::Options {
proxy: Some("socks5h://127.0.0.1:1080".into()),
..Default::default()
};
```
Library operations are silent by default. For progress messages and debug files,
implement `Sink` and set `options.sink` to `Some(Arc::new(your_sink))`.
### Errors
| Error | Cause | Retry? |
| --- | --- | --- |
| `Error::Network` | Connection failed. | Yes |
| `Error::Rejected` | Cloudflare rejected the solution. | Yes |
| `Error::Blocked` | The site returned an error page instead of a challenge. | No |
| `Error::Challenged` | You asked for a Turnstile token but got a challenge page. | Yes, after clearing it |
| `Error::NotChallenged` | You asked for a challenge clearance but there was no challenge. | No |
| `Error::Config` | Invalid profile or options. | No |
| `Error::Unsupported` | This challenge type isn't supported. | No |
## License
MIT, except for the patched dependencies in `vendor/`, which keep their own
licenses.
+53
View File
@@ -0,0 +1,53 @@
//! Store a real browser's probe answers for a device profile.
//! Usage: build_profile <capture.json> > answers.json
//!
//! The capture is what `scripts/cdp_capture.mjs` writes: the iframe's HTML,
//! its POSTs with their responses, and the plaintext payloads. Each probe's
//! record from the second payload is stored under the reference build's
//! names; see `cfsolve::stage2::replay`.
use std::{env, fs};
use anyhow::{Context, Result};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use cfsolve::js::Payload;
use cfsolve::script::Source;
use cfsolve::stage2::replay::Answers;
use cfsolve::{JsValue, challenge};
use url::Url;
fn main() -> Result<()> {
let path = env::args().nth(1).context("supply a capture JSON file")?;
let capture: JsValue = serde_json::from_slice(&fs::read(&path)?)?;
let html = capture["iframeHtml"]
.as_str()
.context("the capture has no iframe HTML")?;
let javascript = challenge::inline_javascript(html)?;
let deobfuscated = cfsolve::deobfuscate(javascript)?;
let source = Source::try_new(&deobfuscated.text)?;
// The first payload's response is the probe program, masked with the ray
// its URL carries.
let post = &capture["posts"][0];
let url = Url::parse(post["url"].as_str().context("the capture has no POST")?)?;
let body = post["responseBody"]
.as_str()
.context("the first payload has no response")?;
let program = STANDARD.decode(challenge::decode_response(
body.as_bytes(),
challenge::ray(&url)?,
)?)?;
// The second payload is the one holding the numbered records.
let payload = capture["payloads"]
.as_array()
.into_iter()
.flatten()
.filter_map(|payload| payload["payload"].as_object())
.find(|payload| payload.contains_key("1"))
.context("the capture has no second payload")?;
let answers = Answers::capture(&source, &program, &Payload::from(payload.clone()))?;
println!("{}", serde_json::to_string_pretty(&answers)?);
Ok(())
}
+60
View File
@@ -0,0 +1,60 @@
//! Print the instructions of a session's VM program.
//!
//! `disassemble <deobfuscated.js> [program.txt [entries.json]]` reads the program as the
//! `runProgram` argument text (base64); without a file it disassembles the
//! script's own embedded program. A third argument adds entries the program
//! reaches some other way, such as a browser's recorded coverage.
use std::{env, fs};
use anyhow::{Context, Result};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use cfsolve::script::Source;
use cfsolve::vm::Position;
fn main() -> Result<()> {
let mut arguments = env::args().skip(1);
let script = arguments
.next()
.context("usage: disassemble <deobfuscated.js> [program.txt]")?;
let text = fs::read_to_string(&script)?;
let program = match arguments.next() {
Some(path) => fs::read_to_string(path)?,
None => {
let start =
text.find("runProgram(`").context("no embedded program")? + "runProgram(`".len();
let end = start + text[start..].find('`').context("unterminated program")?;
text[start..end].to_owned()
}
};
let program = STANDARD.decode(program.trim())?;
let source = Source::try_new(&text)?;
let machine = source.machine()?;
// A third argument lists more entries, as JSON `[[pc, key], ...]`.
let mut entries = vec![machine.entry()];
if let Some(path) = arguments.next() {
let extra: Vec<(u32, u8)> = serde_json::from_str(&fs::read_to_string(path)?)?;
entries.extend(extra.into_iter().map(|(pc, key)| Position::new(pc, key)));
}
let listing = machine.disassemble_from(&program, &entries, &[])?;
for instruction in listing.instructions.values() {
print!("{instruction}");
}
for hidden in &listing.hidden {
println!(
"hidden {} {:?} -> {}",
hidden.compare, hidden.string, hidden.target
);
}
for failure in &listing.failures {
eprintln!("failed at {}:{}: {failure}", failure.pc, failure.key);
}
eprintln!(
"{} instructions, {} functions, {} bytes",
listing.instructions.len(),
listing.functions.len(),
program.len()
);
Ok(())
}
+63
View File
@@ -0,0 +1,63 @@
//! List a captured session's probes: each record's number in the payload,
//! its kind, whether it is replayed or computed, and the reference probe
//! its stored answer is filed under.
//! Usage: probe_plan <capture.json>
//!
//! The capture is what `scripts/cdp_capture.mjs` or the capture proxy
//! writes. Records are shuffled per session, so this is the key for reading
//! a capture's second payload by hand.
use std::{env, fs};
use anyhow::{Context, Result};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use cfsolve::challenge;
use cfsolve::script::Source;
use cfsolve::stage2::analysis;
use cfsolve::stage2::registry::Treatment;
use serde_json::Value;
use url::Url;
fn main() -> Result<()> {
let path = env::args().nth(1).context("supply a capture JSON file")?;
let capture: Value = serde_json::from_slice(&fs::read(&path)?)?;
let html = capture["iframeHtml"]
.as_str()
.context("the capture has no iframe HTML")?;
let javascript = challenge::inline_javascript(html)?;
let deobfuscated = cfsolve::deobfuscate(javascript)?;
let source = Source::try_new(&deobfuscated.text)?;
// The first payload's response is the probe program, masked with the ray
// its URL carries.
let post = &capture["posts"][0];
let url = Url::parse(post["url"].as_str().context("the capture has no POST")?)?;
let body = post["responseBody"]
.as_str()
.context("the first payload has no response")?;
let program = STANDARD.decode(challenge::decode_response(
body.as_bytes(),
challenge::ray(&url)?,
)?)?;
let analysis = analysis::analyze(&source, &program)?;
let plan = analysis.plan();
println!("record\tkind\ttreatment\treference");
for (position, probe) in plan.probes().iter().enumerate() {
let kind = probe.operation.as_ref().map(|operation| operation.kind());
let treatment = kind.map(|kind| match kind.treatment() {
Treatment::Replayed => "replayed",
Treatment::Computed => "computed",
});
let reference = plan.vocabulary().partner(position);
println!(
"{}\t{}\t{}\t{}",
probe.index,
kind.map_or("-".into(), |kind| kind.to_string()),
treatment.unwrap_or("-"),
reference.map_or("-".into(), |partner| partner.to_string()),
);
}
Ok(())
}
+217
View File
@@ -0,0 +1,217 @@
//! Throwaway live check: calls every `Browser` method against captchatest.book.bi.
//!
//! `cargo run -j2 --example solver_smoke`
use std::path::Path;
use std::sync::{Arc, Mutex};
use anyhow::{Context, Result, bail, ensure};
use cfsolve::fingerprint::Transport;
use cfsolve::{
Browser, Error, FetchedPage, Options, Outcome, PageSource, Sink, Turnstile, Url, Widget,
};
const PROFILE: &str = "profiles/safari-26-ios.json";
const MANAGED: &str = "https://captchatest.book.bi/managed";
const UNDER_ATTACK: &str = "https://captchatest.book.bi/under-attack";
/// Keeps the iframe URL a session saves, for `prepare`.
#[derive(Default)]
struct IframeUrl(Mutex<Option<String>>);
impl Sink for IframeUrl {
fn artifact(&self, name: &str, contents: &[u8]) -> Result<()> {
if name == "iframe-url.txt" {
*self.0.lock().unwrap() = Some(String::from_utf8_lossy(contents).trim().to_owned());
}
Ok(())
}
fn progress(&self, _: &str) {}
}
#[tokio::main]
async fn main() -> Result<()> {
let browser = Browser::read(PROFILE)?;
let options = Options::default();
let managed: Url = MANAGED.parse()?;
let under_attack: Url = UNDER_ATTACK.parse()?;
// The managed page's HTML and sitekey, loaded as the profile's browser.
let client = Transport::read(Path::new(PROFILE))?.client(None)?;
let html = cfsolve::http::navigate(&client, &managed).await?.html;
let sitekey = html
.split("data-sitekey=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.context("the managed page names no sitekey")?
.to_owned();
let widget = Widget {
sitekey,
action: None,
cdata: None,
};
let mut failures = 0;
let mut check = |name: &str, result: Result<String>| match result {
Ok(detail) => eprintln!("PASS {name}: {detail}"),
Err(error) => {
failures += 1;
eprintln!("FAIL {name}: {error:#}");
}
};
let turnstile = |page, widget| Turnstile {
url: managed.clone(),
page,
widget,
};
let navigated = turnstile(PageSource::Navigate, None);
check(
"solve_turnstile(Navigate)",
token(browser.solve_turnstile(navigated, &options).await),
);
let page = PageSource::Html {
html: html.clone(),
referrer_policy: None,
};
check(
"solve_turnstile(Html)",
token(
browser
.solve_turnstile(turnstile(page, None), &options)
.await,
),
);
let blank = turnstile(PageSource::Blank, Some(widget.clone()));
check(
"solve_turnstile(Blank, widget)",
token(browser.solve_turnstile(blank, &options).await),
);
let unknown = turnstile(PageSource::Blank, None);
let result = browser.solve_turnstile(unknown, &options).await;
check(
"solve_turnstile(Blank, no widget) is Config",
expect_error(result, |error| matches!(error, Error::Config(_))),
);
let challenged = Turnstile {
url: under_attack.clone(),
page: PageSource::Navigate,
widget: None,
};
let result = browser.solve_turnstile(challenged, &options).await;
check(
"solve_turnstile(under-attack) is Challenged",
expect_error(result, |error| matches!(error, Error::Challenged { .. })),
);
check(
"clear(under-attack)",
clearance(browser.clear(&under_attack, &options).await),
);
let result = browser.clear(&managed, &options).await;
check(
"clear(managed) is NotChallenged",
expect_error(result, |error| matches!(error, Error::NotChallenged)),
);
check(
"clear_fetched(under-attack)",
async {
let page = fetch(&under_attack).await?;
clearance(browser.clear_fetched(page, &options).await)
}
.await,
);
check(
"solve(managed)",
match browser.solve(&managed, &options).await {
Ok(Outcome::Token(token)) => Ok(format!("token of {} bytes", token.len())),
Ok(Outcome::Cleared(_)) => Err(anyhow::anyhow!("cleared instead of a token")),
Err(error) => Err(error.into()),
},
);
check(
"solve(under-attack)",
match browser.solve(&under_attack, &options).await {
Ok(Outcome::Cleared(cleared)) => Ok(format!("cf_clearance={}", cleared.clearance)),
Ok(Outcome::Token(_)) => Err(anyhow::anyhow!("a token instead of a clearance")),
Err(error) => Err(error.into()),
},
);
let sink = Arc::new(IframeUrl::default());
let recording = Options {
proxy: None,
sink: Some(sink.clone()),
};
check(
"send_first_payload(managed, widget)",
browser
.send_first_payload(&managed, Some(&widget), &recording)
.await
.map(|()| "sent".to_owned())
.map_err(Into::into),
);
let iframe = sink.0.lock().unwrap().take();
check(
"prepare(iframe)",
async {
let iframe: Url = iframe.context("no iframe URL was saved")?.parse()?;
browser.prepare(iframe, &options).await?;
Ok("prepared".to_owned())
}
.await,
);
ensure!(failures == 0, "{failures} checks failed");
eprintln!("all checks passed");
Ok(())
}
/// Loads `url` the way a caller of `clear_fetched` would: as the profile's browser.
async fn fetch(url: &Url) -> Result<FetchedPage> {
let client = Transport::read(Path::new(PROFILE))?.client(None)?;
let document = cfsolve::http::navigate(&client, url).await?;
let set_cookies = client
.cookies(&document.url)
.iter()
.map(|cookie| format!("{}={}", cookie.name(), cookie.value()))
.collect();
Ok(FetchedPage {
url: document.url,
status: document.status,
html: document.html,
referrer_policy: None,
set_cookies,
})
}
fn token(result: Result<String, Error>) -> Result<String> {
let token = result?;
ensure!(!token.is_empty(), "the token is empty");
Ok(format!("token of {} bytes", token.len()))
}
fn clearance(result: Result<cfsolve::Clearance, Error>) -> Result<String> {
let cleared = result?;
ensure!(
cleared
.cookies
.iter()
.any(|cookie| cookie.name() == "cf_clearance"),
"cf_clearance is not among the cookies"
);
Ok(format!(
"cf_clearance={}, protected page HTTP {}",
cleared.clearance, cleared.page.status
))
}
fn expect_error<T>(result: Result<T, Error>, expected: impl Fn(&Error) -> bool) -> Result<String> {
match result {
Ok(_) => bail!("succeeded"),
Err(error) if expected(&error) => Ok(error.to_string()),
Err(error) => bail!("wrong error {error:?}"),
}
}
+98
View File
@@ -0,0 +1,98 @@
//! Snapshot every stage2 analysis a saved session directory supports, for
//! comparing analysis output before and after a change.
//! Usage: stage2_snapshot <session-directory>
//!
//! The directory is one the challenge CLI writes: `iframe.js`,
//! `iframe.deobfuscated.js`, `response.decoded.txt` and, when present,
//! `second-response.decoded.txt`, `third-response.decoded.txt` and
//! `options.json`. Each analysis's error is recorded in
//! place of its result, so a regression in one does not hide the others.
use std::path::Path;
use std::{env, fs};
use anyhow::{Context, Result};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use cfsolve::challenge::program::PreparedSession;
use cfsolve::js::Options;
use cfsolve::script::Source;
use cfsolve::stage2::analysis::{self, ProgramOutcome};
use cfsolve::stage2::{call_stack, interaction};
use serde::Serialize;
use serde_json::{Map, Value, json};
use url::Url;
fn main() -> Result<()> {
let directory = env::args().nth(1).context("supply a session directory")?;
let directory = Path::new(&directory);
let read = |name: &str| fs::read_to_string(directory.join(name));
let program = |name: &str| -> Result<Option<Vec<u8>>> {
read(name)
.ok()
.map(|text| Ok(STANDARD.decode(text.trim())?))
.transpose()
};
let source = read("iframe.deobfuscated.js")?;
let original = read("iframe.js")?;
let mut snapshot = Map::new();
let prepared = Source::try_new(&source)?;
// The click stack reads the dispatch cases off the original's own
// deobfuscation, as the CLI does when it fetches the iframe.
let (_, cases) = call_stack::deobfuscate_with_cases(original.clone())?;
let analysis = program("response.decoded.txt")?
.context("no first response")
.and_then(|program| {
let analysis = analysis::analyze(&prepared, &program)?;
Ok(serde_json::to_value(analysis.artifact())?)
});
snapshot.insert("analysis".into(), record(analysis));
// The iframe's URL only places the POST, which this ignores.
let base = Url::parse("https://challenges.cloudflare.com/")?;
let installed = PreparedSession::try_new(&prepared, &base).map(|session| {
let installed = session.into_program().installed;
json!({"options": installed.options, "window": installed.window})
});
snapshot.insert("installed".into(), record(installed));
for name in ["response", "second-response", "third-response"] {
if let Some(program) = program(&format!("{name}.decoded.txt"))? {
let outcome = prepared
.disassemble(&program)
.map(|listing| ProgramOutcome::of(&listing).to_string());
snapshot.insert(format!("{name}-outcome"), record(outcome));
}
}
if let Some(program) = program("second-response.decoded.txt")? {
let checkbox_program = prepared
.disassemble(&program)
.and_then(|listing| interaction::recover(&listing));
if let Ok(plan) = &checkbox_program {
let diagnostics = &plan.diagnostics;
let frames = call_stack::recover(
&original,
&cases,
diagnostics.construct,
diagnostics.callback_arity,
);
snapshot.insert("callback_frames".into(), record(frames));
if let Ok(options) = read("options.json") {
let options: Result<Options> =
serde_json::from_str(&options).map_err(anyhow::Error::from);
let queries =
options.and_then(|options| interaction::checkbox::queries(&prepared, &options));
snapshot.insert("checkbox_queries".into(), record(queries));
}
}
snapshot.insert("interaction".into(), record(checkbox_program));
}
println!("{}", serde_json::to_string_pretty(&snapshot)?);
Ok(())
}
/// `result` as JSON, or its error in its place.
fn record(result: Result<impl Serialize>) -> Value {
result
.and_then(|value| Ok(serde_json::to_value(value)?))
.unwrap_or_else(|error| json!({"error": format!("{error:#}")}))
}
+26
View File
@@ -0,0 +1,26 @@
//! Fetch a TLS echo page through the client a fingerprint's transport
//! describes, to compare its ClientHello and HTTP/2 settings with a real
//! browser's view of the same page.
//! Usage: tls_echo <fingerprint.json> [url]
use std::env;
use std::path::Path;
use anyhow::{Context, Result};
use cfsolve::fingerprint::Transport;
use cfsolve::http::navigate;
use url::Url;
#[tokio::main]
async fn main() -> Result<()> {
let mut args = env::args().skip(1);
let path = args.next().context("supply a fingerprint JSON file")?;
let url = args
.next()
.unwrap_or_else(|| "https://tls.peet.ws/api/all".to_owned());
let browser = Transport::read(Path::new(&path))?.client(None)?;
// Opened the way the solver opens an embedding page.
let document = navigate(&browser, &Url::parse(&url)?).await?;
print!("{}", document.html);
Ok(())
}
+147
View File
@@ -0,0 +1,147 @@
//! Structured disassembly snapshots, for comparing VM changes on real sessions.
//!
//! `vm_snapshot <deobfuscated.js> <program.txt|-> [name,...]` prints every
//! instruction, path, function entry, hidden branch and failure of the
//! program, one per line. `-` disassembles the script's embedded program. The
//! optional third argument lists API names to try on hashed branches, as
//! the probe analysis does with `cf-chl-peek`.
//!
//! `vm_snapshot --fixture <deobfuscated.js>` prints just the function that
//! defines the VM, as a script of its own: enough to build a `Machine`.
use std::time::Instant;
use std::{env, fs};
use anyhow::{Context, Result, bail};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use cfsolve::script::Source;
use swc_core::common::{FileName, SourceMap, Spanned};
use swc_core::ecma::ast::{Class, ClassMember, Decl, Expr, Function, Lit, PropName, Stmt};
use swc_core::ecma::parser::{Parser, StringInput, Syntax};
use swc_core::ecma::visit::{Visit, VisitWith};
fn main() -> Result<()> {
let arguments: Vec<String> = env::args().skip(1).collect();
match arguments.as_slice() {
[flag, script] if flag == "--fixture" => fixture(script),
[script, program, rest @ ..] => snapshot(script, program, rest.first().map(String::as_str)),
_ => bail!("usage: vm_snapshot <deobfuscated.js> <program.txt|-> [names]"),
}
}
fn snapshot(path: &str, program: &str, names: Option<&str>) -> Result<()> {
let source = fs::read_to_string(path)?;
let text = if program == "-" {
let start =
source.find("runProgram(`").context("no embedded program")? + "runProgram(`".len();
let end = start + source[start..].find('`').context("unterminated program")?;
source[start..end].to_owned()
} else {
fs::read_to_string(program)?
};
let program = STANDARD.decode(text.trim())?;
let names: Vec<&str> = names.map_or_else(Vec::new, |names| names.split(',').collect());
let source = Source::try_new(&source)?;
let started = Instant::now();
let machine = source.machine()?;
let built = started.elapsed();
let listing = machine.disassemble_from(&program, &[machine.entry()], &names)?;
let total = started.elapsed();
println!("entry {:?}", (machine.entry().pc, machine.entry().key));
for instruction in listing.instructions.values() {
println!(
"instruction {} {} op{}",
instruction.pc, instruction.key, instruction.opcode
);
for path in &instruction.paths {
println!(" path {:?} -> {:?}", path.conditions, path.exit);
for effect in &path.effects {
println!(" {effect:?}");
}
}
}
// Printed as the tuples these once were, so snapshots stay comparable.
for function in &listing.functions {
println!("function {:?}", (function.pc, function.key));
}
for hidden in &listing.hidden {
println!(
"hidden {:?}",
(
hidden.compare,
&hidden.string,
(hidden.target.pc, hidden.target.key)
)
);
}
for failure in &listing.failures {
println!(
"failure {:?}",
(failure.pc, failure.key, failure.to_string())
);
}
eprintln!(
"{} instructions, {} functions, {} hidden, {} failures; machine {:.3}s, total {:.3}s",
listing.instructions.len(),
listing.functions.len(),
listing.hidden.len(),
listing.failures.len(),
built.as_secs_f64(),
total.as_secs_f64(),
);
Ok(())
}
/// The innermost function declaring a class with a `run` method, printed as
/// an immediately invoked expression with nothing else of the script.
fn fixture(path: &str) -> Result<()> {
let source = fs::read_to_string(path)?;
let source_map = SourceMap::default();
let file = source_map.new_source_file(FileName::Custom(path.into()).into(), source.clone());
let script = Parser::new(Syntax::default(), StringInput::from(&*file), None)
.parse_script()
.map_err(|error| anyhow::anyhow!("{error:?}"))?;
let mut finder = Finder(None);
script.visit_with(&mut finder);
let function = finder.0.context("no VM class in the script")?;
let span = function.span();
let start = file.start_pos.0;
let text = &source[(span.lo.0 - start) as usize..(span.hi.0 - start) as usize];
println!("({text})();");
Ok(())
}
struct Finder(Option<Function>);
impl Visit for Finder {
fn visit_function(&mut self, function: &Function) {
if let Some(body) = &function.body
&& body.stmts.iter().any(|statement| match statement {
Stmt::Decl(Decl::Class(declaration)) => has_run(&declaration.class),
_ => false,
})
{
self.0 = Some(function.clone());
}
function.visit_children_with(self);
}
}
fn has_run(class: &Class) -> bool {
class.body.iter().any(|member| {
let ClassMember::Method(method) = member else {
return false;
};
match &method.key {
PropName::Ident(name) => &*name.sym == "run",
PropName::Str(name) => name.value == *"run",
PropName::Computed(computed) => {
matches!(&*computed.expr, Expr::Lit(Lit::Str(name)) if name.value == *"run")
}
_ => false,
}
})
}
+55
View File
@@ -0,0 +1,55 @@
//! Show how a plan's probes translate into the reference build's names.
//! Usage: vocabulary <plan.json> <probe index> [reference names to look for...]
//!
//! Prints where the probe's translated strings still differ from its
//! reference probe's, which is where a recognizer's names can go missing.
use std::collections::HashSet;
use std::{env, fs};
use anyhow::{Context, Result};
use cfsolve::stage2::vocabulary::Vocabulary;
use serde_json::Value;
fn main() -> Result<()> {
let mut args = env::args().skip(1);
let plan: Value = serde_json::from_slice(&fs::read(args.next().context("supply plan.json")?)?)?;
let index: usize = args.next().context("supply a probe index")?.parse()?;
let probes = plan["probes"].as_array().context("plan has no probes")?;
// A saved plan's features are the session's strings, in order.
let session: Vec<Vec<String>> = probes
.iter()
.map(|probe| {
probe["features"]
.as_array()
.into_iter()
.flatten()
.filter_map(|text| Some(text.as_str()?.to_owned()))
.collect()
})
.collect();
let vocabulary = Vocabulary::infer(&session);
let position = index - 1;
let partner = vocabulary
.partner(position)
.context("the probe has no reference partner")?;
println!("reference probe {partner}");
let translated: Vec<&str> = session[position]
.iter()
.map(|text| vocabulary.to_reference(position, text))
.collect();
let reference: Value = serde_json::from_str(include_str!("../src/stage2/reference.json"))?;
let reference = reference["probes"][partner - 1]
.as_array()
.context("no reference strings")?;
let shared: HashSet<&str> = translated.iter().copied().collect();
for text in reference.iter().filter_map(Value::as_str) {
if !shared.contains(text) {
println!("missing {text:.80}");
}
}
for name in args {
println!("{name}: {}", translated.contains(&name.as_str()));
}
Ok(())
}
+72
View File
@@ -0,0 +1,72 @@
//! Compares the record field order analysis predicts with the order browsers sent.
//! Usage: write_order_check <session directory>...
//!
//! Each directory is one capture proxy session: `capture.json` holds the iframe HTML and the
//! browser's second payload, `session.json` the decoded probe program. Fields go in sorted, so
//! a match comes from the recovered write order rather than the browser's own.
use std::{env, fs};
use anyhow::{Context, Result};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use cfsolve::script::Source;
use cfsolve::stage2::analysis;
use cfsolve::{JsObject, JsValue, challenge};
use serde_json::Value;
fn main() -> Result<()> {
let (mut matched, mut differ) = (0, 0);
for directory in env::args().skip(1) {
let read = |name: &str| -> Result<Value> {
let bytes = fs::read(format!("{directory}/{name}"))?;
Ok(serde_json::from_slice(&bytes)?)
};
let (capture, session) = (read("capture.json")?, read("session.json")?);
let html = capture["iframeHtml"].as_str().context("no iframe HTML")?;
let deobfuscated = cfsolve::deobfuscate(challenge::inline_javascript(html)?)?;
let source = Source::try_new(&deobfuscated.text)?;
let program = session["posts"][0]["decodedProgram"]
.as_str()
.context("no decoded probe program")?;
let analysis = analysis::analyze(&source, &STANDARD.decode(program.trim())?)?;
let plan = analysis.plan();
let payload: JsValue = capture["payloads"][1]["payload"].clone().into();
let names = plan.record_fields.names();
for probe in plan.probes() {
let Some(record) = payload[probe.index.to_string()].as_object() else {
continue;
};
let sent: Vec<&String> = record.keys().collect();
let mut fields: Vec<(String, JsValue)> = record
.iter()
.filter(|(name, _)| !names.contains(&name.as_str()))
.map(|(name, value)| (name.clone(), value.clone()))
.collect();
fields.sort_by(|(left, _), (right, _)| left.cmp(right));
let arranged = probe.writes.arrange(JsObject::from_iter(fields));
let predicted: Vec<&String> = names[1..5]
.iter()
.copied()
.chain(arranged.early.keys().map(String::as_str))
.chain(names[5..].iter().copied())
.chain(arranged.late.keys().map(String::as_str))
.filter_map(|name| record.get_key_value(name).map(|(key, _)| key))
.collect();
if predicted == sent {
matched += 1;
} else {
differ += 1;
let kind = probe
.operation
.as_ref()
.map_or("-".into(), |operation| operation.family().to_string());
println!("{directory} probe {} ({kind})", probe.index);
println!(" sent {sent:?}");
println!(" predicted {predicted:?}");
}
}
}
println!("{matched} match, {differ} differ");
Ok(())
}
+494
View File
@@ -0,0 +1,494 @@
{
"engine": "webkit",
"transport": {
"profile": "safari_ios_26.2",
"platform": "ios",
"headers": {
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.6.2 Mobile/15E148 Safari/604.1"
},
"requests": {
"headers": {
"navigation": [
"sec-fetch-dest: document",
"user-agent",
"upgrade-insecure-requests: 1",
"accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"sec-fetch-site: none",
"sec-fetch-mode: navigate",
"accept-language: en-US,en;q=0.9",
"priority: u=0, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"iframe": [
"sec-fetch-dest: iframe",
"user-agent",
"accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"referer",
"sec-fetch-site: cross-site",
"sec-fetch-mode: navigate",
"accept-language: en-US,en;q=0.9",
"priority: u=0, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"script": [
"sec-fetch-dest: script",
"user-agent",
"accept: */*",
"referer",
"sec-fetch-site: cross-site",
"sec-fetch-mode: no-cors",
"accept-language: en-US,en;q=0.9",
"priority: u=3, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"cors_script": [
"sec-fetch-dest: script",
"user-agent",
"accept: */*",
"referer",
"sec-fetch-site: cross-site",
"origin",
"sec-fetch-mode: cors",
"accept-language: en-US,en;q=0.9",
"priority: u=3, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"script_redirect": [
"accept: */*",
"sec-fetch-site: cross-site",
"priority: u=3, i",
"sec-fetch-mode: no-cors",
"user-agent",
"accept-language: en-US,en;q=0.9",
"sec-fetch-dest: script",
"referer",
"accept-encoding: gzip, deflate, br, zstd"
],
"orchestrator": [
"sec-fetch-dest: script",
"user-agent",
"accept: */*",
"referer",
"sec-fetch-site: same-origin",
"sec-fetch-mode: no-cors",
"accept-language: en-US,en;q=0.9",
"priority: u=1, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"page_image": [
"sec-fetch-dest: image",
"user-agent",
"accept: image/webp,image/avif,image/jxl,image/heic,image/heic-sequence,video/*;q=0.8,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5",
"referer",
"sec-fetch-site: same-origin",
"sec-fetch-mode: no-cors",
"accept-language: en-US,en;q=0.9",
"priority: u=5, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"orchestrator_post": [
"accept: */*",
"content-type: text/plain;charset=UTF-8",
"sec-fetch-site: same-origin",
"origin",
"cf-chl",
"content-length",
"sec-fetch-mode: cors",
"user-agent",
"referer",
"sec-fetch-dest: empty",
"cf-chl-ra: 0",
"accept-language: en-US,en;q=0.9",
"priority: u=3, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"challenge_post": [
"accept: */*",
"content-type: text/plain;charset=UTF-8",
"sec-fetch-site: same-origin",
"origin",
"cf-chl",
"content-length",
"sec-fetch-mode: cors",
"user-agent",
"referer",
"sec-fetch-dest: empty",
"cf-chl-ra: 0",
"accept-language: en-US,en;q=0.9",
"priority: u=3, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"image": [
"sec-fetch-dest: image",
"user-agent",
"accept: image/webp,image/avif,image/jxl,image/heic,image/heic-sequence,video/*;q=0.8,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5",
"referer",
"sec-fetch-site: same-origin",
"sec-fetch-mode: no-cors",
"accept-language: en-US,en;q=0.9",
"priority: u=5, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"worker_fetch": [
"sec-fetch-dest: empty",
"user-agent",
"accept: */*",
"sec-fetch-site",
"cache-control: max-age=0",
"sec-fetch-mode: cors",
"accept-language: en-US,en;q=0.9",
"priority: u=3, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"worker_fetch_without_credentials": [
"sec-fetch-dest: empty",
"user-agent",
"accept: */*",
"sec-fetch-site",
"pragma: no-cache",
"cache-control: no-cache",
"sec-fetch-mode: cors",
"accept-language: en-US,en;q=0.9",
"priority: u=3, i",
"accept-encoding: gzip, deflate, br, zstd"
],
"form": [
"accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"content-type: application/x-www-form-urlencoded",
"sec-fetch-site",
"origin",
"sec-fetch-mode: navigate",
"user-agent",
"referer",
"sec-fetch-dest: document",
"content-length",
"accept-language: en-US,en;q=0.9",
"priority: u=0, i",
"accept-encoding: gzip, deflate, br, zstd"
]
}
}
},
"browser": {
"inner_width": 375,
"inner_height": 553,
"challenge_page": {
"top": 378,
"left": 16,
"right": 359
}
},
"timeline": {
"script_fetch": 90.0,
"implicit_render": 2,
"render_start": 2,
"render_end": 3,
"init_start": 225,
"params_start": 225,
"collect_start": 225,
"sent": 226
},
"intervals": {
"initialise": 7,
"handoff": 8,
"collect": 20,
"send": 123
},
"orchestrator": {
"intervals": {
"initialise": 6,
"handoff": 0,
"collect": 92,
"send": 195
},
"program_startup_ms": 15,
"callback_ms": 30
},
"interaction": {
"width": 300,
"height": 65,
"checkbox": {"x": 9, "y": 20.5, "width": 168.125, "height": 24},
"ready_delay_ms": 1000,
"device_pixel_ratio": 2,
"touch": true
},
"resource_timing": {
"phases": {"request": 0.07, "response": 0.04},
"navigation": {"request": 0, "response": 0.9},
"sizes_exposed": false
},
"second": {
"facts": {
"worker_fetch_rejected": true,
"navigator": {
"hardwareConcurrency": 4
},
"media": {
"outcome": "observed",
"preparation": {
"receiver": {
"outcome": "observed",
"calls": [
{
"outcome": "returned",
"value": {
"codecs": [
{
"mimeType": "audio/opus",
"clockRate": 48000,
"sdpFmtpLine": "minptime=10;useinbandfec=1"
},
{
"mimeType": "audio/red",
"clockRate": 48000
},
{
"mimeType": "audio/G722",
"clockRate": 8000
},
{
"mimeType": "audio/PCMU",
"clockRate": 8000
},
{
"mimeType": "audio/PCMA",
"clockRate": 8000
},
{
"mimeType": "audio/CN",
"clockRate": 8000
},
{
"mimeType": "audio/telephone-event",
"clockRate": 48000
},
{
"mimeType": "audio/telephone-event",
"clockRate": 8000
}
]
}
},
{
"outcome": "returned",
"value": {
"codecs": [
{
"mimeType": "video/H264",
"clockRate": 90000,
"sdpFmtpLine": "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640c1f"
},
{
"mimeType": "video/rtx",
"clockRate": 90000
},
{
"mimeType": "video/H264",
"clockRate": 90000,
"sdpFmtpLine": "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"
},
{
"mimeType": "video/H264",
"clockRate": 90000,
"sdpFmtpLine": "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=640c1f"
},
{
"mimeType": "video/H264",
"clockRate": 90000,
"sdpFmtpLine": "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f"
},
{
"mimeType": "video/H265",
"clockRate": 90000
},
{
"mimeType": "video/VP8",
"clockRate": 90000
},
{
"mimeType": "video/VP9",
"clockRate": 90000,
"sdpFmtpLine": "profile-id=0"
},
{
"mimeType": "video/VP9",
"clockRate": 90000,
"sdpFmtpLine": "profile-id=2"
},
{
"mimeType": "video/red",
"clockRate": 90000
},
{
"mimeType": "video/ulpfec",
"clockRate": 90000
},
{
"mimeType": "video/flexfec-03",
"clockRate": 90000,
"sdpFmtpLine": "repair-window=10000000"
}
]
}
}
]
},
"type_support": [
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
],
"audio_decoding": null,
"video_decoding": null,
"message_length": null
},
"snapshot": {
"connection": {
"data_channel": true,
"sdp": "v=0\r\no=- 4614139716320554648 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\nc=IN IP4 0.0.0.0\r\na=ice-ufrag:6d+C\r\na=ice-pwd:v8cXDj/2Pl1T+N6K5egLTMMb\r\na=ice-options:trickle\r\na=fingerprint:sha-256 D9:43:8F:C3:9D:49:DA:18:B4:43:64:AF:88:16:1A:D5:95:C5:65:AE:39:6E:4E:78:DC:C8:F3:EF:69:75:2E:8A\r\na=setup:actpass\r\na=mid:0\r\na=sctp-port:5000\r\na=max-message-size:262144\r\n",
"pub_candidates": [
{
"candidate": "candidate:2090291584 1 udp 2113939711 a620b7e1-44bb-4d4b-9634-28efa841a789.local 50405 typ host generation 0 ufrag 6d+C network-cost 999",
"observed_ms": 1792606280929
},
{
"candidate": "candidate:1236921985 1 udp 2113937151 624f554e-e7a7-4613-8022-f2f6d9f1a264.local 57490 typ host generation 0 ufrag 6d+C network-cost 999",
"observed_ms": 1792606280929
},
{
"candidate": "candidate:913227231 1 udp 1677729535 192.0.2.1 62924 typ srflx raddr 0.0.0.0 rport 0 generation 0 ufrag 6d+C network-cost 999",
"observed_ms": 1792606280945
},
{
"candidate": "candidate:1148993836 1 udp 1677732095 2001:db8::1 50405 typ srflx raddr :: rport 0 generation 0 ufrag 6d+C network-cost 999",
"observed_ms": 1792606280946
}
]
},
"started_ms": 1792606282000,
"finished_ms": 1792606282002,
"ice_state": "complete"
}
},
"proof_worker": {
"digest_us": [
35.7,
31.8,
36.5
],
"startup_ms": [
27.5,
21.0,
28.8
]
},
"benchmark_worker": {
"compile_ms": [
11.5,
2.04,
1.16,
2.0
],
"kernel_ms_per_million": [
[
1.003,
1.035,
1.291,
1.214,
0.93,
0.972,
0.962,
0.971,
0.944,
0.946,
0.941,
0.971
],
[
1.055,
1.027,
1.061,
1.007,
0.932,
0.933,
0.942,
1.007,
0.946,
0.944,
0.947,
1.007
],
[
1.222,
0.801,
0.665,
0.645,
0.617,
0.621,
0.628,
0.645,
0.635,
0.626,
0.631,
0.645
],
[
5.798,
5.75,
5.978,
5.831,
5.567,
5.574,
5.707,
5.831,
5.609,
5.692,
5.707,
5.831
]
]
}
},
"document": {
"shadow_root": "[null,\"closed\",\"<body></body>\",\"\",4,4,37,\"function attachShadow() {\\n [native code]\\n}\"]"
},
"image": {
"effective_type": "",
"online": true
},
"durations": {
"clock_resolution": 6,
"date_parsing_offsets": 1,
"dom_mutation": 2,
"empty": 0,
"image": 14,
"media": 5,
"network_information": 0,
"parent_info": 0,
"performance_entries": 0,
"private_token": 1,
"worker_fetch": 1,
"worker_navigator": 7,
"stack": 1
},
"startup_ms": 105,
"pending_ms": 42
},
"answers": "safari-26-ios/answers.json",
"challenge_page_answers": "safari-26-ios/challenge-page-answers.json"
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
[toolchain]
channel = "1.98.0"
profile = "minimal"
components = ["clippy", "rustfmt"]
+12
View File
@@ -0,0 +1,12 @@
# Google Rust style guide: https://google.github.io/styleguide/rustguide.html
max_width = 100
# Nightly-only options from the guide; stable rustfmt ignores them, so apply
# them with `cargo +nightly fmt`.
imports_granularity = "Module"
hex_literal_case = "Lower"
format_macro_matchers = true
# The guide leaves import group order open; the nightly-only grouping keeps it
# automatic: std, then external crates, then `crate`/`super`/`self`.
group_imports = "StdExternalCrate"
+221
View File
@@ -0,0 +1,221 @@
//! Command-line options, help text, and option validation. Parsing does not read files.
use std::ffi::OsString;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::path::PathBuf;
use anyhow::{Context, Result, anyhow, bail, ensure};
use cfsolve::capture::CHALLENGE_HOST;
use url::Url;
pub const USAGE: &str = "\
Usage: capture-proxy --fingerprint <fingerprint.json> [options]
capture-proxy --help
Options:
--fingerprint <fingerprint.json>
Required. The browser the upstream requests present
themselves as; only its `transport` is read.
--site <url> Intercept the host of this page, which embeds the
widget. May be repeated.
--mitm-host <host> Intercept this host. May be repeated.
challenges.cloudflare.com is always intercepted.
--listen <address> Where the proxy listens. Default 127.0.0.1:8888.
--ca-dir <directory>
Where the proxy's CA is kept, generated on first use.
Default ./proxy-ca.
--out <directory> Where the session logs go. Default ./captures.
--upstream-proxy <url>
Reach the internet through an http://, https://,
socks5:// or socks5h:// proxy.
Point a browser at this proxy and open http://proxy.ca/ssl to
download its CA certificate.";
const LISTEN: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 8888));
const CA_DIR: &str = "./proxy-ca";
const OUT_DIR: &str = "./captures";
/// Proxy settings from the command line.
#[derive(Debug)]
pub struct ProxyArgs {
pub fingerprint: PathBuf,
pub listen: SocketAddr,
/// Lowercase hostnames to intercept, with the challenge host first.
pub mitm_hosts: Vec<String>,
pub ca_dir: PathBuf,
pub out_dir: PathBuf,
/// The `--upstream-proxy` value used for tunnels and forwarded requests.
pub upstream_proxy: Option<String>,
}
/// Parses options after the program name, or returns `None` for `--help`.
pub fn parse(arguments: impl IntoIterator<Item = OsString>) -> Result<Option<ProxyArgs>> {
let mut arguments = arguments.into_iter();
let (mut fingerprint, mut listen, mut ca_dir, mut out_dir) = (None, None, None, None);
let mut upstream_proxy = None;
let mut mitm_hosts = vec![CHALLENGE_HOST.to_owned()];
while let Some(argument) = arguments.next() {
let Some(name) = argument.to_str().filter(|text| text.starts_with('-')) else {
bail!(
"unexpected argument {}\n\n{USAGE}",
argument.to_string_lossy()
);
};
match name {
"-h" | "--help" => return Ok(None),
"--fingerprint" => once(&mut fingerprint, name, value(&mut arguments, name)?)?,
"--site" => {
let site = text(&mut arguments, name)?;
let site = Url::parse(&site).with_context(|| format!("invalid site URL {site}"))?;
let host = site
.host_str()
.with_context(|| format!("{name} {site} has no host"))?;
intercept(&mut mitm_hosts, host);
}
"--mitm-host" => intercept(&mut mitm_hosts, &text(&mut arguments, name)?),
"--listen" => {
let address = text(&mut arguments, name)?;
let address: SocketAddr = address.parse().with_context(|| {
format!("{name} needs a socket address such as {LISTEN}, not {address}")
})?;
once(&mut listen, name, address)?;
}
"--ca-dir" => once(&mut ca_dir, name, value(&mut arguments, name)?)?,
"--out" => once(&mut out_dir, name, value(&mut arguments, name)?)?,
"--upstream-proxy" => once(&mut upstream_proxy, name, text(&mut arguments, name)?)?,
_ => bail!("unknown option {name}\n\n{USAGE}"),
}
}
let fingerprint = fingerprint
.context("the proxy needs --fingerprint, whose transport its upstream requests present")?;
Ok(Some(ProxyArgs {
fingerprint: fingerprint.into(),
listen: listen.unwrap_or(LISTEN),
mitm_hosts,
ca_dir: ca_dir.unwrap_or_else(|| CA_DIR.into()).into(),
out_dir: out_dir.unwrap_or_else(|| OUT_DIR.into()).into(),
upstream_proxy,
}))
}
/// Adds `host` in lowercase to match the proxy's hostname comparisons.
fn intercept(hosts: &mut Vec<String>, host: &str) {
let host = host.to_lowercase();
if !hosts.contains(&host) {
hosts.push(host);
}
}
/// Reads the next argument as the value of `option`. Rejects another option in its place. Use
/// `./--name` for a path starting with `--`.
fn value(arguments: &mut impl Iterator<Item = OsString>, option: &str) -> Result<OsString> {
let value = arguments
.next()
.with_context(|| format!("{option} needs a value\n\n{USAGE}"))?;
ensure!(
!value.to_str().is_some_and(|text| text.starts_with("--")),
"{option} needs a value, not {}",
value.to_string_lossy()
);
Ok(value)
}
/// Reads a text value with [`value`].
fn text(arguments: &mut impl Iterator<Item = OsString>, option: &str) -> Result<String> {
value(arguments, option)?
.into_string()
.map_err(|value| anyhow!("{option} needs text, not {}", value.to_string_lossy()))
}
fn once<T>(slot: &mut Option<T>, option: &str, value: T) -> Result<()> {
ensure!(slot.is_none(), "{option} is given more than once");
*slot = Some(value);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// Parses space-separated arguments.
fn parse(arguments: &str) -> Result<Option<ProxyArgs>, String> {
let arguments = arguments.split_whitespace().map(OsString::from);
super::parse(arguments).map_err(|error| format!("{error:#}"))
}
fn proxy(arguments: &str) -> ProxyArgs {
parse(arguments).expect(arguments).expect("not --help")
}
#[test]
fn reads_the_options_and_their_defaults() {
let defaults = proxy("--fingerprint f.json");
assert_eq!(defaults.fingerprint.to_str(), Some("f.json"));
assert_eq!(defaults.listen, LISTEN);
assert_eq!(defaults.mitm_hosts, [CHALLENGE_HOST]);
assert_eq!(defaults.ca_dir.to_str(), Some(CA_DIR));
assert_eq!(defaults.out_dir.to_str(), Some(OUT_DIR));
assert_eq!(defaults.upstream_proxy, None);
let given = proxy(
"--listen 0.0.0.0:9000 --ca-dir /tmp/ca --out /tmp/out \
--upstream-proxy socks5h://127.0.0.1:1080 --fingerprint f.json \
--site https://CaptchaTest.Book.BI/path --mitm-host CHALLENGES.cloudflare.com \
--mitm-host captchatest.book.bi --mitm-host Cdn.CaptchaTest.Book.BI",
);
assert_eq!(given.listen.to_string(), "0.0.0.0:9000");
assert_eq!(given.ca_dir.to_str(), Some("/tmp/ca"));
assert_eq!(given.out_dir.to_str(), Some("/tmp/out"));
let upstream_proxy = given.upstream_proxy.as_deref();
assert_eq!(upstream_proxy, Some("socks5h://127.0.0.1:1080"));
assert_eq!(
given.mitm_hosts,
[
CHALLENGE_HOST,
"captchatest.book.bi",
"cdn.captchatest.book.bi"
]
);
assert!(matches!(parse("--help"), Ok(None)));
assert!(matches!(parse("--out /tmp/out -h"), Ok(None)));
}
#[test]
fn rejects_what_it_cannot_interpret() {
let cases = [
("", "the proxy needs --fingerprint"),
("f.json", "unexpected argument f.json"),
("--fingerprint", "--fingerprint needs a value"),
(
"--fingerprint --listen",
"--fingerprint needs a value, not --listen",
),
(
"--fingerprint a --fingerprint b",
"--fingerprint is given more than once",
),
(
"--listen localhost",
"--listen needs a socket address such as 127.0.0.1:8888, not localhost",
),
(
"--site captchatest.book.bi",
"invalid site URL captchatest.book.bi",
),
(
"--site data:text/plain,",
"--site data:text/plain, has no host",
),
("--slove", "unknown option --slove"),
];
for (arguments, expected) in cases {
let error = parse(arguments).expect_err(arguments);
assert!(
error.starts_with(expected),
"{arguments:?} reported {error}"
);
}
}
}
+78
View File
@@ -0,0 +1,78 @@
//! Disk storage for the proxy's certificate authority and session logs.
use std::path::Path;
use anyhow::{Context, Result, bail};
use cfsolve::capture::{CA_HOST, CA_PATH, CertificateAuthority};
use sha2::Sha256;
/// Loads the certificate authority from `directory`, creating one if needed. Writes its PEM
/// copy on every call so it is ready to install.
pub fn certificate_authority(directory: &Path) -> Result<CertificateAuthority> {
create_dir(directory)?;
let cert_path = directory.join("ca-cert.der");
let key_path = directory.join("ca-key.der");
let ca = match (cert_path.exists(), key_path.exists()) {
(true, true) => {
eprintln!("loading the CA from {}", directory.display());
CertificateAuthority::load(&read(&cert_path)?, &read(&key_path)?)
.with_context(|| format!("loading the CA from {}", directory.display()))?
}
(false, false) => {
eprintln!("generating a fresh CA in {}", directory.display());
let ca = CertificateAuthority::generate()?;
write(&cert_path, ca.cert_der())?;
write(&key_path, &ca.key_der())?;
ca
}
// Keep the existing certificate because a phone may already trust it.
_ => bail!(
"{} holds only half of a CA: restore ca-cert.der and ca-key.der, or remove both",
directory.display()
),
};
write(&directory.join("ca-cert.pem"), ca.pem().as_bytes())?;
Ok(ca)
}
pub fn print_trust_instructions(ca: &CertificateAuthority) {
use sha2::Digest;
let digest = Sha256::digest(ca.cert_der());
let hex_bytes: Vec<String> = digest.iter().map(|byte| format!("{byte:02X}")).collect();
eprintln!("CA SHA-256 fingerprint:\n{}", hex_bytes.join(":"));
eprintln!("Install this CA on the phone (as PEM):\n{}", ca.pem());
eprintln!("Proxy clients can also download it at http://{CA_HOST}{CA_PATH} through the proxy");
}
pub fn create_dir(directory: &Path) -> Result<()> {
std::fs::create_dir_all(directory).with_context(|| format!("creating {}", directory.display()))
}
fn read(path: &Path) -> Result<Vec<u8>> {
std::fs::read(path).with_context(|| format!("reading {}", path.display()))
}
fn write(path: &Path, contents: &[u8]) -> Result<()> {
std::fs::write(path, contents).with_context(|| format!("writing {}", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_ca_is_generated_once_and_never_half_replaced() {
let directory =
std::env::temp_dir().join(format!("capture-proxy-ca-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&directory);
let generated = certificate_authority(&directory).unwrap();
assert!(directory.join("ca-cert.pem").is_file());
let loaded = certificate_authority(&directory).unwrap();
assert_eq!(loaded.cert_der(), generated.cert_der());
std::fs::remove_file(directory.join("ca-key.der")).unwrap();
let error = format!("{:#}", certificate_authority(&directory).err().unwrap());
assert!(error.contains("holds only half of a CA"), "{error}");
std::fs::remove_dir_all(&directory).unwrap();
}
}
+58
View File
@@ -0,0 +1,58 @@
//! Captures decrypted browser challenge payloads with [`cfsolve::capture`].
//!
//! Configure the phone to use this HTTP proxy, download its CA certificate from
//! `http://proxy.ca/ssl` through the proxy, and trust the certificate. Then load the target
//! site in Safari.
//!
//! Each iframe session is saved in `<out>/sessions/session-NNNN/`. Its `capture.json` can be
//! converted to `answers.json` with `cargo run --example build_profile`. `<out>/traffic.json`
//! records ClientHellos, HTTP/2 connection openings, and request headers. `<out>/bodies/` keeps
//! challenge pages, their orchestrator scripts and programs, and the Turnstile loader, each
//! named by its request's index in `traffic.json`. Pass the site with `--site` so its challenge
//! pages are intercepted.
//!
//! Ctrl-C waits for session extraction to finish and writes the logs. A second Ctrl-C writes
//! the logs without waiting.
mod cli;
mod io;
use std::env;
use anyhow::Result;
use cfsolve::capture::{CHALLENGE_HOST, CaptureProxy, Config, UpstreamProxy};
use cfsolve::fingerprint::Transport;
use tokio::runtime::Builder;
fn main() -> Result<()> {
let Some(arguments) = cli::parse(env::args_os().skip(1))? else {
println!("{}", cli::USAGE);
return Ok(());
};
let transport = Transport::read(&arguments.fingerprint)?;
let upstream_proxy: UpstreamProxy = match &arguments.upstream_proxy {
Some(url) => url.parse()?,
None => UpstreamProxy::Direct,
};
let config = Config {
listen: arguments.listen,
mitm_hosts: arguments.mitm_hosts,
challenge_host: CHALLENGE_HOST.to_owned(),
upstream_tls: true,
upstream_proxy,
out_dir: arguments.out_dir,
};
// Check that logs can be written before starting the proxy.
io::create_dir(&config.out_dir)?;
let ca = io::certificate_authority(&arguments.ca_dir)?;
io::print_trust_instructions(&ca);
let runtime = Builder::new_multi_thread().enable_all().build()?;
let result = runtime.block_on(async {
// Use the same upstream proxy for forwarded requests and tunnels.
let client = transport.client(arguments.upstream_proxy.as_deref())?;
CaptureProxy::try_new(config, client, ca)?.run().await
});
// Exit without waiting for an extraction still in progress.
runtime.shutdown_background();
result
}
+336
View File
@@ -0,0 +1,336 @@
//! Command-line forms, help text, and option validation. Parsing does not read files.
use std::ffi::{OsStr, OsString};
use std::path::PathBuf;
use anyhow::{Context, Result, anyhow, bail, ensure};
use cfsolve::{PageSource, Turnstile, Widget};
use url::Url;
pub const USAGE: &str = "\
Usage: challenge <iframe-url> <output-directory> --fingerprint <fingerprint.json>
challenge --page <page-url> <output-directory> --fingerprint <fingerprint.json>
challenge --page <page-url> <output-directory> --solve --fingerprint <fingerprint.json>
challenge --help
The output directory must be new or empty. A solve prints the widget's token,
or `cf_clearance=<value>` once a challenge page clears.
Options:
--fingerprint <fingerprint.json>
Required. The browser the session presents itself as.
--solve Answer the returned program and send the probe and
interaction POSTs. Needs --page; the fingerprint's
`answers` holds the device's stored probe answers.
--sitekey <sitekey>
The widget to answer: the page's .cf-turnstile
container with this sitekey, or, if the page renders
it from script, one rendered as turnstile.render
would. Without it, the page's first container.
Needs --page. A challenge page in the widget's
page's place fails the session.
--action <action>, --cdata <cdata>
The widget's action and cData, in place of its
container's. Need --sitekey.
--blank-page Render the --sitekey widget on a blank page at the
page's address instead of navigating to it. Needs
--solve.
--proxy <url> Send every request through an http://, https://,
socks5:// or socks5h:// proxy. Credentials go in the
URL: socks5h://user:password@host:port.";
/// Session settings from the command line.
#[derive(Debug)]
pub struct SessionArgs {
pub entry: Entry,
pub directory: PathBuf,
pub fingerprint: PathBuf,
pub proxy: Option<String>,
}
/// The page or iframe that starts a session, and how far the session goes.
#[derive(Debug)]
pub enum Entry {
/// Sends the iframe's first payload.
Iframe(Url),
/// Sends the first payload of `widget`, or of the page's first widget.
Page { url: Url, widget: Option<Widget> },
/// Solves the page's first widget, or clears its challenge page.
Solve(Url),
/// Solves the widget named by `--sitekey`.
Turnstile(Turnstile),
}
/// Parses arguments after the program name, or returns `None` for `--help`. Options may appear
/// anywhere until `--`.
pub fn parse(arguments: impl IntoIterator<Item = OsString>) -> Result<Option<SessionArgs>> {
let mut arguments = arguments.into_iter();
let (mut page, mut fingerprint, mut proxy) = (None, None, None);
let (mut sitekey, mut action, mut cdata) = (None, None, None);
let (mut solve, mut blank) = (None, None);
let mut positional = Vec::new();
while let Some(argument) = arguments.next() {
let Some(name) = argument
.to_str()
.filter(|text| text.starts_with('-') && *text != "-")
else {
positional.push(argument);
continue;
};
match name {
"--" => {
positional.extend(arguments.by_ref());
break;
}
"-h" | "--help" => return Ok(None),
"--solve" => once(&mut solve, name, ())?,
"--blank-page" => once(&mut blank, name, ())?,
"--page" => once(&mut page, name, value(&mut arguments, name)?)?,
"--fingerprint" => once(&mut fingerprint, name, value(&mut arguments, name)?)?,
"--sitekey" => once(&mut sitekey, name, text(&mut arguments, name)?)?,
"--action" => once(&mut action, name, text(&mut arguments, name)?)?,
"--cdata" => once(&mut cdata, name, text(&mut arguments, name)?)?,
"--proxy" => once(&mut proxy, name, proxy_url(&value(&mut arguments, name)?)?)?,
_ => bail!("unknown option {name}\n\n{USAGE}"),
}
}
let (solve, blank) = (solve.is_some(), blank.is_some());
ensure!(
sitekey.is_some() || (action.is_none() && cdata.is_none()),
"--action and --cdata require --sitekey: they configure the widget it names"
);
ensure!(
!blank || (solve && sitekey.is_some()),
"--blank-page requires --solve and --sitekey: a solve renders the widget it names"
);
let widget = sitekey.map(|sitekey| Widget {
sitekey,
action,
cdata,
});
let (entry, directory) = match (page, positional.as_slice()) {
(Some(page), [directory]) => {
let url = url(&page, "page")?;
let entry = match (solve, widget) {
(false, widget) => Entry::Page { url, widget },
(true, None) => Entry::Solve(url),
(true, widget @ Some(_)) => {
let page = if blank {
PageSource::Blank
} else {
PageSource::Navigate
};
Entry::Turnstile(Turnstile { url, page, widget })
}
};
(entry, directory)
}
(None, [iframe, directory]) => {
let iframe = url(iframe, "iframe")?;
ensure!(
!solve,
"--solve requires --page: answering the returned program needs the embedding page"
);
ensure!(
widget.is_none(),
"--sitekey requires --page: the embedding page renders the widget"
);
(Entry::Iframe(iframe), directory)
}
_ => bail!("{USAGE}"),
};
let fingerprint = fingerprint.context(
"a session needs --fingerprint, which describes the browser it presents, starting with its transport",
)?;
Ok(Some(SessionArgs {
entry,
directory: directory.into(),
fingerprint: fingerprint.into(),
proxy,
}))
}
/// Reads the next argument as the value of `option`. Rejects another option in its place. Use
/// `./--name` for a path starting with `--`.
fn value(arguments: &mut impl Iterator<Item = OsString>, option: &str) -> Result<OsString> {
let value = arguments
.next()
.with_context(|| format!("{option} needs a value\n\n{USAGE}"))?;
ensure!(
!value.to_str().is_some_and(|text| text.starts_with("--")),
"{option} needs a value, not {}",
value.to_string_lossy()
);
Ok(value)
}
/// Reads a text value with [`value`].
fn text(arguments: &mut impl Iterator<Item = OsString>, option: &str) -> Result<String> {
value(arguments, option)?
.into_string()
.map_err(|value| anyhow!("{option} needs text, not {}", value.to_string_lossy()))
}
fn once<T>(slot: &mut Option<T>, option: &str, value: T) -> Result<()> {
ensure!(slot.is_none(), "{option} is given more than once");
*slot = Some(value);
Ok(())
}
fn url(text: &OsStr, what: &str) -> Result<Url> {
let text = text
.to_str()
.with_context(|| format!("invalid {what} URL {}", text.to_string_lossy()))?;
Url::parse(text).with_context(|| format!("invalid {what} URL {text}"))
}
/// Reads `text` as a proxy URL whose scheme the client supports. Rejecting one here fails
/// before the output directory is created.
fn proxy_url(text: &OsStr) -> Result<String> {
let proxy = url(text, "proxy")?;
let scheme = proxy.scheme();
ensure!(
matches!(scheme, "http" | "https" | "socks5" | "socks5h"),
"unsupported proxy scheme {scheme}: --proxy takes http, https, socks5, or socks5h"
);
ensure!(proxy.has_host(), "the proxy URL has no host");
Ok(proxy.into())
}
#[cfg(test)]
mod tests {
use super::*;
/// Parses space-separated arguments.
fn parse(arguments: &str) -> Result<Option<SessionArgs>, String> {
let arguments = arguments.split_whitespace().map(OsString::from);
super::parse(arguments).map_err(|error| format!("{error:#}"))
}
fn session(arguments: &str) -> SessionArgs {
parse(arguments).expect(arguments).expect("not --help")
}
/// Options may appear anywhere until `--`.
#[test]
fn reads_the_command_forms() {
let iframe = session("https://x/iframe /tmp/out --fingerprint f.json");
assert!(matches!(iframe.entry, Entry::Iframe(url) if url.as_str() == "https://x/iframe"));
assert_eq!(iframe.directory.to_str(), Some("/tmp/out"));
let ended = session("--fingerprint f.json https://x/iframe -- --odd-directory");
assert_eq!(ended.directory.to_str(), Some("--odd-directory"));
let page = session("--page https://x/ /tmp/out --fingerprint f.json");
assert!(matches!(page.entry, Entry::Page { widget: None, .. }));
let named = session("--page https://x/ /tmp/out --sitekey k --action a --fingerprint f");
let Entry::Page {
widget: Some(widget),
..
} = &named.entry
else {
panic!("{:?} names no widget", named.entry);
};
assert_eq!(widget.sitekey, "k");
assert_eq!(widget.action.as_deref(), Some("a"));
assert_eq!(widget.cdata, None);
let solved = session("--solve --fingerprint f.json /tmp/out --page https://x/");
assert!(matches!(solved.entry, Entry::Solve(_)));
assert_eq!(solved.directory.to_str(), Some("/tmp/out"));
assert_eq!(solved.fingerprint.to_str(), Some("f.json"));
assert_eq!(solved.proxy, None);
let proxied =
session("https://x/iframe /tmp/out --proxy socks5h://u:p@h:1080 --fingerprint f");
assert_eq!(proxied.proxy.as_deref(), Some("socks5h://u:p@h:1080"));
let blank =
session("--page https://x/ /tmp/out --solve --sitekey k --blank-page --fingerprint f");
assert!(matches!(
blank.entry,
Entry::Turnstile(Turnstile {
page: PageSource::Blank,
widget: Some(_),
..
})
));
assert!(matches!(parse("--help"), Ok(None)));
assert!(matches!(parse("https://x/ -h"), Ok(None)));
}
#[test]
fn rejects_what_it_cannot_interpret_or_honour() {
let cases = [
("", "Usage:"),
("one", "Usage:"),
("one two three", "Usage:"),
("--page https://x/ one two", "Usage:"),
("--page", "--page needs a value"),
("not-a-url /tmp/out", "invalid iframe URL"),
("https://x/ /tmp/out --slove", "unknown option --slove"),
(
"https://x/ /tmp/out --fingerprint a --fingerprint b",
"--fingerprint is given more than once",
),
(
"--page https://x/ /tmp/out --solve --solve",
"--solve is given more than once",
),
(
"https://x/ /tmp/out --fingerprint --solve",
"--fingerprint needs a value, not --solve",
),
(
"https://x/ /tmp/out --fingerprint",
"--fingerprint needs a value",
),
("https://x/iframe /tmp/out", "a session needs --fingerprint"),
(
"--page https://x/ /tmp/out --solve",
"a session needs --fingerprint",
),
(
"https://x/iframe /tmp/out --solve",
"--solve requires --page",
),
(
"https://x/iframe /tmp/out --sitekey k",
"--sitekey requires --page",
),
(
"--page https://x/ /tmp/out --cdata c",
"--action and --cdata require --sitekey",
),
(
"--page https://x/ /tmp/out --sitekey a --sitekey b",
"--sitekey is given more than once",
),
(
"--page https://x/ /tmp/out --sitekey k --blank-page",
"--blank-page requires --solve and --sitekey",
),
(
"https://x/ /tmp/out --proxy h:1080",
"unsupported proxy scheme h",
),
(
"https://x/ /tmp/out --proxy socks5:h",
"the proxy URL has no host",
),
("https://x/ /tmp/out --proxy :1080", "invalid proxy URL"),
(
"https://x/ /tmp/out --proxy http://a --proxy http://b",
"--proxy is given more than once",
),
];
for (arguments, expected) in cases {
let error = parse(arguments).expect_err(arguments);
assert!(
error.starts_with(expected),
"{arguments:?} reported {error}"
);
}
}
}
+68
View File
@@ -0,0 +1,68 @@
//! Session artifacts in the output directory, with progress on standard error.
use std::io::ErrorKind;
use std::path::PathBuf;
use anyhow::{Context, Result, ensure};
use cfsolve::Sink;
/// Saves session artifacts as they become available so diagnostics survive later failures.
pub struct Artifacts {
directory: PathBuf,
}
impl Artifacts {
/// Opens a new or empty output directory before network access. Reusing a nonempty
/// directory could mix artifacts from different sessions.
pub fn try_new(directory: PathBuf) -> Result<Self> {
match std::fs::read_dir(&directory) {
Ok(mut entries) => ensure!(
entries.next().is_none(),
"{} is not empty; use a fresh session directory",
directory.display()
),
Err(error) if error.kind() == ErrorKind::NotFound => {
std::fs::create_dir_all(&directory)
.with_context(|| format!("creating {}", directory.display()))?;
}
Err(error) => {
return Err(error).with_context(|| format!("reading {}", directory.display()));
}
}
Ok(Self { directory })
}
}
impl Sink for Artifacts {
fn artifact(&self, name: &str, contents: &[u8]) -> Result<()> {
let path = self.directory.join(name);
std::fs::write(&path, contents).with_context(|| format!("writing {}", path.display()))
}
fn progress(&self, message: &str) {
eprintln!("{message}");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_session_directory_must_be_new_or_empty() {
let directory =
std::env::temp_dir().join(format!("challenge-artifacts-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&directory);
let fresh = directory.join("session");
let artifacts = Artifacts::try_new(fresh.clone()).unwrap();
assert!(fresh.is_dir());
Artifacts::try_new(fresh.clone()).expect("an empty directory is still fresh");
artifacts.artifact("payload.json", b"{}").unwrap();
let error = format!("{:#}", Artifacts::try_new(fresh.clone()).err().unwrap());
assert!(
error.ends_with("is not empty; use a fresh session directory"),
"{error}"
);
std::fs::remove_dir_all(&directory).unwrap();
}
}
+52
View File
@@ -0,0 +1,52 @@
//! Runs a [`cfsolve::Browser`] session from a page or iframe URL. Builds the first payload and,
//! with `--solve`, answers the probe and checkbox programs.
mod cli;
mod io;
use std::env;
use std::sync::Arc;
use anyhow::Result;
use cfsolve::{Browser, Options, Outcome};
use tokio::runtime::Builder;
use crate::cli::Entry;
use crate::io::Artifacts;
fn main() -> Result<()> {
let Some(arguments) = cli::parse(env::args_os().skip(1))? else {
println!("{}", cli::USAGE);
return Ok(());
};
// Load the browser before any network access.
let browser = Browser::read(&arguments.fingerprint)?;
let artifacts = Artifacts::try_new(arguments.directory)?;
let options = Options {
proxy: arguments.proxy,
sink: Some(Arc::new(artifacts)),
};
let runtime = Builder::new_multi_thread().enable_all().build()?;
runtime.block_on(async {
match arguments.entry {
Entry::Iframe(iframe) => browser.prepare(iframe, &options).await,
Entry::Page { url, widget } => {
browser
.send_first_payload(&url, widget.as_ref(), &options)
.await
}
Entry::Solve(url) => {
match browser.solve(&url, &options).await? {
Outcome::Token(token) => println!("{token}"),
Outcome::Cleared(cleared) => println!("cf_clearance={}", cleared.clearance),
}
Ok(())
}
Entry::Turnstile(turnstile) => {
println!("{}", browser.solve_turnstile(turnstile, &options).await?);
Ok(())
}
}
})?;
Ok(())
}
+438
View File
@@ -0,0 +1,438 @@
//! Describes the browser used by a session. Profiles and stored answers are validated before
//! any network requests.
//!
//! Fingerprint files use JSON and ignore unknown keys. The engine, transport, request headers,
//! page and orchestrator timelines, resource timing, interaction, probe timings, and navigator
//! are required. Errors identify missing fields. The `browser` page layout section uses
//! defaults when absent, but rejects invalid values, including `null`.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::{fs, mem};
use anyhow::{Context, Result, ensure};
use serde::Deserialize;
use serde_json::Value;
use wreq::header::USER_AGENT;
use crate::challenge::state::Intervals;
use crate::embedding_page::extra_params::Timeline;
use crate::embedding_page::page::Layout;
use crate::engine::Engine;
use crate::error::Error;
use crate::fingerprint::{self, Transport, TransportSection};
use crate::js::{JsObject, JsValue, Window};
use crate::resource_timing::Reporting;
use crate::stage2::interaction::native::Viewport;
use crate::stage2::payload::Document;
use crate::stage2::registry::Facts;
use crate::stage2::replay::Answers;
/// A validated profile shared by solves. Each solve starts a fresh browser session.
pub struct Browser {
pub(crate) transport: Transport,
pub(crate) page: Page,
pub(crate) solve: Solve,
}
/// Browser settings needed by the page that contains the widget.
pub(crate) struct Page {
pub layout: Layout,
pub timeline: Timeline,
pub intervals: Intervals,
pub orchestrator_pacing: OrchestratorPacing,
/// Resource timing for fetches whose total duration is the only measurement available.
pub resource_timing: Reporting,
}
/// Timing settings from the fingerprint's `orchestrator` section. Required even for ordinary
/// pages, since the response determines whether a challenge is needed. Durations must be
/// nonnegative.
#[derive(Deserialize)]
pub(crate) struct OrchestratorPacing {
/// Startup timestamp intervals (`URVD0`), time to payload construction (`shUar7`), and time
/// to sending (`mHsm4`).
pub intervals: Intervals,
/// Time from widget-program arrival to record creation.
pub program_startup_ms: u32,
/// Delay from iframe completion to widget callback settlement.
pub callback_ms: u32,
}
/// Settings and stored answers for programs returned by the server.
pub(crate) struct Solve {
pub profile: Profile,
/// Worker `navigator.hardwareConcurrency`, also reported by the click and proof programs.
pub hardware_concurrency: f64,
pub answers: Option<Answers>,
/// Separate stored answers for widgets on Cloudflare challenge pages, if needed.
pub challenge_page_answers: Option<Answers>,
pub viewport: Viewport,
}
/// Browser behavior from the fingerprint's `second` section. Durations must be nonnegative.
#[derive(Deserialize)]
pub(crate) struct Profile {
/// Probe measurements. This section is required but may be empty. Navigator values combine
/// stored capabilities, the transport user agent, and explicit profile overrides.
pub facts: Facts,
pub document: Document,
pub image: ImageProbe,
/// Window globals the iframe holds when the payload is sent.
#[serde(default)]
pub window: Window,
/// Duration of each kind of probe, in milliseconds.
#[serde(default)]
pub durations: BTreeMap<String, u32>,
/// Delay between receiving the program and starting its first probe.
pub startup_ms: u32,
/// Time the program allows pending work to finish before sending a response.
pub pending_ms: u32,
}
/// Navigator values read by the image probe. Connection data must match the network information
/// probe.
#[derive(Deserialize)]
pub(crate) struct ImageProbe {
/// `navigator.connection.effectiveType`.
pub effective_type: String,
/// `navigator.onLine`.
pub online: bool,
}
/// Fingerprint settings loaded for a solve.
#[derive(Deserialize)]
struct Fingerprint {
engine: Engine,
transport: TransportSection,
#[serde(default)]
browser: Layout,
timeline: Timeline,
intervals: Intervals,
orchestrator: OrchestratorPacing,
resource_timing: Reporting,
interaction: Viewport,
second: Profile,
/// Stored answer files, relative to the fingerprint file.
answers: Option<PathBuf>,
challenge_page_answers: Option<PathBuf>,
}
impl Browser {
/// Loads the fingerprint at `path` and the stored answers it names, relative to its directory.
pub fn read(path: impl AsRef<Path>) -> Result<Self, Error> {
let load = || {
let path = path.as_ref();
let fingerprint: Fingerprint = fingerprint::read(path)?;
let directory = path.parent().unwrap_or(Path::new(""));
let answers = stored_answers(directory, fingerprint.answers.as_deref())?;
let challenge_page_answers =
stored_answers(directory, fingerprint.challenge_page_answers.as_deref())?;
Self::configure(fingerprint, answers, challenge_page_answers)
};
load().map_err(Error::Config)
}
/// Uses a parsed fingerprint and the supplied answers instead of loading the answer files
/// named by the fingerprint.
pub fn try_new(
fingerprint: Value,
answers: Option<Answers>,
challenge_page_answers: Option<Answers>,
) -> Result<Self, Error> {
let load = || {
for answers in answers.iter().chain(&challenge_page_answers) {
answers.check()?;
}
let fingerprint: Fingerprint =
serde_json::from_value(fingerprint).context("reading the fingerprint")?;
Self::configure(fingerprint, answers, challenge_page_answers)
};
load().map_err(Error::Config)
}
fn configure(
fingerprint: Fingerprint,
answers: Option<Answers>,
challenge_page_answers: Option<Answers>,
) -> Result<Self> {
let transport = Transport::try_new(fingerprint.engine, fingerprint.transport)?;
let page = Page {
layout: fingerprint.browser,
timeline: fingerprint.timeline,
intervals: fingerprint.intervals,
orchestrator_pacing: fingerprint.orchestrator,
resource_timing: fingerprint.resource_timing,
};
let mut profile = fingerprint.second;
let facts = &mut profile.facts;
// The image and network information probes must report the same connection.
if let Some(effective_type) = facts
.connection
.as_ref()
.and_then(|connection| connection.get("effectiveType"))
{
ensure!(
effective_type.as_str() == Some(profile.image.effective_type.as_str()),
"fingerprint `second.image.effective_type` disagrees with `second.facts.connection.effectiveType`"
);
}
facts.navigator = navigator(
answers.as_ref().map(|answers| &answers.navigator),
mem::take(&mut facts.navigator),
transport
.headers
.get(USER_AGENT)
.and_then(|value| value.to_str().ok()),
);
let hardware_concurrency = facts
.navigator
.get("hardwareConcurrency")
.and_then(JsValue::as_f64)
.context(
"the navigator has no numeric `hardwareConcurrency`: give it in the stored answers or `second.facts.navigator`",
)?;
Ok(Self {
transport,
page,
solve: Solve {
profile,
hardware_concurrency,
answers,
challenge_page_answers,
viewport: fingerprint.interaction,
},
})
}
}
/// Builds the worker navigator from the stored one, then applies the HTTP user agent and explicit
/// profile properties. Partial overrides preserve the other stored capabilities.
fn navigator(stored: Option<&JsObject>, overrides: JsObject, user_agent: Option<&str>) -> JsObject {
let mut navigator = stored.cloned().unwrap_or_default();
if let Some(user_agent) = user_agent {
navigator.insert("userAgent".into(), JsValue::from(user_agent));
}
navigator.extend(overrides);
navigator
}
/// Loads stored answers from `path`, relative to the fingerprint's `directory`.
fn stored_answers(directory: &Path, path: Option<&Path>) -> Result<Option<Answers>> {
let Some(path) = path else {
return Ok(None);
};
let path = directory.join(path);
let bytes = fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
let answers: Answers = serde_json::from_slice(&bytes)
.with_context(|| format!("reading stored answers {}", path.display()))?;
answers.check()?;
Ok(Some(answers))
}
#[cfg(test)]
impl Browser {
/// Loads the tracked iOS Safari profile for tests.
pub(crate) fn safari() -> &'static Self {
static SAFARI: std::sync::OnceLock<Browser> = std::sync::OnceLock::new();
SAFARI.get_or_init(|| {
let profile = Path::new(env!("CARGO_MANIFEST_DIR")).join("profiles/safari-26-ios.json");
Self::read(profile).expect("the tracked iOS Safari profile loads")
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::js::{self, json};
#[test]
fn partial_navigator_override_preserves_stored_capabilities() {
let stored: JsObject = js::from_value(json!({
"hardwareConcurrency": 4, "userAgent": "captured", "deviceMemory": 16,
"languages": ["en-US", "en"], "platform": "Linux x86_64"
}))
.unwrap();
let overrides = JsObject::from_iter([("hardwareConcurrency".into(), JsValue::from(8))]);
let complete = navigator(Some(&stored), overrides, Some("current HTTP user agent"));
assert_eq!(
JsValue::Object(complete),
json!({
"hardwareConcurrency": 8, "userAgent": "current HTTP user agent",
"deviceMemory": 16, "languages": ["en-US", "en"], "platform": "Linux x86_64"
})
);
let explicit = JsObject::from_iter([("userAgent".into(), JsValue::from("explicit"))]);
assert_eq!(
navigator(Some(&stored), explicit, Some("header"))["userAgent"],
"explicit"
);
}
/// A complete fingerprint, using the tracked iOS Safari 26 profile's requests, timelines,
/// resource timing, interaction and worker costs.
fn complete() -> Value {
let tracked: Value = serde_json::from_str(include_str!("../profiles/safari-26-ios.json"))
.expect("the tracked profile is JSON");
let mut fingerprint = serde_json::json!({
"engine": "webkit",
"transport": {"profile": "safari_ios_26.2", "platform": "ios"},
"orchestrator": {
"intervals": {"initialise": 6, "handoff": 0, "collect": 92, "send": 195},
"program_startup_ms": 15, "callback_ms": 30},
"second": {"facts": {"navigator": {"hardwareConcurrency": 4},
"connection": {"effectiveType": "4g"}},
"document": {"shadow_root": "{}"},
"image": {"effective_type": "4g", "online": true},
"durations": {"image": 5}, "startup_ms": 400, "pending_ms": 15}
});
fingerprint["transport"]["requests"] = tracked["transport"]["requests"].clone();
for section in ["timeline", "intervals", "resource_timing", "interaction"] {
fingerprint[section] = tracked[section].clone();
}
for costs in ["proof_worker", "benchmark_worker"] {
fingerprint["second"]["facts"][costs] = tracked["second"]["facts"][costs].clone();
}
fingerprint
}
/// Browser facts have no defaults. Missing or invalid facts are reported before any
/// network requests.
#[test]
fn missing_or_invalid_browser_facts_are_named() {
for (pointer, value, expected) in [
("/engine", None, "missing field `engine`"),
(
"/engine",
Some(Value::from("gecko")),
"unknown variant `gecko`",
),
("/transport/profile", None, "missing field `profile`"),
("/transport/platform", None, "missing field `platform`"),
("/transport/requests", None, "missing field `requests`"),
(
"/transport/requests/headers",
None,
"missing field `headers`",
),
(
"/transport/requests/headers/image",
None,
"no order for `image` requests",
),
(
"/transport/requests/headers/iframe",
Some(serde_json::json!(["user-agent", "sec-fetch-dest"])),
"nothing gives `sec-fetch-dest` a value",
),
("/orchestrator", None, "missing field `orchestrator`"),
(
"/orchestrator/callback_ms",
None,
"missing field `callback_ms`",
),
("/orchestrator/intervals/send", None, "missing field `send`"),
(
"/orchestrator/callback_ms",
Some(Value::from(-1)),
"invalid value: integer `-1`",
),
(
"/orchestrator/intervals/collect",
Some(Value::from(-1)),
"invalid value: integer `-1`",
),
("/timeline", None, "missing field `timeline`"),
("/intervals", None, "missing field `intervals`"),
("/resource_timing", None, "missing field `resource_timing`"),
("/interaction", None, "missing field `interaction`"),
(
"/interaction/ready_delay_ms",
None,
"missing field `ready_delay_ms`",
),
("/second", None, "missing field `second`"),
(
"/second/facts/proof_worker",
None,
"missing field `proof_worker`",
),
(
"/second/facts/benchmark_worker",
None,
"missing field `benchmark_worker`",
),
("/second/image", None, "missing field `image`"),
("/second/image/online", None, "missing field `online`"),
(
"/second/durations/image",
Some(Value::from(-5)),
"invalid value: integer `-5`",
),
(
"/second/facts/navigator/hardwareConcurrency",
None,
"the navigator has no numeric `hardwareConcurrency`",
),
(
"/second/facts/navigator/hardwareConcurrency",
Some(Value::from("4")),
"the navigator has no numeric `hardwareConcurrency`",
),
(
"/second/facts/connection/effectiveType",
Some(Value::from("3g")),
"disagrees",
),
] {
let mut fingerprint = complete();
match value {
Some(value) => *fingerprint.pointer_mut(pointer).unwrap() = value,
None => {
let (parent, key) = pointer.rsplit_once('/').unwrap();
let parent = fingerprint.pointer_mut(parent).unwrap();
parent.as_object_mut().unwrap().remove(key).unwrap();
}
}
let error = Browser::try_new(fingerprint, None, None)
.err()
.unwrap_or_else(|| panic!("{pointer} was accepted"));
let error = format!("{error:#}");
assert!(error.contains(expected), "{pointer}: {error}");
}
}
#[test]
fn a_complete_fingerprint_resolves_its_facts() {
let browser = Browser::try_new(complete(), None, None).unwrap();
let (page, solve) = (&browser.page, &browser.solve);
assert_eq!(page.orchestrator_pacing.intervals.send, 195);
assert_eq!(page.orchestrator_pacing.program_startup_ms, 15);
assert_eq!(page.orchestrator_pacing.callback_ms, 30);
assert_eq!(solve.profile.durations["image"], 5);
assert_eq!(solve.profile.startup_ms, 400);
assert_eq!(solve.hardware_concurrency, 4.0);
assert_eq!(solve.profile.image.effective_type, "4g");
assert!(solve.profile.image.online);
assert!(solve.answers.is_none());
}
#[test]
fn tracked_profiles_load_with_their_answers() {
let profiles = Path::new(env!("CARGO_MANIFEST_DIR")).join("profiles");
for entry in fs::read_dir(profiles).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|extension| extension != "json") {
continue;
}
let browser = Browser::read(&path)
.unwrap_or_else(|error| panic!("{}: {error:#}", path.display()));
assert!(
browser.solve.answers.is_some(),
"{} names no stored answers",
path.display()
);
}
}
}
+32
View File
@@ -0,0 +1,32 @@
//! Rejects ambiguous script analysis results. Conflicting values indicate an unsupported script
//! build.
use std::fmt::Debug;
use anyhow::{Result, bail};
/// Returns the only item in `items`. Fails unless there is exactly one.
pub(crate) fn exactly_one<T>(items: impl IntoIterator<Item = T>, what: &str) -> Result<T> {
let mut items = items.into_iter();
match (items.next(), items.next()) {
(Some(item), None) => Ok(item),
(None, _) => bail!("expected one {what}, found 0"),
(Some(_), Some(_)) => bail!("expected one {what}, found {}", items.count() + 2),
}
}
/// Returns the distinct item in `items`, or `None` if empty. Ignores equal duplicates and
/// reports conflicting values in an error naming `what`.
pub(crate) fn at_most_one_distinct<T: PartialEq + Debug>(
items: impl IntoIterator<Item = T>,
what: &str,
) -> Result<Option<T>> {
let mut items = items.into_iter();
let Some(first) = items.next() else {
return Ok(None);
};
if let Some(other) = items.find(|other| *other != first) {
bail!("found conflicting {what} candidates: {first:?} and {other:?}");
}
Ok(Some(first))
}
+17
View File
@@ -0,0 +1,17 @@
//! Captures decrypted challenge payloads and transport details from browsers the solver cannot
//! drive, such as iOS Safari.
//!
//! Each challenge POST encrypts a seed under an RSA modulus in the iframe script. The proxy swaps
//! in its own modulus and rewraps the browser's seed under the original before forwarding it.
mod ca;
mod head;
mod proxy;
mod rsa;
mod sessions;
mod traffic;
mod upstream;
pub use ca::CertificateAuthority;
pub use proxy::{CA_HOST, CA_PATH, CHALLENGE_HOST, CaptureProxy, Config};
pub use upstream::{Credentials, UpstreamProxy};
+102
View File
@@ -0,0 +1,102 @@
//! Certificate authority trusted by the phone, with one leaf certificate per intercepted host.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use anyhow::Result;
use base64::engine::general_purpose::STANDARD;
use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair, KeyUsagePurpose};
use rustls::crypto::ring::sign;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::CertifiedKey;
/// A certificate authority that caches issued certificates by hostname. Its `Debug` output
/// omits keys, while satisfying rustls's trait requirement.
#[derive(Debug)]
pub struct CertificateAuthority {
cert: CertificateDer<'static>,
issuer: Issuer<'static, KeyPair>,
leaves: Mutex<HashMap<String, Arc<CertifiedKey>>>,
}
impl CertificateAuthority {
pub fn generate() -> Result<Self> {
let mut params = CertificateParams::new(vec![])?;
params
.distinguished_name
.push(DnType::CommonName, "capture-proxy CA");
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
params.key_usages = vec![
KeyUsagePurpose::DigitalSignature,
KeyUsagePurpose::KeyCertSign,
];
let key = KeyPair::generate()?;
let cert = params.self_signed(&key)?;
Self::load(cert.der(), &key.serialize_der())
}
/// Restores a certificate authority from [`Self::cert_der`] and [`Self::key_der`].
pub fn load(cert: &[u8], key: &[u8]) -> Result<Self> {
let cert = CertificateDer::from(cert.to_vec());
let key = KeyPair::try_from(&PrivateKeyDer::Pkcs8(key.into()))?;
Ok(Self {
issuer: Issuer::from_ca_cert_der(&cert, key)?,
cert,
leaves: Mutex::default(),
})
}
#[must_use]
pub fn cert_der(&self) -> &[u8] {
&self.cert
}
/// The CA key in PKCS#8 DER.
#[must_use]
pub fn key_der(&self) -> Vec<u8> {
self.issuer.key().serialize_der()
}
/// The CA certificate in PEM format for installation on the phone.
#[must_use]
pub fn pem(&self) -> String {
use base64::Engine;
let encoded = STANDARD.encode(&self.cert);
let lines: Vec<_> = encoded
.as_bytes()
.chunks(64)
.map(String::from_utf8_lossy)
.collect();
format!(
"-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n",
lines.join("\n")
)
}
/// Returns the certificate for `host`, issuing it on first use.
fn leaf(&self, host: &str) -> Result<Arc<CertifiedKey>> {
let mut leaves = self.leaves.lock().expect("the leaf cache lock");
if let Some(leaf) = leaves.get(host) {
return Ok(Arc::clone(leaf));
}
let key = KeyPair::generate()?;
let mut params = CertificateParams::new(vec![host.to_owned()])?;
params.distinguished_name.push(DnType::CommonName, host);
let cert = params.signed_by(&key, &self.issuer)?;
let signing = sign::any_supported_type(&PrivateKeyDer::Pkcs8(key.serialize_der().into()))?;
let leaf = Arc::new(CertifiedKey::new(vec![cert.der().clone()], signing));
leaves.insert(host.to_owned(), Arc::clone(&leaf));
Ok(leaf)
}
}
impl ResolvesServerCert for CertificateAuthority {
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
let host = hello.server_name()?.to_lowercase();
self.leaf(&host)
.inspect_err(|error| eprintln!("issuing a leaf for {host}: {error:#}"))
.ok()
}
}
+210
View File
@@ -0,0 +1,210 @@
//! Reads connection headers before forwarding streams: HTTP/1 request and response headers, TLS
//! ClientHellos, and HTTP/2 connection openings.
use anyhow::{Context, Result, bail, ensure};
use hyper::Method;
use hyper::http::uri::Authority;
use tokio::io::AsyncRead;
/// Maximum bytes to read before forwarding a stream.
const MAX_READ_AHEAD: usize = 64 * 1024;
const H2_PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
/// Reads one HTTP header block, preserving bytes read past its end.
pub(super) async fn read_head(stream: &mut (impl AsyncRead + Unpin)) -> Result<Vec<u8>> {
let mut head = Vec::new();
read_through(stream, &mut head, "the head", |bytes| {
bytes
.windows(4)
.position(|window| window == b"\r\n\r\n")
.map(|end| end + 4)
})
.await?;
Ok(head)
}
/// Reads into `bytes` until `end` returns the header length, keeping extra bytes for replay.
pub(super) async fn read_through(
stream: &mut (impl AsyncRead + Unpin),
bytes: &mut Vec<u8>,
what: &str,
end: impl Fn(&[u8]) -> Option<usize>,
) -> Result<usize> {
use tokio::io::AsyncReadExt;
let mut buffer = [0; 4096];
loop {
if let Some(length) = end(bytes) {
return Ok(length);
}
ensure!(
bytes.len() <= MAX_READ_AHEAD,
"{what} is over {MAX_READ_AHEAD} bytes"
);
let count = stream
.read(&mut buffer)
.await
.with_context(|| format!("reading {what}"))?;
ensure!(count != 0, "unexpected EOF in {what}");
bytes.extend_from_slice(&buffer[..count]);
}
}
/// The length of the TLS records carrying the ClientHello, once `bytes` holds all of them.
#[must_use]
pub(super) fn client_hello_length(bytes: &[u8]) -> Option<usize> {
// The first record holds the handshake type followed by the message length.
let needed = 4 + u24(bytes.get(6..9)?);
let (mut length, mut carried) = (0, 0);
while carried < needed {
let header = bytes.get(length..length + 5)?;
let fragment = usize::from(u16::from_be_bytes([header[3], header[4]]));
length += 5 + fragment;
carried += fragment;
}
(length <= bytes.len()).then_some(length)
}
/// The length of the HTTP/2 preface and frames through the end of the first header block.
#[must_use]
pub(super) fn h2_opening_length(bytes: &[u8]) -> Option<usize> {
const HEADERS: u8 = 0x1;
const CONTINUATION: u8 = 0x9;
const END_HEADERS: u8 = 0x4;
let mut length = H2_PREFACE.len();
loop {
let header = bytes.get(length..length + 9)?;
length += 9 + u24(&header[..3]);
if matches!(header[3], HEADERS | CONTINUATION) && header[4] & END_HEADERS != 0 {
return (length <= bytes.len()).then_some(length);
}
}
}
/// Reads the big-endian 24-bit length used in TLS handshakes and HTTP/2 frames.
fn u24(bytes: &[u8]) -> usize {
bytes
.iter()
.fold(0, |length, &byte| length << 8 | usize::from(byte))
}
/// Extracts the request or status line from an HTTP header block.
pub(super) fn first_line(head: &[u8]) -> Result<&str> {
let line = head
.split(|&byte| byte == b'\r' || byte == b'\n')
.next()
.unwrap_or_default();
std::str::from_utf8(line).context("the head's first line is not UTF-8")
}
/// Extracts the method and target from an HTTP request line, such as `CONNECT example.com:443`
/// or `GET http://proxy.ca/ssl`.
pub(super) fn request_line(head: &[u8]) -> Result<(Method, &str)> {
let line = first_line(head)?;
let mut parts = line.split_whitespace();
let (Some(method), Some(target)) = (parts.next(), parts.next()) else {
bail!("not an HTTP request: {line:?}");
};
let method = Method::from_bytes(method.as_bytes())
.with_context(|| format!("not an HTTP method: {method:?}"))?;
Ok((method, target))
}
/// Parses a CONNECT target into a lowercase host and a port, defaulting to 443.
pub(super) fn connect_target(target: &str) -> Result<(String, u16)> {
let target: Authority = target.parse().context("parsing the CONNECT target")?;
ensure!(!target.host().is_empty(), "CONNECT names an empty host");
Ok((
target.host().to_lowercase(),
target.port_u16().unwrap_or(443),
))
}
/// Whether an intercepted request needs a tunnel: a CONNECT or an upgrade such as WebSocket.
#[must_use]
pub(super) fn is_tunnel_request(head: &[u8]) -> bool {
let connect = request_line(head).is_ok_and(|(method, _)| method == Method::CONNECT);
connect
|| String::from_utf8_lossy(head)
.lines()
.skip(1)
.take_while(|line| !line.is_empty())
.any(|line| {
line.split_once(':')
.is_some_and(|(name, _)| name.trim().eq_ignore_ascii_case("upgrade"))
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn connect_targets_and_bad_request_lines() {
let parse = |target| connect_target(target).unwrap();
assert_eq!(parse("Example.com:8443"), ("example.com".to_owned(), 8443));
assert_eq!(parse("example.com"), ("example.com".to_owned(), 443));
assert!(connect_target("").is_err());
assert!(request_line(b"GARBAGE\r\n\r\n").is_err());
assert!(request_line(b"CONNECT\r\n\r\n").is_err());
}
/// A TLS handshake record carrying `fragment`.
fn record(fragment: &[u8]) -> Vec<u8> {
let length = u16::try_from(fragment.len()).unwrap().to_be_bytes();
[&[22, 3, 1], &length[..], fragment].concat()
}
/// An HTTP/2 frame of `kind` with `flags` and a `length`-byte payload.
fn frame(kind: u8, flags: u8, length: u8) -> Vec<u8> {
[
&[0, 0, length, kind, flags, 0, 0, 0, 1][..],
&vec![0; length.into()],
]
.concat()
}
#[test]
fn client_hellos_end_with_their_last_record() {
// The handshake type and length precede this six-byte ClientHello body.
let message = [1, 0, 0, 6, 10, 11, 12, 13, 14, 15];
let whole = record(&message);
assert_eq!(client_hello_length(&whole), Some(whole.len()));
assert_eq!(client_hello_length(&whole[..whole.len() - 1]), None);
assert_eq!(client_hello_length(&whole[..4]), None);
// The handshake spans two records. The browser has already sent more bytes after it.
let split = [record(&message[..7]), record(&message[7..]), vec![20]].concat();
assert_eq!(client_hello_length(&split), Some(split.len() - 1));
assert_eq!(client_hello_length(&split[..14]), None);
}
#[test]
fn h2_openings_end_with_the_first_header_block() {
let settings = frame(0x4, 0, 6);
let window_update = frame(0x8, 0, 4);
let headers = frame(0x1, 0x4 | 0x1, 3);
let opening = [H2_PREFACE, &settings, &window_update, &headers].concat();
let data = frame(0x0, 0x1, 2);
let read = [&opening[..], &data].concat();
assert_eq!(h2_opening_length(&read), Some(opening.len()));
assert_eq!(h2_opening_length(&opening[..opening.len() - 1]), None);
// A header block continued in a CONTINUATION frame ends there.
let unended = frame(0x1, 0, 3);
let continuation = frame(0x9, 0x4, 2);
let continued = [H2_PREFACE, &settings, &unended, &continuation].concat();
assert_eq!(h2_opening_length(&continued), Some(continued.len()));
assert_eq!(h2_opening_length(&continued[..continued.len() - 11]), None);
}
#[test]
fn upgrades_and_connects_tunnel() {
let websocket = b"GET /ws HTTP/1.1\r\nUpgrade: websocket\r\n\r\n";
assert!(is_tunnel_request(websocket));
assert!(is_tunnel_request(b"CONNECT x:443 HTTP/1.1\r\n\r\n"));
assert!(!is_tunnel_request(b"GET / HTTP/1.1\r\n\r\nUpgrade: body"));
assert!(!is_tunnel_request(H2_PREFACE));
}
}
+598
View File
@@ -0,0 +1,598 @@
//! CONNECT proxy that intercepts TLS for selected hosts and tunnels the rest.
//!
//! Intercepted connections use per-host certificates signed by the proxy CA, serve HTTP/1.1 or
//! HTTP/2, and forward requests through the emulated browser client; WebSocket upgrades are
//! tunneled. The proxy replaces the modulus in iframe HTML and rewraps challenge POST seeds;
//! other traffic passes through unchanged.
use std::convert::Infallible;
use std::io::Cursor;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::pin::pin;
use std::sync::{Arc, Mutex, MutexGuard};
use anyhow::{Context, Result};
use base64::engine::general_purpose::STANDARD;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::header::{self, AsHeaderName, HeaderMap};
use hyper::server::conn::{http1, http2};
use hyper::{Method, Request, Response, StatusCode, service};
use hyper_util::rt::{TokioExecutor, TokioIo};
use rustls::ServerConfig;
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio_rustls::TlsAcceptor;
use url::Url;
use super::ca::CertificateAuthority;
use super::head;
use super::rsa::{self, ProxyKey};
use super::sessions::{self, Iframe, Post, Sessions};
use super::traffic::{Connection, Traffic};
use super::upstream::{self, Stream, UpstreamProxy};
use crate::challenge;
use crate::http::{self, BrowserClient, Proxied};
const ESTABLISHED: &[u8] = b"HTTP/1.1 200 Connection Established\r\n\r\n";
/// The host serving Turnstile iframes and receiving their challenge POSTs.
pub const CHALLENGE_HOST: &str = "challenges.cloudflare.com";
/// Local hostname for downloading the CA certificate at [`CA_PATH`]. Supports HTTP and, after
/// the client trusts the CA, HTTPS. `GET /ssl` on the listening socket also serves the
/// certificate.
pub const CA_HOST: &str = "proxy.ca";
pub const CA_PATH: &str = "/ssl";
type ProxyResponse = Response<Full<Bytes>>;
/// Proxy serving and logging settings.
pub struct Config {
pub listen: SocketAddr,
/// Hostnames to intercept, lowercased, without ports.
pub mitm_hosts: Vec<String>,
/// The host whose challenge POSTs need rewrapping: [`CHALLENGE_HOST`] or a loopback test
/// origin.
pub challenge_host: String,
/// Whether intercepted requests go upstream over TLS. Loopback tests serve plain HTTP.
pub upstream_tls: bool,
/// How tunnels reach the internet.
pub upstream_proxy: UpstreamProxy,
/// Parent directory for session captures.
pub out_dir: PathBuf,
}
/// A running proxy with its sessions and capture logs.
pub struct CaptureProxy {
config: Config,
client: BrowserClient,
acceptor: TlsAcceptor,
ca: Arc<CertificateAuthority>,
sessions: Arc<Sessions>,
traffic: Mutex<Traffic>,
}
impl CaptureProxy {
/// Creates a proxy that sends upstream requests with `client`.
pub fn try_new(
config: Config,
client: BrowserClient,
ca: CertificateAuthority,
) -> Result<Self> {
let ca = Arc::new(ca);
let mut server = ServerConfig::builder()
.with_no_client_auth()
.with_cert_resolver(ca.clone());
server.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Ok(Self {
config,
client,
acceptor: TlsAcceptor::from(Arc::new(server)),
ca,
sessions: Arc::new(Sessions::new(ProxyKey::generate()?)),
traffic: Mutex::default(),
})
}
fn traffic(&self) -> MutexGuard<'_, Traffic> {
self.traffic.lock().expect("the traffic log lock")
}
/// Listens until Ctrl-C or SIGTERM, then waits for extraction and writes session and
/// traffic logs. A second stop request skips the wait.
pub async fn run(self) -> Result<()> {
let proxy = Arc::new(self);
let listener = TcpListener::bind(proxy.config.listen)
.await
.with_context(|| format!("binding {}", proxy.config.listen))?;
eprintln!("capture-proxy listening on {}", proxy.config.listen);
let mut shutdown = pin!(shutdown_requested());
loop {
tokio::select! {
accepted = listener.accept() => match accepted {
Ok((stream, peer)) => {
let proxy = Arc::clone(&proxy);
tokio::spawn(async move {
if let Err(error) = proxy.serve(stream).await {
eprintln!("{peer}: {error:#}");
}
});
}
Err(error) => eprintln!("accepting a client: {error}"),
},
() = &mut shutdown => break,
}
}
eprintln!("shutting down; finishing the session extractions (Ctrl-C again to skip)");
tokio::select! {
() = proxy.sessions.finish_extractions() => {}
() = shutdown_requested() => eprintln!("skipped the unfinished extractions"),
}
eprintln!("writing the session logs");
proxy.sessions.write_all(&proxy.config.out_dir);
match proxy.traffic().write(&proxy.config.out_dir) {
Ok(path) => eprintln!("traffic: {}", path.display()),
Err(error) => eprintln!("traffic: writing the log failed: {error:#}"),
}
Ok(())
}
/// Serves one client connection. Plain HTTP serves only CA downloads so new clients can
/// install trust. Other connections start with CONNECT.
async fn serve(self: Arc<Self>, mut client: TcpStream) -> Result<()> {
let head = head::read_head(&mut client).await?;
let (method, target) = head::request_line(&head)?;
if method != Method::CONNECT {
let response = match ca_path(target)? {
Some(path) => self.serve_ca(&method, &path),
None => text_response(
StatusCode::BAD_REQUEST,
"capture-proxy: plain HTTP only serves http://proxy.ca/ssl; browse https:// sites (CONNECT) or fetch the CA there",
),
};
return write_response(&mut client, response).await;
}
let (host, port) = head::connect_target(target)?;
if host == CA_HOST || self.config.mitm_hosts.contains(&host) {
return self.serve_mitm(client, &host, port).await;
}
let upstream = self.config.upstream_proxy.connect(&host, port).await?;
client.write_all(ESTABLISHED).await?;
tunnel(client, upstream).await
}
/// Serves `GET /ssl` locally on the CA host over plain HTTP or TLS. Rejects other requests
/// without contacting an upstream server.
fn serve_ca(&self, method: &Method, path: &str) -> ProxyResponse {
if path != CA_PATH {
return text_response(StatusCode::NOT_FOUND, "capture-proxy: try /ssl");
}
if *method != Method::GET {
return text_response(
StatusCode::METHOD_NOT_ALLOWED,
"capture-proxy: only GET serves the CA download",
);
}
// This content type prompts phones to offer certificate installation.
Response::builder()
.header(header::CONTENT_TYPE, "application/x-x509-ca-cert")
.header(
header::CONTENT_DISPOSITION,
"attachment; filename=\"capture-proxy-ca.crt\"",
)
.body(Full::from(self.ca.pem()))
.expect("static headers")
}
/// Terminates TLS for an intercepted host, logs the connection headers, and serves
/// requests.
async fn serve_mitm(
self: Arc<Self>,
mut client: TcpStream,
host: &str,
port: u16,
) -> Result<()> {
use tokio::io::AsyncReadExt;
client.write_all(ESTABLISHED).await?;
let mut read = Vec::new();
let length = head::read_through(
&mut client,
&mut read,
"the ClientHello",
head::client_hello_length,
)
.await?;
let client_hello = hex(&read[..length]);
// Replay the ClientHello to the TLS acceptor.
let (reader, writer) = tokio::io::split(client);
let client = tokio::io::join(Cursor::new(read).chain(reader), writer);
let mut tls = self
.acceptor
.accept(client)
.await
.context("TLS handshake")?;
let mut head = head::read_head(&mut tls).await?;
// The CA host is served here, never reached upstream.
let scheme = if self.config.upstream_tls {
"https"
} else {
"http"
};
let origin = (host != CA_HOST).then(|| format!("{scheme}://{host}:{port}"));
if origin.is_some() && head::is_tunnel_request(&head) {
let upstream = self.config.upstream_proxy.connect(host, port).await?;
// Start a separate TLS connection upstream because the browser's connection
// terminates here.
let mut upstream: Box<dyn Stream> = if self.config.upstream_tls {
Box::new(upstream::tls_connect(upstream, host).await?)
} else {
upstream
};
upstream.write_all(&head).await?;
return tunnel(tls, upstream).await;
}
let (_, server_connection) = tls.get_ref();
let alpn: Option<String> = server_connection
.alpn_protocol()
.map(|protocol| String::from_utf8_lossy(protocol).into_owned());
let h2 = alpn.as_deref() == Some("h2");
// Browsers send the first headers without waiting for server SETTINGS.
let h2_opening = if h2 {
let length = head::read_through(
&mut tls,
&mut head,
"the HTTP/2 opening",
head::h2_opening_length,
)
.await?;
Some(hex(&head[..length]))
} else {
None
};
let connection = self.traffic().connect(Connection {
host: host.to_owned(),
port,
client_hello,
alpn,
h2_opening,
});
// Replay the head and any frames read with it to hyper.
let (reader, writer) = tokio::io::split(tls);
let io = TokioIo::new(tokio::io::join(Cursor::new(head).chain(reader), writer));
let service = service::service_fn(move |request| {
let (proxy, origin) = (Arc::clone(&self), origin.clone());
async move {
Ok::<_, Infallible>(proxy.handle(origin.as_deref(), connection, request).await)
}
});
if h2 {
http2::Builder::new(TokioExecutor::new())
.serve_connection(io, service)
.await?;
} else {
http1::Builder::new().serve_connection(io, service).await?;
}
Ok(())
}
/// Handles one request on `connection`, returning 502 on failure. A missing `origin`
/// identifies a request to the local CA host.
async fn handle(
&self,
origin: Option<&str>,
connection: usize,
request: Request<Incoming>,
) -> ProxyResponse {
let Some(origin) = origin else {
return self.serve_ca(request.method(), request.uri().path());
};
let path = request
.uri()
.path_and_query()
.map_or("/", |path| path.as_str());
let url = format!("{origin}{path}");
let logged = self.traffic().request(connection, &url, &request);
let routed = self.route(logged, &url, request).await;
let response = routed.unwrap_or_else(|error| {
eprintln!("{origin}: {error:#}");
text_response(
StatusCode::BAD_GATEWAY,
&format!("capture-proxy: {error:#}"),
)
});
self.traffic().answered(logged);
response
}
/// Forwards request `logged`, rewrapping challenge POSTs and rewriting iframe GETs as
/// needed, and keeps the bodies of challenge pages and their scripts.
async fn route(
&self,
logged: usize,
url: &str,
request: Request<Incoming>,
) -> Result<ProxyResponse> {
let (parts, body) = request.into_parts();
let headers = end_to_end(&parts.headers);
let body = body
.collect()
.await
.context("reading the request body")?
.to_bytes();
if self.is_challenge_post(&parts.method, url) {
return self.post_challenge(url, headers, body).await;
}
let method = parts.method;
let mut upstream = self
.client
.proxy_fetch(method.clone(), url, headers, body)
.await?;
if let Some(kind) = kept(&method, url, &self.config.challenge_host, &upstream.headers) {
self.traffic().keep(logged, kind, decoded_body(&upstream));
}
let content_type = header_value(&upstream.headers, header::CONTENT_TYPE);
let html = content_type.to_ascii_lowercase().contains("html");
if method == Method::GET
&& html
&& let Some(rewritten) = self.rewrite_iframe(url, &upstream)
{
upstream.body = Bytes::from(rewritten);
}
Ok(passthrough(upstream))
}
/// Checks for a challenge-platform `/fo/` POST on the challenge host. Requests to site
/// paths pass through unchanged, including orchestrator POSTs: those use a script whose
/// modulus the proxy has not replaced.
fn is_challenge_post(&self, method: &Method, url: &str) -> bool {
*method == Method::POST
&& Url::parse(url).is_ok_and(|url| {
url.host_str() == Some(self.config.challenge_host.as_str())
&& challenge::is_post_path(url.path())
})
}
/// Unwraps a challenge POST's seed, rewraps it with the real modulus, and logs the payload.
/// Passes the response through unchanged. If no session can rewrap the POST, forwards it
/// unchanged and excludes that session from stored answers.
async fn post_challenge(
&self,
url: &str,
mut headers: HeaderMap,
body: Bytes,
) -> Result<ProxyResponse> {
let parsed = Url::parse(url).context("parsing the POST URL")?;
let Some(session) = self.sessions.bind(&parsed) else {
return self.forward(url, headers, body).await;
};
let Ok(encrypted) = std::str::from_utf8(&body) else {
self.sessions.lock()[session].poison("the POST body is not UTF-8");
return self.forward(url, headers, body).await;
};
let mut post = Post {
url: url.to_owned(),
cf_chl: header_value(&headers, "cf-chl"),
encrypted_body: encrypted.to_owned(),
..Post::default()
};
let rewrapped = match self.sessions.rewrap(session, encrypted) {
Ok(rewrapped) => rewrapped,
Err(error) => {
let error = format!("re-wrap failed: {error:#}");
let response = text_response(
StatusCode::BAD_GATEWAY,
&format!("capture-proxy: rejecting a POST that opens under no key: {error}"),
);
post.error = Some(error);
self.sessions.lock()[session].record(post);
return Ok(response);
}
};
post.seed = Some(hex(&rewrapped.seed));
post.padding = Some(rewrapped.padding);
headers.insert(header::CONTENT_LENGTH, rewrapped.body.len().into());
let upstream = self
.client
.proxy_fetch(Method::POST, url, headers, Bytes::from(rewrapped.body))
.await
.context("forwarding the re-wrapped POST")
.inspect_err(|error| self.sessions.lock()[session].poison(&format!("{error:#}")))?;
post.response_body = String::from_utf8_lossy(&decoded_body(&upstream)).into_owned();
post.decoded_program = decode_program(&parsed, &post.response_body);
if post.decoded_program.is_none() {
eprintln!("{url}: the POST response did not decode; forwarding anyway");
}
self.sessions.lock()[session].record(post);
Ok(passthrough(upstream))
}
async fn forward(&self, url: &str, headers: HeaderMap, body: Bytes) -> Result<ProxyResponse> {
let upstream = self
.client
.proxy_fetch(Method::POST, url, headers, body)
.await?;
Ok(passthrough(upstream))
}
/// Replaces the modulus in an iframe response and opens its session. Returns `None` for
/// bodies that cannot be rewritten; those pass through unchanged.
fn rewrite_iframe(&self, url: &str, upstream: &Proxied) -> Option<Vec<u8>> {
let encoding = header_value(&upstream.headers, header::CONTENT_ENCODING);
let html = String::from_utf8(http::decode_body(&upstream.body, &encoding).ok()?).ok()?;
let (rewritten, real_modulus) =
rsa::swap_modulus(&html, &self.sessions.proxy_key.modulus).ok()?;
let alphabet = challenge::inline_javascript(&html)
.and_then(|javascript| sessions::scan_alphabet(&javascript))
.inspect_err(|error| eprintln!("{url}: forwarding the original iframe: {error:#}"))
.ok()?;
let encoded = http::encode_body(rewritten.as_bytes(), &encoding).ok()?;
let session = self.sessions.open(Iframe {
url: url.to_owned(),
real_modulus,
scanned_alphabet: alphabet,
upstream_encoded_bytes: upstream.body.len() as u64,
upstream_decoded_bytes: html.len() as u64,
observed_encoded_bytes: encoded.len() as u64,
// Replacement preserves every decoded byte offset.
observed_decoded_bytes: html.len() as u64,
original: html,
rewritten,
});
eprintln!("{url}: rewrote the modulus (session {session})");
Some(encoded)
}
}
/// Identifies response bodies needed to reconstruct a challenge page's widget without network
/// access. Orchestrator programs stay masked with the ray identifier from their URL.
fn kept(
method: &Method,
url: &str,
challenge_host: &str,
headers: &HeaderMap,
) -> Option<&'static str> {
let url = Url::parse(url).ok()?;
let path = url.path();
let platform = path.starts_with("/cdn-cgi/challenge-platform/");
let on_challenge_host = url.host_str() == Some(challenge_host);
let challenged = header_value(headers, "cf-mitigated") == "challenge";
match *method {
// A form POST to a challenged site is answered with a challenge page too.
_ if challenged => Some("challenge-page.html"),
Method::GET if platform && path.contains("/orchestrate/") => Some("orchestrator.js"),
Method::GET if on_challenge_host && path.ends_with("/api.js") => Some("api.js"),
Method::POST if !on_challenge_host && challenge::is_post_path(path) => {
Some("orchestrator-response.txt")
}
_ => None,
}
}
/// Waits for Ctrl-C or SIGTERM so the proxy can write logs before exiting.
async fn shutdown_requested() {
use tokio::signal::unix::{self, SignalKind};
let mut terminate = unix::signal(SignalKind::terminate()).expect("watching for SIGTERM");
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = terminate.recv() => {}
}
}
/// Extracts the CA download path from a plain HTTP target. Origin-form targets address the
/// listen socket; absolute-form targets must name the CA host. Returns `None` for other hosts.
fn ca_path(target: &str) -> Result<Option<String>> {
if target.starts_with('/') {
let path = target.split(['?', '#']).next().unwrap_or(target);
return Ok(Some(path.to_owned()));
}
let url = Url::parse(target).context("parsing the plain-HTTP target")?;
let ca_host = url
.host_str()
.is_some_and(|host| host.eq_ignore_ascii_case(CA_HOST));
Ok(ca_host.then(|| url.path().to_owned()))
}
/// Writes `response` to a plain HTTP connection that closes afterward.
async fn write_response(client: &mut TcpStream, response: ProxyResponse) -> Result<()> {
let (parts, body) = response.into_parts();
let Ok(body) = body.collect().await;
let body = body.to_bytes();
let headers: String = parts
.headers
.iter()
.map(|(name, value)| format!("{name}: {}\r\n", http::header_text(value)))
.collect();
let head = format!(
"HTTP/1.1 {}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n",
parts.status,
body.len()
);
client.write_all(head.as_bytes()).await?;
client.write_all(&body).await?;
Ok(())
}
async fn tunnel(
mut client: impl AsyncRead + AsyncWrite + Unpin,
mut upstream: impl AsyncRead + AsyncWrite + Unpin,
) -> Result<()> {
tokio::io::copy_bidirectional(&mut client, &mut upstream)
.await
.context("tunneling")?;
Ok(())
}
/// Copies headers in order, excluding `host` and hop-by-hop headers. The URL supplies the host,
/// and each connection supplies its own hop-by-hop headers. Removing entries from the original
/// map would change their order.
fn end_to_end(headers: &HeaderMap) -> HeaderMap {
headers
.iter()
.filter(|(name, _)| {
!matches!(
name.as_str(),
"connection"
| "keep-alive"
| "proxy-connection"
| "proxy-authorization"
| "te"
| "trailer"
| "transfer-encoding"
| "upgrade"
| "content-length"
| "host"
)
})
.map(|(name, value)| (name.clone(), value.clone()))
.collect()
}
/// Builds an upstream response for the browser, letting hyper set its length.
fn passthrough(upstream: Proxied) -> ProxyResponse {
let mut response = Response::new(Full::new(upstream.body));
*response.status_mut() = upstream.status;
*response.headers_mut() = end_to_end(&upstream.headers);
response
}
fn text_response(status: StatusCode, text: &str) -> ProxyResponse {
Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "text/plain;charset=UTF-8")
.body(Full::from(text.to_owned()))
.expect("static headers")
}
/// Returns the text of header `name`, or an empty string if it is absent.
fn header_value(headers: &HeaderMap, name: impl AsHeaderName) -> String {
headers.get(name).map(http::header_text).unwrap_or_default()
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
/// Undoes a response's content encoding, or returns its wire bytes if that fails.
fn decoded_body(response: &Proxied) -> Vec<u8> {
let encoding = header_value(&response.headers, header::CONTENT_ENCODING);
http::decode_body(&response.body, &encoding).unwrap_or_else(|_| response.body.to_vec())
}
/// Unmasks the challenge POST response for `url`, if the result is valid base64 text.
fn decode_program(url: &Url, response_body: &str) -> Option<String> {
use base64::Engine;
let ray = challenge::ray(url).ok()?;
let program = challenge::decode_response(response_body.as_bytes(), ray).ok()?;
String::from_utf8(program)
.ok()
.filter(|program| STANDARD.decode(program).is_ok())
}
#[cfg(test)]
mod tests;
+377
View File
@@ -0,0 +1,377 @@
//! Tests the proxy over loopback with a fake origin and a TLS client that trusts the proxy CA.
//! Checks iframe rewriting, seed rewrapping, and capture logs.
use std::net::SocketAddr;
use std::path::Path;
use std::sync::{Arc, Mutex};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use rustls::pki_types::{CertificateDer, ServerName};
use rustls::{ClientConfig, RootCertStore};
use serde_json::{Value, json};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio_rustls::TlsConnector;
use super::{CA_HOST, CA_PATH, CaptureProxy, Config};
use crate::capture::rsa::ProxyKey;
use crate::capture::{CertificateAuthority, UpstreamProxy, head};
use crate::challenge::codec::{self, Codec, KEY_LENGTH, SEED_LENGTH};
use crate::fingerprint::Transport;
use crate::http;
use crate::js::JsObject;
const ALPHABET: &str = "BCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/A";
const SECRET: [u8; KEY_LENGTH] = *b"0123456789abcdef";
/// Builds a fake iframe with a modulus, an alphabet literal for the fast scan, and the marker
/// required by `inline_javascript`.
fn iframe_html(modulus_hex: &str) -> String {
format!(
"<html><body><script>\nvar _cf_chl_opt = {{}};\nvar alphabet = \"{ALPHABET}\";\nvar n = BigInt(\"0x{modulus_hex}\");\n</script></body></html>"
)
}
/// A proxy serving loopback connections, and a TLS client that trusts its CA.
struct Loopback {
proxy: Arc<CaptureProxy>,
address: SocketAddr,
tls: Arc<ClientConfig>,
}
impl Loopback {
/// Starts a proxy intercepting `mitm_hosts`, with `localhost` as the challenge host and the
/// tracked iOS Safari 26 profile's client.
async fn start(mitm_hosts: Vec<String>) -> Self {
let profile = Path::new("profiles/safari-26-ios.json");
let transport = Transport::read(profile).unwrap();
let client = transport.client(None).unwrap();
let config = Config {
listen: "127.0.0.1:0".parse().unwrap(),
mitm_hosts,
challenge_host: "localhost".to_owned(),
upstream_tls: false,
upstream_proxy: UpstreamProxy::Direct,
out_dir: std::env::temp_dir().join(format!("capture-proxy-{}", std::process::id())),
};
let ca = CertificateAuthority::generate().unwrap();
let mut roots = RootCertStore::empty();
roots
.add(CertificateDer::from(ca.cert_der().to_vec()))
.unwrap();
let tls = ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
let proxy = Arc::new(CaptureProxy::try_new(config, client, ca).unwrap());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let serving = Arc::clone(&proxy);
tokio::spawn(async move {
loop {
let (stream, _) = listener.accept().await.unwrap();
tokio::spawn(Arc::clone(&serving).serve(stream));
}
});
Self {
proxy,
address,
tls: Arc::new(tls),
}
}
/// Sends `request` over TLS through a CONNECT tunnel to `authority`.
async fn tls(&self, authority: &str, request: &str) -> (String, Vec<u8>) {
let mut stream = TcpStream::connect(self.address).await.unwrap();
let connect = format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n\r\n");
let (head, _) = exchange(&mut stream, &connect).await;
assert!(head.contains(" 200 "), "CONNECT refused");
let host = authority.split(':').next().unwrap();
let name = ServerName::try_from(host.to_owned()).unwrap();
let mut tls = TlsConnector::from(Arc::clone(&self.tls))
.connect(name, stream)
.await
.unwrap();
exchange(&mut tls, request).await
}
}
/// Reads one HTTP message. Returns the headers without the final blank line, followed by the
/// body of the length specified by `content-length`.
async fn read_message(stream: &mut (impl AsyncRead + Unpin)) -> (String, Vec<u8>) {
let mut head = head::read_head(stream).await.unwrap();
let end = head.windows(4).position(|window| window == b"\r\n\r\n");
let mut body = head.split_off(end.unwrap() + 4);
head.truncate(head.len() - 4);
let head = String::from_utf8(head).unwrap();
let mut length = 0;
for line in head.lines().skip(1) {
if let Some((name, value)) = line.split_once(':')
&& name.trim().eq_ignore_ascii_case("content-length")
{
length = value.trim().parse().unwrap();
}
}
assert!(body.len() <= length, "the head's read ran past the body");
let start = body.len();
body.resize(length, 0);
stream.read_exact(&mut body[start..]).await.unwrap();
(head, body)
}
async fn exchange(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
request: &str,
) -> (String, Vec<u8>) {
stream.write_all(request.as_bytes()).await.unwrap();
read_message(stream).await
}
/// Builds the fake upstream's POST response: a program for ray `RAY123`, masked as the iframe
/// expects before calling the program runner.
fn masked_response() -> String {
let mask = b"RAY123_0".iter().fold(32_u8, |a, b| a ^ b);
let program = STANDARD.encode(b"hello-program");
let masked: Vec<_> = program
.bytes()
.enumerate()
.map(|(index, byte)| ((usize::from(byte) + usize::from(mask) + index % 65535) % 255) as u8)
.collect();
STANDARD.encode(masked)
}
/// Runs a fake origin. `/iframe` serves HTML, `/iframe-gzip` serves compressed HTML, and POSTs
/// are recorded and answered with a compressed masked program.
async fn run_upstream(listener: TcpListener, posts: Arc<Mutex<Vec<String>>>, html: String) {
loop {
let (mut stream, _) = listener.accept().await.unwrap();
let (head, body) = read_message(&mut stream).await;
let request = head.lines().next().unwrap();
let (encoding, body) = if request.starts_with("GET /iframe-gzip") {
("gzip", http::encode_body(html.as_bytes(), "gzip").unwrap())
} else if request.starts_with("GET /iframe") {
("identity", html.clone().into_bytes())
} else if request.starts_with("POST ") {
posts.lock().unwrap().push(String::from_utf8(body).unwrap());
let masked = http::encode_body(masked_response().as_bytes(), "gzip").unwrap();
("gzip", masked)
} else {
panic!("unexpected upstream request: {request}");
};
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Encoding: {encoding}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
stream.write_all(response.as_bytes()).await.unwrap();
stream.write_all(&body).await.unwrap();
}
}
/// Tests iframe rewriting for plain and compressed responses, challenge POST rewrapping, and
/// the resulting capture log over loopback.
#[tokio::test]
async fn mitm_rewrites_iframes_and_rewraps_posts() {
let real = ProxyKey::generate().unwrap();
let html = iframe_html(&real.modulus.to_str_radix(16));
let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
let upstream_port = upstream.local_addr().unwrap().port();
let host = format!("localhost:{upstream_port}");
let posts = Arc::new(Mutex::new(Vec::new()));
tokio::spawn(run_upstream(upstream, Arc::clone(&posts), html.clone()));
let loopback = Loopback::start(vec!["localhost".to_owned()]).await;
let proxy = &loopback.proxy;
let proxy_modulus = proxy.sessions.proxy_key.modulus.clone();
// A plain iframe comes back with the proxy modulus in place of the real one.
let get = format!("GET /iframe HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
let (head, body) = loopback.tls(&host, &get).await;
assert!(head.contains(" 200 "), "{head}");
let rewritten = String::from_utf8(body).unwrap();
assert_eq!(rewritten, iframe_html(&proxy_modulus.to_str_radix(16)));
// The browser encrypts the seed with the proxy modulus. The proxy forwards the body the
// encoder would have built under the real modulus. This POST binds the ray to the first
// session before the next GET opens another session.
let mut seed = [42; SEED_LENGTH];
seed[0] = codec::SEED_MARKER;
let payload: JsObject =
serde_json::from_value(json!({"1": {"a": [1, 2, {"b": "x"}]}, "counter": 39})).unwrap();
let encode = |modulus| {
let encoder = Codec::try_new(ALPHABET, modulus, SECRET).unwrap();
encoder.encode(&payload, seed)
};
let browser_body = encode(proxy_modulus);
let post_path = "/cdn-cgi/challenge-platform/h/g/fo/sess/RAY123/tok456";
let post_url = format!("http://{host}{post_path}");
let post = format!(
"POST {post_path} HTTP/1.1\r\nHost: {host}\r\nContent-Type: text/plain;charset=UTF-8\r\ncf-chl: tok456\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{browser_body}",
browser_body.len()
);
let (head, response) = loopback.tls(&host, &post).await;
assert!(head.contains(" 200 "), "{head}");
assert_eq!(*posts.lock().unwrap(), [encode(real.modulus.clone())]);
// The encoded response goes back untouched.
assert!(head.contains("content-encoding: gzip"), "{head}");
let decoded = http::decode_body(&response, "gzip").unwrap();
assert_eq!(decoded, masked_response().as_bytes());
// A gzipped iframe decodes to the same rewrite on the way out.
let get = format!(
"GET /iframe-gzip HTTP/1.1\r\nHost: {host}\r\nAccept-Encoding: gzip\r\nConnection: close\r\n\r\n"
);
let (head, body) = loopback.tls(&host, &get).await;
assert!(head.contains("content-encoding: gzip"), "{head}");
let decoded = http::decode_body(&body, "gzip").unwrap();
assert_eq!(decoded, rewritten.as_bytes());
// A site's own `/fo/` path must pass through unchanged. Treating it as a challenge POST
// would bind the unbound gzip session and fail to decrypt it.
let plain = format!(
"POST /site/fo/sess/RAY456/tok789 HTTP/1.1\r\nHost: {host}\r\nContent-Length: 5\r\nConnection: close\r\n\r\nplain"
);
let (head, _) = loopback.tls(&host, &plain).await;
assert!(head.contains(" 200 "), "{head}");
assert_eq!(posts.lock().unwrap()[1], "plain");
// The session log uses the format expected by `build_profile`, including the decoded
// response body.
proxy.sessions.finish_extractions().await;
let out = &proxy.config.out_dir;
proxy.sessions.write_all(out);
let session = out.join("sessions/session-0000");
let read_text = |name: &str| std::fs::read_to_string(session.join(name)).unwrap();
let read_json = |name: &str| -> Value { serde_json::from_str(&read_text(name)).unwrap() };
let capture = read_json("capture.json");
let logged = json!({
"url": post_url, "cfChl": "tok456", "seed": super::hex(&seed),
"padding": capture["posts"][0]["padding"], "error": null,
"responseBody": masked_response(),
});
assert_eq!(
capture,
json!({"iframeHtml": html, "posts": [logged], "payloads": []})
);
let program = &read_json("session.json")["posts"][0]["decodedProgram"];
assert_eq!(*program, STANDARD.encode(b"hello-program"));
assert_eq!(read_text("original.html"), html);
assert_eq!(read_text("rewritten.html"), rewritten);
// The traffic log records each connection's ClientHello and each request's headers in their
// original order.
let path = proxy.traffic().write(out).unwrap();
let traffic: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
let connections = traffic["connections"].as_array().unwrap();
assert_eq!(connections.len(), 4);
for connection in connections {
let hello = connection["clientHello"].as_str().unwrap();
let is_client_hello = hello.starts_with("16030") && hello[10..].starts_with("01");
assert!(is_client_hello, "{hello}");
let expected = json!({
"host": "localhost", "port": upstream_port, "clientHello": hello,
"alpn": null, "h2Opening": null,
});
assert_eq!(*connection, expected);
}
assert_eq!(traffic["requests"].as_array().unwrap().len(), 4);
let post = &traffic["requests"][1];
assert!(post["receivedMs"].as_i64().unwrap() <= post["answeredMs"].as_i64().unwrap());
let expected = json!({
"connection": 1, "method": "POST", "url": post_url, "version": "HTTP/1.1",
"headers": [
["host", host], ["content-type", "text/plain;charset=UTF-8"], ["cf-chl", "tok456"],
["content-length", browser_body.len().to_string()], ["connection", "close"],
],
"receivedMs": post["receivedMs"], "answeredMs": post["answeredMs"],
});
assert_eq!(*post, expected);
std::fs::remove_dir_all(out).unwrap();
}
/// Checks CA downloads over plain HTTP before the client trusts the CA, for absolute and origin
/// request targets, and over intercepted TLS after it does.
#[tokio::test]
async fn serves_the_ca_download() {
let loopback = Loopback::start(vec![]).await;
let cases = [
(false, format!("GET http://{CA_HOST}{CA_PATH}"), " 200 "),
(false, format!("GET {CA_PATH}"), " 200 "),
(false, format!("GET http://{CA_HOST}/other"), " 404 "),
(false, "GET http://example.com/".to_owned(), " 400 "),
(false, format!("POST http://{CA_HOST}{CA_PATH}"), " 405 "),
(true, format!("GET {CA_PATH}"), " 200 "),
(true, "GET /other".to_owned(), " 404 "),
];
for (tls, line, status) in cases {
let request = format!(
"{line} HTTP/1.1\r\nHost: {CA_HOST}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
let (head, body) = if tls {
loopback.tls(&format!("{CA_HOST}:443"), &request).await
} else {
let mut stream = TcpStream::connect(loopback.address).await.unwrap();
exchange(&mut stream, &request).await
};
assert!(head.contains(status), "{line}: {head}");
if status == " 200 " {
assert!(head.contains("application/x-x509-ca-cert"), "{head}");
assert_eq!(body, loopback.proxy.ca.pem().as_bytes());
}
}
}
/// Checks that saved bodies include only challenge pages, orchestrator scripts and programs,
/// and the loader.
#[test]
fn keeps_what_rebuilds_a_challenge_page() {
use hyper::Method;
use hyper::header::HeaderMap;
let none = HeaderMap::new();
let mut challenged = HeaderMap::new();
challenged.insert("cf-mitigated", "challenge".parse().unwrap());
let page = "https://example.com/login";
let orchestrator = "https://example.com/cdn-cgi/challenge-platform/h/b/orchestrate/v1?ray=a";
let program = "https://example.com/cdn-cgi/challenge-platform/h/b/fo/1:2:x/a/tok";
let iframe_post = "https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/fo/1:2/a/t";
let loader = "https://challenges.cloudflare.com/turnstile/v0/b/d2d3/api.js?render=explicit";
for (method, url, headers, expected) in [
(Method::GET, page, &challenged, Some("challenge-page.html")),
(Method::POST, page, &challenged, Some("challenge-page.html")),
(Method::GET, page, &none, None),
(Method::GET, orchestrator, &none, Some("orchestrator.js")),
(
Method::POST,
program,
&none,
Some("orchestrator-response.txt"),
),
// The challenge host's own POSTs are logged per session instead.
(Method::POST, iframe_post, &none, None),
(Method::GET, loader, &none, Some("api.js")),
] {
let kept = super::kept(&method, url, "challenges.cloudflare.com", headers);
assert_eq!(kept, expected, "{method} {url}");
}
}
/// Blind tunnels carry bytes both ways.
#[tokio::test]
async fn untunneled_hosts_pass_through() {
let echo = TcpListener::bind("127.0.0.1:0").await.unwrap();
let echo_port = echo.local_addr().unwrap().port();
tokio::spawn(async move {
let (mut stream, _) = echo.accept().await.unwrap();
let (mut reader, mut writer) = stream.split();
tokio::io::copy(&mut reader, &mut writer).await.unwrap();
});
let loopback = Loopback::start(vec![]).await;
let mut stream = TcpStream::connect(loopback.address).await.unwrap();
let connect = format!("CONNECT 127.0.0.1:{echo_port} HTTP/1.1\r\nHost: x\r\n\r\n");
let (head, _) = exchange(&mut stream, &connect).await;
assert!(head.contains(" 200 "));
stream.write_all(b"through the tunnel").await.unwrap();
let mut echo = [0; 18];
stream.read_exact(&mut echo).await.unwrap();
assert_eq!(&echo, b"through the tunnel");
}
+272
View File
@@ -0,0 +1,272 @@
//! The proxy's RSA-1024 keypair, which lets it read the seeds browsers encrypt.
//!
//! The encoder encrypts its seed with textbook RSA and `e = 65537` under a modulus in the iframe
//! script (see `crate::challenge::codec`). The proxy swaps in its own modulus, then rewraps each
//! POST's seed under the real one. A body holds the wrapped seed, a padding byte, and an
//! XTEA-encrypted frame that does not depend on the modulus.
use std::iter;
use std::sync::LazyLock;
use anyhow::{Context, Result, ensure};
use num_bigint::BigUint;
use regex::Regex;
use serde_json::Value;
use crate::candidates;
use crate::challenge::codec::{self, Envelope, KEY_LENGTH, PUBLIC_EXPONENT, SEED_LENGTH};
/// Matches a `BigInt` call with a hexadecimal literal, capturing its quotes and digits. The
/// regex engine has no backreferences, so code checks that the quotes match.
static MODULUS: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"BigInt\((["'`])0x([0-9a-fA-F]+)(["'`])\)"#).expect("a fixed pattern")
});
/// A 1024-bit RSA keypair with `e = 65537` and the modulus's top bit set. Every seed starts
/// with byte 2, so it is smaller than the modulus.
pub(super) struct ProxyKey {
pub(super) modulus: BigUint,
private: BigUint,
}
/// A rewrapped body and the values decrypted for logging.
pub(super) struct Rewrapped {
/// The body to forward upstream, encoded with the session's alphabet.
pub(super) body: String,
pub(super) seed: [u8; SEED_LENGTH],
pub(super) padding: u8,
}
impl ProxyKey {
/// Generates two distinct primes whose product has the seed's width and whose totient is
/// coprime to `e`.
pub(super) fn generate() -> Result<Self> {
let exponent = BigUint::from(PUBLIC_EXPONENT);
loop {
let (first, second) = (random_prime()?, random_prime()?);
let modulus = &first * &second;
if first == second || modulus.bits() != SEED_LENGTH as u64 * 8 {
continue;
}
let totient = (first - 1u32) * (second - 1u32);
if let Some(private) = exponent.modinv(&totient) {
return Ok(Self { modulus, private });
}
}
}
/// Rewraps the seed in `body` with `real`, keeping the padding byte and frame. Rejects seeds
/// that do not unwrap to a value starting with the encoder's fixed byte.
pub(super) fn rewrap(&self, body: &str, alphabet: &str, real: &BigUint) -> Result<Rewrapped> {
let engine = codec::engine(alphabet)?;
let envelope = Envelope::decode(body, &engine)?;
let seed = codec::rsa(&envelope.wrapped_seed, &self.private, &self.modulus);
ensure!(
seed[0] == codec::SEED_MARKER,
"the unwrapped seed is not the encoder's: refusing to forward it"
);
let padding = envelope.padding;
let rewrapped = Envelope {
wrapped_seed: codec::wrap_seed(&seed, real),
..envelope
};
Ok(Rewrapped {
body: rewrapped.encode(&engine),
seed,
padding,
})
}
/// Decrypts a body's payload with the session's alphabet and key-transform secret.
pub(super) fn read_payload(
&self,
body: &str,
alphabet: &str,
secret: &[u8; KEY_LENGTH],
) -> Result<Value> {
let envelope = Envelope::decode(body, &codec::engine(alphabet)?)?;
let seed = codec::rsa(&envelope.wrapped_seed, &self.private, &self.modulus);
envelope.payload(&seed, secret)
}
}
/// Replaces the iframe's 128-byte `BigInt` hexadecimal literal (see `rsa_modulus` in
/// `crate::challenge::program`) with `proxy`, zero-padded to the same width so the HTML length
/// and stack-trace positions stay unchanged. Returns the rewritten HTML and the real modulus.
pub(super) fn swap_modulus(html: &str, proxy: &BigUint) -> Result<(String, BigUint)> {
let literals = MODULUS.captures_iter(html).filter_map(|captures| {
let (_, [open, digits, close]) = captures.extract();
let modulus = BigUint::parse_bytes(digits.as_bytes(), 16).expect("hex digits");
let wide = open == close && modulus.bits().div_ceil(8) == SEED_LENGTH as u64;
wide.then(|| (captures.get(2).expect("the digits group").range(), modulus))
});
let what = format!("{SEED_LENGTH}-byte BigInt literal in the iframe");
let (digits, real) = candidates::exactly_one(literals, &what)?;
let width = digits.len();
let proxy_digits = proxy.to_str_radix(16);
ensure!(
proxy_digits.len() <= width,
"the proxy modulus needs {} hex digits, wider than the session's {width}",
proxy_digits.len()
);
let mut rewritten = html.to_owned();
rewritten.replace_range(digits, &format!("{proxy_digits:0>width$}"));
Ok((rewritten, real))
}
/// Generates a random prime half the seed's width, with its top bit set.
fn random_prime() -> Result<BigUint> {
let mut bytes = [0; SEED_LENGTH / 2];
loop {
getrandom::fill(&mut bytes).context("drawing prime bits")?;
bytes[0] |= 0x80;
bytes[SEED_LENGTH / 2 - 1] |= 1;
let candidate = BigUint::from_bytes_be(&bytes);
if is_prime(&candidate)? {
return Ok(candidate);
}
}
}
/// Tests a candidate greater than 1 using trial division and 16 Miller-Rabin rounds with random
/// bases. Always accepts primes; may accept a composite with negligible probability.
fn is_prime(candidate: &BigUint) -> Result<bool> {
let one = BigUint::from(1u32);
let trial_divisors = iter::once(2u32).chain((3..1000).step_by(2));
for factor in trial_divisors {
if candidate % factor == BigUint::ZERO {
return Ok(*candidate == BigUint::from(factor));
}
}
let less_one = candidate - 1u32;
let squarings = less_one.trailing_zeros().expect("an odd candidate above 2");
let odd = &less_one >> squarings;
let mut bytes = vec![0; candidate.bits().div_ceil(8) as usize];
'bases: for _ in 0..16 {
getrandom::fill(&mut bytes).context("drawing a Miller-Rabin base")?;
// A base in [2, candidate - 2].
let base = BigUint::from_bytes_be(&bytes) % (candidate - 3u32) + 2u32;
let mut witness = base.modpow(&odd, candidate);
if witness == one || witness == less_one {
continue;
}
for _ in 1..squarings {
witness = &witness * &witness % candidate;
if witness == less_one {
continue 'bases;
}
}
return Ok(false);
}
Ok(true)
}
#[cfg(test)]
mod tests {
use std::sync::OnceLock;
use serde_json::json;
use super::*;
use crate::challenge::codec::Codec;
use crate::js::JsObject;
/// A permuted alphabet, to check that encoding respects the session's character order.
const ALPHABET: &str = "NOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLM";
const SECRET: [u8; KEY_LENGTH] = *b"0123456789abcdef";
/// Generates proxy, real, and unrelated keypairs once because prime generation is the
/// slowest part of the suite.
fn keys() -> &'static [ProxyKey; 3] {
static KEYS: OnceLock<[ProxyKey; 3]> = OnceLock::new();
KEYS.get_or_init(|| std::array::from_fn(|_| ProxyKey::generate().unwrap()))
}
fn encode(modulus: &BigUint, payload: &Value, seed: [u8; SEED_LENGTH]) -> String {
let payload: JsObject = serde_json::from_value(payload.clone()).unwrap();
let codec = Codec::try_new(ALPHABET, modulus.clone(), SECRET).unwrap();
codec.encode(&payload, seed)
}
/// A page with a narrow decoy literal before the modulus literal.
fn page(quote: char, modulus: &BigUint) -> String {
format!("var a = BigInt(\"0x1234\"); var n = BigInt({quote}0x{modulus:x}{quote}); send(n);")
}
#[test]
fn small_primes_pass_and_composites_fail() {
for candidate in [2u32, 3, 5, 101, 65537] {
assert!(is_prime(&BigUint::from(candidate)).unwrap(), "{candidate}");
}
for candidate in [4u32, 9, 561, 65537 * 257] {
assert!(!is_prime(&BigUint::from(candidate)).unwrap(), "{candidate}");
}
}
#[test]
fn rewrap_rejects_garbage() {
let [proxy, real, other] = keys();
assert!(proxy.rewrap("!!!", ALPHABET, &real.modulus).is_err());
let body = encode(&other.modulus, &json!({"a": 1}), [3; SEED_LENGTH]);
assert!(
proxy.rewrap(&body, ALPHABET, &real.modulus).is_err(),
"a body wrapped under another key does not open under the proxy's"
);
}
/// Rewrapping matches the session encoder's output for the same seed, padding, and frame, and
/// both raw and DEFLATE-compressed payloads read back.
#[test]
fn rewrap_matches_encoding_under_the_real_modulus() {
let [proxy, real, _] = keys();
let payloads = [
json!({"1": {"a": [1, 2, {"b": "x"}]}, "counter": 39}),
json!({"1": {"a": "x".repeat(500)}, "2": [1, 2, 3]}),
];
for payload in payloads {
let body = encode(&proxy.modulus, &payload, [11; SEED_LENGTH]);
let rewrapped = proxy.rewrap(&body, ALPHABET, &real.modulus).unwrap();
assert_eq!(
rewrapped.body,
encode(&real.modulus, &payload, rewrapped.seed)
);
let read = proxy.read_payload(&body, ALPHABET, &SECRET).unwrap();
assert_eq!(read, payload);
}
}
/// The pages spell the literal with double quotes or template literals.
#[test]
fn swap_replaces_only_the_modulus_digits() {
let [proxy, real, _] = keys();
for quote in ['"', '`'] {
let html = page(quote, &real.modulus);
let (rewritten, found) = swap_modulus(&html, &proxy.modulus).unwrap();
assert_eq!(found, real.modulus);
assert_eq!(rewritten, page(quote, &proxy.modulus));
}
}
#[test]
fn swap_fails_closed() {
let [proxy, real, _] = keys();
let wide = page('"', &real.modulus);
let narrow = (BigUint::from(1u32) << 1016) + 7u32;
let cases = [
("var n = 1;".to_owned(), "no literal at all"),
(page('"', &BigUint::from(0x1234u32)), "only narrow literals"),
(wide.repeat(2), "two wide literals"),
(
format!("BigInt(\"0x{:x}`)", real.modulus),
"quotes that do not match",
),
(
page('"', &narrow),
"a literal narrower than the proxy modulus",
),
];
for (html, case) in cases {
assert!(swap_modulus(&html, &proxy.modulus).is_err(), "{case}");
}
}
}
+352
View File
@@ -0,0 +1,352 @@
//! Tracks iframe sessions and writes their captures.
//!
//! Each rewritten iframe GET opens a session with the real modulus and an alphabet read by a
//! fast scan. Background extraction checks that alphabet and recovers the key-transform secret
//! from the original HTML. Challenge POSTs use the session bound to their ray, or bind to the
//! latest unbound session. Shutdown waits for extraction, decrypts payloads, and writes logs.
//!
//! Each session directory holds the original and rewritten HTML, the full log `session.json`,
//! and `capture.json`, which `cargo run --example build_profile` turns into `answers.json`.
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};
use anyhow::{Context, Result};
use num_bigint::BigUint;
use serde::{Serialize, Serializer};
use serde_json::Value;
use tokio::task::JoinSet;
use url::Url;
use super::rsa::{ProxyKey, Rewrapped};
use crate::challenge::codec::{Codec, KEY_LENGTH};
use crate::challenge::program::{self, PreparedSession};
use crate::js::ast;
use crate::script::Source;
use crate::{challenge, deep_stack};
/// An iframe GET whose response was rewritten, starting a new session.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct Iframe {
#[serde(rename = "iframeUrl")]
pub(super) url: String,
#[serde(serialize_with = "lower_hex")]
pub(super) real_modulus: BigUint,
/// Alphabet from the fast scan, used until full extraction finishes.
#[serde(skip)]
pub(super) scanned_alphabet: String,
#[serde(skip)]
pub(super) original: String,
#[serde(skip)]
pub(super) rewritten: String,
// Body sizes before and after rewriting, as observed by the browser.
pub(super) upstream_encoded_bytes: u64,
pub(super) upstream_decoded_bytes: u64,
pub(super) observed_encoded_bytes: u64,
pub(super) observed_decoded_bytes: u64,
}
/// A challenge POST, its decrypted values, and its response.
#[derive(Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct Post {
pub(super) url: String,
pub(super) cf_chl: String,
/// The unwrapped seed, in hex.
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) seed: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) padding: Option<u8>,
/// The body as the browser encrypted it, under the proxy modulus.
pub(super) encrypted_body: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) error: Option<String>,
pub(super) response_body: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) decoded_program: Option<String>,
/// The frame plaintext, read once the session's secret is known.
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) payload: Option<Value>,
}
/// `capture.json`: the iframe page and its POSTs, with the payloads that could be read.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CaptureJson<'session> {
iframe_html: &'session str,
posts: Vec<CapturedPost<'session>>,
payloads: Vec<CapturedPayload<'session>>,
}
/// A POST in `capture.json`. Unlike `session.json`, absent values are written as `null`.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct CapturedPost<'session> {
url: &'session str,
cf_chl: &'session str,
seed: Option<&'session str>,
padding: Option<u8>,
error: Option<&'session str>,
response_body: &'session str,
}
#[derive(Serialize)]
struct CapturedPayload<'session> {
url: &'session str,
payload: &'session Value,
}
/// One iframe session, serialized as its `session.json`.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct Session {
#[serde(flatten)]
iframe: Iframe,
#[serde(serialize_with = "lower_hex")]
proxy_modulus: BigUint,
/// Alphabet and key-transform secret recovered by full extraction.
alphabet: Option<String>,
#[serde(serialize_with = "as_text")]
secret: Option<[u8; KEY_LENGTH]>,
/// Whether capture succeeded. Only complete sessions can become stored answers.
complete: bool,
/// The reason capture is incomplete.
notes: Vec<String>,
posts: Vec<Post>,
/// The ray bound to this session's POSTs.
#[serde(skip)]
ray: Option<String>,
}
/// The proxy's sessions, indexed in the order they opened.
pub(super) struct Sessions {
pub(super) proxy_key: ProxyKey,
sessions: Mutex<Vec<Session>>,
/// The background extractions, awaited before the logs are written.
extractions: Mutex<JoinSet<()>>,
}
impl Sessions {
#[must_use]
pub(super) fn new(proxy_key: ProxyKey) -> Self {
Self {
proxy_key,
sessions: Mutex::default(),
extractions: Mutex::default(),
}
}
pub(super) fn lock(&self) -> MutexGuard<'_, Vec<Session>> {
self.sessions.lock().expect("the session table lock")
}
/// Opens a session for `iframe` and starts background parameter extraction.
pub(super) fn open(self: &Arc<Self>, iframe: Iframe) -> usize {
let original = iframe.original.clone();
let index = {
let mut sessions = self.lock();
sessions.push(Session {
iframe,
proxy_modulus: self.proxy_key.modulus.clone(),
alphabet: None,
secret: None,
complete: true,
notes: Vec::new(),
posts: Vec::new(),
ray: None,
});
sessions.len() - 1
};
let sessions = Arc::clone(self);
let mut extractions = self.extractions.lock().expect("the extraction set lock");
extractions.spawn(async move {
let codec = deep_stack::run("extraction", move || extract_codec(&original))
.await
.flatten();
sessions.lock()[index].set_codec(codec);
});
index
}
/// Waits for all current extractions so subsequent logs include their secrets.
pub(super) async fn finish_extractions(&self) {
let mut extractions =
std::mem::take(&mut *self.extractions.lock().expect("the extraction set lock"));
while extractions.join_next().await.is_some() {}
}
/// Finds the session for a POST to `url`. Binds a new ray to the latest unbound session.
/// Returns `None` when no session is available.
#[must_use]
pub(super) fn bind(&self, url: &Url) -> Option<usize> {
let ray = challenge::ray(url).ok()?;
let mut sessions = self.lock();
let bound = |session: &Session| session.ray.as_deref() == Some(ray);
if let Some(index) = sessions.iter().position(bound) {
return Some(index);
}
let index = sessions.iter().rposition(|session| session.ray.is_none())?;
sessions[index].ray = Some(ray.to_owned());
Some(index)
}
/// Re-encrypts session `index`'s POST seed with the real modulus.
pub(super) fn rewrap(&self, index: usize, body: &str) -> Result<Rewrapped> {
let sessions = self.lock();
let Session {
iframe, alphabet, ..
} = &sessions[index];
let alphabet = alphabet.as_ref().unwrap_or(&iframe.scanned_alphabet);
self.proxy_key.rewrap(body, alphabet, &iframe.real_modulus)
}
/// Decrypts each session's payloads and writes its log under `out_dir`.
pub(super) fn write_all(&self, out_dir: &Path) {
for (index, session) in self.lock().iter_mut().enumerate() {
session.read_payloads(&self.proxy_key);
let dir = out_dir.join(format!("sessions/session-{index:04}"));
match session.write(&dir) {
Ok(path) => eprintln!(
"session {index}: {} (complete: {})",
path.display(),
session.complete
),
Err(error) => eprintln!("session {index}: writing the log failed: {error:#}"),
}
}
}
}
impl Session {
/// Marks capture as incomplete and records the reason.
pub(super) fn poison(&mut self, note: &str) {
self.complete = false;
self.notes.push(note.to_owned());
}
/// Records a POST and marks its session incomplete if the POST has an error.
pub(super) fn record(&mut self, post: Post) {
if let Some(error) = &post.error {
self.poison(&format!("POST {}: {error}", post.url));
}
self.posts.push(post);
}
/// Accepts extracted parameters after checking them against the replaced modulus and
/// scanned alphabet.
fn set_codec(&mut self, codec: Result<Codec>) {
let codec = match codec {
Ok(codec) => codec,
Err(error) => {
self.poison(&format!("extracting the session params: {error:#}"));
return;
}
};
if codec.modulus != self.iframe.real_modulus {
self.poison("the pipeline modulus differs from the swapped one");
return;
}
if codec.alphabet_text != self.iframe.scanned_alphabet {
self.poison("the pipeline alphabet differs from the scanned one");
}
self.alphabet = Some(codec.alphabet_text);
self.secret = Some(codec.secret);
}
/// Decrypts POST payloads after extraction supplies the secret. Marks capture incomplete if
/// decryption fails.
fn read_payloads(&mut self, proxy_key: &ProxyKey) {
let (Some(alphabet), Some(secret)) = (&self.alphabet, &self.secret) else {
if !self.posts.is_empty() {
self.poison("the pipeline never supplied the secret to read payloads with");
}
return;
};
for post in &mut self.posts {
match proxy_key.read_payload(&post.encrypted_body, alphabet, secret) {
Ok(payload) => post.payload = Some(payload),
Err(error) => {
let error = format!("{error:#}");
self.complete = false;
self.notes.push(format!("POST {}: {error}", post.url));
// Keep the first error so a decryption failure cannot hide the rewrapping
// failure that rejected the POST.
post.error.get_or_insert(error);
}
}
}
}
/// Writes the session files to `dir` and returns the path to `capture.json`.
fn write(&self, dir: &Path) -> Result<PathBuf> {
fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
write_file(&dir.join("original.html"), &self.iframe.original)?;
write_file(&dir.join("rewritten.html"), &self.iframe.rewritten)?;
let log = serde_json::to_string_pretty(self)?;
write_file(&dir.join("session.json"), log)?;
let mut capture = CaptureJson {
iframe_html: &self.iframe.original,
posts: Vec::new(),
payloads: Vec::new(),
};
for post in &self.posts {
capture.posts.push(CapturedPost {
url: &post.url,
cf_chl: &post.cf_chl,
seed: post.seed.as_deref(),
padding: post.padding,
error: post.error.as_deref(),
response_body: &post.response_body,
});
if let Some(payload) = &post.payload {
capture.payloads.push(CapturedPayload {
url: &post.url,
payload,
});
}
}
let path = dir.join("capture.json");
write_file(&path, serde_json::to_string_pretty(&capture)?)?;
Ok(path)
}
}
/// Writes `contents` to `path`, naming the path in any error.
pub(super) fn write_file(path: &Path, contents: impl AsRef<[u8]>) -> Result<()> {
fs::write(path, contents).with_context(|| format!("writing {}", path.display()))
}
fn lower_hex<S: Serializer>(number: &BigUint, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(&format_args!("{number:x}"))
}
/// Serializes secret bytes as script characters. The `&Option` parameter is required by Serde's
/// `serialize_with` callback.
fn as_text<S: Serializer>(
secret: &Option<[u8; KEY_LENGTH]>,
serializer: S,
) -> Result<S::Ok, S::Error> {
let text: Option<String> = secret.map(|secret| secret.map(char::from).iter().collect());
text.serialize(serializer)
}
/// Runs the solver's extraction on the original iframe HTML.
fn extract_codec(original: &str) -> Result<Codec> {
let javascript = challenge::inline_javascript(original)?;
let deobfuscated = crate::deobfuscate::deobfuscate(javascript)?;
let source = Source::try_new(&deobfuscated.text)?;
// Extraction checks that POSTs share the iframe's origin. Any challenge host works for this
// check.
let base = Url::parse("https://challenges.cloudflare.com/")?;
let session = PreparedSession::try_new(&source, &base)?;
Ok(session.into_program().codec)
}
/// Scans the raw script with the solver's alphabet rule, without restricting it to the IIFE.
/// Background extraction checks the result before the session can become stored answers.
pub(super) fn scan_alphabet(javascript: &str) -> Result<String> {
let parsed = ast::parse_javascript("iframe.js", javascript)?;
program::base64_alphabet(&parsed.script)
}
+138
View File
@@ -0,0 +1,138 @@
//! Records browser connections and requests in `traffic.json`, alongside session directories.
//! These records allow reconstruction of transport settings and delays between POSTs. Saved
//! response bodies go in `bodies/`, named by request.
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::Serialize;
use super::sessions;
use crate::{http, performance_clock};
/// The directory beside `traffic.json` holding kept response bodies.
const BODIES: &str = "bodies";
#[derive(Default, Serialize)]
pub(super) struct Traffic {
connections: Vec<Connection>,
requests: Vec<Request>,
}
/// One intercepted connection, as the browser opened it.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(super) struct Connection {
pub(super) host: String,
pub(super) port: u16,
/// The TLS records carrying the ClientHello, in hex.
pub(super) client_hello: String,
/// The protocol negotiated by ALPN.
pub(super) alpn: Option<String>,
/// The HTTP/2 preface and frames through the first request's header block, in hex.
pub(super) h2_opening: Option<String>,
}
/// A request on an intercepted connection. hyper preserves header order, groups repeated values
/// at the first occurrence of their name, and lowercases names as HTTP/2 does.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Request {
/// Index of this request's connection in `connections`.
connection: usize,
method: String,
url: String,
version: String,
headers: Vec<(String, String)>,
/// Time received, in milliseconds since the Unix epoch.
received_ms: i64,
/// Time the response was handed to the browser.
answered_ms: Option<i64>,
/// The file holding the decoded response body, relative to `traffic.json`, if kept.
#[serde(skip_serializing_if = "Option::is_none")]
body_file: Option<String>,
#[serde(skip)]
body: Vec<u8>,
}
impl Traffic {
/// Records a connection and returns the index used by its requests.
pub(super) fn connect(&mut self, connection: Connection) -> usize {
self.connections.push(connection);
self.connections.len() - 1
}
/// Records a request received now and returns the index used by [`Self::answered`].
pub(super) fn request<B>(
&mut self,
connection: usize,
url: &str,
request: &hyper::Request<B>,
) -> usize {
self.requests.push(Request {
connection,
method: request.method().to_string(),
url: url.to_owned(),
version: format!("{:?}", request.version()),
headers: http::text_headers(request.headers())
.map(|(name, value)| (name.to_owned(), value))
.collect(),
received_ms: performance_clock::epoch_ms(),
answered_ms: None,
body_file: None,
body: Vec::new(),
});
self.requests.len() - 1
}
/// Records the current time as the response time for request `index`.
pub(super) fn answered(&mut self, index: usize) {
self.requests[index].answered_ms = Some(performance_clock::epoch_ms());
}
/// Saves request `index`'s decoded response body as `kind` when [`Self::write`] runs.
pub(super) fn keep(&mut self, index: usize, kind: &str, body: Vec<u8>) {
let request = &mut self.requests[index];
request.body_file = Some(format!("{BODIES}/{index:04}-{kind}"));
request.body = body;
}
/// Writes `traffic.json` and the kept bodies into the existing `dir`, returning the log's path.
pub(super) fn write(&self, dir: &Path) -> Result<PathBuf> {
for request in &self.requests {
if let Some(file) = &request.body_file {
let bodies = dir.join(BODIES);
fs::create_dir_all(&bodies)
.with_context(|| format!("creating {}", bodies.display()))?;
sessions::write_file(&dir.join(file), &request.body)?;
}
}
let path = dir.join("traffic.json");
sessions::write_file(&path, serde_json::to_string_pretty(self)?)?;
Ok(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kept_bodies_are_written_beside_the_log_named_by_their_requests() {
let dir = std::env::temp_dir().join(format!("traffic-bodies-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
let mut traffic = Traffic::default();
let request = hyper::Request::new(());
let page = traffic.request(0, "https://example.com/", &request);
let script = traffic.request(0, "https://example.com/v1", &request);
traffic.keep(script, "orchestrator.js", b"script".to_vec());
let log: serde_json::Value =
serde_json::from_slice(&fs::read(traffic.write(&dir).unwrap()).unwrap()).unwrap();
assert!(log["requests"][page].get("bodyFile").is_none());
let file = log["requests"][script]["bodyFile"].as_str().unwrap();
assert_eq!(file, "bodies/0001-orchestrator.js");
assert_eq!(fs::read(dir.join(file)).unwrap(), b"script");
fs::remove_dir_all(dir).unwrap();
}
}
+323
View File
@@ -0,0 +1,323 @@
//! Connects tunnels directly or through an HTTP or SOCKS5 proxy.
use std::net::IpAddr;
use std::str::FromStr;
use std::sync::{Arc, LazyLock};
use anyhow::{Context, Result, bail, ensure};
use base64::engine::general_purpose::STANDARD;
use rustls::pki_types::ServerName;
use rustls::{ClientConfig, RootCertStore};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;
use tokio_rustls::client::TlsStream;
use url::Url;
use super::head;
/// How the proxy reaches the internet.
#[derive(Debug, PartialEq)]
pub enum UpstreamProxy {
Direct,
Http {
host: String,
port: u16,
tls: bool,
auth: Option<Credentials>,
},
/// A SOCKS5 proxy. With `remote_dns`, the proxy resolves hostnames, matching `socks5h`.
Socks {
host: String,
port: u16,
auth: Option<Credentials>,
remote_dns: bool,
},
}
#[derive(Debug, PartialEq)]
pub struct Credentials {
pub user: String,
pub password: String,
}
/// A tunnel's byte stream.
pub(super) trait Stream: AsyncRead + AsyncWrite + Unpin + Send {}
impl<T: AsyncRead + AsyncWrite + Unpin + Send> Stream for T {}
impl FromStr for UpstreamProxy {
type Err = anyhow::Error;
/// Parses an `http://`, `https://`, `socks5://`, or `socks5h://` proxy URL.
fn from_str(url: &str) -> Result<Self> {
let url = Url::parse(url).context("parsing the upstream proxy URL")?;
let host = url
.host_str()
.context("the proxy URL has no host")?
.to_owned();
// `Url` keeps the userinfo percent-encoded.
let decode = |text: &str| -> Result<String> {
let decoded = percent_encoding::percent_decode_str(text).decode_utf8();
Ok(decoded
.context("the proxy credentials are not UTF-8")?
.into_owned())
};
let auth = if url.username().is_empty() {
None
} else {
Some(Credentials {
user: decode(url.username())?,
password: decode(url.password().unwrap_or_default())?,
})
};
let port = url.port_or_known_default();
Ok(match url.scheme() {
"http" | "https" => Self::Http {
port: port.expect("http and https have default ports"),
host,
tls: url.scheme() == "https",
auth,
},
"socks5" | "socks5h" => Self::Socks {
port: port.unwrap_or(1080),
host,
auth,
remote_dns: url.scheme() == "socks5h",
},
scheme => bail!("unsupported upstream proxy scheme {scheme}"),
})
}
}
impl UpstreamProxy {
pub(super) async fn connect(&self, host: &str, port: u16) -> Result<Box<dyn Stream>> {
match self {
Self::Direct => Ok(Box::new(tcp_connect(host, port).await?)),
Self::Http {
host: proxy_host,
port: proxy_port,
tls,
auth,
} => {
let stream = tcp_connect(proxy_host, *proxy_port).await?;
// TLS to an `https://` proxy carries the whole tunnel.
let mut stream: Box<dyn Stream> = if *tls {
Box::new(tls_connect(stream, proxy_host).await?)
} else {
Box::new(stream)
};
http_connect(&mut stream, host, port, auth.as_ref()).await?;
Ok(stream)
}
Self::Socks {
host: proxy_host,
port: proxy_port,
auth,
remote_dns,
} => {
let mut stream = tcp_connect(proxy_host, *proxy_port).await?;
socks_connect(&mut stream, host, port, auth.as_ref(), *remote_dns).await?;
Ok(Box::new(stream))
}
}
}
}
async fn tcp_connect(host: &str, port: u16) -> Result<TcpStream> {
TcpStream::connect((host, port))
.await
.with_context(|| format!("connecting to {host}:{port}"))
}
/// Wraps `stream` in TLS for `host`. Verifies certificates against system roots, loaded on
/// first use.
pub(super) async fn tls_connect<S: AsyncRead + AsyncWrite + Unpin>(
stream: S,
host: &str,
) -> Result<TlsStream<S>> {
static CONNECTOR: LazyLock<Option<TlsConnector>> = LazyLock::new(|| {
let mut roots = RootCertStore::empty();
let (added, _) =
roots.add_parsable_certificates(rustls_native_certs::load_native_certs().certs);
let config = ClientConfig::builder()
.with_root_certificates(roots)
.with_no_client_auth();
(added > 0).then(|| TlsConnector::from(Arc::new(config)))
});
let connector = CONNECTOR
.as_ref()
.context("no usable system root certificates")?;
let name = ServerName::try_from(host.to_owned()).context("the host is not a DNS name")?;
connector
.connect(name, stream)
.await
.with_context(|| format!("TLS to {host}"))
}
async fn http_connect(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
host: &str,
port: u16,
auth: Option<&Credentials>,
) -> Result<()> {
use base64::Engine;
let authorization = auth.map_or_else(String::new, |Credentials { user, password }| {
let credentials = STANDARD.encode(format!("{user}:{password}"));
format!("Proxy-Authorization: Basic {credentials}\r\n")
});
let request =
format!("CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n{authorization}\r\n");
stream.write_all(request.as_bytes()).await?;
stream.flush().await?;
let head = head::read_head(stream).await?;
let status = head::first_line(&head)?;
ensure!(
status.split_whitespace().nth(1) == Some("200"),
"the proxy refused CONNECT: {status}"
);
Ok(())
}
/// Opens a SOCKS5 CONNECT tunnel (RFC 1928) to `host:port`. With `remote_dns`, asks the proxy
/// to resolve `host`.
async fn socks_connect(
stream: &mut (impl AsyncRead + AsyncWrite + Unpin),
host: &str,
port: u16,
auth: Option<&Credentials>,
remote_dns: bool,
) -> Result<()> {
// Offer the configured authentication method: username and password (RFC 1929), or no
// authentication.
let method = if auth.is_some() { 2 } else { 0 };
stream.write_all(&[5, 1, method]).await?;
let mut reply = [0; 2];
stream.read_exact(&mut reply).await?;
ensure!(
reply == [5, method],
"the SOCKS proxy refuses authentication method {method}"
);
if let Some(Credentials { user, password }) = auth {
let mut request = vec![1];
for field in [user, password] {
let length =
u8::try_from(field.len()).context("SOCKS credentials are over 255 bytes")?;
request.push(length);
request.extend_from_slice(field.as_bytes());
}
stream.write_all(&request).await?;
stream.read_exact(&mut reply).await?;
ensure!(reply == [1, 0], "SOCKS authentication failed");
}
// Send CONNECT with a domain name (3), IPv4 address (1), or IPv6 address (4).
let mut request = vec![5, 1, 0];
if remote_dns {
let length = u8::try_from(host.len()).context("the target hostname is over 255 bytes")?;
request.extend_from_slice(&[3, length]);
request.extend_from_slice(host.as_bytes());
} else {
let address = tokio::net::lookup_host((host, port))
.await?
.next()
.with_context(|| format!("resolving {host}"))?;
let (kind, octets) = match address.ip() {
IpAddr::V4(ip) => (1, ip.octets().to_vec()),
IpAddr::V6(ip) => (4, ip.octets().to_vec()),
};
request.push(kind);
request.extend_from_slice(&octets);
}
request.extend_from_slice(&port.to_be_bytes());
stream.write_all(&request).await?;
let mut reply = [0; 4];
stream.read_exact(&mut reply).await?;
ensure!(reply[..2] == [5, 0], "SOCKS CONNECT failed ({reply:02x?})");
// Skip the address and port the proxy bound.
let address_length = match reply[3] {
1 => 4,
3 => usize::from(stream.read_u8().await?),
4 => 16,
kind => bail!("bad SOCKS address type {kind}"),
};
stream.read_exact(&mut vec![0; address_length + 2]).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use tokio::net::TcpListener;
use super::*;
#[test]
fn upstream_proxy_urls_parse() {
let parse = |url| UpstreamProxy::from_str(url).unwrap();
let http = |port, tls, auth: Option<(&str, &str)>| UpstreamProxy::Http {
host: "proxy".to_owned(),
port,
tls,
auth: auth.map(|(user, password)| Credentials {
user: user.to_owned(),
password: password.to_owned(),
}),
};
assert_eq!(parse("http://proxy:8080"), http(8080, false, None));
let https = parse("https://user:pass@proxy");
assert_eq!(https, http(443, true, Some(("user", "pass"))));
let encoded = parse("http://us%40er:p%3As%25s@proxy");
assert_eq!(encoded, http(80, false, Some(("us@er", "p:s%s"))));
let socks = UpstreamProxy::Socks {
host: "proxy".to_owned(),
port: 1080,
auth: None,
remote_dns: true,
};
assert_eq!(parse("socks5h://proxy"), socks);
assert!(UpstreamProxy::from_str("ftp://proxy").is_err());
assert!(UpstreamProxy::from_str("://missing").is_err());
}
#[tokio::test]
async fn socks5_chains_the_tunnel() {
let socks = TcpListener::bind("127.0.0.1:0").await.unwrap();
let socks_port = socks.local_addr().unwrap().port();
let (request_sender, request_receiver) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
let (mut stream, _) = socks.accept().await.unwrap();
let mut greeting = [0; 3];
stream.read_exact(&mut greeting).await.unwrap();
assert_eq!(greeting, [5, 1, 0]);
stream.write_all(&[5, 0]).await.unwrap();
let mut request = [0; 10];
stream.read_exact(&mut request).await.unwrap();
request_sender.send(request).unwrap();
stream
.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0])
.await
.unwrap();
let (mut reader, mut writer) = stream.split();
tokio::io::copy(&mut reader, &mut writer).await.unwrap();
});
let socks = UpstreamProxy::Socks {
host: "127.0.0.1".to_owned(),
port: socks_port,
auth: None,
remote_dns: false,
};
let mut tunnel = socks.connect("localhost", 80).await.unwrap();
let request = request_receiver.await.unwrap();
assert_eq!(
request[..4],
[5, 1, 0, 1],
"a CONNECT to a locally resolved IPv4 target"
);
assert_eq!(request[8..], 80u16.to_be_bytes(), "the target's port");
tunnel.write_all(b"socks").await.unwrap();
let mut echo = [0; 5];
tunnel.read_exact(&mut echo).await.unwrap();
assert_eq!(&echo, b"socks");
}
}
+17
View File
@@ -0,0 +1,17 @@
//! Extracts challenge-script parameters, encoding constants, parameter mappings, startup state,
//! and page orchestrators. Builds the first payload.
pub(crate) mod codec;
pub(crate) mod expression;
pub mod installed;
pub(crate) mod merge;
pub(crate) mod orchestrator;
pub(crate) mod payload;
pub mod program;
pub mod reduced_timing;
pub(crate) mod source;
pub mod state;
pub mod tally;
pub use codec::decode_response;
pub use source::{inline_javascript, is_post_path, ray};
+544
View File
@@ -0,0 +1,544 @@
//! Encodes payloads in the session's format, and reads them back.
//!
//! Sessions share one algorithm but differ in base64 alphabet, RSA modulus, and key-transform
//! secret. The serialized JSON, wrapped in spaces, is deflated if that makes it smaller, framed,
//! padded to whole blocks, and encrypted with XTEA under a key taken from a random seed. The
//! seed, encrypted with textbook RSA, precedes the ciphertext.
//!
//! [`decode_response`] removes the simpler mask applied to POST responses.
use std::{array, iter};
use anyhow::{Context, Result, bail, ensure};
use base64::Engine;
use base64::alphabet::Alphabet;
use base64::engine::general_purpose::STANDARD;
use base64::engine::{DecodePaddingMode, GeneralPurpose, GeneralPurposeConfig};
use flate2::read::DeflateDecoder;
use num_bigint::BigUint;
use serde_json::Value;
use crate::js::{self, JsObject};
/// Random seed length, also the RSA-encrypted seed length.
pub(crate) const SEED_LENGTH: usize = 128;
/// Length of the symmetric key and key-transform secret.
pub(crate) const KEY_LENGTH: usize = 16;
/// XTEA encrypts 8-byte blocks; the frame is padded to whole blocks.
const BLOCK_LENGTH: usize = 8;
/// The frame's leading `fd 01` marker and version.
const FRAME_MARKER: [u8; 2] = [0xfd, 1];
/// The seed's first byte, which the encoder fixes to keep the seed below the modulus.
pub(crate) const SEED_MARKER: u8 = 2;
/// RSA public exponent used to encrypt seeds in every session.
pub(crate) const PUBLIC_EXPONENT: u32 = 65_537;
/// Serialized payloads shorter than this are never compressed.
const COMPRESSION_THRESHOLD: usize = 128;
/// XTEA's key schedule constant.
const DELTA: u32 = 0x9e37_79b9;
#[derive(Clone)]
pub(crate) struct Codec {
/// The 64-character alphabet as the session spells it, kept for export.
pub(crate) alphabet_text: String,
alphabet: GeneralPurpose,
pub(crate) modulus: BigUint,
pub(crate) secret: [u8; KEY_LENGTH],
}
impl Codec {
/// Requires 64 distinct printable ASCII characters and a modulus exactly as wide as the
/// seed.
pub(crate) fn try_new(
alphabet: &str,
modulus: BigUint,
secret: [u8; KEY_LENGTH],
) -> Result<Self> {
ensure!(
modulus.bits().div_ceil(8) == SEED_LENGTH as u64,
"RSA modulus must be {SEED_LENGTH} bytes wide, not {} bits",
modulus.bits()
);
Ok(Self {
alphabet_text: alphabet.to_owned(),
alphabet: engine(alphabet)?,
modulus,
secret,
})
}
#[must_use]
pub(crate) fn encode(&self, payload: &JsObject, mut seed: [u8; SEED_LENGTH]) -> String {
let mut frame = frame(payload);
let padded = frame.len().next_multiple_of(BLOCK_LENGTH);
let padding = (padded - frame.len()) as u8;
frame.resize(padded, 0);
seed[0] = SEED_MARKER;
let key = frame_key(&seed, padding, &self.secret);
apply(&mut frame, &key, encrypt_block);
Envelope {
wrapped_seed: wrap_seed(&seed, &self.modulus),
padding,
frame,
}
.encode(&self.alphabet)
}
}
/// A request body's parts: the RSA-wrapped seed, the padding byte, and the encrypted frame.
pub(crate) struct Envelope {
pub(crate) wrapped_seed: [u8; SEED_LENGTH],
pub(crate) padding: u8,
pub(crate) frame: Vec<u8>,
}
impl Envelope {
pub(crate) fn decode(body: &str, engine: &GeneralPurpose) -> Result<Self> {
let envelope = engine.decode(body).context("decoding the POST envelope")?;
let (wrapped_seed, rest) = envelope
.split_first_chunk()
.context("the POST envelope is shorter than a wrapped seed")?;
let (&padding, frame) = rest
.split_first()
.context("the POST envelope has no padding byte")?;
ensure!(
frame.len().is_multiple_of(BLOCK_LENGTH),
"the POST frame is not whole blocks: {} bytes",
frame.len()
);
ensure!(
usize::from(padding) < BLOCK_LENGTH,
"the padding byte is not below a block: {padding}"
);
Ok(Self {
wrapped_seed: *wrapped_seed,
padding,
frame: frame.to_vec(),
})
}
#[must_use]
pub(crate) fn encode(&self, engine: &GeneralPurpose) -> String {
engine.encode([&self.wrapped_seed[..], &[self.padding], &self.frame].concat())
}
/// Decrypts the frame with the key derived from `seed` and the session's key-transform
/// `secret`, and reads its payload.
pub(crate) fn payload(
mut self,
seed: &[u8; SEED_LENGTH],
secret: &[u8; KEY_LENGTH],
) -> Result<Value> {
let key = frame_key(seed, self.padding, secret);
apply(&mut self.frame, &key, decrypt_block);
unframe(&self.frame, self.padding)
}
}
/// A session's base64 engine. It encodes without padding characters and,
/// as the challenge server does, decodes with or without them.
pub(crate) fn engine(alphabet: &str) -> Result<GeneralPurpose> {
Ok(GeneralPurpose::new(
&Alphabet::new(alphabet).context("session base64 alphabet")?,
GeneralPurposeConfig::new()
.with_encode_padding(false)
.with_decode_padding_mode(DecodePaddingMode::Indifferent),
))
}
/// Encrypts `seed` with `modulus` using the encoder's textbook RSA.
#[must_use]
pub(crate) fn wrap_seed(seed: &[u8; SEED_LENGTH], modulus: &BigUint) -> [u8; SEED_LENGTH] {
rsa(seed, &PUBLIC_EXPONENT.into(), modulus)
}
/// Computes `block^exponent mod modulus` as big-endian bytes, left-padded to [`SEED_LENGTH`].
///
/// # Panics
///
/// Panics if a modulus wider than [`SEED_LENGTH`] produces a longer result.
#[must_use]
pub(crate) fn rsa(
block: &[u8; SEED_LENGTH],
exponent: &BigUint,
modulus: &BigUint,
) -> [u8; SEED_LENGTH] {
let value = BigUint::from_bytes_be(block)
.modpow(exponent, modulus)
.to_bytes_be();
let mut padded = [0; SEED_LENGTH];
padded[SEED_LENGTH - value.len()..].copy_from_slice(&value);
padded
}
/// Derives the XTEA key from a seed window selected by `padding`, masked with the session's
/// key-transform secret.
#[must_use]
fn frame_key(seed: &[u8; SEED_LENGTH], padding: u8, secret: &[u8; KEY_LENGTH]) -> [u8; KEY_LENGTH] {
let start = 40 + 9 * usize::from(padding);
array::from_fn(|index| seed[start + index] ^ secret[index])
}
/// Builds a frame containing the `fd 01` marker and version, a compression flag, and the
/// serialized payload.
fn frame(payload: &JsObject) -> Vec<u8> {
let json = format!(" {} ", js::stringify_object(payload)).into_bytes();
if json.len() >= COMPRESSION_THRESHOLD {
let compressed = deflate(&json);
if compressed.len() < json.len() {
return [&FRAME_MARKER[..], &[1], &compressed].concat();
}
}
[&FRAME_MARKER[..], &[0], &json].concat()
}
/// Reads a payload from a decrypted frame after removing `padding` zero bytes. Reverses
/// [`frame`].
fn unframe(frame: &[u8], padding: u8) -> Result<Value> {
use std::io::Read;
let unpadded = frame
.len()
.checked_sub(usize::from(padding))
.context("the padding overruns the frame")?;
let (frame, zeros) = frame.split_at(unpadded);
ensure!(
zeros.iter().all(|&byte| byte == 0),
"the frame's padding is not zero bytes"
);
let (&flag, payload) = frame
.strip_prefix(&FRAME_MARKER)
.context("the frame has no fd 01 marker")?
.split_first()
.context("the frame has no compression flag")?;
let json = match flag {
0 => payload.to_vec(),
1 => {
let mut inflated = Vec::new();
DeflateDecoder::new(payload)
.read_to_end(&mut inflated)
.context("inflating the frame payload")?;
inflated
}
flag => bail!("the frame names no compression {flag}"),
};
let json = json
.strip_prefix(b" ")
.and_then(|json| json.strip_suffix(b" "))
.context("the frame payload is not space-wrapped JSON")?;
serde_json::from_slice(json).context("parsing the frame payload")
}
const LENGTH_BASES: [usize; 29] = [
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131,
163, 195, 227, 258,
];
const LENGTH_EXTRA_BITS: [u32; 29] = [
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
];
const DISTANCE_BASES: [usize; 30] = [
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
];
const DISTANCE_EXTRA_BITS: [u32; 30] = [
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13,
13,
];
/// Maximum DEFLATE match length, in bytes.
const MAXIMUM_MATCH: usize = 258;
/// Maximum backward distance for a DEFLATE match, in bytes.
const WINDOW: usize = 32_768;
/// Encodes raw DEFLATE in one fixed-Huffman block. Finds matches with a 13-bit hash of the next
/// three bytes and checks at most two earlier positions per hash.
fn deflate(input: &[u8]) -> Vec<u8> {
let mut out = Bits::default();
// `BFINAL` set, then `BTYPE` 01: a final block with fixed Huffman codes.
out.write(0b011, 3);
let mut chains = Chains {
heads: vec![None; 8192],
links: vec![None; WINDOW],
};
let mut position = 0;
while position < input.len() {
let (mut length, mut distance) = (0, 0);
if position + 3 <= input.len() {
let limit = MAXIMUM_MATCH.min(input.len() - position);
let candidates = iter::successors(chains.insert(input, position), |&earlier| {
chains.before(earlier)
});
let nearest = candidates
.take_while(|&earlier| earlier < position && position - earlier <= WINDOW)
.take(2);
for earlier in nearest {
let matched = (0..limit)
.take_while(|&offset| input[earlier + offset] == input[position + offset])
.count();
if matched > length && matched > 2 {
(length, distance) = (matched, position - earlier);
if matched == limit {
break;
}
}
}
}
if length > 2 {
out.back_reference(length, distance);
let covered =
(position + 1..position + length).take_while(|&skipped| skipped + 3 <= input.len());
for skipped in covered {
chains.insert(input, skipped);
}
position += length;
} else {
out.symbol(usize::from(input[position]));
position += 1;
}
}
out.symbol(256);
out.finish()
}
/// Stores earlier positions by their three-byte hash, newest first.
struct Chains {
heads: Vec<Option<usize>>,
links: Vec<Option<usize>>,
}
impl Chains {
/// Records `position` and returns the most recent earlier position with the same hash.
fn insert(&mut self, input: &[u8], position: usize) -> Option<usize> {
let hash = (usize::from(input[position]) << 5
^ usize::from(input[position + 1]) << 2
^ usize::from(input[position + 2]))
& 8191;
let previous = self.heads[hash].replace(position);
self.links[position % WINDOW] = previous;
previous
}
fn before(&self, position: usize) -> Option<usize> {
self.links[position % WINDOW]
}
}
/// A DEFLATE bit stream, least significant bit first.
#[derive(Default)]
struct Bits {
bytes: Vec<u8>,
pending: u32,
count: u32,
}
impl Bits {
fn write(&mut self, value: u32, bits: u32) {
self.pending |= value << self.count;
self.count += bits;
while self.count >= 8 {
self.bytes.push(self.pending as u8);
self.pending >>= 8;
self.count -= 8;
}
}
/// Writes a literal or length symbol using fixed Huffman codes, most significant bit first.
fn symbol(&mut self, symbol: usize) {
let (code, bits) = match symbol {
0..144 => (0x30 + symbol, 8),
144..256 => (0x190 + symbol - 144, 9),
256..280 => (symbol - 256, 7),
_ => (0xc0 + symbol - 280, 8),
};
self.write(reverse(code, bits), bits);
}
/// Encodes length and distance using the first code range that contains each value.
fn back_reference(&mut self, length: usize, distance: usize) {
let code = (0..LENGTH_BASES.len())
.find(|&code| length < LENGTH_BASES[code] + (1 << LENGTH_EXTRA_BITS[code]))
.expect("matches are at most 258 bytes long");
self.symbol(257 + code);
self.write(
(length - LENGTH_BASES[code]) as u32,
LENGTH_EXTRA_BITS[code],
);
let code = (0..DISTANCE_BASES.len())
.find(|&code| distance < DISTANCE_BASES[code] + (1 << DISTANCE_EXTRA_BITS[code]))
.expect("matches are at most 32768 bytes back");
self.write(reverse(code, 5), 5);
self.write(
(distance - DISTANCE_BASES[code]) as u32,
DISTANCE_EXTRA_BITS[code],
);
}
fn finish(mut self) -> Vec<u8> {
if self.count > 0 {
self.bytes.push(self.pending as u8);
}
self.bytes
}
}
fn reverse(code: usize, bits: u32) -> u32 {
(code as u32).reverse_bits() >> (32 - bits)
}
/// Applies `cipher` to each complete block. Block `i` uses a key derived by encrypting `i` and
/// `i + 1`, modulo 256, with the original key.
fn apply(data: &mut [u8], key: &[u8; KEY_LENGTH], cipher: fn([u32; 2], &[u32; 64]) -> [u32; 2]) {
let base = schedule(words(key));
let schedules: Vec<_> = (0..=u8::MAX)
.take(data.len() / BLOCK_LENGTH)
.map(|index| {
let [a, b] = encrypt_block([0, index.into()], &base);
let [c, d] = encrypt_block([0, index.wrapping_add(1).into()], &base);
schedule([a, b, c, d])
})
.collect();
let (blocks, _) = data.as_chunks_mut::<BLOCK_LENGTH>();
let keyed_blocks = blocks.iter_mut().zip(schedules.iter().cycle());
for (block, keys) in keyed_blocks {
let [a, b] = cipher(words(block), keys);
block[..4].copy_from_slice(&a.to_be_bytes());
block[4..].copy_from_slice(&b.to_be_bytes());
}
}
/// XTEA's round keys, each with its running sum already added.
fn schedule(key: [u32; 4]) -> [u32; 64] {
let mut keys = [0; 64];
let mut sum = 0_u32;
for round in keys.as_chunks_mut::<2>().0 {
round[0] = sum.wrapping_add(key[(sum & 3) as usize]);
sum = sum.wrapping_add(DELTA);
round[1] = sum.wrapping_add(key[(sum >> 11 & 3) as usize]);
}
keys
}
fn encrypt_block([mut a, mut b]: [u32; 2], keys: &[u32; 64]) -> [u32; 2] {
let mix = |value: u32| ((value << 4) ^ (value >> 5)).wrapping_add(value);
for [first, second] in keys.as_chunks::<2>().0 {
a = a.wrapping_add(mix(b) ^ first);
b = b.wrapping_add(mix(a) ^ second);
}
[a, b]
}
fn decrypt_block([mut a, mut b]: [u32; 2], keys: &[u32; 64]) -> [u32; 2] {
let mix = |value: u32| ((value << 4) ^ (value >> 5)).wrapping_add(value);
let (rounds, _) = keys.as_chunks::<2>();
for [first, second] in rounds.iter().rev() {
b = b.wrapping_sub(mix(a) ^ second);
a = a.wrapping_sub(mix(b) ^ first);
}
[a, b]
}
fn words<const N: usize>(bytes: &[u8]) -> [u32; N] {
array::from_fn(|index| u32::from_be_bytes(bytes.as_chunks().0[index]))
}
/// Removes the response mask before the program runs. `token` is the ray identifier in the
/// request path `/fo/.../<ray>/...`.
pub fn decode_response(body: &[u8], token: &str) -> Result<Vec<u8>> {
ensure!(token.is_ascii(), "response token must be ASCII");
let mask = token
.bytes()
.chain(b"_0".iter().copied())
.fold(32_u8, |mask, byte| mask ^ byte);
let bytes = STANDARD
.decode(body)
.context("decoding the response envelope")?;
// The position term repeats every 65535 bytes, and bytes are reduced modulo 255, not 256.
Ok(bytes
.into_iter()
.enumerate()
.map(|(index, byte)| {
(i64::from(byte) - i64::from(mask) - (index % 65_535) as i64).rem_euclid(255) as u8
})
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
/// Checks that an independent inflater handles output with no matches, overlapping runs,
/// maximum match lengths, and distances spanning the window.
#[test]
fn deflate_round_trips_through_an_independent_inflater() {
use std::io::Read;
let mut noise = 0x2545_f491_u32;
let random: Vec<u8> = (0..70_000)
.map(|_| {
noise ^= noise << 13;
noise ^= noise >> 17;
noise ^= noise << 5;
noise as u8
})
.collect();
let mut far = random[..WINDOW - 10].to_vec();
far.extend_from_slice(&random[..300]);
let inputs: [&[u8]; 7] = [
b"",
b"a",
b"abcabcabcabcabcabcabc",
&[b'x'; 1000],
br#"{"a":1,"b":[1,2,3],"c":{"a":1,"b":[1,2,3]}}"#,
&random,
&far,
];
for input in inputs {
let mut inflated = Vec::new();
DeflateDecoder::new(&deflate(input)[..])
.read_to_end(&mut inflated)
.unwrap();
assert!(inflated == input, "{} bytes", input.len());
}
}
const ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#[test]
fn rejects_parameters_the_encoding_cannot_use() {
let modulus = BigUint::from(1u8) << (SEED_LENGTH * 8 - 1);
let secret = [7; KEY_LENGTH];
assert!(Codec::try_new(ALPHABET, modulus.clone(), secret).is_ok());
for bad in [BigUint::ZERO, BigUint::from(3u8), modulus.clone() << 1] {
assert!(
Codec::try_new(ALPHABET, bad, secret).is_err(),
"a zero or narrow modulus would reach modpow or under-size the envelope; a wide \
one would overflow it"
);
}
for alphabet in [&ALPHABET[1..], "é".repeat(32).as_str(), &"A".repeat(64)] {
assert!(Codec::try_new(alphabet, modulus.clone(), secret).is_err());
}
}
#[test]
fn response_position_wraps_at_65535() {
let token = "abcdef0123456789";
let mask = token
.bytes()
.chain(b"_0".iter().copied())
.fold(32_u8, |mask, byte| mask ^ byte);
let plaintext: Vec<_> = (0..65538).map(|index| (index % 254) as u8).collect();
let masked: Vec<_> = plaintext
.iter()
.enumerate()
.map(|(index, &byte)| {
((usize::from(byte) + usize::from(mask) + index % 65535) % 255) as u8
})
.collect();
assert_eq!(
decode_response(STANDARD.encode(masked).as_bytes(), token).unwrap(),
plaintext
);
}
}
+264
View File
@@ -0,0 +1,264 @@
//! AST helpers for challenge-script expressions: `_cf_chl_opt` reads and writes, padded build
//! hashes, objects built in a block, and expressions used to construct options and payloads.
use anyhow::{Context, Result, bail, ensure};
use swc_core::ecma::ast::{
AssignExpr, AssignTarget, BinExpr, BinaryOp, BlockStmt, Expr, Lit, SimpleAssignTarget, Stmt,
UnaryOp,
};
use crate::js::{self, JsValue, Options, Window, ast};
/// Reads the build hash from `"0…0" + <number>.toString(16)`. The zero literal sets the
/// hexadecimal width. Requires an integer literal that fits without truncation; accepts any
/// numeric base and ignores surrounding parentheses.
#[must_use]
pub(crate) fn padded_build(sum: &BinExpr) -> Option<String> {
let zeros = ast::static_str(&sum.left)?;
let call = sum.right.unwrap_parens().as_call()?;
let member = call.callee.as_expr()?.unwrap_parens().as_member()?;
let (Expr::Lit(Lit::Num(number)), [radix]) = (member.obj.unwrap_parens(), &call.args[..])
else {
return None;
};
let padded =
sum.op == BinaryOp::Add && !zeros.is_empty() && zeros.bytes().all(|byte| byte == b'0');
let hexadecimal = ast::member_str(&member.prop) == Some("toString")
&& radix.spread.is_none()
&& ast::index_literal(&radix.expr) == Some(16);
let (number, width) = (number.value, zeros.len());
// For padding wider than sixteen hex digits, the `u64` range limits the value.
let limit = 16f64.powi(i32::try_from(width).ok()?).min(2f64.powi(64));
(padded && hexadecimal && number.fract() == 0.0 && (0.0..limit).contains(&number))
.then(|| format!("{:0width$x}", number as u64))
}
/// Resolves a static expression using known options (see [`evaluate`]). Unknown options have no
/// static value.
#[must_use]
pub(crate) fn static_value(expression: &Expr, options: &Options) -> Option<JsValue> {
evaluate(expression, options, &Window::new()).ok()?
}
/// The `_cf_chl_opt` property read by `<global>._cf_chl_opt.<name>`.
#[must_use]
pub(crate) fn option_key(expression: &Expr) -> Option<&str> {
let member = expression.as_member()?;
ast::member_str(&member.prop).filter(|_| is_options(&member.obj))
}
/// The option assigned by `_cf_chl_opt.<name> = ...`.
#[must_use]
pub(crate) fn option_assignment(target: &AssignTarget) -> Option<&str> {
let member = target.as_simple()?.as_member()?;
ast::member_str(&member.prop).filter(|_| is_options(&member.obj))
}
/// Returns the assignment contained in an expression statement.
pub(crate) fn assignment(statement: &Stmt) -> Option<&AssignExpr> {
statement.as_expr()?.expr.as_assign()
}
/// Finds standalone assignment statements in `body`.
pub(crate) fn assignments(body: &BlockStmt) -> impl Iterator<Item = &AssignExpr> {
body.stmts.iter().filter_map(assignment)
}
/// An object held by a local variable in a block.
pub(crate) struct BuiltObject<'body> {
pub local: &'body str,
pub fields: Vec<ObjectField<'body>>,
}
/// One field of an object, as `key: value` or `<local>.<key> = <value>`.
pub(crate) struct ObjectField<'body> {
pub key: &'body str,
pub value: &'body Expr,
}
/// Records an object assigned to a local, or a property write to one, in `built`. Returns
/// whether it matched. The deobfuscator may emit a literal, or an empty object followed by
/// property writes.
pub(crate) fn track<'body>(
built: &mut Vec<BuiltObject<'body>>,
assignment: &'body AssignExpr,
) -> bool {
let value = &*assignment.right;
match assignment.left.as_simple() {
Some(SimpleAssignTarget::Ident(local)) => {
let Some(fields) = object_fields(value) else {
return false;
};
built.push(BuiltObject {
local: &local.id.sym,
fields,
});
}
Some(SimpleAssignTarget::Member(member)) => {
let Expr::Ident(object) = &*member.obj else {
return false;
};
let target = built
.iter_mut()
.rfind(|target| target.local == &*object.sym);
let (Some(key), Some(target)) = (ast::member_str(&member.prop), target) else {
return false;
};
match target.fields.iter_mut().find(|field| field.key == key) {
Some(field) => field.value = value,
None => target.fields.push(ObjectField { key, value }),
}
}
_ => return false,
}
true
}
/// The fields of an object literal whose keys are all names.
pub(crate) fn object_fields(expression: &Expr) -> Option<Vec<ObjectField<'_>>> {
let fields = expression.as_object()?.props.iter().map(|property| {
let property = ast::key_value(property)?;
Some(ObjectField {
key: ast::key_str(&property.key)?,
value: &property.value,
})
});
fields.collect()
}
/// Evaluates expressions used to build options and payloads. Supports literals, `undefined`,
/// arrays, objects, `!`, `||`, `+`, `-`, `===`, `!==`, and `JSON.stringify`. Reads options from
/// `<global>._cf_chl_opt.<key>` and globals from `<global>.<key>`, including getters called
/// without arguments.
///
/// Objects keep static properties and omit callbacks, matching `JSON.stringify`. `None`
/// represents `undefined`. Unsupported expressions return errors.
pub(crate) fn evaluate(
expression: &Expr,
options: &Options,
globals: &Window,
) -> Result<Option<JsValue>> {
let evaluate = |expression: &Expr| evaluate(expression, options, globals);
Ok(match expression {
Expr::Paren(paren) => evaluate(&paren.expr)?,
Expr::Lit(Lit::Str(_)) | Expr::Tpl(_) => Some(JsValue::from(
ast::static_str(expression).context("unsupported template or string literal")?,
)),
Expr::Lit(Lit::Num(number)) => Some(JsValue::Number(number.value)),
Expr::Lit(Lit::Bool(value)) => Some(JsValue::Bool(value.value)),
Expr::Lit(Lit::Null(_)) => Some(JsValue::Null),
Expr::Ident(ident) if ident.sym == "undefined" => None,
// `JSON.stringify` writes an undefined element as `null`.
Expr::Array(array) => {
let mut elements = Vec::with_capacity(array.elems.len());
for element in &array.elems {
let element = element.as_ref().context("unsupported array hole")?;
ensure!(element.spread.is_none(), "unsupported spread element");
elements.push(evaluate(&element.expr)?.unwrap_or(JsValue::Null));
}
Some(JsValue::Array(elements))
}
Expr::Object(object) => Some(JsValue::Object(
ast::key_values(object)
.filter_map(|property| {
let value = evaluate(&property.value).ok()??;
Some((ast::key_str(&property.key)?.to_owned(), value))
})
.collect(),
)),
// `!x` is always a boolean; an unset option is `undefined`, so falsy.
Expr::Unary(unary) if unary.op == UnaryOp::Bang => Some(JsValue::Bool(
!evaluate(&unary.arg)?.as_ref().is_some_and(js::truthy),
)),
Expr::Bin(binary) => {
let left = evaluate(&binary.left)?;
match binary.op {
// The right-hand side runs only when the left is falsy.
BinaryOp::LogicalOr if left.as_ref().is_some_and(js::truthy) => left,
BinaryOp::LogicalOr => evaluate(&binary.right)?,
BinaryOp::Sub => Some(JsValue::Number(
js::number(left.as_ref()) - js::number(evaluate(&binary.right)?.as_ref()),
)),
BinaryOp::Add => {
let right = evaluate(&binary.right)?;
// Strings, arrays, and objects trigger string concatenation; other values
// use numeric addition.
let textual = |value: Option<&JsValue>| {
matches!(
value,
Some(JsValue::String(_) | JsValue::Array(_) | JsValue::Object(_))
)
};
let (left, right) = (left.as_ref(), right.as_ref());
Some(if textual(left) || textual(right) {
JsValue::String(format!("{}{}", js::string(left), js::string(right)))
} else {
JsValue::Number(js::number(left) + js::number(right))
})
}
BinaryOp::EqEqEq | BinaryOp::NotEqEq => {
let [left, right] = [left, evaluate(&binary.right)?]
.map(|value| value.unwrap_or(JsValue::Undefined));
// `JsValue` equality implements `===` for primitive values. Copies of
// objects have no identity to compare.
let object =
|value: &JsValue| matches!(value, JsValue::Array(_) | JsValue::Object(_));
ensure!(
!object(&left) || !object(&right),
"unsupported identity comparison of an object"
);
Some(JsValue::Bool(
(left == right) == (binary.op == BinaryOp::EqEqEq),
))
}
operator => bail!("unsupported operator {operator}"),
}
}
Expr::Member(member) => {
let key = ast::member_str(&member.prop).context("unsupported computed property")?;
match &*member.obj {
object if is_options(object) => options.get(key).cloned(),
Expr::Ident(_) => globals.get(key).cloned(),
object => match evaluate(object)? {
Some(JsValue::Object(object)) => object.get(key).cloned(),
None | Some(JsValue::Undefined) => bail!("reads {key} of undefined"),
Some(other) => bail!("unsupported read of {key} from {other}"),
},
}
}
Expr::Call(call) => {
let member = call
.callee
.as_expr()
.and_then(|callee| callee.as_member())
.context("unsupported call")?;
if ast::is_method_of(member, "JSON", "stringify") {
let [argument] = &call.args[..] else {
bail!("unsupported JSON.stringify arguments");
};
ensure!(argument.spread.is_none(), "unsupported spread argument");
// `JSON.stringify(undefined)` is itself `undefined`.
evaluate(&argument.expr)?
.and_then(|value| value.stringify())
.map(JsValue::String)
} else if matches!(&*member.obj, Expr::Ident(_)) && call.args.is_empty() {
// Use the getter's collected value instead of running the call.
globals
.get(ast::member_str(&member.prop).context("unsupported computed getter")?)
.cloned()
} else {
bail!("unsupported call")
}
}
_ => bail!("unsupported expression"),
})
}
/// Whether an expression is the `_cf_chl_opt` object itself, rather than one of its properties.
#[must_use]
pub(crate) fn is_options(expression: &Expr) -> bool {
matches!(
expression,
Expr::Member(member) if ast::member_str(&member.prop) == Some("_cf_chl_opt")
)
}
+182
View File
@@ -0,0 +1,182 @@
//! Recovers options and globals installed by the iframe's initial VM program.
//!
//! Some installed options have `toJSON` methods returning constants, but the payload encoder
//! never calls `toJSON` and skips function members, so it sends the other members. The window
//! globals include a build marker, a selector log, and functions built from constants, such as
//! the key transform's `window[name] = factory(secret)`.
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use anyhow::Result;
use crate::js::{JsObject, JsValue, Options, Window, json};
use crate::listing::fold::{Frame, Known};
use crate::listing::query;
use crate::script::Source;
use crate::vm::{Effect, Exit, Listing, Term};
/// Values tracked beyond literals while recovering installed options.
#[derive(Clone)]
enum Held {
EmptyArray,
Options,
Window,
/// The result of a call with one string-constant argument.
Built(String),
}
/// Options and globals left by the initial program.
#[derive(Clone, Debug, Default)]
pub struct Installed {
/// Option objects as the payload encoder serializes them.
pub options: Options,
/// Literal window globals. If several paths assign a global, the ordinary path is processed
/// last and wins.
pub window: Window,
/// Window globals created by calls with one string constant, mapped to that constant.
pub built: BTreeMap<String, String>,
}
/// Recovers values installed by the initial `program`, decoded from its program runner call.
pub fn read(source: &Source, program: &[u8]) -> Result<Installed> {
let listing = source.disassemble(program)?;
let initialization = initialization(&listing);
let mut frame: Frame<Held> = Frame::default();
let mut objects: HashMap<u32, JsObject> = HashMap::new();
let mut installed = Installed::default();
for (&pc, instruction) in &listing.instructions {
if !initialization.contains(&pc) {
continue;
}
for path in &instruction.paths {
frame.begin();
frame.follow(pc, &path.effects, evaluate, |frame, effect| {
let Effect::SetProperty { object, key, value } = effect else {
return;
};
let (Some(object), Some(Known::Literal(JsValue::String(key))), Some(value)) = (
frame.resolve(object),
frame.resolve(key),
frame.resolve(value),
) else {
return;
};
match (object, value) {
// The encoder skips function members, such as `toJSON`.
(Known::Object(id), Known::Literal(value)) => {
objects.entry(id).or_default().insert(key, value);
}
(
Known::Ext(Held::Window),
Known::Literal(value @ (JsValue::String(_) | JsValue::Number(_))),
) => {
installed.window.insert(key, value);
}
(Known::Ext(Held::Window), Known::Ext(Held::EmptyArray)) => {
installed.window.insert(key, json!([]));
}
(Known::Ext(Held::Window), Known::Ext(Held::Built(constant))) => {
installed.built.insert(key, constant);
}
(Known::Ext(Held::Options), Known::Object(id)) => {
let members = objects.get(&id).cloned().unwrap_or_default();
installed.options.insert(key, JsValue::Object(members));
}
_ => {}
}
});
}
}
Ok(installed)
}
/// The value an assignment writes. Recognizes calls with one string constant, such as the key
/// transform `factory(secret)`.
fn evaluate(frame: &Frame<Held>, value: &Term) -> Option<Known<Held>> {
Some(match value {
Term::Array(elements) if elements.is_empty() => Known::Ext(Held::EmptyArray),
Term::Get(_, key) => match frame.resolve(key)?.text()? {
"_cf_chl_opt" => Known::Ext(Held::Options),
"window" => Known::Ext(Held::Window),
_ => return None,
},
Term::Call { arguments, .. } => {
let [argument] = arguments.as_slice() else {
return None;
};
Known::Ext(Held::Built(frame.resolve(argument)?.text()?.to_owned()))
}
value => frame.resolve(value)?,
})
}
/// Finds startup instructions reachable from the entry, the returned function called by the
/// iframe, and their callees. Excludes exception handlers and callbacks that are installed
/// without being called.
fn initialization(listing: &Listing) -> BTreeSet<u32> {
let returned = return_register(listing);
let entry = listing.functions.first().map(|function| function.pc);
let mut reached = BTreeSet::new();
let mut functions: Vec<u32> = entry.into_iter().collect();
let mut entered = HashSet::new();
while let Some(function) = functions.pop() {
if !entered.insert(function) {
continue;
}
let entry_function = Some(function) == entry;
let mut closures: HashMap<u8, u32> = HashMap::new();
let unreached = |pc: u32| !reached.contains(&pc);
let walked = query::walk(listing, function, unreached, |_, instruction, pending| {
for path in &instruction.paths {
for effect in &path.effects {
match effect {
Effect::Set(register, Term::Closure { pc, .. }) => {
closures.insert(*register, *pc);
}
Effect::Set(register, Term::Reg(source))
if entry_function && Some(*register) == returned =>
{
functions.extend(closures.get(source));
}
_ => {
if let Some((Term::Reg(register), _)) = effect.call()
&& let Some(&function) = closures.get(register)
{
functions.push(function);
}
}
}
}
if let Exit::Next { pc, .. } | Exit::Unfollowed { pc, .. } = path.exit {
pending.push(pc);
}
}
});
reached.extend(walked);
}
reached
}
/// Finds the register that most return instructions write last.
fn return_register(listing: &Listing) -> Option<u8> {
let mut counts: HashMap<u8, usize> = HashMap::new();
let returns = listing
.instructions
.values()
.flat_map(|instruction| &instruction.paths)
.filter(|path| path.exit == Exit::Return);
for path in returns {
// Newer instruction layouts restore the VM stack after assigning the return value.
let written = path.effects.iter().rev().find_map(|effect| match effect {
Effect::Set(register, _) => Some(*register),
_ => None,
});
if let Some(register) = written {
*counts.entry(register).or_default() += 1;
}
}
counts
.into_iter()
.max_by_key(|&(register, count)| (count, register))
.map(|(register, _)| register)
}
+509
View File
@@ -0,0 +1,509 @@
//! Recovers how the iframe copies the embedding page's `extraParams` message fields into
//! randomly named `_cf_chl_opt` options.
use anyhow::{Context, Result};
use swc_core::ecma::ast::{
AssignTarget, BinaryOp, CallExpr, Callee, Expr, FnDecl, SimpleAssignTarget, Stmt, UnaryOp,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use crate::challenge::expression;
use crate::js::ast::{self, ParsedScript};
use crate::js::{JsValue, Options, json};
use crate::{candidates, js};
/// Minimum number of option writes from parameter fields that identifies the merge function.
const MINIMUM_FIELDS: usize = 10;
/// Where one option's value comes from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OptionSource {
/// A field of the embedding page's `extraParams` message.
Message(String),
/// The origin the message arrived from.
Origin,
/// The time the iframe merged the message.
Merged,
/// Copied from another option, possibly after stored state overrides it.
Copied(String),
/// Embedding-page call-stack samples, rewritten by the iframe during copying.
Samples(String),
/// The iframe's own state. The embedding page supplies nothing for these.
Runtime,
}
/// An option written by the merge and the source of its value.
#[derive(Debug, Clone)]
pub struct OptionEntry {
pub option: String,
pub source: OptionSource,
/// The fallback the iframe substitutes for a falsy value.
pub default: Option<JsValue>,
}
/// Every option the merge writes, in the order the iframe writes them.
#[derive(Debug, Clone)]
pub struct Mapping(pub Vec<OptionEntry>);
impl Mapping {
#[cfg(test)]
pub(crate) fn from_javascript(source: &str) -> Result<Self> {
Self::from_parsed(&ast::parse_iframe_javascript(source)?)
}
pub(crate) fn from_parsed(parsed: &ParsedScript) -> Result<Self> {
let merges = ast::in_declared_functions(&parsed.script, merge_function);
let merge =
candidates::exactly_one(merges, "function merging the embedding page's parameters")?;
let mut calls = Calls {
merge: &merge,
roles: Vec::new(),
};
parsed.script.visit_with(&mut calls);
let roles = candidates::at_most_one_distinct(calls.roles, "merge call arguments")?
.context("could not find where the merge is called")?;
let entries = merge.writes.into_iter().map(|write| write.entry(&roles));
Ok(Self(entries.collect()))
}
/// Merges the collected message into bootstrap options. Returns the options that still need
/// iframe state unavailable to this caller.
pub fn merge(
&self,
options: &mut Options,
message: &JsValue,
origin: &str,
merged_at: i64,
) -> Vec<String> {
let mut runtime = Vec::new();
for entry in &self.0 {
let value = match &entry.source {
OptionSource::Message(key) => message.get(key).cloned(),
OptionSource::Origin => Some(json!(origin)),
OptionSource::Merged => Some(json!(merged_at)),
OptionSource::Copied(from) => options.get(from).cloned(),
OptionSource::Samples(key) => Some(samples(message.get(key))),
OptionSource::Runtime => {
runtime.push(entry.option.clone());
continue;
}
};
let value = value
.filter(|value| entry.default.is_none() || js::truthy(value))
.or_else(|| entry.default.clone());
if let Some(value) = value {
options.insert(entry.option.clone(), value);
} else {
// Assigning `undefined` removes the field from the payload.
options.shift_remove(&entry.option);
}
}
runtime
}
/// The option timestamped when the iframe merges the embedding page's parameters.
#[must_use]
pub fn merged(&self) -> Option<&str> {
self.0
.iter()
.find(|entry| entry.source == OptionSource::Merged)
.map(|entry| entry.option.as_str())
}
/// Lists `extraParams` fields read by this session so collectors can be checked against the
/// script.
#[must_use]
pub fn fields(&self) -> Vec<&str> {
let mut fields: Vec<&str> = self
.0
.iter()
.filter_map(|entry| match &entry.source {
OptionSource::Message(key) => Some(key.as_str()),
_ => None,
})
.collect();
fields.sort_unstable();
fields.dedup();
fields
}
}
/// The source of an option assignment's right-hand side.
enum Written {
/// A parameter, or a field of one.
Field {
parameter: usize,
key: Option<String>,
},
/// Another option's value, copied through a local variable.
Copied(String),
Samples {
parameter: usize,
key: String,
},
Now,
Other,
}
/// One `_cf_chl_opt.<option> = ...` in the merge's body.
struct OptionWrite {
option: String,
value: Written,
/// The literal the value falls back to when it is falsy.
default: Option<JsValue>,
}
impl OptionWrite {
/// Resolves an assignment's source from the merge arguments. If the caller extracted a
/// message field before the call, uses the fallback supplied by that caller.
fn entry(self, roles: &[Role]) -> OptionEntry {
let (source, fallback) = match self.value {
Written::Now => (OptionSource::Merged, None),
Written::Copied(from) => (OptionSource::Copied(from), None),
Written::Other => (OptionSource::Runtime, None),
Written::Field { parameter, key } => match (&roles[parameter], key) {
// Reading a property of the message supplies the field name.
(Role::Message, Some(key)) => (OptionSource::Message(key), None),
(Role::Origin, None) => (OptionSource::Origin, None),
// The caller passed a message field directly.
(Role::Field { key, fallback }, None) => {
(OptionSource::Message(key.clone()), fallback.clone())
}
_ => (OptionSource::Runtime, None),
},
Written::Samples { parameter, key } => match &roles[parameter] {
Role::Message => (OptionSource::Samples(key), None),
_ => (OptionSource::Runtime, None),
},
};
OptionEntry {
option: self.option,
source,
default: self.default.or(fallback),
}
}
}
/// The value passed as one merge argument.
#[derive(Debug, Clone, PartialEq)]
enum Role {
Message,
Origin,
/// A field of the message, unwrapped by the caller with the fallback it applied.
Field {
key: String,
fallback: Option<JsValue>,
},
Unknown,
}
/// A candidate merge function.
struct Merge {
name: String,
arity: usize,
writes: Vec<OptionWrite>,
}
/// A function declaration that writes enough options from parameter fields to be the merge.
fn merge_function(function: &FnDecl) -> Option<Merge> {
let writes = writes(function);
let fields = writes
.iter()
.filter(|write| matches!(write.value, Written::Field { key: Some(_), .. }));
(fields.count() >= MINIMUM_FIELDS).then(|| Merge {
name: function.ident.sym.to_string(),
arity: function.function.params.len(),
writes,
})
}
/// Identifies arguments in merge calls that pass the message exactly once and have no unknown
/// arguments. Calls that deliver the message also pass its origin. Other calls use stored local
/// variables; treating them as message delivery would produce incorrect field mappings.
struct Calls<'merge> {
merge: &'merge Merge,
roles: Vec<Vec<Role>>,
}
impl Visit for Calls<'_> {
fn visit_call_expr(&mut self, call: &CallExpr) {
if let Callee::Expr(callee) = &call.callee
&& let Expr::Ident(ident) = &**callee
&& ident.sym == *self.merge.name
&& call.args.len() == self.merge.arity
{
let roles: Vec<Role> = call
.args
.iter()
.map(|argument| role(&argument.expr))
.collect();
if roles.iter().filter(|role| **role == Role::Message).count() == 1
&& !roles.contains(&Role::Unknown)
{
self.roles.push(roles);
}
}
call.visit_children_with(self);
}
}
fn role(expression: &Expr) -> Role {
match expression {
Expr::Ident(_) => Role::Message,
Expr::Bin(binary) if binary.op == BinaryOp::LogicalOr => match role(&binary.left) {
Role::Field { key, .. } => Role::Field {
key,
fallback: expression::static_value(&binary.right, &Options::new()),
},
other => other,
},
_ => match expression.as_member().and_then(ast::ident_property) {
Some("origin") => Role::Origin,
Some(key) => Role::Field {
key: key.to_owned(),
fallback: None,
},
None => Role::Unknown,
},
}
}
/// Every `_cf_chl_opt.<name> = ...` in a function's own body.
fn writes(function: &FnDecl) -> Vec<OptionWrite> {
let parameters: Vec<&str> = function
.function
.params
.iter()
.map(|parameter| parameter.pat.as_ident().map_or("", |ident| &*ident.id.sym))
.collect();
let Some(body) = &function.function.body else {
return Vec::new();
};
// Some options pass through a local so stored browser state can override them before they
// are written back.
let mut staged: Vec<(&str, &str)> = Vec::new();
let mut writes = Vec::new();
for statement in &body.stmts {
if let Some(write) = sampled(statement, &parameters) {
writes.push(write);
continue;
}
let Some(assignment) = expression::assignment(statement) else {
continue;
};
if let AssignTarget::Simple(SimpleAssignTarget::Ident(local)) = &assignment.left
&& let Some(option) = expression::option_key(&assignment.right)
{
staged.push((&local.id.sym, option));
continue;
}
let Some(option) = expression::option_assignment(&assignment.left).map(str::to_owned)
else {
continue;
};
let (mut value, default) = read(&assignment.right, &parameters);
if let (Written::Other, Expr::Ident(ident)) = (&value, &*assignment.right)
&& let Some((_, from)) = staged.iter().rfind(|(local, _)| *local == &*ident.sym)
{
value = Written::Copied((*from).to_owned());
}
writes.push(OptionWrite {
option,
value,
default,
});
}
writes
}
/// Recognizes the first sample copy: `if (!_cf_chl_opt.<option>.length) {
/// copy(<parameter>.<key>); }`.
fn sampled(statement: &Stmt, parameters: &[&str]) -> Option<OptionWrite> {
if let Stmt::If(branch) = statement
&& let Expr::Unary(test) = &*branch.test
&& test.op == UnaryOp::Bang
&& let Expr::Member(length) = &*test.arg
&& ast::member_str(&length.prop) == Some("length")
&& let Some(option) = expression::option_key(&length.obj)
&& let Stmt::Block(block) = &*branch.cons
&& let [Stmt::Expr(copy)] = &block.stmts[..]
&& let Expr::Call(copy) = &*copy.expr
&& let [argument] = &copy.args[..]
&& let (Written::Field { parameter, key }, _) = read(&argument.expr, parameters)
&& let Some(key) = key
{
Some(OptionWrite {
option: option.to_owned(),
value: Written::Samples { parameter, key },
default: None,
})
} else {
None
}
}
/// Converts `[method, time, stack, count]` samples to the iframe's object format, with a letter
/// identifying the method.
fn samples(entries: Option<&JsValue>) -> JsValue {
let entries = entries.and_then(JsValue::as_array).into_iter().flatten();
let samples = entries.filter_map(|entry| {
let [method, time, stack, count] = entry.as_array()?.as_slice() else {
return None;
};
Some(json!({
"m": char::from(b'a' + method.as_f64()? as u8).to_string(),
"t": time,
"s": stack,
"c": count,
}))
});
samples.collect()
}
/// Resolves `expression` and its literal fallback for falsy values.
fn read(expression: &Expr, parameters: &[&str]) -> (Written, Option<JsValue>) {
let field = |name: &str, key: Option<&str>| {
let parameter = parameters.iter().position(|parameter| *parameter == name)?;
let key = key.map(str::to_owned);
Some(Written::Field { parameter, key })
};
let written = match expression {
Expr::Paren(paren) => return read(&paren.expr, parameters),
Expr::Bin(binary) if binary.op == BinaryOp::LogicalOr => {
let (written, _) = read(&binary.left, parameters);
let fallback = expression::static_value(&binary.right, &Options::new());
return (written, fallback);
}
Expr::Ident(ident) => field(&ident.sym, None),
Expr::Member(member) => match (&*member.obj, ast::member_str(&member.prop)) {
(Expr::Ident(object), Some(key)) => field(&object.sym, Some(key)),
_ => None,
},
Expr::Call(_) if ast::is_date_now(expression) => Some(Written::Now),
_ => None,
};
(written.unwrap_or(Written::Other), None)
}
#[cfg(test)]
mod tests {
use super::*;
const SOURCE: &str = r#"
function tC(tL, tq, ta, tn) {
e._cf_chl_opt.OqAoN4 = tL.action;
e._cf_chl_opt.BkYo5 = tL.cData;
e._cf_chl_opt.vXDzj6 = tL.url;
e._cf_chl_opt.YghXX0 = tL.retry || "auto";
e._cf_chl_opt.XOKPk1 = tL["retry-interval"] || 8e3;
e._cf_chl_opt.CHyD3 = tL.language || "auto";
e._cf_chl_opt.ZTew0 = tL.execution || "render";
e._cf_chl_opt.VnGsz1 = tq;
e._cf_chl_opt.IPeXW2 = tL.ch || ``;
e._cf_chl_opt.vVvpJ8 = tL.wPr || {};
e._cf_chl_opt.tZwbF3 = tL.timeLoadInitMs || 0;
e._cf_chl_opt.yAFE2 = ta;
e._cf_chl_opt.zfniV9 = tn;
e._cf_chl_opt.AOzXq2 = Date.now();
e._cf_chl_opt.WbdgY0 = z2;
}
function handler(tP) {
var tU = tP.data;
if (tU.event === "extraParams") {
tC(tU, tP.origin, tU.apiJsMismatchReloadAttempts || 0, tU.apiJsMismatchReloadCompletedCount || 0);
}
}"#;
#[test]
fn recovers_field_names_defaults_and_argument_roles() {
let mapping = Mapping::from_javascript(SOURCE).unwrap();
let message = |field: &str| OptionSource::Message(field.into());
for (option, source, default) in [
("OqAoN4", message("action"), None),
("XOKPk1", message("retry-interval"), Some(json!(8000))),
("vVvpJ8", message("wPr"), Some(json!({}))),
("IPeXW2", message("ch"), Some(json!(""))),
("VnGsz1", OptionSource::Origin, None),
// The call site unwrapped this argument; it keeps the field name it came from.
(
"yAFE2",
message("apiJsMismatchReloadAttempts"),
Some(json!(0)),
),
("AOzXq2", OptionSource::Merged, None),
("WbdgY0", OptionSource::Runtime, None),
] {
let entry = mapping
.0
.iter()
.find(|entry| entry.option == option)
.unwrap();
assert_eq!(
(&entry.source, &entry.default),
(&source, &default),
"{option}"
);
}
assert!(mapping.fields().contains(&"wPr"));
}
#[test]
fn rejects_merge_calls_that_disagree_about_their_arguments() {
let source = format!("{SOURCE}\nfunction other(tU) {{ tC(tU, tU.origin, tU.x, tU.y); }}");
let error = Mapping::from_javascript(&source).unwrap_err().to_string();
assert!(error.contains("conflicting"), "{error}");
// This call passes the message through two local variables, so it cannot be the
// delivery call. Repeating it does not create a conflicting mapping.
for caller in [
"function replay(r0, r1) { tC(r0, r1, r0.apiJsMismatchReloadAttempts || 0, r0.apiJsMismatchReloadCompletedCount || 0); }",
"function again(tP) { var tU = tP.data; tC(tU, tP.origin, tU.apiJsMismatchReloadAttempts || 0, tU.apiJsMismatchReloadCompletedCount || 0); }",
] {
let source = format!("{SOURCE}\n{caller}");
assert!(Mapping::from_javascript(&source).is_ok(), "{caller}");
}
}
/// Uses fallbacks for falsy values. Omits absent fields without fallbacks as `undefined`,
/// and leaves runtime options for the iframe to supply.
#[test]
fn merge_applies_javascript_fallbacks_and_reports_what_it_cannot_fill() {
let mapping = Mapping::from_javascript(SOURCE).unwrap();
let mut options = Options::from_iter([("WbdgY0".to_owned(), json!("bootstrap-id"))]);
let message = json!({
"action": "login",
"url": "https://example.com/",
"retry": "",
"retry-interval": 0,
"language": "de",
"wPr": {"w.iW": 1280},
"timeLoadInitMs": 323,
"apiJsMismatchReloadAttempts": 0,
});
let runtime = mapping.merge(
&mut options,
&message,
"https://example.com",
1_789_331_612_058,
);
assert_eq!(runtime, ["WbdgY0"]);
assert_eq!(
JsValue::from(options),
json!({
"WbdgY0": "bootstrap-id",
"OqAoN4": "login",
"vXDzj6": "https://example.com/",
"YghXX0": "auto",
"XOKPk1": 8000,
"CHyD3": "de",
"ZTew0": "render",
"VnGsz1": "https://example.com",
"IPeXW2": "",
"vVvpJ8": {"w.iW": 1280},
"tZwbF3": 323,
"yAFE2": 0,
"zfniV9": 0,
"AOzXq2": 1_789_331_612_058_i64,
})
);
}
}
+303
View File
@@ -0,0 +1,303 @@
//! Reads Cloudflare's challenge page, served with status 403 as "Just a moment...".
//!
//! The page's inline script installs options and loads an orchestrator from the protected
//! site's origin, which uses the iframe's VM and encoder. Its first response program renders a
//! Turnstile widget; after the widget completes, a second POST returns a program that submits
//! the form that obtains the clearance cookie.
use std::collections::BTreeSet;
use anyhow::{Context, Result};
use swc_core::ecma::ast::{AssignExpr, BinExpr, BinaryOp, CallExpr, Callee, Expr, MemberExpr};
use swc_core::ecma::visit::{Visit, VisitWith};
use url::Url;
use crate::candidates;
use crate::challenge::{expression, source};
use crate::js::{JsValue, Options, ast};
use crate::script::Source;
/// The orchestrator is served from this path prefix of the challenge page's origin.
const ORCHESTRATOR: &str = "/orchestrate/";
/// Query parameter used in the temporary page address while the orchestrator loads.
const LOADING_TOKEN: &str = "__cf_chl_rt_tk=";
/// The loader path the orchestrator builds.
const LOADER: &str = "/api.js?onload=";
/// Fixed page option holding the address to restore after the challenge. The orchestrator
/// renames page options during startup.
const ANSWERED: &str = "cUPMDTk";
/// A challenge page, as the protected site served it.
#[derive(Debug, Clone)]
pub(crate) struct ChallengePage {
pub url: Url,
pub html: String,
/// The inline script that installs the options and loads the orchestrator.
pub inline: String,
pub orchestrator: Url,
/// Temporary page URL, the referrer while the orchestrator loads.
pub loading: Url,
/// Page address restored after the challenge, which the clearance form is submitted from.
pub answered: Option<Url>,
}
impl ChallengePage {
/// `None` when `html` is not a challenge page.
pub(crate) fn parse(html: &str, url: &Url) -> Result<Option<Self>> {
let Ok(inline) = source::inline_javascript(html) else {
return Ok(None);
};
let parsed = ast::parse_javascript("challenge page", &inline)?;
let literals = ast::string_literals(&parsed.script);
let Some(orchestrator) = candidates::at_most_one_distinct(
literals.iter().filter(|text| {
text.starts_with("/cdn-cgi/challenge-platform/") && text.contains(ORCHESTRATOR)
}),
"orchestrator path",
)?
else {
return Ok(None);
};
let loading = candidates::at_most_one_distinct(
literals.iter().filter(|text| text.contains(LOADING_TOKEN)),
"loading address",
)?
.context("challenge page shows no loading address")?;
let answered = source::bootstrap_options(&parsed)
.get(ANSWERED)
.and_then(JsValue::as_str)
.map(|address| url.join(address))
.transpose()?;
Ok(Some(Self {
orchestrator: url.join(orchestrator)?,
loading: url.join(loading)?,
answered,
url: url.clone(),
html: html.to_owned(),
inline,
}))
}
/// Combines the inline options script and orchestrator for session extraction.
#[must_use]
pub(crate) fn javascript(&self, orchestrator: &str) -> String {
format!("{}\n;\n{orchestrator}", self.inline)
}
}
/// Recovers unset frame options from startup checks such as `top !== self` and
/// `!top.location.hostname`. Recognizes direct reads of `top` and calls to functions that read
/// it. These checks are all false on a top-level challenge page.
#[must_use]
pub(crate) fn frame_options(source: &Source, options: &Options) -> Options {
let script = &source.parsed().script;
let readers = ast::in_declared_functions(script, |function| {
reads_top(&*function.function).then(|| function.ident.sym.to_string())
});
let mut framing = Framing {
readers: &readers,
options,
found: Options::new(),
};
script.visit_with(&mut framing);
framing.found
}
/// Whether a node reads a `top` property.
fn reads_top(node: &impl VisitWith<TopRead>) -> bool {
let mut read = TopRead(false);
node.visit_with(&mut read);
read.0
}
struct TopRead(bool);
impl Visit for TopRead {
fn visit_member_expr(&mut self, member: &MemberExpr) {
self.0 |= ast::member_str(&member.prop) == Some("top");
member.visit_children_with(self);
}
}
/// Assigns `false` to unset options whose value reads `top` or calls a declared function that
/// does.
struct Framing<'known> {
readers: &'known [String],
options: &'known Options,
found: Options,
}
impl Visit for Framing<'_> {
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
if let Some(option) = expression::option_assignment(&assignment.left)
&& !self.options.contains_key(option)
{
let value = assignment.right.unwrap_parens();
let calls_reader = ast::direct_call(value).is_some_and(|(name, arguments)| {
arguments.is_empty() && self.readers.iter().any(|reader| *reader == *name.sym)
});
if calls_reader || reads_top(value) {
self.found.insert(option.to_owned(), JsValue::Bool(false));
}
}
assignment.visit_children_with(self);
}
}
/// Recovers the Turnstile loader URL from its host option and a path assembled from literals,
/// options, and a padded build number.
pub(crate) fn loader_url(source: &Source, options: &Options) -> Result<Url> {
let mut found = Loader {
options,
builds: BTreeSet::new(),
paths: Vec::new(),
hosts: BTreeSet::new(),
};
source.parsed().script.visit_with(&mut found);
let build = candidates::exactly_one(found.builds, "loader build")?;
let host = candidates::exactly_one(found.hosts, "loader host")?;
let paths: BTreeSet<String> = found
.paths
.into_iter()
.map(|parts| {
parts
.into_iter()
.map(|part| part.unwrap_or_else(|| build.clone()))
.collect()
})
.collect();
let path = candidates::exactly_one(paths, "loader path")?;
Url::parse(&format!("https://{host}{path}")).context("building the loader URL")
}
struct Loader<'options> {
options: &'options Options,
/// `("000…" + <number>.toString(16)).slice(-n)`.
builds: BTreeSet<String>,
/// Loader-path concatenations. `None` marks the build component.
paths: Vec<Vec<Option<String>>>,
/// Options a concatenation puts right after `"https://"`.
hosts: BTreeSet<String>,
}
impl Loader<'_> {
/// Returns the operands of a `+` chain from left to right.
fn operands<'e>(expression: &'e Expr, out: &mut Vec<&'e Expr>) {
match expression.unwrap_parens() {
Expr::Bin(binary) if binary.op == BinaryOp::Add => {
Self::operands(&binary.left, out);
Self::operands(&binary.right, out);
}
other => out.push(other),
}
}
fn option(&self, operand: &Expr) -> Option<String> {
self.options
.get(expression::option_key(operand)?)?
.as_str()
.map(str::to_owned)
}
}
impl Visit for Loader<'_> {
fn visit_call_expr(&mut self, call: &CallExpr) {
// `(zeros + number.toString(16)).slice(-width)`.
if let Callee::Expr(callee) = &call.callee
&& let Expr::Member(slice) = callee.unwrap_parens()
&& ast::member_str(&slice.prop) == Some("slice")
&& let Expr::Bin(sum) = slice.obj.unwrap_parens()
&& let Some(build) = expression::padded_build(sum)
{
self.builds.insert(build);
}
call.visit_children_with(self);
}
fn visit_bin_expr(&mut self, binary: &BinExpr) {
if binary.op == BinaryOp::Add {
let mut operands = Vec::new();
Self::operands(&binary.left, &mut operands);
Self::operands(&binary.right, &mut operands);
if operands
.iter()
.any(|operand| ast::static_str(operand).is_some_and(|text| text.contains(LOADER)))
{
// The path references its build once through a variable.
let parts: Option<Vec<_>> = operands
.iter()
.map(|operand| match (ast::static_str(operand), operand) {
(Some(text), _) => Some(Some(text.to_owned())),
(None, Expr::Ident(_)) => Some(None),
(None, _) => self.option(operand).map(Some),
})
.collect();
if let Some(parts) = parts
&& parts.iter().filter(|part| part.is_none()).count() == 1
{
self.paths.push(parts);
}
return;
}
if let [first, second, ..] = operands.as_slice()
&& ast::static_str(first) == Some("https://")
&& let Some(host) = self.option(second)
{
self.hosts.insert(host);
}
}
binary.visit_children_with(self);
}
}
/// Reads the page language tag stored beside the message table, regardless of its option name.
#[must_use]
pub(crate) fn language(options: &Options) -> Option<&str> {
let is_tag = |text: &&str| {
let mut parts = text.split('-');
parts.next().is_some_and(|primary| {
(2..=3).contains(&primary.len())
&& primary.bytes().all(|byte| byte.is_ascii_lowercase())
}) && parts.all(|part| {
(2..=8).contains(&part.len()) && part.bytes().all(|byte| byte.is_ascii_alphanumeric())
})
};
let tags = options
.values()
.filter_map(JsValue::as_object)
.flat_map(|table| table.values().filter_map(JsValue::as_str))
.filter(is_tag);
candidates::at_most_one_distinct(tags, "page language").ok()?
}
#[cfg(test)]
mod tests {
use super::*;
const PAGE: &str = r#"<html><body><script nonce="n">(function(){window._cf_chl_opt = {cH: 'token', cRay: 'ray', cUPMDTk: "/protected?__cf_chl_tk=answered"};var a = document.createElement('script');a.src = '/cdn-cgi/challenge-platform/h/b/orchestrate/chl_page/v1?ray=ray';if (window.history && window.history.replaceState) {history.replaceState(null, null,"/protected?__cf_chl_rt_tk=loading"+ window._cf_chl_opt.cOgUHash);}document.getElementsByTagName('head')[0].appendChild(a);}());</script></body></html>"#;
#[test]
fn finds_the_orchestrator_and_the_loading_address() {
let url = Url::parse("https://example.com/protected").unwrap();
let page = ChallengePage::parse(PAGE, &url).unwrap().unwrap();
assert_eq!(
page.orchestrator.as_str(),
"https://example.com/cdn-cgi/challenge-platform/h/b/orchestrate/chl_page/v1?ray=ray"
);
assert_eq!(
page.loading.as_str(),
"https://example.com/protected?__cf_chl_rt_tk=loading"
);
assert_eq!(
page.answered.unwrap().as_str(),
"https://example.com/protected?__cf_chl_tk=answered"
);
let widget = r#"<script>window._cf_chl_opt = {}; render();</script>"#;
for html in [widget, "<p>no script</p>"] {
assert!(
ChallengePage::parse(html, &url).unwrap().is_none(),
"{html}"
);
}
}
}
+344
View File
@@ -0,0 +1,344 @@
//! Builds the plaintext first challenge payload by evaluating the template's field expressions
//! against session options and the script's namespace.
use anyhow::{Context, Result, ensure};
use swc_core::ecma::ast::{BinaryOp, Expr};
use swc_core::ecma::codegen;
use crate::challenge::expression;
use crate::challenge::state::{Difference, ScriptState};
use crate::js::{JsValue, Options, Payload, Window, ast, json};
use crate::random_id;
/// The global selector log serialized in the payload. Starts empty.
#[must_use]
pub(crate) fn selector_log(fields: &[Field]) -> Option<String> {
fields.iter().find_map(|field| match field.global()? {
(name, Shape::Stringified) => Some(name.to_owned()),
_ => None,
})
}
/// Supplies globals read by payload fields. Uses values installed by the initial program when
/// available; otherwise infers the value from the expression. Getter calls read options,
/// stringified reads report arrays, and plain reads report the interaction tally or a per-load
/// identifier.
#[must_use]
pub(crate) fn infer_globals(
fields: &[Field],
script: &ScriptState,
options: &Options,
installed: &Window,
) -> Window {
let mut globals = Window::new();
for field in fields {
let Some((name, shape)) = field.global() else {
continue;
};
let value = match (installed.get(name), shape) {
(Some(value), _) => value.clone(),
// Initialize the getter from its option, which is empty until the script writes it.
(None, Shape::Called) => script
.getters
.get(name)
.and_then(|option| options.get(option))
.cloned()
.unwrap_or_else(|| json!([])),
// No interaction has been recorded, so the collection is empty.
(None, Shape::Stringified) => json!([]),
(None, Shape::Read) => match &script.counters {
Some(tally) if tally.global == name => JsValue::Object(
tally
.counters
.iter()
.map(|counter| (counter.clone(), json!(0)))
.collect(),
),
// Generate a per-load identifier with the same format as session names.
_ => json!(random_id::random_id(
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
6
)),
},
};
globals.insert(name.to_owned(), value);
}
globals
}
#[derive(Debug, Clone)]
pub struct Field {
pub name: String,
pub expression: Expr,
/// The expression's original source text.
pub text: String,
/// Static value before the session runs, if known.
pub bootstrap_value: Option<JsValue>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Shape {
Read,
Called,
Stringified,
}
impl Field {
/// The namespace property this field reads, if any.
fn global(&self) -> Option<(&str, Shape)> {
fn global(expression: &Expr) -> Option<&str> {
ast::ident_property(expression.as_member()?)
}
match &self.expression {
Expr::Call(call) => match &**call.callee.as_expr()? {
Expr::Member(member) if ast::is_method_of(member, "JSON", "stringify") => {
Some((global(&call.args.first()?.expr)?, Shape::Stringified))
}
callee => Some((global(callee)?, Shape::Called)),
},
expression => Some((global(expression)?, Shape::Read)),
}
}
}
/// Finds option pairs whose time difference appears in the payload.
#[must_use]
pub(crate) fn differences(fields: &[Field]) -> Vec<Difference> {
fields
.iter()
.filter_map(|field| match &field.expression {
Expr::Bin(binary) if binary.op == BinaryOp::Sub => Some(Difference {
later: expression::option_key(&binary.left)?.to_owned(),
earlier: expression::option_key(&binary.right)?.to_owned(),
}),
_ => None,
})
.collect()
}
/// Evaluates fields against session options, omitting `undefined` values as `JSON.stringify`
/// does.
pub(crate) fn build(fields: &[Field], options: &Options, globals: &Window) -> Result<Payload> {
let mut payload = Payload::new();
for field in fields {
let value =
expression::evaluate(&field.expression, options, globals).with_context(|| {
format!(
"evaluating payload field {}: {}",
field.name,
codegen::to_code(&field.expression)
)
})?;
if let Some(value) = value {
payload.insert(field.name.clone(), value);
}
}
ensure!(!payload.is_empty(), "no payload field could be evaluated");
Ok(payload)
}
/// Appends the sender's fields in the script's insertion order, which `JSON.stringify` keeps:
/// collected resource timings (if any), payload duration, then forwarded options.
pub(crate) fn append_send_time(
payload: &mut Payload,
script: &ScriptState,
options: &Options,
resources: &[JsValue],
elapsed: i64,
) {
if let Some(timing) = &script.timing
&& !resources.is_empty()
{
payload.insert(timing.option.clone(), json!(resources));
}
if let Some(sender) = &script.elapsed {
payload.insert(sender.key.clone(), json!(elapsed));
}
for key in &script.forwarded {
if let Some(value) = options.get(key) {
payload.insert(key.clone(), value.clone());
}
}
}
/// Appends send-time fields without resource timings. Measures duration from the start mark to
/// `send_at`; see [`append_send_time`].
pub(crate) fn append_send_time_at(
payload: &mut Payload,
script: &ScriptState,
options: &Options,
send_at: i64,
) {
let elapsed = script
.elapsed
.as_ref()
.and_then(|sender| options.get(&sender.mark)?.as_i64())
.map_or(0, |mark| send_at - mark);
append_send_time(payload, script, options, &[], elapsed);
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use super::*;
use crate::challenge::reduced_timing::ResourceTiming;
use crate::challenge::state::Elapsed;
use crate::challenge::tally::Tally;
fn field(name: &str, text: &str) -> Field {
Field {
name: name.into(),
expression: ast::parse_expression("t", text).unwrap(),
text: text.into(),
bootstrap_value: None,
}
}
/// Checks JavaScript evaluation and omission of `undefined` fields during JSON
/// serialization.
#[test]
fn evaluates_fields_with_javascript_semantics() {
let options = Options::from_iter([
("a".to_owned(), json!(1)),
("b".to_owned(), json!(5)),
("o".to_owned(), json!({})),
]);
// Each field as `JSON.stringify` writes it, or `None` when it leaves it out.
let cases = [
("e._cf_chl_opt.a", Some("1")),
("e._cf_chl_opt.missing", None),
("(e._cf_chl_opt.missing || {}).x", None),
("undefined", None),
("JSON.stringify(e.missing)", None),
("null", Some("null")),
("[undefined, null, e.missing]", Some("[null,null,null]")),
(
"({a: undefined, b: null, c: x(), d: 1})",
Some(r#"{"b":null,"d":1}"#),
),
("JSON.stringify(null)", Some(r#""null""#)),
(
"JSON.stringify({b: 1, a: 2.5})",
Some(r#""{\"b\":1,\"a\":2.5}""#),
),
("!undefined", Some("true")),
("![]", Some("false")),
("null || 3", Some("3")),
("[] || x()", Some("[]")),
("true + null", Some("1")),
("[1, null, 2] + {}", Some(r#""1,,2[object Object]""#)),
("undefined + 'x'", Some(r#""undefinedx""#)),
("1 === 1.0", Some("true")),
("1 === '1'", Some("false")),
("null === undefined", Some("false")),
("null !== undefined", Some("true")),
("undefined === {}", Some("false")),
("[] === undefined", Some("false")),
("({}) === null", Some("false")),
// Sessions send `!(_cf_chl_opt.<flag> !== 1)`, which is `false`
// rather than absent when the flag was never set.
("!(e._cf_chl_opt.missing !== 1)", Some("false")),
("!(e._cf_chl_opt.a !== 1)", Some("true")),
("e._cf_chl_opt.missing === undefined", Some("true")),
// `+` and `-` coerce as JavaScript does; `NaN` serialises as `null`.
("e._cf_chl_opt.b - e._cf_chl_opt.a", Some("4")),
("e._cf_chl_opt.a + 1", Some("2")),
("'x' + e._cf_chl_opt.a", Some(r#""x1""#)),
("e._cf_chl_opt.o - 1", Some("null")),
("e._cf_chl_opt.a - e._cf_chl_opt.missing", Some("null")),
// The right-hand side is never reached when the left is truthy.
("e._cf_chl_opt.a || x()", Some("1")),
];
let fields: Vec<_> = cases.iter().map(|(text, _)| field(text, text)).collect();
let built = build(&fields, &options, &Window::new()).unwrap();
for (text, expected) in cases {
let sent = built.get(text).and_then(JsValue::stringify);
assert_eq!(sent.as_deref(), expected, "{text}");
}
}
#[test]
fn unsupported_expressions_fail_naming_their_field() {
let options = Options::from_iter([("a".to_owned(), json!(1)), ("o".to_owned(), json!({}))]);
for (text, reason) in [
("e._cf_chl_opt.a * 2", "unsupported operator *"),
("!foo()", "unsupported call"),
("e._cf_chl_opt.missing.x", "reads x of undefined"),
("e._cf_chl_opt.o === e._cf_chl_opt.o", "identity comparison"),
("bare", "unsupported expression"),
("[1,,2]", "unsupported array hole"),
("[...[]]", "unsupported spread element"),
("JSON.stringify()", "unsupported JSON.stringify arguments"),
("JSON.stringify(...[])", "unsupported spread argument"),
("(JSON.stringify)(null)", "unsupported call"),
("null.x", "unsupported read of x from null"),
("[] === {}", "identity comparison"),
("[] !== []", "identity comparison"),
("`${e._cf_chl_opt.a}`", "unsupported template"),
// Short-circuiting reaches the right-hand side here.
("e._cf_chl_opt.missing || x()", "unsupported call"),
] {
let fields = vec![field("ok", "1"), field("bad", text)];
let error = build(&fields, &options, &Window::new()).unwrap_err();
let error = format!("{error:#}");
assert!(error.contains("payload field bad"), "{text}: {error}");
assert!(error.contains(reason), "{text}: {error}");
}
}
#[test]
fn infers_globals_from_the_window_the_analysis_and_their_shape() {
let fields = vec![
field("id", "e.unknown"),
field("tally", "e.tally"),
field("called", "e.getter()"),
field("selectors", "JSON.stringify(e.log)"),
];
let script = ScriptState {
counters: Some(Tally {
global: "tally".into(),
counters: vec!["a".into()],
}),
getters: BTreeMap::from([("getter".into(), "opt".into())]),
..ScriptState::default()
};
let options = Options::from_iter([("opt".to_owned(), json!(["x"]))]);
let installed = Window::from_iter([("unknown".to_owned(), json!("loadId"))]);
let globals = infer_globals(&fields, &script, &options, &installed);
assert_eq!(
JsValue::from(globals),
json!({"unknown": "loadId", "tally": {"a": 0}, "getter": ["x"], "log": []})
);
let guessed = infer_globals(&fields, &script, &options, &Window::new());
assert_eq!(
guessed["unknown"].as_str().unwrap().len(),
6,
"a guess draws an identifier for the unknown read"
);
assert_eq!(guessed["getter"], json!(["x"]));
}
/// The builder attaches the timings before the sender adds its own keys.
#[test]
fn appends_timings_before_the_senders_keys() {
let script = ScriptState {
elapsed: Some(Elapsed {
key: "elapsed".into(),
mark: "mark".into(),
}),
forwarded: vec!["forwarded".into()],
timing: Some(ResourceTiming {
option: "timings".into(),
fields: Vec::new(),
}),
..ScriptState::default()
};
let options = Options::from_iter([("forwarded".to_owned(), json!("x"))]);
let mut payload = Payload::from_iter([("literal".to_owned(), json!(1))]);
append_send_time(&mut payload, &script, &options, &[json!({})], 5);
let keys: Vec<_> = payload.keys().cloned().collect();
assert_eq!(keys, ["literal", "timings", "elapsed", "forwarded"]);
}
}
+512
View File
@@ -0,0 +1,512 @@
//! Extracts a session's encoding constants and payload template without relying on randomized
//! names. The encoding algorithms are implemented in `crate::challenge::codec`.
use std::collections::{BTreeMap, BTreeSet};
use std::ops::RangeInclusive;
use anyhow::{Context, Result};
use base64::engine::general_purpose::STANDARD;
use num_bigint::BigUint;
use serde::Serialize;
use swc_core::ecma::ast::{
ArrowExpr, AssignExpr, AssignTarget, BlockStmt, CallExpr, Callee, Decl, Expr, Function, IfStmt,
ObjectLit, SimpleAssignTarget, Stmt,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use url::Url;
use crate::challenge::codec::{Codec, KEY_LENGTH, SEED_LENGTH};
use crate::challenge::expression;
use crate::challenge::installed::{self, Installed};
use crate::challenge::merge::Mapping;
use crate::challenge::payload::Field;
use crate::challenge::source::{self, InitialRequest};
use crate::challenge::state::ScriptState;
use crate::js::ast::{self, ParsedScript};
use crate::js::{JsValue, Options, Payload};
use crate::script::Source;
use crate::{candidates, vm};
/// The session's base64 alphabet: 64 distinct characters, optionally followed by the padding
/// character.
const ALPHABET_LENGTH: RangeInclusive<usize> = 64..=65;
/// One session's encoding parameters and payload template. The string fields keep the original
/// JavaScript for `encoder.json`; encoding uses validated encoding parameters.
#[derive(Clone)]
pub struct ExtractedProgram {
pub request: InitialRequest,
/// Iframe URL used to resolve the POST URL.
pub iframe_url: Url,
/// The function whose result is handed to `send`.
pub encoder: String,
/// The one function the encoder calls that the VM defines at runtime.
pub key_transform: String,
/// The runner call that initialises the VM key material with a literal program.
pub initialize_key: String,
pub installed: Installed,
/// The encoder's IIFE with its browser-facing statements removed.
pub bootstrap: String,
pub(crate) codec: Codec,
/// The payload template's fields, in the order the session writes them.
pub payload_fields: Vec<Field>,
}
impl ExtractedProgram {
/// Creates a session encoder with a fresh random seed.
pub fn session_encoder(&self) -> Result<SessionEncoder> {
let mut seed = [0; SEED_LENGTH];
getrandom::fill(&mut seed).context("drawing the session key seed")?;
Ok(self.session_encoder_with_seed(seed))
}
#[must_use]
pub fn session_encoder_with_seed(&self, seed: [u8; SEED_LENGTH]) -> SessionEncoder {
SessionEncoder {
codec: self.codec.clone(),
seed,
}
}
#[must_use]
pub fn encoder_json(&self) -> EncoderJson<'_> {
let payload_fields = self.payload_fields.iter().map(|field| ExportedField {
name: &field.name,
expression: &field.text,
bootstrap_value: field.bootstrap_value.as_ref(),
});
EncoderJson {
url: self.request.url.as_str(),
iframe_url: self.iframe_url.as_str(),
cf_chl: &self.request.cf_chl,
options: &self.request.options,
encoder: &self.encoder,
key_transform: &self.key_transform,
key_secret: self.codec.secret.iter().copied().map(char::from).collect(),
initialize_key: &self.initialize_key,
bootstrap: &self.bootstrap,
alphabet: &self.codec.alphabet_text,
modulus: self.codec.modulus.to_str_radix(16),
payload_fields: payload_fields.collect(),
}
}
}
/// `encoder.json`: the encoding constants under stable keys, with payload expressions as source
/// text.
#[derive(Serialize)]
pub struct EncoderJson<'program> {
pub url: &'program str,
pub iframe_url: &'program str,
pub cf_chl: &'program str,
pub options: &'program Options,
pub encoder: &'program str,
pub key_transform: &'program str,
pub key_secret: String,
pub initialize_key: &'program str,
pub bootstrap: &'program str,
pub alphabet: &'program str,
pub modulus: String,
pub payload_fields: Vec<ExportedField<'program>>,
}
/// A payload template field in `encoder.json`, with its expression as source text.
#[derive(Serialize)]
pub struct ExportedField<'program> {
pub name: &'program str,
pub expression: &'program str,
#[serde(skip_serializing_if = "Option::is_none")]
pub bootstrap_value: Option<&'program JsValue>,
}
/// An extracted program and its parsed source. Parameter merging and iframe state are recovered
/// from the source on demand.
pub struct PreparedSession<'source> {
parsed: &'source ParsedScript,
program: ExtractedProgram,
}
impl<'source> PreparedSession<'source> {
/// Extracts the program from `source` fetched at `iframe_url`. Missing or ambiguous
/// components are errors.
pub fn try_new(source: &'source Source, iframe_url: &Url) -> Result<Self> {
use base64::Engine;
let parsed = source.parsed();
let request = InitialRequest::from_parsed(parsed, iframe_url)?;
let runner =
vm::runner_name(&parsed.script).context("the script installs no program runner")?;
let mut components = Components {
parsed,
options: &request.options,
runner,
encoders: BTreeSet::new(),
programs: BTreeMap::new(),
templates: Vec::new(),
};
parsed.script.visit_with(&mut components);
let encoder = candidates::exactly_one(components.encoders, "XHR body encoder")?;
let (initial_program, initialize_key) =
candidates::exactly_one(components.programs, "literal initial VM program")?;
let payload_fields =
candidates::exactly_one(components.templates, "first payload template")?;
// The encoder assignment may be a standalone statement or part of a sequence or chain.
// Search within IIFE statements without entering their nested functions.
let mut root = EncoderRoot {
parsed,
encoder: &encoder,
found: None,
};
parsed.script.visit_with(&mut root);
let root = root
.found
.context("could not locate encoder's enclosing IIFE")??;
let initial_program = STANDARD
.decode(initial_program.trim())
.context("decoding the initial VM program")?;
// The program installs the key transform as `window[name] = factory(secret)`.
let installed = installed::read(source, &initial_program)?;
let secret = installed.built.get(&root.key_transform).with_context(|| {
format!(
"the initial VM program does not build the key transform {}",
root.key_transform
)
})?;
// The transform reads the secret with `charCodeAt`, one byte each.
let bytes: Option<Vec<u8>> = secret
.chars()
.map(|character| u8::try_from(character).ok())
.collect();
let secret: [u8; KEY_LENGTH] = bytes
.and_then(|bytes| bytes.try_into().ok())
.with_context(|| format!("the key transform's secret is not {KEY_LENGTH} bytes"))?;
let program = ExtractedProgram {
request,
iframe_url: iframe_url.clone(),
encoder,
key_transform: root.key_transform,
initialize_key,
installed,
bootstrap: root.bootstrap,
codec: Codec::try_new(&root.alphabet, root.modulus, secret)?,
payload_fields,
};
Ok(Self { parsed, program })
}
#[must_use]
pub fn program(&self) -> &ExtractedProgram {
&self.program
}
#[must_use]
pub fn into_program(self) -> ExtractedProgram {
self.program
}
/// How this session merges the embedding page's `extraParams`.
pub fn mapping(&self) -> Result<Mapping> {
Mapping::from_parsed(self.parsed)
}
pub fn state(&self) -> Result<ScriptState> {
ScriptState::from_parsed(self.parsed, &self.program.request.options)
}
}
/// State contributed by the encoder's enclosing IIFE.
struct Root {
key_transform: String,
alphabet: String,
modulus: BigUint,
bootstrap: String,
}
impl Root {
fn read(root: &BlockStmt, definition: &Expr, parsed: &ParsedScript) -> Result<Self> {
Ok(Self {
key_transform: key_transform(root, definition)?,
alphabet: base64_alphabet(root)?,
modulus: rsa_modulus(root)?,
bootstrap: bootstrap(root, parsed),
})
}
}
/// Finds the outermost immediately invoked function that defines the encoder. Calls `read`
/// while the borrowed syntax node is valid.
struct EncoderRoot<'session> {
parsed: &'session ParsedScript,
encoder: &'session str,
found: Option<Result<Root>>,
}
impl Visit for EncoderRoot<'_> {
fn visit_call_expr(&mut self, call: &CallExpr) {
if self.found.is_some() {
return;
}
if let Callee::Expr(callee) = &call.callee
&& let Expr::Fn(function) = callee.unwrap_parens()
&& let Some(body) = &function.function.body
&& let Some(definition) = body
.stmts
.iter()
.find_map(|statement| defines(statement, self.encoder))
{
self.found = Some(Root::read(body, &definition, self.parsed));
return;
}
call.visit_children_with(self);
}
}
/// Finds the encoder's one callee not declared by the IIFE, which the VM creates at runtime.
fn key_transform(root: &BlockStmt, definition: &Expr) -> Result<String> {
let mut calls = Calls::default();
definition.visit_with(&mut calls);
let declared = |name: &str| {
root.stmts.iter().any(|statement| {
matches!(statement, Stmt::Decl(Decl::Fn(function)) if function.ident.sym == name)
})
};
let undeclared = calls
.0
.iter()
.filter(|name| *name != "Number" && !declared(name));
candidates::exactly_one(undeclared, "VM-defined key transform").cloned()
}
/// Finds the session alphabet among the string literals in `node`, whether bound once or
/// repeated at each use.
pub(crate) fn base64_alphabet(node: &impl VisitWith<ast::StringLiterals>) -> Result<String> {
let alphabets = ast::string_literals(node).into_iter().filter(|candidate| {
if !candidate.is_ascii() || !ALPHABET_LENGTH.contains(&candidate.len()) {
return false;
}
let distinct: BTreeSet<&u8> = candidate.as_bytes()[..64].iter().collect();
distinct.len() == 64
});
let mut alphabet = candidates::exactly_one(alphabets, "custom base64 alphabet")?;
alphabet.truncate(64);
Ok(alphabet)
}
/// Finds the `BigInt("0x...")` modulus wide enough to encrypt the seed.
fn rsa_modulus(root: &BlockStmt) -> Result<BigUint> {
let moduli = expression::assignments(root)
.filter_map(|assignment| big_int(&assignment.right))
.filter_map(|literal| BigUint::parse_bytes(literal.strip_prefix("0x")?.as_bytes(), 16))
.filter(|modulus| modulus.bits().div_ceil(8) == SEED_LENGTH as u64);
candidates::exactly_one(moduli, "RSA modulus")
}
/// The string `BigInt` is called with.
fn big_int(expression: &Expr) -> Option<&str> {
let (name, arguments) = ast::direct_call(expression)?;
ast::static_str(&arguments.first()?.expr).filter(|_| name.sym == "BigInt")
}
/// Returns source for the IIFE without browser activity. Keeps VM tables, declarations, key
/// generation, and the encoder. Removes startup calls, timers, UI code, and event collection.
fn bootstrap(root: &BlockStmt, parsed: &ParsedScript) -> String {
let inert: Vec<&str> = root
.stmts
.iter()
.filter(|statement| is_inert(statement))
.map(|statement| parsed.text(statement))
.collect();
inert.join("\n")
}
/// Whether a top-level statement can run without starting browser work.
fn is_inert(statement: &Stmt) -> bool {
match statement {
// A conditional that only installs functions does not run their bodies.
Stmt::If(conditional) => conditional.cons.as_block().is_some_and(|block| {
block.stmts.iter().all(|statement| {
expression::assignment(statement)
.is_some_and(|assigned| matches!(&*assigned.right, Expr::Fn(_)))
})
}),
// A property assignment from a call publishes browser work that must be skipped.
// Indexed writes such as `seed[0] = Number(two)` update encoder state and are allowed.
Stmt::Expr(statement) => !matches!(&*statement.expr, Expr::Assign(assignment)
if matches!(&assignment.left, AssignTarget::Simple(SimpleAssignTarget::Member(member))
if !member.prop.is_computed())
&& matches!(&*assignment.right, Expr::Call(_))),
_ => true,
}
}
fn payload_fields(template: &ObjectLit, parsed: &ParsedScript, options: &Options) -> Vec<Field> {
ast::key_values(template)
.filter_map(|property| {
Some(Field {
name: ast::static_key_str(&property.key)?.to_owned(),
// Reparsing the exported expression removes outer parentheses. Remove them here
// too.
expression: property.value.unwrap_parens().clone(),
text: parsed.text(&*property.value).to_owned(),
bootstrap_value: expression::static_value(&property.value, options),
})
})
.collect()
}
/// Finds the function assigned to `name` within a statement.
fn defines(statement: &Stmt, name: &str) -> Option<Expr> {
let mut definition = Definition { name, found: None };
statement.visit_with(&mut definition);
definition.found
}
struct Definition<'name> {
name: &'name str,
found: Option<Expr>,
}
impl Visit for Definition<'_> {
// A declared function's own body belongs to it, not to the IIFE around it.
fn visit_function(&mut self, _: &Function) {}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
// A sequence evaluates to its final expression. Some sessions reset
// the seed immediately before yielding the encoder function.
let mut value = assignment.right.unwrap_parens();
while let Expr::Seq(sequence) = value {
let Some(last) = sequence.exprs.last() else {
return;
};
value = last.unwrap_parens();
}
if let AssignTarget::Simple(SimpleAssignTarget::Ident(target)) = &assignment.left
&& target.id.sym == *self.name
&& matches!(value, Expr::Fn(_) | Expr::Arrow(_))
{
self.found = Some(value.clone());
}
assignment.visit_children_with(self);
}
}
/// The names called directly, as `name(...)`.
#[derive(Default)]
struct Calls(BTreeSet<String>);
impl Visit for Calls {
fn visit_call_expr(&mut self, call: &CallExpr) {
if let Callee::Expr(callee) = &call.callee
&& let Expr::Ident(name) = &**callee
{
self.0.insert(name.sym.to_string());
}
call.visit_children_with(self);
}
}
/// Collects components for [`PreparedSession::try_new`].
struct Components<'session> {
parsed: &'session ParsedScript,
options: &'session Options,
/// The name the program runner is installed under.
runner: String,
/// Functions whose result is handed straight to `send`.
encoders: BTreeSet<String>,
/// Literal programs passed to the runner, each with the source of its first call.
/// Orchestrators may repeat a program for different startup paths.
programs: BTreeMap<String, String>,
templates: Vec<Vec<Field>>,
}
impl Visit for Components<'_> {
fn visit_call_expr(&mut self, call: &CallExpr) {
if vm::calls_runner(call, &self.runner)
&& let Some(program) = call
.args
.first()
.and_then(|argument| ast::static_str(&argument.expr))
{
let text = self.parsed.text(call).to_owned();
self.programs.entry(program.to_owned()).or_insert(text);
}
if let Callee::Expr(callee) = &call.callee
&& let Expr::Member(member) = callee.unwrap_parens()
&& ast::member_str(&member.prop) == Some("send")
&& let Some(argument) = call.args.first()
&& let Some((encoder, _)) = ast::direct_call(&argument.expr)
{
self.encoders.insert(encoder.sym.to_string());
}
call.visit_children_with(self);
}
fn visit_if_stmt(&mut self, conditional: &IfStmt) {
let options = self.options;
source::visit_taken_branches(self, conditional, options);
}
fn visit_object_lit(&mut self, object: &ObjectLit) {
if source::is_payload_template(object, self.options) {
self.templates
.push(payload_fields(object, self.parsed, self.options));
}
object.visit_children_with(self);
}
}
/// Encoder state shared by all session POSTs. The browser generates one seed; each payload's
/// padding length selects a symmetric key from that seed.
pub struct SessionEncoder {
codec: Codec,
seed: [u8; SEED_LENGTH],
}
impl SessionEncoder {
#[must_use]
pub fn encode(&self, payload: &Payload) -> String {
self.codec.encode(payload, self.seed)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn statement(source: &str) -> Stmt {
ast::parse_javascript("t.js", source)
.unwrap()
.script
.body
.into_iter()
.next()
.unwrap()
}
#[test]
fn finds_the_encoder_however_its_assignment_is_spelled() {
for source in [
"P3 = function(Z) { return Z; };",
// A live session combined these expressions into a sequence.
"Zv = (Ge[0] = 0, P3 = function(Z) { return Z; });",
"Zv = P3 = function(Z) { return Z; };",
"P3 = (Ge[0] = 0, function(Z) { return Z; });",
"P3 = (Ge[0] = 0, (Ge[1] = 1, (Z => Z)));",
] {
assert!(
defines(&statement(source), "P3").is_some(),
"missed the encoder in: {source}"
);
}
assert!(
defines(&statement("function f() { P3 = function() {}; }"), "P3").is_none(),
"a declared function's own body is not the IIFE's, so an assignment inside one must \
not claim the enclosing statement"
);
assert!(defines(&statement("P3 = 1;"), "P3").is_none());
assert!(defines(&statement("P3 = (function() {}, 1);"), "P3").is_none());
}
}
+177
View File
@@ -0,0 +1,177 @@
//! Recovers the format the iframe uses to summarize resource timings, then converts this
//! client's fetch measurements to that format.
use swc_core::ecma::ast::{AssignTarget, BinaryOp, BlockStmt, Expr, SimpleAssignTarget};
use crate::challenge::expression::{self, BuiltObject, ObjectField};
use crate::js::{JsObject, JsValue, ast, json};
use crate::resource_timing::{LoadTiming, Phases, ResourceMeasurement};
/// The resource timing property represented by an output field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Measure {
Name,
/// `responseEnd - responseStart`.
Response,
/// `responseStart - requestStart`.
Request,
Duration,
Transfer,
Body,
}
/// Maps collected resource timings to the six fields sent under the collection's option name.
#[derive(Debug, Clone)]
pub struct ResourceTiming {
/// The option the session collects its entries under.
pub option: String,
/// Output keys and their measurements, in insertion order.
pub fields: Vec<(String, Measure)>,
}
impl ResourceTiming {
/// Reduces a measured fetch to the session's resource timing format.
#[must_use]
pub(crate) fn reduce(&self, url: &str, measured: &ResourceMeasurement) -> JsValue {
let mut entry = JsObject::new();
for (name, measure) in &self.fields {
let value = match measure {
Measure::Name => json!(url),
Measure::Response => json!(measured.response.floor()),
Measure::Request => json!(measured.request.floor()),
Measure::Duration => json!(measured.duration.floor()),
Measure::Transfer => json!(measured.transfer_size),
Measure::Body => json!(measured.body_size),
};
entry.insert(name.clone(), value);
}
JsValue::Object(entry)
}
/// Reduces `load` using its measured phases.
#[must_use]
pub(crate) fn entry(&self, load: &LoadTiming) -> JsValue {
self.reduce(&load.url, &load.measurement())
}
/// Splits the session's total document load time into the navigation's `phases`.
#[must_use]
pub(crate) fn navigation(
&self,
url: &str,
duration: f64,
bytes: u64,
phases: Phases,
) -> JsValue {
self.reduce(
url,
&ResourceMeasurement::estimated(duration, bytes, phases),
)
}
}
/// Finds the first resource summary object in `body`, using the resource name and locals
/// holding floored measurements.
pub(super) fn reduction(body: &BlockStmt) -> Option<Vec<(String, Measure)>> {
let mut measured: Vec<(&str, Measure)> = Vec::new();
let mut built: Vec<BuiltObject> = Vec::new();
for assignment in expression::assignments(body) {
if let AssignTarget::Simple(SimpleAssignTarget::Ident(local)) = &assignment.left
&& let Some(measure) = floored(&assignment.right)
{
measured.push((&local.id.sym, measure));
} else {
expression::track(&mut built, assignment);
}
}
built
.iter()
.find_map(|object| reduced_fields(&object.fields, &measured))
}
/// Recognizes a reduced entry when it has enough fields, includes the resource name, and uses
/// only the name or `measured` locals.
fn reduced_fields(
fields: &[ObjectField<'_>],
measured: &[(&str, Measure)],
) -> Option<Vec<(String, Measure)>> {
let mut reduced = Vec::with_capacity(fields.len());
for field in fields {
let measure = match field.value {
Expr::Member(member) if ast::member_str(&member.prop) == Some("name") => Measure::Name,
Expr::Ident(ident) => {
let (_, measure) = measured.iter().rfind(|(local, _)| *local == &*ident.sym)?;
*measure
}
_ => return None,
};
reduced.push((field.key.to_owned(), measure));
}
let names_the_resource = reduced.iter().any(|(_, measure)| *measure == Measure::Name);
(names_the_resource && reduced.len() >= 4).then_some(reduced)
}
/// `Math.floor(entry.a - entry.b)` or `Math.floor(entry.a)`.
fn floored(expression: &Expr) -> Option<Measure> {
let call = expression.as_call()?;
let member = call.callee.as_expr()?.as_member()?;
if !ast::is_method_of(member, "Math", "floor") {
return None;
}
fn attribute(expression: &Expr) -> Option<&str> {
ast::ident_property(expression.as_member()?)
}
match &*call.args.first()?.expr {
Expr::Bin(binary) if binary.op == BinaryOp::Sub => {
match (attribute(&binary.left)?, attribute(&binary.right)?) {
("responseEnd", "responseStart") => Some(Measure::Response),
("responseStart", "requestStart") => Some(Measure::Request),
_ => None,
}
}
single => match attribute(single)? {
"duration" => Some(Measure::Duration),
"transferSize" => Some(Measure::Transfer),
"encodedBodySize" => Some(Measure::Body),
_ => None,
},
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Uses a 137 ms navigation that iOS Safari reported as 124 ms receiving the response and
/// zero time waiting for it.
#[test]
fn navigations_split_into_the_browsers_phases() {
let timing = ResourceTiming {
option: "t".into(),
fields: vec![
("n".into(), Measure::Name),
("r".into(), Measure::Response),
("q".into(), Measure::Request),
("d".into(), Measure::Duration),
("t".into(), Measure::Transfer),
("b".into(), Measure::Body),
],
};
let webkit = Phases {
request: 0.0,
response: 0.9,
};
assert_eq!(
timing.navigation("u", 137.0, 1, webkit),
json!({"n": "u", "r": 123.0, "q": 0.0, "d": 137.0, "t": 301, "b": 1})
);
let chromium = Phases {
request: 0.07,
response: 0.04,
};
assert_eq!(
timing.navigation("u", 137.0, 1, chromium),
json!({"n": "u", "r": 5.0, "q": 9.0, "d": 137.0, "t": 301, "b": 1})
);
}
}
+482
View File
@@ -0,0 +1,482 @@
//! Extracts session parameters from syntax and usage without relying on randomized names.
use std::collections::BTreeSet;
use anyhow::{Context, Result, ensure};
use scraper::{Html, Selector};
use swc_core::ecma::ast::{
AssignExpr, AssignOp, AssignTarget, BinExpr, BinaryOp, CallExpr, Callee, Expr, Function,
IfStmt, Lit, ObjectLit, SimpleAssignTarget, UnaryExpr, UnaryOp,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use url::Url;
use crate::candidates;
use crate::challenge::expression;
use crate::js::ast::{self, ParsedScript};
use crate::js::{JsValue, Options};
use crate::script::Source;
/// Minimum property count distinguishing a payload template from an ordinary options object.
const PAYLOAD_FIELDS: usize = 20;
/// Stable prefix of the initial challenge type: `chl_api_m` for managed widgets or `chl_api_ni`
/// for non-interactive widgets. The containing option name varies by session.
const INITIAL_CHALLENGE: &str = "chl_api_";
/// Challenge types used by page orchestrators. Count these only when no option has an iframe's
/// `chl_api_` type. A page may require interaction but cannot be invisible.
const PAGE_CHALLENGES: [&str; 3] = ["managed", "non-interactive", "interactive"];
/// Turnstile iframe modes echoed by the embedding page's summary.
const WIDGET_MODES: [&str; 3] = ["managed", "non-interactive", "invisible"];
/// The request carrying the session's first payload, as its bootstrap script builds it.
#[derive(Debug, Clone)]
pub struct InitialRequest {
pub url: Url,
/// The token the POST carries in its `cf-chl` header.
pub cf_chl: String,
/// The `_cf_chl_opt` object the bootstrap installs.
pub options: Options,
}
impl InitialRequest {
pub fn ray(&self) -> Result<&str> {
ray(&self.url)
}
#[cfg(test)]
pub(crate) fn from_javascript(source: &str, iframe_url: &Url) -> Result<Self> {
Self::from_parsed(&ast::parse_iframe_javascript(source)?, iframe_url)
}
pub(crate) fn from_parsed(parsed: &ParsedScript, iframe_url: &Url) -> Result<Self> {
let options = bootstrap_options(parsed);
ensure!(!options.is_empty(), "missing _cf_chl_opt object");
let mut request = Request {
options: &options,
paths: BTreeSet::new(),
tokens: BTreeSet::new(),
};
parsed.script.visit_with(&mut request);
let token = candidates::exactly_one(request.tokens, "cf-chl token")?;
let path = candidates::exactly_one(
request
.paths
.into_iter()
.filter(|path| path.rsplit('/').next() == Some(token.as_str())),
"initial /fo/ URL matching cf-chl",
)?;
let url = iframe_url.join(&path)?;
ensure!(
url.origin() == iframe_url.origin(),
"POST URL changed origin"
);
Ok(Self {
url,
cf_chl: token,
options,
})
}
}
/// Whether `path` is a challenge-platform `/fo/` path, where challenge payloads are posted.
#[must_use]
pub fn is_post_path(path: &str) -> bool {
path.starts_with("/cdn-cgi/challenge-platform/") && path.contains("/fo/")
}
/// The ray a challenge POST `url` carries after `/fo/<id>/`.
pub fn ray(url: &Url) -> Result<&str> {
url.path()
.split("/fo/")
.nth(1)
.and_then(|path| path.split('/').nth(1))
.context("the challenge URL carries no ray")
}
/// Reads bootstrap `_cf_chl_opt` values and later static assignments. Returns an empty map if
/// the script installs no options.
#[must_use]
pub(crate) fn bootstrap_options(parsed: &ParsedScript) -> Options {
let mut options = StaticOptions::default();
parsed.script.visit_with(&mut options);
let mut renames = Renames::default();
parsed.script.visit_with(&mut renames);
let StaticOptions(mut options) = options;
for (to, from) in renames.copies {
if renames.deleted.contains(&from)
&& !options.contains_key(&to)
&& let Some(value) = options.shift_remove(&from)
{
options.insert(to, value);
}
}
options
}
/// The mode this session's widget runs in (see [`WIDGET_MODES`]). Its option
/// name is randomised, but its value is not.
#[must_use]
pub(crate) fn mode(options: &Options) -> Option<&str> {
options
.values()
.filter_map(JsValue::as_str)
.find(|value| WIDGET_MODES.contains(value))
}
/// Reads the `api.js` build, padded to twelve hex digits, that this session requires. If it
/// differs from the loader's `ch`, the iframe saves the parameters and asks the page to reload
/// `api.js`. Conflicting candidates produce no build.
#[must_use]
pub(crate) fn expected_build(source: &Source) -> Option<String> {
#[derive(Default)]
struct Builds(Vec<String>);
impl Visit for Builds {
fn visit_bin_expr(&mut self, binary: &BinExpr) {
if let Some(build) = expression::padded_build(binary).filter(|build| build.len() == 12)
{
self.0.push(build);
}
binary.visit_children_with(self);
}
}
let mut builds = Builds::default();
source.parsed().script.visit_with(&mut builds);
candidates::at_most_one_distinct(builds.0, "loader build").ok()?
}
/// Identifies a payload template by its size and a field that reads the initial challenge type
/// option.
#[must_use]
pub(crate) fn is_payload_template(object: &ObjectLit, options: &Options) -> bool {
let challenge = |value: &str| value.starts_with(INITIAL_CHALLENGE);
let in_iframe = options
.values()
.any(|value| value.as_str().is_some_and(challenge));
// The string values of the options the fields read.
let mut read = ast::key_values(object).filter_map(|property| {
let member = property.value.as_member()?;
options.get(ast::member_str(&member.prop)?)?.as_str()
});
object.props.len() > PAYLOAD_FIELDS
&& read.any(|value| challenge(value) || !in_iframe && PAGE_CHALLENGES.contains(&value))
}
/// Visits branches using known option values. For a condition guarded by an unset option,
/// visits only `else`; otherwise visits both branches. This skips an unused second payload
/// template in page orchestrators.
pub(crate) fn visit_taken_branches<V: Visit>(
visitor: &mut V,
conditional: &IfStmt,
options: &Options,
) {
if expression::option_key(conditional.test.unwrap_parens())
.is_some_and(|option| !options.contains_key(option))
{
conditional.alt.visit_with(visitor);
} else {
conditional.visit_children_with(visitor);
}
}
/// Follows option renaming during orchestrator startup. Recognizes copies of
/// `_cf_chl_opt.<old>` to `_cf_chl_opt.<new>`, optionally with an `override ||` fallback.
/// Counts a copy as a rename only if the script also deletes the old option.
#[derive(Default)]
struct Renames {
/// `(to, from)` pairs.
copies: Vec<(String, String)>,
deleted: Vec<String>,
}
impl Visit for Renames {
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
let source = match assignment.right.unwrap_parens() {
Expr::Bin(BinExpr {
op: BinaryOp::LogicalOr,
right,
..
}) => right.unwrap_parens(),
other => other,
};
if assignment.op == AssignOp::Assign
&& let Some(to) = expression::option_assignment(&assignment.left)
&& let Some(from) = expression::option_key(source)
{
self.copies.push((to.to_owned(), from.to_owned()));
}
assignment.visit_children_with(self);
}
fn visit_unary_expr(&mut self, unary: &UnaryExpr) {
if unary.op == UnaryOp::Delete
&& let Some(option) = expression::option_key(unary.arg.unwrap_parens())
{
self.deleted.push(option.to_owned());
}
unary.visit_children_with(self);
}
}
/// The options the script assigns statically.
#[derive(Default)]
struct StaticOptions(Options);
impl Visit for StaticOptions {
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
if let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assignment.left {
if ast::member_str(&member.prop) == Some("_cf_chl_opt") {
if let Some(JsValue::Object(options)) =
expression::static_value(&assignment.right, &Options::new())
{
self.0 = Options::from(options);
}
} else if expression::is_options(&member.obj)
&& let (Some(key), Some(value)) = (
ast::member_str(&member.prop),
expression::static_value(&assignment.right, &self.0),
)
{
self.0.insert(key.to_owned(), value);
}
}
assignment.visit_children_with(self);
}
// Only the bootstrap IIFE, entered below, runs now. Other functions mutate the options
// later, and their writes must not overwrite the bootstrap values.
fn visit_function(&mut self, _: &Function) {}
fn visit_call_expr(&mut self, call: &CallExpr) {
if let Callee::Expr(callee) = &call.callee
&& let Expr::Fn(function) = callee.unwrap_parens()
&& let Some(body) = &function.function.body
{
body.visit_with(self);
}
}
}
struct Request<'options> {
options: &'options Options,
paths: BTreeSet<String>,
tokens: BTreeSet<String>,
}
impl Visit for Request<'_> {
fn visit_expr(&mut self, expression: &Expr) {
// Only inspect string concatenations, avoiding evaluation of complete
// function bodies or the encoded VM program.
if matches!(
expression,
Expr::Bin(_) | Expr::Tpl(_) | Expr::Lit(Lit::Str(_))
) && let Some(JsValue::String(path)) = expression::static_value(expression, self.options)
&& is_post_path(&path)
{
self.paths.insert(path);
}
expression.visit_children_with(self);
}
/// Finds arguments to `<request>.setRequestHeader('cf-chl', <token>)`, even when the method
/// name comes from a variable.
fn visit_call_expr(&mut self, call: &CallExpr) {
if let [header, value] = &call.args[..]
&& expression::static_value(&header.expr, self.options)
== Some(JsValue::String("cf-chl".into()))
&& let Some(JsValue::String(token)) =
expression::static_value(&value.expr, self.options)
{
self.tokens.insert(token);
}
call.visit_children_with(self);
}
}
/// Joins inline scripts from challenge `html`. HTML parsing preserves raw script text,
/// including `<` and text resembling entities.
pub fn inline_javascript(html: &str) -> Result<String> {
let document = Html::parse_document(html);
let selector = Selector::parse("script").expect("static selector");
let inline = document.select(&selector).filter(|script| {
let script = script.value();
script.attr("src").is_none()
&& matches!(
script.attr("type").unwrap_or(""),
"" | "text/javascript" | "application/javascript"
)
});
let scripts: Vec<String> = inline.map(|script| script.text().collect()).collect();
let javascript = scripts.join("\n;\n");
ensure!(
javascript.contains("_cf_chl_opt"),
"iframe contains no challenge options; inspect the returned HTML"
);
Ok(javascript)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_session_parameters_with_different_randomized_names() {
for (variant, ray, token) in [("aaa", "bbb", "ccc"), ("Q7", "jJ1", "zyZ")] {
let source = format!(
r#"(function() {{
window._cf_chl_opt = {{ {variant}: 'g', {ray}: 'ray-id', {token}: 'session-token',
callback: function() {{ window._cf_chl_opt.{token} = 'wrong-token'; }}
}};
}})();
~function() {{
function sender(method) {{
method = 'setRequestHeader';
xhr[method]('cf-chl', global._cf_chl_opt['{token}']);
}}
function start() {{
var path = '/cdn-cgi/challenge-platform/h/' + global._cf_chl_opt.{variant}
+ `/fo/build/` + global._cf_chl_opt.{ray} + '/' + global._cf_chl_opt.{token};
}}
}}();"#
);
let base = Url::parse("https://challenges.cloudflare.com/iframe").unwrap();
let request = InitialRequest::from_javascript(&source, &base).unwrap();
assert_eq!(
request.url.path(),
"/cdn-cgi/challenge-platform/h/g/fo/build/ray-id/session-token"
);
assert_eq!(request.cf_chl, "session-token");
assert!(!request.options.contains_key("callback"));
}
}
#[test]
fn finds_payload_template_for_managed_and_non_interactive_widgets() {
let fields: String = (0..PAYLOAD_FIELDS)
.map(|index| format!("f{index}: {index}, "))
.collect();
let template = format!("{{ {fields}kind: b._cf_chl_opt.mode }}");
let Expr::Object(template) = ast::parse_expression("t", &template).unwrap() else {
panic!("not an object");
};
// An iframe uses its `chl_api_` type. A page type is valid only for an orchestrator
// with no `chl_api_` option.
for (challenge, other, expected) in [
("chl_api_m", "x", true),
("chl_api_ni", "x", true),
("managed", "chl_api_m", false),
("managed", "x", true),
("unknown", "x", false),
] {
let options = Options::from_iter([
("mode".to_owned(), JsValue::from(challenge)),
("other".to_owned(), JsValue::from(other)),
]);
assert_eq!(
is_payload_template(&template, &options),
expected,
"{challenge}"
);
}
}
#[test]
fn follows_an_orchestrators_moved_options() {
let source = r#"(function() {
window._cf_chl_opt = { cFPWv: 'b', cH: 'session-token', cRay: 'ray-id', cType: 'managed' };
})();
~function() {
function start() {
global._cf_chl_opt.variant = global.override || global._cf_chl_opt.cFPWv;
delete global._cf_chl_opt.cFPWv;
global._cf_chl_opt.token = global._cf_chl_opt.cH;
delete global._cf_chl_opt.cH;
global._cf_chl_opt.ray = global._cf_chl_opt.cRay;
delete global._cf_chl_opt.cRay;
// A copy whose source stays is not a move.
global._cf_chl_opt.kind = global._cf_chl_opt.cType;
var path = '/cdn-cgi/challenge-platform/h/' + global._cf_chl_opt.variant
+ `/fo/build/` + global._cf_chl_opt.ray + '/' + global._cf_chl_opt.token;
xhr.setRequestHeader('cf-chl', global._cf_chl_opt.token);
}
}();"#;
let base = Url::parse("https://example.com/protected").unwrap();
let request = InitialRequest::from_javascript(source, &base).unwrap();
assert_eq!(
request.url.as_str(),
"https://example.com/cdn-cgi/challenge-platform/h/b/fo/build/ray-id/session-token"
);
assert_eq!(request.cf_chl, "session-token");
assert!(!request.options.contains_key("cH"));
assert_eq!(request.options["cType"], "managed");
assert!(!request.options.contains_key("kind"));
}
#[test]
fn rejects_missing_or_ambiguous_session_instead_of_using_old_values() {
let base = Url::parse("https://challenges.cloudflare.com/iframe").unwrap();
assert!(InitialRequest::from_javascript("window._cf_chl_opt = {};", &base).is_err());
let source = r#"window._cf_chl_opt = {a: 'first', b: 'second'};
xhr.setRequestHeader('cf-chl', window._cf_chl_opt.a);
xhr.setRequestHeader('cf-chl', window._cf_chl_opt.b);"#;
assert!(
InitialRequest::from_javascript(source, &base)
.unwrap_err()
.to_string()
.contains("found 2")
);
}
#[test]
fn reads_the_expected_build_however_its_constant_is_spelled() {
let parse = |source: &str| Source::try_new(source).unwrap();
for source in [
r#"m = ("000000000000" + 0xe694063b5082.toString(16)).slice(-12);"#,
r#"m = ('000000000000'+253523434098818..toString(16)).slice(-12);"#,
r#"m = (`000000000000` + 0XE694063B5082.toString(0x10)).slice(-12);"#,
// The same build twice is no conflict.
r#"m = "000000000000" + 0xe694063b5082.toString(16); n = "000000000000" + 253523434098818..toString(16);"#,
] {
assert_eq!(
expected_build(&parse(source)).as_deref(),
Some("e694063b5082"),
"{source:.80}"
);
}
for source in [
r#"m = "000000000000" + 0xe694063b5082.toString(16); n = "000000000000" + 0x1.toString(16);"#,
// Without the radix the digits would be decimal.
r#"m = "000000000000" + 0xe694063b5082;"#,
r#"m = "000000000000" + 0xe694063b5082.toString(10);"#,
r#"m = "000000000000" + build.toString(16);"#,
// Thirteen digits do not fit the padding.
r#"m = "000000000000" + 0x1e694063b5082.toString(16);"#,
"m = 1;",
] {
assert_eq!(expected_build(&parse(source)), None, "{source}");
}
}
#[test]
fn reads_the_ray_from_the_challenge_url() {
let url = Url::parse(
"https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/g/flow/ov1/0.1:1:abc/fo/session/8f3c2a1b9d4e5f60",
)
.unwrap();
assert_eq!(ray(&url).unwrap(), "8f3c2a1b9d4e5f60");
assert!(ray(&Url::parse("https://challenges.cloudflare.com/no-ray").unwrap()).is_err());
}
#[test]
fn extracts_raw_inline_javascript_without_json_or_external_scripts() {
let source = inline_javascript(
r#"<script src="api.js"></script>
<script type="application/json">{"ignored":true}</script>
<script nonce="x">window._cf_chl_opt = {}; if (1 < 2) x = '&amp;';</script>
<script>another();</script>"#,
)
.unwrap();
assert!(source.contains("if (1 < 2) x = '&amp;'"));
assert!(source.contains("\n;\nanother();"));
assert!(!source.contains("ignored"));
}
}
+397
View File
@@ -0,0 +1,397 @@
//! Recovers the script state the first payload reports: `Date.now()` marks, the interaction
//! tally ([`super::tally`]), the sender's additions, and the resource timing format
//! ([`super::reduced_timing`]).
use std::collections::BTreeMap;
use anyhow::{Result, bail, ensure};
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize};
use swc_core::ecma::ast::{
ArrowExpr, AssignExpr, AssignTarget, BinaryOp, Expr, Function, IfStmt, ObjectLit,
SimpleAssignTarget, Stmt,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use crate::candidates;
use crate::challenge::reduced_timing::{self, ResourceTiming};
use crate::challenge::tally::{self, CounterEvents, Tally};
use crate::challenge::{expression, source};
use crate::js::ast::{self, ParsedScript};
use crate::js::{JsValue, Options};
/// Script state reported in the first payload.
#[derive(Debug, Default)]
pub struct ScriptState {
/// Options assigned `Date.now()`.
pub marks: Vec<Mark>,
pub counters: Option<Tally>,
/// Recovered event mapping for the interaction tally. Keeps any recovery error until
/// interaction code requests the mapping.
pub counter_events: Option<Result<CounterEvents>>,
/// The time the sender reports just before it encodes.
pub elapsed: Option<Elapsed>,
/// Options copied into the payload under their original names at send time.
pub forwarded: Vec<String>,
pub timing: Option<ResourceTiming>,
/// Functions on the script's namespace, mapped to the option each returns.
pub getters: BTreeMap<String, String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Mark {
pub option: String,
/// Whether the assignment is inside the function that builds the payload.
pub in_builder: bool,
}
/// An elapsed-time field appended by the sender before encoding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Elapsed {
pub key: String,
/// The option holding the mark it measures from.
pub mark: String,
}
/// A timestamp pair reported as `later - earlier`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Difference {
pub later: String,
pub earlier: String,
}
/// Durations reported in the first payload, loaded from the fingerprint's `intervals` section.
/// These come from a browser capture.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Intervals {
/// Time between the two startup timestamps.
#[serde(deserialize_with = "unsigned")]
pub initialise: i64,
/// Time between merging the page's parameters and entering the payload builder.
#[serde(deserialize_with = "unsigned")]
pub handoff: i64,
/// Time spent building the payload.
#[serde(deserialize_with = "unsigned")]
pub collect: i64,
/// Time from entering the payload builder to sending, reported by the sender.
#[serde(deserialize_with = "unsigned")]
pub send: i64,
}
/// Widens an unsigned duration for clock arithmetic.
fn unsigned<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
u32::deserialize(deserializer).map(i64::from)
}
impl ScriptState {
#[cfg(test)]
pub(crate) fn from_javascript(javascript: &str) -> Result<Self> {
let parsed = ast::parse_iframe_javascript(javascript)?;
Self::from_parsed(&parsed, &source::bootstrap_options(&parsed))
}
/// Recovers the state of a parsed script, using bootstrap options to identify its payload
/// template.
pub(crate) fn from_parsed(parsed: &ParsedScript, options: &Options) -> Result<Self> {
let script = &parsed.script;
let mut scopes = Scopes {
options,
stack: Vec::new(),
found: Vec::new(),
};
script.visit_with(&mut scopes);
let mut sender = Sender::default();
script.visit_with(&mut sender);
let elapsed = candidates::at_most_one_distinct(sender.elapsed, "elapsed-time field")?;
let sender_scope = elapsed.as_ref().map(|(scope, _)| *scope);
// The sender forwards option values directly. Another function copies collected
// resource timings into the payload.
let (forwarded, collected): (Vec<_>, Vec<_>) = sender
.copies
.into_iter()
.partition(|(scope, _)| Some(*scope) == sender_scope);
let collected = candidates::at_most_one_distinct(
collected.into_iter().map(|(_, key)| key),
"collected resource timing option",
)?;
let tallies = ast::in_declared_functions(script, |function| {
tally::published_tally(function.function.body.as_ref()?)
});
let counters = candidates::at_most_one_distinct(tallies, "interaction tally")?;
let timing = match collected {
Some(option) => {
let reductions = ast::in_declared_functions(script, |function| {
reduced_timing::reduction(function.function.body.as_ref()?)
});
candidates::at_most_one_distinct(reductions, "resource timing reducer")?
.map(|fields| ResourceTiming { option, fields })
}
None => None,
};
let counter_events = counters
.as_ref()
.map(|tally| CounterEvents::recover(script, tally));
Ok(Self {
marks: scopes.found,
counters,
counter_events,
elapsed: elapsed.map(|(_, elapsed)| elapsed),
forwarded: forwarded.into_iter().map(|(_, key)| key).collect(),
timing,
getters: distinct_getters(sender.getters)?,
})
}
/// Returns the event-to-counter mapping, or the error preventing native tally updates.
pub fn counter_events(&self) -> Result<&CounterEvents> {
let reason = match &self.counter_events {
Some(Ok(counters)) => return Ok(counters),
Some(Err(error)) => format!("{error:#}"),
None => "it keeps no tally".to_owned(),
};
bail!("could not recover the iframe's input event counters: {reason}")
}
fn builds_payload(&self, option: &str) -> bool {
self.marks
.iter()
.any(|mark| mark.option == option && mark.in_builder)
}
/// Assigns timestamps to match configured durations. Skips timestamps unused in
/// differences. Keeps the first value assigned to each timestamp, even if a later duration
/// constraint conflicts.
#[must_use]
pub fn timestamps(
&self,
differences: &[Difference],
merged: Option<&str>,
merged_at: i64,
intervals: &Intervals,
) -> Options {
let mut clock: IndexMap<&str, i64> = IndexMap::new();
if let Some(merged) = merged {
clock.insert(merged, merged_at);
}
for Difference { later, earlier } in differences {
if !self.marks.iter().any(|mark| &mark.option == later) {
continue;
}
// The builder starts after the parameter merge. Other measured work overlaps the
// handoff.
let (start, duration) = if self.builds_payload(later) {
(merged_at + intervals.handoff + 1, intervals.collect)
} else if Some(earlier.as_str()) == merged {
(merged_at + 1, intervals.handoff)
} else {
(merged_at + 1, intervals.initialise)
};
let start = *clock.entry(earlier).or_insert(start);
clock.entry(later).or_insert(start + duration);
}
clock
.into_iter()
.map(|(option, when)| (option.to_owned(), JsValue::from(when)))
.collect()
}
}
/// Groups timestamps by their innermost function and finds the function containing the payload
/// template. A template in a nested callback may subtract timestamps set by different
/// functions.
struct Scopes<'options> {
options: &'options Options,
/// The enclosing functions, innermost last.
stack: Vec<Scope>,
found: Vec<Mark>,
}
/// One function's timestamp options, and whether it holds the payload template.
#[derive(Default)]
struct Scope {
marks: Vec<String>,
builds_payload: bool,
}
impl Scopes<'_> {
fn within<N: VisitWith<Self>>(&mut self, node: &N) {
self.stack.push(Scope::default());
node.visit_children_with(self);
let scope = self.stack.pop().expect("entered a scope first");
let marks = scope.marks.into_iter().map(|option| Mark {
option,
in_builder: scope.builds_payload,
});
self.found.extend(marks);
}
}
impl Visit for Scopes<'_> {
fn visit_function(&mut self, function: &Function) {
self.within(function);
}
fn visit_arrow_expr(&mut self, arrow: &ArrowExpr) {
self.within(arrow);
}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
if let Some(option) = expression::option_assignment(&assignment.left)
&& ast::is_date_now(&assignment.right)
&& let Some(scope) = self.stack.last_mut()
{
scope.marks.push(option.to_owned());
}
assignment.visit_children_with(self);
}
fn visit_if_stmt(&mut self, conditional: &IfStmt) {
let options = self.options;
source::visit_taken_branches(self, conditional, options);
}
fn visit_object_lit(&mut self, object: &ObjectLit) {
if source::is_payload_template(object, self.options)
&& let Some(scope) = self.stack.last_mut()
{
scope.builds_payload = true;
}
object.visit_children_with(self);
}
}
/// Finds property writes that add payload fields or install namespace getters. Records the
/// enclosing function for each write.
#[derive(Default)]
struct Sender {
entered: usize,
scopes: Vec<usize>,
elapsed: Vec<(usize, Elapsed)>,
copies: Vec<(usize, String)>,
getters: Vec<Getter>,
}
/// A namespace getter named `function` that returns the option `option`.
struct Getter {
function: String,
option: String,
}
impl Sender {
fn within<N: VisitWith<Self>>(&mut self, node: &N) {
self.entered += 1;
self.scopes.push(self.entered);
node.visit_children_with(self);
self.scopes.pop();
}
}
impl Visit for Sender {
fn visit_function(&mut self, function: &Function) {
self.within(function);
}
fn visit_arrow_expr(&mut self, arrow: &ArrowExpr) {
self.within(arrow);
}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
let scope = self.scopes.last().copied().unwrap_or_default();
if let AssignTarget::Simple(SimpleAssignTarget::Member(target)) = &assignment.left
&& let Some(key) = ast::ident_property(target)
{
match &*assignment.right {
// `payload.<key> = Date.now() - _cf_chl_opt.<mark>`
Expr::Bin(binary)
if binary.op == BinaryOp::Sub
&& ast::is_date_now(&binary.left)
&& let Some(mark) = expression::option_key(&binary.right) =>
{
let elapsed = Elapsed {
key: key.to_owned(),
mark: mark.to_owned(),
};
self.elapsed.push((scope, elapsed));
}
// `<namespace>.<key> = function () { var ...; local = _cf_chl_opt.<option>; ... }`
Expr::Fn(getter)
if let Some(body) = &getter.function.body
&& let Some(first) = body.stmts.iter().find_map(Stmt::as_expr)
&& let Expr::Assign(first) = &*first.expr
&& let Some(option) = expression::option_key(&first.right) =>
{
self.getters.push(Getter {
function: key.to_owned(),
option: option.to_owned(),
});
}
// `payload.<key> = _cf_chl_opt.<key>`
right if expression::option_key(right) == Some(key) => {
self.copies.push((scope, key.to_owned()));
}
_ => {}
}
}
assignment.visit_children_with(self);
}
}
/// Rejects a getter name that returns different options.
fn distinct_getters(getters: Vec<Getter>) -> Result<BTreeMap<String, String>> {
let mut distinct = BTreeMap::new();
for Getter { function, option } in getters {
let previous = distinct.entry(function.clone()).or_insert(option.clone());
ensure!(
*previous == option,
"getter {function} reads both {previous} and {option}"
);
}
Ok(distinct)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_senders_that_disagree_about_the_elapsed_field() {
let source = r#"
function s1() { p.k = Date.now() - e._cf_chl_opt.m1; }
function s2() { p.j = Date.now() - e._cf_chl_opt.m2; }"#;
let error = ScriptState::from_javascript(source)
.unwrap_err()
.to_string();
assert!(error.contains("conflicting elapsed-time field"), "{error}");
let source =
r#"function s1() { p.k = Date.now() - e._cf_chl_opt.m1; p.f = e._cf_chl_opt.f; }"#;
let script = ScriptState::from_javascript(source).unwrap();
assert_eq!(
script.elapsed,
Some(Elapsed {
key: "k".into(),
mark: "m1".into(),
})
);
assert_eq!(script.forwarded, ["f"]);
}
/// Checks timestamp assignment with the tracked profile's 7 ms between startup timestamps.
/// Assigned timestamps keep their first value.
#[test]
fn places_marks_so_every_reported_difference_matches_its_interval() {
let script = ScriptState {
marks: vec![Mark {
option: "b".into(),
in_builder: false,
}],
..ScriptState::default()
};
let differences = [("b", "a"), ("b", "merged")].map(|(later, earlier)| Difference {
later: later.into(),
earlier: earlier.into(),
});
let intervals = &crate::browser::Browser::safari().page.intervals;
let at = script.timestamps(&differences, Some("merged"), 0, intervals);
assert_eq!(JsValue::from(at).to_string(), r#"{"merged":0,"a":1,"b":8}"#);
}
}
+220
View File
@@ -0,0 +1,220 @@
//! Recovers the tally the iframe keeps of the visitor's input events, and counts events into it
//! as the iframe's listener would.
use std::collections::{BTreeMap, BTreeSet};
use anyhow::{Context, Result, ensure};
use swc_core::ecma::ast::{
AssignExpr, AssignTarget, BlockStmt, Expr, IfStmt, Lit, Pat, Script, SimpleAssignTarget,
UpdateExpr, UpdateOp, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use crate::candidates;
use crate::challenge::expression::{self, BuiltObject, ObjectField};
use crate::js::{JsValue, Window, ast, json};
/// Minimum number of zeroed fields used to recognize an interaction tally.
const COUNTERS: usize = 4;
/// Input event types counted by the iframe listener. Native tally updates require all mappings.
const COUNTED_EVENTS: [&str; 7] = [
"mousemove",
"pointermove",
"pointerover",
"touchstart",
"click",
"keydown",
"wheel",
];
/// The tally the script keeps of the visitor's interactions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tally {
pub global: String,
pub counters: Vec<String>,
}
/// Counts input events using the iframe listener's event mapping.
#[derive(Debug)]
pub struct CounterEvents {
/// The global holding the tally.
pub global: String,
/// Each counted event type, mapped to the field its branch increments.
pub events: BTreeMap<String, String>,
/// The field every counted event increments as well.
pub total: String,
}
impl CounterEvents {
pub(super) fn recover(script: &Script, tally: &Tally) -> Result<Self> {
let mut aliases = Aliases {
global: &tally.global,
found: BTreeSet::new(),
};
script.visit_with(&mut aliases);
let mut handlers = Handlers {
aliases: &aliases.found,
names: &tally.counters,
events: BTreeMap::new(),
};
script.visit_with(&mut handlers);
let used: BTreeSet<_> = handlers.events.values().collect();
let remaining = tally.counters.iter().filter(|name| !used.contains(name));
let total = candidates::exactly_one(remaining, "unhandled counter")
.context("finding the input event tally's total")?
.clone();
ensure!(
handlers.events.len() == COUNTED_EVENTS.len() && used.len() == COUNTED_EVENTS.len(),
"the input listener counts {} of the {} input events, into {} distinct counters",
handlers.events.len(),
COUNTED_EVENTS.len(),
used.len()
);
Ok(Self {
global: tally.global.clone(),
events: handlers.events,
total,
})
}
/// Counts supported `events` in the tally stored on `window`. Ignores event types the
/// iframe listener does not count.
pub fn record(&self, window: &mut Window, events: &[&str]) -> Result<()> {
let tally = window
.get_mut(&self.global)
.and_then(JsValue::as_object_mut)
.context("iframe has no input event tally")?;
for event in events {
let Some(field) = self.events.get(*event) else {
continue;
};
for field in [field, &self.total] {
let count = tally
.get(field)
.and_then(JsValue::as_u64)
.context("input event tally is not an integer")?;
tally.insert(field.clone(), json!(count + 1));
}
}
Ok(())
}
}
/// The locals the tally's global is copied into: `local = <namespace>.<global>`.
struct Aliases<'tally> {
global: &'tally str,
found: BTreeSet<String>,
}
impl Visit for Aliases<'_> {
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
if let AssignTarget::Simple(SimpleAssignTarget::Ident(local)) = &assignment.left
&& let Expr::Member(member) = &*assignment.right
&& ast::member_str(&member.prop) == Some(self.global)
{
self.found.insert(local.id.sym.to_string());
}
assignment.visit_children_with(self);
}
fn visit_var_declarator(&mut self, variable: &VarDeclarator) {
if let Pat::Ident(local) = &variable.name
&& let Some(Expr::Member(member)) = variable.init.as_deref()
&& ast::member_str(&member.prop) == Some(self.global)
{
self.found.insert(local.id.sym.to_string());
}
variable.visit_children_with(self);
}
}
/// The tally fields incremented through an alias: `<alias>.<field>++`.
struct Updates<'tally> {
aliases: &'tally BTreeSet<String>,
names: &'tally [String],
found: BTreeSet<String>,
}
impl Visit for Updates<'_> {
fn visit_update_expr(&mut self, update: &UpdateExpr) {
if update.op == UpdateOp::PlusPlus
&& let Expr::Member(member) = &*update.arg
&& let Expr::Ident(object) = &*member.obj
&& self.aliases.contains(object.sym.as_ref())
&& let Some(field) = ast::member_str(&member.prop)
&& self.names.iter().any(|name| name == field)
{
self.found.insert(field.to_owned());
}
update.visit_children_with(self);
}
}
/// Maps each individually tested event type to the counter incremented by its branch.
struct Handlers<'tally> {
aliases: &'tally BTreeSet<String>,
names: &'tally [String],
events: BTreeMap<String, String>,
}
impl Visit for Handlers<'_> {
fn visit_if_stmt(&mut self, branch: &IfStmt) {
let events = ast::string_literals(&*branch.test)
.into_iter()
.filter(|text| COUNTED_EVENTS.contains(&text.as_str()));
let mut updates = Updates {
aliases: self.aliases,
names: self.names,
found: BTreeSet::new(),
};
branch.cons.visit_with(&mut updates);
if let Ok(event) = candidates::exactly_one(events, "event type")
&& let Ok(field) = candidates::exactly_one(updates.found, "incremented field")
{
self.events.insert(event, field);
}
branch.visit_children_with(self);
}
}
/// Finds the first interaction tally published as `<namespace>.<global> = {...}`. Accepts
/// direct assignment or assignment through a local.
pub(super) fn published_tally(body: &BlockStmt) -> Option<Tally> {
let mut built: Vec<BuiltObject> = Vec::new();
for assignment in expression::assignments(body) {
if expression::track(&mut built, assignment) {
continue;
}
let counters = match &*assignment.right {
Expr::Ident(ident) => built
.iter()
.rfind(|object| object.local == &*ident.sym)
.and_then(|object| zeroed(&object.fields)),
right => expression::object_fields(right).as_deref().and_then(zeroed),
};
if let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assignment.left
&& let Some(global) = ast::ident_property(member)
&& let Some(counters) = counters
{
return Some(Tally {
global: global.to_owned(),
counters,
});
}
}
None
}
/// Returns counter names when there are enough fields and every value starts at zero.
fn zeroed(fields: &[ObjectField<'_>]) -> Option<Vec<String>> {
if fields.len() < COUNTERS {
return None;
}
fields
.iter()
.map(|field| {
matches!(field.value, Expr::Lit(Lit::Num(number)) if number.value == 0.0)
.then(|| field.key.to_owned())
})
.collect()
}
+28
View File
@@ -0,0 +1,28 @@
//! Runs recursive work on a thread with a dedicated stack, independent of the caller's runtime.
use std::thread;
use anyhow::{Context, Result};
use tokio::sync::oneshot;
/// Stack size for recursive deobfuscation, matching the usual Linux main-thread stack.
const STACK_SIZE: usize = 8 << 20;
/// Runs `work` on a new thread named `name` and awaits its result without blocking the runtime.
pub(crate) async fn run<T: Send + 'static>(
name: &str,
work: impl FnOnce() -> T + Send + 'static,
) -> Result<T> {
let (sender, receiver) = oneshot::channel();
thread::Builder::new()
.name(name.into())
.stack_size(STACK_SIZE)
.spawn(move || {
// The receiver is gone only if the caller stopped waiting.
let _ = sender.send(work());
})
.with_context(|| format!("starting the {name} thread"))?;
receiver
.await
.with_context(|| format!("the {name} thread failed"))
}
+41
View File
@@ -0,0 +1,41 @@
//! Deobfuscates Cloudflare challenge scripts in repeated rewrite rounds.
//!
//! Rewrites make further rewrites possible: decoding names allows helper inlining, which
//! reveals control flow and more calls. Each round runs the [`pipeline`] steps in order. A step
//! is skipped if it already left the current program unchanged. Rounds stop when all steps have
//! processed the current program or a whole round makes no net change. The final hygiene pass
//! resolves naming conflicts. Each rewrite module describes its transformation.
/// Fast hashing for the rewrites' identifier and node maps; no rewrite depends on their order.
type HashMap<K, V> = rustc_hash::FxHashMap<K, V>;
type HashSet<T> = rustc_hash::FxHashSet<T>;
mod analysis;
mod argument_arrays;
mod bitwise;
mod blocks;
mod constant_objects;
mod control_flow;
mod copy_propagation;
mod dead_branches;
mod dead_properties;
mod dispatch;
mod encoded_strings;
mod function_lengths;
mod helper_objects;
mod indexed_table;
mod int32_helpers;
mod literals;
mod loops;
mod pipeline;
mod removal;
mod scratch_parameters;
mod statements;
mod static_members;
mod string_array;
#[cfg(test)]
mod testing;
mod unused_bindings;
pub use pipeline::{Deobfuscated, Unconverged, deobfuscate};
pub(crate) use pipeline::{deobfuscate_with, read_decoded};
+62
View File
@@ -0,0 +1,62 @@
//! Shared conservative analysis for deobfuscation rewrites.
//!
//! Allows a rewrite only when analysis proves it safe; unknown syntax prevents rewriting. Uses
//! resolved [`swc_core::ecma::ast::Id`] values for bindings, so results are valid only after
//! name resolution and before hygiene.
use swc_core::common::Mark;
use swc_core::ecma::ast::Program;
mod bindings;
pub(super) mod effects;
mod globals;
pub(super) mod hoisting;
pub(super) mod names;
mod properties;
pub(super) use bindings::Bindings;
pub(super) use globals::Globals;
pub(super) use properties::{Properties, constant_index, member_key, prop_key};
/// Caches analysis of the current program until a rewrite changes it. A rewrite that needs to
/// analyze its own changes must collect fresh results.
pub(crate) struct Analysis {
/// Remains valid across rewrites.
pub(crate) globals: Globals,
bindings: Option<Bindings>,
properties: Option<Properties>,
}
impl Analysis {
#[must_use]
pub(crate) fn new(unresolved_mark: Mark) -> Self {
Self {
globals: Globals::new(unresolved_mark),
bindings: None,
properties: None,
}
}
#[must_use]
pub(crate) fn bindings(&mut self, program: &Program) -> &Bindings {
self.bindings
.get_or_insert_with(|| Bindings::collect(program))
}
/// Returns binding and property summaries; property uses build on the bindings.
#[must_use]
pub(crate) fn properties(&mut self, program: &Program) -> (&Bindings, &Properties) {
let bindings = self
.bindings
.get_or_insert_with(|| Bindings::collect(program));
let properties = self
.properties
.get_or_insert_with(|| Properties::collect(program, bindings));
(bindings, properties)
}
pub(crate) fn invalidate(&mut self) {
self.bindings = None;
self.properties = None;
}
}
+336
View File
@@ -0,0 +1,336 @@
//! Counts binding reads and writes and tracks simple assigned values, so rewrites can identify
//! single assignments and follow copies to their source.
use std::mem;
use swc_core::ecma::ast::{
AssignExpr, AssignOp, BindingIdent, ClassDecl, Expr, FnDecl, ForHead, Function, Id, Ident,
Program, Prop, UpdateExpr, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use swc_ecma_utils::DestructuringFinder;
use crate::deobfuscate::{HashMap, HashSet};
use crate::js::ast;
/// Tracks writes, references, and declarations by resolved [`Id`]. Names alone are insufficient
/// because the obfuscator reuses them across scopes.
///
/// Writes include assignments, updates, initialized declarations, `for-in` and `for-of`
/// targets, and function or class declarations. Parameters and catch clauses do not count:
/// helpers may use parameter slots whose incoming values are never read. An assigned value can
/// be used for substitution only when its binding has exactly one write.
#[derive(Default)]
pub(crate) struct Bindings {
writes: HashMap<Id, Vec<Write>>,
references: HashMap<Id, usize>,
declared: HashSet<Id>,
/// Bindings that receive a copy of each binding's value.
copies: HashMap<Id, Vec<Id>>,
/// Parameters of functions that use `arguments`.
mapped: HashSet<Id>,
/// Whether the function being visited refers to its `arguments`.
uses_arguments: bool,
}
/// One write, and the assigned value when analysis can follow it.
enum Write {
/// `binding = other` or `var binding = other`.
Copy(Id),
/// `binding = f()`, calling `f` without arguments.
Call(Id),
Other,
}
impl Bindings {
#[must_use]
pub(crate) fn collect(program: &Program) -> Self {
let mut bindings = Self::default();
program.visit_with(&mut bindings);
bindings
}
#[must_use]
pub(crate) fn write_count(&self, id: &Id) -> usize {
self.writes.get(id).map_or(0, Vec::len)
}
/// Checks for exactly one write, allowing later reads to use that assigned value.
#[must_use]
pub(crate) fn is_written_once(&self, id: &Id) -> bool {
self.write_count(id) == 1
}
/// Returns the number of value reads, including reads through `binding.property`.
#[must_use]
pub(crate) fn references(&self, id: &Id) -> usize {
self.references.get(id).copied().unwrap_or(0)
}
/// Checks whether the program declares or assigns the binding, including parameter
/// bindings.
#[must_use]
pub(crate) fn is_bound(&self, id: &Id) -> bool {
self.declared.contains(id) || self.writes.contains_key(id)
}
/// Checks whether this is a parameter of a function using `arguments`. In sloppy mode,
/// `arguments[i]` can observe parameter writes and changes to the parameter list.
#[must_use]
pub(crate) fn is_mapped_parameter(&self, id: &Id) -> bool {
self.mapped.contains(id)
}
/// Returns the source binding when `id` has exactly one write that copies it.
#[must_use]
pub(crate) fn copy_source(&self, id: &Id) -> Option<&Id> {
match self.writes.get(id)?.as_slice() {
[Write::Copy(source)] => Some(source),
_ => None,
}
}
/// Follows [`Self::copy_source`] to the original binding in a copy chain. This identifies
/// the first binding assigned a helper object.
#[must_use]
pub(crate) fn root(&self, id: &Id) -> Id {
let mut current = id.clone();
let mut seen = HashSet::default();
while let Some(source) = self.copy_source(&current) {
if !seen.insert(current.clone()) {
break;
}
current = source.clone();
}
current
}
/// The [`Self::root`] of every binding that has a copy source.
#[must_use]
pub(crate) fn roots(&self) -> HashMap<Id, Id> {
let copies = self
.writes
.keys()
.filter(|id| self.copy_source(id).is_some());
copies.map(|id| (id.clone(), self.root(id))).collect()
}
/// Checks whether another binding copies `id` (see [`Self::copy_source`]).
#[must_use]
pub(crate) fn is_copied(&self, id: &Id) -> bool {
self.copies
.get(id)
.is_some_and(|copies| copies.iter().any(|copy| self.copy_source(copy) == Some(id)))
}
/// Returns the callee whose result is the only value assigned to `id`.
#[must_use]
pub(crate) fn sole_call(&self, id: &Id) -> Option<Id> {
match self.writes.get(id)?.as_slice() {
[Write::Call(callee)] => Some(callee.clone()),
_ => None,
}
}
/// Returns `id` and all bindings that copy it, directly or through other copies, regardless
/// of assignment order.
#[must_use]
pub(crate) fn aliases(&self, id: &Id) -> HashSet<Id> {
let mut aliases = HashSet::from_iter([id.clone()]);
let mut pending = vec![id.clone()];
while let Some(source) = pending.pop() {
let copies = self.copies.get(&source).into_iter().flatten();
for copy in copies {
let copies_only_aliases = self.writes[copy]
.iter()
.all(|write| matches!(write, Write::Copy(from) if aliases.contains(from)));
if !aliases.contains(copy) && copies_only_aliases {
aliases.insert(copy.clone());
pending.push(copy.clone());
}
}
}
aliases
}
fn write<N: VisitWith<DestructuringFinder<Id>>>(&mut self, target: &N) {
for id in swc_ecma_utils::find_pat_ids::<_, Id>(target) {
self.writes.entry(id).or_default().push(Write::Other);
}
}
/// A write of `value` to the plain identifier `id`.
fn write_value(&mut self, id: Id, value: &Expr) {
let write = if let Some(source) = value.as_ident() {
self.copies
.entry(source.to_id())
.or_default()
.push(id.clone());
Write::Copy(source.to_id())
} else if let Some((callee, [])) = ast::direct_call(value) {
Write::Call(callee.to_id())
} else {
Write::Other
};
self.writes.entry(id).or_default().push(write);
}
fn reference(&mut self, id: Id) {
*self.references.entry(id).or_default() += 1;
}
}
impl Visit for Bindings {
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
match assignment.left.as_ident() {
Some(target) if assignment.op == AssignOp::Assign => {
self.write_value(target.to_id(), &assignment.right);
}
_ => self.write(&assignment.left),
}
assignment.visit_children_with(self);
}
fn visit_update_expr(&mut self, update: &UpdateExpr) {
if let Expr::Ident(id) = &*update.arg {
self.write(id);
}
update.visit_children_with(self);
}
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if let Some(init) = &declarator.init {
match declarator.name.as_ident() {
Some(name) => self.write_value(name.to_id(), init),
None => self.write(&declarator.name),
}
}
declarator.visit_children_with(self);
}
/// Loop heads assign on every iteration, whether or not they declare.
fn visit_for_head(&mut self, head: &ForHead) {
self.write(head);
head.visit_children_with(self);
}
fn visit_fn_decl(&mut self, function: &FnDecl) {
self.write(&function.ident);
function.visit_children_with(self);
}
fn visit_class_decl(&mut self, class: &ClassDecl) {
self.write(&class.ident);
class.visit_children_with(self);
}
fn visit_function(&mut self, function: &Function) {
// A nested function has its own `arguments`; an arrow shares its enclosing function's.
let outer = mem::take(&mut self.uses_arguments);
function.visit_children_with(self);
if mem::replace(&mut self.uses_arguments, outer) {
self.mapped.extend(
function
.params
.iter()
.flat_map(|param| swc_ecma_utils::find_pat_ids::<_, Id>(&param.pat)),
);
}
}
fn visit_binding_ident(&mut self, identifier: &BindingIdent) {
self.declared.insert(identifier.to_id());
identifier.visit_children_with(self);
}
fn visit_ident(&mut self, identifier: &Ident) {
self.uses_arguments |= identifier.sym == "arguments";
}
fn visit_expr(&mut self, expression: &Expr) {
if let Expr::Ident(id) = expression {
self.reference(id.to_id());
}
expression.visit_children_with(self);
}
fn visit_prop(&mut self, property: &Prop) {
if let Prop::Shorthand(id) = property {
self.reference(id.to_id());
}
property.visit_children_with(self);
}
}
#[cfg(test)]
mod tests {
use super::Bindings;
use crate::deobfuscate::testing;
#[test]
fn counts_writes_and_references() {
testing::check(
"function f(once, twice, escaped, counted, param, m, mutated) {
once = {}; twice = {}; twice = 1; escaped = {}; use(escaped);
counted = {}; counted++; var declared = 1; function g() {}
mutated = {}; mutated.x = 1; [m.w] = [1];
for (const [a, b] of list) {}
return once.x + escaped.y + m.z + m[\"w\"] + mutated.x + { param };
}",
|program, id| {
let writes = Bindings::collect(program);
assert!(writes.is_written_once(&id("once")));
assert!(!writes.is_written_once(&id("twice")));
assert!(writes.is_written_once(&id("escaped")));
assert!(!writes.is_written_once(&id("counted")));
assert!(writes.is_written_once(&id("declared")));
assert!(writes.is_written_once(&id("g")));
assert!(writes.is_written_once(&id("a")));
assert!(!writes.is_written_once(&id("m")));
assert_eq!(writes.references(&id("m")), 3);
assert_eq!(writes.references(&id("escaped")), 2);
assert_eq!(writes.references(&id("param")), 1);
assert_eq!(writes.references(&id("mutated")), 2);
},
);
}
#[test]
fn follows_copies_sole_calls_and_mapped_parameters() {
testing::check(
"function f(late, middle, other, mixed, table, h, p, q) {
late = middle; middle = d; other = d; other = middle;
mixed = d; mixed = g(); table = provider();
function d() {}
function provider() {}
h = {}; p = h; var q = p;
return parseInt(late);
}",
|program, id| {
let bindings = Bindings::collect(program);
let aliases = bindings.aliases(&id("d"));
for alias in ["d", "late", "middle", "other"] {
assert!(aliases.contains(&id(alias)), "{alias}");
}
assert!(!aliases.contains(&id("mixed")));
assert_eq!(bindings.sole_call(&id("table")), Some(id("provider")));
assert_eq!(bindings.sole_call(&id("mixed")), None);
assert!(!bindings.is_bound(&id("parseInt")));
assert!(bindings.is_bound(&id("late")));
assert_eq!(bindings.root(&id("q")), id("h"));
assert_eq!(bindings.root(&id("late")), id("d"));
assert_eq!(bindings.root(&id("mixed")), id("mixed"));
},
);
testing::check(
"function f(a, [b]) { return () => arguments[0]; }
function g(c) { return function () { return arguments; }; }",
|program, id| {
let bindings = Bindings::collect(program);
assert!(bindings.is_mapped_parameter(&id("a")));
assert!(bindings.is_mapped_parameter(&id("b")));
assert!(!bindings.is_mapped_parameter(&id("c")));
},
);
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Tracks expression side effects and binding reads and writes.
use swc_core::ecma::ast::{ArrowExpr, AssignExpr, Expr, Function, Id, Ident, UpdateExpr};
use swc_core::ecma::visit::{Visit, VisitWith};
use swc_ecma_utils::ExprCtx;
use super::Globals;
use crate::deobfuscate::HashSet;
/// Checks for observable effects, including getters and coercions.
///
/// SWC treats local binding reads as effect-free. A global read is effect-free only if it names
/// a known browser global without a getter, such as `Math` or `undefined`. Other globals may
/// throw `ReferenceError` or invoke a getter.
#[must_use]
pub(crate) fn may_have_effects(expression: &Expr, globals: Globals) -> bool {
use swc_ecma_utils::ExprExt;
expression.may_have_side_effects(ExprCtx {
unresolved_ctxt: globals.unresolved,
is_unresolved_ref_safe: false,
in_strict: false,
remaining_depth: 4,
})
}
/// Tracks binding reads and writes outside function bodies. Creating a closure does not execute
/// its body. Does not analyze the effects of calls, `new`, tagged templates, `await`, or
/// `yield`.
#[derive(Default)]
pub(crate) struct Effects {
pub reads: HashSet<Id>,
pub writes: HashSet<Id>,
pub opaque: bool,
}
impl Effects {
#[must_use]
pub(crate) fn collect(expression: &Expr) -> Self {
let mut effects = Self::default();
expression.visit_with(&mut effects);
effects
}
}
impl Visit for Effects {
fn visit_ident(&mut self, identifier: &Ident) {
self.reads.insert(identifier.to_id());
}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
self.writes
.extend(swc_ecma_utils::find_pat_ids::<_, Id>(&assignment.left));
assignment.visit_children_with(self);
}
fn visit_update_expr(&mut self, update: &UpdateExpr) {
if let Some(identifier) = update.arg.as_ident() {
self.writes.insert(identifier.to_id());
}
update.arg.visit_with(self);
}
fn visit_expr(&mut self, expression: &Expr) {
self.opaque |= matches!(
expression,
Expr::Call(_) | Expr::New(_) | Expr::TaggedTpl(_) | Expr::Await(_) | Expr::Yield(_)
);
expression.visit_children_with(self);
}
fn visit_function(&mut self, _: &Function) {}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
}
+33
View File
@@ -0,0 +1,33 @@
//! Distinguishes references to browser globals from local bindings.
use swc_core::common::{Mark, Span, SyntaxContext};
use swc_core::ecma::ast::Ident;
/// Identifies unresolved references marked by the resolver. Only these refer to globals; a
/// local `Reflect` or `undefined` shadows the browser global.
#[derive(Clone, Copy)]
pub(crate) struct Globals {
pub(crate) mark: Mark,
/// The syntax context of every unresolved reference.
pub(crate) unresolved: SyntaxContext,
}
impl Globals {
#[must_use]
pub(crate) fn new(unresolved_mark: Mark) -> Self {
Self {
mark: unresolved_mark,
unresolved: SyntaxContext::empty().apply_mark(unresolved_mark),
}
}
#[must_use]
pub(crate) fn is(&self, identifier: &Ident, name: &str) -> bool {
identifier.ctxt == self.unresolved && identifier.sym == name
}
#[must_use]
pub(crate) fn reference(&self, name: &str, span: Span) -> Ident {
Ident::new(name.into(), span, self.unresolved)
}
}
+279
View File
@@ -0,0 +1,279 @@
//! Tracks which analysis facts hold when a hoisted function runs.
//!
//! A function declaration can be called before the statements above it execute. Facts learned
//! from those statements are safe to use in the function only if they hold at every reference
//! that could make it callable. References through other declarations in the same list also
//! count. Visitors process ordinary statements first and record identifier uses through
//! [`reference`]. They then visit declarations with the facts valid for each one.
//!
//! This treatment applies only to declarations in function bodies. Top-level functions can be
//! called by other scripts at any time. Block functions exist only once the block executes.
//! Both use the facts known on entry.
use std::mem;
use std::rc::Rc;
use swc_core::ecma::ast::{Decl, Function, Id, Ident, Stmt};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use crate::deobfuscate::{HashMap, HashSet};
/// Facts known at a point in the program.
pub(crate) trait HoistFacts: Clone {
/// Keeps facts shared with `other`.
fn meet(&mut self, other: &Self);
}
impl HoistFacts for HashSet<Id> {
fn meet(&mut self, other: &Self) {
self.retain(|id| other.contains(id));
}
}
/// Facts about bindings assigned once. Any known values for the same binding must agree.
impl<V: Clone> HoistFacts for HashMap<Id, V> {
fn meet(&mut self, other: &Self) {
self.retain(|id, _| other.contains_key(id));
}
}
/// Copy-on-write facts, shared between the current node and declaration snapshots.
impl<F: HoistFacts> HoistFacts for Rc<F> {
fn meet(&mut self, other: &Self) {
if !Rc::ptr_eq(self, other) {
Rc::make_mut(self).meet(other);
}
}
}
/// A function declaration, which its whole scope sees from the start.
fn is_declaration(statement: &Stmt) -> bool {
matches!(statement, Stmt::Decl(Decl::Fn(_)))
}
/// Tracks current facts, active function declarations, and facts collected at references to
/// those declarations.
#[derive(Default)]
pub(crate) struct Hoisting<F> {
/// Facts known at the current node.
pub(crate) facts: F,
/// Intersection of facts at references to each declaration; `None` before its first
/// reference.
pending: HashMap<Id, Option<F>>,
/// Whether the next statement list is a function body.
pub(crate) function_body: bool,
}
/// The function declarations of one statement list, from
/// [`Hoisting::enter`] to [`Hoisting::leave`].
struct Declarations<F> {
declarations: Vec<Declaration>,
/// For each declaration, the declarations in this list that reference it.
callers: Vec<Vec<usize>>,
/// Facts at list entry, saved when the list contains declarations.
entry: Option<F>,
function_body: bool,
}
/// One function declaration of a statement list, at `position` in it.
struct Declaration {
position: usize,
id: Id,
}
impl<F: HoistFacts> Hoisting<F> {
/// Starts visiting `statements` with the entry facts.
#[must_use]
fn enter(&mut self, statements: &[Stmt]) -> Declarations<F> {
let function_body = mem::take(&mut self.function_body);
let declarations: Vec<Declaration> = statements
.iter()
.enumerate()
.filter_map(|(position, statement)| {
let id = statement.as_decl()?.as_fn_decl()?.ident.to_id();
Some(Declaration { position, id })
})
.collect();
let mut callers = vec![];
if function_body {
let mut indices: HashMap<Id, Vec<usize>> = HashMap::default();
for (index, declaration) in declarations.iter().enumerate() {
indices
.entry(declaration.id.clone())
.or_default()
.push(index);
self.pending.entry(declaration.id.clone()).or_insert(None);
}
callers = vec![vec![]; declarations.len()];
for (caller, declaration) in declarations.iter().enumerate() {
statements[declaration.position].visit_with(&mut Named {
indices: &indices,
callers: &mut callers,
caller,
});
}
}
Declarations {
entry: (!declarations.is_empty()).then(|| self.facts.clone()),
declarations,
callers,
function_body,
}
}
/// Finishes ordinary statements and returns each declaration's position and facts valid
/// whenever it can run. Unreferenced declarations receive the entry facts.
#[must_use]
fn leave(&mut self, declarations: Declarations<F>) -> Vec<(usize, F)> {
let Declarations {
declarations,
callers,
entry,
function_body,
} = declarations;
let Some(entry) = entry else {
return vec![];
};
if !function_body {
return declarations
.into_iter()
.map(|declaration| (declaration.position, entry.clone()))
.collect();
}
let direct: Vec<Option<F>> = declarations
.iter()
.map(|declaration| self.pending.get(&declaration.id).cloned().flatten())
.collect();
for declaration in &declarations {
self.pending.remove(&declaration.id);
}
// A declaration becomes callable when another declaration that references it, directly
// or indirectly, is referenced.
let mut declared = Vec::with_capacity(declarations.len());
for (index, declaration) in declarations.iter().enumerate() {
let mut facts = None;
let mut seen = vec![false; declarations.len()];
let mut pending = vec![index];
seen[index] = true;
while let Some(current) = pending.pop() {
if let Some(known) = &direct[current] {
meet(&mut facts, known);
}
for &caller in &callers[current] {
if !mem::replace(&mut seen[caller], true) {
pending.push(caller);
}
}
}
declared.push((declaration.position, facts.unwrap_or_else(|| entry.clone())));
}
declared
}
}
/// A rewrite that tracks facts across hoisted declarations.
pub(crate) trait Hoisted {
type Facts: HoistFacts;
fn hoisting(&mut self) -> &mut Hoisting<Self::Facts>;
}
/// Visits ordinary statements through `statement`, then function declarations with facts valid
/// at every possible call. Restores the facts left by ordinary statements afterward.
pub(crate) fn visit_mut_stmts<V: Hoisted + VisitMut>(
visitor: &mut V,
statements: &mut [Stmt],
mut statement: impl FnMut(&mut V, &mut Stmt),
) {
let declarations = visitor.hoisting().enter(statements);
for other in statements.iter_mut() {
if !is_declaration(other) {
statement(visitor, other);
}
}
let declared = visitor.hoisting().leave(declarations);
for (position, facts) in declared {
with_facts(visitor, facts, |visitor| {
statements[position].visit_mut_with(visitor);
});
}
}
/// [`visit_mut_stmts`] for a visitor that only reads the tree.
pub(crate) fn visit_stmts<V: Hoisted + Visit>(
visitor: &mut V,
statements: &[Stmt],
mut statement: impl FnMut(&mut V, &Stmt),
) {
let declarations = visitor.hoisting().enter(statements);
for other in statements {
if !is_declaration(other) {
statement(visitor, other);
}
}
let declared = visitor.hoisting().leave(declarations);
for (position, facts) in declared {
with_facts(visitor, facts, |visitor| {
statements[position].visit_with(visitor);
});
}
}
/// Marks a function body for [`Hoisting::enter`] before visiting it.
pub(crate) fn visit_mut_function<V: Hoisted + VisitMut>(visitor: &mut V, function: &mut Function) {
function.decorators.visit_mut_with(visitor);
function.params.visit_mut_with(visitor);
if let Some(body) = &mut function.body {
visitor.hoisting().function_body = true;
body.visit_mut_with(visitor);
}
}
/// Records current facts at a reference to `identifier`. Direct `eval` can reference any
/// declaration in scope.
pub(crate) fn reference<V: Hoisted>(visitor: &mut V, identifier: &Ident) {
let Hoisting { facts, pending, .. } = visitor.hoisting();
if identifier.sym == "eval" {
for known in pending.values_mut() {
meet(known, facts);
}
} else if let Some(known) = pending.get_mut(&identifier.to_id()) {
meet(known, facts);
}
}
/// Visits with `facts`, then restores the previous facts.
fn with_facts<V: Hoisted>(visitor: &mut V, facts: V::Facts, visit: impl FnOnce(&mut V)) {
let current = mem::replace(&mut visitor.hoisting().facts, facts);
visit(visitor);
visitor.hoisting().facts = current;
}
fn meet<F: HoistFacts>(known: &mut Option<F>, facts: &F) {
match known {
Some(known) => known.meet(facts),
None => *known = Some(facts.clone()),
}
}
/// Records references between function declarations in the same statement list.
struct Named<'declarations> {
indices: &'declarations HashMap<Id, Vec<usize>>,
callers: &'declarations mut [Vec<usize>],
caller: usize,
}
impl Visit for Named<'_> {
fn visit_ident(&mut self, identifier: &Ident) {
if identifier.sym == "eval" {
let every_index = self.indices.values().flatten();
for &index in every_index {
self.callers[index].push(self.caller);
}
} else if let Some(indices) = self.indices.get(&identifier.to_id()) {
for &index in indices {
self.callers[index].push(self.caller);
}
}
}
}
+52
View File
@@ -0,0 +1,52 @@
//! Finds bindings mentioned by a piece of code.
use swc_core::ecma::ast::{Function, Id, Ident, Param};
use swc_core::ecma::visit::{Visit, VisitWith};
/// Checks whether `node` mentions any of `ids`, including values, declarations, assignment
/// targets, and nested functions.
#[must_use]
pub(crate) fn mentions<N: for<'a> VisitWith<Mentions<'a>> + ?Sized>(node: &N, ids: &[Id]) -> bool {
let mut mentions = Mentions { ids, found: false };
node.visit_with(&mut mentions);
mentions.found
}
pub(crate) struct Mentions<'ids> {
ids: &'ids [Id],
found: bool,
}
impl Visit for Mentions<'_> {
fn visit_ident(&mut self, identifier: &Ident) {
self.found |= self.ids.contains(&identifier.to_id());
}
}
/// Checks for any identifier named `arguments`, following arrows, which share the enclosing
/// function's `arguments`, but not nested ordinary functions, which have their own.
#[must_use]
pub(crate) fn uses_arguments<N: VisitWith<Arguments> + ?Sized>(node: &N) -> bool {
let mut arguments = Arguments(false);
node.visit_with(&mut arguments);
arguments.0
}
pub(crate) struct Arguments(bool);
impl Visit for Arguments {
fn visit_ident(&mut self, identifier: &Ident) {
self.0 |= identifier.sym == "arguments";
}
fn visit_function(&mut self, _: &Function) {}
}
/// The bindings of `params`, if every parameter is a plain identifier.
#[must_use]
pub(crate) fn parameter_ids(params: &[Param]) -> Option<Vec<Id>> {
params
.iter()
.map(|param| Some(param.pat.as_ident()?.to_id()))
.collect()
}
+533
View File
@@ -0,0 +1,533 @@
//! Tracks static property reads, calls, definitions, escapes, and dynamic accesses, so rewrites
//! can decide whether properties retain their defined values.
use swc_core::atoms::Atom;
use swc_core::ecma::ast::{
AssignExpr, AssignOp, AssignTarget, BindingIdent, CallExpr, Callee, Expr, Id, Ident,
MemberExpr, MemberProp, OptCall, OptChainBase, Pat, Program, Prop, PropName,
SimpleAssignTarget, TaggedTpl, ThisExpr, UnaryExpr, UnaryOp, UpdateExpr, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use super::Bindings;
use crate::deobfuscate::{HashMap, HashSet};
use crate::js::ast;
/// Tracks property uses by binding and by object. Merges uses through single-assignment copies
/// such as `alias = object`; the copies themselves do not count as uses. See
/// [`Bindings::root`].
pub(crate) struct Properties {
uses: HashMap<Id, Uses>,
/// The uses of each root, merged over every binding with that root.
objects: HashMap<Id, Uses>,
/// See [`Bindings::roots`].
roots: HashMap<Id, Id>,
none: Uses,
}
/// Uses of a binding or of all aliases sharing an object.
#[derive(Default, PartialEq)]
pub(crate) struct Uses {
/// Passed, returned, stored, coerced, or copied to a multiply assigned binding. Such uses
/// expose the object to code this summary cannot track.
whole: bool,
/// Accessed or defined with an unknown key, including `__proto__`, except for reads at
/// constant indices.
computed: bool,
/// Read through a constant non-negative integer index, `binding[0]`.
indexed: bool,
deleted: bool,
/// A property value mentions `this`, so calling it as a method may observe or mutate the
/// object.
this: bool,
/// Assigned through a property with `=`: `binding.key = value` or `binding[key] = value`.
pub(crate) written_through: bool,
/// Static keys accessed through reads, calls, updates, deletions, destructuring writes, or
/// loop targets. Excludes plain `binding.key = value` assignments.
pub(crate) accessed: HashSet<Atom>,
/// The static keys called as methods, `binding.key(...)`.
called: HashSet<Atom>,
/// Definition counts for static keys, including object literals, assignments, updates,
/// destructuring patterns, and loop targets.
defined: HashMap<Atom, usize>,
}
impl Uses {
fn merge(&mut self, other: &Self) {
self.whole |= other.whole;
self.computed |= other.computed;
self.indexed |= other.indexed;
self.deleted |= other.deleted;
self.this |= other.this;
self.written_through |= other.written_through;
self.accessed.extend(other.accessed.iter().cloned());
self.called.extend(other.called.iter().cloned());
for (key, count) in &other.defined {
*self.defined.entry(key.clone()).or_default() += count;
}
}
/// Checks for uses of the whole object or access through a key that could name any
/// property.
#[must_use]
pub(crate) fn is_used_dynamically(&self) -> bool {
self.whole || self.computed || self.indexed
}
/// Checks that every use is a read at a constant index.
#[must_use]
pub(crate) fn is_only_indexed(&self) -> bool {
let indexed_reads = Self {
indexed: self.indexed,
..Self::default()
};
*self == indexed_reads
}
}
impl Properties {
#[must_use]
pub(crate) fn collect(program: &Program, bindings: &Bindings) -> Self {
let mut collect = Collect {
bindings,
uses: HashMap::default(),
};
program.visit_with(&mut collect);
let uses = collect.uses;
let mut objects: HashMap<Id, Uses> = HashMap::default();
for (id, uses) in &uses {
objects.entry(bindings.root(id)).or_default().merge(uses);
}
Self {
uses,
objects,
roots: bindings.roots(),
none: Uses::default(),
}
}
/// The uses through `id` itself.
#[must_use]
pub(crate) fn binding(&self, id: &Id) -> &Uses {
self.uses.get(id).unwrap_or(&self.none)
}
/// Returns uses through all bindings that share `id`'s object.
#[must_use]
pub(crate) fn object(&self, id: &Id) -> &Uses {
let root = self.roots.get(id).unwrap_or(id);
self.objects.get(root).unwrap_or(&self.none)
}
/// Checks for untracked object observations or mutations: escapes, dynamic keys, deletion,
/// or methods that may use `this`. Includes inherited methods such as `hasOwnProperty` and
/// defined methods mentioning `this`.
#[must_use]
pub(crate) fn is_opaque(&self, id: &Id) -> bool {
let object = self.object(id);
object.is_used_dynamically()
|| object.deleted
|| object.this
|| object
.called
.iter()
.any(|name| !object.defined.contains_key(name))
}
/// Checks that `id.key` has one definition. Reads must see that value, or an absent
/// property if they precede the definition.
#[must_use]
pub(crate) fn is_stable(&self, id: &Id, key: &Atom) -> bool {
!self.is_opaque(id) && self.object(id).defined.get(key) == Some(&1)
}
}
/// How a member expression is used.
#[derive(Clone, Copy, PartialEq)]
enum Access {
Read,
Call,
/// `binding.key = value`.
Assign,
/// Read and written: a compound assignment or an update.
Update,
/// Written by a destructuring pattern or a loop head.
Pattern,
Delete,
}
struct Collect<'bindings> {
bindings: &'bindings Bindings,
uses: HashMap<Id, Uses>,
}
impl Collect<'_> {
fn uses(&mut self, id: &Ident) -> &mut Uses {
self.uses.entry(id.to_id()).or_default()
}
/// Records an `access` to `member` when its object is a binding, then visits the remaining
/// evaluated expressions.
fn member(&mut self, member: &MemberExpr, access: Access) {
let Some(object) = member.obj.as_ident() else {
member.visit_children_with(self);
return;
};
let uses = self.uses(object);
match member_key(&member.prop) {
Some(key) => {
if matches!(access, Access::Assign | Access::Update | Access::Pattern) {
*uses.defined.entry(key.clone()).or_default() += 1;
}
if access == Access::Call {
uses.called.insert(key.clone());
}
if access != Access::Assign {
uses.accessed.insert(key);
}
}
None if access == Access::Read && constant_index(&member.prop).is_some() => {
uses.indexed = true;
}
None => uses.computed = true,
}
uses.written_through |= access == Access::Assign;
uses.deleted |= access == Access::Delete;
member.prop.visit_with(self);
}
/// Records `binding = value`. Returns whether it only copies an alias of the same object;
/// such copies do not count as object uses.
fn assignment(&mut self, binding: &Ident, value: &Expr) -> bool {
let Expr::Object(literal) = value else {
let copy_source = self.bindings.copy_source(&binding.to_id());
return value
.as_ident()
.is_some_and(|value| copy_source == Some(&value.to_id()));
};
let this = mentions_this(literal);
let uses = self.uses(binding);
uses.this |= this;
for property in &literal.props {
let key = match property.as_prop().map(|property| &**property) {
Some(Prop::KeyValue(property)) => prop_key(&property.key),
Some(Prop::Getter(property)) => prop_key(&property.key),
Some(Prop::Setter(property)) => prop_key(&property.key),
Some(Prop::Method(property)) => prop_key(&property.key),
Some(Prop::Shorthand(property)) => Some(property.sym.clone()),
Some(Prop::Assign(_)) | None => None,
};
match key {
Some(key) => *uses.defined.entry(key).or_default() += 1,
None => uses.computed = true,
}
}
false
}
/// Records a call, including the receiver passed as `this` for member callees.
fn callee(&mut self, callee: &Expr) {
match callee {
Expr::Paren(paren) => self.callee(&paren.expr),
Expr::Member(member) => self.member(member, Access::Call),
Expr::OptChain(chain) => match &*chain.base {
OptChainBase::Member(member) => self.member(member, Access::Call),
OptChainBase::Call(_) => chain.visit_with(self),
},
callee => callee.visit_with(self),
}
}
}
impl Visit for Collect<'_> {
/// Any mention of a binding that the cases below do not account for.
fn visit_ident(&mut self, identifier: &Ident) {
self.uses(identifier).whole = true;
}
/// Declaring or assigning a binding does not access the object's contents.
fn visit_binding_ident(&mut self, _: &BindingIdent) {}
fn visit_member_expr(&mut self, member: &MemberExpr) {
self.member(member, Access::Read);
}
fn visit_call_expr(&mut self, call: &CallExpr) {
match &call.callee {
Callee::Expr(callee) => self.callee(callee),
callee => callee.visit_with(self),
}
call.args.visit_with(self);
}
fn visit_opt_call(&mut self, call: &OptCall) {
self.callee(&call.callee);
call.args.visit_with(self);
}
fn visit_tagged_tpl(&mut self, template: &TaggedTpl) {
self.callee(&template.tag);
template.tpl.visit_with(self);
}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
let target = match &assignment.left {
AssignTarget::Simple(SimpleAssignTarget::Paren(paren)) => paren.expr.as_member(),
AssignTarget::Simple(SimpleAssignTarget::Member(member)) => Some(member),
_ => None,
};
if let Some(member) = target {
let access = if assignment.op == AssignOp::Assign {
Access::Assign
} else {
Access::Update
};
if let Some(object) = member.obj.as_ident()
&& mentions_this(&assignment.right)
{
self.uses(object).this = true;
}
self.member(member, access);
} else if assignment.op == AssignOp::Assign
&& let Some(target) = assignment.left.as_ident()
{
if self.assignment(&target.id, &assignment.right) {
return;
}
} else {
assignment.left.visit_with(self);
}
assignment.right.visit_with(self);
}
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if let Pat::Ident(name) = &declarator.name
&& let Some(init) = &declarator.init
&& self.assignment(&name.id, init)
{
return;
}
declarator.visit_children_with(self);
}
fn visit_update_expr(&mut self, update: &UpdateExpr) {
match &*update.arg {
Expr::Member(member) => self.member(member, Access::Update),
argument => argument.visit_with(self),
}
}
fn visit_unary_expr(&mut self, unary: &UnaryExpr) {
match &*unary.arg {
Expr::Member(member) if unary.op == UnaryOp::Delete => {
self.member(member, Access::Delete);
}
argument => argument.visit_with(self),
}
}
/// A member a destructuring pattern or a loop head writes.
fn visit_pat(&mut self, pattern: &Pat) {
match pattern {
Pat::Expr(target) if let Expr::Member(member) = &**target => {
self.member(member, Access::Pattern);
}
pattern => pattern.visit_children_with(self),
}
}
}
/// The index `[i]` reads, for a non-negative integer `i`.
#[must_use]
pub(crate) fn constant_index(property: &MemberProp) -> Option<usize> {
ast::index_literal(&property.as_computed()?.expr)
}
/// Identifies `__proto__`, which has special behavior: reads can invoke an inherited accessor,
/// assignments can change the prototype, and object-literal entries set the prototype.
const PROTO: &str = "__proto__";
/// Returns the own-property name in `object.name`, `object["name"]`, or ``object[`name`]``.
/// Rejects keys containing lone surrogates, since converting them to Rust strings would replace
/// them with U+FFFD and could match a different key.
#[must_use]
pub(crate) fn member_key(property: &MemberProp) -> Option<Atom> {
ast::member_str(property)
.filter(|name| *name != PROTO)
.map(Atom::from)
}
/// The own property an object-literal key defines (see [`member_key`]).
#[must_use]
pub(crate) fn prop_key(key: &PropName) -> Option<Atom> {
ast::key_str(key)
.filter(|name| *name != PROTO)
.map(Atom::from)
}
/// Checks for `this` anywhere in `node`, including nested functions. A method mentioning it may
/// observe or change its receiver.
fn mentions_this<N: VisitWith<This>>(node: &N) -> bool {
let mut this = This(false);
node.visit_with(&mut this);
this.0
}
struct This(bool);
impl Visit for This {
fn visit_this_expr(&mut self, _: &ThisExpr) {
self.0 = true;
}
}
#[cfg(test)]
mod tests {
use swc_core::atoms::Atom;
use swc_core::ecma::ast::{Expr, MemberProp, Program, PropName};
use super::{Properties, member_key, prop_key};
use crate::deobfuscate::analysis::Bindings;
use crate::deobfuscate::testing;
use crate::js::ast;
fn properties(program: &Program) -> Properties {
Properties::collect(program, &Bindings::collect(program))
}
fn member(source: &str) -> MemberProp {
match ast::parse_expression("member", source).unwrap() {
Expr::Member(member) => member.prop,
other => panic!("{source} is {other:?}"),
}
}
fn key(source: &str) -> PropName {
let Expr::Object(object) = ast::parse_expression("object", source).unwrap() else {
panic!("{source} is not an object");
};
let property = object.props[0].as_prop().unwrap();
property.as_key_value().unwrap().key.clone()
}
#[test]
fn resolves_static_keys() {
for source in ["o.name", "o['name']", "o[`name`]", r#"o["n\x61me"]"#] {
assert_eq!(
member_key(&member(source)).as_deref(),
Some("name"),
"{source}"
);
}
assert_eq!(prop_key(&key("{ 'name': 1 }")).as_deref(), Some("name"));
assert_eq!(prop_key(&key("{ name: 1 }")).as_deref(), Some("name"));
// Dynamic, prototype, and lone-surrogate names have no key.
for source in [
"o[k]",
"o[0]",
"o[`${k}`]",
"o.__proto__",
"o['__proto__']",
r#"o["\uD800"]"#,
r#"o["\uDC00"]"#,
] {
assert_eq!(member_key(&member(source)), None, "{source}");
}
for source in [
"{ __proto__: 1 }",
"{ '__proto__': 1 }",
"{ 0: 1 }",
"{ [k]: 1 }",
] {
assert_eq!(prop_key(&key(source)), None, "{source}");
}
assert_eq!(
prop_key(&key(r#"{ "\uD800": 1 }"#)),
None,
"two different lone surrogates must not become the same key"
);
}
#[test]
fn counts_definitions_through_aliases() {
testing::check(
"function f(h, p, q, o) {
h = { a: 1, b: function () {} }; p = h; var q = p;
q.c = 2; p.a += 1; h.b(); o = { d: 1 }; o.d++;
return [q.a, p.c];
}",
|program, id| {
let properties = properties(program);
assert!(!properties.is_opaque(&id("q")));
assert!(!properties.is_stable(&id("h"), &"a".into()));
assert!(properties.is_stable(&id("q"), &"b".into()));
assert!(properties.is_stable(&id("h"), &"c".into()));
assert!(!properties.is_stable(&id("o"), &"d".into()));
let object = properties.object(&id("p"));
for key in ["a", "b", "c"] {
assert!(object.accessed.contains(&Atom::from(key)), "{key}");
}
assert!(properties.binding(&id("q")).written_through);
assert!(!properties.binding(&id("h")).written_through);
},
);
}
#[test]
fn makes_objects_opaque() {
for (source, opaque) in [
("h = {}; use(h);", true),
("h = {}; use({ h });", true),
("h = {}; h[k] = 1;", true),
("h = {}; h[0];", true),
("h = {}; h.__proto__;", true),
("h = { __proto__: p };", true),
("h = { [k]: 1 };", true),
("h = {}; delete h.a;", true),
("h = {}; h.hasOwnProperty('a');", true),
("h = {}; (h.hasOwnProperty)('a');", true),
("h = {}; h?.hasOwnProperty('a');", true),
("h = { m: function () { return this; } };", true),
("h = {}; h.m = function () { return this; };", true),
("h = {}; p = h; p = 2; h.a;", true),
(
"h = { m: function () {} }; h.m(); h.a = 1; [h.b] = [1]; h.c;",
false,
),
] {
testing::check(
&format!("function f(h, p, k) {{ {source} }}"),
|program, id| {
assert_eq!(properties(program).is_opaque(&id("h")), opaque, "{source}");
},
);
}
}
#[test]
fn tells_constant_index_reads_from_other_uses() {
for (source, only_indexed) in [
("f = [a]; f[0] + f[3];", true),
("f = [a]; f[0]();", false),
("f = [a]; f[0] = 1;", false),
("f = [a]; f[0]++;", false),
("f = [a]; delete f[0];", false),
("f = [a]; [f[0]] = [1];", false),
("f = [a]; for (f[0] of [1]);", false),
("f = [a]; f.length;", false),
("f = [a]; f[i];", false),
("f = [a]; use({ f });", false),
] {
testing::check(
&format!("function g(a, f, i) {{ {source} }}"),
|program, id| {
assert_eq!(
properties(program).binding(&id("f")).is_only_indexed(),
only_indexed,
"{source}"
);
},
);
}
}
}
+127
View File
@@ -0,0 +1,127 @@
//! Replaces reads from scratch argument arrays with their elements:
//!
//! ```js
//! function (a, b) { var f; f = [a, b]; return f[1] ^ f[0]; } // return b ^ a
//! ```
//!
//! Requires a single array assignment and reads at constant indices only (see
//! [`Properties`](super::analysis::Properties)). Elements must be literals or bindings
//! unchanged by assignments or `arguments`. Excludes globals because repeated reads could throw
//! or invoke getters.
use swc_core::ecma::ast::{ArrayLit, Expr, Id, Program};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::{self, Analysis, Globals, effects};
use super::{HashMap, removal};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let globals = analysis.globals;
let (bindings, properties) = analysis.properties(program);
let mut packed = Packed::default();
program.visit_with(&mut packed);
// An element reads the same value wherever the array is indexed.
let is_fixed = |element: &Expr| match element {
Expr::Ident(identifier) => {
bindings.write_count(&identifier.to_id()) == 0
&& !bindings.is_mapped_parameter(&identifier.to_id())
&& !effects::may_have_effects(element, globals)
}
_ => true,
};
packed.0.retain(|id, elements| {
bindings.is_written_once(id)
&& properties.binding(id).is_only_indexed()
&& elements.iter().all(is_fixed)
});
if packed.0.is_empty() {
return false;
}
let mut unpack = UnpackArguments {
arrays: &packed.0,
globals,
changed: false,
};
program.visit_mut_with(&mut unpack);
let changed = unpack.changed;
let removed = removal::remove_definitions(program, &packed.0.into_keys().collect());
changed || removed
}
/// Bindings assigned an array of identifiers and literals, with its elements.
#[derive(Default)]
struct Packed(HashMap<Id, Vec<Expr>>);
impl Visit for Packed {
fn visit_expr(&mut self, expression: &Expr) {
if let Some((target, Expr::Array(array))) = ast::assignment(expression)
&& let Some(elements) = packed_elements(array)
{
self.0.insert(target, elements);
}
expression.visit_children_with(self);
}
}
/// Returns array elements only if all are identifiers or literals, with no holes or spreads.
fn packed_elements(array: &ArrayLit) -> Option<Vec<Expr>> {
array
.elems
.iter()
.map(|element| {
let element = element
.as_ref()
.filter(|element| element.spread.is_none())?;
matches!(*element.expr, Expr::Ident(_) | Expr::Lit(_)).then(|| *element.expr.clone())
})
.collect()
}
struct UnpackArguments<'arrays> {
arrays: &'arrays HashMap<Id, Vec<Expr>>,
globals: Globals,
changed: bool,
}
impl VisitMut for UnpackArguments<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Member(member) = expression
&& let Some(array) = member.obj.as_ident()
&& let Some(index) = analysis::constant_index(&member.prop)
&& let Some(elements) = self.arrays.get(&array.to_id())
{
self.changed = true;
// Out-of-bounds array reads produce `undefined`. Give the replacement the original
// read's source position, which JavaScript engines use in call stack traces.
*expression = elements
.get(index)
.map(|element| element.clone().with_span(member.span))
.unwrap_or_else(|| Expr::Ident(self.globals.reference("undefined", member.span)));
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn unpacks_arrays_that_neither_change_nor_escape() {
let unpack = |source: &str| testing::rewrite(source, super::run, /* fix= */ false);
let output = unpack(
"g = function (a, b) { var f; f = [a, b, 3]; return f[1] ^ f[0] + f[2] + f[5]; };",
);
assert!(output.contains("return b ^ a + 3 + undefined;"), "{output}");
assert!(!output.contains("f = ["), "{output}");
for source in [
"g = function (a) { var f; f = [a]; f[0] = 2; return f[0]; };",
"g = function (a) { var f; f = [a]; a = 2; return f[0]; };",
"g = function (a) { var f; f = [a]; f = [1]; return f[0]; };",
] {
let output = unpack(source);
assert!(output.contains("f = ["), "{output}");
}
}
}
+105
View File
@@ -0,0 +1,105 @@
//! Removes fractional parts from bitwise operands:
//!
//! ```js
//! x & 255.51; // becomes x & 255
//! ```
//!
//! Applies only to operators whose `ToInt32` or `ToUint32` conversion discards the fractional
//! part before evaluation.
use swc_core::ecma::ast::{AssignExpr, BinExpr, BinaryOp, Expr, Lit, Program, UnaryExpr, UnaryOp};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::Analysis;
pub(super) fn run(program: &mut Program, _: &mut Analysis) -> bool {
let mut truncate = TruncateOperands { changed: false };
program.visit_mut_with(&mut truncate);
truncate.changed
}
struct TruncateOperands {
changed: bool,
}
impl VisitMut for TruncateOperands {
fn visit_mut_bin_expr(&mut self, binary: &mut BinExpr) {
binary.visit_mut_children_with(self);
if is_bitwise(binary.op) {
self.changed |= truncate_operand(&mut binary.left);
self.changed |= truncate_operand(&mut binary.right);
}
}
fn visit_mut_assign_expr(&mut self, assignment: &mut AssignExpr) {
assignment.visit_mut_children_with(self);
if assignment.op.to_update().is_some_and(is_bitwise) {
self.changed |= truncate_operand(&mut assignment.right);
}
}
fn visit_mut_unary_expr(&mut self, unary: &mut UnaryExpr) {
unary.visit_mut_children_with(self);
if unary.op == UnaryOp::Tilde {
self.changed |= truncate_operand(&mut unary.arg);
}
}
}
pub(super) fn is_bitwise(operator: BinaryOp) -> bool {
matches!(
operator,
BinaryOp::BitAnd
| BinaryOp::BitOr
| BinaryOp::BitXor
| BinaryOp::LShift
| BinaryOp::RShift
| BinaryOp::ZeroFillRShift
)
}
/// Returns whether a fractional part was removed.
fn truncate_operand(operand: &mut Expr) -> bool {
match operand {
Expr::Lit(Lit::Num(number)) if number.value.is_finite() && number.value.fract() != 0.0 => {
number.value = number.value.trunc();
number.raw = None;
true
}
Expr::Paren(paren) => truncate_operand(&mut paren.expr),
Expr::Unary(unary) if matches!(unary.op, UnaryOp::Plus | UnaryOp::Minus) => {
truncate_operand(&mut unary.arg)
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn truncates_only_bitwise_operands() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(
"function f(x) { return (x & 255.51) ^ (x | 8.27) ^ (x ^ 60.71) ^ (x << 16.7) ^ (x >> 12.15) ^ (x >>> 10.46); }",
);
let expected = [
"x & 255", "x | 8", "x ^ 60", "x << 16", "x >> 12", "x >>> 10",
];
testing::assert_contains(&output, &expected, &[]);
assert!(!output.contains('.'), "{output}");
assert_eq!(transform(&output), output);
// Compound assignments, negated operands, and complements.
let output =
transform("function f(x) { x &= 63.01; x >>>= 3.94; y = x & -3.7; z = ~9.5; }");
testing::assert_contains(&output, &["x &= 63", "x >>>= 3", "x & -3", "~9"], &[]);
let output =
transform("function f(x) { return [x & 255, x + 255.51, x * 1.5, 0.5, x(23.5)]; }");
let kept = ["x & 255", "x + 255.51", "x * 1.5", "0.5", "x(23.5)"];
testing::assert_contains(&output, &kept, &[]);
}
}
+69
View File
@@ -0,0 +1,69 @@
//! Flattens blocks used only to group statements:
//!
//! ```js
//! { a(); { b(); } } // becomes a(); b();
//! ```
//!
//! Only flattens blocks directly inside a statement list and without scoped declarations. Keeps
//! blocks containing string statements created by [`super::statements`], since unwrapping them
//! could introduce directives.
use std::mem;
use swc_core::ecma::ast::{BlockStmt, Decl, Expr, Lit, Program, Stmt, VarDeclKind};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::Analysis;
pub(super) fn run(program: &mut Program, _: &mut Analysis) -> bool {
let mut flatten = FlattenBlocks { changed: false };
program.visit_mut_with(&mut flatten);
flatten.changed
}
struct FlattenBlocks {
changed: bool,
}
impl VisitMut for FlattenBlocks {
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.visit_mut_children_with(self);
let mut flattened = Vec::with_capacity(statements.len());
for statement in mem::take(statements) {
match statement {
Stmt::Block(block) if is_transparent(&block) => {
flattened.extend(block.stmts);
self.changed = true;
}
statement => flattened.push(statement),
}
}
*statements = flattened;
}
}
fn is_transparent(block: &BlockStmt) -> bool {
block.stmts.iter().all(|statement| match statement {
// Moving a function-scoped `var` out of this block preserves its scope.
Stmt::Decl(Decl::Var(declaration)) => declaration.kind == VarDeclKind::Var,
Stmt::Decl(_) => false,
Stmt::Expr(statement) => !matches!(&*statement.expr, Expr::Lit(Lit::Str(_))),
_ => true,
})
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn flattens_only_grouping_blocks_in_statement_lists() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ false);
let output = transform("function f() { { a(); { b(); } } var c; { var d = 1; } }");
testing::assert_contains(&output, &["var d = 1;"], &["a(); b();"]);
assert_eq!(output.matches('{').count(), 1, "{output}");
let output =
transform("function f() { { let a = 1; use(a); } if (a) { b(); } while (c) { d(); } }");
testing::assert_contains(&output, &["if (a) {", "while(c){"], &["{ let a = 1;"]);
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Replaces numeric properties used to obscure string-array indices:
//!
//! ```js
//! map = { a: 2192 }; decode(map.a); // becomes decode(2192)
//! ```
//!
//! Requires one object assignment and stable literal properties (see
//! [`Properties::is_stable`]), and removes definitions once all reads are replaced. Hoisted
//! function bodies use only definitions available wherever they can be called (see
//! [`hoisting`]).
use swc_core::atoms::Atom;
use swc_core::ecma::ast::{
AssignExpr, AssignOp, Expr, Function, Id, Ident, Lit, Number, Program, Stmt,
};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::hoisting::{self, Hoisted, Hoisting};
use super::analysis::{self, Analysis, Bindings, Properties};
use super::{HashMap, removal};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let (bindings, properties) = analysis.properties(program);
let mut inline = InlineConstantObjects {
bindings,
properties,
hoisting: Hoisting::default(),
replaced: HashMap::default(),
changed: false,
};
program.visit_mut_with(&mut inline);
// Keep the object if a read precedes its definition or accesses a missing property.
let unread = removal::unread(&inline.replaced, bindings);
let removed = removal::remove_definitions(program, &unread);
inline.changed || removed
}
struct InlineConstantObjects<'analysis> {
bindings: &'analysis Bindings,
properties: &'analysis Properties,
/// Tracks objects and properties defined before the current node.
hoisting: Hoisting<HashMap<Id, HashMap<Atom, Number>>>,
/// How many reads of each object were replaced.
replaced: HashMap<Id, usize>,
changed: bool,
}
impl VisitMut for InlineConstantObjects<'_> {
fn visit_mut_assign_expr(&mut self, assignment: &mut AssignExpr) {
assignment.visit_mut_children_with(self);
if assignment.op == AssignOp::Assign
&& let Some(identifier) = assignment.left.as_ident()
&& self.bindings.is_written_once(&identifier.to_id())
&& let Some(object) = assignment.right.as_object()
{
let values: Option<HashMap<Atom, Number>> = object
.props
.iter()
.map(|property| {
let property = ast::key_value(property)?;
let value = property.value.as_lit()?.as_num()?;
Some((analysis::prop_key(&property.key)?, value.clone()))
})
.collect();
if let Some(values) = values.filter(|values| !values.is_empty()) {
self.replaced.insert(identifier.to_id(), 0);
self.hoisting.facts.insert(identifier.to_id(), values);
}
}
}
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Member(member) = expression
&& let Some(identifier) = member.obj.as_ident()
&& let Some(values) = self.hoisting.facts.get(&identifier.to_id())
&& let Some(name) = analysis::member_key(&member.prop)
&& let Some(value) = values.get(&name)
&& self.properties.is_stable(&identifier.to_id(), &name)
{
*self.replaced.entry(identifier.to_id()).or_default() += 1;
*expression = Expr::Lit(Lit::Num(value.clone()));
self.changed = true;
}
}
/// Visit function declarations last, using definitions available at every possible call.
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
hoisting::visit_mut_stmts(self, statements, |inline, statement| {
statement.visit_mut_with(inline);
});
}
fn visit_mut_function(&mut self, function: &mut Function) {
hoisting::visit_mut_function(self, function);
}
fn visit_mut_ident(&mut self, identifier: &mut Ident) {
hoisting::reference(self, identifier);
}
}
impl Hoisted for InlineConstantObjects<'_> {
type Facts = HashMap<Id, HashMap<Atom, Number>>;
fn hoisting(&mut self) -> &mut Hoisting<Self::Facts> {
&mut self.hoisting
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn inlines_single_write_objects_and_removes_unread_ones() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(
"function f(m, out) { m = { A: 10, K: 20 }; out = [decode(m.A), decode(m.K)]; \
return out; }",
);
testing::assert_contains(&output, &["decode(10)", "decode(20)"], &[]);
testing::assert_lacks(&output, &["m = {", "m.A"]);
let output = transform(
"function f(m, n, g) { g = function () { return n.A; }; m = { A: 10 }; \
n = { A: 1 }; return [m['A'], m.A, n.A, n.B, g()]; }",
);
testing::assert_contains(&output, &[], &["10, 10,"]);
assert!(!output.contains("m = {"), "{output}");
assert!(
output.contains("n = {"),
"`g` and `n.B` still read the object: {output}"
);
assert!(
output.contains("return n.A;"),
"`g` reads `n` before the traversal reaches its definition: {output}"
);
assert!(
output.contains("n.B"),
"`n.B` names a property the object does not have: {output}"
);
}
#[test]
fn preserves_reassigned_escaping_and_updated_objects() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(
"function f(m, out) { m = { A: 10, K: 20 }; out = [m.A, m.K]; m = 5; \
out.push(m); m = { A: 1 }; out.push(m.A); return out; }",
);
testing::assert_contains(&output, &["m = {", "m = 5;", "out.push(m);", "m.A"], &[]);
assert!(!output.contains("out.push(1)"), "{output}");
for source in [
"function f(m) { m = { A: 10 }; use(m); return m.A; }",
"function f(m) { m = { A: 10 }; m.A = 3; return m.A; }",
] {
testing::assert_contains(&transform(source), &["m = {", "m.A"], &[]);
}
}
}
+438
View File
@@ -0,0 +1,438 @@
//! Restores flattened switch cases to execution order and removes the dispatcher loop. Handles
//! a `for` dispatcher or its normalized assignments-plus-`while` form:
//!
//! ```js
//! for (order = "b|a".split("|"), cursor = 0; true;) { switch (order[cursor++]) { ... } break; }
//! order = "b|a".split("|"); cursor = 0; while (true) { switch (order[cursor++]) { ... } break; }
//! ```
//!
//! Removes order and cursor assignments only if they are used solely by the dispatcher or never
//! mentioned after the loop in the same statement list.
use swc_core::atoms::Atom;
use swc_core::common::{Span, SyntaxContext};
use swc_core::ecma::ast::{
ArrowExpr, BlockStmt, BreakStmt, Class, ContinueStmt, Expr, ForStmt, Function, Id, LabeledStmt,
Lit, MemberProp, Program, Stmt, SwitchCase, SwitchStmt, UpdateOp, VarDeclOrExpr,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::{Analysis, Bindings, names};
use super::{HashMap, HashSet};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let mut unflatten = UnflattenSwitches {
bindings: analysis.bindings(program),
changed: false,
};
program.visit_mut_with(&mut unflatten);
unflatten.changed
}
struct UnflattenSwitches<'bindings> {
bindings: &'bindings Bindings,
changed: bool,
}
impl UnflattenSwitches<'_> {
/// Checks whether dispatcher setup for `bindings` must be preserved because later
/// statements may use it.
fn keeps_setup(&self, bindings: &[Id; 2], after: Option<&[Stmt]>) -> bool {
bindings.iter().any(|id| self.bindings.references(id) > 1)
&& after.is_none_or(|after| names::mentions(after, bindings))
}
/// Expands a `for` dispatcher in execution order. Preserves leading initializer
/// expressions and, if [`Self::keeps_setup`], the order and cursor assignments.
fn unflatten_for(&self, for_statement: &ForStmt, after: Option<&[Stmt]>) -> Option<Stmt> {
if is_true(for_statement.test.as_deref())
&& for_statement.update.is_none()
&& let Some(VarDeclOrExpr::Expr(initializer)) = &for_statement.init
&& let Expr::Seq(initializer) = &**initializer
&& let [prefix @ .., array_assignment, index_assignment] = initializer.exprs.as_slice()
&& let Some(order) = split_order(array_assignment)
&& let Some(index) = zero_index(index_assignment)
&& let Some(dispatcher) = Dispatcher::of(&for_statement.body)
&& dispatcher.array == order.array
&& dispatcher.index == index
{
let prefix = if self.keeps_setup(&dispatcher.bindings(), after) {
&initializer.exprs[..]
} else {
prefix
};
flattened(&dispatcher, &order, prefix, for_statement.span)
} else {
None
}
}
}
impl VisitMut for UnflattenSwitches<'_> {
/// A `for` dispatcher used directly as another statement's body has no following statement
/// list to check.
fn visit_mut_stmt(&mut self, statement: &mut Stmt) {
statement.visit_mut_children_with(self);
if let Stmt::For(for_statement) = statement
&& let Some(inlined) = self.unflatten_for(for_statement, None)
{
*statement = inlined;
self.changed = true;
}
}
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
// Unflatten statements below, where subsequent statements are available for analysis.
for statement in statements.iter_mut() {
statement.visit_mut_children_with(self);
}
let mut position = 0;
while position < statements.len() {
if let Stmt::For(for_statement) = &statements[position]
&& let Some(inlined) =
self.unflatten_for(for_statement, Some(&statements[position + 1..]))
{
statements[position] = inlined;
self.changed = true;
} else if let Stmt::While(loop_) = &statements[position]
&& is_true(Some(&loop_.test))
&& let Some(dispatcher) = Dispatcher::of(&loop_.body)
&& let Some(setup) = Setup::find(&statements[..position], &dispatcher)
&& let Some(inlined) = flattened(&dispatcher, &setup.order, &[], loop_.span)
{
let bindings = dispatcher.bindings();
statements[position] = inlined;
self.changed = true;
// The setup only fed the loop, unless something after it reads the order or the
// cursor.
if !self.keeps_setup(&bindings, Some(&statements[position + 1..])) {
for index in setup.statements {
statements.remove(index);
}
position -= setup.statements.len();
}
}
position += 1;
}
}
}
/// Finds `order = "...".split(...)` and `cursor = 0` by scanning backward from a `while`
/// dispatcher. Stops at any other reference to either binding.
struct Setup {
order: SplitOrder,
/// Positions of the two setup statements, last first.
statements: [usize; 2],
}
impl Setup {
fn find(preceding: &[Stmt], dispatcher: &Dispatcher) -> Option<Self> {
let bindings = dispatcher.bindings();
let mut order = None;
let mut cursor = None;
let backwards = preceding.iter().enumerate().rev();
for (position, statement) in backwards {
if let Stmt::Expr(statement) = statement
&& order.is_none()
&& let Some(split) = split_order(&statement.expr)
&& split.array == dispatcher.array
{
order = Some((split, position));
} else if let Stmt::Expr(statement) = statement
&& cursor.is_none()
&& zero_index(&statement.expr).is_some_and(|index| index == dispatcher.index)
{
cursor = Some(position);
} else if names::mentions(statement, &bindings) {
return None;
}
if let Some(cursor) = cursor
&& let Some((order, order_position)) = order.take()
{
return Some(Self {
order,
statements: [cursor.max(order_position), cursor.min(order_position)],
});
}
}
None
}
}
fn is_true(test: Option<&Expr>) -> bool {
matches!(test, Some(Expr::Lit(Lit::Bool(value))) if value.value)
}
/// `array = "b|a".split("|")`: the case labels in execution order and their separator.
struct SplitOrder {
array: Id,
order: String,
separator: String,
}
fn split_order(expression: &Expr) -> Option<SplitOrder> {
if let Some((array, value)) = ast::assignment(expression)
&& let Some((order, [separator])) = ast::method_call(value, "split")
&& separator.spread.is_none()
&& let Some(order) = ast::static_str(order)
&& let Some(separator) = ast::static_str(&separator.expr)
&& !separator.is_empty()
{
Some(SplitOrder {
array,
order: order.to_owned(),
separator: separator.to_owned(),
})
} else {
None
}
}
/// `cursor = 0`: the cursor binding.
fn zero_index(expression: &Expr) -> Option<Id> {
let (index, value) = ast::assignment(expression)?;
matches!(value, Expr::Lit(Lit::Num(value)) if value.value == 0.0).then_some(index)
}
/// A loop body `{ switch (order[cursor++]) { ... } break; }`.
struct Dispatcher<'body> {
switch: &'body SwitchStmt,
/// The syntax context of the loop body.
context: SyntaxContext,
array: Id,
index: Id,
}
impl<'body> Dispatcher<'body> {
fn of(body: &'body Stmt) -> Option<Self> {
if let Stmt::Block(body) = body
&& let [Stmt::Switch(switch), Stmt::Break(break_statement)] = body.stmts.as_slice()
&& break_statement.label.is_none()
&& let Expr::Member(discriminant) = &*switch.discriminant
&& let Some(array) = discriminant.obj.as_ident()
&& let MemberProp::Computed(property) = &discriminant.prop
&& let Expr::Update(increment) = &*property.expr
&& increment.op == UpdateOp::PlusPlus
&& !increment.prefix
&& let Some(index) = increment.arg.as_ident()
{
Some(Self {
switch,
context: body.ctxt,
array: array.to_id(),
index: index.to_id(),
})
} else {
None
}
}
fn bindings(&self) -> [Id; 2] {
[self.array.clone(), self.index.clone()]
}
}
/// Orders case bodies after the leading loop initializer expressions. Returns `None` for
/// unsupported cases and missing or unused labels.
fn flattened(
dispatcher: &Dispatcher,
order: &SplitOrder,
prefix: &[Box<Expr>],
span: Span,
) -> Option<Stmt> {
let mut cases = case_bodies(&dispatcher.switch.cases, &dispatcher.bindings())?;
let mut statements: Vec<Stmt> = prefix
.iter()
.map(|expression| ast::expression_statement(expression.clone()))
.collect();
for label in order.order.split(&order.separator) {
statements.extend(cases.remove(label)?);
}
cases.is_empty().then(|| {
Stmt::Block(BlockStmt {
span,
ctxt: dispatcher.context,
stmts: statements,
})
})
}
/// Maps case labels to their bodies. Each body must continue the dispatcher or exit execution
/// so the bodies can be concatenated. Rejects other jumps to the switch or dispatcher loop,
/// since those targets will be removed. Also rejects bodies that read the order or cursor,
/// whose values depend on the loop.
fn case_bodies(cases: &[SwitchCase], bindings: &[Id; 2]) -> Option<HashMap<String, Vec<Stmt>>> {
if cases
.iter()
.any(|case| names::mentions(&case.cons, bindings))
{
return None;
}
let mut bodies = HashMap::default();
for case in cases {
let label = case.test.as_deref().and_then(ast::static_str)?.to_owned();
let mut statements = case.cons.clone();
let continues_loop = matches!(
statements.last(),
Some(Stmt::Continue(continue_statement)) if continue_statement.label.is_none()
);
if continues_loop {
statements.pop();
} else if !matches!(statements.last(), Some(Stmt::Return(_) | Stmt::Throw(_))) {
return None;
}
let mut jumps = Jumps::default();
statements.visit_with(&mut jumps);
if jumps.leaves {
return None;
}
bodies.insert(label, statements);
}
Some(bodies)
}
/// Detects jumps from case statements to enclosing constructs: unlabeled `break` or
/// `continue` without an internal target, or `continue` to an external label. Labeled `break`
/// remains valid because its target still encloses the expanded cases.
#[derive(Default)]
struct Jumps {
/// Loops around the node, within the case.
loops: usize,
/// Loops and `switch` statements around the node, within the case.
breakable: usize,
/// Labels declared around the node, within the case.
labels: HashSet<Atom>,
leaves: bool,
}
impl Visit for Jumps {
fn visit_stmt(&mut self, statement: &Stmt) {
let depth = usize::from(matches!(
statement,
Stmt::For(_) | Stmt::ForIn(_) | Stmt::ForOf(_) | Stmt::While(_) | Stmt::DoWhile(_)
));
self.loops += depth;
self.breakable += depth;
statement.visit_children_with(self);
self.loops -= depth;
self.breakable -= depth;
}
fn visit_break_stmt(&mut self, jump: &BreakStmt) {
self.leaves |= jump.label.is_none() && self.breakable == 0;
}
fn visit_continue_stmt(&mut self, jump: &ContinueStmt) {
self.leaves |= match &jump.label {
Some(label) => !self.labels.contains(&label.sym),
None => self.loops == 0,
};
}
fn visit_labeled_stmt(&mut self, labeled: &LabeledStmt) {
let added = self.labels.insert(labeled.label.sym.clone());
labeled.body.visit_with(self);
if added {
self.labels.remove(&labeled.label.sym);
}
}
fn visit_switch_stmt(&mut self, switch: &SwitchStmt) {
switch.discriminant.visit_with(self);
self.breakable += 1;
switch.cases.visit_with(self);
self.breakable -= 1;
}
// Functions and classes have jump targets of their own.
fn visit_function(&mut self, _: &Function) {}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
fn visit_class(&mut self, _: &Class) {}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
fn fixture(separator: &str) -> String {
format!(
r#"(function (order, cursor) {{
for (order = "second{separator}first".split(`{separator}`), cursor = 0; true;) {{
switch (order[cursor++]) {{
case "first": console.log("first"); continue;
case "second": console.log("second"); continue;
}}
break;
}}
}})();"#
)
}
#[test]
fn unflattens_for_and_while_dispatchers_in_execution_order() {
let while_loop = r#"(function (order, cursor) {
order = "second|first".split("|");
unrelated();
cursor = 0;
true;
while (true) {
switch (order[cursor++]) {
case "first": console.log("first"); continue;
case "second": console.log("second"); continue;
}
break;
}
})();"#;
let output = testing::transform(while_loop);
assert!(!output.contains("split"), "{output}");
assert!(output.contains("unrelated()"), "{output}");
for source in [
fixture("|"),
fixture(";"),
fixture("::"),
while_loop.to_owned(),
] {
let output = testing::transform(&source);
assert!(!output.contains("switch"), "{output}");
assert!(
output.find("console.log(\"second\")").unwrap()
< output.find("console.log(\"first\")").unwrap(),
"{output}"
);
}
}
#[test]
fn keeps_setups_read_later_and_loops_it_cannot_unflatten() {
// Jumps that stay inside a case do not prevent unflattening.
let output = testing::transform(&format!(
"{} function g() {{ return 1; }}",
fixture("|")
.replace(
"console.log(\"first\");",
"for (;;) { if (g()) break; else continue; } console.log(\"first\");",
)
.replace(
"break;\n }",
"break;\n }\n console.log(order);"
)
));
assert!(!output.contains("switch"), "{output}");
assert!(output.contains("split"), "{output}");
for source in [
fixture("|").replace("order[cursor++]", "different[cursor++]"),
fixture("|").replace("order[cursor++]", "order[++cursor]"),
fixture("|").replace("order[cursor++]", "order[other++]"),
fixture("|").replace("true;", "true; effect()"),
fixture("|").replace(".split(`|`)", ".split(`|`, 1)"),
] {
let output = testing::transform(&source);
assert!(output.contains("switch"), "{output}");
}
}
}
+221
View File
@@ -0,0 +1,221 @@
//! Replaces scratch copies with their assigned values:
//!
//! ```js
//! flag = true; listen(handler, flag); // becomes listen(handler, true)
//! ```
//!
//! Requires exactly one assignment and proof that it ran before each replaced read. This
//! includes later statements in the same list and hoisted functions callable only after the
//! assignment (see [`hoisting`]). Removes assignments once no reads remain.
use std::rc::Rc;
use swc_core::ecma::ast::{AssignOp, Decl, Expr, Function, Id, Ident, Lit, Program, Stmt};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::hoisting::{self, Hoisted, Hoisting};
use super::analysis::{Analysis, Bindings};
use super::{HashMap, HashSet, removal};
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let bindings = analysis.bindings(program);
let mut propagate = PropagateCopies {
bindings,
hoisting: Hoisting::default(),
functions: HashSet::default(),
substituted: HashMap::default(),
changed: false,
};
program.visit_mut_with(&mut propagate);
let unread = removal::unread(&propagate.substituted, bindings);
let removed = removal::remove_definitions(program, &unread);
propagate.changed || removed
}
struct PropagateCopies<'bindings> {
bindings: &'bindings Bindings,
/// Bindings with exactly one assignment that has run on every path to this node. Includes
/// replacement values when known. Shares storage with declaration snapshots until changed.
hoisting: Hoisting<Rc<HashMap<Id, Option<Expr>>>>,
/// Single-write function declarations, which hold their value from the start of their
/// scope.
functions: HashSet<Id>,
/// How many reads of each substitutable binding were substituted.
substituted: HashMap<Id, usize>,
changed: bool,
}
impl VisitMut for PropagateCopies<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Ident(identifier) = expression
&& let Some(Some(value)) = self.hoisting.facts.get(&identifier.to_id())
{
*self.substituted.entry(identifier.to_id()).or_default() += 1;
*expression = value.clone();
self.changed = true;
}
}
/// Keep assignments known for the rest of their statement list. Visit function declarations
/// last with facts valid at every possible call; discard list-local facts afterward.
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
let outer = self.hoisting.facts.clone();
for statement in statements.iter() {
if let Stmt::Decl(Decl::Fn(declaration)) = statement
&& self.bindings.is_written_once(&declaration.ident.to_id())
{
self.functions.insert(declaration.ident.to_id());
}
}
hoisting::visit_mut_stmts(self, statements, |propagate, statement| match statement {
Stmt::Expr(statement) => propagate.statement_expression(&mut statement.expr),
Stmt::Decl(Decl::Var(declaration)) => {
for declarator in &mut declaration.decls {
declarator.init.visit_mut_with(propagate);
if let Some(target) = declarator.name.as_ident()
&& let Some(value) = &declarator.init
{
propagate.record(target.to_id(), value);
}
}
}
Stmt::If(conditional) => {
propagate.statement_expression(&mut conditional.test);
conditional.cons.visit_mut_with(propagate);
conditional.alt.visit_mut_with(propagate);
}
statement => statement.visit_mut_with(propagate),
});
self.hoisting.facts = outer;
}
fn visit_mut_function(&mut self, function: &mut Function) {
hoisting::visit_mut_function(self, function);
}
fn visit_mut_ident(&mut self, identifier: &mut Ident) {
hoisting::reference(self, identifier);
}
}
impl Hoisted for PropagateCopies<'_> {
type Facts = Rc<HashMap<Id, Option<Expr>>>;
fn hoisting(&mut self) -> &mut Hoisting<Self::Facts> {
&mut self.hoisting
}
}
impl PropagateCopies<'_> {
/// Visits an expression that always runs with its statement. Records unconditional
/// assignments in sequences, assigned values, and the left operands of short-circuit
/// operators.
fn statement_expression(&mut self, expression: &mut Expr) {
match expression {
Expr::Paren(paren) => self.statement_expression(&mut paren.expr),
Expr::Seq(sequence) => {
for operand in &mut sequence.exprs {
self.statement_expression(operand);
}
}
Expr::Bin(binary) if binary.op.may_short_circuit() => {
self.statement_expression(&mut binary.left);
binary.right.visit_mut_with(self);
}
Expr::Assign(assignment) => {
assignment.left.visit_mut_with(self);
self.statement_expression(&mut assignment.right);
if assignment.op == AssignOp::Assign
&& let Some(target) = assignment.left.as_ident()
{
self.record(target.to_id(), &assignment.right);
}
}
expression => expression.visit_mut_with(self),
}
}
/// Records that `target` now holds `value`, if this is its only write.
fn record(&mut self, target: Id, value: &Expr) {
if !self.bindings.is_written_once(&target) || self.bindings.is_mapped_parameter(&target) {
return;
}
let value = self.is_stable(value).then(|| value.clone());
if value.is_some() {
self.substituted.entry(target.clone()).or_default();
}
Rc::make_mut(&mut self.hoisting.facts).insert(target, value);
}
/// Excludes regex literals, which have identity and state. A copied binding must already
/// hold its sole assigned value.
fn is_stable(&self, value: &Expr) -> bool {
match value {
Expr::Lit(literal) => !matches!(literal, Lit::Regex(_)),
Expr::Tpl(template) => template.exprs.is_empty(),
Expr::Ident(identifier) => {
let id = identifier.to_id();
self.hoisting.facts.contains_key(&id) || self.functions.contains(&id)
}
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn substitutes_copies_assigned_before_every_read() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform("function f(a, b, c) { a = {}; b = a; c = true; b.x = c; use(b); }");
testing::assert_contains(&output, &["a.x = true;", "use(a);"], &[]);
testing::assert_lacks(&output, &["b = a", "c = true"]);
// Declarations, and values assigned alongside others.
let output = transform(
"function f(a, b, c) { c = (a = 1, b = g, function () { return a; }); \
return b(c); function g() {} }",
);
testing::assert_contains(&output, &["return g(c);"], &["c = function() { return 1;"]);
// Values assigned where a condition always runs.
let output = transform(
"function f(a, b, c) { if ((a = `m`, c) && (b = 1, g())) { return; } x[a](b); }",
);
testing::assert_contains(&output, &["x[`m`](b);"], &[]);
testing::assert_lacks(&output, &["a = `m`"]);
// A read before the write keeps the binding.
let output = transform("function f(a) { use(a); a = 1; return a; }");
testing::assert_contains(&output, &["return 1;"], &["use(a); a = 1;"]);
}
#[test]
fn preserves_reads_the_assignment_may_not_precede() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
for (source, kept) in [
(
"function f(c, r) { if (c) { r = 1; } return r; }",
"return r;",
),
(
"function f(c, r) { if (c && (r = 1)) { g(); } return r; }",
"return r;",
),
(
"function f(a, b) { b = a; a = a.x; return b; }",
"return b;",
),
("function f(a) { a = 1; return { a }; }", "a = 1;"),
("function f(a) { a = 1; a = 2; return a; }", "return a;"),
(
"function f(a, b) { b = a; a = 1; a = 2; return b; }",
"return b;",
),
] {
let output = transform(source);
assert!(output.contains(kept), "{source}: {output}");
}
}
}
+116
View File
@@ -0,0 +1,116 @@
//! Removes unreachable or effect-free code:
//!
//! ```js
//! if (false) { undefined; } // removed
//! if (true) a(); else b(); // a();
//! true; // removed
//! ```
//!
//! Preserves branches containing declarations because `var` and function declarations may be
//! hoisted into the enclosing scope.
use swc_core::ecma::ast::{
ArrowExpr, Decl, EmptyStmt, Expr, Function, Lit, Program, Stmt, VarDecl, VarDeclKind,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith};
use super::analysis::Analysis;
use super::removal;
pub(super) fn run(program: &mut Program, _: &mut Analysis) -> bool {
let mut remove = RemoveDeadBranches { changed: false };
program.visit_mut_with(&mut remove);
remove.changed
}
struct RemoveDeadBranches {
changed: bool,
}
impl VisitMut for RemoveDeadBranches {
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.visit_mut_children_with(self);
self.changed |= removal::retain(statements, |statement| !is_inert(statement));
}
fn visit_mut_stmt(&mut self, statement: &mut Stmt) {
statement.visit_mut_children_with(self);
if let Stmt::If(conditional) = statement
&& let Expr::Lit(Lit::Bool(test)) = &*conditional.test
{
let (taken, dropped) = if test.value {
(Some(&*conditional.cons), conditional.alt.as_deref())
} else {
(conditional.alt.as_deref(), Some(&*conditional.cons))
};
if dropped.is_none_or(|dropped| !declares(dropped)) {
*statement = taken.cloned().unwrap_or(Stmt::Empty(EmptyStmt {
span: conditional.span,
}));
self.changed = true;
}
}
}
}
/// Checks whether a statement is empty or has no effects. Keeps string statements because they
/// may be directives.
fn is_inert(statement: &Stmt) -> bool {
match statement {
Stmt::Empty(_) => true,
Stmt::Expr(statement) => match &*statement.expr {
Expr::Lit(Lit::Bool(_) | Lit::Num(_) | Lit::Null(_)) => true,
Expr::Ident(id) => id.sym == "undefined",
_ => false,
},
_ => false,
}
}
fn declares(statement: &Stmt) -> bool {
use swc_core::ecma::visit::VisitWith;
let mut declarations = Declarations(false);
statement.visit_with(&mut declarations);
declarations.0
}
/// Checks whether a statement contains declarations hoisted into its enclosing scope.
struct Declarations(bool);
impl Visit for Declarations {
fn visit_decl(&mut self, declaration: &Decl) {
match declaration {
Decl::Fn(_) => self.0 = true,
Decl::Var(variables) => self.visit_var_decl(variables),
_ => {}
}
}
fn visit_var_decl(&mut self, declaration: &VarDecl) {
self.0 |= declaration.kind == VarDeclKind::Var;
}
// Nested function declarations stay within their own function scope.
fn visit_function(&mut self, _: &Function) {}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn removes_dead_code_but_not_hoisted_declarations() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ false);
let output = transform(
"function f() { if (false) { undefined; } true; 0; if (true) a(); else b(); if (false) c(); else { d(); } return g(); }",
);
testing::assert_lacks(&output, &["undefined", "true", "b()", "c()"]);
testing::assert_contains(&output, &["a();", "d();"], &[]);
let output = transform(
"function f() { if (false) { var x; } if (false) { function g() {} } return x; }",
);
testing::assert_contains(&output, &["var x", "function g"], &[]);
}
}
+335
View File
@@ -0,0 +1,335 @@
//! Removes unread helper-object properties:
//!
//! ```js
//! h = { keep: function (a) { return a; }, drop: function (a) { return a; } };
//! h.keep(1); // the drop entry goes
//! ```
//!
//! After [`super::helper_objects`] inlines calls, unused properties and their object or alias
//! assignments may remain. Removal requires a single-assignment object used only through static
//! keys (see [`Properties`]), with no reads of the property through any alias.
use swc_core::atoms::Atom;
use swc_core::ecma::ast::{
AssignExpr, AssignOp, AssignTarget, Expr, Id, Program, PropOrSpread, SeqExpr,
SimpleAssignTarget, Stmt,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::{self, Analysis, Bindings, Properties};
use super::{HashSet, removal};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let (bindings, properties) = analysis.properties(program);
let mut remove = RemoveDeadProperties {
bindings,
properties,
literals: HashSet::default(),
member_definitions: HashSet::default(),
poisoned: HashSet::default(),
changed: false,
};
program.visit_with(&mut remove);
program.visit_mut_with(&mut remove);
remove.changed
}
struct RemoveDeadProperties<'analysis> {
bindings: &'analysis Bindings,
properties: &'analysis Properties,
/// Bindings defined by `binding = { ... }`.
literals: HashSet<Id>,
/// The binding and property of each `binding.property = <Fn|Lit>`.
member_definitions: HashSet<(Id, Atom)>,
/// Roots of bindings with definitions that cannot be removed: unsupported property values
/// or assignments outside removable positions.
poisoned: HashSet<Id>,
changed: bool,
}
impl VisitMut for RemoveDeadProperties<'_> {
fn visit_mut_assign_expr(&mut self, assignment: &mut AssignExpr) {
assignment.visit_mut_children_with(self);
if let Expr::Object(object) = &mut *assignment.right
&& let Some(identifier) = assignment.left.as_ident()
&& self.is_dead_root(&identifier.to_id())
{
let root = identifier.to_id();
self.changed |= removal::retain(&mut object.props, |property| {
removable_key(property).is_none_or(|key| self.is_live(&root, &key))
});
}
}
/// Removes statements that are one dead assignment or a sequence of only dead assignments.
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.visit_mut_children_with(self);
self.changed |= removal::remove_expr_stmts(statements, |expression| match expression {
Expr::Seq(sequence) => sequence.exprs.iter().all(|item| self.is_dead_operand(item)),
expression => self.is_dead_operand(expression),
});
}
fn visit_mut_seq_expr(&mut self, sequence: &mut SeqExpr) {
sequence.visit_mut_children_with(self);
// The final sequence operand supplies its value. A later round removes the whole
// sequence if every operand is a dead assignment.
if sequence.exprs.len() > 1
&& sequence
.exprs
.iter()
.any(|expression| !self.is_dead_operand(expression))
{
self.changed |= removal::retain(&mut sequence.exprs, |expression| {
!self.is_dead_operand(expression)
});
}
}
}
impl RemoveDeadProperties<'_> {
/// Checks whether an object can be removed after its unread properties. Requires one
/// literal assignment and definitions in removable positions. Aliases must be used only for
/// static property access and must not expose the object as `this`.
fn is_dead_root(&self, identifier: &Id) -> bool {
let root = self.bindings.root(identifier);
self.bindings.is_written_once(&root)
&& self.literals.contains(&root)
&& !self.poisoned.contains(&root)
&& !self.properties.is_opaque(&root)
}
/// Whether `property` is read through `root` or one of its aliases.
fn is_live(&self, root: &Id, property: &Atom) -> bool {
self.properties.object(root).accessed.contains(property)
}
fn is_dead_operand(&self, expression: &Expr) -> bool {
let Expr::Assign(assignment) = expression else {
return false;
};
if assignment.op != AssignOp::Assign {
return false;
}
if let Some(identifier) = assignment.left.as_ident() {
let identifier = identifier.to_id();
let uses = self.properties.binding(&identifier);
return match assignment.right.unwrap_parens() {
// Remove unused `alias = object` assignments only when no other alias depends
// on them. Repeated rounds collapse chains. Property writes keep an alias until
// those writes are removed.
Expr::Ident(object) => {
self.bindings.copy_source(&identifier) == Some(&object.to_id())
&& !uses.is_used_dynamically()
&& uses.accessed.is_empty()
&& !uses.written_through
&& !self.bindings.is_copied(&identifier)
}
// `root = {}` once every property is gone and nothing reads it.
Expr::Object(object) => {
object.props.is_empty()
&& self.is_dead_root(&identifier)
&& self.properties.object(&identifier).accessed.is_empty()
}
_ => false,
};
}
if let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assignment.left
&& let Some(identifier) = member.obj.as_ident()
&& let Some(property) = analysis::member_key(&member.prop)
&& matches!(&*assignment.right, Expr::Fn(_) | Expr::Lit(_))
&& self
.member_definitions
.contains(&(identifier.to_id(), property.clone()))
{
let root = self.bindings.root(&identifier.to_id());
return self.is_dead_root(&root) && !self.is_live(&root, &property);
}
false
}
/// Records the definition `expression` makes, if any.
fn define(&mut self, expression: &Expr, position: Position) {
expression.visit_children_with(self);
let Expr::Assign(assignment) = expression else {
return;
};
if assignment.op != AssignOp::Assign {
return;
}
if let Some(identifier) = assignment.left.as_ident()
&& let Expr::Object(object) = assignment.right.unwrap_parens()
{
let identifier = identifier.to_id();
if object
.props
.iter()
.any(|property| removable_key(property).is_none())
{
self.poisoned.insert(self.bindings.root(&identifier));
}
self.literals.insert(identifier);
} else if let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assignment.left
&& let Some(identifier) = member.obj.as_ident()
{
let identifier = identifier.to_id();
match analysis::member_key(&member.prop) {
Some(property) if matches!(&*assignment.right, Expr::Fn(_) | Expr::Lit(_)) => {
// Keep the object while this property definition remains.
if position == Position::Fixed {
self.poisoned.insert(self.bindings.root(&identifier));
}
self.member_definitions.insert((identifier, property));
}
_ => {
self.poisoned.insert(self.bindings.root(&identifier));
}
}
}
}
}
/// Collects definitions and whether their positions allow removal.
impl Visit for RemoveDeadProperties<'_> {
fn visit_stmts(&mut self, statements: &[Stmt]) {
for statement in statements {
// Remove entire statements containing only dead assignments.
match statement {
Stmt::Expr(statement) => match &*statement.expr {
Expr::Seq(sequence) => {
for operand in &sequence.exprs {
self.define(operand, Position::Removable);
}
}
expression => self.define(expression, Position::Removable),
},
statement => statement.visit_with(self),
}
}
}
fn visit_seq_expr(&mut self, sequence: &SeqExpr) {
// Remove dead sequence operands only if a retained operand remains.
let keeps_live = sequence.exprs.iter().any(|operand| !may_be_dead(operand));
let position = if keeps_live {
Position::Removable
} else {
Position::Fixed
};
for operand in &sequence.exprs {
self.define(operand, position);
}
}
fn visit_expr(&mut self, expression: &Expr) {
self.define(expression, Position::Fixed);
}
}
/// Whether a definition's position lets it be removed.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Position {
/// A standalone statement, or a sequence operand beside a retained operand.
Removable,
Fixed,
}
/// Recognizes assignments that may be removable: `alias = object`, `root = {}`, or
/// `object.property = <Fn|Lit>`.
fn may_be_dead(expression: &Expr) -> bool {
let Expr::Assign(assignment) = expression else {
return false;
};
let value = assignment.right.unwrap_parens();
assignment.op == AssignOp::Assign
&& match &assignment.left {
AssignTarget::Simple(SimpleAssignTarget::Ident(_)) => {
value.is_ident()
|| value
.as_object()
.is_some_and(|object| object.props.is_empty())
}
AssignTarget::Simple(SimpleAssignTarget::Member(_)) => {
matches!(&*assignment.right, Expr::Fn(_) | Expr::Lit(_))
}
_ => false,
}
}
/// Returns the static key of a removable function or literal property definition.
fn removable_key(property: &PropOrSpread) -> Option<Atom> {
let property = ast::key_value(property)?;
let removable = matches!(&*property.value, Expr::Fn(_) | Expr::Lit(_));
analysis::prop_key(&property.key).filter(|_| removable)
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn removes_unread_properties_dead_aliases_and_dead_objects() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(
"function f(h) { h = { live: function(a) { return a + 1; }, \
dead: function(a) { return a - 1; }, name: \"n\", gone: \"g\" }; \
return [h.live(1), h.name]; }",
);
testing::assert_contains(&output, &["live", "\"n\""], &[]);
testing::assert_lacks(&output, &["dead", "gone"]);
let output = transform(
"function f(c, G) { c = {}; c.keep = function(a) { return a; }; \
c.drop = function(a) { return a; }; G = c; return c.keep(1); }",
);
testing::assert_contains(&output, &["c = {};", "c.keep = function"], &[]);
testing::assert_lacks(&output, &["c.drop", "G = c"]);
// One level of an alias chain collapses per pass.
let output = transform(
"function f(c, G, H) { c = {}; c.drop = function(a) { return a; }; \
G = c; H = G; return 1; }",
);
testing::assert_lacks(&output, &["c.drop", "H = G"]);
let output = transform(&output);
assert!(!output.contains("G = c"), "{output}");
let output = transform(&output);
assert!(!output.contains("c = {};"), "{output}");
}
#[test]
fn preserves_objects_that_escape_or_keep_a_definition() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
for source in [
"function f(c, k) { c = {}; c.a = function() {}; use(c[k]); return c.a(); }",
"function f(c) { c = {}; c.a = function() {}; c.__proto__ = {}; return c.a(); }",
"function f(c) { c = {}; c.a = function() {}; use(c); return c.a(); }",
"function f(c, G) { c = {}; c.a = function() {}; G = c; use(G); return 1; }",
"function f(c) { c = {}; c.a = effect(); return 1; }",
] {
testing::assert_contains(&transform(source), &["c = {};", "c.a = "], &[]);
}
for source in [
"function f(c, x) { c = {}; c.a = function() {}; if (x) c.b = 1; return 1; }",
"function f(c, G, k) { c = {}; c.a = function() {}; G = c; use(G[k]); return 1; }",
"function f(c, x) { c = {}; c.a = function() {}; return x && (c.b = 1); }",
] {
let output = transform(source);
assert!(output.contains("c = {};"), "{output}");
}
// Properties that methods read through `this`.
for (source, kept) in [
(
"function f(s) { s = { n: 0, inc: function () { this.n++; } }; s.inc(); }",
"n: 0",
),
(
"function f(h) { h = { a: 1 }; return h.hasOwnProperty('a'); }",
"a: 1",
),
] {
let output = transform(source);
assert!(output.contains(kept), "{output}");
}
}
}
+408
View File
@@ -0,0 +1,408 @@
//! Inlines calls to dispatchers whose first argument selects a return value through `if`,
//! `switch`, or nested blocks. Supports applied calls and operator expressions:
//!
//! ```js
//! function b(n, f, args) {
//! switch (3832 ^ n) {
//! case 973348: return Reflect.apply(f, undefined, args);
//! }
//! }
//! function w(op, x, y) { if (op === 0) return x + y; else return x - y; }
//!
//! b(971996, encode, [payload]); // encode(payload)
//! w(1, 630, 622); // 630 - 622
//! ```
//!
//! Requires a literal selector. Applied targets must be identifiers to preserve undefined
//! `this`. Operator arguments must have no side effects so repeated or reordered evaluation is
//! safe. `Reflect` and `undefined` must resolve to globals.
use swc_core::ecma::ast::{
BinaryOp, CallExpr, Callee, Expr, ExprOrSpread, FnDecl, Function, Id, Lit, Program, Stmt,
UnaryOp,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::{Analysis, Globals, effects, names};
use super::{HashMap, helper_objects};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let globals = analysis.globals;
let bindings = analysis.bindings(program);
let mut functions = Functions::default();
program.visit_with(&mut functions);
// The declaration or assignment that defines the function is its only write, so every call
// reaches this function.
functions.0.retain(|id, _| bindings.is_written_once(id));
if functions.0.is_empty() {
return false;
}
let mut inline = InlineDispatchers {
functions: &functions.0,
globals,
changed: false,
};
program.visit_mut_with(&mut inline);
inline.changed
}
/// Functions with only identifier parameters.
#[derive(Default)]
struct Functions(HashMap<Id, Candidate>);
struct Candidate {
params: Vec<Id>,
body: Vec<Stmt>,
}
impl Candidate {
fn try_new(function: &Function) -> Option<Self> {
let params = names::parameter_ids(&function.params)?;
let body = &function.body.as_ref()?.stmts;
(!params.is_empty() && !function.is_async && !function.is_generator && may_select(body))
.then(|| Self {
params,
body: body.clone(),
})
}
}
impl Visit for Functions {
fn visit_expr(&mut self, expression: &Expr) {
if let Some((id, Expr::Fn(function))) = ast::assignment(expression)
&& let Some(candidate) = Candidate::try_new(&function.function)
{
self.0.insert(id, candidate);
}
expression.visit_children_with(self);
}
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
if let Some(candidate) = Candidate::try_new(&declaration.function) {
self.0.insert(declaration.ident.to_id(), candidate);
}
declaration.visit_children_with(self);
}
}
/// Checks whether some selector could reach `return value` through [`Path::run`]. Avoids
/// cloning large unrelated functions, such as VM helpers.
fn may_select<'a>(statements: impl IntoIterator<Item = &'a Stmt>) -> bool {
for statement in statements {
let selects = match statement {
Stmt::Return(returned) => return returned.arg.is_some(),
Stmt::Block(block) => may_select(&block.stmts),
Stmt::Empty(_) => false,
Stmt::If(conditional) => {
may_select([&*conditional.cons]) || may_select(conditional.alt.as_deref())
}
Stmt::Switch(switch) => switch.cases.iter().any(|case| may_select(&case.cons)),
_ => return false,
};
if selects {
return true;
}
}
false
}
/// Follows a function body for one known selector value.
struct Path<'body> {
selector: &'body Id,
value: f64,
}
impl<'body> Path<'body> {
/// Returns `Some(Some(value))` for a return with a value, `Some(None)` for normal
/// completion, and `None` for a path it cannot analyze.
fn run(
&self,
statements: impl IntoIterator<Item = &'body Stmt>,
) -> Option<Option<&'body Expr>> {
for statement in statements {
let returned = match statement {
Stmt::Return(returned) => return Some(Some(returned.arg.as_deref()?)),
Stmt::Block(block) => self.run(&block.stmts)?,
Stmt::Empty(_) => None,
Stmt::If(conditional) => match self.truthy(&conditional.test)? {
true => self.run([&*conditional.cons])?,
false => self.run(conditional.alt.as_deref())?,
},
Stmt::Switch(switch) => {
let value = self.number(&switch.discriminant)?;
let mut matching = None;
let mut default = None;
for (index, case) in switch.cases.iter().enumerate() {
let Some(test) = &case.test else {
default.get_or_insert(index);
continue;
};
if self.number(test)? == value {
matching.get_or_insert(index);
}
}
let Some(start) = matching.or(default) else {
continue;
};
// Fall through from the matching case until a return.
let body: Vec<&Stmt> = switch.cases[start..]
.iter()
.flat_map(|case| &case.cons)
.collect();
if body
.iter()
.any(|statement| matches!(statement, Stmt::Break(_)))
{
return None;
}
self.run(body)?
}
_ => return None,
};
if returned.is_some() {
return Some(returned);
}
}
Some(None)
}
fn truthy(&self, expression: &Expr) -> Option<bool> {
match expression {
Expr::Paren(inner) => self.truthy(&inner.expr),
Expr::Unary(unary) if unary.op == UnaryOp::Bang => Some(!self.truthy(&unary.arg)?),
Expr::Lit(Lit::Bool(value)) => Some(value.value),
Expr::Bin(binary) => {
let (left, right) = (self.number(&binary.left)?, self.number(&binary.right)?);
match binary.op {
BinaryOp::EqEqEq | BinaryOp::EqEq => Some(left == right),
BinaryOp::NotEqEq | BinaryOp::NotEq => Some(left != right),
BinaryOp::Lt => Some(left < right),
BinaryOp::LtEq => Some(left <= right),
BinaryOp::Gt => Some(left > right),
BinaryOp::GtEq => Some(left >= right),
_ => None,
}
}
_ => None,
}
}
fn number(&self, expression: &Expr) -> Option<f64> {
ast::fold_number(expression, &|leaf| {
(leaf.as_ident()?.to_id() == *self.selector).then_some(self.value)
})
}
}
/// The parameter positions of `target` and `args` in `Reflect.apply(target, undefined, args)`.
struct ReflectApply {
target: usize,
arguments: usize,
}
fn reflect_apply(expression: &Expr, params: &[Id], globals: Globals) -> Option<ReflectApply> {
let position = |expression: &Expr| {
let id = expression.as_ident()?.to_id();
params.iter().position(|param| *param == id)
};
if let Some((reflect, [function, this, arguments])) = ast::method_call(expression, "apply")
&& reflect
.as_ident()
.is_some_and(|id| globals.is(id, "Reflect"))
&& [function, this, arguments]
.iter()
.all(|arg| arg.spread.is_none())
&& match &*this.expr {
Expr::Ident(id) => globals.is(id, "undefined"),
Expr::Unary(unary) => {
unary.op == UnaryOp::Void && !effects::may_have_effects(&unary.arg, globals)
}
_ => false,
}
{
Some(ReflectApply {
target: position(&function.expr)?,
arguments: position(&arguments.expr)?,
})
} else {
None
}
}
/// Operators other than `delete` combining leaves that `leaf` accepts.
fn is_operation(expression: &Expr, leaf: &impl Fn(&Expr) -> bool) -> bool {
match expression {
Expr::Paren(inner) => is_operation(&inner.expr, leaf),
Expr::Unary(unary) => unary.op != UnaryOp::Delete && is_operation(&unary.arg, leaf),
Expr::Bin(binary) => is_operation(&binary.left, leaf) && is_operation(&binary.right, leaf),
expression => leaf(expression),
}
}
struct InlineDispatchers<'functions> {
functions: &'functions HashMap<Id, Candidate>,
globals: Globals,
changed: bool,
}
impl InlineDispatchers<'_> {
fn replacement(&self, callee: &Id, args: &[ExprOrSpread]) -> Option<Expr> {
let candidate = self.functions.get(callee)?;
if args.iter().any(|arg| arg.spread.is_some()) {
return None;
}
let Expr::Lit(Lit::Num(selector)) = &*args.first()?.expr else {
return None;
};
// Returns the selected expression only if choosing it requires constant selector
// comparisons with no other evaluation.
let path = Path {
selector: &candidate.params[0],
value: selector.value,
};
let returned = path.run(&candidate.body)??;
if let Some(apply) = reflect_apply(returned, &candidate.params, self.globals)
&& let Some(target) = args.get(apply.target)
&& target.expr.is_ident()
&& let Expr::Array(applied) = &*args.get(apply.arguments)?.expr
&& let Some(applied) = applied
.elems
.iter()
.map(|element| element.clone().filter(|element| element.spread.is_none()))
.collect::<Option<Vec<_>>>()
{
return Some(Expr::Call(CallExpr {
callee: Callee::Expr(target.expr.clone()),
args: applied,
..Default::default()
}));
}
// The operation may repeat or reorder arguments. Allow only literals and bindings whose
// reads have no effects. Unknown globals could throw or invoke getters.
let is_parameter_or_number = |leaf: &Expr| match leaf {
Expr::Ident(id) => candidate.params.contains(&id.to_id()),
leaf => matches!(leaf, Expr::Lit(Lit::Num(_))),
};
let is_pure = |leaf: &Expr| match leaf {
Expr::Ident(_) => !effects::may_have_effects(leaf, self.globals),
leaf => matches!(leaf, Expr::Lit(Lit::Num(_) | Lit::Str(_) | Lit::Bool(_))),
};
if args.len() == candidate.params.len()
&& is_operation(returned, &is_parameter_or_number)
&& args.iter().all(|arg| is_operation(&arg.expr, &is_pure))
{
let values: HashMap<Id, &Expr> = candidate
.params
.iter()
.cloned()
.zip(args.iter().map(|arg| &*arg.expr))
.collect();
// The operation calls nothing, so no parameter needs detaching.
Some(helper_objects::replace_parameters(returned, values))
} else {
None
}
}
}
impl VisitMut for InlineDispatchers<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Some((callee, args)) = ast::direct_call(expression)
&& let Some(replacement) = self.replacement(&callee.to_id(), args)
{
*expression = replacement;
self.changed = true;
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
const APPLY: &str = "var b; b = function (n, m, r) {
switch (3832 ^ n) {
case 973348: return Reflect.apply(m, undefined, r);
case 428312: return Reflect.apply(m, void 0, r);
}
};";
const OPERATOR: &str = "var w; w = function (E, P, S) {
switch (E) { case 0: return P + S; case 1: return P - S; case 2: return S * P; default: return P % S; }
};";
#[test]
fn applies_the_target_only_for_provable_applications() {
let inline = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = inline(&format!(
"{APPLY} f(b(971996, encode, [x, 1]), b(428000, g, []));"
));
assert!(output.contains("f(encode(x, 1), g())"), "{output}");
for call in [
"b(1, encode, [x])",
"b(971996, o.encode, [x])",
"b(971996, encode, args)",
"b(971996, encode, [...x])",
] {
let output = inline(&format!("{APPLY} f({call});"));
assert!(output.contains("f(b("), "{output}");
}
let reassigned = inline(&format!("{APPLY} b = h; f(b(971996, encode, [x]));"));
assert!(reassigned.contains("f(b("), "{reassigned}");
}
#[test]
fn inlines_selected_operations_through_switches_if_chains_and_xor_keys() {
let inline = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = inline(&format!(
"{OPERATOR} function g(a, b) {{ f(w(1, 630, 622), w(2, a, b + 1), w(9, 7, 2)); }}"
));
testing::assert_contains(&output, &["f(630 - 622, (b + 1) * a, 7 % 2)"], &[]);
let output = inline(
"t = function (V, c, X) {
if (!(V !== 0)) { return c + X; } else { if (!(2 === V)) { return c % X; } else { return X * c; } }
};
function q(J, r, n) { switch (2774 ^ J) { case 0: return r | n; default: return r & n; } }
function g(a, b) { f(t(0, a, b), t(2, a, b), t(5, a, b), q(2774, a, b), q(2775, a, b)); }",
);
testing::assert_contains(&output, &["f(a + b, b * a, a % b, a | b, a & b)"], &[]);
// Arguments with effects and unknown selectors stay.
for call in ["w(1, g(), 2)", "w(n, 1, 2)", "w(1, 2)", "w(1, missing, 2)"] {
let output = inline(&format!("{OPERATOR} f({call});"));
assert!(output.contains(&format!("f({call})")), "{output}");
}
}
#[test]
fn only_bodies_that_can_select_a_return_are_candidates() {
use swc_core::ecma::ast::{Decl, Stmt};
let selects = |body: &str| {
let script =
crate::js::ast::parse_javascript("a test", &format!("function f(n) {{ {body} }}"))
.unwrap()
.script;
let Some(Stmt::Decl(Decl::Fn(function))) = script.body.first() else {
panic!("not a function declaration: {body}");
};
super::may_select(&function.function.body.as_ref().unwrap().stmts)
};
for body in [
"return 1;",
";{ if (n) {} else { return 2; } }",
"switch (n) { case 0: g(); case 1: return 3; }",
] {
assert!(selects(body), "{body}");
}
for body in [
"",
"return;",
"var x = 1; return x;",
"while (n) { return 1; }",
] {
assert!(!selects(body), "{body}");
}
}
}
+277
View File
@@ -0,0 +1,277 @@
//! Replaces constant calls to the obfuscator's string decoder with their results:
//!
//! ```js
//! var decode = function(global) { ... return function(encoded) { ... } }(globalThis);
//! decode(`ZJd1i3w=`); // becomes "apply"
//! ```
//!
//! The decoder swaps the bytes of a 16-bit key before processing each byte, then XORs the input
//! byte with the key's high byte. A byte of 255 introduces a code unit encoded in the next two
//! bytes. Only the key varies between scripts. Requires a decoder binding assigned once.
//! Because decoding has no side effects, constant calls can be replaced wherever they occur.
//! Removes the decoder when no reads remain.
use base64::engine::general_purpose::STANDARD;
use swc_core::atoms::Wtf8Atom;
use swc_core::atoms::wtf8::Wtf8Buf;
use swc_core::ecma::ast::{BinaryOp, Expr, Id, Lit, Program, Str, VarDeclarator};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::Analysis;
use super::{HashMap, HashSet, removal};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let bindings = analysis.bindings(program);
let mut decoders = Decoders::default();
program.visit_with(&mut decoders);
decoders.0.retain(|id, _| bindings.is_written_once(id));
if decoders.0.is_empty() {
return false;
}
let mut decode = DecodeCalls {
decoders: &decoders.0,
decoded: HashMap::default(),
};
program.visit_mut_with(&mut decode);
let unread = removal::unread(&decode.decoded, bindings);
program.visit_mut_with(&mut DropDecoders(unread));
!decode.decoded.is_empty()
}
/// Decodes `encoded` as the decoder holding `key` does, or `None` if it is not base64.
fn decode(encoded: &str, mut key: u16) -> Option<Wtf8Atom> {
use base64::Engine;
let mut bytes = STANDARD.decode(encoded).ok()?.into_iter();
let mut next = || {
key = key.rotate_left(8);
Some(bytes.next()? ^ (key >> 8) as u8)
};
let mut units = vec![];
while let Some(unit) = next() {
units.push(if unit == 255 {
u16::from_le_bytes([next()?, next()?])
} else {
u16::from(unit)
});
}
Some(Wtf8Atom::from(Wtf8Buf::from_ill_formed_utf16(&units)))
}
/// Decoders by binding, with their keys.
#[derive(Default)]
struct Decoders(HashMap<Id, u16>);
impl Visit for Decoders {
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if let Some(name) = declarator.name.as_ident()
&& let Some(key) = declarator.init.as_deref().and_then(decoder_key)
{
self.0.insert(name.to_id(), key);
}
declarator.visit_children_with(self);
}
}
/// The key of `function(global) { ...; return function(encoded) { ... } }(globalThis)`. The
/// inner decoder declares it beside `bytes = global.atob(encoded)` and rotates it by
/// `key = (key << 8 | key >>> 8) & 65535`.
fn decoder_key(expression: &Expr) -> Option<u16> {
let call = expression.as_call()?;
let [global] = &call.args[..] else {
return None;
};
if global.spread.is_some() || global.expr.as_ident()?.sym != "globalThis" {
return None;
}
let outer = call.callee.as_expr()?.unwrap_parens().as_fn_expr()?;
let returned = outer
.function
.body
.as_ref()?
.stmts
.last()?
.as_return_stmt()?;
let decoder = &returned.arg.as_deref()?.as_fn_expr()?.function;
let [parameter] = &decoder.params[..] else {
return None;
};
let mut keys = Keys {
encoded: parameter.pat.as_ident()?.to_id(),
key: None,
rotated: false,
};
decoder.visit_with(&mut keys);
let (_, key) = keys.key?;
keys.rotated.then_some(key)
}
/// Finds the key declaration and its rotation in an inner decoder.
struct Keys {
encoded: Id,
key: Option<(Id, u16)>,
rotated: bool,
}
impl Visit for Keys {
fn visit_var_declarators(&mut self, declarators: &[VarDeclarator]) {
for pair in declarators.windows(2) {
if let [bytes, key] = pair
&& let Some(init) = bytes.init.as_deref()
&& let Some((_, [argument])) = ast::method_call(init, "atob")
&& argument
.expr
.as_ident()
.is_some_and(|id| id.to_id() == self.encoded)
&& let Some(name) = key.name.as_ident()
&& let Some(value) = key.init.as_deref().and_then(ast::number)
&& value.fract() == 0.0
&& let Ok(value) = u16::try_from(value as i64)
{
self.key = Some((name.to_id(), value));
}
}
declarators.visit_children_with(self);
}
fn visit_expr(&mut self, expression: &Expr) {
if let Some((key, _)) = &self.key
&& is_rotation(expression, key)
{
self.rotated = true;
}
expression.visit_children_with(self);
}
}
/// `(key << 8 | key >>> 8) & 65535`.
fn is_rotation(expression: &Expr, key: &Id) -> bool {
let shifts_key = |expression: &Expr, op| {
expression.as_bin().is_some_and(|shift| {
shift.op == op
&& shift
.left
.as_ident()
.is_some_and(|name| name.to_id() == *key)
&& ast::number(&shift.right) == Some(8.0)
})
};
let Some(mask) = expression.as_bin() else {
return false;
};
let Some(swap) = mask.left.unwrap_parens().as_bin() else {
return false;
};
mask.op == BinaryOp::BitAnd
&& ast::number(&mask.right) == Some(65535.0)
&& swap.op == BinaryOp::BitOr
&& shifts_key(&swap.left, BinaryOp::LShift)
&& shifts_key(&swap.right, BinaryOp::ZeroFillRShift)
}
/// Replaces `decoder(encoded)` with its result, counting the calls replaced per decoder.
struct DecodeCalls<'decoders> {
decoders: &'decoders HashMap<Id, u16>,
decoded: HashMap<Id, usize>,
}
impl VisitMut for DecodeCalls<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Some((callee, [encoded])) = ast::direct_call(expression)
&& encoded.spread.is_none()
&& let Some(&key) = self.decoders.get(&callee.to_id())
&& let Some(value) = ast::static_str(&encoded.expr).and_then(|text| decode(text, key))
{
*self.decoded.entry(callee.to_id()).or_default() += 1;
*expression = Expr::Lit(Lit::Str(Str {
span: callee.span,
value,
raw: None,
}));
}
}
}
/// Drops the initializers of decoders nothing reads, leaving `var decoder;`.
struct DropDecoders(HashSet<Id>);
impl VisitMut for DropDecoders {
fn visit_mut_var_declarator(&mut self, declarator: &mut VarDeclarator) {
if declarator
.name
.as_ident()
.is_some_and(|name| self.0.contains(&name.to_id()))
{
declarator.init = None;
}
declarator.visit_mut_children_with(self);
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
/// The decoder of a challenge script, with its key.
const DECODER: &str = "var decode = function(J) {
var d = { __proto__: null }, e = J.String;
return function(l) {
var E = d[l];
if (E === void 0) {
var V = J.atob(l), z = 59141, E = ``, H = 0, C = [];
while (H < V.length) {
z = (z << 8 | z >>> 8) & 65535;
var t = V.charCodeAt(H++) ^ z >>> 8;
if (t === 255) {
z = (z << 8 | z >>> 8) & 65535;
t = V.charCodeAt(H++) ^ z >>> 8;
z = (z << 8 | z >>> 8) & 65535;
t |= (V.charCodeAt(H++) ^ z >>> 8) << 8;
}
C.push(t);
if (C.length === 128) {
E += e.fromCharCode.apply(e, C);
C = [];
}
}
E += e.fromCharCode.apply(e, C);
d[l] = E;
}
return E;
};
}(globalThis);";
#[test]
fn decodes_constant_calls_and_drops_an_unread_decoder() {
let transform = |source: &str| {
testing::rewrite(
&format!("{DECODER}\n{source}"),
super::run,
/* fix= */ true,
)
};
let output = transform("f(decode(`ZJd1i3w=`), decode('ZoZpiw=='));");
testing::assert_contains(&output, &["\"apply\"", "\"call\""], &["var decode;"]);
// Dynamic calls keep the decoder; reassignment disables decoding.
let output = transform("f(decode(`ZJd1i3w=`), decode(name));");
let expected = ["\"apply\"", "decode(name)"];
testing::assert_contains(&output, &expected, &["var decode = function"]);
let output = transform("decode = other; f(decode(`ZJd1i3w=`));");
assert!(output.contains("decode(`ZJd1i3w=`)"), "{output}");
}
#[test]
fn decodes_escaped_code_units() {
use base64::Engine;
// 255 escapes the code unit U+D800, a lone surrogate.
let encoded = super::STANDARD.encode([255 ^ 0x05, 0x00 ^ 0xe7, 0xd8 ^ 0x05]);
let decoded = super::decode(&encoded, 59141).unwrap();
assert_eq!(
decoded.as_wtf8().to_ill_formed_utf16().collect::<Vec<_>>(),
[0xd800]
);
}
}
+74
View File
@@ -0,0 +1,74 @@
//! Replaces a function literal's `length` with its parameter count, exposing constants hidden
//! by the obfuscator:
//!
//! ```js
//! ((a) => a).length + 2; // becomes 1 + 2
//! ```
//!
//! Counts parameters before the first default or rest parameter, as `length` does.
use swc_core::ecma::ast::{Expr, Lit, Number, Pat, Program};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::Analysis;
use crate::js::ast;
pub(super) fn run(program: &mut Program, _: &mut Analysis) -> bool {
let mut lengths = FoldLengths { changed: false };
program.visit_mut_with(&mut lengths);
lengths.changed
}
struct FoldLengths {
changed: bool,
}
impl VisitMut for FoldLengths {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Member(member) = expression
&& ast::member_str(&member.prop) == Some("length")
&& let Some(length) = literal_length(&member.obj)
{
*expression = Expr::Lit(Lit::Num(Number {
span: member.span,
value: length as f64,
raw: None,
}));
self.changed = true;
}
}
}
/// The `length` of a function or arrow literal, possibly parenthesized.
fn literal_length(expression: &Expr) -> Option<usize> {
let counted = |pattern: &&Pat| !matches!(pattern, Pat::Assign(_) | Pat::Rest(_));
let length = match expression.unwrap_parens() {
Expr::Arrow(arrow) => arrow.params.iter().take_while(counted).count(),
Expr::Fn(function) => function
.function
.params
.iter()
.map(|parameter| &parameter.pat)
.take_while(counted)
.count(),
_ => return None,
};
Some(length)
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn counts_parameters_before_defaults_and_rest() {
let output = testing::rewrite(
"f((a => a).length, (function(a, b) {}).length, ((a, b = 1, c) => a).length,
((...a) => a).length, g.length);",
super::run,
/* fix= */ true,
);
testing::assert_contains(&output, &[], &["f(1, 2, 1, 0, g.length)"]);
}
}
+804
View File
@@ -0,0 +1,804 @@
//! Inlines literal and single-return function properties of helper objects:
//!
//! ```js
//! h = { add: function (a, b) { return a + b; }, key: "name" };
//! h.add(x, 1); h.key; // becomes (x) + (1); "name"
//! ```
//!
//! Requires each property to be defined once on an object that does not escape (see
//! [`Properties::is_stable`]), and calls that preserve argument evaluation and order (see
//! [`can_inline`]). Hoisted function bodies use only objects known wherever they can be called
//! (see [`hoisting`]).
use std::iter;
use std::rc::Rc;
use swc_core::atoms::Atom;
use swc_core::common::SyntaxContext;
use swc_core::ecma::ast::{
AssignExpr, AssignOp, AssignTarget, CallExpr, Callee, Decl, Expr, ExprOrSpread, FnExpr,
ForStmt, Function, Id, Ident, Lit, MemberExpr, MemberProp, MetaPropExpr, Number, ObjectLit,
Program, ReturnStmt, SeqExpr, SimpleAssignTarget, Stmt, Super, ThisExpr, UnaryOp,
VarDeclOrExpr,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::HashMap;
use super::analysis::effects::{self, Effects};
use super::analysis::hoisting::{self, HoistFacts, Hoisted, Hoisting};
use super::analysis::{self, Analysis, Bindings, Globals, Properties, names};
use crate::js::ast;
/// Tracks helper objects and aliases only while their bindings have exactly one write, leaving
/// reassigned bindings unchanged.
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let globals = analysis.globals;
let (bindings, properties) = analysis.properties(program);
let mut inline = InlineHelpers {
bindings,
properties,
globals,
hoisting: Hoisting::default(),
lists: 0,
defined_in: HashMap::default(),
changed: false,
};
program.visit_mut_with(&mut inline);
inline.changed
}
/// Properties of one helper object that can replace property reads.
#[derive(Clone, Default)]
struct ObjectProperties {
functions: HashMap<Atom, FnExpr>,
literals: HashMap<Atom, Expr>,
}
impl ObjectProperties {
/// Every inlinable property of a helper object literal.
fn collect(object: &ObjectLit) -> Self {
let mut properties = Self::default();
for property in ast::key_values(object) {
if let Some(name) = analysis::prop_key(&property.key) {
properties.insert(name, &property.value);
}
}
properties
}
/// Records substitutable properties. Leaves unsupported properties as object reads.
fn insert(&mut self, name: Atom, value: &Expr) {
match value {
Expr::Fn(function) => {
self.functions.insert(name, function.clone());
}
// A regular expression carries state and identity, so it cannot
// stand in for every read.
Expr::Lit(literal) if !matches!(literal, Lit::Regex(_)) => {
self.literals.insert(name, Expr::Lit(literal.clone()));
}
_ => {}
}
}
}
/// The helper objects and functions known at one point, by binding.
#[derive(Clone, Default)]
struct Helpers {
objects: HashMap<Id, Rc<ObjectProperties>>,
/// Functions assigned to a binding written once.
functions: HashMap<Id, Rc<FnExpr>>,
}
/// At a control-flow join, keeps the objects and properties known on both paths.
impl HoistFacts for Helpers {
fn meet(&mut self, other: &Self) {
self.objects.retain(|id, properties| {
let Some(theirs) = other.objects.get(id) else {
return false;
};
if !Rc::ptr_eq(properties, theirs) {
let properties = Rc::make_mut(properties);
properties
.functions
.retain(|name, _| theirs.functions.contains_key(name));
properties
.literals
.retain(|name, _| theirs.literals.contains_key(name));
}
true
});
self.functions.meet(&other.functions);
}
}
struct InlineHelpers<'analysis> {
bindings: &'analysis Bindings,
properties: &'analysis Properties,
globals: Globals,
/// Tracks known helpers. An alias gets the properties known when its assignment runs.
hoisting: Hoisting<Helpers>,
/// Counter assigning an identity to each entered statement list or sequence.
lists: usize,
/// The statement list or sequence whose top level assigns each object binding.
defined_in: HashMap<Id, usize>,
changed: bool,
}
impl InlineHelpers<'_> {
/// Visits a statement in `list`, recording expressions that always execute before visiting
/// its children. These include expression statements, return and throw values, loop
/// initializers, branch tests, switch discriminants, and `var` initializers.
fn statement(&mut self, statement: &mut Stmt, list: usize) {
match statement {
Stmt::Expr(statement) => self.top_level(&mut statement.expr, list),
Stmt::Return(ReturnStmt {
arg: Some(argument),
..
}) => self.top_level(argument, list),
Stmt::Throw(statement) => self.top_level(&mut statement.arg, list),
Stmt::If(statement) => {
self.top_level(&mut statement.test, list);
statement.cons.visit_mut_with(self);
statement.alt.visit_mut_with(self);
}
Stmt::Switch(statement) => {
self.top_level(&mut statement.discriminant, list);
statement.cases.visit_mut_with(self);
}
Stmt::Decl(Decl::Var(declaration)) => {
for declarator in &mut declaration.decls {
declarator.name.visit_mut_with(self);
if let Some(init) = &mut declarator.init {
self.top_level(init, list);
}
}
}
Stmt::For(ForStmt {
init: Some(VarDeclOrExpr::Expr(init)),
test,
update,
body,
..
}) => {
self.top_level(init, list);
test.visit_mut_with(self);
update.visit_mut_with(self);
body.visit_mut_with(self);
}
statement => statement.visit_mut_with(self),
}
}
/// Visits an expression guaranteed to run with its statement or sequence, preserving
/// sequence order.
fn top_level(&mut self, expression: &mut Expr, list: usize) {
if let Expr::Seq(sequence) = expression {
for operand in &mut sequence.exprs {
self.top_level(operand, list);
}
return;
}
expression.visit_mut_with(self);
let Expr::Assign(assignment) = expression else {
return;
};
if let Some(target) = assignment.left.as_ident()
&& self.hoisting.facts.objects.contains_key(&target.to_id())
{
self.defined_in.insert(target.to_id(), list);
} else if assignment.op == AssignOp::Assign
&& let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assignment.left
&& let Some(identifier) = member.obj.as_ident()
&& let Some(property) = analysis::member_key(&member.prop)
&& self.defined_in.get(&identifier.to_id()) == Some(&list)
&& let Some(object) = self.hoisting.facts.objects.get_mut(&identifier.to_id())
{
// Only property assignments beside the object's definition safely extend it.
// Elsewhere, a read might run before the assignment.
Rc::make_mut(object).insert(property, &assignment.right);
}
}
/// Resolves a stable `helper.name` read to its helper object and property.
fn stable(&self, member: &MemberExpr) -> Option<(&ObjectProperties, Atom)> {
let identifier = member.obj.as_ident()?.to_id();
let property = analysis::member_key(&member.prop)?;
if !self.properties.is_stable(&identifier, &property) {
return None;
}
Some((self.hoisting.facts.objects.get(&identifier)?, property))
}
}
impl VisitMut for InlineHelpers<'_> {
fn visit_mut_assign_expr(&mut self, assignment: &mut AssignExpr) {
assignment.visit_mut_children_with(self);
if assignment.op == AssignOp::Assign
&& let Some(target) = assignment.left.as_ident()
&& self.bindings.is_written_once(&target.to_id())
{
let target = target.to_id();
// Track object definitions, helper functions, and copies of known objects by
// binding.
let helpers = &mut self.hoisting.facts;
if let Some(object) = assignment.right.as_object() {
let properties = Rc::new(ObjectProperties::collect(object));
helpers.objects.insert(target, properties);
} else if let Some(function) = assignment.right.as_fn_expr() {
helpers.functions.insert(target, Rc::new(function.clone()));
} else if let Some(alias) = assignment.right.as_ident()
&& let Some(object) = helpers.objects.get(&alias.to_id()).cloned()
{
helpers.objects.insert(target, object);
}
}
}
/// Visit function declarations last with objects known at every possible call.
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
self.lists += 1;
let list = self.lists;
hoisting::visit_mut_stmts(self, statements, |inline, statement| {
inline.statement(statement, list);
});
}
fn visit_mut_function(&mut self, function: &mut Function) {
hoisting::visit_mut_function(self, function);
}
fn visit_mut_ident(&mut self, identifier: &mut Ident) {
hoisting::reference(self, identifier);
}
/// The operands of a sequence run together and in order, like the statements of a list.
fn visit_mut_seq_expr(&mut self, sequence: &mut SeqExpr) {
self.lists += 1;
let list = self.lists;
for operand in &mut sequence.exprs {
self.top_level(operand, list);
}
}
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
// `helper.name(...)`, with the expression the function returns.
if let Expr::Call(call) = expression
&& let Callee::Expr(callee) = &call.callee
&& let Expr::Member(member) = &**callee
&& let Some((object, property)) = self.stable(member)
&& let Some(function) = object.functions.get(&property)
&& let Some(result) = ast::returned(&function.function)
&& can_inline(function, result, &call.args, self.globals)
&& let Some(replacement) = substitute(function, result, &call.args)
{
*expression = replacement;
self.changed = true;
}
// Inline a helper call only when its result uses parameters, sibling bindings, or
// globals visible to every caller.
if let Some((callee, args)) = ast::direct_call(expression)
&& let Some(function) = self.hoisting.facts.functions.get(&callee.to_id())
&& let Some(result) = ast::returned(&function.function)
&& names_only(result, &function.function, callee.ctxt, self.globals)
&& can_inline(function, result, args, self.globals)
&& let Some(replacement) = substitute(function, result, args)
{
*expression = replacement;
self.changed = true;
}
// A `helper.name` read of a literal.
if let Some(member) = expression.as_member()
&& let Some((object, property)) = self.stable(member)
&& let Some(value) = object.literals.get(&property)
{
*expression = value.clone();
self.changed = true;
}
}
}
/// Checks that every name in `result` is a parameter of `function`, a binding in `scope`, or a
/// global.
fn names_only(result: &Expr, function: &Function, scope: SyntaxContext, globals: Globals) -> bool {
struct Names {
parameters: Vec<Id>,
scopes: [SyntaxContext; 2],
all_allowed: bool,
}
impl Visit for Names {
fn visit_ident(&mut self, identifier: &Ident) {
self.all_allowed &= self.scopes.contains(&identifier.ctxt)
|| self.parameters.contains(&identifier.to_id());
}
}
let mut names = Names {
parameters: function
.params
.iter()
.filter_map(|parameter| Some(parameter.pat.as_ident()?.to_id()))
.collect(),
scopes: [scope, globals.unresolved],
all_allowed: true,
};
result.visit_with(&mut names);
names.all_allowed
}
impl Hoisted for InlineHelpers<'_> {
type Facts = Helpers;
fn hoisting(&mut self) -> &mut Hoisting<Helpers> {
&mut self.hoisting
}
}
/// Checks whether substituting `args` into `result` preserves evaluations and their order.
#[must_use]
fn can_inline(function: &FnExpr, result: &Expr, args: &[ExprOrSpread], globals: Globals) -> bool {
function.function.params.len() >= args.len()
&& trailing_parameters_unused(function, result, args.len())
&& args.iter().all(|argument| argument.spread.is_none())
&& !function.function.is_async
&& !function.function.is_generator
&& !uses_own_context(result)
&& (evaluates_arguments_safely(function, result, args, globals)
|| args
.iter()
.all(|argument| !effects::may_have_effects(&argument.expr, globals)))
}
/// Parameters without arguments disappear when the call is inlined. Allow this only for unused
/// plain identifiers. Destructuring may evaluate defaults, and referenced parameters would have
/// no binding after substitution.
fn trailing_parameters_unused(function: &FnExpr, result: &Expr, argument_count: usize) -> bool {
let params = &function.function.params;
let trailing = names::parameter_ids(&params[argument_count.min(params.len())..]);
trailing.is_some_and(|trailing| !names::mentions(result, &trailing))
}
/// Checks for `this`, `arguments`, `new.target`, or `super` outside nested functions, which
/// inlining would resolve in the caller instead.
fn uses_own_context(result: &Expr) -> bool {
struct Context(bool);
impl Visit for Context {
fn visit_this_expr(&mut self, _: &ThisExpr) {
self.0 = true;
}
fn visit_super(&mut self, _: &Super) {
self.0 = true;
}
fn visit_meta_prop_expr(&mut self, _: &MetaPropExpr) {
self.0 = true;
}
fn visit_function(&mut self, _: &Function) {}
}
let mut context = Context(false);
result.visit_with(&mut context);
context.0 || names::uses_arguments(result)
}
/// Requires each supplied parameter to appear exactly once in an operand that always runs.
/// Reordering operands must preserve behavior. Coercions must run after operand evaluation, so
/// nested arithmetic and short-circuit expressions need stricter checks.
fn evaluates_arguments_safely(
function: &FnExpr,
result: &Expr,
args: &[ExprOrSpread],
globals: Globals,
) -> bool {
let Some(operands) = eager_operands(result).filter(|operands| operands.len() == args.len())
else {
return false;
};
// The supplied parameters not yet read by an operand.
let mut unread: Vec<Option<Id>> = function
.function
.params
.iter()
.take(args.len())
.map(|parameter| Some(parameter.pat.as_ident()?.to_id()))
.collect();
// The parameter each operand reads, in evaluation order.
let mut order = Vec::with_capacity(args.len());
for operand in operands {
let operand = operand.as_ident().map(Ident::to_id);
let Some(index) = unread
.iter()
.position(|parameter| parameter.is_some() && *parameter == operand)
else {
return false;
};
unread[index] = None;
order.push(index);
}
for (position, &first) in order.iter().enumerate() {
for &second in &order[position + 1..] {
if first > second && !commutes(&args[first].expr, &args[second].expr, globals) {
return false;
}
}
}
true
}
/// Two arguments may swap if both have no effects, or one has no effects and reads no binding
/// the other writes. Calls and other opaque operations may write through closures, so binding
/// reads cannot move across them.
fn commutes(first: &Expr, second: &Expr, globals: Globals) -> bool {
let (pure, impure) = match (
effects::may_have_effects(first, globals),
effects::may_have_effects(second, globals),
) {
(false, false) => return true,
(false, true) => (first, second),
(true, false) => (second, first),
(true, true) => return false,
};
let pure = Effects::collect(pure);
pure.reads.is_empty() || {
let impure = Effects::collect(impure);
!impure.opaque && impure.writes.is_disjoint(&pure.reads)
}
}
/// Lists operands in evaluation order. Looks through outer unary operators such as `!` in `!(b
/// !== a)`, which run after their operands. Excludes `delete`, which does not read its operand.
fn eager_operands(result: &Expr) -> Option<Vec<&Expr>> {
match result {
Expr::Paren(paren) => eager_operands(&paren.expr),
Expr::Unary(unary) if unary.op != UnaryOp::Delete => eager_operands(&unary.arg),
Expr::Bin(binary) if !binary.op.may_short_circuit() => {
Some(vec![&binary.left, &binary.right])
}
// The property key is converted after both operands are evaluated.
Expr::Member(member) => match &member.prop {
MemberProp::Ident(_) => Some(vec![&member.obj]),
MemberProp::Computed(key) => Some(vec![&member.obj, &key.expr]),
MemberProp::PrivateName(_) => None,
},
Expr::Call(call)
if let Callee::Expr(callee) = &call.callee
&& call.args.iter().all(|argument| argument.spread.is_none()) =>
{
Some(
iter::once(&**callee)
.chain(call.args.iter().map(|argument| &*argument.expr))
.collect(),
)
}
_ => None,
}
}
/// Substitutes arguments for `function` parameters in `result`. Returns `None` unless
/// parameters are distinct plain identifiers.
#[must_use]
fn substitute(function: &FnExpr, result: &Expr, args: &[ExprOrSpread]) -> Option<Expr> {
let mut parameters = HashMap::default();
let bound = function.function.params.iter().zip(args);
for (parameter, argument) in bound {
let parameter = parameter.pat.as_ident()?;
if parameters
.insert(parameter.to_id(), &*argument.expr)
.is_some()
{
return None;
}
}
Some(replace_parameters(result, parameters))
}
/// Substitutes parenthesized arguments for parameter references and parenthesizes the result.
/// Preserves calls without a receiver; see [`needs_detaching`].
#[must_use]
pub(super) fn replace_parameters(expression: &Expr, parameters: HashMap<Id, &Expr>) -> Expr {
let mut replacement = expression.clone();
replacement.visit_mut_with(&mut ParameterReplacer { parameters });
ast::parenthesized(Box::new(replacement))
}
struct ParameterReplacer<'arguments> {
parameters: HashMap<Id, &'arguments Expr>,
}
impl VisitMut for ParameterReplacer<'_> {
fn visit_mut_call_expr(&mut self, call: &mut CallExpr) {
use swc_core::common::Spanned;
let parameter_callee = matches!(&call.callee, Callee::Expr(callee)
if callee.as_ident().is_some_and(|id| self.parameters.contains_key(&id.to_id())));
call.visit_mut_children_with(self);
if parameter_callee
&& let Callee::Expr(callee) = &mut call.callee
&& needs_detaching(callee.unwrap_parens())
{
// The wrapper calls a parameter as a value. Substituting `obj.method`
// must not bind `obj` as `this`, or turn a passed `eval` into direct eval.
**callee = Expr::Seq(SeqExpr {
span: callee.span(),
exprs: vec![
Box::new(Expr::Lit(Lit::Num(Number {
span: callee.span(),
value: 0.0,
raw: None,
}))),
callee.clone(),
],
});
}
}
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Ident(identifier) = expression
&& let Some(value) = self.parameters.get(&identifier.to_id())
{
*expression = ast::parenthesized(Box::new((*value).clone()));
}
}
}
/// Checks whether a substituted callee needs `(0, callee)` to preserve call behavior. Member
/// references would otherwise receive `this`, and `eval` could become a direct eval call. A
/// local named `eval` may also hold the built-in function.
fn needs_detaching(callee: &Expr) -> bool {
match callee {
Expr::Member(_) | Expr::SuperProp(_) | Expr::OptChain(_) => true,
Expr::Ident(identifier) => identifier.sym == "eval",
_ => false,
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
/// Helper-call test cases and expected results. Calls remain unchanged when inlining could
/// alter evaluation or its order. `set()` writes the parameters read by the arguments;
/// `first()` and `second()` have unknown effects.
const CALLS: [(&str, &str, &str); 27] = [
// Inlined results are parenthesized, as are their substituted arguments.
(
"function(a, b) { return a & b; }",
"h.op(local >>> 16, 65535) * 8133",
"((local >>> 16) & (65535)) * 8133",
),
// Eager operators evaluate their operands in argument order.
(
"function(a, b) { return a + b; }",
"h.op(values[i++], first())",
"(values[i++]) + (first())",
),
// Reordering is safe when only one operand has effects and the other reads no affected
// binding.
(
"function(a, b) { return b - a; }",
"h.op(values[i++], 2)",
"(2) - (values[i++])",
),
(
"function(a, b) { return b === a; }",
"h.op(typeof values, 'object')",
"('object') === (typeof values)",
),
(
"function(a, b) { return b | a; }",
"h.op(first(), 2)",
"(2) | (first())",
),
// An effect-free operand may move past a write only if it does not read the written
// binding.
(
"function(a, b) { return b | a; }",
"h.op(values[i++], local)",
"(local) | (values[i++])",
),
(
"function(a, b) { return b | a; }",
"h.op(values[i++], i)",
"h.op(values[i++], i)",
),
(
"function(a, b) { return b | a; }",
"h.op(set(), v)",
"h.op(set(), v)",
),
(
"function(a, b) { return b | a; }",
"h.op(v, set())",
"h.op(v, set())",
),
(
"function(a, b) { return b === a; }",
"h.op(first(), second())",
"h.op(first(), second())",
),
// An outer unary operator runs after both operands, so `!(b !== a)` permits the same
// reordering as `b === a`. `delete` has different operand evaluation rules.
(
"function(aX, ae) { return !(ae !== aX); }",
"h.op(q._cf_chl_opt.EcMJs8, 1)",
"!((1) !== (q._cf_chl_opt.EcMJs8))",
),
(
"function(a, b) { return -(b - a); }",
"h.op(q.x, 2)",
"-((2) - (q.x))",
),
(
"function(aX, ae) { return !(ae !== aX); }",
"h.op(first(), second())",
"h.op(first(), second())",
),
(
"function(a, b) { return delete b[a]; }",
"h.op(first(), q)",
"h.op(first(), q)",
),
// A member read evaluates its object, then its key.
(
"function(a) { return a.key; }",
"h.op(first())",
"(first()).key",
),
(
"function(a, b) { return b[a]; }",
"h.op(first(), second())",
"h.op(first(), second())",
),
// Unused parameters beyond the supplied arguments can be removed.
(
"function(rn, rw, ri, ru, KA) { return rn(rw, ri, ru); }",
"h.op(local, 1, 2, 3)",
"(local)((1), (2), (3))",
),
(
"function(a, b, extra) { return b | a; }",
"h.op(local, 2, 3)",
"(2) | (local)",
),
(
"function(a, b, extra) { return extra + b; }",
"h.op(1, 2)",
"h.op(1, 2)",
),
(
"function(a, b) { return a + b; }",
"h.op(1, 2, 3)",
"h.op(1, 2, 3)",
),
// Reading an undefined global throws, so such an argument is not
// dropped; a known one like `Math` can be.
(
"function(a, b) { return b; }",
"h.op(missing, 1)",
"h.op(missing, 1)",
),
("function(a, b) { return b; }", "h.op(Math, 1)", "((1))"),
// Tests bodies that skip, repeat, or reorder operands within larger expressions.
(
"function(a, b) { return a + a; }",
"h.op(first(), second())",
"h.op(first(), second())",
),
(
"function(a, b) { return a && b; }",
"h.op(first(), second())",
"h.op(first(), second())",
),
(
"function(a, b) { return (a + 1) + b; }",
"h.op(first(), second())",
"h.op(first(), second())",
),
(
"function(a, a) { return a + a; }",
"h.op(first(), second())",
"h.op(first(), second())",
),
(
"async function(a, b) { return a + b; }",
"h.op(1, 2)",
"h.op(1, 2)",
),
];
fn transform(source: &str) -> String {
testing::rewrite(source, super::run, /* fix= */ false)
}
#[test]
fn inlines_calls_only_when_evaluation_is_unchanged() {
for (method, call, expected) in CALLS {
let output = transform(&format!(
"function f(h, i, values, q, local, v) {{ h = {{ op: {method} }}; \
const set = () => v = 1; return {call}; }}"
));
assert!(output.contains(expected), "{method} {call}: {output}");
}
// Forwarded methods and `eval` are detached from their receiver.
let output = testing::transform(
r#"function f(h, obj, plain) {
h = { invoke: function(fn, arg) { return fn(arg); } };
h.invoke(obj.method, effect());
h.invoke(plain, 1);
h.invoke(Number, obj.value);
return h.invoke(eval, "typeof local");
}"#,
);
testing::assert_contains(&output, &["(0, obj.method)(effect())", "plain(1);"], &[]);
let expected = ["(0, eval)(\"typeof local\")", "Number(obj.value);"];
testing::assert_contains(&output, &expected, &[]);
assert!(!output.contains("(0, plain)"), "{output}");
}
#[test]
fn inlines_member_assigned_properties_and_helper_functions() {
let output = transform(
"function f(h, p) { h = {}; h.op = function (a, b) { return a + b; }; \
h.name = \"n\"; p = h; return [p.op(1, 2), p.name, h.name]; }",
);
assert!(output.contains("(1) + (2)"), "{output}");
testing::assert_lacks(&output, &["p.name", "h.name]"]);
// Helper functions inline when they name only what callers see.
let output = transform(
"function f(add, call, read, g) { add = function(a, b) { return a + b; }; \
call = function(a) { return add(a, 1) + Math.max(a); }; \
g = function(local) { read = function() { return local; }; }; \
g(5); return [call(2), add(3, 4), read()]; }",
);
let expected = ["((2)) + (1))", "Math.max((2))", "(3) + (4)", "read()]"];
testing::assert_contains(&output, &[], &expected);
}
#[test]
fn preserves_reassigned_objects_regular_expressions_and_what_methods_reach() {
let output = transform(
r#"function g(h, out) {
h = { add: function (a, b) { return a + b; }, name: "first" };
out = [h.add(1, 2), h.name];
h = other();
out.push(h.add(3, 4), h.name);
return out;
}
function k(h, alias) {
h = { add: function (a, b) { return a + b; }, name: "first" };
alias = h;
alias = other();
return [alias.add(1, 2), alias.name, h.add(1, 2)];
}"#,
);
testing::assert_contains(&output, &["h.add(1, 2)", "h.add(3, 4)"], &[]);
assert!(output.matches("h.name").count() == 2, "{output}");
testing::assert_contains(&output, &["alias.add(1, 2)", "alias.name"], &[]);
assert!(
!output.contains("(1) + (2)"),
"`h` is copied into a binding that is assigned again, which could change it before \
that, so its properties are not trusted either: {output}"
);
assert!(
output.matches("\"first\"").count() == 2,
"nor are the literals of `h`: {output}"
);
let output = transform(
"function f(s, h) { s = { n: 0, inc: function () { this.n++; } }; s.inc(); \
h = { re: /a/g }; return [s.n, h.re.test(x), h.re.test(x)]; }",
);
assert!(output.contains("s.n,"), "{output}");
assert_eq!(output.matches("h.re.test").count(), 2, "{output}");
}
}
+161
View File
@@ -0,0 +1,161 @@
//! Inlines constant string-table reads through a single accessor:
//!
//! ```js
//! t = ["apply", "push"];
//! function a(i) { return t[i] }
//! a(1); // becomes "push"
//! ```
//!
//! Requires one assignment of a string-literal array and no table reads outside the accessor,
//! ensuring that entries remain unchanged.
use swc_core::ecma::ast::{Expr, FnDecl, Id, Lit, MemberProp, Program, Str, VarDeclarator};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::Analysis;
use super::{HashMap, HashSet};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let bindings = analysis.bindings(program);
let mut tables = Tables::default();
program.visit_with(&mut tables);
let mut changed = false;
for Accessor { accessor, table } in tables.accessors {
// The accessor's declaration is its only write.
if bindings.is_written_once(&accessor)
&& bindings.is_written_once(&table)
&& bindings.references(&table) == 1
&& let Some(strings) = tables.strings.get(&table)
{
let mut inline = InlineTable {
aliases: bindings.aliases(&accessor),
strings,
changed: false,
};
program.visit_mut_with(&mut inline);
changed |= inline.changed;
}
}
changed
}
/// Finds string tables and their accessor functions.
#[derive(Default)]
struct Tables {
accessors: Vec<Accessor>,
/// Bindings assigned string-literal arrays, paired with their contents.
strings: HashMap<Id, Vec<Str>>,
}
/// An accessor `function a(i) { return t[i] }`.
struct Accessor {
accessor: Id,
table: Id,
}
impl Tables {
fn record(&mut self, id: Id, value: &Expr) {
let strings: Option<Vec<Str>> = value.as_array().and_then(|array| {
array
.elems
.iter()
.map(|element| {
let element = element
.as_ref()
.filter(|element| element.spread.is_none())?;
Some(element.expr.as_lit()?.as_str()?.clone())
})
.collect()
});
if let Some(strings) = strings {
self.strings.insert(id, strings);
}
}
}
impl Visit for Tables {
fn visit_expr(&mut self, expression: &Expr) {
if let Some((id, value)) = ast::assignment(expression) {
self.record(id, value);
}
expression.visit_children_with(self);
}
fn visit_var_declarator(&mut self, declaration: &VarDeclarator) {
if let Some(id) = declaration.name.as_ident()
&& let Some(init) = &declaration.init
{
self.record(id.to_id(), init);
}
declaration.visit_children_with(self);
}
fn visit_fn_decl(&mut self, function: &FnDecl) {
if let [param] = function.function.params.as_slice()
&& let Some(param) = param.pat.as_ident()
&& let Some(Expr::Member(member)) = ast::returned(&function.function)
&& let MemberProp::Computed(index) = &member.prop
&& index.expr.as_ident().map(|id| id.to_id()) == Some(param.to_id())
&& let Some(table) = member.obj.as_ident()
{
self.accessors.push(Accessor {
accessor: function.ident.to_id(),
table: table.to_id(),
});
}
function.visit_children_with(self);
}
}
struct InlineTable<'table> {
aliases: HashSet<Id>,
strings: &'table [Str],
changed: bool,
}
impl VisitMut for InlineTable<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
use swc_core::common::Spanned;
expression.visit_mut_children_with(self);
if let Some((callee, [index])) = ast::direct_call(expression)
&& self.aliases.contains(&callee.to_id())
&& index.spread.is_none()
&& let Some(index) = ast::index_literal(&index.expr)
&& let Some(string) = self.strings.get(index)
{
*expression = Expr::Lit(Lit::Str(Str {
span: expression.span(),
..string.clone()
}));
self.changed = true;
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn inlines_reads_only_from_tables_that_cannot_change_or_escape() {
let inline = |source: &str| testing::rewrite(source, super::run, /* fix= */ false);
let output = inline(
r#"var t; t = ["apply", "push"];
function a(i) { return t[i]; }
var b = a;
f(a(0), b(1), a(2), a(n));"#,
);
testing::assert_contains(&output, &[r#"f("apply", "push", a(2), a(n))"#], &[]);
for source in [
r#"var t = ["x"]; function a(i) { return t[i]; } t.push("y"); f(a(0));"#,
r#"var t = ["x"]; function a(i) { return t[i]; } t = ["y"]; f(a(0));"#,
r#"var t = ["x", g()]; function a(i) { return t[i]; } f(a(0));"#,
r#"var t = ["x"]; function a(i) { return t[i]; } a = h; f(a(0));"#,
] {
assert!(inline(source).contains("f(a(0))"), "{source}");
}
}
}
+232
View File
@@ -0,0 +1,232 @@
//! Replaces calls to helpers that reconstruct their argument's low bits by counting:
//!
//! ```js
//! function convert(x) {
//! var low = x & 7, count = 0;
//! for (; low; low--) { count++; }
//! return x & -8 | count;
//! }
//! convert(a & 255); // becomes a & 255
//! convert(a); // becomes a | 0
//! ```
//!
//! The helper is `ToInt32` when its two masks complement each other, so an argument that is
//! already a 32-bit integer is returned unchanged. Requires a helper declared once. Removes the
//! helper once no reads remain.
use swc_core::ecma::ast::{
BinExpr, BinaryOp, Decl, Expr, FnDecl, Function, Id, Lit, Number, Program, Stmt, UnaryOp,
UpdateOp, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::Analysis;
use super::{HashMap, HashSet, bitwise, removal};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let bindings = analysis.bindings(program);
let mut helpers = Helpers::default();
program.visit_with(&mut helpers);
helpers.0.retain(|id| bindings.is_written_once(id));
if helpers.0.is_empty() {
return false;
}
let mut inline = InlineCalls {
helpers: &helpers.0,
replaced: HashMap::default(),
};
program.visit_mut_with(&mut inline);
let uncalled = removal::unread(&inline.replaced, bindings);
program.visit_mut_with(&mut RemoveHelpers(uncalled));
!inline.replaced.is_empty()
}
/// Declared helpers, by binding.
#[derive(Default)]
struct Helpers(Vec<Id>);
impl Visit for Helpers {
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
if helper_mask(&declaration.function).is_some() {
self.0.push(declaration.ident.to_id());
}
declaration.visit_children_with(self);
}
}
/// The mask of a helper, or `None` if `function` is not one. Its declarations may be split:
///
/// ```js
/// function(x) {
/// var low = x & mask, count = 0;
/// for (; low; low--) count++;
/// return x & ~mask | count;
/// }
/// ```
fn helper_mask(function: &Function) -> Option<i32> {
let [parameter] = &function.params[..] else {
return None;
};
let [
declarations @ ..,
Stmt::For(counting),
Stmt::Return(returned),
] = &function.body.as_ref()?.stmts[..]
else {
return None;
};
let mut declarators: Vec<&VarDeclarator> = Vec::new();
for statement in declarations {
declarators.extend(&statement.as_decl()?.as_var()?.decls);
}
let [low, count] = declarators[..] else {
return None;
};
let argument = parameter.pat.as_ident()?.to_id();
let low_name = low.name.as_ident()?.to_id();
let count_name = count.name.as_ident()?.to_id();
let mask = masked(low.init.as_deref()?, &argument)?;
let combined = returned.arg.as_deref()?.unwrap_parens().as_bin()?;
let increment = match &*counting.body {
Stmt::Block(block) => match &block.stmts[..] {
[statement] => statement,
_ => return None,
},
statement => statement,
};
let reads = |expression: &Expr, id: &Id| {
expression
.as_ident()
.is_some_and(|name| name.to_id() == *id)
};
let updates = |expression: &Expr, id: &Id, op: UpdateOp| {
expression
.as_update()
.is_some_and(|update| update.op == op && reads(&update.arg, id))
};
let is_helper = mask >= 0
&& count.init.as_deref().and_then(ast::number) == Some(0.0)
&& counting.init.is_none()
&& counting
.test
.as_deref()
.is_some_and(|test| reads(test, &low_name))
&& counting
.update
.as_deref()
.is_some_and(|update| updates(update, &low_name, UpdateOp::MinusMinus))
&& increment
.as_expr()
.is_some_and(|statement| updates(&statement.expr, &count_name, UpdateOp::PlusPlus))
&& combined.op == BinaryOp::BitOr
&& masked(&combined.left, &argument) == Some(!mask)
&& reads(&combined.right, &count_name);
is_helper.then_some(mask)
}
/// The `mask` of `argument & mask`, if it is a 32-bit integer.
fn masked(expression: &Expr, argument: &Id) -> Option<i32> {
let Expr::Bin(BinExpr {
op: BinaryOp::BitAnd,
left,
right,
..
}) = expression.unwrap_parens()
else {
return None;
};
if left.as_ident()?.to_id() != *argument {
return None;
}
let mask = ast::number(right)?;
if mask.fract() != 0.0 {
return None;
}
i32::try_from(mask as i64).ok()
}
/// Whether `expression` always evaluates to a 32-bit signed integer. `>>>` yields an unsigned
/// one.
fn is_int32(expression: &Expr) -> bool {
match expression.unwrap_parens() {
Expr::Bin(binary) => {
bitwise::is_bitwise(binary.op) && binary.op != BinaryOp::ZeroFillRShift
}
Expr::Unary(unary) => unary.op == UnaryOp::Tilde,
Expr::Lit(Lit::Num(number)) => f64::from(number.value as i32) == number.value,
_ => false,
}
}
/// Replaces `helper(x)` with `x`, or `x | 0` when `x` may not be a 32-bit integer.
struct InlineCalls<'helpers> {
helpers: &'helpers [Id],
replaced: HashMap<Id, usize>,
}
impl VisitMut for InlineCalls<'_> {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
let Some((callee, [argument])) = ast::direct_call(expression) else {
return;
};
if argument.spread.is_some() || !self.helpers.contains(&callee.to_id()) {
return;
}
*self.replaced.entry(callee.to_id()).or_default() += 1;
let span = callee.span;
let argument = argument.expr.clone();
*expression = if is_int32(&argument) {
ast::parenthesized(argument)
} else {
Expr::Bin(BinExpr {
span,
op: BinaryOp::BitOr,
left: Box::new(ast::parenthesized(argument)),
right: Box::new(Expr::Lit(Lit::Num(Number {
span,
value: 0.0,
raw: None,
}))),
})
};
}
}
/// Removes the declarations of helpers nothing calls any longer.
struct RemoveHelpers(HashSet<Id>);
impl VisitMut for RemoveHelpers {
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.retain(|statement| {
!matches!(statement, Stmt::Decl(Decl::Fn(declaration))
if self.0.contains(&declaration.ident.to_id()))
});
statements.visit_mut_children_with(self);
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
const HELPER: &str = "function convert(x) {
var low = x & 7, count = 0;
for (; low; low--) { count++; }
return x & -8 | count;
}";
#[test]
fn inlines_helpers_whose_masks_complement() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(&format!(
"{HELPER}\nf(convert(a - b & 255), convert(a), convert(~a));"
));
testing::assert_contains(&output, &[], &["f(a - b & 255, a | 0, ~a)"]);
assert!(!output.contains("function convert"), "{output}");
let helper = HELPER.replace("-8", "-16");
let output = transform(&format!("{helper}\nf(convert(a & 255));"));
assert!(output.contains("convert(a & 255)"), "{output}");
}
}
+113
View File
@@ -0,0 +1,113 @@
//! Restores plain expressions from minifier forms:
//!
//! ```js
//! !0; void 0; (0, f)(x); // becomes true; undefined; f(x)
//! ```
//!
//! Folds `!` and `void` only for effect-free literal operands. Unwraps literal callee sequences
//! only when they end in an identifier other than `eval`, preserving call behavior. New
//! `undefined` references use the global resolution context.
use swc_core::ecma::ast::{
ArrayLit, Bool, Callee, Expr, Lit, ObjectLit, Program, UnaryExpr, UnaryOp,
};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::{Analysis, Globals};
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let mut restore = RestoreKeywords {
globals: analysis.globals,
changed: false,
};
program.visit_mut_with(&mut restore);
restore.changed
}
struct RestoreKeywords {
globals: Globals,
changed: bool,
}
impl VisitMut for RestoreKeywords {
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Unary(UnaryExpr { span, op, arg }) = expression
&& let Some(truthy) = literal_truthiness(arg)
{
*expression = match op {
UnaryOp::Bang => Expr::Lit(Lit::Bool(Bool {
span: *span,
value: !truthy,
})),
UnaryOp::Void => Expr::Ident(self.globals.reference("undefined", *span)),
_ => return,
};
self.changed = true;
}
}
/// `(0, f)` and `f` both call without a receiver, except when `f` is named `eval`. Calling
/// that name directly may invoke direct eval, even for a local binding holding the built-in
/// function.
fn visit_mut_callee(&mut self, callee: &mut Callee) {
callee.visit_mut_children_with(self);
if let Callee::Expr(expression) = callee
&& let Expr::Seq(sequence) = expression.unwrap_parens_mut()
&& let [discarded @ .., last] = &sequence.exprs[..]
&& let Expr::Ident(name) = &**last
&& name.sym != "eval"
&& discarded.iter().all(|operand| operand.is_lit())
{
let name = sequence.exprs.pop().expect("the sequence ends in a name");
*expression = name;
self.changed = true;
}
}
}
/// Truthiness of a side-effect-free literal, or `None` if it is not one.
fn literal_truthiness(expression: &Expr) -> Option<bool> {
match expression {
Expr::Lit(Lit::Num(number)) => Some(number.value != 0.0 && !number.value.is_nan()),
Expr::Lit(Lit::Str(string)) => Some(!string.value.is_empty()),
Expr::Lit(Lit::Bool(boolean)) => Some(boolean.value),
Expr::Lit(Lit::Null(_)) => Some(false),
Expr::Array(ArrayLit { elems, .. }) if elems.is_empty() => Some(true),
Expr::Object(ObjectLit { props, .. }) if props.is_empty() => Some(true),
Expr::Paren(paren) => literal_truthiness(&paren.expr),
_ => None,
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn restores_literals_and_direct_calls() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output =
transform("function f() { return [!0, !1, !2, !'', !'a', !null, !![], !{}]; }");
testing::assert_contains(
&output,
&[],
&["true, false, false, true, false, true, true, false"],
);
assert!(!output.contains('!'), "{output}");
assert_eq!(transform(&output), output);
let output = transform("function f(x) { x = void 0; return x === void 0 ? void 1 : x; }");
let expected = ["x = undefined;", "x === undefined ? undefined : x"];
testing::assert_contains(&output, &expected, &[]);
assert!(!output.contains("void"), "{output}");
// Operands that may have effects stay.
let output = transform("function f(x) { return [!x, !f(), !x.y, void f(), void x]; }");
testing::assert_contains(&output, &["!x", "!f()", "!x.y", "void f()", "void x"], &[]);
assert!(!output.contains("undefined"), "{output}");
// Indirect calls of names other than `eval` become direct.
let output = transform("function f(g, o) { (0, g)(this, 1); (0, o.m)(); (0, eval)('x'); }");
testing::assert_contains(&output, &["g(this, 1);", "(0, o.m)();", "(0, eval)("], &[]);
}
}
+83
View File
@@ -0,0 +1,83 @@
//! Restores loop bodies and `while` loops from minified `for` headers:
//!
//! ```js
//! for (; test; effect(), i++); // becomes for (; test; i++) { effect(); }
//! ```
//!
//! Requires a final increment preceded only by effects. Moving those effects into an empty body
//! preserves their execution point. A loop with no initializer or update becomes `while`.
use std::mem;
use swc_core::ecma::ast::{Bool, Expr, Lit, Program, Stmt, WhileStmt};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::Analysis;
use crate::js::ast;
pub(super) fn run(program: &mut Program, _: &mut Analysis) -> bool {
let mut restore = RestoreLoops { changed: false };
program.visit_mut_with(&mut restore);
restore.changed
}
struct RestoreLoops {
changed: bool,
}
impl VisitMut for RestoreLoops {
fn visit_mut_stmt(&mut self, statement: &mut Stmt) {
use swc_core::common::util::take::Take;
statement.visit_mut_children_with(self);
let Stmt::For(loop_statement) = statement else {
return;
};
if loop_statement.body.is_empty()
&& let Some(update) = &mut loop_statement.update
&& let Expr::Seq(sequence) = &mut **update
&& let Some(last) = sequence.exprs.pop()
{
let effects = mem::take(&mut sequence.exprs);
**update = *last;
let statements: Vec<Stmt> =
effects.into_iter().map(ast::expression_statement).collect();
*loop_statement.body = ast::block(statements);
self.changed = true;
}
// An absent test is the implicit `true` that `for (;;)` means.
if loop_statement.init.is_none() && loop_statement.update.is_none() {
let span = loop_statement.span;
*statement = Stmt::While(WhileStmt {
span,
test: loop_statement
.test
.take()
.unwrap_or_else(|| Box::new(Expr::Lit(Lit::Bool(Bool { span, value: true })))),
body: loop_statement.body.take(),
});
self.changed = true;
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn restores_loop_bodies_and_while_loops() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform("for (var i = 0; i < n; use(i), tick(), i++);");
assert!(output.contains("for(var i = 0; i < n; i++)"), "{output}");
testing::assert_contains(&output, &[], &["use(i); tick();"]);
let output = transform("for (; ready; use(i), i++) work();");
assert!(
output.contains("for(; ready; use(i), i++)"),
"only an empty body takes the effects: {output}"
);
let output = transform("for (;;) tick(); for (; ready;) work(); for (; ready; step());");
let expected = ["while(true)", "while(ready)", "for(; ready; step())"];
testing::assert_contains(&output, &expected, &[]);
}
}
+319
View File
@@ -0,0 +1,319 @@
//! Parses a challenge script, runs the deobfuscation rewrites in rounds, and prints the result
//! through SWC.
use std::fmt;
use std::sync::Arc;
use anyhow::Result;
use rustc_hash::FxHasher;
use swc::Compiler;
use swc::config::{Config, IsModule, JscConfig, Options};
use swc_core::common::comments::SingleThreadedComments;
use swc_core::common::errors::Handler;
use swc_core::common::{BytePos, FileName, GLOBALS, Globals, Mark, SourceMap};
use swc_core::ecma::ast::{EsVersion, Pass, Program, fn_pass, noop_pass};
use swc_ecma_transforms::optimization::simplify::expr::{self, Config as ExprSimplifierConfig};
use swc_ecma_transforms::{fixer, hygiene};
use super::analysis::Analysis;
use super::{
HashMap, argument_arrays, bitwise, blocks, constant_objects, control_flow, copy_propagation,
dead_branches, dead_properties, dispatch, encoded_strings, function_lengths, helper_objects,
indexed_table, int32_helpers, literals, loops, scratch_parameters, statements, static_members,
string_array, unused_bindings,
};
/// Deobfuscated JavaScript with optional convergence diagnostics for the caller to report.
pub struct Deobfuscated {
/// JavaScript printed after the rewrites, including partial output if they hit the limit.
pub text: String,
/// Diagnostics when rewrites reached the round limit before settling.
pub unconverged: Option<Unconverged>,
}
/// Applies the same SWC transformations to saved scripts and newly fetched iframe scripts.
pub fn deobfuscate(source: String) -> Result<Deobfuscated> {
Ok(deobfuscate_with(source, |_, _| ())?.0)
}
/// Deobfuscates `source`, then calls `read` before printing the result. The callback receives
/// the deobfuscated program and the source's starting position. Retained nodes keep their
/// original spans so the callback can locate them in the input.
pub(crate) fn deobfuscate_with<T>(
source: String,
read: impl FnMut(&Program, BytePos) -> T,
) -> Result<(Deobfuscated, T)> {
// Hygiene renames bindings whose references moved into conflicting scopes. It runs last
// because it clears the syntax contexts the rewrites use.
run(source, STEPS, hygiene::hygiene, read)
}
/// Calls `read` after normalization and table decoding, which preserve browser-visible
/// structure and positions. Passes the source and its starting position. Returns partial output
/// if decoding does not converge.
pub(crate) fn read_decoded<T>(
source: String,
read: impl FnMut(&Program, BytePos) -> Result<T>,
) -> Result<T> {
run(source, &[DECODE_STEPS], noop_pass, read)?.1
}
/// Runs `steps`, then the pass `finish` returns, then `read`, and prints the result.
fn run<T, P: Pass>(
source: String,
steps: &'static [&'static [Step]],
finish: impl FnOnce() -> P,
mut read: impl FnMut(&Program, BytePos) -> T,
) -> Result<(Deobfuscated, T)> {
use anyhow::Context;
let mut result = None;
let slot = &mut result;
let mut unconverged = None;
let text = transform(source, |start, unresolved_mark| {
(
Pipeline {
steps,
unconverged: &mut unconverged,
analysis: Analysis::new(unresolved_mark),
version: 0,
unchanged_at: HashMap::default(),
},
finish(),
fn_pass(move |program: &mut Program| *slot = Some(read(program, start))),
)
})?;
let read = result.context("the script was never read")?;
Ok((Deobfuscated { text, unconverged }, read))
}
/// Parses `source` as a classic script and applies `pass` before printing. The pass receives
/// the source start and the resolver's mark for unresolved references. Disables SWC's early
/// hygiene pass because it would clear syntax contexts needed by the rewrites.
pub(super) fn transform<P: Pass>(
source: String,
pass: impl FnOnce(BytePos, Mark) -> P,
) -> Result<String> {
let source_map: Arc<SourceMap> = Arc::default();
let handler =
Handler::with_emitter_writer(Box::new(std::io::stderr()), Some(source_map.clone()));
let compiler = Compiler::new(source_map.clone());
let file = source_map.new_source_file(FileName::Custom("challenge.js".into()).into(), source);
let start = file.start_pos;
GLOBALS.set(&Globals::new(), || {
// Marks belong to the globals they are created in.
let unresolved_mark = Mark::new();
let options = Options {
disable_hygiene: true,
skip_helper_injection: true,
unresolved_mark: Some(unresolved_mark),
top_level_mark: Some(Mark::new()),
config: Config {
jsc: JscConfig {
target: Some(EsVersion::EsNext),
..Default::default()
},
is_module: Some(IsModule::Bool(false)),
..Default::default()
},
..Default::default()
};
let output = compiler.process_js_with_custom_pass(
file,
None,
&handler,
&options,
SingleThreadedComments::default(),
|_| noop_pass(),
|_| pass(start, unresolved_mark),
)?;
Ok(output.code)
})
}
/// The rounds stopped at their limit while some rewrite still changed the
/// program, so the output may be partially transformed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Unconverged {
/// How many rounds ran before the limit stopped them.
pub rounds: usize,
}
impl fmt::Display for Unconverged {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"deobfuscation stopped after {} rounds without converging; \
the output may be partially transformed",
self.rounds
)
}
}
/// A named rewrite that reports whether it changed the program. Repeated occurrences share a
/// name. Running any occurrence records that the step has processed the current program.
struct Step {
name: &'static str,
rewrite: fn(&mut Program, &mut Analysis) -> bool,
}
const fn step(name: &'static str, rewrite: fn(&mut Program, &mut Analysis) -> bool) -> Step {
Step { name, rewrite }
}
const SIMPLIFY: Step = step("simplify", simplify);
const STATIC_MEMBERS: Step = step("static members", static_members::run);
const HELPER_OBJECTS: Step = step("helper objects", helper_objects::run);
const CONTROL_FLOW: Step = step("control flow", control_flow::run);
const UNUSED_BINDINGS: Step = step("unused bindings", unused_bindings::run);
const FIX_PARENTHESES: Step = step("fix parentheses", fix_parentheses);
const STEPS: &[&[Step]] = &[DECODE_STEPS, LATER_STEPS];
/// The normalizing and table-recovering steps, which also form the decoding-only pass.
const DECODE_STEPS: &[Step] = &[
// Normalize.
SIMPLIFY,
step("function lengths", function_lengths::run),
step("bitwise operands", bitwise::run),
step("constant objects", constant_objects::run),
step("dead branches", dead_branches::run),
// Recover tables.
step("encoded strings", encoded_strings::run),
step("string array", string_array::run),
step("indexed table", indexed_table::run),
step("argument arrays", argument_arrays::run),
step("dispatch", dispatch::run),
];
/// The steps that restructure the script once its tables are decoded.
const LATER_STEPS: &[Step] = &[
// Inline helpers, once unused scratch declarations no longer hide their returns.
UNUSED_BINDINGS,
STATIC_MEMBERS,
HELPER_OBJECTS,
STATIC_MEMBERS,
SIMPLIFY,
CONTROL_FLOW,
// Remove dead helpers.
HELPER_OBJECTS,
UNUSED_BINDINGS,
STATIC_MEMBERS,
step("dead properties", dead_properties::run),
SIMPLIFY,
CONTROL_FLOW,
// Expand statements.
step("literals", literals::run),
step("statements", statements::run),
FIX_PARENTHESES,
// Clean up locals. Propagate copies before narrowing parameters so unused parameters are
// removed instead of declared. The next round fixes parentheses.
step("blocks", blocks::run),
step("loops", loops::run),
step("copy propagation", copy_propagation::run),
// Run after copy propagation so the masks are constants.
step("int32 helpers", int32_helpers::run),
step("scratch parameters", scratch_parameters::run),
];
/// Guards against rewrites that keep undoing each other.
const MAX_ROUNDS: usize = 10;
/// Runs ordered groups of steps and tracks which have seen the current program. Grouping lets a
/// pass run a prefix of [`STEPS`].
struct Pipeline<'outcome> {
steps: &'static [&'static [Step]],
unconverged: &'outcome mut Option<Unconverged>,
analysis: Analysis,
/// Program version, incremented after each change.
version: u64,
/// Last program version each named step processed without changes.
unchanged_at: HashMap<&'static str, u64>,
}
impl Pass for Pipeline<'_> {
fn process(&mut self, program: &mut Program) {
let mut converged = false;
let mut rounds = 0;
while !converged && rounds < MAX_ROUNDS {
rounds += 1;
let start = fingerprint(program);
converged = self.round(program) || fingerprint(program) == start;
}
*self.unconverged = (!converged).then_some(Unconverged { rounds });
// Even without convergence, fix parentheses introduced by the last rewrites so output
// prints correctly.
self.run(&FIX_PARENTHESES, program);
}
}
impl Pipeline<'_> {
/// Runs the steps in order, stopping early once every step has seen the current program.
/// Returns whether that happened.
fn round(&mut self, program: &mut Program) -> bool {
let steps = self.steps.iter().copied().flatten();
for step in steps.clone() {
self.run(step, program);
if steps.clone().all(|step| self.has_seen(step)) {
return true;
}
}
false
}
/// Whether `step` last ran on this exact program without changing it.
fn has_seen(&self, step: &Step) -> bool {
self.unchanged_at.get(step.name) == Some(&self.version)
}
/// Runs `step` unless it already ran on this exact program.
fn run(&mut self, step: &Step, program: &mut Program) {
if self.has_seen(step) {
return;
}
// Tests check every step's report against the program itself.
let before = cfg!(test).then(|| fingerprint(program));
let changed = (step.rewrite)(program, &mut self.analysis);
if let Some(before) = before {
assert_eq!(
changed,
fingerprint(program) != before,
"the {} step misreported whether it changed the program",
step.name
);
}
if changed {
self.version += 1;
self.analysis.invalidate();
} else {
self.unchanged_at.insert(step.name, self.version);
}
}
}
/// Hashes the entire syntax tree, including spans and syntax contexts, to detect unreported
/// changes. For a fixed input word, each FxHash step is reversible, so trees whose encodings
/// differ in exactly one word cannot collide.
fn fingerprint(program: &Program) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = FxHasher::default();
program.hash(&mut hasher);
hasher.finish()
}
/// Folds constant expressions such as `1 + 2`. Compares fingerprints because the simplifier's
/// change flag misses some rewrites, such as single-element sequences.
fn simplify(program: &mut Program, analysis: &mut Analysis) -> bool {
let before = fingerprint(program);
expr::expr_simplifier(analysis.globals.mark, ExprSimplifierConfig::default()).process(program);
fingerprint(program) != before
}
/// Adds parentheses that rewritten expressions need, such as in `x = (a, b)`. SWC's own fixer
/// ran before the rewrites.
fn fix_parentheses(program: &mut Program, _: &mut Analysis) -> bool {
let before = fingerprint(program);
fixer::fixer(None).process(program);
fingerprint(program) != before
}
+82
View File
@@ -0,0 +1,82 @@
//! Removes definitions after a rewrite has replaced all reads of their bindings.
use swc_core::ecma::ast::{Expr, Id, Program, SeqExpr, Stmt};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::Bindings;
use super::{HashMap, HashSet};
/// Returns bindings whose reads have all been replaced, using replacement counts for each
/// binding.
#[must_use]
pub(super) fn unread(replaced: &HashMap<Id, usize>, bindings: &Bindings) -> HashSet<Id> {
replaced
.iter()
.filter(|(id, replaced)| **replaced == bindings.references(id))
.map(|(id, _)| id.clone())
.collect()
}
/// Removes assignments to `unread` bindings when their values are discarded. Preserves the
/// final value of a sequence.
pub(super) fn remove_definitions(program: &mut Program, unread: &HashSet<Id>) -> bool {
let mut remove = RemoveDefinitions {
unread,
changed: false,
};
if !unread.is_empty() {
program.visit_mut_with(&mut remove);
}
remove.changed
}
struct RemoveDefinitions<'unread> {
unread: &'unread HashSet<Id>,
changed: bool,
}
impl RemoveDefinitions<'_> {
fn is_definition(&self, expression: &Expr) -> bool {
expression
.as_assign()
.and_then(|assignment| assignment.left.as_ident())
.is_some_and(|identifier| self.unread.contains(&identifier.to_id()))
}
}
impl VisitMut for RemoveDefinitions<'_> {
fn visit_mut_seq_expr(&mut self, sequence: &mut SeqExpr) {
sequence.visit_mut_children_with(self);
// The last operand supplies the sequence's value.
if let Some(last) = sequence.exprs.pop() {
self.changed |= retain(&mut sequence.exprs, |expression| {
!self.is_definition(expression)
});
sequence.exprs.push(last);
}
}
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.visit_mut_children_with(self);
self.changed |= remove_expr_stmts(statements, |expression| self.is_definition(expression));
}
}
/// Retains items accepted by `keep` and returns whether any were removed.
pub(super) fn retain<T>(items: &mut Vec<T>, keep: impl FnMut(&T) -> bool) -> bool {
let count = items.len();
items.retain(keep);
items.len() != count
}
/// Removes expression statements accepted by `dead` and returns whether any were removed.
pub(super) fn remove_expr_stmts(
statements: &mut Vec<Stmt>,
mut dead: impl FnMut(&Expr) -> bool,
) -> bool {
retain(statements, |statement| {
statement
.as_expr()
.is_none_or(|statement| !dead(&statement.expr))
})
}
+458
View File
@@ -0,0 +1,458 @@
//! Replaces trailing scratch parameters with local declarations:
//!
//! ```js
//! function f(a, b, c) { c = a + 1; return c; } // becomes function f(a) { var c; ... }
//! ```
//!
//! The obfuscator uses extra parameters as temporary variables. Converts them only when every
//! path assigns the parameter before reading its incoming value, and removes unused ones. This
//! changes the observable `fn.length`.
//!
//! If a function uses `arguments`, removes only unreferenced parameters unless an immediate
//! call proves that no argument reaches them. This preserves sloppy-mode aliasing between
//! parameters and `arguments[i]`.
use std::mem;
use swc_core::atoms::Atom;
use swc_core::common::DUMMY_SP;
use swc_core::ecma::ast::{
ArrowExpr, AssignExpr, AssignOp, BinExpr, CallExpr, Callee, CondExpr, Decl, Expr, Function, Id,
Ident, Pat, Program, Stmt, VarDecl, VarDeclKind, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::HashSet;
use super::analysis::hoisting::{self, Hoisted, Hoisting};
use super::analysis::{Analysis, names};
pub(super) fn run(program: &mut Program, _: &mut Analysis) -> bool {
let mut demote = DemoteScratchParameters { changed: false };
program.visit_mut_with(&mut demote);
demote.changed
}
struct DemoteScratchParameters {
changed: bool,
}
impl VisitMut for DemoteScratchParameters {
fn visit_mut_function(&mut self, function: &mut Function) {
function.visit_mut_children_with(self);
if function.params.is_empty() {
return;
}
let scratch = Scratch::scan(function);
// Keep parameters through the last one whose incoming value can be observed. With
// mapped `arguments`, even a write can expose the parameter binding.
let needed =
if names::uses_arguments(&function.params) || names::uses_arguments(&function.body) {
&scratch.used
} else {
&scratch.observed
};
let keep = function
.params
.iter()
.rposition(|parameter| {
parameter
.pat
.as_ident()
.is_none_or(|name| needed.contains(&name.to_id()))
})
.map_or(0, |last| last + 1);
self.changed |= demote(function, keep, &scratch.used);
}
fn visit_mut_call_expr(&mut self, call: &mut CallExpr) {
call.visit_mut_children_with(self);
// An immediate anonymous-function call gives the argument count. Plain parameters
// beyond it start as `undefined`, matching replacement locals. Patterns may include
// defaults or rest parameters and need separate handling.
if let Callee::Expr(callee) = &mut call.callee
&& let Expr::Fn(callee) = callee.unwrap_parens_mut()
&& callee.ident.is_none()
&& call.args.iter().all(|argument| argument.spread.is_none())
&& callee
.function
.params
.iter()
.skip(call.args.len())
.all(|parameter| parameter.pat.is_ident())
{
let used = Scratch::scan(&callee.function).used;
self.changed |= demote(&mut callee.function, call.args.len(), &used);
}
}
}
/// Removes parameters starting at `keep`, declaring those `used` as locals. Returns whether
/// parameters were removed.
fn demote(function: &mut Function, keep: usize, used: &HashSet<Id>) -> bool {
if keep >= function.params.len() {
return false;
}
let declarators: Vec<VarDeclarator> = function
.params
.drain(keep..)
.filter_map(|parameter| match parameter.pat {
Pat::Ident(name) if used.contains(&name.to_id()) => Some(VarDeclarator {
span: DUMMY_SP,
name: Pat::Ident(name),
init: None,
definite: false,
}),
_ => None,
})
.collect();
if !declarators.is_empty()
&& let Some(body) = &mut function.body
{
// Insert after directives: moving `"use strict"` behind another statement would disable
// strict mode.
swc_ecma_utils::prepend_stmt(
&mut body.stmts,
Stmt::Decl(Decl::Var(Box::new(VarDecl {
kind: VarDeclKind::Var,
decls: declarators,
..Default::default()
}))),
);
}
true
}
/// Finds parameters that may be read before assignment. Tracks assignments along each path.
/// Assignments in optional or repeated paths are not guaranteed; branch joins keep only
/// assignments made on every path.
#[derive(Default)]
struct Scratch {
parameters: HashSet<Id>,
/// Read on some path before being assigned on it.
observed: HashSet<Id>,
/// Mentioned anywhere, and so still needing a binding.
used: HashSet<Id>,
/// The labelled statements around the node, innermost last.
labels: Vec<Label>,
/// Tracks parameters assigned on the path to the current node.
hoisting: Hoisting<HashSet<Id>>,
}
/// A labelled statement around the node being scanned.
struct Label {
name: Atom,
/// Intersection of assignments from all `break` paths seen so far; absent before the first
/// break.
broken: Option<HashSet<Id>>,
}
impl Scratch {
fn scan(function: &Function) -> Self {
let mut scratch = Self {
parameters: function
.params
.iter()
.filter_map(|parameter| Some(parameter.pat.as_ident()?.to_id()))
.collect(),
..Default::default()
};
if let Some(body) = &function.body {
scratch.hoisting.function_body = true;
scratch.statements(&body.stmts);
}
scratch
}
/// Scans statements and reports whether execution can continue after them. Visits hoisted
/// declarations even after a return or throw, using assignments guaranteed at every
/// possible call. See [`hoisting`].
fn statements(&mut self, statements: &[Stmt]) -> bool {
let mut reachable = true;
hoisting::visit_stmts(self, statements, |scratch, statement| {
reachable &= scratch.statement(statement);
});
reachable
}
/// Whether control can reach the statement after `statement`.
fn statement(&mut self, statement: &Stmt) -> bool {
match statement {
Stmt::Block(block) => self.statements(&block.stmts),
Stmt::Labeled(labeled) => {
self.labels.push(Label {
name: labeled.label.sym.clone(),
broken: None,
});
let flows = self.statement(&labeled.body);
let Label { broken, .. } = self.labels.pop().expect("the label was pushed above");
// A `break` leaves this statement and joins the normal fallthrough path.
match broken {
Some(broken) if flows => {
self.hoisting.facts.retain(|id| broken.contains(id));
true
}
Some(broken) => {
self.hoisting.facts = broken;
true
}
None => flows,
}
}
Stmt::Break(jump) => {
if let Some(label) = &jump.label
&& let Some(Label { broken, .. }) = self
.labels
.iter_mut()
.rev()
.find(|enclosing| enclosing.name == label.sym)
{
match broken {
Some(broken) => broken.retain(|id| self.hoisting.facts.contains(id)),
None => *broken = Some(self.hoisting.facts.clone()),
}
}
// An unlabelled `break` leaves a loop or `switch`, after which
// nothing they assign is known anyway.
false
}
Stmt::Return(_) | Stmt::Throw(_) | Stmt::Continue(_) => {
statement.visit_children_with(self);
false
}
Stmt::If(conditional) => {
conditional.test.visit_with(self);
let entry = self.hoisting.facts.clone();
let consequent = self.path(&entry, |scratch| scratch.statement(&conditional.cons));
let alternate = self.path(&entry, |scratch| {
conditional
.alt
.as_deref()
.is_none_or(|alternate| scratch.statement(alternate))
});
self.hoisting.facts = match (consequent.flows, alternate.flows) {
(true, false) => consequent.assigned,
(false, true) => alternate.assigned,
_ => &consequent.assigned & &alternate.assigned,
};
consequent.flows || alternate.flows
}
Stmt::Expr(_) | Stmt::Decl(_) | Stmt::Empty(_) | Stmt::Debugger(_) => {
statement.visit_children_with(self);
true
}
// The handler may start after any part of the block; the finalizer may start after
// any part of the block or handler. Both therefore use assignments known before the
// block.
Stmt::Try(statement) => {
self.fork(|scratch| statement.block.visit_with(scratch));
self.fork(|scratch| statement.handler.visit_with(scratch));
self.fork(|scratch| statement.finalizer.visit_with(scratch));
true
}
// Cases may be entered by a matching test or by fallthrough. Conservatively start
// each test and case with assignments known after the discriminant.
Stmt::Switch(switch) => {
switch.discriminant.visit_with(self);
for case in &switch.cases {
self.fork(|scratch| case.test.visit_with(scratch));
}
for case in &switch.cases {
self.fork(|scratch| case.cons.visit_with(scratch));
}
true
}
// The update can follow the body or a `continue`, so only assignments before the
// body are guaranteed.
Stmt::For(loop_) => {
self.fork(|scratch| {
loop_.init.visit_with(scratch);
loop_.test.visit_with(scratch);
scratch.fork(|scratch| _ = scratch.statement(&loop_.body));
loop_.update.visit_with(scratch);
});
true
}
// Likewise the test, which a `continue` jumps to.
Stmt::DoWhile(loop_) => {
self.fork(|scratch| {
scratch.fork(|scratch| _ = scratch.statement(&loop_.body));
loop_.test.visit_with(scratch);
});
true
}
// Other loops may execute an unknown number of times. Discard assignments made
// inside them.
statement => {
self.fork(|scratch| statement.visit_children_with(scratch));
true
}
}
}
/// Scans a path that may be skipped, keeping only what it reads.
fn fork(&mut self, scan: impl FnOnce(&mut Self)) {
let entry = self.hoisting.facts.clone();
scan(self);
self.hoisting.facts = entry;
}
/// Scans from `entry`.
fn path(&mut self, entry: &HashSet<Id>, scan: impl FnOnce(&mut Self) -> bool) -> Branch {
self.hoisting.facts.clone_from(entry);
let flows = scan(self);
Branch {
assigned: mem::take(&mut self.hoisting.facts),
flows,
}
}
}
/// What one branch of a conditional guarantees.
struct Branch {
/// Parameters the branch is guaranteed to assign.
assigned: HashSet<Id>,
/// Whether execution can fall through the branch.
flows: bool,
}
impl Visit for Scratch {
fn visit_stmt(&mut self, statement: &Stmt) {
self.statement(statement);
}
fn visit_stmts(&mut self, statements: &[Stmt]) {
self.statements(statements);
}
fn visit_ident(&mut self, identifier: &Ident) {
hoisting::reference(self, identifier);
let id = identifier.to_id();
if self.parameters.contains(&id) {
if !self.hoisting.facts.contains(&id) {
self.observed.insert(id.clone());
}
self.used.insert(id);
}
}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
if assignment.op == AssignOp::Assign
&& let Some(target) = assignment.left.as_ident()
{
// The value is evaluated before the store, so it reads first.
assignment.right.visit_with(self);
let id = target.to_id();
if self.parameters.contains(&id) {
self.used.insert(id.clone());
self.hoisting.facts.insert(id);
}
} else {
assignment.visit_children_with(self);
}
}
fn visit_cond_expr(&mut self, conditional: &CondExpr) {
conditional.test.visit_with(self);
self.fork(|scratch| conditional.cons.visit_with(scratch));
self.fork(|scratch| conditional.alt.visit_with(scratch));
}
fn visit_bin_expr(&mut self, binary: &BinExpr) {
if binary.op.may_short_circuit() {
binary.left.visit_with(self);
self.fork(|scratch| binary.right.visit_with(scratch));
} else {
binary.visit_children_with(self);
}
}
/// A function expression's body uses assignments known when it was created. Declarations
/// use facts supplied by [`Scratch::statements`].
fn visit_function(&mut self, function: &Function) {
self.fork(|scratch| {
function.decorators.visit_with(scratch);
function.params.visit_with(scratch);
if let Some(body) = &function.body {
scratch.hoisting.function_body = true;
scratch.statements(&body.stmts);
}
});
}
fn visit_arrow_expr(&mut self, arrow: &ArrowExpr) {
self.fork(|scratch| arrow.visit_children_with(scratch));
}
}
impl Hoisted for Scratch {
type Facts = HashSet<Id>;
fn hoisting(&mut self) -> &mut Hoisting<HashSet<Id>> {
&mut self.hoisting
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn demotes_parameters_every_path_writes_first() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform("function f(a, b, c, d) { c = a + 1; return c; }");
testing::assert_contains(&output, &["function f(a)", "var c;"], &[]);
assert!(!output.contains('d'), "{output}");
for source in [
"function f(x, a) { if (x) { a = 1; use(a); } else { for (a = 0; a < 2; a++) use(a); } }",
"function f(c, a) { l: { if (c) { a = 2; break l; } a = 1; } return a; }",
"function f(c, a) { try { a = 1; } catch (e) {} return; }",
"function f(a) { a = 1; g(); function g() { return a; } }",
] {
let output = transform(source);
assert!(output.contains("var a;"), "{source}: {output}");
}
// An immediate call leaves every parameter past its arguments unset.
let output = transform("(function (a, b, c) { g(b); b = 1; return a + b + c; })(x);");
testing::assert_contains(&output, &["function(a)", "var b, c;"], &[]);
}
#[test]
fn keeps_parameters_that_may_hold_an_argument() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
// Additional try, switch, label, and loop cases are covered in `tests/deobfuscate.rs`.
for source in [
"function f(a) { a = a || 1; return a; }",
"function f(a) { if (x) a = 1; return a; }",
"function f(a) { for(;;) a = 1; return a; }",
"function f(a) { x ? a = 1 : 0; return a; }",
"function f(a) { x && (a = 1); return a; }",
"function f(a) { g(); a = 1; function g() { return a; } }",
"function f(a) { g(a); a = 1; return a; }",
"function f(a) { h(); a = 1; function h() { return g(); } function g() { return a; } }",
] {
let output = transform(source);
assert!(output.contains("function f(a)"), "{source}: {output}");
}
// Functions using `arguments`.
let output = transform(
"function f(a, b) { b = 2; return arguments[1]; } \
function g(a, b) { b = 2; return () => arguments[1]; } \
function h(a, b) { b = 2; return function () { return arguments[0]; }; } \
function k(a, b, c) { return arguments.length; }",
);
testing::assert_contains(&output, &["function k()", "function f(a, b)"], &[]);
testing::assert_contains(&output, &["function g(a, b)", "function h()"], &[]);
// Patterns, defaults, and recursive calls that can fill a parameter.
let output = transform("function f(a, b = 1, { c }, ...d) { b = 2; return [a, b, c, d]; }");
testing::assert_contains(&output, &["function f(a, b = 1, { c }, ...d)"], &[]);
let output = transform("(function (a, b = 1, ...c) { return [a, b, c]; })(x);");
assert!(output.contains("function(a, b = 1, ...c)"), "{output}");
let output = transform("(function g(a, b) { return b ? a : g(a, 1); })(x);");
assert!(output.contains("function g(a, b)"), "{output}");
}
}
+353
View File
@@ -0,0 +1,353 @@
//! Expands comma and conditional expressions into statement control flow:
//!
//! ```js
//! flag && (third(), fourth()); // becomes if (flag) { third(); fourth(); }
//! ```
//!
//! Expands comma expressions only where doing so preserves evaluation order and values. Turns
//! conditional values into `if` branches so only the selected expression runs. Runs after
//! simplification, which could otherwise combine the statements again.
use std::mem;
use swc_core::common::Span;
use swc_core::common::util::take::Take;
use swc_core::ecma::ast::{
AssignOp, BinaryOp, CondExpr, Expr, IfStmt, LabeledStmt, Lit, Program, ReturnStmt, Stmt,
ThrowStmt, UnaryExpr, UnaryOp, VarDeclOrExpr,
};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::Analysis;
use crate::js::ast;
pub(super) fn run(program: &mut Program, _: &mut Analysis) -> bool {
let mut expand = ExpandStatements { changed: false };
program.visit_mut_with(&mut expand);
expand.changed
}
struct ExpandStatements {
changed: bool,
}
impl VisitMut for ExpandStatements {
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
let mut expanded = Vec::with_capacity(statements.len());
for mut statement in mem::take(statements) {
statement.visit_mut_children_with(self);
expanded.extend(self.expand(statement));
}
*statements = expanded;
}
fn visit_mut_stmt(&mut self, statement: &mut Stmt) {
statement.visit_mut_children_with(self);
let statements = self.expand(statement.take());
// This position accepts one statement. Wrap multi-statement expansions in a block.
*statement = match <[Stmt; 1]>::try_from(statements) {
Ok([single]) => single,
Err(statements) => ast::block(statements),
};
}
fn visit_mut_labeled_stmt(&mut self, statement: &mut LabeledStmt) {
// A label on a loop must stay on the loop for `continue label`.
// In particular, do not replace its body with a block of lifted initializers.
if let Stmt::Labeled(nested) = &mut *statement.body {
self.visit_mut_labeled_stmt(nested);
} else {
statement.body.visit_mut_children_with(self);
}
}
}
/// A statement evaluating an expression taken out of a larger one.
fn expression_statement(expression: Box<Expr>) -> Stmt {
guard_directive(ast::expression_statement(expression))
}
/// Wrap newly exposed string statements in a block so they cannot become function or script
/// directives.
fn guard_directive(statement: Stmt) -> Stmt {
if is_string_statement(&statement) {
ast::block(vec![statement])
} else {
statement
}
}
fn is_string_statement(statement: &Stmt) -> bool {
matches!(
statement,
Stmt::Expr(statement) if matches!(&*statement.expr, Expr::Lit(Lit::Str(_)))
)
}
/// Keeps sequences such as `name = (effects, function () {})`. Removing the sequence would give
/// the function an inferred `.name` that the original did not have.
fn ends_with_anonymous_function(expression: &Expr) -> bool {
match expression {
Expr::Paren(paren) => ends_with_anonymous_function(&paren.expr),
Expr::Seq(sequence) => sequence
.exprs
.last()
.is_some_and(|last| ends_with_anonymous_function(last)),
Expr::Fn(function) => function.ident.is_none(),
Expr::Class(class) => class.ident.is_none(),
Expr::Arrow(_) => true,
_ => false,
}
}
impl ExpandStatements {
/// Applies the same statement to either arm of a conditional value.
fn conditional(
&mut self,
conditional: CondExpr,
span: Span,
statement: impl Fn(Box<Expr>) -> Stmt,
) -> Stmt {
self.changed = true;
Stmt::If(IfStmt {
span,
test: conditional.test,
cons: Box::new(ast::block(self.expand(statement(conditional.cons)))),
alt: Some(Box::new(ast::block(
self.expand(statement(conditional.alt)),
))),
})
}
/// Moves sequence operands into statements only where evaluation order and values are
/// preserved. Leaves commas in callees, assignment targets, and loop tests or updates in
/// place.
fn split_sequence(&mut self, mut expression: Box<Expr>) -> (Vec<Stmt>, Box<Expr>) {
while let Expr::Paren(paren) = *expression {
expression = paren.expr;
self.changed = true;
}
if let Expr::Seq(sequence) = &mut *expression
&& let Some(last) = sequence.exprs.pop()
{
self.changed = true;
let mut prefix = Vec::new();
for expression in mem::take(&mut sequence.exprs) {
prefix.extend(self.expand(expression_statement(expression)));
}
let (tail_prefix, last) = self.split_sequence(last);
prefix.extend(tail_prefix);
(prefix, last)
} else {
(vec![], expression)
}
}
fn expand(&mut self, statement: Stmt) -> Vec<Stmt> {
let mut prefix = Vec::new();
let mut statement = match statement {
// A string statement stays as written: it may be a directive.
statement if is_string_statement(&statement) => return vec![statement],
Stmt::Expr(mut statement) => {
(prefix, statement.expr) = self.split_sequence(statement.expr);
// `name = (first(), value)` evaluates `first()` before the store, and a
// plain identifier target has nothing to evaluate ahead of it.
if let Expr::Assign(assignment) = &mut *statement.expr
&& assignment.op == AssignOp::Assign
&& assignment.left.as_ident().is_some()
&& !ends_with_anonymous_function(&assignment.right)
{
let (effects, value) = self.split_sequence(assignment.right.take());
prefix.extend(effects);
assignment.right = value;
}
match *statement.expr {
Expr::Cond(conditional) => {
self.conditional(conditional, statement.span, expression_statement)
}
Expr::Bin(binary)
if matches!(binary.op, BinaryOp::LogicalAnd | BinaryOp::LogicalOr) =>
{
self.changed = true;
let test = if binary.op == BinaryOp::LogicalOr {
Box::new(Expr::Unary(UnaryExpr {
span: binary.span,
op: UnaryOp::Bang,
arg: binary.left,
}))
} else {
binary.left
};
Stmt::If(IfStmt {
span: statement.span,
test,
cons: Box::new(ast::block(
self.expand(expression_statement(binary.right)),
)),
alt: None,
})
}
// Splitting or removing parentheses can expose a string.
expression => {
statement.expr = Box::new(expression);
guard_directive(Stmt::Expr(statement))
}
}
}
Stmt::Return(mut statement) => {
let Some(argument) = statement.arg.take() else {
return vec![Stmt::Return(statement)];
};
let (effects, argument) = self.split_sequence(argument);
prefix = effects;
match *argument {
Expr::Cond(conditional) => {
self.conditional(conditional, statement.span, |arg| {
Stmt::Return(ReturnStmt {
span: statement.span,
arg: Some(arg),
})
})
}
Expr::Unary(unary) if unary.op == UnaryOp::Void => {
self.changed = true;
prefix.extend(self.expand(expression_statement(unary.arg)));
Stmt::Return(statement)
}
argument => {
statement.arg = Some(Box::new(argument));
Stmt::Return(statement)
}
}
}
Stmt::Throw(mut statement) => {
(prefix, statement.arg) = self.split_sequence(statement.arg);
if let Expr::Cond(conditional) = *statement.arg {
self.conditional(conditional, statement.span, |arg| {
Stmt::Throw(ThrowStmt {
span: statement.span,
arg,
})
})
} else {
Stmt::Throw(statement)
}
}
Stmt::Switch(mut statement) => {
(prefix, statement.discriminant) = self.split_sequence(statement.discriminant);
Stmt::Switch(statement)
}
Stmt::For(mut statement) => {
statement.init = match statement.init.take() {
Some(VarDeclOrExpr::Expr(initializer)) => {
self.changed = true;
prefix.extend(self.expand(expression_statement(initializer)));
None
}
initializer => initializer,
};
Stmt::For(statement)
}
statement => statement,
};
// Conditions created above can themselves have a comma prefix.
if let Stmt::If(conditional) = &mut statement {
let (effects, test) = self.split_sequence(conditional.test.take());
prefix.extend(effects);
conditional.test = test;
}
prefix.push(statement);
prefix
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn expands_sequences_conditionals_and_void_returns() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
let output = transform(
"function f(flag) { first(), second(); flag && (third(), fourth()); \
flag || fallback(); return before(), flag ? (yes(), result()) : void no(); }",
);
testing::assert_contains(
&output,
&["if (flag)", "if (!flag)", "return result();"],
&["first(); second();", "no(); return;"],
);
testing::assert_lacks(&output, &["&&", " ? "]);
let output = transform(
"function f(flag) { if (before(), flag) a(); \
switch (select(), flag) { case 1: break; } \
throw prepare(), flag ? (yes(), one) : (no(), two); }",
);
testing::assert_contains(
&output,
&["throw one;", "throw two;"],
&["before(); if (flag)", "select(); switch(flag)"],
);
assert!(!output.contains("throw prepare()"), "{output}");
// A single-statement body expands without changing which `if` an `else` binds to.
let output = transform("function f(a, b) { if (a) b ? yes() : no(); else other(); }");
testing::assert_contains(&output, &["if (a)", "if (b)"], &[]);
assert_eq!(output.matches("else").count(), 2, "{output}");
assert!(!output.contains('?'), "{output}");
assert_eq!(transform(&output), output);
}
#[test]
fn preserves_evaluation_order_frequency_labels_and_references() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
// Only sequences assigned to identifiers are lifted out of assignments.
let output = transform(
"function f(a, b, obj) { a = (b = obj.x, first(), b + 1); \
obj[key()] = (effect(), value); obj.y = (effect(), value); a += (effect(), 1); \
a = (effect(), function () {}); a = (effect(), () => 1); a = (effect(), function named() {}); }",
);
testing::assert_contains(
&output,
&[
"a = (effect(), function() {})",
"a = (effect(), ()=>1)",
"obj[key()] = (effect(), value)",
"obj.y = (effect(), value)",
"a += (effect(), 1)",
],
&[
"effect(); a = function named() {}",
"b = obj.x; first(); a = b + 1;",
],
);
let output = transform(
"function f() { for (start(), setup(); test(), ready; tick(), step()) body(); \
outer: inner: for (init(), reset(); check(); next()) { continue outer; } \
for (let i = 0; i < 2; i++) use(i); \
while (poll(), ready) work(); do work(); while (poll(), ready); }",
);
testing::assert_contains(
&output,
&[
"test(), ready; tick(), step()",
"outer: inner: for(init(), reset();",
"continue outer;",
"for(let i = 0;",
"while(poll(), ready)",
"while (poll(), ready)",
],
&["start(); setup();"],
);
let output = transform(
r#"function f() { (0, obj.method)(); (0, eval)("x");
consume(first(), (second(), third())); return left && right; }"#,
);
let expected = [
"(0, obj.method)()",
"(0, eval)(\"x\")",
"consume(first(), (second(), third()))",
"return left && right;",
];
testing::assert_contains(&output, &expected, &[]);
}
}
+51
View File
@@ -0,0 +1,51 @@
//! Replaces computed properties with dot accesses:
//!
//! ```js
//! console["log"]; // becomes console.log
//! ```
//!
//! Accepts string literals and templates without substitutions only when the value is a valid
//! identifier. Both forms then access the same property.
use swc_core::ecma::ast::{IdentName, MemberExpr, MemberProp, Program};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::Analysis;
use crate::js::ast;
pub(super) fn run(program: &mut Program, _: &mut Analysis) -> bool {
let mut members = NameStaticMembers { changed: false };
program.visit_mut_with(&mut members);
members.changed
}
struct NameStaticMembers {
changed: bool,
}
impl VisitMut for NameStaticMembers {
fn visit_mut_member_expr(&mut self, member: &mut MemberExpr) {
member.visit_mut_children_with(self);
if let MemberProp::Computed(property) = &member.prop
&& let Some(property_name) = ast::static_str(&property.expr)
&& swc_ecma_utils::is_valid_ident(property_name)
{
member.prop = MemberProp::Ident(IdentName::new(property_name.into(), property.span));
self.changed = true;
}
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn uses_cooked_static_template_properties() {
let output =
testing::transform(r#"obj[`lo\u0067`](); obj?.[`name`]; obj[`a-b`]; obj[`${key}`];"#);
let expected = ["obj.log()", "obj?.name", "obj[`a-b`]", "obj[`${key}`]"];
testing::assert_contains(&output, &expected, &[]);
}
}
+736
View File
@@ -0,0 +1,736 @@
//! Decodes the obfuscator's string table:
//!
//! ```js
//! decoder(23); // becomes "message"
//! ```
//!
//! Recognizes the [`Table`] and solves its checksum rotation ([`Rotations`]) without executing
//! JavaScript, then replaces constant-index calls through decoders, aliases, and wrappers.
//! Removes decoding code only when no references remain. Unsupported setups stay unchanged.
use std::iter;
use swc_core::atoms::Wtf8Atom;
use swc_core::atoms::wtf8::{CodePoint, Wtf8Buf};
use swc_core::common::Span;
use swc_core::ecma::ast::{
BinaryOp, CallExpr, Callee, Decl, Expr, ExprOrSpread, FnDecl, Function, Id, Lit, MemberProp,
Null, Program, Stmt, Str, VarDeclOrExpr, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith};
use super::analysis::{Analysis, Bindings, names};
use super::{HashMap, HashSet, removal};
use crate::js::{self, ast};
/// Decodes supported string tables one at a time.
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let mut bindings = analysis.bindings(program);
let mut updated = None;
let mut tried = HashSet::default();
let mut changed = false;
while let Some(plan) = Plan::next(program, bindings, &mut tried) {
if plan.apply(program) {
changed = true;
// Analyze subsequent tables against the updated program.
bindings = updated.insert(Bindings::collect(program));
}
}
changed
}
/// Information collected before modifying a string table, sufficient to decode it.
struct Plan {
/// The table, already rotated the way the setup leaves it.
table: Table,
/// The decoder and every binding that only ever holds it.
aliases: HashSet<Id>,
/// Wrapper functions indexed by every binding that names them.
wrappers: HashMap<Id, Wrapper>,
/// The call that rotates the table at runtime.
setup: Span,
}
impl Plan {
/// Finds the first untried decodable table in source order. Requires one setup with a
/// solvable rotation.
fn next(program: &Program, bindings: &Bindings, tried: &mut HashSet<Id>) -> Option<Self> {
let mut functions = Functions::default();
program.visit_with(&mut functions);
let mut candidates: Vec<&FnDecl> = functions.0.values().collect();
candidates.sort_by_key(|function| function.function.span.lo);
for function in candidates {
let Some(mut table) = Table::discover(function, &functions.0, bindings) else {
continue;
};
// The decoder's declaration must be its only write.
if !bindings.is_written_once(&table.decoder) || !tried.insert(table.decoder.clone()) {
continue;
}
let aliases = bindings.aliases(&table.decoder);
let mut rotations = Rotations {
table: &table,
aliases: &aliases,
bindings,
matches: vec![],
};
program.visit_with(&mut rotations);
let [setup] = rotations.matches[..] else {
continue;
};
table.strings.rotate_left(setup.rotation);
let wrappers = Wrapper::discover(&functions.0, &aliases, bindings);
return Some(Self {
table,
aliases,
wrappers,
setup: setup.call,
});
}
None
}
/// Decodes every constant call, then removes the table machinery if nothing refers to it.
fn apply(&self, program: &mut Program) -> bool {
let mut decoder = DecodeStrings {
plan: self,
changed: false,
};
program.visit_mut_with(&mut decoder);
// Try cleanup before deciding whether dynamic calls or escaped aliases still require
// the runtime decoder.
let mut cleaned = program.clone();
cleaned.visit_mut_with(&mut Cleanup(self));
let remaining = Bindings::collect(&cleaned);
if iter::once(&self.table.provider)
.chain(&self.aliases)
.any(|id| remaining.references(id) > 0)
{
return decoder.changed;
}
*program = cleaned;
true
}
/// Returns the constant decoder index for `callee(args)`, if known.
fn index(&self, callee: &Id, args: &[ExprOrSpread]) -> Option<f64> {
if args.iter().any(|argument| argument.spread.is_some()) {
return None;
}
if self.aliases.contains(callee) {
match args {
[argument] => ast::number(&argument.expr),
_ => None,
}
} else {
self.wrappers.get(callee)?.index(args)
}
}
/// Whether `function` declares the decoder or the provider.
fn is_machinery(&self, function: &FnDecl) -> bool {
let id = function.ident.to_id();
id == self.table.decoder || id == self.table.provider
}
fn is_setup_call(&self, expression: &Expr) -> bool {
matches!(expression, Expr::Call(call) if call.span == self.setup)
}
}
/// `alias = other`, copying one decoder alias into another.
fn is_alias_copy(expression: &Expr, aliases: &HashSet<Id>) -> bool {
ast::assignment(expression).is_some_and(|(id, value)| {
aliases.contains(&id)
&& value
.as_ident()
.is_some_and(|id| aliases.contains(&id.to_id()))
})
}
/// Collects single-return function declarations by binding. Decoders, providers, and wrappers
/// share this form; avoid cloning larger functions.
#[derive(Default)]
struct Functions(HashMap<Id, FnDecl>);
impl Visit for Functions {
fn visit_fn_decl(&mut self, function: &FnDecl) {
if ast::returned(&function.function).is_some() {
self.0.insert(function.ident.to_id(), function.clone());
}
function.visit_children_with(self);
}
}
/// Recognizes wrappers such as `function w(i, o, d) { return d = decoder, d(i + o) }`. Extra
/// decoder arguments must be literals that the decoder overwrites before reading them.
#[derive(Clone)]
struct Wrapper {
params: Vec<Id>,
index: Expr,
}
impl Wrapper {
/// Every binding that names a wrapper, mapped to that wrapper.
#[must_use]
fn discover(
functions: &HashMap<Id, FnDecl>,
decoders: &HashSet<Id>,
bindings: &Bindings,
) -> HashMap<Id, Self> {
let mut wrappers = HashMap::default();
for (id, function) in functions {
if bindings.is_written_once(id)
&& let Some(wrapper) = Self::recognize(&function.function, decoders)
{
for alias in bindings.aliases(id) {
wrappers.insert(alias, wrapper.clone());
}
}
}
wrappers
}
fn recognize(function: &Function, decoders: &HashSet<Id>) -> Option<Self> {
let params = names::parameter_ids(&function.params)?;
// Either `return decoder(...)` or `return local = decoder, local(...)`.
let is_decoder = |expression: &Expr| {
expression
.as_ident()
.is_some_and(|id| decoders.contains(&id.to_id()))
};
if let Some((local, call)) = match ast::returned(function)? {
Expr::Seq(sequence)
if let [binding, call] = sequence.exprs.as_slice()
&& let Some((local, decoder)) = ast::assignment(binding)
&& params.contains(&local)
&& is_decoder(decoder) =>
{
Some((Some(local), &**call))
}
Expr::Seq(_) => None,
call => Some((None, call)),
} && let Some((callee, [index, extra @ ..])) = ast::direct_call(call)
&& (local.as_ref() == Some(&callee.to_id()) || decoders.contains(&callee.to_id()))
&& index.spread.is_none()
&& extra
.iter()
.all(|argument| argument.spread.is_none() && matches!(*argument.expr, Expr::Lit(_)))
{
Some(Self {
params,
index: (*index.expr).clone(),
})
} else {
None
}
}
/// Resolves the decoder index selected by these literal arguments.
#[must_use]
fn index(&self, args: &[ExprOrSpread]) -> Option<f64> {
let values: HashMap<Id, f64> = self
.params
.iter()
.zip(args)
.map(|(param, argument)| Some((param.clone(), ast::number(&argument.expr)?)))
.collect::<Option<_>>()?;
ast::fold_number(&self.index, &|leaf| {
values.get(&leaf.as_ident()?.to_id()).copied()
})
}
}
/// Replaces constant-index calls to decoder aliases or wrappers with decoded strings. Leaves
/// the decoder, provider, and setup for [`Cleanup`].
struct DecodeStrings<'plan> {
plan: &'plan Plan,
changed: bool,
}
impl VisitMut for DecodeStrings<'_> {
fn visit_mut_fn_decl(&mut self, function: &mut FnDecl) {
if !self.plan.is_machinery(function) {
function.visit_mut_children_with(self);
}
}
fn visit_mut_expr(&mut self, expression: &mut Expr) {
if self.plan.is_setup_call(expression) {
return;
}
expression.visit_mut_children_with(self);
if let Some((callee, args)) = ast::direct_call(expression)
&& let Some(index) = self.plan.index(&callee.to_id(), args)
&& let Some(value) = self.plan.table.lookup(index, 0)
{
*expression = Expr::Lit(Lit::Str(Str {
span: callee.span,
value,
raw: None,
}));
self.changed = true;
}
}
}
/// Removes the decoder, the provider, the setup call, and copies between decoder aliases.
struct Cleanup<'plan>(&'plan Plan);
impl Cleanup<'_> {
fn is_setup(&self, expression: &Expr) -> bool {
self.0.is_setup_call(expression) || is_alias_copy(expression, &self.0.aliases)
}
}
impl VisitMut for Cleanup<'_> {
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
removal::retain(
statements,
|statement| !matches!(statement, Stmt::Decl(Decl::Fn(function)) if self.0.is_machinery(function)),
);
removal::remove_expr_stmts(statements, |expression| self.is_setup(expression));
statements.visit_mut_children_with(self);
}
fn visit_mut_var_declarator(&mut self, declaration: &mut VarDeclarator) {
let aliases = &self.0.aliases;
if declaration
.name
.as_ident()
.is_some_and(|id| aliases.contains(&id.to_id()))
&& declaration
.init
.as_deref()
.and_then(Expr::as_ident)
.is_some_and(|id| aliases.contains(&id.to_id()))
{
// Retain the binding (including const's required initializer).
declaration.init = Some(Box::new(Expr::Lit(Lit::Null(Null {
span: declaration.span,
}))));
}
declaration.visit_mut_children_with(self);
}
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Seq(sequence) = expression {
// The last operand supplies the sequence's value; only drop discarded values.
if let Some(last) = sequence.exprs.pop() {
removal::retain(&mut sequence.exprs, |expression| !self.is_setup(expression));
sequence.exprs.push(last);
}
if sequence.exprs.len() == 1 {
*expression = *sequence.exprs.remove(0);
}
}
}
}
/// A string table, its decoder, and the provider function that builds it.
struct Table {
decoder: Id,
provider: Id,
offset: f64,
strings: Vec<Wtf8Atom>,
/// Whether the decoder reverses each entry with `Array.from(value).reverse().join('')`.
reversed: bool,
}
impl Table {
/// Recognizes two decoder layouts:
///
/// ```js
/// function d(i, a, v) { return i = i - 21, a = provider(), v = a[i], v }
/// function d(i, v) { return i = i - 21, v = strings[i], Array.from(v).reverse().join('') }
/// ```
///
/// The second requires `strings` to be assigned `provider()` exactly once.
#[must_use]
fn discover(
function: &FnDecl,
functions: &HashMap<Id, FnDecl>,
bindings: &Bindings,
) -> Option<Self> {
if let Some(body) = ast::return_sequence(&function.function)
&& let Some((offset, rest)) = body.split_first()
&& let Some((index, offset)) = ast::assignment(offset)
&& function.function.params.first()?.pat.as_ident()?.to_id() == index
&& let Expr::Bin(subtract) = offset
&& subtract.op == BinaryOp::Sub
&& subtract.left.as_ident()?.to_id() == index
&& let Some(offset) = ast::number(&subtract.right)
&& offset.is_finite()
&& offset.fract() == 0.0
&& let Some((array, provider, lookup, result)) = match rest {
[array, lookup, result]
if let Some((array, provider_call)) = ast::assignment(array)
&& let Some((provider, [])) = ast::direct_call(provider_call) =>
{
Some((array, provider.to_id(), lookup, result))
}
[lookup, result]
if let Some((_, Expr::Member(member))) = ast::assignment(lookup)
&& let Some(array) = member.obj.as_ident()
&& let Some(provider) = bindings.sole_call(&array.to_id()) =>
{
Some((array.to_id(), provider, lookup, result))
}
_ => None,
}
&& let Some((value, lookup)) = ast::assignment(lookup)
&& let Expr::Member(member) = lookup
&& let MemberProp::Computed(property) = &member.prop
&& member.obj.as_ident()?.to_id() == array
&& property.expr.as_ident()?.to_id() == index
&& let Some(reversed) = if result.as_ident().is_some_and(|id| id.to_id() == value) {
Some(false)
} else {
(reversal_of(result)? == value).then_some(true)
}
&& let Some(strings) = factory_strings(functions.get(&provider)?, &provider)
{
Some(Self {
decoder: function.ident.to_id(),
provider,
offset,
strings,
reversed,
})
} else {
None
}
}
/// The decoded entry at `index` once the table is rotated left by `rotation` entries.
#[must_use]
fn lookup(&self, index: f64, rotation: usize) -> Option<Wtf8Atom> {
let index =
ast::array_index(index - self.offset).filter(|index| *index < self.strings.len())?;
let value = &self.strings[(index + rotation) % self.strings.len()];
Some(if self.reversed {
reverse_code_points(value)
} else {
value.clone()
})
}
}
/// `Array.from(value).reverse().join('')`, returning `value`'s binding.
fn reversal_of(expression: &Expr) -> Option<Id> {
if let Some((reversed, [separator])) = ast::method_call(expression, "join")
&& separator.spread.is_none()
&& ast::static_str(&separator.expr)?.is_empty()
&& let Some((from, [])) = ast::method_call(reversed, "reverse")
&& let Some((array, [value])) = ast::method_call(from, "from")
&& array.as_ident()?.sym == "Array"
&& value.spread.is_none()
{
Some(value.expr.as_ident()?.to_id())
} else {
None
}
}
/// Reverses by JavaScript code points as `Array.from` does. Preserves surrogate pairs; moves
/// lone surrogates individually.
fn reverse_code_points(value: &Wtf8Atom) -> Wtf8Atom {
let points: Vec<CodePoint> = value.as_wtf8().code_points().collect();
let reversed: Wtf8Buf = points.into_iter().rev().collect();
Wtf8Atom::from(reversed)
}
/// Reads strings returned by a self-replacing table factory:
///
/// ```js
/// function provider(v) {
/// v = `a;b`.split(`;`);
/// provider = function () { return v };
/// return provider();
/// }
/// ```
fn factory_strings(factory: &FnDecl, provider: &Id) -> Option<Vec<Wtf8Atom>> {
if let Some([split, redefine, call]) = ast::return_sequence(&factory.function)
&& let Some((storage, split)) = ast::assignment(split)
&& let Some((object, [separator])) = ast::method_call(split, "split")
&& separator.spread.is_none()
&& let Some(separator) = ast::static_wtf8(&separator.expr)
&& let Some(strings) = split_utf16(ast::static_wtf8(object)?, separator)
&& let Some((redefined, Expr::Fn(redefine_function))) = ast::assignment(redefine)
&& redefined == *provider
&& let Some(returned) = ast::returned(&redefine_function.function)
&& returned.as_ident()?.to_id() == storage
&& redefine_function.function.params.is_empty()
&& let Some((called, [])) = ast::direct_call(call)
&& called.to_id() == *provider
{
Some(strings)
} else {
None
}
}
/// Splits UTF-16 code units as `String.prototype.split` does, keeping lone surrogates that Rust
/// strings would corrupt. Returns `None` for an empty separator, which splits every code unit.
fn split_utf16(source: &Wtf8Atom, separator: &Wtf8Atom) -> Option<Vec<Wtf8Atom>> {
let source: Vec<u16> = source.as_wtf8().to_ill_formed_utf16().collect();
let separator: Vec<u16> = separator.as_wtf8().to_ill_formed_utf16().collect();
if separator.is_empty() {
return None;
}
let part = |units: &[u16]| Wtf8Atom::from(Wtf8Buf::from_ill_formed_utf16(units));
let mut parts = Vec::new();
let mut start = 0;
let mut position = 0;
while position + separator.len() <= source.len() {
if source[position..].starts_with(&separator) {
parts.push(part(&source[start..position]));
position += separator.len();
start = position;
} else {
position += 1;
}
}
parts.push(part(&source[start..]));
Some(parts)
}
/// Finds table-rotation calls and solves the rotation at which their decoded-entry checksums
/// match.
struct Rotations<'plan> {
table: &'plan Table,
aliases: &'plan HashSet<Id>,
bindings: &'plan Bindings,
matches: Vec<Setup>,
}
/// A call that rotates the table at runtime.
#[derive(Clone, Copy)]
struct Setup {
call: Span,
/// How far the call rotates the table left.
rotation: usize,
}
impl Visit for Rotations<'_> {
fn visit_call_expr(&mut self, call: &CallExpr) {
if let Some(rotation) = self.rotation(call) {
self.matches.push(Setup {
call: call.span,
rotation,
});
}
call.visit_children_with(self);
}
}
impl Rotations<'_> {
/// Solves the rotation for `call` when its loop initializer binds only the array and known
/// decoder aliases.
fn rotation(&self, call: &CallExpr) -> Option<usize> {
if let Callee::Expr(callee) = &call.callee
&& let Expr::Fn(function) = callee.unwrap_parens()
&& let [provider, target] = call.args.as_slice()
&& provider.spread.is_none()
&& target.spread.is_none()
&& provider.expr.as_ident()?.to_id() == self.table.provider
&& let Some(target_value) = ast::number(&target.expr)
&& !function.function.is_async
&& !function.function.is_generator
&& let [provider_param, target_param, ..] = function.function.params.as_slice()
&& let Some(provider_param) = provider_param.pat.as_ident()
&& let Some(target_param) = target_param.pat.as_ident()
&& let Some(loop_body) = function.function.body.as_ref()
&& let [Stmt::For(loop_)] = loop_body.stmts.as_slice()
&& loop_.update.is_none()
&& matches!(loop_.test.as_deref(), Some(Expr::Lit(Lit::Bool(test))) if test.value)
&& let Some(VarDeclOrExpr::Expr(init)) = &loop_.init
&& let Expr::Seq(init) = &**init
&& let Some((last, leading)) = init.exprs.split_last()
&& let Some((array, array_call)) = ast::assignment(last)
&& let Some((called, [])) = ast::direct_call(array_call)
&& called.to_id() == provider_param.to_id()
&& leading
.iter()
.all(|expression| is_alias_copy(expression, self.aliases))
&& let Stmt::Try(try_) = &*loop_.body
&& try_.finalizer.is_none()
&& let [Stmt::If(check)] = try_.block.stmts.as_slice()
&& matches!(&*check.cons, Stmt::Break(statement) if statement.label.is_none())
&& is_rotation(check.alt.as_deref()?, &array)
&& let Some(handler) = try_.handler.as_ref()
&& let [catch] = handler.body.stmts.as_slice()
&& is_rotation(catch, &array)
&& let Expr::Seq(test) = &*check.test
&& let [checksum, comparison] = test.exprs.as_slice()
&& let Some((checksum_id, checksum)) = ast::assignment(checksum)
&& let Expr::Bin(comparison) = &**comparison
&& matches!(comparison.op, BinaryOp::EqEq | BinaryOp::EqEqEq)
&& let Some(left) = comparison.left.as_ident()
&& let Some(right) = comparison.right.as_ident()
&& ((left.to_id() == target_param.to_id() && right.to_id() == checksum_id)
|| (right.to_id() == target_param.to_id() && left.to_id() == checksum_id))
{
// Try at most one table length of rotations instead of executing the input loop.
(0..self.table.strings.len())
.find(|&rotation| self.evaluate(checksum, rotation) == Some(target_value))
} else {
None
}
}
/// Folds the checksum under `rotation`, reading `parseInt(decoder(index))` from the table.
fn evaluate(&self, expression: &Expr, rotation: usize) -> Option<f64> {
ast::fold_number(expression, &|leaf| {
let (callee, [argument]) = ast::direct_call(leaf)? else {
return None;
};
let (decoder, [index]) = ast::direct_call(&argument.expr)? else {
return None;
};
if callee.sym != "parseInt"
|| self.bindings.is_bound(&callee.to_id())
|| argument.spread.is_some()
|| !self.aliases.contains(&decoder.to_id())
|| index.spread.is_some()
{
return None;
}
let value = self.table.lookup(ast::number(&index.expr)?, rotation)?;
Some(js::parse_integer(&value.to_string_lossy()))
})
}
}
fn is_rotation(statement: &Stmt, array: &Id) -> bool {
if let Stmt::Expr(expression) = statement
&& let Some((object, [argument])) = ast::method_call(&expression.expr, "push")
&& let Some((shifted, [])) = ast::method_call(&argument.expr, "shift")
{
argument.spread.is_none()
&& object.as_ident().is_some_and(|id| &id.to_id() == array)
&& shifted.as_ident().is_some_and(|id| &id.to_id() == array)
} else {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::deobfuscate::testing;
fn fixture(offset: u32, separator: &str, consumer: &str) -> String {
let next = offset + 1;
let index = offset + 2;
format!(
r#"
(function () {{
function useAlias(late) {{ late = middle; return late({index}); }}
var middle = decoder;
(function (factory, target, alias, values, checksum) {{
for (alias = decoder, values = factory(); true;) try {{
if (checksum = parseInt(alias({offset})) + parseInt(alias({next})), target === checksum)
break;
else values.push(values.shift());
}} catch (error) {{ values.push(values.shift()); }}
}})(provider, 18);
function decoder(index, unused, values, result) {{
return index = index - {offset}, values = provider(), result = values[index], result;
}}
function provider(values) {{
return values = `noise{separator}7abc{separator}11def{separator}message`.split(`{separator}`),
provider = function () {{ return values; }}, provider();
}}
function shadow(decoder) {{ return decoder({index}); }}
function x() {{ return 'unrelated x'; }}
function d() {{ return 'unrelated d'; }}
console.log(useAlias(), shadow(function (v) {{ return v; }}), x(), d());
{consumer}
}})();
"#
)
}
#[test]
fn decodes_tables_with_any_names_offsets_delimiters_and_quoting() {
for (offset, separator, name) in [
(21, ";", "alpha"),
(700, "::", "renamed"),
(4096, "|", "thirdDecoder"),
] {
let source = fixture(offset, separator, "")
.replace("decoder", name)
.replace("provider", "tableFactory");
let output = testing::transform(&source);
assert!(output.contains("return \"message\";"), "{output}");
testing::assert_lacks(&output, &["function tableFactory(", "parseInt("]);
testing::assert_contains(&output, &[&format!("return {name}({});", offset + 2)], &[]);
testing::assert_contains(&output, &["function x()", "function d()"], &[]);
}
// Quoted tables keep their UTF-16 code units.
let source = fixture(21, ";", "").replace(
"`noise;7abc;11def;message`.split(`;`)",
r#""noise;7abc;11def;\uD800"["split"](";")"#,
);
let output = testing::transform(&source);
assert!(output.contains(r#"return "\uD800";"#), "{output}");
assert!(!output.contains("function provider("), "{output}");
}
#[test]
fn preserves_setups_still_needed_or_not_solved() {
// Dynamic calls, escaped aliases, and extra arguments still need the decoder.
for consumer in [
"console.log(middle(input));",
"console.log(middle(23, effect()));",
"console.log(middle(...args));",
"console.log(middle(22.5));",
"console.log(middle(1000));",
"consume(middle);",
"consume({ middle });",
] {
let output = testing::transform(&fixture(21, ";", consumer));
assert!(output.contains("return \"message\";"), "{output}");
let expected = ["function provider(", "function decoder(", "parseInt("];
testing::assert_contains(&output, &expected, &[]);
}
// Unsolved setups and reassigned decoders.
for source in [
fixture(21, ";", "").replace("provider, 18", "provider, 999"),
fixture(21, ";", "").replace("values.push(values.shift())", "values.pop()"),
fixture(21, ";", "").replace(
"var middle",
"function parseInt(v) { return 0; } var middle",
),
fixture(21, ";", "").replace("var middle", "decoder = replacement; var middle"),
fixture(21, ";", "middle = replacement; console.log(middle(23));"),
] {
let output = testing::transform(&source);
assert!(!output.contains("return \"message\";"), "{output}");
testing::assert_contains(&output, &["function provider(", "function decoder("], &[]);
}
}
#[test]
fn reverses_code_points_and_preserves_surrogates() {
for (source, expected) in [
(vec![], vec![]),
(
vec![0x61, 0xd83d, 0xde00, 0x62],
vec![0x62, 0xd83d, 0xde00, 0x61],
),
(vec![0xd800, 0x61, 0xdc00], vec![0xdc00, 0x61, 0xd800]),
(vec![0xdc00, 0xd800], vec![0xd800, 0xdc00]),
] {
let source = Wtf8Atom::from(Wtf8Buf::from_ill_formed_utf16(&source));
let reversed = reverse_code_points(&source);
assert_eq!(
reversed.as_wtf8().to_ill_formed_utf16().collect::<Vec<_>>(),
expected
);
}
}
}
+78
View File
@@ -0,0 +1,78 @@
//! Helpers for testing deobfuscation passes on source text.
use swc_core::ecma::ast::{Id, Ident, Pass, Program, fn_pass};
use swc_core::ecma::visit::{Visit, VisitWith};
use swc_ecma_transforms::fixer;
use super::analysis::Analysis;
/// The whole deobfuscation pass, as the library applies it.
pub(crate) fn transform(source: &str) -> String {
super::deobfuscate(source.to_owned())
.expect("test deobfuscation should succeed")
.text
}
/// Checks that `output` contains each `expected` string verbatim and each `code` string
/// ignoring whitespace, so printer layout does not affect the check.
pub(crate) fn assert_contains(output: &str, expected: &[&str], code: &[&str]) {
for expected in expected {
assert!(output.contains(expected), "{expected}: {output}");
}
let strip = |text: &str| -> String { text.split_whitespace().collect() };
for code in code {
assert!(strip(output).contains(&strip(code)), "{code}: {output}");
}
}
pub(crate) fn assert_lacks(output: &str, absent: &[&str]) {
for absent in absent {
assert!(!output.contains(absent), "{absent}: {output}");
}
}
/// One rewrite in isolation, followed by the fixer when `fix` is set.
pub(super) fn rewrite(
source: &str,
rewrite: fn(&mut Program, &mut Analysis) -> bool,
fix: bool,
) -> String {
super::pipeline::transform(source.to_owned(), |_, unresolved_mark| {
fn_pass(move |program: &mut Program| {
rewrite(program, &mut Analysis::new(unresolved_mark));
if fix {
fixer::fixer(None).process(program);
}
})
})
.expect("test transformation should succeed")
}
/// Every identifier of a program, in visiting order.
struct Names(Vec<Id>);
impl Visit for Names {
fn visit_ident(&mut self, identifier: &Ident) {
self.0.push(identifier.to_id());
}
}
/// Resolves names in `source` and runs `check` with a lookup from each spelling to the binding
/// of its first identifier.
pub(crate) fn check(source: &str, mut check: impl FnMut(&Program, &dyn Fn(&str) -> Id)) {
let checked = super::pipeline::transform(source.to_owned(), |_, _| {
fn_pass(|program: &mut Program| {
let mut names = Names(vec![]);
program.visit_with(&mut names);
check(program, &|name: &str| {
names
.0
.iter()
.find(|(spelling, _)| *spelling == name)
.unwrap_or_else(|| panic!("{name} not found"))
.clone()
});
})
});
checked.expect("test transformation should succeed");
}
+155
View File
@@ -0,0 +1,155 @@
//! Removes the declarations of unread locals, and their definitions when evaluating the value
//! has no effects:
//!
//! ```js
//! var unused, add, all;
//! add = function(a, b) { var scratch; return a + b; };
//! all = [add]; // everything is removed, `all` first
//! ```
//!
//! Leaves globals, whose writes other scripts can observe, and parameters of functions using
//! `arguments`, whose writes `arguments` reflects.
use swc_core::ecma::ast::{Decl, Expr, Id, Program, SeqExpr, Stmt, VarDeclarator};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};
use super::analysis::{Analysis, Bindings, Globals};
use super::{HashMap, removal};
use crate::js::ast;
pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool {
let globals = analysis.globals;
let mut remove = RemoveUnused {
bindings: analysis.bindings(program),
globals,
removed: HashMap::default(),
changed: false,
};
program.visit_mut_with(&mut remove);
remove.changed
}
struct RemoveUnused<'bindings> {
bindings: &'bindings Bindings,
globals: Globals,
/// How many writes of each binding this pass has removed. Statement lists are visited
/// after the lists they contain, so a declaration sees the definitions removed below it.
removed: HashMap<Id, usize>,
changed: bool,
}
impl RemoveUnused<'_> {
fn is_unused(&self, id: &Id) -> bool {
id.1 != self.globals.unresolved
&& self.bindings.references(id) == 0
&& !self.bindings.is_mapped_parameter(id)
}
/// Recognizes an assignment of an effect-free value to an unused binding. Records the
/// removed write.
fn remove_definition(&mut self, expression: &Expr) -> bool {
match ast::assignment(expression) {
Some((id, value)) if self.is_unused(&id) && self.is_pure(value) => {
*self.removed.entry(id).or_default() += 1;
true
}
_ => false,
}
}
/// Whether evaluating `value` has no effects and cannot throw. Reading a global can throw
/// or run a getter; reading a local cannot.
fn is_pure(&self, value: &Expr) -> bool {
match value {
Expr::Fn(_) | Expr::Arrow(_) | Expr::Lit(_) => true,
Expr::Ident(identifier) => identifier.ctxt != self.globals.unresolved,
Expr::Tpl(template) => template.exprs.is_empty(),
Expr::Paren(paren) => self.is_pure(&paren.expr),
Expr::Array(array) => array
.elems
.iter()
.flatten()
.all(|element| element.spread.is_none() && self.is_pure(&element.expr)),
_ => false,
}
}
/// Matches an unused binding declaration, with or without an initializer, only when no
/// remaining write needs the binding. Initializers must have no effects. Removing a
/// declaration while keeping a write could turn that write into a global assignment.
fn is_declaration(&self, declarator: &VarDeclarator) -> bool {
let Some(name) = declarator.name.as_ident() else {
return false;
};
let id = name.to_id();
let removed = self.removed.get(&id).copied().unwrap_or(0);
self.is_unused(&id)
&& self.bindings.write_count(&id) - removed == usize::from(declarator.init.is_some())
&& declarator
.init
.as_deref()
.is_none_or(|value| self.is_pure(value))
}
}
impl VisitMut for RemoveUnused<'_> {
fn visit_mut_seq_expr(&mut self, sequence: &mut SeqExpr) {
sequence.visit_mut_children_with(self);
// The last operand supplies the sequence's value.
if let Some(last) = sequence.exprs.pop() {
self.changed |= removal::retain(&mut sequence.exprs, |operand| {
!self.remove_definition(operand)
});
sequence.exprs.push(last);
}
}
fn visit_mut_expr(&mut self, expression: &mut Expr) {
expression.visit_mut_children_with(self);
if let Expr::Seq(sequence) = expression
&& sequence.exprs.len() == 1
{
*expression = *sequence.exprs.remove(0);
}
}
fn visit_mut_stmts(&mut self, statements: &mut Vec<Stmt>) {
statements.visit_mut_children_with(self);
self.changed |=
removal::remove_expr_stmts(statements, |expression| self.remove_definition(expression));
for statement in statements.iter_mut() {
if let Stmt::Decl(Decl::Var(declaration)) = statement {
self.changed |= removal::retain(&mut declaration.decls, |declarator| {
!self.is_declaration(declarator)
});
}
}
removal::retain(statements, |statement| match statement {
Stmt::Decl(Decl::Var(declaration)) => !declaration.decls.is_empty(),
_ => true,
});
}
}
#[cfg(test)]
mod tests {
use crate::deobfuscate::testing;
#[test]
fn removes_unread_locals_but_keeps_globals_effects_and_mapped_parameters() {
let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true);
// Removing `all` leaves `add` unread, for the pipeline's next round.
let output = transform(&transform(
"function f(a, b) { var unused, add, all, kept = g(); \
add = function(x) { var scratch; return x; }; all = [add, a]; return a + b; }",
));
let expected = "function f(a, b) { var kept = g(); return a + b; }";
testing::assert_contains(&output, &[], &[expected]);
let output = transform(
"global = function() {}; function f(a) { var v, w; v = g(); w = [missing]; \
return arguments; } function h(p) { p = 1; return arguments; }",
);
let kept = ["global = function", "var v", "v = g()", "w = [", "p = 1"];
testing::assert_contains(&output, &kept, &[]);
}
}
+10
View File
@@ -0,0 +1,10 @@
//! Reconstructs the embedding page's DOM, page summary, `extraParams` reply, and render stack
//! sample.
pub(crate) mod challenge_page;
pub(crate) mod extra_params;
pub(crate) mod page;
pub(crate) mod render_sample;
#[cfg(test)]
pub(crate) mod tests;
+86
View File
@@ -0,0 +1,86 @@
//! The challenge page as it stands when its orchestrator renders the widget.
use anyhow::{Context, Result, ensure};
use url::{Position, Url};
use crate::challenge::orchestrator::ChallengePage;
/// Selector for the widget container in the rendered page.
pub(crate) const WIDGET_HOST: &str = "#challenge-widget-host";
/// Reconstructs the page at widget render time, including its language, scripts, header,
/// status text, widget container, hidden panels, and footer.
///
/// The `api.js` summary records tags, attribute names, counts, and the widget's path
/// through the tree. It omits randomized IDs and classes. Layout follows a Chromium capture
/// from 2026-10-16, template version 5.
pub(crate) fn render(
page: &ChallengePage,
loader: &Url,
language: &str,
ray: &str,
) -> Result<String> {
let host = page.url.host_str().context("challenge page has no host")?;
let html = &page.html;
let opening = html
.find("<html")
.and_then(|start| Some(start..start + html[start..].find('>')? + 1))
.context("challenge page has no html element")?;
let head_end = html.find("</head>").context("challenge page has no head")?;
let content = html
.find("<div class=\"main-content\">")
.map(|start| start + "<div class=\"main-content\">".len())
.context("challenge page has no main content")?;
let body_end = html
.rfind("</body>")
.context("challenge page has no body")?;
ensure!(
opening.end <= head_end && head_end < content && content < body_end,
"challenge page is out of order"
);
let scripts = format!(
r#"<script src="{}"></script><style></style><script src="{}" async="" defer="" crossorigin="anonymous"></script>"#,
escape(&page.orchestrator[Position::BeforePath..]),
escape(loader.as_str()),
);
let panels = format!(
concat!(
r#"<div class="a"><img src="/favicon.ico" class="a b" alt="Icon for {host}"><h1>{host}</h1></div>"#,
r#"<h2 id="a" class="a b">Performing security verification</h2>"#,
r#"<p id="b" class="a b">This website uses a security service to protect against malicious bots. This page is displayed while the website verifies you are not a bot.</p>"#,
r#"<div id="{widget}" style="display: grid;"></div>"#,
r#"<div id="c" style="display: none;"><h2 id="d" class="a">Verification successful. Waiting for {host} to respond</h2></div>"#,
r#"<div id="e" class="a b" style="display: none; visibility: hidden;"><div class="a"><div></div><div></div><div></div><div></div></div></div>"#,
),
host = escape(host),
widget = &WIDGET_HOST[1..],
);
let footer = format!(
concat!(
r#"<div class="footer" role="contentinfo"><div class="footer-inner"><div class="footer-wrapper">"#,
r#"<div><div class="ray-id">Ray ID: <code>{ray}</code></div></div>"#,
r#"<div class="footer-link-wrapper"><span class="footer-text">Performance and Security by <a rel="noopener noreferrer" href="https://www.cloudflare.com?utm_source=challenge&amp;utm_campaign=m" target="_blank" aria-label="Cloudflare, opens in a new tab">Cloudflare</a></span>"#,
r#"<span class="footer-divider"></span><a target="_blank" rel="noopener noreferrer" href="https://www.cloudflare.com/privacypolicy/" aria-label="Privacy, opens in a new tab" class="footer-text">Privacy</a></div>"#,
r#"</div></div></div>"#,
),
ray = escape(ray),
);
Ok(format!(
r#"{}<html lang="{}" dir="ltr">{}{scripts}{}{panels}{}{footer}{}"#,
&html[..opening.start],
escape(language),
&html[opening.end..head_end],
&html[head_end..content],
&html[content..body_end],
&html[body_end..],
))
}
/// Escapes text for HTML attributes and text nodes.
#[must_use]
fn escape(text: &str) -> String {
text.replace('&', "&amp;")
.replace('"', "&quot;")
.replace('<', "&lt;")
.replace('>', "&gt;")
}
+422
View File
@@ -0,0 +1,422 @@
//! Builds the `extraParams` reply `api.js` sends to the iframe's `requestExtraParams`: widget
//! configuration, elapsed times, loader resource timing, and the page summary.
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use swc_core::ecma::ast::{CallExpr, Expr, KeyValueProp};
use swc_core::ecma::visit::{Visit, VisitWith};
use url::Url;
use crate::challenge::reduced_timing::ResourceTiming;
use crate::embedding_page::page::{Layout, PageSignals, RenderedPage};
use crate::embedding_page::render_sample::RenderSample;
use crate::engine::Engine;
use crate::js::{JsValue, ast, json};
use crate::resource_timing::{NEXT_HOP_PROTOCOL, Phases, ResourceMeasurement};
use crate::{candidates, random_id};
/// Loader timestamps from `Date.now()`, in milliseconds since the loader started. Loaded from
/// the fingerprint's `timeline` section, based on a browser capture.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Timeline {
/// When the loader script itself was fetched, relative to navigation start.
pub script_fetch: f64,
/// The loader began rendering the widgets declared in the page.
pub implicit_render: i64,
/// `render()` began building the widget.
pub render_start: i64,
/// The iframe element was in the document.
pub render_end: i64,
/// The iframe announced itself.
pub init_start: i64,
/// The iframe asked for these parameters.
pub params_start: i64,
/// The page summary started being collected.
pub collect_start: i64,
/// The message was posted.
pub sent: i64,
}
/// Loader script details observed by the embedding page.
#[derive(Debug, Clone)]
pub(crate) struct ApiScript {
/// `au`: the script's URL as the page requested it, before any redirect.
pub url: Url,
/// `ch`: the loader build required by the iframe. A mismatch triggers an `api.js` reload
/// before the iframe continues.
pub build: String,
/// Challenge-platform route requested by this loader. It changes with the build; a stale
/// route can fetch an iframe that rejects `build`.
pub variant: String,
pub start_time_ms: f64,
pub response: LoaderResponse,
/// The stack sample the loader takes as it renders the page's widgets.
pub render_sample: RenderSample,
/// The loader's source, for [`RenderSample::explicit`] once a render's caller is known.
pub source: String,
}
/// Resource timing information for the loader response.
#[derive(Debug, Clone)]
pub(crate) struct LoaderResponse {
/// Final response URL after redirects.
pub body_url: Url,
/// Time from request start to the last body byte, rounded to the page clock's resolution.
pub duration_ms: f64,
pub encoded_body_size: u64,
pub decoded_body_size: u64,
/// Whether the page can read the response's detailed timings; see [`timing_exposed`].
pub timing_exposed: bool,
/// Whether the page can read the response's sizes. WebKit withholds the cross-origin
/// loader's sizes even when its timings are exposed.
pub sizes_exposed: bool,
/// How the browser divides the fetch's duration.
pub phases: Phases,
}
/// Checks whether `Timing-Allow-Origin` value `allowed` permits `page` to read detailed timings
/// for `url`.
#[must_use]
pub(crate) fn timing_exposed(url: &Url, page: &Url, allowed: &str) -> bool {
url.origin() == page.origin()
|| allowed.split(',').any(|entry| {
let entry = entry.trim();
entry == "*" || entry == page.origin().ascii_serialization()
})
}
impl ApiScript {
/// Reads the build, route, and stack sample for `engine` from loader `source` fetched at
/// `url`, using `response` metadata.
pub(crate) fn from_source(
url: Url,
source: &str,
response: LoaderResponse,
timeline: &Timeline,
engine: Engine,
) -> Result<Self> {
let parsed = ast::parse_javascript("the Turnstile loader", source)?;
let mut literals = Literals::default();
parsed.script.visit_with(&mut literals);
let build = candidates::at_most_one_distinct(literals.builds, "build hash")?
.context("loader script has no api.js build hash; is this really api.js?")?;
let variant =
candidates::at_most_one_distinct(literals.routes, "challenge-platform route")?
.context("loader script names no challenge-platform route")?;
let render_sample =
RenderSample::from_parsed(&parsed, stack_url(&url, &response, engine), engine)?;
Ok(Self {
url,
build,
variant,
start_time_ms: timeline.script_fetch,
response,
render_sample,
source: source.to_owned(),
})
}
/// The loader's URL as `engine` names it in stacks.
#[must_use]
pub(crate) fn stack_url(&self, engine: Engine) -> &Url {
stack_url(&self.url, &self.response, engine)
}
/// Reports the loader fetch as a resource timing entry. Estimates phases and withholds
/// restricted attributes unless the response permits access.
fn measurement(&self) -> ResourceMeasurement {
let response = &self.response;
let end = self.start_time_ms + response.duration_ms;
if !response.timing_exposed {
return ResourceMeasurement::restricted(response.duration_ms, end);
}
let mut measured = ResourceMeasurement::estimated(
response.duration_ms,
response.encoded_body_size,
response.phases,
);
if !response.sizes_exposed {
measured.transfer_size = 0;
measured.body_size = 0;
}
measured
}
/// The loader's `PerformanceResourceTiming`, which the iframe reduces as [`Self::reduced`]
/// does. Without `Timing-Allow-Origin`, only `startTime`, `fetchStart`, `duration`, and
/// `responseEnd` remain available.
#[must_use]
pub(crate) fn timing(&self) -> JsValue {
let response = &self.response;
let measured = self.measurement();
let start = self.start_time_ms;
let end = start + measured.duration;
let exposed = response.timing_exposed;
let connection = if exposed { start } else { 0.0 };
// Restricted entries report zero for response start, so the response interval extends
// from zero to response end.
let response_start = end - measured.response;
let request_start = response_start - measured.request;
json!({
"name": self.url.as_str(),
"entryType": "resource",
"startTime": start,
"duration": measured.duration,
"initiatorType": "script",
"deliveryType": "",
"nextHopProtocol": if exposed { NEXT_HOP_PROTOCOL } else { "" },
"renderBlockingStatus": "non-blocking",
"workerStart": 0.0,
"redirectStart": 0.0,
"redirectEnd": 0.0,
"fetchStart": start,
"domainLookupStart": connection,
"domainLookupEnd": connection,
"connectStart": connection,
"connectEnd": connection,
"secureConnectionStart": connection,
"requestStart": request_start,
"responseStart": response_start,
"firstInterimResponseStart": 0.0,
"finalResponseHeadersStart": response_start,
"responseEnd": end,
"transferSize": measured.transfer_size,
"encodedBodySize": measured.body_size,
"decodedBodySize": if response.sizes_exposed { response.decoded_body_size } else { 0 },
"responseStatus": if exposed { 200 } else { 0 },
"contentType": if exposed { "script" } else { "" },
})
}
/// Reduces [`Self::timing`] to the six fields forwarded by the challenge.
#[must_use]
pub(crate) fn reduced(&self, timing: &ResourceTiming) -> JsValue {
timing.reduce(self.url.as_str(), &self.measurement())
}
}
/// V8 names the loader in stacks by the URL requested, JavaScriptCore by the final response URL.
fn stack_url<'u>(requested: &'u Url, response: &'u LoaderResponse, engine: Engine) -> &'u Url {
match engine {
Engine::Chromium => requested,
Engine::WebKit => &response.body_url,
}
}
/// The loader's candidates for its build hash and challenge-platform route.
#[derive(Default)]
struct Literals {
builds: Vec<String>,
routes: Vec<String>,
}
impl Visit for Literals {
/// `ch: "e694063b5082"`: the twelve-digit hexadecimal build hash, which the iframe compares
/// with its compiled-in build.
fn visit_key_value_prop(&mut self, property: &KeyValueProp) {
if ast::key_str(&property.key) == Some("ch")
&& let Some(value) = ast::static_str(&property.value)
&& value.len() == 12
&& value
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
{
self.builds.push(value.to_owned());
}
property.visit_children_with(self);
}
/// `f(..., "b", Reason.New, ...)`: the one-letter route beside the render reason when the
/// loader builds a widget's first iframe URL.
fn visit_call_expr(&mut self, call: &CallExpr) {
for pair in call.args.windows(2) {
if let Expr::Member(reason) = &*pair[1].expr
&& ast::member_str(&reason.prop) == Some("New")
&& let Some(route) = ast::static_str(&pair[0].expr)
&& route.len() == 1
&& route.bytes().all(|byte| byte.is_ascii_lowercase())
{
self.routes.push(route.to_owned());
}
}
call.visit_children_with(self);
}
}
/// The embedding page's reply to `requestExtraParams`. Fields serialize in the order `api.js`
/// writes them, which the merge into `_cf_chl_opt` keeps.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ExtraParams<'page> {
#[serde(skip_serializing_if = "Option::is_none")]
pub action: Option<&'page str>,
pub api_js_mismatch_reload_attempts: u32,
pub api_js_mismatch_reload_completed_count: u32,
pub api_js_resource_timing: JsValue,
pub appearance: &'page str,
#[serde(rename = "au")]
pub loader_url: &'page str,
#[serde(rename = "cData", skip_serializing_if = "Option::is_none")]
pub cdata: Option<&'page str>,
#[serde(rename = "ch")]
pub build: &'page str,
#[serde(skip_serializing_if = "Option::is_none")]
pub chl_page_data: Option<&'page str>,
/// Stack samples: method, elapsed milliseconds, stack, and consecutive occurrence count.
#[serde(rename = "cs")]
pub samples: Vec<(f64, i64, &'page str, u32)>,
pub event: &'static str,
pub execution: &'page str,
#[serde(rename = "expiry-interval")]
pub expiry_interval: i64,
pub language: &'page str,
/// The challenge variant. Absent on the first render.
#[serde(rename = "rcV")]
pub challenge_variant: &'static str,
#[serde(rename = "refresh-expired")]
pub refresh_expired: &'page str,
#[serde(rename = "refresh-timeout")]
pub refresh_timeout: &'page str,
pub retry: &'page str,
#[serde(rename = "retry-interval")]
pub retry_interval: i64,
/// Both sides check this before reading a message.
pub source: &'static str,
pub upgrade_attempts: u32,
pub upgrade_completed_count: u32,
pub url: &'page str,
#[serde(rename = "wPr")]
pub signals: PageSignals,
pub widget_id: &'page str,
pub time_extra_params_ms: i64,
pub time_init_ms: i64,
pub time_load_init_ms: i64,
pub time_params_ms: i64,
pub time_render_ms: i64,
pub time_tief_ms: i64,
}
/// Builds the reply to `requestExtraParams`. Omits widget parameters that the page does not
/// set. The iframe treats missing and `undefined` values alike, applying `||` defaults or
/// storing them directly.
#[must_use]
pub(crate) fn collect<'page>(
page: &'page RenderedPage,
layout: &Layout,
timeline: &Timeline,
script: &'page ApiScript,
mode: Option<&str>,
) -> ExtraParams<'page> {
let params = &page.params;
ExtraParams {
action: params.action.as_deref(),
api_js_mismatch_reload_attempts: 0,
api_js_mismatch_reload_completed_count: 0,
api_js_resource_timing: script.timing(),
appearance: &params.appearance,
loader_url: script.url.as_str(),
cdata: params.cdata.as_deref(),
build: &script.build,
chl_page_data: params.chl_page_data.as_deref(),
samples: vec![(
script.render_sample.method,
timeline.implicit_render,
&script.render_sample.stack,
1,
)],
event: "extraParams",
execution: &params.execution,
expiry_interval: params.expiry_interval,
language: &params.language,
challenge_variant: "",
refresh_expired: &params.refresh_expired,
refresh_timeout: &params.refresh_timeout,
retry: &params.retry,
retry_interval: params.retry_interval,
source: "cloudflare-challenge",
upgrade_attempts: 0,
upgrade_completed_count: 0,
url: page.url.as_str(),
signals: page.signals(layout, mode),
widget_id: &page.widget_id,
time_extra_params_ms: timeline.sent - timeline.render_start,
time_init_ms: timeline.init_start - timeline.render_end,
// The loader script starts the clock, so this is the mark itself.
time_load_init_ms: timeline.sent,
time_params_ms: timeline.params_start - timeline.init_start,
time_render_ms: timeline.render_end - timeline.render_start,
time_tief_ms: timeline.sent - timeline.collect_start,
}
}
/// The widget's first iframe URL, with an empty challenge variant, which later responses may
/// supply.
pub(crate) fn iframe_url(page: &RenderedPage, script: &ApiScript) -> Result<Url> {
let params = &page.params;
let feedback = if params.feedback_enabled {
"fbE"
} else {
"fbD"
};
let origin = script.url.origin().ascii_serialization();
let route = &script.variant;
let mut url = Url::parse(&format!(
"{origin}/cdn-cgi/challenge-platform/h/{route}/turnstile/f/av0/rch/{}/{}/{}/{feedback}/new/{}",
page.widget_id, params.sitekey, params.theme, params.size
))
.context("building the challenge iframe URL")?;
let mut query = url.query_pairs_mut();
query.append_pair("lang", &params.language);
for (key, value) in [
("offlabel_show_privacy", params.offlabel_show_privacy),
("offlabel_show_help", params.offlabel_show_help),
] {
if let Some(value) = value {
query.append_pair(key, &value.to_string());
}
}
drop(query);
Ok(url)
}
/// Generates a five-character widget ID using the `api.js` format.
#[must_use]
pub(crate) fn widget_id() -> String {
random_id::random_id(b"abcdefghijklmnopqrstuvwxyz0123456789", 5)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_build_hashes_and_routes_only_where_the_loader_keeps_them() {
let literals = |source: &str| {
let mut literals = Literals::default();
let parsed = ast::parse_javascript("t", source).unwrap();
parsed.script.visit_with(&mut literals);
literals
};
let hash = "e694063b5082";
for (source, builds) in [
(
r#"me(Q,Ce({action:o.action,ch:"e694063b5082",cs:At(o)}));"#,
&[hash][..],
),
(
"x = {'ch': `e694063b5082`}; y = { ch : 'e694063b5082' };",
&[hash, hash],
),
// A non-hash `ch` must not be mistaken for the build.
(r#"x = {ch: "auto", bach: "e694063b5082"};"#, &[]),
] {
assert_eq!(literals(source).builds, builds, "{source}");
}
for (source, routes) in [
(r#"f(a, "g", e.New); f('g', e['New']);"#, &["g", "g"][..]),
(r#"f("G", e.New); f("gg", e.New); e.New = 'new';"#, &[]),
] {
assert_eq!(literals(source).routes, routes, "{source}");
}
}
}
File diff suppressed because it is too large Load Diff
+391
View File
@@ -0,0 +1,391 @@
//! Reconstructs the render call-stack sample sent with `extraParams`.
//!
//! When `api.js` renders a widget, it records a method code, elapsed milliseconds, and
//! `new Error().stack`. The iframe copies the sample into its first payload. The loader's own
//! frames follow from its source names and call positions. Widgets declared in markup are
//! rendered from the loader's DOM-ready handler; a page script's `turnstile.render` call adds
//! that script's frames instead.
//!
//! V8 starts with `Error`, locates frames at the callee's start, names render calls by their
//! property, and keeps ten frames. JavaScriptCore uses `name@url:line:column` and locates
//! frames at the opening argument parenthesis. In strict code, tail calls can replace their
//! caller's frame.
use std::collections::{HashMap, HashSet};
use std::mem;
use anyhow::{Context, Result};
use swc_core::atoms::Atom;
use swc_core::common::BytePos;
use swc_core::ecma::ast::{
BinaryOp, CallExpr, Callee, CondExpr, Expr, FnDecl, Function, KeyValueProp, Lit, MemberExpr,
MemberProp, Pat, PropName, ReturnStmt, TryStmt, UnaryOp, VarDeclarator,
};
use swc_core::ecma::visit::{Visit, VisitWith};
use url::Url;
use crate::candidates;
use crate::engine::{Engine, StackFrame, V8_STACK_LIMIT};
use crate::js::ast::{self, ParsedScript};
/// The loader's entry point for widgets declared in markup.
const IMPLICIT_RENDER: &str = "runImplicitRender";
/// The loader's entry point for page scripts.
const EXPLICIT_RENDER: &str = "render";
/// The sample the loader takes when it renders a widget.
#[derive(Debug, Clone)]
pub(crate) struct RenderSample {
/// The code the loader records for the render.
pub method: f64,
pub stack: String,
}
impl RenderSample {
/// Rebuilds the stack for markup-triggered rendering from `parsed`, using `engine`'s format
/// and `url` as the script name.
pub(crate) fn from_parsed(parsed: &ParsedScript, url: &Url, engine: Engine) -> Result<Self> {
let loader = Loader::read(parsed);
let (method, mut frames) = loader.sampled(IMPLICIT_RENDER, engine)?;
// The outer frames cover queue insertion and the DOM-ready handler draining that queue.
let queued = candidates::at_most_one_distinct(
&loader.implicit_calls,
"named calls of the implicit render",
)?
.context("loader never calls its implicit render from a named function")?;
let ready = candidates::at_most_one_distinct(&loader.ready, "DOMContentLoaded handlers")?
.context("loader waits for no DOMContentLoaded")?;
let drained = loader
.calls
.iter()
.find(|call| call.scope.as_ref() == Some(ready))
.context("the ready handler calls nothing it queued")?;
frames.push((queued.function.to_string(), &queued.site));
frames.push((ready.to_string(), &drained.site));
Ok(Self {
method,
stack: engine.error_stack(placed(parsed, url, &frames, engine)),
})
}
/// Rebuilds the stack for a page script calling `turnstile.render` in the loader fetched
/// from `url`. `caller` supplies script frames from innermost to outermost, ending at the
/// callback invoked by the loader's `onload` timer. V8's ten-frame limit ends the stack
/// inside the script; JavaScriptCore also includes the timer.
pub(crate) fn explicit<'caller>(
source: &str,
url: &Url,
caller: impl IntoIterator<Item = StackFrame<'caller>>,
engine: Engine,
) -> Result<Self> {
let parsed = ast::parse_javascript("the Turnstile loader", source)?;
let loader = Loader::read(&parsed);
let (method, frames) = loader.sampled(EXPLICIT_RENDER, engine)?;
let caller = caller.into_iter().map(|frame| StackFrame { ..frame });
let frames = placed(&parsed, url, &frames, engine)
.into_iter()
.chain(caller);
let stack = match engine {
Engine::Chromium => engine.error_stack(frames.take(V8_STACK_LIMIT)),
Engine::WebKit => {
let onload = candidates::at_most_one_distinct(
&loader.onload_calls,
"onload callback calls",
)?
.context("loader never calls an onload callback")?;
let timer = [(String::new(), onload)];
engine.error_stack(frames.chain(placed(&parsed, url, &timer, engine)))
}
};
Ok(Self { method, stack })
}
}
/// Places loader frames for `engine`, leaving out the frames JavaScriptCore's tail calls
/// replace.
fn placed<'a>(
parsed: &ParsedScript,
url: &'a Url,
frames: &'a [(String, &Site)],
engine: Engine,
) -> Vec<StackFrame<'a>> {
let mut surviving = Vec::with_capacity(frames.len());
for (function, site) in frames {
let at = match engine {
Engine::Chromium => site.v8,
Engine::WebKit if site.tail => continue,
Engine::WebKit => site.jsc,
};
let (line, column) = parsed.position(at);
surviving.push(StackFrame {
function,
url: url.as_str(),
line,
column,
});
}
surviving
}
/// Engine-specific source positions for a call frame.
#[derive(Debug, PartialEq)]
struct Site {
/// The start of the callee, V8's position.
v8: BytePos,
/// The opening argument parenthesis, used by JavaScriptCore.
jsc: BytePos,
/// Whether this call is directly returned and therefore eligible for JavaScriptCore
/// tail-call replacement.
tail: bool,
}
/// A call through a plain identifier.
#[derive(Debug, PartialEq)]
struct Call {
scope: Option<Atom>,
callee: Atom,
site: Site,
first: Option<Atom>,
}
/// A frame position inside the named function `function`.
#[derive(Debug, PartialEq)]
struct FunctionSite {
function: Atom,
site: Site,
}
/// Finds the functions and calls involved in stack sampling.
#[derive(Default)]
struct Loader {
scope: Option<Atom>,
/// `new Error().stack` reads, at the error's construction site.
samples: Vec<FunctionSite>,
calls: Vec<Call>,
/// `runImplicitRender` property calls.
implicit_calls: Vec<FunctionSite>,
/// Calls returned directly outside `try` blocks.
tail_calls: HashSet<BytePos>,
/// Whether the visit is inside a `try` block of the current function.
in_try: bool,
/// `key: function` in object literals.
properties: HashMap<Atom, Atom>,
/// Variables initialised to a number.
numbers: HashMap<Atom, f64>,
/// The functions handed to `addEventListener("DOMContentLoaded", ...)`.
ready: Vec<Atom>,
/// Delay of the timer whose callback is currently being visited.
timer_delay: Option<f64>,
/// Calls to the page's defined `onload` callback from a timer with no delay. Another timer
/// retries after one second if the callback is not yet defined.
onload_calls: Vec<Site>,
}
impl Loader {
fn read(parsed: &ParsedScript) -> Self {
let mut loader = Self::default();
parsed.script.visit_with(&mut loader);
loader
}
/// Returns the sampling method code for loader export `property` and its frames, innermost
/// first: sampler, timing wrapper, and export. Fails if any step is ambiguous.
fn sampled(&self, property: &str, engine: Engine) -> Result<(f64, Vec<(String, &Site)>)> {
let sample = candidates::at_most_one_distinct(&self.samples, "stack samplers")?
.context("loader takes no stack sample")?;
let wrapper = candidates::at_most_one_distinct(
self.calls
.iter()
.filter(|call| call.callee == sample.function),
"calls of the stack sampler",
)?
.context("loader never calls its stack sampler")?;
let measured = wrapper
.scope
.as_ref()
.context("the stack sampler is called from an anonymous function")?;
let exported = self
.properties
.get(&Atom::from(property))
.with_context(|| format!("loader exports no {property}"))?;
let call = candidates::at_most_one_distinct(
self.calls
.iter()
.filter(|call| call.scope.as_ref() == Some(exported) && call.callee == *measured),
"stack samples in the exported render",
)?
.with_context(|| format!("the loader's {property} takes no stack sample"))?;
let method = call
.first
.as_ref()
.and_then(|code| self.numbers.get(code))
.with_context(|| format!("the loader's {property} has no constant method code"))?;
let exported = match engine {
Engine::Chromium => format!("Object.{exported} [as {property}]"),
Engine::WebKit => exported.to_string(),
};
Ok((
*method,
vec![
(sample.function.to_string(), &sample.site),
(measured.to_string(), &wrapper.site),
(exported, &call.site),
],
))
}
fn within(&mut self, name: Option<Atom>, function: &Function) {
let previous = mem::replace(&mut self.scope, name);
let in_try = mem::take(&mut self.in_try);
function.visit_children_with(self);
self.scope = previous;
self.in_try = in_try;
}
fn site(&self, call: &CallExpr, v8: BytePos, jsc: BytePos) -> Site {
Site {
v8,
jsc,
tail: self.tail_calls.contains(&call.span.lo),
}
}
}
impl Visit for Loader {
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
self.within(Some(declaration.ident.sym.clone()), &declaration.function);
}
fn visit_function(&mut self, function: &Function) {
self.within(None, function);
}
/// V8 names a function expression after the variable it initialises.
fn visit_var_declarator(&mut self, declarator: &VarDeclarator) {
if let Pat::Ident(name) = &declarator.name {
match declarator.init.as_deref() {
Some(Expr::Fn(function)) => {
self.within(Some(name.id.sym.clone()), &function.function);
return;
}
Some(Expr::Lit(Lit::Num(number))) => {
self.numbers.insert(name.id.sym.clone(), number.value);
}
_ => {}
}
}
declarator.visit_children_with(self);
}
fn visit_member_expr(&mut self, member: &MemberExpr) {
if ast::member_str(&member.prop) == Some("stack")
&& let Expr::New(error) = &*member.obj
&& let Expr::Ident(callee) = &*error.callee
&& callee.sym == "Error"
&& let Some(function) = self.scope.clone()
{
self.samples.push(FunctionSite {
function,
site: Site {
v8: error.span.lo,
jsc: callee.span.hi,
tail: false,
},
});
}
member.visit_children_with(self);
}
/// `found === void 0 ? report() : found()`: the call of a callback once it is defined.
fn visit_cond_expr(&mut self, conditional: &CondExpr) {
if self.timer_delay == Some(0.0)
&& let Expr::Bin(test) = &*conditional.test
&& test.op == BinaryOp::EqEqEq
&& let Expr::Ident(tested) = &*test.left
&& matches!(&*test.right, Expr::Unary(unary) if unary.op == UnaryOp::Void)
&& let Expr::Call(call) = &*conditional.alt
&& call.args.is_empty()
&& let Callee::Expr(callee) = &call.callee
&& let Expr::Ident(callee) = &**callee
&& callee.sym == tested.sym
{
let site = self.site(call, callee.span.lo, callee.span.hi);
self.onload_calls.push(site);
}
conditional.visit_children_with(self);
}
fn visit_call_expr(&mut self, call: &CallExpr) {
let outer_delay = self.timer_delay;
if let Callee::Expr(callee) = &call.callee {
match &**callee {
Expr::Ident(callee) => {
// `setTimeout(function () { ... }, delay)`: the callback runs from a timer.
if callee.sym == "setTimeout"
&& let [callback, delay] = &call.args[..]
&& callback.expr.is_fn_expr()
{
self.timer_delay = ast::number(&delay.expr);
}
self.calls.push(Call {
scope: self.scope.clone(),
callee: callee.sym.clone(),
site: self.site(call, callee.span.lo, callee.span.hi),
first: call
.args
.first()
.and_then(|argument| Some(argument.expr.as_ident()?.sym.clone())),
});
}
Expr::Member(member) => {
if let MemberProp::Ident(property) = &member.prop
&& property.sym == IMPLICIT_RENDER
&& let Some(function) = self.scope.clone()
{
let site = self.site(call, property.span.lo, property.span.hi);
self.implicit_calls.push(FunctionSite { function, site });
}
if ast::member_str(&member.prop) == Some("addEventListener")
&& let [event, listener, ..] = &call.args[..]
&& matches!(&*event.expr, Expr::Lit(Lit::Str(_)))
&& ast::static_str(&event.expr) == Some("DOMContentLoaded")
&& let Expr::Ident(listener) = &*listener.expr
{
self.ready.push(listener.sym.clone());
}
}
_ => {}
}
}
call.visit_children_with(self);
self.timer_delay = outer_delay;
}
/// A directly returned call is in tail position unless an enclosing `try` requires work
/// after it returns.
fn visit_return_stmt(&mut self, statement: &ReturnStmt) {
if !self.in_try
&& let Some(Expr::Call(call)) = statement.arg.as_deref()
{
self.tail_calls.insert(call.span.lo);
}
statement.visit_children_with(self);
}
fn visit_try_stmt(&mut self, statement: &TryStmt) {
let outer = mem::replace(&mut self.in_try, true);
statement.block.visit_with(self);
self.in_try = outer;
statement.handler.visit_with(self);
statement.finalizer.visit_with(self);
}
fn visit_key_value_prop(&mut self, property: &KeyValueProp) {
if let PropName::Ident(key) = &property.key
&& let Expr::Ident(value) = &*property.value
{
self.properties.insert(key.sym.clone(), value.sym.clone());
}
property.visit_children_with(self);
}
}
+17
View File
@@ -0,0 +1,17 @@
//! The test page that other modules' tests render.
use url::Url;
use crate::embedding_page::page::RenderedPage;
/// A page rendering one widget.
pub(crate) const PAGE: &str = r#"<!DOCTYPE html><html><head><meta charset="utf-8"><title>Turnstile test page</title>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
</head><body><h1>Heading</h1><p>Text</p>
<div class="cf-turnstile" data-sitekey="0x4AAAAAAB8gDxRzm2UASWbL" data-action="login" data-cdata="test-cdata"></div>
</body></html>"#;
pub(crate) fn page() -> RenderedPage {
let url = Url::parse("http://127.0.0.1:8000/index.html").unwrap();
RenderedPage::render(PAGE, url, "j5gbk", None).unwrap()
}
+128
View File
@@ -0,0 +1,128 @@
//! Browser engine behavior used by fingerprints: stack formatting, clocks, API availability,
//! and referrer handling. Header order varies by browser version and comes from the profile
//! (see [`crate::http::HeaderOrder`]).
use serde::Deserialize;
/// An engine family, named in lowercase in the fingerprint's `engine`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Engine {
/// Blink and V8, used by Chrome and related browsers.
Chromium,
/// WebKit and JavaScriptCore, used by Safari and iOS browser profiles.
WebKit,
}
/// A stack frame with the engine's function name and one-based line and UTF-16 column of the
/// call in `url`.
pub(crate) struct StackFrame<'frame> {
pub function: &'frame str,
pub url: &'frame str,
pub line: usize,
pub column: usize,
}
/// The kind of text a stack position counts lines in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Lines {
/// Script source, where `\n`, `\r`, `\r\n`, U+2028 and U+2029 each end a line.
Script,
/// An HTML document, whose input stream turns `\r\n` and `\r` into `\n` but keeps U+2028
/// and U+2029 as text.
Document,
}
/// Returns the zero-based line and UTF-16 column after `prefix`, using the line-break rules
/// specified by `lines`.
#[must_use]
pub(crate) fn line_and_column(prefix: &str, lines: Lines) -> (u32, u32) {
let (mut line, mut column, mut after_cr) = (0, 0, false);
for character in prefix.chars() {
match character {
'\n' if after_cr => {}
'\r' | '\n' => {
line += 1;
column = 0;
}
'\u{2028}' | '\u{2029}' if lines == Lines::Script => {
line += 1;
column = 0;
}
_ => column += character.len_utf16() as u32,
}
after_cr = character == '\r';
}
(line, column)
}
/// V8's default `Error.stackTraceLimit`: an `Error` stack keeps its innermost ten frames.
pub(crate) const V8_STACK_LIMIT: usize = 10;
impl Engine {
/// Formats an `Error` stack created in the innermost frame. V8 includes the error name;
/// JavaScriptCore lists only frames, leaving the query and fragment out of their URLs.
#[must_use]
pub(crate) fn error_stack<'frame>(
self,
frames: impl IntoIterator<Item = StackFrame<'frame>>,
) -> String {
let mut lines = Vec::new();
if self == Self::Chromium {
lines.push("Error".to_owned());
}
for frame in frames {
let StackFrame {
function,
url,
line,
column,
} = frame;
lines.push(match self {
// V8 gives an anonymous function's frame its location alone.
Self::Chromium if function.is_empty() => format!(" at {url}:{line}:{column}"),
Self::Chromium => format!(" at {function} ({url}:{line}:{column})"),
Self::WebKit => {
let url = url.find(['?', '#']).map_or(url, |end| &url[..end]);
format!("{function}@{url}:{line}:{column}")
}
});
}
lines.join("\n")
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Checks that both formats count `\r\n` as one line break and measure columns in UTF-16
/// code units. Only script source treats U+2028 and U+2029 as line breaks.
#[test]
fn scripts_and_documents_count_lines_their_own_way() {
let text = "a\r\nb\rc\u{2028}d\u{2029}e\n\u{1F600}é";
assert_eq!(line_and_column(text, Lines::Script), (5, 3));
assert_eq!(line_and_column(text, Lines::Document), (3, 3));
assert_eq!(line_and_column("", Lines::Document), (0, 0));
}
/// As iOS Safari reports an iframe loaded with `?lang=auto`.
#[test]
fn only_v8_stack_frames_keep_the_query() {
let url = "https://challenges.cloudflare.com/normal?lang=auto";
let frame = || StackFrame {
function: "f",
url,
line: 1,
column: 2,
};
assert_eq!(
Engine::WebKit.error_stack([frame()]),
"f@https://challenges.cloudflare.com/normal:1:2"
);
assert_eq!(
Engine::Chromium.error_stack([frame()]),
"Error\n at f (https://challenges.cloudflare.com/normal?lang=auto:1:2)"
);
}
}
+142
View File
@@ -0,0 +1,142 @@
//! Classifies solve failures to help callers decide whether to retry. The wrapped error chain
//! retains the details.
use std::error::Error as StdError;
use std::fmt;
use wreq::StatusCode;
use crate::session::Stage;
/// A failed solve, or a profile that cannot solve.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
/// The profile or options are invalid. Found before any network access.
Config(anyhow::Error),
/// A request failed or timed out. Retrying may succeed.
Network(anyhow::Error),
/// The page answered with an error status and no challenge.
Blocked {
/// HTTP status of the response that blocked navigation.
status: StatusCode,
},
/// A Turnstile solve received a challenge page with `status` instead of the requested page.
/// Use [`Browser::clear`](crate::Browser::clear) to clear it.
Challenged {
/// HTTP status of the challenge-page response.
status: StatusCode,
},
/// The page answered without a challenge page, so there was nothing to clear.
NotChallenged,
/// Cloudflare refused the answers it was sent at `stage`. A new solve may succeed.
Rejected {
/// Payload stage whose answers were refused.
stage: Stage,
/// Rejection details, including request context.
error: anyhow::Error,
},
/// The solver cannot handle this page or challenge, for example because it uses a new
/// challenge build. Retrying will not help.
Unsupported(anyhow::Error),
}
impl Error {
/// Classifies a failure using a wrapped `Error`, if present, or the first recognized marker
/// or network error in the chain.
pub(crate) fn classify(error: anyhow::Error) -> Self {
let error = match error.downcast::<Self>() {
Ok(error) => return error,
Err(error) => error,
};
for cause in error.chain() {
if let Some(&Refused { stage, .. }) = cause.downcast_ref() {
return Self::Rejected { stage, error };
}
if cause.is::<wreq::Error>() {
return Self::Network(error);
}
}
Self::Unsupported(error)
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Config(error)
| Self::Network(error)
| Self::Rejected { error, .. }
| Self::Unsupported(error) => fmt::Display::fmt(error, formatter),
Self::Blocked { status } => write!(formatter, "the page answered HTTP {status}"),
Self::Challenged { status } => write!(
formatter,
"the page answered HTTP {status} with a challenge page; clear it before solving its widget"
),
Self::NotChallenged => {
formatter.write_str("the page answered without a challenge page")
}
}
}
}
impl StdError for Error {
/// The wrapped error's source, since `Display` already shows the wrapped error itself.
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Self::Config(error)
| Self::Network(error)
| Self::Rejected { error, .. }
| Self::Unsupported(error) => error.source(),
Self::Blocked { .. } | Self::Challenged { .. } | Self::NotChallenged => None,
}
}
}
/// Marks a failure caused by Cloudflare refusing the answers sent at `stage`.
#[derive(Debug)]
pub(crate) struct Refused {
stage: Stage,
message: String,
}
impl Refused {
pub(crate) fn new(stage: Stage, message: impl Into<String>) -> Self {
Self {
stage,
message: message.into(),
}
}
}
impl fmt::Display for Refused {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl StdError for Refused {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_by_the_marker_beneath_any_context() {
let refused = anyhow::Error::new(Refused::new(Stage::Probes, "refused"))
.context("sending the probes");
let refused = Error::classify(refused);
assert!(matches!(refused, Error::Rejected { stage, .. } if stage == Stage::Probes));
// `anyhow` displays the classified error's chain as it did before classification.
let refused = anyhow::Error::new(refused);
assert_eq!(format!("{refused:#}"), "sending the probes: refused");
let blocked = anyhow::Error::new(Error::Blocked {
status: StatusCode::FORBIDDEN,
});
let blocked = Error::classify(blocked.context("solving the widget"));
assert!(matches!(blocked, Error::Blocked { status } if status == 403));
assert_eq!(blocked.to_string(), "the page answered HTTP 403 Forbidden");
let unknown = Error::classify(anyhow::anyhow!("no orchestrator path"));
assert!(matches!(unknown, Error::Unsupported(_)));
}
}
+93
View File
@@ -0,0 +1,93 @@
//! Reads browser facts from caller-supplied fingerprint JSON. Unknown keys are ignored, and each
//! program reads only the sections it needs.
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use anyhow::{Context, Result};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use wreq::header::{HeaderMap, HeaderName, HeaderValue};
use wreq_util::{Platform, Profile};
use crate::engine::Engine;
use crate::http::{BrowserClient, ClientHello, Requests};
/// Reads the JSON file at `path` as `T`.
pub(crate) fn read<T: DeserializeOwned>(path: &Path) -> Result<T> {
let bytes = fs::read(path).with_context(|| format!("reading {}", path.display()))?;
serde_json::from_slice(&bytes)
.with_context(|| format!("reading fingerprint JSON {}", path.display()))
}
/// The fingerprint's `transport` section.
#[derive(Deserialize)]
pub(crate) struct TransportSection {
profile: Profile,
platform: Platform,
/// Headers that replace the emulated profile's headers.
#[serde(default)]
headers: BTreeMap<String, String>,
#[serde(default)]
client_hello: ClientHello,
requests: Requests,
}
/// Transport settings from the fingerprint's `engine` and `transport` sections.
pub struct Transport {
pub engine: Engine,
pub profile: Profile,
pub platform: Platform,
/// `transport.headers`, which replace those of the emulated profile.
pub headers: HeaderMap,
pub client_hello: ClientHello,
pub requests: Requests,
}
impl Transport {
/// Reads only the transport sections of the fingerprint at `path`.
pub fn read(path: &Path) -> Result<Self> {
#[derive(Deserialize)]
struct Sections {
engine: Engine,
transport: TransportSection,
}
let sections: Sections = read(path)?;
Self::try_new(sections.engine, sections.transport)
}
pub(crate) fn try_new(engine: Engine, transport: TransportSection) -> Result<Self> {
let headers: Result<HeaderMap> = transport
.headers
.iter()
.map(|(name, value)| {
Ok((
HeaderName::from_bytes(name.as_bytes())?,
HeaderValue::from_str(value)?,
))
})
.collect();
Ok(Self {
engine,
profile: transport.profile,
platform: transport.platform,
headers: headers.context("reading fingerprint `transport.headers`")?,
client_hello: transport.client_hello,
requests: transport.requests,
})
}
/// Creates a client with this transport, optionally using `proxy`.
pub fn client(&self, proxy: Option<&str>) -> Result<BrowserClient> {
BrowserClient::try_new(
self.profile,
self.platform,
self.headers.clone(),
&self.client_hello,
self.requests.clone(),
self.engine,
proxy,
)
}
}
+21
View File
@@ -0,0 +1,21 @@
//! HTTP transport and response handling for challenge sessions.
mod client;
mod decode;
mod header_order;
mod referrer;
mod requests;
#[cfg(feature = "internals")]
pub(crate) use client::Proxied;
pub use client::{BrowserClient, ClientHello, Requests};
pub use decode::{ResponseMetrics, header_text, read_encoded, text_headers};
#[cfg(feature = "internals")]
pub(crate) use decode::{decode_body, encode_body};
pub use header_order::HeaderOrder;
pub use referrer::ReferrerPolicy;
pub use requests::{
FetchOptions, Iframe, PageDocument, ScriptLoad, fetch_from_worker, fetch_iframe, fetch_image,
fetch_orchestrator, fetch_page_image, fetch_script, navigate, post_challenge,
post_orchestrator, submit_form,
};
+298
View File
@@ -0,0 +1,298 @@
//! Browser HTTP transport, ordered request headers, and stream weights.
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result, ensure};
#[cfg(feature = "internals")]
use bytes::Bytes;
use serde::Deserialize;
use url::Url;
use wreq::cookie::{Cookie, Jar};
use wreq::header::HeaderMap;
use wreq::http2::{StreamDependency, StreamId};
use wreq::redirect::Policy;
use wreq::{Client, Proxy, RequestBuilder, Response};
#[cfg(feature = "internals")]
use wreq::{Method, StatusCode};
use wreq_util::{Emulation, Platform, Profile};
#[cfg(feature = "internals")]
use super::decode;
use super::header_order::{HeaderOrder, RequestKind, Slot};
use crate::engine::Engine;
/// HTTP client configured from the browser fingerprint. Shared by all session requests to
/// preserve cookies and transport settings.
pub struct BrowserClient {
pub(super) http: Client,
/// The cookies the browser holds, `cf_clearance` among them once a challenge page clears.
pub(super) jar: Arc<Jar>,
/// User agent and client hints from the profile, overridden by `transport.headers`.
pub(super) own: HeaderMap,
pub(super) requests: Requests,
pub(super) engine: Engine,
}
/// Browser request settings beyond the transport profile, which vary by browser version.
#[derive(Clone, Debug, Deserialize)]
pub struct Requests {
/// HTTP/2 stream weights, from 1 to 256, indexed by RFC 9218 urgency. Missing `priority`
/// implies urgency 3. Unspecified urgencies, or an absent map, use the transport profile's
/// weight.
#[serde(default)]
pub weights: BTreeMap<u8, u16>,
/// The headers each kind of request carries, in the browser's order.
pub headers: HeaderOrder,
}
impl Requests {
/// Reads request settings from tracked profile text.
#[cfg(test)]
pub(crate) fn from_profile(profile: &str) -> Self {
let profile: serde_json::Value =
serde_json::from_str(profile).expect("a tracked profile is JSON");
let requests = profile
.pointer("/transport/requests")
.expect("a tracked profile describes its requests");
Self::deserialize(requests).expect("a tracked profile's requests are valid")
}
}
impl BrowserClient {
/// Creates a client from a wreq-util transport profile. `headers` replace the profile's
/// user agent and client hints, `hello` adds ClientHello fields for newer browsers, and
/// `proxy` is an `http://`, `https://`, `socks5://`, or `socks5h://` URL.
pub fn try_new(
profile: Profile,
platform: Platform,
headers: HeaderMap,
hello: &ClientHello,
requests: Requests,
engine: Engine,
proxy: Option<&str>,
) -> Result<Self> {
use wreq::IntoEmulation;
let mut emulation = Emulation::builder()
.profile(profile)
.platform(platform)
.build()
.into_emulation();
if let Some(tls) = &mut emulation.tls_options {
if !hello.advertised_sigalgs_prefix.is_empty() {
tls.advertised_sigalgs_prefix =
Some(hello.advertised_sigalgs_prefix.clone().into());
}
tls.grease_sigalgs = hello.grease_sigalgs;
if let Some(ids) = &hello.requested_trust_anchors {
let ids = decode_hex(ids).context("trust anchor IDs must be hex")?;
tls.requested_trust_anchors = Some(ids.into());
}
}
for weight in requests.weights.values() {
ensure!(
(1..=256).contains(weight),
"HTTP/2 weight {weight} is not from 1 to 256"
);
}
let mut own = emulation.headers.clone();
for (name, value) in &headers {
own.insert(name, value.clone());
}
requests.headers.check_own(&own)?;
let jar = Arc::new(Jar::default());
let mut builder = Client::builder()
.emulation(emulation)
.default_headers(headers)
.cookie_provider(Arc::clone(&jar))
.redirect(Policy::limited(5))
.timeout(Duration::from_secs(30));
if let Some(proxy) = proxy {
builder = builder.proxy(Proxy::all(proxy)?);
}
Ok(Self {
http: builder.build()?,
jar,
own,
requests,
engine,
})
}
#[must_use]
pub fn engine(&self) -> Engine {
self.engine
}
/// The cookies the browser would send to `url`.
#[must_use]
pub fn cookies(&self, url: &Url) -> Vec<Cookie<'static>> {
self.jar.matches(url.as_str()).collect()
}
/// Stores the cookie a `Set-Cookie` header from `url` sets.
pub fn add_cookie(&self, set_cookie: &str, url: &Url) {
self.jar.add(set_cookie, url.as_str());
}
/// Creates a test browser using HTTP and the tracked iOS Safari 26 request profile.
#[cfg(test)]
pub(super) fn from_http(http: Client) -> Self {
Self {
http,
jar: Arc::default(),
own: HeaderMap::new(),
requests: Requests::from_profile(include_str!("../../profiles/safari-26-ios.json")),
engine: Engine::WebKit,
}
}
/// Checks whether the profile defines a header order for `kind`. Required request kinds
/// must have one.
#[must_use]
pub(super) fn orders(&self, kind: RequestKind) -> bool {
self.requests.headers.get(kind).is_some()
}
/// Sends a request with the profile's header order and stream weight for `kind`, replacing
/// client defaults. `supplied` provides header values; `None` omits a header.
///
/// # Panics
///
/// Panics if the profile has no header order for `kind`. Only optional kinds may be absent.
pub(super) async fn send(
&self,
request: RequestBuilder,
kind: RequestKind,
supplied: &[(&str, Option<&str>)],
) -> Result<Response, wreq::Error> {
debug_assert!(
supplied.len() == kind.supplied().len()
&& supplied
.iter()
.all(|(name, _)| kind.supplied().contains(name)),
"a `{kind}` request supplies {:?}, not {supplied:?}",
kind.supplied()
);
let order = self
.requests
.headers
.get(kind)
.unwrap_or_else(|| panic!("the profile orders no `{kind}` requests"));
let mut request = request.default_headers(false);
for slot in order {
request = match slot {
Slot::Fixed(name, value) => request.header(name, value),
// Request-supplied values override browser defaults, including an explicit
// omission.
Slot::Named(name) => match supplied.iter().find(|(given, _)| name == given) {
Some((_, Some(value))) => request.header(name, *value),
Some((_, None)) => request,
None => match self.own.get(name) {
Some(value) => request.header(name, value),
None => request,
},
},
};
}
let (http, request) = request.build_split();
let mut request = request?;
let urgency = request
.headers()
.get("priority")
.and_then(|priority| priority.to_str().ok())
.map_or(3, urgency);
if let Some(&weight) = self.requests.weights.get(&urgency) {
// The wire weight is one less than the configured weight. The stream exclusively
// depends on the connection while no other stream is open.
let dependency = StreamDependency::new(StreamId::zero(), (weight - 1) as u8, true);
request.extensions_mut().insert(dependency);
}
RequestBuilder::from_parts(http, request).send().await
}
/// Forwards a capture-proxy request without following redirects or decoding the response.
/// Keeps the response's wire bytes. Uses an empty cookie jar so earlier sessions cannot add
/// cookies.
///
/// Sends only the browser's headers. Client defaults include high-entropy client hints that
/// Cloudflare incorporates into challenge options and tokens.
#[cfg(feature = "internals")]
pub(crate) async fn proxy_fetch(
&self,
method: Method,
url: &str,
headers: HeaderMap,
body: Bytes,
) -> Result<Proxied> {
let response = decode::preserve_encoding(self.http.request(method, url))
.default_headers(false)
.redirect(Policy::none())
.cookie_provider(Jar::default())
.headers(headers)
.body(body)
.send()
.await?;
Ok(Proxied {
status: response.status(),
headers: response.headers().clone(),
body: response.bytes().await?,
})
}
}
/// A response fetched for the capture proxy, with its wire bytes intact.
#[cfg(feature = "internals")]
pub(crate) struct Proxied {
pub status: StatusCode,
pub headers: HeaderMap,
pub body: Bytes,
}
/// Reads RFC 9218 urgency from `priority`, defaulting to 3.
fn urgency(priority: &str) -> u8 {
priority
.split(',')
.find_map(|item| item.trim().strip_prefix("u=")?.parse().ok())
.unwrap_or(3)
}
/// Additional ClientHello fields from the fingerprint's browser, beyond the installed wreq-util
/// profiles.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct ClientHello {
/// Signature algorithm code points prepended to the profile's list, such as Chrome's ML-DSA
/// values. They are advertised but never accepted.
pub advertised_sigalgs_prefix: Vec<u16>,
/// Whether `signature_algorithms` starts with a GREASE value.
pub grease_sigalgs: bool,
/// Hex-encoded, length-prefixed list of IDs for the `trust_anchors` extension.
pub requested_trust_anchors: Option<String>,
}
/// Bytes written as pairs of hexadecimal digits.
fn decode_hex(text: &str) -> Result<Vec<u8>> {
ensure!(
text.len().is_multiple_of(2) && text.bytes().all(|byte| byte.is_ascii_hexdigit()),
"{text:?} is not pairs of hex digits"
);
let byte = |start: usize| u8::from_str_radix(&text[start..start + 2], 16).expect("hex digits");
Ok((0..text.len()).step_by(2).map(byte).collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn urgency_reads_the_priority_dictionary_and_defaults_to_three() {
assert_eq!(urgency("u=0, i"), 0);
assert_eq!(urgency("i, u=4"), 4);
assert_eq!(urgency("u=1"), 1);
assert_eq!(urgency("i"), 3);
assert_eq!(urgency(""), 3);
}
}
+186
View File
@@ -0,0 +1,186 @@
//! Decodes responses manually to retain encoded and decoded body sizes and server timing.
use std::io::{self, Read};
use anyhow::{Context, Result, bail};
use brotli::{CompressorReader, Decompressor};
use flate2::Compression;
use flate2::read::{GzDecoder, GzEncoder, ZlibDecoder, ZlibEncoder};
use serde::Serialize;
use wreq::header::{HeaderMap, HeaderValue};
use wreq::{RequestBuilder, Response};
use zstd::stream;
/// Response measurements: encoded and decoded body sizes and server timing.
#[derive(Debug, Default, Serialize)]
pub struct ResponseMetrics {
pub encoded_bytes: u64,
pub decoded_bytes: u64,
pub content_encoding: String,
pub server_timing: Vec<(String, f64)>,
}
/// Returns each `Server-Timing` metric's name and `dur`, skipping metrics without a duration.
fn server_timing(headers: &HeaderMap) -> Vec<(String, f64)> {
headers
.get_all("server-timing")
.iter()
.filter_map(|header| header.to_str().ok())
.flat_map(|header| split_unquoted(header, ','))
.filter_map(metric_duration)
.collect()
}
/// Parses a `Server-Timing` metric's name and finite `dur`, if present.
fn metric_duration(metric: &str) -> Option<(String, f64)> {
let mut parts = split_unquoted(metric, ';');
let name = parts.next()?.trim();
for part in parts {
if let Some((key, value)) = part.trim().split_once('=')
&& key.trim().eq_ignore_ascii_case("dur")
&& let Ok(duration) = value.trim().trim_matches('"').parse::<f64>()
{
return duration.is_finite().then(|| (name.to_owned(), duration));
}
}
None
}
/// Splits `text` at separators outside quoted strings. Backslash escapes any character inside
/// quotes.
fn split_unquoted(text: &str, separator: char) -> impl Iterator<Item = &str> {
let (mut quoted, mut escaped) = (false, false);
text.split(move |character| {
match character {
_ if escaped => escaped = false,
'\\' if quoted => escaped = true,
'"' => quoted = !quoted,
_ => return character == separator && !quoted,
}
false
})
}
/// Reverses `Content-Encoding`, decoding in the reverse of the listed order.
pub(crate) fn decode_body(body: &[u8], encoding: &str) -> Result<Vec<u8>> {
let mut decoded = body.to_vec();
let last_applied_first = encoding.split(',').rev();
for coding in last_applied_first {
decoded = match coding.trim().to_ascii_lowercase().as_str() {
"" | "identity" => continue,
"gzip" | "x-gzip" => read_all(GzDecoder::new(decoded.as_slice()))?,
"deflate" => read_all(ZlibDecoder::new(decoded.as_slice()))?,
"br" => read_all(Decompressor::new(decoded.as_slice(), 4096))?,
"zstd" => stream::decode_all(decoded.as_slice())?,
other => bail!("unsupported content encoding {other}"),
};
}
Ok(decoded)
}
/// Restores `Content-Encoding` after the capture proxy rewrites a body, reversing
/// [`decode_body`]. Rejects unsupported encodings so the caller can forward the original body.
pub(crate) fn encode_body(body: &[u8], encoding: &str) -> Result<Vec<u8>> {
let level = Compression::default();
let mut encoded = body.to_vec();
for coding in encoding.split(',') {
encoded = match coding.trim().to_ascii_lowercase().as_str() {
"" | "identity" => continue,
"gzip" | "x-gzip" => read_all(GzEncoder::new(encoded.as_slice(), level))?,
"deflate" => read_all(ZlibEncoder::new(encoded.as_slice(), level))?,
// A 4 KiB buffer, quality 4, and a 4 MiB window.
"br" => read_all(CompressorReader::new(encoded.as_slice(), 4096, 4, 22))?,
"zstd" => stream::encode_all(encoded.as_slice(), 0)?,
other => bail!("cannot re-encode content encoding {other}"),
};
}
Ok(encoded)
}
fn read_all(mut reader: impl Read) -> io::Result<Vec<u8>> {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes)?;
Ok(bytes)
}
/// Keeps the encoded body for size measurements while accepting the browser's compression
/// formats.
pub(super) fn preserve_encoding(request: RequestBuilder) -> RequestBuilder {
request.gzip(false).brotli(false).deflate(false).zstd(false)
}
/// A header value as text, with any invalid UTF-8 replaced.
#[must_use]
pub fn header_text(value: &HeaderValue) -> String {
String::from_utf8_lossy(value.as_bytes()).into_owned()
}
/// Returns header names and values in order, formatting values with [`header_text`].
pub fn text_headers(headers: &HeaderMap) -> impl Iterator<Item = (&str, String)> {
headers
.iter()
.map(|(name, value)| (name.as_str(), header_text(value)))
}
/// Decodes an HTTP response and retains its encoded and decoded body sizes.
pub async fn read_encoded(response: Response) -> Result<(Vec<u8>, ResponseMetrics)> {
let content_encoding = match response.headers().get("content-encoding") {
Some(value) => value.to_str()?.to_owned(),
None => String::new(),
};
let server_timing = server_timing(response.headers());
let uri = response.uri().to_string();
let encoded = response.bytes().await?;
let decoded = decode_body(&encoded, &content_encoding)
.with_context(|| format!("decoding the body of {uri}"))?;
let metrics = ResponseMetrics {
encoded_bytes: encoded.len() as u64,
decoded_bytes: decoded.len() as u64,
content_encoding,
server_timing,
};
Ok((decoded, metrics))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bodies_round_trip_through_each_coding() {
let body = b"iframe content that must retain its exact decoded byte count";
for encoding in ["br", "zstd", "deflate", "gzip", "identity"] {
let encoded = encode_body(body, encoding).unwrap();
assert_eq!(decode_body(&encoded, encoding).unwrap(), body, "{encoding}");
}
assert!(decode_body(body, "unsupported").is_err());
assert!(decode_body(body, "gzip").is_err());
let zstd = stream::encode_all(body.as_slice(), 1).unwrap();
let gzip = read_all(GzEncoder::new(zstd.as_slice(), Compression::default())).unwrap();
assert_eq!(
decode_body(&gzip, "ZSTD, GZip").unwrap(),
body,
"codings are case-insensitive, and undone last first"
);
}
#[test]
fn server_timing_parameters_may_quote_separators() {
let mut headers = HeaderMap::new();
headers.append(
"server-timing",
r#"cache;desc="hit, fresh;ok \" ,";dur=1.5, db;DUR=53, total"#
.parse()
.unwrap(),
);
headers.append("server-timing", "cfL4;dur=\"7\"".parse().unwrap());
assert_eq!(
server_timing(&headers),
[
("cache".to_owned(), 1.5),
("db".to_owned(), 53.0),
("cfL4".to_owned(), 7.0)
]
);
}
}
+253
View File
@@ -0,0 +1,253 @@
//! Header order for each request kind, from `transport.requests.headers`.
//!
//! A `"name: value"` entry sends a fixed value. A bare `"name"` uses a request-supplied value
//! (see [`RequestKind::supplied`]) or the browser's user agent and client hints.
//! Request-supplied headers may be omitted; browser identity headers must have a value.
use std::collections::BTreeMap;
use std::fmt;
use anyhow::{Context, Result, ensure};
use serde::de::{self, Deserializer};
use serde::{Deserialize, Serialize};
use wreq::header::{HeaderMap, HeaderName, HeaderValue, USER_AGENT};
/// Each kind of request the challenge flow makes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum RequestKind {
/// A navigation to a typed address.
Navigation,
/// A navigation retried with the high-entropy client hints its response demanded.
NavigationWithHints,
/// The challenge iframe's navigation.
Iframe,
/// A classic `<script src>` from another site.
Script,
/// A `crossorigin="anonymous"` script from another site.
CorsScript,
/// A classic script request after a redirect.
ScriptRedirect,
/// The orchestrator a challenge page loads from its own origin.
Orchestrator,
/// An image a challenge page loads from its own origin.
PageImage,
/// The orchestrator's XHR carrying an encoded challenge body.
OrchestratorPost,
/// The iframe's XHR carrying an encoded challenge body.
ChallengePost,
/// An image the challenge iframe loads.
Image,
/// A worker's `fetch(url, {cache: "no-cache"})`.
WorkerFetch,
/// A worker's `fetch(url, {cache: "no-store", credentials: "omit"})`.
WorkerFetchWithoutCredentials,
Form,
}
impl RequestKind {
/// Request kinds required in every profile. Profiles may omit hint retries if the browser
/// has no high-entropy client hints. They may omit a redirect order if the browser
/// preserves script headers on redirects.
const REQUIRED: [Self; 12] = [
Self::Navigation,
Self::Iframe,
Self::Script,
Self::CorsScript,
Self::Orchestrator,
Self::PageImage,
Self::OrchestratorPost,
Self::ChallengePost,
Self::Image,
Self::WorkerFetch,
Self::WorkerFetchWithoutCredentials,
Self::Form,
];
/// Lists headers this request kind can supply when the profile names a header without a
/// fixed value.
#[must_use]
pub(super) fn supplied(self) -> &'static [&'static str] {
match self {
Self::Navigation | Self::NavigationWithHints => &[],
Self::Iframe
| Self::Script
| Self::ScriptRedirect
| Self::Orchestrator
| Self::PageImage
| Self::Image => &["referer"],
Self::CorsScript => &["origin", "referer"],
Self::OrchestratorPost | Self::ChallengePost => {
&["content-length", "cf-chl", "origin", "referer"]
}
Self::WorkerFetch | Self::WorkerFetchWithoutCredentials => &["sec-fetch-site"],
Self::Form => &["content-length", "origin", "sec-fetch-site", "referer"],
}
}
}
/// Returns the request kind's profile name.
impl fmt::Display for RequestKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.serialize(formatter)
}
}
/// One header in a request's order.
#[derive(Clone, Debug)]
pub(super) enum Slot {
/// A header every request of the kind sends with this value.
Fixed(HeaderName, HeaderValue),
/// A header that takes its value from the request or the browser's own headers.
Named(HeaderName),
}
impl Slot {
/// A `"name: value"` or `"name"` entry in the header order for `kind`.
fn parse(kind: RequestKind, entry: &str) -> Result<Self> {
let header = |name: &str| {
HeaderName::from_bytes(name.as_bytes())
.with_context(|| format!("{name:?} is not a header name"))
};
let Some((name, value)) = entry.split_once(':') else {
let name = header(entry)?;
let identity = name == USER_AGENT || name.as_str().starts_with("sec-ch-");
ensure!(
identity || kind.supplied().contains(&name.as_str()),
"nothing gives `{name}` a value; write it as `{name}: <value>`"
);
return Ok(Self::Named(name));
};
let value = value.trim_start();
let value = HeaderValue::from_str(value)
.with_context(|| format!("{value:?} is not a header value"))?;
Ok(Self::Fixed(header(name)?, value))
}
}
/// Each kind of request's headers, in the order the browser sends them.
#[derive(Clone, Debug)]
pub struct HeaderOrder(BTreeMap<RequestKind, Vec<Slot>>);
impl HeaderOrder {
fn try_new(entries: BTreeMap<RequestKind, Vec<String>>) -> Result<Self> {
for kind in RequestKind::REQUIRED {
ensure!(
entries.contains_key(&kind),
"no order for `{kind}` requests"
);
}
let mut orders = BTreeMap::new();
for (kind, entries) in entries {
let slots = entries
.iter()
.map(|entry| Slot::parse(kind, entry))
.collect::<Result<Vec<Slot>>>()
.with_context(|| format!("reading the order of `{kind}` requests"))?;
orders.insert(kind, slots);
}
Ok(Self(orders))
}
/// The order of `kind` requests, if the profile gives one.
#[must_use]
pub(super) fn get(&self, kind: RequestKind) -> Option<&[Slot]> {
self.0.get(&kind).map(Vec::as_slice)
}
/// Checks that browser headers in `own` supply values for bare names that no request
/// supplies.
pub(super) fn check_own(&self, own: &HeaderMap) -> Result<()> {
for (kind, slots) in &self.0 {
for slot in slots {
if let Slot::Named(name) = slot
&& !kind.supplied().contains(&name.as_str())
{
ensure!(
own.contains_key(name),
"the order of `{kind}` requests names `{name}`, which the \
browser's headers do not give"
);
}
}
}
Ok(())
}
}
impl<'de> Deserialize<'de> for HeaderOrder {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let entries = BTreeMap::<RequestKind, Vec<String>>::deserialize(deserializer)?;
Self::try_new(entries).map_err(|error| de::Error::custom(format!("{error:#}")))
}
}
#[cfg(test)]
mod tests {
use serde_json::{Map, Value, json};
use super::*;
/// Creates header orders for every required request kind from the same `entries`.
fn every_kind(entries: &[&str]) -> Value {
let orders: Map<String, Value> = RequestKind::REQUIRED
.iter()
.map(|kind| (kind.to_string(), json!(entries)))
.collect();
Value::Object(orders)
}
fn read(orders: Value) -> Result<HeaderOrder, String> {
serde_json::from_value(orders).map_err(|error| error.to_string())
}
#[test]
fn entries_fix_a_value_or_name_one_something_supplies() {
let order = read(every_kind(&["user-agent", "sec-fetch-mode: navigate"])).unwrap();
let [Slot::Named(named), Slot::Fixed(name, value)] = order.get(RequestKind::Form).unwrap()
else {
panic!("not one named and one fixed header");
};
assert_eq!(*named, USER_AGENT);
assert_eq!(name, "sec-fetch-mode");
assert_eq!(value, "navigate");
let error = read(every_kind(&["sec-fetch-mode"])).unwrap_err();
assert!(
error.contains("nothing gives `sec-fetch-mode` a value"),
"{error}"
);
let error = read(every_kind(&["referer"])).unwrap_err();
assert!(
error.contains("the order of `navigation` requests"),
"a navigation supplies no referer: {error}"
);
}
#[test]
fn the_browser_gives_what_no_request_supplies() {
let order = read(every_kind(&["user-agent", "sec-ch-ua-model"])).unwrap();
let mut own = HeaderMap::new();
own.insert(USER_AGENT, HeaderValue::from_static("Mozilla/5.0"));
let error = order.check_own(&own).unwrap_err().to_string();
assert!(error.contains("names `sec-ch-ua-model`"), "{error}");
own.insert("sec-ch-ua-model", HeaderValue::from_static("\"\""));
order.check_own(&own).unwrap();
}
#[test]
fn only_the_optional_kinds_may_be_left_out() {
let mut orders = every_kind(&["user-agent"]);
let order = read(orders.clone()).unwrap();
assert!(order.get(RequestKind::ScriptRedirect).is_none());
assert!(order.get(RequestKind::NavigationWithHints).is_none());
orders
.as_object_mut()
.expect("every_kind builds an object")
.remove("image");
let error = read(orders).unwrap_err();
assert!(error.contains("no order for `image` requests"), "{error}");
}
}
+152
View File
@@ -0,0 +1,152 @@
//! Applies W3C Referrer Policy to request `Referer` headers and navigated frames'
//! `document.referrer`.
use scraper::{Html, Selector};
use url::Url;
/// Controls how much of a document's address is exposed as a referrer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ReferrerPolicy {
NoReferrer,
NoReferrerWhenDowngrade,
SameOrigin,
Origin,
StrictOrigin,
OriginWhenCrossOrigin,
/// The policy used when a document specifies none.
#[default]
StrictOriginWhenCrossOrigin,
UnsafeUrl,
}
impl ReferrerPolicy {
/// Parses a policy token without case sensitivity.
fn token(token: &str) -> Option<Self> {
Some(match token.trim().to_ascii_lowercase().as_str() {
"no-referrer" => Self::NoReferrer,
"no-referrer-when-downgrade" => Self::NoReferrerWhenDowngrade,
"same-origin" => Self::SameOrigin,
"origin" => Self::Origin,
"strict-origin" => Self::StrictOrigin,
"origin-when-cross-origin" => Self::OriginWhenCrossOrigin,
"strict-origin-when-cross-origin" => Self::StrictOriginWhenCrossOrigin,
"unsafe-url" => Self::UnsafeUrl,
_ => return None,
})
}
/// Parses a `<meta name="referrer">` value, including legacy keywords.
fn meta(content: &str) -> Option<Self> {
match content.trim().to_ascii_lowercase().as_str() {
"never" => Some(Self::NoReferrer),
"default" => Some(Self::StrictOriginWhenCrossOrigin),
"always" => Some(Self::UnsafeUrl),
"origin-when-crossorigin" => Some(Self::OriginWhenCrossOrigin),
other => Self::token(other),
}
}
/// Reads the last valid `Referrer-Policy` header token, then applies `<meta
/// name="referrer">` elements in document order.
#[must_use]
pub fn of_document(header: Option<&str>, html: &str) -> Self {
let mut policy = header
.into_iter()
.flat_map(|header| header.split(','))
.filter_map(Self::token)
.next_back()
.unwrap_or_default();
let metas = Selector::parse(r#"meta[name="referrer" i][content]"#)
.expect("a constant, valid selector");
for meta in Html::parse_document(html).select(&metas) {
if let Some(stated) = meta.attr("content").and_then(Self::meta) {
policy = stated;
}
}
policy
}
/// Returns the referrer for a request from `page` to `target`, if permitted.
#[must_use]
pub fn referrer(self, page: &Url, target: &Url) -> Option<String> {
let mut full = page.clone();
full.set_fragment(None);
// Credential setters require a host, which page URLs always have.
let _ = full.set_username("");
let _ = full.set_password(None);
let origin = origin_referrer(page);
let same_origin = page.origin() == target.origin();
let downgrade = page.scheme() == "https" && target.scheme() != "https";
match self {
Self::NoReferrer => None,
Self::UnsafeUrl => Some(full.into()),
Self::Origin => Some(origin),
Self::NoReferrerWhenDowngrade => (!downgrade).then(|| full.into()),
Self::SameOrigin => same_origin.then(|| full.into()),
Self::StrictOrigin => (!downgrade).then_some(origin),
Self::OriginWhenCrossOrigin if same_origin => Some(full.into()),
Self::OriginWhenCrossOrigin => Some(origin),
Self::StrictOriginWhenCrossOrigin if same_origin => Some(full.into()),
Self::StrictOriginWhenCrossOrigin => (!downgrade).then_some(origin),
}
}
}
/// The referrer that names only `url`'s origin.
#[must_use]
pub(super) fn origin_referrer(url: &Url) -> String {
format!("{}/", url.origin().ascii_serialization())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_meta_tag_overrides_the_header() {
// Some sites state their policy in markup.
let html = r#"<head><meta name="referrer" content="no-referrer"></head>"#;
let legacy = r#"<meta name="Referrer" content="never">"#;
let header = "no-referrer, bogus, same-origin, bogus";
let cases = [
(None, html, ReferrerPolicy::NoReferrer),
(Some("unsafe-url"), html, ReferrerPolicy::NoReferrer),
// The header's last valid token.
(Some(header), "", ReferrerPolicy::SameOrigin),
(None, legacy, ReferrerPolicy::NoReferrer),
// The default without a valid token.
(Some("bogus"), "<p>", ReferrerPolicy::default()),
];
for (header, html, expected) in cases {
let policy = ReferrerPolicy::of_document(header, html);
assert_eq!(policy, expected, "{header:?} with {html}");
}
}
#[test]
fn requests_carry_what_the_policy_allows() {
let page = Url::parse("https://user:pass@captchatest.book.bi/managed?x=1#top").unwrap();
let other = Url::parse("https://challenges.cloudflare.com/turnstile/v0/api.js").unwrap();
let same = page.join("/style.css").unwrap();
let insecure = Url::parse("http://example.com/").unwrap();
let full = Some("https://captchatest.book.bi/managed?x=1");
let origin = Some("https://captchatest.book.bi/");
let default = ReferrerPolicy::default();
let cases = [
// What the iPhone sent captchatest's widget iframe and loader.
(default, &other, origin),
(default, &same, full),
(default, &insecure, None),
(ReferrerPolicy::NoReferrer, &same, None),
(ReferrerPolicy::SameOrigin, &other, None),
(ReferrerPolicy::SameOrigin, &same, full),
(ReferrerPolicy::UnsafeUrl, &insecure, full),
(ReferrerPolicy::StrictOrigin, &insecure, None),
(ReferrerPolicy::Origin, &insecure, origin),
];
for (policy, target, expected) in cases {
let referrer = policy.referrer(&page, target);
assert_eq!(referrer.as_deref(), expected, "{policy:?} to {target}");
}
}
}
+592
View File
@@ -0,0 +1,592 @@
//! Builds requests used by the challenge flow. [`super::HeaderOrder`] supplies headers and
//! ordering; each request supplies values such as its referrer.
use anyhow::{Context, Result};
use url::Url;
use url::form_urlencoded::Serializer;
use wreq::cookie::Jar;
use wreq::header::LOCATION;
use wreq::redirect::Policy;
use wreq::{Response, StatusCode};
use super::client::BrowserClient;
use super::decode::{self, ResponseMetrics};
use super::header_order::RequestKind;
use super::referrer::{self, ReferrerPolicy};
use crate::engine::Engine;
/// Fetched iframe URL, HTML, and navigation measurements.
#[derive(Debug)]
pub struct Iframe {
pub url: Url,
pub html: String,
pub navigation: ResponseMetrics,
}
/// Fetches the embedding API's iframe URL using the page-policy `referer`. Never caches
/// challenge options because every response creates a separate POST session.
pub async fn fetch_iframe(
client: &BrowserClient,
url: Url,
referer: Option<&str>,
) -> Result<Iframe> {
let request = decode::preserve_encoding(client.http.get(url.as_str()));
let response = client
.send(request, RequestKind::Iframe, &[("referer", referer)])
.await?
.error_for_status()?;
let url = Url::parse(&response.uri().to_string())?;
let (decoded, navigation) = decode::read_encoded(response).await?;
let html = String::from_utf8(decoded).context("iframe HTML is not UTF-8")?;
Ok(Iframe {
url,
html,
navigation,
})
}
/// A fetched document and response metadata, regardless of status. Challenge pages use 403.
#[derive(Clone, Debug)]
pub struct PageDocument {
/// Final navigation URL, used to resolve relative links.
pub url: Url,
pub status: StatusCode,
pub html: String,
/// Referrer policy applied to the page's outgoing requests.
pub(crate) referrer_policy: ReferrerPolicy,
}
impl PageDocument {
/// A document served at `url` with its `Referrer-Policy` header, if any.
#[must_use]
pub(crate) fn new(url: Url, status: StatusCode, html: String, policy: Option<&str>) -> Self {
Self {
referrer_policy: ReferrerPolicy::of_document(policy, &html),
url,
status,
html,
}
}
async fn read(response: Response) -> Result<Self> {
let url = Url::parse(&response.uri().to_string())?;
let status = response.status();
let header = response
.headers()
.get("referrer-policy")
.map(decode::header_text);
let html = response.text().await?;
Ok(Self::new(url, status, html, header.as_deref()))
}
}
/// Navigates as if the user typed an address. Retries once if `Critical-CH` requires
/// high-entropy client hints and the profile supports that retry.
pub async fn navigate(client: &BrowserClient, url: &Url) -> Result<PageDocument> {
let navigation = async |kind| {
let request = client.http.get(url.as_str());
client
.send(request, kind, &[])
.await
.context("navigating to the page")
};
let mut response = navigation(RequestKind::Navigation).await?;
if response.headers().contains_key("critical-ch")
&& client.orders(RequestKind::NavigationWithHints)
{
response = navigation(RequestKind::NavigationWithHints).await?;
}
PageDocument::read(response).await
}
/// Loads a same-origin orchestrator script after the page has requested high-entropy hints.
/// `referer` is the page's temporary address during loading.
pub async fn fetch_orchestrator(
client: &BrowserClient,
url: &Url,
referer: &Url,
) -> Result<String> {
let request = client.http.get(url.as_str());
let supplied = [("referer", Some(referer.as_str()))];
let response = client
.send(request, RequestKind::Orchestrator, &supplied)
.await
.context("loading the orchestrator")?
.error_for_status()?;
Ok(response.text().await?)
}
/// Loads a same-origin image as the orchestrator would. Reads and discards the body, retaining
/// response timing.
pub async fn fetch_page_image(
client: &BrowserClient,
page: &Url,
url: &Url,
) -> Result<ResponseMetrics> {
let request = decode::preserve_encoding(client.http.get(url.as_str()));
let supplied = [("referer", Some(page.as_str()))];
let response = client
.send(request, RequestKind::PageImage, &supplied)
.await
.context("loading the page's image")?;
let (_, metrics) = decode::read_encoded(response).await?;
Ok(metrics)
}
/// Posts an encoded challenge body to `post_url` from `document` using `referer`. Does not
/// follow redirects, preserving the response for the caller.
async fn encoded_post(
client: &BrowserClient,
kind: RequestKind,
document: &Url,
referer: &str,
post_url: &Url,
cf_chl: &str,
encoded_body: String,
) -> Result<Response, wreq::Error> {
let length = encoded_body.len().to_string();
let origin = document.origin().ascii_serialization();
let request = decode::preserve_encoding(client.http.post(post_url.as_str()))
.redirect(Policy::none())
.body(encoded_body);
let supplied = [
("content-length", Some(length.as_str())),
("cf-chl", Some(cf_chl)),
("origin", Some(origin.as_str())),
("referer", Some(referer)),
];
client.send(request, kind, &supplied).await
}
/// The orchestrator's XHR to its challenge URL on the page's own origin.
/// Like [`post_challenge`], the response is returned intact.
pub async fn post_orchestrator(
client: &BrowserClient,
page: &Url,
post_url: &Url,
cf_chl: &str,
encoded_body: String,
) -> Result<Response> {
encoded_post(
client,
RequestKind::OrchestratorPost,
page,
page.as_str(),
post_url,
cf_chl,
encoded_body,
)
.await
.context("sending the orchestrator POST")
}
/// Submits a URL-encoded form as a navigation from `referer` to `action`.
pub async fn submit_form(
client: &BrowserClient,
referer: &Url,
action: &Url,
fields: &[(String, String)],
) -> Result<PageDocument> {
let body = Serializer::new(String::new()).extend_pairs(fields).finish();
let length = body.len().to_string();
let origin = referer.origin().ascii_serialization();
let site = if action.origin() == referer.origin() {
"same-origin"
} else {
"cross-site"
};
let request = client.http.post(action.as_str()).body(body);
let supplied = [
("content-length", Some(length.as_str())),
("origin", Some(origin.as_str())),
("sec-fetch-site", Some(site)),
("referer", Some(referer.as_str())),
];
let response = client
.send(request, RequestKind::Form, &supplied)
.await
.context("submitting the form")?;
PageDocument::read(response).await
}
/// How a page loads a script from another site.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScriptLoad {
/// A classic `<script src>`.
Classic,
/// An anonymous cross-origin script request. Sends no cookies and reports no storage
/// access.
Anonymous,
}
/// Loads a cross-origin script into `page`, using the page policy's `referer` as for the widget
/// loader.
pub async fn fetch_script(
client: &BrowserClient,
url: &Url,
load: ScriptLoad,
page: &Url,
referer: Option<&str>,
) -> Result<Response> {
let origin = page.origin().ascii_serialization();
let (kind, supplied): (RequestKind, &[(&str, Option<&str>)]) = match load {
ScriptLoad::Classic => (RequestKind::Script, &[("referer", referer)]),
ScriptLoad::Anonymous => (
RequestKind::CorsScript,
&[("origin", Some(origin.as_str())), ("referer", referer)],
),
};
// Follow the redirect manually when the browser uses a separate header order for redirected
// scripts.
let reorders_redirect = client.orders(RequestKind::ScriptRedirect);
let mut request = decode::preserve_encoding(client.http.get(url.as_str()));
if reorders_redirect {
request = request.redirect(Policy::none());
}
let response = client.send(request, kind, supplied).await?;
if !reorders_redirect || !response.status().is_redirection() {
return Ok(response.error_for_status()?);
}
let location = response
.headers()
.get(LOCATION)
.context("the loader's redirect has no location")?;
let target = url.join(location.to_str()?)?;
let redirected = match load {
ScriptLoad::Classic => RequestKind::ScriptRedirect,
// No redirected CORS load has been observed, so preserve its original order.
ScriptLoad::Anonymous => kind,
};
let request = decode::preserve_encoding(client.http.get(target.as_str()));
Ok(client
.send(request, redirected, supplied)
.await?
.error_for_status()?)
}
/// The iframe's XHR of a challenge's encoded body to `post_url`. The response
/// is returned intact, so callers can read Cloudflare's error body too.
pub async fn post_challenge(
client: &BrowserClient,
iframe: &Iframe,
post_url: &Url,
cf_chl: &str,
encoded_body: String,
) -> Result<Response> {
let referer = iframe_referrer(client, iframe);
encoded_post(
client,
RequestKind::ChallengePost,
&iframe.url,
&referer,
post_url,
cf_chl,
encoded_body,
)
.await
.context("sending the challenge POST")
}
/// Loads an image in the iframe document as an `<img>` element would.
pub async fn fetch_image(client: &BrowserClient, iframe: &Iframe, url: &Url) -> Result<Response> {
let request = decode::preserve_encoding(client.http.get(url.as_str()));
let referer = iframe_referrer(client, iframe);
let supplied = [("referer", Some(referer.as_str()))];
client
.send(request, RequestKind::Image, &supplied)
.await
.context("loading a challenge image")
}
/// Returns the iframe request's referrer. WebKit exposes only the iframe URL's origin.
fn iframe_referrer(client: &BrowserClient, iframe: &Iframe) -> String {
match client.engine {
Engine::Chromium => iframe.url.to_string(),
Engine::WebKit => referrer::origin_referrer(&iframe.url),
}
}
/// Worker fetch options that affect request headers and cookies.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FetchOptions {
/// `{cache: "no-cache"}`: revalidate whatever the cache holds.
NoCache,
/// `{cache: "no-store", credentials: "omit"}`: bypasses the cache, sends no cookies, and
/// ignores response cookies.
NoStoreWithoutCredentials,
}
/// Fetches from an iframe worker using its `fetch` options. Worker requests send neither a
/// referrer nor client hints.
pub async fn fetch_from_worker(
client: &BrowserClient,
iframe: &Iframe,
url: &Url,
options: FetchOptions,
) -> Result<Response> {
let site = if url.origin() == iframe.url.origin() {
"same-origin"
} else {
"same-site"
};
let mut request = client.http.get(url.as_str());
let kind = match options {
FetchOptions::NoCache => RequestKind::WorkerFetch,
FetchOptions::NoStoreWithoutCredentials => {
request = request.cookie_provider(Jar::default());
RequestKind::WorkerFetchWithoutCredentials
}
};
let supplied = [("sec-fetch-site", Some(site))];
client
.send(request, kind, &supplied)
.await
.context("fetching from the challenge worker")
}
#[cfg(test)]
mod tests {
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use wreq::Client;
use wreq::header::{HeaderMap, HeaderValue, USER_AGENT};
use super::*;
/// A request the test server received.
struct Received {
/// The request line and headers, each ending in CRLF.
head: String,
body: String,
}
fn read_request(stream: &mut TcpStream) -> Received {
let mut reader = BufReader::new(stream);
let mut head = String::new();
while !head.ends_with("\r\n\r\n") {
let read = reader.read_line(&mut head).unwrap();
assert_ne!(read, 0, "the client closed the connection mid-request");
}
// Leave off the blank line that ends the head.
head.truncate(head.len() - 2);
let length: usize = head
.lines()
.filter_map(|line| line.split_once(':'))
.find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
.map_or(0, |(_, value)| value.trim().parse().unwrap());
let mut body = vec![0; length];
reader.read_exact(&mut body).unwrap();
let body = String::from_utf8(body).unwrap();
Received { head, body }
}
/// Serves each of `responses` on its own loopback connection. Returns the address and a
/// thread that returns the requests it received.
fn serve(responses: Vec<Vec<u8>>) -> (SocketAddr, JoinHandle<Vec<Received>>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let server = thread::spawn(move || {
let mut received = Vec::with_capacity(responses.len());
for response in responses {
let (mut stream, _) = listener.accept().unwrap();
// Fail the test if a request stalls instead of waiting indefinitely.
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
received.push(read_request(&mut stream));
stream.write_all(&response).unwrap();
}
received
});
(address, server)
}
#[tokio::test]
async fn iframe_fetch_preserves_compressed_sizes_and_server_timing() {
let html = "<html><script>window._cf_chl_opt = {};</script></html>";
let compressed = decode::encode_body(html.as_bytes(), "gzip").unwrap();
let encoded_length = compressed.len();
let mut response = format!("HTTP/1.1 200 OK\r\nContent-Encoding: gzip\r\nContent-Length: {}\r\nServer-Timing: session;dur={}\r\nConnection: close\r\n\r\n", encoded_length, html.len()).into_bytes();
response.extend_from_slice(&compressed);
let (address, server) = serve(vec![response]);
let client = BrowserClient::from_http(Client::builder().gzip(true).build().unwrap());
let iframe = fetch_iframe(
&client,
Url::parse(&format!("http://{address}/iframe")).unwrap(),
None,
)
.await
.unwrap();
server.join().unwrap();
assert_eq!(iframe.html, html);
assert_eq!(iframe.navigation.encoded_bytes, encoded_length as u64);
assert_eq!(iframe.navigation.decoded_bytes, html.len() as u64);
assert_eq!(
iframe.navigation.server_timing,
[("session".into(), html.len() as f64)]
);
}
/// Runs widget requests against a loopback server. Returns its address and lowercase
/// request headers. Matches captured Safari traffic: the loader redirects, and the page
/// sends its origin as referrer when no policy is specified.
async fn flow(client: &BrowserClient) -> (SocketAddr, Vec<String>) {
let body = "<script>window._cf_chl_opt = {};</script>";
let ok = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let redirect =
b"HTTP/1.1 302 Found\r\nLocation: /b/api.js\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
let mut responses = vec![ok.into_bytes(); 6];
responses.insert(1, redirect.to_vec());
let (address, server) = serve(responses);
let page = Url::parse(&format!("http://{address}/page")).unwrap();
let origin = format!("http://{address}/");
let referer = Some(origin.as_str());
navigate(client, &page).await.unwrap();
let script = page.join("/api.js").unwrap();
fetch_script(client, &script, ScriptLoad::Classic, &page, referer)
.await
.unwrap();
let iframe = fetch_iframe(client, page.join("/iframe").unwrap(), referer)
.await
.unwrap();
let url = iframe.url.join("/resource").unwrap();
post_challenge(client, &iframe, &url, "token", "body".into())
.await
.unwrap();
fetch_image(client, &iframe, &url).await.unwrap();
fetch_from_worker(client, &iframe, &url, FetchOptions::NoCache)
.await
.unwrap();
let heads: Vec<String> = server
.join()
.unwrap()
.into_iter()
.map(|request| request.head.to_ascii_lowercase())
.collect();
(address, heads)
}
/// Lists header names from `heads` in order, excluding `host` and separating names with
/// spaces.
fn header_names(heads: &[String]) -> Vec<String> {
let mut sent = Vec::new();
for head in heads {
let names: Vec<&str> = head
.lines()
.skip(1)
.map(|line| line.split(':').next().unwrap())
.filter(|name| *name != "host")
.collect();
sent.push(names.join(" "));
}
sent
}
/// Expected header order from the tracked iOS Safari 26.6 profile, verified against
/// captchatest proxy traffic. Includes Safari's separate redirected-loader order.
#[tokio::test]
async fn webkit_requests_send_safaris_headers_in_its_order() {
let client = BrowserClient {
own: HeaderMap::from_iter([(USER_AGENT, HeaderValue::from_static("Mozilla/5.0"))]),
..BrowserClient::from_http(Client::new())
};
let (address, heads) = flow(&client).await;
let loaded = "sec-fetch-dest user-agent accept referer sec-fetch-site sec-fetch-mode \
accept-language priority accept-encoding";
let expected = [
"sec-fetch-dest user-agent upgrade-insecure-requests accept sec-fetch-site \
sec-fetch-mode accept-language priority accept-encoding",
loaded,
"accept sec-fetch-site priority sec-fetch-mode user-agent accept-language \
sec-fetch-dest referer accept-encoding",
loaded,
"accept content-type sec-fetch-site origin cf-chl content-length sec-fetch-mode \
user-agent referer sec-fetch-dest cf-chl-ra accept-language priority \
accept-encoding",
loaded,
"sec-fetch-dest user-agent accept sec-fetch-site cache-control sec-fetch-mode \
accept-language priority accept-encoding",
];
assert!(heads[2].starts_with("get /b/api.js "), "{}", heads[2]);
for head in &heads[4..6] {
assert!(
head.contains(&format!("referer: http://{address}/\r\n")),
"inside the iframe, only its origin is the referrer: {head}"
);
}
assert_eq!(header_names(&heads), expected);
}
#[tokio::test]
async fn worker_fetches_that_omit_credentials_neither_send_nor_keep_cookies() {
let responses = ["session=kept", "omitted=dropped", "later=1"].map(|cookie| {
format!("HTTP/1.1 200 OK\r\nSet-Cookie: {cookie}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").into_bytes()
});
let (address, server) = serve(responses.into());
let client =
BrowserClient::from_http(Client::builder().cookie_store(true).build().unwrap());
let iframe = Iframe {
url: Url::parse(&format!("http://{address}/iframe")).unwrap(),
html: String::new(),
navigation: ResponseMetrics::default(),
};
let url = iframe.url.join("/fetch").unwrap();
// Set a same-origin cookie to check whether worker fetches send it.
client.http.get(iframe.url.as_str()).send().await.unwrap();
let without_credentials = FetchOptions::NoStoreWithoutCredentials;
for options in [without_credentials, FetchOptions::NoCache] {
fetch_from_worker(&client, &iframe, &url, options)
.await
.unwrap();
}
let received = server.join().unwrap();
let omitted = received[1].head.to_ascii_lowercase();
let included = received[2].head.to_ascii_lowercase();
assert!(!omitted.contains("cookie:"), "{omitted}");
assert!(included.contains("cookie: session=kept"), "{included}");
assert!(!included.contains("omitted=dropped"), "{included}");
}
#[tokio::test]
async fn sends_encoded_bytes_and_session_headers_without_following_redirects() {
let (address, server) = serve(vec![
b"HTTP/1.1 302 Found\r\nLocation: /unexpected\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec(),
]);
let iframe = Iframe {
url: Url::parse(&format!("http://{address}/iframe?lang=auto")).unwrap(),
html: String::new(),
navigation: ResponseMetrics::default(),
};
let client = BrowserClient::from_http(Client::new());
let response = post_challenge(
&client,
&iframe,
&iframe.url.join("/fo/build/ray/token").unwrap(),
"token",
"abc+$-123".into(),
)
.await
.unwrap();
assert_eq!(response.status().as_u16(), 302);
let Received { head, body } = server.join().unwrap().remove(0);
assert_eq!(body, "abc+$-123");
let headers = head.to_ascii_lowercase();
for expected in [
"content-type: text/plain;charset=utf-8",
"cf-chl: token",
"cf-chl-ra: 0",
"content-length: 9",
"sec-fetch-site: same-origin",
] {
assert!(headers.contains(expected), "missing {expected}: {headers}");
}
// WebKit sends only the iframe's origin.
assert!(headers.contains(&format!("referer: http://{address}/\r\n")));
}
}
+16
View File
@@ -0,0 +1,16 @@
//! JavaScript support shared across the crate: syntax helpers, numeric conversions, value
//! semantics, and the challenge's typed objects.
pub(crate) mod ast;
mod numeric;
mod objects;
mod value;
pub(crate) use numeric::{
bit_and, bit_not, bit_or, bit_xor, int32, parse_integer, shl, shr, string_number, uint32, ushr,
};
pub use objects::{Options, Payload, Window};
#[cfg(test)]
pub(crate) use value::from_value;
pub(crate) use value::{ErrorValue, json, number, present, string, stringify_object, truthy};
pub use value::{JsObject, JsValue};
+421
View File
@@ -0,0 +1,421 @@
//! JavaScript parsing, syntax matchers, and node constructors shared by extraction and
//! deobfuscation.
//!
//! Matchers accept different syntax depending on the extractor's requirements.
use std::collections::BTreeSet;
use anyhow::{Result, ensure};
use swc_core::atoms::Wtf8Atom;
use swc_core::common::sync::Lrc;
use swc_core::common::{
BytePos, DUMMY_SP, FileName, SourceFile, SourceMap, Spanned, SyntaxContext,
};
use swc_core::ecma::ast::{
AssignExpr, AssignOp, BinaryOp, BlockStmt, Expr, ExprOrSpread, ExprStmt, FnDecl, Function, Id,
Ident, KeyValueProp, Lit, MemberExpr, MemberProp, ObjectLit, ParenExpr, Pat, PropName,
PropOrSpread, Script, Stmt, UnaryOp, VarDeclarator,
};
use swc_core::ecma::parser::{Parser, StringInput, Syntax};
use swc_core::ecma::visit::{Visit, VisitWith};
use crate::engine::{self, Lines};
/// A parsed script and its original source text.
pub(crate) struct ParsedScript {
pub script: Script,
file: Lrc<SourceFile>,
}
impl ParsedScript {
/// Returns the original source text for `node`.
///
/// # Panics
///
/// Panics if `node` was not parsed from this script.
#[must_use]
pub(crate) fn text(&self, node: &dyn Spanned) -> &str {
let span = node.span();
let offset = |position: BytePos| (position.0 - self.file.start_pos.0) as usize;
&self.file.src[offset(span.lo)..offset(span.hi)]
}
/// Returns the one-based line and UTF-16 column at `at`, matching V8 stack traces.
///
/// # Panics
///
/// Panics if `at` is outside this script.
#[must_use]
pub(crate) fn position(&self, at: BytePos) -> (usize, usize) {
let before = &self.file.src[..(at.0 - self.file.start_pos.0) as usize];
let (line, column) = engine::line_and_column(before, Lines::Script);
(line as usize + 1, column as usize + 1)
}
}
pub(crate) fn parse_iframe_javascript(source: &str) -> Result<ParsedScript> {
parse_javascript("deobfuscated iframe", source)
}
/// Parses `source`, using `what` to identify it in errors.
pub(crate) fn parse_javascript(what: &str, source: &str) -> Result<ParsedScript> {
let source_map = SourceMap::default();
let file = source_map.new_source_file(FileName::Custom(what.into()).into(), source.to_owned());
let mut parser = Parser::new(Syntax::default(), StringInput::from(&*file), None);
let script = parser
.parse_script()
.map_err(|error| anyhow::anyhow!("cannot parse {what}: {error:?}"))?;
ensure!(parser.take_errors().is_empty(), "{what} has parse errors");
Ok(ParsedScript { script, file })
}
/// Parses one expression, without its surrounding parentheses.
#[cfg(test)]
pub(crate) fn parse_expression(what: &str, text: &str) -> Result<Expr> {
// Parentheses make leading braces parse as an object literal.
let parsed = parse_javascript(what, &format!("({text})"))?;
let [Stmt::Expr(statement)] = parsed.script.body.as_slice() else {
anyhow::bail!("{what} is not one expression");
};
Ok(statement.expr.unwrap_parens().clone())
}
/// Returns a string literal or template without substitutions as WTF-8, preserving lone
/// surrogates. Does not unwrap parentheses.
#[must_use]
pub(crate) fn static_wtf8(expression: &Expr) -> Option<&Wtf8Atom> {
match expression {
Expr::Lit(Lit::Str(value)) => Some(&value.value),
Expr::Tpl(template) if template.exprs.is_empty() => {
template.quasis.first()?.cooked.as_ref()
}
_ => None,
}
}
/// Converts [`static_wtf8`] to a Rust string. Returns `None` for lone surrogates instead of
/// replacing them with U+FFFD and changing the recovered value.
#[must_use]
pub(crate) fn static_str(expression: &Expr) -> Option<&str> {
static_wtf8(expression)?.as_str()
}
/// The static name of a member property: `object.name`, `object["name"]`, or
/// ``object[`name`]`` when the template has no substitutions.
#[must_use]
pub(crate) fn member_str(property: &MemberProp) -> Option<&str> {
match property {
MemberProp::Ident(name) => Some(&*name.sym),
MemberProp::Computed(computed) => static_str(&computed.expr),
_ => None,
}
}
/// Matches a property read directly from an identifier, such as a namespace or local, using
/// [`member_str`].
#[must_use]
pub(crate) fn ident_property(member: &MemberExpr) -> Option<&str> {
match &*member.obj {
Expr::Ident(_) => member_str(&member.prop),
_ => None,
}
}
/// Reads an identifier or quoted object-literal key. Excludes numeric and computed keys.
#[must_use]
pub(crate) fn key_str(key: &PropName) -> Option<&str> {
match key {
PropName::Ident(name) => Some(&*name.sym),
PropName::Str(name) => name.value.as_str(),
_ => None,
}
}
/// Reads keys accepted by [`key_str`], plus computed static strings such as `["name"]` or
/// ``[`name`]``.
#[must_use]
pub(crate) fn static_key_str(key: &PropName) -> Option<&str> {
match key {
PropName::Computed(name) => static_str(&name.expr),
key => key_str(key),
}
}
/// Matches `key: value` properties, excluding spreads, methods, accessors, and shorthand
/// entries.
#[must_use]
pub(crate) fn key_value(property: &PropOrSpread) -> Option<&KeyValueProp> {
property.as_prop()?.as_key_value()
}
/// Returns only [`key_value`] properties from an object literal.
pub(crate) fn key_values(object: &ObjectLit) -> impl Iterator<Item = &KeyValueProp> {
object.props.iter().filter_map(key_value)
}
/// Collects distinct static strings from `node`; see [`static_str`].
#[must_use]
pub(crate) fn string_literals(node: &impl VisitWith<StringLiterals>) -> BTreeSet<String> {
let mut literals = StringLiterals(BTreeSet::new());
node.visit_with(&mut literals);
literals.0
}
pub(crate) struct StringLiterals(BTreeSet<String>);
impl Visit for StringLiterals {
fn visit_expr(&mut self, expression: &Expr) {
if let Some(literal) = static_str(expression) {
self.0.insert(literal.to_owned());
}
expression.visit_children_with(self);
}
}
/// Applies `read` to each function declaration in `script`, in source order, keeping what it
/// returns.
pub(crate) fn in_declared_functions<T>(script: &Script, read: fn(&FnDecl) -> Option<T>) -> Vec<T> {
struct Found<T> {
read: fn(&FnDecl) -> Option<T>,
results: Vec<T>,
}
impl<T> Visit for Found<T> {
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
self.results.extend((self.read)(declaration));
declaration.visit_children_with(self);
}
}
let mut found = Found {
read,
results: Vec::new(),
};
script.visit_with(&mut found);
found.results
}
/// Returns function declarations in `script` by name, in source order.
#[must_use]
pub(crate) fn declared_functions(script: &Script) -> Vec<(String, Function)> {
in_declared_functions(script, |declaration| {
Some((
declaration.ident.sym.to_string(),
(*declaration.function).clone(),
))
})
}
/// Returns declared, assigned, and variable-initialized functions by binding ID in source order.
#[must_use]
pub(crate) fn named_functions(node: &impl VisitWith<NamedFunctions>) -> Vec<(Id, Function)> {
let mut functions = NamedFunctions(Vec::new());
node.visit_with(&mut functions);
functions.0
}
pub(crate) struct NamedFunctions(Vec<(Id, Function)>);
impl Visit for NamedFunctions {
fn visit_fn_decl(&mut self, declaration: &FnDecl) {
let function = (*declaration.function).clone();
self.0.push((declaration.ident.to_id(), function));
declaration.visit_children_with(self);
}
fn visit_assign_expr(&mut self, assignment: &AssignExpr) {
if assignment.op == AssignOp::Assign
&& let Some(name) = assignment.left.as_ident()
&& let Expr::Fn(function) = &*assignment.right
{
self.0.push((name.to_id(), (*function.function).clone()));
}
assignment.visit_children_with(self);
}
fn visit_var_declarator(&mut self, declaration: &VarDeclarator) {
if let Pat::Ident(name) = &declaration.name
&& let Some(Expr::Fn(function)) = declaration.init.as_deref()
{
self.0.push((name.to_id(), (*function.function).clone()));
}
declaration.visit_children_with(self);
}
}
/// Whether an expression is a `Date.now()` call.
#[must_use]
pub(crate) fn is_date_now(expression: &Expr) -> bool {
expression
.as_call()
.and_then(|call| call.callee.as_expr()?.as_member())
.is_some_and(|member| is_method_of(member, "Date", "now"))
}
/// Matches a method call on the plain identifier `object`, such as `<object>.<property>(...)`.
#[must_use]
pub(crate) fn is_method_of(member: &MemberExpr, object: &str, property: &str) -> bool {
matches!(&*member.obj, Expr::Ident(ident) if ident.sym == object)
&& member_str(&member.prop) == Some(property)
}
/// Returns the binding and assigned value from `binding = value`.
#[must_use]
pub(crate) fn assignment(expression: &Expr) -> Option<(Id, &Expr)> {
let assignment = expression.as_assign()?;
if assignment.op != AssignOp::Assign {
return None;
}
Some((assignment.left.as_ident()?.to_id(), &assignment.right))
}
/// Matches `callee(args)` when the callee is a plain identifier.
#[must_use]
pub(crate) fn direct_call(expression: &Expr) -> Option<(&Ident, &[ExprOrSpread])> {
let call = expression.as_call()?;
Some((call.callee.as_expr()?.as_ident()?, &call.args))
}
/// Returns the object and arguments from `object.name(args)` or `object["name"](args)`.
#[must_use]
pub(crate) fn method_call<'a>(
expression: &'a Expr,
name: &str,
) -> Option<(&'a Expr, &'a [ExprOrSpread])> {
let call = expression.as_call()?;
let member = call.callee.as_expr()?.as_member()?;
(member_str(&member.prop) == Some(name)).then_some((&*member.obj, &call.args[..]))
}
/// A numeric literal, possibly signed or parenthesized.
#[must_use]
pub(crate) fn number(expression: &Expr) -> Option<f64> {
match expression {
Expr::Lit(Lit::Num(value)) => Some(value.value),
Expr::Paren(value) => number(&value.expr),
Expr::Unary(value) if value.op == UnaryOp::Minus => Some(-number(&value.arg)?),
Expr::Unary(value) if value.op == UnaryOp::Plus => number(&value.arg),
_ => None,
}
}
/// Evaluates numeric arithmetic: literals, parentheses, and the unary and binary numeric
/// operators. `leaf` supplies the value of anything else, such as a known parameter.
#[must_use]
pub(crate) fn fold_number(expression: &Expr, leaf: &impl Fn(&Expr) -> Option<f64>) -> Option<f64> {
let fold = |expression: &Expr| fold_number(expression, leaf);
match expression {
Expr::Lit(Lit::Num(value)) => Some(value.value),
Expr::Paren(value) => fold(&value.expr),
Expr::Unary(value) => {
let operand = fold(&value.arg)?;
match value.op {
UnaryOp::Minus => Some(-operand),
UnaryOp::Plus => Some(operand),
UnaryOp::Tilde => Some(super::bit_not(operand)),
_ => None,
}
}
Expr::Bin(binary) => {
let (left, right) = (fold(&binary.left)?, fold(&binary.right)?);
match binary.op {
BinaryOp::Add => Some(left + right),
BinaryOp::Sub => Some(left - right),
BinaryOp::Mul => Some(left * right),
BinaryOp::Div => Some(left / right),
BinaryOp::Mod => Some(left % right),
BinaryOp::BitAnd => Some(super::bit_and(left, right)),
BinaryOp::BitOr => Some(super::bit_or(left, right)),
BinaryOp::BitXor => Some(super::bit_xor(left, right)),
BinaryOp::LShift => Some(super::shl(left, right)),
BinaryOp::RShift => Some(super::shr(left, right)),
BinaryOp::ZeroFillRShift => Some(super::ushr(left, right)),
_ => None,
}
}
_ => leaf(expression),
}
}
/// Converts `value` to a nonnegative array index, treating `-0` as zero. Rejects infinities and
/// NaN. Saturates finite values above `usize::MAX` so bounds checks still reject them.
#[must_use]
pub(crate) fn array_index(value: f64) -> Option<usize> {
(value.fract() == 0.0 && value >= 0.0).then_some(value as usize)
}
/// Matches a numeric-literal [`array_index`]. Unlike [`number`], does not unwrap signs or
/// parentheses.
#[must_use]
pub(crate) fn index_literal(expression: &Expr) -> Option<usize> {
match expression {
Expr::Lit(Lit::Num(value)) => array_index(value.value),
_ => None,
}
}
/// Returns the expression from a function whose entire body is `return value;`.
#[must_use]
pub(crate) fn returned(function: &Function) -> Option<&Expr> {
match function.body.as_ref()?.stmts.as_slice() {
[Stmt::Return(returned)] => returned.arg.as_deref(),
_ => None,
}
}
/// Returns the sequence operands from a function whose entire body is `return a, b, ...;`.
#[must_use]
pub(crate) fn return_sequence(function: &Function) -> Option<&[Box<Expr>]> {
if function.is_async || function.is_generator {
return None;
}
Some(returned(function)?.as_seq()?.exprs.as_slice())
}
/// A block grouping statements that came from one place.
#[must_use]
pub(crate) fn block(statements: Vec<Stmt>) -> Stmt {
Stmt::Block(BlockStmt {
span: DUMMY_SP,
ctxt: SyntaxContext::default(),
stmts: statements,
})
}
/// Creates an expression statement with the expression's source span.
#[must_use]
pub(crate) fn expression_statement(expression: Box<Expr>) -> Stmt {
Stmt::Expr(ExprStmt {
span: expression.span(),
expr: expression,
})
}
/// Wraps an expression in parentheses with the same span so an inlined value remains a single
/// operand.
#[must_use]
pub(crate) fn parenthesized(expression: Box<Expr>) -> Expr {
Expr::Paren(ParenExpr {
span: expression.span(),
expr: expression,
})
}
#[cfg(test)]
mod tests {
use super::*;
/// Only a static key reads through a computed string literal.
#[test]
fn static_keys_also_accept_computed_strings() {
let Expr::Object(object) =
parse_expression("t", r#"{a: 1, "b": 2, ["c"]: 3, [d]: 4, 5: 5}"#).unwrap()
else {
panic!("not an object")
};
let keys: Vec<_> = key_values(&object).map(|p| key_str(&p.key)).collect();
assert_eq!(keys, [Some("a"), Some("b"), None, None, None]);
let keys: Vec<_> = key_values(&object)
.map(|p| static_key_str(&p.key))
.collect();
assert_eq!(keys, [Some("a"), Some("b"), Some("c"), None, None]);
}
}
+205
View File
@@ -0,0 +1,205 @@
//! JavaScript's `ToInt32`, `ToUint32`, bitwise operators, `Number`, and `parseInt` on `f64`.
/// Converts to a signed 32-bit integer using JavaScript's `value | 0` rules.
#[must_use]
#[inline(always)]
pub(crate) fn int32(value: f64) -> i32 {
uint32(value) as i32
}
/// Converts to an unsigned 32-bit integer using JavaScript's `value >>> 0` rules.
#[must_use]
#[inline(always)]
pub(crate) fn uint32(value: f64) -> u32 {
// A truncated value with magnitude below 2^63 fits exactly in `i64`. Its low 32 bits give
// the value modulo 2^32.
if value.abs() < 9_223_372_036_854_775_808.0 {
value as i64 as u32
} else if value.is_finite() {
value.rem_euclid(4_294_967_296.0) as u32
} else {
0
}
}
// JavaScript's bitwise operators, with `ushr` as `>>>`. Shifts take the count modulo 32.
#[must_use]
#[inline(always)]
pub(crate) fn bit_and(a: f64, b: f64) -> f64 {
f64::from(int32(a) & int32(b))
}
#[must_use]
#[inline(always)]
pub(crate) fn bit_or(a: f64, b: f64) -> f64 {
f64::from(int32(a) | int32(b))
}
#[must_use]
#[inline(always)]
pub(crate) fn bit_xor(a: f64, b: f64) -> f64 {
f64::from(int32(a) ^ int32(b))
}
#[must_use]
#[inline(always)]
pub(crate) fn bit_not(a: f64) -> f64 {
f64::from(!int32(a))
}
#[must_use]
#[inline(always)]
pub(crate) fn shl(a: f64, b: f64) -> f64 {
f64::from(int32(a).wrapping_shl(uint32(b)))
}
#[must_use]
#[inline(always)]
pub(crate) fn shr(a: f64, b: f64) -> f64 {
f64::from(int32(a).wrapping_shr(uint32(b)))
}
#[must_use]
#[inline(always)]
pub(crate) fn ushr(a: f64, b: f64) -> f64 {
f64::from(uint32(a).wrapping_shr(uint32(b)))
}
/// Matches ECMAScript whitespace and line terminators skipped by `Number`, `parseInt`, and
/// `trim`. Includes the byte order mark (BOM) and excludes U+0085 (NEXT LINE).
fn is_whitespace(c: char) -> bool {
c == '\u{feff}' || (c.is_whitespace() && c != '\u{85}')
}
/// `Number(text)`: JavaScript's StringToNumber.
#[must_use]
pub(crate) fn string_number(text: &str) -> f64 {
let text = text.trim_matches(is_whitespace);
match text {
"" => return 0.0,
"Infinity" | "+Infinity" => return f64::INFINITY,
"-Infinity" => return f64::NEG_INFINITY,
_ => {}
}
let radix = match text.get(..2) {
Some("0x" | "0X") => Some(16),
Some("0o" | "0O") => Some(8),
Some("0b" | "0B") => Some(2),
_ => None,
};
if let Some(radix) = radix {
let digits = &text[2..];
if digits.is_empty() {
return f64::NAN;
}
let value = digits.chars().try_fold(0.0, |n, c| {
Some(n * f64::from(radix) + f64::from(c.to_digit(radix)?))
});
return value.unwrap_or(f64::NAN);
}
if text
.bytes()
.any(|b| !b.is_ascii_digit() && !b"+-.eE".contains(&b))
{
return f64::NAN;
}
text.parse().unwrap_or(f64::NAN)
}
/// `parseInt(text)` with no radix: decimal, or hexadecimal after `0x`.
#[must_use]
pub(crate) fn parse_integer(text: &str) -> f64 {
let text = text.trim_start_matches(is_whitespace);
let (sign, text) = match text.strip_prefix('-') {
Some(text) => (-1.0, text),
None => (1.0, text.strip_prefix('+').unwrap_or(text)),
};
let (radix, text) = match text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
Some(text) => (16, text),
None => (10, text),
};
if !text.starts_with(|character: char| character.is_digit(radix)) {
return f64::NAN;
}
let digits = text
.chars()
.map_while(|character| character.to_digit(radix));
sign * digits.fold(0.0, |value, digit| {
value * f64::from(radix) + f64::from(digit)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn text_follows_string_to_number() {
assert_eq!(string_number(" \u{feff}12 "), 12.0);
assert_eq!(string_number(""), 0.0);
assert_eq!(string_number("0x1f"), 31.0);
assert!(string_number("0x").is_nan());
assert_eq!(string_number("-Infinity"), f64::NEG_INFINITY);
assert!(string_number("1_000").is_nan());
for (text, number) in [("0b101", 5.0), ("1e3", 1000.0), (".5", 0.5), ("5.", 5.0)] {
assert_eq!(string_number(text), number, "{text:?}");
}
let whitespace = "\t\n\r\u{b}\u{c} \u{a0}\u{1680}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\
\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200a}\u{2028}\u{2029}\
\u{202f}\u{205f}\u{3000}\u{feff}";
for c in whitespace.chars() {
assert_eq!(string_number(&format!("{c}12{c}")), 12.0, "{c:?}");
}
for text in [
"\u{85}12",
"\u{200b}12",
"\u{180e}12",
"inf",
"nan",
"infinity",
"-0x1",
"e5",
"+",
] {
assert!(string_number(text).is_nan(), "{text:?}");
}
}
#[test]
fn parses_javascript_integer_prefixes() {
for (text, expected) in [
(" -12tail", -12.0),
("+0x20suffix", 32.0),
("1e3", 1.0),
("\u{feff}42", 42.0),
] {
assert_eq!(parse_integer(text), expected, "{text:?}");
}
assert!(parse_integer("text").is_nan());
assert!(parse_integer("\u{85}12").is_nan());
}
#[test]
fn integer_conversions_wrap_and_truncate() {
assert_eq!(int32(-1.5), -1);
assert_eq!(int32(2_147_483_648.0), -2_147_483_648);
assert_eq!(int32(f64::NAN), 0);
assert_eq!(int32(f64::INFINITY), 0);
assert_eq!(uint32(-1.0), 4_294_967_295);
assert_eq!(uint32(-4_294_967_297.5), 4_294_967_295);
assert_eq!(uint32(2f64.powi(63) + 2f64.powi(31) * 3.0), 2_147_483_648);
assert_eq!(int32(-2f64.powi(70)), 0);
assert_eq!(uint32(f64::NEG_INFINITY), 0);
}
#[test]
fn shifts_take_the_count_modulo_32() {
assert_eq!(shl(1.0, 33.0), 2.0);
assert_eq!(shl(1.0, 31.0), -2_147_483_648.0);
assert_eq!(shr(-8.0, 1.0), -4.0);
assert_eq!(ushr(-8.0, 1.0), 2_147_483_644.0);
assert_eq!(ushr(-1.0, 0.0), 4_294_967_295.0);
assert_eq!(bit_not(f64::NAN), -1.0);
}
}
+80
View File
@@ -0,0 +1,80 @@
//! Typed [`JsObject`]s for the iframe's `_cf_chl_opt` options, window globals, and plaintext
//! payloads, kept apart so callers cannot mix them up.
use std::ops::{Deref, DerefMut};
use serde::{Deserialize, Serialize};
use crate::js::{JsObject, JsValue};
macro_rules! object {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(transparent)]
pub struct $name(JsObject);
impl $name {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl Deref for $name {
type Target = JsObject;
fn deref(&self) -> &JsObject {
&self.0
}
}
impl DerefMut for $name {
fn deref_mut(&mut self) -> &mut JsObject {
&mut self.0
}
}
impl From<JsObject> for $name {
fn from(properties: JsObject) -> Self {
Self(properties)
}
}
impl From<$name> for JsValue {
fn from(object: $name) -> Self {
Self::Object(object.0)
}
}
impl IntoIterator for $name {
type Item = (String, JsValue);
type IntoIter = indexmap::map::IntoIter<String, JsValue>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<(String, JsValue)> for $name {
fn from_iter<I: IntoIterator<Item = (String, JsValue)>>(properties: I) -> Self {
Self(properties.into_iter().collect())
}
}
};
}
object! {
/// `window._cf_chl_opt`.
Options
}
object! {
/// Globals on the window, or on the namespace the challenge script keeps there.
Window
}
object! {
/// A payload before encoding.
Payload
}

Some files were not shown because too many files have changed in this diff Show More