MQTT publish ignores given payload length (truncates data at null byte OR creates a buffer overflow, possibly spilling sensitive information, if the payload does not contain any null byte)
- Dominant language
- No language data
- Stars
- 313
- Forks
- 40
- PR merge metrics
- No merged PRs in 30d
Description
### The problem
When calling id(mqtt_client).publish() in a lambda the data will be truncated at a null byte or will lead to a buffer overflow even when using the overloaded publish function in the following version that specifies a payload length:
`bool MQTTClientComponent::publish(const std::string &topic, const char *payload, size_t payload_length, uint8_t qos, bool retain);`
The only statement in the function body is:
`return publish({.topic = topic, .payload = payload, .qos = qos, .retain = retain});`
This ignores `payload_length` completely and implicitly casts the char* to a std::string without any checking. The data will either be truncated at the first null byte (meaning the MQTT message is incomplete) OR, and that is much worse and could even be a security issue, the MQTT message is longer than specified and will contain garbage data (or sensitive information) up to the first null byte in memory after the payload.
The correct `publish` function to call instead exists in the mqtt_backend:
`bool publish(const char *topic, const char *payload, size_t length, uint8_t qos, bool retain) final`
The result of the following will not be an MQTT message with the expected content of "01234" (the first 5 bytes), but be the full "0123456789". Ignore that it is counterintuitive to only send part of a "string". This is an example for the buffer overflow.
```
size_t data_length = 5;
char buffer[] = "0123456789";
id(mqtt_client).publish("/buffer_overflow", buffer, data_length);
```
### Which version of ESPHome has the issue?
2024.8.3
### What type of installation are you using?
Home Assistant Add-on
### Which version of Home Assistant has the issue?
2024.8.2
### What platform are you using?
ESP32
### Board
NodeMCU ESP-C3
### Component causing the issue
MQTT
### Example YAML snippet
_No response_
### Anything in the logs that might be useful for us?
_No response_
### Additional information
_No response_
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.