CAN_PACKET_FILL_RX_BUFFER(_LONG): a frame shorter than its header makes `len` negative before memcpy

Open Beginner friendly
#993 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
77/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
c
Domain
embedded-iot

Research direction

Read comm/comm_can.c around decode_msg and the CAN_PACKET_FILL_RX_BUFFER and _LONG cases. Check how each case handles the frame DLC before reading payload bytes or calculating the copy length, then review existing CAN receive tests if available. Done means short frames are rejected before unsafe reads or copies, with coverage for DLC 0 and 1.

Written by the indexing model from the issue text.

Description

Hi, I think a CAN frame with too few data bytes can make decode_msg call memcpy with a negative length.

The bug

In comm/comm_can.c (L1652-L1675):

case CAN_PACKET_FILL_RX_BUFFER: {
    int buf_ind = -1;
    int offset = data8[0];
    data8++;
    len--;
    /* … find buf_ind; offset 0 selects buffer 0 … */
    memcpy(rx_buffer[buf_ind] + offset, data8, len);
  • len is the frame's DLC and is not checked. With DLC 0, len becomes -1 and memcpy gets (size_t)-1. offset is read from a data byte the frame doesn't have, so whether the copy happens depends on that stale value (0, or an offset already in progress, gets through).
  • CAN_PACKET_FILL_RX_BUFFER_LONG (L1677-L1703) has a bounds check, (offset + len) <= RX_BUFFER_SIZE, but with DLC 0 or 1 len is -2 or -1 and the check passes.
  • decode_msg accepts the broadcast id 255 (L1615), so any node on the bus can send this.
What it costs

One malformed frame can hard-fault the controller. I found it by reading the code and have not reproduced it on hardware.

Where it came from

The lines are on master (0d4b313). git blame points to 0dec878 (2023-01-02, "Multiple CAN RX buffers").

Fix
case CAN_PACKET_FILL_RX_BUFFER: {
    if (len < 1) {
        break;
    }
/* … */
case CAN_PACKET_FILL_RX_BUFFER_LONG: {
    if (len < 2) {
        break;
    }
Dominant language
C
Stars
3.6k
Forks
2k
Avg merge
20h 29m
Merged PRs (30d)
12

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from vedderb/bldc

All issues in vedderb/bldc

Similar issues

More C issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.