From 239de7191f7a5ec1f6fdb72f53a87beede153429 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jos=C3=A9=20Roberto=20de=20Souza?= <jose.souza@intel.com>
Date: Mon, 16 Oct 2017 11:02:03 -0700
Subject: [PATCH] dataman: Prevent database corruption

The size in g_per_item_size[item] is the real struct size
+ DM_SECTOR_HDR_SIZE bytes of header and the backend functions were
not taking in care it. So a call to dm_write() with more bytes than
the real struct is allowed, causing corruption in the header of the
next item.

Kudos to jeonghwan-lee for finding it. https://github.com/PX4/Firmware/issues/7927
---
 src/modules/dataman/dataman.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/modules/dataman/dataman.cpp b/src/modules/dataman/dataman.cpp
index 4de8f5d828..96c928c900 100644
--- a/src/modules/dataman/dataman.cpp
+++ b/src/modules/dataman/dataman.cpp
@@ -470,7 +470,7 @@ static ssize_t _ram_write(dm_item_t item, unsigned index, dm_persitence_t persis
 	}
 
 	/* Make sure caller has not given us more data than we can handle */
-	if (count > g_per_item_size[item]) {
+	if (count > (g_per_item_size[item] - DM_SECTOR_HDR_SIZE)) {
 		return -E2BIG;
 	}
 
@@ -511,7 +511,7 @@ _file_write(dm_item_t item, unsigned index, dm_persitence_t persistence, const v
 	}
 
 	/* Make sure caller has not given us more data than we can handle */
-	if (count > g_per_item_size[item]) {
+	if (count > (g_per_item_size[item] - DM_SECTOR_HDR_SIZE)) {
 		return -E2BIG;
 	}
 
@@ -581,7 +581,7 @@ static ssize_t _ram_read(dm_item_t item, unsigned index, void *buf, size_t count
 	}
 
 	/* Make sure the caller hasn't asked for more data than we can handle */
-	if (count > g_per_item_size[item]) {
+	if (count > (g_per_item_size[item] - DM_SECTOR_HDR_SIZE)) {
 		return -E2BIG;
 	}
 
@@ -624,7 +624,7 @@ _file_read(dm_item_t item, unsigned index, void *buf, size_t count)
 	}
 
 	/* Make sure the caller hasn't asked for more data than we can handle */
-	if (count > g_per_item_size[item]) {
+	if (count > (g_per_item_size[item] - DM_SECTOR_HDR_SIZE)) {
 		return -E2BIG;
 	}
 
-- 
GitLab