Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid security issue in with `#{str}`

It is a convenient way to write code like this:

str = "John"
p "Welcome, #{str}"
# => "Welcome, John" 

In real Rails app, it is possible that str be intentionally written to terminate the current expression and start malicious code. How can I avoid using #{} in cases we do need to mix string with evaluated function values? e.g.: "Hello, #{foo(param)}".

like image 341
OneZero Avatar asked Jan 26 '26 22:01

OneZero


1 Answers

"#{str}" is safe with this caveat: the format itself must not be user-supplied. On the other hand, the value (the evaluation of str) being interpolated in is not of (eval) consequence.

So, to make this code unsafe is actually fairly hard:

fmt = "doBadStuff()"
eval('"Welcome #{' + fmt + '}"')

Of course, the resulting string (from the initial question) must be used correctly (e.g. database placeholders or quoted correctly for HTML) to avoid standard injection vulnerabilities; but the imagined vulnerability does not exist.

like image 115
user2246674 Avatar answered Jan 29 '26 11:01

user2246674



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!