HomebrewのCaskリポジトリを介した任意コード実行
A bug in the git_diff library used by Homebrew's automated PR review allowed a malicious pull request to be misclassified as a harmless change, enabling automatic merging of arbitrary Ruby code into the homebrew-cask repository. This could lead to arbitrary code execution on users' computers when they run brew commands that evaluate Cask files.
blog.ryotak.net
Published on blog.ryotak.net
2021-04-21 6267 字 Homebrew 脆弱性 Ruby Supply Chain
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.
## Context
Homebrew runs a vulnerability disclosure programme on HackerOne, and the programme's policy page accepts reports not only for the `brew` command itself but also for GitHub repositories matching `Homebrew/homebrew-*`. The author, who finds reading complex Ruby code difficult, chose to look at those repositories rather than the command.
{{media:0}}
The scope section of the programme is what pointed at the tap repositories.
{{media:1}}
The feature at the centre of the report is the automatic review and merge of pull requests against `Homebrew/homebrew-cask`. Two GitHub Actions workflows cooperate: `review.yml` inspects a submitted pull request and, if the change is very simple (a version bump, for example), approves it automatically; `automerge.yml` then merges approved pull requests automatically. The Ruby script behind `review.yml` fetches the change as a diff file and parses it with a Gem called [`git_diff`](https://github.com/anolson/git_diff).
{{media:2}}
{{media:3}}
## Setup
No accounts, roles or tool versions beyond the above are described. The work was done under the Homebrew disclosure programme on HackerOne, with the project's permission, and the report explicitly frames itself as authorised testing rather than an encouragement of unauthorised testing. The researcher's own machine had `brew` installed, which is what prompted looking at Homebrew in the first place.
## Finding it
The researcher started from the two vulnerability classes that are common in GitHub repositories:
1. Leakage of a token with write permission to the repository.
2. Vulnerabilities in the CI scripts the repository uses.
For the first, every repository owned by users belonging to the [Homebrew](https://github.com/Homebrew) organisation was collected and searched for strings that looked like tokens. Nothing valid turned up, which the author notes is the usual outcome of that approach. The report also mentions that Homebrew had already had an incident related to a leaked GitHub API token in 2018, so members were likely conscious of the risk.
For the second, the `.github/workflows/` directory of each repository was reviewed. In `Homebrew/homebrew-cask`, two files stood out: [`review.yml`](https://github.com/Homebrew/homebrew-cask/blob/[redacted]/.github/workflows/review.yml) and [`automerge.yml`](https://github.com/Homebrew/homebrew-cask/blob/[redacted]/.github/workflows/automerge.yml). Together they approve and then merge simple pull requests without human review.
### The approval conditions
The Ruby script used by `review.yml` (linked in the report as `Homebrew/actions`, `.github/workflows/review-cask-pr.yml`) approves a pull request only when all of the following hold:
1. Exactly one file is being changed.
2. No file is moved, created or deleted.
3. The changed file path matches `\ACasks/[^/]+\.rb\Z`.
4. The number of deleted lines equals the number of added lines.
5. Every deleted or added line matches either `/\A[+-]\s*version "([^"]+)"\Z/` or `\A[+-]\s*sha256 "[0-9a-f]{64}"\Z`.
6. If the version changes, its format stays the same (for example `1.2.3` to `2.3.4`).
The report notes that further conditions existed but were omitted as unimportant to the finding.
These conditions looked strict enough that the researcher initially concluded arbitrary code could not be inserted under them, and moved on to other scripts. The script would not leave his head, though, so he went back and started examining the library that parses the diff.
### The parser bug
While reading the [`git_diff`](https://github.com/anolson/git_diff) repository he found [an issue stating that the parsing of changed line counts was wrong](https://github.com/anolson/git_diff/issues/12). That prompted the idea of confusing `git_diff` so that a malicious change would satisfy the conditions above.
Reading the code showed that `git_diff` parses a diff file as follows:
1. Split the file contents on newlines.
2. For each line, check whether `^diff --git(?: a/(\S+))?(?: b/(\S+))?` matches. If it does, treat the line as file information and replace the file information currently being processed with what the regex captured.
3. If step 2 did not match, check the line against the regex below; if it matches, rewrite the source or destination file path according to the content.
{{media:4}}
4. If step 3 did not match, treat the line as a change to the file itself: a line starting with `+` is an addition, a line starting with `-` is a deletion, anything else is original file content.
5. Repeat until every line has been processed.
The flaw is that the check in step 3, which decides whether a line is a source or destination file path, can be triggered more than once. GitHub builds the diff for each changed file in the following structure and concatenates them into a single file:
```diff
diff --git a/変更前のファイルパス b/変更後のファイルパス
index 親コミットハッシュ..現コミットハッシュ ファイルモード
--- a/変更前のファイルパス
+++ b/変更後のファイルパス
@@ 行�
報 @@
以下変更詳細 (例: `+asdf`、`-zxcv`等)
```
An added line is represented by prefixing the added content with `+`. So any added line that matches `++ "?b/(.*)` is taken as a change of the file path being processed rather than as file content. Since the only path condition in the approval rules is `\ACasks/[^/]+\.rb\Z`, and the path can be rewritten several times, a change like the following could plausibly bypass the conditions and make the pull request look like a harmless zero-line change:
```ruby
++ "b/#{ここに任意のコード}"
++ b/Casks/cask.rb
```
The second line is deliberately not a string literal: because of the `git_diff` bug, the closing double quote would itself be treated as part of the file path.
## Exploitation
### Step 1: choosing a target Cask
Modifying a Cask that people actually use without permission would be inappropriate, so the researcher looked for a test Cask inside `homebrew-cask`. None existed. He emailed the person responsible for the Homebrew disclosure programme, and the reply was, in substance, that adding a test Cask just for this was unreasonable and that he should make a harmless change to an existing Cask instead.
He had seen, the day before, [a pull request that had accidentally included a GitHub API token](https://github.com/Homebrew/homebrew-cask/pull/104167), and that pull request had been modifying `iterm2.rb`, so he chose that Cask.
### Step 2: the first payload
While writing the change he noticed that `++ "b/"` is valid Ruby but `++ b/Casks/iterm2.rb` raises an error unless the variables are defined. He forked `Homebrew/homebrew-cask` and appended these two lines to `Casks/iterm2.rb`:
```ruby
++ "b/#{puts 'Going to report it - RyotaK (https://hackeorne.com/ryotak)';b = 1;Casks = 1;iterm2 = {};iterm2.define_singleton_method(:rb) do 1 end}"
++ b/Casks/iterm2.rb
```
The first line defines `b`, `Casks`, `iterm2` and `iterm2.rb` so that the second line does not raise, making the whole thing a valid Ruby script. GitHub then returns the following diff:
```diff
diff --git a/Casks/iterm2.rb b/Casks/iterm2.rb
index 3c376126bb1cf9..ba6f4299c1824e 100644
--- a/Casks/iterm2.rb
+++ b/Casks/iterm2.rb
@@ -8,6 +8,8 @@
sha256 "[redacted]"
end
+++ "b/#{puts 'Going to report it - RyotaK (https://hackeorne.com/ryotak)';b = 1;Casks = 1;iterm2 = {};iterm2.define_singleton_method(:rb) do 1 end}"
+++ b/Casks/iterm2.rb
url "https://iterm2.com/downloads/stable/iTerm2-#{version.dots_to_underscores}.zip"
name "iTerm2"
desc "Terminal emulator as alternative to Apple's Terminal app"
```
Because `git_diff` treats any line matching `+++ "?b/(.*)` as file information rather than an addition, this diff is read as a zero-line change to `Casks/iterm2.rb`. He opened [pull request 104191](https://github.com/Homebrew/homebrew-cask/pull/104191) with the change and began the demonstration.
### Step 3: Rubocop blocks the merge
The pull request was not merged. The CI log showed `Required status checks for pull request 104191 are not successful.` One of the failing checks runs `brew style`, which performs syntax checking, and the [Rubocop](https://github.com/rubocop/rubocop) run inside it objected to the code style.
{{media:5}}
Rubocop warnings on a specific line can be silenced with a `# rubocop:disable all` comment at the end of the line. That worked for the first line, but not for the second: the part of `+++ "?b/(.*)` captured by the group had to be exactly `Casks/iterm2.rb`, so a comment could not be appended there.
### Step 4: silencing Rubocop without touching the last line
After some trial and error he found a change that keeps the final line intact while satisfying Rubocop:
```ruby
++ "b/#{puts 'Going to report it - RyotaK (https://hackerone.com/ryotak)';b = 1;Casks = 1;iterm2 = {};iterm2.define_singleton_method(:rb) do 1 end; }"
++ "b/" if
++ b/Casks/iterm2.rb
```
Adding `if` on the second line makes the following line be evaluated as an `if` expression, which avoids the `Operator / used in void context.` warning. With this, every check on the pull request passed and `BrewTestBot` merged it.
{{media:6}}
### Step 5: confirming execution
With the pull request merged, he ran `brew install iterm2 --cask` and confirmed that `Going to report it - RyotaK (https://hackerone.com/ryotak)` was printed, then sent a screenshot as the proof of concept.
{{media:7}}
### Step 6: the payload ran more widely than expected
While waiting for a reply to the report, a reply arrived on Twitter. At first he did not understand it, but on closer inspection `Going to report it - RyotaK (https://hackerone.com/ryotak)` was also being printed when `brew cleanup` was run. He tried it locally and confirmed it.
Later investigation showed that the modified Cask was also executed by commands such as `brew search`. Some commands evaluate every Cask, so the modified code ran even on machines where the Cask was not installed. At the time of the change he had believed a Cask file is only executed by `brew install`, and, given that he was in contact with the maintainers and could revert quickly, had assumed no user would actually run the modified code.
The change only printed a log line and was reverted promptly, so the impact was limited, but the author states he had not anticipated this behaviour.
## Root cause
The bug is in `git_diff`'s diff parser. The regex that recognises a source or destination file path line can match repeatedly, so an added line whose content begins with `++ b/` (or `+++ "b/`) is interpreted as a new file path for the file currently being processed instead of as an added line. The approval logic in `review.yml` trusts the parser's view of which file is being changed and how many lines were added or deleted, so a pull request containing real added code can be presented to it as a zero-line change to a path matching `\ACasks/[^/]+\.rb\Z`. The path condition, the equal added/deleted line count and the per-line content regexes are all evaluated against the parser's output, so none of them catches the discrepancy. The report does not describe any defence that was in place.
## Impact
An attacker could get arbitrary Ruby code merged automatically into `Homebrew/homebrew-cask` and executed on the computers of Homebrew users. The author notes that, had the vulnerability been abused, every user who performed certain `brew` operations before discovery could have had their machine compromised. Execution was not limited to users who installed the affected Cask: commands such as `brew cleanup` and `brew search` evaluate Casks, so the code ran for users who had never installed it. In this demonstration the payload only printed a string and the change was reverted quickly.
## Fix
The report does not describe the fix that was applied. The timeline shows that the pull request was reverted about an hour after it was merged, that primary remediation was completed on 2021/04/18 at around 20:00 and secondary remediation on 2021/04/19, and that the incident was disclosed on 2021/04/21. The official incident disclosure is linked at the top of the report.
## Variants to test
- **Other consumers of `git_diff`.** Any tool that decides whether a diff is safe by parsing it with this Gem inherits the same confusion. A positive result is a diff in which an added line beginning with `++ b/` changes the parser's notion of the current file path.
- **Other diff parsers with repeated path matching.** Look for parsers that allow the `---`/`+++` path lines to be recognised more than once per file. A positive result is a crafted diff whose reported added/deleted line counts differ from what a human sees.
- **Auto-approval rules keyed on parsed paths and line counts.** Wherever a bot approves changes based on a parsed diff, try to make the parsed path match the allowlist while the real content differs. A positive result is an automatic approval of a pull request that contains code outside the permitted pattern.
- **CI style checks as the only remaining gate.** When a payload is blocked only by a linter, look for constructs that satisfy the linter without altering the line the parser depends on, as the `if` continuation did here. A positive result is a payload that passes every required status check.
- **Commands that evaluate all package definitions.** For package managers, check which commands load every formula or Cask rather than only the requested one. A positive result is code execution from a package the user never installed.
## Timeline
| Date (JST) | Event |
| --- | --- |
| 2021/04/17 | Vulnerability discovered |
| 2021/04/17 | Maintainers contacted |
| 2021/04/18 | Reply from maintainers received |
| 2021/04/18 around 17:00 | Demonstration started |
| 2021/04/18 around 17:00 | Report submitted |
| 2021/04/18 around 18:00 | Pull request successfully merged |
| 2021/04/18 around 19:00 | Pull request reverted |
| 2021/04/18 around 20:00 | Primary remediation completed |
| 2021/04/19 | Secondary remediation completed |
| 2021/04/21 | Incident disclosed |## What happened, in plain words
Homebrew is a package manager: a program that installs other programs on a Mac (and on Linux) for you. You type a command like `brew install iterm2` and Homebrew fetches the software, checks it, and puts it on your computer. The recipes that describe how to fetch and install each piece of software are kept in public repositories on GitHub, and anyone can propose a change to them by opening what GitHub calls a pull request.
Because those recipes are public and anyone can propose changes, the Homebrew project built automation: a bot reads each pull request, and if the change looks very simple and harmless (for example, only a version number was updated), the bot approves it and merges it without a human looking at it. That is convenient, and it is also a lot of trust to place in a bot.
The author of this report found a way to fool that bot. By crafting the change in a particular shape, he made the bot believe the pull request changed nothing at all, while in reality it added real Ruby code to a recipe. The bot approved it and merged it, and from then on the added code ran for users who performed certain `brew` operations. In the demonstration the code only printed a message, and the change was reverted about an hour later, but the same trick could have been used to run anything.
This article walks through how he found it, step by step, explaining each idea from scratch.
## Some background you need first
A few everyday concepts appear throughout, so here they are before we start.
- **A repository** is a folder of files whose entire history is tracked. GitHub hosts repositories, and anyone can read a public one.
- **A pull request** is a proposal to change files in a repository. You copy the repository (a *fork*), make your change in your copy, and ask the original project to pull your change in. The project can review it, discuss it, and then merge it or reject it.
- **A diff** is the format used to show what a pull request changes. It lists, file by file, which lines were removed (marked with a leading `-`) and which were added (marked with a leading `+`).
- **A bot** is a program that acts on GitHub automatically, for example by commenting, approving or merging.
- **GitHub Actions** is GitHub's built-in system for running such programs. The instructions for a bot live in a file under `.github/workflows/` in the repository, and each such file is called a workflow.
- **CI (continuous integration)** means running automatic checks on every proposed change: does the code compile, do the tests pass, is the style acceptable. If a check fails, GitHub marks the pull request as not ready to merge.
- **Ruby** is a programming language. Homebrew itself and its recipes are written in Ruby.
- **A Gem** is a reusable Ruby library, a package of code written by someone else that a program can load instead of writing everything itself.
- **A regular expression** (regex) is a pattern for matching text. `\ACasks/[^/]+\.rb\Z` is a regex that means: the text starts with `Casks/`, then has one or more characters that are not a slash, then ends with `.rb`. Regular expressions are used everywhere in this story, because the bot decides what a diff means by matching lines against patterns.
- **A token** is a secret string that acts like a password for a program. If someone obtains a GitHub token with write permission, they can change the repository as if they were its owner.
## Why Homebrew, and why these repositories
Homebrew runs a vulnerability disclosure programme on HackerOne. A disclosure programme is a public promise: "if you find a security problem in our software, report it to us here, and we will not take legal action against you for looking". HackerOne is the website that hosts such programmes. The report is explicit that the work described was done under that programme, with the project's permission, and that it is not an encouragement to test systems without permission.
{{media:0}}
One afternoon the author had a gap before his next appointment and looked for an interesting programme on HackerOne. He wanted to look at software he actually uses, so he browsed his own computer, noticed the `brew` command, and remembered seeing Homebrew on HackerOne.
The programme's policy page said reports were accepted not only for the `brew` command itself but also for GitHub repositories whose names match `Homebrew/homebrew-*`. Those repositories are the *taps*: collections of recipes. The author says he finds complex Ruby code hard to read, so he chose the repositories rather than the command itself.
{{media:1}}
The feature at the centre of the report is the automatic review and merge of pull requests against `Homebrew/homebrew-cask`, the repository that holds the recipes for graphical Mac applications (called Casks). Two workflows cooperate. `review.yml` inspects a submitted pull request and, if the change is very simple, such as a version bump, approves it automatically. `automerge.yml` then merges approved pull requests automatically. The Ruby script behind `review.yml` fetches the change as a diff file and parses it with a Gem called [`git_diff`](https://github.com/anolson/git_diff).
{{media:2}}
{{media:3}}
## How he looked for problems
He started from the two kinds of problem that are common in GitHub repositories:
1. A token with write permission to the repository leaks out.
2. The CI scripts the repository uses contain a vulnerability.
For the first, he collected every repository owned by users in the [Homebrew](https://github.com/Homebrew) organisation and searched them for strings that looked like tokens. Nothing valid turned up. He notes that this is the usual outcome of that approach. He also mentions that Homebrew had already had an incident in 2018 involving a leaked GitHub API token, so the members were probably conscious of the risk.
For the second, he read the `.github/workflows/` directory of each repository. In `Homebrew/homebrew-cask`, two files stood out: [`review.yml`](https://github.com/Homebrew/homebrew-cask/blob/[redacted]/.github/workflows/review.yml) and [`automerge.yml`](https://github.com/Homebrew/homebrew-cask/blob/[redacted]/.github/workflows/automerge.yml). Together they approve and then merge simple pull requests without a human looking at them.
### The conditions the bot checks
The Ruby script used by `review.yml` (linked in the report as `Homebrew/actions`, `.github/workflows/review-cask-pr.yml`) approves a pull request only when all of the following hold:
1. Exactly one file is being changed.
2. No file is moved, created or deleted.
3. The changed file path matches `\ACasks/[^/]+\.rb\Z`.
4. The number of deleted lines equals the number of added lines.
5. Every deleted or added line matches either `/\A[+-]\s*version "([^"]+)"\Z/` or `\A[+-]\s*sha256 "[0-9a-f]{64}"\Z`.
6. If the version changes, its format stays the same (for example `1.2.3` to `2.3.4`).
The report notes that further conditions existed but were left out as unimportant to the finding.
In plain words: the bot only trusts a change that touches one recipe file, does not add or remove files, removes exactly as many lines as it adds, and where every touched line is either a version line or a checksum line. A checksum is a long fingerprint of a downloaded file, used to confirm the file is the one expected.
These conditions looked strict enough that the author first concluded no arbitrary code could be inserted under them, and moved on to other scripts. The script would not leave his head, though, so he went back and started examining the library that parses the diff.
### The bug in the parser
While reading the [`git_diff`](https://github.com/anolson/git_diff) repository he found [an issue stating that the parsing of changed line counts was wrong](https://github.com/anolson/git_diff/issues/12). That gave him the idea of confusing `git_diff` so that a malicious change would satisfy the conditions above.
Reading the code showed that `git_diff` parses a diff file as follows:
1. Split the file contents on newlines.
2. For each line, check whether `^diff --git(?: a/(\S+))?(?: b/(\S+))?` matches. If it does, treat the line as file information and replace the file information currently being processed with what the regex captured.
3. If step 2 did not match, check the line against the regex below; if it matches, rewrite the source or destination file path according to the content.
{{media:4}}
4. If step 3 did not match, treat the line as a change to the file itself: a line starting with `+` is an addition, a line starting with `-` is a deletion, anything else is original file content.
5. Repeat until every line has been processed.
The flaw is that the check in step 3, which decides whether a line is a source or destination file path, can be triggered more than once.
GitHub builds the diff for each changed file in the following structure and concatenates them into a single file:
```diff
diff --git a/変更前のファイルパス b/変更後のファイルパス
index 親コミットハッシュ..現コミットハッシュ ファイルモード
--- a/変更前のファイルパス
+++ b/変更後のファイルパス
@@ 行�
報 @@
以下変更詳細 (例: `+asdf`、`-zxcv`等)
```
Line by line: the first line names the file before and after the change. The `index` line records the commit hashes and the file mode. The `---` line names the old path and the `+++` line names the new path. The `@@` line says where in the file the change sits. Everything after that is the actual change, where an added line is written with a leading `+` and a removed line with a leading `-`.
An added line is represented by prefixing the added content with `+`. So any added line that matches `++ "?b/(.*)` is taken as a change of the file path being processed rather than as file content. Since the only path condition in the approval rules is `\ACasks/[^/]+\.rb\Z`, and the path can be rewritten several times, a change like the following could plausibly bypass the conditions and make the pull request look like a harmless zero-line change:
```ruby
++ "b/#{ここに任意のコード}"
++ b/Casks/cask.rb
```
Line by line: the first line is an added line (the outer `+` is the diff marker) whose content begins with `+ "b/`, which the parser mistakes for a new file path. Inside the `#{...}` is where arbitrary code would go. The second line is another added line that resets the parser's idea of the current path to `Casks/cask.rb`, which satisfies the path condition. The second line is deliberately not a string literal: because of the `git_diff` bug, the closing double quote would itself be treated as part of the file path.
## Carrying out the demonstration
### Step 1: choosing a target Cask
Modifying a Cask that people actually use without permission would be inappropriate, so the author looked for a test Cask inside `homebrew-cask`. None existed. He emailed the person responsible for the Homebrew disclosure programme, and the reply was, in substance, that adding a test Cask just for this was unreasonable and that he should make a harmless change to an existing Cask instead.
He had seen, the day before, [a pull request that had accidentally included a GitHub API token](https://github.com/Homebrew/homebrew-cask/pull/104167), and that pull request had been modifying `iterm2.rb`, so he chose that Cask.
### Step 2: the first payload
While writing the change he noticed that `++ "b/"` is valid Ruby but `++ b/Casks/iterm2.rb` raises an error unless the variables are defined. In Ruby, `b/Casks/iterm2.rb` raises an error unless the variables are defined. He forked `Homebrew/homebrew-cask` and appended these two lines to `Casks/iterm2.rb`:
```ruby
++ "b/#{puts 'Going to report it - RyotaK (https://hackeorne.com/ryotak)';b = 1;Casks = 1;iterm2 = {};iterm2.define_singleton_method(:rb) do 1 end}"
++ b/Casks/iterm2.rb
```
Line by line: the first line is an added line whose content starts with `+ "b/`. Inside the string interpolation `#{...}` sits a small Ruby program: `puts` prints the message, then `b`, `Casks` and `iterm2` are defined so the next line does not raise, and `iterm2.define_singleton_method(:rb)` defines a method so that `iterm2.rb` on the next line is a valid call. The second line is the added line that resets the parser's current path to `Casks/iterm2.rb`.
GitHub then returns the following diff:
```diff
diff --git a/Casks/iterm2.rb b/Casks/iterm2.rb
index 3c376126bb1cf9..ba6f4299c1824e 100644
--- a/Casks/iterm2.rb
+++ b/Casks/iterm2.rb
@@ -8,6 +8,8 @@
sha256 "[redacted]"
end
+++ "b/#{puts 'Going to report it - RyotaK (https://hackeorne.com/ryotak)';b = 1;Casks = 1;iterm2 = {};iterm2.define_singleton_method(:rb) do 1 end}"
+++ b/Casks/iterm2.rb
url "https://iterm2.com/downloads/stable/iTerm2-#{version.dots_to_underscores}.zip"
name "iTerm2"
desc "Terminal emulator as alternative to Apple's Terminal app"
```
Line by line: the header says the file `Casks/iterm2.rb` is being changed. The `@@ -8,6 +8,8 @@` line says where in the file the change sits. The two lines starting with `+++` are the payload: the first is an added line whose content begins with `++ "b/`, the second is an added line whose content begins with `++ b/`. The remaining lines are ordinary context from the recipe.
Because `git_diff` treats any line matching `+++ "?b/(.*)` as file information rather than an addition, this diff is read as a zero-line change to `Casks/iterm2.rb`. He opened [pull request 104191](https://github.com/Homebrew/homebrew-cask/pull/104191) with the change and began the demonstration.
### Step 3: Rubocop blocks the merge
The pull request was not merged. The CI log showed `Required status checks for pull request 104191 are not successful.` One of the failing checks runs `brew style`, which performs syntax checking, and the [Rubocop](https://github.com/rubocop/rubocop) run inside it objected to the code style. Rubocop is a linter: a program that reads code and complains about formatting and style, not about whether the code works.
{{media:5}}
Rubocop warnings on a specific line can be silenced with a `# rubocop:disable all` comment at the end of the line. That worked for the first line, but not for the second: the part of `+++ "?b/(.*)` captured by the group had to be exactly `Casks/iterm2.rb`, so a comment could not be appended there. Appending anything would change the captured path and break the trick.
### Step 4: silencing Rubocop without touching the last line
After some trial and error he found a change that keeps the final line intact while satisfying Rubocop:
```ruby
++ "b/#{puts 'Going to report it - RyotaK (https://hackerone.com/ryotak)';b = 1;Casks = 1;iterm2 = {};iterm2.define_singleton_method(:rb) do 1 end; }"
++ "b/" if
++ b/Casks/iterm2.rb
```
Line by line: the first line is the same payload as before, with a semicolon and a space added before the closing brace. The second line adds `if`, which makes the following line be evaluated as an `if` expression. Adding `if` on the second line makes the following line be evaluated as an `if` expression, which avoids the `Operator / used in void context.` warning. The third line is unchanged and still resets the parser's path to `Casks/iterm2.rb`.
With this, every check on the pull request passed and `BrewTestBot` merged it.
{{media:6}}
### Step 5: confirming execution
With the pull request merged, he ran `brew install iterm2 --cask` and confirmed that `Going to report it - RyotaK (https://hackerone.com/ryotak)` was printed, then sent a screenshot as the proof of concept. A proof of concept is a demonstration that the problem is real, not theoretical.
{{media:7}}
### Step 6: the payload ran more widely than expected
While waiting for a reply to the report, a reply arrived on Twitter. At first he did not understand it, but on closer inspection `Going to report it - RyotaK (https://hackerone.com/ryotak)` was also being printed when `brew cleanup` was run. He tried it locally and confirmed it.
Later investigation showed that the modified Cask was also executed by commands such as `brew search`. Some commands evaluate every Cask, so the modified code ran even on machines where the Cask was not installed. At the time of the change he had believed a Cask file is only executed by `brew install`, and, given that he was in contact with the maintainers and could revert quickly, had assumed no user would actually run the modified code.
The change only printed a log line and was reverted promptly, so the impact was limited, but the author states he had not anticipated this behaviour.
## Why it worked
The bug is in `git_diff`'s diff parser. The regex that recognises a source or destination file path line can match repeatedly, so an added line whose content begins with `++ b/` (or `+++ "b/`) is interpreted as a new file path for the file currently being processed instead of as an added line. The approval logic in `review.yml` trusts the parser's view of which file is being changed and how many lines were added or deleted, so a pull request containing real added code can be presented to it as a zero-line change to a path matching `\ACasks/[^/]+\.rb\Z`. The path condition, the equal added/deleted line count and the per-line content regexes are all evaluated against the parser's output, so none of them catches the discrepancy. The report does not describe any defence that was in place.
## What the impact could have been
An attacker could get arbitrary Ruby code merged automatically into `Homebrew/homebrew-cask` and executed on the computers of Homebrew users. The author notes that, had the vulnerability been abused, every user who performed certain `brew` operations before discovery could have had their machine compromised. Execution was not limited to users who installed the affected Cask: commands such as `brew cleanup` and `brew search` evaluate Casks, so the code ran for users who had never installed it. In this demonstration the payload only printed a string and the change was reverted quickly.
## How it was fixed
The report does not describe the fix that was applied. The timeline shows that the pull request was reverted about an hour after it was merged, that primary remediation was completed on 2021/04/18 at around 20:00 and secondary remediation on 2021/04/19, and that the incident was disclosed on 2021/04/21. The official incident disclosure is linked at the top of the report.
## Things worth testing elsewhere
- **Other users of `git_diff`.** Any tool that decides whether a diff is safe by parsing it with this Gem inherits the same confusion. A positive result is a diff in which an added line beginning with `++ b/` changes the parser's notion of the current file path.
- **Other diff parsers that allow repeated path matching.** Look for parsers that allow the `---`/`+++` path lines to be recognised more than once per file. A positive result is a crafted diff whose reported added/deleted line counts differ from what a human sees.
- **Auto-approval rules based on parsed paths and line counts.** Wherever a bot approves changes based on a parsed diff, try to make the parsed path match the allowlist while the real content differs. A positive result is an automatic approval of a pull request that contains code outside the permitted pattern.
- **CI style checks as the only remaining gate.** When a payload is blocked only by a linter, look for constructs that satisfy the linter without altering the line the parser depends on, as the `if` continuation did here. A positive result is a payload that passes every required status check.
- **Commands that evaluate all package definitions.** For package managers, check which commands load every formula or Cask rather than only the requested one. A positive result is code execution from a package the user never installed.
## Timeline
| Date (JST) | Event |
| --- | --- |
| 2021/04/17 | Vulnerability discovered |
| 2021/04/17 | Maintainers contacted |
| 2021/04/18 | Reply from maintainers received |
| 2021/04/18 around 17:00 | Demonstration started |
| 2021/04/18 around 17:00 | Report submitted |
| 2021/04/18 around 18:00 | Pull request successfully merged |
| 2021/04/18 around 19:00 | Pull request reverted |
| 2021/04/18 around 20:00 | Primary remediation completed |
| 2021/04/19 | Secondary remediation completed |
| 2021/04/21 | Incident disclosed |
## Glossary
- **API**: an interface that lets one program talk to another. A GitHub API token is a secret string that lets a program act on GitHub on your behalf.
- **Bot**: a program that acts automatically on a service, here approving and merging pull requests.
- **Cask**: a Homebrew recipe describing how to install a graphical Mac application.
- **Checksum (sha256)**: a long fingerprint of a file, used to confirm the downloaded file is the expected one.
- **CI (continuous integration)**: automatic checks run on every proposed change.
- **Diff**: the text format that shows which lines a change adds and removes.
- **Disclosure programme**: a public promise that security problems reported through a given channel will be handled and not punished.
- **Fork**: your own copy of someone else's repository, where you can make changes before proposing them.
- **Gem**: a reusable Ruby library.
- **GitHub Actions**: GitHub's system for running automated workflows on repositories.
- **HackerOne**: a website that hosts vulnerability disclosure and bug bounty programmes.
- **Homebrew**: a package manager for macOS and Linux, driven by the `brew` command.
- **Linter**: a program that checks code for style and formatting problems.
- **Merge**: accept a pull request and apply its changes to the repository.
- **Package manager**: a program that installs, updates and removes other software for you.
- **Parser**: a program that reads structured text and turns it into data the program can work with.
- **Proof of concept (PoC)**: a demonstration that a problem is real.
- **Pull request**: a proposal to change files in a repository.
- **Regex (regular expression)**: a pattern for matching text.
- **Repository**: a folder of files whose history is tracked, hosted on a service such as GitHub.
- **Rubocop**: a linter for Ruby code.
- **Ruby**: the programming language Homebrew and its recipes are written in.
- **Tap**: a collection of Homebrew recipes kept in its own repository.
- **Token**: a secret string that acts like a password for a program.
- **Workflow**: a file under `.github/workflows/` that tells GitHub Actions what to run and when.