rack 2.2.8.1 → 2.2.20

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: 7707e75748cda81d20950b3a934018fdc136c5e4c9b551911bdb993418adf31c
4
- data.tar.gz: 7a87520904eb86c7e1761d2895e0ed3c11bb2bded7cbd7d716e75488e27f9b37
3
+ metadata.gz: ef82ea76fce7ba344410cc419cff56e201f8ec9ded624b01b34ad9521b613f99
4
+ data.tar.gz: de812a77455e5e05e6e2ced224c8cd0ea3c664f9244ed055346a9912ad0091eb
5
5
  SHA512:
6
- metadata.gz: c38c9c18ec842262eeb25e1c06bbfe0c6b7ef5f74ee43f9952105a53e96d9dfaead4c0786a0a9f2bb999004d45d738e05104b9e3c612f16b35a30b6441afa2e6
7
- data.tar.gz: 890b77739013bc80a83a74c2ecc112dfdd8a68a090d831f7ca3ea5106cf5cad1d61baf4df0c2d39bef3cb3b37e1bb30f44109d8e85ceded57345611090f85a75
6
+ metadata.gz: 53b096b3b1d67e810a7dbb880dab8e06a107bb9b9e640f94cc1136b5eb9dc9ca9712d9a0d1c28de7544796095222d71ab589776ea361e56a2136e791bbaf5110
7
+ data.tar.gz: 8fdc0b68d511c84b62d8eaaad9c520928d6e48b75aa2c01ede21b6309231a32652188726bb1e2bff67f849d6b804ad80c8896b3cf28e6a9c700edf8a9fc26ee3
data/CHANGELOG.md CHANGED
@@ -2,6 +2,78 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. For info on how to format all future additions to this file please reference [Keep A Changelog](https://keepachangelog.com/en/1.0.0/).
4
4
 
5
+ ## [2.2.20] - 2025-10-10
6
+
7
+ ### Security
8
+
9
+ - [CVE-2025-61780](https://github.com/advisories/GHSA-r657-rxjc-j557) Improper handling of headers in `Rack::Sendfile` may allow proxy bypass.
10
+ - [CVE-2025-61919](https://github.com/advisories/GHSA-6xw4-3v39-52mm) Unbounded read in `Rack::Request` form parsing can lead to memory exhaustion.
11
+
12
+ ## [2.2.19] - 2025-10-07
13
+
14
+ ### Security
15
+
16
+ - [CVE-2025-61772](https://github.com/advisories/GHSA-wpv5-97wm-hp9c) Multipart parser buffers unbounded per-part headers, enabling DoS (memory exhaustion)
17
+ - [CVE-2025-61771](https://github.com/advisories/GHSA-w9pc-fmgc-vxvw) Multipart parser buffers large non‑file fields entirely in memory, enabling DoS (memory exhaustion)
18
+ - [CVE-2025-61770](https://github.com/advisories/GHSA-p543-xpfm-54cp) Unbounded multipart preamble buffering enables DoS (memory exhaustion)
19
+
20
+ ## [2.2.18] - 2025-09-25
21
+
22
+ ### Security
23
+
24
+ - [CVE-2025-59830](https://github.com/advisories/GHSA-625h-95r8-8xpm) Unbounded parameter parsing in `Rack::QueryParser` can lead to memory exhaustion via semicolon-separated parameters.
25
+
26
+ ## [2.2.17] - 2025-06-03
27
+
28
+ - Backport `Rack::MediaType#params` now handles parameters without values. ([#2263](https://github.com/rack/rack/pull/2263), [@AllyMarthaJ](https://github.com/AllyMarthaJ))
29
+
30
+ ## [2.2.16] - 2025-05-22
31
+
32
+ - Fix incorrect backport of optional `CGI::Cookie` support. ([#2335](https://github.com/rack/rack/pull/2335), [@jeremyevans])
33
+
34
+ ## [2.2.15] - 2025-05-18
35
+
36
+ - Optional support for `CGI::Cookie` if not available. ([#2327](https://github.com/rack/rack/pull/2327), [#2333](https://github.com/rack/rack/pull/2333), [@earlopain])
37
+
38
+ ## [2.2.14] - 2025-05-06
39
+
40
+ ### Security
41
+
42
+ - [CVE-2025-32441](https://github.com/advisories/GHSA-vpfw-47h7-xj4g) Rack session can be restored after deletion.
43
+ - [CVE-2025-46727](https://github.com/advisories/GHSA-gjh7-p2fx-99vx) Unbounded parameter parsing in `Rack::QueryParser` can lead to memory exhaustion.
44
+
45
+ ## [2.2.13] - 2025-03-11
46
+
47
+ ### Security
48
+
49
+ - [CVE-2025-27610](https://github.com/advisories/GHSA-7wqh-767x-r66v) Local file inclusion in `Rack::Static`.
50
+
51
+ ## [2.2.12] - 2025-03-04
52
+
53
+ ### Security
54
+
55
+ - [CVE-2025-27111](https://github.com/advisories/GHSA-8cgq-6mh2-7j6v) Possible Log Injection in `Rack::Sendfile`.
56
+
57
+ ## [2.2.11] - 2025-02-12
58
+
59
+ ### Security
60
+
61
+ - [CVE-2025-25184](https://github.com/advisories/GHSA-7g2v-jj9q-g3rg) Possible Log Injection in `Rack::CommonLogger`.
62
+
63
+ ## [2.2.10] - 2024-10-14
64
+
65
+ - Fix compatibility issues with Ruby v3.4.0. ([#2248](https://github.com/rack/rack/pull/2248), [@byroot](https://github.com/byroot))
66
+
67
+ ## [2.2.9] - 2023-03-21
68
+
69
+ - Return empty when parsing a multi-part POST with only one end delimiter. ([#2104](https://github.com/rack/rack/pull/2104), [@alpaca-tc])
70
+
71
+ ## [2.2.8] - 2023-07-31
72
+
73
+ - Regenerate SPEC ([#2102](https://github.com/rack/rack/pull/2102), [@skipkayhil](https://github.com/skipkayhil))
74
+ - Limit file extension length of multipart tempfiles ([#2015](https://github.com/rack/rack/pull/2015), [@dentarg](https://github.com/dentarg))
75
+ - Fix "undefined method DelegateClass for Rack::Session::Cookie:Class" ([#2092](https://github.com/rack/rack/pull/2092), [@onigra](https://github.com/onigra) [@dchandekstark](https://github.com/dchandekstark))
76
+
5
77
  ## [2.2.7] - 2023-03-13
6
78
 
7
79
  - Correct the year number in the changelog ([#2015](https://github.com/rack/rack/pull/2015), [@kimulab](https://github.com/kimulab))
@@ -738,3 +810,7 @@ Items below this line are from the previously maintained HISTORY.md and NEWS.md
738
810
  - Removed Rails adapter, was too alpha.
739
811
 
740
812
  ## [0.1] 2007-03-03
813
+
814
+ [@ioquatix]: https://github.com/ioquatix "Samuel Williams"
815
+ [@jeremyevans]: https://github.com/jeremyevans "Jeremy Evans"
816
+ [@earlopain]: https://github.com/earlopain "Earlopain"
data/README.rdoc CHANGED
@@ -179,6 +179,41 @@ e.g:
179
179
 
180
180
  Rack::Utils.key_space_limit = 128
181
181
 
182
+ === `RACK_QUERY_PARSER_BYTESIZE_LIMIT`
183
+
184
+ This environment variable sets the default for the maximum query string bytesize
185
+ that `Rack::QueryParser` will attempt to parse. Attempts to use a query string
186
+ that exceeds this number of bytes will result in a
187
+ `Rack::QueryParser::QueryLimitError` exception. If this enviroment variable is
188
+ provided, it must be an integer, or `Rack::QueryParser` will raise an exception.
189
+
190
+ The default limit can be overridden on a per-`Rack::QueryParser` basis using
191
+ the `bytesize_limit` keyword argument when creating the `Rack::QueryParser`.
192
+
193
+ === `RACK_QUERY_PARSER_PARAMS_LIMIT`
194
+
195
+ This environment variable sets the default for the maximum number of query
196
+ parameters that `Rack::QueryParser` will attempt to parse. Attempts to use a
197
+ query string with more than this many query parameters will result in a
198
+ `Rack::QueryParser::QueryLimitError` exception. If this enviroment variable is
199
+ provided, it must be an integer, or `Rack::QueryParser` will raise an exception.
200
+
201
+ The default limit can be overridden on a per-`Rack::QueryParser` basis using
202
+ the `params_limit` keyword argument when creating the `Rack::QueryParser`.
203
+
204
+ This is implemented by counting the number of parameter separators in the
205
+ query string, before attempting parsing, so if the same parameter key is
206
+ used multiple times in the query, each counts as a separate parameter for
207
+ this check.
208
+
209
+ === `RACK_MULTIPART_BUFFERED_UPLOAD_BYTESIZE_LIMIT`
210
+
211
+ This environment variable sets the maximum amount of memory Rack will use
212
+ to buffer multipart parameters when parsing a request body. This considers
213
+ the size of the multipart mime headers and the body part for multipart
214
+ parameters that are buffered in memory and do not use tempfiles. This
215
+ defaults to 16MB if not provided.
216
+
182
217
  === key_space_limit
183
218
 
184
219
  The default number of bytes to allow all parameters keys in a given parameter hash to take up.
@@ -2,7 +2,6 @@
2
2
 
3
3
  require_relative 'abstract/handler'
4
4
  require_relative 'abstract/request'
5
- require 'base64'
6
5
 
7
6
  module Rack
8
7
  module Auth
@@ -48,7 +47,7 @@ module Rack
48
47
  end
49
48
 
50
49
  def credentials
51
- @credentials ||= Base64.decode64(params).split(':', 2)
50
+ @credentials ||= params.unpack("m").first.split(':', 2)
52
51
  end
53
52
 
54
53
  def username
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'digest/md5'
4
- require 'base64'
5
4
 
6
5
  module Rack
7
6
  module Auth
@@ -21,7 +20,7 @@ module Rack
21
20
  end
22
21
 
23
22
  def self.parse(string)
24
- new(*Base64.decode64(string).split(' ', 2))
23
+ new(*string.unpack("m").first.split(' ', 2))
25
24
  end
26
25
 
27
26
  def initialize(timestamp = Time.now, given_digest = nil)
@@ -29,7 +28,7 @@ module Rack
29
28
  end
30
29
 
31
30
  def to_s
32
- Base64.encode64("#{@timestamp} #{digest}").strip
31
+ ["#{@timestamp} #{digest}"].pack("m").strip
33
32
  end
34
33
 
35
34
  def digest
@@ -15,7 +15,7 @@ module Rack
15
15
  # The actual format is slightly different than the above due to the
16
16
  # separation of SCRIPT_NAME and PATH_INFO, and because the elapsed
17
17
  # time in seconds is included at the end.
18
- FORMAT = %{%s - %s [%s] "%s %s%s%s %s" %d %s %0.4f\n}
18
+ FORMAT = %{%s - %s [%s] "%s %s%s%s %s" %d %s %0.4f }
19
19
 
20
20
  # +logger+ can be any object that supports the +write+ or +<<+ methods,
21
21
  # which includes the standard library Logger. These methods are called
@@ -60,7 +60,8 @@ module Rack
60
60
  length,
61
61
  Utils.clock_time - began_at ]
62
62
 
63
- msg.gsub!(/[^[:print:]\n]/) { |c| "\\x#{c.ord}" }
63
+ msg.gsub!(/[^[:print:]]/) { |c| sprintf("\\x%x", c.ord) }
64
+ msg[-1] = "\n"
64
65
 
65
66
  logger = @logger || env[RACK_ERRORS]
66
67
 
@@ -15,8 +15,6 @@ module Rack
15
15
  host = options.delete(:Host) || default_host
16
16
  port = options.delete(:Port) || 8080
17
17
  args = [host, port, app, options]
18
- # Thin versions below 0.8.0 do not support additional options
19
- args.pop if ::Thin::VERSION::MAJOR < 1 && ::Thin::VERSION::MINOR < 8
20
18
  server = ::Thin::Server.new(*args)
21
19
  yield server if block_given?
22
20
  server.start
@@ -27,6 +27,11 @@ module Rack
27
27
  # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
28
28
  # this method responds with the following Hash:
29
29
  # { 'charset' => 'utf-8' }
30
+ #
31
+ # This will pass back parameters with empty strings in the hash if they
32
+ # lack a value (e.g., "text/plain;charset=" will return { 'charset' => '' },
33
+ # and "text/plain;charset" will return { 'charset' => '' }, similarly to
34
+ # the query params parser (barring the latter case, which returns nil instead)).
30
35
  def params(content_type)
31
36
  return {} if content_type.nil?
32
37
 
@@ -40,9 +45,9 @@ module Rack
40
45
 
41
46
  private
42
47
 
43
- def strip_doublequotes(str)
44
- (str.start_with?('"') && str.end_with?('"')) ? str[1..-2] : str
45
- end
48
+ def strip_doublequotes(str)
49
+ (str && str.start_with?('"') && str.end_with?('"')) ? str[1..-2] : str || ''
50
+ end
46
51
  end
47
52
  end
48
53
  end
data/lib/rack/mock.rb CHANGED
@@ -3,7 +3,6 @@
3
3
  require 'uri'
4
4
  require 'stringio'
5
5
  require_relative '../rack'
6
- require 'cgi/cookie'
7
6
 
8
7
  module Rack
9
8
  # Rack::MockRequest helps testing your Rack application without
@@ -171,6 +170,36 @@ module Rack
171
170
  # MockRequest.
172
171
 
173
172
  class MockResponse < Rack::Response
173
+ begin
174
+ # Recent versions of the CGI gem may not provide `CGI::Cookie`.
175
+ require 'cgi/cookie'
176
+ Cookie = CGI::Cookie
177
+ rescue LoadError
178
+ class Cookie
179
+ attr_reader :name, :value, :path, :domain, :expires, :secure
180
+
181
+ def initialize(args)
182
+ @name = args["name"]
183
+ @value = args["value"]
184
+ @path = args["path"]
185
+ @domain = args["domain"]
186
+ @expires = args["expires"]
187
+ @secure = args["secure"]
188
+ end
189
+
190
+ def method_missing(method_name, *args, &block)
191
+ @value.send(method_name, *args, &block)
192
+ end
193
+ # :nocov:
194
+ ruby2_keywords(:method_missing) if respond_to?(:ruby2_keywords, true)
195
+ # :nocov:
196
+
197
+ def respond_to_missing?(method_name, include_all = false)
198
+ @value.respond_to?(method_name, include_all) || super
199
+ end
200
+ end
201
+ end
202
+
174
203
  class << self
175
204
  alias [] new
176
205
  end
@@ -236,7 +265,7 @@ module Rack
236
265
  set_cookie_header.split("\n").each do |cookie|
237
266
  cookie_name, cookie_filling = cookie.split('=', 2)
238
267
  cookie_attributes = identify_cookie_attributes cookie_filling
239
- parsed_cookie = CGI::Cookie.new(
268
+ parsed_cookie = Cookie.new(
240
269
  'name' => cookie_name.strip,
241
270
  'value' => cookie_attributes.fetch('value'),
242
271
  'path' => cookie_attributes.fetch('path', nil),
@@ -253,7 +282,7 @@ module Rack
253
282
  def identify_cookie_attributes(cookie_filling)
254
283
  cookie_bits = cookie_filling.split(';')
255
284
  cookie_attributes = Hash.new
256
- cookie_attributes.store('value', cookie_bits[0].strip)
285
+ cookie_attributes.store('value', Array(cookie_bits[0].strip))
257
286
  cookie_bits.each do |bit|
258
287
  if bit.include? '='
259
288
  cookie_attribute, attribute_value = bit.split('=')
@@ -20,6 +20,27 @@ module Rack
20
20
 
21
21
  BOUNDARY_REGEX = /\A([^\n]*(?:\n|\Z))/
22
22
 
23
+ BOUNDARY_START_LIMIT = 16 * 1024
24
+ private_constant :BOUNDARY_START_LIMIT
25
+
26
+ MIME_HEADER_BYTESIZE_LIMIT = 64 * 1024
27
+ private_constant :MIME_HEADER_BYTESIZE_LIMIT
28
+
29
+ env_int = lambda do |key, val|
30
+ if str_val = ENV[key]
31
+ begin
32
+ val = Integer(str_val, 10)
33
+ rescue ArgumentError
34
+ raise ArgumentError, "non-integer value provided for environment variable #{key}"
35
+ end
36
+ end
37
+
38
+ val
39
+ end
40
+
41
+ BUFFERED_UPLOAD_BYTESIZE_LIMIT = env_int.call("RACK_MULTIPART_BUFFERED_UPLOAD_BYTESIZE_LIMIT", 16 * 1024 * 1024)
42
+ private_constant :BUFFERED_UPLOAD_BYTESIZE_LIMIT
43
+
23
44
  class BoundedIO # :nodoc:
24
45
  def initialize(io, content_length)
25
46
  @io = io
@@ -187,10 +208,13 @@ module Rack
187
208
  @end_boundary = @boundary + '--'
188
209
  @state = :FAST_FORWARD
189
210
  @mime_index = 0
211
+ @body_retained = nil
212
+ @retained_size = 0
190
213
  @collector = Collector.new tempfile
191
214
 
192
215
  @sbuf = StringScanner.new("".dup)
193
216
  @body_regex = /(?:#{EOL})?#{Regexp.quote(@boundary)}(?:#{EOL}|--)/m
217
+ @end_boundary_size = boundary.bytesize + 6 # (-- at start, -- at finish, EOL at end)
194
218
  @rx_max_size = EOL.size + @boundary.bytesize + [EOL.size, '--'.size].max
195
219
  @head_regex = /(.*?#{EOL})#{EOL}/m
196
220
  end
@@ -231,11 +255,22 @@ module Rack
231
255
  end
232
256
 
233
257
  def handle_fast_forward
234
- if consume_boundary
258
+ tok = consume_boundary
259
+
260
+ if tok == :END_BOUNDARY && @sbuf.pos == @end_boundary_size && @sbuf.eos?
261
+ # stop parsing a buffer if a buffer is only an end boundary.
262
+ @state = :DONE
263
+ elsif tok
235
264
  @state = :MIME_HEAD
236
265
  else
237
266
  raise EOFError, "bad content body" if @sbuf.rest_size >= @bufsize
238
- :want_read
267
+
268
+ # We raise if we don't find the multipart boundary, to avoid unbounded memory
269
+ # buffering. Note that the actual limit is the higher of 16KB and the buffer size (1MB by default)
270
+ raise EOFError, "multipart boundary not found within limit" if @sbuf.string.bytesize > BOUNDARY_START_LIMIT
271
+
272
+ # no boundary found, keep reading data
273
+ return :want_read
239
274
  end
240
275
  end
241
276
 
@@ -265,16 +300,30 @@ module Rack
265
300
  name = filename || "#{content_type || TEXT_PLAIN}[]".dup
266
301
  end
267
302
 
303
+ # Mime part head data is retained for both TempfilePart and BufferPart
304
+ # for the entireity of the parse, even though it isn't used for BufferPart.
305
+ update_retained_size(head.bytesize)
306
+
307
+ # If a filename is given, a TempfilePart will be used, so the body will
308
+ # not be buffered in memory. However, if a filename is not given, a BufferPart
309
+ # will be used, and the body will be buffered in memory.
310
+ @body_retained = !filename
311
+
268
312
  @collector.on_mime_head @mime_index, head, filename, content_type, name
269
313
  @state = :MIME_BODY
270
314
  else
271
- :want_read
315
+ # We raise if the mime part header is too large, to avoid unbounded memory
316
+ # buffering. Note that the actual limit is the higher of 64KB and the buffer size (1MB by default)
317
+ raise EOFError, "multipart mime part header too large" if @sbuf.string.bytesize > MIME_HEADER_BYTESIZE_LIMIT
318
+
319
+ return :want_read
272
320
  end
273
321
  end
274
322
 
275
323
  def handle_mime_body
276
324
  if (body_with_boundary = @sbuf.check_until(@body_regex)) # check but do not advance the pointer yet
277
325
  body = body_with_boundary.sub(/#{@body_regex}\z/m, '') # remove the boundary from the string
326
+ update_retained_size(body.bytesize) if @body_retained
278
327
  @collector.on_mime_body @mime_index, body
279
328
  @sbuf.pos += body.length + 2 # skip \r\n after the content
280
329
  @state = :CONSUME_TOKEN
@@ -283,7 +332,9 @@ module Rack
283
332
  # Save what we have so far
284
333
  if @rx_max_size < @sbuf.rest_size
285
334
  delta = @sbuf.rest_size - @rx_max_size
286
- @collector.on_mime_body @mime_index, @sbuf.peek(delta)
335
+ body = @sbuf.peek(delta)
336
+ update_retained_size(body.bytesize) if @body_retained
337
+ @collector.on_mime_body @mime_index, body
287
338
  @sbuf.pos += delta
288
339
  @sbuf.string = @sbuf.rest
289
340
  end
@@ -293,6 +344,17 @@ module Rack
293
344
 
294
345
  def full_boundary; @full_boundary; end
295
346
 
347
+ def update_retained_size(size)
348
+ @retained_size += size
349
+ if @retained_size > BUFFERED_UPLOAD_BYTESIZE_LIMIT
350
+ raise EOFError, "multipart data over retained size limit"
351
+ end
352
+ end
353
+
354
+ # Scan until the we find the start or end of the boundary.
355
+ # If we find it, return the appropriate symbol for the start or
356
+ # end of the boundary. If we don't find the start or end of the
357
+ # boundary, clear the buffer and return nil.
296
358
  def consume_boundary
297
359
  while read_buffer = @sbuf.scan_until(BOUNDARY_REGEX)
298
360
  case read_buffer.strip
@@ -16,20 +16,49 @@ module Rack
16
16
  # sequence.
17
17
  class InvalidParameterError < ArgumentError; end
18
18
 
19
- # ParamsTooDeepError is the error that is raised when params are recursively
20
- # nested over the specified limit.
21
- class ParamsTooDeepError < RangeError; end
19
+ # QueryLimitError is for errors raised when the query provided exceeds one
20
+ # of the query parser limits.
21
+ class QueryLimitError < RangeError
22
+ end
23
+
24
+ # ParamsTooDeepError is the old name for the error that is raised when params
25
+ # are recursively nested over the specified limit. Make it the same as
26
+ # as QueryLimitError, so that code that rescues ParamsTooDeepError error
27
+ # to handle bad query strings also now handles other limits.
28
+ ParamsTooDeepError = QueryLimitError
22
29
 
23
- def self.make_default(key_space_limit, param_depth_limit)
24
- new Params, key_space_limit, param_depth_limit
30
+ def self.make_default(key_space_limit, param_depth_limit, **options)
31
+ new(Params, key_space_limit, param_depth_limit, **options)
25
32
  end
26
33
 
27
34
  attr_reader :key_space_limit, :param_depth_limit
28
35
 
29
- def initialize(params_class, key_space_limit, param_depth_limit)
36
+ env_int = lambda do |key, val|
37
+ if str_val = ENV[key]
38
+ begin
39
+ val = Integer(str_val, 10)
40
+ rescue ArgumentError
41
+ raise ArgumentError, "non-integer value provided for environment variable #{key}"
42
+ end
43
+ end
44
+
45
+ val
46
+ end
47
+
48
+ BYTESIZE_LIMIT = env_int.call("RACK_QUERY_PARSER_BYTESIZE_LIMIT", 4194304)
49
+ private_constant :BYTESIZE_LIMIT
50
+
51
+ PARAMS_LIMIT = env_int.call("RACK_QUERY_PARSER_PARAMS_LIMIT", 4096)
52
+ private_constant :PARAMS_LIMIT
53
+
54
+ attr_reader :bytesize_limit
55
+
56
+ def initialize(params_class, key_space_limit, param_depth_limit, bytesize_limit: BYTESIZE_LIMIT, params_limit: PARAMS_LIMIT)
30
57
  @params_class = params_class
31
58
  @key_space_limit = key_space_limit
32
59
  @param_depth_limit = param_depth_limit
60
+ @bytesize_limit = bytesize_limit
61
+ @params_limit = params_limit
33
62
  end
34
63
 
35
64
  # Stolen from Mongrel, with some small modifications:
@@ -42,7 +71,7 @@ module Rack
42
71
 
43
72
  params = make_params
44
73
 
45
- (qs || '').split(d ? (COMMON_SEP[d] || /[#{d}] */n) : DEFAULT_SEP).each do |p|
74
+ check_query_string(qs, d).split(d ? (COMMON_SEP[d] || /[#{d}] */n) : DEFAULT_SEP).each do |p|
46
75
  next if p.empty?
47
76
  k, v = p.split('=', 2).map!(&unescaper)
48
77
 
@@ -69,7 +98,7 @@ module Rack
69
98
  params = make_params
70
99
 
71
100
  unless qs.nil? || qs.empty?
72
- (qs || '').split(d ? (COMMON_SEP[d] || /[#{d}] */n) : DEFAULT_SEP).each do |p|
101
+ check_query_string(qs, d).split(d ? (COMMON_SEP[d] || /[#{d}] */n) : DEFAULT_SEP).each do |p|
73
102
  k, v = p.split('=', 2).map! { |s| unescape(s) }
74
103
 
75
104
  normalize_params(params, k, v, param_depth_limit)
@@ -155,8 +184,24 @@ module Rack
155
184
  true
156
185
  end
157
186
 
158
- def unescape(s)
159
- Utils.unescape(s)
187
+ def check_query_string(qs, sep)
188
+ if qs
189
+ if qs.bytesize > @bytesize_limit
190
+ raise QueryLimitError, "total query size exceeds limit (#{@bytesize_limit})"
191
+ end
192
+
193
+ if (param_count = qs.count(sep.is_a?(String) ? sep : '&;')) >= @params_limit
194
+ raise QueryLimitError, "total number of query parameters (#{param_count+1}) exceeds limit (#{@params_limit})"
195
+ end
196
+
197
+ qs
198
+ else
199
+ ''
200
+ end
201
+ end
202
+
203
+ def unescape(string)
204
+ Utils.unescape(string)
160
205
  end
161
206
 
162
207
  class Params
data/lib/rack/request.rb CHANGED
@@ -444,7 +444,10 @@ module Rack
444
444
  get_header(RACK_REQUEST_FORM_HASH)
445
445
  elsif form_data? || parseable_data?
446
446
  unless set_header(RACK_REQUEST_FORM_HASH, parse_multipart)
447
- form_vars = get_header(RACK_INPUT).read
447
+ # Add 2 bytes. One to check whether it is over the limit, and a second
448
+ # in case the slice! call below removes the last byte
449
+ # If read returns nil, use the empty string
450
+ form_vars = get_header(RACK_INPUT).read(query_parser.bytesize_limit + 2) || ''
448
451
 
449
452
  # Fix for Safari Ajax postings that always append \0
450
453
  # form_vars.sub!(/\0\z/, '') # performance replacement:
data/lib/rack/sendfile.rb CHANGED
@@ -40,18 +40,23 @@ module Rack
40
40
  # proxy_set_header X-Real-IP $remote_addr;
41
41
  # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
42
42
  #
43
- # proxy_set_header X-Sendfile-Type X-Accel-Redirect;
44
43
  # proxy_set_header X-Accel-Mapping /var/www/=/files/;
45
44
  #
46
45
  # proxy_pass http://127.0.0.1:8080/;
47
46
  # }
48
47
  #
49
- # Note that the X-Sendfile-Type header must be set exactly as shown above.
50
48
  # The X-Accel-Mapping header should specify the location on the file system,
51
49
  # followed by an equals sign (=), followed name of the private URL pattern
52
50
  # that it maps to. The middleware performs a simple substitution on the
53
51
  # resulting path.
54
52
  #
53
+ # To enable X-Accel-Redirect, you must configure the middleware explicitly:
54
+ #
55
+ # use Rack::Sendfile, "X-Accel-Redirect"
56
+ #
57
+ # For security reasons, the X-Sendfile-Type header from requests is ignored.
58
+ # The sendfile variation must be set via the middleware constructor.
59
+ #
55
60
  # See Also: https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile
56
61
  #
57
62
  # === lighttpd
@@ -96,13 +101,25 @@ module Rack
96
101
  # X-Accel-Mapping header. Mappings should be provided in tuples of internal to
97
102
  # external. The internal values may contain regular expression syntax, they
98
103
  # will be matched with case indifference.
104
+ #
105
+ # When X-Accel-Redirect is explicitly enabled via the variation parameter,
106
+ # and no application-level mappings are provided, the middleware will read
107
+ # the X-Accel-Mapping header from the proxy. This allows nginx to control
108
+ # the path mapping without requiring application-level configuration.
109
+ #
110
+ # === Security
111
+ #
112
+ # For security reasons, the X-Sendfile-Type header from HTTP requests is
113
+ # ignored. The sendfile variation must be explicitly configured via the
114
+ # middleware constructor to prevent information disclosure vulnerabilities
115
+ # where attackers could bypass proxy restrictions.
99
116
 
100
117
  class Sendfile
101
118
  def initialize(app, variation = nil, mappings = [])
102
119
  @app = app
103
120
  @variation = variation
104
121
  @mappings = mappings.map do |internal, external|
105
- [/^#{internal}/i, external]
122
+ [/\A#{internal}/i, external]
106
123
  end
107
124
  end
108
125
 
@@ -133,29 +150,42 @@ module Rack
133
150
  end
134
151
  when '', nil
135
152
  else
136
- env[RACK_ERRORS].puts "Unknown x-sendfile variation: '#{type}'.\n"
153
+ env[RACK_ERRORS].puts "Unknown x-sendfile variation: #{type.inspect}"
137
154
  end
138
155
  end
139
156
  [status, headers, body]
140
157
  end
141
158
 
142
159
  private
160
+
143
161
  def variation(env)
144
- @variation ||
145
- env['sendfile.type'] ||
146
- env['HTTP_X_SENDFILE_TYPE']
162
+ # Note: HTTP_X_SENDFILE_TYPE is intentionally NOT read for security reasons.
163
+ # Attackers could use this header to enable x-accel-redirect and bypass proxy restrictions.
164
+ @variation || env['sendfile.type']
165
+ end
166
+
167
+ def x_accel_mapping(env)
168
+ # Only allow header when:
169
+ # 1. X-Accel-Redirect is explicitly enabled via constructor.
170
+ # 2. No application-level mappings are configured.
171
+ return nil unless @variation =~ /x-accel-redirect/i
172
+ return nil if @mappings.any?
173
+
174
+ env['HTTP_X_ACCEL_MAPPING']
147
175
  end
148
176
 
149
177
  def map_accel_path(env, path)
150
178
  if mapping = @mappings.find { |internal, _| internal =~ path }
151
- path.sub(*mapping)
152
- elsif mapping = env['HTTP_X_ACCEL_MAPPING']
179
+ return path.sub(*mapping)
180
+ elsif mapping = x_accel_mapping(env)
181
+ # Safe to use header: explicit config + no app mappings:
153
182
  mapping.split(',').map(&:strip).each do |m|
154
183
  internal, external = m.split('=', 2).map(&:strip)
155
- new_path = path.sub(/^#{internal}/i, external)
184
+ new_path = path.sub(/\A#{internal}/i, external)
156
185
  return new_path unless path == new_path
157
186
  end
158
- path
187
+
188
+ return path
159
189
  end
160
190
  end
161
191
  end
@@ -4,7 +4,6 @@ require 'openssl'
4
4
  require 'zlib'
5
5
  require_relative 'abstract/id'
6
6
  require 'json'
7
- require 'base64'
8
7
  require 'delegate'
9
8
 
10
9
  module Rack
@@ -51,11 +50,11 @@ module Rack
51
50
  # Encode session cookies as Base64
52
51
  class Base64
53
52
  def encode(str)
54
- ::Base64.strict_encode64(str)
53
+ [str].pack("m0")
55
54
  end
56
55
 
57
56
  def decode(str)
58
- ::Base64.decode64(str)
57
+ str.unpack("m").first
59
58
  end
60
59
 
61
60
  # Encode session cookies as Marshaled Base64 data
@@ -55,6 +55,7 @@ module Rack
55
55
 
56
56
  def write_session(req, session_id, new_session, options)
57
57
  with_lock(req) do
58
+ return false unless get_session_with_fallback(session_id)
58
59
  @pool.store session_id.private_id, new_session
59
60
  session_id
60
61
  end
@@ -64,7 +65,11 @@ module Rack
64
65
  with_lock(req) do
65
66
  @pool.delete(session_id.public_id)
66
67
  @pool.delete(session_id.private_id)
67
- generate_sid unless options[:drop]
68
+ unless options[:drop]
69
+ sid = generate_sid
70
+ @pool.store(sid.private_id, {})
71
+ sid
72
+ end
68
73
  end
69
74
  end
70
75
 
data/lib/rack/static.rb CHANGED
@@ -122,8 +122,9 @@ module Rack
122
122
 
123
123
  def call(env)
124
124
  path = env[PATH_INFO]
125
+ actual_path = Utils.clean_path_info(Utils.unescape_path(path))
125
126
 
126
- if can_serve(path)
127
+ if can_serve(actual_path)
127
128
  if overwrite_file_path(path)
128
129
  env[PATH_INFO] = (add_index_root?(path) ? path + @index : @urls[path])
129
130
  elsif @gzip && env['HTTP_ACCEPT_ENCODING'] && /\bgzip\b/.match?(env['HTTP_ACCEPT_ENCODING'])
data/lib/rack/utils.rb CHANGED
@@ -24,6 +24,7 @@ module Rack
24
24
 
25
25
  RFC2822_DAY_NAME = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]
26
26
  RFC2822_MONTH_NAME = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
27
+ RFC2396_PARSER = defined?(URI::RFC2396_PARSER) ? URI::RFC2396_PARSER : URI::RFC2396_Parser.new
27
28
 
28
29
  class << self
29
30
  attr_accessor :default_query_parser
@@ -42,13 +43,13 @@ module Rack
42
43
  # Like URI escaping, but with %20 instead of +. Strictly speaking this is
43
44
  # true URI escaping.
44
45
  def escape_path(s)
45
- ::URI::DEFAULT_PARSER.escape s
46
+ RFC2396_PARSER.escape s
46
47
  end
47
48
 
48
49
  # Unescapes the **path** component of a URI. See Rack::Utils.unescape for
49
50
  # unescaping query parameters or form components.
50
51
  def unescape_path(s)
51
- ::URI::DEFAULT_PARSER.unescape s
52
+ RFC2396_PARSER.unescape s
52
53
  end
53
54
 
54
55
  # Unescapes a URI escaped string with +encoding+. +encoding+ will be the
@@ -381,7 +382,7 @@ module Rack
381
382
  ranges << (r0..r1) if r0 <= r1
382
383
  end
383
384
 
384
- return [] if ranges.map(&:size).sum > size
385
+ return [] if ranges.map(&:size).inject(0, :+) > size
385
386
 
386
387
  ranges
387
388
  end
data/lib/rack/version.rb CHANGED
@@ -20,7 +20,7 @@ module Rack
20
20
  VERSION.join(".")
21
21
  end
22
22
 
23
- RELEASE = "2.2.8.1"
23
+ RELEASE = "2.2.20"
24
24
 
25
25
  # Return the Rack release as a dotted string.
26
26
  def self.release
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rack
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.8.1
4
+ version: 2.2.20
5
5
  platform: ruby
6
6
  authors:
7
7
  - Leah Neukirchen
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2024-02-21 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: minitest
@@ -77,9 +76,9 @@ executables:
77
76
  - rackup
78
77
  extensions: []
79
78
  extra_rdoc_files:
80
- - README.rdoc
81
79
  - CHANGELOG.md
82
80
  - CONTRIBUTING.md
81
+ - README.rdoc
83
82
  files:
84
83
  - CHANGELOG.md
85
84
  - CONTRIBUTING.md
@@ -169,7 +168,6 @@ metadata:
169
168
  changelog_uri: https://github.com/rack/rack/blob/master/CHANGELOG.md
170
169
  documentation_uri: https://rubydoc.info/github/rack/rack
171
170
  source_code_uri: https://github.com/rack/rack
172
- post_install_message:
173
171
  rdoc_options: []
174
172
  require_paths:
175
173
  - lib
@@ -184,8 +182,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
184
182
  - !ruby/object:Gem::Version
185
183
  version: '0'
186
184
  requirements: []
187
- rubygems_version: 3.4.10
188
- signing_key:
185
+ rubygems_version: 3.6.9
189
186
  specification_version: 4
190
187
  summary: A modular Ruby webserver interface.
191
188
  test_files: []