From: dohzya Date: 2007-08-08T20:17:00+09:00 Subject: Re: non-constant strings ------=_Part_178_14927050.1186571824054 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi, 2007/8/7, Dmitry Bilunov : > > Hello. Why does Ruby have non-constant strings? It seems there is a way > to bypass object encapsulation paradigm and break object integrity. Here > is any example: > > class SecureRunner > # This class implements a sudo-like > # runner > > def initialize(command) > # Creates an instance. Guaranties, that a command is safe. > if command.safe? > @comamnd = command > else > raise RuntimeError, "Security check failed!" > end > end > > def run > # Only safe commands should be run > system(@command) > end > end > > # This class seems to be safe > # Here is a way to bypass security check: > > command = "some_safe_command" > runner = SecureRunner.new(command) > # a command is safe, so check will be passed > > command.replace("evil_command") # BYPASS THE CHECK > > runner.run # runs evil_command, that is not safe > > The same can be done to fields of instances, which are exported as > read-only (attr_reader). I know there is a way to fix it (using .clone > or .dup), but what is the reason Ruby has non-constant strings, as most > languages (Java, Python) do? Is there a way to disable such behaviour > ($SAFE will not help, because internal class methods will not be able to > change instance-variable strings too). > -- > Posted via http://www.ruby-forum.com/. > > You want to freeze the object @command, not the class String, don't you ? So you don't need to use an Immutable_String class, just add @command.freeze in your code -- Etienne Vallette d'Osia ------=_Part_178_14927050.1186571824054--