]> git.ipfire.org Git - thirdparty/asterisk.git/commitdiff
general: Fix memory Corruption in __ast_string_field_ptr_build_va.
authorWalter Doekes <walter+asterisk@wjd.nu>
Mon, 11 Aug 2014 10:24:06 +0000 (10:24 +0000)
committerWalter Doekes <walter+asterisk@wjd.nu>
Mon, 11 Aug 2014 10:24:06 +0000 (10:24 +0000)
If the space left in a stringfield is between 0 and
(alignof(ast_string_field_allocation)-1) adding new data would cause
memory corruption, because we would assume enough space (unsigned
underrun).

Thanks Arnd Schmitter for reporting and finding out the cause!

ASTERISK-23508 #close
Reported by: Arnd Schmitter
Tested by: Arnd Schmitter, JoshE

Review: https://reviewboard.asterisk.org/r/3898/

git-svn-id: https://origsvn.digium.com/svn/asterisk/branches/1.8@420680 65c4cc65-6c06-0410-ace0-fbb531ad65f3

main/utils.c

index 93c1f1bf82071054688d625508871b887adf84ab..1bb6e76a4640b1828913916f4ffda6cfc6a75ebe 100644 (file)
@@ -1913,6 +1913,7 @@ void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
        size_t needed;
        size_t available;
        size_t space = (*pool_head)->size - (*pool_head)->used;
+       int res;
        ssize_t grow;
        char *target;
 
@@ -1931,10 +1932,19 @@ void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
                 * so we don't need to re-align anything here.
                 */
                target = (*pool_head)->base + (*pool_head)->used + ast_alignof(ast_string_field_allocation);
-               available = space - ast_alignof(ast_string_field_allocation);
+               if (space > ast_alignof(ast_string_field_allocation)) {
+                       available = space - ast_alignof(ast_string_field_allocation);
+               } else {
+                       available = 0;
+               }
        }
 
-       needed = vsnprintf(target, available, format, ap1) + 1;
+       res = vsnprintf(target, available, format, ap1);
+       if (res < 0) {
+               /* Are we out of memory? */
+               return;
+       }
+       needed = (size_t)res + 1; /* NUL byte */
 
        if (needed > available) {
                /* the allocation could not be satisfied using the field's current allocation
@@ -1953,7 +1963,8 @@ void __ast_string_field_ptr_build_va(struct ast_string_field_mgr *mgr,
                */
                __ast_string_field_release_active(*pool_head, *ptr);
                mgr->last_alloc = *ptr = target;
-               AST_STRING_FIELD_ALLOCATION(target) = needed;
+               ast_assert(needed < (ast_string_field_allocation)-1);
+               AST_STRING_FIELD_ALLOCATION(target) = (ast_string_field_allocation)needed;
                (*pool_head)->used += ast_make_room_for(needed, ast_string_field_allocation);
                (*pool_head)->active += needed;
        } else if ((grow = (needed - AST_STRING_FIELD_ALLOCATION(*ptr))) > 0) {