When do Ruby objects need to be made tainted and when should we untaint them? How does the concept of tainted object make a Ruby script run in safe mode? Can anyone elaborate on this to make the concept clear with some code snippets?
User input is tainted, by definition. For example:
string = gets
string.tainted?
# => true
You can also manually taint an object.
string = 'Not yet tainted.'
string.tainted?
# => false
(string = 'Explicitly taint me!').taint
string.tainted?
# => true
Generally, you would untaint an object only after you validate and/or sanitize it. Untainting an object marks it as "safe" for certain operations that you wouldn't want to run on untrusted strings or other objects, or when your safe level requires an untainted object to perform the desired operation.
The easiest way to untaint an object is to call the Object#untaint method on it. For example, if your string variable holds a tainted object, then:
(string = "Let's taint this string!").taint
string.untaint.tainted?
# => false
You can find out more about tainted objects from the Locking Ruby in the Safe chapter of Programming Ruby.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With