Skip to content

deps: Update dependency semver to v3.1.3 [SECURITY] - #30

Merged
gagantrivedi merged 1 commit into
mainfrom
renovate/pypi-semver-vulnerability
Dec 3, 2026
Merged

gagantrivedi merged 1 commit into
mainfrom
renovate/pypi-semver-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor

This PR contains the following updates:

Package Change Age Confidence
semver (changelog) 3.0.4 → 3.1.3 age confidence

python-semver: Super-quadratic ReDoS in _LAST_NUMBER via attacker-controlled version strings

CVE-2026-140095 / GHSA-3qgw-g8j9-rcg4

More information

Details

Summary

python-semver/python-semver is the Python Semantic Versioning library published on PyPI as semver. At src/semver/version.py:95 it defines:

_LAST_NUMBER = re.compile(r"(?:[^\d]*(\d+)[^\d]*)+")

The pattern is used by bump_build() to find and increment the last numeric component of a version string's build metadata. Its outer repeated group (?:[^\d]*(\d+)[^\d]*)+ contains two unbounded [^\d]* quantifiers plus \d+, and adjacent repetitions can consume the same run of non-digit characters. When the build metadata is a long alphabetic string with no digits, the engine must try an enormous number of ways to divide that run among the quantifiers before the overall match fails, producing super-quadratic catastrophic backtracking, a CWE-1333 (Inefficient Regular Expression Complexity / ReDoS) condition.

The vulnerability is reachable end to end through the public API semver.Version.parse("1.0.0+" + "a" * N).bump_build(): the library's BUILD_IDENTIFIER rule is [0-9a-zA-Z-]+, so an arbitrarily long all-letter build identifier parses successfully and is then passed to the vulnerable search. The untrusted input surface is any version string supplied by an external party: package manifests and dependency constraints, version validation in CI and release pipelines, registry metadata, SBOM imports, update-check services, and multi-tenant version-policy validation. A roughly 32 KB build identifier blocks the parsing process for about 15 seconds, and longer values reach minute scale. Python's regular-expression engine cannot be interrupted by a timeout during that work.

The ambiguity inside _LAST_NUMBER is structural: the trailing [^\d]* of one iteration and the leading [^\d]* of the next iteration can consume the same characters, and there is no separator that forces a unique division. With no digit anywhere in the input, the engine keeps generating new candidate partitions for the outer +, each of which must then fail at the mandatory digits, until the search has explored a combinatorial number of possibilities. The control run with interleaved digits confirms that the presence of a matchable \d collapses the search to linear time.

Affected version
  • Repository: python-semver/python-semver; package: semver.
  • Affected release: latest release tag 3.1.0, with master HEAD f3c7138120d7f49e190bd7c555c6e7eb155b482d; the pattern is present in both and unfixed.
  • Regex definition: src/semver/version.py:95.
  • Trigger chain: src/semver/version.py:424 (bump_build()) calls src/semver/version.py:452 (_increment_string(self._build)), which calls Version._LAST_NUMBER.search(string) at src/semver/version.py:324 inside _increment_string (lines 313-329).
  • Affected public entry point: semver.Version.parse(version_string).bump_build(), and any other public path that eventually calls _increment_string.
Reproduction and timing

All timings below were measured under CPython 3.12 with python-semver 3.1.0 in a controlled local environment. Isolated regex measurements are listed separately from the end-to-end public-API measurements.

Isolated _LAST_NUMBER search on a payload of 'a' * N with no digits:

n=1000   len=1000     7.34 ms
n=2000   len=2000    40.98 ms
n=4000   len=4000   161.87 ms
n=8000   len=8000   495.65 ms
n=16000  len=16000 1932.34 ms
n=32000  len=32000 16038.80 ms

End-to-end via the public API Version.parse('1.0.0+' + 'a' * N).bump_build() (first measurement series):

N=1000    8.1 ms
N=2000   30.5 ms  x3.8
N=4000  124.7 ms  x4.1
N=8000  459.2 ms  x3.7
N=16000 2001 ms   x4.4
N=32000 15177 ms  x7.6

A second end-to-end measurement series of the same call, recorded in the detailed evidence, gives:

N=1000    7.31 ms
N=2000   29.48 ms
N=4000  120.50 ms
N=8000  517.93 ms
N=16000 2091.86 ms
N=32000 15655.43 ms

The roughly fourfold cost for each doubling up to 16000 characters, followed by a larger factor at 32000, is consistent with quadratic behaviour that becomes super-quadratic at larger sizes. A control run using a payload of 'a1' * N, which does contain digits, stays linear and confirms that the blowup is specifically triggered by a long run with no \d match:

n=1000  len=2000    0.68 ms
n=4000  len=8000    2.08 ms
n=16000 len=32000  11.46 ms
Reachability

No special configuration is needed. A caller passes a syntactically valid semantic version whose build component is a long run of letters; Version.parse accepts it because BUILD_IDENTIFIER is [0-9a-zA-Z-]+ and imposes no length limit. Calling bump_build() then reads self._build, passes it to _increment_string, and reaches _LAST_NUMBER.search. Because the version string itself is attacker-controlled in many integration paths, an external party can choose both that it parses successfully and that the subsequent increment becomes arbitrarily expensive. There is no input length validation at the parse, build, or increment stages, and the search cannot be aborted once it starts backtracking.

In practice the untrusted version string can arrive through a requirements.txt or lock file submitted for analysis, a tag or version number checked by a release pipeline, registry or SBOM metadata imported from a third party, an update-check response, or a tenant-supplied policy in a multi-tenant service. In each case the caller typically parses first and only afterwards decides whether the version is acceptable, so an attacker does not need the string to survive validation: successful parsing with an expensive subsequent increment is enough.

Impact

The principal consequence is denial of service. A single call with a 32 KB all-letter build identifier consumes about 15 seconds of CPU in the parsing process; a small number of concurrent calls can occupy all available workers and make a service unresponsive. The trigger is a valid version string, so it passes ordinary validation, and the amplification ratio is severe: doubling the input roughly quadruples the cost, with a worse factor at the largest measured size. The affected code sits in a public parsing and increment API, so any downstream application that consumes untrusted version strings from manifests, registry metadata, CI inputs, or client submissions is exposed. This is rated High because the input threshold is low, the amplification is clearly measured, the path is public API, and no privileges are required; the impact is availability only, with no data disclosure or code execution, so it is not Critical.

The measured progression illustrates the risk: about 8 ms at 1000 characters, just over 2 seconds at 16000, and roughly 15 seconds at 32000. A service that accepts version strings over the network can therefore be pushed from negligible latency to a full CPU stall by a single modest payload, and the super-quadratic step at the largest size means the effect grows faster than the amount of data sent.

Suggested fix
  • Rewrite the pattern to remove ambiguity. The goal is simply to obtain the last run of digits, so use re.compile(r'\d+') with finditer and keep the final match, use a bounded-backtracking form such as (\d+)(?!.*\d), or perform a hand-written right-to-left scan. Preserve the existing _increment_string semantics for match.group(1) and match.span(1).
  • Apply a reasonable length limit, for example 256 bytes, to the overall version string and to the build and prerelease components in Version.parse and bump_build, rejecting longer values outright.
  • Add timing or timeout regression tests for long all-non-digit build strings such as 'a' * N, so a future reintroduction of the nested quantifier is caught.
  • Where a service exposes version parsing to external callers, add timeouts, rate limits, and input size checks on the calling side, and avoid unbounded increment operations on untrusted paths.
  • Add static regular-expression complexity scanning to CI and scan the rest of the library for unbounded quantifiers inside repeated groups.

Taken together, rewriting the expression and bounding the input length remove both the computational flaw and the ability of an attacker to feed it an arbitrarily large value. The regression test should include the all-letter build identifier as well as other digit-free strings, since the vulnerable condition is the absence of a digit rather than the specific character used.

Disclosure

Reported by Jiawei Guo (GitHub: plailenceGrill).

Severity

  • CVSS Score: 8.7 / 10 (High)
  • Vector String: CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:N/VI:N/VA:H/SC:N/SI:N/SA:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


Release Notes

python-semver/python-semver (semver)

v3.1.3

Compare Source

=============

:Released: 2026-11-26
:Maintainer: Tom Schraitle

Security

  • Fix potential denial-of-service vulnerability when parsing untrusted input with excessive length or large numeric components.
    For details, see GHSA-3qgw-g8j9-rcg4 <https://github.com/python-semver/python-semver/security/advisories/GHSA-3qgw-g8j9-rcg4>_.

Bug Fixes

  • :gh:515: Fix :meth:Version.__hash__ so that versions which compare equal now produce
    equal hashes. A numeric prerelease identifier with leading zeros (for example
    "007") compares equal to its normalized form ("7"), but previously
    hashed differently, which broke set and dict behavior.

    Fix GitHub Python test to use pinned versions in :file:pyproject.toml.

Improved Documentation

  • :pr:514: The prefixed-version documentation example now rejects empty input with
    ValueError, allowing its inherited is_valid method to return False.

v3.1.2

Compare Source

=============

:Released: 2026-11-15
:Maintainer: Tom Schraitle

Deprecations

  • :gh:506: Equality comparisons between :class:~semver.version.Version instances and strings, bytes, tuples,
    or lists now issue a :py:exc:DeprecationWarning and will be removed in semver 4.
    :class:~semver.version.Version remains hashable, but do not mix these types as dictionary keys or
    set elements during the transition. Convert strings and bytes with
    :meth:~semver.version.Version.parse and tuples or lists with Version(*parts).

Trivial Changes

  • :gh:511: :meth:Version.compare now returns early when both prerelease parts are equal,
    or when only one version has a prerelease. This makes comparisons and sorting faster.

v3.1.1

Compare Source

=============

:Released: 2026-11-09
:Maintainer: Tom Schraitle

Bug Fixes

  • :pr:483: Fix :meth:~semver.Version.bump_prerelease and :meth:~semver.Version.bump_build to raise a :class:ValueError when the token argument is not a valid dot-separated SemVer identifier (for example build+meta or rc.). Previously such tokens were concatenated unchecked, producing version strings that :meth:~semver.Version.parse itself would reject.

  • :pr:486: Fix :meth:~semver.Version.next_version to drop the build metadata when incrementing an old-style prerelease without a dot separator (for example rc3). Previously 1.2.3-rc3+build.5 became 1.2.3-rc4+build.5 while 1.2.3-rc.3+build.5 became 1.2.3-rc.4.

  • :pr:489: Version.next_version now validates used prerelease tokens and matches token
    families literally. Invalid tokens raise ValueError. Dotted prefixes advance
    correctly while existing qualifier chains and legacy counters are preserved.

  • :pr:495: The type annotation of Version.is_valid() now includes its existing support for UTF-8 encoded byte strings.

  • :pr:501: Version.replace() now preserves the original constructor TypeError
    when an existing version component receives an invalid value, rather than
    reporting zero unexpected keyword arguments.

  • :pr:508: Version subscripts now accept objects implementing __index__ and raise
    TypeError for invalid key types.

  • :gh:484: Fix :meth:~semver.Version.next_version to correctly increment old-style prerelease versions without a dot separator (for example rc3). Previously, calling next_version("prerelease") on such versions would reset the prerelease number to 1 instead of incrementing it.

  • :gh:487: Comparing versions with long numeric prerelease identifiers no longer raises
    ValueError because of Python's integer string conversion limit.

  • :gh:497: Version.next_version("prerelease", prerelease_token=...) now advances the
    patch version when switching tokens would otherwise produce a lower version.
    For example, switching from 1.2.3-rc.1 to alpha returns
    1.2.4-alpha.1. Forward token changes retain the current patch version.

  • :gh:499: Version.next_version("prerelease") now advances the patch version when
    incrementing an old-style prerelease counter would produce an older version.
    For example, 1.2.3-rc9 becomes 1.2.4-rc10. The legacy token and
    incremented counter are preserved; increments that already move forward keep
    the current patch version.

Trivial Changes

  • :pr:502: Add tests for six behaviours that mutation testing showed were not covered: :func:match() at the boundary version, build metadata in :func:is_compatible(), numeric-only prereleases in :func:bump_prerelease(), the :command:pysemver return code for an invalid version, and the :func:deprecated() messages.

v3.1.0

Compare Source

=============

:Released: 2026-09-12
:Maintainer: Tom Schraitle

Bug Fixes

  • :pr:478: Version.parse() and Version.is_valid() now reject non-ASCII digits and
    trailing newlines, in accordance with the SemVer grammar. Optional minor and
    patch parsing applies the same character restrictions.

  • :pr:479: Comparing a :class:~semver.Version with a dict, tuple, or list that cannot construct a valid version (for example, an empty collection, wrong number of parts, non-numeric parts, or unknown keys) no longer raises internal errors from Version.__init__. The comparison operators now return :py:const:NotImplemented for such operands, following the general rule for invalid comparison operand types: equality evaluates to False and ordering raises Python's standard :py:exc:TypeError (for example, '>' not supported between instances of 'Version' and 'dict').

  • :pr:480: (:meth:~semver.version.Version.bump_build) will now add .0 to an existing build when the last segment of the current build metadata, split by dots (.), is not numeric. This is to ensure the bumped version contains a raised build instead of silently returning an unchanged version. For example, 1.2.3+alpha is bumped to 1.2.3+alpha.0. This mirrors the corresponding fix for the prerelease part (:gh:460). Related to :gh:466.

  • :gh:460: :meth:~semver.version.Version.bump_prerelease will now add .0 to an
    existing prerelease when the last segment of the current prerelease, split by
    dots (.), is not numeric. This is to ensure the new prerelease is considered
    higher than the previous one.

    :meth:~semver.version.Version.bump_prerelease now also support an argument
    bump_when_empty which will bump the patch version if there is no existing
    prerelease, to ensure the resulting version is considered a higher version than
    the previous one.

Features

  • :pr:476: Added optional [native] extra to accelerate parsing on CPython via the
    fast-semver-rs-backend package. The pure-Python parser remains the default;
    the native backend is opt-in and only available on CPython.

Internal Changes

: Update GitHub Actions for astral-sh/setup-uv (version 0.10.1), github/codeql-action (version 4)

Trivial Changes

  • :gh:463: Remove double code in :meth:Version.bump_build

: Improve test coverage to 100% by ignoring the optional Rust backend fallback.

: Improve test suite for comparisons and fix test coverage.

: Suppress deprecation warnings in test suite.


Configuration

📅 Schedule: (UTC)

  • Branch creation
    • At any time (no schedule defined)
  • Automerge
    • At any time (no schedule defined)

🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

♻ Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this PR and you won't be reminded about this update again.


  • If you want to rebase/retry this PR, check this box

This PR was generated by Mend Renovate. View the repository job log.

@renovate
renovate Bot requested a review from a team as a code owner December 3, 2026 09:06
@renovate
renovate Bot requested review from khvn26 and removed request for a team December 3, 2026 09:06
@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown

File Coverage Missing
All files 100% ✅

Minimum allowed coverage is 100%

Generated by 🐒 cobertura-action against e4294b8

@gagantrivedi
gagantrivedi merged commit b8df480 into main Dec 3, 2026
3 checks passed
@renovate
renovate Bot deleted the renovate/pypi-semver-vulnerability branch December 3, 2026 10:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant