diff mbox series

[BlueZ,13/15] gdbus: Check sprintf retval

Message ID 20240516090340.61417-14-hadess@hadess.net
State New
Headers show
Series Fix a number of static analysis issues #2 | expand

Commit Message

Bastien Nocera May 16, 2024, 9:03 a.m. UTC
Error: SNYK_CODE_WARNING (CWE-125): [#def63] [important]
bluez-5.75/gdbus/watch.c:131:11: error[cpp/NegativeIndex]: The value from snprintf, a standard library function that can return a negative value is used as an index. A negative array index can lead to reading or writing outside the bounds of the array. Ensure the value of the index used is within bounds before use.
129|	int offset;
130|
131|->	offset = snprintf(rule, size, "type='signal'");
132|	sender = data->name ? : data->owner;
133|
---
 gdbus/watch.c | 46 ++++++++++++++++++++++++++++++++++------------
 1 file changed, 34 insertions(+), 12 deletions(-)
diff mbox series

Patch

diff --git a/gdbus/watch.c b/gdbus/watch.c
index 25f367613a52..22f77ea72861 100644
--- a/gdbus/watch.c
+++ b/gdbus/watch.c
@@ -123,29 +123,51 @@  static struct filter_data *filter_data_find(DBusConnection *connection)
 	return NULL;
 }
 
-static void format_rule(struct filter_data *data, char *rule, size_t size)
+static gboolean format_rule(struct filter_data *data, char *rule, size_t size)
 {
 	const char *sender;
-	int offset;
+	int offset, ret;
 
 	offset = snprintf(rule, size, "type='signal'");
+	if (offset < 0)
+		return FALSE;
 	sender = data->name ? : data->owner;
 
-	if (sender)
-		offset += snprintf(rule + offset, size - offset,
+	if (sender) {
+		ret = snprintf(rule + offset, size - offset,
 				",sender='%s'", sender);
-	if (data->path)
-		offset += snprintf(rule + offset, size - offset,
+		if (ret < 0)
+			return FALSE;
+		offset += ret;
+	}
+	if (data->path) {
+		ret = snprintf(rule + offset, size - offset,
 				",path='%s'", data->path);
-	if (data->interface)
-		offset += snprintf(rule + offset, size - offset,
+		if (ret < 0)
+			return FALSE;
+		offset += ret;
+	}
+	if (data->interface) {
+		ret = snprintf(rule + offset, size - offset,
 				",interface='%s'", data->interface);
-	if (data->member)
-		offset += snprintf(rule + offset, size - offset,
+		if (ret < 0)
+			return FALSE;
+		offset += ret;
+	}
+	if (data->member) {
+		ret = snprintf(rule + offset, size - offset,
 				",member='%s'", data->member);
-	if (data->argument)
-		snprintf(rule + offset, size - offset,
+		if (ret < 0)
+			return FALSE;
+		offset += ret;
+	}
+	if (data->argument) {
+		ret = snprintf(rule + offset, size - offset,
 				",arg0='%s'", data->argument);
+		if (ret < 0)
+			return FALSE;
+	}
+	return TRUE;
 }
 
 static gboolean add_match(struct filter_data *data,