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?
Asked
Active
Viewed 6,110 times
19
-
Related answer, but not a duplicate question: http://stackoverflow.com/a/14259324/1301972 – Todd A. Jacobs Jan 11 '13 at 15:17
-
Can a bit focus on to the question `How does the concept of tainted object make a Ruby script run in safe mode?`? – Arup Rakshit Jan 11 '13 at 15:49
1 Answers
20
What is Tainted?
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
Why Untaint an Object?
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.
Untainting an Object
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
More About Tainted Objects
You can find out more about tainted objects from the Locking Ruby in the Safe chapter of Programming Ruby.

Tim Abell
- 11,186
- 8
- 79
- 110

Todd A. Jacobs
- 81,402
- 15
- 141
- 199
-
1Perfect explanation! `+1` to you! but `How does the concept of tainted object make a Ruby script run in safe mode?` any suggestions on this question? – Arup Rakshit Jan 11 '13 at 15:36
-
2@PythonLikeYOU I updated the answer to reflect when you might want to untaint an object. By itself, (un)tainting doesn't do anything except change a flag on your object. It really only matters when you're concerned about the safety of your inputs (e.g. SQL injection or #eval methods), or when `$SAFE >= 1`. – Todd A. Jacobs Jan 11 '13 at 15:41
-
has my above asked question(in comment) also answered? I am just wandering in your post! – Arup Rakshit Jan 11 '13 at 16:05
-
What does `"safe" for certain operations` mean? which operations are being referred to here? – Wand Maker May 28 '16 at 10:20