From 2dde7e5be301774d38d4085e118db8db4d67fe5e Mon Sep 17 00:00:00 2001 From: Christopher Tarry Date: Tue, 27 Oct 2026 23:29:53 -0400 Subject: [PATCH] fix for new build --- Cargo.lock | 374 +--- Cargo.toml | 14 +- examples/build_profile.rs | 54 +- examples/fill_profile.rs | 34 + examples/probe_plan.rs | 33 +- examples/stage2_snapshot.rs | 52 +- profiles/safari-26-ios.json | 164 +- profiles/safari-26-ios/answers.json | 1134 +++++++----- .../safari-26-ios/challenge-page-answers.json | 1280 ++++++++------ src/capture.rs | 5 + src/capture/profile.rs | 418 +++++ src/capture/profile/headers.rs | 246 +++ src/capture/proxy.rs | 15 +- src/capture/recorded.rs | 159 ++ src/capture/rsa.rs | 93 +- src/capture/sessions.rs | 14 +- src/capture/traffic.rs | 49 +- src/challenge/payload.rs | 33 +- src/challenge/program.rs | 89 +- src/challenge/reduced_timing.rs | 137 +- src/challenge/state.rs | 389 ++++- src/deobfuscate.rs | 11 +- src/deobfuscate/analysis/bindings.rs | 81 +- src/deobfuscate/analysis/hoisting.rs | 96 +- src/deobfuscate/arrow_blocks.rs | 194 +++ src/deobfuscate/call_helpers.rs | 212 +++ src/deobfuscate/constant_objects.rs | 163 -- src/deobfuscate/copy_propagation.rs | 22 +- src/deobfuscate/dispatch.rs | 134 +- src/deobfuscate/encoded_strings.rs | 84 +- src/deobfuscate/helper_objects.rs | 77 +- src/deobfuscate/indexed_table.rs | 161 -- src/deobfuscate/literals.rs | 27 +- src/deobfuscate/memoized_strings.rs | 224 +++ src/deobfuscate/merged_functions.rs | 356 ++++ src/deobfuscate/pipeline.rs | 24 +- src/deobfuscate/register_arrays.rs | 519 ++++++ src/deobfuscate/scratch_parameters.rs | 458 ----- src/deobfuscate/state_machines.rs | 215 +++ src/deobfuscate/statements.rs | 43 +- src/deobfuscate/static_members.rs | 30 +- src/deobfuscate/string_array.rs | 736 -------- src/deobfuscate/unused_bindings.rs | 30 +- src/embedding_page/extra_params.rs | 78 +- src/http.rs | 3 +- src/http/client.rs | 63 +- src/http/header_order.rs | 44 +- src/http/requests.rs | 76 +- src/js.rs | 8 +- src/js/ast.rs | 9 - src/js/numeric.rs | 37 - src/js/value.rs | 1 - src/session/challenge_page.rs | 31 +- src/session/initial.rs | 7 + src/session/interaction.rs | 5 +- src/session/probes.rs | 172 +- src/stage2/analysis/analyze.rs | 10 + src/stage2/analysis/recognize.rs | 8 + src/stage2/benchmark.rs | 39 +- src/stage2/call_stack.rs | 1526 ++++++++++++----- src/stage2/interaction/plan.rs | 7 +- src/stage2/probes.rs | 2 + src/stage2/probes/empty.rs | 40 +- src/stage2/probes/error_message_length.rs | 8 +- src/stage2/probes/host_reachability.rs | 92 + src/stage2/probes/media.rs | 214 ++- src/stage2/probes/performance.rs | 65 +- src/stage2/probes/rects.rs | 14 +- src/stage2/probes/stack.rs | 125 +- src/stage2/probes/websocket_echo.rs | 255 +++ src/stage2/probes/worker_fetch.rs | 15 +- src/stage2/reference.rs | 8 - src/stage2/registry.rs | 35 +- src/stage2/replay.rs | 23 +- src/stage2/vocabulary.rs | 68 +- src/vm.rs | 1 + src/vm/dataflow.rs | 16 +- src/vm/disassemble.rs | 36 +- src/vm/dispatch.rs | 733 ++------ src/vm/extract.rs | 342 ++-- src/vm/interpret.rs | 3 +- src/vm/interpret/access.rs | 190 +- src/vm/interpret/builtin.rs | 105 +- src/vm/interpret/call.rs | 2 +- src/vm/interpret/copies.rs | 8 + src/vm/interpret/evaluate.rs | 61 +- src/vm/interpret/evaluate/tests.rs | 3 +- src/vm/interpret/explore.rs | 66 +- src/vm/interpret/plan.rs | 79 +- src/vm/interpret/run.rs | 103 +- src/vm/interpret/semantics.rs | 2 + src/vm/machine.rs | 21 +- src/vm/output.rs | 5 + src/vm/registers.rs | 90 + src/vm/session.rs | 302 +++- src/vm/value.rs | 12 +- tests/deobfuscate.rs | 416 ----- tests/main.rs | 5 - tests/vm.rs | 348 ---- 99 files changed, 9047 insertions(+), 5673 deletions(-) create mode 100644 examples/fill_profile.rs create mode 100644 src/capture/profile.rs create mode 100644 src/capture/profile/headers.rs create mode 100644 src/capture/recorded.rs create mode 100644 src/deobfuscate/arrow_blocks.rs create mode 100644 src/deobfuscate/call_helpers.rs delete mode 100644 src/deobfuscate/constant_objects.rs delete mode 100644 src/deobfuscate/indexed_table.rs create mode 100644 src/deobfuscate/memoized_strings.rs create mode 100644 src/deobfuscate/merged_functions.rs create mode 100644 src/deobfuscate/register_arrays.rs delete mode 100644 src/deobfuscate/scratch_parameters.rs create mode 100644 src/deobfuscate/state_machines.rs delete mode 100644 src/deobfuscate/string_array.rs create mode 100644 src/stage2/probes/host_reachability.rs create mode 100644 src/stage2/probes/websocket_echo.rs create mode 100644 src/vm/registers.rs delete mode 100644 tests/deobfuscate.rs delete mode 100644 tests/main.rs delete mode 100644 tests/vm.rs diff --git a/Cargo.lock b/Cargo.lock index 1b89a96..ecda47c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -204,8 +204,6 @@ dependencies = [ "cexpr", "clang-sys", "itertools", - "log", - "prettyplease", "proc-macro2", "quote", "regex", @@ -356,16 +354,6 @@ dependencies = [ "serde", ] -[[package]] -name = "calendrical_calculations" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" -dependencies = [ - "core_maths", - "displaydoc", -] - [[package]] name = "camino" version = "1.2.2" @@ -473,7 +461,6 @@ dependencies = [ "tokio", "tokio-rustls", "url", - "v8", "wreq", "wreq-util", "zstd 0.13.3", @@ -571,15 +558,6 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" -[[package]] -name = "core_maths" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" -dependencies = [ - "libm", -] - [[package]] name = "cpufeatures" version = "0.2.17" @@ -777,38 +755,6 @@ dependencies = [ "crypto-common", ] -[[package]] -name = "diplomat" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8b37a6cea72eb6df5143d3e091d4c34cb0cf4046dd1ddcc082988886fe1f809" -dependencies = [ - "diplomat_core", - "proc-macro2", - "quote", - "syn 3.0.5", -] - -[[package]] -name = "diplomat-runtime" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae517853d9f82b2d144393b1c32c34c46c2e361de2b6c44a8fdfce23beb211cd" - -[[package]] -name = "diplomat_core" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b18e806f9ecb92df828d080efe47984ae1193958295d4a84fb8b32c9a1aa1b" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "smallvec", - "strck", - "syn 3.0.5", -] - [[package]] name = "displaydoc" version = "0.2.5" @@ -888,7 +834,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" dependencies = [ "crc32fast", - "miniz_oxide 0.9.1", + "miniz_oxide", "zlib-rs", ] @@ -1012,6 +958,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", + "futures-sink", "futures-task", "pin-project-lite", "slab", @@ -1088,15 +1035,6 @@ dependencies = [ "regex-syntax", ] -[[package]] -name = "gzip-header" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86848f4fd157d91041a62c78046fb7b248bcc2dce78376d436a1756e9a038577" -dependencies = [ - "crc32fast", -] - [[package]] name = "h2" version = "0.4.20" @@ -1160,15 +1098,6 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" -[[package]] -name = "home" -version = "0.5.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "hstr" version = "3.0.3" @@ -1314,28 +1243,6 @@ dependencies = [ "cc", ] -[[package]] -name = "icu_calendar" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c" -dependencies = [ - "calendrical_calculations", - "displaydoc", - "icu_calendar_data", - "icu_locale_core", - "icu_locale_fallback", - "icu_provider", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_calendar_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc00caaa3fb3201ff7a18aa458e8c3ab042b9da154cfdf948bdde3936c31c36e" - [[package]] name = "icu_collections" version = "2.1.1" @@ -1357,32 +1264,11 @@ checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" dependencies = [ "displaydoc", "litemap", - "serde", "tinystr", "writeable", "zerovec", ] -[[package]] -name = "icu_locale_fallback" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9" -dependencies = [ - "icu_locale_core", - "icu_locale_fallback_data", - "icu_provider", - "potential_utf", - "tinystr", - "zerovec", -] - -[[package]] -name = "icu_locale_fallback_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8" - [[package]] name = "icu_normalizer" version = "2.1.1" @@ -1431,8 +1317,6 @@ checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" dependencies = [ "displaydoc", "icu_locale_core", - "serde", - "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -1518,12 +1402,6 @@ version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2" -[[package]] -name = "ixdtf" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d3667095d64c3ecffc96463a21157b04bf3e252f6e8d5750b20c02e33c194e3" - [[package]] name = "jobserver" version = "0.1.35" @@ -1575,18 +1453,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "libm" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" - -[[package]] -name = "linux-raw-sys" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" - [[package]] name = "litemap" version = "0.8.1" @@ -1673,15 +1539,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", -] - [[package]] name = "miniz_oxide" version = "0.9.1" @@ -1859,12 +1716,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - [[package]] name = "path-clean" version = "0.1.0" @@ -1947,7 +1798,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ "phf_shared 0.11.3", - "rand", + "rand 0.8.5", ] [[package]] @@ -2022,8 +1873,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" dependencies = [ - "serde_core", - "writeable", "zerovec", ] @@ -2033,6 +1882,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "precomputed-hash" version = "0.1.1" @@ -2063,16 +1921,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.113", -] - [[package]] name = "proc-macro2" version = "1.0.107" @@ -2121,7 +1969,27 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -2130,6 +1998,15 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rcgen" version = "0.14.10" @@ -2192,16 +2069,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "resb" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22d392791f3c6802a1905a509e9d1a6039cbbcb5e9e00e5a6d3661f7c874f390" -dependencies = [ - "potential_utf", - "serde_core", -] - [[package]] name = "ring" version = "0.17.14" @@ -2240,19 +2107,6 @@ dependencies = [ "nom", ] -[[package]] -name = "rustix" -version = "0.38.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.59.0", -] - [[package]] name = "rustls" version = "0.23.46" @@ -2588,15 +2442,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" -[[package]] -name = "strck" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42316e70da376f3d113a68d138a60d8a9883c604fe97942721ec2068dab13a9f" -dependencies = [ - "unicode-ident", -] - [[package]] name = "string_cache" version = "0.9.0" @@ -3617,40 +3462,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" -[[package]] -name = "temporal_capi" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f48eb9ca4ca22caaa48d1e7a534ad3fd598a23d1a71945e8ad5ac0be501fa5f2" -dependencies = [ - "diplomat", - "diplomat-runtime", - "icu_calendar", - "icu_locale_core", - "num-traits", - "temporal_rs", - "timezone_provider", - "writeable", - "zoneinfo64", -] - -[[package]] -name = "temporal_rs" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a978fef907a27736827d336c0bfaab14fb8a7509dd6dc2b43c44e51d59aca5b" -dependencies = [ - "calendrical_calculations", - "core_maths", - "icu_calendar", - "icu_locale_core", - "ixdtf", - "num-traits", - "timezone_provider", - "tinystr", - "writeable", -] - [[package]] name = "tendril" version = "0.5.1" @@ -3740,18 +3551,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "timezone_provider" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ec4f4eebb4817fde02a411aedc7ac5f66c89c68c49e5d4b17a8139f077af52" -dependencies = [ - "tinystr", - "zerotrie", - "zerovec", - "zoneinfo64", -] - [[package]] name = "tinystr" version = "0.8.4" @@ -3759,7 +3558,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" dependencies = [ "displaydoc", - "serde_core", "zerovec", ] @@ -3822,6 +3620,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.19" @@ -3930,6 +3740,22 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", +] + [[package]] name = "typed-builder" version = "0.23.2" @@ -4020,23 +3846,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "v8" -version = "152.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a10fe1a92da5c32c7c7f838ce36c0ccfcfd5edf0865b58bdde820aa64cea9888" -dependencies = [ - "bindgen", - "bitflags", - "fslock", - "gzip-header", - "home", - "miniz_oxide 0.8.9", - "paste", - "temporal_capi", - "which", -] - [[package]] name = "vergen" version = "9.0.6" @@ -4164,18 +3973,6 @@ dependencies = [ "rustls-pki-types", ] -[[package]] -name = "which" -version = "6.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" -dependencies = [ - "either", - "home", - "rustix", - "winsafe", -] - [[package]] name = "winapi" version = "0.3.9" @@ -4266,15 +4063,6 @@ dependencies = [ "windows-targets", ] -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -4348,12 +4136,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "winsafe" -version = "0.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" - [[package]] name = "wit-bindgen" version = "0.46.0" @@ -4383,6 +4165,7 @@ dependencies = [ "tokio", "tokio-btls", "tokio-socks", + "tokio-tungstenite", "tower", "tower-http", "url", @@ -4558,7 +4341,6 @@ dependencies = [ "displaydoc", "yoke", "zerofrom", - "zerovec", ] [[package]] @@ -4567,7 +4349,6 @@ version = "0.11.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" dependencies = [ - "serde", "yoke", "zerofrom", "zerovec-derive", @@ -4596,19 +4377,6 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcb2c125bd7365735bebeb420ccb880265ed2d2bddcbcd49f597fdfe6bd5e577" -[[package]] -name = "zoneinfo64" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed6eb2607e906160c457fd573e9297e65029669906b9ac8fb1b5cd5e055f0705" -dependencies = [ - "calendrical_calculations", - "icu_locale_core", - "potential_utf", - "resb", - "serde", -] - [[package]] name = "zstd" version = "0.13.3" diff --git a/Cargo.toml b/Cargo.toml index 1803d15..e09da2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,14 +4,8 @@ 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] @@ -63,7 +57,7 @@ tokio = { version = "1.53.1", features = ["macros", "net", "rt-multi-thread", "s 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"] } +wreq = { version = "=0.16.1", features = ["cookies", "gzip", "brotli", "deflate", "zstd", "socks", "ws"] } 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. @@ -80,10 +74,6 @@ rustls = { version = "0.23", default-features = false, features = ["std", "tls12 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/. @@ -92,7 +82,7 @@ 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 +# Full debug info for swc 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" diff --git a/examples/build_profile.rs b/examples/build_profile.rs index de2e0ed..ccdf544 100644 --- a/examples/build_profile.rs +++ b/examples/build_profile.rs @@ -1,53 +1,27 @@ //! Store a real browser's probe answers for a device profile. //! Usage: build_profile > 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`. +//! The capture is a session's `capture.json` from the capture proxy, or 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 std::env; +use std::path::Path; use anyhow::{Context, Result}; -use base64::Engine; -use base64::engine::general_purpose::STANDARD; -use cfsolve::js::Payload; -use cfsolve::script::Source; +use cfsolve::capture::CapturedSession; 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()))?; + let capture = CapturedSession::read(Path::new(&path))?; + let answers = Answers::capture( + &capture.source()?, + &capture.program()?, + capture.probe_payload()?, + )?; println!("{}", serde_json::to_string_pretty(&answers)?); Ok(()) } diff --git a/examples/fill_profile.rs b/examples/fill_profile.rs new file mode 100644 index 0000000..1f97d30 --- /dev/null +++ b/examples/fill_profile.rs @@ -0,0 +1,34 @@ +//! Fill a device profile's measured sections from capture-proxy runs. +//! Usage: fill_profile ... > profile.json +//! +//! Each capture directory is one the proxy wrote with `--out`. The new profile keeps the base's +//! other values, and the notes on stderr say where each section came from and what was left out. +//! `build_profile` writes the answers the profile's `answers` names. + +use std::path::Path; +use std::{env, fs}; + +use anyhow::{Context, Result, ensure}; +use cfsolve::capture::{self, Recording}; +use serde_json::Value; + +fn main() -> Result<()> { + let mut arguments = env::args().skip(1); + let base = arguments + .next() + .context("supply a base profile and capture directories")?; + let recordings: Vec = arguments + .map(|dir| Recording::read(Path::new(&dir))) + .collect::>()?; + ensure!( + !recordings.is_empty(), + "supply at least one capture directory" + ); + let text = fs::read(&base).with_context(|| format!("reading {base}"))?; + let mut profile: Value = serde_json::from_slice(&text)?; + for note in capture::fill_profile(&mut profile, &recordings)? { + eprintln!("{note}"); + } + println!("{}", serde_json::to_string_pretty(&profile)?); + Ok(()) +} diff --git a/examples/probe_plan.rs b/examples/probe_plan.rs index ecbd541..6bac17f 100644 --- a/examples/probe_plan.rs +++ b/examples/probe_plan.rs @@ -7,41 +7,18 @@ //! 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 std::env; +use std::path::Path; use anyhow::{Context, Result}; -use base64::Engine; -use base64::engine::general_purpose::STANDARD; -use cfsolve::challenge; -use cfsolve::script::Source; +use cfsolve::capture::CapturedSession; 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 capture = CapturedSession::read(Path::new(&path))?; + let analysis = analysis::analyze(&capture.source()?, &capture.program()?)?; let plan = analysis.plan(); println!("record\tkind\ttreatment\treference"); for (position, probe) in plan.probes().iter().enumerate() { diff --git a/examples/stage2_snapshot.rs b/examples/stage2_snapshot.rs index 1898170..366f077 100644 --- a/examples/stage2_snapshot.rs +++ b/examples/stage2_snapshot.rs @@ -18,6 +18,7 @@ use cfsolve::challenge::program::PreparedSession; use cfsolve::js::Options; use cfsolve::script::Source; use cfsolve::stage2::analysis::{self, ProgramOutcome}; +use cfsolve::stage2::registry::{Kind, Operation}; use cfsolve::stage2::{call_stack, interaction}; use serde::Serialize; use serde_json::{Map, Value, json}; @@ -41,16 +42,50 @@ fn main() -> Result<()> { // 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 loops = call_stack::dispatch_summary(&original, &cases); + snapshot.insert("dispatch_loops".into(), record(loops)); 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())?) - }); + .and_then(|program| analysis::analyze(&prepared, &program)); + // The stack probe's frames, which the CLI rebuilds for Chromium. + if let Ok(analysis) = &analysis + && let Some((_, Operation::Stack { fields })) = analysis.plan().operation(Kind::Stack) + { + let frames = fields + .calls + .context("the stack probe's calls have an unrecognized shape") + .and_then(|calls| call_stack::recover_probe(&original, &cases, calls)) + .map(|geometry| { + json!({ + "frames": geometry.frames, + "jsc_frames": geometry.jsc_frames, + "reflected": geometry.reflected, + }) + }); + snapshot.insert("probe_frames".into(), record(frames)); + } + let analysis = analysis.and_then(|analysis| 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 session = PreparedSession::try_new(&prepared, &base); + // The first payload's fields and the options the script marks with `Date.now()`, which + // its timestamp differences need. + let first_payload = match &session { + Ok(session) => session.state().map(|state| { + let marks: Vec = state.marks.into_iter().map(|mark| mark.option).collect(); + json!({ + "marks": marks, + "fields": session.program().encoder_json().payload_fields, + "timing": state.timing.map(|timing| timing.option), + "post_log": state.post_log.map(|log| log.option), + "forwarded": state.forwarded, + }) + }), + Err(error) => Err(anyhow::anyhow!("{error:#}")), + }; + snapshot.insert("first_payload".into(), record(first_payload)); + let installed = session.map(|session| { let installed = session.into_program().installed; json!({"options": installed.options, "window": installed.window}) }); @@ -77,10 +112,9 @@ fn main() -> Result<()> { ); snapshot.insert("callback_frames".into(), record(frames)); if let Ok(options) = read("options.json") { - let options: Result = - serde_json::from_str(&options).map_err(anyhow::Error::from); - let queries = - options.and_then(|options| interaction::checkbox::queries(&prepared, &options)); + let queries = serde_json::from_str::(&options) + .map_err(anyhow::Error::from) + .and_then(|options| interaction::checkbox::queries(&prepared, &options)); snapshot.insert("checkbox_queries".into(), record(queries)); } } diff --git a/profiles/safari-26-ios.json b/profiles/safari-26-ios.json index cb020d8..542bb1f 100644 --- a/profiles/safari-26-ios.json +++ b/profiles/safari-26-ios.json @@ -165,6 +165,17 @@ "accept-language: en-US,en;q=0.9", "priority: u=0, i", "accept-encoding: gzip, deflate, br, zstd" + ], + "websocket": [ + "upgrade: websocket", + "connection: Upgrade", + "origin", + "pragma: no-cache", + "cache-control: no-cache", + "sec-websocket-version: 13", + "user-agent", + "accept-language: en-US,en;q=0.9", + "accept-encoding: gzip, deflate, br, zstd" ] } } @@ -191,8 +202,8 @@ "intervals": { "initialise": 7, "handoff": 8, - "collect": 20, - "send": 123 + "collect": 19, + "send": 121 }, "orchestrator": { "intervals": { @@ -359,29 +370,29 @@ }, "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:3460880736 1 udp 2113939711 f1bed2f8-f860-457f-b026-2d23d9140c03.local 59340 typ host generation 0 ufrag mtbG network-cost 999", + "observed_ms": 1792876992039 }, { - "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:3747697418 1 udp 2113937151 f9501b39-1d57-4eb6-8029-16167a5a330b.local 51498 typ host generation 0 ufrag mtbG network-cost 999", + "observed_ms": 1792876992039 }, { - "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:1648342598 1 udp 1677729535 192.0.2.1 64597 typ srflx raddr 0.0.0.0 rport 0 generation 0 ufrag mtbG network-cost 999", + "observed_ms": 1792876992052 }, { - "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 + "candidate": "candidate:2007285888 1 udp 1677732095 2001:db8::1 59340 typ srflx raddr :: rport 0 generation 0 ufrag mtbG network-cost 999", + "observed_ms": 1792876992056 } - ] + ], + "data_channel": true, + "sdp": "v=0\r\no=- 2400467206764510475 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:mtbG\r\na=ice-pwd:0Dc00kOlIMYBy8fnUlejV6Qu\r\na=ice-options:trickle\r\na=fingerprint:sha-256 DD:42:3A:63:B0:F3:DD:05:09:2E:04:DB:DC:08:0F:95:85:98:BB:9E:04:10:8B:72:64:14:09:0E:31:EA:13:69\r\na=setup:actpass\r\na=mid:0\r\na=sctp-port:5000\r\na=max-message-size:262144\r\n" }, - "started_ms": 1792606282000, - "finished_ms": 1792606282002, + "started_ms": 1792876992546, + "finished_ms": 1792876992554, "ice_state": "complete" } }, @@ -399,67 +410,93 @@ }, "benchmark_worker": { "compile_ms": [ - 11.5, - 2.04, - 1.16, - 2.0 + 11.499999999999993, + 2.039999999999992, + 1.1599999999999966, + 2.0, + 1.6599999999999682, + 2.5 ], "kernel_ms_per_million": [ [ 1.003, - 1.035, - 1.291, - 1.214, 0.93, - 0.972, - 0.962, - 0.971, 0.944, + 1.035, + 0.972, 0.946, + 1.291, + 0.962, 0.941, - 0.971 + 1.214, + 0.971, + 0.971, + 1.003, + 0.935, + 0.964, + 1.002, + 0.953, + 0.968 ], [ 1.055, - 1.027, - 1.061, - 1.007, 0.932, - 0.933, - 0.942, - 1.007, 0.946, + 1.027, + 0.933, 0.944, + 1.061, + 0.942, 0.947, - 1.007 + 1.007, + 1.007, + 1.007, + 1.399, + 0.926, + 0.941, + 1.379, + 0.936, + 0.946 ], [ 1.222, - 0.801, - 0.665, - 0.645, 0.617, - 0.621, - 0.628, - 0.645, 0.635, + 0.801, + 0.621, 0.626, + 0.665, + 0.628, 0.631, - 0.645 + 0.645, + 0.645, + 0.645, + 0.746, + 0.62, + 0.63, + 0.656, + 0.629, + 0.641 ], [ 5.798, - 5.75, - 5.978, - 5.831, 5.567, + 5.609, + 5.75, 5.574, + 5.692, + 5.978, + 5.707, 5.707, 5.831, - 5.609, - 5.692, - 5.707, - 5.831 + 5.831, + 5.831, + 5.931, + 5.554, + 5.673, + 5.869, + 5.693, + 5.791 ] ] } @@ -472,22 +509,45 @@ "online": true }, "durations": { + "audio": 24, + "behavior": 4, "clock_resolution": 6, + "computed_style_hash": 12, + "console": 26, "date_parsing_offsets": 1, + "document_structure": 0, + "document_summary": 1, "dom_mutation": 2, + "emoji_color": 3, "empty": 0, + "environment": 5, + "environment_audit": 17, + "error_message_length": 1, + "font_enumeration": 6, + "graphics": 48, + "high_entropy_user_agent": 1, "image": 14, + "intl": 3, + "isolation": 16, + "keyboard_layout": 0, + "math": 6, "media": 5, + "native_inspection": 65, "network_information": 0, "parent_info": 0, - "performance_entries": 0, + "performance_entries": 1, "private_token": 1, + "rects": 5, + "stack": 1, + "storage": 5, + "stylesheets": 3, + "summarizer_availability": 0, + "svg_geometry": 18, "worker_fetch": 1, - "worker_navigator": 7, - "stack": 1 + "worker_navigator": 7 }, - "startup_ms": 105, - "pending_ms": 42 + "startup_ms": 119, + "pending_ms": 227 }, "answers": "safari-26-ios/answers.json", "challenge_page_answers": "safari-26-ios/challenge-page-answers.json" diff --git a/profiles/safari-26-ios/answers.json b/profiles/safari-26-ios/answers.json index 4525426..b83304a 100644 --- a/profiles/safari-26-ios/answers.json +++ b/profiles/safari-26-ios/answers.json @@ -2,7 +2,7 @@ "reference": "a562732e38934444", "probes": { "2": { - "duration": 17, + "duration": 22, "fields": { "Mrvi5": { "0": [ @@ -23,7 +23,7 @@ "s.availLeft", "s.availTop", "so.angle", - "o.gfOgY8" + "o.ZMiod6" ], "1": [ "d.childElementCount", @@ -78,7 +78,7 @@ "s.pixelDepth" ], "30": [ - "o.LeviO5" + "o.GsfY1" ], "32": [ "d.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC" @@ -194,10 +194,10 @@ "s.orientation", "o.event", "o._cf_chl_opt", - "o.HKul9", - "o.nTlR0", - "o.MpSwI7", - "o.xrbo0", + "o.sSkll6", + "o.nYPYj0", + "o.KryNx3", + "o.ygHP1", "o.angular" ], "F": [ @@ -471,7 +471,7 @@ "n.pdfViewerEnabled", "d.pictureInPictureEnabled", "d.isConnected", - "o.AgLL2", + "o.kMLRO6", "o.n.cookieEnabled" ], "https://challenges.cloudflare.com": [ @@ -1012,7 +1012,7 @@ "RangeError", "ReferenceError", "SyntaxError", - "TypeError", + "KCuZ3", "URIError", "AggregateError", "Proxy", @@ -1403,26 +1403,26 @@ "so.addEventListener", "so.removeEventListener", "so.dispatchEvent", - "o.THirw9", - "o.IXEYu6", - "o.nOLY0", - "o.runProgram", - "o.vUAjb0", - "o.zCGb4", - "o.AGRfA7", - "o.qpPe1", - "o.atAFr0", - "o.SABtz7", - "o.FIac3", - "o.RpzJz6", - "o.QSqpx9", - "o.ueZh9", - "o.FBBK4", - "o.ZliED2", - "o.NmGWd6", - "o.TZpt2", - "o.AwUcP3", - "o.MkvrI5", + "o.YDta0", + "o.yCpNJ2", + "o.YMwdw2", + "o.armBH3", + "o.ENLzH2", + "o.Ewgxh3", + "o.uOdMb2", + "o.qwQRi7", + "o.sSEGO7", + "o.eJeI1", + "o.qgcO0", + "o.xNxMK4", + "o.pRxjE3", + "o.wsqXE7", + "o.JwCUQ7", + "o.fXaz8", + "o.iqzpL9", + "o.HNiY8", + "o.ZahLT8", + "o.Tlvt6", "o.Array" ], "Infinity": [ @@ -1435,7 +1435,7 @@ "openDatabase", "d.all" ], - "p5": [ + "C": [ "Array" ], "Mozilla": [ @@ -1481,14 +1481,14 @@ "challenges.cloudflare.com": [ "d.domain" ], - "https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal?lang=auto": [ + "https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/g/turnstile/f/av0/rch/bp3rp/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal?lang=auto": [ "d.referrer", "d.baseURI" ], "s": [ "d.cookie" ], - "10/24/2026 17:24:10": [ + "10/27/2026 19:03:23": [ "d.lastModified" ], "complete": [ @@ -1502,7 +1502,7 @@ ], "": [ "d.adoptedStyleSheets", - "o.vvfHL3" + "o.hbRVt7" ], "#document": [ "d.nodeName" @@ -1510,17 +1510,17 @@ "portrait-primary": [ "so.type" ], - "4wNwTokYX9Fu+cj3d8F8HsywiHABX4h/R16FveVtEWM=$km+MVByr0jgLtg9vj2y+NQ==,Bmi207WUML6KlWmVggqwUQOEc0iltLiaIxOhpStpg6VMZiNgJ8/zNDGEad0jxN/F$qRLkr0cCZO6vR8hsVLbwgw==,KJA6EpnlBQBxeZsQdNeI4YtP7rqDVE8fajRYk6r0p9A/0fUJbsObL9I7U3BxOxZP$Q3Zg8DpEIIzuCEOau8Gqpw==": [ - "o.qrht8" + "4f9QFeRps2/ZDfRAjYgOssNGvS6DNKP2iTP6An7qkYg=$z+gkCZYGur1V/qmFmVOy4w==,Ccx5Fwb7FK2t7F/JQ616ajqUwCTwRL/xvZpoN9nac5w=$yGmD6uSO6Ch8wHZG/krY5A==,pwmp3o3VHSfMh1qvc9HYrUMBOivyyW69vYEYGHPdTp6VFVi0H+dLg/Xngxo5BL8L$sD/s2YFBo2Vo57v89wucYQ==": [ + "o.Vnlyd3" ], - "-3": [ - "o.vMhC1" + "-4": [ + "o.BWRSl4" ], - "qCZq4": [ - "o.lffN9" + "suNuW1": [ + "o.TRcGA3" ], "function querySelector() {\n [native code]\n},function querySelectorAll() {\n [native code]\n},function querySelector() {\n [native code]\n},function querySelectorAll() {\n [native code]\n}": [ - "o.dSvRK1" + "o.DIkC7" ] }, "gVIOJ1": { @@ -1528,8 +1528,8 @@ "CvjRv6": true, "VJeMl3": null, "CUFA2": 0, - "qYdP1": 284361, - "qivJU1": 118422 + "qYdP1": 596645, + "qivJU1": 193479 } } }, @@ -1540,7 +1540,7 @@ } }, "6": { - "duration": 5, + "duration": 1, "fields": { "RUGg3": false, "YdPI7": false, @@ -1550,29 +1550,29 @@ "faCRA3": false, "ZTGE3": false, "RwUzK9": "navigate", - "IEoo6": "https://captchatest.book.bi/", - "jSAze1": [], + "IEoo6": "", + "ZzbI2": [], "VQWKy9": false, - "ybXT7": "[{\"name\":\"geolocation\",\"state\":\"denied\"},{\"name\":\"notifications\",\"state\":\"denied\"},{\"name\":\"camera\",\"state\":\"denied\"},{\"name\":\"microphone\",\"state\":\"denied\"}]" + "kEkZQ3": "[{\"name\":\"geolocation\",\"state\":\"denied\"},{\"name\":\"notifications\",\"state\":\"denied\"},{\"name\":\"camera\",\"state\":\"denied\"},{\"name\":\"microphone\",\"state\":\"denied\"}]" } }, "7": { - "duration": 1, + "duration": 0, "fields": { "uYtjJ5": "SOSG9" } }, "8": { - "duration": 3, + "duration": 6, "fields": { "pYHZ2": "JNcIn7" } }, "10": { - "duration": 4, + "duration": 3, "fields": { - "eHTM1": "uvFa8", - "jskZ5": [ + "bQBt4": "zOENR5", + "vbrE9": [ true, true, true, @@ -1658,7 +1658,7 @@ true, true, true, - "

mgkO0

kCzq0

", + "

geEP5

wiZZO1

", "
", true, true, @@ -1676,7 +1676,7 @@ true, true, true, - "

mgkO0

kCzq0

", + "

geEP5

wiZZO1

", "
", -1, -1, @@ -1691,8 +1691,8 @@ true, false, "[object Undefined]", - "BLdW9611", - "BLdW9/\\u0067\\u0075\\u006c\\u0065/" + "dLoV1611", + "dLoV1/\\u0067\\u0075\\u006c\\u0065/" ] } }, @@ -1704,107 +1704,144 @@ } }, "13": { - "duration": 26, + "duration": 24, "fields": { - "wZzhY9": [ - "fAhw2", - "MBTMg5", - "xgZp0", - "abAh2", - "SGPo1", - "XMexs0", - "farG1", + "CnBd1": 0, + "yCNNi5": [ + "bbewo8", + "bbewo8" + ], + "COUZf0": [ + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8" + ], + "arqA7": [ + "IHdE7", + "IHdE7", + "IHdE7", + "IHdE7", + "IHdE7", + "IHdE7" + ], + "TsnFY8": "QEZg7", + "agmL8": "tedVy6", + "ClXn8": "fuNGU7", + "QAlM4": [ + "BPcA0", + "BPcA0", + "BPcA0", + "BPcA0" + ], + "oPxfw0": [ + "QrrLS4", + "YQrqM9", + "djRQ8", + "ZkNZ1", + "DHaWI3", + "Eiqe1", + "HLKa2", 61, - "kHBYa0", - "kHBYa0", + "lBhq6", + "lBhq6", "tjoAf2", "tjoAf2", - "MBTMg5", + "YQrqM9", "LrHWa3", - "xgZp0", + "djRQ8", "LrHWa3", - "MBTMg5", + "YQrqM9", "LrHWa3", - "xgZp0", + "djRQ8", "LrHWa3", - "MBTMg5", + "YQrqM9", "oUia2", - "xgZp0", + "djRQ8", "oUia2", - "MBTMg5", + "YQrqM9", "oUia2", - "xgZp0", + "djRQ8", "oUia2", - "MBTMg5", + "YQrqM9", "vXLPk0", - "xgZp0", + "djRQ8", "vXLPk0", - "MBTMg5", + "YQrqM9", "vXLPk0", - "xgZp0", + "djRQ8", "vXLPk0", - "MBTMg5", + "YQrqM9", "fOxd0", - "xgZp0", + "djRQ8", "fOxd0", - "MBTMg5", + "YQrqM9", "fOxd0", - "xgZp0", + "djRQ8", "fOxd0", - "MBTMg5", + "YQrqM9", "bKAX5", - "xgZp0", + "djRQ8", "bKAX5", - "MBTMg5", + "YQrqM9", "bKAX5", - "xgZp0", + "djRQ8", "bKAX5", - "MBTMg5", + "YQrqM9", "qAyyq5", - "xgZp0", + "djRQ8", "qAyyq5", - "MBTMg5", + "YQrqM9", "qAyyq5", - "xgZp0", + "djRQ8", "qAyyq5", - "MBTMg5", + "YQrqM9", "yEWMp2", - "xgZp0", + "djRQ8", "yEWMp2", - "MBTMg5", + "YQrqM9", "yEWMp2", - "xgZp0", + "djRQ8", "yEWMp2", - "MBTMg5", + "YQrqM9", "BLqf9", - "xgZp0", + "djRQ8", "BLqf9", - "MBTMg5", + "YQrqM9", "BLqf9", - "xgZp0", + "djRQ8", "BLqf9", - "MBTMg5", - "rukf4", - "xgZp0", - "rukf4", - "MBTMg5", - "rukf4", - "xgZp0", - "rukf4", - "MBTMg5", + "YQrqM9", + "AONvF9", + "djRQ8", + "AONvF9", + "YQrqM9", + "AONvF9", + "djRQ8", + "AONvF9", + "YQrqM9", "cXWh3", - "xgZp0", + "djRQ8", "cXWh3", - "abAh2", + "ZkNZ1", "cXWh3" ], - "ZOif6": "YPqu7" + "mBxH7": null, + "YmXV0": "hCig9" } }, "14": { - "duration": 6, + "duration": 11, "fields": { - "HgNL2": [ + "QsQH7": [ "1.457511857388766", "0.7853981633974483", "709.889355822726", @@ -1822,7 +1859,7 @@ "1.2626272556789115", "0.5493061443340549", "0.5493061443340549", - "5.587684646268005e-309", + "5e-311", "1.0038848218538872", "4.641588833612779", "4.641588833612778", @@ -1993,7 +2030,7 @@ } }, "15": { - "duration": 0, + "duration": 1, "fields": { "vyifZ0": "ejWF3", "weHRb8": [ @@ -2005,11 +2042,26 @@ } }, "18": { - "duration": 42, + "duration": 80, "fields": { - "nXks6": "JzCDC7bc30e1cd6821fc831ca77da21bcecacaEETJ6", - "nGLC2": "JzCDC7bc30e1cd6821fc831ca77da21bcecacaEETJ6", - "qKwk8": [ + "MBXf3": "DEAR3bc66faf385f3c8fb7a7e0cf423386d9fcicCP7", + "ySrtS5": "DEAR3bc66faf385f3c8fb7a7e0cf423386d9fcicCP7", + "FXpXv1": [ + [ + 62, + 32, + 0, + 255 + ], + [ + 0, + 0, + 0, + 255 + ], + null + ], + "CNRnh6": [ [ "WebKit", "WebKit WebGL" @@ -2019,7 +2071,7 @@ "Apple GPU" ] ], - "wzhU9": [ + "oHFLJ5": [ [ "apple", "apple", @@ -2190,14 +2242,14 @@ [] ] ], - "zpuw5": "827939e838fdb83387cf852d4a505360", - "Dqeg5": "4cc68c48404248a9a84563c711d22b6a", - "OWFf4": [ + "wsksA3": "827939e838fdb83387cf852d4a505360", + "fVCRI9": "4cc68c48404248a9a84563c711d22b6a", + "AvIxy5": [ 2, 0, 0 ], - "zkuPb4": [ + "nardr7": [ 33, "ANGLE_instanced_arrays,EXT_blend_minmax,EXT_clip_control,EXT_color_buffer_half_float,EXT_depth_clamp,EXT_frag_depth,EXT_polygon_offset_clamp,EXT_shader_texture_lod,EXT_texture_filter_anisotropic,EXT_texture_mirror_clamp_to_edge,EXT_sRGB,KHR_parallel_shader_compile,OES_element_index_uint,OES_fbo_render_mipmap,OES_standard_derivatives,OES_texture_float,OES_texture_half_float,OES_texture_half_float_linear,OES_vertex_array_object,WEBGL_blend_func_extended,WEBGL_color_buffer_float,WEBGL_compressed_texture_astc,WEBGL_compressed_texture_etc,WEBGL_compressed_texture_etc1,WEBGL_compressed_texture_pvrtc,WEBKIT_WEBGL_compressed_texture_pvrtc,WEBGL_debug_renderer_info,WEBGL_debug_shaders,WEBGL_depth_texture,WEBGL_draw_buffers,WEBGL_lose_context,WEBGL_multi_draw,WEBGL_polygon_mode", "EXT_disjoint_timer_query,EXT_float_blend,EXT_texture_compression_bptc,EXT_texture_compression_rgtc,OES_texture_float_linear,WEBGL_compressed_texture_s3tc,WEBGL_compressed_texture_s3tc_srgb,WEBGL_provoking_vertex", @@ -2264,7 +2316,7 @@ 1024, [] ], - "hHFd9": [ + "oXlug7": [ 2048, 2147483647, 2147483647, @@ -2313,7 +2365,7 @@ "srgb", null ], - "IXea2": [ + "GqCeX8": [ 16, 4352, null, @@ -2356,11 +2408,11 @@ "srgb", null ], - "kdniG6": [ - "254,254,254,254,183,183,183,253,226,226,226,252,48,48,48,255,", + "FJbU2": [ + "255,255,255,255,184,184,184,254,229,229,229,255,46,46,46,254,", 1, 0.0040984375000000005, - "51770521534eb017ad1986bc2ab5973c", + "dc0cd76a96827a8df274584a19558db6", -19762, [ [ @@ -2518,10 +2570,10 @@ "srgb", null, 4, - 253, - 25, - 125, - 253 + 255, + 28, + 128, + 255 ] ], [ @@ -2548,10 +2600,10 @@ "srgb", null, 4, - 253, - 25, - 125, - 253 + 255, + 28, + 128, + 255 ] ], [ @@ -2578,15 +2630,15 @@ [ 49, 44, - "4c1d5ad1788e9226743507db0c2e79df" + "8ccc78796e37a532c95d29a86b83c09d" ], [ 49, 44, - "4c1d5ad1788e9226743507db0c2e79df" + "8ccc78796e37a532c95d29a86b83c09d" ] ], - "ChJe3": [ + "NBcX0": [ [ [ 4, @@ -2745,7 +2797,7 @@ 36194 ] ], - "uvmjh4": [ + "Ooyv2": [ [ 0, 0, @@ -2781,30 +2833,31 @@ ], null ], - "bzTe1": [ + "pUHnB0": [ "e4ceffd6e4cfff84e4d0ff32e4d1ffdf", 1 ] }, "late": [ - "nXks6", - "nGLC2", - "qKwk8", - "wzhU9", - "zpuw5", - "Dqeg5", - "OWFf4", - "zkuPb4", - "hHFd9", - "IXea2", - "kdniG6", - "ChJe3", - "uvmjh4", - "bzTe1" + "MBXf3", + "ySrtS5", + "FXpXv1", + "CNRnh6", + "oHFLJ5", + "wsksA3", + "fVCRI9", + "AvIxy5", + "nardr7", + "oXlug7", + "GqCeX8", + "FJbU2", + "NBcX0", + "Ooyv2", + "pUHnB0" ] }, "19": { - "duration": 18, + "duration": 23, "fields": { "dNIwz0": "3a6635a800297ace2b2ffc992f5c2878c273d285b55e928decab1a802dbb8879", "IrCAn7": "21432bab72d581205049471541e706481667716e4feacd434c60315f008bb80b", @@ -2819,29 +2872,28 @@ } }, "21": { - "duration": 25, + "duration": 7, "fields": { - "bqCm2": "ae4ed95a2045eb64098f7efc56a8bedcb8c2c5918775cfe5876e0cec40a23ba0", - "YEAOn3": "ef2848d3ecd2e509e77068f6615924b5abbb6ebd6b8236e4f2f2ccd69d2a3de0", + "bqCm2": "55cd22f7b5b42d88b29f3f1896ea9a269480ef9d581a4349706d74409b60c1f7", + "YEAOn3": "40f032f05de1bd5d7f30d7c0d31521d2a764b9f26d0b8d8b835fb1ddca0630bf", "aYBt7": false, "qEeg7": true } }, "22": { - "duration": 62, + "duration": 51, "fields": { - "tikJ6": [ + "gOEm7": [ 54, 57, 59, 62, 63, 91, - 147, - 149, - 153, - 162, - 165, + 148, + 150, + 154, + 163, 166, 167, 168, @@ -2849,144 +2901,150 @@ 170, 171, 172, - 173 + 173, + 174 ], - "ZnIRF1": [], - "GMYd6": [], - "ltXr7": [ - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "hKxg0", - "GkwBC7", - "GkwBC7", - "hKxg0", - "sGUjD4", - "hKxg0", - "sGUjD4", - "sGUjD4", - "hKxg0", - "hKxg0", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "GkwBC7", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "hKxg0", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4" + "rLrku6": [], + "XEUHT5": [], + "hRxVQ2": [ + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "wdhwX8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "adPVv8", + "wdhwX8", + "wdhwX8", + "adPVv8", + "MntR6", + "adPVv8", + "MntR6", + "MntR6", + "adPVv8", + "adPVv8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "wdhwX8", + "MntR6", + "MntR6", + "wdhwX8", + "wdhwX8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "wdhwX8", + "adPVv8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "wdhwX8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6" ], - "fayBq4": [ + "vxrRf4": [ + 0, + 0, + 0, + 0, + 0, 0, - 1000, 0, 0, 1000, @@ -2995,14 +3053,6 @@ 1000, 0, 0, - 1000, - 0, - 0, - 1000, - 0, - 1000, - 0, - 0, 0, 0, 0, @@ -3013,21 +3063,17 @@ 1000, 0, 0, + 1000, 0, 0, + 1000, + 0, 0, 1000, 1000, 0, - 1000, 0, 0, - 0, - 0, - 0, - 0, - 1000, - 0, 1000, 0, 0, @@ -3038,9 +3084,17 @@ 0, 0, 0, + 1000, + 0, + 0, + 1000, + 0, + 0, + 0, + 1000, 0, null, - 1000, + 0, 0, null, 0, @@ -3053,8 +3107,6 @@ 0, 0, 0, - 1000, - 0, 0, 0, 0, @@ -3075,10 +3127,13 @@ 0, 0, 0, + 1000, + 0, 0, null, 0, 0, + 0, 1000, 0, 0, @@ -3096,15 +3151,6 @@ 0, 0, 0, - 1000, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, 0, 0, 0, @@ -3112,7 +3158,6 @@ 0, 0, 0, - 0, 1000, 0, 0, @@ -3123,42 +3168,12 @@ 0, 0, 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - null, 1000, - null, 0, 0, - 0, - null, - 0, 1000, 0, 0, - 0, - 0, - 0, - 0, - null, - 0, - 0, - null, - null, - null, - null, - null, - null, - null, - null, - null, 1000, 0, 0, @@ -3169,37 +3184,228 @@ 0, 0, 0, + 1000, + 0, + 0, + null, + 0, + null, + 0, + 1000, + 0, + null, + 0, + 0, + 0, + 1000, + 0, + 0, + 0, + 0, + null, + 1000, + 0, + null, + null, + null, + null, + null, + null, + null, + null, + null, + 0, + 0, + 0, + 1000, + 0, + 0, + 0, + 0, + 1000, + 0, 0 ] } }, "23": { - "duration": 6, + "duration": 36, "fields": { - "FMLM9": [ + "SUBTl0": [ 0, 0, 0 ], - "SUBTl0": 0, + "vqzXM2": 0, "IzIpb8": [ "Apple Symbols", + "Arial", "Carlito", - "Galvji" + "Courier New", + "Galvji", + "Georgia", + "Helvetica", + "Impact", + "Times New Roman", + "Trebuchet MS", + "Verdana" ], - "KfgrY7": 3, + "kxzY1": 11, "EgIt8": "zJmE3", - "ezfp5": "2ea1e7a55d02be42ec3813109860eb7cd5781fa6d11b61e5d296d8bdb486d7b8", - "FynYg2": false + "LvRtb9": "1e678cbed43b27b4971c3200244a0a8d51563c1ffc52f5e093d3e97664ec4363", + "FynYg2": false, + "sibaD1": [ + "JBik9", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "true", + "false", + "false", + "false", + "false", + "true", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "true", + "true", + "true", + "true", + "true", + "true", + "false", + "true", + "false", + "true", + "true" + ], + "uoBG2": [ + "JBik9", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "90.125", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "136.90625", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "113.734375", + "120.890625", + "137.796875", + "120.890625", + "130.453125", + "134.421875", + "134.421875", + "120.890625", + "134.421875", + "123.734375", + "111.84375" + ], + "jrVX6": [ + "JBik9", + "620.05078125", + "561.69140625" + ] }, "late": [ - "FMLM9", "SUBTl0", + "vqzXM2", "IzIpb8", - "KfgrY7", + "kxzY1", "EgIt8", - "ezfp5", - "FynYg2" + "LvRtb9", + "FynYg2", + "sibaD1", + "uoBG2", + "jrVX6" ] }, "25": { @@ -3224,8 +3430,9 @@ } }, "27": { - "duration": 13, + "duration": 19, "fields": { + "dKjG5": {}, "cHblg8": "44ca9def45b49811e6a42235806b0aaa" }, "late": [ @@ -3233,7 +3440,7 @@ ] }, "31": { - "duration": 2, + "duration": 13, "fields": { "kZjr6": "en-US", "pewev9": [ @@ -3243,14 +3450,14 @@ "en-US" ], "YjKFO8": "en-us", - "tNVv9": "December at Eastern Standard Time", - "jtrA4": "Esperanto (Ukraine)", - "FnmhP9": "VoKES5, dhKV4, or xvcOC9", - "NtXV4": "21,000 trillion" + "UnMvf4": "December at Eastern Standard Time", + "HlWP7": "Esperanto (Ukraine)", + "CrRYD0": "mtya3, SDLOP8, or telh0", + "tvDL8": "21,000 trillion" } }, "32": { - "duration": 2, + "duration": 16, "fields": { "HcgE7": true, "yenvB9": 104857600, @@ -3260,24 +3467,24 @@ } }, "34": { - "duration": 3, + "duration": 8, "fields": { - "QqUE6": ".CjrhA8 { background-position: -1px -1px; background-repeat: no-repeat; }1", - "VukLq9": "c2e7a3596911ad633eed1c27fa2b517f" + "QqUE6": ".GPyAk9 { background-position: -1px -1px; background-repeat: no-repeat; }1", + "VukLq9": "c1a724f41cfb926f286c97201828ea21" }, "late": [ "VukLq9" ] }, "35": { - "duration": 15, + "duration": 20, "fields": { "LYTA4": false, "nVkj7": null, - "zwLw0": "djqZ2", + "zwLw0": "PuLjv3", "UaEqn8": 7, "AHei9": true, - "TyEK7": "djqZ2" + "TyEK7": "PuLjv3" } }, "37": { @@ -3285,110 +3492,109 @@ "fields": { "ukMAx1": [ { - "ymsu2": 30.9375, - "vCSZ5": 30.9375, - "IBsj3": 12.109375, - "RHQtR0": 800, - "WAZR9": 0, - "yqYok3": 787.890625, - "iyWVk8": 12.109375, - "BGhxB2": 0 + "Cmnj0": 30.9375, + "VwYDD8": 30.9375, + "knUS7": 12.109375, + "cyNU4": 800, + "nCLYc7": 0, + "UCluM4": 787.890625, + "YptYf3": 12.109375, + "wAVRH3": 0 }, { - "ymsu2": 443.17383575439453, - "vCSZ5": 383.47265625, - "IBsj3": 0, - "RHQtR0": 800, - "WAZR9": 59.70117950439453, - "yqYok3": 800, - "iyWVk8": 0, - "BGhxB2": 59.70117950439453 + "Cmnj0": 443.17383575439453, + "VwYDD8": 383.47265625, + "knUS7": 0, + "cyNU4": 800, + "nCLYc7": 59.70117950439453, + "UCluM4": 800, + "YptYf3": 0, + "wAVRH3": 59.70117950439453 }, { - "ymsu2": 407.1925048828125, - "vCSZ5": 111.510009765625, - "IBsj3": -2147483648, - "RHQtR0": 2147483648, - "WAZR9": 295.6824951171875, - "yqYok3": 4294967296, - "iyWVk8": -2147483648, - "BGhxB2": 295.6824951171875 + "Cmnj0": 407.1925048828125, + "VwYDD8": 111.510009765625, + "knUS7": -2147483648, + "cyNU4": 2147483648, + "nCLYc7": 295.6824951171875, + "UCluM4": 4294967296, + "YptYf3": -2147483648, + "wAVRH3": 295.6824951171875 }, { - "ymsu2": 457.75205993652344, - "vCSZ5": 315.81304931640625, - "IBsj3": 389.3282775878906, - "RHQtR0": 547.5862426757812, - "WAZR9": 141.9390106201172, - "yqYok3": 158.25796508789062, - "iyWVk8": 389.3282775878906, - "BGhxB2": 141.9390106201172 + "Cmnj0": 457.75205993652344, + "VwYDD8": 315.81304931640625, + "knUS7": 389.3282775878906, + "cyNU4": 547.5862426757812, + "nCLYc7": 141.9390106201172, + "UCluM4": 158.25796508789062, + "YptYf3": 389.3282775878906, + "wAVRH3": 141.9390106201172 }, { - "ymsu2": 465.9375, - "vCSZ5": 85, - "IBsj3": 56.515625, - "RHQtR0": 189.8125, - "WAZR9": 380.9375, - "yqYok3": 133.296875, - "iyWVk8": 56.515625, - "BGhxB2": 380.9375 + "Cmnj0": 465.9375, + "VwYDD8": 85, + "knUS7": 56.515625, + "cyNU4": 189.8125, + "nCLYc7": 380.9375, + "UCluM4": 133.296875, + "YptYf3": 56.515625, + "wAVRH3": 380.9375 }, { - "ymsu2": 512.1200561523438, - "vCSZ5": 46.3651123046875, - "IBsj3": -3.174727201461792, - "RHQtR0": 803.1747601032257, - "WAZR9": 465.75494384765625, - "yqYok3": 806.3494873046875, - "iyWVk8": -3.174727201461792, - "BGhxB2": 465.75494384765625 + "Cmnj0": 512.1200561523438, + "VwYDD8": 46.3651123046875, + "knUS7": -3.174727201461792, + "cyNU4": 803.1747601032257, + "nCLYc7": 465.75494384765625, + "UCluM4": 806.3494873046875, + "YptYf3": -3.174727201461792, + "wAVRH3": 465.75494384765625 }, { - "ymsu2": 185.390625, - "vCSZ5": 24, - "IBsj3": 14.546875, - "RHQtR0": 83.546875, - "WAZR9": 161.390625, - "yqYok3": 69, - "iyWVk8": 14.546875, - "BGhxB2": 161.390625 + "Cmnj0": 185.390625, + "VwYDD8": 24, + "knUS7": 14.546875, + "cyNU4": 83.546875, + "nCLYc7": 161.390625, + "UCluM4": 69, + "YptYf3": 14.546875, + "wAVRH3": 161.390625 }, { - "ymsu2": 383.390625, - "vCSZ5": 22, - "IBsj3": 254.546875, - "RHQtR0": 339.28125, - "WAZR9": 361.390625, - "yqYok3": 84.734375, - "iyWVk8": 254.546875, - "BGhxB2": 361.390625 + "Cmnj0": 383.390625, + "VwYDD8": 22, + "knUS7": 254.546875, + "cyNU4": 339.28125, + "nCLYc7": 361.390625, + "UCluM4": 84.734375, + "YptYf3": 254.546875, + "wAVRH3": 361.390625 }, { - "ymsu2": 423.390625, - "vCSZ5": 22, - "IBsj3": 254.546875, - "RHQtR0": 398.546875, - "WAZR9": 401.390625, - "yqYok3": 144, - "iyWVk8": 254.546875, - "BGhxB2": 401.390625 + "Cmnj0": 423.390625, + "VwYDD8": 22, + "knUS7": 254.546875, + "cyNU4": 398.546875, + "nCLYc7": 401.390625, + "UCluM4": 144, + "YptYf3": 254.546875, + "wAVRH3": 401.390625 }, { - "ymsu2": 223.390625, - "vCSZ5": 27, - "IBsj3": 254.546875, - "RHQtR0": 282.546875, - "WAZR9": 196.390625, - "yqYok3": 28, - "iyWVk8": 254.546875, - "BGhxB2": 196.390625 + "Cmnj0": 223.390625, + "VwYDD8": 27, + "knUS7": 254.546875, + "cyNU4": 282.546875, + "nCLYc7": 196.390625, + "UCluM4": 28, + "YptYf3": 254.546875, + "wAVRH3": 196.390625 } ] } } }, - "stack": "construct@[native code]\nP@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:44766\nWf@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:82036\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:58334\nio@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:131166\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:50221\nWI@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:83873\nP@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:44682\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:58409\nio@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:131166\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:49976\nWz@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:74958\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:55792\nio@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:131166\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:49976\nP@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:44724\niJ@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:125084\nWE@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:121771\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:55708\nio@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:131166\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:49976\nWG@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:89432\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:55815\nio@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:131166\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/18ion/0x4AAAAAAFYhfjRHf5P8Sryc/auto/fbE/new/normal:1:49976", "navigator": { "platform": "iPhone", "languages": [ diff --git a/profiles/safari-26-ios/challenge-page-answers.json b/profiles/safari-26-ios/challenge-page-answers.json index 9ba3fff..ec93652 100644 --- a/profiles/safari-26-ios/challenge-page-answers.json +++ b/profiles/safari-26-ios/challenge-page-answers.json @@ -2,7 +2,7 @@ "reference": "a562732e38934444", "probes": { "2": { - "duration": 17, + "duration": 69, "fields": { "Mrvi5": { "0": [ @@ -23,7 +23,7 @@ "s.availLeft", "s.availTop", "so.angle", - "o.gfOgY8" + "o.ZMiod6" ], "1": [ "d.childElementCount", @@ -78,7 +78,7 @@ "s.pixelDepth" ], "30": [ - "o.LeviO5" + "o.GsfY1" ], "32": [ "d.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC" @@ -194,10 +194,10 @@ "s.orientation", "o.event", "o._cf_chl_opt", - "o.HKul9", - "o.nTlR0", - "o.MpSwI7", - "o.xrbo0", + "o.sSkll6", + "o.nYPYj0", + "o.KryNx3", + "o.ygHP1", "o.angular" ], "F": [ @@ -471,7 +471,7 @@ "n.pdfViewerEnabled", "d.pictureInPictureEnabled", "d.isConnected", - "o.AgLL2", + "o.kMLRO6", "o.n.cookieEnabled" ], "https://challenges.cloudflare.com": [ @@ -1012,7 +1012,7 @@ "RangeError", "ReferenceError", "SyntaxError", - "TypeError", + "KCuZ3", "URIError", "AggregateError", "Proxy", @@ -1404,26 +1404,26 @@ "so.addEventListener", "so.removeEventListener", "so.dispatchEvent", - "o.THirw9", - "o.IXEYu6", - "o.nOLY0", - "o.runProgram", - "o.vUAjb0", - "o.zCGb4", - "o.AGRfA7", - "o.qpPe1", - "o.atAFr0", - "o.SABtz7", - "o.FIac3", - "o.RpzJz6", - "o.QSqpx9", - "o.ueZh9", - "o.FBBK4", - "o.ZliED2", - "o.NmGWd6", - "o.TZpt2", - "o.AwUcP3", - "o.MkvrI5", + "o.YDta0", + "o.yCpNJ2", + "o.YMwdw2", + "o.armBH3", + "o.ENLzH2", + "o.Ewgxh3", + "o.uOdMb2", + "o.qwQRi7", + "o.sSEGO7", + "o.eJeI1", + "o.qgcO0", + "o.xNxMK4", + "o.pRxjE3", + "o.wsqXE7", + "o.JwCUQ7", + "o.fXaz8", + "o.iqzpL9", + "o.HNiY8", + "o.ZahLT8", + "o.Tlvt6", "o.Array" ], "Infinity": [ @@ -1436,7 +1436,7 @@ "openDatabase", "d.all" ], - "p5": [ + "C": [ "Array" ], "Mozilla": [ @@ -1482,14 +1482,14 @@ "challenges.cloudflare.com": [ "d.domain" ], - "https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal?lang=auto": [ + "https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/g/turnstile/f/av0/rch/kafuv/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal?lang=auto": [ "d.referrer", "d.baseURI" ], "s": [ "d.cookie" ], - "10/24/2026 17:23:12": [ + "10/27/2026 19:02:46": [ "d.lastModified" ], "complete": [ @@ -1503,7 +1503,7 @@ ], "": [ "d.adoptedStyleSheets", - "o.vvfHL3" + "o.hbRVt7" ], "#document": [ "d.nodeName" @@ -1511,17 +1511,17 @@ "portrait-primary": [ "so.type" ], - "4wNwTokYX9Fu+cj3d8F8HsywiHABX4h/R16FveVtEWM=$km+MVByr0jgLtg9vj2y+NQ==,laZfK7iKr0+9nrlGP7Kcs5ZuRXdd7Zr7TM4Vj9i/j8ts+uGBf4Vv4xEhMWRm6Ff4$XncbnhOVWhy8Q2MDQe2UCA==,iGrOd1/NUIJvSfQQHP3lBjgWBzjYfQ0AWeLDLKevbply+czm/BNOZ+JJiA/PrAK/$d6nzvfYrWuhvcMFWb/zuAg==": [ - "o.qrht8" + "4f9QFeRps2/ZDfRAjYgOssNGvS6DNKP2iTP6An7qkYg=$z+gkCZYGur1V/qmFmVOy4w==,Ccx5Fwb7FK2t7F/JQ616ajqUwCTwRL/xvZpoN9nac5w=$yGmD6uSO6Ch8wHZG/krY5A==,FUSigE0eHO76gz16eQi4nHWpF80F0iGLlqKv4wvpQ48E+m0GBaSryTVbWz+UqlGQ$X1Snllu6N93PV+uTx/QH9g==": [ + "o.Vnlyd3" ], - "-3": [ - "o.vMhC1" + "-4": [ + "o.BWRSl4" ], - "qCZq4": [ - "o.lffN9" + "suNuW1": [ + "o.TRcGA3" ], "function querySelector() {\n [native code]\n},function querySelectorAll() {\n [native code]\n},function querySelector() {\n [native code]\n},function querySelectorAll() {\n [native code]\n}": [ - "o.dSvRK1" + "o.DIkC7" ] }, "gVIOJ1": { @@ -1529,8 +1529,8 @@ "CvjRv6": true, "VJeMl3": null, "CUFA2": 0, - "qYdP1": 275444, - "qivJU1": 115776 + "qYdP1": 605668, + "qivJU1": 193480 } } }, @@ -1541,7 +1541,7 @@ } }, "6": { - "duration": 5, + "duration": 7, "fields": { "RUGg3": false, "YdPI7": false, @@ -1552,9 +1552,9 @@ "ZTGE3": false, "RwUzK9": "navigate", "IEoo6": "", - "jSAze1": [], + "ZzbI2": [], "VQWKy9": false, - "ybXT7": "[{\"name\":\"geolocation\",\"state\":\"denied\"},{\"name\":\"notifications\",\"state\":\"denied\"},{\"name\":\"camera\",\"state\":\"denied\"},{\"name\":\"microphone\",\"state\":\"denied\"}]" + "kEkZQ3": "[{\"name\":\"geolocation\",\"state\":\"denied\"},{\"name\":\"notifications\",\"state\":\"denied\"},{\"name\":\"camera\",\"state\":\"denied\"},{\"name\":\"microphone\",\"state\":\"denied\"}]" } }, "7": { @@ -1564,7 +1564,7 @@ } }, "8": { - "duration": 3, + "duration": 77, "fields": { "pYHZ2": "JNcIn7" } @@ -1572,8 +1572,8 @@ "10": { "duration": 4, "fields": { - "eHTM1": "uvFa8", - "jskZ5": [ + "bQBt4": "zOENR5", + "vbrE9": [ true, true, true, @@ -1659,7 +1659,7 @@ true, true, true, - "

mgkO0

kCzq0

", + "

geEP5

wiZZO1

", "
", true, true, @@ -1677,7 +1677,7 @@ true, true, true, - "

mgkO0

kCzq0

", + "

geEP5

wiZZO1

", "
", -1, -1, @@ -1692,8 +1692,8 @@ true, false, "[object Undefined]", - "BLdW9611", - "BLdW9/\\u0067\\u0075\\u006c\\u0065/" + "dLoV1611", + "dLoV1/\\u0067\\u0075\\u006c\\u0065/" ] } }, @@ -1705,107 +1705,144 @@ } }, "13": { - "duration": 26, + "duration": 21, "fields": { - "wZzhY9": [ - "fAhw2", - "MBTMg5", - "xgZp0", - "abAh2", - "SGPo1", - "XMexs0", - "farG1", + "CnBd1": 0, + "yCNNi5": [ + "bbewo8", + "bbewo8" + ], + "COUZf0": [ + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8", + "bbewo8" + ], + "arqA7": [ + "IHdE7", + "IHdE7", + "IHdE7", + "IHdE7", + "IHdE7", + "IHdE7" + ], + "TsnFY8": "QEZg7", + "agmL8": "tedVy6", + "ClXn8": "fuNGU7", + "QAlM4": [ + "BPcA0", + "BPcA0", + "BPcA0", + "BPcA0" + ], + "oPxfw0": [ + "QrrLS4", + "YQrqM9", + "djRQ8", + "ZkNZ1", + "DHaWI3", + "Eiqe1", + "HLKa2", 61, - "kHBYa0", - "kHBYa0", + "lBhq6", + "lBhq6", "tjoAf2", "tjoAf2", - "MBTMg5", + "YQrqM9", "LrHWa3", - "xgZp0", + "djRQ8", "LrHWa3", - "MBTMg5", + "YQrqM9", "LrHWa3", - "xgZp0", + "djRQ8", "LrHWa3", - "MBTMg5", + "YQrqM9", "oUia2", - "xgZp0", + "djRQ8", "oUia2", - "MBTMg5", + "YQrqM9", "oUia2", - "xgZp0", + "djRQ8", "oUia2", - "MBTMg5", + "YQrqM9", "vXLPk0", - "xgZp0", + "djRQ8", "vXLPk0", - "MBTMg5", + "YQrqM9", "vXLPk0", - "xgZp0", + "djRQ8", "vXLPk0", - "MBTMg5", + "YQrqM9", "fOxd0", - "xgZp0", + "djRQ8", "fOxd0", - "MBTMg5", + "YQrqM9", "fOxd0", - "xgZp0", + "djRQ8", "fOxd0", - "MBTMg5", + "YQrqM9", "bKAX5", - "xgZp0", + "djRQ8", "bKAX5", - "MBTMg5", + "YQrqM9", "bKAX5", - "xgZp0", + "djRQ8", "bKAX5", - "MBTMg5", + "YQrqM9", "qAyyq5", - "xgZp0", + "djRQ8", "qAyyq5", - "MBTMg5", + "YQrqM9", "qAyyq5", - "xgZp0", + "djRQ8", "qAyyq5", - "MBTMg5", + "YQrqM9", "yEWMp2", - "xgZp0", + "djRQ8", "yEWMp2", - "MBTMg5", + "YQrqM9", "yEWMp2", - "xgZp0", + "djRQ8", "yEWMp2", - "MBTMg5", + "YQrqM9", "BLqf9", - "xgZp0", + "djRQ8", "BLqf9", - "MBTMg5", + "YQrqM9", "BLqf9", - "xgZp0", + "djRQ8", "BLqf9", - "MBTMg5", - "rukf4", - "xgZp0", - "rukf4", - "MBTMg5", - "rukf4", - "xgZp0", - "rukf4", - "MBTMg5", + "YQrqM9", + "AONvF9", + "djRQ8", + "AONvF9", + "YQrqM9", + "AONvF9", + "djRQ8", + "AONvF9", + "YQrqM9", "cXWh3", - "xgZp0", + "djRQ8", "cXWh3", - "abAh2", + "ZkNZ1", "cXWh3" ], - "ZOif6": "YPqu7" + "mBxH7": null, + "YmXV0": "hCig9" } }, "14": { - "duration": 6, + "duration": 17, "fields": { - "HgNL2": [ + "QsQH7": [ "1.457511857388766", "0.7853981633974483", "709.889355822726", @@ -1823,7 +1860,7 @@ "1.2626272556789115", "0.5493061443340549", "0.5493061443340549", - "5.587684646268005e-309", + "5e-311", "1.0038848218538872", "4.641588833612779", "4.641588833612778", @@ -2007,11 +2044,26 @@ } }, "18": { - "duration": 42, + "duration": 97, "fields": { - "nXks6": "JzCDC73e980ced8ba12e4d2b062a678c06873aEETJ6", - "nGLC2": "JzCDC73e980ced8ba12e4d2b062a678c06873aEETJ6", - "qKwk8": [ + "MBXf3": "DEAR33684fc6e5dc7baaa470608366da4516bcicCP7", + "ySrtS5": "DEAR33684fc6e5dc7baaa470608366da4516bcicCP7", + "FXpXv1": [ + [ + 62, + 32, + 0, + 255 + ], + [ + 0, + 0, + 0, + 255 + ], + null + ], + "CNRnh6": [ [ "WebKit", "WebKit WebGL" @@ -2021,7 +2073,7 @@ "Apple GPU" ] ], - "wzhU9": [ + "oHFLJ5": [ [ "apple", "apple", @@ -2192,14 +2244,14 @@ [] ] ], - "zpuw5": "827939e838fdb83387cf852d4a505360", - "Dqeg5": "4cc68c48404248a9a84563c711d22b6a", - "OWFf4": [ + "wsksA3": "827939e838fdb83387cf852d4a505360", + "fVCRI9": "4cc68c48404248a9a84563c711d22b6a", + "AvIxy5": [ 2, 0, 0 ], - "zkuPb4": [ + "nardr7": [ 33, "ANGLE_instanced_arrays,EXT_blend_minmax,EXT_clip_control,EXT_color_buffer_half_float,EXT_depth_clamp,EXT_frag_depth,EXT_polygon_offset_clamp,EXT_shader_texture_lod,EXT_texture_filter_anisotropic,EXT_texture_mirror_clamp_to_edge,EXT_sRGB,KHR_parallel_shader_compile,OES_element_index_uint,OES_fbo_render_mipmap,OES_standard_derivatives,OES_texture_float,OES_texture_half_float,OES_texture_half_float_linear,OES_vertex_array_object,WEBGL_blend_func_extended,WEBGL_color_buffer_float,WEBGL_compressed_texture_astc,WEBGL_compressed_texture_etc,WEBGL_compressed_texture_etc1,WEBGL_compressed_texture_pvrtc,WEBKIT_WEBGL_compressed_texture_pvrtc,WEBGL_debug_renderer_info,WEBGL_debug_shaders,WEBGL_depth_texture,WEBGL_draw_buffers,WEBGL_lose_context,WEBGL_multi_draw,WEBGL_polygon_mode", "EXT_disjoint_timer_query,EXT_float_blend,EXT_texture_compression_bptc,EXT_texture_compression_rgtc,OES_texture_float_linear,WEBGL_compressed_texture_s3tc,WEBGL_compressed_texture_s3tc_srgb,WEBGL_provoking_vertex", @@ -2266,7 +2318,7 @@ 1024, [] ], - "hHFd9": [ + "oXlug7": [ 2048, 2147483647, 2147483647, @@ -2315,7 +2367,7 @@ "srgb", null ], - "IXea2": [ + "GqCeX8": [ 16, 4352, null, @@ -2358,11 +2410,11 @@ "srgb", null ], - "kdniG6": [ - "253,253,253,253,183,183,183,253,228,228,228,254,48,48,48,255,", + "FJbU2": [ + "255,255,255,255,186,186,186,255,230,230,230,255,45,45,45,253,", 1, 0.0040984375000000005, - "09412c789e7ce7fc3b999df4acc11ed2", + "eee99c103643e637df4f5a62fc024c8b", -19762, [ [ @@ -2520,10 +2572,10 @@ "srgb", null, 4, - 255, - 29, - 129, - 255 + 254, + 26, + 126, + 254 ] ], [ @@ -2535,10 +2587,10 @@ "display-p3", null, 4, - 254, - 63, - 128, - 254 + 255, + 65, + 129, + 255 ] ], [ @@ -2550,10 +2602,10 @@ "srgb", null, 4, - 255, - 29, - 129, - 255 + 254, + 26, + 126, + 254 ] ], [ @@ -2565,10 +2617,10 @@ "display-p3", null, 4, - 254, - 63, - 128, - 254 + 255, + 65, + 129, + 255 ] ] ], @@ -2580,15 +2632,15 @@ [ 49, 44, - "df11939d553a900f17b396e3db15662e" + "8f46d7c78a4e4cece7c8c2fd8c49f9f1" ], [ 49, 44, - "df11939d553a900f17b396e3db15662e" + "8f46d7c78a4e4cece7c8c2fd8c49f9f1" ] ], - "ChJe3": [ + "NBcX0": [ [ [ 4, @@ -2747,7 +2799,7 @@ 36194 ] ], - "uvmjh4": [ + "Ooyv2": [ [ 0, 0, @@ -2783,30 +2835,31 @@ ], null ], - "bzTe1": [ + "pUHnB0": [ "e4ceffd6e4cfff84e4d0ff32e4d1ffdf", 1 ] }, "late": [ - "nXks6", - "nGLC2", - "qKwk8", - "wzhU9", - "zpuw5", - "Dqeg5", - "OWFf4", - "zkuPb4", - "hHFd9", - "IXea2", - "kdniG6", - "ChJe3", - "uvmjh4", - "bzTe1" + "MBXf3", + "ySrtS5", + "FXpXv1", + "CNRnh6", + "oHFLJ5", + "wsksA3", + "fVCRI9", + "AvIxy5", + "nardr7", + "oXlug7", + "GqCeX8", + "FJbU2", + "NBcX0", + "Ooyv2", + "pUHnB0" ] }, "19": { - "duration": 18, + "duration": 33, "fields": { "dNIwz0": "3a6635a800297ace2b2ffc992f5c2878c273d285b55e928decab1a802dbb8879", "IrCAn7": "21432bab72d581205049471541e706481667716e4feacd434c60315f008bb80b", @@ -2821,29 +2874,28 @@ } }, "21": { - "duration": 25, + "duration": 26, "fields": { - "bqCm2": "7a6b663e4ccf9bb39566f69f4c710711daae97572c95c413681033d17fc70a88", - "YEAOn3": "282aa1427df6944cb457ddc10048207006fe321c0a345dd5aeb76b369db96b21", + "bqCm2": "cd006c49597d372ed196b474c8f0ebcb8d6c79a3167f25c19ffa4aaa66f6d48b", + "YEAOn3": "81f1ca72a74bb102adfdcceeb7b41b4f49323230137748a594caf23d65d7486b", "aYBt7": false, "qEeg7": true } }, "22": { - "duration": 62, + "duration": 77, "fields": { - "tikJ6": [ + "gOEm7": [ 54, 57, 59, 62, 63, 91, - 147, - 149, - 153, - 162, - 165, + 148, + 150, + 154, + 163, 166, 167, 168, @@ -2851,273 +2903,279 @@ 170, 171, 172, - 173 + 173, + 174 ], - "ZnIRF1": [], - "GMYd6": [], - "ltXr7": [ - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "hKxg0", - "GkwBC7", - "GkwBC7", - "hKxg0", - "sGUjD4", - "hKxg0", - "sGUjD4", - "sGUjD4", - "hKxg0", - "hKxg0", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "GkwBC7", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "hKxg0", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "GkwBC7", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4", - "sGUjD4" + "rLrku6": [], + "XEUHT5": [], + "hRxVQ2": [ + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "wdhwX8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "adPVv8", + "wdhwX8", + "wdhwX8", + "adPVv8", + "MntR6", + "adPVv8", + "MntR6", + "MntR6", + "adPVv8", + "adPVv8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "wdhwX8", + "MntR6", + "MntR6", + "wdhwX8", + "wdhwX8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "wdhwX8", + "adPVv8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "wdhwX8", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6", + "MntR6" ], - "fayBq4": [ - 320, + "vxrRf4": [ + 360, + 240, 260, + 260, + 200, + 180, + 180, + 200, + 180, + 200, + 200, + 200, + 200, + 180, + 160, + 180, + 180, + 200, + 160, + 180, + 160, + 180, + 180, + 180, + 160, + 160, + 200, + 180, + 160, + 200, + 160, + 200, + 160, + 180, + 180, + 160, + 160, + 160, + 160, + 160, + 160, + 160, + 220, + 180, + 180, + 180, + 180, + 160, + 180, + 160, + 160, + 200, + 180, + 180, + null, + 160, + 160, + null, + 180, + null, + 160, + 180, + null, + null, + 200, + 180, + 180, + 160, 300, - 280, + 240, + 240, + 240, + 240, + 220, + 240, + 240, + 240, + 220, + 260, + 260, + 220, + 240, + 240, + 240, + 220, + 240, + 220, + 240, 300, - 280, - 280, - 280, - 240, - 200, - 200, - 200, - 200, - 180, 220, 220, - 200, - 200, - 200, - 220, - 200, - 2700, - 220, - 240, - 220, - 220, - 200, - 220, - 200, - 200, - 200, - 220, - 220, - 340, - 180, - 180, - 160, - 180, - 180, - 180, - 200, - 320, - 440, + null, 240, 240, 220, - 220, - 200, - 220, - 200, - 220, 240, 220, 240, - null, - 200, + 240, + 240, + 260, + 240, + 240, + 240, 220, - null, + 240, + 240, + 240, + 240, + 240, + 220, + 240, + 220, + 260, + 220, + 220, + 240, + 240, + 220, + 240, + 180, + 180, 200, - null, - 200, - 1320, - null, - null, 180, 200, - 160, 180, 180, - 160, - 160, - 160, - 160, - 140, - 160, - 140, - 160, - 160, - 160, - 140, - 160, - 140, - 140, - 140, - 140, - 140, - 160, - 1220, 180, - 140, - 160, - null, - 140, - 140, - 160, - 140, - 140, - 160, - 140, - 160, - 140, - 140, - 140, - 140, - 160, - 140, - 140, - 160, - 140, + 180, + 1500, 180, 160, - 160, - 140, - 140, - 140, - 140, 140, 160, 140, - 100, - 100, - 100, - 100, - 100, - 100, - 100, - 100, - 100, - 160, - 160, - 180, 160, 160, 140, @@ -3126,27 +3184,24 @@ 140, 140, 140, - 140, 160, 140, - 140, - 140, - 140, - 140, + 160, + 160, 140, null, 140, null, 140, 140, - 140, + 160, null, 140, + 160, + 160, 140, 140, - 140, - 140, - 140, + 160, 140, 140, null, @@ -3161,47 +3216,198 @@ null, null, null, - 120, - 120, - 120, - 120, - 120, + 160, 140, - 120, - 120, - 120, - 120, - 120 + 140, + 140, + 140, + 160, + 140, + 160, + 140, + 160, + 140 ] } }, "23": { - "duration": 6, + "duration": 38, "fields": { - "FMLM9": [ + "SUBTl0": [ 0, 0, 0 ], - "SUBTl0": 0, + "vqzXM2": 0, "IzIpb8": [ "Apple Symbols", + "Arial", "Carlito", - "Galvji" + "Courier New", + "Galvji", + "Georgia", + "Helvetica", + "Impact", + "Times New Roman", + "Trebuchet MS", + "Verdana" ], - "KfgrY7": 3, + "kxzY1": 11, "EgIt8": "zJmE3", - "ezfp5": "2ea1e7a55d02be42ec3813109860eb7cd5781fa6d11b61e5d296d8bdb486d7b8", - "FynYg2": false + "LvRtb9": "1e678cbed43b27b4971c3200244a0a8d51563c1ffc52f5e093d3e97664ec4363", + "FynYg2": false, + "sibaD1": [ + "JBik9", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "true", + "false", + "false", + "false", + "false", + "true", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "false", + "true", + "true", + "true", + "true", + "true", + "true", + "false", + "true", + "false", + "true", + "true" + ], + "uoBG2": [ + "JBik9", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "90.125", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "136.90625", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "134.421875", + "113.734375", + "120.890625", + "137.796875", + "120.890625", + "130.453125", + "134.421875", + "134.421875", + "120.890625", + "134.421875", + "123.734375", + "111.84375" + ], + "jrVX6": [ + "JBik9", + "620.05078125", + "561.69140625" + ] }, "late": [ - "FMLM9", "SUBTl0", + "vqzXM2", "IzIpb8", - "KfgrY7", + "kxzY1", "EgIt8", - "ezfp5", - "FynYg2" + "LvRtb9", + "FynYg2", + "sibaD1", + "uoBG2", + "jrVX6" ] }, "25": { @@ -3226,8 +3432,9 @@ } }, "27": { - "duration": 13, + "duration": 22, "fields": { + "dKjG5": {}, "cHblg8": "44ca9def45b49811e6a42235806b0aaa" }, "late": [ @@ -3235,7 +3442,7 @@ ] }, "31": { - "duration": 2, + "duration": 18, "fields": { "kZjr6": "en-US", "pewev9": [ @@ -3245,14 +3452,14 @@ "en-US" ], "YjKFO8": "en-us", - "tNVv9": "December at Eastern Standard Time", - "jtrA4": "Esperanto (Ukraine)", - "FnmhP9": "VoKES5, dhKV4, or xvcOC9", - "NtXV4": "21,000 trillion" + "UnMvf4": "December at Eastern Standard Time", + "HlWP7": "Esperanto (Ukraine)", + "CrRYD0": "mtya3, SDLOP8, or telh0", + "tvDL8": "21,000 trillion" } }, "32": { - "duration": 2, + "duration": 3, "fields": { "HcgE7": true, "yenvB9": 104857600, @@ -3262,135 +3469,134 @@ } }, "34": { - "duration": 3, + "duration": 4, "fields": { - "QqUE6": ".CjrhA8 { background-position: -1px -1px; background-repeat: no-repeat; }1", - "VukLq9": "c2e7a3596911ad633eed1c27fa2b517f" + "QqUE6": ".GPyAk9 { background-position: -1px -1px; background-repeat: no-repeat; }1", + "VukLq9": "c1a724f41cfb926f286c97201828ea21" }, "late": [ "VukLq9" ] }, "35": { - "duration": 15, + "duration": 16, "fields": { "LYTA4": false, "nVkj7": null, - "zwLw0": "djqZ2", + "zwLw0": "PuLjv3", "UaEqn8": 7, "AHei9": true, - "TyEK7": "djqZ2" + "TyEK7": "PuLjv3" } }, "37": { - "duration": 5, + "duration": 10, "fields": { "ukMAx1": [ { - "ymsu2": 30.9375, - "vCSZ5": 30.9375, - "IBsj3": 12.109375, - "RHQtR0": 800, - "WAZR9": 0, - "yqYok3": 787.890625, - "iyWVk8": 12.109375, - "BGhxB2": 0 + "Cmnj0": 30.9375, + "VwYDD8": 30.9375, + "knUS7": 12.109375, + "cyNU4": 800, + "nCLYc7": 0, + "UCluM4": 787.890625, + "YptYf3": 12.109375, + "wAVRH3": 0 }, { - "ymsu2": 443.17383575439453, - "vCSZ5": 383.47265625, - "IBsj3": 0, - "RHQtR0": 800, - "WAZR9": 59.70117950439453, - "yqYok3": 800, - "iyWVk8": 0, - "BGhxB2": 59.70117950439453 + "Cmnj0": 443.17383575439453, + "VwYDD8": 383.47265625, + "knUS7": 0, + "cyNU4": 800, + "nCLYc7": 59.70117950439453, + "UCluM4": 800, + "YptYf3": 0, + "wAVRH3": 59.70117950439453 }, { - "ymsu2": 407.1925048828125, - "vCSZ5": 111.510009765625, - "IBsj3": -2147483648, - "RHQtR0": 2147483648, - "WAZR9": 295.6824951171875, - "yqYok3": 4294967296, - "iyWVk8": -2147483648, - "BGhxB2": 295.6824951171875 + "Cmnj0": 407.1925048828125, + "VwYDD8": 111.510009765625, + "knUS7": -2147483648, + "cyNU4": 2147483648, + "nCLYc7": 295.6824951171875, + "UCluM4": 4294967296, + "YptYf3": -2147483648, + "wAVRH3": 295.6824951171875 }, { - "ymsu2": 457.75205993652344, - "vCSZ5": 315.81304931640625, - "IBsj3": 389.3282775878906, - "RHQtR0": 547.5862426757812, - "WAZR9": 141.9390106201172, - "yqYok3": 158.25796508789062, - "iyWVk8": 389.3282775878906, - "BGhxB2": 141.9390106201172 + "Cmnj0": 457.75205993652344, + "VwYDD8": 315.81304931640625, + "knUS7": 389.3282775878906, + "cyNU4": 547.5862426757812, + "nCLYc7": 141.9390106201172, + "UCluM4": 158.25796508789062, + "YptYf3": 389.3282775878906, + "wAVRH3": 141.9390106201172 }, { - "ymsu2": 465.9375, - "vCSZ5": 85, - "IBsj3": 56.515625, - "RHQtR0": 189.8125, - "WAZR9": 380.9375, - "yqYok3": 133.296875, - "iyWVk8": 56.515625, - "BGhxB2": 380.9375 + "Cmnj0": 465.9375, + "VwYDD8": 85, + "knUS7": 56.515625, + "cyNU4": 189.8125, + "nCLYc7": 380.9375, + "UCluM4": 133.296875, + "YptYf3": 56.515625, + "wAVRH3": 380.9375 }, { - "ymsu2": 512.1200561523438, - "vCSZ5": 46.3651123046875, - "IBsj3": -3.174727201461792, - "RHQtR0": 803.1747601032257, - "WAZR9": 465.75494384765625, - "yqYok3": 806.3494873046875, - "iyWVk8": -3.174727201461792, - "BGhxB2": 465.75494384765625 + "Cmnj0": 512.1200561523438, + "VwYDD8": 46.3651123046875, + "knUS7": -3.174727201461792, + "cyNU4": 803.1747601032257, + "nCLYc7": 465.75494384765625, + "UCluM4": 806.3494873046875, + "YptYf3": -3.174727201461792, + "wAVRH3": 465.75494384765625 }, { - "ymsu2": 185.390625, - "vCSZ5": 24, - "IBsj3": 14.546875, - "RHQtR0": 83.546875, - "WAZR9": 161.390625, - "yqYok3": 69, - "iyWVk8": 14.546875, - "BGhxB2": 161.390625 + "Cmnj0": 185.390625, + "VwYDD8": 24, + "knUS7": 14.546875, + "cyNU4": 83.546875, + "nCLYc7": 161.390625, + "UCluM4": 69, + "YptYf3": 14.546875, + "wAVRH3": 161.390625 }, { - "ymsu2": 383.390625, - "vCSZ5": 22, - "IBsj3": 254.546875, - "RHQtR0": 339.28125, - "WAZR9": 361.390625, - "yqYok3": 84.734375, - "iyWVk8": 254.546875, - "BGhxB2": 361.390625 + "Cmnj0": 383.390625, + "VwYDD8": 22, + "knUS7": 254.546875, + "cyNU4": 339.28125, + "nCLYc7": 361.390625, + "UCluM4": 84.734375, + "YptYf3": 254.546875, + "wAVRH3": 361.390625 }, { - "ymsu2": 423.390625, - "vCSZ5": 22, - "IBsj3": 254.546875, - "RHQtR0": 398.546875, - "WAZR9": 401.390625, - "yqYok3": 144, - "iyWVk8": 254.546875, - "BGhxB2": 401.390625 + "Cmnj0": 423.390625, + "VwYDD8": 22, + "knUS7": 254.546875, + "cyNU4": 398.546875, + "nCLYc7": 401.390625, + "UCluM4": 144, + "YptYf3": 254.546875, + "wAVRH3": 401.390625 }, { - "ymsu2": 223.390625, - "vCSZ5": 27, - "IBsj3": 254.546875, - "RHQtR0": 282.546875, - "WAZR9": 196.390625, - "yqYok3": 28, - "iyWVk8": 254.546875, - "BGhxB2": 196.390625 + "Cmnj0": 223.390625, + "VwYDD8": 27, + "knUS7": 254.546875, + "cyNU4": 282.546875, + "nCLYc7": 196.390625, + "UCluM4": 28, + "YptYf3": 254.546875, + "wAVRH3": 196.390625 } ] } } }, - "stack": "construct@[native code]\nVB@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:130348\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:56776\nQK@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:61920\ni@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:43057\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:48373\nVP@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:77156\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:56847\nQK@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:61920\ni@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:42968\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:48241\nVl@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:100783\ni@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:43057\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:54334\nQK@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:61920\ni@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:42968\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:48241\nQd@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:103618\nVj@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:113603\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:54243\nQK@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:61920\ni@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:42968\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:48241\nVT@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:98298\ni@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:42968\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:54359\nQK@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:61920\ni@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:42968\n@https://challenges.cloudflare.com/cdn-cgi/challenge-platform/h/b/turnstile/f/av0/rch/2t0ss/0x4AAAAAAAAjq6WYeRDKmebM/light/fbE/new/normal:1:48241", "navigator": { "platform": "iPhone", "languages": [ diff --git a/src/capture.rs b/src/capture.rs index 08814ef..7a13f16 100644 --- a/src/capture.rs +++ b/src/capture.rs @@ -3,15 +3,20 @@ //! //! 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. +//! [`Recording`] reads capture logs; [`fill_profile`] uses them to fill a device profile. mod ca; mod head; +mod profile; mod proxy; +mod recorded; mod rsa; mod sessions; mod traffic; mod upstream; pub use ca::CertificateAuthority; +pub use profile::fill as fill_profile; pub use proxy::{CA_HOST, CA_PATH, CHALLENGE_HOST, CaptureProxy, Config}; +pub use recorded::{CapturedSession, Recording}; pub use upstream::{Credentials, UpstreamProxy}; diff --git a/src/capture/profile.rs b/src/capture/profile.rs new file mode 100644 index 0000000..356cc96 --- /dev/null +++ b/src/capture/profile.rs @@ -0,0 +1,418 @@ +//! Fills device profiles from proxy recordings. +//! +//! `traffic.json` provides the user agent, client hints, and header order for each request type. +//! Session payloads provide probe durations, startup and pending times, benchmark speeds, media +//! observations, first-payload intervals, and loader timestamps. Most values use the median across +//! sessions. Loader timestamps come from a single session chosen by median send time, so they +//! remain consistent. +//! +//! Values that captures cannot provide stay unchanged: engine, TLS and HTTP/2 settings, request +//! priorities, page layout, interaction, resource timing phases, orchestrator pacing, and navigator +//! properties. `build_profile` writes the stored answers. + +mod headers; + +use std::collections::BTreeMap; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + +use anyhow::{Context, Result, bail}; +use serde::Serialize; +use serde_json::Value; +use url::Url; + +use self::headers::Headers; +use super::CHALLENGE_HOST; +use super::recorded::{CapturedSession, Recording}; +use crate::challenge::merge::OptionSource; +use crate::challenge::payload::Field; +use crate::challenge::program::PreparedSession; +use crate::challenge::state::{Intervals, ScriptState}; +use crate::embedding_page::extra_params::{ElapsedTimes, Timeline}; +use crate::http::{HeaderOrder, RequestKind}; +use crate::js::{self, JsObject, JsValue, Payload}; +use crate::script::Source; +use crate::stage2::analysis; +use crate::stage2::benchmark::WorkerCosts; +use crate::stage2::probes::media::Measurement; +use crate::stage2::registry::{Kind, Operation}; + +/// Updates measured profile values from `recordings`. Returns notes about the sources used and data +/// skipped. Other profile values stay unchanged. +pub fn fill(profile: &mut Value, recordings: &[Recording]) -> Result> { + let mut notes = Vec::new(); + for recording in recordings { + let dir = recording.dir.display(); + for skipped in &recording.skipped { + notes.push(format!("{dir}: left out {skipped}")); + } + } + let requests = recordings + .iter() + .flat_map(|recording| &recording.traffic.requests); + fill_headers(profile, Headers::observe(requests), &mut notes)?; + let script_fetch = section(profile, "/timeline/script_fetch")? + .as_f64() + .context("the profile's timeline has no script_fetch")?; + let mut reported = Reported { + script_fetch, + ..Reported::default() + }; + for recording in recordings { + for (name, session) in &recording.sessions { + let path = recording.dir.join(name); + for problem in reported.read(recording, session) { + notes.push(format!("{}: {problem:#}", path.display())); + } + } + } + reported.fill(profile, &mut notes)?; + Ok(notes) +} + +/// Updates header orders and browser identity headers for the request types found in the traffic. +fn fill_headers(profile: &mut Value, headers: Headers, notes: &mut Vec) -> Result<()> { + let own = section(profile, "/transport/headers")? + .as_object_mut() + .context("the profile's transport headers are not an object")?; + let sent = headers.identity.len(); + for (name, value) in headers.identity { + // Preserve the spelling of headers already in the profile. + let existing = own + .keys() + .find(|key| key.eq_ignore_ascii_case(&name)) + .cloned(); + own.insert(existing.unwrap_or(name), Value::String(value)); + } + notes.push(format!( + "transport.headers: the user agent and client hints, {sent} headers from traffic.json" + )); + let orders = section(profile, "/transport/requests/headers")? + .as_object_mut() + .context("the profile's header orders are not an object")?; + let observed = &headers.orders; + for (kind, order) in observed { + orders.insert(kind.to_string(), serde_json::to_value(order)?); + } + // Use one header order if the browser sends the same order before and after a script redirect. + if let Some(redirect) = observed.get(&RequestKind::ScriptRedirect) + && observed.get(&RequestKind::Script) == Some(redirect) + { + orders.remove(&RequestKind::ScriptRedirect.to_string()); + } + serde_json::from_value::(Value::Object(orders.clone())) + .context("the derived header orders are not valid")?; + let kept: Vec<&str> = orders + .keys() + .filter(|kind| !observed.keys().any(|seen| seen.to_string() == **kind)) + .map(String::as_str) + .collect(); + let kept = if kept.is_empty() { + "none".to_owned() + } else { + kept.join(", ") + }; + notes.push(format!( + "transport.requests.headers: {} kinds from traffic.json; kept the profile's {kept}", + observed.len(), + )); + Ok(()) +} + +/// Measurements collected from session payloads for use in a profile. +#[derive(Default)] +struct Reported { + /// Loader fetch time from the profile; payloads do not report it. + script_fetch: f64, + /// Probe durations by family. + durations: BTreeMap<&'static str, Vec>, + startup_ms: Vec, + pending_ms: Vec, + benchmark: Vec, + /// The first session's media observations. + media: Option, + intervals: Vec, + /// Loader timestamps from ordinary sites. Challenge pages load the loader late, so the solver + /// uses the timestamps from ordinary sites. + timelines: Vec, +} + +impl Reported { + /// Collects measurements from `session` and returns notes about data it could not read. + fn read(&mut self, recording: &Recording, session: &CapturedSession) -> Vec { + let source = match session.source() { + Ok(source) => source, + Err(error) => return vec![error.context("deobfuscating the iframe script")], + }; + let mut problems = Vec::new(); + let first = session.first_payload(); + if let Err(error) = first.and_then(|first| self.read_first(&source, first, &mut problems)) { + problems.push(error.context("reading the first payload")); + } + if let Err(error) = self.read_records(recording, session, &source, &mut problems) { + problems.push(error.context("reading the probe records")); + } + problems + } + + /// Collects first-payload intervals and the loader timestamps passed from the site to the + /// iframe. + fn read_first( + &mut self, + source: &Source, + payload: &Payload, + problems: &mut Vec, + ) -> Result<()> { + // Extraction only needs an iframe URL with the same origin as the POSTs. + let iframe = Url::parse(&format!("https://{CHALLENGE_HOST}/"))?; + let prepared = PreparedSession::try_new(source, &iframe)?; + let mapping = prepared.mapping()?; + let state = prepared.state()?; + let fields = &prepared.program().payload_fields; + match state.intervals(fields, mapping.merged(), payload) { + Ok(intervals) => self.intervals.push(intervals), + Err(error) => problems.push(error.context("reading the first payload")), + } + let mut message = JsObject::new(); + let mut implicit_render = None; + for entry in &mapping.0 { + let Some(value) = reported(payload, fields, &state, &entry.option) else { + continue; + }; + match &entry.source { + OptionSource::Message(key) => { + message.insert(key.clone(), value.clone()); + } + // The loader samples its own stack as it renders the page's widgets. + OptionSource::Samples(_) => { + let sample = value.as_array().and_then(|samples| samples.first()); + implicit_render = sample.and_then(|sample| sample.get("t")?.as_i64()); + } + _ => {} + } + } + // The orchestrator passes its page data only to widgets on challenge pages. + if message.get("chlPageData").is_some_and(js::truthy) { + return Ok(()); + } + let times: ElapsedTimes = js::from_value(JsValue::Object(message)) + .context("the first payload lacks the loader's elapsed times")?; + let implicit_render = + implicit_render.context("the first payload lacks the loader's stack sample")?; + let timeline = Timeline::from_times(×, implicit_render, self.script_fetch); + self.timelines.push(timeline); + Ok(()) + } + + /// Collects probe durations, benchmark speeds, the first media connection, and probe times + /// relative to the POSTs. + fn read_records( + &mut self, + recording: &Recording, + session: &CapturedSession, + source: &Source, + problems: &mut Vec, + ) -> Result<()> { + let program = session.program()?; + let payload = session.probe_payload()?; + let analysis = analysis::analyze(source, &program)?; + let plan = analysis.plan(); + let envelope = &plan.record_fields; + let completion = &envelope.completion; + let (mut first_started, mut last_finished) = (i64::MAX, i64::MIN); + for probe in plan.probes() { + let record = payload + .get(&probe.index.to_string()) + .and_then(JsValue::as_object) + .with_context(|| format!("the payload has no record for probe {}", probe.index))?; + let mark = |name: &str| record.get(name).and_then(JsValue::as_i64); + let (Some(started), Some(finished)) = + (mark(&completion.started), mark(&completion.finished)) + else { + bail!("probe {}'s record has no clock marks", probe.index); + }; + first_started = first_started.min(started); + last_finished = last_finished.max(finished); + let Some(operation) = &probe.operation else { + continue; + }; + match operation { + Operation::Benchmark { fields } => match fields.costs(record) { + Ok(costs) => self.benchmark.push(costs), + Err(error) => problems.push(error.context("reading the benchmark")), + }, + Operation::Media { fields } if self.media.is_none() => { + let names = envelope.names(); + let mut observed = record.clone(); + observed.retain(|name, _| !names.contains(&name.as_str())); + plan.vocabulary() + .rewrite_to_reference(probe.position(), &mut observed); + match fields.observed(&observed, started) { + Ok(media) => self.media = Some(without_addresses(media)), + Err(error) => problems.push(error.context("reading the media probe")), + } + } + _ => {} + } + // The solver measures its own benchmark's duration. + let family = operation.family(); + if family != Kind::Benchmark + && let Some(duration) = mark(&completion.duration) + { + self.durations + .entry(family.as_str()) + .or_default() + .push(duration); + } + } + let posts = recording.post_times(session)?; + self.startup_ms + .push(first_started - posts.first_answered_ms); + // The schedule reserves a millisecond after each probe. + self.pending_ms + .push(posts.second_sent_ms - last_finished - 1); + Ok(()) + } + + fn fill(mut self, profile: &mut Value, notes: &mut Vec) -> Result<()> { + let mut filled = |pointer: &str, value: Option, source: &str| -> Result<()> { + let name = pointer.trim_start_matches('/').replace('/', "."); + match value { + Some(value) => { + *section(profile, pointer)? = value; + notes.push(format!("{name}: {source}")); + } + None => notes.push(format!( + "{name}: kept the profile's; no session reported it" + )), + } + Ok(()) + }; + let sessions = |count: usize| format!("medians of {count} sessions"); + + let durations: BTreeMap<&str, u32> = self + .durations + .into_iter() + .filter_map(|(family, durations)| Some((family, unsigned(median(durations)?)))) + .collect(); + let count = self.startup_ms.len(); + let durations = (!durations.is_empty()).then_some(durations); + filled("/second/durations", json(durations)?, &sessions(count))?; + for (pointer, values) in [ + ("/second/startup_ms", self.startup_ms), + ("/second/pending_ms", self.pending_ms), + ] { + filled( + pointer, + json(median(values).map(unsigned))?, + &sessions(count), + )?; + } + + let benchmarks = self.benchmark.len(); + let benchmark = self.benchmark.into_iter().reduce(|mut all, costs| { + all.compile_ms.extend(costs.compile_ms); + for (speeds, more) in all + .kernel_ms_per_million + .iter_mut() + .zip(costs.kernel_ms_per_million) + { + speeds.extend(more); + } + all + }); + let source = format!("every round of {benchmarks} sessions"); + filled("/second/facts/benchmark_worker", json(benchmark)?, &source)?; + let source = "the first session's, its addresses replaced"; + filled("/second/facts/media", json(self.media)?, source)?; + + let intervals = median_intervals(&self.intervals); + filled( + "/intervals", + json(intervals)?, + &sessions(self.intervals.len()), + )?; + + // Use one session to keep timestamps consistent. Choose the session with the median loader + // send time. + let count = self.timelines.len(); + self.timelines.sort_by_key(|timeline| timeline.sent); + let source = format!( + "the median of {count} site widget sessions by send time; script_fetch kept, as no \ + payload reports it" + ); + filled("/timeline", json(self.timelines.get(count / 2))?, &source) + } +} + +/// Returns the median of each interval across sessions. +fn median_intervals(sessions: &[Intervals]) -> Option { + let column = |interval: fn(&Intervals) -> i64| median(sessions.iter().map(interval).collect()); + Some(Intervals { + initialise: column(|intervals| intervals.initialise)?, + handoff: column(|intervals| intervals.handoff)?, + collect: column(|intervals| intervals.collect)?, + send: column(|intervals| intervals.send)?, + }) +} + +/// Reads the value reported for `option`, either from its template field or directly from a +/// forwarded option. +fn reported<'payload>( + payload: &'payload Payload, + fields: &[Field], + state: &ScriptState, + option: &str, +) -> Option<&'payload JsValue> { + match fields + .iter() + .find(|field| field.option(state) == Some(option)) + { + Some(field) => payload.get(&field.name), + None if state.forwarded.iter().any(|key| key == option) => payload.get(option), + None => None, + } +} + +/// Replaces recorded IP addresses with documentation addresses so shared profiles do not reveal the +/// capture network. These addresses are never sent: [`crate::stage2::probes::ice::refresh`] +/// generates new names for host candidates. +fn without_addresses(mut media: Measurement) -> Measurement { + if let Measurement::Observed { snapshot, .. } = &mut media { + for candidate in &mut snapshot.connection.published_candidates { + let Some(line) = candidate.candidate.as_str() else { + continue; + }; + let tokens = line.split(' ').map(|token| match token.parse::() { + Ok(address) if address.is_unspecified() => token.to_owned(), + Ok(IpAddr::V4(_)) => Ipv4Addr::new(192, 0, 2, 1).to_string(), + Ok(IpAddr::V6(_)) => Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1).to_string(), + Err(_) => token.to_owned(), + }); + candidate.candidate = JsValue::String(tokens.collect::>().join(" ")); + } + } + media +} + +/// Returns the profile value at the JSON `pointer`. Panics if the path does not exist. +fn section<'profile>(profile: &'profile mut Value, pointer: &str) -> Result<&'profile mut Value> { + profile + .pointer_mut(pointer) + .with_context(|| format!("the profile has no {pointer}")) +} + +fn json(value: Option) -> Result> { + Ok(value.map(serde_json::to_value).transpose()?) +} + +/// Returns the median, choosing the upper middle value for an even count. +fn median(mut values: Vec) -> Option { + values.sort_unstable(); + values.get(values.len() / 2).copied() +} + +/// Converts a duration to the profile format. Negative durations caused by clock differences become +/// zero. +fn unsigned(duration: i64) -> u32 { + u32::try_from(duration.max(0)).unwrap_or(u32::MAX) +} diff --git a/src/capture/profile/headers.rs b/src/capture/profile/headers.rs new file mode 100644 index 0000000..5724cbc --- /dev/null +++ b/src/capture/profile/headers.rs @@ -0,0 +1,246 @@ +//! Derives header orders and the browser's identity headers from the requests in `traffic.json`. + +use std::cmp::Reverse; +use std::collections::BTreeMap; +use std::hash::Hash; + +use indexmap::IndexMap; +use url::Url; + +use crate::capture::CHALLENGE_HOST; +use crate::capture::traffic::Request; +use crate::http::RequestKind; + +/// Client hints that can appear on any request. Other hints identify navigation retries made after +/// the server requested high-entropy hints. +const LOW_ENTROPY_HINTS: [&str; 3] = ["sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform"]; + +/// Header orders and browser identity headers collected from requests. +pub(super) struct Headers { + /// Header order for each request type. Prefer orders with the most supplied headers, then the + /// most common order. The solver omits headers it cannot supply, such as a referrer withheld by + /// page policy. Orders include high-entropy hints requested before the challenge. For request + /// types shared by ordinary sites and challenge pages, such as icons, only challenge-page + /// requests matter. + pub(super) orders: BTreeMap>, + /// Most common value for each user agent or client hint header, in the order the headers first + /// appeared. + pub(super) identity: IndexMap, +} + +impl Headers { + pub(super) fn observe<'r>(requests: impl IntoIterator) -> Self { + let mut orders: BTreeMap>> = BTreeMap::new(); + let mut identity: IndexMap> = IndexMap::new(); + for request in requests { + let Some(kind) = kind(request) else { + continue; + }; + let sent = request.headers.iter().filter(|(name, _)| name != "cookie"); + let order: Vec = sent.map(|(name, value)| kind.entry(name, value)).collect(); + orders.entry(kind).or_default().add(order); + for (name, value) in &request.headers { + if name == "user-agent" || name.starts_with("sec-ch-") { + identity.entry(name.clone()).or_default().add(value.clone()); + } + } + } + // Fixed headers use `name: value`; headers filled at request time use bare names. + let supplied = + |order: &Vec| order.iter().filter(|entry| !entry.contains(':')).count(); + Self { + orders: orders + .into_iter() + .map(|(kind, tally)| (kind, tally.best(supplied))) + .collect(), + identity: identity + .into_iter() + .map(|(name, tally)| (name, tally.best(|_| ()))) + .collect(), + } + } +} + +/// Classifies requests the solver can send. Excludes cache revalidation requests because each solve +/// starts with an empty cache. +fn kind(request: &Request) -> Option { + if request.header("if-none-match").is_some() || request.header("if-modified-since").is_some() { + return None; + } + let url = Url::parse(&request.url).ok()?; + let challenge = url.host_str() == Some(CHALLENGE_HOST); + let post = request.method == "POST"; + let mode = request.header("sec-fetch-mode"); + // Challenge pages load the orchestrator and post to it on their own origin. + let platform = |route: &str| { + let path = url.path(); + path.starts_with("/cdn-cgi/challenge-platform/") && path.contains(route) + }; + Some(match (request.header("sec-fetch-dest")?, challenge, post) { + ("document", _, true) => RequestKind::Form, + // Match navigation from a typed address. Reloads and links use different headers. + ("document", _, false) if request.header("sec-fetch-site") == Some("none") => { + let hints = request.headers.iter().any(|(name, _)| { + name.starts_with("sec-ch-") && !LOW_ENTROPY_HINTS.contains(&name.as_str()) + }); + if hints { + RequestKind::NavigationWithHints + } else { + RequestKind::Navigation + } + } + ("iframe", true, false) => RequestKind::Iframe, + ("script", true, false) if mode == Some("cors") => RequestKind::CorsScript, + // The loader URL redirects to a URL for a specific build. + ("script", true, false) if url.path() == "/turnstile/v0/api.js" => RequestKind::Script, + ("script", true, false) => RequestKind::ScriptRedirect, + ("script", false, false) if platform("/orchestrate/") => RequestKind::Orchestrator, + ("image", false, false) => RequestKind::PageImage, + ("image", true, false) => RequestKind::Image, + ("empty", false, true) if platform("/fo/") => RequestKind::OrchestratorPost, + ("empty", true, true) => RequestKind::ChallengePost, + // The private token probe fetches with `{cache: "no-cache"}`. + ("empty", true, false) if url.path().contains("/pat/") => RequestKind::WorkerFetch, + ("empty", true, false) => RequestKind::WorkerFetchWithoutCredentials, + _ => return None, + }) +} + +/// Counts occurrences of each value while preserving insertion order. +#[derive(Default)] +struct Tally(IndexMap); + +impl Tally { + fn add(&mut self, value: T) { + *self.0.entry(value).or_default() += 1; + } + + /// Returns the highest-ranked value. Breaks ties by frequency, then by insertion order. + fn best(self, rank: impl Fn(&T) -> R) -> T { + // For equal keys, `min_by_key` returns the first entry; `max_by_key` returns the last. + let counts = self.0.into_iter(); + let best = counts.min_by_key(|(value, count)| Reverse((rank(value), *count))); + best.expect("a tally holds what was added to it").0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(method: &str, url: &str, headers: &[(&str, &str)]) -> Request { + let headers = headers + .iter() + .map(|&(name, value)| (name.into(), value.into())); + Request::received(method, url, headers.collect()) + } + + /// Select the most common order among those with the most supplied headers. Break ties by first + /// occurrence. Ignore cookies and cache revalidations. + #[test] + fn orders_each_kind_of_request_as_most_often_sent() { + let challenge = "https://challenges.cloudflare.com"; + let script = [ + ("sec-fetch-dest", "script"), + ("sec-fetch-mode", "no-cors"), + ("user-agent", "Mozilla/5.0"), + ("referer", "https://example.com/"), + ]; + let image = |storage: &str, referred: bool, revalidated: bool| { + let mut headers = vec![ + ("sec-fetch-dest", "image"), + ("cookie", "a=b"), + ("sec-fetch-storage-access", storage), + ]; + if referred { + headers.push(("referer", "https://challenges.cloudflare.com/")); + } + if revalidated { + headers.push(("if-none-match", "\"1\"")); + } + request("GET", &format!("{challenge}/ci/1"), &headers) + }; + let navigation = |hint: (&str, &str)| { + let headers = [ + hint, + ("sec-fetch-site", "none"), + ("sec-fetch-dest", "document"), + ]; + request("GET", "https://example.com/", &headers) + }; + let requests = [ + // A site's own script should not be classified as the orchestrator. + request( + "GET", + "https://example.com/app.js", + &[("sec-fetch-dest", "script")], + ), + navigation(("sec-ch-ua", "\"Chromium\"")), + navigation(("sec-ch-ua-arch", "\"x86\"")), + request("GET", &format!("{challenge}/turnstile/v0/api.js"), &script), + request( + "GET", + &format!("{challenge}/turnstile/v0/b/1/api.js"), + &script, + ), + image("none", false, false), + image("none", false, false), + image("none", true, true), + image("none", true, true), + image("active", true, false), + ]; + let headers = Headers::observe(&requests); + let orders: Vec<(RequestKind, Vec)> = headers.orders.into_iter().collect(); + let entries = |entries: &[&str]| entries.iter().map(|&entry| entry.to_owned()).collect(); + let script_order: Vec = entries(&[ + "sec-fetch-dest: script", + "sec-fetch-mode: no-cors", + "user-agent", + "referer", + ]); + assert_eq!( + orders, + [ + ( + RequestKind::Navigation, + entries(&[ + "sec-ch-ua", + "sec-fetch-site: none", + "sec-fetch-dest: document" + ]) + ), + ( + RequestKind::NavigationWithHints, + entries(&[ + "sec-ch-ua-arch", + "sec-fetch-site: none", + "sec-fetch-dest: document" + ]) + ), + (RequestKind::Script, script_order.clone()), + (RequestKind::ScriptRedirect, script_order), + ( + RequestKind::Image, + entries(&[ + "sec-fetch-dest: image", + "sec-fetch-storage-access: active", + "referer" + ]) + ), + ] + ); + let identity: Vec<(&str, &str)> = headers + .identity + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + .collect(); + assert_eq!( + identity, + [ + ("sec-ch-ua", "\"Chromium\""), + ("sec-ch-ua-arch", "\"x86\""), + ("user-agent", "Mozilla/5.0") + ] + ); + } +} diff --git a/src/capture/proxy.rs b/src/capture/proxy.rs index cf91022..3eadba0 100644 --- a/src/capture/proxy.rs +++ b/src/capture/proxy.rs @@ -33,8 +33,9 @@ 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}; +use crate::js::ast; +use crate::{challenge, deobfuscate}; const ESTABLISHED: &[u8] = b"HTTP/1.1 200 Connection Established\r\n\r\n"; @@ -423,10 +424,14 @@ impl CaptureProxy { fn rewrite_iframe(&self, url: &str, upstream: &Proxied) -> Option> { 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)) + let scanned = challenge::inline_javascript(&html).and_then(|javascript| { + let parsed = ast::parse_javascript("iframe.js", &javascript)?; + let strings = deobfuscate::inline_strings(&parsed.script); + let alphabet = sessions::scan_alphabet(&parsed.script, &strings)?; + let swapped = rsa::swap_modulus(&html, &strings, &self.sessions.proxy_key.modulus)?; + anyhow::Ok((alphabet, swapped)) + }); + let (alphabet, (rewritten, real_modulus)) = scanned .inspect_err(|error| eprintln!("{url}: forwarding the original iframe: {error:#}")) .ok()?; let encoded = http::encode_body(rewritten.as_bytes(), &encoding).ok()?; diff --git a/src/capture/recorded.rs b/src/capture/recorded.rs new file mode 100644 index 0000000..bd14a65 --- /dev/null +++ b/src/capture/recorded.rs @@ -0,0 +1,159 @@ +//! Reads session data from `capture.json` and request traffic from `traffic.json`. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD; +use serde::Deserialize; +use serde::de::DeserializeOwned; +use url::Url; + +use super::traffic::{Request, Traffic}; +use crate::js::Payload; +use crate::script::Source; +use crate::{challenge, deobfuscate}; + +/// Session data from `capture.json`: the iframe page, POSTs, and decoded payloads. +/// `scripts/cdp_capture.mjs` writes the same format without `cfChl`. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CapturedSession { + iframe_html: String, + posts: Vec, + payloads: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct CapturedPost { + url: String, + cf_chl: Option, + response_body: String, +} + +#[derive(Deserialize)] +struct CapturedPayload { + payload: Payload, +} + +impl CapturedSession { + pub fn read(path: &Path) -> Result { + read_json(path) + } + + /// Returns the deobfuscated inline script from the iframe. + pub fn source(&self) -> Result { + let javascript = challenge::inline_javascript(&self.iframe_html)?; + Source::try_new(&deobfuscate::deobfuscate(javascript)?.text) + } + + /// Returns the probe program from the first POST response, unmasked using the ray ID in the + /// URL. + pub fn program(&self) -> Result> { + let post = self.posts.first().context("the capture has no POST")?; + let url = Url::parse(&post.url)?; + let encoded = + challenge::decode_response(post.response_body.as_bytes(), challenge::ray(&url)?)?; + Ok(STANDARD.decode(encoded)?) + } + + /// Returns the payload built before probes run. + pub fn first_payload(&self) -> Result<&Payload> { + let first = self.payloads.first().map(|payload| &payload.payload); + first.context("the capture has no first payload") + } + + /// Returns the second payload, which contains a numbered record for each probe. + pub fn probe_payload(&self) -> Result<&Payload> { + let mut payloads = self.payloads.iter().map(|payload| &payload.payload); + payloads + .find(|payload| payload.contains_key("1")) + .context("the capture has no payload with probe records") + } +} + +/// Traffic and complete sessions from one proxy run directory. +pub struct Recording { + pub(super) dir: PathBuf, + pub(super) traffic: Traffic, + pub(super) sessions: BTreeMap, + /// Excluded sessions and the reasons they were skipped. + pub(super) skipped: Vec, +} + +/// Capture completeness status read from `session.json`. +#[derive(Deserialize)] +struct SessionLog { + complete: bool, + notes: Vec, +} + +impl Recording { + /// Reads the proxy output directory `dir`, skipping incomplete session captures. + pub fn read(dir: &Path) -> Result { + let traffic: Traffic = read_json(&dir.join("traffic.json"))?; + let sessions_dir = dir.join("sessions"); + let mut names: Vec = fs::read_dir(&sessions_dir) + .with_context(|| format!("reading {}", sessions_dir.display()))? + .map(|entry| Ok(entry?.file_name().to_string_lossy().into_owned())) + .collect::>()?; + names.sort(); + let mut sessions = BTreeMap::new(); + let mut skipped = Vec::new(); + for name in names { + let session_dir = sessions_dir.join(&name); + let log: SessionLog = read_json(&session_dir.join("session.json"))?; + if !log.complete { + skipped.push(format!( + "{name}: incomplete capture: {}", + log.notes.join("; ") + )); + continue; + } + let capture = CapturedSession::read(&session_dir.join("capture.json"))?; + sessions.insert(name, capture); + } + Ok(Self { + dir: dir.to_owned(), + traffic, + sessions, + skipped, + }) + } + + /// Groups POSTs by the `cf-chl` header shared by all POSTs in a session. + pub(super) fn post_times(&self, session: &CapturedSession) -> Result { + let cf_chl = session + .posts + .first() + .and_then(|post| post.cf_chl.as_deref()) + .context("the capture's first POST has no cf-chl header")?; + let posted = |request: &&Request| { + request.method == "POST" && request.header("cf-chl") == Some(cf_chl) + }; + let mut posts = self.traffic.requests.iter().filter(posted); + let first = posts.next().context("traffic.json lacks the first POST")?; + let second = posts.next().context("traffic.json lacks the second POST")?; + Ok(PostTimes { + first_answered_ms: first + .answered_ms + .context("traffic.json records no response to the first POST")?, + second_sent_ms: second.received_ms, + }) + } +} + +/// Returns the times when the browser received the first POST response and sent the second POST, in +/// milliseconds since the Unix epoch. +pub(super) struct PostTimes { + pub(super) first_answered_ms: i64, + pub(super) second_sent_ms: i64, +} + +fn read_json(path: &Path) -> Result { + let text = fs::read(path).with_context(|| format!("reading {}", path.display()))?; + serde_json::from_slice(&text).with_context(|| format!("reading {}", path.display())) +} diff --git a/src/capture/rsa.rs b/src/capture/rsa.rs index 29a957b..ca0623b 100644 --- a/src/capture/rsa.rs +++ b/src/capture/rsa.rs @@ -15,6 +15,7 @@ use serde_json::Value; use crate::candidates; use crate::challenge::codec::{self, Envelope, KEY_LENGTH, PUBLIC_EXPONENT, SEED_LENGTH}; +use crate::deobfuscate::{self, Encoded}; /// 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. @@ -90,28 +91,59 @@ impl ProxyKey { } } -/// 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)) +/// Replaces the iframe's 128-byte RSA modulus with `proxy`. Returns the rewritten HTML and the +/// original modulus. See `rsa_modulus` in `crate::challenge::program`. +/// +/// Pads the replacement with zeros to preserve HTML length and stack trace positions. The modulus +/// can be a hexadecimal `BigInt` literal or an inline encoded string from `strings`. Encoded +/// replacements use the original key. +pub(super) fn swap_modulus( + html: &str, + strings: &[Encoded], + proxy: &BigUint, +) -> Result<(String, BigUint)> { + let wide = |modulus: &BigUint| modulus.bits().div_ceil(8) == SEED_LENGTH as u64; + let literals: Vec<_> = 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"); + (open == close && wide(&modulus)) + .then(|| (captures.get(2).expect("the digits group").range(), modulus)) + }) + .collect(); + if !literals.is_empty() { + let what = format!("{SEED_LENGTH}-byte BigInt literal in the iframe"); + let (digits, real) = candidates::exactly_one(literals, &what)?; + let mut rewritten = html.to_owned(); + rewritten.replace_range(digits.clone(), &padded(proxy, digits.len())?); + return Ok((rewritten, real)); + } + let encoded = strings.iter().filter_map(|string| { + let digits = string.decoded.strip_prefix("0x")?; + let modulus = BigUint::parse_bytes(digits.as_bytes(), 16)?; + wide(&modulus).then_some((string, digits.len(), 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); + let what = format!("{SEED_LENGTH}-byte modulus in the iframe"); + let (string, width, real) = candidates::exactly_one(encoded, &what)?; + let replacement = + deobfuscate::encode_string(&format!("0x{}", padded(proxy, width)?), string.key); ensure!( - proxy_digits.len() <= width, - "the proxy modulus needs {} hex digits, wider than the session's {width}", - proxy_digits.len() + replacement.len() == string.encoded.len() && html.matches(&string.encoded).count() == 1, + "the encoded modulus cannot be replaced in place" ); - let mut rewritten = html.to_owned(); - rewritten.replace_range(digits, &format!("{proxy_digits:0>width$}")); - Ok((rewritten, real)) + Ok((html.replacen(&string.encoded, &replacement, 1), real)) +} + +/// Formats `proxy` as hexadecimal, padded with zeros to `width`. +fn padded(proxy: &BigUint, width: usize) -> Result { + let digits = proxy.to_str_radix(16); + ensure!( + digits.len() <= width, + "the proxy modulus needs {} hex digits, wider than the session's {width}", + digits.len() + ); + Ok(format!("{digits:0>width$}")) } /// Generates a random prime half the seed's width, with its top bit set. @@ -241,12 +273,31 @@ mod tests { let [proxy, real, _] = keys(); for quote in ['"', '`'] { let html = page(quote, &real.modulus); - let (rewritten, found) = swap_modulus(&html, &proxy.modulus).unwrap(); + let (rewritten, found) = swap_modulus(&html, &[], &proxy.modulus).unwrap(); assert_eq!(found, real.modulus); assert_eq!(rewritten, page(quote, &proxy.modulus)); } } + /// Find the modulus inside a decoder call when the build encodes strings. + #[test] + fn swap_reencodes_an_encoded_modulus() { + let [proxy, real, _] = keys(); + let key = 59141; + let text = |modulus: &BigUint| format!("0x00{modulus:x}"); + let encoded = deobfuscate::encode_string(&text(&real.modulus), key); + let html = format!(""); + let strings = [Encoded { + encoded: encoded.clone(), + key, + decoded: text(&real.modulus), + }]; + let (rewritten, found) = swap_modulus(&html, &strings, &proxy.modulus).unwrap(); + assert_eq!(found, real.modulus); + let swapped = deobfuscate::encode_string(&text(&proxy.modulus), key); + assert_eq!(rewritten, html.replace(&encoded, &swapped)); + } + #[test] fn swap_fails_closed() { let [proxy, real, _] = keys(); @@ -266,7 +317,7 @@ mod tests { ), ]; for (html, case) in cases { - assert!(swap_modulus(&html, &proxy.modulus).is_err(), "{case}"); + assert!(swap_modulus(&html, &[], &proxy.modulus).is_err(), "{case}"); } } } diff --git a/src/capture/sessions.rs b/src/capture/sessions.rs index 8805f1d..b31438c 100644 --- a/src/capture/sessions.rs +++ b/src/capture/sessions.rs @@ -16,12 +16,14 @@ use anyhow::{Context, Result}; use num_bigint::BigUint; use serde::{Serialize, Serializer}; use serde_json::Value; +use swc_core::ecma::ast::Script; 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::deobfuscate::Encoded; use crate::js::ast; use crate::script::Source; use crate::{challenge, deep_stack}; @@ -344,9 +346,11 @@ fn extract_codec(original: &str) -> Result { 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 { - let parsed = ast::parse_javascript("iframe.js", javascript)?; - program::base64_alphabet(&parsed.script) +/// Searches literals and inline decoded `strings` for a custom base64 alphabet using the solver's +/// alphabet rule. Searches the entire raw script, including outside the immediately invoked +/// function. Background extraction validates the result before saving session answers. +pub(super) fn scan_alphabet(script: &Script, strings: &[Encoded]) -> Result { + let mut candidates = ast::string_literals(script); + candidates.extend(strings.iter().map(|string| string.decoded.clone())); + program::base64_alphabet(candidates) } diff --git a/src/capture/traffic.rs b/src/capture/traffic.rs index d721103..171cffe 100644 --- a/src/capture/traffic.rs +++ b/src/capture/traffic.rs @@ -6,7 +6,7 @@ use std::fs; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use super::sessions; use crate::{http, performance_clock}; @@ -14,14 +14,15 @@ use crate::{http, performance_clock}; /// The directory beside `traffic.json` holding kept response bodies. const BODIES: &str = "bodies"; -#[derive(Default, Serialize)] +#[derive(Default, Deserialize, Serialize)] pub(super) struct Traffic { connections: Vec, - requests: Vec, + /// The requests, in the order they arrived. + pub(super) requests: Vec, } /// One intercepted connection, as the browser opened it. -#[derive(Serialize)] +#[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub(super) struct Connection { pub(super) host: String, @@ -36,19 +37,19 @@ pub(super) struct Connection { /// 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)] +#[derive(Deserialize, Serialize)] #[serde(rename_all = "camelCase")] -struct Request { +pub(super) struct Request { /// Index of this request's connection in `connections`. connection: usize, - method: String, - url: String, + pub(super) method: String, + pub(super) url: String, version: String, - headers: Vec<(String, String)>, + pub(super) headers: Vec<(String, String)>, /// Time received, in milliseconds since the Unix epoch. - received_ms: i64, + pub(super) received_ms: i64, /// Time the response was handed to the browser. - answered_ms: Option, + pub(super) answered_ms: Option, /// The file holding the decoded response body, relative to `traffic.json`, if kept. #[serde(skip_serializing_if = "Option::is_none")] body_file: Option, @@ -114,6 +115,30 @@ impl Traffic { } } +impl Request { + /// Creates a request received at the current time on connection 0. + #[cfg(test)] + pub(super) fn received(method: &str, url: &str, headers: Vec<(String, String)>) -> Self { + Self { + connection: 0, + method: method.to_owned(), + url: url.to_owned(), + version: "HTTP/2.0".to_owned(), + headers, + received_ms: performance_clock::epoch_ms(), + answered_ms: None, + body_file: None, + body: Vec::new(), + } + } + + /// Returns the value of header `name`. The name must be lowercase. + pub(super) fn header(&self, name: &str) -> Option<&str> { + let mut headers = self.headers.iter(); + headers.find_map(|(header, value)| (header == name).then_some(value.as_str())) + } +} + #[cfg(test)] mod tests { use super::*; @@ -133,6 +158,8 @@ mod tests { 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"); + let read: Traffic = serde_json::from_value(log).unwrap(); + assert_eq!(read.requests[script].url, "https://example.com/v1"); fs::remove_dir_all(dir).unwrap(); } } diff --git a/src/challenge/payload.rs b/src/challenge/payload.rs index bd36881..c92175e 100644 --- a/src/challenge/payload.rs +++ b/src/challenge/payload.rs @@ -84,6 +84,28 @@ enum Shape { } impl Field { + /// Returns the option reported by this field, whether read directly or through a namespace + /// getter. + #[must_use] + pub(crate) fn option<'a>(&'a self, script: &'a ScriptState) -> Option<&'a str> { + expression::option_key(&self.expression).or_else(|| match self.global()? { + (name, Shape::Called) => script.getters.get(name).map(String::as_str), + _ => None, + }) + } + + /// Returns the two options subtracted by this field, if it reports a time difference. + #[must_use] + pub(crate) fn difference(&self) -> Option { + match &self.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, + } + } + /// The namespace property this field reads, if any. fn global(&self) -> Option<(&str, Shape)> { fn global(expression: &Expr) -> Option<&str> { @@ -104,16 +126,7 @@ impl Field { /// Finds option pairs whose time difference appears in the payload. #[must_use] pub(crate) fn differences(fields: &[Field]) -> Vec { - 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() + fields.iter().filter_map(Field::difference).collect() } /// Evaluates fields against session options, omitting `undefined` values as `JSON.stringify` diff --git a/src/challenge/program.rs b/src/challenge/program.rs index 430e8c2..06d6b0b 100644 --- a/src/challenge/program.rs +++ b/src/challenge/program.rs @@ -9,8 +9,8 @@ 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, + ArrowExpr, AssignExpr, AssignTarget, BindingIdent, BlockStmt, CallExpr, Callee, ClassDecl, + Expr, FnDecl, Function, IfStmt, ObjectLit, Script, SimpleAssignTarget, Stmt, VarDeclarator, }; use swc_core::ecma::visit::{Visit, VisitWith}; use url::Url; @@ -227,8 +227,8 @@ struct Root { impl Root { fn read(root: &BlockStmt, definition: &Expr, parsed: &ParsedScript) -> Result { Ok(Self { - key_transform: key_transform(root, definition)?, - alphabet: base64_alphabet(root)?, + key_transform: key_transform(&parsed.script, definition)?, + alphabet: base64_alphabet(ast::string_literals(root))?, modulus: rsa_modulus(root)?, bootstrap: bootstrap(root, parsed), }) @@ -263,26 +263,44 @@ impl Visit for EncoderRoot<'_> { } } -/// 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 { +/// Finds the encoder callee created by the VM at runtime. It is the only callee without a binding +/// in the script; any remaining deobfuscation helpers have bindings. +fn key_transform(script: &Script, definition: &Expr) -> Result { 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 + let mut bound = Bound::default(); + script.visit_with(&mut bound); + let unbound = calls .0 - .iter() - .filter(|name| *name != "Number" && !declared(name)); - candidates::exactly_one(undeclared, "VM-defined key transform").cloned() + .into_iter() + .filter(|name| name != "Number" && !bound.0.contains(name)); + candidates::exactly_one(unbound, "VM-defined key transform") } -/// 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) -> Result { - let alphabets = ast::string_literals(node).into_iter().filter(|candidate| { +/// Names declared or assigned anywhere in the script. +#[derive(Default)] +struct Bound(BTreeSet); + +impl Visit for Bound { + fn visit_binding_ident(&mut self, identifier: &BindingIdent) { + self.0.insert(identifier.sym.to_string()); + } + + fn visit_fn_decl(&mut self, declaration: &FnDecl) { + self.0.insert(declaration.ident.sym.to_string()); + declaration.visit_children_with(self); + } + + fn visit_class_decl(&mut self, declaration: &ClassDecl) { + self.0.insert(declaration.ident.sym.to_string()); + declaration.visit_children_with(self); + } +} + +/// Finds the custom base64 alphabet in `candidates`: a string with 64 distinct ASCII characters and +/// optional trailing padding. +pub(crate) fn base64_alphabet(candidates: impl IntoIterator) -> Result { + let alphabets = candidates.into_iter().filter(|candidate| { if !candidate.is_ascii() || !ALPHABET_LENGTH.contains(&candidate.len()) { return false; } @@ -374,23 +392,34 @@ impl Visit for Definition<'_> { 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(_)) + && let Some(function) = yielded_function(&assignment.right) { - self.found = Some(value.clone()); + self.found = Some(function.clone()); } assignment.visit_children_with(self); } + + fn visit_var_declarator(&mut self, declarator: &VarDeclarator) { + if let Some(target) = declarator.name.as_ident() + && target.id.sym == *self.name + && let Some(function) = declarator.init.as_deref().and_then(yielded_function) + { + self.found = Some(function.clone()); + } + declarator.visit_children_with(self); + } +} + +/// Finds the function produced by `value`, including through sequence expressions. Some sessions +/// reset the seed just before returning the encoder function. +fn yielded_function(value: &Expr) -> Option<&Expr> { + let mut value = value.unwrap_parens(); + while let Expr::Seq(sequence) = value { + value = sequence.exprs.last()?.unwrap_parens(); + } + matches!(value, Expr::Fn(_) | Expr::Arrow(_)).then_some(value) } /// The names called directly, as `name(...)`. diff --git a/src/challenge/reduced_timing.rs b/src/challenge/reduced_timing.rs index 3e33748..4941efe 100644 --- a/src/challenge/reduced_timing.rs +++ b/src/challenge/reduced_timing.rs @@ -1,5 +1,6 @@ //! Recovers the format the iframe uses to summarize resource timings, then converts this -//! client's fetch measurements to that format. +//! client's fetch measurements to that format. Depending on the build, entries contain rounded-down +//! phase durations or the original timestamps. use swc_core::ecma::ast::{AssignTarget, BinaryOp, BlockStmt, Expr, SimpleAssignTarget}; @@ -11,13 +12,30 @@ use crate::resource_timing::{LoadTiming, Phases, ResourceMeasurement}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Measure { Name, - /// `responseEnd - responseStart`. + /// `Math.floor(responseEnd - responseStart)`. Response, - /// `responseStart - requestStart`. + /// `Math.floor(responseStart - requestStart)`. Request, + /// `Math.floor(duration)`. Duration, Transfer, Body, + /// Original timestamps: `startTime`, `requestStart`, `responseStart`, `responseEnd`, and + /// `duration`. + Start, + RequestStart, + ResponseStart, + ResponseEnd, + ExactDuration, +} + +/// A resource load with its name, start time, and measured phases. The start time is in +/// milliseconds from the document's time origin. The response ends when the load finishes. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(crate) struct Entry<'a> { + pub name: &'a str, + pub start: f64, + pub measured: ResourceMeasurement, } /// Maps collected resource timings to the six fields sent under the collection's option name. @@ -30,31 +48,48 @@ pub struct ResourceTiming { } impl ResourceTiming { - /// Reduces a measured fetch to the session's resource timing format. + /// Converts a load to the resource timing format used by this session. #[must_use] - pub(crate) fn reduce(&self, url: &str, measured: &ResourceMeasurement) -> JsValue { - let mut entry = JsObject::new(); + pub(crate) fn reduce(&self, entry: &Entry<'_>) -> JsValue { + let measured = &entry.measured; + // Restricted entries report a response start of zero; see + // `ResourceMeasurement::restricted`. + let response_end = entry.start + measured.duration; + let response_start = response_end - measured.response; + let request_start = response_start - measured.request; + let mut reduced = JsObject::new(); for (name, measure) in &self.fields { let value = match measure { - Measure::Name => json!(url), + Measure::Name => json!(entry.name), 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), + Measure::Start => json!(entry.start), + Measure::RequestStart => json!(request_start), + Measure::ResponseStart => json!(response_start), + Measure::ResponseEnd => json!(response_end), + Measure::ExactDuration => json!(measured.duration), }; - entry.insert(name.clone(), value); + reduced.insert(name.clone(), value); } - JsValue::Object(entry) + JsValue::Object(reduced) } - /// Reduces `load` using its measured phases. + /// Converts measured phases from `load` to the session format. Times are relative to + /// `origin_ms`, the document navigation time in milliseconds since the Unix epoch. #[must_use] - pub(crate) fn entry(&self, load: &LoadTiming) -> JsValue { - self.reduce(&load.url, &load.measurement()) + pub(crate) fn entry(&self, load: &LoadTiming, origin_ms: i64) -> JsValue { + self.reduce(&Entry { + name: &load.url, + start: (load.started_ms - origin_ms) as f64, + measured: load.measurement(), + }) } - /// Splits the session's total document load time into the navigation's `phases`. + /// Splits the total document load time into navigation `phases`. Navigation starts at the + /// document's time origin. #[must_use] pub(crate) fn navigation( &self, @@ -63,10 +98,11 @@ impl ResourceTiming { bytes: u64, phases: Phases, ) -> JsValue { - self.reduce( - url, - &ResourceMeasurement::estimated(duration, bytes, phases), - ) + self.reduce(&Entry { + name: url, + start: 0.0, + measured: ResourceMeasurement::estimated(duration, bytes, phases), + }) } } @@ -90,7 +126,7 @@ pub(super) fn reduction(body: &BlockStmt) -> Option> { } /// Recognizes a reduced entry when it has enough fields, includes the resource name, and uses -/// only the name or `measured` locals. +/// only properties of the entry itself or locals listed in `measured`. fn reduced_fields( fields: &[ObjectField<'_>], measured: &[(&str, Measure)], @@ -98,7 +134,17 @@ fn reduced_fields( 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::Member(member) => match ast::member_str(&member.prop)? { + "name" => Measure::Name, + "startTime" => Measure::Start, + "requestStart" => Measure::RequestStart, + "responseStart" => Measure::ResponseStart, + "responseEnd" => Measure::ResponseEnd, + "duration" => Measure::ExactDuration, + "transferSize" => Measure::Transfer, + "encodedBodySize" => Measure::Body, + _ => return None, + }, Expr::Ident(ident) => { let (_, measure) = measured.iter().rfind(|(local, _)| *local == &*ident.sym)?; *measure @@ -174,4 +220,57 @@ mod tests { json!({"n": "u", "r": 5.0, "q": 9.0, "d": 137.0, "t": 301, "b": 1}) ); } + + /// Builds from 2026-10-27 onward copy original timestamps rather than rounding down phase + /// durations. + #[test] + fn summaries_may_copy_the_entrys_timestamps() { + let parsed = ast::parse_javascript( + "t.js", + "function f(e) { var r; r = { a: e.name, b: e.startTime, c: e.requestStart, \ + d: e.responseStart, g: e.responseEnd, h: e.duration, i: e.transferSize, \ + j: e.encodedBodySize }; list.push(r); }", + ) + .unwrap(); + let function = parsed.script.body[0] + .as_decl() + .unwrap() + .as_fn_decl() + .unwrap(); + let fields = reduction(function.function.body.as_ref().unwrap()).unwrap(); + let measures: Vec = fields.iter().map(|(_, measure)| *measure).collect(); + assert_eq!( + measures, + [ + Measure::Name, + Measure::Start, + Measure::RequestStart, + Measure::ResponseStart, + Measure::ResponseEnd, + Measure::ExactDuration, + Measure::Transfer, + Measure::Body, + ] + ); + let timing = ResourceTiming { + option: "t".into(), + fields, + }; + let entry = Entry { + name: "u", + start: 10.0, + measured: ResourceMeasurement { + duration: 100.0, + request: 60.0, + response: 5.0, + transfer_size: 1300, + body_size: 1000, + }, + }; + assert_eq!( + timing.reduce(&entry), + json!({"a": "u", "b": 10.0, "c": 45.0, "d": 105.0, "g": 110.0, "h": 100.0, + "i": 1300, "j": 1000}) + ); + } } diff --git a/src/challenge/state.rs b/src/challenge/state.rs index 045c389..90df877 100644 --- a/src/challenge/state.rs +++ b/src/challenge/state.rs @@ -1,24 +1,26 @@ //! 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`]). +//! tally ([`super::tally`]), the sender's additions and POST log, and the resource timing +//! format ([`super::reduced_timing`]). use std::collections::BTreeMap; -use anyhow::{Result, bail, ensure}; +use anyhow::{Context, 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, + ArrowExpr, AssignExpr, AssignTarget, BinaryOp, CallExpr, Expr, Function, IfStmt, ObjectLit, + SimpleAssignTarget, Stmt, VarDeclarator, }; use swc_core::ecma::visit::{Visit, VisitWith}; use crate::candidates; +use crate::challenge::payload::Field; 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}; +use crate::js::{JsObject, JsValue, Options, Payload, json}; +use crate::resource_timing::LoadTiming; /// Script state reported in the first payload. #[derive(Debug, Default)] @@ -36,6 +38,73 @@ pub struct ScriptState { pub timing: Option, /// Functions on the script's namespace, mapped to the option each returns. pub getters: BTreeMap, + pub post_log: Option, +} + +/// Log of challenge POSTs. Each payload includes the log so far. The sender then adds an entry for +/// the current POST and records its response time when the response arrives. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PostLog { + /// The option holding the log. + pub option: String, + /// Option containing the POST counter recorded in each entry. + pub counter: String, + /// Entry fields in insertion order, excluding the response time added later. + pub fields: Vec<(String, Logged)>, + /// The field holding the response time. + pub answered: String, +} + +/// Value recorded by a field in a POST log entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Logged { + Url, + Count, + /// When the POST was sent. + Sent, +} + +impl PostLog { + /// Initializes an empty log, matching the iframe before its first POST. + pub(crate) fn start(&self, options: &mut Options) { + options.insert(self.option.clone(), json!([])); + options.insert(self.counter.clone(), json!(0)); + } + + /// Appends `post` to the log in `options`. Times are relative to `origin_ms`, the document + /// navigation time in milliseconds since the Unix epoch. + pub(crate) fn record( + &self, + options: &mut Options, + post: &LoadTiming, + origin_ms: i64, + ) -> Result<()> { + let count = options + .get(&self.counter) + .and_then(JsValue::as_i64) + .unwrap_or(0) + + 1; + options.insert(self.counter.clone(), json!(count)); + let mut entry = JsObject::new(); + for (field, logged) in &self.fields { + let value = match logged { + Logged::Url => json!(post.url), + Logged::Count => json!(count), + Logged::Sent => json!((post.started_ms - origin_ms) as f64), + }; + entry.insert(field.clone(), value); + } + entry.insert( + self.answered.clone(), + json!(post.ended_ms() - origin_ms as f64), + ); + options + .get_mut(&self.option) + .and_then(JsValue::as_array_mut) + .context("the session keeps no POST log")? + .push(JsValue::Object(entry)); + Ok(()) + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -102,6 +171,7 @@ impl ScriptState { script.visit_with(&mut scopes); let mut sender = Sender::default(); script.visit_with(&mut sender); + let post_log = sender.post_log()?; 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 @@ -139,6 +209,7 @@ impl ScriptState { forwarded: forwarded.into_iter().map(|(_, key)| key).collect(), timing, getters: distinct_getters(sender.getters)?, + post_log, }) } @@ -158,6 +229,22 @@ impl ScriptState { .any(|mark| mark.option == option && mark.in_builder) } + /// Identifies the interval measured by `difference`, using `merged` as the marked option. + /// Returns no interval if the script never marks the later timestamp. + fn span(&self, difference: &Difference, merged: Option<&str>) -> Option { + let Difference { later, earlier } = difference; + if !self.marks.iter().any(|mark| &mark.option == later) { + return None; + } + Some(if self.builds_payload(later) { + Span::Collect + } else if Some(earlier.as_str()) == merged { + Span::Handoff + } else { + Span::Initialise + }) + } + /// 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. @@ -173,27 +260,72 @@ impl ScriptState { 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) { + for difference in differences { + let Some(span) = self.span(difference, merged) else { 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, duration) = match span { + Span::Collect => (merged_at + intervals.handoff + 1, intervals.collect), + Span::Handoff => (merged_at + 1, intervals.handoff), + Span::Initialise => (merged_at + 1, intervals.initialise), }; - let start = *clock.entry(earlier).or_insert(start); - clock.entry(later).or_insert(start + duration); + let start = *clock.entry(&difference.earlier).or_insert(start); + clock.entry(&difference.later).or_insert(start + duration); } clock .into_iter() .map(|(option, when)| (option.to_owned(), JsValue::from(when))) .collect() } + + /// Recovers intervals from a captured first `payload` using its template `fields`. This + /// reverses [`Self::timestamps`]. Uses the first difference that measures each interval; `send` + /// is the sender's elapsed time. + pub fn intervals( + &self, + fields: &[Field], + merged: Option<&str>, + payload: &Payload, + ) -> Result { + let (mut initialise, mut handoff, mut collect) = (None, None, None); + for field in fields { + let span = field + .difference() + .and_then(|difference| self.span(&difference, merged)); + let slot = match span { + Some(Span::Initialise) => &mut initialise, + Some(Span::Handoff) => &mut handoff, + Some(Span::Collect) => &mut collect, + None => continue, + }; + if let Some(value) = payload.get(&field.name).and_then(JsValue::as_i64) { + slot.get_or_insert(value); + } + } + let send = self + .elapsed + .as_ref() + .and_then(|elapsed| payload.get(&elapsed.key)?.as_i64()); + let reported = |interval: Option, name: &str| { + interval.with_context(|| format!("the payload reports no {name} interval")) + }; + Ok(Intervals { + initialise: reported(initialise, "initialise")?, + handoff: reported(handoff, "handoff")?, + collect: reported(collect, "collect")?, + send: reported(send, "send")?, + }) + } +} + +/// Interval measured by a timestamp difference in the first payload. +#[derive(Clone, Copy)] +enum Span { + Initialise, + Handoff, + Collect, } /// Groups timestamps by their innermost function and finds the function containing the payload @@ -269,6 +401,9 @@ struct Sender { elapsed: Vec<(usize, Elapsed)>, copies: Vec<(usize, String)>, getters: Vec, + pushes: Vec, + entries: Vec, + stamps: Vec, } /// A namespace getter named `function` that returns the option `option`. @@ -277,6 +412,18 @@ struct Getter { option: String, } +/// Matches `_cf_chl_opt..push()`. +struct Push { + log: String, + local: String, +} + +/// Matches `. = ()`. +struct Stamp { + local: String, + key: String, +} + impl Sender { fn within>(&mut self, node: &N) { self.entered += 1; @@ -284,6 +431,71 @@ impl Sender { node.visit_children_with(self); self.scopes.pop(); } + + /// Finds the log that receives an entry whose response time is assigned later. + fn post_log(&self) -> Result> { + let logs = self.pushes.iter().filter_map(|push| { + let entry = self + .entries + .iter() + .find(|entry| entry.local == push.local)?; + let answered = self.stamps.iter().find(|stamp| { + stamp.local == push.local + && !entry.fields.iter().any(|(field, _)| *field == stamp.key) + })?; + Some(PostLog { + option: push.log.clone(), + counter: entry.counter.clone(), + fields: entry.fields.clone(), + answered: answered.key.clone(), + }) + }); + candidates::at_most_one_distinct(logs, "POST log") + } +} + +/// Finds a local initialized with a POST log entry: `{ url: new URL(...).href, count: +/// _cf_chl_opt., sent: clock() }`. +struct LogEntry { + local: String, + fields: Vec<(String, Logged)>, + counter: String, +} + +impl LogEntry { + fn read(local: &str, value: &Expr) -> Option { + let Expr::Object(object) = value.unwrap_parens() else { + return None; + }; + let mut fields = Vec::new(); + let mut counter = None; + for property in ast::key_values(object) { + let value = property.value.unwrap_parens(); + let logged = if let Some(option) = expression::option_key(value) { + counter = Some(option.to_owned()); + Logged::Count + } else if value.as_call().is_some_and(|call| call.args.is_empty()) { + Logged::Sent + } else if let Expr::Member(member) = value + && ast::member_str(&member.prop) == Some("href") + && member.obj.unwrap_parens().is_new() + { + Logged::Url + } else { + return None; + }; + fields.push((ast::key_str(&property.key)?.to_owned(), logged)); + } + let complete = fields.len() == 3 + && [Logged::Url, Logged::Count, Logged::Sent] + .iter() + .all(|logged| fields.iter().any(|(_, field)| field == logged)); + complete.then_some(Self { + local: local.to_owned(), + fields, + counter: counter?, + }) + } } impl Visit for Sender { @@ -295,8 +507,39 @@ impl Visit for Sender { self.within(arrow); } + fn visit_var_declarator(&mut self, declarator: &VarDeclarator) { + if let Some(local) = declarator.name.as_ident() + && let Some(init) = &declarator.init + && let Some(entry) = LogEntry::read(&local.sym, init) + { + self.entries.push(entry); + } + declarator.visit_children_with(self); + } + + fn visit_call_expr(&mut self, call: &CallExpr) { + // `_cf_chl_opt..push()` + if let Some(callee) = call.callee.as_expr().and_then(|callee| callee.as_member()) + && ast::member_str(&callee.prop) == Some("push") + && let Some(option) = expression::option_key(&callee.obj) + && let [entry] = &call.args[..] + && let Some(local) = entry.expr.as_ident() + { + self.pushes.push(Push { + log: option.to_owned(), + local: local.sym.to_string(), + }); + } + call.visit_children_with(self); + } + fn visit_assign_expr(&mut self, assignment: &AssignExpr) { let scope = self.scopes.last().copied().unwrap_or_default(); + if let AssignTarget::Simple(SimpleAssignTarget::Ident(local)) = &assignment.left + && let Some(entry) = LogEntry::read(&local.sym, &assignment.right) + { + self.entries.push(entry); + } if let AssignTarget::Simple(SimpleAssignTarget::Member(target)) = &assignment.left && let Some(key) = ast::ident_property(target) { @@ -329,6 +572,16 @@ impl Visit for Sender { right if expression::option_key(right) == Some(key) => { self.copies.push((scope, key.to_owned())); } + // `entry. = clock()` + Expr::Call(call) + if call.args.is_empty() + && let Some(local) = target.obj.as_ident() => + { + self.stamps.push(Stamp { + local: local.sym.to_string(), + key: key.to_owned(), + }); + } _ => {} } } @@ -352,6 +605,8 @@ fn distinct_getters(getters: Vec) -> Result> { #[cfg(test)] mod tests { use super::*; + use crate::challenge::payload; + use crate::js::Window; #[test] fn rejects_senders_that_disagree_about_the_elapsed_field() { @@ -394,4 +649,104 @@ mod tests { let at = script.timestamps(&differences, Some("merged"), 0, intervals); assert_eq!(JsValue::from(at).to_string(), r#"{"merged":0,"a":1,"b":8}"#); } + + /// Builds from 2026-10-27 onward log each POST and include the log in every payload. + #[test] + fn recovers_the_senders_post_log() { + let source = r#" + function send(url, payload, attempt) { + var entry; + payload.k = Date.now() - w._cf_chl_opt.m; + payload.log = w._cf_chl_opt.log; + if (attempt === 0) w._cf_chl_opt.n++; + entry = { u: new URL(url, w.location.href).href, c: w._cf_chl_opt.n, s: clock() }; + w._cf_chl_opt.log.push(entry); + function answered() { if (entry && entry.a === undefined) entry.a = clock(); } + }"#; + let script = ScriptState::from_javascript(source).unwrap(); + assert_eq!(script.forwarded, ["log"]); + let log = script.post_log.unwrap(); + assert_eq!( + [&log.option, &log.counter, &log.answered], + ["log", "n", "a"] + ); + let mut options = Options::new(); + log.start(&mut options); + assert_eq!(options.get("log"), Some(&json!([]))); + let post = LoadTiming { + url: "https://example.com/fo".into(), + started_ms: 1_100, + duration_ms: 250.0, + waiting_ms: 0.0, + receiving_ms: 0.0, + body_bytes: 1, + }; + log.record(&mut options, &post, 1_000).unwrap(); + assert_eq!( + options.get("log"), + Some(&json!([{"u": "https://example.com/fo", "c": 1, "s": 100.0, "a": 350.0}])) + ); + assert_eq!(options.get("n"), Some(&json!(1))); + } + + /// Building a payload from [`ScriptState::timestamps`] preserves the input intervals. + #[test] + fn reads_back_the_intervals_a_payload_reports() { + let script = ScriptState { + elapsed: Some(Elapsed { + key: "sent".into(), + mark: "zWnC9".into(), + }), + marks: [("dwQH2", false), ("WVhrW1", true), ("mrjlM3", false)] + .map(|(option, in_builder)| Mark { + option: option.into(), + in_builder, + }) + .to_vec(), + ..ScriptState::default() + }; + let pairs = [ + ("dwQH2", "pUyWp4"), + ("WVhrW1", "gyhng3"), + ("mrjlM3", "zWnC9"), + ]; + let fields: Vec = pairs + .iter() + .enumerate() + .map(|(index, (later, earlier))| { + let text = format!("e._cf_chl_opt.{later} - e._cf_chl_opt.{earlier}"); + Field { + name: format!("f{index}"), + expression: ast::parse_expression("t", &text).unwrap(), + text, + bootstrap_value: None, + } + }) + .collect(); + let intervals = &Intervals { + initialise: 15, + handoff: 17, + collect: 70, + send: 123, + }; + let differences = payload::differences(&fields); + let clock = script.timestamps(&differences, Some("zWnC9"), 0, intervals); + let mut built = payload::build(&fields, &clock, &Window::new()).unwrap(); + built.insert("sent".into(), json!(intervals.send)); + let read = script.intervals(&fields, Some("zWnC9"), &built).unwrap(); + assert_eq!( + [read.initialise, read.handoff, read.collect, read.send], + [ + intervals.initialise, + intervals.handoff, + intervals.collect, + intervals.send + ] + ); + built.shift_remove("sent"); + let error = script + .intervals(&fields, Some("zWnC9"), &built) + .unwrap_err(); + assert!(error.to_string().contains("no send interval"), "{error}"); + } } diff --git a/src/deobfuscate.rs b/src/deobfuscate.rs index f23ae68..e0323d3 100644 --- a/src/deobfuscate.rs +++ b/src/deobfuscate.rs @@ -12,9 +12,10 @@ type HashSet = rustc_hash::FxHashSet; mod analysis; mod argument_arrays; +mod arrow_blocks; mod bitwise; mod blocks; -mod constant_objects; +mod call_helpers; mod control_flow; mod copy_propagation; mod dead_branches; @@ -23,19 +24,21 @@ mod dispatch; mod encoded_strings; mod function_lengths; mod helper_objects; -mod indexed_table; mod int32_helpers; mod literals; mod loops; +mod memoized_strings; +mod merged_functions; mod pipeline; +mod register_arrays; mod removal; -mod scratch_parameters; +mod state_machines; mod statements; mod static_members; -mod string_array; #[cfg(test)] mod testing; mod unused_bindings; +pub(crate) use encoded_strings::{Encoded, encode as encode_string, inline_strings}; pub use pipeline::{Deobfuscated, Unconverged, deobfuscate}; pub(crate) use pipeline::{deobfuscate_with, read_decoded}; diff --git a/src/deobfuscate/analysis/bindings.rs b/src/deobfuscate/analysis/bindings.rs index e691e13..c41e276 100644 --- a/src/deobfuscate/analysis/bindings.rs +++ b/src/deobfuscate/analysis/bindings.rs @@ -4,16 +4,15 @@ use std::mem; use swc_core::ecma::ast::{ - AssignExpr, AssignOp, BindingIdent, ClassDecl, Expr, FnDecl, ForHead, Function, Id, Ident, + ArrowExpr, AssignExpr, AssignOp, ClassDecl, Expr, FnDecl, ForHead, Function, Id, Ident, Param, 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 +/// Tracks writes and references by resolved [`Id`]. Names are not enough /// because the obfuscator reuses them across scopes. /// /// Writes include assignments, updates, initialized declarations, `for-in` and `for-of` @@ -24,9 +23,10 @@ use crate::js::ast; pub(crate) struct Bindings { writes: HashMap>, references: HashMap, - declared: HashSet, /// Bindings that receive a copy of each binding's value. copies: HashMap>, + /// Parameters of functions and arrows. + parameters: HashSet, /// Parameters of functions that use `arguments`. mapped: HashSet, /// Whether the function being visited refers to its `arguments`. @@ -37,8 +37,6 @@ pub(crate) struct Bindings { enum Write { /// `binding = other` or `var binding = other`. Copy(Id), - /// `binding = f()`, calling `f` without arguments. - Call(Id), Other, } @@ -67,11 +65,10 @@ impl Bindings { self.references.get(id).copied().unwrap_or(0) } - /// Checks whether the program declares or assigns the binding, including parameter - /// bindings. + /// Returns whether the binding is a function or arrow parameter that can hold an argument. #[must_use] - pub(crate) fn is_bound(&self, id: &Id) -> bool { - self.declared.contains(id) || self.writes.contains_key(id) + pub(crate) fn is_parameter(&self, id: &Id) -> bool { + self.parameters.contains(id) } /// Checks whether this is a parameter of a function using `arguments`. In sloppy mode, @@ -123,36 +120,6 @@ impl Bindings { .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 { - 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 { - 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>>(&mut self, target: &N) { for id in swc_ecma_utils::find_pat_ids::<_, Id>(target) { self.writes.entry(id).or_default().push(Write::Other); @@ -167,8 +134,6 @@ impl Bindings { .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 }; @@ -238,9 +203,16 @@ impl Visit for Bindings { } } - fn visit_binding_ident(&mut self, identifier: &BindingIdent) { - self.declared.insert(identifier.to_id()); - identifier.visit_children_with(self); + fn visit_param(&mut self, parameter: &Param) { + self.parameters + .extend(swc_ecma_utils::find_pat_ids::<_, Id>(¶meter.pat)); + parameter.visit_children_with(self); + } + + fn visit_arrow_expr(&mut self, arrow: &ArrowExpr) { + self.parameters + .extend(swc_ecma_utils::find_pat_ids::<_, Id>(&arrow.params)); + arrow.visit_children_with(self); } fn visit_ident(&mut self, identifier: &Ident) { @@ -296,27 +268,16 @@ mod tests { } #[test] - fn follows_copies_sole_calls_and_mapped_parameters() { + fn follows_copies_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 f(late, middle, mixed, h, p, q) { + late = middle; middle = d; mixed = d; mixed = g(); function d() {} - function provider() {} h = {}; p = h; var q = p; - return parseInt(late); + return 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")); diff --git a/src/deobfuscate/analysis/hoisting.rs b/src/deobfuscate/analysis/hoisting.rs index 20c5ab0..4a3bec0 100644 --- a/src/deobfuscate/analysis/hoisting.rs +++ b/src/deobfuscate/analysis/hoisting.rs @@ -6,14 +6,17 @@ //! 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. +//! Block declarations work the same way, with an extra rule for sloppy mode: after a block function +//! declaration runs, the function is also accessible through the enclosing function's `var` +//! binding. Include the facts known at that declaration. +//! +//! Other scripts can call top-level functions at any time. Any switch case can call functions +//! declared in another case. For both, use only 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::ast::{BlockStmt, Decl, Function, Id, Ident, Stmt}; use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith}; use crate::deobfuscate::{HashMap, HashSet}; @@ -51,6 +54,16 @@ fn is_declaration(statement: &Stmt) -> bool { matches!(statement, Stmt::Decl(Decl::Fn(_))) } +/// Context of a statement list containing declarations. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum List { + /// A script's top level or a switch case. + #[default] + Other, + FunctionBody, + Block, +} + /// Tracks current facts, active function declarations, and facts collected at references to /// those declarations. #[derive(Default)] @@ -60,8 +73,8 @@ pub(crate) struct Hoisting { /// Intersection of facts at references to each declaration; `None` before its first /// reference. pending: HashMap>, - /// Whether the next statement list is a function body. - pub(crate) function_body: bool, + /// Context to use for the next statement list. + pub(crate) list: List, } /// The function declarations of one statement list, from @@ -72,7 +85,9 @@ struct Declarations { callers: Vec>, /// Facts at list entry, saved when the list contains declarations. entry: Option, - function_body: bool, + list: List, + /// Facts known at each block declaration, in statement order. + reached: Vec, } /// One function declaration of a statement list, at `position` in it. @@ -85,7 +100,7 @@ impl Hoisting { /// Starts visiting `statements` with the entry facts. #[must_use] fn enter(&mut self, statements: &[Stmt]) -> Declarations { - let function_body = mem::take(&mut self.function_body); + let mut list = mem::take(&mut self.list); let declarations: Vec = statements .iter() .enumerate() @@ -94,8 +109,16 @@ impl Hoisting { Some(Declaration { position, id }) }) .collect(); + // Sharing a binding with an enclosing declaration would stop tracking that binding. + if list == List::Block + && declarations + .iter() + .any(|declaration| self.pending.contains_key(&declaration.id)) + { + list = List::Other; + } let mut callers = vec![]; - if function_body { + if list != List::Other { let mut indices: HashMap> = HashMap::default(); for (index, declaration) in declarations.iter().enumerate() { indices @@ -117,7 +140,15 @@ impl Hoisting { entry: (!declarations.is_empty()).then(|| self.facts.clone()), declarations, callers, - function_body, + list, + reached: Vec::new(), + } + } + + /// Records the facts known when a block declaration runs. + fn reach(&self, declarations: &mut Declarations) { + if declarations.list == List::Block { + declarations.reached.push(self.facts.clone()); } } @@ -129,12 +160,13 @@ impl Hoisting { declarations, callers, entry, - function_body, + list, + reached, } = declarations; let Some(entry) = entry else { return vec![]; }; - if !function_body { + if list == List::Other { return declarations .into_iter() .map(|declaration| (declaration.position, entry.clone())) @@ -165,6 +197,9 @@ impl Hoisting { } } } + if let Some(reached) = reached.get(index) { + meet(&mut facts, reached); + } declared.push((declaration.position, facts.unwrap_or_else(|| entry.clone()))); } declared @@ -185,9 +220,11 @@ pub(crate) fn visit_mut_stmts( statements: &mut [Stmt], mut statement: impl FnMut(&mut V, &mut Stmt), ) { - let declarations = visitor.hoisting().enter(statements); + let mut declarations = visitor.hoisting().enter(statements); for other in statements.iter_mut() { - if !is_declaration(other) { + if is_declaration(other) { + visitor.hoisting().reach(&mut declarations); + } else { statement(visitor, other); } } @@ -199,36 +236,25 @@ pub(crate) fn visit_mut_stmts( } } -/// [`visit_mut_stmts`] for a visitor that only reads the tree. -pub(crate) fn visit_stmts( - 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(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; + visitor.hoisting().list = List::FunctionBody; body.visit_mut_with(visitor); } } +/// Marks non-function blocks for [`Hoisting::enter`] before visiting them. +pub(crate) fn visit_mut_block(visitor: &mut V, block: &mut BlockStmt) { + let list = &mut visitor.hoisting().list; + if *list == List::Other { + *list = List::Block; + } + block.visit_mut_children_with(visitor); +} + /// Records current facts at a reference to `identifier`. Direct `eval` can reference any /// declaration in scope. pub(crate) fn reference(visitor: &mut V, identifier: &Ident) { diff --git a/src/deobfuscate/arrow_blocks.rs b/src/deobfuscate/arrow_blocks.rs new file mode 100644 index 0000000..9df3c55 --- /dev/null +++ b/src/deobfuscate/arrow_blocks.rs @@ -0,0 +1,194 @@ +//! Replaces calls to arrow functions with their block bodies: +//! +//! ```js +//! function f() { +//! var a, step; +//! step = () => { a = g(); }; +//! h(); +//! { step(); } // becomes { { a = g(); } } +//! } +//! ``` +//! +//! The arrow must be synchronous, take no parameters, and have a block body with no `return`. +//! It must be assigned once in the enclosing function body and called once, without arguments, +//! in a later statement or nested block. The call can run at most once per enclosing call. +//! +//! Inlining preserves `this`, `arguments`, and local variables because arrows share them with +//! the enclosing function. The unused-bindings pass removes the arrow definition afterwards. + +use swc_core::ecma::ast::{ + ArrowExpr, BlockStmt, BlockStmtOrExpr, Constructor, Function, Id, Program, ReturnStmt, Stmt, +}; +use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith}; + +use super::HashMap; +use super::analysis::{Analysis, Bindings}; +use crate::js::ast; + +pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool { + let mut inline = Inline { + bindings: analysis.bindings(program), + changed: false, + }; + program.visit_mut_with(&mut inline); + inline.changed +} + +struct Inline<'bindings> { + bindings: &'bindings Bindings, + changed: bool, +} + +/// The binding and body of `binding = () => { ... }` without `return`. +fn block_arrow(statement: &Stmt) -> Option<(Id, &BlockStmt)> { + let (id, value) = ast::assignment(&statement.as_expr()?.expr)?; + let ArrowExpr { + params, + body, + is_async: false, + is_generator: false, + .. + } = value.as_arrow()? + else { + return None; + }; + let BlockStmtOrExpr::BlockStmt(body) = &**body else { + return None; + }; + (params.is_empty() && !returns(body)).then_some((id, body)) +} + +/// Returns the binding called by an argument-free statement such as `binding();`. +fn called(statement: &Stmt) -> Option { + let (callee, []) = ast::direct_call(&statement.as_expr()?.expr)? else { + return None; + }; + Some(callee.to_id()) +} + +fn returns(body: &BlockStmt) -> bool { + struct Returns(bool); + impl Visit for Returns { + fn visit_return_stmt(&mut self, _: &ReturnStmt) { + self.0 = true; + } + fn visit_function(&mut self, _: &Function) {} + fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} + } + let mut returns = Returns(false); + body.visit_with(&mut returns); + returns.0 +} + +/// Replaces calls in `statements` and nested blocks with the arrow bodies. +fn replace_calls(statements: &mut [Stmt], bodies: &HashMap) -> bool { + let mut changed = false; + for statement in statements { + if let Some(body) = called(statement).and_then(|id| bodies.get(&id)) { + *statement = Stmt::Block(body.clone()); + changed = true; + } else if let Stmt::Block(block) = statement { + changed |= replace_calls(&mut block.stmts, bodies); + } + } + changed +} + +/// Finds calls in `statement` and nested blocks. +fn calls(statement: &Stmt, found: &mut Vec) { + if let Some(id) = called(statement) { + found.push(id); + } else if let Stmt::Block(block) = statement { + for statement in &block.stmts { + calls(statement, found); + } + } +} + +impl Inline<'_> { + fn inline(&mut self, statements: &mut [Stmt]) { + let mut arrows: HashMap = HashMap::default(); + let mut bodies = HashMap::default(); + for statement in statements.iter() { + let mut found = vec![]; + calls(statement, &mut found); + // Only replace calls after the arrow definition in the same function. + for id in found { + if let Some(body) = arrows.remove(&id) { + bodies.insert(id, body.clone()); + } + } + if let Some((id, body)) = block_arrow(statement) + && self.bindings.is_written_once(&id) + && self.bindings.references(&id) == 1 + { + arrows.insert(id, body); + } + } + self.changed |= !bodies.is_empty() && replace_calls(statements, &bodies); + } +} + +impl VisitMut for Inline<'_> { + fn visit_mut_function(&mut self, function: &mut Function) { + function.visit_mut_children_with(self); + if let Some(body) = &mut function.body { + self.inline(&mut body.stmts); + } + } + + fn visit_mut_constructor(&mut self, constructor: &mut Constructor) { + constructor.visit_mut_children_with(self); + if let Some(body) = &mut constructor.body { + self.inline(&mut body.stmts); + } + } + + fn visit_mut_arrow_expr(&mut self, arrow: &mut ArrowExpr) { + arrow.visit_mut_children_with(self); + if let BlockStmtOrExpr::BlockStmt(body) = &mut *arrow.body { + self.inline(&mut body.stmts); + } + } +} + +#[cfg(test)] +mod tests { + use crate::deobfuscate::testing; + + #[test] + fn inlines_blocks_called_once_after_their_definition() { + let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true); + let output = transform( + "function f() { + var a, s, t; + s = () => { a = g(); }; + t = () => { var b = a; h(b, this, arguments); }; + h(); + { t(); s(); } + }", + ); + testing::assert_contains( + &output, + &[], + &["{ { var b = a; h(b, this, arguments); } { a = g(); } }"], + ); + let output = + transform("class K { constructor() { var s; s = () => { this.a = 1; }; s(); } }"); + testing::assert_contains(&output, &[], &["{ this.a = 1; }"]); + for kept in [ + "function f() { var s; s(); s = () => { a(); }; }", + "function f() { var s; s = () => { a(); }; s(); s(); }", + "function f() { var s; s = () => { a(); }; if (b) s(); }", + "function f() { var s; s = () => { a(); }; while (b) { s(); } }", + "function f() { var s; s = () => { return a(); }; s(); }", + "function f() { var s; s = (x) => { a(x); }; s(); }", + "function f() { var s; s = () => { a(); }; g(s()); }", + "function f() { var s; s = () => { a(); }; function g() { s(); } }", + "function f() { var s; s = () => { a(); }; s = h; s(); }", + ] { + let output = transform(kept); + assert!(output.contains("s()"), "{output}"); + } + } +} diff --git a/src/deobfuscate/call_helpers.rs b/src/deobfuscate/call_helpers.rs new file mode 100644 index 0000000..a7fdb26 --- /dev/null +++ b/src/deobfuscate/call_helpers.rs @@ -0,0 +1,212 @@ +//! Restores method calls that the obfuscator routes through `Function.prototype.call`: +//! +//! ```js +//! var call = function(self, method, a) { return (function() {}).call.call(method, self, a); }; +//! call(xhr, xhr.send, body); // becomes xhr.send(body) +//! call(o = xhr, o.open, "POST"); // becomes (o = xhr).open("POST"), or xhr.open("POST") +//! // when nothing else reads o +//! ``` +//! +//! The helper must be assigned once and forward parameters in order, except for swapping the +//! method and receiver. The method must be read from the receiver's local binding. This keeps +//! the same `this` value as a regular method call. + +use swc_core::common::util::take::Take; +use swc_core::ecma::ast::{ + CallExpr, Callee, Expr, ExprOrSpread, FnDecl, Function, Id, MemberExpr, Pat, Program, Stmt, + VarDeclarator, +}; +use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith}; + +use super::HashSet; +use super::analysis::{Analysis, Bindings, Globals, names}; +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 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 restore = Restore { + helpers: &helpers.0, + bindings, + globals, + changed: false, + }; + program.visit_mut_with(&mut restore); + restore.changed +} + +/// Checks for a helper of the form `function(self, method, ...rest) { return (function() +/// {}).call.call(method, self, ...rest); }` with plain parameters. +fn is_helper(function: &Function) -> bool { + let is_call = |member: &MemberExpr| ast::member_str(&member.prop) == Some("call"); + if let Some(parameters) = names::parameter_ids(&function.params) + && parameters.len() >= 2 + && !function.is_async + && !function.is_generator + && let Some([Stmt::Return(returned)]) = function.body.as_ref().map(|body| &body.stmts[..]) + && let Some(call) = returned.arg.as_deref().and_then(Expr::as_call) + && let Some(callee) = call.callee.as_expr().and_then(|callee| callee.as_member()) + && let Some(inner) = callee.obj.as_member() + && is_call(callee) + && is_call(inner) + && matches!(inner.obj.unwrap_parens(), Expr::Fn(_) | Expr::Arrow(_)) + { + let passed = call.args.iter().map(|argument| { + let id = argument + .expr + .as_ident() + .filter(|_| argument.spread.is_none())? + .to_id(); + parameters.iter().position(|parameter| *parameter == id) + }); + let swapped = [1, 0].into_iter().chain(2..parameters.len()).map(Some); + passed.eq(swapped) + } else { + false + } +} + +/// Helpers by binding. +#[derive(Default)] +struct Helpers(HashSet); + +impl Visit for Helpers { + fn visit_expr(&mut self, expression: &Expr) { + if let Some((id, Expr::Fn(function))) = ast::assignment(expression) + && is_helper(&function.function) + { + self.0.insert(id); + } + expression.visit_children_with(self); + } + + fn visit_fn_decl(&mut self, declaration: &FnDecl) { + if is_helper(&declaration.function) { + self.0.insert(declaration.ident.to_id()); + } + declaration.visit_children_with(self); + } + + fn visit_var_declarator(&mut self, declarator: &VarDeclarator) { + if let Pat::Ident(name) = &declarator.name + && let Some(Expr::Fn(function)) = declarator.init.as_deref() + && is_helper(&function.function) + { + self.0.insert(name.to_id()); + } + declarator.visit_children_with(self); + } +} + +struct Restore<'a> { + helpers: &'a HashSet, + bindings: &'a Bindings, + globals: Globals, + changed: bool, +} + +impl Restore<'_> { + /// Rewrites `helper(receiver, receiver.method, ...rest)` as a method call. + fn method_call(&self, arguments: &mut Vec) -> Option { + let [receiver, method, ..] = &mut arguments[..] else { + return None; + }; + if receiver.spread.is_some() || method.spread.is_some() { + return None; + } + let Expr::Member(member) = &mut *method.expr else { + return None; + }; + let object = member.obj.as_ident()?.to_id(); + let (target, unread) = match &*receiver.expr { + Expr::Ident(identifier) => (identifier.to_id(), false), + assignment => { + let (target, _) = ast::assignment(assignment)?; + // The method access below is the only read of the assigned local. + let unread = self.bindings.references(&target) == 1 + && target.1 != self.globals.unresolved + && !self.bindings.is_mapped_parameter(&target); + (target, unread) + } + }; + if target != object { + return None; + } + let mut receiver = receiver.expr.take(); + if unread { + receiver = receiver.expect_assign().right; + } + member.obj = receiver; + Some(Expr::Call(CallExpr { + callee: Callee::Expr(method.expr.take()), + args: arguments.split_off(2), + ..Default::default() + })) + } +} + +impl VisitMut for Restore<'_> { + fn visit_mut_expr(&mut self, expression: &mut Expr) { + expression.visit_mut_children_with(self); + if let Expr::Call(call) = expression + && let Some(callee) = call.callee.as_expr().and_then(|callee| callee.as_ident()) + && self.helpers.contains(&callee.to_id()) + && let Some(replacement) = self.method_call(&mut call.args) + { + *expression = replacement; + self.changed = true; + } + } +} + +#[cfg(test)] +mod tests { + use crate::deobfuscate::testing; + + #[test] + fn restores_method_calls_on_the_receiver_they_read() { + let output = testing::rewrite( + "var call = function(s, m, a, b) { return (function() {}).call.call(m, s, a, b); }; + function f(x) { + var o, p, q; + call(x, x.send, 1, 2); + call(o = g(), o.open, 3, 4); + call(p = g(), p.open, 5, 6); h(p); + call(q = g(), x.open, 7, 8); + call(x, x.y.z, 9, 10); + }", + super::run, + /* fix= */ true, + ); + testing::assert_contains( + &output, + &[], + &[ + "x.send(1, 2);", + "g().open(3, 4);", + "(p = g()).open(5, 6);", + "call(q = g(), x.open, 7, 8);", + "call(x, x.y.z, 9, 10);", + ], + ); + for helper in [ + "function(s, m, a) { return (function() {}).call.call(m, s); }", + "function(s, m, a) { return (function() {}).call.call(m, a, s); }", + "function(s, m) { return (function() {}).apply.call(m, s); }", + "function(s, m) { g(); return (function() {}).call.call(m, s); }", + ] { + let output = testing::rewrite( + &format!("var call = {helper}; call(x, x.send, 1);"), + super::run, + /* fix= */ true, + ); + assert!(output.contains("call(x, x.send"), "{output}"); + } + } +} diff --git a/src/deobfuscate/constant_objects.rs b/src/deobfuscate/constant_objects.rs deleted file mode 100644 index b5e5208..0000000 --- a/src/deobfuscate/constant_objects.rs +++ /dev/null @@ -1,163 +0,0 @@ -//! 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>>, - /// How many reads of each object were replaced. - replaced: HashMap, - 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> = 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) { - 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>; - - fn hoisting(&mut self) -> &mut Hoisting { - &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"], &[]); - } - } -} diff --git a/src/deobfuscate/copy_propagation.rs b/src/deobfuscate/copy_propagation.rs index f5aa673..41a3c5b 100644 --- a/src/deobfuscate/copy_propagation.rs +++ b/src/deobfuscate/copy_propagation.rs @@ -10,7 +10,9 @@ use std::rc::Rc; -use swc_core::ecma::ast::{AssignOp, Decl, Expr, Function, Id, Ident, Lit, Program, Stmt}; +use swc_core::ecma::ast::{ + AssignOp, BlockStmt, Decl, Expr, Function, Id, Ident, Lit, Program, Stmt, +}; use swc_core::ecma::visit::{VisitMut, VisitMutWith}; use super::analysis::hoisting::{self, Hoisted, Hoisting}; @@ -95,6 +97,10 @@ impl VisitMut for PropagateCopies<'_> { hoisting::visit_mut_function(self, function); } + fn visit_mut_block_stmt(&mut self, block: &mut BlockStmt) { + hoisting::visit_mut_block(self, block); + } + fn visit_mut_ident(&mut self, identifier: &mut Ident) { hoisting::reference(self, identifier); } @@ -150,14 +156,19 @@ impl PropagateCopies<'_> { } /// Excludes regex literals, which have identity and state. A copied binding must already - /// hold its sole assigned value. + /// hold its only assigned value, or be a parameter whose argument is never overwritten. 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) + let unchanged_parameter = self.bindings.is_parameter(&id) + && self.bindings.write_count(&id) == 0 + && !self.bindings.is_mapped_parameter(&id); + self.hoisting.facts.contains_key(&id) + || self.functions.contains(&id) + || unchanged_parameter } _ => false, } @@ -189,6 +200,11 @@ mod tests { // 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;"]); + // Parameters whose arguments are never overwritten. + let output = transform("function f(p, q) { var a, b; a = p; b = q; q = 1; return a + b; }"); + testing::assert_contains(&output, &["return p + b;"], &[]); + let output = transform("function f(p) { var a; a = p; return a + arguments[0]; }"); + testing::assert_contains(&output, &["return a + arguments[0];"], &[]); } #[test] diff --git a/src/deobfuscate/dispatch.rs b/src/deobfuscate/dispatch.rs index e58789a..50ca06a 100644 --- a/src/deobfuscate/dispatch.rs +++ b/src/deobfuscate/dispatch.rs @@ -1,5 +1,5 @@ -//! Inlines calls to dispatchers whose first argument selects a return value through `if`, -//! `switch`, or nested blocks. Supports applied calls and operator expressions: +//! Inlines dispatcher calls by following `if`, `switch`, and nested blocks with known numeric +//! arguments. Handles applied calls, direct calls, and operator expressions: //! //! ```js //! function b(n, f, args) { @@ -7,15 +7,23 @@ //! case 973348: return Reflect.apply(f, undefined, args); //! } //! } +//! function c(n, m, f, x) { switch (n) { case 1: switch (m) { case 2: return f(x); } } } //! function w(op, x, y) { if (op === 0) return x + y; else return x - y; } //! //! b(971996, encode, [payload]); // encode(payload) +//! c(1, 2, 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. +//! The first selector must be a literal. Applied and direct call targets must be identifiers to +//! keep `this` undefined. Direct calls must forward the remaining parameters in order, omitting +//! only numeric selectors. Operator arguments must have no side effects because they may be +//! evaluated repeatedly or in a different order. `Reflect` and `undefined` must refer to globals. +//! +//! The decoding pass only follows the first argument and leaves direct calls unchanged. This +//! preserves the dispatcher frames needed to recover click stacks. + +use std::iter; use swc_core::ecma::ast::{ BinaryOp, CallExpr, Callee, Expr, ExprOrSpread, FnDecl, Function, Id, Lit, Program, Stmt, @@ -27,7 +35,24 @@ use super::analysis::{Analysis, Globals, effects, names}; use super::{HashMap, helper_objects}; use crate::js::ast; +/// Dispatcher patterns enabled for a pass. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Reach { + /// Applied calls and operations selected by the first argument. + Decoding, + /// Also includes direct calls and selection by any numeric argument. + All, +} + pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool { + inline(program, analysis, Reach::Decoding) +} + +pub(super) fn run_all(program: &mut Program, analysis: &mut Analysis) -> bool { + inline(program, analysis, Reach::All) +} + +fn inline(program: &mut Program, analysis: &mut Analysis, reach: Reach) -> bool { let globals = analysis.globals; let bindings = analysis.bindings(program); let mut functions = Functions::default(); @@ -41,6 +66,7 @@ pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool { let mut inline = InlineDispatchers { functions: &functions.0, globals, + reach, changed: false, }; program.visit_mut_with(&mut inline); @@ -107,16 +133,15 @@ fn may_select<'a>(statements: impl IntoIterator) -> bool { false } -/// Follows a function body for one known selector value. -struct Path<'body> { - selector: &'body Id, - value: f64, +/// Follows a function body for known numeric parameter values. +struct Path { + values: HashMap, } -impl<'body> Path<'body> { +impl Path { /// 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( + fn run<'body>( &self, statements: impl IntoIterator, ) -> Option> { @@ -190,11 +215,31 @@ impl<'body> Path<'body> { fn number(&self, expression: &Expr) -> Option { ast::fold_number(expression, &|leaf| { - (leaf.as_ident()?.to_id() == *self.selector).then_some(self.value) + self.values.get(&leaf.as_ident()?.to_id()).copied() }) } } +/// Returns parameter positions for the target and arguments of a call such as `target(a, b)`. Each +/// must refer to a parameter. +fn parameter_call(expression: &Expr, params: &[Id]) -> Option> { + let call = expression.as_call()?; + let arguments = call + .args + .iter() + .map(|arg| arg.spread.is_none().then_some(&*arg.expr)); + iter::once(Some(&**call.callee.as_expr()?)) + .chain(arguments) + .map(|expression| parameter_position(expression?, params)) + .collect() +} + +/// Returns the index in `params` of the parameter named by `expression`. +fn parameter_position(expression: &Expr, params: &[Id]) -> Option { + let id = expression.as_ident()?.to_id(); + params.iter().position(|param| *param == id) +} + /// The parameter positions of `target` and `args` in `Reflect.apply(target, undefined, args)`. struct ReflectApply { target: usize, @@ -202,10 +247,6 @@ struct ReflectApply { } fn reflect_apply(expression: &Expr, params: &[Id], globals: Globals) -> Option { - 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() @@ -222,8 +263,8 @@ fn reflect_apply(expression: &Expr, params: &[Id], globals: Globals) -> Option bool) -> bool { struct InlineDispatchers<'functions> { functions: &'functions HashMap, globals: Globals, + reach: Reach, changed: bool, } @@ -252,16 +294,41 @@ impl InlineDispatchers<'_> { if args.iter().any(|arg| arg.spread.is_some()) { return None; } - let Expr::Lit(Lit::Num(selector)) = &*args.first()?.expr else { - return None; + let number = |arg: &ExprOrSpread| match &*arg.expr { + Expr::Lit(Lit::Num(number)) => Some(number.value), + _ => None, + }; + number(args.first()?)?; + let selectors = match self.reach { + Reach::Decoding => 1, + Reach::All => args.len(), }; // 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, + values: candidate + .params + .iter() + .zip(&args[..selectors]) + .filter_map(|(param, arg)| Some((param.clone(), number(arg)?))) + .collect(), }; let returned = path.run(&candidate.body)??; + if self.reach == Reach::All + && let Some(positions) = parameter_call(returned, &candidate.params) + && args.len() == candidate.params.len() + && positions.is_sorted_by(|before, after| before < after) + && (0..args.len()) + .all(|index| positions.contains(&index) || number(&args[index]).is_some()) + && let [target, passed @ ..] = &positions[..] + && args[*target].expr.is_ident() + { + return Some(Expr::Call(CallExpr { + callee: Callee::Expr(args[*target].expr.clone()), + args: passed.iter().map(|&index| args[index].clone()).collect(), + ..Default::default() + })); + } if let Some(apply) = reflect_apply(returned, &candidate.params, self.globals) && let Some(target) = args.get(apply.target) && target.expr.is_ident() @@ -353,6 +420,29 @@ mod tests { assert!(reassigned.contains("f(b("), "{reassigned}"); } + #[test] + fn calls_targets_selected_by_several_selectors_only_in_argument_order() { + let inline = |source: &str| testing::rewrite(source, super::run_all, /* fix= */ true); + let dispatchers = "function c(n, m, f, x, y) { + switch (n ^ 5) { case 1: switch (3 ^ m) { case 1: return f(x, y); } return; } + } + function d(n, f, x, y) { switch (n) { case 0: return f(y, x); } }"; + let source = format!("{dispatchers} g(c(4, 2, encode, a(), b));"); + let output = inline(&source); + assert!(output.contains("g(encode(a(), b))"), "{output}"); + let decoding = testing::rewrite(&source, super::run, /* fix= */ true); + assert!(decoding.contains("g(c(4, 2,"), "{decoding}"); + for call in [ + "c(4, 2, o.encode, a, b)", + "c(4, 2, encode, a)", + "c(4, 1, encode, a, b)", + "d(0, encode, a, b)", + ] { + let output = inline(&format!("{dispatchers} g({call});")); + assert!(output.contains(&format!("g({call})")), "{output}"); + } + } + #[test] fn inlines_selected_operations_through_switches_if_chains_and_xor_keys() { let inline = |source: &str| testing::rewrite(source, super::run, /* fix= */ true); diff --git a/src/deobfuscate/encoded_strings.rs b/src/deobfuscate/encoded_strings.rs index ba4ebf8..b298e6c 100644 --- a/src/deobfuscate/encoded_strings.rs +++ b/src/deobfuscate/encoded_strings.rs @@ -14,7 +14,7 @@ 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::ast::{BinaryOp, Expr, Id, Lit, Program, Script, Str, VarDeclarator}; use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith}; use super::analysis::Analysis; @@ -39,6 +39,72 @@ pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool { !decode.decoded.is_empty() } +/// A string decoder call with constant arguments in the original script, including the encoded +/// input, key, and decoded text. +pub(crate) struct Encoded { + pub(crate) encoded: String, + pub(crate) key: u16, + pub(crate) decoded: String, +} + +/// Finds constant decoder calls in `script` before name resolution. Identifies decoders by their +/// declared names. +pub(crate) fn inline_strings(script: &Script) -> Vec { + struct Calls<'decoders> { + decoders: &'decoders HashMap, + found: Vec, + } + impl Visit for Calls<'_> { + fn visit_expr(&mut self, expression: &Expr) { + if let Some((callee, [argument])) = ast::direct_call(expression) + && argument.spread.is_none() + && let Some(&key) = self.decoders.get(&callee.to_id()) + && let Some(encoded) = ast::static_str(&argument.expr) + && let Some(decoded) = decode(encoded, key) + && let Some(decoded) = decoded.as_str() + { + self.found.push(Encoded { + encoded: encoded.to_owned(), + key, + decoded: decoded.to_owned(), + }); + } + expression.visit_children_with(self); + } + } + let mut decoders = Decoders::default(); + script.visit_with(&mut decoders); + let mut calls = Calls { + decoders: &decoders.0, + found: Vec::new(), + }; + script.visit_with(&mut calls); + calls.found +} + +/// Encodes `text` so that [`decode`] with `key` returns it. +pub(crate) fn encode(text: &str, mut key: u16) -> String { + use base64::Engine; + + let mut bytes = Vec::new(); + let mut push = |byte: u8| { + key = key.rotate_left(8); + bytes.push(byte ^ (key >> 8) as u8); + }; + for unit in text.encode_utf16() { + match u8::try_from(unit) { + Ok(byte) if byte != 255 => push(byte), + _ => { + let [low, high] = unit.to_le_bytes(); + push(255); + push(low); + push(high); + } + } + } + STANDARD.encode(bytes) +} + /// Decodes `encoded` as the decoder holding `key` does, or `None` if it is not base64. fn decode(encoded: &str, mut key: u16) -> Option { use base64::Engine; @@ -262,6 +328,22 @@ mod tests { assert!(output.contains("decode(`ZJd1i3w=`)"), "{output}"); } + #[test] + fn finds_and_reencodes_the_strings_a_served_script_decodes() { + let source = format!("{DECODER}\nf(decode(`ZJd1i3w=`), decode('ZoZpiw=='), other(`x`));"); + let parsed = crate::js::ast::parse_javascript("x.js", &source).unwrap(); + let strings = super::inline_strings(&parsed.script); + let decoded: Vec<(&str, &str)> = strings + .iter() + .map(|string| (string.encoded.as_str(), string.decoded.as_str())) + .collect(); + assert_eq!(decoded, [("ZJd1i3w=", "apply"), ("ZoZpiw==", "call")]); + assert_eq!(super::encode("apply", strings[0].key), "ZJd1i3w="); + // Code units of 255 or greater need an escape byte followed by two bytes. + let encoded = super::encode("a€", 59141); + assert_eq!(super::decode(&encoded, 59141).unwrap().as_str(), Some("a€")); + } + #[test] fn decodes_escaped_code_units() { use base64::Engine; diff --git a/src/deobfuscate/helper_objects.rs b/src/deobfuscate/helper_objects.rs index 2126fb9..5d6c42c 100644 --- a/src/deobfuscate/helper_objects.rs +++ b/src/deobfuscate/helper_objects.rs @@ -16,16 +16,16 @@ 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, + AssignExpr, AssignOp, AssignTarget, BlockStmt, 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::hoisting::{self, HoistFacts, Hoisted, Hoisting, List}; use super::analysis::{self, Analysis, Bindings, Globals, Properties, names}; use crate::js::ast; @@ -220,10 +220,18 @@ impl VisitMut for InlineHelpers<'_> { && 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 method = assignment + .right + .as_member() + .and_then(|member| self.stable(member)) + .and_then(|(object, property)| object.functions.get(&property)) + .cloned(); + // Track object definitions, helper functions, and copies of objects and helper methods + // by binding. let helpers = &mut self.hoisting.facts; - if let Some(object) = assignment.right.as_object() { + if let Some(method) = method { + helpers.functions.insert(target, Rc::new(method)); + } else 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() { @@ -240,6 +248,21 @@ impl VisitMut for InlineHelpers<'_> { fn visit_mut_stmts(&mut self, statements: &mut Vec) { self.lists += 1; let list = self.lists; + // Function declarations are available from the start of a function body. Top-level + // declarations can be replaced by other scripts. + if self.hoisting.list == List::FunctionBody { + for statement in statements.iter() { + if let Stmt::Decl(Decl::Fn(declaration)) = statement + && self.bindings.is_written_once(&declaration.ident.to_id()) + { + let function = Rc::new(FnExpr::from(declaration.function.clone())); + self.hoisting + .facts + .functions + .insert(declaration.ident.to_id(), function); + } + } + } hoisting::visit_mut_stmts(self, statements, |inline, statement| { inline.statement(statement, list); }); @@ -249,6 +272,10 @@ impl VisitMut for InlineHelpers<'_> { hoisting::visit_mut_function(self, function); } + fn visit_mut_block_stmt(&mut self, block: &mut BlockStmt) { + hoisting::visit_mut_block(self, block); + } + fn visit_mut_ident(&mut self, identifier: &mut Ident) { hoisting::reference(self, identifier); } @@ -763,6 +790,19 @@ mod tests { ); let expected = ["((2)) + (1))", "Math.max((2))", "(3) + (4)", "read()]"]; testing::assert_contains(&output, &[], &expected); + // Function declarations inside function bodies are also stable; top-level declarations are + // not. + let output = transform( + "function f(x) { return g(x, 1); function g(a, b) { return a + b; } } \ + function h(a) { return a; } k(h(2));", + ); + testing::assert_contains(&output, &[], &["return ((x) + (1));", "k(h(2));"]); + // Copies of helper methods are stable too. + let output = transform( + "function f(h, m) { h = { shr: function (a, b) { return a >> b; } }; m = h.shr; \ + return m(8, 1); }", + ); + assert!(output.contains("(8) >> (1)"), "{output}"); } #[test] @@ -801,4 +841,27 @@ mod tests { assert!(output.contains("s.n,"), "{output}"); assert_eq!(output.matches("h.re.test").count(), 2, "{output}"); } + + /// A block function can run after the block references it or, in sloppy mode, after its + /// declaration exposes it to the enclosing function. Properties assigned before either point + /// are known. + #[test] + fn block_functions_see_properties_set_before_they_can_run() { + let output = transform( + r#"function f(h, p) { { h = {}; h.k = "v"; p = h; listen(g); function g(e) { + return e === p.k; } } }"#, + ); + assert!(output.contains(r#"e === "v""#), "{output}"); + // The function is referenced before its properties are assigned. + let output = transform( + r#"function f(h) { { listen(g); h = {}; h.k = "v"; function g(e) { return e === h.k; } } }"#, + ); + assert!(output.contains("e === h.k"), "{output}"); + // The declaration exposes the function to the enclosing scope before its properties are + // assigned. + let output = transform( + r#"function f(h) { { function g(e) { return e === h.k; } h = {}; h.k = "v"; } listen(g); }"#, + ); + assert!(output.contains("e === h.k"), "{output}"); + } } diff --git a/src/deobfuscate/indexed_table.rs b/src/deobfuscate/indexed_table.rs deleted file mode 100644 index 7f36065..0000000 --- a/src/deobfuscate/indexed_table.rs +++ /dev/null @@ -1,161 +0,0 @@ -//! 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, - /// Bindings assigned string-literal arrays, paired with their contents. - strings: HashMap>, -} - -/// 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> = 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, - 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}"); - } - } -} diff --git a/src/deobfuscate/literals.rs b/src/deobfuscate/literals.rs index be68c82..56c6204 100644 --- a/src/deobfuscate/literals.rs +++ b/src/deobfuscate/literals.rs @@ -1,15 +1,16 @@ //! Restores plain expressions from minifier forms: //! //! ```js -//! !0; void 0; (0, f)(x); // becomes true; undefined; f(x) +//! !0; void 0; (0, f)(x); (0, Date).now(); // becomes true; undefined; f(x); Date.now() //! ``` //! //! 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. +//! only when the final value is an identifier other than `eval`, preserving call behavior. Also +//! simplifies literal sequences used for property access. New `undefined` references resolve to the +//! global binding. use swc_core::ecma::ast::{ - ArrayLit, Bool, Callee, Expr, Lit, ObjectLit, Program, UnaryExpr, UnaryOp, + ArrayLit, Bool, Callee, Expr, Lit, MemberExpr, ObjectLit, Program, UnaryExpr, UnaryOp, }; use swc_core::ecma::visit::{VisitMut, VisitMutWith}; @@ -66,6 +67,19 @@ impl VisitMut for RestoreKeywords { self.changed = true; } } + + /// `(0, o).p` and `o.p` read the same property and preserve the same receiver when called. + fn visit_mut_member_expr(&mut self, member: &mut MemberExpr) { + member.visit_mut_children_with(self); + + if let Expr::Seq(sequence) = member.obj.unwrap_parens_mut() + && let [discarded @ .., _] = &sequence.exprs[..] + && discarded.iter().all(|operand| operand.is_lit()) + { + member.obj = sequence.exprs.pop().expect("the sequence is not empty"); + self.changed = true; + } + } } /// Truthiness of a side-effect-free literal, or `None` if it is not one. @@ -109,5 +123,10 @@ mod tests { // 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)("], &[]); + // A property access uses the final value of the sequence as its object. + let output = transform( + "function f(o) { return [(0, Date).now(), (1, o).p, (0, o.a).push(1), (g(), o).q]; }", + ); + testing::assert_contains(&output, &[], &["Date.now(), o.p, o.a.push(1), (g(), o).q"]); } } diff --git a/src/deobfuscate/memoized_strings.rs b/src/deobfuscate/memoized_strings.rs new file mode 100644 index 0000000..770fdd5 --- /dev/null +++ b/src/deobfuscate/memoized_strings.rs @@ -0,0 +1,224 @@ +//! Replaces cached strings and arrays of switch labels with their values: +//! +//! ```js +//! var cache, order; +//! f(cache || (cache = "apply")); // becomes f("apply") +//! f(option || cache || (cache = "apply")); // becomes f(option || "apply") +//! steps = order || (order = "1|0".split("|")); // becomes steps = "1|0".split("|") +//! ``` +//! +//! The cache must be an uninitialized `var`, not a parameter. Every read and write must use +//! this pattern with the same value, except for resets to undefined. Replacing these +//! expressions leaves no reads of the cache. +//! +//! Splitting a string creates a new array on each evaluation instead of reusing one. This is +//! safe for the dispatchers that consume these arrays because they never modify them. + +use swc_core::atoms::Wtf8Atom; +use swc_core::ecma::ast::{ + BinExpr, BinaryOp, Expr, ExprOrSpread, Id, Ident, Program, UnaryOp, VarDeclarator, +}; +use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith}; + +use super::analysis::{Analysis, Globals}; +use super::{HashMap, HashSet}; +use crate::js::ast; + +pub(super) fn run(program: &mut Program, analysis: &mut Analysis) -> bool { + let mut caches = Caches { + globals: analysis.globals, + memoized: HashMap::default(), + resets: HashMap::default(), + uninitialized: HashSet::default(), + }; + let bindings = analysis.bindings(program); + program.visit_with(&mut caches); + let constant: HashSet = caches + .memoized + .into_iter() + .filter(|(id, constants)| { + let count = constants.len(); + let resets = caches.resets.get(id).copied().unwrap_or(0); + constants.iter().all(|constant| *constant == constants[0]) + && bindings.write_count(id) == count + resets + && bindings.references(id) == count + && caches.uninitialized.contains(id) + && !bindings.is_parameter(id) + }) + .map(|(id, _)| id) + .collect(); + if constant.is_empty() { + return false; + } + program.visit_mut_with(&mut Inline(&constant)); + true +} + +/// A cached string or an array created by splitting a string. +#[derive(PartialEq)] +struct Constant { + string: Wtf8Atom, + separator: Option, +} + +impl Constant { + fn of(value: &Expr) -> Option { + if let Some(string) = ast::static_wtf8(value) { + return Some(Self { + string: string.clone(), + separator: None, + }); + } + let ( + string, + [ + ExprOrSpread { + spread: None, + expr: separator, + }, + ], + ) = ast::method_call(value, "split")? + else { + return None; + }; + Some(Self { + string: ast::static_wtf8(string)?.clone(), + separator: Some(ast::static_wtf8(separator)?.clone()), + }) + } +} + +/// Matches `[fallback ||] cache || (cache = value)`. +struct Memoized<'a> { + fallback: Option<&'a Expr>, + cache: &'a Ident, + value: &'a Expr, + constant: Constant, +} + +impl<'a> Memoized<'a> { + fn of(expression: &'a Expr) -> Option { + let either = expression + .as_bin() + .filter(|either| either.op == BinaryOp::LogicalOr)?; + let (fallback, cache) = match either.left.unwrap_parens() { + Expr::Ident(cache) => (None, cache), + Expr::Bin(BinExpr { + op: BinaryOp::LogicalOr, + left, + right, + .. + }) => (Some(&**left), right.unwrap_parens().as_ident()?), + _ => return None, + }; + let (target, value) = ast::assignment(either.right.unwrap_parens())?; + if target != cache.to_id() { + return None; + } + Some(Self { + fallback, + cache, + value, + constant: Constant::of(value)?, + }) + } +} + +struct Caches { + globals: Globals, + /// Cached value for each matched expression. + memoized: HashMap>, + /// Number of resets to undefined for each binding, including `binding = void value`. + resets: HashMap, + uninitialized: HashSet, +} + +impl Visit for Caches { + fn visit_expr(&mut self, expression: &Expr) { + if let Some((id, value)) = ast::assignment(expression) + && match value { + Expr::Unary(value) => value.op == UnaryOp::Void, + Expr::Ident(value) => self.globals.is(value, "undefined"), + _ => false, + } + { + *self.resets.entry(id).or_default() += 1; + } + if let Some(memoized) = Memoized::of(expression) { + let constants = self.memoized.entry(memoized.cache.to_id()).or_default(); + constants.push(memoized.constant); + } + expression.visit_children_with(self); + } + + fn visit_var_declarator(&mut self, declarator: &VarDeclarator) { + if declarator.init.is_none() + && let Some(name) = declarator.name.as_ident() + { + self.uninitialized.insert(name.to_id()); + } + declarator.visit_children_with(self); + } +} + +/// Replaces memoized reads of the constant caches with their values. +struct Inline<'constant>(&'constant HashSet); + +impl VisitMut for Inline<'_> { + fn visit_mut_expr(&mut self, expression: &mut Expr) { + expression.visit_mut_children_with(self); + let Some(memoized) = + Memoized::of(expression).filter(|memoized| self.0.contains(&memoized.cache.to_id())) + else { + return; + }; + *expression = match memoized.fallback { + Some(fallback) => Expr::Bin(BinExpr { + span: memoized.cache.span, + op: BinaryOp::LogicalOr, + left: Box::new(fallback.clone()), + right: Box::new(memoized.value.clone()), + }), + None => memoized.value.clone(), + }; + } +} + +#[cfg(test)] +mod tests { + use crate::deobfuscate::testing; + + #[test] + fn inlines_values_only_their_caches_hold() { + let output = testing::rewrite( + "(function(p) { + var a, b, c, d, e = 'x', o, p; + o = void 0; o = undefined; + f(a || (a = 'apply'), x || a || (a = 'apply'), o || (o = '1|0'.split('|'))); + f(b || (b = 'one'), b || (b = 'two')); + f(c || (c = 'read'), c); + f(d || (d = 'written')); + d = other; + f(e || (e = 'initialized')); + f(p || (p = 'parameter'), ((q) => q || (q = 'arrow'))()); + f(g || (g = 'global')); + })();", + super::run, + /* fix= */ true, + ); + testing::assert_contains( + &output, + &[], + &[ + "f('apply', x || 'apply', '1|0'.split('|'));", + "b || (b = 'one'), b || (b = 'two')", + "c || (c = 'read'), c", + "d || (d = 'written')", + "e || (e = 'initialized')", + "p || (p = 'parameter')", + "q || (q = 'arrow')", + "g || (g = 'global')", + ], + ); + } +} diff --git a/src/deobfuscate/merged_functions.rs b/src/deobfuscate/merged_functions.rs new file mode 100644 index 0000000..c6e1038 --- /dev/null +++ b/src/deobfuscate/merged_functions.rs @@ -0,0 +1,356 @@ +//! Splits functions that the obfuscator merged behind a selector back into separate functions: +//! +//! ```js +//! function merged(selector, a) { +//! switch (selector ^ 5) { +//! case 1: return a + 1; +//! case 2: g(a); return; +//! } +//! } +//! merged(4, x); merged(7, y); +//! // becomes +//! function merged_0(a) { return a + 1; } +//! function merged_1(a) { g(a); return; } +//! merged_0(x); merged_1(y); +//! ``` +//! +//! The function body must contain only a switch whose value depends solely on the first +//! parameter. Case labels must be constant, with no default. Each case must end in `return` or +//! `throw` and have no other jump out of the switch. +//! +//! Every reference must be a call with a literal selector that matches a case. Cases must not +//! use the selector, `arguments`, or declarations from another case. Each new function gets +//! separate bindings for the remaining parameters. Cases with no callers are removed. + +use swc_core::common::{DUMMY_SP, Mark, SyntaxContext}; +use swc_core::ecma::ast::{ + BlockStmt, CallExpr, Callee, ClassDecl, Decl, Expr, FnDecl, Function, Id, Ident, Lit, Program, + Stmt, SwitchStmt, VarDeclarator, +}; +use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith}; + +use super::analysis::{Analysis, Bindings, names}; +use super::state_machines::escapes; +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 merged = Merged { + bindings, + functions: HashMap::default(), + }; + program.visit_with(&mut merged); + let mut calls = Calls { + functions: &merged.functions, + picked: HashMap::default(), + }; + program.visit_with(&mut calls); + // Replacement function for each case selected by a call. + let mut splits: HashMap>> = HashMap::default(); + for (id, picked) in calls.picked { + let Some(picked) = picked.filter(|picked| picked.calls == bindings.references(&id)) else { + continue; + }; + let context = SyntaxContext::empty().apply_mark(Mark::new()); + let names: Vec> = (0..merged.functions[&id].labels.len()) + .map(|index| { + picked + .cases + .contains(&index) + .then(|| Ident::new(format!("{}_{index}", id.0).into(), DUMMY_SP, context)) + }) + .collect(); + splits.insert(id, names); + } + if splits.is_empty() { + return false; + } + program.visit_mut_with(&mut Unmerge { + functions: &merged.functions, + splits: &splits, + }); + true +} + +/// Maps selector values to cases in a merged function. +struct Selection { + selector: Id, + discriminant: Expr, + labels: Vec, +} + +impl Selection { + /// Returns the case selected by `selector`. + fn case(&self, selector: f64) -> Option { + let value = ast::fold_number(&self.discriminant, &|leaf| { + (leaf.as_ident()?.to_id() == self.selector).then_some(selector) + })?; + self.labels.iter().position(|&label| label == value) + } +} + +/// Finds merged function declarations. +struct Merged<'bindings> { + bindings: &'bindings Bindings, + functions: HashMap, +} + +impl Merged<'_> { + fn selection(&self, function: &Function) -> Option { + let selector = names::parameter_ids(&function.params)?.first()?.clone(); + let [Stmt::Switch(switch)] = &function.body.as_ref()?.stmts[..] else { + return None; + }; + // The discriminant is computed from the selector alone. + ast::fold_number(&switch.discriminant, &|leaf| { + (leaf.as_ident()?.to_id() == selector).then_some(0.0) + })?; + let labels = switch + .cases + .iter() + .map(|case| ast::fold_number(case.test.as_deref()?, &|_| None)) + .collect::>>()?; + let separate = !function.is_async + && !function.is_generator + && names::mentions(&*switch.discriminant, std::slice::from_ref(&selector)) + && self.bindings.references(&selector) == 1 + && !names::uses_arguments(&switch.cases) + && switch.cases.iter().all(|case| { + matches!(case.cons.last(), Some(Stmt::Return(_) | Stmt::Throw(_))) + && !escapes(&case.cons) + }) + && independent(switch); + separate.then(|| Selection { + selector, + discriminant: (*switch.discriminant).clone(), + labels, + }) + } +} + +impl Visit for Merged<'_> { + fn visit_fn_decl(&mut self, declaration: &FnDecl) { + if self.bindings.is_written_once(&declaration.ident.to_id()) + && let Some(selection) = self.selection(&declaration.function) + { + self.functions.insert(declaration.ident.to_id(), selection); + } + declaration.visit_children_with(self); + } +} + +/// Checks that no case refers to a binding declared in another case. +fn independent(switch: &SwitchStmt) -> bool { + let declared: Vec> = switch + .cases + .iter() + .map(|case| { + let mut declarations = Declarations::default(); + case.cons.visit_with(&mut declarations); + declarations.0 + }) + .collect(); + switch.cases.iter().enumerate().all(|(index, case)| { + declared + .iter() + .enumerate() + .all(|(other, ids)| other == index || !names::mentions(&case.cons, ids)) + }) +} + +#[derive(Default)] +struct Declarations(Vec); + +impl Visit for Declarations { + fn visit_var_declarator(&mut self, declarator: &VarDeclarator) { + self.0 + .extend(swc_ecma_utils::find_pat_ids::<_, Id>(&declarator.name)); + declarator.visit_children_with(self); + } + + fn visit_fn_decl(&mut self, declaration: &FnDecl) { + self.0.push(declaration.ident.to_id()); + declaration.visit_children_with(self); + } + + fn visit_class_decl(&mut self, declaration: &ClassDecl) { + self.0.push(declaration.ident.to_id()); + declaration.visit_children_with(self); + } +} + +/// Finds the cases selected by calls to a merged function. Returns `None` if any reference is not a +/// direct call with a literal selector that matches a case. +#[derive(Default)] +struct Picked { + calls: usize, + cases: HashSet, +} + +struct Calls<'functions> { + functions: &'functions HashMap, + picked: HashMap>, +} + +/// Extracts the function name and literal selector from `function(selector, ...)`. +fn selected_call(call: &CallExpr) -> Option<(Id, Option)> { + let callee = call.callee.as_expr()?.as_ident()?.to_id(); + let spreads = call.args.iter().any(|argument| argument.spread.is_some()); + let selector = match call.args.first().map(|first| &*first.expr) { + Some(Expr::Lit(Lit::Num(number))) if !spreads => Some(number.value), + _ => None, + }; + Some((callee, selector)) +} + +impl Visit for Calls<'_> { + fn visit_call_expr(&mut self, call: &CallExpr) { + if let Some((id, selector)) = selected_call(call) + && let Some(selection) = self.functions.get(&id) + { + let case = selector.and_then(|value| selection.case(value)); + let picked = self + .picked + .entry(id) + .or_insert_with(|| Some(Picked::default())); + match (picked.as_mut(), case) { + (Some(picked), Some(case)) => { + picked.calls += 1; + picked.cases.insert(case); + } + _ => *picked = None, + } + } + call.visit_children_with(self); + } +} + +/// Creates replacement functions for the cases of `declaration` listed in `names`. +fn split(declaration: FnDecl, names: &[Option]) -> Vec { + let mut function = declaration.function; + let mut body = function.body.take().expect("checked when collected"); + let Some(Stmt::Switch(switch)) = body.stmts.pop() else { + unreachable!("checked when collected"); + }; + let _selector = function.params.remove(0); + let mut functions = vec![]; + for (case, name) in switch.cases.into_iter().zip(names) { + let Some(name) = name else { continue }; + // Give each split function separate parameter bindings. + let context = SyntaxContext::empty().apply_mark(Mark::new()); + let renamed: HashMap = function + .params + .iter() + .filter_map(|parameter| parameter.pat.as_ident()) + .map(|parameter| { + let fresh = Ident::new(parameter.sym.clone(), parameter.span, context); + (parameter.to_id(), fresh) + }) + .collect(); + let mut rename = Rename(&renamed); + let mut separate = function.clone(); + separate.params.visit_mut_with(&mut rename); + let mut stmts = case.cons; + stmts.visit_mut_with(&mut rename); + separate.body = Some(BlockStmt { + stmts, + ..body.clone() + }); + functions.push(Stmt::Decl(Decl::Fn(FnDecl { + ident: name.clone(), + declare: false, + function: separate, + }))); + } + functions +} + +struct Unmerge<'a> { + functions: &'a HashMap, + splits: &'a HashMap>>, +} + +impl VisitMut for Unmerge<'_> { + fn visit_mut_stmts(&mut self, statements: &mut Vec) { + statements.visit_mut_children_with(self); + let mut replaced = Vec::with_capacity(statements.len()); + for statement in statements.drain(..) { + match statement { + Stmt::Decl(Decl::Fn(declaration)) + if self.splits.contains_key(&declaration.ident.to_id()) => + { + let names = &self.splits[&declaration.ident.to_id()]; + replaced.extend(split(declaration, names)); + } + statement => replaced.push(statement), + } + } + *statements = replaced; + } + + fn visit_mut_call_expr(&mut self, call: &mut CallExpr) { + call.visit_mut_children_with(self); + if let Some((id, Some(selector))) = selected_call(call) + && let Some(names) = self.splits.get(&id) + && let Some(case) = self.functions[&id].case(selector) + && let Some(Some(name)) = names.get(case) + { + call.callee = Callee::Expr(Box::new(Expr::Ident(name.clone()))); + call.args.remove(0); + } + } +} + +struct Rename<'a>(&'a HashMap); + +impl VisitMut for Rename<'_> { + fn visit_mut_ident(&mut self, identifier: &mut Ident) { + if let Some(fresh) = self.0.get(&identifier.to_id()) { + *identifier = fresh.clone(); + } + } +} + +#[cfg(test)] +mod tests { + use crate::deobfuscate::testing; + + #[test] + fn splits_cases_that_literal_selectors_pick() { + let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true); + let merged = "function m(s, a) { + switch (s ^ 5) { + case 1: var x = a + 1; return x; + case 2: g(a); return; + case 3: dead(); return; + } + }"; + let output = transform(&format!("{merged} h(m(4, p), m(7, q), m(4, r));")); + testing::assert_contains( + &output, + &[], + &[ + "function m_0(a) { var x = a + 1; return x; }", + "function m_1(a) { g(a); return; }", + "h(m_0(p), m_1(q), m_0(r));", + ], + ); + testing::assert_lacks(&output, &["dead", "switch"]); + for kept in [ + format!("{merged} h(m(4, p), m(9, q));"), + format!("{merged} h(m(s, p));"), + format!("{merged} h(m);"), + "function m(s, a) { switch (s) { case 1: var x = 1; return; case 2: return x; } } m(1, 2);" + .to_owned(), + "function m(s, a) { switch (s) { case 1: g(); case 2: return; } } m(1, 2);".to_owned(), + "function m(s, a) { switch (s) { case 1: return s; } } m(1, 2);".to_owned(), + "function m(s, a) { switch (s) { case 1: return arguments; } } m(1, 2);".to_owned(), + "function m(s, a) { switch (s) { case 1: return; default: return; } } m(1, 2);" + .to_owned(), + ] { + let output = transform(&kept); + assert!(output.contains("switch"), "{output}"); + } + } +} diff --git a/src/deobfuscate/pipeline.rs b/src/deobfuscate/pipeline.rs index 0b37fa7..73e297f 100644 --- a/src/deobfuscate/pipeline.rs +++ b/src/deobfuscate/pipeline.rs @@ -17,10 +17,10 @@ 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, + HashMap, argument_arrays, arrow_blocks, bitwise, blocks, call_helpers, control_flow, + copy_propagation, dead_branches, dead_properties, dispatch, encoded_strings, function_lengths, + helper_objects, int32_helpers, literals, loops, memoized_strings, merged_functions, + register_arrays, state_machines, statements, static_members, unused_bindings, }; /// Deobfuscated JavaScript with optional convergence diagnostics for the caller to report. @@ -176,18 +176,22 @@ const DECODE_STEPS: &[Step] = &[ 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("memoized strings", memoized_strings::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] = &[ + // Restore locals and method calls the obfuscator hides. + step("register arrays", register_arrays::run), + step("call helpers", call_helpers::run), + // Inline call dispatchers first. Splitting merged functions would turn them into forwarders. + step("call dispatchers", dispatch::run_all), + step("merged functions", merged_functions::run), // Inline helpers, once unused scratch declarations no longer hide their returns. UNUSED_BINDINGS, STATIC_MEMBERS, @@ -195,6 +199,8 @@ const LATER_STEPS: &[Step] = &[ STATIC_MEMBERS, SIMPLIFY, CONTROL_FLOW, + step("state machines", state_machines::run), + step("arrow blocks", arrow_blocks::run), // Remove dead helpers. HELPER_OBJECTS, UNUSED_BINDINGS, @@ -206,14 +212,12 @@ const LATER_STEPS: &[Step] = &[ 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. + // Clean up locals. 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. diff --git a/src/deobfuscate/register_arrays.rs b/src/deobfuscate/register_arrays.rs new file mode 100644 index 0000000..30d931b --- /dev/null +++ b/src/deobfuscate/register_arrays.rs @@ -0,0 +1,519 @@ +//! Replaces local array slots with separate variables when all accesses use constant indices: +//! +//! ```js +//! var r, a; +//! r = [void 0, void 0, void 0]; +//! a = r[1] = f(); g(r[0]++); r[2] = h(); // becomes +//! var r_0, a; +//! a = f(); g(r_0++); h(); +//! ``` +//! +//! The array must be local to a function and assigned once from a literal without spreads. +//! That assignment must discard its value. All other uses must access constant indices within +//! bounds, without calling or deleting slots. Writes to unread slots keep only the assigned +//! expression so its side effects still run. +//! +//! Undefined slots need no assignment if the literal runs at most once per call, in the +//! declaring function and outside loops. The replacement locals already start undefined. + +use swc_core::common::util::take::Take; +use swc_core::common::{DUMMY_SP, Mark, SyntaxContext}; +use swc_core::ecma::ast::{ + ArrayLit, ArrowExpr, AssignExpr, AssignOp, AssignTarget, BindingIdent, CallExpr, Callee, + Constructor, Expr, ExprStmt, ForStmt, Function, GetterProp, Id, Ident, MemberExpr, Pat, + Program, SeqExpr, SetterProp, SimpleAssignTarget, Stmt, TaggedTpl, UnaryExpr, UnaryOp, + VarDeclOrExpr, VarDeclarator, +}; +use swc_core::ecma::visit::{Visit, VisitMut, VisitMutWith, VisitWith}; + +use super::analysis::{Analysis, Globals, effects}; +use super::{HashMap, HashSet, removal}; +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 uses = Uses { + globals, + created: HashMap::default(), + slots: HashMap::default(), + declared: HashMap::default(), + function: 0, + functions: 0, + loops: 0, + }; + program.visit_with(&mut uses); + let mut arrays = HashMap::default(); + for (id, created) in uses.created { + let slots = uses.slots.remove(&id).unwrap_or_default(); + let [creation] = &created[..] else { + continue; + }; + if creation.function == 0 + || uses.declared.get(&id) != Some(&creation.function) + || bindings.write_count(&id) != 1 + || bindings.is_parameter(&id) + || slots.opaque + || slots.accesses != bindings.references(&id) + || slots + .read + .iter() + .chain(&slots.written) + .any(|&slot| slot >= creation.length) + { + continue; + } + // Give each array a separate context so same-named arrays stay distinct until hygiene + // renames them. + let context = SyntaxContext::empty().apply_mark(Mark::new()); + let locals: Vec> = (0..creation.length) + .map(|slot| { + let needed = slots.read.contains(&slot) || creation.defined.contains(&slot); + needed.then(|| Ident::new(format!("{}_{slot}", id.0).into(), DUMMY_SP, context)) + }) + .collect(); + arrays.insert( + id, + Array { + locals, + read: slots.read, + // Replacement locals already start undefined on each call. + assign_undefined: !creation.once, + }, + ); + } + if arrays.is_empty() { + return false; + } + program.visit_mut_with(&mut Split { + arrays: &arrays, + globals, + }); + true +} + +/// Checks whether an element is undefined with no side effects: a hole, a side-effect-free `void` +/// expression, or global `undefined`. +fn is_undefined(element: Option<&Expr>, globals: Globals) -> bool { + match element { + None => true, + // Constant arithmetic has no side effects, even when nested. + Some(Expr::Unary(unary)) => { + unary.op == UnaryOp::Void + && (ast::fold_number(&unary.arg, &|_| None).is_some() + || !effects::may_have_effects(&unary.arg, globals)) + } + Some(Expr::Ident(identifier)) => globals.is(identifier, "undefined"), + Some(_) => false, + } +} + +fn undefined() -> Expr { + Expr::Unary(UnaryExpr { + span: DUMMY_SP, + op: UnaryOp::Void, + arg: 0.0.into(), + }) +} + +/// Extracts the array and constant index from `array[slot]`. Folds indices because the simplifier +/// leaves them unchanged in optional chains. +fn slot(member: &MemberExpr) -> Option<(Id, usize)> { + let index = &member.prop.as_computed()?.expr; + let slot = ast::array_index(ast::fold_number(index, &|_| None)?)?; + Some((member.obj.as_ident()?.to_id(), slot)) +} + +struct Creation { + length: usize, + /// Slots initialized to values other than undefined. + defined: HashSet, + function: usize, + /// Whether creation occurs outside loops and at most once per call of `function`. + once: bool, +} + +#[derive(Default)] +struct Slots { + /// Number of constant-index accesses, for comparison with the total reference count. + accesses: usize, + /// Slots read, updated, or assigned with an operator other than `=`. + read: HashSet, + written: HashSet, + /// Whether a slot is called or deleted. These operations depend on the array itself. + opaque: bool, +} + +/// Collects array assignments whose values are discarded, slot accesses, and the function declaring +/// each array binding. +struct Uses { + globals: Globals, + created: HashMap>, + slots: HashMap, + declared: HashMap, + /// Current function number in traversal order; 0 denotes the script. + function: usize, + functions: usize, + loops: usize, +} + +impl Uses { + fn create(&mut self, id: Id, array: &ArrayLit) { + let mut defined = HashSet::default(); + for (slot, element) in array.elems.iter().enumerate() { + if element + .as_ref() + .is_some_and(|element| element.spread.is_some()) + { + return; + } + if !is_undefined(element.as_ref().map(|element| &*element.expr), self.globals) { + defined.insert(slot); + } + } + let creation = Creation { + length: array.elems.len(), + defined, + function: self.function, + once: self.loops == 0, + }; + self.created.entry(id).or_default().push(creation); + } + + /// Records an array assignment whose value is discarded by a statement. Sequence expressions + /// handle their other operands separately. + fn statement(&mut self, expression: &Expr) { + let last = expression + .as_seq() + .and_then(|sequence| sequence.exprs.last()); + self.discarded(last.map_or(expression, |last| &**last)); + } + + /// Records `binding = [...]`. + fn discarded(&mut self, expression: &Expr) { + if let Some((id, Expr::Array(array))) = ast::assignment(expression) { + self.create(id, array); + } + } + + fn access(&mut self, member: &MemberExpr, read: bool) { + if let Some((id, slot)) = slot(member) { + let slots = self.slots.entry(id).or_default(); + slots.accesses += 1; + if read { + slots.read.insert(slot); + } else { + slots.written.insert(slot); + } + } + } + + fn opaque(&mut self, expression: &Expr) { + if let Some(member) = expression.unwrap_parens().as_member() + && let Some((id, _)) = slot(member) + { + self.slots.entry(id).or_default().opaque = true; + } + } + + fn in_function(&mut self, visit: impl FnOnce(&mut Self)) { + self.functions += 1; + let function = std::mem::replace(&mut self.function, self.functions); + let loops = std::mem::take(&mut self.loops); + visit(self); + self.function = function; + self.loops = loops; + } + + fn in_loop(&mut self, visit: impl FnOnce(&mut Self)) { + self.loops += 1; + visit(self); + self.loops -= 1; + } +} + +impl Visit for Uses { + fn visit_expr_stmt(&mut self, statement: &ExprStmt) { + self.statement(&statement.expr); + statement.visit_children_with(self); + } + + fn visit_seq_expr(&mut self, sequence: &SeqExpr) { + if let [discarded @ .., _] = &sequence.exprs[..] { + for expression in discarded { + self.discarded(expression); + } + } + sequence.visit_children_with(self); + } + + fn visit_var_declarator(&mut self, declarator: &VarDeclarator) { + if let Some(name) = declarator.name.as_ident() { + self.declared.insert(name.to_id(), self.function); + if let Some(Expr::Array(array)) = declarator.init.as_deref() { + self.create(name.to_id(), array); + } + } + declarator.visit_children_with(self); + } + + fn visit_expr(&mut self, expression: &Expr) { + if let Expr::Member(member) = expression { + self.access(member, /* read= */ true); + } + expression.visit_children_with(self); + } + + fn visit_assign_expr(&mut self, assignment: &AssignExpr) { + if let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assignment.left { + self.access(member, assignment.op != AssignOp::Assign); + } + assignment.visit_children_with(self); + } + + fn visit_call_expr(&mut self, call: &CallExpr) { + if let Callee::Expr(callee) = &call.callee { + self.opaque(callee); + } + call.visit_children_with(self); + } + + fn visit_tagged_tpl(&mut self, template: &TaggedTpl) { + self.opaque(&template.tag); + template.visit_children_with(self); + } + + fn visit_unary_expr(&mut self, unary: &UnaryExpr) { + if unary.op == UnaryOp::Delete { + self.opaque(&unary.arg); + } + unary.visit_children_with(self); + } + + fn visit_function(&mut self, function: &Function) { + self.in_function(|uses| function.visit_children_with(uses)); + } + + fn visit_arrow_expr(&mut self, arrow: &ArrowExpr) { + self.in_function(|uses| arrow.visit_children_with(uses)); + } + + fn visit_constructor(&mut self, constructor: &Constructor) { + self.in_function(|uses| constructor.visit_children_with(uses)); + } + + fn visit_getter_prop(&mut self, getter: &GetterProp) { + self.in_function(|uses| getter.visit_children_with(uses)); + } + + fn visit_setter_prop(&mut self, setter: &SetterProp) { + self.in_function(|uses| setter.visit_children_with(uses)); + } + + /// A loop initializer runs once before the loop and discards its value. + fn visit_for_stmt(&mut self, statement: &ForStmt) { + if let Some(VarDeclOrExpr::Expr(init)) = &statement.init { + self.statement(init); + } + statement.init.visit_with(self); + self.in_loop(|uses| { + statement.test.visit_with(uses); + statement.update.visit_with(uses); + statement.body.visit_with(uses); + }); + } + + fn visit_stmt(&mut self, statement: &Stmt) { + if matches!( + statement, + Stmt::ForIn(_) | Stmt::ForOf(_) | Stmt::While(_) | Stmt::DoWhile(_) + ) { + self.in_loop(|uses| statement.visit_children_with(uses)); + } else { + statement.visit_children_with(self); + } + } +} + +struct Array { + /// Replacement local for each slot that is read or initialized with a value. + locals: Vec>, + read: HashSet, + assign_undefined: bool, +} + +struct Split<'arrays> { + arrays: &'arrays HashMap, + globals: Globals, +} + +impl Split<'_> { + /// Builds assignments to replacement locals for an array initialization. + fn initial(&self, array: &Array, literal: &mut ArrayLit) -> Vec<(Ident, Box)> { + let mut assignments = vec![]; + for (local, element) in array.locals.iter().zip(&mut literal.elems) { + let element = element.take().map(|element| element.expr); + if let Some(local) = local + && (array.assign_undefined || !is_undefined(element.as_deref(), self.globals)) + { + let value = element.unwrap_or_else(|| Box::new(undefined())); + assignments.push((local.clone(), value)); + } + } + assignments + } + + /// Replaces slot assignment targets in place. Returns a replacement expression for slot reads, + /// writes to unread slots, and array creation. + fn replacement(&self, expression: &mut Expr) -> Option { + match expression { + Expr::Member(member) => { + let (id, slot) = slot(member)?; + let local = self.arrays.get(&id)?.locals.get(slot)?.clone()?; + Some(Expr::Ident(local)) + } + Expr::Assign(assignment) => { + if let AssignTarget::Simple(SimpleAssignTarget::Member(member)) = &assignment.left { + let (id, slot) = slot(member)?; + let array = self.arrays.get(&id)?; + return match &array.locals[slot] { + Some(local) if array.read.contains(&slot) => { + assignment.left = AssignTarget::Simple(SimpleAssignTarget::Ident( + local.clone().into(), + )); + None + } + _ => Some(*assignment.right.take()), + }; + } + // The array binding is assigned only when the array is created. + let array = self.arrays.get(&assignment.left.as_ident()?.to_id())?; + let Expr::Array(literal) = &mut *assignment.right else { + return None; + }; + let mut assignments: Vec> = self + .initial(array, literal) + .into_iter() + .map(|(local, value)| { + Box::new(Expr::Assign(AssignExpr { + span: DUMMY_SP, + op: AssignOp::Assign, + left: AssignTarget::Simple(SimpleAssignTarget::Ident(local.into())), + right: value, + })) + }) + .collect(); + Some(match assignments.len() { + 0 => undefined(), + 1 => *assignments.remove(0), + _ => Expr::Seq(SeqExpr { + span: assignment.span, + exprs: assignments, + }), + }) + } + _ => None, + } + } +} + +impl VisitMut for Split<'_> { + fn visit_mut_expr(&mut self, expression: &mut Expr) { + expression.visit_mut_children_with(self); + if let Some(replacement) = self.replacement(expression) { + *expression = replacement; + } + } + + /// Removes `void 0` left by array creations that need no assignments. + fn visit_mut_stmts(&mut self, statements: &mut Vec) { + statements.visit_mut_children_with(self); + removal::remove_expr_stmts(statements, |expression| { + is_undefined(Some(expression), self.globals) + }); + } + + fn visit_mut_var_declarators(&mut self, declarators: &mut Vec) { + declarators.visit_mut_children_with(self); + let mut split = Vec::with_capacity(declarators.len()); + for mut declarator in declarators.drain(..) { + let Some(array) = declarator + .name + .as_ident() + .and_then(|name| self.arrays.get(&name.to_id())) + else { + split.push(declarator); + continue; + }; + let mut initial: HashMap> = match declarator.init.as_deref_mut() { + Some(Expr::Array(literal)) => self + .initial(array, literal) + .into_iter() + .map(|(local, value)| (local.to_id(), value)) + .collect(), + _ => HashMap::default(), + }; + split.extend(array.locals.iter().flatten().map(|local| VarDeclarator { + span: declarator.span, + name: Pat::Ident(BindingIdent::from(local.clone())), + init: initial.remove(&local.to_id()), + definite: false, + })); + } + *declarators = split; + } +} + +#[cfg(test)] +mod tests { + use crate::deobfuscate::testing; + + #[test] + fn splits_arrays_reached_only_through_constant_slots() { + let transform = |source: &str| testing::rewrite(source, super::run, /* fix= */ true); + let output = transform( + "function f(x) { + var r, a, s = [1, void 0]; + r = [void 0, void (2 ^ (3 + (4 | (5 ^ (6 + 7))))), void 0]; + a = r[1] = g(); g(r[0]++, s[0], s[1]); r[2] = h(); + return function() { return r[0]; }; + }", + ); + testing::assert_contains( + &output, + &[], + &[ + "var r_0, a, s_0 = 1, s_1;", + "a = g(); g(r_0++, s_0, s_1); h();", + "return r_0;", + ], + ); + testing::assert_lacks(&output, &["r_1", "r_2", "[", "void 0"]); + // A loop's initializer runs once. + let output = transform( + "function f() { var r, i; for (r = [void 0], i = 0; i < 2; i++) { h(r[0]); r[0] = i; } }", + ); + testing::assert_contains(&output, &[], &["h(r_0);", "r_0 = i;"]); + testing::assert_lacks(&output, &["r_0 = void 0", "["]); + // A creation in a loop resets the slots on every iteration. + let output = + transform("function f() { var r; while (g()) { r = [void 0]; h(r[0]); r[0] = 1; } }"); + testing::assert_contains(&output, &[], &["r_0 = void 0;", "h(r_0);", "r_0 = 1;"]); + for kept in [ + "function f() { var r; r = [1]; g(r); }", + "function f() { var r; r = [1]; r[0](); }", + "function f() { var r; r = [1]; delete r[0]; }", + "function f() { var r; r = [1]; g(r[1]); }", + "function f() { var r; r = [1]; g(r[i]); }", + "function f() { var r; r = [1]; r = [2]; g(r[0]); }", + "function f() { var r; g(r = [1]); g(r[0]); }", + "function f(r) { var r; r = [1]; g(r[0]); }", + "function f() { var r; (function() { r = [1]; })(); g(r[0]); }", + "function f() { var r; r = [...a]; g(r[0]); }", + "var r; r = [1]; g(r[0]);", + ] { + let output = transform(kept); + assert!(!output.contains("r_0"), "{output}"); + } + } +} diff --git a/src/deobfuscate/scratch_parameters.rs b/src/deobfuscate/scratch_parameters.rs deleted file mode 100644 index 7b28509..0000000 --- a/src/deobfuscate/scratch_parameters.rs +++ /dev/null @@ -1,458 +0,0 @@ -//! 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) -> bool { - if keep >= function.params.len() { - return false; - } - let declarators: Vec = 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, - /// Read on some path before being assigned on it. - observed: HashSet, - /// Mentioned anywhere, and so still needing a binding. - used: HashSet, - /// The labelled statements around the node, innermost last. - labels: Vec