Repository: redis/redis

Problem statement:
[CRASH] Crash with `hrandfield`
Notice!
- If a Redis module was involved, please open an issue in the module's repo instead!
- If you're using docker on Apple M1, please make sure the image you're using was compiled for ARM!


**Crash report**

Paste the complete crash log between the quotes below. Please include a few lines from the log preceding the crash report to provide some context.

```
3633768:C 31 Dec 2022 06:52:11.383 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
3633768:C 31 Dec 2022 06:52:11.383 # Redis version=255.255.255, bits=64, commit=af0a4fe2, modified=0, pid=3633768, just started
3633768:C 31 Dec 2022 06:52:11.383 # Configuration loaded
3633768:M 31 Dec 2022 06:52:11.383 * monotonic clock: POSIX clock_gettime
3633768:M 31 Dec 2022 06:52:11.384 * Running mode=standalone, port=6379.
3633768:M 31 Dec 2022 06:52:11.385 # Server initialized
3633768:M 31 Dec 2022 06:52:11.385 * Loading RDB produced by version 255.255.255
3633768:M 31 Dec 2022 06:52:11.385 * RDB age 20 seconds
3633768:M 31 Dec 2022 06:52:11.385 * RDB memory usage when created 0.82 Mb
3633768:M 31 Dec 2022 06:52:11.385 * Done loading RDB, keys loaded: 2, keys expired: 0.
3633768:M 31 Dec 2022 06:52:11.385 * DB loaded from disk: 0.000 seconds
3633768:M 31 Dec 2022 06:52:11.385 * Ready to accept connections tcp


=== REDIS BUG REPORT START: Cut & paste starting from here ===
3633768:M 31 Dec 2022 06:52:20.404 # === ASSERTION FAILED ===
3633768:M 31 Dec 2022 06:52:20.404 # ==> networking.c:967 'length >= 0' is not true

------ STACK TRACE ------

Backtrace:
./src/redis-server 127.0.0.1:6379(+0xb2b32)[0x55586e9d7b32]
./src/redis-server 127.0.0.1:6379(+0xabb79)[0x55586e9d0b79]
./src/redis-server 127.0.0.1:6379(hrandfieldWithCountCommand+0x3d9)[0x55586ea1db49]
./src/redis-server 127.0.0.1:6379(call+0xc6)[0x55586e9ae486]
./src/redis-server 127.0.0.1:6379(processCommand+0xb10)[0x55586e9af9d0]
./src/redis-server 127.0.0.1:6379(processInputBuffer+0x107)[0x55586e9cfe07]
./src/redis-server 127.0.0.1:6379(readQueryFromClient+0x348)[0x55586e9d0368]
./src/redis-server 127.0.0.1:6379(+0x1b50ac)[0x55586eada0ac]
./src/redis-server 127.0.0.1:6379(aeMain+0xf1)[0x55586e9a3d81]
./src/redis-server 127.0.0.1:6379(main+0x3d4)[0x55586e999264]
/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7fd70409ed90]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7fd70409ee40]
./src/redis-server 127.0.0.1:6379(_start+0x25)[0x55586e999a25]

------ INFO OUTPUT ------
# Server
redis_version:255.255.255
redis_git_sha1:af0a4fe2
redis_git_dirty:0
redis_build_id:b21063553f60d4ba
redis_mode:standalone
os:Linux 5.4.0-135-generic x86_64
arch_bits:64
monotonic_clock:POSIX clock_gettime
multiplexing_api:epoll
atomicvar_api:c11-builtin
gcc_version:11.3.0
process_id:3633768
process_supervised:no
run_id:28f27a1c7d7643e444e5af989b45e7a49b12d00f
tcp_port:6379
server_time_usec:1672469540404864
uptime_in_seconds:9
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:11525156
executable:/not_patched_redis/./src/redis-server
config_file:/redis/redis.conf
io_threads_active:0
listener0:name=tcp,bind=127.0.0.1,port=6379

# Clients
connected_clients:1
cluster_connections:0
maxclients:10000
client_recent_max_input_buffer:20480
client_recent_max_output_buffer:0
blocked_clients:0
tracking_clients:0
clients_in_timeout_table:0

# Memory
used_memory:938808
used_memory_human:916.80K
used_memory_rss:8962048
used_memory_rss_human:8.55M
used_memory_peak:1111952
used_memory_peak_human:1.06M
used_memory_peak_perc:84.43%
used_memory_overhead:866408
used_memory_startup:864240
used_memory_dataset:72400
used_memory_dataset_perc:97.09%
allocator_allocated:1464320
allocator_active:1818624
allocator_resident:14163968
total_system_memory:134823165952
total_system_memory_human:125.56G
used_memory_lua:31744
used_memory_vm_eval:31744
used_memory_lua_human:31.00K
used_memory_scripts_eval:0
number_of_cached_scripts:0
number_of_functions:0
number_of_libraries:0
used_memory_vm_functions:32768
used_memory_vm_total:64512
used_memory_vm_total_human:63.00K
used_memory_functions:184
used_memory_scripts:184
used_memory_scripts_human:184B
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
allocator_frag_ratio:1.24
allocator_frag_bytes:354304
allocator_rss_ratio:7.79
allocator_rss_bytes:12345344
rss_overhead_ratio:0.63
rss_overhead_bytes:-5201920
mem_fragmentation_ratio:9.78
mem_fragmentation_bytes:8045784
mem_not_counted_for_evict:0
mem_replication_backlog:0
mem_total_replication_buffers:0
mem_clients_slaves:0
mem_clients_normal:1800
mem_cluster_links:0
mem_aof_buffer:0
mem_allocator:jemalloc-5.2.1
active_defrag_running:0
lazyfree_pending_objects:0
lazyfreed_objects:0

# Persistence
loading:0
async_loading:0
current_cow_peak:0
current_cow_size:0
current_cow_size_age:0
current_fork_perc:0.00
current_save_keys_processed:0
current_save_keys_total:0
rdb_changes_since_last_save:1
rdb_bgsave_in_progress:0
rdb_last_save_time:1672469531
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:-1
rdb_current_bgsave_time_sec:-1
rdb_saves:0
rdb_last_cow_size:0
rdb_last_load_keys_expired:0
rdb_last_load_keys_loaded:2
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_rewrites:0
aof_rewrites_consecutive_failures:0
aof_last_write_status:ok
aof_last_cow_size:0
module_fork_in_progress:0
module_fork_last_cow_size:0

# Stats
total_connections_received:1
total_commands_processed:2
instantaneous_ops_per_sec:0
total_net_input_bytes:145
total_net_output_bytes:200344
total_net_repl_input_bytes:0
total_net_repl_output_bytes:0
instantaneous_input_kbps:0.00
instantaneous_output_kbps:0.00
instantaneous_input_repl_kbps:0.00
instantaneous_output_repl_kbps:0.00
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
expired_stale_perc:0.00
expired_time_cap_reached_count:0
expire_cycle_cpu_milliseconds:0
evicted_keys:0
evicted_clients:0
total_eviction_exceeded_time:0
current_eviction_exceeded_time:0
keyspace_hits:1
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
pubsubshard_channels:0
latest_fork_usec:0
total_forks:0
migrate_cached_sockets:0
slave_expires_tracked_keys:0
active_defrag_hits:0
active_defrag_misses:0
active_defrag_key_hits:0
active_defrag_key_misses:0
total_active_defrag_time:0
current_active_defrag_time:0
tracking_total_keys:0
tracking_total_items:0
tracking_total_prefixes:0
unexpected_error_replies:0
total_error_replies:0
dump_payload_sanitizations:0
total_reads_processed:3
total_writes_processed:4
io_threaded_reads_processed:0
io_threaded_writes_processed:0
reply_buffer_shrinks:1
reply_buffer_expands:0
acl_access_denied_auth:0
acl_access_denied_cmd:0
acl_access_denied_key:0
acl_access_denied_channel:0

# Replication
role:master
connected_slaves:0
master_failover_state:no-failover
master_replid:172d71b53c21febc471fdae91ac3fb0fd483770b
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0

# CPU
used_cpu_sys:0.002051
used_cpu_user:0.019260
used_cpu_sys_children:0.000000
used_cpu_user_children:0.000000
used_cpu_sys_main_thread:0.004229
used_cpu_user_main_thread:0.016919

# Modules

# Commandstats
cmdstat_hmset:calls=1,usec=8,usec_per_call=8.00,rejected_calls=0,failed_calls=0
cmdstat_command|docs:calls=1,usec=1712,usec_per_call=1712.00,rejected_calls=0,failed_calls=0

# Errorstats

# Latencystats
latency_percentiles_usec_hmset:p50=8.031,p99=8.031,p99.9=8.031
latency_percentiles_usec_command|docs:p50=1712.127,p99=1712.127,p99.9=1712.127

# Cluster
cluster_enabled:0

# Keyspace
db0:keys=3,expires=0,avg_ttl=0

------ CLIENT LIST OUTPUT ------
id=3 addr=127.0.0.1:58398 laddr=127.0.0.1:6379 fd=7 name= age=7 idle=0 flags=N db=0 sub=0 psub=0 ssub=0 multi=-1 qbuf=77 qbuf-free=20397 argv-mem=46 multi-mem=0 rbs=1024 rbp=0 obl=0 oll=0 omem=0 tot-mem=22350 events=r cmd=hrandfield user=default redir=-1 resp=2

------ CURRENT CLIENT INFO ------
id=3 addr=127.0.0.1:58398 laddr=127.0.0.1:6379 fd=7 name= age=7 idle=0 flags=N db=0 sub=0 psub=0 ssub=0 multi=-1 qbuf=77 qbuf-free=20397 argv-mem=46 multi-mem=0 rbs=1024 rbp=0 obl=0 oll=0 omem=0 tot-mem=22350 events=r cmd=hrandfield user=default redir=-1 resp=2
argv[0]: '"hrandfield"'
argv[1]: '"myhash"'
argv[2]: '"-9223372036854770000"'
argv[3]: '"withvalues"'
3633768:M 31 Dec 2022 06:52:20.406 # key 'myhash' found in DB containing the following object:
3633768:M 31 Dec 2022 06:52:20.406 # Object type: 4
3633768:M 31 Dec 2022 06:52:20.406 # Object encoding: 11
3633768:M 31 Dec 2022 06:52:20.406 # Object refcount: 1

------ MODULES INFO OUTPUT ------

------ CONFIG DEBUG OUTPUT ------
lazyfree-lazy-eviction no
sanitize-dump-payload no
io-threads 1
repl-diskless-load disabled
lazyfree-lazy-server-del no
io-threads-do-reads no
repl-diskless-sync yes
lazyfree-lazy-expire no
slave-read-only yes
client-query-buffer-limit 1gb
replica-read-only yes
list-compress-depth 0
proto-max-bulk-len 512mb
lazyfree-lazy-user-flush no
activedefrag no
lazyfree-lazy-user-del no

------ FAST MEMORY TEST ------
3633768:M 31 Dec 2022 06:52:20.406 # Bio thread for job type #0 terminated
3633768:M 31 Dec 2022 06:52:20.406 # Bio thread for job type #1 terminated
3633768:M 31 Dec 2022 06:52:20.406 # Bio thread for job type #2 terminated
*** Preparing to test memory region 55586ec93000 (2306048 bytes)
*** Preparing to test memory region 55586f03c000 (135168 bytes)
*** Preparing to test memory region 7fd700e00000 (8388608 bytes)
*** Preparing to test memory region 7fd701600000 (6291456 bytes)
*** Preparing to test memory region 7fd701d15000 (8388608 bytes)
*** Preparing to test memory region 7fd702516000 (8388608 bytes)
*** Preparing to test memory region 7fd702d17000 (8388608 bytes)
*** Preparing to test memory region 7fd703800000 (8388608 bytes)
*** Preparing to test memory region 7fd704071000 (16384 bytes)
*** Preparing to test memory region 7fd704290000 (53248 bytes)
*** Preparing to test memory region 7fd70438a000 (8192 bytes)
.O.O.O.O.O.O.O.O.O.O.O
Fast memory test PASSED, however your memory can still be broken. Please run a memory test for several hours if possible.

=== REDIS BUG REPORT END. Make sure to include from START to END. ===

       Please report the crash by opening an issue on github:

           http://github.com/redis/redis/issues

  If a Redis module was involved, please open in the module's repo instead.

  Suspect RAM error? Use redis-server --test-memory to verify it.

  Some other issues could be detected by redis-server --check-system

```

**Additional information**

1. OS distribution and version
```
Ubuntu 22.04.1 LTS
Redis ver: built from commit af0a4fe20771603f0eab75a1f60748d124cf33c3
```
2. Steps to reproduce (if any)

Run the following command in cli:
```
hmset myhash a 1
hrandfield myhash -9223372036854770000 withvalues
```


Hints:

Patch:
diff --git a/src/t_hash.c b/src/t_hash.c
index a2af438aee3..9ebd99ccc04 100644
--- a/src/t_hash.c
+++ b/src/t_hash.c
@@ -1120,8 +1120,13 @@ void hrandfieldCommand(client *c) {
         if (c->argc > 4 || (c->argc == 4 && strcasecmp(c->argv[3]->ptr,"withvalues"))) {
             addReplyErrorObject(c,shared.syntaxerr);
             return;
-        } else if (c->argc == 4)
+        } else if (c->argc == 4) {
             withvalues = 1;
+            if (l < LONG_MIN/2 || l > LONG_MAX/2) {
+                addReplyError(c,"value is out of range");
+                return;
+            }
+        }
         hrandfieldWithCountCommand(c, l, withvalues);
         return;
     }
diff --git a/src/t_zset.c b/src/t_zset.c
index eb87c5d7dac..ff2198ea4fb 100644
--- a/src/t_zset.c
+++ b/src/t_zset.c
@@ -4317,8 +4317,13 @@ void zrandmemberCommand(client *c) {
         if (c->argc > 4 || (c->argc == 4 && strcasecmp(c->argv[3]->ptr,"withscores"))) {
             addReplyErrorObject(c,shared.syntaxerr);
             return;
-        } else if (c->argc == 4)
+        } else if (c->argc == 4) {
             withscores = 1;
+            if (l < LONG_MIN/2 || l > LONG_MAX/2) {
+                addReplyError(c,"value is out of range");
+                return;
+            }
+        }
         zrandmemberWithCountCommand(c, l, withscores);
         return;
     }


Test patch:
diff --git a/tests/unit/type/hash.tcl b/tests/unit/type/hash.tcl
index e7b9f3d855a..113780ff792 100644
--- a/tests/unit/type/hash.tcl
+++ b/tests/unit/type/hash.tcl
@@ -71,6 +71,11 @@ start_server {tags {"hash"}} {
         r hrandfield myhash 0
     } {}
 
+    test "HRANDFIELD count overflow" {
+        r hmset myhash a 1
+        assert_error {*value is out of range*} {r hrandfield myhash -9223372036854770000 withvalues}
+    } {}
+
     test "HRANDFIELD with <count> against non existing key" {
         r hrandfield nonexisting_key 100
     } {}
diff --git a/tests/unit/type/zset.tcl b/tests/unit/type/zset.tcl
index 41898f27b02..036638510a4 100644
--- a/tests/unit/type/zset.tcl
+++ b/tests/unit/type/zset.tcl
@@ -2322,6 +2322,11 @@ start_server {tags {"zset"}} {
         r zrandmember nonexisting_key 100
     } {}
 
+    test "ZRANDMEMBER count overflow" {
+        r zadd myzset 0 a
+        assert_error {*value is out of range*} {r zrandmember myzset -9223372036854770000 withscores}
+    } {}
+
     # Make sure we can distinguish between an empty array and a null response
     r readraw 1