At the end of September 2026, Polish SaaS invoicing platform Fakturownia reported a security incident involving unauthorized access to its production infrastructure. The company confirmed potential exposure of password hashes, session tokens, API keys, bank account details, and application system secrets. In response, their engineering team immediately rotated all credentials and provisioned clean server infrastructure.
Online discussion quickly zeroed in on the technical mechanics. The attacker, operating under the handle Fingerprint, claimed to have exploited a time oracle to extract the Rails master.key, forged session cookies, and achieved remote code execution while declaring the exfiltration of 6 TB of customer invoices (a claim noted as unconfirmed by Sekurak). Independent security researchers at Zaufana Trzecia Strona analyzed the incident, proposing that the timing oracle likely pointed to a time-based blind SQL injection, and noted a subsequent vendor hardening patch addressing PDF generation.
Whether the entry point in that specific case was SQL injection or a server-side document renderer, both threat vectors are classic, documented risks in Ruby on Rails applications. When chained together, an unauthenticated input flaw and a misconfigured cookie serializer can escalate into complete host compromise.
Consider a typical invoicing app managing an Invoice model with sortable customer tables, automated email receipts, and a PDF download endpoint.
What does the attack chain look like in a Rails app?
The exploit chain described by the attacker relies on three sequential transitions. Eliminating any single link halts the compromise.
The attack starts with an input vulnerability that leaks internal state. In a time-based blind SQL injection, the application returns no database errors or query results in HTTP responses. Instead, the database evaluates conditional logic such as PostgreSQL pg_sleep(0.5). Measuring HTTP response latency byte by byte allows an automated script to reconstruct database contents or server files.
That extracted secret exposes Rails's session signing secret (secret_key_base). If the database role has file-reading permissions, or if an alternative vulnerability such as an unescaped PDF renderer reads config/master.key, the attacker retrieves the key from disk.
With secret_key_base in hand, the attacker can forge session cookies. By default, ActionDispatch::Cookies signs or encrypts session cookies using a key derived from this secret with PBKDF2. When an application still uses the legacy Marshal cookie serializer, loading the forged cookie triggers object deserialization and gadget chains that execute arbitrary system commands.
If the entry point instead originates in PDF generation, an unescaped field inside an HTML-to-PDF template allows an attacker to inject an iframe pointing to file:///app/config/master.key or trigger server-side request forgery against cloud metadata endpoints.
Can SQL injection still happen in ActiveRecord?
ActiveRecord parameterizes queries when developers pass arguments as hashes or query placeholders. The risk re-emerges whenever unvalidated strings from params reach raw SQL fragments.
Since Rails 6.0, methods like order and pluck raise ActiveRecord::UnknownAttributeReference when passed non-column strings. A frequent mistake in invoicing tables is bypassing this protection with Arel.sql:
# Vulnerable: Arel.sql marks untrusted input as trusted SQL
Invoice.where(account_id: current_account.id).order(Arel.sql(params[:sort]))
# Also vulnerable: direct string interpolation
Invoice.where("number LIKE '%#{params[:q]}%'")
Methods including order, pluck, group, having, joins, and find_by_sql accept SQL fragments directly. If an input contains string interpolation, ActiveRecord cannot sanitize the underlying command.
The defense requires strict parameterization for query values and rigid allowlists for column identifiers and directions:
class InvoicesController < ApplicationController
ALLOWED_SORTS = {
"newest" => { issued_on: :desc },
"oldest" => { issued_on: :asc },
"amount" => { total_cents: :desc }
}.freeze
def index
sort_order = ALLOWED_SORTS.fetch(params[:sort], { id: :desc })
@invoices = current_account.invoices
.where("number ILIKE ?", "%#{Invoice.sanitize_sql_like(params[:q].to_s)}%")
.order(sort_order)
end
end
The allowlist ensures that unknown sort keys safely default to a predictable sort order without touching database query construction. The sanitize_sql_like helper escapes % and _ characters to prevent wildcard manipulation.
Add static analysis to your continuous integration pipeline by running bundle exec brakeman -A -z. While Brakeman flags common unescaped queries, it cannot replace architectural reviews of complex query builders.
Why should the database role matter for a web app?
In Rails applications, secret_key_base lives in environment variables or config/credentials.yml.enc rather than database tables. For an SQL injection vulnerability to leak server keys, the database role itself must have permissions to read operating system files from the host filesystem.
PostgreSQL restricts filesystem access through superuser privileges and predefined roles such as pg_read_server_files and pg_execute_server_program. When an application connects using an overly permissive database role, an attacker exploiting SQL injection can read local configuration files directly through database functions.
Verify your production connection role directly in PostgreSQL:
SELECT rolname, rolsuper, rolcreaterole, rolcreatedb
FROM pg_roles
WHERE rolname = current_user;
SELECT r.rolname AS granted_role
FROM pg_auth_members m
JOIN pg_roles r ON r.oid = m.roleid
WHERE m.member = (SELECT oid FROM pg_roles WHERE rolname = current_user);
The application user must return false across all administrative columns in the first query, and the second query must not list pg_read_server_files, pg_write_server_files, or pg_execute_server_program. Run database migrations under a dedicated administrative role during deployments, and restrict daily application connections to least-privilege operations.
Is my Rails app still deserializing cookies with Marshal?
This link turns cookie forgery into remote code execution. Rails controls session deserialization through config.action_dispatch.cookies_serializer.
In the Rails codebase within ActionDispatch::Cookies, if cookies_serializer is not explicitly configured, Rails falls back to :marshal. Applications running with load_defaults below 7.0 that lack an explicit initializer remain vulnerable to Marshal.load exploitation.
Marshal.load reconstructs arbitrary Ruby objects from byte sequences. Because object instantiation in Ruby can trigger callbacks and method dispatches across loaded gems, attackers chain these behaviors into gadget chains that execute system commands. Pure JSON serialization eliminates this vulnerability because JSON parses exclusively into strings, numbers, arrays, and hashes.
Comparing how Marshal and JSON deserialize objects:
require "json"
Invoice = Struct.new(:number, :total_cents)
invoice = Invoice.new("FV/2026/09/17", 12_300)
from_marshal = Marshal.load(Marshal.dump(invoice))
from_json = JSON.parse(JSON.generate(invoice.to_h))
puts from_marshal.class # Invoice
puts from_json.class # Hash
Marshal instantiates a concrete class instance, while JSON produces standard Ruby data structures without invoking class lifecycles.
Check your application configuration in the terminal:
bin/rails runner 'p Rails.application.config.action_dispatch.cookies_serializer'
If the command returns :marshal or nil, configure JSON serialization immediately:
# config/initializers/cookies_serializer.rb
Rails.application.config.action_dispatch.cookies_serializer = :json
Do not rely on :hybrid mode for security. While :hybrid writes new cookies as JSON, it still parses incoming cookies with Marshal.load and remains vulnerable to deserialization gadgets. Switching to :json requires that session data contain only primitive types. Symbols stored in cookies will deserialize as strings.
Setting :json eliminates remote code execution, though session hijacking remains possible if secret_key_base is leaked. An attacker possessing secret_key_base can still sign a JSON payload containing {"user_id": 1} and impersonate an administrator.
How do I rotate secret_key_base after a leak?
Rails documentation describes config.action_dispatch.cookies_rotations for migrating cookie encryption digests or keys without user disruption:
# Warning: Do not use this pattern following a confirmed secret leak!
Rails.application.config.action_dispatch.cookies_rotations.tap do |cookies|
cookies.rotate :signed, old_derived_secret
end
Cookie rotations do not resolve a leak because the helper continues to accept cookies signed with the old secret. Because the attacker holds that exact key, the rotation mechanism continues to authenticate forged attacker sessions.
When secret_key_base is compromised, follow the hard replacement procedure outlined in the Rails security guide. Generate a fresh secret and replace the production value:
bin/rails secret
EDITOR=vim bin/rails credentials:edit --environment production
Hard replacement immediately invalidates active user sessions and requires users to log in again. Encrypted cookies and signed Active Storage attachment tokens will also reset.
Rotate auxiliary credentials accessible from that host: config/master.key, production database passwords, customer API tokens, and webhook secrets. If an attacker executed arbitrary code on a host, do not try to clean compromised hosts in place. Provision completely new virtual machines or container instances from verified base images.
Verify that sensitive key files were never committed to revision control:
git log --all --full-history -- "master.key" "**/master.key"
Any commit history for those files means the key was exposed in every clone of the repository and must be revoked immediately.
How do I stop a PDF generator from leaking files?
Server-side HTML-to-PDF rendering engines behave like headless web browsers. If unsanitized user inputs, such as billing names or custom invoice line items, reach templates as unescaped markup, an attacker can manipulate the rendering engine into accessing internal files or private networks.
An attacker can supply an HTML payload containing <iframe src="file:///app/config/master.key"></iframe>. When the rendering engine compiles the invoice, it embeds the file contents directly into the resulting PDF document.
Preventing this requires escaping template inputs strictly. Audit PDF view templates for calls to raw, html_safe, <%==, or lenient sanitize filters so that user-supplied text remains escaped.
Renderer configuration and engine selection introduce additional security risks. The popular wkhtmltopdf utility was archived on January 2, 2023, and receives no security updates. Wrappers like wicked_pdf and PDFKit inherit these risks. In older wicked_pdf setups, developers often enabled enable_local_file_access = true to load invoice logos, which exposed the server to arbitrary file disclosure:
# config/initializers/wicked_pdf.rb
WickedPdf.configure do |config|
config.disable_local_file_access = true
end
When using Chromium-based tools like Grover, keep allow_file_uris and allow_local_network_access disabled. The second option only covers localhost and exists since Puppeteer 24.16, so it does not protect private networks on its own. Because headless Chrome resolves external network requests, configure Puppeteer request interception to block connections to RFC 1918 private subnets and the cloud metadata IP address 169.254.169.254.
You can also avoid HTML rendering engines altogether. Libraries such as Prawn and HexaPDF generate documents through Ruby method calls without a browser runtime, removing file inclusion and request forgery vectors:
require "prawn"
def invoice_pdf(invoice)
Prawn::Document.new do |pdf|
pdf.text "Invoice #{invoice.number}", size: 18, style: :bold
pdf.move_down 12
pdf.text invoice.buyer_name
pdf.text invoice.notes.to_s
end.render
end
For high-volume production deployments, isolate document generation inside a dedicated worker container. This container should run without application source code, config/master.key, or credentials (DATABASE_URL, SECRET_KEY_BASE) in its environment.
Do rate limits and query timeouts stop blind SQL injection?
A time-based blind SQL injection requires hundreds of sequential requests to extract data character by character. Rate limiting and query timeouts slow down that extraction and produce actionable logs, though they do not replace parameterized queries.
Implementing IP-based request throttling with Rack::Attack introduces latency and generates alert telemetry:
# config/initializers/rack_attack.rb
Rack::Attack.throttle("invoices/ip", limit: 300, period: 5.minutes) do |req|
req.ip if req.path.start_with?("/invoices")
end
Database query limits in config/database.yml prevent runaway resource exhaustion:
# config/database.yml
production:
adapter: postgresql
variables:
statement_timeout: 5000
While a five-second statement_timeout stops long-running denial of service queries, it cannot prevent an extraction script measuring 200-millisecond delays. Parameterized queries are the permanent fix.
Moving session storage from client-side cookies to a centralized backend like Redis via config.session_store :cache_store prevents attackers from delivering serialized session structures to the application layer. The client retains only a random session identifier while the server stores session state in Redis.
30-minute security checklist for your Rails repository
- Run
bin/rails runner 'p Rails.application.config.action_dispatch.cookies_serializer'and confirm it returns:json. - Inspect
config/initializers/cookies_serializer.rbto ensure:hybridmode is not active in production. - Query
pg_rolesin PostgreSQL to verify the application database user lacks superuser status andpg_read_server_files. - Audit database queries for unescaped string interpolation in
where,order(Arel.sql()),pluck, andfind_by_sql. - Add
brakemanandbundle-auditsecurity scans to your pull request CI workflow. - Run
git log --all --full-history -- "master.key" "**/master.key"to verify secrets were never checked into git history. - Audit PDF templates for
raw,html_safe, or unescaped user inputs. - Enforce
disable_local_file_access = truein legacy PDF generators or migrate to Prawn. - Isolate background PDF workers into unprivileged containers lacking application credentials.
- Set
statement_timeoutinconfig/database.ymland configure endpoint rate limits inRack::Attack.
FAQ
Does :json cookie serialization prevent session forgery?
No. JSON serialization prevents remote code execution by disallowing Ruby object instantiation during cookie parsing. An attacker with access to secret_key_base can still forge signed JSON session cookies to impersonate arbitrary users.
Is :hybrid cookie serializer safe?
No. The :hybrid setting is designed solely as a migration bridge. While it writes outgoing cookies in JSON format, it still processes incoming cookies using Marshal.load and remains vulnerable to gadget chains.
Where is secret_key_base stored in Rails?
In production, Rails retrieves secret_key_base from the SECRET_KEY_BASE environment variable or decrypts config/credentials.yml.enc using config/master.key or RAILS_MASTER_KEY. Rails does not store this secret in database tables unless custom application code explicitly writes it there.
Is wicked_pdf safe to use in 2026?
The underlying wkhtmltopdf binary was archived in January 2023 and no longer receives maintenance or security patches. While disabling local file access mitigates immediate file disclosure risks, teams should migrate production document generation to Prawn, HexaPDF, or isolated browser-based services.
Happy hardening!
