From 518f0bf79bae984e5b93e03b5b951369419d4ca3 Mon Sep 17 00:00:00 2001 From: Binbin Date: Fri, 28 Jun 2024 23:02:52 +0800 Subject: [PATCH] Fix limit undefined behavior crash in CLUSTER SLOT-STATS (#709) We did not set a default value for limit, but it will be used in addReplyOrderBy later, the undefined behavior may crash the server since the value could be negative and crash will happen in addReplyArrayLen. An interesting reproducible example (limit reuses the value of -1): ``` > cluster slot-stats orderby key-count desc limit -1 (error) ERR Limit has to lie in between 1 and 16384 (maximum number of slots). > cluster slot-stats orderby key-count desc Error: Server closed the connection ``` Set the default value of limit to 16384. --------- Signed-off-by: Binbin --- src/cluster_slot_stats.c | 2 +- tests/unit/cluster/slot-stats.tcl | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/cluster_slot_stats.c b/src/cluster_slot_stats.c index 515be588f..597cfa009 100644 --- a/src/cluster_slot_stats.c +++ b/src/cluster_slot_stats.c @@ -147,7 +147,7 @@ void clusterSlotStatsCommand(client *c) { } int i = 4; /* Next argument index, following ORDERBY */ int limit_counter = 0, asc_desc_counter = 0; - long limit; + long limit = CLUSTER_SLOTS; while (i < c->argc) { int moreargs = c->argc > i + 1; if (!strcasecmp(c->argv[i]->ptr, "limit") && moreargs) { diff --git a/tests/unit/cluster/slot-stats.tcl b/tests/unit/cluster/slot-stats.tcl index c2923dc8b..2ee950f7b 100644 --- a/tests/unit/cluster/slot-stats.tcl +++ b/tests/unit/cluster/slot-stats.tcl @@ -199,7 +199,7 @@ start_cluster 1 0 {tags {external:skip cluster}} { # ----------------------------------------------------------------------------- start_cluster 1 0 {tags {external:skip cluster}} { - + # SET keys for target hashslots, to encourage ordering. set hash_tags [list 0 1 2 3 4] set num_keys 1 @@ -220,6 +220,7 @@ start_cluster 1 0 {tags {external:skip cluster}} { test "CLUSTER SLOT-STATS ORDERBY DESC correct ordering" { set orderby "key-count" + assert_error "ERR*" {R 0 CLUSTER SLOT-STATS ORDERBY $orderby DESC LIMIT -1} set slot_stats [R 0 CLUSTER SLOT-STATS ORDERBY $orderby DESC] assert_slot_stats_monotonic_descent $slot_stats $orderby }