Breaking Into Databases: Methods Hackers Use

When a database breach reaches the news, the story often starts with stolen records. The actual failure may have happened much earlier: an application assembled a query from untrusted input, accepted a request for another customer’s invoice, or connected to the database using credentials powerful enough to read every tenant’s records. Those are different trust failures. Fixing one does not automatically fix the others.

That distinction is essential for anyone responsible for database-backed websites and APIs. A parameterized SQL statement can safely treat user input as data while still returning a record the current user has no right to see. An authorization check can correctly identify a user while the application’s database account retains unnecessary administrative permissions. A protected network path can still carry an overprivileged, compromised application request. The useful security review follows the request across these boundaries and records what each layer actually enforces.

Trace the request before blaming the database

Imagine a fictional freight company, Marlow Freight, whose customers can retrieve shipping invoices through a web portal. A customer authenticates, opens an invoice and receives its line items. Behind that simple action are several decisions: the portal identifies the session, decides which invoice the customer may view, builds a query, uses a service identity to contact the database, and returns selected fields. Failure at any stage can expose records, even if the database engine itself is fully patched.

It helps to identify the three main questions separately. Query safety asks whether request data can change the structure of an instruction sent to the database. Object authorization asks whether the identified user has permission to access the requested invoice and its properties. Database privileges ask how much the application account could do if the application made a mistake or was compromised. These controls are complementary, not alternative answers to the same question.

The original article correctly recommends prepared statements and least privilege, but does not connect them to a concrete record-level authorization decision. OWASP’s SQL injection prevention guidance makes the first boundary precise: parameterized queries keep command structure separate from bound values. This reduces the risk of injected input becoming executable SQL. It does not decide whether the bound invoice identifier belongs to the person making the request.

Prevent injection without confusing validation with parameterization

Injection is fundamentally a query-construction failure. If an application concatenates a search value into executable SQL, the database may interpret characters from the request as part of the command. Defenders should use prepared statements and bound parameters where supported, with well-defined query templates. Stored procedures can also be appropriate, but a stored procedure that constructs unsafe dynamic SQL is not protected merely because it is stored inside the database.

A useful code-review question is whether a value is bound as data or changes the shape of the query. For instance, the illustrative statement SELECT status FROM invoices WHERE invoice_id = ? AND tenant_id = ? has two value placeholders. The authorized tenant identifier must come from a server-trusted session or policy decision, not simply from a second client-supplied field. The example is conceptual; it is not a substitute for checking an actual database driver’s binding behavior and the application’s access rules.

There are practical limits to binding. Table names, column names and sort directions commonly cannot be parameterized as ordinary values. OWASP’s injection prevention guidance recommends mapping those identifiers to small, predefined allowlists or redesigning the query. General input validation is still useful for business rules and data quality, but it is not a safe replacement for bound values. Escaping every input string is a fragile last resort, not the default design.

The right regression test uses an authorized test application and known, harmless records. Confirm that unexpected data is handled as data rather than code, that invalid sort or field requests are rejected, and that an error does not reveal query text or sensitive values. Passing those tests is evidence about specified code paths only. It does not establish that every query builder, stored procedure or import job uses the same controls.

Check ownership of every record and property returned

Even perfect parameterization cannot enforce a business relationship the application never checks. OWASP identifies broken object-level authorization as an API risk: endpoints receiving an object identifier must verify that the active principal may perform the requested operation on that particular object. A user being logged in, or the identifier having an unpredictable format, is not proof of permission.

At Marlow Freight, imagine Customer A is entitled to its own invoices but not Customer B’s. A request for B’s invoice must be denied even when its identifier is syntactically valid and a prepared statement retrieves the correct row. The application should derive the customer’s authorized scope from reliable server-side context and enforce it before returning the record. Review both read and write paths: viewing an invoice, exporting its PDF, changing its delivery address and deleting a draft can require different authorizations.

Object-level checks also need a property-level companion. OWASP’s object-property authorization guidance warns that broad serialization can expose internal fields and automated binding can let a user modify attributes reserved for administrators. An authorized view of an invoice total need not include payment routing details, audit flags or internal notes. Use explicit response schemas and permitted update fields, then compare outputs with the actual role and task.

The OWASP authorization review principles reinforce two decisions: deny access when permission is not established and verify authority on each request rather than trusting a prior screen or client-side restriction. Negative tests should use only owned test records and preapproved test accounts. A valid result is a documented denial with no unauthorized data in the response, not merely a warning message alongside leaked fields.

Boundary Question to verify What a successful result does not prove
SQL construction Are client values bound as data and unsupported identifiers mapped to approved choices? The requesting user is permitted to see the resulting row
Object authorization May this user read or change this precise record and operation? Every field inside the object should be returned or accepted for update
Property authorization Does the response or mutation include only approved attributes? The application’s database account has limited privileges
Database account Can this service identity perform only required SQL operations on required objects? The browser session is authentic or the API business rules are correct

Contain damage with narrow database roles and row policies

Applications should not connect as a database administrator simply because broad permission makes development easier. OWASP’s database hardening guidance recommends restricting network access, encrypting database connections, authenticating clients and using separate accounts with the permissions their services actually require. A public-facing browser or mobile client should normally reach an application API rather than receiving direct backend database credentials.

Database privileges deserve review at the real object level. The PostgreSQL 18 GRANT reference distinguishes privileges on tables, columns, sequences and other objects from membership in database roles. A reporting service that needs to read approved reporting views should not automatically gain write access to customer tables, schema modification rights, or a powerful shared owner account. Actual permissions depend on role membership, inherited grants, the PUBLIC role and the engine’s configuration.

Row-level security can add a database-side boundary in supported systems. PostgreSQL’s row security documentation describes policies that restrict which rows a role can view or change. Enabling row security with no applicable policy is generally default-deny for affected queries, but there are important exceptions: superusers and roles with BYPASSRLS bypass policies, and table owners normally do too unless explicitly made subject to them. Using one powerful pooled database role for every tenant can also undermine a policy based on database identity if the application has not designed trustworthy tenant context.

These mechanisms should be tested together rather than treated as labels on an architecture diagram. Marlow’s reviewer can document the application identity, permitted tables or views, expected tenant-scoped reads, forbidden updates, and privileged maintenance operations kept outside the web service. A row policy is not a substitute for verifying API authorization, and an API check is not an excuse to retain administrator credentials in a general-purpose service.

Secure the connection and credentials without assuming that TLS solves access control

An exposed database listener adds a different route to compromise. Network policy should make database services reachable only by the approved application, administration and recovery systems. The application-to-database connection should use authenticated encryption as required by the deployment, and the client should validate the database server certificate. Encrypting this hop protects data in transit, but it will faithfully transport an unauthorized query if the application or service account allows one.

Credentials stored in code repositories, build logs or long-lived configuration files can outlive the people and systems that originally needed them. OWASP’s secrets lifecycle guidance describes controlled provisioning, short-lived credentials where feasible, rotation, revocation and auditable access. Rotation is not sufficient by itself: a leaked static credential remains useful until the backing database rejects it, and a newly issued credential with unnecessarily broad rights remains dangerous.

Different services should have different credentials or trusted identities so that one compromised application does not automatically grant access to another application’s data. Maintenance access should be time-bounded and attributable. Review actual network rules and login records rather than inferring isolation merely because a database uses a private address or its administrator interface is not linked from a website.

Retain evidence without creating a second data breach in the logs

When an application unexpectedly reads many rows, the investigation needs to distinguish an approved batch job from a stolen session, a failed authorization check and a compromised database role. Useful records include the request and correlation identifier, authenticated principal or service, authorization decision, affected resource class, database account, operation type, timestamps and system owner. Store these under access controls, with defensible retention and integrity protections.

Logging the entire SQL statement with literal secrets and every returned record may create a second disclosure channel. The OWASP logging guidance cautions against recording passwords, session identifiers, access tokens, sensitive personal data and database connection strings directly. Prefer the narrow fields necessary for incident reconstruction, masking or omitting sensitive values and controlling log access. Evidence must be trustworthy without unnecessarily reproducing the data at risk.

Backup and recovery are separate from breach prevention. PostgreSQL’s backup and restore documentation distinguishes SQL dumps, file-system backups and continuous archiving with point-in-time recovery. Each has different assumptions and recovery capabilities. A backup that has never been restored in an approved test is not proof that the service can recover within its business target; restored data should also be protected from the same authorization mistake that affected production.

Review evidence Owner’s decision Limitation to record
Query template and bound parameters Does untrusted input remain data? Only the exercised query paths have been checked
Two approved test tenants and role-scoped records Are cross-tenant reads and writes denied, including exports? Other endpoints or property mutations may need separate tests
Effective database role grants and policies Can an application identity access only necessary objects? Ownership, inherited grants and bypass roles can alter enforcement
Redacted logs, timestamps and correlation keys Can the team reconstruct a suspicious request safely? Uncollected fields or overwritten logs leave uncertainty
Isolated recovery exercise Can trusted data and access policy be restored together? A successful restore does not prove the original flaw was repaired

Review one business path all the way through

For Marlow Freight, the useful security exercise begins with a clearly bounded invoice-view workflow. The team identifies who owns the endpoint, which customers may view invoices, what fields should appear, which prepared statements execute and which database role serves the request. It then uses non-sensitive, owned test data to demonstrate both allowed access and appropriate denial across tenants and operations.

Next, the reviewers inspect privileges and transport. They verify the effective grants and any row policies against the role actually used in production, confirm credential handling and check whether an unnecessary network path can reach the database listener. They examine redacted evidence from the application and database and make sure a temporary test account has not been left with persistent permissions. No live Marlow system, customer record, database configuration or exploit has been tested here; the case is a design exercise.

If an issue is found, its disposition should be specific. Was the SQL structure controllable by input? Did the server skip a business authorization check? Could the database account read too much? Were audit events missing or contaminated with secrets? An investigation that merely concludes “the database was vulnerable” does not give an engineer enough information to repair the failure or an owner enough evidence to accept the residual risk.

The defensible outcome is a smaller breach path, not a longer tool list

Database security is often discussed as a catalogue of hacker techniques: injection, passwords, exposed ports, privilege escalation and data theft. Those mechanisms matter, but a practical review is stronger when each technique points to an enforceable boundary and evidence of the boundary’s behavior. Prepared queries prevent one class of command manipulation; per-object authorization enforces who may use data; narrow database roles constrain the consequences of an application failure; controlled credentials, network rules, logs and recoverable backups complete the picture.

No single layer certifies a database-backed application as safe. A successful test of SQL binding does not validate tenant ownership, and a clean permissions list does not prove that a service’s business logic is correct. Record the original question, what was examined, what was deliberately not examined and who must approve the next change. That turns an abstract story about hackers entering a database into a repeatable way for engineers and service owners to close the doors that actually matter.

img