From b0c3bfcf7ae95ac2c4e6df41204a7e5cd5d34bb0 Mon Sep 17 00:00:00 2001 From: Diptendu Kar Date: Thu, 19 Nov 2026 11:03:10 -0500 Subject: [PATCH 1/2] Add CVE-2026-132825 "Ruby2Shell" detection Host detectors for the seven Ruby interpreter advisories fixed in Ruby 4.0.10, 3.4.13 and 3.3.14 (2026-11-18): CVE-2026-132825, the string case-conversion heap overflow, and six siblings in case conversion and the regular expression engine. - linux/detect-ruby2shell.sh: reads the running interpreter's version from libruby, checks package backports, and reports CVE-2026-132825 as impacted when the application mounts Rack::MethodOverride (Rails unless api_only, classic Sinatra), enables Rodauth create_account, or has an affected encoding module loaded. Containers are read through /proc/PID/root. Only running Rubies decide the verdict; --count-installed counts idle ones. - windows/Detect-Ruby2Shell.ps1: the same decisions for Windows. - SSH, Ansible, DaemonSet, kubectl exec and PowerShell remoting wrappers. - Test harnesses and CI workflows (Ubuntu with Docker, host Ruby on Ubuntu and macOS, Windows). Co-Authored-By: Claude Mythos 5.2 --- .github/workflows/ruby2shell-linux.yml | 66 +++ .github/workflows/ruby2shell-windows.yml | 36 ++ CVE-2026-132825/README.md | 424 ++++++++++++++ CVE-2026-132825/linux/ansible-ruby2shell.yml | 89 +++ CVE-2026-132825/linux/detect-ruby2shell.sh | 551 ++++++++++++++++++ CVE-2026-132825/linux/k8s-exec-ruby2shell.sh | 62 ++ CVE-2026-132825/linux/k8s-ruby2shell.yaml | 76 +++ CVE-2026-132825/linux/ssh-ruby2shell.sh | 78 +++ CVE-2026-132825/linux/tests/run-tests-host.sh | 120 ++++ CVE-2026-132825/linux/tests/run-tests.sh | 182 ++++++ CVE-2026-132825/windows/Detect-Ruby2Shell.ps1 | 392 +++++++++++++ CVE-2026-132825/windows/remote-ruby2shell.ps1 | 86 +++ CVE-2026-132825/windows/tests/FakeRuby.cs | 38 ++ CVE-2026-132825/windows/tests/Run-Tests.ps1 | 138 +++++ README.md | 1 + 15 files changed, 2339 insertions(+) create mode 100644 .github/workflows/ruby2shell-linux.yml create mode 100644 .github/workflows/ruby2shell-windows.yml create mode 100644 CVE-2026-132825/README.md create mode 100644 CVE-2026-132825/linux/ansible-ruby2shell.yml create mode 100755 CVE-2026-132825/linux/detect-ruby2shell.sh create mode 100755 CVE-2026-132825/linux/k8s-exec-ruby2shell.sh create mode 100644 CVE-2026-132825/linux/k8s-ruby2shell.yaml create mode 100755 CVE-2026-132825/linux/ssh-ruby2shell.sh create mode 100755 CVE-2026-132825/linux/tests/run-tests-host.sh create mode 100755 CVE-2026-132825/linux/tests/run-tests.sh create mode 100644 CVE-2026-132825/windows/Detect-Ruby2Shell.ps1 create mode 100644 CVE-2026-132825/windows/remote-ruby2shell.ps1 create mode 100644 CVE-2026-132825/windows/tests/FakeRuby.cs create mode 100644 CVE-2026-132825/windows/tests/Run-Tests.ps1 diff --git a/.github/workflows/ruby2shell-linux.yml b/.github/workflows/ruby2shell-linux.yml new file mode 100644 index 0000000..a99931b --- /dev/null +++ b/.github/workflows/ruby2shell-linux.yml @@ -0,0 +1,66 @@ +name: ruby2shell bash detector (Linux) + +on: + push: + paths: + - "CVE-2026-132825/linux/**" + - ".github/workflows/ruby2shell-linux.yml" + pull_request: + paths: + - "CVE-2026-132825/linux/**" + - ".github/workflows/ruby2shell-linux.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + shellcheck: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: shellcheck + run: >- + shellcheck -S warning + CVE-2026-132825/linux/detect-ruby2shell.sh CVE-2026-132825/linux/tests/run-tests.sh + CVE-2026-132825/linux/tests/run-tests-host.sh + CVE-2026-132825/linux/ssh-ruby2shell.sh CVE-2026-132825/linux/k8s-exec-ruby2shell.sh + + test: + name: bash on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, ubuntu-22.04] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # The harness pulls the official ruby 3.4.12-slim and 3.4.13-slim images, + # pinned by digest inside run-tests.sh, and debian:stable-slim. + - name: Run tests (Docker) + run: bash ./CVE-2026-132825/linux/tests/run-tests.sh + + # Decision logic against the runner's own Ruby; skips itself if that + # Ruby is already patched. + - name: Run tests (host Ruby) + run: bash ./CVE-2026-132825/linux/tests/run-tests-host.sh + + # macOS ships bash 3.2 and an unpatched Ruby 2.6 in /usr/bin. This job is the + # only test of the detector's macOS process scan (ps and lsof instead of /proc). + test-macos: + name: bash 3.2 on macos-latest + runs-on: macos-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Run tests (host Ruby) + run: /bin/bash ./CVE-2026-132825/linux/tests/run-tests-host.sh diff --git a/.github/workflows/ruby2shell-windows.yml b/.github/workflows/ruby2shell-windows.yml new file mode 100644 index 0000000..8d36be0 --- /dev/null +++ b/.github/workflows/ruby2shell-windows.yml @@ -0,0 +1,36 @@ +name: ruby2shell PowerShell detector (Windows) + +on: + push: + paths: + - "CVE-2026-132825/windows/**" + - ".github/workflows/ruby2shell-windows.yml" + pull_request: + paths: + - "CVE-2026-132825/windows/**" + - ".github/workflows/ruby2shell-windows.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + name: ${{ matrix.shell }} on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + os: [windows-latest] + shell: [powershell.exe, pwsh.exe] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # Run-Tests.ps1 builds tests/FakeRuby.cs into ruby.exe stand-ins with the + # .NET Framework C# compiler; no Ruby is installed or needed. + - name: Run tests + shell: pwsh + run: ./CVE-2026-132825/windows/tests/Run-Tests.ps1 -Shell '${{ matrix.shell }}' diff --git a/CVE-2026-132825/README.md b/CVE-2026-132825/README.md new file mode 100644 index 0000000..0b675de --- /dev/null +++ b/CVE-2026-132825/README.md @@ -0,0 +1,424 @@ +# CVE-2026-132825 (Ruby2Shell) detection + +Fleet checks for the seven memory-safety bugs in the Ruby interpreter (CRuby) +that were fixed together in Ruby 4.0.10, 3.4.13 and 3.3.14 on 2026-11-18. +CVE-2026-132825, "Ruby2Shell", is a one-byte heap overflow in string case +conversion that stock Rails and classic-style Sinatra expose before +authentication. The other six have GHSA IDs only so far. + +| Advisory | Bug | Reached when the application | +|---|---|---| +| CVE-2026-132825 (GHSA-34m4-m9fh-gqp5) | One-byte heap overflow in string case conversion for 14 single-byte encodings | changes the case of an attacker-supplied string tagged with one of those encodings | +| GHSA-87fm-7w84-j2px | Integer overflow, then heap overflow, in string case conversion | changes the case of a multi-gigabyte string | +| GHSA-7x2q-68qv-6p8x | Double free in regular expression compilation | compiles a Regexp from attacker input | +| GHSA-3p8q-wmhx-vm2w | Heap overflow in regular expression compilation | compiles a very large Regexp from attacker input | +| GHSA-7whj-cfh7-xgm4 | Heap overflow in `Regexp#to_s` | calls `Regexp#to_s` or `Regexp.union` on, or interpolates, a Regexp built from attacker input | +| GHSA-wpqw-5qxg-m68r | Out-of-bounds read in case-insensitive matching | matches attacker text against a case-insensitive UTF-16/32 pattern, or lets the attacker supply the pattern | +| GHSA-pvgc-g7gj-pv6h | Out-of-bounds read in case-insensitive backreference matching | matches attacker text against a case-insensitive pattern that contains a backreference | + +These are interpreter bugs, not gem bugs. `bundle update` does not fix them, +`Gemfile.lock` does not show them, and dependency scanners do not report them. +The fix is a new Ruby, or a distribution package that backports it. + +**CVE-2026-132825.** In ISO-8859-1, -2, -3, -4, -9, -10, -13, -14, -15, -16 and +Windows-1250, -1252, -1254, -1257, upper-casing or case-folding `ß` (byte 0xDF) +writes two bytes where the loop checked room for one. With 21 or more of them, +one byte lands past the end of a heap buffer. `upcase`, `swapcase`, +`downcase(:fold)` and `casecmp?` reach it. `capitalize`, plain `downcase`, +`casecmp` and `/i` matching do not. UTF-8, US-ASCII and binary strings are not +affected. The Ruby advisory rates it Critical and states that proof-of-concept +exploits reach code execution in some scenarios. + +**Exposure in stock frameworks.** A multipart form part can declare its own +charset, and that tag survives into the application. Two default code paths +then change the case of such a value before authentication: + +- `Rack::MethodOverride` upper-cases the `_method` field of a POST. It runs + before routing and CSRF checks. Rails mounts it by default (not with + `config.api_only = true`), and so does classic-style Sinatra + (`require 'sinatra'`; not `Sinatra::Base` subclasses). +- Rodauth's `create_account` feature compares the login and login-confirm + fields with `casecmp?`. + +Both paths were confirmed at runtime: `Rack::MethodOverride` on Rails 8.1 and +7.2, Sinatra 4.2 and 3.2, Rack 3.2 and 2.2; Rodauth on 2.51.0. + +## Directory contents + +Scripts are grouped by where they run. The examples below are run from this +directory. + +`linux/` holds bash scripts for Linux and macOS hosts: the host detector and +the wrappers that run it across a fleet. + +| File | Purpose | +|---|---| +| `linux/detect-ruby2shell.sh` | Host detector (bash 3.2+; also runs under dash and busybox `sh`) | +| `linux/ansible-ruby2shell.yml` | Fleet run through Ansible | +| `linux/ssh-ruby2shell.sh` | Fleet run over plain SSH | +| `linux/k8s-ruby2shell.yaml` | Fleet run as a privileged Kubernetes DaemonSet | +| `linux/k8s-exec-ruby2shell.sh` | Fleet run with `kubectl exec` into each container | + +`windows/` holds PowerShell scripts for Windows (PowerShell 5.1 and 7). + +| File | Purpose | +|---|---| +| `windows/Detect-Ruby2Shell.ps1` | Host detector | +| `windows/remote-ruby2shell.ps1` | Fleet run over PowerShell remoting | + +The fleet wrappers find their detector next to themselves, so keep each +platform's files together. The `tests/` folders hold the maintainers' test +harnesses; they are not needed to run any script. + +## What counts as impacted + +Each Ruby gets a version check and a backport check, then one line per +advisory. A Ruby is impacted when it is unpatched and CVE-2026-132825 is +exposed. + +1. **version**: 4.0.0 to 4.0.9, 3.4.0 to 3.4.12, 3.3.0 to 3.3.13, and every + older release back to 2.4.0 are affected. + - 3.2 and older are end-of-life and receive no upstream fix; they are `[!]` + with "no upstream fix". + - Releases before 2.4.0 predate these bugs and are `OK`. + - Preview and development builds are `[?]`. + - JRuby and TruffleRuby are `OK`: they do not share the memory-corruption + bugs. The advisories' inputs were run against JRuby 10.1.3.0 and 9.4.15.0 + and TruffleRuby 40.0.0. Other engines are `[?]`. +2. **backport** (Linux): the package that owns the interpreter records no fix. + Distribution packages patch without changing the upstream version. + - **dpkg:** `/usr/share/doc//changelog.Debian.gz` is searched for the + CVE or GHSA ID. + - **rpm:** `rpm -q --changelog` on the host. An rpm-based container is `[?]`. + - **Alpine:** apk packages have no changelog on disk, so a vendor package + is `[?]`. + - **Judged on version alone:** interpreters no package owns. That covers + the official Docker `ruby` images, rbenv, RVM, asdf, mise and source + builds, Rubies bundled inside products, and all Windows builds. + + If the package on disk carries a fix but a process still runs the file it + replaced, the result is `[!]` with "restart it". +3. **CVE-2026-132825**: `[!]` when the Ruby is unpatched and any of these holds. + - The application mounts `Rack::MethodOverride`: a Rails application + without `config.api_only = true` and without + `middleware.delete Rack::MethodOverride`; a classic-style Sinatra + application without `disable :method_override`; or an explicit + `use Rack::MethodOverride`. + - The application enables Rodauth's `create_account` feature without + `require_login_confirmation? false` or `only_json? true`. + - The process has one of the 14 affected encoding modules loaded + (`enc/iso_8859_1.so` and the others). Ruby loads these on first use, so a + loaded module shows that the process has handled strings in an affected + encoding. It is not evidence of an attack, and its absence rules nothing + out. + + Otherwise the line is `[?]`. Application code may still change the case of + legacy-encoded input: see [Application code](#application-code). +4. **The six siblings** depend on application code that a host script cannot + read, so they are `[?]` on every unpatched Ruby. + +A running unpatched Ruby is therefore never `not impacted`: it is `impacted` +when CVE-2026-132825 is exposed and `unknown` otherwise. + +The detector reads the version from the `ruby X.Y.Z (` banner inside the +running process's own `libruby` (or `ruby`) file. A patched and an unpatched +Ruby return identical results for every input, and the fix leaves no marker in +the binary, so the bug itself is not probed. + +### Only running Rubies decide the verdict + +These bugs need a live process handling attacker input, and most hosts have +some idle Ruby on disk: macOS ships 2.6 in `/usr/bin`, version managers keep +old releases, and tools bundle their own. An unpatched interpreter that +nothing is running is listed with `=> not counted` and does not change the +exit code. Interpreters passed with `-r` (`-Ruby`) are always counted. + +Anything that is not running at the moment of the scan is not counted either. +That includes application servers that start workers on demand, cron jobs, +scheduled tasks and command-line scripts. `--count-installed` +(`-CountInstalled`) counts every unpatched interpreter on disk; such hosts +then come out `unknown`. + +## Output + +``` +Ruby check: CVE-2026-132825 (Ruby2Shell, string case conversion) and six sibling advisories fixed in Ruby 4.0.10 / 3.4.13 / 3.3.14 +legend: [!] impacted | OK not impacted | [?] could not check | n/a not checked +checks: version, backport, then per advisory. CVE-2026-132825 is [!] when the application mounts + Rack::MethodOverride (Rails unless api_only, classic Sinatra), enables Rodauth create_account, + or has an affected encoding module loaded. Only running Rubies (and -r paths) are counted. + The six siblings depend on application code, so they stay [?] on an unpatched Ruby. +host: Linux x86_64 + +/usr/local/bin/ruby (pid 4120, container web-6c9f7d8b5-x2x7q: puma 6.4.3 (tcp://0.0.0.0:3000) [app]) + version: ruby 3.4.12: affected, fixed in 3.4.13 [!] + backport: no package owns the interpreter, judged on version [!] + CVE-2026-132825 (GHSA-34m4-m9fh-gqp5): Rails 8.1.4 mounts Rack::MethodOverride by default, rack 3.2.8 (/app) [!] + GHSA-87fm-7w84-j2px: case conversion of multi-GB strings; depends on application code [?] + GHSA-7x2q-68qv-6p8x: Regexp compiled from untrusted input (double free); depends on application code [?] + GHSA-3p8q-wmhx-vm2w: Regexp compiled from untrusted input (size overflow); depends on application code [?] + GHSA-7whj-cfh7-xgm4: Regexp#to_s or Regexp.union on an untrusted pattern; depends on application code [?] + GHSA-wpqw-5qxg-m68r: case-insensitive UTF-16/32 pattern matched on untrusted text; depends on application code [?] + GHSA-pvgc-g7gj-pv6h: case-insensitive backreference matched on untrusted text; depends on application code [?] + => [!] impacted: CVE-2026-132825 + +/usr/bin/ruby3.3 (installed, not running) + version: ruby 3.3.13: affected, fixed in 3.3.14 [!] + backport: ruby3.3 3.3.13-0+deb13u1 (dpkg), changelog does not list CVE-2026-132825 [!] + => not counted: installed but not running (--count-installed to count it) + +note: 1 Ruby interpreter(s) installed but not running were listed and not counted. + They become exposed when something runs them; --count-installed counts them. + +impacted +``` + +Each Ruby is one block. Each check ends in `[!]` (points to impacted), `OK` +(rules this Ruby out), `[?]` (could not check) or `n/a` (not checked, because +an earlier check already ruled the Ruby out). The title line names the +interpreter and where it came from: + +- `pid N`: a running process, followed by its command line. +- `container `: the process runs in another container. In + Kubernetes the hostname is the pod name. +- `installed, not running`: an interpreter found on disk. +- `-r`: an interpreter passed on the command line. + +Worker processes that share an interpreter, working directory and container +are reported once. `-q` / `-Quiet` prints only the verdict line. + +## Exit codes + +| Code | Last line | Meaning | +|---|---|---| +| 0 | `not impacted` | every running Ruby is patched, or no Ruby is running | +| 1 | `impacted` | at least one running unpatched Ruby with CVE-2026-132825 exposed | +| 2 | `unknown` | at least one counted Ruby is unpatched or could not be evaluated, and none is impacted | +| 3 | (usage) | bad arguments (bash only) | + +`powershell.exe` also exits 1 when it rejects the arguments before the script +runs. Treat exit 1 as impacted only when the last line is `impacted`. + +## Usage + +```sh +sudo ./linux/detect-ruby2shell.sh # per-Ruby blocks, then the verdict +sudo ./linux/detect-ruby2shell.sh -q # verdict only +sudo ./linux/detect-ruby2shell.sh --no-disk # running processes only +sudo ./linux/detect-ruby2shell.sh --count-installed # idle unpatched Rubies count too +./linux/detect-ruby2shell.sh -r /opt/app/ruby/bin/ruby --no-procs +``` + +```powershell +powershell.exe -NoProfile -ExecutionPolicy Bypass -File windows\Detect-Ruby2Shell.ps1 -Quiet +.\windows\Detect-Ruby2Shell.ps1 -CountInstalled +.\windows\Detect-Ruby2Shell.ps1 -Ruby 'D:\apps\ruby\bin\ruby.exe' -NoProcesses +``` + +Run as root (elevated on Windows). Without it, other users' processes and +containers are missed. + +The detector is read-only. On Linux it reads `/proc` and package metadata, and +runs `ruby -e` only on interpreters found on disk, to print their engine and +version. Nothing is started inside a container. + +## Coverage + +| | bash (Linux) | bash (macOS) | PowerShell (Windows) | +|---|---|---|---| +| `ruby` on PATH and common install dirs (rbenv, RVM, asdf, mise, chruby, Homebrew) | yes | yes | yes (RubyInstaller, Chocolatey, Scoop) | +| Rubies bundled in products (`/opt/*/embedded`, GitLab, Puppet, Chef, Vagrant, Fluentd, Habitat) | yes | n/a | yes, common paths | +| Running Ruby processes and the application they serve | yes | yes, through `ps` and `lsof` | yes, when the command line holds an absolute path in the application | +| Processes in containers (Docker, containerd, Kubernetes pods) | yes, as root, through `/proc/PID/root` | no | no | +| Package backports: dpkg, rpm | yes (rpm on the host only) | n/a | n/a | +| Interpreter replaced on disk since the process started | detected, "restart it" | no | no | +| Affected encoding module loaded | yes | yes | yes | + +Not covered: + +- What the application code does. See [Application code](#application-code). +- Ruby processes that are not running during the scan. +- JRuby and TruffleRuby processes, which run as `java` or a native launcher. + Their installed interpreters are reported `OK`. +- Ruby inside WSL, from the Windows detector. Run the Linux detector there. +- An application whose root cannot be found from the process's working + directory (Linux, macOS) or from an absolute path on its command line + (Windows). A server started as `ruby bin/rails s` on Windows is not matched + to its application. Such a Ruby is `[?]`. +- Middleware added or removed by code the checks do not read, such as gems + and engines. The application check reads `config/application.rb`, + `config/environments/*.rb`, `config/initializers/*.rb`, `config.ru` and + top-level `*.rb`. For Sinatra and Rodauth it also searches four directory + levels down, skipping `vendor`, `node_modules`, `spec` and `test`. + +## Fleet runs + +Every wrapper runs this directory's own detector and nothing else. + +### Ansible + +`ansible-ruby2shell.yml` runs `detect-ruby2shell.sh` on every Linux/macOS host +in the inventory and collects each host's verdict on the control node. No +agent is installed; `ansible.builtin.script` copies the detector to a temp +path, runs it, and removes it. + +```sh +ansible-playbook -i inventory linux/ansible-ruby2shell.yml +ansible-playbook -i inventory linux/ansible-ruby2shell.yml -e detect_args="--no-disk" +``` + +Each host's full detector output is saved to `./results/.txt`, and a +per-verdict host list prints at the end. Exit codes `1` (impacted) and `2` +(unknown) are verdicts and do not fail the play; `3` (usage error) does. Run +with `become` (the default here) for full coverage. + +### SSH + +`ssh-ruby2shell.sh` runs the detector across Linux/macOS hosts with no Ansible +and nothing installed: `detect-ruby2shell.sh` is piped to each host's bash over +stdin and run there, so nothing is copied to or left on the target. + +```sh +sh linux/ssh-ruby2shell.sh hosts.txt results # one host or user@host per line +PARALLEL=20 sh linux/ssh-ruby2shell.sh hosts.txt +DETECT_ARGS="-q" sh linux/ssh-ruby2shell.sh hosts.txt # save just the verdict line +SUDO="" sh linux/ssh-ruby2shell.sh hosts.txt # run as the login user (less coverage) +``` + +Needs key-based SSH and, for full coverage, passwordless sudo and bash on the +targets. Each host's output goes to `results/.txt`; the per-host exit +code is the verdict (`0/1/2`, or `255`/other for an SSH failure). An impacted / +unknown / not impacted / error roll-up prints at the end, and the script exits +`1` if any host is impacted, else `2` if any unknown/error, else `0`. + +### Windows (PowerShell remoting) + +`remote-ruby2shell.ps1` runs `Detect-Ruby2Shell.ps1` on many Windows hosts over +PowerShell remoting. The detector's text is sent over the session and run in +memory; nothing is installed. + +```powershell +.\windows\remote-ruby2shell.ps1 -ComputerList hosts.txt -OutDir results +.\windows\remote-ruby2shell.ps1 -ComputerList hosts.txt -DetectArgs '-Quiet' +``` + +Needs WinRM enabled and a local-administrator account on the targets. Each +host's output is saved to `results\.txt`; the per-host verdict is the +detector's last output line. A roll-up prints at the end and the script exits +`1` / `2` / `0` as above. For Intune or Configuration Manager, deploy +`Detect-Ruby2Shell.ps1` directly as a detection script instead (exit `1` means +impacted when the last line says so). + +### Kubernetes + +Two methods, both running this directory's own detector. + +`k8s-ruby2shell.yaml` is a DaemonSet: one pod per node with `hostPID` and +`privileged`, so the detector checks every Ruby on the node, including those +in other pods. It reads their files through `/proc/PID/root`, so it needs no +`nsenter`, installs nothing at start, and copies nothing into workloads. The +detector is mounted from a ConfigMap: + +```sh +kubectl create namespace ruby2shell +kubectl -n ruby2shell create configmap detect --from-file=linux/detect-ruby2shell.sh +kubectl apply -f linux/k8s-ruby2shell.yaml +kubectl -n ruby2shell rollout status daemonset/ruby2shell +kubectl -n ruby2shell logs -l app=ruby2shell --tail=-1 --prefix --max-log-requests=500 +kubectl delete namespace ruby2shell +``` + +The pod is privileged by design. Review the manifest and delete the namespace +when you have your results. + +`k8s-exec-ruby2shell.sh` is for clusters that forbid privileged pods. It +`kubectl exec`s the detector (piped over stdin) into every running container +and needs only list and exec rights. It uses bash where the container has it +and plain `sh` otherwise. Containers with no shell at all (distroless) are +reported unknown; use the DaemonSet for those. + +```sh +sh linux/k8s-exec-ruby2shell.sh > results.txt # all namespaces +sh linux/k8s-exec-ruby2shell.sh -n web > results.txt # one namespace +``` + +## Application code + +The detector cannot read application code, so on an unpatched Ruby it leaves +these questions open. Each one is answered by reviewing the application. + +- **CVE-2026-132825 outside the framework paths.** Look for `upcase`, + `swapcase`, `downcase(:fold)` or `casecmp?` (including `map(&:upcase)`) + applied to strings a remote party controls and that can carry an affected + encoding: + - request parameters. Rails keeps the charset a multipart part declared for + every text parameter, API mode included. Sinatra keeps it for nested + parameters and upload filenames; + - HTTP client response bodies. open-uri, HTTParty, Faraday, RestClient and + http.rb tag the body with the server's `charset=`; + - Nokogiri HTML4/XML output (`to_s`, `to_html`, `to_xml`, `inner_html`), + which inherits the document's declared encoding; + - email parts the application re-tags with the sender's charset; + - database rows on a connection whose encoding is latin1, cp1252 or similar; + - CSV and other files read with `encoding: "ISO-8859-1"`. + + HTTP header values are binary and JSON bodies are UTF-8; neither reaches + the bug. +- **GHSA-7x2q-68qv-6p8x, GHSA-3p8q-wmhx-vm2w.** `Regexp.new`, + `Regexp.compile` or `/#{...}/` built from request data without + `Regexp.escape`. A Rails server running in development mode does this + itself at `/rails/info/routes` and `/rails/info/notes`. +- **GHSA-7whj-cfh7-xgm4.** `Regexp#to_s`, `Regexp.union` or interpolation of + a Regexp that was built from request data. +- **GHSA-pvgc-g7gj-pv6h.** Request data matched against a case-insensitive + pattern that contains a backreference (`\1`, `\k`). +- **GHSA-wpqw-5qxg-m68r.** Request data matched against a case-insensitive + UTF-16 or UTF-32 pattern. +- **GHSA-87fm-7w84-j2px.** Case conversion of strings larger than 2 GB. + +## Remediation + +1. **Upgrade Ruby** to 4.0.10, 3.4.13 or 3.3.14, or to the distribution's or + product vendor's fixed release. Rebuild container images on a fixed base. + Ruby 3.2 and older receive no fix: move to a supported series. +2. **Restart** every application server and background worker, then re-run + the detector. A process still running a replaced interpreter is reported + with "restart it". +3. **Until the upgrade, CVE-2026-132825 through the framework paths.** Ruby + publishes no workaround. The following close the two framework paths only; + they do not cover application code or the six siblings. + - Rails: `config.middleware.delete Rack::MethodOverride`. HTML forms that + send PUT, PATCH or DELETE through a hidden `_method` field stop working. + - Sinatra: `disable :method_override`. + - Rodauth: `require_login_confirmation? false`. + - Alternatively, reject multipart parts that declare a charset other than + UTF-8, in a Rack middleware at the very front of the stack or at the + reverse proxy or WAF. In classic-style Sinatra a middleware added with + `use` runs after `Rack::MethodOverride` and is too late. + + The Rails and Sinatra settings and the front-of-stack middleware were + tested against Rails 8.1 and 7.2 and Sinatra 4.2 and 3.2. The Rodauth + setting and a proxy rule were not. +4. **Self-hosted products** that bundle Ruby, such as GitLab, GitHub + Enterprise Server, Mastodon, Discourse, OpenProject and Chatwoot, need the + vendor's release with a fixed Ruby. Until then, restrict who can reach them. + +## Sources + +- Ruby security announcement, 2026-11-18: + +- Ruby advisory GHSA-34m4-m9fh-gqp5: + +- Upstream fix: ruby/ruby commit `d582f8f13d700d8e39714d3a8f11eb4bd2bc69f0`. +- Veria Labs write-up: +- Affected encodings and methods: the 14 `enc/*.c` files changed by the fix + and `rb_str_casemap` in `string.c` at `v3_4_12`, checked with valgrind on the + official `ruby:3.4.12` and `ruby:3.4.13` images. +- `Rack::MethodOverride`: `lib/rack/method_override.rb` in rack 3.2.8 and + 2.2.25, Rails `default_middleware_stack.rb`, Sinatra `base.rb`. +- Rodauth: `lib/rodauth/features/login_password_requirements_base.rb` in + rodauth 2.51.0. + +As of 2026-11-19, Debian, Ubuntu and SUSE had not shipped fixed packages. When +they do, the backport check picks them up with no script change, provided the +package changelog names the CVE or GHSA ID. diff --git a/CVE-2026-132825/linux/ansible-ruby2shell.yml b/CVE-2026-132825/linux/ansible-ruby2shell.yml new file mode 100644 index 0000000..abb829f --- /dev/null +++ b/CVE-2026-132825/linux/ansible-ruby2shell.yml @@ -0,0 +1,89 @@ +--- +# ansible-ruby2shell.yml +# +# Run the Ruby2Shell (CVE-2026-132825) host detector on every Linux/macOS host in the inventory +# and collect each host's verdict on the control node. +# +# Self-contained: it drives this repo's own detect-ruby2shell.sh and nothing +# else. No agent is installed on the targets. ansible.builtin.script copies the +# detector to a temp path, runs it, and removes it. The detector is read-only: +# it reads /proc and runs `ruby -e` only on installed interpreters; it changes nothing. +# +# Usage: +# ansible-playbook -i inventory ansible-ruby2shell.yml +# ansible-playbook -i inventory ansible-ruby2shell.yml -e detect_args="-q" +# ansible-playbook -i inventory ansible-ruby2shell.yml -e detect_args="--no-disk" +# +# Exit-code contract (from the detector; this is the fleet signal): +# 0 not impacted 1 impacted 2 unknown 3 usage error +# Codes 1 and 2 are verdicts, not failures, so they do not fail the play; 3 does. +# +# Output: +# - each host's full detector output is saved to ./results/.txt +# - a per-verdict host summary prints at the end +# +# Run as root (become) for full coverage of other users' processes and +# containers, matching the detector's own guidance. + +- name: Ruby2Shell (CVE-2026-132825) host detection + hosts: all + gather_facts: false + become: true + vars: + detect_script: "{{ playbook_dir }}/detect-ruby2shell.sh" + detect_args: "" + results_dir: "{{ playbook_dir }}/results" + + tasks: + - name: Run the detector (copied, run, and removed by Ansible; nothing installed) + ansible.builtin.script: "{{ detect_script }} {{ detect_args }}" + args: + executable: bash + register: detect + changed_when: false + failed_when: detect.rc not in [0, 1, 2] + + - name: Derive this host's verdict from the exit code + ansible.builtin.set_fact: + ruby2shell_verdict: "{{ 'impacted' if detect.rc == 1 else ('unknown' if detect.rc == 2 else 'not impacted') }}" + + - name: Create the results folder on the control node + ansible.builtin.file: + path: "{{ results_dir }}" + state: directory + mode: "0755" + delegate_to: localhost + become: false + run_once: true + + - name: Save this host's detector output on the control node + ansible.builtin.copy: + content: "{{ detect.stdout }}" + dest: "{{ results_dir }}/{{ inventory_hostname }}.txt" + mode: "0644" + delegate_to: localhost + become: false + changed_when: false + + - name: Print the fleet summary + run_once: true + delegate_to: localhost + become: false + vars: + # [host, verdict] pairs. Hosts that failed or were unreachable have no + # fact set, so extract yields Undefined, mapped to "no result". + pairs: >- + {{ ansible_play_hosts_all + | zip(ansible_play_hosts_all + | map('extract', hostvars, 'ruby2shell_verdict') + | map('default', 'no result') + | list) + | list }} + ansible.builtin.debug: + msg: + - "Ruby2Shell fleet detection (CVE-2026-132825 and six sibling Ruby advisories)" + - "impacted: {{ pairs | selectattr('1', 'equalto', 'impacted') | map(attribute='0') | list }}" + - "unknown: {{ pairs | selectattr('1', 'equalto', 'unknown') | map(attribute='0') | list }}" + - "not impacted: {{ pairs | selectattr('1', 'equalto', 'not impacted') | map(attribute='0') | list }}" + - "no result: {{ pairs | selectattr('1', 'equalto', 'no result') | map(attribute='0') | list }}" + - "per-host output saved under {{ results_dir }}/" diff --git a/CVE-2026-132825/linux/detect-ruby2shell.sh b/CVE-2026-132825/linux/detect-ruby2shell.sh new file mode 100755 index 0000000..783ed45 --- /dev/null +++ b/CVE-2026-132825/linux/detect-ruby2shell.sh @@ -0,0 +1,551 @@ +#!/usr/bin/env bash +# +# detect-ruby2shell.sh +# +# Checks whether this host runs a Ruby exposed to "Ruby2Shell" (CVE-2026-132825, +# GHSA-34m4-m9fh-gqp5) or to the six other memory-safety advisories fixed in the +# same releases (Ruby 4.0.10, 3.4.13 and 3.3.14, 2026-11-18). +# +# The bugs are in the Ruby interpreter (CRuby), not in gems, so the verdict +# rests on the interpreter: +# 1. version: 4.0.0-4.0.9, 3.4.0-3.4.12, 3.3.0-3.3.13 and every older release +# back to 2.4.0 are affected. 3.2 and older are end-of-life: no upstream fix. +# 2. backport: the package that owns the interpreter records no fix. +# 3. per advisory: +# - CVE-2026-132825 is reachable before authentication when the application +# mounts Rack::MethodOverride: Rails unless api_only, classic-style +# Sinatra, or a config.ru that uses it; or when it enables Rodauth's +# create_account feature with login confirmation. A process that has +# loaded one of the 14 affected encoding modules also counts. +# - The six siblings depend on what the application code does (for example +# compiling a regular expression from user input). A host script cannot +# see that, so they stay [?] on an unpatched Ruby. +# +# A patched and an unpatched Ruby give identical results for every input, and the +# fix leaves no marker in the binary, so nothing is probed: the script reads the +# version banner out of the running libruby (or ruby) file. +# +# What gets checked: +# - every running CRuby process, including those in containers (Linux, root, +# read through /proc/PID/root; nothing is started inside a container) +# - ruby on PATH and in common install and bundle directories +# - any ruby binary passed with -r +# +# Only RUNNING Rubies (and those passed with -r) decide the verdict. The bugs +# need a live process handling attacker input, and most hosts have some idle +# Ruby on disk (macOS ships 2.6 in /usr/bin), so an unpatched interpreter that +# nothing is running is listed as information and not counted. Blind spot: +# anything not running during the scan (app servers that start workers on +# demand, cron jobs, command-line scripts) is not counted either. Use +# --count-installed to count every unpatched interpreter on disk. +# +# Exit codes, for fleet tooling: +# 0 not impacted: every running Ruby is patched, or none is running +# 1 impacted: at least one unpatched Ruby with CVE-2026-132825 exposed +# 2 unknown: at least one unpatched or unreadable Ruby and none is impacted +# 3 usage error +# +# The last line of output is always exactly one of: +# impacted | not impacted | unknown +# +# Works with bash 3.2 (macOS) and later. Run as root for full coverage of other +# users' processes and containers. Read-only. + +set -u +set -f + +FIX_40=10; FIX_34=13; FIX_33=14 # 4.0.10 / 3.4.13 / 3.3.14 +CVE=CVE-2026-132825 +GHSA=GHSA-34m4-m9fh-gqp5 +SIBLINGS="GHSA-87fm-7w84-j2px:case conversion of multi-GB strings +GHSA-7x2q-68qv-6p8x:Regexp compiled from untrusted input (double free) +GHSA-3p8q-wmhx-vm2w:Regexp compiled from untrusted input (size overflow) +GHSA-7whj-cfh7-xgm4:Regexp#to_s or Regexp.union on an untrusted pattern +GHSA-wpqw-5qxg-m68r:case-insensitive UTF-16/32 pattern matched on untrusted text +GHSA-pvgc-g7gj-pv6h:case-insensitive backreference matched on untrusted text" +ENC_RE='enc/(iso_8859_(1|2|3|4|9|10|13|14|15|16)|windows_125(0|2|4|7))\.(so|bundle)' + +QUIET=0 +VERBOSE=0 +SCAN_PROCS=1 +SCAN_DISK=1 +STRICT=0 +COUNT_THIS=1 +EXTRA_RUBIES="" + +usage() { + cat <<'EOF' +usage: detect-ruby2shell.sh [-q] [-v] [-r /path/to/ruby]... [--no-procs] [--no-disk] + [--count-installed] + + -q, --quiet print only the verdict line + -v, --verbose print diagnostic detail + -r, --ruby PATH also check this ruby binary and count it (repeatable) + --no-procs skip running processes + --no-disk skip installed Rubies on disk + --count-installed let unpatched Rubies that are installed but not running + count toward the verdict (default: listed, not counted) + +Exit: 0 not impacted, 1 impacted, 2 unknown, 3 usage error. +EOF +} + +while [ $# -gt 0 ]; do + case "$1" in + -q|--quiet) QUIET=1 ;; + -v|--verbose) VERBOSE=1 ;; + -r|--ruby) + [ $# -ge 2 ] || { usage >&2; exit 3; } + EXTRA_RUBIES="$EXTRA_RUBIES$2 +" + shift ;; + --no-procs) SCAN_PROCS=0 ;; + --no-disk) SCAN_DISK=0 ;; + --count-installed) STRICT=1 ;; + -h|--help) usage; exit 0 ;; + *) echo "unknown argument: $1" >&2; usage >&2; exit 3 ;; + esac + shift +done + +N_IMPACTED=0 +N_UNKNOWN=0 +N_OK=0 +N_INFO=0 +SEEN="" + +say() { [ "$QUIET" -eq 1 ] || printf '%s\n' "$*"; } +dbg() { [ "$VERBOSE" -eq 1 ] && printf 'debug: %s\n' "$*" >&2; return 0; } +tally() { + case "$1" in + impacted) N_IMPACTED=$((N_IMPACTED + 1)) ;; + unknown) N_UNKNOWN=$((N_UNKNOWN + 1)) ;; + *) N_OK=$((N_OK + 1)) ;; + esac +} +mark() { + case "$1" in + impacted) echo "[!]" ;; + ok) echo "OK" ;; + unknown) echo "[?]" ;; + *) echo "n/a" ;; + esac +} + +# "X.Y.Z" out of the "ruby X.Y.Z (" banner in a libruby or ruby file, without +# running it. Ruby 3.1 and older append a patch level ("3.0.2p107"); drop it. +# Preview and dev builds ("4.1.0preview1", "3.5.0dev") keep their suffix. +banner_ver() { + LC_ALL=C tr -c ' -~' '\n' < "$1" 2>/dev/null | + LC_ALL=C grep -m 1 -oE '^ruby [0-9]+\.[0-9]+\.[0-9]+[a-z0-9]* \(' | + sed -e 's/^ruby //' -e 's/ ($//' -e 's/\([0-9]\)p[0-9][0-9]*$/\1/' +} + +# classify VERSION -> VER_STATE (ok|impacted|unknown) and VER_MSG +classify() { + v=$1 + VER_STATE=unknown; VER_MSG="version not recognised" + case "$v" in + ''|*[!0-9.a-z]*) return ;; + esac + maj=${v%%.*}; rest=${v#*.}; min=${rest%%.*}; pat=${rest#*.} + case "$pat" in *[!0-9]*) VER_MSG="preview or release candidate: not assessed"; return ;; esac + case "$maj.$min" in + 4.0) fix=$FIX_40 ;; + 3.4) fix=$FIX_34 ;; + 3.3) fix=$FIX_33 ;; + 3.2|3.1|3.0|2.7|2.6|2.5|2.4) + VER_STATE=impacted; VER_MSG="affected, end-of-life branch: no upstream fix"; return ;; + 2.3|2.2|2.1|2.0|1.*) + VER_STATE=ok; VER_MSG="older than 2.4.0: predates these bugs (end-of-life, upgrade anyway)"; return ;; + *) VER_MSG="newer branch than the releases checked on 2026-11-19"; return ;; + esac + if [ "$pat" -ge "$fix" ]; then + VER_STATE=ok; VER_MSG="fixed" + else + VER_STATE=impacted; VER_MSG="affected, fixed in $maj.$min.$fix" + fi +} + +# backport ROOT FILE -> BP_STATE, BP_MSG. ROOT is "" on the host or /proc/PID/root. +backport() { + root=$1; file=$2 + BP_STATE=impacted; BP_MSG="no package owns the interpreter, judged on version" + pkg="" + if [ -d "$root/var/lib/dpkg/info" ]; then + set +f + pkg=$(grep -lxF "$file" "$root"/var/lib/dpkg/info/*.list 2>/dev/null | head -n 1) + set -f + pkg=${pkg##*/}; pkg=${pkg%.list} + if [ -n "$pkg" ]; then + pver=$(awk -v P="${pkg%%:*}" '$1=="Package:"{p=$2} $1=="Version:"&&p==P{print $2; exit}' "$root/var/lib/dpkg/status" 2>/dev/null) + cl="$root/usr/share/doc/${pkg%%:*}/changelog.Debian.gz" + if [ -f "$cl" ] && gzip -dc "$cl" 2>/dev/null | grep -qE "$CVE|$GHSA"; then + BP_STATE=ok; BP_MSG="${pkg%%:*} $pver (dpkg), changelog lists $CVE" + elif [ -f "$cl" ]; then + BP_STATE=impacted; BP_MSG="${pkg%%:*} $pver (dpkg), changelog does not list $CVE" + else + BP_STATE=unknown; BP_MSG="${pkg%%:*} $pver (dpkg), no changelog on disk: check the distribution advisory" + fi + return + fi + fi + if [ -z "$root" ] && command -v rpm >/dev/null 2>&1; then + pkg=$(rpm -qf "$file" 2>/dev/null | grep -v 'not owned' | head -n 1) + if [ -n "$pkg" ]; then + if rpm -q --changelog "$pkg" 2>/dev/null | grep -qE "$CVE|$GHSA"; then + BP_STATE=ok; BP_MSG="$pkg (rpm), changelog lists $CVE" + else + BP_STATE=impacted; BP_MSG="$pkg (rpm), changelog does not list $CVE" + fi + return + fi + fi + if [ -f "$root/lib/apk/db/installed" ]; then + if awk -v F="${file#/}" '/^P:/{p=substr($0,3)} /^V:/{v=substr($0,3)} /^F:/{d=substr($0,3)} /^R:/{if (d"/"substr($0,3)==F){print p" "v; exit}}' "$root/lib/apk/db/installed" 2>/dev/null | grep -q .; then + pkg=$(awk -v F="${file#/}" '/^P:/{p=substr($0,3)} /^V:/{v=substr($0,3)} /^F:/{d=substr($0,3)} /^R:/{if (d"/"substr($0,3)==F){print p" "v; exit}}' "$root/lib/apk/db/installed" 2>/dev/null) + BP_STATE=unknown; BP_MSG="$pkg (apk): no changelog on disk, check secdb.alpinelinux.org" + return + fi + fi + if [ -n "$root" ] && [ -d "$root/var/lib/rpm" ]; then + BP_STATE=unknown; BP_MSG="rpm-based container: package changelog not read, judged on version" + fi +} + +# app_check ROOT DIR -> APP_STATE (impacted|unknown), APP_MSG. +# Looks for an application root at DIR (walking up to three levels) and decides +# whether Rack::MethodOverride is mounted. +app_check() { + root=$1; dir=$2 + APP_STATE=unknown; APP_MSG="no application found for this process; application code not analysed" + lock=""; d=$dir; i=0 + while [ $i -lt 4 ] && [ -n "$d" ]; do + if [ -f "$root$d/Gemfile.lock" ] || [ -f "$root$d/config.ru" ]; then lock=$d; break; fi + [ "$d" = "/" ] && break + d=${d%/*}; [ -n "$d" ] || d=/ + i=$((i + 1)) + done + [ -n "$lock" ] || return + app="$root$lock"; lf="$app/Gemfile.lock" + rails=""; sin=""; rack="" + if [ -f "$lf" ]; then + rails=$(sed -n 's/^ railties (\([0-9][^)]*\)).*/\1/p' "$lf" | head -n 1) + sin=$(sed -n 's/^ sinatra (\([0-9][^)]*\)).*/\1/p' "$lf" | head -n 1) + rack=$(sed -n 's/^ rack (\([0-9][^)]*\)).*/\1/p' "$lf" | head -n 1) + fi + set +f + cfg=$(cat "$app"/config/application.rb "$app"/config/environments/*.rb "$app"/config/initializers/*.rb 2>/dev/null) + top=$(cat "$app"/config.ru "$app"/*.rb 2>/dev/null) + set -f + where="$lock" + # `use X` and `middleware.use X` mount X. `insert_before A, X` mounts X; a line + # that only names Rack::MethodOverride as the anchor A does not. + if printf '%s\n%s\n' "$cfg" "$top" | grep -qE '^[^#]*middleware\.use[ (]+Rack::MethodOverride|^[^#]*middleware\.insert[_a-z]*[ (]+[^,#]+,[[:space:]]*Rack::MethodOverride|^[[:space:]]*use[ (]+Rack::MethodOverride'; then + APP_STATE=impacted; APP_MSG="Rack::MethodOverride is mounted explicitly ($where)"; return + fi + # A lockfile can list railties without the app being a Rails app. + [ -f "$app/config/application.rb" ] || rails="" + # Rodauth: create_account compares login and login-confirm with casecmp? before + # authentication, on raw request params (rodauth 2.51.0, confirmed at runtime). + rod="" + [ -f "$lf" ] && rod=$(sed -n 's/^ rodauth (\([0-9][^)]*\)).*/\1/p' "$lf" | head -n 1) + if [ -n "$rod" ]; then + rsrc=$(find "$app" -maxdepth 4 -name '*.rb' ! -path '*/vendor/*' ! -path '*/node_modules/*' \ + ! -path '*/spec/*' ! -path '*/test/*' 2>/dev/null | head -n 400 | + xargs grep -hE 'create_account|require_login_confirmation|only_json' 2>/dev/null) + if printf '%s\n' "$rsrc" | grep -qE '^[^#]*enable[ (].*:create_account' && + ! printf '%s\n' "$rsrc" | grep -qE '^[^#]*(require_login_confirmation\?[[:space:]]+false|only_json\?[[:space:]]+true)'; then + APP_STATE=impacted + APP_MSG="Rodauth $rod create_account compares login and login-confirm with casecmp? before authentication ($where)" + return + fi + fi + if [ -n "$rails" ]; then + if printf '%s\n' "$cfg" | grep -qE '^[^#]*middleware\.delete[ (]+Rack::MethodOverride'; then + APP_MSG="Rails $rails with Rack::MethodOverride deleted ($where); application code not analysed"; return + fi + if printf '%s\n' "$cfg" | grep -qE '^[^#]*config\.api_only[[:space:]]*=[[:space:]]*true'; then + APP_MSG="Rails $rails api_only, no Rack::MethodOverride ($where); application code not analysed"; return + fi + APP_STATE=impacted + APP_MSG="Rails $rails mounts Rack::MethodOverride by default, rack ${rack:-?} ($where)"; return + fi + if [ -n "$sin" ]; then + # The app file is not always at the top level: look a few levels down. + ssrc=$(find "$app" -maxdepth 4 \( -name '*.rb' -o -name 'config.ru' \) ! -path '*/vendor/*' \ + ! -path '*/node_modules/*' ! -path '*/spec/*' ! -path '*/test/*' 2>/dev/null | head -n 400 | + xargs grep -hE 'method_override|sinatra|Sinatra' 2>/dev/null) + if printf '%s\n' "$ssrc" | grep -qE '^[^#]*(disable[ (]+:method_override|set[ (]+:method_override,[[:space:]]*false)'; then + APP_MSG="Sinatra $sin with method_override disabled ($where); application code not analysed"; return + fi + if printf '%s\n' "$ssrc" | grep -qE '^[^#]*(enable[ (]+:method_override|set[ (]+:method_override,[[:space:]]*true)'; then + APP_STATE=impacted; APP_MSG="Sinatra $sin with method_override enabled, rack ${rack:-?} ($where)"; return + fi + if printf '%s\n' "$ssrc" | grep -qE "^[^#]*require[ (]+['\"]sinatra['\"]"; then + APP_STATE=impacted; APP_MSG="classic-style Sinatra $sin enables method_override by default, rack ${rack:-?} ($where)"; return + fi + if printf '%s\n' "$ssrc" | grep -qE 'Sinatra::Base|sinatra/base'; then + APP_MSG="modular Sinatra $sin, method_override off by default ($where); application code not analysed"; return + fi + APP_MSG="Sinatra $sin, style not determined ($where); application code not analysed"; return + fi + APP_MSG="Rack application without Rack::MethodOverride ($where); application code not analysed" +} + +not_counted() { + say " => not counted: installed but not running (--count-installed to count it)" + N_INFO=$((N_INFO + 1)) +} + +# report TITLE VERSION ROOT FILE CWD ENCMODS STALE (COUNT_THIS=0: list only) +report() { + title=$1; ver=$2; root=$3; file=$4; cwd=$5; encmods=$6; stale=$7 + say "" + say "$title" + if [ -z "$ver" ]; then + say " version: could not read the version banner [?]" + if [ "$COUNT_THIS" -eq 0 ]; then not_counted; return; fi + say " => [?] unknown" + tally unknown; return + fi + classify "$ver" + say " version: ruby $ver: $VER_MSG $(mark "$VER_STATE")" + if [ "$VER_STATE" = ok ]; then + say " backport: - n/a" + say " $CVE: - n/a" + say " => OK not impacted" + tally ok; return + fi + if [ "$VER_STATE" = unknown ]; then + if [ "$COUNT_THIS" -eq 0 ]; then not_counted; return; fi + say " => [?] unknown" + tally unknown; return + fi + backport "$root" "$file" + if [ "$COUNT_THIS" -eq 0 ] && [ "$BP_STATE" != ok ]; then + say " backport: $BP_MSG $(mark "$BP_STATE")" + not_counted; return + fi + [ -n "$stale" ] && [ "$BP_STATE" = ok ] && { BP_STATE=impacted; BP_MSG="$BP_MSG, but this process still runs the replaced file: restart it"; } + say " backport: $BP_MSG $(mark "$BP_STATE")" + if [ "$BP_STATE" = ok ]; then + say " $CVE: - n/a" + say " => OK not impacted" + tally ok; return + fi + [ -n "$stale" ] && say " note: the interpreter file was replaced on disk; this process runs the old code until restarted" + if [ -n "$cwd" ]; then app_check "$root" "$cwd"; else APP_STATE=unknown; APP_MSG="not running: no application to check"; fi + if [ -n "$encmods" ]; then + APP_STATE=impacted + APP_MSG="$APP_MSG; affected encoding module loaded: $encmods" + fi + say " $CVE ($GHSA): $APP_MSG $(mark "$APP_STATE")" + old=$IFS; IFS=' +' + for s in $SIBLINGS; do + say " ${s%%:*}: ${s#*:}; depends on application code [?]" + done + IFS=$old + if [ "$APP_STATE" = impacted ] && [ "$BP_STATE" = impacted ]; then + say " => [!] impacted: $CVE" + tally impacted + elif [ "$APP_STATE" = impacted ]; then + say " => [?] unknown: $CVE is exposed unless the package carries the fix (check the distribution advisory)" + tally unknown + else + say " => [?] unknown: unpatched Ruby, exposure depends on application code (see \"Application code\" in the README)" + tally unknown + fi +} + +say "Ruby check: $CVE (Ruby2Shell, string case conversion) and six sibling advisories fixed in Ruby 4.0.10 / 3.4.13 / 3.3.14" +say "legend: [!] impacted | OK not impacted | [?] could not check | n/a not checked" +say "checks: version, backport, then per advisory. $CVE is [!] when the application mounts" +say " Rack::MethodOverride (Rails unless api_only, classic Sinatra), enables Rodauth create_account," +say " or has an affected encoding module loaded. Only running Rubies (and -r paths) are counted." +say " The six siblings depend on application code, so they stay [?] on an unpatched Ruby." +say "host: $(uname -s 2>/dev/null) $(uname -m 2>/dev/null)" +[ "$(id -u 2>/dev/null)" = 0 ] || say "note: not running as root: other users' processes and containers may be missed" + +# ---- running processes (Linux) ---------------------------------------------------------- +if [ "$SCAN_PROCS" -eq 1 ] && [ -d /proc/self ]; then + selfmnt=$(readlink /proc/self/ns/mnt 2>/dev/null) + selfhost=$(head -n 1 /etc/hostname 2>/dev/null) + set +f + for d in /proc/[0-9]*; do + set -f + pid=${d#/proc/} + maps=$(cat "$d/maps" 2>/dev/null) || continue + [ -n "$maps" ] || continue + exe=$(readlink "$d/exe" 2>/dev/null) + libline=$(printf '%s\n' "$maps" | grep -m 1 -E '/[^ ]*libruby[^ /]*\.so') + lib=$(printf '%s\n' "$libline" | sed -n 's/^[^/]*\(\/.*\)$/\1/p') + base=${exe##*/}; base=${base% (deleted)} + case "$base" in ruby|ruby[0-9]*) isruby=1 ;; *) isruby=0 ;; esac + [ -n "$lib" ] || [ "$isruby" -eq 1 ] || continue + cwd=$(readlink "$d/cwd" 2>/dev/null) + key="$exe|$lib|$cwd|$(readlink "$d/ns/mnt" 2>/dev/null)" + case "$SEEN" in *" +$key +"*) continue ;; esac + SEEN="$SEEN +$key +" + stale="" + if [ -n "$lib" ]; then + file=${lib% (deleted)} + case "$lib" in *" (deleted)") stale=1 + range=${libline%% *} + src="$d/map_files/$range" ;; + *) src="$d/root$file" ;; + esac + else + file=${exe% (deleted)} + case "$exe" in *" (deleted)") stale=1 ;; esac + src="$d/exe" + fi + ver=$(banner_ver "$src") + [ -n "$ver" ] || ver=$(banner_ver "$d/exe") + encmods=$(printf '%s\n' "$maps" | grep -oE "$ENC_RE" | sort -u | tr '\n' ' ' | sed 's/ $//') + cmd=$(tr '\0' ' ' < "$d/cmdline" 2>/dev/null | cut -c1-60 | sed 's/ $//') + mnt=$(readlink "$d/ns/mnt" 2>/dev/null) + where="pid $pid" + root="" + if [ -n "$mnt" ] && [ "$mnt" != "$selfmnt" ]; then + # Another mount namespace: a container, or a sandboxed systemd service + # on this host. Read its files through /proc/PID/root either way, and + # call it a container only when its hostname differs from ours. + root="$d/root" + h=$(head -n 1 "$d/root/etc/hostname" 2>/dev/null) + [ -n "$h" ] && [ "$h" != "$selfhost" ] && where="$where, container $h" + else + SEEN="$SEEN +run|${exe% (deleted)} +" + fi + dbg "pid=$pid exe=$exe lib=$lib cwd=$cwd" + COUNT_THIS=1 + report "${exe% (deleted)} ($where: $cmd)" "$ver" "$root" "$file" "$cwd" "$encmods" "$stale" + set +f + done + set -f +elif [ "$SCAN_PROCS" -eq 1 ] && [ "$(uname -s 2>/dev/null)" = Darwin ]; then + # macOS has no /proc: list processes with ps, find the working directory and + # loaded encoding bundles with lsof, and ask the binary for its version. + plist=$(ps -axo pid=,comm= 2>/dev/null) + old=$IFS; IFS=' +' + for line in $plist; do + IFS=$old + line=${line#"${line%%[![:space:]]*}"} + pid=${line%% *}; exe=${line#* } + base=${exe##*/} + case "$base" in ruby|ruby[0-9]*) : ;; *) continue ;; esac + [ -x "$exe" ] || continue + lsout=$(lsof -a -p "$pid" -d cwd,txt -Fn 2>/dev/null) + cwd=$(printf '%s\n' "$lsout" | sed -n 's/^n//p' | head -n 1) + key="$exe|$cwd" + case "$SEEN" in *" +$key +"*) continue ;; esac + SEEN="$SEEN +$key +" + encmods=$(printf '%s\n' "$lsout" | grep -oE "$ENC_RE" | sort -u | tr '\n' ' ' | sed 's/ $//') + ver=$("$exe" -e 'print RUBY_VERSION if RUBY_ENGINE == "ruby"' 2>/dev/null) + cmd=$(ps -o command= -p "$pid" 2>/dev/null | cut -c1-60) + COUNT_THIS=1 + report "$exe (pid $pid: $cmd)" "$ver" "" "$exe" "$cwd" "$encmods" "" + done + IFS=$old +fi + +# ---- installed interpreters ------------------------------------------------------------- +check_disk() { + r=$1; how=$2 + [ -x "$r" ] && [ ! -d "$r" ] || return + real=$(readlink -f "$r" 2>/dev/null || echo "$r") + case "$SEEN" in *" +disk|$real +"*) return ;; esac + # already reported as a running process in this mount namespace + case "$SEEN" in *" +run|$real +"*) return ;; esac + SEEN="$SEEN +disk|$real +" + if [ "$how" = "-r" ]; then COUNT_THIS=1; else COUNT_THIS=$STRICT; how="installed, not running"; fi + desc=$("$r" -e 'print RUBY_ENGINE, " ", RUBY_VERSION, " ", (defined?(RUBY_ENGINE_VERSION) ? RUBY_ENGINE_VERSION : "")' 2>/dev/null) || desc="" + eng=${desc%% *} + if [ "$eng" = jruby ] || [ "$eng" = truffleruby ]; then + say "" + say "$real ($how)" + say " version: $desc: not CRuby; this engine does not share the memory-corruption bugs OK" + say " => OK not impacted (it has its own non-memory bugs for similar input: keep it updated)" + tally ok; return + fi + if [ -n "$desc" ] && [ "$eng" != ruby ]; then + say "" + say "$real ($how)" + say " version: $desc: not CRuby, these advisories do not name it [?]" + if [ "$COUNT_THIS" -eq 0 ]; then not_counted; return; fi + say " => [?] unknown" + tally unknown; return + fi + ver=$(printf '%s\n' "$desc" | awk '{print $2}') + lib=$("$r" -e 'c = RbConfig::CONFIG; f = File.join(c["libdir"], c["LIBRUBY_SO"].to_s); print(File.file?(f) ? File.realpath(f) : "")' 2>/dev/null) + report "$real ($how)" "$ver" "" "${lib:-$real}" "" "" "" +} + +# Paths given with -r go first, so the disk scan cannot list one as "not +# counted" before it is judged. +old=$IFS; IFS=' +' +for r in $EXTRA_RUBIES; do + IFS=$old + [ -n "$r" ] && check_disk "$r" "-r" +done +IFS=$old + +if [ "$SCAN_DISK" -eq 1 ]; then + p=$(command -v ruby 2>/dev/null) && check_disk "$p" installed + set +f + for g in /usr/bin/ruby /usr/bin/ruby[0-9]* /usr/local/bin/ruby /opt/rubies/*/bin/ruby \ + /usr/local/rvm/rubies/*/bin/ruby /home/*/.rvm/rubies/*/bin/ruby /root/.rvm/rubies/*/bin/ruby \ + /home/*/.rbenv/versions/*/bin/ruby /root/.rbenv/versions/*/bin/ruby /usr/local/rbenv/versions/*/bin/ruby \ + /home/*/.asdf/installs/ruby/*/bin/ruby /root/.asdf/installs/ruby/*/bin/ruby \ + /home/*/.local/share/mise/installs/ruby/*/bin/ruby /root/.local/share/mise/installs/ruby/*/bin/ruby \ + /Users/*/.rbenv/versions/*/bin/ruby /Users/*/.rvm/rubies/*/bin/ruby /Users/*/.asdf/installs/ruby/*/bin/ruby \ + /opt/*/embedded/bin/ruby /opt/*/*/embedded/bin/ruby /opt/puppetlabs/puppet/bin/ruby /opt/fluent/bin/ruby \ + /hab/pkgs/*/ruby*/*/*/bin/ruby /home/*/.rubies/*/bin/ruby /root/.rubies/*/bin/ruby /Users/*/.rubies/*/bin/ruby \ + /usr/local/Homebrew/Library/Homebrew/vendor/portable-ruby/*/bin/ruby \ + /opt/homebrew/Library/Homebrew/vendor/portable-ruby/*/bin/ruby \ + /home/linuxbrew/.linuxbrew/Homebrew/Library/Homebrew/vendor/portable-ruby/*/bin/ruby \ + /opt/td-agent/bin/ruby /opt/td-agent/embedded/bin/ruby /usr/local/Cellar/ruby*/*/bin/ruby \ + /opt/homebrew/opt/ruby*/bin/ruby /usr/local/opt/ruby*/bin/ruby; do + set -f + check_disk "$g" installed + set +f + done + set -f +fi + +if [ $((N_IMPACTED + N_UNKNOWN + N_OK + N_INFO)) -eq 0 ]; then + say "" + say "no Ruby interpreter found" +fi +if [ "$N_INFO" -gt 0 ]; then + say "" + say "note: $N_INFO Ruby interpreter(s) installed but not running were listed and not counted." + say " They become exposed when something runs them; --count-installed counts them." +fi +say "" +if [ "$N_IMPACTED" -gt 0 ]; then + echo "impacted"; exit 1 +elif [ "$N_UNKNOWN" -gt 0 ]; then + echo "unknown"; exit 2 +else + echo "not impacted"; exit 0 +fi diff --git a/CVE-2026-132825/linux/k8s-exec-ruby2shell.sh b/CVE-2026-132825/linux/k8s-exec-ruby2shell.sh new file mode 100755 index 0000000..a704436 --- /dev/null +++ b/CVE-2026-132825/linux/k8s-exec-ruby2shell.sh @@ -0,0 +1,62 @@ +#!/bin/sh +# k8s-exec-ruby2shell.sh -- kubectl exec the Ruby2Shell (CVE-2026-132825) detector into every +# running container. For clusters that forbid the privileged DaemonSet. +# +# Needs only the right to list pods and to exec into them. The detector is piped +# in over stdin and run in memory; nothing is copied into the container. It runs +# under bash, or under plain sh (dash, busybox) where there is no bash. Containers +# with no shell at all (distroless) are reported unknown -- use the DaemonSet +# (k8s-ruby2shell.yaml) for those. +# +# Usage: +# sh k8s-exec-ruby2shell.sh > results.txt # all namespaces +# sh k8s-exec-ruby2shell.sh -n web > results.txt # one namespace (any kubectl get pods opts) +# +# Prints a per-container block (the detector's output) and a roll-up. Exits 1 if +# any container is impacted, else 2 if any unknown, else 0. +set -u + +SCRIPT=${DETECT:-$(dirname "$0")/detect-ruby2shell.sh} +[ -f "$SCRIPT" ] || { echo "detector not found at $SCRIPT (set DETECT=/path/to/detect-ruby2shell.sh)" >&2; exit 3; } +[ $# -gt 0 ] || set -- -A + +NL=' +' +LIST=$(kubectl get pods "$@" --field-selector=status.phase=Running \ + -o go-template='{{range .items}}{{$ns := .metadata.namespace}}{{$pod := .metadata.name}}{{$node := .spec.nodeName}}{{range .spec.containers}}{{$ns}} {{$pod}} {{.name}} {{$node}}{{"\n"}}{{end}}{{end}}') || exit 3 + +imp=0; unk=0; ok=0 +IFS=$NL +for line in $LIST; do + IFS=' ' + # shellcheck disable=SC2086 + set -- $line + ns=$1; pod=$2; ctr=$3; node=$4 + printf '=== %s/%s/%s (node %s) ===\n' "$ns" "$pod" "$ctr" "$node" + shx="" + if kubectl exec -n "$ns" "$pod" -c "$ctr" -- sh -c 'command -v bash >/dev/null 2>&1' >/dev/null 2>&1; then + shx=bash + elif kubectl exec -n "$ns" "$pod" -c "$ctr" -- sh -c 'true' >/dev/null 2>&1; then + shx=sh + fi + if [ -n "$shx" ]; then + out=$(kubectl exec -i -n "$ns" "$pod" -c "$ctr" -- "$shx" -s -- -q < "$SCRIPT" 2>/dev/null) + printf '%s\n' "$out" + case "$(printf '%s\n' "$out" | tail -1)" in + impacted) imp=$((imp + 1)) ;; + "not impacted") ok=$((ok + 1)) ;; + *) unk=$((unk + 1)) ;; + esac + else + echo "unknown: no shell in this container; use the DaemonSet (k8s-ruby2shell.yaml)" + unk=$((unk + 1)) + fi + IFS=$NL +done +IFS=' ' + +echo "---" +echo "Ruby2Shell (CVE-2026-132825) containers: $imp impacted, $unk unknown, $ok not impacted" +[ "$imp" -gt 0 ] && exit 1 +[ "$unk" -gt 0 ] && exit 2 +exit 0 diff --git a/CVE-2026-132825/linux/k8s-ruby2shell.yaml b/CVE-2026-132825/linux/k8s-ruby2shell.yaml new file mode 100644 index 0000000..87d8c62 --- /dev/null +++ b/CVE-2026-132825/linux/k8s-ruby2shell.yaml @@ -0,0 +1,76 @@ +# k8s-ruby2shell.yaml -- check every running Ruby on every Linux node with one DaemonSet. +# +# One pod per node, with host process visibility (hostPID) and privileged, so the +# detector can read each container's interpreter and application files through +# /proc/PID/root. Nothing is started in, copied into, or changed in any workload +# pod. Self-contained: it runs this repo's own detect-ruby2shell.sh, mounted from a +# ConfigMap. +# +# The detector needs only bash and coreutils, which the base image here +# (debian:stable-slim) already has, so the pod needs no registry or apt access +# beyond pulling that image. The pod runs: detect-ruby2shell.sh --no-disk, so it +# reports the node's running Rubies (including those in other pods) and skips the +# detector pod's own empty filesystem. Add -q for the verdict line only. +# +# Run: +# kubectl create namespace ruby2shell +# kubectl -n ruby2shell create configmap detect --from-file=detect-ruby2shell.sh +# kubectl apply -f k8s-ruby2shell.yaml +# kubectl -n ruby2shell rollout status daemonset/ruby2shell +# kubectl -n ruby2shell logs -l app=ruby2shell --tail=-1 --prefix --max-log-requests=500 +# Remove: +# kubectl delete namespace ruby2shell +# +# Each instance block names the container (its hostname, which is the pod name in +# Kubernetes), so results can be mapped back to workloads. +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: ruby2shell + namespace: ruby2shell +spec: + selector: + matchLabels: + app: ruby2shell + template: + metadata: + labels: + app: ruby2shell + spec: + hostPID: true + nodeSelector: + kubernetes.io/os: linux + tolerations: + - operator: Exists + terminationGracePeriodSeconds: 1 + containers: + - name: detect + image: debian:stable-slim + securityContext: + privileged: true + env: + - name: NODE_NAME + valueFrom: + fieldRef: + fieldPath: spec.nodeName + command: ["/bin/sh", "-c"] + args: + - | + echo "=== node: ${NODE_NAME} ===" + bash /scripts/detect-ruby2shell.sh --no-disk || true + echo "=== end node: ${NODE_NAME} ===" + sleep infinity + resources: + requests: + cpu: 50m + memory: 64Mi + limits: + memory: 512Mi + volumeMounts: + - name: detect + mountPath: /scripts + readOnly: true + volumes: + - name: detect + configMap: + name: detect diff --git a/CVE-2026-132825/linux/ssh-ruby2shell.sh b/CVE-2026-132825/linux/ssh-ruby2shell.sh new file mode 100755 index 0000000..7874d39 --- /dev/null +++ b/CVE-2026-132825/linux/ssh-ruby2shell.sh @@ -0,0 +1,78 @@ +#!/bin/sh +# ssh-ruby2shell.sh -- run the Ruby2Shell (CVE-2026-132825) detector across Linux/macOS hosts over SSH. +# +# No agent, no install: detect-ruby2shell.sh is piped to each host's bash over +# stdin and run there, so nothing is copied to or left on the target. Read-only; +# the detector reads /proc and runs `ruby -e` only on installed interpreters. +# +# Usage: +# sh ssh-ruby2shell.sh hosts.txt [results_dir] # one host or user@host per line, # comments ok +# PARALLEL=20 sh ssh-ruby2shell.sh hosts.txt +# DETECT_ARGS="-q" sh ssh-ruby2shell.sh hosts.txt +# SUDO="" sh ssh-ruby2shell.sh hosts.txt # run as the login user (less coverage) +# +# Needs key-based SSH; for full coverage, passwordless sudo on the targets and +# bash present there (the detector requires bash). Each host's output goes to +# results_dir/.txt. The detector's exit code is the verdict (their contract): +# 0 not impacted 1 impacted 2 unknown 3 usage 255/other = SSH/transport error +# An impacted / unknown / not impacted / error roll-up prints at the end; this +# script exits 1 if any host is impacted, else 2 if any unknown/error, else 0. +set -u + +SCRIPT=${DETECT:-$(dirname "$0")/detect-ruby2shell.sh} +HOSTS=${1:?usage: ssh-ruby2shell.sh hosts.txt [results_dir]} +OUT=${2:-results} +PARALLEL=${PARALLEL:-10} +SUDO=${SUDO-sudo -n} +DETECT_ARGS=${DETECT_ARGS:-} + +[ -f "$SCRIPT" ] || { echo "detector not found at $SCRIPT (set DETECT=/path/to/detect-ruby2shell.sh)" >&2; exit 3; } +[ -f "$HOSTS" ] || { echo "hosts file not found: $HOSTS" >&2; exit 3; } +mkdir -p "$OUT" || exit 3 +rm -f "$OUT"/.status.* 2>/dev/null + +safe() { printf '%s' "$1" | tr -c 'A-Za-z0-9._@-' '_'; } + +one() { + h=$1 + s=$(safe "$h") + f="$OUT/$s.txt" + if ssh -o BatchMode=yes -o ConnectTimeout=15 "$h" "$SUDO bash -s -- $DETECT_ARGS" < "$SCRIPT" > "$f" 2>"$f.err"; then + rc=0 + else + rc=$? + fi + case "$rc" in + 0) v="not impacted" ;; + 1) v="impacted" ;; + 2) v="unknown" ;; + 3) v="error (usage)" ;; + 255) v="error (ssh/connection)" ;; + *) v="error (rc=$rc)" ;; + esac + printf '%s\t%s\n' "$v" "$h" > "$OUT/.status.$s" + [ -s "$f.err" ] || rm -f "$f.err" +} + +n=0 +while IFS= read -r h || [ -n "$h" ]; do + case "$h" in ''|\#*) continue ;; esac + one "$h" & + n=$((n + 1)) + [ $((n % PARALLEL)) -eq 0 ] && wait +done < "$HOSTS" +wait + +cat "$OUT"/.status.* 2>/dev/null > "$OUT/.all" || true +echo "Ruby2Shell (CVE-2026-132825) fleet detection ($n host(s))" +for v in impacted unknown "not impacted"; do + hs=$(awk -F'\t' -v V="$v" '$1==V{print $2}' "$OUT/.all" 2>/dev/null | sort | tr '\n' ' ') + printf ' %-13s %s\n' "$v:" "${hs:-(none)}" +done +errs=$(awk -F'\t' '$1 ~ /^error/{printf "%s(%s) ", $2, $1}' "$OUT/.all" 2>/dev/null) +[ -n "$errs" ] && printf ' %-13s %s\n' "error:" "$errs" +echo "per-host output in $OUT/" + +if awk -F'\t' '$1=="impacted"{f=1} END{exit !f}' "$OUT/.all" 2>/dev/null; then exit 1; fi +if awk -F'\t' '$1=="unknown" || $1 ~ /^error/{f=1} END{exit !f}' "$OUT/.all" 2>/dev/null; then exit 2; fi +exit 0 diff --git a/CVE-2026-132825/linux/tests/run-tests-host.sh b/CVE-2026-132825/linux/tests/run-tests-host.sh new file mode 100755 index 0000000..0ea8530 --- /dev/null +++ b/CVE-2026-132825/linux/tests/run-tests-host.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash +# +# Decision-logic tests for detect-ruby2shell.sh that need no Docker: they use an +# unpatched Ruby already on this host (Linux or macOS, bash 3.2+, no root). +# +# Each case starts an idle `ruby -e sleep` in a small application directory +# built here and checks the detector's exit code and output. No request is sent +# and no vulnerable input is used. +# +# The host Ruby must be unpatched for the expectations to hold. /usr/bin/ruby is +# tried first (macOS ships 2.6 there, distributions ship their own), then ruby +# on PATH. If neither is unpatched the tests are skipped with exit 0. +# +# usage: run-tests-host.sh + +set -u + +HERE=$(cd "$(dirname "$0")" && pwd) +DET="$HERE/../detect-ruby2shell.sh" + +RUBY="" +for c in /usr/bin/ruby "$(command -v ruby 2>/dev/null)"; do + [ -n "$c" ] && [ -x "$c" ] || continue + bash "$DET" -q --no-procs --no-disk -r "$c" >/dev/null 2>&1 + if [ $? -eq 2 ]; then RUBY=$c; break; fi +done +if [ -z "$RUBY" ]; then + echo "skipped: no unpatched Ruby on this host to test against" + exit 0 +fi +echo "ruby: $RUBY: $("$RUBY" -e 'print RUBY_DESCRIPTION')" + +W=$(mktemp -d "${TMPDIR:-/tmp}/ruby2shell-host.XXXXXX") +PID="" +cleanup() { [ -n "$PID" ] && kill "$PID" 2>/dev/null; rm -rf "$W"; } +trap cleanup EXIT + +lock() { # DIR GEM VERSION [GEM VERSION]... + d="$W/$1"; shift; mkdir -p "$d" + { echo "GEM"; echo " specs:"; while [ $# -gt 1 ]; do echo " $1 ($2)"; shift 2; done; } > "$d/Gemfile.lock" +} +railscfg() { # DIR EXTRA_LINES + mkdir -p "$W/$1/config/initializers" + printf 'module App\n class Application < Rails::Application\n%b end\nend\n' "$2" > "$W/$1/config/application.rb" +} + +lock rails rack 3.2.8 railties 8.1.4; railscfg rails "" +lock rails-api rack 3.2.8 railties 8.1.4; railscfg rails-api " config.api_only = true\n" +lock rails-api-guard rack 3.2.8 railties 8.1.4; railscfg rails-api-guard " config.api_only = true\n" +printf 'Rails.application.config.middleware.insert_before Rack::MethodOverride, CharsetGuard\n' > "$W/rails-api-guard/config/initializers/guard.rb" +lock rails-api-readd rack 3.2.8 railties 8.1.4 +railscfg rails-api-readd " config.api_only = true\n config.middleware.insert_after Rack::Runtime, Rack::MethodOverride\n" +lock rails-deleted rack 3.2.8 railties 8.1.4; railscfg rails-deleted "" +printf 'Rails.application.config.middleware.delete Rack::MethodOverride\n' > "$W/rails-deleted/config/initializers/mo.rb" +lock railties-not-rails rack 3.2.8 railties 8.1.4 sinatra 4.2.2 +mkdir -p "$W/railties-not-rails/lib" +printf "require 'sinatra/base'\nclass App < Sinatra::Base\nend\n" > "$W/railties-not-rails/lib/app.rb" +lock sinatra-classic rack 3.2.8 sinatra 4.2.2 +printf "require 'sinatra'\nget('/') { 'ok' }\n" > "$W/sinatra-classic/app.rb" +lock sinatra-deep rack 3.2.8 sinatra 4.2.2 +mkdir -p "$W/sinatra-deep/app/web" +printf "require 'sinatra'\nget('/') { 'ok' }\n" > "$W/sinatra-deep/app/web/main.rb" +lock sinatra-disabled rack 3.2.8 sinatra 4.2.2 +printf "require 'sinatra'\ndisable :method_override\n" > "$W/sinatra-disabled/app.rb" +lock sinatra-unknown rack 3.2.8 sinatra 4.2.2 +lock rodauth rack 3.2.8 roda 3.110.0 rodauth 2.51.0 +mkdir -p "$W/rodauth/app/misc" +printf "class RodauthMain < Rodauth::Rails::Auth\n configure do\n enable :create_account, :login\n end\nend\n" > "$W/rodauth/app/misc/rodauth_main.rb" +lock rodauth-off rack 3.2.8 roda 3.110.0 rodauth 2.51.0 +printf "class App < Roda\n plugin :rodauth do\n enable :create_account\n require_login_confirmation? false\n end\nend\n" > "$W/rodauth-off/app.rb" +lock rack-mo rack 3.2.8 +printf "use Rack::MethodOverride\nrun ->(env) { [200, {}, ['ok']] }\n" > "$W/rack-mo/config.ru" +lock commented rack 3.2.8 +printf "# use Rack::MethodOverride\nrun ->(env) { [200, {}, ['ok']] }\n" > "$W/commented/config.ru" +mkdir -p "$W/empty" + +PASS=0 +FAIL=0 +# t NAME DIR WANT_CODE MUST_CONTAIN [detector args...] (DIR "" = nothing running) +t() { + name=$1; dir=$2; want=$3; must=$4; shift 4 + PID="" + if [ -n "$dir" ]; then + (cd "$W/$dir" && exec "$RUBY" -e 'sleep 300') & + PID=$! + sleep 1 + fi + out=$(bash "$DET" "$@" 2>&1); rc=$? + if [ -n "$PID" ]; then kill "$PID" 2>/dev/null; wait "$PID" 2>/dev/null; PID=""; fi + if [ "$rc" = "$want" ] && printf '%s\n' "$out" | grep -qF -- "$must"; then + PASS=$((PASS + 1)); echo "PASS $name" + else + FAIL=$((FAIL + 1)); echo "FAIL $name (exit $rc, want $want, must contain: $must)" + printf '%s\n' "$out" | sed 's/^/ /' + fi +} + +t "rails, default stack" rails 1 "mounts Rack::MethodOverride by default" --no-disk +t "rails, api_only" rails-api 2 "api_only" --no-disk +t "api_only, insert_before names it only as anchor" rails-api-guard 2 "api_only" --no-disk +t "api_only, MethodOverride re-added" rails-api-readd 1 "mounted explicitly" --no-disk +t "rails, middleware deleted" rails-deleted 2 "Rack::MethodOverride deleted" --no-disk +t "railties in lockfile, not a Rails app" railties-not-rails 2 "modular Sinatra" --no-disk +t "sinatra, classic style" sinatra-classic 1 "classic-style Sinatra" --no-disk +t "sinatra, classic style below the top level" sinatra-deep 1 "classic-style Sinatra" --no-disk +t "sinatra, method_override disabled" sinatra-disabled 2 "method_override disabled" --no-disk +t "sinatra, style not determined" sinatra-unknown 2 "style not determined" --no-disk +t "rodauth create_account" rodauth 1 "create_account compares login" --no-disk +t "rodauth, login confirmation off" rodauth-off 2 "without Rack::MethodOverride" --no-disk +t "rack with explicit MethodOverride" rack-mo 1 "mounted explicitly" --no-disk +t "commented-out use line" commented 2 "without Rack::MethodOverride" --no-disk +t "no application" empty 2 "no application found" --no-disk +t "-r is counted" "" 2 "(-r)" --no-procs --no-disk -r "$RUBY" +t "-r is counted with the disk scan on" "" 2 "(-r)" --no-procs -r "$RUBY" +t "running process decides with the disk scan on" rails 1 "=> [!] impacted: CVE-2026-132825" +t "quiet prints the verdict" rails 1 "impacted" -q --no-disk +t "usage error exits 3" "" 3 "unknown argument" --bogus + +echo "passed=$PASS failed=$FAIL" +[ "$FAIL" = 0 ] diff --git a/CVE-2026-132825/linux/tests/run-tests.sh b/CVE-2026-132825/linux/tests/run-tests.sh new file mode 100755 index 0000000..aeb6c48 --- /dev/null +++ b/CVE-2026-132825/linux/tests/run-tests.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# +# Tests detect-ruby2shell.sh against real Ruby interpreters in Docker. +# +# Each case starts an idle Ruby process (ruby -e 'sleep') in a small application +# directory built here, runs the detector inside the same container with +# --no-disk, and checks the exit code and the last line. One case runs the +# detector from a second, privileged container that shares the first one's PID +# namespace, which is how the Kubernetes DaemonSet sees workloads. +# +# No request is sent and no vulnerable input is used: the "encoding module" case +# upcases the three-byte string "abc" in ISO-8859-1, which only makes Ruby load +# enc/iso_8859_1.so. +# +# usage: run-tests.sh [--vuln-image IMAGE] [--fixed-image IMAGE] +# Needs docker. Defaults are the official images, pinned by digest. + +set -u + +HERE=$(cd "$(dirname "$0")" && pwd) +DET=$(cd "$HERE/.." && pwd) +# ruby:3.4.12-slim and ruby:3.4.13-slim +VULN="ruby@sha256:65680693964528b522a38d85ec5065538c7ab9e75268802aab9770f39ee56de0" +FIXED="ruby@sha256:03e203fab47d495a1d0046d10040db89367b361328ecd4af469f0433e2dd9ce1" +while [ $# -gt 0 ]; do + case "$1" in + --vuln-image) VULN=$2; shift ;; + --fixed-image) FIXED=$2; shift ;; + *) echo "usage: run-tests.sh [--vuln-image IMAGE] [--fixed-image IMAGE]" >&2; exit 3 ;; + esac + shift +done +command -v docker >/dev/null 2>&1 || { echo "docker not found" >&2; exit 3; } + +PASS=0 +FAIL=0 +WORK=$(mktemp -d "${TMPDIR:-/tmp}/ruby2shell-tests.XXXXXX") +NAME="ruby2shell-test-$$" +cleanup() { + docker rm -f "$NAME" "$NAME-side" >/dev/null 2>&1 + rm -rf "$WORK" +} +trap cleanup EXIT + +# On Git Bash (Windows) docker needs Windows paths and no path rewriting. +winpath() { if pwd -W >/dev/null 2>&1; then (cd "$1" && pwd -W); else echo "$1"; fi; } +export MSYS_NO_PATHCONV=1 + +lock() { # DIR GEM VERSION [GEM VERSION]... + d="$WORK/$1"; shift; mkdir -p "$d" + { + echo "GEM"; echo " remote: https://rubygems.org/"; echo " specs:" + while [ $# -gt 1 ]; do echo " $1 ($2)"; shift 2; done + echo; echo "PLATFORMS"; echo " ruby" + } > "$d/Gemfile.lock" +} +for a in rails rails-api rails-deleted; do + lock "$a" rack 3.2.8 railties 8.1.4 + mkdir -p "$WORK/$a/config/environments" "$WORK/$a/config/initializers" + printf 'run Rails.application\n' > "$WORK/$a/config.ru" +done +printf 'module App\n class Application < Rails::Application\n config.load_defaults 8.1\n end\nend\n' > "$WORK/rails/config/application.rb" +printf 'module App\n class Application < Rails::Application\n config.api_only = true\n end\nend\n' > "$WORK/rails-api/config/application.rb" +cp "$WORK/rails/config/application.rb" "$WORK/rails-deleted/config/application.rb" +printf 'Rails.application.config.middleware.delete Rack::MethodOverride\n' > "$WORK/rails-deleted/config/initializers/mo.rb" +for a in sinatra-classic sinatra-modular sinatra-disabled; do lock "$a" rack 3.2.8 sinatra 4.2.2; done +printf "require 'sinatra'\nget('/') { 'ok' }\n" > "$WORK/sinatra-classic/app.rb" +printf "require 'sinatra/base'\nclass App < Sinatra::Base\nend\n" > "$WORK/sinatra-modular/app.rb" +printf "run App\n" > "$WORK/sinatra-modular/config.ru" +printf "require 'sinatra'\ndisable :method_override\n" > "$WORK/sinatra-disabled/app.rb" +lock rack-mo rack 3.2.8 +printf "use Rack::MethodOverride\nrun ->(env) { [200, {}, ['ok']] }\n" > "$WORK/rack-mo/config.ru" +for a in rodauth rodauth-noconfirm; do lock "$a" rack 3.2.8 roda 3.110.0 rodauth 2.51.0; printf "run App.freeze.app\n" > "$WORK/$a/config.ru"; done +printf "class App < Roda\n plugin :rodauth do\n enable :login, :logout, :create_account\n end\nend\n" > "$WORK/rodauth/app.rb" +printf "class App < Roda\n plugin :rodauth do\n enable :login, :create_account\n require_login_confirmation? false\n end\nend\n" > "$WORK/rodauth-noconfirm/app.rb" +for a in rails-api-guard rails-api-readd; do + lock "$a" rack 3.2.8 railties 8.1.4 + mkdir -p "$WORK/$a/config/initializers" + printf 'run Rails.application\n' > "$WORK/$a/config.ru" +done +cp "$WORK/rails-api/config/application.rb" "$WORK/rails-api-guard/config/application.rb" +printf 'Rails.application.config.middleware.insert_before Rack::MethodOverride, CharsetGuard\n' > "$WORK/rails-api-guard/config/initializers/guard.rb" +printf 'module App\n class Application < Rails::Application\n config.api_only = true\n config.middleware.insert_after Rack::Runtime, Rack::MethodOverride\n end\nend\n' > "$WORK/rails-api-readd/config/application.rb" +lock railties-not-rails rack 3.2.8 railties 8.1.4 sinatra 4.2.2 +mkdir -p "$WORK/railties-not-rails/lib" +printf "require 'sinatra/base'\nclass App < Sinatra::Base\nend\n" > "$WORK/railties-not-rails/lib/app.rb" +lock sinatra-deep rack 3.2.8 sinatra 4.2.2 +mkdir -p "$WORK/sinatra-deep/app/web" +printf "require 'sinatra'\nget('/') { 'ok' }\n" > "$WORK/sinatra-deep/app/web/main.rb" +mkdir -p "$WORK/empty" +chmod -R a+rX "$WORK" + +verdict() { + case "$1" in 0) echo "not impacted" ;; 1) echo "impacted" ;; 2) echo "unknown" ;; *) echo "" ;; esac +} + +# check NAME WANT_CODE [MUST_CONTAIN]... (uses OUT, CODE) +check() { + name=$1; want=$2; shift 2 + ok=1 + last=$(printf '%s\n' "$OUT" | sed '/^[[:space:]]*$/d' | tail -n 1) + [ "$CODE" = "$want" ] || ok=0 + [ "$last" = "$(verdict "$want")" ] || ok=0 + for c in "$@"; do + printf '%s\n' "$OUT" | grep -qF -- "$c" || ok=0 + done + if [ "$ok" = 1 ]; then + PASS=$((PASS + 1)); echo "PASS $name" + else + FAIL=$((FAIL + 1)); echo "FAIL $name (exit $CODE, last line '$last')" + printf '%s\n' "$OUT" | sed 's/^/ /' + fi +} + +# start IMAGE APP ENC : idle Ruby with cwd /fx/APP +start() { + if [ "$3" = 1 ]; then rb='"abc".force_encoding("ISO-8859-1").upcase; sleep 600'; else rb='sleep 600'; fi + docker rm -f "$NAME" >/dev/null 2>&1 + docker run -d --name "$NAME" --hostname web-test-pod -v "$(winpath "$DET"):/d:ro" -v "$(winpath "$WORK"):/fx:ro" \ + -w "/fx/$2" "$1" ruby -e "$rb" >/dev/null || { echo "could not start $1" >&2; exit 3; } + sleep 2 +} +# one NAME IMAGE APP ENC WANT [MUST_CONTAIN]... +one() { + name=$1; img=$2; app=$3; enc=$4; want=$5; shift 5 + start "$img" "$app" "$enc" + OUT=$(docker exec "$NAME" bash /d/detect-ruby2shell.sh --no-disk 2>&1); CODE=$? + check "$name" "$want" "$@" +} + +one "rails, default stack" "$VULN" rails 0 1 "mounts Rack::MethodOverride by default" "=> [!] impacted: CVE-2026-132825" +one "rails, api_only" "$VULN" rails-api 0 2 "api_only" "=> [?] unknown" +one "rails, middleware deleted" "$VULN" rails-deleted 0 2 "Rack::MethodOverride deleted" +one "sinatra, classic style" "$VULN" sinatra-classic 0 1 "classic-style Sinatra" +one "sinatra, modular" "$VULN" sinatra-modular 0 2 "modular Sinatra" +one "sinatra, method_override disabled" "$VULN" sinatra-disabled 0 2 "method_override disabled" +one "rack with explicit MethodOverride" "$VULN" rack-mo 0 1 "mounted explicitly" +one "rodauth create_account" "$VULN" rodauth 0 1 "Rodauth 2.51.0 create_account" +one "rodauth, login confirmation off" "$VULN" rodauth-noconfirm 0 2 "Rack application without Rack::MethodOverride" +one "api_only, insert_before names it only as anchor" "$VULN" rails-api-guard 0 2 "api_only" +one "api_only, MethodOverride re-added" "$VULN" rails-api-readd 0 1 "mounted explicitly" +one "railties in lockfile, not a Rails app" "$VULN" railties-not-rails 0 2 "modular Sinatra" +one "classic sinatra below the top level" "$VULN" sinatra-deep 0 1 "classic-style Sinatra" +one "no application" "$VULN" empty 0 2 "no application found" +one "no application, encoding module loaded" "$VULN" empty 1 1 "affected encoding module loaded: enc/iso_8859_1.so" +one "rails on a fixed Ruby" "$FIXED" rails 1 0 ": fixed OK" "=> OK not impacted" + +# quiet: verdict line only +start "$VULN" rails 0 +OUT=$(docker exec "$NAME" bash /d/detect-ruby2shell.sh -q --no-disk 2>&1); CODE=$? +[ "$(printf '%s\n' "$OUT" | wc -l | tr -d ' ')" = 1 ] || OUT="$OUT +(expected exactly one line)" +check "quiet prints only the verdict" 1 + +# installed interpreter, nothing running in that container +OUT=$(docker run --rm -v "$(winpath "$DET"):/d:ro" "$VULN" bash /d/detect-ruby2shell.sh --no-procs 2>&1); CODE=$? +check "installed only, unpatched: listed, not counted" 0 "(installed, not running)" "=> not counted: installed but not running" "1 Ruby interpreter(s) installed but not running" +OUT=$(docker run --rm -v "$(winpath "$DET"):/d:ro" "$VULN" bash /d/detect-ruby2shell.sh --no-procs --count-installed 2>&1); CODE=$? +check "installed only, unpatched, --count-installed" 2 "not running: no application to check" "=> [?] unknown" +OUT=$(docker run --rm -v "$(winpath "$DET"):/d:ro" "$VULN" bash /d/detect-ruby2shell.sh --no-procs --no-disk -r /usr/local/bin/ruby 2>&1); CODE=$? +check "interpreter passed with -r is counted" 2 "(-r)" "=> [?] unknown" +OUT=$(docker run --rm -v "$(winpath "$DET"):/d:ro" "$VULN" bash /d/detect-ruby2shell.sh --no-procs -r /usr/local/bin/ruby 2>&1); CODE=$? +check "-r is counted with the disk scan on" 2 "(-r)" "=> [?] unknown" +OUT=$(docker run --rm -v "$(winpath "$DET"):/d:ro" "$FIXED" bash /d/detect-ruby2shell.sh --no-procs 2>&1); CODE=$? +check "installed only, fixed" 0 "=> OK not impacted" +# a running unpatched Ruby still decides the verdict when an idle one is also listed +start "$VULN" rails 0 +OUT=$(docker exec "$NAME" bash /d/detect-ruby2shell.sh 2>&1); CODE=$? +check "running process counted with disk scan on" 1 "=> [!] impacted: CVE-2026-132825" + +# another container, seen from a privileged container in the same PID namespace +start "$VULN" rails 0 +OUT=$(docker run --rm --name "$NAME-side" --pid "container:$NAME" --privileged -v "$(winpath "$DET"):/d:ro" \ + debian:stable-slim bash /d/detect-ruby2shell.sh --no-disk 2>&1); CODE=$? +check "process in another container, read through /proc" 1 "container web-test-pod" "mounts Rack::MethodOverride by default" + +# usage error +OUT=$(docker run --rm -v "$(winpath "$DET"):/d:ro" "$FIXED" bash /d/detect-ruby2shell.sh --bogus 2>&1); CODE=$? +if [ "$CODE" = 3 ]; then PASS=$((PASS + 1)); echo "PASS usage error exits 3"; else FAIL=$((FAIL + 1)); echo "FAIL usage error exits 3 (exit $CODE)"; fi + +echo "passed=$PASS failed=$FAIL" +[ "$FAIL" = 0 ] diff --git a/CVE-2026-132825/windows/Detect-Ruby2Shell.ps1 b/CVE-2026-132825/windows/Detect-Ruby2Shell.ps1 new file mode 100644 index 0000000..6ab32b9 --- /dev/null +++ b/CVE-2026-132825/windows/Detect-Ruby2Shell.ps1 @@ -0,0 +1,392 @@ +<# +.SYNOPSIS + Checks whether this host runs a Ruby exposed to "Ruby2Shell" (CVE-2026-132825, + GHSA-34m4-m9fh-gqp5) or to the six other memory-safety advisories fixed in the + same releases (Ruby 4.0.10, 3.4.13 and 3.3.14, 2026-11-18). + +.DESCRIPTION + The bugs are in the Ruby interpreter (CRuby), not in gems, so the verdict + rests on the interpreter: + 1. version: 4.0.0-4.0.9, 3.4.0-3.4.12, 3.3.0-3.3.13 and every older release + back to 2.4.0 are affected. 3.2 and older are end-of-life: no upstream + fix. Windows builds (RubyInstaller, Chocolatey, Scoop, bundled Rubies) + are plain upstream builds, so there is no backport check. + 2. per advisory: + - CVE-2026-132825 is reachable before authentication when the + application mounts Rack::MethodOverride: Rails unless api_only, + classic-style Sinatra, or a config.ru that uses it. A process that + has loaded one of the 14 affected encoding modules also counts. + - The six siblings depend on what the application code does (for + example compiling a regular expression from user input). A host + script cannot see that, so they stay [?] on an unpatched Ruby. + + A patched and an unpatched Ruby give identical results for every input, so + nothing is probed for the bug. Each ruby.exe is asked only for its engine + and version (ruby -e "print RUBY_ENGINE, RUBY_VERSION"). + + What gets checked: + - every running ruby.exe / rubyw.exe, and its application directory when + the command line names a path inside one + - ruby.exe on PATH and in common install and bundle directories + - any ruby.exe passed with -Ruby + + Only RUNNING Rubies (and those passed with -Ruby) decide the verdict. The + bugs need a live process handling attacker input, so an unpatched ruby.exe + that nothing is running is listed as information and not counted. Blind + spot: anything not running during the scan (scheduled tasks, command-line + scripts, services that are stopped) is not counted either. Use + -CountInstalled to count every unpatched interpreter on disk. + + Not covered: Ruby inside WSL distributions (run the Linux detector there) + and inside Windows containers. + + Exit codes, for fleet tooling: + 0 not impacted: every running Ruby is patched, or none is running + 1 impacted: at least one unpatched Ruby with CVE-2026-132825 exposed + 2 unknown: at least one unpatched or unreadable Ruby and none is impacted + 3 usage error + + The last line of output is exactly one of: impacted | not impacted | unknown. + If PowerShell itself rejects the arguments, powershell.exe exits 1 before + the script runs and that line is missing. Fleet tooling should treat exit + 1 as impacted only when the last line says so. + + Works with Windows PowerShell 5.1 and PowerShell 7. Run elevated for full + coverage of other users' processes. Read-only. + +.PARAMETER Ruby + Additional ruby.exe paths to check. These are always counted. + +.PARAMETER CountInstalled + Let unpatched Rubies that are installed but not running count toward the + verdict (default: listed, not counted). + +.EXAMPLE + powershell.exe -NoProfile -ExecutionPolicy Bypass -File Detect-Ruby2Shell.ps1 -Quiet +#> +[CmdletBinding()] +param( + [string[]]$Ruby = @(), + [switch]$NoProcesses, + [switch]$NoDisk, + [switch]$CountInstalled, + [switch]$Quiet, + [int]$ProbeTimeoutSec = 20 +) + +$ErrorActionPreference = 'Continue' + +trap { + Write-Output ("error: {0}: {1} {2}" -f $_.Exception.GetType().FullName, $_.Exception.Message, + $_.InvocationInfo.PositionMessage) + Write-Output 'unknown' + exit 2 +} + +# Under -File, "-Ruby a,b" arrives as the single string "a,b"; split it. +$Ruby = @($Ruby | ForEach-Object { $_ -split ',' } | Where-Object { $_ }) + +$Cve = 'CVE-2026-132825' +$Ghsa = 'GHSA-34m4-m9fh-gqp5' +$Fixed = @{ '4.0' = 10; '3.4' = 13; '3.3' = 14 } +$Eol = @('3.2', '3.1', '3.0', '2.7', '2.6', '2.5', '2.4') +$Siblings = @( + @('GHSA-87fm-7w84-j2px', 'case conversion of multi-GB strings'), + @('GHSA-7x2q-68qv-6p8x', 'Regexp compiled from untrusted input (double free)'), + @('GHSA-3p8q-wmhx-vm2w', 'Regexp compiled from untrusted input (size overflow)'), + @('GHSA-7whj-cfh7-xgm4', 'Regexp#to_s or Regexp.union on an untrusted pattern'), + @('GHSA-wpqw-5qxg-m68r', 'case-insensitive UTF-16/32 pattern matched on untrusted text'), + @('GHSA-pvgc-g7gj-pv6h', 'case-insensitive backreference matched on untrusted text') +) +$EncRe = '^(iso_8859_(1|2|3|4|9|10|13|14|15|16)|windows_125(0|2|4|7))\.so$' + +$script:nImpacted = 0 +$script:nUnknown = 0 +$script:nOk = 0 +$script:nInfo = 0 +$script:seen = @{} + +function Say([string]$Text) { if (-not $Quiet) { Write-Output $Text } } +function Mark([string]$State) { + switch ($State) { 'impacted' { '[!]' } 'ok' { 'OK' } 'unknown' { '[?]' } default { 'n/a' } } +} +function Tally([string]$State) { + switch ($State) { + 'impacted' { $script:nImpacted++ } + 'unknown' { $script:nUnknown++ } + default { $script:nOk++ } + } +} + +function Get-VersionState([string]$Version) { + if ($Version -notmatch '^(\d+)\.(\d+)\.(\d+)$') { + return @{ State = 'unknown'; Msg = 'preview, release candidate or unreadable version: not assessed' } + } + $branch = "$($Matches[1]).$($Matches[2])" + $patch = [int]$Matches[3] + if ($Fixed.ContainsKey($branch)) { + if ($patch -ge $Fixed[$branch]) { return @{ State = 'ok'; Msg = 'fixed' } } + return @{ State = 'impacted'; Msg = "affected, fixed in $branch.$($Fixed[$branch])" } + } + if ($Eol -contains $branch) { + return @{ State = 'impacted'; Msg = 'affected, end-of-life branch: no upstream fix' } + } + if ([int]$Matches[1] -lt 2 -or ($Matches[1] -eq '2' -and [int]$Matches[2] -lt 4)) { + return @{ State = 'ok'; Msg = 'older than 2.4.0: predates these bugs (end-of-life, upgrade anyway)' } + } + return @{ State = 'unknown'; Msg = 'newer branch than the releases checked on 2026-11-19' } +} + +# Runs " -e " with a timeout. Returns "engine version" or ''. +function Get-RubyIdentity([string]$Exe) { + try { + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = $Exe + $psi.Arguments = '-e "print RUBY_ENGINE, 32.chr, RUBY_VERSION"' + $psi.UseShellExecute = $false + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $psi.CreateNoWindow = $true + $p = [System.Diagnostics.Process]::Start($psi) + $out = $p.StandardOutput.ReadToEndAsync() + if (-not $p.WaitForExit($ProbeTimeoutSec * 1000)) { try { $p.Kill() } catch { }; return '' } + return ("$($out.Result)").Trim() + } catch { return '' } +} + +# Finds an application root from a list of candidate paths and decides whether +# Rack::MethodOverride is mounted. Returns @{ State; Msg }. +function Get-AppState([string[]]$Candidates) { + $app = $null + foreach ($c in $Candidates) { + $d = $c + if (Test-Path -LiteralPath $d -PathType Leaf) { $d = Split-Path -Parent $d } + for ($i = 0; $i -lt 5 -and $d; $i++) { + if ((Test-Path -LiteralPath (Join-Path $d 'Gemfile.lock')) -or (Test-Path -LiteralPath (Join-Path $d 'config.ru'))) { + $app = $d; break + } + $d = Split-Path -Parent $d + } + if ($app) { break } + } + if (-not $app) { + return @{ State = 'unknown'; Msg = 'no application found for this process; application code not analysed' } + } + $lock = '' + $lf = Join-Path $app 'Gemfile.lock' + if (Test-Path -LiteralPath $lf) { $lock = Get-Content -LiteralPath $lf -Raw -ErrorAction SilentlyContinue } + $rails = ''; $sin = ''; $rack = '?' + if ($lock -match '(?m)^ railties \(([0-9][^)]*)\)') { $rails = $Matches[1] } + if ($lock -match '(?m)^ sinatra \(([0-9][^)]*)\)') { $sin = $Matches[1] } + if ($lock -match '(?m)^ rack \(([0-9][^)]*)\)') { $rack = $Matches[1] } + $cfgFiles = @() + $cfgFiles += Get-ChildItem -LiteralPath (Join-Path $app 'config') -Filter application.rb -ErrorAction SilentlyContinue + $cfgFiles += Get-ChildItem -Path (Join-Path $app 'config\environments\*.rb') -ErrorAction SilentlyContinue + $cfgFiles += Get-ChildItem -Path (Join-Path $app 'config\initializers\*.rb') -ErrorAction SilentlyContinue + $topFiles = @() + $topFiles += Get-ChildItem -Path (Join-Path $app '*.rb') -ErrorAction SilentlyContinue + $topFiles += Get-ChildItem -LiteralPath $app -Filter config.ru -ErrorAction SilentlyContinue + $cfg = (@($cfgFiles | ForEach-Object { Get-Content -LiteralPath $_.FullName -Raw -ErrorAction SilentlyContinue }) -join "`n") + $top = (@($topFiles | ForEach-Object { Get-Content -LiteralPath $_.FullName -Raw -ErrorAction SilentlyContinue }) -join "`n") + $all = "$cfg`n$top" + # `use X` and `middleware.use X` mount X. `insert_before A, X` mounts X; a line + # that only names Rack::MethodOverride as the anchor A does not. + if ($all -match '(?m)^[^#\r\n]*middleware\.use[ (]+Rack::MethodOverride|^[^#\r\n]*middleware\.insert\w*[ (]+[^,#\r\n]+,[ \t]*Rack::MethodOverride|^[ \t]*use[ (]+Rack::MethodOverride') { + return @{ State = 'impacted'; Msg = "Rack::MethodOverride is mounted explicitly ($app)" } + } + # A lockfile can list railties without the app being a Rails app. + if (-not (Test-Path -LiteralPath (Join-Path $app 'config\application.rb'))) { $rails = '' } + # Rodauth: create_account compares login and login-confirm with casecmp? before + # authentication, on raw request params (rodauth 2.51.0, confirmed at runtime). + if ($lock -match '(?m)^ rodauth \(([0-9][^)]*)\)') { + $rod = $Matches[1] + $rfiles = @(Get-ChildItem -LiteralPath $app -Recurse -Depth 4 -Filter *.rb -File -ErrorAction SilentlyContinue | + Where-Object { $_.FullName -notmatch '\\(vendor|node_modules|spec|test)\\' } | Select-Object -First 400) + $rsrc = (@($rfiles | ForEach-Object { Get-Content -LiteralPath $_.FullName -Raw -ErrorAction SilentlyContinue }) -join "`n") + if (($rsrc -match '(?m)^[^#\r\n]*enable[ (].*:create_account') -and + ($rsrc -notmatch '(?m)^[^#\r\n]*(require_login_confirmation\?\s+false|only_json\?\s+true)')) { + return @{ State = 'impacted'; Msg = "Rodauth $rod create_account compares login and login-confirm with casecmp? before authentication ($app)" } + } + } + if ($rails) { + if ($cfg -match '(?m)^[^#\r\n]*middleware\.delete[ (]+Rack::MethodOverride') { + return @{ State = 'unknown'; Msg = "Rails $rails with Rack::MethodOverride deleted ($app); application code not analysed" } + } + if ($cfg -match '(?m)^[^#\r\n]*config\.api_only\s*=\s*true') { + return @{ State = 'unknown'; Msg = "Rails $rails api_only, no Rack::MethodOverride ($app); application code not analysed" } + } + return @{ State = 'impacted'; Msg = "Rails $rails mounts Rack::MethodOverride by default, rack $rack ($app)" } + } + if ($sin) { + # The app file is not always at the top level: look a few levels down. + $sfiles = @(Get-ChildItem -LiteralPath $app -Recurse -Depth 4 -File -ErrorAction SilentlyContinue | + Where-Object { ($_.Name -like '*.rb' -or $_.Name -eq 'config.ru') -and + $_.FullName -notmatch '\\(vendor|node_modules|spec|test)\\' } | Select-Object -First 400) + $ssrc = (@($sfiles | ForEach-Object { Get-Content -LiteralPath $_.FullName -Raw -ErrorAction SilentlyContinue }) -join "`n") + if ($ssrc -match '(?m)^[^#\r\n]*(disable[ (]+:method_override|set[ (]+:method_override,\s*false)') { + return @{ State = 'unknown'; Msg = "Sinatra $sin with method_override disabled ($app); application code not analysed" } + } + if ($ssrc -match '(?m)^[^#\r\n]*(enable[ (]+:method_override|set[ (]+:method_override,\s*true)') { + return @{ State = 'impacted'; Msg = "Sinatra $sin with method_override enabled, rack $rack ($app)" } + } + if ($ssrc -match '(?m)^[^#\r\n]*require[ (]+[''"]sinatra[''"]') { + return @{ State = 'impacted'; Msg = "classic-style Sinatra $sin enables method_override by default, rack $rack ($app)" } + } + if ($ssrc -match 'Sinatra::Base|sinatra/base') { + return @{ State = 'unknown'; Msg = "modular Sinatra $sin, method_override off by default ($app); application code not analysed" } + } + return @{ State = 'unknown'; Msg = "Sinatra $sin, style not determined ($app); application code not analysed" } + } + return @{ State = 'unknown'; Msg = "Rack application without Rack::MethodOverride ($app); application code not analysed" } +} + +function Skip-NotCounted { + Say ' => not counted: installed but not running (-CountInstalled to count it)' + $script:nInfo++ +} + +# $Count = $false: list the interpreter but keep it out of the verdict. +function Report([string]$Title, [string]$Identity, [string[]]$AppCandidates, [string]$EncMods, [bool]$Running, [bool]$Count) { + Say '' + Say $Title + if (-not $Identity) { + Say ' version: could not run this ruby to read its version [?]' + if (-not $Count) { Skip-NotCounted; return } + Say ' => [?] unknown' + Tally 'unknown'; return + } + $engine, $version = $Identity -split '\s+', 2 + if ($engine -eq 'jruby' -or $engine -eq 'truffleruby') { + Say " version: ${Identity}: not CRuby; this engine does not share the memory-corruption bugs OK" + Say ' => OK not impacted (it has its own non-memory bugs for similar input: keep it updated)' + Tally 'ok'; return + } + if ($engine -ne 'ruby') { + Say " version: ${Identity}: not CRuby, these advisories do not name it [?]" + if (-not $Count) { Skip-NotCounted; return } + Say ' => [?] unknown' + Tally 'unknown'; return + } + $v = Get-VersionState $version + Say " version: ruby $version`: $($v.Msg) $(Mark $v.State)" + if ($v.State -eq 'ok') { + Say " $Cve`: - n/a" + Say ' => OK not impacted' + Tally 'ok'; return + } + if (-not $Count) { Skip-NotCounted; return } + if ($v.State -eq 'unknown') { + Say ' => [?] unknown' + Tally 'unknown'; return + } + if ($Running) { $a = Get-AppState $AppCandidates } + else { $a = @{ State = 'unknown'; Msg = 'not running: no application to check' } } + if ($EncMods) { + $a = @{ State = 'impacted'; Msg = "$($a.Msg); affected encoding module loaded: $EncMods" } + } + Say " $Cve ($Ghsa): $($a.Msg) $(Mark $a.State)" + foreach ($s in $Siblings) { Say " $($s[0]): $($s[1]); depends on application code [?]" } + if ($a.State -eq 'impacted') { + Say " => [!] impacted: $Cve" + Tally 'impacted' + } else { + Say ' => [?] unknown: unpatched Ruby, exposure depends on application code (see "Application code" in the README)' + Tally 'unknown' + } +} + +# Splits a Windows command line into arguments (quotes respected, no escapes). +function Split-CommandLine([string]$Line) { + $out = @() + foreach ($m in [regex]::Matches("$Line", '"([^"]*)"|(\S+)')) { + if ($m.Groups[1].Success) { $out += $m.Groups[1].Value } else { $out += $m.Groups[2].Value } + } + return $out +} + +Say "Ruby check: $Cve (Ruby2Shell, string case conversion) and six sibling advisories fixed in Ruby 4.0.10 / 3.4.13 / 3.3.14" +Say 'legend: [!] impacted | OK not impacted | [?] could not check | n/a not checked' +Say "checks: version, then per advisory. $Cve is [!] when the application mounts" +Say ' Rack::MethodOverride (Rails unless api_only, classic Sinatra), enables Rodauth create_account,' +Say ' or has an affected encoding module loaded. Only running Rubies (and -Ruby paths) are counted.' +Say ' The six siblings depend on application code, so they stay [?] on an unpatched Ruby.' +Say "host: Windows $([Environment]::OSVersion.Version) $env:PROCESSOR_ARCHITECTURE" +$admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( + [Security.Principal.WindowsBuiltInRole]::Administrator) +if (-not $admin) { Say "note: not elevated: other users' processes may be missed" } + +if (-not $NoProcesses) { + $procs = @(Get-CimInstance Win32_Process -Filter "Name='ruby.exe' OR Name='rubyw.exe'" -ErrorAction SilentlyContinue) + foreach ($p in $procs) { + $exe = $p.ExecutablePath + $argv = @(Split-CommandLine $p.CommandLine) + $cands = @($argv | Select-Object -Skip 1 | Where-Object { $_ -and ($_ -notmatch '^-') -and (Test-Path -LiteralPath $_ -ErrorAction SilentlyContinue) }) + $key = "$exe|$($cands -join '|')" + if ($script:seen.ContainsKey($key)) { continue } + $script:seen[$key] = 1 + $enc = '' + try { + $mods = (Get-Process -Id $p.ProcessId -ErrorAction Stop).Modules + $enc = (@($mods | Where-Object { $_.ModuleName -match $EncRe } | ForEach-Object { $_.ModuleName } | Sort-Object -Unique) -join ' ') + } catch { } + $cmd = "$($p.CommandLine)" + if ($cmd.Length -gt 70) { $cmd = $cmd.Substring(0, 70) } + if ($exe) { $id = Get-RubyIdentity $exe; $script:seen["disk|$exe".ToLower()] = 1 } else { $id = '' ; $exe = $p.Name } + Report "$exe (pid $($p.ProcessId): $cmd)" $id $cands $enc $true $true + } +} + +function Test-Disk([string]$Exe, [string]$How) { + if (-not $Exe -or -not (Test-Path -LiteralPath $Exe -PathType Leaf)) { return } + $full = (Resolve-Path -LiteralPath $Exe).ProviderPath + $key = "disk|$full".ToLower() + if ($script:seen.ContainsKey($key)) { return } + $script:seen[$key] = 1 + $count = ($How -eq "-Ruby") -or [bool]$CountInstalled + if ($How -ne "-Ruby") { $How = "installed, not running" } + Report "$full ($How)" (Get-RubyIdentity $full) @() "" $false $count +} + +# Paths given with -Ruby go first, so the disk scan cannot list one as "not +# counted" before it is judged. +foreach ($r in $Ruby) { + if (-not (Test-Path -LiteralPath $r -PathType Leaf)) { + Say '' + Say "$r (-Ruby)" + Say ' version: file not found [?]' + Say ' => [?] unknown' + Tally 'unknown'; continue + } + Test-Disk $r '-Ruby' +} + +if (-not $NoDisk) { + foreach ($c in @(Get-Command ruby.exe -All -ErrorAction SilentlyContinue)) { Test-Disk $c.Source 'installed' } + $sd = $env:SystemDrive + $globs = @( + "$sd\Ruby*\bin\ruby.exe", "$sd\tools\ruby*\bin\ruby.exe", "$sd\RubyInstaller*\bin\ruby.exe", + "$env:ProgramFiles\Ruby*\bin\ruby.exe", "$sd\Users\*\scoop\apps\ruby*\current\bin\ruby.exe", + "$env:ProgramData\scoop\apps\ruby*\current\bin\ruby.exe", "$sd\Users\*\.rubies\*\bin\ruby.exe", + "$sd\opscode\*\embedded\bin\ruby.exe", "$sd\cinc-project\*\embedded\bin\ruby.exe", + "$env:ProgramFiles\Puppet Labs\Puppet\puppet\bin\ruby.exe", "$env:ProgramFiles\Puppet Labs\Puppet\sys\ruby\bin\ruby.exe", + "$sd\HashiCorp\Vagrant\embedded\mingw64\bin\ruby.exe", "$env:ProgramFiles\Vagrant\embedded\mingw64\bin\ruby.exe", + "$sd\opt\td-agent\bin\ruby.exe", "$sd\opt\fluent\bin\ruby.exe", "$sd\metasploit-framework\embedded\bin\ruby.exe" + ) + foreach ($g in $globs) { + foreach ($f in @(Get-ChildItem -Path $g -ErrorAction SilentlyContinue)) { Test-Disk $f.FullName 'installed' } + } +} + +if (($script:nImpacted + $script:nUnknown + $script:nOk + $script:nInfo) -eq 0) { + Say '' + Say 'no Ruby interpreter found' +} +if ($script:nInfo -gt 0) { + Say '' + Say "note: $($script:nInfo) Ruby interpreter(s) installed but not running were listed and not counted." + Say ' They become exposed when something runs them; -CountInstalled counts them.' +} +Say '' +if ($script:nImpacted -gt 0) { Write-Output 'impacted'; exit 1 } +elseif ($script:nUnknown -gt 0) { Write-Output 'unknown'; exit 2 } +else { Write-Output 'not impacted'; exit 0 } diff --git a/CVE-2026-132825/windows/remote-ruby2shell.ps1 b/CVE-2026-132825/windows/remote-ruby2shell.ps1 new file mode 100644 index 0000000..4e4af9b --- /dev/null +++ b/CVE-2026-132825/windows/remote-ruby2shell.ps1 @@ -0,0 +1,86 @@ +<# +.SYNOPSIS + Run Detect-Ruby2Shell.ps1 on many Windows hosts over PowerShell remoting and + collect each host's verdict. Self-contained: it drives only this folder's + detector, nothing else. + +.DESCRIPTION + Nothing is installed on the targets: the detector's text is sent over the + remoting session and run in memory. Needs WinRM enabled on the targets and an + account that is a local administrator there (for full process coverage). + + Each host's full output is saved to \.txt. The per-host verdict + is the detector's last output line (their contract: impacted | not impacted | + unknown). An impacted / unknown / not impacted / error roll-up prints at the + end. Exit: 1 if any host is impacted, else 2 if any unknown/error, else 0. + +.EXAMPLE + .\remote-ruby2shell.ps1 -ComputerList hosts.txt -OutDir results +.EXAMPLE + .\remote-ruby2shell.ps1 -ComputerList hosts.txt -DetectArgs '-Quiet' + +.NOTES + Intune / Configuration Manager instead of remoting: deploy Detect-Ruby2Shell.ps1 + as a detection script. Its exit code fits: 1 = impacted (last line "impacted"). +#> +param( + [Parameter(Mandatory = $true)][string]$ComputerList, + [string]$OutDir = "results", + [string]$Script = (Join-Path $PSScriptRoot "Detect-Ruby2Shell.ps1"), + [int]$ThrottleLimit = 32, + [string]$DetectArgs = "" +) + +if (-not (Test-Path -LiteralPath $Script)) { throw "detector not found at $Script" } +$computers = @(Get-Content -LiteralPath $ComputerList | + ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') }) +if (-not $computers) { throw "no hosts in $ComputerList" } +New-Item -ItemType Directory -Force -Path $OutDir | Out-Null +$outFull = (Resolve-Path -LiteralPath $OutDir).ProviderPath + +$source = Get-Content -LiteralPath $Script -Raw +# The detector ends with 'exit'; inside a remote script block that only ends the block. +$block = [scriptblock]::Create("& { $source } $DetectArgs") + +$results = Invoke-Command -ComputerName $computers -ScriptBlock $block ` + -ThrottleLimit $ThrottleLimit -ErrorAction SilentlyContinue -ErrorVariable failed + +$verdict = @{} +foreach ($group in ($results | Group-Object PSComputerName)) { + $lines = @($group.Group | ForEach-Object { "$_" }) + [System.IO.File]::WriteAllLines((Join-Path $outFull "$($group.Name).txt"), [string[]]$lines) + $last = ($lines | Where-Object { $_ -match '\S' } | Select-Object -Last 1) + $verdict[$group.Name] = switch -regex ($last) { + '^\s*impacted\s*$' { 'impacted'; break } + '^\s*not impacted\s*$' { 'not impacted'; break } + '^\s*unknown\s*$' { 'unknown'; break } + default { 'unknown' } + } +} +foreach ($f in $failed) { + $name = "$($f.TargetObject)" + # Only connection failures name a target host. Errors written by the detector + # itself on a reachable host also land here; skip them so they do not + # replace that host's verdict. + if (-not $name -or $computers -notcontains $name) { continue } + $detail = ("$($f.Exception.Message)" -replace '\s+', ' ') + [System.IO.File]::WriteAllLines((Join-Path $outFull "$name.txt"), [string[]]@("error: remoting failed: $detail")) + $verdict[$name] = 'error' +} + +function Show-Bucket([string]$Label, [string]$Value) { + $hs = @($verdict.GetEnumerator() | Where-Object { $_.Value -eq $Value } | + ForEach-Object { $_.Key } | Sort-Object) + "{0,-14}{1}" -f ($Label + ':'), $(if ($hs) { $hs -join ', ' } else { '(none)' }) +} + +"Ruby2Shell (CVE-2026-132825) fleet detection ($($computers.Count) host(s))" +Show-Bucket 'impacted' 'impacted' +Show-Bucket 'unknown' 'unknown' +Show-Bucket 'not impacted' 'not impacted' +Show-Bucket 'error' 'error' +"per-host output in $OutDir\" + +if ($verdict.Values -contains 'impacted') { exit 1 } +if (($verdict.Values -contains 'unknown') -or ($verdict.Values -contains 'error')) { exit 2 } +exit 0 diff --git a/CVE-2026-132825/windows/tests/FakeRuby.cs b/CVE-2026-132825/windows/tests/FakeRuby.cs new file mode 100644 index 0000000..c8fc335 --- /dev/null +++ b/CVE-2026-132825/windows/tests/FakeRuby.cs @@ -0,0 +1,38 @@ +// FakeRuby.cs -- stand-in for ruby.exe in the detector's tests. Not Ruby, runs no Ruby code. +// +// ruby.exe -e "" prints the contents of fake-identity.txt next to the exe +// (default "ruby 3.4.12") and exits 0, like the detector's +// version probe expects. +// ruby.exe if load-enc.txt exists next to the exe, loads +// enc\iso_8859_1.so (any DLL copied under that name) so the +// module shows up in the process's module list; then sleeps +// until killed (at most 10 minutes). +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; + +static class FakeRuby +{ + [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] + static extern IntPtr LoadLibrary(string path); + + static int Main(string[] args) + { + string dir = AppDomain.CurrentDomain.BaseDirectory; + if (args.Length > 0 && args[0] == "-e") + { + string id = "ruby 3.4.12"; + string f = Path.Combine(dir, "fake-identity.txt"); + if (File.Exists(f)) id = File.ReadAllText(f).Trim(); + Console.Out.Write(id); + return 0; + } + if (File.Exists(Path.Combine(dir, "load-enc.txt"))) + { + LoadLibrary(Path.Combine(dir, "enc", "iso_8859_1.so")); + } + Thread.Sleep(TimeSpan.FromMinutes(10)); + return 0; + } +} diff --git a/CVE-2026-132825/windows/tests/Run-Tests.ps1 b/CVE-2026-132825/windows/tests/Run-Tests.ps1 new file mode 100644 index 0000000..055fb13 --- /dev/null +++ b/CVE-2026-132825/windows/tests/Run-Tests.ps1 @@ -0,0 +1,138 @@ +<# +.SYNOPSIS + Tests for Detect-Ruby2Shell.ps1. No Ruby needed: builds FakeRuby.cs with the + .NET Framework C# compiler into several "ruby.exe" stand-ins, starts them the + way an app server would be started, and checks the detector's exit code and + last line for each case. + +.DESCRIPTION + Everything is created under -WorkDir (default: .work next to this script) and + removed at the end unless -Keep is given. The stand-ins are killed after each + case. Exit 0 when every case passes, 1 otherwise. +#> +param( + [string]$WorkDir = (Join-Path $PSScriptRoot '.work'), + [switch]$Keep, + [switch]$Show, + [string]$Shell = "powershell.exe" +) +$ErrorActionPreference = 'Stop' +$detector = Join-Path (Split-Path -Parent $PSScriptRoot) 'Detect-Ruby2Shell.ps1' +$csc = Get-ChildItem "$env:WINDIR\Microsoft.NET\Framework64\v4*\csc.exe" -ErrorAction SilentlyContinue | Select-Object -Last 1 +if (-not $csc) { throw 'csc.exe (.NET Framework 4) not found' } + +if (Test-Path -LiteralPath $WorkDir) { Remove-Item -Recurse -Force -LiteralPath $WorkDir } +New-Item -ItemType Directory -Force -Path $WorkDir | Out-Null +$fake = Join-Path $WorkDir 'FakeRuby.exe' +& $csc.FullName /nologo /out:$fake (Join-Path $PSScriptRoot 'FakeRuby.cs') | Out-Null +if (-not (Test-Path -LiteralPath $fake)) { throw 'FakeRuby.exe did not build' } + +function New-Ruby([string]$Name, [string]$Identity, [switch]$LoadEnc) { + $d = Join-Path $WorkDir "rubies\$Name\bin" + New-Item -ItemType Directory -Force -Path $d | Out-Null + Copy-Item -LiteralPath $fake -Destination (Join-Path $d 'ruby.exe') + Set-Content -LiteralPath (Join-Path $d 'fake-identity.txt') -Value $Identity -Encoding ascii + if ($LoadEnc) { + New-Item -ItemType Directory -Force -Path (Join-Path $d 'enc') | Out-Null + Copy-Item -LiteralPath "$env:WINDIR\System32\version.dll" -Destination (Join-Path $d 'enc\iso_8859_1.so') + Set-Content -LiteralPath (Join-Path $d 'load-enc.txt') -Value '1' -Encoding ascii + } + return (Join-Path $d 'ruby.exe') +} +function New-App([string]$Name, [string[]]$Gems, [hashtable]$Files) { + $d = Join-Path $WorkDir "apps\$Name" + New-Item -ItemType Directory -Force -Path $d | Out-Null + $lock = @('GEM', ' remote: https://rubygems.org/', ' specs:') + @($Gems | ForEach-Object { " $_" }) + @('', 'PLATFORMS', ' ruby') + Set-Content -LiteralPath (Join-Path $d 'Gemfile.lock') -Value $lock -Encoding ascii + foreach ($k in $Files.Keys) { + $p = Join-Path $d $k + New-Item -ItemType Directory -Force -Path (Split-Path -Parent $p) | Out-Null + Set-Content -LiteralPath $p -Value $Files[$k] -Encoding ascii + } + return $d +} + +$vuln = New-Ruby 'v3412' 'ruby 3.4.12' +$vulnEnc = New-Ruby 'v3412enc' 'ruby 3.4.12' -LoadEnc +$fixed = New-Ruby 'v3413' 'ruby 3.4.13' +$eol = New-Ruby 'v322' 'ruby 3.2.9' +$jruby = New-Ruby 'jruby' 'jruby 3.4.2' + +$railsGems = @('rack (3.2.8)', 'railties (8.1.4)') +$appCfg = "module App`n class Application < Rails::Application`n config.load_defaults 8.1`n end`nend" +$apiCfg = "module App`n class Application < Rails::Application`n config.api_only = true`n end`nend" +$rails = New-App 'rails' $railsGems @{ 'config.ru' = 'run Rails.application'; 'config\application.rb' = $appCfg } +$railsApi = New-App 'rails-api' $railsGems @{ 'config.ru' = 'run Rails.application'; 'config\application.rb' = $apiCfg } +$railsDel = New-App 'rails-deleted' $railsGems @{ 'config.ru' = 'run Rails.application'; 'config\application.rb' = $appCfg + 'config\initializers\mo.rb' = 'Rails.application.config.middleware.delete Rack::MethodOverride' } +$sinGems = @('rack (3.2.8)', 'sinatra (4.2.2)') +$sinClassic = New-App 'sinatra-classic' $sinGems @{ 'app.rb' = "require 'sinatra'`nget('/') { 'ok' }" } +$sinModular = New-App 'sinatra-modular' $sinGems @{ 'app.rb' = "require 'sinatra/base'`nclass App < Sinatra::Base`nend"; 'config.ru' = 'run App' } +$rackMo = New-App 'rack-mo' @('rack (3.2.8)') @{ 'config.ru' = "use Rack::MethodOverride`nrun ->(env) { [200, {}, ['ok']] }" } +$rodGems = @('rack (3.2.8)', 'roda (3.110.0)', 'rodauth (2.51.0)') +$rodauth = New-App 'rodauth' $rodGems @{ 'config.ru' = 'run App.freeze.app' + 'app.rb' = "class App < Roda`n plugin :rodauth do`n enable :login, :logout, :create_account`n end`nend" } +$rodauthOff = New-App 'rodauth-noconfirm' $rodGems @{ 'config.ru' = 'run App.freeze.app' + 'app.rb' = "class App < Roda`n plugin :rodauth do`n enable :login, :create_account`n require_login_confirmation? false`n end`nend" } +$apiGuard = New-App 'rails-api-guard' $railsGems @{ 'config.ru' = 'run Rails.application'; 'config\application.rb' = $apiCfg + 'config\initializers\guard.rb' = 'Rails.application.config.middleware.insert_before Rack::MethodOverride, CharsetGuard' } +$apiReadd = New-App 'rails-api-readd' $railsGems @{ 'config.ru' = 'run Rails.application' + 'config\application.rb' = "module App`n class Application < Rails::Application`n config.api_only = true`n config.middleware.insert_after Rack::Runtime, Rack::MethodOverride`n end`nend" } +$notRails = New-App 'railties-not-rails' ($railsGems + 'sinatra (4.2.2)') @{ 'config.ru' = 'run App' + 'lib\app.rb' = "require 'sinatra/base'`nclass App < Sinatra::Base`nend" } +$sinDeep = New-App 'sinatra-deep' $sinGems @{ 'config.ru' = "require './app/web/main'`nrun Sinatra::Application" + 'app\web\main.rb' = "require 'sinatra'`nget('/') { 'ok' }" } +$empty = Join-Path $WorkDir 'apps\empty'; New-Item -ItemType Directory -Force -Path $empty | Out-Null +Set-Content -LiteralPath (Join-Path $empty 'job.rb') -Value 'sleep' -Encoding ascii + +$script:pass = 0; $script:fail = 0 +function Invoke-Case([string]$Name, [int]$Want, [string]$WantLast, [string]$Exe, [string]$Arg, [string[]]$DetectArgs) { + $proc = $null + if ($Exe) { $proc = Start-Process -FilePath $Exe -ArgumentList ('"{0}"' -f $Arg) -PassThru -WindowStyle Hidden; Start-Sleep -Milliseconds 900 } + try { + $out = & $Shell -NoProfile -ExecutionPolicy Bypass -File $detector @DetectArgs 2>&1 | ForEach-Object { "$_" } + $rc = $LASTEXITCODE + } finally { + if ($proc) { Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue } + } + $last = @($out | Where-Object { $_ -match '\S' } | Select-Object -Last 1) + $ok = ($rc -eq $Want) -and ("$last" -eq $WantLast) + if ($ok) { $script:pass++; $st = 'PASS' } else { $script:fail++; $st = 'FAIL' } + "{0} {1} rc={2} want={3} last='{4}'" -f $st, $Name, $rc, $Want, "$last" + if (-not $ok -or $Show) { $out | ForEach-Object { " $_" } } +} + +Invoke-Case 'rails non-API, running' 1 'impacted' $vuln (Join-Path $rails 'config.ru') @('-NoDisk') +Invoke-Case 'rails api_only, running' 2 'unknown' $vuln (Join-Path $railsApi 'config.ru') @('-NoDisk') +Invoke-Case 'rails middleware deleted' 2 'unknown' $vuln (Join-Path $railsDel 'config.ru') @('-NoDisk') +Invoke-Case 'sinatra classic, running' 1 'impacted' $vuln (Join-Path $sinClassic 'app.rb') @('-NoDisk') +Invoke-Case 'sinatra modular, running' 2 'unknown' $vuln (Join-Path $sinModular 'config.ru') @('-NoDisk') +Invoke-Case 'bare rack + MethodOverride' 1 'impacted' $vuln (Join-Path $rackMo 'config.ru') @('-NoDisk') +Invoke-Case 'rodauth create_account' 1 'impacted' $vuln (Join-Path $rodauth 'config.ru') @('-NoDisk') +Invoke-Case 'rodauth, login confirmation off' 2 'unknown' $vuln (Join-Path $rodauthOff 'config.ru') @('-NoDisk') +Invoke-Case 'api_only, insert_before anchor only' 2 'unknown' $vuln (Join-Path $apiGuard 'config.ru') @('-NoDisk') +Invoke-Case 'api_only, MethodOverride re-added' 1 'impacted' $vuln (Join-Path $apiReadd 'config.ru') @('-NoDisk') +Invoke-Case 'railties in lockfile, not Rails' 2 'unknown' $vuln (Join-Path $notRails 'config.ru') @('-NoDisk') +Invoke-Case 'classic sinatra in a subdirectory' 1 'impacted' $vuln (Join-Path $sinDeep 'config.ru') @('-NoDisk') +Invoke-Case '-Ruby counted with disk scan on' 2 'unknown' '' '' @('-NoProcesses', '-Ruby', $vuln) +Invoke-Case 'no app, running' 2 'unknown' $vuln (Join-Path $empty 'job.rb') @('-NoDisk') +Invoke-Case 'no app, encoding module loaded' 1 'impacted' $vulnEnc (Join-Path $empty 'job.rb') @('-NoDisk') +Invoke-Case 'rails non-API on fixed Ruby' 0 'not impacted' $fixed (Join-Path $rails 'config.ru') @('-NoDisk') +Invoke-Case 'rails on end-of-life Ruby 3.2' 1 'impacted' $eol (Join-Path $rails 'config.ru') @('-NoDisk') +Invoke-Case 'installed only, unpatched (-Ruby)' 2 'unknown' '' '' @('-NoProcesses', '-NoDisk', '-Ruby', $vuln) +Invoke-Case 'installed only, fixed (-Ruby)' 0 'not impacted' '' '' @('-NoProcesses', '-NoDisk', '-Ruby', $fixed) +Invoke-Case 'JRuby (-Ruby) is not affected' 0 'not impacted' '' '' @('-NoProcesses', '-NoDisk', '-Ruby', $jruby) +Invoke-Case 'no Ruby at all' 0 'not impacted' '' '' @('-NoProcesses', '-NoDisk') +# An unpatched ruby.exe found on PATH but not running is listed, not counted, +# unless -CountInstalled is given. (Another Ruby on this machine cannot change +# either expectation: idle ones are not counted, and the stand-in is unpatched.) +$savedPath = $env:PATH +$env:PATH = "$(Split-Path -Parent $vuln);$env:PATH" +Invoke-Case 'on PATH, unpatched: not counted' 0 'not impacted' '' '' @('-NoProcesses') +Invoke-Case 'on PATH, unpatched, -CountInstalled' 2 'unknown' '' '' @('-NoProcesses', '-CountInstalled') +$env:PATH = $savedPath +Invoke-Case 'quiet prints only the verdict' 1 'impacted' $vuln (Join-Path $rails 'config.ru') @('-NoDisk', '-Quiet') + +"passed=$($script:pass) failed=$($script:fail)" +if (-not $Keep) { Remove-Item -Recurse -Force -LiteralPath $WorkDir -ErrorAction SilentlyContinue } +if ($script:fail -gt 0) { exit 1 } else { exit 0 } diff --git a/README.md b/README.md index 7c35b1e..fd47685 100644 --- a/README.md +++ b/README.md @@ -19,3 +19,4 @@ Where possible, detections are written to be fleet-policy compatible - known una |---|---| | `CVE-2026-114938/` | JVMs exposed to the HotSpot x86-64 AVX-512 Base64 decode heap overwrite (CVE-2026-114938, JDK-8392044) | | `CVE-2026-123633.CVE-2026-123007/` | nginx exposed to the HTTP/2 flow-control overflow (CVE-2026-123007) or use-after-free (CVE-2026-123633) with HTTP/2 on, to the resolver use-after-free (CVE-2026-123634) with a `resolver` configured, to the HTTP/3 use-after-free (CVE-2026-121810) with a QUIC listener, or to the mail proxy use-after-free (CVE-2026-113425) with a mail server | +| `CVE-2026-132825/` | Ruby interpreters exposed to "Ruby2Shell", the string case-conversion heap overflow (CVE-2026-132825), when the application mounts `Rack::MethodOverride` (Rails unless `api_only`, classic-style Sinatra) or enables Rodauth account creation; also reports the six sibling advisories fixed in the same Ruby releases (4.0.10, 3.4.13, 3.3.14) | From 9c66d3ca5672f995e476095247c29354b64cb98c Mon Sep 17 00:00:00 2001 From: Diptendu Kar Date: Thu, 19 Nov 2026 11:09:33 -0500 Subject: [PATCH 2/2] Quote string assignments flagged by shellcheck (SC2100, SC2209) No behaviour change: quoting literal assignments only. Co-Authored-By: Claude Opus 5.5 --- CVE-2026-132825/linux/detect-ruby2shell.sh | 4 ++-- CVE-2026-132825/linux/k8s-exec-ruby2shell.sh | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CVE-2026-132825/linux/detect-ruby2shell.sh b/CVE-2026-132825/linux/detect-ruby2shell.sh index 783ed45..6469d13 100755 --- a/CVE-2026-132825/linux/detect-ruby2shell.sh +++ b/CVE-2026-132825/linux/detect-ruby2shell.sh @@ -55,8 +55,8 @@ set -u set -f FIX_40=10; FIX_34=13; FIX_33=14 # 4.0.10 / 3.4.13 / 3.3.14 -CVE=CVE-2026-132825 -GHSA=GHSA-34m4-m9fh-gqp5 +CVE="CVE-2026-132825" +GHSA="GHSA-34m4-m9fh-gqp5" SIBLINGS="GHSA-87fm-7w84-j2px:case conversion of multi-GB strings GHSA-7x2q-68qv-6p8x:Regexp compiled from untrusted input (double free) GHSA-3p8q-wmhx-vm2w:Regexp compiled from untrusted input (size overflow) diff --git a/CVE-2026-132825/linux/k8s-exec-ruby2shell.sh b/CVE-2026-132825/linux/k8s-exec-ruby2shell.sh index a704436..c329c8f 100755 --- a/CVE-2026-132825/linux/k8s-exec-ruby2shell.sh +++ b/CVE-2026-132825/linux/k8s-exec-ruby2shell.sh @@ -35,9 +35,9 @@ for line in $LIST; do printf '=== %s/%s/%s (node %s) ===\n' "$ns" "$pod" "$ctr" "$node" shx="" if kubectl exec -n "$ns" "$pod" -c "$ctr" -- sh -c 'command -v bash >/dev/null 2>&1' >/dev/null 2>&1; then - shx=bash + shx="bash" elif kubectl exec -n "$ns" "$pod" -c "$ctr" -- sh -c 'true' >/dev/null 2>&1; then - shx=sh + shx="sh" fi if [ -n "$shx" ]; then out=$(kubectl exec -i -n "$ns" "$pod" -c "$ctr" -- "$shx" -s -- -q < "$SCRIPT" 2>/dev/null)