last day (15 days later) » 

4:08 PM
0
A: Eval a string without string interpolation

PhrogzYou can do this via regex by ensuring that there are an even number of backslashes before the character you want to escape: def safe_eval(str) eval str.gsub( /([^\\](?:\\\\)*)#(?=[{@$])/, '\1\#' ) end …which says: Find a character that is not a backslash [^\\] followed by two backslashes (...

 
But am I missing an attack vector for running arbitrary Ruby code?
 
@Phogrez: If you're running this on a server anywhere, say goodbye to your data. If this is just a local app, this is good enough.
 
@Linuxios "Maybe before we rush to adopt eval we should stop to consider the consequences of blithely giving this technology such a central position in our server"? Which is to say, "It sounds like you're giving good advice, but all you seem to actually be doing is fearmongering based on the presence of eval. Could you please provide a concrete attack vector that this does not guard against?"
 
@Phogrez: Agree with the XKCD, Let me think on this for a moment.
What's preventing someone from just puttong some Ruby code instead of a string? E.g.: some_str = 'system('rm -rf /')?
 
@Linuxios This string is being extracted by a parser and is thus guaranteed to be surrounded by double quotes. The parser also ensures that it can't be something like "foo" + evil_code + "bar".
 
4:08 PM
Alright. Here's something: What if the string equals (without your parsers quotes around it: str";puts 'Doing something bad';"return value of safe_eval? I run this, and the message prints.
 
Per my last comment, the parser won't pull such a thing out. There cannot be an unescaped " in the middle of the string.
 
@Phrogz: Looks like you're set then. I can't see a way to get around this, besides a bug in the parser.
Just curious, but why is eval necessary at all?
 
Great. Thanks for thinking about this.
 
Sure. (Not like I'm a penetration tester, but two minds is better than one)
 
I wouldn't say it's necessary. It's just convenient to turn \n into a real newline, \" into a real quote, \u2633 into a real unicode character.
 
4:11 PM
But that could be done with a little more peace of mind with some GSUBing that's a lot simpler than what you've done (I think).
 
A better answer to that question might be something that doesn't use eval() at all, but has a big replacement table of all known escape characters, and unicode escape sequences, etc.
 
Something like
 
Yup.
 
Hold on (goes to write Gist)
 
If you feel like writing up such an answer, I'll certainly +1 it :)
Might even accept it, if robust enough.
 
4:11 PM
Thanks.
 
4:51 PM
@Phrogz: Done. It works pretty well.
I also though I had your approach hacked for a minute there by using \u0022 in place of " in my old attack, but yours still held up.
 

last day (15 days later) »