mavlink: fix stack buffer overflow in log handler filepath parsing

- Size LogEntry.filepath to PX4_MAX_FILEPATH instead of hardcoded 60 bytes
- Add width specifier to sscanf calls to prevent buffer overflow
- Move platform defines from .cpp to .h for reuse
- Add static_assert to enforce scanf width < buffer size at compile time

Signed-off-by: Ramon Roche <mrpollo@gmail.com>
This commit is contained in:
Ramon Roche 2026-03-02 11:02:15 -08:00
parent f11e2106af
commit 616b25a280
2 changed files with 22 additions and 17 deletions

View File

@ -36,24 +36,14 @@
#include <dirent.h>
#include <sys/stat.h>
static_assert(PX4_MAX_FILEPATH_SCANF < PX4_MAX_FILEPATH,
"sscanf width specifier must be less than filepath buffer size");
static constexpr int MAX_BYTES_BURST = 256 * 1024;
static const char *kLogListFilePath = PX4_STORAGEDIR "/logdata.txt";
static const char *kLogListFilePathTemp = PX4_STORAGEDIR "/$log$.txt";
static const char *kLogDir = PX4_STORAGEDIR "/log";
#ifdef __PX4_NUTTX
#define PX4LOG_REGULAR_FILE DTYPE_FILE
#define PX4LOG_DIRECTORY DTYPE_DIRECTORY
#define PX4_MAX_FILEPATH CONFIG_PATH_MAX
#else
#ifndef PATH_MAX
#define PATH_MAX 1024 // maximum on macOS
#endif
#define PX4LOG_REGULAR_FILE DT_REG
#define PX4LOG_DIRECTORY DT_DIR
#define PX4_MAX_FILEPATH PATH_MAX
#endif
MavlinkLogHandler::MavlinkLogHandler(Mavlink &mavlink)
: _mavlink(mavlink)
{}
@ -174,7 +164,7 @@ void MavlinkLogHandler::state_listing()
char filepath[PX4_MAX_FILEPATH];
// If parsed lined successfully, send the entry
if (sscanf(line, "%" PRIu32 " %" PRIu32 " %s", &time_utc, &size_bytes, filepath) != 3) {
if (sscanf(line, "%" PRIu32 " %" PRIu32 " %" STRINGIFY(PX4_MAX_FILEPATH_SCANF) "s", &time_utc, &size_bytes, filepath) != 3) {
PX4_DEBUG("sscanf failed");
continue;
}
@ -506,7 +496,8 @@ bool MavlinkLogHandler::log_entry_from_id(uint16_t log_id, LogEntry *entry)
continue;
}
if (sscanf(line, "%" PRIu32 " %" PRIu32 " %s", &(entry->time_utc), &(entry->size_bytes), entry->filepath) != 3) {
if (sscanf(line, "%" PRIu32 " %" PRIu32 " %" STRINGIFY(PX4_MAX_FILEPATH_SCANF) "s", &(entry->time_utc), &(entry->size_bytes),
entry->filepath) != 3) {
PX4_DEBUG("sscanf failed");
continue;
}

View File

@ -32,10 +32,24 @@
****************************************************************************/
#pragma once
#include <perf/perf_counter.h>
#include "mavlink_bridge_header.h"
#ifdef __PX4_NUTTX
#define PX4LOG_REGULAR_FILE DTYPE_FILE
#define PX4LOG_DIRECTORY DTYPE_DIRECTORY
#define PX4_MAX_FILEPATH CONFIG_PATH_MAX
#define PX4_MAX_FILEPATH_SCANF 255
#else
#ifndef PATH_MAX
#define PATH_MAX 1024 // maximum on macOS
#endif
#define PX4LOG_REGULAR_FILE DT_REG
#define PX4LOG_DIRECTORY DT_DIR
#define PX4_MAX_FILEPATH PATH_MAX
#define PX4_MAX_FILEPATH_SCANF 1023
#endif
class Mavlink;
class MavlinkLogHandler
@ -53,7 +67,7 @@ private:
uint32_t time_utc{};
uint32_t size_bytes{};
FILE *fp{nullptr};
char filepath[60];
char filepath[PX4_MAX_FILEPATH];
uint32_t offset{};
};