Welcome to little lamb

Code » anopa » commit e6461cc

Fix possible memory corruption

author Olivier Brunel
2016-09-11 11:53:44 UTC
committer Olivier Brunel
2016-09-11 14:23:21 UTC
parent 3a13f4d31fc5e8c7173100b6be78d92105edff61

Fix possible memory corruption

openreadfileclose() means to automatically enlarge the given stralloc
according to the passed limit *if needed*, i.e. it will not necesarilly
do so; It might not enlarge it, or only to fit the data read from the
file.

So assuming that svst->sa had been enlarged up to the possible limit was
wrong, and could result in writing to svst->sa.s[svst->sa.len] as out of
bounds write, leading to memory corruption.

Thanks to John O'M. for reporting & tracking this; Closes #5

src/libanopa/service_status.c +10 -3

diff --git a/src/libanopa/service_status.c b/src/libanopa/service_status.c
index 0d53cf1..68a9e4b 100644
--- a/src/libanopa/service_status.c
+++ b/src/libanopa/service_status.c
@@ -44,10 +44,15 @@ aa_service_status_read (aa_service_status *svst, const char *dir)
     char file[len + 1 + sizeof (AA_SVST_FILENAME)];
     uint32 u;
 
+    /* most cases should be w/out a message, so we'll only need FIXED_SIZE and
+     * one extra byte to NUL-terminate the (empty) message */
+    if (!stralloc_ready_tuned (&svst->sa, AA_SVST_FIXED_SIZE + 1, 0, 0, 1))
+        return -1;
+
     byte_copy (file, len, dir);
     byte_copy (file + len, 1 + sizeof (AA_SVST_FILENAME), "/" AA_SVST_FILENAME);
 
-    if (!openreadfileclose (file, &svst->sa, AA_SVST_FIXED_SIZE + AA_SVST_MAX_MSG_SIZE + 1)
+    if (!openreadfileclose (file, &svst->sa, AA_SVST_FIXED_SIZE + AA_SVST_MAX_MSG_SIZE)
             || svst->sa.len < AA_SVST_FIXED_SIZE)
     {
         int e = errno;
@@ -57,9 +62,11 @@ aa_service_status_read (aa_service_status *svst, const char *dir)
     }
     tain_now_g ();
 
+    if (svst->sa.len >= svst->sa.a
+            && !stralloc_ready_tuned (&svst->sa, svst->sa.len + 1, 0, 0, 1))
+        return -1;
     svst->sa.s[svst->sa.len] = '\0';
-    if (svst->sa.len < AA_SVST_FIXED_SIZE + AA_SVST_MAX_MSG_SIZE + 1)
-        svst->sa.len++;
+    svst->sa.len++;
 
     tain_unpack (svst->sa.s, &svst->stamp);
     uint32_unpack (svst->sa.s + 12, &u);