Skip to content

fix(mqtt): prevent stack buffer overrun when parsing command topics - #3256

Open
mathieucarbou wants to merge 1 commit into
tbnobody:masterfrom
mathieucarbou:fix/mqtt_stack_overrun
Open

mathieucarbou wants to merge 1 commit into
tbnobody:masterfrom
mathieucarbou:fix/mqtt_stack_overrun

Conversation

@mathieucarbou

Copy link
Copy Markdown
Contributor

onMqttMessage() copied the received MQTT topic into a fixed 72-byte stack buffer (MQTT_MAX_TOPIC_STRLEN + 40) using strncpy() without guaranteeing NUL termination.

The subscribed command topics follow the pattern
//cmd/, where the longest command subtopic is 'limit_nonpersistent_relative' (27 chars). With the maximum allowed prefix (32 chars) the fully qualified topic is up to 77 characters and therefore longer than the buffer. strncpy() then left the buffer unterminated, and the subsequent strlen(), strtok_r() and strtoull() read past its end, corrupting the stack of the mqttclient task.

Fix this by sizing the copy from the actual topic length, guaranteeing NUL termination. Also make sure the configured prefix is part of the received topic before indexing past it.

@mathieucarbou

Copy link
Copy Markdown
Contributor Author

Note: I have included this fix in my dev branch and runs with it today.

@mathieucarbou

Copy link
Copy Markdown
Contributor Author

@tbnobody Will this fix be included in next release ?

@tbnobody

Copy link
Copy Markdown
Owner

Thank you. Will include it in the next release

onMqttMessage() copied the received MQTT topic into a fixed 72-byte
stack buffer (MQTT_MAX_TOPIC_STRLEN + 40) using strncpy() without
guaranteeing NUL termination.

The subscribed command topics follow the pattern
<prefix>/<serial>/cmd/<command>, where the longest command subtopic is
'limit_nonpersistent_relative' (27 chars). With the maximum allowed
prefix (32 chars) the fully qualified topic is up to 77 characters and
therefore longer than the buffer. strncpy() then left the buffer
unterminated, and the subsequent strlen(), strtok_r() and strtoull()
read past its end, corrupting the stack of the mqttclient task.

Fix this by sizing the copy from the actual topic length, guaranteeing
NUL termination. Also make sure the configured prefix is part of the
received topic before indexing past it.
@mathieucarbou

Copy link
Copy Markdown
Contributor Author

Note: commit added in latest OpenDTU Zero-Export release v26.11.11-ze1 rebased on latest OpenDTU version v26.11.11

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