Skip to content

fix: harden unsafe socket code against alignment UB and bad cmsg - #102

Merged
lance0 merged 2 commits into
masterfrom
fix/socket-safety
Jul 1, 2026
Merged

lance0 merged 2 commits into
masterfrom
fix/socket-safety

Conversation

@lance0

@lance0 lance0 commented Jul 1, 2026

Copy link
Copy Markdown
Owner

Summary

Hardens unsafe socket code to eliminate alignment UB and out-of-bounds reads in the ICMP receiver's ancillary-data (CMSG) handling.

Changes

  • IPv6 not working #4 (high): Replace 1-byte-aligned [u8; 64] cmsg buffer with a #[repr(align(8))] wrapper to satisfy struct cmsghdr alignment requirements (8-byte on Linux/FreeBSD, 4-byte on macOS/NetBSD).
  • IPv6 not working #4 (high): Replace &*cmsg dereferences with ptr::addr_of! + read_unaligned for cmsg_level, cmsg_type, cmsg_len, and the TTL/hop-limit integer — eliminating unaligned reference UB that works on x86 only by hardware tolerance.
  • Add animated replay mode with speed control #27 (low): Validate cmsg_len >= CMSG_LEN(sizeof(c_int)) before reading the TTL integer, preventing read past the cmsg boundary on malformed/truncated ancillary data.
  • Bump socket2 from 0.6.1 to 0.6.2 #33 (low): Add explicit SAFETY comment documenting that recv() initializes the first n bytes before from_raw_parts is called on the MaybeUninit buffer in the raw-socket test.

Testing

  • All 493 tests pass; cargo clippy --all-targets -- -D warnings clean.
  • The #[repr(align(8))] struct is defined inline in recv_icmp_with_ttl — no public API change.

Risk

Medium — touches unsafe code in the ICMP receive path, but the changes are mechanical: aligned buffer + read_unaligned + bounds check. No logic changes.

lance0 added 2 commits July 1, 2026 15:15
- Use #[repr(align(8))] buffer for cmsghdr ancillary data to satisfy
  alignment requirements on all platforms (was 1-byte aligned [u8; 64]) (#4)
- Use ptr::read_unaligned and addr_of! for cmsg header fields and TTL data
  instead of creating &cmsghdr references from raw CMSG pointers (#4)
- Validate cmsg_len >= CMSG_LEN(sizeof(c_int)) before reading TTL integer,
  preventing read past cmsg boundary on malformed ancillary data (#27)
- Add SAFETY comment for MaybeUninit -> &[u8] cast in test (#33)

All 493 tests pass; clippy clean.
@lance0
lance0 requested a review from Copilot July 1, 2026 19:49
@lance0
lance0 merged commit 1b15dda into master Jul 1, 2026
5 checks passed
@lance0
lance0 deleted the fix/socket-safety branch July 1, 2026 20:53
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