Blame SOURCES/redis-CVE-2021-32627.patch

e8abc3
From f6a40570fa63d5afdd596c78083d754081d80ae3 Mon Sep 17 00:00:00 2001
e8abc3
From: Oran Agra <oran@redislabs.com>
e8abc3
Date: Thu, 3 Jun 2021 12:10:02 +0300
e8abc3
Subject: [PATCH] Fix ziplist and listpack overflows and truncations
e8abc3
 (CVE-2021-32627, CVE-2021-32628)
e8abc3
e8abc3
- fix possible heap corruption in ziplist and listpack resulting by trying to
e8abc3
  allocate more than the maximum size of 4GB.
e8abc3
- prevent ziplist (hash and zset) from reaching size of above 1GB, will be
e8abc3
  converted to HT encoding, that's not a useful size.
e8abc3
- prevent listpack (stream) from reaching size of above 1GB.
e8abc3
- XADD will start a new listpack if the new record may cause the previous
e8abc3
  listpack to grow over 1GB.
e8abc3
- XADD will respond with an error if a single stream record is over 1GB
e8abc3
- List type (ziplist in quicklist) was truncating strings that were over 4GB,
e8abc3
  now it'll respond with an error.
e8abc3
---
e8abc3
 src/geo.c                 |   5 +-
e8abc3
 src/listpack.c            |   2 +-
e8abc3
 src/quicklist.c           |  17 ++++-
e8abc3
 src/rdb.c                 |  36 ++++++---
e8abc3
 src/server.h              |   2 +-
e8abc3
 src/t_hash.c              |  13 +++-
e8abc3
 src/t_list.c              |  30 ++++++++
e8abc3
 src/t_stream.c            |  48 +++++++++---
e8abc3
 src/t_zset.c              |  43 +++++++----
e8abc3
 src/ziplist.c             |  17 ++++-
e8abc3
 src/ziplist.h             |   1 +
e8abc3
 tests/support/util.tcl    |  18 ++++-
e8abc3
 tests/unit/violations.tcl | 156 ++++++++++++++++++++++++++++++++++++++
e8abc3
 13 files changed, 339 insertions(+), 49 deletions(-)
e8abc3
 create mode 100644 tests/unit/violations.tcl
e8abc3
e8abc3
diff --git a/src/geo.c b/src/geo.c
e8abc3
index 5c505441486c..a8710cd8b3ae 100644
e8abc3
--- a/src/geo.c
e8abc3
+++ b/src/geo.c
e8abc3
@@ -635,7 +635,7 @@ void georadiusGeneric(client *c, int flags) {
e8abc3
         robj *zobj;
e8abc3
         zset *zs;
e8abc3
         int i;
e8abc3
-        size_t maxelelen = 0;
e8abc3
+        size_t maxelelen = 0, totelelen = 0;
e8abc3
 
e8abc3
         if (returned_items) {
e8abc3
             zobj = createZsetObject();
e8abc3
@@ -650,13 +650,14 @@ void georadiusGeneric(client *c, int flags) {
e8abc3
             size_t elelen = sdslen(gp->member);
e8abc3
 
e8abc3
             if (maxelelen < elelen) maxelelen = elelen;
e8abc3
+            totelelen += elelen;
e8abc3
             znode = zslInsert(zs->zsl,score,gp->member);
e8abc3
             serverAssert(dictAdd(zs->dict,gp->member,&znode->score) == DICT_OK);
e8abc3
             gp->member = NULL;
e8abc3
         }
e8abc3
 
e8abc3
         if (returned_items) {
e8abc3
-            zsetConvertToZiplistIfNeeded(zobj,maxelelen);
e8abc3
+            zsetConvertToZiplistIfNeeded(zobj,maxelelen,totelelen);
e8abc3
             setKey(c,c->db,storekey,zobj);
e8abc3
             decrRefCount(zobj);
e8abc3
             notifyKeyspaceEvent(NOTIFY_ZSET,"georadiusstore",storekey,
e8abc3
diff --git a/src/listpack.c b/src/listpack.c
e8abc3
index f8c34429ec1e..6c111e83e029 100644
e8abc3
--- a/src/listpack.c
e8abc3
+++ b/src/listpack.c
e8abc3
@@ -283,7 +283,7 @@ int lpEncodeGetType(unsigned char *ele, uint32_t size, unsigned char *intenc, ui
e8abc3
     } else {
e8abc3
         if (size < 64) *enclen = 1+size;
e8abc3
         else if (size < 4096) *enclen = 2+size;
e8abc3
-        else *enclen = 5+size;
e8abc3
+        else *enclen = 5+(uint64_t)size;
e8abc3
         return LP_ENCODING_STRING;
e8abc3
     }
e8abc3
 }
e8abc3
diff --git a/src/quicklist.c b/src/quicklist.c
e8abc3
index 52e3988f59b1..c4bf5274eb05 100644
e8abc3
--- a/src/quicklist.c
e8abc3
+++ b/src/quicklist.c
e8abc3
@@ -29,6 +29,7 @@
e8abc3
  */
e8abc3
 
e8abc3
 #include <string.h> /* for memcpy */
e8abc3
+#include "redisassert.h"
e8abc3
 #include "quicklist.h"
e8abc3
 #include "zmalloc.h"
e8abc3
 #include "ziplist.h"
e8abc3
@@ -43,11 +44,16 @@
e8abc3
 #define REDIS_STATIC static
e8abc3
 #endif
e8abc3
 
e8abc3
-/* Optimization levels for size-based filling */
e8abc3
+/* Optimization levels for size-based filling.
e8abc3
+ * Note that the largest possible limit is 16k, so even if each record takes
e8abc3
+ * just one byte, it still won't overflow the 16 bit count field. */
e8abc3
 static const size_t optimization_level[] = {4096, 8192, 16384, 32768, 65536};
e8abc3
 
e8abc3
 /* Maximum size in bytes of any multi-element ziplist.
e8abc3
- * Larger values will live in their own isolated ziplists. */
e8abc3
+ * Larger values will live in their own isolated ziplists.
e8abc3
+ * This is used only if we're limited by record count. when we're limited by
e8abc3
+ * size, the maximum limit is bigger, but still safe.
e8abc3
+ * 8k is a recommended / default size limit */
e8abc3
 #define SIZE_SAFETY_LIMIT 8192
e8abc3
 
e8abc3
 /* Minimum ziplist size in bytes for attempting compression. */
e8abc3
@@ -449,6 +455,8 @@ REDIS_STATIC int _quicklistNodeAllowInsert(const quicklistNode *node,
e8abc3
     unsigned int new_sz = node->sz + sz + ziplist_overhead;
e8abc3
     if (likely(_quicklistNodeSizeMeetsOptimizationRequirement(new_sz, fill)))
e8abc3
         return 1;
e8abc3
+    /* when we return 1 above we know that the limit is a size limit (which is
e8abc3
+     * safe, see comments next to optimization_level and SIZE_SAFETY_LIMIT) */
e8abc3
     else if (!sizeMeetsSafetyLimit(new_sz))
e8abc3
         return 0;
e8abc3
     else if ((int)node->count < fill)
e8abc3
@@ -468,6 +476,8 @@ REDIS_STATIC int _quicklistNodeAllowMerge(const quicklistNode *a,
e8abc3
     unsigned int merge_sz = a->sz + b->sz - 11;
e8abc3
     if (likely(_quicklistNodeSizeMeetsOptimizationRequirement(merge_sz, fill)))
e8abc3
         return 1;
e8abc3
+    /* when we return 1 above we know that the limit is a size limit (which is
e8abc3
+     * safe, see comments next to optimization_level and SIZE_SAFETY_LIMIT) */
e8abc3
     else if (!sizeMeetsSafetyLimit(merge_sz))
e8abc3
         return 0;
e8abc3
     else if ((int)(a->count + b->count) <= fill)
e8abc3
@@ -487,6 +497,7 @@ REDIS_STATIC int _quicklistNodeAllowMerge(const quicklistNode *a,
e8abc3
  * Returns 1 if new head created. */
e8abc3
 int quicklistPushHead(quicklist *quicklist, void *value, size_t sz) {
e8abc3
     quicklistNode *orig_head = quicklist->head;
e8abc3
+    assert(sz < UINT32_MAX); /* TODO: add support for quicklist nodes that are sds encoded (not zipped) */
e8abc3
     if (likely(
e8abc3
             _quicklistNodeAllowInsert(quicklist->head, quicklist->fill, sz))) {
e8abc3
         quicklist->head->zl =
e8abc3
@@ -510,6 +521,7 @@ int quicklistPushHead(quicklist *quicklist, void *value, size_t sz) {
e8abc3
  * Returns 1 if new tail created. */
e8abc3
 int quicklistPushTail(quicklist *quicklist, void *value, size_t sz) {
e8abc3
     quicklistNode *orig_tail = quicklist->tail;
e8abc3
+    assert(sz < UINT32_MAX); /* TODO: add support for quicklist nodes that are sds encoded (not zipped) */
e8abc3
     if (likely(
e8abc3
             _quicklistNodeAllowInsert(quicklist->tail, quicklist->fill, sz))) {
e8abc3
         quicklist->tail->zl =
e8abc3
@@ -852,6 +864,7 @@ REDIS_STATIC void _quicklistInsert(quicklist *quicklist, quicklistEntry *entry,
e8abc3
     int fill = quicklist->fill;
e8abc3
     quicklistNode *node = entry->node;
e8abc3
     quicklistNode *new_node = NULL;
e8abc3
+    assert(sz < UINT32_MAX); /* TODO: add support for quicklist nodes that are sds encoded (not zipped) */
e8abc3
 
e8abc3
     if (!node) {
e8abc3
         /* we have no reference node, so let's create only node in the list */
e8abc3
diff --git a/src/rdb.c b/src/rdb.c
e8abc3
index ecd2c0e9870a..11cc41b56240 100644
e8abc3
--- a/src/rdb.c
e8abc3
+++ b/src/rdb.c
e8abc3
@@ -1561,7 +1561,7 @@ robj *rdbLoadObject(int rdbtype, rio *rdb, sds key) {
e8abc3
     } else if (rdbtype == RDB_TYPE_ZSET_2 || rdbtype == RDB_TYPE_ZSET) {
e8abc3
         /* Read list/set value. */
e8abc3
         uint64_t zsetlen;
e8abc3
-        size_t maxelelen = 0;
e8abc3
+        size_t maxelelen = 0, totelelen = 0;
e8abc3
         zset *zs;
e8abc3
 
e8abc3
         if ((zsetlen = rdbLoadLen(rdb,NULL)) == RDB_LENERR) return NULL;
e8abc3
@@ -1598,6 +1598,7 @@ robj *rdbLoadObject(int rdbtype, rio *rdb, sds key) {
e8abc3
 
e8abc3
             /* Don't care about integer-encoded strings. */
e8abc3
             if (sdslen(sdsele) > maxelelen) maxelelen = sdslen(sdsele);
e8abc3
+            totelelen += sdslen(sdsele);
e8abc3
 
e8abc3
             znode = zslInsert(zs->zsl,score,sdsele);
e8abc3
             dictAdd(zs->dict,sdsele,&znode->score);
e8abc3
@@ -1605,8 +1606,11 @@ robj *rdbLoadObject(int rdbtype, rio *rdb, sds key) {
e8abc3
 
e8abc3
         /* Convert *after* loading, since sorted sets are not stored ordered. */
e8abc3
         if (zsetLength(o) <= server.zset_max_ziplist_entries &&
e8abc3
-            maxelelen <= server.zset_max_ziplist_value)
e8abc3
-                zsetConvert(o,OBJ_ENCODING_ZIPLIST);
e8abc3
+            maxelelen <= server.zset_max_ziplist_value &&
e8abc3
+            ziplistSafeToAdd(NULL, totelelen))
e8abc3
+        {
e8abc3
+            zsetConvert(o,OBJ_ENCODING_ZIPLIST);
e8abc3
+        }
e8abc3
     } else if (rdbtype == RDB_TYPE_HASH) {
e8abc3
         uint64_t len;
e8abc3
         int ret;
e8abc3
@@ -1635,21 +1639,25 @@ robj *rdbLoadObject(int rdbtype, rio *rdb, sds key) {
e8abc3
                 return NULL;
e8abc3
             }
e8abc3
 
e8abc3
-            /* Add pair to ziplist */
e8abc3
-            o->ptr = ziplistPush(o->ptr, (unsigned char*)field,
e8abc3
-                    sdslen(field), ZIPLIST_TAIL);
e8abc3
-            o->ptr = ziplistPush(o->ptr, (unsigned char*)value,
e8abc3
-                    sdslen(value), ZIPLIST_TAIL);
e8abc3
-
e8abc3
             /* Convert to hash table if size threshold is exceeded */
e8abc3
             if (sdslen(field) > server.hash_max_ziplist_value ||
e8abc3
-                sdslen(value) > server.hash_max_ziplist_value)
e8abc3
+                sdslen(value) > server.hash_max_ziplist_value ||
e8abc3
+                !ziplistSafeToAdd(o->ptr, sdslen(field)+sdslen(value)))
e8abc3
             {
e8abc3
-                sdsfree(field);
e8abc3
-                sdsfree(value);
e8abc3
                 hashTypeConvert(o, OBJ_ENCODING_HT);
e8abc3
+                ret = dictAdd((dict*)o->ptr, field, value);
e8abc3
+                if (ret == DICT_ERR) {
e8abc3
+                    rdbExitReportCorruptRDB("Duplicate hash fields detected");
e8abc3
+                }
e8abc3
                 break;
e8abc3
             }
e8abc3
+
e8abc3
+            /* Add pair to ziplist */
e8abc3
+            o->ptr = ziplistPush(o->ptr, (unsigned char*)field,
e8abc3
+                    sdslen(field), ZIPLIST_TAIL);
e8abc3
+            o->ptr = ziplistPush(o->ptr, (unsigned char*)value,
e8abc3
+                    sdslen(value), ZIPLIST_TAIL);
e8abc3
+
e8abc3
             sdsfree(field);
e8abc3
             sdsfree(value);
e8abc3
         }
e8abc3
@@ -1726,6 +1734,10 @@ robj *rdbLoadObject(int rdbtype, rio *rdb, sds key) {
e8abc3
                     while ((zi = zipmapNext(zi, &fstr, &flen, &vstr, &vlen)) != NULL) {
e8abc3
                         if (flen > maxlen) maxlen = flen;
e8abc3
                         if (vlen > maxlen) maxlen = vlen;
e8abc3
+                        if (!ziplistSafeToAdd(zl, (size_t)flen + vlen)) {
e8abc3
+                            rdbExitReportCorruptRDB("Hash zipmap too big (%u)", flen);
e8abc3
+                        }
e8abc3
+
e8abc3
                         zl = ziplistPush(zl, fstr, flen, ZIPLIST_TAIL);
e8abc3
                         zl = ziplistPush(zl, vstr, vlen, ZIPLIST_TAIL);
e8abc3
                     }
e8abc3
diff --git a/src/server.h b/src/server.h
e8abc3
index 530355421a8d..38774bbc2fa7 100644
e8abc3
--- a/src/server.h
e8abc3
+++ b/src/server.h
e8abc3
@@ -1999,7 +1999,7 @@ unsigned char *zzlFirstInRange(unsigned char *zl, zrangespec *range);
e8abc3
 unsigned char *zzlLastInRange(unsigned char *zl, zrangespec *range);
e8abc3
 unsigned long zsetLength(const robj *zobj);
e8abc3
 void zsetConvert(robj *zobj, int encoding);
e8abc3
-void zsetConvertToZiplistIfNeeded(robj *zobj, size_t maxelelen);
e8abc3
+void zsetConvertToZiplistIfNeeded(robj *zobj, size_t maxelelen, size_t totelelen);
e8abc3
 int zsetScore(robj *zobj, sds member, double *score);
e8abc3
 unsigned long zslGetRank(zskiplist *zsl, double score, sds o);
e8abc3
 int zsetAdd(robj *zobj, double score, sds ele, int *flags, double *newscore);
e8abc3
diff --git a/src/t_hash.c b/src/t_hash.c
e8abc3
index 8e79432a4fbd..3cdfdd169abf 100644
e8abc3
--- a/src/t_hash.c
e8abc3
+++ b/src/t_hash.c
e8abc3
@@ -39,17 +39,22 @@
e8abc3
  * as their string length can be queried in constant time. */
e8abc3
 void hashTypeTryConversion(robj *o, robj **argv, int start, int end) {
e8abc3
     int i;
e8abc3
+    size_t sum = 0;
e8abc3
 
e8abc3
     if (o->encoding != OBJ_ENCODING_ZIPLIST) return;
e8abc3
 
e8abc3
     for (i = start; i <= end; i++) {
e8abc3
-        if (sdsEncodedObject(argv[i]) &&
e8abc3
-            sdslen(argv[i]->ptr) > server.hash_max_ziplist_value)
e8abc3
-        {
e8abc3
+        if (!sdsEncodedObject(argv[i]))
e8abc3
+            continue;
e8abc3
+        size_t len = sdslen(argv[i]->ptr);
e8abc3
+        if (len > server.hash_max_ziplist_value) {
e8abc3
             hashTypeConvert(o, OBJ_ENCODING_HT);
e8abc3
-            break;
e8abc3
+            return;
e8abc3
         }
e8abc3
+        sum += len;
e8abc3
     }
e8abc3
+    if (!ziplistSafeToAdd(o->ptr, sum))
e8abc3
+        hashTypeConvert(o, OBJ_ENCODING_HT);
e8abc3
 }
e8abc3
 
e8abc3
 /* Get the value from a ziplist encoded hash, identified by field.
e8abc3
diff --git a/src/t_list.c b/src/t_list.c
e8abc3
index 4f0bd7b81a5d..621b6932759e 100644
e8abc3
--- a/src/t_list.c
e8abc3
+++ b/src/t_list.c
e8abc3
@@ -29,6 +29,8 @@
e8abc3
 
e8abc3
 #include "server.h"
e8abc3
 
e8abc3
+#define LIST_MAX_ITEM_SIZE ((1ull<<32)-1024)
e8abc3
+
e8abc3
 /*-----------------------------------------------------------------------------
e8abc3
  * List API
e8abc3
  *----------------------------------------------------------------------------*/
e8abc3
@@ -196,6 +198,14 @@ void listTypeConvert(robj *subject, int enc) {
e8abc3
 
e8abc3
 void pushGenericCommand(client *c, int where) {
e8abc3
     int j, pushed = 0;
e8abc3
+
e8abc3
+    for (j = 2; j < c->argc; j++) {
e8abc3
+        if (sdslen(c->argv[j]->ptr) > LIST_MAX_ITEM_SIZE) {
e8abc3
+            addReplyError(c, "Element too large");
e8abc3
+            return;
e8abc3
+        }
e8abc3
+    }
e8abc3
+
e8abc3
     robj *lobj = lookupKeyWrite(c->db,c->argv[1]);
e8abc3
 
e8abc3
     if (lobj && lobj->type != OBJ_LIST) {
e8abc3
@@ -277,6 +287,11 @@ void linsertCommand(client *c) {
e8abc3
         return;
e8abc3
     }
e8abc3
 
e8abc3
+    if (sdslen(c->argv[4]->ptr) > LIST_MAX_ITEM_SIZE) {
e8abc3
+        addReplyError(c, "Element too large");
e8abc3
+        return;
e8abc3
+    }
e8abc3
+
e8abc3
     if ((subject = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
e8abc3
         checkType(c,subject,OBJ_LIST)) return;
e8abc3
 
e8abc3
@@ -344,6 +359,11 @@ void lsetCommand(client *c) {
e8abc3
     long index;
e8abc3
     robj *value = c->argv[3];
e8abc3
 
e8abc3
+    if (sdslen(value->ptr) > LIST_MAX_ITEM_SIZE) {
e8abc3
+        addReplyError(c, "Element too large");
e8abc3
+        return;
e8abc3
+    }
e8abc3
+
e8abc3
     if ((getLongFromObjectOrReply(c, c->argv[2], &index, NULL) != C_OK))
e8abc3
         return;
e8abc3
 
e8abc3
@@ -510,6 +530,11 @@ void lposCommand(client *c) {
e8abc3
     int direction = LIST_TAIL;
e8abc3
     long rank = 1, count = -1, maxlen = 0; /* Count -1: option not given. */
e8abc3
 
e8abc3
+    if (sdslen(ele->ptr) > LIST_MAX_ITEM_SIZE) {
e8abc3
+        addReplyError(c, "Element too large");
e8abc3
+        return;
e8abc3
+    }
e8abc3
+
e8abc3
     /* Parse the optional arguments. */
e8abc3
     for (int j = 3; j < c->argc; j++) {
e8abc3
         char *opt = c->argv[j]->ptr;
e8abc3
@@ -610,6 +635,11 @@ void lremCommand(client *c) {
e8abc3
     long toremove;
e8abc3
     long removed = 0;
e8abc3
 
e8abc3
+    if (sdslen(obj->ptr) > LIST_MAX_ITEM_SIZE) {
e8abc3
+        addReplyError(c, "Element too large");
e8abc3
+        return;
e8abc3
+    }
e8abc3
+
e8abc3
     if ((getLongFromObjectOrReply(c, c->argv[2], &toremove, NULL) != C_OK))
e8abc3
         return;
e8abc3
 
e8abc3
diff --git a/src/t_stream.c b/src/t_stream.c
e8abc3
index 43b67e8826ca..30411388697f 100644
e8abc3
--- a/src/t_stream.c
e8abc3
+++ b/src/t_stream.c
e8abc3
@@ -40,6 +40,12 @@
e8abc3
 #define STREAM_ITEM_FLAG_DELETED (1<<0)     /* Entry is deleted. Skip it. */
e8abc3
 #define STREAM_ITEM_FLAG_SAMEFIELDS (1<<1)  /* Same fields as master entry. */
e8abc3
 
e8abc3
+/* Don't let listpacks grow too big, even if the user config allows it.
e8abc3
+ * doing so can lead to an overflow (trying to store more than 32bit length
e8abc3
+ * into the listpack header), or actually an assertion since lpInsert
e8abc3
+ * will return NULL. */
e8abc3
+#define STREAM_LISTPACK_MAX_SIZE (1<<30)
e8abc3
+
e8abc3
 void streamFreeCG(streamCG *cg);
e8abc3
 void streamFreeNACK(streamNACK *na);
e8abc3
 size_t streamReplyWithRangeFromConsumerPEL(client *c, stream *s, streamID *start, streamID *end, size_t count, streamConsumer *consumer);
e8abc3
@@ -191,8 +197,11 @@ int streamCompareID(streamID *a, streamID *b) {
e8abc3
  *
e8abc3
  * The function returns C_OK if the item was added, this is always true
e8abc3
  * if the ID was generated by the function. However the function may return
e8abc3
- * C_ERR if an ID was given via 'use_id', but adding it failed since the
e8abc3
- * current top ID is greater or equal. */
e8abc3
+ * C_ERR in several cases:
e8abc3
+ * 1. If an ID was given via 'use_id', but adding it failed since the
e8abc3
+ *    current top ID is greater or equal. errno will be set to EDOM.
e8abc3
+ * 2. If a size of a single element or the sum of the elements is too big to
e8abc3
+ *    be stored into the stream. errno will be set to ERANGE. */
e8abc3
 int streamAppendItem(stream *s, robj **argv, int64_t numfields, streamID *added_id, streamID *use_id) {
e8abc3
     
e8abc3
     /* Generate the new entry ID. */
e8abc3
@@ -206,7 +215,23 @@ int streamAppendItem(stream *s, robj **argv, int64_t numfields, streamID *added_
e8abc3
      * or return an error. Automatically generated IDs might
e8abc3
      * overflow (and wrap-around) when incrementing the sequence 
e8abc3
        part. */
e8abc3
-    if (streamCompareID(&id,&s->last_id) <= 0) return C_ERR;
e8abc3
+    if (streamCompareID(&id,&s->last_id) <= 0) {
e8abc3
+        errno = EDOM;
e8abc3
+        return C_ERR;
e8abc3
+    }
e8abc3
+
e8abc3
+    /* Avoid overflow when trying to add an element to the stream (listpack
e8abc3
+     * can only host up to 32bit length sttrings, and also a total listpack size
e8abc3
+     * can't be bigger than 32bit length. */
e8abc3
+    size_t totelelen = 0;
e8abc3
+    for (int64_t i = 0; i < numfields*2; i++) {
e8abc3
+        sds ele = argv[i]->ptr;
e8abc3
+        totelelen += sdslen(ele);
e8abc3
+    }
e8abc3
+    if (totelelen > STREAM_LISTPACK_MAX_SIZE) {
e8abc3
+        errno = ERANGE;
e8abc3
+        return C_ERR;
e8abc3
+    }
e8abc3
 
e8abc3
     /* Add the new entry. */
e8abc3
     raxIterator ri;
e8abc3
@@ -265,9 +290,10 @@ int streamAppendItem(stream *s, robj **argv, int64_t numfields, streamID *added_
e8abc3
      * if we need to switch to the next one. 'lp' will be set to NULL if
e8abc3
      * the current node is full. */
e8abc3
     if (lp != NULL) {
e8abc3
-        if (server.stream_node_max_bytes &&
e8abc3
-            lp_bytes >= server.stream_node_max_bytes)
e8abc3
-        {
e8abc3
+        size_t node_max_bytes = server.stream_node_max_bytes;
e8abc3
+        if (node_max_bytes == 0 || node_max_bytes > STREAM_LISTPACK_MAX_SIZE)
e8abc3
+            node_max_bytes = STREAM_LISTPACK_MAX_SIZE;
e8abc3
+        if (lp_bytes + totelelen >= node_max_bytes) {
e8abc3
             lp = NULL;
e8abc3
         } else if (server.stream_node_max_entries) {
e8abc3
             int64_t count = lpGetInteger(lpFirst(lp));
e8abc3
@@ -1267,11 +1293,13 @@ void xaddCommand(client *c) {
e8abc3
 
e8abc3
     /* Append using the low level function and return the ID. */
e8abc3
     if (streamAppendItem(s,c->argv+field_pos,(c->argc-field_pos)/2,
e8abc3
-        &id, id_given ? &id : NULL)
e8abc3
-        == C_ERR)
e8abc3
+        &id, id_given ? &id : NULL) == C_ERR)
e8abc3
     {
e8abc3
-        addReplyError(c,"The ID specified in XADD is equal or smaller than the "
e8abc3
-                        "target stream top item");
e8abc3
+        if (errno == EDOM)
e8abc3
+            addReplyError(c,"The ID specified in XADD is equal or smaller than "
e8abc3
+                            "the target stream top item");
e8abc3
+        else
e8abc3
+            addReplyError(c,"Elements are too large to be stored");
e8abc3
         return;
e8abc3
     }
e8abc3
     addReplyStreamID(c,&id;;
e8abc3
diff --git a/src/t_zset.c b/src/t_zset.c
e8abc3
index d0ffe2f8b20a..b44f9551cc33 100644
e8abc3
--- a/src/t_zset.c
e8abc3
+++ b/src/t_zset.c
e8abc3
@@ -1238,15 +1238,18 @@ void zsetConvert(robj *zobj, int encoding) {
e8abc3
 }
e8abc3
 
e8abc3
 /* Convert the sorted set object into a ziplist if it is not already a ziplist
e8abc3
- * and if the number of elements and the maximum element size is within the
e8abc3
- * expected ranges. */
e8abc3
-void zsetConvertToZiplistIfNeeded(robj *zobj, size_t maxelelen) {
e8abc3
+ * and if the number of elements and the maximum element size and total elements size
e8abc3
+ * are within the expected ranges. */
e8abc3
+void zsetConvertToZiplistIfNeeded(robj *zobj, size_t maxelelen, size_t totelelen) {
e8abc3
     if (zobj->encoding == OBJ_ENCODING_ZIPLIST) return;
e8abc3
     zset *zset = zobj->ptr;
e8abc3
 
e8abc3
     if (zset->zsl->length <= server.zset_max_ziplist_entries &&
e8abc3
-        maxelelen <= server.zset_max_ziplist_value)
e8abc3
-            zsetConvert(zobj,OBJ_ENCODING_ZIPLIST);
e8abc3
+        maxelelen <= server.zset_max_ziplist_value &&
e8abc3
+        ziplistSafeToAdd(NULL, totelelen))
e8abc3
+    {
e8abc3
+        zsetConvert(zobj,OBJ_ENCODING_ZIPLIST);
e8abc3
+    }
e8abc3
 }
e8abc3
 
e8abc3
 /* Return (by reference) the score of the specified member of the sorted set
e8abc3
@@ -1355,20 +1358,28 @@ int zsetAdd(robj *zobj, double score, sds ele, int *flags, double *newscore) {
e8abc3
             }
e8abc3
             return 1;
e8abc3
         } else if (!xx) {
e8abc3
-            /* Optimize: check if the element is too large or the list
e8abc3
+            /* check if the element is too large or the list
e8abc3
              * becomes too long *before* executing zzlInsert. */
e8abc3
-            zobj->ptr = zzlInsert(zobj->ptr,ele,score);
e8abc3
-            if (zzlLength(zobj->ptr) > server.zset_max_ziplist_entries ||
e8abc3
-                sdslen(ele) > server.zset_max_ziplist_value)
e8abc3
+            if (zzlLength(zobj->ptr)+1 > server.zset_max_ziplist_entries ||
e8abc3
+                sdslen(ele) > server.zset_max_ziplist_value ||
e8abc3
+                !ziplistSafeToAdd(zobj->ptr, sdslen(ele)))
e8abc3
+            {
e8abc3
                 zsetConvert(zobj,OBJ_ENCODING_SKIPLIST);
e8abc3
-            if (newscore) *newscore = score;
e8abc3
-            *flags |= ZADD_ADDED;
e8abc3
-            return 1;
e8abc3
+            } else {
e8abc3
+                zobj->ptr = zzlInsert(zobj->ptr,ele,score);
e8abc3
+                if (newscore) *newscore = score;
e8abc3
+                *flags |= ZADD_ADDED;
e8abc3
+                return 1;
e8abc3
+            }
e8abc3
         } else {
e8abc3
             *flags |= ZADD_NOP;
e8abc3
             return 1;
e8abc3
         }
e8abc3
-    } else if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
e8abc3
+    }
e8abc3
+
e8abc3
+    /* Note that the above block handling ziplist would have either returned or
e8abc3
+     * converted the key to skiplist. */
e8abc3
+    if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {
e8abc3
         zset *zs = zobj->ptr;
e8abc3
         zskiplistNode *znode;
e8abc3
         dictEntry *de;
e8abc3
@@ -2180,7 +2191,7 @@ void zunionInterGenericCommand(client *c, robj *dstkey, int op) {
e8abc3
     zsetopsrc *src;
e8abc3
     zsetopval zval;
e8abc3
     sds tmp;
e8abc3
-    size_t maxelelen = 0;
e8abc3
+    size_t maxelelen = 0, totelelen = 0;
e8abc3
     robj *dstobj;
e8abc3
     zset *dstzset;
e8abc3
     zskiplistNode *znode;
e8abc3
@@ -2304,6 +2315,7 @@ void zunionInterGenericCommand(client *c, robj *dstkey, int op) {
e8abc3
                     tmp = zuiNewSdsFromValue(&zval);
e8abc3
                     znode = zslInsert(dstzset->zsl,score,tmp);
e8abc3
                     dictAdd(dstzset->dict,tmp,&znode->score);
e8abc3
+                    totelelen += sdslen(tmp);
e8abc3
                     if (sdslen(tmp) > maxelelen) maxelelen = sdslen(tmp);
e8abc3
                 }
e8abc3
             }
e8abc3
@@ -2340,6 +2352,7 @@ void zunionInterGenericCommand(client *c, robj *dstkey, int op) {
e8abc3
                     /* Remember the longest single element encountered,
e8abc3
                      * to understand if it's possible to convert to ziplist
e8abc3
                      * at the end. */
e8abc3
+                     totelelen += sdslen(tmp);
e8abc3
                      if (sdslen(tmp) > maxelelen) maxelelen = sdslen(tmp);
e8abc3
                     /* Update the element with its initial score. */
e8abc3
                     dictSetKey(accumulator, de, tmp);
e8abc3
@@ -2380,7 +2393,7 @@ void zunionInterGenericCommand(client *c, robj *dstkey, int op) {
e8abc3
     if (dbDelete(c->db,dstkey))
e8abc3
         touched = 1;
e8abc3
     if (dstzset->zsl->length) {
e8abc3
-        zsetConvertToZiplistIfNeeded(dstobj,maxelelen);
e8abc3
+        zsetConvertToZiplistIfNeeded(dstobj,maxelelen,totelelen);
e8abc3
         dbAdd(c->db,dstkey,dstobj);
e8abc3
         addReplyLongLong(c,zsetLength(dstobj));
e8abc3
         signalModifiedKey(c,c->db,dstkey);
e8abc3
diff --git a/src/ziplist.c b/src/ziplist.c
e8abc3
index 5933d19151b0..582eed2c9b4a 100644
e8abc3
--- a/src/ziplist.c
e8abc3
+++ b/src/ziplist.c
e8abc3
@@ -265,6 +265,17 @@
e8abc3
         ZIPLIST_LENGTH(zl) = intrev16ifbe(intrev16ifbe(ZIPLIST_LENGTH(zl))+incr); \
e8abc3
 }
e8abc3
 
e8abc3
+/* Don't let ziplists grow over 1GB in any case, don't wanna risk overflow in
e8abc3
+ * zlbytes*/
e8abc3
+#define ZIPLIST_MAX_SAFETY_SIZE (1<<30)
e8abc3
+int ziplistSafeToAdd(unsigned char* zl, size_t add) {
e8abc3
+    size_t len = zl? ziplistBlobLen(zl): 0;
e8abc3
+    if (len + add > ZIPLIST_MAX_SAFETY_SIZE)
e8abc3
+        return 0;
e8abc3
+    return 1;
e8abc3
+}
e8abc3
+
e8abc3
+
e8abc3
 /* We use this function to receive information about a ziplist entry.
e8abc3
  * Note that this is not how the data is actually encoded, is just what we
e8abc3
  * get filled by a function in order to operate more easily. */
e8abc3
@@ -586,7 +597,8 @@ unsigned char *ziplistNew(void) {
e8abc3
 }
e8abc3
 
e8abc3
 /* Resize the ziplist. */
e8abc3
-unsigned char *ziplistResize(unsigned char *zl, unsigned int len) {
e8abc3
+unsigned char *ziplistResize(unsigned char *zl, size_t len) {
e8abc3
+    assert(len < UINT32_MAX);
e8abc3
     zl = zrealloc(zl,len);
e8abc3
     ZIPLIST_BYTES(zl) = intrev32ifbe(len);
e8abc3
     zl[len-1] = ZIP_END;
e8abc3
@@ -898,6 +910,9 @@ unsigned char *ziplistMerge(unsigned char **first, unsigned char **second) {
e8abc3
     /* Combined zl length should be limited within UINT16_MAX */
e8abc3
     zllength = zllength < UINT16_MAX ? zllength : UINT16_MAX;
e8abc3
 
e8abc3
+    /* larger values can't be stored into ZIPLIST_BYTES */
e8abc3
+    assert(zlbytes < UINT32_MAX);
e8abc3
+
e8abc3
     /* Save offset positions before we start ripping memory apart. */
e8abc3
     size_t first_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*first));
e8abc3
     size_t second_offset = intrev32ifbe(ZIPLIST_TAIL_OFFSET(*second));
e8abc3
diff --git a/src/ziplist.h b/src/ziplist.h
e8abc3
index 964a47f6dc29..f6ba6c8be47d 100644
e8abc3
--- a/src/ziplist.h
e8abc3
+++ b/src/ziplist.h
e8abc3
@@ -49,6 +49,7 @@ unsigned char *ziplistFind(unsigned char *p, unsigned char *vstr, unsigned int v
e8abc3
 unsigned int ziplistLen(unsigned char *zl);
e8abc3
 size_t ziplistBlobLen(unsigned char *zl);
e8abc3
 void ziplistRepr(unsigned char *zl);
e8abc3
+int ziplistSafeToAdd(unsigned char* zl, size_t add);
e8abc3
 
e8abc3
 #ifdef REDIS_TEST
e8abc3
 int ziplistTest(int argc, char *argv[]);
e8abc3
diff --git a/tests/support/util.tcl b/tests/support/util.tcl
e8abc3
index 970d63314fd6..343912ac0049 100644
e8abc3
--- a/tests/support/util.tcl
e8abc3
+++ b/tests/support/util.tcl
e8abc3
@@ -109,7 +109,23 @@ proc wait_done_loading r {
e8abc3
 
e8abc3
 # count current log lines in server's stdout
e8abc3
 proc count_log_lines {srv_idx} {
e8abc3
-    set _ [exec wc -l < [srv $srv_idx stdout]]
e8abc3
+    set _ [string trim [exec wc -l < [srv $srv_idx stdout]]]
e8abc3
+}
e8abc3
+
e8abc3
+# returns the number of times a line with that pattern appears in a file
e8abc3
+proc count_message_lines {file pattern} {
e8abc3
+    set res 0
e8abc3
+    # exec fails when grep exists with status other than 0 (when the patter wasn't found)
e8abc3
+    catch {
e8abc3
+        set res [string trim [exec grep $pattern $file 2> /dev/null | wc -l]]
e8abc3
+    }
e8abc3
+    return $res
e8abc3
+}
e8abc3
+
e8abc3
+# returns the number of times a line with that pattern appears in the log
e8abc3
+proc count_log_message {srv_idx pattern} {
e8abc3
+    set stdout [srv $srv_idx stdout]
e8abc3
+    return [count_message_lines $stdout $pattern]
e8abc3
 }
e8abc3
 
e8abc3
 # verify pattern exists in server's sdtout after a certain line number
e8abc3
diff --git a/tests/unit/violations.tcl b/tests/unit/violations.tcl
e8abc3
new file mode 100644
e8abc3
index 000000000000..d87b9236528e
e8abc3
--- /dev/null
e8abc3
+++ b/tests/unit/violations.tcl
e8abc3
@@ -0,0 +1,156 @@
e8abc3
+# These tests consume massive amounts of memory, and are not
e8abc3
+# suitable to be executed as part of the normal test suite
e8abc3
+set ::str500 [string repeat x 500000000] ;# 500mb
e8abc3
+
e8abc3
+# Utility function to write big argument into redis client connection
e8abc3
+proc write_big_bulk {size} {
e8abc3
+    r write "\$$size\r\n"
e8abc3
+    while {$size >= 500000000} {
e8abc3
+        r write $::str500
e8abc3
+        incr size -500000000
e8abc3
+    }
e8abc3
+    if {$size > 0} {
e8abc3
+        r write [string repeat x $size]
e8abc3
+    }
e8abc3
+    r write "\r\n"
e8abc3
+}
e8abc3
+
e8abc3
+# One XADD with one huge 5GB field
e8abc3
+# Expected to fail resulting in an empty stream
e8abc3
+start_server [list overrides [list save ""] ] {
e8abc3
+    test {XADD one huge field} {
e8abc3
+        r config set proto-max-bulk-len 10000000000 ;#10gb
e8abc3
+        r config set client-query-buffer-limit 10000000000 ;#10gb
e8abc3
+        r write "*5\r\n\$4\r\nXADD\r\n\$2\r\nS1\r\n\$1\r\n*\r\n"
e8abc3
+        r write "\$1\r\nA\r\n"
e8abc3
+        write_big_bulk 5000000000 ;#5gb
e8abc3
+        r flush
e8abc3
+        catch {r read} err
e8abc3
+        assert_match {*too large*} $err
e8abc3
+        r xlen S1
e8abc3
+    } {0}
e8abc3
+}
e8abc3
+
e8abc3
+# One XADD with one huge (exactly nearly) 4GB field
e8abc3
+# This uncovers the overflow in lpEncodeGetType
e8abc3
+# Expected to fail resulting in an empty stream
e8abc3
+start_server [list overrides [list save ""] ] {
e8abc3
+    test {XADD one huge field - 1} {
e8abc3
+        r config set proto-max-bulk-len 10000000000 ;#10gb
e8abc3
+        r config set client-query-buffer-limit 10000000000 ;#10gb
e8abc3
+        r write "*5\r\n\$4\r\nXADD\r\n\$2\r\nS1\r\n\$1\r\n*\r\n"
e8abc3
+        r write "\$1\r\nA\r\n"
e8abc3
+        write_big_bulk 4294967295 ;#4gb-1
e8abc3
+        r flush
e8abc3
+        catch {r read} err
e8abc3
+        assert_match {*too large*} $err
e8abc3
+        r xlen S1
e8abc3
+    } {0}
e8abc3
+}
e8abc3
+
e8abc3
+# Gradually add big stream fields using repeated XADD calls
e8abc3
+start_server [list overrides [list save ""] ] {
e8abc3
+    test {several XADD big fields} {
e8abc3
+        r config set stream-node-max-bytes 0
e8abc3
+        for {set j 0} {$j<10} {incr j} {
e8abc3
+            r xadd stream * 1 $::str500 2 $::str500
e8abc3
+        }
e8abc3
+        r ping
e8abc3
+        r xlen stream
e8abc3
+    } {10}
e8abc3
+}
e8abc3
+
e8abc3
+# Add over 4GB to a single stream listpack (one XADD command)
e8abc3
+# Expected to fail resulting in an empty stream
e8abc3
+start_server [list overrides [list save ""] ] {
e8abc3
+    test {single XADD big fields} {
e8abc3
+        r write "*23\r\n\$4\r\nXADD\r\n\$1\r\nS\r\n\$1\r\n*\r\n"
e8abc3
+        for {set j 0} {$j<10} {incr j} {
e8abc3
+            r write "\$1\r\n$j\r\n"
e8abc3
+            write_big_bulk 500000000 ;#500mb
e8abc3
+        }
e8abc3
+        r flush
e8abc3
+        catch {r read} err
e8abc3
+        assert_match {*too large*} $err
e8abc3
+        r xlen S
e8abc3
+    } {0}
e8abc3
+}
e8abc3
+
e8abc3
+# Gradually add big hash fields using repeated HSET calls
e8abc3
+# This reproduces the overflow in the call to ziplistResize
e8abc3
+# Object will be converted to hashtable encoding
e8abc3
+start_server [list overrides [list save ""] ] {
e8abc3
+    r config set hash-max-ziplist-value 1000000000 ;#1gb
e8abc3
+    test {hash with many big fields} {
e8abc3
+        for {set j 0} {$j<10} {incr j} {
e8abc3
+            r hset h $j $::str500
e8abc3
+        }
e8abc3
+        r object encoding h
e8abc3
+    } {hashtable}
e8abc3
+}
e8abc3
+
e8abc3
+# Add over 4GB to a single hash field (one HSET command)
e8abc3
+# Object will be converted to hashtable encoding
e8abc3
+start_server [list overrides [list save ""] ] {
e8abc3
+    test {hash with one huge field} {
e8abc3
+        catch {r config set hash-max-ziplist-value 10000000000} ;#10gb
e8abc3
+        r config set proto-max-bulk-len 10000000000 ;#10gb
e8abc3
+        r config set client-query-buffer-limit 10000000000 ;#10gb
e8abc3
+        r write "*4\r\n\$4\r\nHSET\r\n\$2\r\nH1\r\n"
e8abc3
+        r write "\$1\r\nA\r\n"
e8abc3
+        write_big_bulk 5000000000 ;#5gb
e8abc3
+        r flush
e8abc3
+        r read
e8abc3
+        r object encoding H1
e8abc3
+    } {hashtable}
e8abc3
+}
e8abc3
+
e8abc3
+# Add over 4GB to a single list member (one LPUSH command)
e8abc3
+# Currently unsupported, and expected to fail rather than being truncated
e8abc3
+# Expected to fail resulting in a non-existing list
e8abc3
+start_server [list overrides [list save ""] ] {
e8abc3
+    test {list with one huge field} {
e8abc3
+        r config set proto-max-bulk-len 10000000000 ;#10gb
e8abc3
+        r config set client-query-buffer-limit 10000000000 ;#10gb
e8abc3
+        r write "*3\r\n\$5\r\nLPUSH\r\n\$2\r\nL1\r\n"
e8abc3
+        write_big_bulk 5000000000 ;#5gb
e8abc3
+        r flush
e8abc3
+        catch {r read} err
e8abc3
+        assert_match {*too large*} $err
e8abc3
+        r exists L1
e8abc3
+    } {0}
e8abc3
+}
e8abc3
+
e8abc3
+# SORT which attempts to store an element larger than 4GB into a list.
e8abc3
+# Currently unsupported and results in an assertion instead of truncation
e8abc3
+start_server [list overrides [list save ""] ] {
e8abc3
+    test {SORT adds huge field to list} {
e8abc3
+        r config set proto-max-bulk-len 10000000000 ;#10gb
e8abc3
+        r config set client-query-buffer-limit 10000000000 ;#10gb
e8abc3
+        r write "*3\r\n\$3\r\nSET\r\n\$2\r\nS1\r\n"
e8abc3
+        write_big_bulk 5000000000 ;#5gb
e8abc3
+        r flush
e8abc3
+        r read
e8abc3
+        assert_equal [r strlen S1] 5000000000
e8abc3
+        r set S2 asdf
e8abc3
+        r sadd myset 1 2
e8abc3
+        r mset D1 1 D2 2
e8abc3
+        catch {r sort myset by D* get S* store mylist}
e8abc3
+        # assert_equal [count_log_message 0 "crashed by signal"] 0   - not suitable for 6.0
e8abc3
+        assert_equal [count_log_message 0 "ASSERTION FAILED"] 1
e8abc3
+    }
e8abc3
+}
e8abc3
+
e8abc3
+# SORT which stores an integer encoded element into a list.
e8abc3
+# Just for coverage, no news here.
e8abc3
+start_server [list overrides [list save ""] ] {
e8abc3
+    test {SORT adds integer field to list} {
e8abc3
+        r set S1 asdf
e8abc3
+        r set S2 123 ;# integer encoded
e8abc3
+        assert_encoding "int" S2
e8abc3
+        r sadd myset 1 2
e8abc3
+        r mset D1 1 D2 2
e8abc3
+        r sort myset by D* get S* store mylist
e8abc3
+        r llen mylist
e8abc3
+    } {2}
e8abc3
+}