Repository navigation
chore: sync upstream changes (4f6da9fb) - #187
Merged
Merged
Conversation
In Serializer::write_value, literal block scalars only indent lines after LF (stripping a preceding CR). A lone CR not followed by LF, as well as NEL (U+0085), LS (U+2028), and PS (U+2029) which YAML 1.1 parsers treat as line breaks, started an unindented line that exited the scalar and allowed untrusted strings to inject YAML structure into yr dump output. Fall back to double-quoted scalars whenever a multi-line string contains a lone CR, NEL, LS, or PS, and escape NEL, LS, and PS using the YAML named escapes \N, \L, and \P in Serializer::escape. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-DZ7NK2SF
During condition evaluation, timeouts were previously enforced only by Wasmtime epoch checks at function entries and loop headers. A loop-free condition consisting of many sequential host function calls (such as hash.md5 or math.entropy) stayed inside a single rules_N function and ran far past the configured timeout without returning ScanError::Timeout. Add ScanContext::deadline_reached() and check it in the impl_wasm_exported_fn trampoline whenever a host function returns, returning ScanError::Timeout once the deadline has passed. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-C19QGOC0
MachOFile::cs_superblob previously parsed each of up to MAX_CS_BLOBS (256) SuperBlob index entries independently without checking whether multiple entries pointed to the same or overlapping byte ranges. A crafted Mach-O with repeated or nested CS_MAGIC_BLOBWRAPPER or CS_MAGIC_EMBEDDED_ENTITLEMENTS entries re-parsed the same CMS signature or entitlements XML up to 256 times, causing multi-gigabyte memory exhaustion and stalling scans past the configured timeout. Track the byte ranges of parsed entitlements and signature blobs in cs_superblob and skip any blob whose range overlaps one already parsed. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-XOQ3FY52
…c UTF-8 validation Tokenizer::unexpected_token previously called utf8_chunks().next() on the entire remaining source buffer before truncating the token at the first whitespace. On valid UTF-8 inputs containing many short unknown tokens (such as vertical tabs or unknown characters separated by spaces), every unknown token re-validated the rest of the file, leading to quadratic tokenization time. Decode characters incrementally with bstr::decode_utf8 and stop at the first whitespace or invalid UTF-8 sequence so work is proportional to each token's length. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-IHMGGU8O
…ification and reporting verify_signer_info previously selected the signing certificate by serial number alone, while AuthenticodeSignature::chain selected the reported signer by issuer alone, and countersignature chains were built from the full certificate list even after later MS_COUNTERSIGN attributes added certificates. An attacker could sign a modified PE with their own key while pairing verified=true with another publisher's thumbprint and certificate chain. Add a shared find_signing_cert helper that matches both issuer and serial number (falling back to the first matching serial if no exact match exists), pass the resolved certificate directly to CertificateChain::new for both verification and reporting, and record the issuer, serial number, and certificate pool length at verification time on AuthenticodeCountersign. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-7DCSC2WL
…thenticode hashes PE::hash previously subtracted cert_table_size from the file length without verifying that cert_table_offset + cert_table_size equals the file length. Raising Size in the unauthenticated security directory entry allowed inserting unsigned data before the certificate table without changing the Authenticode hash. Additionally, AuthenticodeParser::parse_content_info ignored the Option returned by AuthenticodeHasher::hash and finalized the partially updated digest, allowing Size=0xFFFFFFFF to pass verification as well. Require cert_table_offset + cert_table_size == self.data.len() in PE::hash, store Option<Vec<u8>> in AuthenticodeParser::digest_cache, propagate hash() failures instead of finalizing partial digests, and treat signatures whose hash could not be computed as unverified. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-41X864CH
Compiler::c_import previously checked self.banned_modules only after adding the module to root_struct, imported_modules, and the current namespace's symbol table. When a caller continued using the compiler after the failed add_source, rules in the same source or subsequent sources in that namespace could still use the banned module, and the module remained in Rules::imports(). Check self.banned_modules before registering the module in c_import. To preserve the single-error behavior when rules in the same source reference a banned module (or a rule ignored for depending on one), track banned identifiers in c_items and record dependent rules in ignored_rules under the import's error without emitting redundant E009 errors. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-3X676W5Y
…onHook WarningSuppressionHook::next previously queued every comment into pending_comments and walked the entire vector with retain_mut on every NEWLINE. Consecutive comment-only lines left all earlier comments without a code span, causing O(n^2) work in the number of consecutive comment-only lines. Keep only comments waiting for a code span in pending_comments and process each comment immediately once its code span is known (code preceding the comment on the same line, end of a line with code, or start of a RULE_DECL/PATTERN_DEF), leaving newlines on comment-only or blank lines O(1). Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-BO4C4S11
Dex::parse_dex_header previously required header_size == 0x70 for all versions even though DEX version 041 adds container_size and header_offset at offsets 0x70 and 0x74, making its header 0x78 bytes long. Spec-conforming DEX 041 files therefore failed to parse and reported is_dex = false. Accept DEX_HEADER_SIZE_V41 (0x78) when header.version >= DexVersion::DEX41 while keeping 0x70 accepted for all versions and rejecting 0x78 for versions up to 40. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-AYMQK2ZB
…s (#912)
## Summary
Fixes #909.
When `re::fast::Compiler` compiles a single-piece
`PatternPiece::Alternation` (for example, a chained tail produced by
`split_at_large_gaps` as in `/C0A.*(1x|1xy)/s`, or a standalone masked
alternation like `{ (31 78 79 | 31 7?) }`), full-length atoms for each
alternative were previously left marked `exact = true`. At scan time,
exact atoms short-circuit `verify_regexp()` and report
`atom_pos..atom_pos + atom.len()` directly without invoking `FastVM`,
breaking ordered alternation semantics whenever earlier alternatives
overlap later ones with different lengths:
- **Shadowed atom** (`prev.len() <= atom.len()` and `prev` matches
`atom[..prev.len()]`, e.g. `"1xy"` in `(1x|1xy)`): in a greedy chain
like `/C0A.*(1x|1xy)/s`, `"1xy"` bypassed `FastVM` and overwrote `[0:8]`
with `[0:9]` via `replace_if_longer`. Because `prev` always wins at the
same start offset and already emits atoms covering it, the shadowed atom
is now dropped (keeping `"1x"` exact with zero `FastVM` invocations).
- **Ambiguous prefix** (`prev.len() > atom.len()` and `atom` matches
`prev[..atom.len()]`, e.g. `"1x"` in `(1xy|1x)`): in a non-greedy chain
like `/C0A.*?(1xy|1x)/s` or a masked alternation like `{ (31 78 79 | 31
7?) }`, `"1x"` fired before `"1xy"` and won prematurely. Because seeing
`"1x"` alone is genuinely insufficient to determine the match length
without checking subsequent bytes, the atom is now marked inexact so
`FastVM` verifies the alternation in priority order.
- Disjoint variable-length alternatives (e.g. `(1x|2xy)`) and
non-overlapping expanded atoms of masked alternations remain `exact =
true`.
## Changes
- `lib/src/re/fast/compiler.rs`:
- Added `Pattern::len` and `Pattern::matches_prefix`.
- Added `finalize_atom` in `Compiler::compile` to reconcile
exactness/shadowing for single-piece alternations (covering both literal
and expanded masked atoms) and clear `exact` on multi-piece patterns.
- Added unit tests in
`re::fast::compiler::tests::alternation_exact_atoms`.
- `lib/src/re/mod.rs`:
- Removed the now-unused `RegexpAtom::set_exact` method.
- `lib/src/tests/mod.rs`:
- Added end-to-end regression tests for issue #909 (greedy/non-greedy
chains, `wide`, and standalone masked alternations).
## Testing
- `cargo fmt --check`
- `cargo test -p yara-x --lib` (default features: `fast-regexp` +
`exact-atoms`)
- `cargo test -p yara-x --lib --no-default-features --features
exact-atoms regexp_patterns_1` (PikeVM)
- `cargo test -p yara-x --lib --no-default-features --features
fast-regexp regexp_patterns_1` (FastVM without `exact-atoms`)
PE::parse_exports previously computed each export ordinal with exports.base.checked_add(i) and silently dropped the entire function entry on 32-bit overflow. Setting Base = 0xFFFFFFFF therefore hid every export after slot 0 from pe.exports, pe.exports_index, pe.export_details, and pe.number_of_exports even though export names map through AddressOfNameOrdinals directly by 0-based function index. Use wrapping_add for the ordinal so all exported functions are kept, and look up export names by the function's index in exported_funcs instead of subtracting exports.base from f.ordinal. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-OBIOEVKN
…x40 is set Dotnet::parse_tilde_stream previously assumed metadata tables begin immediately after the table row counts. When bit 0x40 (CoreCLR's EXTRA_DATA) is set in HeapSizes, the .NET runtime reads a 4-byte extra data value before the first table. Not skipping those 4 bytes shifted every table by 4 bytes, causing corrupted module names and dropped metadata tables. Consume the 4-byte extra data value after the row counts in parse_tilde_stream whenever heap_sizes & 0x40 != 0. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-5GIFLJVJ
Skip rendering source and patch snippets in Report::fmt when the source slice exceeds 32 KiB or contains a line longer than 4 * max_width, falling back to each label's origin (file:line:column) and message. This prevents diagnostic text size and rendering time from growing quadratically on long single-line or very large rules. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-TXGM1CYO
…ended_patterns_in_sets Deduplicate per-branch explicit patterns and wildcard pattern sets, locate matching patterns by binary search over sorted rule pattern names, track longer overlapping prefixes in a single longest-to-shortest pass, and key reported warnings by (pattern_idx, prefix) instead of source span. Lazily initialize per-rule/per-branch tables only when a branch contains wildcard sets so non-wildcard rules incur no extra allocations or hashing. Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-WRHG8J3E
…t (#913) `Rules::deserialize` has documented the requirement since `25efa375`, under `# Safety`: > As long as you are deserializing rules from binary content produced by `Rules::serialize` you are safe. But you should never attempt to do so from binary content that was produced or could be manipulated by a third party. This implies a security risk and your program may panic during scanning. None of the other entry points to the same code say it: | | documented | |---|---| | `Rules::deserialize` | yes | | `Rules::deserialize_from` | no | | `yrx_rules_deserialize` | no | | `yrx_rules_deserialize` on the C API page | no | | `Rules.deserialize_from` (Python) | no | | `ReadFrom` (Go) | no | The five without it are the ones that take a file or a reader, which is where bytes from somewhere else actually come from. Someone loading rules over the network reaches for `ReadFrom` or `deserialize_from`, not for `deserialize`, and sees nothing. This adds the same note to each of them, in the wording of the API it sits on. No code changes. For context, I filed #910 about panics from a tampered stream and closed it myself: the answer was in that `# Safety` section all along, and I had not read it. This is the only thing I took from that, and it is the part that would have saved me the trip.
`yrx_scanner_scan_file` is exported in `capi/include/yara_x.h` and the Go API builds `Scanner.ScanFile` on top of it, but it has no entry on the C API page. This adds one next to `yrx_scanner_scan`, in the wording of the header comment, plus the restriction that it cannot be used on a scanner in block scanning mode, which the implementation rejects with `cannot use yrx_scanner_scan_file on a scanner in multi-block mode`. I compared every function declared in the header against the page. The header declares 55 and the page has 45 `###` entries, and the difference accounts for itself: - `yrx_scanner_scan_file`, the one this PR adds. - `yrx_compiler_enable_feature`, which the header itself marks as hidden from the public documentation, so I left it out. - the five `yrx_compiler_define_global_*` and five `yrx_scanner_set_global_*` functions, which the page already documents collectively under `yrx_compiler_define_global_xxxx` and `yrx_scanner_set_global_xxxx`. So `yrx_scanner_scan_file` was the only one genuinely absent.
The C API page is published at `/docs/api/c/c-/`, while its siblings are
at `/docs/api/go/`, `/docs/api/python/` and `/docs/api/rust/`.
`/docs/api/c/`, which is what the file name suggests and what people
type, returns 404.
The cause is in the permalink. `config/_default/hugo.toml` has:
```toml
[permalinks]
docs = "/docs/:sections[1:]/:slug/"
```
`c.md` sets no slug, so `:slug` falls back to the urlized title, and the
title is `C/C++`, which urlizes to `c/c-`. The other three API pages are
unaffected only because their titles happen to match their file names.
The same thing is visible across the blog, where
`leveraging-macho-module/` is published as
`/blog/using-the-mach-o-module-in-yara-x/`.
Setting `slug: "c"` is enough. I built the site locally with the Hugo
version the repo installs (0.123.7 extended) to check both directions
rather than reason about it:
| | output |
|---|---|
| without the change | `public/docs/api/c/c-/index.html` |
| with the change | `public/docs/api/c/index.html` |
Internal links need nothing: the two `{{< ref "c.md" >}}` links in
`go.md` render as `https://virustotal.github.io/yara-x/docs/api/c/`
after the change, and no page hardcodes the old path.
**The one downside, so it is your call rather than a surprise.**
`/docs/api/c/c-/` stops working, and it is the URL search engines have
indexed. I tried adding `aliases` for it, both with and without a
trailing slash, and the redirect page is never written, because
`disableAliases = true` is set in `config/_default/hugo.toml`. So there
is no way to keep the old URL alive from front matter. If you would
rather not lose it, the alternative is leaving this as it is, or
changing the title, which I did not want to do on my own.
No code changes.
Six links in the docs don't go where they say. I found them by asking each published page which of its own internal links resolve to an id on that page, so every one is confirmed broken on the live site rather than inferred from the Markdown. | page | link | target | |---|---|---| | pe.md | `#richSignature` | `richsignature` | | pe.md | `#dirEntry` | `direntry` | | macho.md | `#dyldInfo` | `dyldinfo` | | macho.md | `#certificates` | does not exist, the section is `certificate` | | elf.md | `#elf-DynType` | `dyntype` | Hugo lowercases the generated ids and fragment matching is case-sensitive, so the five camelCase ones silently do nothing when clicked. What makes these safe to fix without judgement is that each file already contains the correct form. `macho.md` links `#dyldinfo` in the module structure table and `#dyldInfo` in the `File` table. `pe.md` writes `#optionalmagic`, `#dllcharacteristics`, `#keyvalue` and `#section` in lowercase. `elf.md` writes `#sectiontype`, `#segmenttype`, `#symtype`, `#symbind` and `#symvisibility` in lowercase, and line 103 is the only row carrying an `elf-` prefix. The `certificates` row needed a bit more than the anchor. The proto declares `repeated Certificate certificates = 22`, there is no `Certificates` type, and the module structure table already describes the same field as `[Certificate](#certificate) array`. The `File` table now says the same thing. Last one, `rust.md` linked to `https:///docs.rs/yara-x/latest`, with three slashes and therefore an empty authority. Browsers normalize it and the link does work, so this is a typo rather than a broken link, but it is the only URL of that shape in the docs. One cosmetic note: the `certificates` cell is now four characters wider than its column in `macho.md`, which renders the same but leaves the pipes ragged in the source. Re-aligning the column would have turned two fixes into a thirty line diff, so I left it. Happy to re-align that table if you prefer it tidy. No code changes.
`profile.json` in the repository root is a 335 KB samply / Firefox
Profiler capture of the `yr` binary. It entered the tree in `eb695344`
("refactor: limit the number of warnings"), together with eleven
unrelated source files, so it looks like an accidental `git add` rather
than something meant to be tracked.
Why it can be removed:
- Nothing in the repository references it.
- The samples are unsymbolicated, only raw addresses, so resolving them
would need the exact release build it was recorded against (`breakpadId
E5EB8756562D376488D9FB78BBE19EAB0`, May 2024). It is not usable as a
reference profile by anyone else.
- It embeds the absolute path of the machine it was recorded on.
No code changes, one deletion.
I left `.gitignore` alone on purpose. `samply record` writes
`profile.json` into the current directory by default, so an entry for it
would prevent this from happening again, but `profile.json` is a generic
enough name that I did not want to decide that in this PR. Happy to add
it if you prefer.
I compared the Python API page against the surface that `py/src/lib.rs`
registers in the `yara_x` module on `main` (`46bd8570`). One documented
signature is out of date and eight things are not documented at all.
**The correction.** The page documents the compiler constructor as
`.__init__(relaxed_re_syntax=False)`, but `#[pyo3(signature = ...)]`
declares four arguments:
```rust
#[pyo3(signature = (relaxed_re_syntax=false, error_on_slow_pattern=false,
includes_enabled=true, ignore_invalid_rules=false))]
```
`error_on_slow_pattern`, `includes_enabled` and `ignore_invalid_rules`
appear nowhere on the page. The last two are equivalent to the
`.enable_includes()` and `.ignore_invalid_rules()` methods, which is
what the new text says, after checking that `new_inner` really does call
`compiler.enable_includes(includes_enabled)`.
**The additions**, all registered in `fn yara_x(m)` and all absent from
the page:
| | |
|---|---|
| `module_names()` | `#[pyfunction]`, added with `add_function` |
| `Compiler.ignore_module()` | |
| `Compiler.ignore_invalid_rules()` | |
| `Compiler.ignored_rules()` | |
| `Scanner.max_matches_per_pattern()` | |
| `Scanner.console_log()` | |
| `Rule.tags` | a `#[getter]`, next to the documented `identifier`,
`namespace`, `patterns` and `metadata` |
| the `Formatter` class | `add_class::<Formatter>()`, with its
constructor and `.format()` |
`IgnoredRuleReason` is documented inline under `.ignored_rules()` rather
than as its own section, which is how `MetaType` is already handled
under `.allowed_metadata()`.
One thing worth flagging rather than silently copying. The docstring on
`ignored_rules` says it returns "a list of tuples where the first item
is the rule name and the second item is the reason", but the
`IgnoredRule` pyclass exposes three getters, `name`, `message` and
`reason`. I documented the class, not the docstring, so the docstring is
now the stale one. Happy to send a separate patch for it if you want
them to agree.
The cross-reference anchors were checked against the published page
rather than guessed: `.enable_includes(bool)` resolves to
`#enable_includesbool` and `.errors()` to `#errors`, so the new ones
follow the same shape.
No code changes.
willdurand
marked this pull request as ready for review
November 30, 2026 09:13
willdurand
approved these changes
Nov 30, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR brings in the latest changes from VirusTotal/yara-x.
Commits included