diff mbox series

[BlueZ,15/15] android/handsfree: Check sprintf retval

Message ID 20240516090340.61417-16-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): [#def62] [important]
bluez-5.75/android/handsfree.c:1247:15: error[cpp/NegativeIndex]: The value from sprintf, 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.
1245|			buf = g_malloc(len);
1246|
1247|->			ptr = buf + sprintf(buf, "+CIND:");
1248|
1249|			for (i = 0; i < IND_COUNT; i++) {
---
 android/handsfree.c | 14 +++++++++++---
 1 file changed, 11 insertions(+), 3 deletions(-)
diff mbox series

Patch

diff --git a/android/handsfree.c b/android/handsfree.c
index 2365356c2cf7..7b803fae5263 100644
--- a/android/handsfree.c
+++ b/android/handsfree.c
@@ -1243,15 +1243,22 @@  static void at_cmd_cind(struct hfp_context *result, enum hfp_gw_cmd_type type,
 		}
 
 		buf = g_malloc(len);
-
-		ptr = buf + sprintf(buf, "+CIND:");
+		if (sprintf(buf, "+CIND:") != strlen("+CIND:")) {
+			g_free(buf);
+			break;
+		}
+		ptr = buf + strlen("+CIND:");
 
 		for (i = 0; i < IND_COUNT; i++) {
-			ptr += sprintf(ptr, "(\"%s\",(%d%c%d)),",
+			int printed;
+			printed = sprintf(ptr, "(\"%s\",(%d%c%d)),",
 					dev->inds[i].name,
 					dev->inds[i].min,
 					dev->inds[i].max == 1 ? ',' : '-',
 					dev->inds[i].max);
+			if (printed < 0)
+				goto fail;
+			ptr += printed;
 		}
 
 		ptr--;
@@ -1273,6 +1280,7 @@  static void at_cmd_cind(struct hfp_context *result, enum hfp_gw_cmd_type type,
 		break;
 	}
 
+fail:
 	hfp_gw_send_result(dev->gw, HFP_RESULT_ERROR);
 
 	if (dev->state != HAL_EV_HANDSFREE_CONN_STATE_SLC_CONNECTED)