Invalid handling of zero-length heredoc identifiers leads to infinite loop in the sandbox
An invalid Ruby program using a heredoc with an empty identifier causes MRuby's parser to loop forever instead of raising a syntax error. An attacker could submit such code to the mruby-engine sandbox and make the process unresponsive to SIGTERM, requiring SIGABRT or SIGKILL to stop it.
- Triaged in 3 hours
- Fixed in 7 days
- Paid in 41 days
- Disclosed after 42 days
Introduction
Certain invalid Ruby programs (which should normally raise a syntax error) are able to cause an infinite loop in MRuby's parser which makes the mruby-engine sandbox (and consequently the MRI process it is running in) unresponsive to SIGTERM. The process begins looping forever and has to be terminated using SIGABRT or SIGKILL. The bug is caused by an improper handling of heredocs with a zero-length identifier.
Proof of concept
infinite_heredoc.rb:
<<''.a begin
- Save the above code as
infinite_heredoc.rb. - Run either:
a)
mruby infinite_heredoc.rbb)sandbox infinite_heredoc.rb - Both cause an infinite loop, but b) also leaves the process unresponsive to SIGTERM.
Discussion
Everything below assumes the latest master of the mruby repository as of Dec 01th, which is commit 2cca9d368815e9c83a7489c40d69937d68cb43a2.
The <<''˙in the above POC code is parsed as a heredoc with an empty identifier. The rest of the POC is needed to bring the parser in a state where it is:
- Continually searching for the identifier.
- Erroneously thinking it found it, thereby signalling an end of the heredoc by pushing a
tHEREDOC_ENDtoken. - This token is then invalid for the current parser state, which makes it push an error token.
- Finally, while processing the error, the parser eventually calls
parse_stringagain, which brings the process back to step 1, resulting in an infinite loop.
A variation of the bug, using do instead of begin:
infinite_heredoc_variation.rb:
<<''.a do
An excerpt from the parser's debug output, demonstrating the above:
Reading a token: Next token is token tHEREDOC_END ()
Error: discarding token tHEREDOC_END ()
Error: popping token error ()
Stack now 0 2 81 370 586 257 8 199
Shifting token error ()
Entering state 271
Reading a token: Next token is token tHEREDOC_END ()
Error: discarding token tHEREDOC_END ()
[...]
It is interesting to study what output MRI's parser gives for the same input:
infinite_heredoc.rb:1: can't find string "" anywhere before EOF
infinite_heredoc.rb:1: syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
<<''.a begin
^
For a heredoc with a non-zero name, both MRuby and MRI produce similar outputs:
heredoc_valid_name.rb
<<'h'.a begin
MRuby output
heredoc_valid_name.rb:3:0: can't find heredoc delimiter "h" anywhere before EOF
heredoc_valid_name.rb:3:0: syntax error, unexpected $end
MRI output
heredoc_valid_name.rb:1: can't find string "h" anywhere before EOF
heredoc_valid_name.rb:1: syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
<<'h'.a begin
^
Solution
The problematic code is located parse.y, function parse_string, starting at line 3956:
if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0)) {
return tHEREDOC_END;
}
The above code checks whether the current heredoc identifier can be matched and, if so, signals the end of the heredoc by returning a tHEREDOC_END token. The code is incorrect in the case when the length parameter is 0 due to the use of strncmp since it will return 0 even when the input strings are different (as is the case here, where s is "\n" and hinf->term is ""). Therefore, the check incorrectly succeeds when it shouldn't.
A possible fix is to check whether hinf->term_len != 0 in addition to the present checks so zero-length heredoc identifiers are invalidated.
empty_heredoc_identifier.patch
diff --git a/mrbgems/mruby-compiler/core/parse.y b/mrbgems/mruby-compiler/core/parse.y
index bf893fb..85150fc 100644
--- a/mrbgems/mruby-compiler/core/parse.y
+++ b/mrbgems/mruby-compiler/core/parse.y
@@ -3953,7 +3953,7 @@ parse_string(parser_state *p)
--len;
}
}
- if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0)) {
+ if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0) && (hinf->term_len != 0)) {
return tHEREDOC_END;
}
}
With the provided patch, MRuby correctly terminates with the POC and issues an error message very similar to the one in MRI:
infinite_heredoc.rb:3:0: can't find heredoc delimiter "" anywhere before EOF
infinite_heredoc.rb:3:0: syntax error, unexpected $end
In addition, all the tests pass.
-- Denis Kasak Damir Jelić
Context
Shopify Scripts ran untrusted Ruby code inside a sandbox built on MRuby, the embeddable Ruby implementation. The sandbox is the mruby-engine, and it runs inside an MRI (standard Ruby) process. The parser that turns source text into tokens and grammar actions lives in parse.y, and one of its jobs is to recognise the end of a heredoc: a string literal that starts with << and continues until a delimiter line is found.
A heredoc normally has a non-empty identifier, as in <<'h'. The parser scans forward for that identifier and, when it matches, emits a tHEREDOC_END token. The report shows that a heredoc with a zero-length identifier is handled incorrectly, and that this can put the parser into an infinite loop.
Setup
The analysis is against the latest master of the mruby repository as of 1 December, commit [redacted]. Two executables are used: mruby, the standalone interpreter, and sandbox, the mruby-engine sandbox. No accounts or roles are involved; the precondition is simply the ability to submit Ruby source that the parser will process.
Finding it
Certain invalid Ruby programs, which should raise a syntax error, instead cause an infinite loop in MRuby's parser. In the sandbox this also makes the MRI process it runs in unresponsive to SIGTERM. The process loops forever and has to be terminated with SIGABRT or SIGKILL. The bug is caused by improper handling of heredocs with a zero-length identifier.
Exploitation
Step 1: write the payload
Save the following as infinite_heredoc.rb:
<<''.a begin
The <<'' is parsed as a heredoc with an empty identifier. The rest of the POC is needed to bring the parser into the state where it loops.
Step 2: run it
Run either of the following:
mruby infinite_heredoc.rb
sandbox infinite_heredoc.rb
Both cause an infinite loop. The second also leaves the process unresponsive to SIGTERM, so it must be killed with SIGABRT or SIGKILL.
What the loop looks like
The parser cycles through four states:
- It continually searches for the identifier.
- It erroneously thinks it has found it, signalling the end of the heredoc by pushing a
tHEREDOC_ENDtoken. - That token is invalid for the current parser state, so the parser pushes an error token.
- While processing the error, the parser eventually calls
parse_stringagain, which returns the process to step 1.
The parser's debug output shows the cycle directly:
Reading a token: Next token is token tHEREDOC_END ()
Error: discarding token tHEREDOC_END ()
Error: popping token error ()
Stack now 0 2 81 370 586 257 8 199
Shifting token error ()
Entering state 271
Reading a token: Next token is token tHEREDOC_END ()
Error: discarding token tHEREDOC_END ()
[...]
A variation
Replacing begin with do triggers the same bug:
<<''.a do
How MRI handles the same input
For comparison, MRI's parser rejects the input cleanly:
infinite_heredoc.rb:1: can't find string "" anywhere before EOF
infinite_heredoc.rb:1: syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
<<''.a begin
^
With a non-zero heredoc name, MRuby and MRI behave similarly. The file heredoc_valid_name.rb contains:
<<'h'.a begin
MRuby output:
heredoc_valid_name.rb:3:0: can't find heredoc delimiter "h" anywhere before EOF
heredoc_valid_name.rb:3:0: syntax error, unexpected $end
MRI output:
heredoc_valid_name.rb:1: can't find string "h" anywhere before EOF
heredoc_valid_name.rb:1: syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
<<'h'.a begin
^
Root cause
The problematic code is in parse.y, in the function parse_string, starting at line 3956:
if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0)) {
return tHEREDOC_END;
}
This check decides whether the current heredoc identifier can be matched and, if so, signals the end of the heredoc by returning tHEREDOC_END. It is wrong when the length parameter is 0, because strncmp returns 0 even when the input strings differ. Here s is "\n" and hinf->term is "", so the comparison succeeds when it should not. The parser therefore believes the heredoc has ended, emits a token that is invalid in the current state, and the error handling leads back into parse_string, producing the loop.
Impact
An invalid Ruby program submitted to the sandbox can make the mruby-engine sandbox, and the MRI process hosting it, loop forever. The process becomes unresponsive to SIGTERM and must be terminated with SIGABRT or SIGKILL. The report describes no consequence beyond the process looping and needing SIGABRT or SIGKILL.
Fix
The suggested fix adds a check that hinf->term_len != 0 alongside the existing conditions, so zero-length heredoc identifiers are invalidated:
diff --git a/mrbgems/mruby-compiler/core/parse.y b/mrbgems/mruby-compiler/core/parse.y
index bf893fb..85150fc 100644
--- a/mrbgems/mruby-compiler/core/parse.y
+++ b/mrbgems/mruby-compiler/core/parse.y
@@ -3953,7 +3953,7 @@ parse_string(parser_state *p)
--len;
}
}
- if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0)) {
+ if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0) && (hinf->term_len != 0)) {
return tHEREDOC_END;
}
}
With the patch applied, MRuby terminates on the proof of concept and issues an error message very similar to MRI's:
infinite_heredoc.rb:3:0: can't find heredoc delimiter "" anywhere before EOF
infinite_heredoc.rb:3:0: syntax error, unexpected $end
All the tests pass with the patch.
Variants to test
- Replace
beginwithdoin the payload, as in the report's variation. A positive result is the same infinite loop and, under the sandbox, the same unresponsiveness to SIGTERM. - Try other zero-length or degenerate delimiter forms in heredoc syntax and see whether the parser still emits
tHEREDOC_ENDwhen it should not. A positive result is a parser that never terminates on input that MRI rejects with a syntax error. - Compare MRuby and MRI output for the same malformed heredoc input. A positive result is a divergence where MRuby loops or accepts and MRI reports a syntax error.
Hunting notes
This class of bug hides in hand-written parsers and lexers, especially where C string functions are used with lengths derived from user input. strncmp with a zero length always matches, and any comparison that trusts a length field without validating it is a candidate. During recon, look for embedded interpreters and sandboxes that accept source code, and for parser code paths that handle delimiters, terminators and end-of-input markers.
The proof of concept was run with both mruby and sandbox; the sandbox run also left the process unresponsive to SIGTERM. The report compares MRI's output for the same input and notes that all tests pass with the patch.
What happened, in plain words
Instead they were run inside a sandbox: a sealed-off area, like a playpen, where a program can do its thing without touching anything important outside.
The sandbox in this report is called mruby-engine, and it is built on MRuby. The sandbox itself runs inside a normal Ruby process (called MRI, the standard Ruby interpreter).
Before a program can run, it has to be read and understood. That job belongs to the parser: the part of the software that reads the raw text of a program and works out what each piece means, a bit like a person reading a sentence and identifying the words and grammar. The parser in MRuby lives in a file called parse.y.
One thing the parser must recognise is a heredoc. A heredoc is a way of writing a long piece of text inside a program: it starts with << followed by a name, and everything after it is treated as text until a line containing that same name appears. Think of it as saying "here comes a block of text, and it ends when you see this word again". Normally the name is not empty, for example <<'h'. The parser scans forward looking for that name, and when it finds it, it produces a signal called a token meaning "the heredoc ends here". This particular token is named tHEREDOC_END.
A heredoc with an empty name is handled incorrectly. Instead of producing a syntax error (the parser's way of saying "this program is not valid Ruby"), the parser gets stuck in an endless loop. In the sandbox, this also makes the whole surrounding Ruby process hang, so it no longer responds to the normal polite request to stop (a signal called SIGTERM). It has to be killed more forcefully, with SIGABRT or SIGKILL.
Setup
The analysis was done against the latest master of the mruby repository as of 1 December, which is commit [redacted]. A commit is a saved snapshot of a code project, identified by a long string of characters, so anyone can refer to exactly the same version of the code.
Two programs are used in the tests:
mruby, the standalone MRuby interpreter: a program you run from a command line, which reads a Ruby file and executes it.sandbox, the mruby-engine sandbox: the same idea, but wrapped in the sealed-off environment Shopify used.
Finding it
Certain invalid Ruby programs, which should raise a syntax error, instead cause an infinite loop in MRuby's parser. In the sandbox this also makes the MRI process it runs in unresponsive to SIGTERM. The process loops forever and has to be terminated with SIGABRT or SIGKILL. The bug is caused by improper handling of heredocs with a zero-length identifier.
Exploitation
Step 1: write the payload
Save the following as infinite_heredoc.rb:
<<''.a begin
Line by line:
<<''is the start of a heredoc whose name is the empty string. The two single quotes contain nothing at all, so the name the parser is looking for is zero characters long..aandbeginare ordinary Ruby-looking text that follows on the same line. The rest of the POC is needed to bring the parser into the state where it loops.
The whole file is saved under the name infinite_heredoc.rb so it can be handed to the interpreters in the next step.
Step 2: run it
Run either of the following:
mruby infinite_heredoc.rb
sandbox infinite_heredoc.rb
Line by line:
mruby infinite_heredoc.rbasks the standalone MRuby interpreter to read and run the file.sandbox infinite_heredoc.rbasks the sandbox to do the same.
Both cause an infinite loop. The second also leaves the process unresponsive to SIGTERM, so it must be killed with SIGABRT or SIGKILL. SIGTERM is the normal "please stop" signal that a well-behaved program obeys; SIGABRT and SIGKILL are blunter ways of stopping a process that will not listen.
What the loop looks like
The parser cycles through four states:
- It continually searches for the identifier.
- It erroneously thinks it has found it, signalling the end of the heredoc by pushing a
tHEREDOC_ENDtoken. - That token is invalid for the current parser state, so the parser pushes an error token.
- While processing the error, the parser eventually calls
parse_stringagain, which returns the process to step 1.
In everyday terms: the parser keeps looking for a name that is not there, keeps wrongly deciding it found it, keeps complaining that the result does not fit, and the complaint sends it back to the start. Nothing ever moves forward.
The parser's debug output shows the cycle directly:
Reading a token: Next token is token tHEREDOC_END ()
Error: discarding token tHEREDOC_END ()
Error: popping token error ()
Stack now 0 2 81 370 586 257 8 199
Shifting token error ()
Entering state 271
Reading a token: Next token is token tHEREDOC_END ()
Error: discarding token tHEREDOC_END ()
[...]
Line by line:
Reading a token: Next token is token tHEREDOC_END ()means the parser has just produced the "heredoc ends here" token.Error: discarding token tHEREDOC_END ()means that token is not allowed at this point, so it is thrown away.Error: popping token error ()andStack now 0 2 81 370 586 257 8 199show the parser's internal bookkeeping (its stack) being adjusted while it handles the error. The numbers are internal state identifiers, not anything meaningful to a user.Shifting token error ()andEntering state 271show the parser moving into its error-handling state.Reading a token: Next token is token tHEREDOC_END ()and the following lines repeat the same sequence, which is the loop itself. The[...]means the output carries on like this indefinitely.
A variation
Replacing begin with do triggers the same bug:
<<''.a do
Line by line:
<<''is again a heredoc with an empty name..a doplays the same role as.a begindid: it puts the parser into the state where the bad token is rejected and the error handling loops back.
How MRI handles the same input
For comparison, MRI's parser rejects the input cleanly:
infinite_heredoc.rb:1: can't find string "" anywhere before EOF
infinite_heredoc.rb:1: syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
<<''.a begin
^
Line by line:
- The first line says MRI could not find the empty string anywhere before the end of the file, and names the file and line number.
- The second line is the syntax error itself: the program ended unexpectedly, and the parser lists the kinds of token it would have accepted instead.
- The last two lines repeat the offending source line and put a
^under the position where the problem was detected.
With a non-zero heredoc name, MRuby and MRI behave similarly. The file heredoc_valid_name.rb contains:
<<'h'.a begin
Line by line:
<<'h'is a heredoc whose name is the single letterh, so the name is not empty..a beginis the same trailing text as before, so the only difference from the failing payload is that the name has a length.
MRuby output:
heredoc_valid_name.rb:3:0: can't find heredoc delimiter "h" anywhere before EOF
heredoc_valid_name.rb:3:0: syntax error, unexpected $end
Line by line:
- The first line reports that the delimiter
hwas never found before the end of the file, with the file name and position. - The second line reports a syntax error because the input ended unexpectedly (
$endis the parser's name for end of input).
MRI output:
heredoc_valid_name.rb:1: can't find string "h" anywhere before EOF
heredoc_valid_name.rb:1: syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
<<'h'.a begin
^
Line by line:
- The first line is MRI's version of "the delimiter
hwas never found". - The second line is the syntax error, listing the token types it expected.
- The last two lines show the offending source line with a
^marking the position.
For a heredoc with a non-zero name, both MRuby and MRI produce similar outputs.
Root cause
The problematic code is in parse.y, in the function parse_string, starting at line 3956:
if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0)) {
return tHEREDOC_END;
}
Line by line:
if (...)starts a check. If everything inside the brackets is true, the code inside the braces runs.len-1 == hinf->term_lencompares the length of the text being examined (minus one) with the stored length of the heredoc's name.hinf->term_lenis simply a number saying how many characters the name has.strncmp(s, hinf->term, len-1) == 0compares the textswith the stored namehinf->term, looking atlen-1characters.strncmpis a standard C function for comparing two pieces of text; it returns 0 when they match.return tHEREDOC_END;means "tell the parser the heredoc has ended here".
This check decides whether the current heredoc identifier can be matched and, if so, signals the end of the heredoc by returning tHEREDOC_END. It is wrong when the length parameter is 0, because strncmp returns 0 even when the input strings differ. Here s is "\n" (a newline character) and hinf->term is "" (nothing at all), so the comparison succeeds when it should not. A useful comparison: if someone asks you to compare the first zero letters of two words, you have compared nothing, and "nothing" always matches "nothing". The parser therefore believes the heredoc has ended, emits a token that is invalid in the current state, and the error handling leads back into parse_string, producing the loop.
Impact
An invalid Ruby program submitted to the sandbox can make the mruby-engine sandbox, and the MRI process hosting it, loop forever. The process becomes unresponsive to SIGTERM and must be terminated with SIGABRT or SIGKILL. The report does not describe any further consequence beyond this denial of service against the process.
Fix
The suggested fix adds a check that hinf->term_len != 0 alongside the existing conditions, so zero-length heredoc identifiers are invalidated:
diff --git a/mrbgems/mruby-compiler/core/parse.y b/mrbgems/mruby-compiler/core/parse.y
index bf893fb..85150fc 100644
--- a/mrbgems/mruby-compiler/core/parse.y
+++ b/mrbgems/mruby-compiler/core/parse.y
@@ -3953,7 +3953,7 @@ parse_string(parser_state *p)
--len;
}
}
- if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0)) {
+ if ((len-1 == hinf->term_len) && (strncmp(s, hinf->term, len-1) == 0) && (hinf->term_len != 0)) {
return tHEREDOC_END;
}
}
Line by line:
- The
diff --gitline names the file being changed,mrbgems/mruby-compiler/core/parse.y. - The
indexline identifies the old and new versions of the file by short codes. - The
---and+++lines mark the old and new file. - The
@@ -3953,7 +3953,7 @@line says the change is around line 3953 and shows seven lines of context on each side. - The lines starting with a space are unchanged context.
- The line starting with
-is the old check, and the line starting with+is the new one. The only addition is&& (hinf->term_len != 0), which means "and the name must not be empty". - The remaining lines are unchanged context, including the
return tHEREDOC_END;and the closing braces.
With the patch applied, MRuby terminates on the proof of concept and issues an error message very similar to MRI's:
infinite_heredoc.rb:3:0: can't find heredoc delimiter "" anywhere before EOF
infinite_heredoc.rb:3:0: syntax error, unexpected $end
Line by line:
- The first line says the empty delimiter was never found before the end of the file, with the file name and position.
- The second line is the syntax error for the unexpected end of input.
All the tests pass with the patch.
Variants to test
- Replace
beginwithdoin the payload, as in the report's variation. A positive result is the same infinite loop and, under the sandbox, the same unresponsiveness to SIGTERM. - Try other zero-length or degenerate delimiter forms in heredoc syntax and see whether the parser still emits
tHEREDOC_ENDwhen it should not. A positive result is a parser that never terminates on input that MRI rejects with a syntax error. - Compare MRuby and MRI output for the same malformed heredoc input. A positive result is a divergence where MRuby loops or accepts and MRI reports a syntax error.
Hunting notes
This class of bug hides in hand-written parsers and lexers, especially where C string functions are used with lengths derived from user input. A lexer is the part that chops raw text into tokens; a parser then decides what those tokens mean together. strncmp with a zero length always matches, and any comparison that trusts a length field without validating it is a candidate. During recon, look for embedded interpreters and sandboxes that accept source code, and for parser code paths that handle delimiters, terminators and end-of-input markers.
The proof of concept was run with both mruby and sandbox; the sandbox run also left the process unresponsive to SIGTERM. The report compares MRI's output for the same input and notes that all tests pass with the patch.
Glossary
- Sandbox: a sealed-off environment where untrusted code can run without affecting the rest of the system.
- Ruby: a programming language, often used for web applications.
- MRuby: a small, embeddable implementation of Ruby, designed to be built into other programs.
- MRI: the standard Ruby interpreter, the reference implementation of the language.
- Parser: the part of a program that reads source text and works out its structure.
- Lexer: the part of a program that splits raw text into small units called tokens.
- Token: a labelled piece of input produced by the lexer, such as "a string starts here" or "the heredoc ends here".
- Heredoc: a way of writing a block of text in Ruby, starting with
<<and a name, and ending at a line containing that name. - Identifier / delimiter: the name used to mark the end of a heredoc.
tHEREDOC_END: the token the parser emits when it believes a heredoc has ended.- Syntax error: the parser's way of saying the program is not valid and cannot be run.
- Infinite loop: a situation where a program repeats the same steps forever and never finishes.
- Denial of service: an attack that stops a service from working, without necessarily stealing data or breaking in.
- SIGTERM: the normal signal asking a process to stop; well-behaved programs obey it.
- SIGABRT: a signal that aborts a process immediately.
- SIGKILL: a signal that forces a process to stop and cannot be ignored.
- Process: a running instance of a program on a computer.
- Commit: a saved snapshot of a code project, identified by a long string of characters.
strncmp: a standard C function that compares two pieces of text up to a given number of characters.- Patch: a small change to source code, usually shown as a diff.
- Diff: a display of the differences between two versions of a file, with
-for removed lines and+for added lines. - Proof of concept (POC): a small input or program that demonstrates a bug actually happens.
- Recon: the early stage of security testing where you look around a target to find things worth testing.