Skip to content

Reject UniformDuration sampler state which can panic in Duration::new - #1841

Merged
dhardy merged 4 commits into
rust-random:masterfrom
shoemoney:fix-uniform-duration-serde-panic
Nov 15, 2026
Merged

dhardy merged 4 commits into
rust-random:masterfrom
shoemoney:fix-uniform-duration-serde-panic

Conversation

@shoemoney

@shoemoney shoemoney commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor
  • Added a CHANGELOG.md entry

Summary

A deserialized UniformDuration can panic in Duration::new. This is the unguarded sibling of the Uniform<char> problem fixed in #1831: same threat model, same fix shape.

Motivation

UniformChar carries a validating deserializer on its sampler field (src/distr/uniform_other.rs:36, added by #1831):

#[cfg_attr(feature = "serde", serde(deserialize_with = "deser_sampler"))]
sampler: UniformInt<u32>,

UniformDuration (src/distr/uniform_other.rs:127) and the private UniformDurationMode use a bare derive(Serialize, Deserialize) with no validation, and sample feeds that state straight to Duration::new, which panics on overflow:

  • Small arm: Duration::new(secs, n), where n comes from a Uniform<u32> whose range is whatever was deserialized. If n >= 1_000_000_000 the carry can push secs past u64::MAX.
  • Large arm: Duration::new(s, n + self.offset). The rejection test only fires when s == max_secs, so a seconds sampler whose maximum exceeds max_secs is never rejected, and offset is never checked to be a valid subsecond count (it can also overflow the n + self.offset addition).

The UniformInt hardening in #1831 only fixed max() for the range == 0 case; it does not reject out-of-range low/range, so it is not a guard here.

This is only reachable by deserializing untrusted or corrupted sampler state. That is the same threat model the project already accepted when it hardened Uniform<char>, so I am filing it as a normal bug rather than through the security advisory process. It is not a memory-safety issue.

Details

Before, on master (9e7d328), deserializing and sampling:

let json = r#"{"mode":{"Small":{"secs":18446744073709551615,"nanos":{"low":1000000000,"range":1,"thresh":0}}},"offset":0}"#;
let distr: UniformDuration = serde_json::from_str(json).unwrap();
let _ = distr.sample(&mut rng);
thread '...' panicked at library/core/src/time.rs:201:18:
overflow in Duration::new

The new test test_duration_bad_deser, run against unmodified source:

test distr::uniform::other::tests::test_duration_bad_deser ... FAILED
---- distr::uniform::other::tests::test_duration_bad_deser stdout ----
panicked at src/distr/uniform_other.rs:346:13:
assertion failed: result.is_err()
test result: FAILED. 0 passed; 1 failed

The fix replaces the derived Deserialize for UniformDuration with one that checks the invariants new_inclusive establishes: offset is a valid subsecond nanosecond count, the Small nanos sampler cannot carry a second past u64::MAX, and the Large seconds sampler cannot exceed max_secs or carry past u64::MAX. Medium needs no check, since Duration::new(nanos / 1e9, nanos % 1e9) cannot overflow for any u64. Rejection produces a clean serde data error, matching the UniformChar behaviour and its test.

After:

test distr::uniform::other::tests::test_duration_bad_deser ... ok
test distr::uniform::other::tests::test_serialization_uniform_duration ... ok
test result: ok. 113 passed; 0 failed; 0 ignored

Baseline on master with --features serde was 112 passed, so the delta is exactly the one new test. Round-tripping a validly constructed UniformDuration is unaffected. cargo fmt --check and cargo clippy --features serde --all-targets are clean, and cargo build --no-default-features still builds.

sample() passes the deserialized sampler state directly to Duration::new,
which panics on overflow. UniformChar already validates its deserialized
UniformInt<u32> for the same reason (rust-random#1831); UniformDuration and
UniformDurationMode used a bare derive with no validation.

Replace the derived Deserialize for UniformDuration with one that checks
the invariants new_inclusive establishes: offset is a valid subsecond
nanosecond count, the Small nanos sampler cannot carry a second past
u64::MAX, and the Large seconds sampler cannot exceed max_secs or carry
past u64::MAX.
Comment thread src/distr/uniform_other.rs Resolved
Comment thread src/distr/uniform_other.rs Resolved
Comment thread src/distr/uniform_other.rs Resolved

@dhardy dhardy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me — thanks for the contribution.

Comment thread CHANGELOG.md Resolved
@dhardy
dhardy merged commit c03e547 into rust-random:master Nov 15, 2026
17 checks passed
kodiakhq Bot pushed a commit to pdylanross/fatigue that referenced this pull request Nov 19, 2026
Bumps rand from 0.10.3 to 0.10.4.

Changelog
Sourced from rand's changelog.

[0.10.4] — 2026-11-15
Fixes

Fix possible panic due to sampling a deserialized Uniform<Duration> (#1841)

#1841: rust-random/rand#1841



Commits

c03e547 Rand 0.10.4: reject validate UniformDuration sampler state during deserializa...
d1cbc13 Document StdRng / ThreadRng duplication concerns (#1844)
See full diff in compare view




Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


Dependabot commands and options

You can trigger Dependabot actions by commenting on this PR:

@dependabot rebase will rebase this PR
@dependabot recreate will recreate this PR, overwriting any edits that have been made to it
@dependabot show <dependency name> ignore conditions will show all of the ignore conditions of the specified dependency
@dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
@dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
@dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
markharding pushed a commit to futo-org/Harbor that referenced this pull request Nov 24, 2026
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [rand](https://rust-random.github.io/book) ([source](https://github.com/rust-random/rand)) | dependencies | patch | `0.10.3` → `0.10.4` |

---

> ⚠️ **Warning**
>
> Some dependencies could not be looked up. Check the [Dependency Dashboard](issues/2097) for more information.

---

### Release Notes

<details>
<summary>rust-random/rand (rand)</summary>

### [`v0.10.4`](https://github.com/rust-random/rand/blob/HEAD/CHANGELOG.md#0104--2026-11-15)

[Compare Source](rust-random/rand@0.10.3...0.10.4)

##### Fixes

- Fix possible panic due to sampling a deserialized `Uniform<Duration>` ([#&#8203;1841])

[#&#8203;1841]: rust-random/rand#1841

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - "before 9am on tuesday"
- 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.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yNTIuMCIsInVwZGF0ZWRJblZlciI6IjQ0LjI1Mi4wIiwidGFyZ2V0QnJhbmNoIjoiZGV2ZWxvcCIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiLCJyZW5vdmF0ZSJdfQ==-->

Co-authored-by: Thomas de Zeeuw <thomas@futo.org>
Reviewed-on: https://code.futo.org/harbor/harbor/pulls/2474
Reviewed-by: Thomas de Zeeuw <thomas@futo.org>
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.

2 participants