Skip to content
RCE Write-up Advanced

Not Your Stdout Bug - RCE in Cosmos SDK

Cosmovisor, a process manager for Cosmos SDK nodes, parsed upgrade instructions from stdout using a regex. An attacker could submit a governance parameter-change proposal containing a crafted string that matched the regex, causing Cosmovisor to download and execute an arbitrary binary (RCE) or, if downloads were disabled, crash the node (DoS).

Maxwell Dulin Follow

Published on maxwelldulin.com

Bounty$2,500 View original

Imagine, you're hunting for bugs in a project. You're reading through the documentation of a widely used framework with millions of dollars at stake.

Maxwell Dulin (@Dooflin5), on maxwelldulin.com

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. 10 min read.

Context

Cosmos SDK is a framework for building application-specific blockchains. Instead of deploying a trading platform as a smart contract on a general-purpose chain, a project builds its own chain that natively runs the required code, with control over low-level features such as gas costs and node settings. The SDK ships plug-and-play modules, for example a bank module for token ownership and a governance module for voting on changes to the chain. Inter-Blockchain Communication (IBC) is a central feature for talking to other Cosmos chains.

A node is an individual instance of a blockchain running in the network. Cosmovisor is a small process manager that wraps the node binary as a watchdog: it keeps track of logs, performs upgrades and helps start and sync additional nodes. The documentation that caught the author's eye described it as a process manager that "monitors stdout for incoming chain upgrade proposals", and that, when it sees an approved proposal, can automatically download the new binary, switch from the old binary to the new one and restart the node.

Upgrades themselves are a governance feature. A user proposes an update through the governance module, everyone votes, and at a specific block the chain is updated. If an approved proposal includes a chain update, the governance module outputs a string to stdout, and Cosmovisor downloads the new binary as specified by that stdout and restarts itself with it. The automatic download and upgrade keeps the chain current, but it would be horrifying if a single user could force an upgrade.

Cosmovisor is configured mostly through environment variables. Three matter here:

  • DAEMON_NAME: the name of the blockchain binary being executed.
  • DAEMON_ALLOW_DOWNLOAD_BINARIES: allow Cosmovisor to download the new application binary and replace the current one. Defaults to false, but many projects have instructions to turn it on.
  • DAEMON_RESTART_AFTER_UPGRADE: restart the application automatically after an upgrade. Defaults to true.

Setup

The work was a code review of the Cosmos SDK by Maxwell Dulin and Nathan Kirkland, followed by dynamic testing. No special accounts or roles were needed for the core bug: the code path is reachable from the Cosmos SDK CLI without special authorisation.

Testing progressed in three environments:

  1. The Cosmovisor test suite, which uses files as input for stdout and stderr. An existing upgrade test was copied and a file with the payload was created.
  2. A real Desmos node, chosen because the project has good documentation for creating a local testnet. The node used gov for the parameter change proposal.
  3. A Dockerised proof of concept that installs a Cosmos SDK chain (Cronos, Desmos or Osmosis), runs the node, and includes a bash script with the environment configured to run the exploit.

Finding it

While reviewing the Cosmos SDK, the documentation quoted above stood out: a watchdog that scans stdout to decide whether an update has occurred. If true, anyone who can write to stdout can make the process manager update the binary. The author notes that most such "obvious" issues turn into dead ends, but this one was real.

The upgrade regex

Nathan found the regex responsible for parsing upgrade information. Cosmovisor searched every line of both stdout and stderr with it.

Figure 2: Upgrade Regex

From the source and the test files, the parsed pieces are:

  1. Upgrade name, ".*": the name of the upgrade. Cosmovisor creates a folder for the new upgrade with this name.
  2. Upgrade height, (height)(\d+): the block number at which the chain should be updated. All systems need to update at the same time to keep the chain running smoothly.
  3. Upgrade information, (\S+)):\s+(\S*): upgrade JSON with fields that determine how the upgrade is performed. Two important fields are the target system (the architecture the binary is for, for example linux/amd64) and the link (an HTTP link to grab the binary from, which can include a SHA hash, for example https://maxwelldulin.com/hacker.sh).

First test against the project's own tests

The approach was to fail fast: find the fastest, laziest way to test a theory, because roughly 1 in 1000 big ideas works. Building a full Cosmos SDK chain with Cosmovisor would likely waste time. The tests are a shortcut: they contain happy-path examples and wrappers that isolate specific code without many external dependencies.

The test suite used files as input for stdout and stderr. Copying an existing upgrade test and creating a file with the payload worked: the injected string in the test file triggered the update.

Second test: a print sink in a real chain

To reproduce it in a real blockchain, the team set up a Desmos node, because functionality they had not fully understood might block the attack. Again failing fast, instead of hunting for a way to print an arbitrary string (a print sink), they compiled their own print statement into easy-to-hit functionality. The added code called the print statement and Cosmovisor saw the update and processed it. Seeing fmt.Println(...) perform the update is when the idea became reality.

Exploitation

Step 1: understand what the logger will let through

The Cosmos SDK uses the Tendermint logger, the logging component of the consensus and networking layer. It uses conditional logic to decide when to output to stdout or stderr depending on the verbosity setting, which the node operator specifies at startup. Modules call Error(), Info() (the default visibility) or Debug(), and the data is output according to the requested visibility.

The logging function takes a first parameter, a string describing the logs and the data to come, followed by optional key and value pairs. The output looks like LogString key1=value1, key2=value2.

Figure 3: Cosmos Logger Code and Output

The key=value part of the string is quote escaped: the logger turns " into \" whenever a double quote is output. That breaks the regex parsing above, and it is the reason the attack was stuck for a long time.

So the useful sinks are:

  • The beginning of the logging function: the initial string is not quote escaped, so a string placed in the first parameter is rendered properly.
  • fmt.Println(): the standard Go logging mechanism. Not every developer uses the SDK's logging mechanism.

Step 2: find the perfect sink

After a week, with the Cosmos SDK read four times each and various SDK-based projects downloaded, the team looked for sprintf() used in the beginning parameter of the logger. On the seventh night they found the param module:

Figure 4: Perfect Logger Sink in Params Module

The code proposes a new param change. The parameters can be an arbitrary key and an arbitrary value. The sink is the initial string of the logger and uses %s in a format string for sprintf(), which is not quote escaped, so double quotes can be placed inside and valid JSON produced. There is no input validation before this in the Cosmos SDK, so any string can be supplied for these values.

The code path is available in every blockchain using the Cosmos SDK, it uses .Info(), the default visibility, and it needs no special setup, circumstances or authorisation. A single function call from the Cosmos SDK CLI reaches it.

Step 3: craft the proposal

Depending on the SDK version, param is either its own module or under governance. The testing used Desmos, which uses gov. The parameter change proposal is a JSON file when used from the CLI, and the sink is within this proposal JSON. A valid example, with a placeholder for the attack data:

JSON
{
  "title": "TitleDK",
  "description": "DescDK",
  "changes": [
    {
      "key": "PwnMe",
      "value": "PAYLOAD HERE",
      "subspace": "bank"
    }
  ],
  "address": "desmos1jtu..."
}

The payload for the value field is shown in Figure 5. Because the string sits inside JSON, the payload needs to be quote escaped there (\" instead of ").

Figure 5: Injected Upgrade Payload

The goal is to match the upgrade regex perfectly within either the key or value proposal field. The fields in the payload are:

  • chain2: the chain upgrade name. It can be an arbitrary string but must match the regex.
  • linux/amd64: the architecture key for the binaries field. Testing was on Linux, but other systems can be used.
  • http://hacker.com/hacker.sh: the exploit code link. Cosmovisor reaches out to this URL to get the new binary to execute, which gives code execution.
  • A space: after the fake JSON blob a space is required, so the regex parsing stops before unintended characters in the logging output. Without it, testing failed because of a comma in the logs after the value.

Step 4: send the proposal

The CLI call that sends the proposal and hits the print sink on Desmos:

Bash
$ desmosd tx gov \
  submit-legacy-proposal param-change \
  proposal.json --from test_user

This executes the parameter change proposal from the CLI. The magic is in the crafted proposal.json, which contains the string that forces the upgrade.

Or watch on YouTube
Cosmos SDK RCE From the original on maxwelldulin.com

Figure 6: Exploit Video PoC

The video goes from executing the command to getting RCE on the box. A fully Dockerised proof of concept is available at mdulin2: it installs a Cosmos SDK chain (Cronos, Desmos or Osmosis), runs the node, and includes a bash script with the environment configured to run the exploit.

Root cause

Cosmovisor decided whether an upgrade had happened by pattern-matching stdout and stderr with a regex, rather than by reading a trusted, structured source. Any module that can write attacker-controlled text to the beginning of a log line, or to stdout through fmt.Println(), can therefore forge an upgrade instruction. The param module's proposal handler passed the user-supplied key and value into the first, non-quote-escaped parameter of the logger through sprintf(), with no validation, so a crafted value produced a line that matched the upgrade regex. The quote escaping applied to key=value pairs was the only obstacle, and the first parameter bypassed it.

Impact

With the remote download flag on, the vulnerability results in remote code execution. A compromised validator could have all its funds stolen. The worst case is a malicious actor compromising all nodes to force the network to perform malicious actions, such as token transfers to themselves.

With the remote download flag off, the vulnerability is a denial of service: when the update fails, the node does not reboot. Taking down a blockchain is catastrophic, leading to a lack of trust in the system and preventing users from performing actions.

The bug only existed in v0.1.0 of Cosmovisor, but it existed in the Cosmos SDK main branch until version 46.0, because the updated Cosmovisor was kept in a separate branch. Vulnerable parties are people still using v0.1.0, since there were no notices of security-related updates, and projects installing directly from the SDK, since many fork the main Cosmos-SDK and use a version prior to 46.0. The author calls this the Android Problem. It is impossible to know which version of Cosmovisor runs locally on a node, but the prevalence of forked, un-upgraded versions made this likely non-trivial and possibly affecting more chains than initially thought.

The bug had already been fixed in newer versions: a developer saw it as a potential issue and rewrote the tool to use files instead of stdout. The issue mentioned the attack as theoretically possible, but there was no mention of an exploit path and no urgency regarding upgrades.

Reporting

The Cosmos SDK has a bug bounty program on HackerOne. This bug was considered out of scope at the time; the program was later expanded to make these classes of vulnerabilities in scope. The team gave a $1250 bonus for the work, considering it was a bug in older versions and the scope of impact was unclear.

A second vulnerability was a simple role-based authorisation bug in the circuit module, reported separately, which paid $2K plus a $500 bonus for a good report. Overall the two bugs brought in 3.75K. The work ended with a disclosure on the Cosmos SDK forums.

Figure 7: Advisory from Cosmos

Fix

The fix was a rewrite of Cosmovisor to use files instead of stdout, made by a developer. The report does not describe the file-based mechanism in detail.

Variants to test

  • Other loggers with an unescaped first parameter: look for sprintf() or string concatenation feeding the initial string of a logging call, where user input reaches it. A positive result is a log line containing your double quotes unescaped, which lets you build valid JSON inside the log.
  • Direct fmt.Println() calls with user input: any module that prints user-controlled data directly to stdout. A positive result is your string appearing verbatim in the node output.
  • Other proposal types that echo user input: parameter changes, text proposals or metadata fields that end up in logs. A positive result is a proposal whose submitted value appears in stdout in a form that matches the upgrade regex.
  • Regex boundary handling: test whether a trailing space or delimiter is needed to stop the regex before the next log character, as a comma after the value broke the match here. A positive result is a payload that matches cleanly with and without surrounding log text.
  • Version and configuration checks: determine whether the target runs Cosmovisor v0.1.0 or an SDK fork before 46.0, and whether DAEMON_ALLOW_DOWNLOAD_BINARIES is enabled. A positive result is a node that downloads and executes a binary from a URL you control, or one that fails to restart after a forced upgrade.

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. 20 min read.

What happened, in plain words

A blockchain is a shared record book that many computers keep copies of, and those computers have to agree on what is written in it. Cosmos is a toolkit for building your own blockchain, and Cosmovisor is a small helper program that runs alongside one of those blockchain computers (called a node) and keeps it up to date. When the people who run the chain vote to change its software, Cosmovisor is supposed to notice, download the new version and restart the node with it.

The problem was how Cosmovisor noticed. It did not ask a trusted source; it simply read the text that the node printed on its screen (its "output") and looked for a particular pattern in that text. If the pattern appeared, Cosmovisor believed an upgrade had been approved and went off to download and run whatever program the text pointed at.

That means anyone who could get their own text printed on that screen could pretend to be an approved upgrade. Two researchers, Maxwell Dulin and Nathan Kirkland, found a place in the Cosmos software where an ordinary user could put text of their choosing into the node's output. By shaping that text to look exactly like an upgrade announcement, they could make Cosmovisor download and run a program from a web address they controlled. In plain terms: they could run their own code on someone else's blockchain computer. If the download feature was switched off, the same trick instead made the update fail and the node did not reboot, which takes the chain offline.

This is a beginner's walkthrough of how they found it, tested it and reported it. You do not need to know anything about blockchains to follow along; every term is explained where it first appears, and there is a glossary at the end.

Background

Cosmos SDK

Ethereum was the first big blockchain that let people run small programs (called smart contracts) on it. It has drawbacks, as the researchers describe them:

  • It is slow: around 14 transactions per second.
  • Running code on it costs money, paid as a fee called "gas".
  • Developers cannot customise how the blockchain itself works.
  • Different blockchains cannot easily talk to each other. Bridges exist, but they are clunky and prone to vulnerabilities.

The answer is to build something faster, cheaper and customisable, where blockchains can talk to each other. The Cosmos SDK is a framework (a set of ready-made building blocks) for making application-specific blockchains: a blockchain built for one particular project, so the developers control the details.

An everyday comparison: Ethereum is like a big shared office where anyone can rent a desk and run their business, but the building rules are fixed and the rent is high. Cosmos lets a project build its own small office block, with its own rules, its own rent and its own front door to the neighbours.

For instance, instead of running a trading platform as a smart contract on Ethereum, a project can create its own blockchain that natively runs all the code the trading platform needs. That lets the developer customise low-level features such as gas costs and node settings. The Cosmos SDK also has Inter-Blockchain Communication (IBC) as a central feature, which lets Cosmos blockchains talk to each other by default, for example to transfer funds.

Cosmos comes with modules that developers pick and choose from. A module is a packaged piece of functionality, like an app you install on a phone. Each one adds a capability, and the plug-and-play nature makes building a blockchain much faster. For example, there is a bank module for handling ownership of tokens and a governance module for voting on changes to the blockchain.

Cosmovisor

Figure 1: Cosmos Node Output

A node is one individual computer running a copy of the blockchain within the network. Cosmovisor manages the node as a watchdog program: it keeps track of the logs, performs upgrades and helps start and sync additional nodes. Figure 1 shows what a running node's output looks like.

When an upgrade is needed, a user proposes an update through the governance module, and everyone votes on it. If the proposal gets enough votes, then at a specific block (a point in time in the chain's history) the blockchain is updated with the new information. This is a general-purpose way to update the chain in a decentralised fashion, from fine-tuning settings to changing the chain's code itself.

If an approved proposal includes a chain update, the governance module prints a string to stdout. Cosmovisor downloads the new binary (the program file) named in that output and restarts itself using the new application. Automatic download and upgrade is great for keeping a blockchain current, but it would be horrifying if a single user could force an upgrade. Keep that thought.

Because Cosmovisor is a wrapper around the blockchain binary (a program that sits around another program and watches it), most of its settings are controlled with environment variables. An environment variable is a named setting that lives outside the program, a bit like a sticky note on the fridge that the program reads when it starts. Three matter here:

  • DAEMON_NAME: the name of the blockchain binary being executed.
  • DAEMON_ALLOW_DOWNLOAD_BINARIES: allow Cosmovisor to download the new application binary and replace the current one. It defaults to false, but many projects have instructions telling people to turn it on.
  • DAEMON_RESTART_AFTER_UPGRADE: restart the application automatically after an upgrade. It defaults to true.

Setup

The work was a code review of the Cosmos SDK by Maxwell Dulin and Nathan Kirkland, followed by hands-on testing. A code review means reading the program's source code line by line, looking for mistakes, rather than poking at a running system. No special accounts or roles were needed for the core bug: the code path can be reached from the Cosmos SDK command-line tool without any special permission.

Testing moved through three environments:

  1. The Cosmovisor test suite, which uses files as input for stdout and stderr. An existing upgrade test was copied and a file with the payload was created.
  2. A real Desmos node, chosen because the project has good documentation for creating a local testnet (a small private copy of the blockchain for experiments). The node used gov for the parameter change proposal.
  3. A Dockerised proof of concept that installs a Cosmos SDK chain (Cronos, Desmos or Osmosis), runs the node, and includes a bash script with the environment configured to run the exploit. Docker is a tool that packages a whole computer setup into a box you can run anywhere, so anyone can repeat the experiment.

Finding it

While reviewing the Cosmos SDK, the documentation quoted above stood out: a watchdog that scans stdout to decide whether an update has occurred. If that is true, anyone who can write to stdout can make the process manager update the binary. The author notes that most such "obvious" issues turn into dead ends, but this one was real.

The upgrade regex

Nathan found the regex responsible for parsing upgrade information. A regex (regular expression) is a pattern used to find text that has a particular shape, like a search rule that says "find something that looks like a date". Cosmovisor searched every line of both stdout and stderr with it. Stdout is the normal output channel of a program; stderr is the separate channel for error messages. Both end up in the logs.

Figure 2: Upgrade Regex

From the source and the test files, the parsed pieces are:

  1. Upgrade name, ".*": the name of the upgrade. Cosmovisor creates a folder for the new upgrade with this name.
  2. Upgrade height, (height)(\d+): the block number at which the chain should be updated. All systems need to update at the same time to keep the chain running smoothly.
  3. Upgrade information, (\S+)):\s+(\S*): upgrade JSON with fields that determine how the upgrade is performed. JSON is a text format for structured data, using curly brackets and quoted names, like a very strict shopping list. Two important fields are the target system (the architecture the binary is for, for example linux/amd64) and the link (an HTTP link to grab the binary from, which can include a SHA hash, for example https://maxwelldulin.com/hacker.sh). A SHA hash is a fingerprint of a file, used to check that the downloaded file is the right one.

First test against the project's own tests

The approach was to fail fast: find the fastest, laziest way to test a theory, because roughly 1 in 1000 big ideas works. Building a full Cosmos SDK chain with Cosmovisor would likely waste time. The tests are a shortcut: they contain happy-path examples (the normal, working case) and wrappers that isolate specific code without many external dependencies.

The test suite used files as input for stdout and stderr. Copying an existing upgrade test and creating a file with the payload worked: the injected string in the test file triggered the update. In other words, a text file standing in for the node's output was enough to trigger the update in the test suite.

Second test: a print sink in a real chain

To reproduce it in a real blockchain, the team set up a Desmos node, because functionality they had not fully understood might block the attack. Again failing fast, instead of hunting for a way to print an arbitrary string (a print sink), they compiled their own print statement into easy-to-hit functionality. A print sink is any place in a program where text you control ends up in the output. The added code called the print statement and Cosmovisor saw the update and processed it. Seeing fmt.Println(...) perform the update is when the idea became reality. fmt.Println(...) is the standard Go instruction for printing a line of text.

Exploitation

Step 1: understand what the logger will let through

The Cosmos SDK uses the Tendermint logger, the logging component of the consensus and networking layer. Consensus is the process by which the computers agree on the shared record; the networking layer is how they talk to each other. The logger uses conditional logic to decide when to output to stdout or stderr depending on the verbosity setting, which the node operator specifies at startup. Verbosity means how chatty the logs are. Modules call Error(), Info() (the default visibility) or Debug(), and the data is output according to the requested visibility. Think of three levels of announcement: errors always get printed, info is the normal level, and debug is the extra-detailed level you only switch on when investigating.

The logging function takes a first parameter, a string describing the logs and the data to come, followed by optional key and value pairs. The output looks like LogString key1=value1, key2=value2.

Figure 3: Cosmos Logger Code and Output

The key=value part of the string is quote escaped: the logger turns " into \" whenever a double quote is output. Quote escaping means putting a backslash in front of a special character so it is treated as ordinary text rather than as part of the format. That breaks the regex parsing above, and it is the reason the attack was stuck for a long time: the fake upgrade announcement needs double quotes to look like JSON, and the logger kept spoiling them.

So the useful sinks are:

  • The beginning of the logging function: the initial string is not quote escaped, so a string placed in the first parameter is rendered properly.
  • fmt.Println(): the standard Go logging mechanism. Not every developer uses the SDK's logging mechanism.

Step 2: find the perfect sink

After a week, with the Cosmos SDK read four times each and various SDK-based projects downloaded, the team looked for sprintf() used in the beginning parameter of the logger. sprintf() is a function that builds a string from a template, filling in placeholders with values, like a mail-merge letter. On the seventh night they found the param module:

Figure 4: Perfect Logger Sink in Params Module

The code proposes a new param change. A parameter is a setting of the blockchain, and this module lets users propose changing one. The parameters can be an arbitrary key and an arbitrary value. The sink is the initial string of the logger and uses %s in a format string for sprintf(), which is not quote escaped, so double quotes can be placed inside and valid JSON produced. %s is a placeholder that means "put a piece of text here". There is no input validation before this in the Cosmos SDK, so any string can be supplied for these values. Input validation means checking that what a user sends is sensible before using it; here there was none.

The code path is available in every blockchain using the Cosmos SDK, it uses .Info(), the default visibility, and it needs no special setup, circumstances or authorisation. A single function call from the Cosmos SDK CLI reaches it. CLI stands for command-line interface, the text-based way of giving a program instructions by typing commands.

Step 3: craft the proposal

Depending on the SDK version, param is either its own module or under governance. The testing used Desmos, which uses gov. The parameter change proposal is a JSON file when used from the CLI, and the sink is within this proposal JSON. A valid example, with a placeholder for the attack data:

JSON
{
  "title": "TitleDK",
  "description": "DescDK",
  "changes": [
    {
      "key": "PwnMe",
      "value": "PAYLOAD HERE",
      "subspace": "bank"
    }
  ],
  "address": "desmos1jtu..."
}

Line by line:

  • The outer curly brackets hold one JSON object, a bundle of named fields.
  • "title": "TitleDK" gives the proposal a title. The value is just a label here.
  • "description": "DescDK" is the longer explanation of the proposal.
  • "changes" is a list (the square brackets) of changes to make. Each entry in the list is itself a bundle in curly brackets.
  • "key": "PwnMe" is the name of the setting being changed. The researchers chose a name that makes it obvious this is a test.
  • "value": "PAYLOAD HERE" is where the attack text goes. This is the field that reaches the logger.
  • "subspace": "bank" says which module the setting belongs to; here, the bank module.
  • "address": "desmos1jtu..." is the address of the account submitting the proposal. The dots stand for the rest of the address, which is shortened here.

The payload for the value field is shown in Figure 5. Because the string sits inside JSON, the payload needs to be quote escaped there (\" instead of ").

Figure 5: Injected Upgrade Payload

The goal is to match the upgrade regex perfectly within either the key or value proposal field. The fields in the payload are:

  • chain2: the chain upgrade name. It can be an arbitrary string but must match the regex.
  • linux/amd64: the architecture key for the binaries field. Testing was on Linux, but other systems can be used. Architecture here means the kind of computer the program is built for.
  • http://hacker.com/hacker.sh: the exploit code link. Cosmovisor reaches out to this URL to get the new binary to execute, which gives code execution. A URL is a web address; the researchers used a domain they controlled, so the download would fetch their program.
  • A space: after the fake JSON blob a space is required, so the regex parsing stops before unintended characters in the logging output. Without it, testing failed because of a comma in the logs after the value. The logger adds a comma after the value, and the regex would otherwise swallow it and fail to match.

Step 4: send the proposal

The CLI call that sends the proposal and hits the print sink on Desmos:

Bash
$ desmosd tx gov \
  submit-legacy-proposal param-change \
  proposal.json --from test_user

Line by line:

  • $ is the prompt symbol, showing this is typed into a terminal. It is not part of the command.
  • desmosd is the name of the Desmos node program, the command-line tool for that blockchain.
  • tx means "transaction": send something to the chain.
  • gov selects the governance module, the part that handles proposals and votes.
  • submit-legacy-proposal is the command that submits a proposal in the older format.
  • param-change says the proposal is a parameter change.
  • proposal.json is the file crafted above, containing the attack text.
  • --from test_user says which account is sending it. test_user is a local test account.
  • The backslashes at the end of the first two lines simply mean "the command continues on the next line".

This executes the parameter change proposal from the CLI. The magic is in the crafted proposal.json, which contains the string that forces the upgrade.

Or watch on YouTube
Cosmos SDK RCE From the original on maxwelldulin.com

Figure 6: Exploit Video PoC

The video goes from executing the command to getting RCE on the box. RCE means remote code execution: someone else's program runs on your machine. A fully Dockerised proof of concept is available at mdulin2: it installs a Cosmos SDK chain (Cronos, Desmos or Osmosis), runs the node, and includes a bash script with the environment configured to run the exploit. A proof of concept is a small demonstration that the attack really works, and a bash script is a text file of commands that the computer runs in order.

Root cause

Cosmovisor decided whether an upgrade had happened by pattern-matching stdout and stderr with a regex, rather than by reading a trusted, structured source. Any module that can write attacker-controlled text to the beginning of a log line, or to stdout through fmt.Println(), can therefore forge an upgrade instruction. The param module's proposal handler passed the user-supplied key and value into the first, non-quote-escaped parameter of the logger through sprintf(), with no validation, so a crafted value produced a line that matched the upgrade regex. The quote escaping applied to key=value pairs was the only obstacle, and the first parameter bypassed it.

In everyday terms: the guard at the door was checking a handwritten note instead of an official pass, and the researchers found a way to write their own note.

Impact

With the remote download flag on, the vulnerability results in remote code execution. A compromised validator could have all its funds stolen. A validator is a node that takes part in agreeing on the blockchain's contents. The worst case is a malicious actor compromising all nodes to force the network to perform malicious actions, such as token transfers to themselves.

With the remote download flag off, the vulnerability is a denial of service: when the update fails, the node does not reboot. Denial of service means making a service unavailable to its users. Taking down a blockchain is catastrophic, leading to a lack of trust in the system and preventing users from performing actions.

The bug only existed in v0.1.0 of Cosmovisor, but it existed in the Cosmos SDK main branch until version 46.0, because the updated Cosmovisor was kept in a separate branch. A branch is a parallel copy of the code where changes are developed. Vulnerable parties are people still using v0.1.0, since there were no notices of security-related updates, and projects installing directly from the SDK, since many fork the main Cosmos-SDK and use a version prior to 46.0. A fork is a copy of a project that then develops on its own. The author calls this the Android Problem: many phones run old Android versions because manufacturers do not pass on updates, and the same happens with copied codebases.

It is impossible to know which version of Cosmovisor runs locally on a node, but the prevalence of forked, un-upgraded versions made this likely non-trivial and possibly affecting more chains than initially thought.

The bug had already been fixed in newer versions: a developer saw it as a potential issue and rewrote the tool to use files instead of stdout. The issue mentioned the attack as theoretically possible, but there was no mention of an exploit path and no urgency regarding upgrades.

Reporting

The Cosmos SDK has a bug bounty program on HackerOne. A bug bounty program is a scheme where a company pays researchers for reporting security problems responsibly instead of exploiting them. This bug was considered out of scope at the time, meaning the program's rules did not cover it; the program was later expanded to make these classes of vulnerabilities in scope. The team gave a $1250 bonus for the work, considering it was a bug in older versions and the scope of impact was unclear.

A second vulnerability was a simple role-based authorisation bug in the circuit module, reported separately, which paid $2K plus a $500 bonus for a good report. Role-based authorisation means deciding what someone may do based on their role; the bug let someone do something their role should not allow. Overall the two bugs brought in 3.75K. The work ended with a disclosure on the Cosmos SDK forums.

Figure 7: Advisory from Cosmos

Fix

The fix was a rewrite of Cosmovisor to use files instead of stdout, made by a developer. The report does not describe the file-based mechanism in detail.

Variants to test

If you want to look for similar bugs yourself, these are the directions the researchers suggest:

  • Other loggers with an unescaped first parameter: look for sprintf() or string concatenation feeding the initial string of a logging call, where user input reaches it. A positive result is a log line containing your double quotes unescaped, which lets you build valid JSON inside the log.
  • Direct fmt.Println() calls with user input: any module that prints user-controlled data directly to stdout. A positive result is your string appearing verbatim in the node output.
  • Other proposal types that echo user input: parameter changes, text proposals or metadata fields that end up in logs. A positive result is a proposal whose submitted value appears in stdout in a form that matches the upgrade regex.
  • Regex boundary handling: test whether a trailing space or delimiter is needed to stop the regex before the next log character, as a comma after the value broke the match here. A positive result is a payload that matches cleanly with and without surrounding log text.
  • Version and configuration checks: determine whether the target runs Cosmovisor v0.1.0 or an SDK fork before 46.0, and whether DAEMON_ALLOW_DOWNLOAD_BINARIES is enabled. A positive result is a node that downloads and executes a binary from a URL you control, or one that fails to restart after a forced upgrade.

Glossary

  • Application-specific blockchain: a blockchain built for one particular project, with its own rules and settings.
  • Architecture: the kind of computer a program is built for, such as linux/amd64.
  • Bash script: a text file of commands that a computer runs in order.
  • Binary: a program file that the computer can execute.
  • Block: a point in the blockchain's history where a batch of transactions is recorded.
  • Blockchain: a shared record book kept in agreement by many computers.
  • Branch: a parallel copy of a codebase where changes are developed.
  • Bug bounty program: a scheme that pays researchers for responsibly reporting security problems.
  • CLI (command-line interface): the text-based way of giving a program instructions by typing commands.
  • Code review: reading source code line by line to look for mistakes.
  • Consensus: the process by which computers agree on the shared record.
  • Cosmos SDK: a framework of building blocks for making custom blockchains.
  • Cosmovisor: a watchdog program that runs a blockchain node and performs upgrades.
  • Denial of service (DoS): making a service unavailable to its users.
  • Docker: a tool that packages a whole computer setup into a box that runs anywhere.
  • Environment variable: a named setting outside a program that the program reads at startup.
  • Fork: a copy of a project that then develops on its own.
  • Gas: a fee paid for running code on a blockchain.
  • Governance module: the part of a blockchain that handles proposals and votes.
  • Happy path: the normal, working case of a feature.
  • IBC (Inter-Blockchain Communication): a Cosmos feature that lets blockchains talk to each other.
  • Input validation: checking that user-supplied data is sensible before using it.
  • JSON: a text format for structured data using curly brackets and quoted names.
  • Logger: the part of a program that writes messages to the output.
  • Module: a packaged piece of functionality that can be added to a blockchain.
  • Node: one computer running a copy of the blockchain.
  • Out of scope: not covered by a bug bounty program's rules.
  • Parameter: a setting of the blockchain.
  • Print sink: any place in a program where text you control ends up in the output.
  • Proof of concept (PoC): a small demonstration that an attack really works.
  • Quote escaping: putting a backslash before a special character so it is treated as ordinary text.
  • RCE (remote code execution): running your own program on someone else's machine.
  • Regex (regular expression): a pattern used to find text of a particular shape.
  • Role-based authorisation: deciding what someone may do based on their role.
  • SHA hash: a fingerprint of a file, used to check it is the right one.
  • Smart contract: a small program that runs on a blockchain.
  • Stderr: the separate output channel a program uses for error messages.
  • Stdout: the normal output channel of a program.
  • Testnet: a small private copy of a blockchain used for experiments.
  • Transaction: an action sent to the blockchain, such as a transfer or a proposal.
  • URL: a web address.
  • Validator: a node that takes part in agreeing on the blockchain's contents and holds funds.
  • Verbosity: how chatty a program's logs are.
  • Vulnerability: a weakness in software that can be abused.

More by Maxwell Dulin

View all

1 more disclosed report, best first.

More from Cosmos

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.