Mortal and immortal symbols in Ruby
In this article, we’re going to explore the following topics:
- symbols are unique
- symbols since Ruby 2.2
- exploiting a security breach using symbols
Before to start
I’m thrilled to share with you our latest project: Fun Facts about Ruby — Volume 1
Please feel free to spread the word and share this post! 🙏
Fun Facts about Ruby - Volume 1
Fun Facts about Ruby - Volume 1 is a collection of cards..
Thank you for your time!
Symbols are unique
A symbol is a unique instance of the
Symbol class which is generally used for identifying a specific resource. A resource can be a method, a variable, a hash key, a state, etc..
A symbol is unique because only one instance of the
Symbol class can be created for a specific symbol in a running program
Here, we can see that the
:pending symbol is only created once as the two calls to
:pending.object_id return the same object identifier. Symbols are often compared to strings. But the main difference between them relies on the fact that a new
String object is created for each created string — even if they’re identical
Now that we’re more familiar with symbols, let’s have a look to the changes provided by Ruby 2.2.
Symbol since Ruby 2.2
Ruby 2.2 introduced the notion of mortal/immortal symbols. Let’s have a look to the differences between these 2 concepts.
Immortal symbols are symbols that’ll never be garbage collected. They’re created when your code is dynamically modified. For example:
- defining a new method using
- setting an instance variable using
- creating a constant or variable using
Mortal symbol on the other hand are eligible for garbage collection. They’re created in any other cases. For example:
- using symbol literals
Ok, now that we are more familiar with these 2 concepts, let’s see how immortal symbols can generate security issues.
Security breach using immortal symbols
It might not be a good idea to create immortal symbols from user inputs. Indeed, this would allow a malicious user to mount a DoS attack against your application by flooding it with unique strings, which will cause memory to grow indefinitely until the Ruby process is killed.
Indeed, as immortal symbols are not garbage collected, creating a huge amount of them can force your Ruby process to slow down.. or to be killed.
The notion of mortal symbol has been introduced in Ruby 2.2 to optimize the memory usage of Ruby programs. On the other hand, immortal symbols can generate security problems and you must use them in a completely safe environment. Avoid to use them when dealing with user interaction.
Thank you for taking the time to read this article.