Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix regexp #6

Merged
merged 1 commit into from
Jan 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/erb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,7 @@ def detect_magic_comment(s, enc = nil)
frozen = nil
s.scan(re) do
comment = $+
comment = $1 if comment[/-\*-\s*(.*?)\s*-*-$/]
comment = $1 if comment[/-\*-\s*([^\s].*?)\s*-*-$/]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it intentional that you changed the behavior of the regexp?

"-*--"[/-\*-\s*(.*?)\s*-*-$/] #=> "-*--"

"-*--"[/-\*-\s*([^\s].*?)\s*-*-$/] #=> nil

First of all, I believe the magic comment syntax is -*- xxx -*-, so it's weird that the last * is not escaped. Would just escaping it fix the ReDoS problem?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, the change in regexp behavior was unintentional.

Even if escape last *, the ReDoS problem seems to remain.

# current
❯ time ruby -e '"-*-#{" "* 3456}"[/-\*-\s*(.*?)\s*-*-$/]'
ruby -e '"-*-#{" "* 3456}"[/-\*-\s*(.*?)\s*-*-$/]'  41.47s user 0.14s system 99% cpu 41.773 total

# escape last `*` 
❯ time ruby -e '"-*-#{" "* 3456}"[/-\*-\s*(.*?)\s*-\*-$/]'
ruby -e '"-*-#{" "* 3456}"[/-\*-\s*(.*?)\s*-\*-$/]'  30.50s user 0.12s system 99% cpu 30.741 total

# fix ReDoS
❯ time ruby -e '"-*-#{" "* 3456}"[/-\*-\s*([^\s].*?)\s*-*-$/]'
ruby -e '"-*-#{" "* 3456}"[/-\*-\s*([^\s].*?)\s*-*-$/]'  0.05s user 0.05s system 73% cpu 0.129 total

# fix ReDoS and escape last `*`
❯ time ruby -e '"-*-#{" "* 3456}"[/-\*-\s*([^\s].*?)\s*-\*-$/]'
ruby -e '"-*-#{" "* 3456}"[/-\*-\s*([^\s].*?)\s*-\*-$/]'  0.05s user 0.05s system 75% cpu 0.122 total

/-\*-\s*([^\s].*?)\s*-\*-$/ seems to be a regular expression with the correct intent.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was only looking at this line, but looking at how comment is used, the change seems fine. So I'll merge your change, also addressing \* separately.

case comment
when %r"coding\s*[=:]\s*([[:alnum:]\-_]+)"
enc = Encoding.find($1.sub(/-(?:mac|dos|unix)/i, ''))
Expand Down