dalli 5.0.14 → 5.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1b52725fdd6dd9e4e890f506cca29a520e12e5458b29d9e315b6bb8805d749c7
4
- data.tar.gz: 504b5d320f3802d5aeb98608ffbc1ff629a89c76ba48957440b3403b40a5a69e
3
+ metadata.gz: 1ce80da13769b71c1dfd62b1f29e7e28b3a324323041b1af039a6dc07e1150c5
4
+ data.tar.gz: 0fbe3ef934b0d7e55f52a7af66f4a32f6622f56338555dfc806926f42eeb4935
5
5
  SHA512:
6
- metadata.gz: 1d258b16c57f90309b60867fac9e1aa03fd9ae6a67607d04f2cfd76c205e5f096e8322c532ecf4404d74895dd8a6deca766fac2ca3bb5fff17b646e321e6962f
7
- data.tar.gz: 430cc33100948d985f373247848122dc79c6ab6cfc1fa295c7fe8fbcc1463cf91e26a17a93d91145ef9c06d57e887aad592d2a437ccc79868886f7b4a40a0cd5
6
+ metadata.gz: 974e522fa379bca7717f8287118ac4e91bdd68f4ffc1491e07cecd7d9f47e9d9932c4b64ee83cbd363fb48859821dfad4819a979fc2a39e77b907bb709733971
7
+ data.tar.gz: fa59fd8c65034d5769d8768001e1b26929de13a564d2135906160d533c1afb97e99e617ae7fecc6476fc118f3745bf6b8041e7fb6182aaa51ce081fc6dc3c333
data/CHANGELOG.md CHANGED
@@ -1,9 +1,13 @@
1
1
  Dalli Changelog
2
2
  =====================
3
3
 
4
- Unreleased
4
+ 5.0.15
5
5
  ==========
6
6
 
7
+ Security:
8
+
9
+ - Bound memcached reply headers, incoming value sizes, and response counts, and enforce TLS timeouts for blocking operations (GHSA-5wpc-45jc-6ccc)
10
+
7
11
  5.0.14
8
12
  ==========
9
13
 
data/README.md CHANGED
@@ -44,6 +44,10 @@ Dalli::Client.new('localhost:11211', namespace: 'myapp', namespace_separator: '/
44
44
 
45
45
  The separator must be a single non-alphanumeric character. Valid examples: `:`, `/`, `|`, `.`, `-`, `_`, `#`
46
46
 
47
+ ### Maximum Value Size
48
+
49
+ `value_max_bytes` limits values written to memcached (1 MiB by default). Values read from a server have the same default limit. If another client writes larger values that this client must read, configure `max_response_bytes` explicitly.
50
+
47
51
  ## Security Note
48
52
 
49
53
  By default, Dalli uses Ruby's Marshal for serialization. Deserializing untrusted data with Marshal can lead to remote code execution. If you cache user-controlled data, consider using a safer serializer:
data/lib/dalli/client.rb CHANGED
@@ -35,6 +35,9 @@ module Dalli
35
35
  # to memcached. Default: true.
36
36
  # - :compression_min_size - the minimum size (in bytes) for which Dalli will compress values sent to Memcached.
37
37
  # Defaults to 4K.
38
+ # - :value_max_bytes - largest value Dalli will write, 1MB by default.
39
+ # - :max_response_bytes - largest value accepted from a server. Defaults to :value_max_bytes (1MB by default).
40
+ # Set this explicitly when reading larger items written by another client.
38
41
  # - :serializer - defaults to Marshal
39
42
  # - :compressor - defaults to Dalli::Compressor, a Zlib-based implementation
40
43
  # - :cache_nils - defaults to false, if true Dalli will not treat cached nil values as 'not found' for
@@ -193,6 +193,16 @@ module Dalli
193
193
  def servers_with_response(servers, timeout)
194
194
  return [] if servers.empty?
195
195
 
196
+ # A bounded read can stop while OpenSSL still holds decrypted bytes.
197
+ # IO.select only sees the underlying socket, so process those bytes
198
+ # before waiting for another network event.
199
+ buffered = nil
200
+ servers.each do |server|
201
+ sock = server.sock
202
+ (buffered ||= []) << server if sock.respond_to?(:pending_data?) && sock.pending_data?
203
+ end
204
+ return buffered if buffered
205
+
196
206
  sockets = servers.map(&:sock)
197
207
  readable, = IO.select(sockets, nil, nil, timeout)
198
208
  return [] if readable.nil?
@@ -152,6 +152,9 @@ module Dalli
152
152
  # to the noop at the end of the pipeline
153
153
  finish_pipeline && break if status && key.nil?
154
154
 
155
+ @pipeline_response_count += 1
156
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
157
+
155
158
  # A key that wasn't requested means the replies are out of step
156
159
  # (see expect_reply_keys): keep what was read so far, drop the rest
157
160
  if unexpected_reply_key?(key)
@@ -192,6 +195,8 @@ module Dalli
192
195
  response_buffer.clear
193
196
  @pipeline_out_of_step = false
194
197
  @expected_reply_keys = nil
198
+ @expected_response_count = nil
199
+ @pipeline_response_count = nil
195
200
  @connection_manager.abort_request!
196
201
  return true unless connected?
197
202
 
@@ -340,7 +345,7 @@ module Dalli
340
345
  # Non-blocking read and processing of any available pipeline responses.
341
346
  # Used during interleaved pipelined gets to prevent buffer deadlock.
342
347
  # Populates the provided results hash directly to avoid allocation overhead.
343
- def drain_pipeline_responses(results)
348
+ def drain_pipeline_responses(results) # rubocop:disable Metrics/CyclomaticComplexity
344
349
  return unless connected?
345
350
 
346
351
  # Non-blocking check if socket has data available
@@ -354,6 +359,9 @@ module Dalli
354
359
  status, cas, key, value = response_buffer.process_single_getk_response
355
360
  break if status.nil? # No complete response available
356
361
 
362
+ @pipeline_response_count += 1
363
+ raise Dalli::DalliError, 'Too many get_multi replies' if @pipeline_response_count > @expected_response_count
364
+
357
365
  # Handled by the next pipeline_next_responses, once sending is done
358
366
  if unexpected_reply_key?(key)
359
367
  @pipeline_out_of_step = true
@@ -387,6 +395,8 @@ module Dalli
387
395
  # other clients created, on memcached versions with the behavior.
388
396
  def expect_reply_keys(keys)
389
397
  @pipeline_out_of_step = false
398
+ @expected_response_count = keys.size
399
+ @pipeline_response_count = 0
390
400
  @expected_reply_keys = (keys.to_set { |k| reply_key_form(k) } if @verify_reply_keys)
391
401
  end
392
402
 
@@ -204,7 +204,7 @@ module Dalli
204
204
 
205
205
  def read_line
206
206
  flush_write_buffer
207
- data = @sock.gets("\r\n", MAX_LINE_BYTES)
207
+ data = timed_tls_operation { @sock.gets("\r\n", MAX_LINE_BYTES) }
208
208
  error_on_request!('EOF in read_line') if data.nil?
209
209
  # Without its CRLF the line either ran past MAX_LINE_BYTES or was cut
210
210
  # short by EOF; either way the connection is out of step
@@ -369,13 +369,23 @@ module Dalli
369
369
 
370
370
  private
371
371
 
372
+ # Ruby 3.3's default OpenSSL can block past IO#timeout= on the TCP
373
+ # socket. Bound the blocking TLS call itself; error_on_request! closes
374
+ # the connection after the Timeout::Error, so a partial reply or write
375
+ # is never reused.
376
+ def timed_tls_operation(&)
377
+ return yield unless @sock.is_a?(Dalli::Socket::SSLSocket)
378
+
379
+ Timeout.timeout(socket_timeout, &)
380
+ end
381
+
372
382
  # One write per flush. A TLS socket sends each argument of
373
383
  # write(*parts) as its own record and system call, so the parts are
374
384
  # joined first.
375
385
  def flush_write_buffer
376
386
  return if @write_buffer.empty?
377
387
 
378
- @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer)
388
+ timed_tls_operation { @sock.write(@write_buffer.size == 1 ? @write_buffer.first : joined_write_buffer) }
379
389
  discard_write_buffer
380
390
  end
381
391
 
@@ -408,7 +418,7 @@ module Dalli
408
418
  # error_on_request!, which closes the dirty socket for a retry on a fresh
409
419
  # connection (and preserves the $ERROR_INFO context down! relies on).
410
420
  def read_bytes(count)
411
- buffer = @sock.read(count)
421
+ buffer = timed_tls_operation { @sock.read(count) }
412
422
  return buffer if buffer && buffer.bytesize == count
413
423
 
414
424
  raise EOFError, "EOF reading #{count} bytes; received #{buffer ? buffer.bytesize : 0}"
@@ -189,7 +189,7 @@ module Dalli
189
189
 
190
190
  def finish_pipelined_delete(sent)
191
191
  write_noop
192
- sent - response_processor.pipelined_delete_non_deletions
192
+ sent - response_processor.pipelined_delete_non_deletions(sent)
193
193
  end
194
194
 
195
195
  # Arithmetic Commands
@@ -292,8 +292,13 @@ module Dalli
292
292
  expect_reply_keys(keys)
293
293
  hash = {}
294
294
  key_index = is_raw ? 2 : 3
295
+ replies = 0
295
296
  while (line = @connection_manager.read_line)
296
297
  break if line.start_with?('MN')
298
+
299
+ replies += 1
300
+ raise Dalli::DalliError, 'Too many get_multi replies' if replies > keys.size
301
+
297
302
  next unless line.start_with?('VA ')
298
303
 
299
304
  key, value = parse_multi_get_value(line, key_index, is_raw)
@@ -344,7 +349,7 @@ module Dalli
344
349
  buffer = RequestFormatter.multi_meta_set(entries, ttl: ttl)
345
350
  flushed_write(buffer)
346
351
  buffer.clear
347
- response_processor.consume_all_responses_until_mn
352
+ response_processor.consume_all_responses_until_mn(entries.size)
348
353
  end
349
354
  raise value_error if value_error
350
355
  end
@@ -355,7 +360,7 @@ module Dalli
355
360
  buffer = RequestFormatter.multi_meta_delete(keys)
356
361
  flushed_write(buffer)
357
362
  buffer.clear
358
- keys.size - response_processor.pipelined_delete_non_deletions
363
+ keys.size - response_processor.pipelined_delete_non_deletions(keys.size)
359
364
  end
360
365
 
361
366
  require_relative 'key_regularizer'
@@ -25,6 +25,8 @@ module Dalli
25
25
 
26
26
  # memcached can't store an item larger than 1 GiB (its -I maximum)
27
27
  MAX_VALUE_BYTES = 1024 * 1024 * 1024
28
+ MAX_STATS_ENTRIES = 10_000
29
+ MAX_QUIET_RESPONSES = 100_000
28
30
 
29
31
  T_OK = [OK].freeze
30
32
  T_RESET = [RESET].freeze
@@ -138,7 +140,11 @@ module Dalli
138
140
  def stats
139
141
  tokens = error_on_unexpected!(T_END_TOKEN_STAT)
140
142
  values = {}
143
+ replies = 0
141
144
  while tokens.first != END_TOKEN
145
+ replies += 1
146
+ raise Dalli::DalliError, 'Too many stats replies' if replies > MAX_STATS_ENTRIES
147
+
142
148
  values[tokens[1]] = tokens[2]
143
149
  tokens = next_line_to_tokens
144
150
  end
@@ -162,10 +168,16 @@ module Dalli
162
168
  tokens.last
163
169
  end
164
170
 
165
- def consume_all_responses_until_mn
171
+ def consume_all_responses_until_mn(max_responses = MAX_QUIET_RESPONSES)
166
172
  tokens = next_line_to_tokens
167
173
 
168
- tokens = next_line_to_tokens while tokens.first != MN
174
+ replies = 0
175
+ while tokens.first != MN
176
+ replies += 1
177
+ raise Dalli::DalliError, 'Too many quiet replies' if replies > max_responses
178
+
179
+ tokens = next_line_to_tokens
180
+ end
169
181
  true
170
182
  end
171
183
 
@@ -176,11 +188,13 @@ module Dalli
176
188
  # was NOT deleted -- a miss (NF) or an error. Returns that count so
177
189
  # callers can derive the number of successful deletes as
178
190
  # (keys_sent - non_deletions).
179
- def pipelined_delete_non_deletions
191
+ def pipelined_delete_non_deletions(max_responses = MAX_QUIET_RESPONSES)
180
192
  non_deletions = 0
181
193
  tokens = next_line_to_tokens
182
194
  until tokens.first == MN
183
195
  non_deletions += 1
196
+ raise Dalli::DalliError, 'Too many delete replies' if non_deletions > max_responses
197
+
184
198
  tokens = next_line_to_tokens
185
199
  end
186
200
  non_deletions
@@ -208,6 +222,13 @@ module Dalli
208
222
  def getk_response_from_buffer(buf, offset = 0)
209
223
  # Find the header terminator starting from offset
210
224
  term_idx = buf.byteindex(TERMINATOR, offset)
225
+ max_line_bytes = ConnectionManager::MAX_LINE_BYTES
226
+ header_too_long = if term_idx
227
+ term_idx - offset + TERMINATOR.bytesize > max_line_bytes
228
+ else
229
+ buf.bytesize - offset >= max_line_bytes
230
+ end
231
+ raise Dalli::DalliError, "Reply line without CRLF in the first #{max_line_bytes} bytes" if header_too_long
211
232
  return [0] unless term_idx
212
233
 
213
234
  header = buf.byteslice(offset, term_idx - offset)
@@ -305,9 +326,11 @@ module Dalli
305
326
  end
306
327
 
307
328
  def check_value_size!(size)
308
- return if size.between?(0, MAX_VALUE_BYTES)
329
+ limit = @value_marshaller.max_response_bytes
330
+ return if size >= 0 && size <= MAX_VALUE_BYTES && size <= limit # rubocop:disable Style/ComparableBetween
309
331
 
310
- raise Dalli::DalliError, "Reply value size #{size} is out of range"
332
+ effective_limit = [MAX_VALUE_BYTES, limit].min
333
+ raise Dalli::DalliError, "Reply value size #{size} exceeds the #{effective_limit}-byte response limit"
311
334
  end
312
335
 
313
336
  def read_line
@@ -14,12 +14,14 @@ module Dalli
14
14
  value_max_bytes: 1024 * 1024
15
15
  }.freeze
16
16
 
17
- attr_reader :value_max_bytes
17
+ attr_reader :value_max_bytes, :max_response_bytes
18
18
 
19
19
  def initialize(client_options)
20
20
  @value_max_bytes = client_options.fetch(:value_max_bytes) do
21
21
  DEFAULTS.fetch(:value_max_bytes)
22
22
  end.to_i
23
+ @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, @value_max_bytes))
24
+ raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
23
25
  end
24
26
 
25
27
  def store(key, value, _options = nil)
@@ -28,6 +28,9 @@ module Dalli
28
28
 
29
29
  @marshal_options =
30
30
  DEFAULTS.merge(client_options.slice(*OPTIONS))
31
+ @marshal_options[:value_max_bytes] = @marshal_options[:value_max_bytes].to_i
32
+ @max_response_bytes = Integer(client_options.fetch(:max_response_bytes, value_max_bytes))
33
+ raise ArgumentError, 'max_response_bytes must be positive' unless @max_response_bytes.positive?
31
34
  end
32
35
 
33
36
  def store(key, value, options = nil)
@@ -48,6 +51,8 @@ module Dalli
48
51
  @marshal_options[:value_max_bytes]
49
52
  end
50
53
 
54
+ attr_reader :max_response_bytes
55
+
51
56
  def error_if_over_max_value_bytes(key, value)
52
57
  return if value.bytesize <= value_max_bytes
53
58
 
data/lib/dalli/socket.rb CHANGED
@@ -12,22 +12,35 @@ module Dalli
12
12
  # Common methods for all socket implementations.
13
13
  ##
14
14
  module InstanceMethods
15
+ READ_CHUNK_SIZE = 8196
16
+ # Give the response parser control between bounded socket reads. In
17
+ # particular, a peer continuously sending a header without CRLF must
18
+ # not keep this method appending forever.
19
+ MAX_AVAILABLE_BYTES = READ_CHUNK_SIZE * 8
20
+
21
+ # Reads whatever is available without blocking. A read that returns less
22
+ # than a full chunk means the socket was drained, so we stop there rather
23
+ # than spend another read_nonblock call just to get :wait_readable back.
24
+ # Callers keep waiting on IO.select for anything that arrives later.
15
25
  def read_available(reusable_buffer = nil)
16
26
  if reusable_buffer
17
- value = read_nonblock(8196, reusable_buffer, exception: false)
27
+ value = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES].min, reusable_buffer, exception: false)
18
28
  case value
19
29
  when :wait_writable, :wait_readable
20
30
  return reusable_buffer.clear
21
31
  when nil
22
32
  raise Errno::ECONNRESET, "Connection reset: #{logged_options.inspect}"
23
33
  end
34
+ return value if drained_after?(value)
35
+ return value if value.bytesize >= MAX_AVAILABLE_BYTES
24
36
  else
25
37
  value = ''.b
26
38
  end
27
39
 
28
40
  buffer = ''.b
29
41
  loop do
30
- result = read_nonblock(8196, buffer, exception: false)
42
+ result = read_nonblock([READ_CHUNK_SIZE, MAX_AVAILABLE_BYTES - value.bytesize].min,
43
+ buffer, exception: false)
31
44
  case result
32
45
  when :wait_writable, :wait_readable
33
46
  buffer.clear
@@ -36,10 +49,20 @@ module Dalli
36
49
  raise Errno::ECONNRESET, "Connection reset: #{logged_options.inspect}"
37
50
  else
38
51
  value << result
52
+ return value if drained_after?(result)
53
+ return value if value.bytesize >= MAX_AVAILABLE_BYTES
39
54
  end
40
55
  end
41
56
  end
42
57
 
58
+ def drained_after?(chunk)
59
+ chunk.bytesize < READ_CHUNK_SIZE && !buffered_data?
60
+ end
61
+
62
+ def buffered_data?
63
+ false
64
+ end
65
+
43
66
  FILTERED_OUT_OPTIONS = %i[username password].freeze
44
67
  def logged_options
45
68
  options.except(*FILTERED_OUT_OPTIONS)
@@ -83,6 +106,27 @@ module Dalli
83
106
  io.options
84
107
  end
85
108
 
109
+ # OpenSSL can hold decrypted bytes that IO.select won't report as readable.
110
+ # With OpenSSL's default (no read-ahead) a short read has already used up
111
+ # the current record, so this is normally 0; it guards read-ahead setups.
112
+ #
113
+ # jruby-openssl can take the next record off the socket during a short
114
+ # read and hold it where neither pending nor IO.select sees it, so on
115
+ # JRuby a read continues until the socket would block.
116
+ def pending_data?
117
+ pending.positive? || (@rbuffer && !@rbuffer.empty?)
118
+ end
119
+
120
+ if RUBY_ENGINE == 'jruby'
121
+ def buffered_data?
122
+ true
123
+ end
124
+ else
125
+ def buffered_data?
126
+ pending_data?
127
+ end
128
+ end
129
+
86
130
  unless method_defined?(:wait_readable)
87
131
  def wait_readable(timeout = nil)
88
132
  to_io.wait_readable(timeout)
@@ -116,7 +160,12 @@ module Dalli
116
160
  sock.options = { host: host, port: port }.merge(options)
117
161
  init_socket_options(sock, options)
118
162
 
119
- options[:ssl_context] ? wrapping_ssl_socket(sock, host, options[:ssl_context]) : sock
163
+ if options[:ssl_context]
164
+ wrapping_ssl_socket(sock, host, options[:ssl_context],
165
+ options[:socket_timeout])
166
+ else
167
+ sock
168
+ end
120
169
  end
121
170
  end
122
171
 
@@ -205,13 +254,15 @@ module Dalli
205
254
 
206
255
  # Closes the TCP socket if the handshake fails or times out, so a failed
207
256
  # attempt doesn't hold a file descriptor until GC.
208
- def self.wrapping_ssl_socket(tcp_socket, host, ssl_context)
257
+ def self.wrapping_ssl_socket(tcp_socket, host, ssl_context, timeout = nil)
209
258
  warn_if_unverified(ssl_context)
210
259
  connected = false
211
260
  ssl_socket = Dalli::Socket::SSLSocket.new(tcp_socket, ssl_context)
212
261
  ssl_socket.hostname = host
213
262
  ssl_socket.sync_close = true
214
- ssl_socket.connect
263
+ # The underlying TCP socket's IO#timeout= does not reliably bound
264
+ # OpenSSL's blocking handshake on Ruby 3.3.
265
+ Timeout.timeout(timeout) { ssl_socket.connect }
215
266
  connected = true
216
267
  ssl_socket
217
268
  ensure
data/lib/dalli/version.rb CHANGED
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Dalli
4
- VERSION = '5.0.14'
4
+ VERSION = '5.0.15'
5
5
 
6
6
  MIN_SUPPORTED_MEMCACHED_VERSION = '1.6'
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: dalli
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.0.14
4
+ version: 5.0.15
5
5
  platform: ruby
6
6
  authors:
7
7
  - Peter M. Goldstein
@@ -88,7 +88,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
88
88
  - !ruby/object:Gem::Version
89
89
  version: '0'
90
90
  requirements: []
91
- rubygems_version: 4.0.23
91
+ rubygems_version: 4.0.24
92
92
  specification_version: 4
93
93
  summary: High performance memcached client for Ruby
94
94
  test_files: []