chiark / gitweb /
integer and buffer overflows: introduce safe_malloc_ary
[secnet.git] / util.c
diff --git a/util.c b/util.c
index 997979ac93b4e99b498602077f72519755eb68c6..44a45e50d4c22d0c19350e9277e91d93d4ed65c3 100644 (file)
--- a/util.c
+++ b/util.c
@@ -74,6 +74,12 @@ void *safe_malloc(size_t size, const char *message)
     }
     return r;
 }
+void *safe_malloc_ary(size_t size, size_t count, const char *message) {
+    if (count >= INT_MAX/size) {
+       fatal("array allocation overflow: %s", message);
+    }
+    return safe_malloc(size*count, message);
+}
 
 /* Convert a buffer into its MP_INT representation */
 void read_mpbin(MP_INT *a, uint8_t *bin, int binsize)
@@ -243,12 +249,14 @@ void buffer_init(struct buffer_if *buffer, uint32_t max_start_pad)
 
 void *buf_append(struct buffer_if *buf, uint32_t amount) {
     void *p;
+    assert(buf->size <= buf->len - amount);
     p=buf->start + buf->size;
     buf->size+=amount;
     return p;
 }
 
 void *buf_prepend(struct buffer_if *buf, uint32_t amount) {
+    assert(amount <= buf->start - buf->base);
     buf->size+=amount;
     return buf->start-=amount;
 }
@@ -273,6 +281,7 @@ void buf_append_string(struct buffer_if *buf, cstring_t s)
     uint16_t len;
 
     len=strlen(s);
+    /* fixme: if string is longer than 65535, result is a corrupted packet */
     buf_append_uint16(buf,len);
     memcpy(buf_append(buf,len),s,len);
 }