Ruby: Add another code injection example to qhelp

This commit is contained in:
Harry Maclean
2022-12-28 11:20:56 +13:00
parent d95a4a7baf
commit d3812f5906
3 changed files with 47 additions and 0 deletions

View File

@@ -66,6 +66,26 @@ to define the getter method.
<sample src="examples/UnsafeCodeConstruction2Safe.rb" />
</example>
<example>
<p>
This example dynamically registers a method on another class which
forwards its arguments to the registering module. This approach uses
<code>module_eval</code> and string interpolation to construct class variables
and methods.
</p>
<sample src="examples/UnsafeCodeConstruction3.rb" />
<p>
A safer approach is to use <code>class_variable_set</code> and
<code>class_variable_get</code> along with <code>define_method</code>. String
interpolation is still used to construct the class variable name, but this is
safe because <code>class_variable_set<code> is not susceptible to code injection.
</p>
<sample src="examples/UnsafeCodeConstruction3Safe.rb" />
</example>
<references>
<li>
OWASP:
@@ -74,5 +94,11 @@ OWASP:
<li>
Wikipedia: <a href="https://en.wikipedia.org/wiki/Code_injection">Code Injection</a>.
</li>
<li>
Ruby documentation: <a href="https://docs.ruby-lang.org/en/3.2/Module.html#method-i-define_method"><code>define_method</code></a>.
</li>
<li>
Ruby documentation: <a href="https://docs.ruby-lang.org/en/3.2/Module.html#method-i-class_variable_set"><code>class_variable_set</code></a>.
</li>
</references>
</qhelp>

View File

@@ -0,0 +1,12 @@
module Invoker
def attach(klass, name)
invoker = self
klass.module_eval <<-CODE
@@#{name} = invoker
def #{name}(*args)
@@#{name}.call(*args)
end
CODE
end
end

View File

@@ -0,0 +1,9 @@
module Invoker
def attach(klass, name)
var = :"@@#{name}"
klass.class_variable_set(var, self)
klass.define_method(name) do |*args|
self.class.class_variable_get(var).call(*args)
end
end
end