Skip to content

Keep USB and Ethernet transfers inside the buffers they were given (#822) - #843

Merged
chrisgleissner merged 9 commits into
GideonZ:masterfrom
enver-haase:fix/usb-net-buffer-bounds
Oct 2, 2026
Merged

chrisgleissner merged 9 commits into
GideonZ:masterfrom
enver-haase:fix/usb-net-buffer-bounds

Conversation

@enver-haase

@enver-haase enver-haase commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Status: merged by @chrisgleissner on 2 October. Follow-up from me: the AX88772 path on hardware (FTP round trip, master vs. this change) once an adapter is here.

Fixes two of the transmit defects in #822.

What this fixes

  • RMII (built-in Ethernet: U64, U64 Elite II / C64 Ultimate, U2+, U2+L). A frame under 60 bytes had its length register raised to 60 but its data not padded, so up to 18 bytes of neighbouring memory went on the wire. Short frames are now copied into a driver-owned buffer and zero filled.
  • AX88772 (USB Ethernet adapters, every target with USB networking, including the U2). The 4-byte length header was written at buffer - 4, in front of a buffer lwIP owns. Header and frame are now assembled in a driver-owned buffer, at the cost of a copy of up to 1518 bytes per frame (throughput not measured).
  • Adjacent: ~RmiiInterface released a new[] array with delete. Separate commit.

Tests

  • Host, make -C software/io/network/tests, in CI: 12 pass on the fix, 11 fail against a model of the pre-fix drivers.

  • RMII on hardware (@chrisgleissner), frames under 60 bytes, padding bytes that are zero vs. other:

    Device Firmware Zero Other
    C64 Ultimate master 7117d8857 0 427
    C64 Ultimate this PR 7e877b0c2 429 0
    U2+L 3.15 46f8005ca 0 274
    U2+L this PR, CI build 264 0

    Also passed on both with this PR: pings of 0 to 1472 bytes, a 300 KB FTP round trip with byte comparison, REST/FTP/Telnet health checks.

  • Build: u64, u64ii, u2, u2plus, u2pl.

Not tested

  • AX88772 on hardware: no adapter run yet; follows after the merge (see status).
  • U64 and U2+ on hardware; same RMII driver as the two measured.

@chrisgleissner chrisgleissner added 3.16 Targeted for release 3.16. bug Existing behavior is incorrect, broken, or regressed; includes supported documentation defects. labels Sep 9, 2026
@chrisgleissner
chrisgleissner changed the base branch from test-merge to master September 13, 2026 12:42
@chrisgleissner

Copy link
Copy Markdown
Collaborator

Hi @enver-haase ,

any chance for you to add a unit or ideally E2E test? As it is, without any test, this PR is not merge-ready.

Thanks
Christian

@chrisgleissner chrisgleissner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Request changes for 3.15b: the build proves these files compile, but no regression test exercises any changed path. Please add a host test (and wire it into CI) for: (1) AX88772 frame assembly at 0, 1, 1500, 1536 and 1537 bytes, with canaries before and after the caller buffer; assert the four-byte length/complement header and exact copied payload; (2) RMII frames of 42, 59, and 60 bytes; assert the first two are zero-padded to 60 without modifying the caller buffer; and (3) control_exchange with a non-8-byte setup; assert its semaphore is released before it returns -10. Narrow pure helpers are acceptable if that is what makes these memory-safety contracts host-testable. A hardware AX88772 transfer/capture remains useful additional evidence, but the deterministic regression tests are required before this patch can be release-ready.

@enver-haase

Copy link
Copy Markdown
Contributor Author

Will look into it!

@chrisgleissner

Copy link
Copy Markdown
Collaborator

Thanks @enver-haase . Once you got some tests added, thanks for also updating the PR here with red/green TDD results, demonstrating that the tests fail against the unpatched firmware and pass against the patched one.

control_exchange() takes the mutex on entry and gives it back on every path out
except one: a setup length other than 8 returns -10 while still holding it.
Every later USB operation would then wait its full five seconds and fail, which
on this device means the keyboard, mass storage and the Ethernet adapter all
stop at once.

Latent today, because no caller passes anything but 8. Found by reading, in the
sweep in GideonZ#822, problem 5.
output_packet() wrote the Ethernet minimum into the length register but left
the buffer alone:

    RMII_TX_LENGTH = (uint16_t)((pkt_len < 60)?60:pkt_len);

The engine transmits as many bytes as that register names, so for a 42 byte ARP
request it read 18 bytes past the frame and put them on the wire. Nothing is
corrupted -- the transmit path only reads -- but those bytes leave the device,
and with MEM_LIBC_MALLOC set the pbufs come from pvPortMalloc, so what goes out
is the neighbouring heap block. Every ARP request the device sends does this.

Short frames are now copied into a buffer this driver owns and zero filled to
60 there. Transmission is asynchronous, but the RMII_TX_BUSY test at the top of
the function means the previous frame has left before that buffer is written
again. Frames of 60 bytes or more are transmitted from the caller's buffer as
before, so the copy costs nothing on the traffic that matters.

Reported in GideonZ#822, problem 4.
output_packet() wrote the adapter's four byte length header in front of the
buffer it was handed:

    uint8_t *size = buffer - 4;

That holds for a buffer from this driver's own receive pool, because the
receive path gives the stack usb_buffer + 4 and keeps those four bytes as
headroom. Neither buffer the stack supplies on transmit has any.
lwip_output_callback() passes a static uint8_t[1536] for a chained pbuf, so the
write lands in whatever precedes that array in .bss, and pbuf->payload for a
single one, where ETH_PAD_SIZE is 0 and PBUF_LINK_ENCAPSULATION_HLEN is left at
its default of 0, so it lands in the pbuf's own metadata or the neighbouring
pool entry. It is a plain CPU write, so no DMA behaviour is needed to trigger
it, and where it lands depends on the link order.

Header and frame are now assembled in a driver-owned buffer. bulk_out() holds
the USB mutex until the transfer has completed, so one buffer is enough. The
length is checked against it rather than trusted.

Incidentally that buffer comes from the allocator, so what reaches bulk_out()
is word aligned, which the two stack buffers were not required to be.

Reported in GideonZ#822, problem 1.
`ram_buffer` is `new uint8_t[(NUM_BUFFERS * 1536) + 256]` and was released with
plain `delete`, which is undefined behaviour for an array. Noticed only because
the previous change puts a correct `delete[]` on the line below it.

Nothing to do with GideonZ#822; it is a one word correction in a
destructor that this branch already touches.
Both fixes in this PR are about what leaves the device, and neither could be
checked anywhere but on the machine, because the decision lived inline in a
driver method that only builds for the target. Lift the two decisions into free
functions over plain integers, the way software/drive/gcr_track_bounds.h does
it, and pin them down on a build host.

eth_tx_frame_to_send() chooses the buffer and length to transmit: a frame of 60
bytes or more goes out of the caller's buffer untouched, a shorter one is copied
into the driver's pad buffer and zero filled. ax88772_tx_block() assembles the
four byte length header and the frame in the driver's own buffer and returns how
much to send, or -1 for a frame that does not fit.

The tests state the property rather than the implementation: fill the memory
around the frame with a sentinel byte, then require that no sentinel is inside
what the function says to transmit. That is exactly the leak -- 18 bytes of the
neighbouring heap block on every 42 byte ARP request -- and it is checked for
every short length from 0 to 59. The AX88772 case guards the eight bytes in
front of both buffers, since the header used to be written in front of the one
the network stack owns.

Ten cases, wired into the build workflow next to the UCI palette test. Against
this commit all ten pass. Against a header restored to the two pre-fix
behaviours -- pad the length but not the data, and write the header at
frame - 4 -- nine of the ten fail; the tenth is the path that does not change,
a frame of 60 bytes or more transmitted from the caller's buffer.

Still not covered here, and still needing the machine: the sentinel word in
front of the driver's transmit buffer on a live system, and an ARP capture off
the LAN showing the padding bytes are zero.
@enver-haase
enver-haase force-pushed the fix/usb-net-buffer-bounds branch from ca4d815 to 6a15ed2 Compare September 16, 2026 02:06
… green

The suite pinned the two decisions but not at every length GideonZ#843 asked for, and
it guarded only the memory in front of each buffer. A leak past the end is what
problem 4 actually was, so that was the wrong side to watch.

Both contracts are now checked with eight sentinel bytes in front of the frame
and eight behind it, at the lengths from the review: 0, 1, 1500, 1536 and 1537
for the AX88772 block, where 1537 is one byte too many and has to be refused,
and 42, 59 and 60 for the RMII path. Each case asserts the four byte header,
length little endian then each byte complemented, the payload byte for byte,
that the padding is zero and not the neighbour, and that the caller's buffer
comes back exactly as it went in.

The red half is new. eth_tx_frame_legacy.h models what the two drivers did to
memory before the fix -- the AX88772 header at frame - 4, and a short frame
whose length register was raised to 60 while the data was not -- and the same
suite runs against it. It is a model of the defect, not of the device, and no
firmware builds it.

  against this commit             12 passed
  against the pre-fix behaviour   11 failed

The one that stays green either way is the control case: a frame of 60 bytes or
more goes out of the caller's buffer untouched in both versions, and must.

`make -C software/io/network/tests` now runs both halves, and the red one fails
the build if it ever passes, so a later change that guts the checks is caught
here instead of going quiet.
This reverts commit 3e37859.

Problem 5 of GideonZ#822 is USB, not networking, and it only travelled in this PR
because the sweep that found it also found the two transmit defects. It now has
its own branch, where it is joined by the change that makes the class of defect
impossible -- a single exit for the mutex -- and by the red/green measurement
from a C64 Ultimate that the two together deserve.

Reverted here rather than dropped, so this PR stays a fast-forward and the
review on it keeps its anchors.

What remains in this PR is the network half: the AX88772 length header, the
short-frame padding, the delete[], and the host tests that pin all of it.
@enver-haase

Copy link
Copy Markdown
Contributor Author

@chrisgleissner — all three items are answered, and problem 4 is now measured at the wire as well as on a build host.

(1) and (2), the two transmit paths: host tests at exactly the lengths you named, canaries on both sides of every buffer — a leak past the end is what problem 4 actually was — with the four-byte header and complements checked, payload compared byte for byte, padding asserted zero, and the caller's buffer asserted unchanged. Wired into CI. 12 passed against the branch, 11 failed against eth_tx_frame_legacy.h, a model of the pre-fix drivers. The twelfth is the control case: a 60 byte frame transmits from the caller's buffer in both versions and must stay green. make fails the build if the red half ever passes, so the checks cannot be quietly gutted later.

The ARP capture you asked for. A C64 Ultimate on a direct cable to a capturing host, its Ethernet given a static address whose gateway does not exist, so it repeats ARP requests: 42 bytes of ARP, padded to Ethernet's 60. Same machine, same cable, same analysis script; only the firmware changed between the two runs.

unfixed (f0ec31cc1)   24 requests    0 zero-padded   24 carrying other bytes   14 distinct patterns
fixed   (6720894a4)   17 requests   17 zero-padded    0 carrying other bytes    1 pattern

The counts differ because the two capture windows caught different numbers of retries. What matters is that not one frame in the first run was zero and not one in the second was anything else.

The leaked bytes are readable. Bytes 42..59 of three frames from the unfixed device:

00 40 ec 01 00 38 2e 38 22 0a 7d 2c 0a 20 20 22 65 72    ".@...8.8".},.  "er"
00 40 ec 01 00 01 00 00 00 00 00 00 04 70 6f 6f 6c 03    ".@...........pool."
00 40 f4 00 00 b4 00 35 00 2a e1 9b 7f 78 01 00 00 01    ".@.....5.*..x...."

The first is a fragment of a REST response — 8.8" is the tail of 8.8.8.8, then "},\n "er beginning "errors". The second is a DNS query: 04 70 6f 6f 6c is the length-prefixed label pool, from pool.ntp.org. The third carries 00 35, port 53, and a UDP length of 42. So this is not "undefined bytes" in the abstract: every address resolution broadcasts eighteen bytes of whatever last used that heap.

(3) control_exchange: moved to #915 rather than host-tested here. usb_base.cc reaches the Nano core through about fifty hardware symbols, and faking them to get it onto a build host fakes away the thing under test. It is measured on the device instead, red and green, with a debug probe that is not in either branch.

That measurement corrects something in this PR: the wait is 25 seconds, not 5. xSemaphoreTake() counts ticks and configTICK_RATE_HZ is 200, so the 5000 in that file is 25 s. Measured: 24997 ms unfixed, 0 ms fixed. The "five seconds" in the description above was mine and it was wrong.

Built: make u64ii_no_esp in ghcr.io/gideonz/riscv, from a tree with every output/ and result/ under target/ removed first: 431 files compiled, exit 0, zero errors, no new warning from usb_ax88772.cc or rmii_interface.cc.

@chrisgleissner

chrisgleissner commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Excellent work. Many thanks @enver-haase

@GideonZ I think this is merge ready based on the analysis of Enver. Do you agree?

@chrisgleissner chrisgleissner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-reviewed the current head adversarially, including the new shared-buffer lifetime/serialization assumptions. I found no actionable issue.

The AX88772 block is bounds-checked before assembly, uses the existing uncached alias convention, and remains live through the synchronous bulk_out(). The RMII pad remains live until RMII_TX_BUSY clears, and lwIP serializes the link-output path, so the single pad buffer does not introduce a concurrent reuse window. The 0/1/1500/1536/1537 and 42/59/60 cases pass locally; the green suite also passes under ASan+UBSan with -Werror. CI is green and compiled both changed drivers across its target matrix. The on-wire red/green capture directly covers the RMII disclosure fix.

Approving.

@enver-haase

Copy link
Copy Markdown
Contributor Author

@GideonZ — a gentle nudge on this one. Approved since 17 September, CI green, and it still merges cleanly against master.

Problem 4 is the part I would not leave sitting: the RMII length register was raised to 60 while the data was not, so every ARP request puts 18 bytes of the neighbouring heap block on the wire. Measured on hardware, the padding was readable — fragments of REST answers and a DNS label.

Happy to rebase it, split the delete[] commit out, or answer anything that is in the way.

@chrisgleissner chrisgleissner added 3.15 Targeted for release 3.15. and removed 3.16 Targeted for release 3.16. labels Oct 2, 2026
@chrisgleissner

Copy link
Copy Markdown
Collaborator

Merged master into this branch (7e877b0) and shortened the comments in eth_tx_frame.h, rmii_interface.cc and usb_ax88772.cc (20d84e2). The second commit changes comments only.

What this PR fixes

  • RMII (the built-in Ethernet port on U64, U64 Elite II / C64 Ultimate, U2+ and U2+L). The driver set RMII_TX_LENGTH to 60 for a shorter frame but did not pad the data, so the transmit engine sent up to 18 bytes of whatever followed the frame in memory. ARP packets, small ICMP echo replies and other frames under 60 bytes all carried those bytes. Short frames are now copied into a driver-owned buffer and zero filled.
  • AX88772 (USB-to-Ethernet adapters only, on every target with USB networking, including the U2). The driver wrote the 4-byte length header at buffer - 4, in front of a buffer that lwIP owns and that has no headroom, so it overwrote neighbouring memory on every transmitted frame. The header and frame are now assembled in a driver-owned buffer.

Build

With the merge, u64, u64ii, u2, u2plus and u2pl all compile. On u2 and u2plus the application links and only the local packaging step stops, on an artifact that a software-only build does not produce. The u2 application is 768,320 bytes, within its 811,008-byte partition. make -C software/io/network/tests gives 12 passes on the fix and 11 failures on the pre-fix model.

Hardware

I captured every frame shorter than 60 bytes sent by the device over 15 seconds of REST requests and zero-payload pings, and checked the padding bytes:

Device Firmware Zero padding Other bytes
C64 Ultimate flashed 1.2.1RC 0 409
C64 Ultimate master 7117d88, JTAG 0 427
C64 Ultimate this PR 7e877b0, JTAG 429 0
U2+L flashed 3.15 (46f8005) 0 274
U2+L this PR, CI build 46d506d, flashed 264 0

On both devices running this PR, pings with payloads of 0 to 40, 1400 and 1472 bytes, a 300 KB FTP upload and download with byte comparison, and REST, FTP and Telnet health checks all passed.

Not tested on hardware: the U64 and the U2+, which use the same RMII driver, and the AX88772 path, because no USB Ethernet adapter was available. The AX88772 change is covered by the host tests and the builds only.

@chrisgleissner
chrisgleissner merged commit 6c2880d into GideonZ:master Oct 2, 2026
1 check passed
@enver-haase

Copy link
Copy Markdown
Contributor Author

No, not yet. There may be an AX88772 adapter in my office; I'll check there. If there isn't one, I'll order a UGREEN USB 2.0 10/100 adapter, which lists an AX88772A, and report the FTP round trip on master and on this branch once it has run.

@enver-haase
enver-haase deleted the fix/usb-net-buffer-bounds branch October 4, 2026 05:12
@enver-haase

Copy link
Copy Markdown
Contributor Author

@chrisgleissner @GideonZ The AX88772 run on hardware that I promised above (FTP round trip, master vs. this change) has not happened: the delivery of the adapter I ordered was cancelled. Is it still wanted now that this is merged? If so, I'll order another adapter and post the run here. If the host tests are enough for the AX88772 path, I'll drop the follow-up from the description.

chrisgleissner pushed a commit that referenced this pull request Oct 22, 2026
My Ethernet driver work (#843) is finished, so a network change has no
reason to wait for me. The row keeps the drive code I still work on.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

3.15 Targeted for release 3.15. bug Existing behavior is incorrect, broken, or regressed; includes supported documentation defects.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants