ruby/psych

YAML.safe_load fails when a string contains regexp pattern

ciscolive opened this issue · 3 comments

YAML.safe_load will raise an exception when you try to load text that happens to contain a sequence of regexp that looks like a network device propmt but is not:

3.0.0 :003 > YAML.safe_load '!ruby/regexp /^([\w.@-]+[#>]\s?)$/'
/usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/class_loader.rb:99:in find': Tried to load unspecified class: Regexp (Psych::DisallowedClass) from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/class_loader.rb:28:in load'
from (eval):2:in regexp' from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/visitors/to_ruby.rb:96:in deserialize'
from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/visitors/to_ruby.rb:127:in visit_Psych_Nodes_Scalar' from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/visitors/visitor.rb:30:in visit'
from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/visitors/visitor.rb:6:in accept' from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/visitors/to_ruby.rb:34:in accept'
from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/visitors/to_ruby.rb:317:in visit_Psych_Nodes_Document' from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/visitors/visitor.rb:30:in visit'
from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/visitors/visitor.rb:6:in accept' from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych/visitors/to_ruby.rb:34:in accept'
from /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/3.0.0/psych.rb:361:in safe_load' from (irb):3:in

'
from /usr/local/rvm/gems/ruby-3.0.0/gems/irb-1.3.5/exe/irb:11:in <top (required)>' from /usr/local/rvm/gems/ruby-3.0.0/bin/irb:23:in load'
from /usr/local/rvm/gems/ruby-3.0.0/bin/irb:23:in `'

Using YAML.load instead of safe_load works fine and text that contains a correct date works fine too. But this can be used to raise an exception on any application that uses YAML.safe_load on user provided text (accidentally or otherwise)

careline:~ # gem info psych

*** LOCAL GEMS ***

psych (4.0.0, 3.3.0)
Authors: Aaron Patterson, SHIBATA Hiroshi, Charles Oliver Nutter
Homepage: https://github.com/ruby/psych
License: MIT
Installed at (4.0.0): /usr/local/rvm/gems/ruby-3.0.0
(3.3.0, default): /usr/local/rvm/rubies/ruby-3.0.0/lib/ruby/gems/3.0.0

Psych is a YAML parser and emitter

You can see #489 .

hsbt commented

Use permitted_classes

>> YAML.safe_load '!ruby/regexp /^([\w.@-]+[#>]\s?)$/', permitted_classes: [Regexp]
=> /^([\w.@-]+[#>]\s?)$/