rack 2.2.17 → 2.2.25

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: e5a64927e310e6bb3eff5b74ae3894d9c4592333d48615103e2dba14738ddc0a
4
- data.tar.gz: 956fac8fbd0b4fb46777d005f853219651c5b19f12679c2a64545f62508f60e1
3
+ metadata.gz: c5322ca41af487959f08981c9964d7ef877f82b0ee4374e4338bedbeb93d3538
4
+ data.tar.gz: 4accf7c52defac80efd55caef60ef967f1a813743d8487723e733f66591fce5d
5
5
  SHA512:
6
- metadata.gz: f9a8fbea5c3a62dd839da7c022f78d5dc7e198f0de0a91b9efab5453e3124ecbe9cd802c14e88f2a92c217d7ffab9ca5afcd3a7ff09fee24e9576d3f9973b3b2
7
- data.tar.gz: 6c3bb1fe9b3f8082af8d0d4def0d4237991008358a88832e8b0cd5216a688643e9f5013494d2dbd6634b6e1d3e63cf24266de6320f1e6cc292d79f1f6f58dc22
6
+ metadata.gz: 4b5cedb21343a2e062ca5daf8c55f88fe29bc7d884244dcd13ca6cad858e61764b18f71ea93cfb6a538bc03dadbb82ad7471895d1f6cbc1b2bc727651a807a11
7
+ data.tar.gz: 5bc5a948d20e77d1c831173b4ba5ba5b661bc985f60a6bf9fd1224033c6725ed2c8753f39766a3fe386b56457de9439ace3459cd0f1f650dd0c7fdb2effdcc13
data/CHANGELOG.md CHANGED
@@ -2,6 +2,72 @@
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.25] - 2026-10-30
6
+
7
+ ### Security
8
+
9
+ - [GHSA-5v64-555j-wjxm](https://github.com/advisories/GHSA-5v64-555j-wjxm) Multipart parser retains parsed data in its scan buffer, allowing denial of service via memory exhaustion.
10
+ - [GHSA-wvg4-6p58-3gh3](https://github.com/advisories/GHSA-wvg4-6p58-3gh3) `Rack::Static` header rules were matched against an unnormalized path, allowing dot segments to bypass them.
11
+ - [GHSA-p8x9-v4hv-2w4g](https://github.com/advisories/GHSA-p8x9-v4hv-2w4g) Multipart requests with more than one `boundary` parameter were accepted when the first value was empty or began with a quote, semicolon, or comma, bypassing the guard added for CVE-2026-26961.
12
+
13
+ ### Fixed
14
+
15
+ - Multipart parser: scan boundary lines with a literal newline search instead of a backtracking regexp, which allocated tens of megabytes per scan for long lines and made the scan buffer fix above ineffective on this series.
16
+
17
+ ## [2.2.24] - 2026-08-13
18
+
19
+ ### Security
20
+
21
+ - [CVE-2026-26962](https://github.com/advisories/GHSA-rx22-g9mx-qrhv) Improper unfolding of folded multipart headers preserves CRLF in parsed parameter values.
22
+
23
+ ## [2.2.23] - 2026-04-01
24
+
25
+ ### Security
26
+
27
+ - [CVE-2026-34763](https://github.com/advisories/GHSA-7mqq-6cf9-v2qp) Root directory disclosure via unescaped regex interpolation in `Rack::Directory`.
28
+ - [CVE-2026-34230](https://github.com/advisories/GHSA-v569-hp3g-36wr) Avoid O(n^2) algorithm in `Rack::Utils.select_best_encoding` which could lead to denial of service.
29
+ - [CVE-2026-26961](https://github.com/advisories/GHSA-vgpv-f759-9wx3) Raise error for multipart requests with multiple boundary parameters.
30
+ - [CVE-2026-34786](https://github.com/advisories/GHSA-q4qf-9j86-f5mh) `Rack::Static` `header_rules` bypass via URL-encoded path mismatch.
31
+ - [CVE-2026-34831](https://github.com/advisories/GHSA-q2ww-5357-x388) `Content-Length` mismatch in `Rack::Files` error responses.
32
+ - [CVE-2026-34826](https://github.com/advisories/GHSA-x8cg-fq8g-mxfx) Multipart byte range processing allows denial of service via excessive overlapping ranges.
33
+ - [CVE-2026-34830](https://github.com/advisories/GHSA-qv7j-4883-hwh7) `Rack::Sendfile` header-based `X-Accel-Mapping` regex injection enables unauthorized `X-Accel-Redirect`.
34
+ - [CVE-2026-34785](https://github.com/advisories/GHSA-h2jq-g4cq-5ppq) `Rack::Static` prefix matching can expose unintended files under the static root.
35
+ - [CVE-2026-34829](https://github.com/advisories/GHSA-8vqr-qjwx-82mw) Multipart parsing without `Content-Length` header allows unbounded chunked file uploads.
36
+
37
+ ## [2.2.22] - 2026-02-16
38
+
39
+ ### Security
40
+
41
+ - [CVE-2026-25500](https://github.com/advisories/GHSA-whrj-4476-wvmp) XSS injection via malicious filename in `Rack::Directory`.
42
+ - [CVE-2026-22860](https://github.com/advisories/GHSA-mxw3-3hh2-x2mh) Directory traversal via root prefix bypass in `Rack::Directory`.
43
+
44
+ ## [2.2.21] - 2025-11-03
45
+
46
+ ### Fixed
47
+
48
+ - Multipart parser: limit MIME header size check to the unread buffer region to avoid false `multipart mime part header too large` errors when previously read data accumulates in the scan buffer. ([#2392](https://github.com/rack/rack/pull/2392), [@alpaca-tc](https://github.com/alpaca-tc), [@willnet](https://github.com/willnet), [@krororo](https://github.com/krororo))
49
+
50
+ ## [2.2.20] - 2025-10-10
51
+
52
+ ### Security
53
+
54
+ - [CVE-2025-61780](https://github.com/advisories/GHSA-r657-rxjc-j557) Improper handling of headers in `Rack::Sendfile` may allow proxy bypass.
55
+ - [CVE-2025-61919](https://github.com/advisories/GHSA-6xw4-3v39-52mm) Unbounded read in `Rack::Request` form parsing can lead to memory exhaustion.
56
+
57
+ ## [2.2.19] - 2025-10-07
58
+
59
+ ### Security
60
+
61
+ - [CVE-2025-61772](https://github.com/advisories/GHSA-wpv5-97wm-hp9c) Multipart parser buffers unbounded per-part headers, enabling DoS (memory exhaustion)
62
+ - [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)
63
+ - [CVE-2025-61770](https://github.com/advisories/GHSA-p543-xpfm-54cp) Unbounded multipart preamble buffering enables DoS (memory exhaustion)
64
+
65
+ ## [2.2.18] - 2025-09-25
66
+
67
+ ### Security
68
+
69
+ - [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.
70
+
5
71
  ## [2.2.17] - 2025-06-03
6
72
 
7
73
  - Backport `Rack::MediaType#params` now handles parameters without values. ([#2263](https://github.com/rack/rack/pull/2263), [@AllyMarthaJ](https://github.com/AllyMarthaJ))
@@ -18,26 +84,26 @@ All notable changes to this project will be documented in this file. For info on
18
84
 
19
85
  ### Security
20
86
 
21
- - [CVE-2025-32441](https://github.com/rack/rack/security/advisories/GHSA-vpfw-47h7-xj4g) Rack session can be restored after deletion.
22
- - [CVE-2025-46727](https://github.com/rack/rack/security/advisories/GHSA-gjh7-p2fx-99vx) Unbounded parameter parsing in `Rack::QueryParser` can lead to memory exhaustion.
87
+ - [CVE-2025-32441](https://github.com/advisories/GHSA-vpfw-47h7-xj4g) Rack session can be restored after deletion.
88
+ - [CVE-2025-46727](https://github.com/advisories/GHSA-gjh7-p2fx-99vx) Unbounded parameter parsing in `Rack::QueryParser` can lead to memory exhaustion.
23
89
 
24
90
  ## [2.2.13] - 2025-03-11
25
91
 
26
92
  ### Security
27
93
 
28
- - [CVE-2025-27610](https://github.com/rack/rack/security/advisories/GHSA-7wqh-767x-r66v) Local file inclusion in `Rack::Static`.
94
+ - [CVE-2025-27610](https://github.com/advisories/GHSA-7wqh-767x-r66v) Local file inclusion in `Rack::Static`.
29
95
 
30
96
  ## [2.2.12] - 2025-03-04
31
97
 
32
98
  ### Security
33
99
 
34
- - [CVE-2025-27111](https://github.com/rack/rack/security/advisories/GHSA-8cgq-6mh2-7j6v) Possible Log Injection in `Rack::Sendfile`.
100
+ - [CVE-2025-27111](https://github.com/advisories/GHSA-8cgq-6mh2-7j6v) Possible Log Injection in `Rack::Sendfile`.
35
101
 
36
102
  ## [2.2.11] - 2025-02-12
37
103
 
38
104
  ### Security
39
105
 
40
- - [CVE-2025-25184](https://github.com/rack/rack/security/advisories/GHSA-7g2v-jj9q-g3rg) Possible Log Injection in `Rack::CommonLogger`.
106
+ - [CVE-2025-25184](https://github.com/advisories/GHSA-7g2v-jj9q-g3rg) Possible Log Injection in `Rack::CommonLogger`.
41
107
 
42
108
  ## [2.2.10] - 2024-10-14
43
109
 
data/README.rdoc CHANGED
@@ -206,6 +206,14 @@ query string, before attempting parsing, so if the same parameter key is
206
206
  used multiple times in the query, each counts as a separate parameter for
207
207
  this check.
208
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
+
209
217
  === key_space_limit
210
218
 
211
219
  The default number of bytes to allow all parameters keys in a given parameter hash to take up.
@@ -11,7 +11,7 @@ module Rack
11
11
  # If +app+ is not specified, a Rack::Files of the same +root+ will be used.
12
12
 
13
13
  class Directory
14
- DIR_FILE = "<tr><td class='name'><a href='%s'>%s</a></td><td class='size'>%s</td><td class='type'>%s</td><td class='mtime'>%s</td></tr>\n"
14
+ DIR_FILE = "<tr><td class='name'><a href='./%s'>%s</a></td><td class='size'>%s</td><td class='type'>%s</td><td class='mtime'>%s</td></tr>\n"
15
15
  DIR_PAGE_HEADER = <<-PAGE
16
16
  <html><head>
17
17
  <title>%s</title>
@@ -45,7 +45,7 @@ table { width:100%%; }
45
45
  class DirectoryBody < Struct.new(:root, :path, :files)
46
46
  # Yield strings for each part of the directory entry
47
47
  def each
48
- show_path = Utils.escape_html(path.sub(/^#{root}/, ''))
48
+ show_path = Utils.escape_html(path.sub(/\A#{Regexp.escape(root)}/, ''))
49
49
  yield(DIR_PAGE_HEADER % [ show_path, show_path ])
50
50
 
51
51
  unless path.chomp('/') == root
@@ -76,6 +76,7 @@ table { width:100%%; }
76
76
  # Set the root directory and application for serving files.
77
77
  def initialize(root, app = nil)
78
78
  @root = ::File.expand_path(root)
79
+ @root_with_separator = @root.end_with?(::File::SEPARATOR) ? @root : "#{@root}#{::File::SEPARATOR}"
79
80
  @app = app || Files.new(@root)
80
81
  @head = Head.new(method(:get))
81
82
  end
@@ -112,7 +113,9 @@ table { width:100%%; }
112
113
  # Rack response to use for requests with paths outside the root, or nil if path is inside the root.
113
114
  def check_forbidden(path_info)
114
115
  return unless path_info.include? ".."
115
- return if ::File.expand_path(::File.join(@root, path_info)).start_with?(@root)
116
+
117
+ expanded_path = ::File.expand_path(::File.join(@root, path_info))
118
+ return if expanded_path == @root || expanded_path.start_with?(@root_with_separator)
116
119
 
117
120
  body = "Forbidden\n"
118
121
  [403, { CONTENT_TYPE => "text/plain",
data/lib/rack/files.rb CHANGED
@@ -196,7 +196,7 @@ EOF
196
196
  status,
197
197
  {
198
198
  CONTENT_TYPE => "text/plain",
199
- CONTENT_LENGTH => body.size.to_s,
199
+ CONTENT_LENGTH => body.bytesize.to_s,
200
200
  "X-Cascade" => "pass"
201
201
  }.merge!(headers),
202
202
  [body]
@@ -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
@@ -20,6 +20,38 @@ module Rack
20
20
 
21
21
  BOUNDARY_REGEX = /\A([^\n]*(?:\n|\Z))/
22
22
 
23
+ LINE_END = /\n/
24
+ private_constant :LINE_END
25
+
26
+ BOUNDARY_START_LIMIT = 16 * 1024
27
+ private_constant :BOUNDARY_START_LIMIT
28
+
29
+ MIME_HEADER_BYTESIZE_LIMIT = 64 * 1024
30
+
31
+ OBS_UNFOLD = /\r\n([ \t])/
32
+
33
+ private_constant :OBS_UNFOLD
34
+ private_constant :MIME_HEADER_BYTESIZE_LIMIT
35
+
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
+ BUFFERED_UPLOAD_BYTESIZE_LIMIT = env_int.call("RACK_MULTIPART_BUFFERED_UPLOAD_BYTESIZE_LIMIT", 16 * 1024 * 1024)
49
+ private_constant :BUFFERED_UPLOAD_BYTESIZE_LIMIT
50
+
51
+ bytesize_limit = env_int.call("RACK_MULTIPART_PARSER_BYTESIZE_LIMIT", 10 * 1024 * 1024 * 1024)
52
+ PARSER_BYTESIZE_LIMIT = bytesize_limit > 0 ? bytesize_limit : nil
53
+ private_constant :PARSER_BYTESIZE_LIMIT
54
+
23
55
  class BoundedIO # :nodoc:
24
56
  def initialize(io, content_length)
25
57
  @io = io
@@ -60,7 +92,19 @@ module Rack
60
92
  return unless content_type
61
93
  data = content_type.match(MULTIPART)
62
94
  return unless data
63
- data[1]
95
+
96
+ unless data[1].empty?
97
+ raise EOFError, "whitespace between boundary parameter name and equal sign"
98
+ end
99
+ # Count across the whole header rather than only after the match: the
100
+ # lazy prefix in MULTIPART can skip a first boundary parameter whose
101
+ # value is empty or starts with a quote, semicolon, or comma. Also
102
+ # count RFC 2231 boundary* parameters, which some parsers prefer.
103
+ if content_type.scan(/boundary(?:\*\d*\*?)?\s*=/i).size > 1
104
+ raise EOFError, "multiple boundary parameters found in multipart content type"
105
+ end
106
+
107
+ data[2]
64
108
  end
65
109
 
66
110
  def self.parse(io, content_length, content_type, tmpfile, bufsize, qp)
@@ -69,6 +113,10 @@ module Rack
69
113
  boundary = parse_boundary content_type
70
114
  return EMPTY unless boundary
71
115
 
116
+ if PARSER_BYTESIZE_LIMIT && content_length && content_length > PARSER_BYTESIZE_LIMIT
117
+ raise EOFError, "multipart Content-Length #{content_length} exceeds limit of #{PARSER_BYTESIZE_LIMIT} bytes"
118
+ end
119
+
72
120
  io = BoundedIO.new(io, content_length) if content_length
73
121
  outbuf = String.new
74
122
 
@@ -187,6 +235,9 @@ module Rack
187
235
  @end_boundary = @boundary + '--'
188
236
  @state = :FAST_FORWARD
189
237
  @mime_index = 0
238
+ @body_retained = nil
239
+ @retained_size = 0
240
+ @total_bytes_read = (0 if PARSER_BYTESIZE_LIMIT)
190
241
  @collector = Collector.new tempfile
191
242
 
192
243
  @sbuf = StringScanner.new("".dup)
@@ -198,6 +249,12 @@ module Rack
198
249
 
199
250
  def on_read(content)
200
251
  handle_empty_content!(content)
252
+ if @total_bytes_read
253
+ @total_bytes_read += content.bytesize
254
+ if @total_bytes_read > PARSER_BYTESIZE_LIMIT
255
+ raise EOFError, "multipart upload exceeds limit of #{PARSER_BYTESIZE_LIMIT} bytes"
256
+ end
257
+ end
201
258
  @sbuf.concat content
202
259
  run_parser
203
260
  end
@@ -241,7 +298,13 @@ module Rack
241
298
  @state = :MIME_HEAD
242
299
  else
243
300
  raise EOFError, "bad content body" if @sbuf.rest_size >= @bufsize
244
- :want_read
301
+
302
+ # We raise if we don't find the multipart boundary, to avoid unbounded memory
303
+ # buffering. Note that the actual limit is the higher of 16KB and the buffer size (1MB by default)
304
+ raise EOFError, "multipart boundary not found within limit" if @sbuf.string.bytesize > BOUNDARY_START_LIMIT
305
+
306
+ # no boundary found, keep reading data
307
+ return :want_read
245
308
  end
246
309
  end
247
310
 
@@ -258,29 +321,47 @@ module Rack
258
321
  def handle_mime_head
259
322
  if @sbuf.scan_until(@head_regex)
260
323
  head = @sbuf[1]
261
- content_type = head[MULTIPART_CONTENT_TYPE, 1]
262
- if name = head[MULTIPART_CONTENT_DISPOSITION, 1]
324
+ # Implement OBS unfolding (RFC 5322 Section 2.2.3). Done on a copy
325
+ # because content type, disposition and filename are extracted by regex.
326
+ unfolded_head = head.gsub(OBS_UNFOLD, '\\1')
327
+ content_type = unfolded_head[MULTIPART_CONTENT_TYPE, 1]
328
+ if name = unfolded_head[MULTIPART_CONTENT_DISPOSITION, 1]
263
329
  name = Rack::Auth::Digest::Params::dequote(name)
264
330
  else
265
- name = head[MULTIPART_CONTENT_ID, 1]
331
+ name = unfolded_head[MULTIPART_CONTENT_ID, 1]
266
332
  end
267
333
 
268
- filename = get_filename(head)
334
+ filename = get_filename(unfolded_head)
269
335
 
270
336
  if name.nil? || name.empty?
271
337
  name = filename || "#{content_type || TEXT_PLAIN}[]".dup
272
338
  end
273
339
 
340
+ # Mime part head data is retained for both TempfilePart and BufferPart
341
+ # for the entireity of the parse, even though it isn't used for BufferPart.
342
+ update_retained_size(head.bytesize)
343
+
344
+ # If a filename is given, a TempfilePart will be used, so the body will
345
+ # not be buffered in memory. However, if a filename is not given, a BufferPart
346
+ # will be used, and the body will be buffered in memory.
347
+ @body_retained = !filename
348
+
274
349
  @collector.on_mime_head @mime_index, head, filename, content_type, name
275
350
  @state = :MIME_BODY
276
351
  else
277
- :want_read
352
+ # We raise if the mime part header is too large, to avoid unbounded memory
353
+ # buffering. Note that the actual limit is the higher of 64KB and the buffer size (1MB by default)
354
+ raise EOFError, "multipart mime part header too large" if @sbuf.rest.bytesize > MIME_HEADER_BYTESIZE_LIMIT
355
+
356
+ @sbuf.string = @sbuf.rest
357
+ return :want_read
278
358
  end
279
359
  end
280
360
 
281
361
  def handle_mime_body
282
362
  if (body_with_boundary = @sbuf.check_until(@body_regex)) # check but do not advance the pointer yet
283
363
  body = body_with_boundary.sub(/#{@body_regex}\z/m, '') # remove the boundary from the string
364
+ update_retained_size(body.bytesize) if @body_retained
284
365
  @collector.on_mime_body @mime_index, body
285
366
  @sbuf.pos += body.length + 2 # skip \r\n after the content
286
367
  @state = :CONSUME_TOKEN
@@ -289,18 +370,31 @@ module Rack
289
370
  # Save what we have so far
290
371
  if @rx_max_size < @sbuf.rest_size
291
372
  delta = @sbuf.rest_size - @rx_max_size
292
- @collector.on_mime_body @mime_index, @sbuf.peek(delta)
373
+ body = @sbuf.peek(delta)
374
+ update_retained_size(body.bytesize) if @body_retained
375
+ @collector.on_mime_body @mime_index, body
293
376
  @sbuf.pos += delta
294
- @sbuf.string = @sbuf.rest
295
377
  end
378
+ @sbuf.string = @sbuf.rest
296
379
  :want_read
297
380
  end
298
381
  end
299
382
 
300
383
  def full_boundary; @full_boundary; end
301
384
 
385
+ def update_retained_size(size)
386
+ @retained_size += size
387
+ if @retained_size > BUFFERED_UPLOAD_BYTESIZE_LIMIT
388
+ raise EOFError, "multipart data over retained size limit"
389
+ end
390
+ end
391
+
392
+ # Scan until the we find the start or end of the boundary.
393
+ # If we find it, return the appropriate symbol for the start or
394
+ # end of the boundary. If we don't find the start or end of the
395
+ # boundary, clear the buffer and return nil.
302
396
  def consume_boundary
303
- while read_buffer = @sbuf.scan_until(BOUNDARY_REGEX)
397
+ while read_buffer = scan_line
304
398
  case read_buffer.strip
305
399
  when full_boundary then return :BOUNDARY
306
400
  when @end_boundary then return :END_BOUNDARY
@@ -309,6 +403,21 @@ module Rack
309
403
  end
310
404
  end
311
405
 
406
+ # Return the next line of the buffer including its trailing "\n", or the
407
+ # rest of the buffer if it contains no "\n", and advance past it. This is
408
+ # equivalent to `@sbuf.scan_until(BOUNDARY_REGEX)`, but searching for the
409
+ # "\n" directly avoids the regexp engine's backtracking stack, which grows
410
+ # by one entry per byte matched by `[^\n]*` (tens of MB for a 1 MB line).
411
+ def scan_line
412
+ if line = @sbuf.scan_until(LINE_END)
413
+ line
414
+ else
415
+ line = @sbuf.rest
416
+ @sbuf.terminate
417
+ line
418
+ end
419
+ end
420
+
312
421
  def get_filename(head)
313
422
  filename = nil
314
423
  case head
@@ -12,7 +12,7 @@ module Rack
12
12
 
13
13
  EOL = "\r\n"
14
14
  MULTIPART_BOUNDARY = "AaB03x"
15
- MULTIPART = %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|ni
15
+ MULTIPART = %r|\Amultipart/.*?boundary(\s*)=\"?([^\";,]+)\"?|ni
16
16
  TOKEN = /[^\s()<>,;:\\"\/\[\]?=]+/
17
17
  CONDISP = /Content-Disposition:\s*#{TOKEN}\s*/i
18
18
  VALUE = /"(?:\\"|[^"])*"|#{TOKEN}/
@@ -51,6 +51,8 @@ module Rack
51
51
  PARAMS_LIMIT = env_int.call("RACK_QUERY_PARSER_PARAMS_LIMIT", 4096)
52
52
  private_constant :PARAMS_LIMIT
53
53
 
54
+ attr_reader :bytesize_limit
55
+
54
56
  def initialize(params_class, key_space_limit, param_depth_limit, bytesize_limit: BYTESIZE_LIMIT, params_limit: PARAMS_LIMIT)
55
57
  @params_class = params_class
56
58
  @key_space_limit = key_space_limit
@@ -185,10 +187,10 @@ module Rack
185
187
  def check_query_string(qs, sep)
186
188
  if qs
187
189
  if qs.bytesize > @bytesize_limit
188
- raise QueryLimitError, "total query size (#{qs.bytesize}) exceeds limit (#{@bytesize_limit})"
190
+ raise QueryLimitError, "total query size exceeds limit (#{@bytesize_limit})"
189
191
  end
190
192
 
191
- if (param_count = qs.count(sep.is_a?(String) ? sep : '&')) >= @params_limit
193
+ if (param_count = qs.count(sep.is_a?(String) ? sep : '&;')) >= @params_limit
192
194
  raise QueryLimitError, "total number of query parameters (#{param_count+1}) exceeds limit (#{@params_limit})"
193
195
  end
194
196
 
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
- # that it maps to. The middleware performs a simple substitution on the
50
+ # that it maps to. The middleware performs a case-insensitive 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
 
@@ -140,22 +157,35 @@ module Rack
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#{Regexp.escape(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
data/lib/rack/static.rb CHANGED
@@ -91,6 +91,9 @@ module Rack
91
91
  def initialize(app, options = {})
92
92
  @app = app
93
93
  @urls = options[:urls] || ["/favicon.ico"]
94
+ if @urls.kind_of?(Array)
95
+ @urls = @urls.map { |url| [url, url.end_with?('/') ? url : "#{url}/".freeze].freeze }.freeze
96
+ end
94
97
  @index = options[:index]
95
98
  @gzip = options[:gzip]
96
99
  @cascade = options[:cascade]
@@ -113,7 +116,7 @@ module Rack
113
116
  end
114
117
 
115
118
  def route_file(path)
116
- @urls.kind_of?(Array) && @urls.any? { |url| path.index(url) == 0 }
119
+ @urls.kind_of?(Array) && @urls.any? { |url, url_slash| path == url || path.start_with?(url_slash) }
117
120
  end
118
121
 
119
122
  def can_serve(path)
@@ -165,6 +168,8 @@ module Rack
165
168
 
166
169
  # Convert HTTP header rules to HTTP headers
167
170
  def applicable_rules(path)
171
+ path = ::Rack::Utils.clean_path_info(::Rack::Utils.unescape_path(path))
172
+
168
173
  @header_rules.find_all do |rule, new_headers|
169
174
  case rule
170
175
  when :all
@@ -172,10 +177,9 @@ module Rack
172
177
  when :fonts
173
178
  /\.(?:ttf|otf|eot|woff2|woff|svg)\z/.match?(path)
174
179
  when String
175
- path = ::Rack::Utils.unescape(path)
176
180
  path.start_with?(rule) || path.start_with?('/' + rule)
177
181
  when Array
178
- /\.(#{rule.join('|')})\z/.match?(path)
182
+ /\.#{Regexp.union(rule)}\z/.match?(path)
179
183
  when Regexp
180
184
  rule.match?(path)
181
185
  else
data/lib/rack/utils.rb CHANGED
@@ -186,17 +186,41 @@ module Rack
186
186
  string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] }
187
187
  end
188
188
 
189
+ # Given an array of available encoding strings, and an array of
190
+ # acceptable encodings for a request, where each element of the
191
+ # acceptable encodings array is an array where the first element
192
+ # is an encoding name and the second element is the numeric
193
+ # priority for the encoding, return the available encoding with
194
+ # the highest priority.
195
+ #
196
+ # The accept_encoding argument is typically generated by calling
197
+ # Request#accept_encoding.
198
+ #
199
+ # Example:
200
+ #
201
+ # select_best_encoding(%w(compress gzip identity),
202
+ # [["compress", 0.5], ["gzip", 1.0]])
203
+ # # => "gzip"
204
+ #
205
+ # To reduce denial of service potential, only the first 16
206
+ # acceptable encodings are considered.
189
207
  def select_best_encoding(available_encodings, accept_encoding)
190
208
  # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
191
209
 
210
+ # Only process the first 16 encodings
211
+ accept_encoding = accept_encoding[0...16]
192
212
  expanded_accept_encoding = []
213
+ wildcard_seen = false
193
214
 
194
215
  accept_encoding.each do |m, q|
195
216
  preference = available_encodings.index(m) || available_encodings.size
196
217
 
197
218
  if m == "*"
198
- (available_encodings - accept_encoding.map(&:first)).each do |m2|
199
- expanded_accept_encoding << [m2, q, preference]
219
+ unless wildcard_seen
220
+ (available_encodings - accept_encoding.map(&:first)).each do |m2|
221
+ expanded_accept_encoding << [m2, q, preference]
222
+ end
223
+ wildcard_seen = true
200
224
  end
201
225
  else
202
226
  expanded_accept_encoding << [m, q, preference]
@@ -204,7 +228,13 @@ module Rack
204
228
  end
205
229
 
206
230
  encoding_candidates = expanded_accept_encoding
207
- .sort_by { |_, q, p| [-q, p] }
231
+ .sort do |(_, q1, p1), (_, q2, p2)|
232
+ if r = (q1 <=> q2).nonzero?
233
+ -r
234
+ else
235
+ (p1 <=> p2).nonzero? || 0
236
+ end
237
+ end
208
238
  .map!(&:first)
209
239
 
210
240
  unless encoding_candidates.include?("identity")
@@ -350,16 +380,17 @@ module Rack
350
380
  # Parses the "Range:" header, if present, into an array of Range objects.
351
381
  # Returns nil if the header is missing or syntactically invalid.
352
382
  # Returns an empty array if none of the ranges are satisfiable.
353
- def byte_ranges(env, size)
354
- warn "`byte_ranges` is deprecated, please use `get_byte_ranges`" if $VERBOSE
355
- get_byte_ranges env['HTTP_RANGE'], size
383
+ def byte_ranges(env, size, max_ranges: 100)
384
+ get_byte_ranges env['HTTP_RANGE'], size, max_ranges: max_ranges
356
385
  end
357
386
 
358
- def get_byte_ranges(http_range, size)
387
+ def get_byte_ranges(http_range, size, max_ranges: 100)
359
388
  # See <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35>
360
389
  return nil unless http_range && http_range =~ /bytes=([^;]+)/
390
+ byte_range = $1
391
+ return nil if byte_range.count(',') >= max_ranges
361
392
  ranges = []
362
- $1.split(/,\s*/).each do |range_spec|
393
+ byte_range.split(/,[ \t]*/).each do |range_spec|
363
394
  return nil unless range_spec.include?('-')
364
395
  range = range_spec.split('-')
365
396
  r0, r1 = range[0], range[1]
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.17"
23
+ RELEASE = "2.2.25"
24
24
 
25
25
  # Return the Rack release as a dotted string.
26
26
  def self.release
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: rack
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.2.17
4
+ version: 2.2.25
5
5
  platform: ruby
6
6
  authors:
7
7
  - Leah Neukirchen
@@ -182,7 +182,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
182
182
  - !ruby/object:Gem::Version
183
183
  version: '0'
184
184
  requirements: []
185
- rubygems_version: 3.7.0.dev
185
+ rubygems_version: 4.0.10
186
186
  specification_version: 4
187
187
  summary: A modular Ruby webserver interface.
188
188
  test_files: []