new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

OWASP Cheat Sheets · all subjects

abuse_cases/validation

149 notes in this subject, read out of this brain and free to use. This is page 2 of 3.

GraphQL batching attack mitigation: object rate limiting

To mitigate GraphQL batching attacks, create a code-level rate limit on how many objects that callers can request. The backend would track how many different object instances the caller has requested, so they will be blocked after requesting too many objects even if they batch the object requests in a single network call. This replicates a network-level rate limit that a WAF or other tool would do.

CORS Origin header not sufficient for access control

Do not rely only on the Origin header for Access Control checks. Browser always sends this header in CORS requests but it may be spoofed outside the browser. Application-level protocols should be used to protect sensitive data.

Web Messaging postMessage origin parameter

When posting a message with postMessage, explicitly state the expected origin as the second argument rather than using '*' to prevent sending the message to an unknown origin after a redirect or other changes to the target window's origin.

Web Messaging receiving page validation

The receiving page should always check the origin attribute of the sender to verify data is originating from the expected location, and perform input validation on the data attribute of the event to ensure it is in the desired format.

Web Messaging origin validation strict matching

Check the origin properly to match exactly the FQDN(s) expected. Using indexOf to match part of a domain like 'if(message.origin.indexOf(".owasp.org")!=-1)' is insecure because 'owasp.org.attacker.com' will match. Perform exact matching instead.

Web Messaging never evaluate as code

Never evaluate passed messages as code via eval() or insert into page DOM via innerHTML, as this creates a DOM-based XSS vulnerability. Instead of element.innerHTML=data, use element.textContent=data.

CORS Access-Control-Allow-Origin configuration

Allow only selected, trusted domains in the Access-Control-Allow-Origin header. Prefer allowing specific domains over blocking or allowing any domain. Do not use the '*' wildcard nor blindly return the Origin header content without any checks. Ensure that URLs responding with 'Access-Control-Allow-Origin: *' do not include sensitive content that might aid attackers.

CORS XMLHttpRequest.open URL validation

Validate URLs passed to XMLHttpRequest.open. Current browsers allow these URLs to be cross domain, which can lead to code injection by a remote attacker. Pay extra attention to absolute URLs.

CORS pre-flight OPTIONS request

While the Fetch Standard recommends a pre-flight request with the OPTIONS verb, current implementations might not perform this request. It is important that 'ordinary' GET and POST requests perform any access control necessary.

CORS mixed content bug prevention

Discard requests received over plain HTTP with HTTPS origins to prevent mixed content bugs.

Server-Sent Events EventSource URL validation

Validate URLs passed to the EventSource constructor, even though only same-origin URLs are allowed. Process messages as data and never evaluate the content as HTML or script code. Always check the origin attribute of the message to ensure it is coming from a trusted domain using an allow-list approach.

Geolocation API requires user permission

The Geolocation API requires that user agents ask for the user's permission before calculating location. Whether or how this decision is remembered varies from browser to browser. For privacy reasons, it is recommended to require user input before calling getCurrentPosition or watchPosition.

Web Workers no user-supplied scripts

Web Workers are allowed to use XMLHttpRequest for in-domain and Cross Origin Resource Sharing requests. While Web Workers do not have access to the DOM of the calling page, malicious Web Workers can use excessive CPU for computation leading to Denial of Service or abuse CORS for further exploitation. Ensure code in all Web Workers scripts is not malevolent. Do not allow creating Web Worker scripts from user supplied input.

Web Workers message validation

Validate messages exchanged with a Web Worker. Do not try to exchange snippets of JavaScript for evaluation via eval() as that could introduce a DOM Based XSS vulnerability.

Sandboxed iframe restrictions

Use the sandbox attribute of an iframe for untrusted content. When the sandbox attribute is set, the following restrictions are active: all markup is treated as being from a unique origin, all forms and scripts are disabled, all links are prevented from targeting other browsing contexts, all features that trigger automatically are blocked, and all plugins are disabled.

Sandboxed iframe fine-grained control

The sandbox attribute value enables fine-grained control over iframe capabilities. In old versions of user agents where this feature is not supported, the attribute will be ignored. Use this feature as an additional layer of protection or check if the browser supports sandboxed frames and only show untrusted content if supported.

IDOR mitigation: scope database queries to current user

When looking up objects based on primary keys, use datasets that users have access to. For example, in Ruby on Rails, use @project = @current_user.projects.find(params[:id]) instead of @project = Project.find(params[:id]). The first approach only searches projects related to the current user, while the vulnerable approach searches all projects.

IDOR defense-in-depth: use complex random identifiers

As a defense-in-depth measure to complement access control checks, replace enumerable numeric identifiers with more complex, random identifiers. Options include adding a column with random strings to the database table and using those strings in URLs instead of numeric primary keys, or using UUIDs or other long random values as primary keys. Avoid encrypting identifiers as it can be challenging to do so securely.

Complex identifiers reduce guessing but do not eliminate need for access control

Using complex identifiers like GUIDs can make it practically impossible for attackers to guess valid values through enumeration. However, even with complex identifiers, access control checks are essential. If attackers obtain URLs for unauthorized objects through other means, the application should still block their access attempts.

IDOR mitigation: implement object-level authorization checks

To mitigate IDOR, implement access control checks for each object that users try to access. Verify the user's permission every time an access attempt is made. Implement this structurally using the recommended approach for your web framework.

IDOR mitigation: avoid exposing identifiers in URLs and POST bodies

Avoid exposing identifiers in URLs and POST bodies if possible. Instead, determine the currently authenticated user from session information. When using multi-step flows, pass identifiers in the session to prevent tampering.

LDAP search filter special characters requiring escape

In LDAP search filters, the following characters must be escaped according to RFC4515: asterisk, parentheses, backslash, and NUL (null character).

Java allowlist LDAP input validation

Use allowlist validation to restrict input to valid characters before constructing LDAP queries. Example: if (!userSN.matches("[\\w\\s]*")) { throw new IllegalArgumentException("Invalid input"); } This ensures the filter string contains only valid characters.

LDAP DN special characters requiring escape

In LDAP Distinguished Names, the following characters must be escaped: backslash, hash, plus, less than, greater than, comma, semicolon, double quote, equals sign, and leading or trailing spaces. These are JNDI metacharacters and LDAP special characters that must be excluded from allowlists.

LDAP DN allowed characters not requiring escape

Characters that are allowed in Distinguished Names and do not need to be escaped include: asterisk, parentheses, period, ampersand, hyphen, underscore, square brackets, backtick, tilde, pipe, at sign, dollar sign, percent sign, caret, question mark, colon, curly braces, exclamation mark, and apostrophe.

File upload validation: mime types and size

Always validate file type and size in Laravel to prevent storage DOS attacks and remote code execution. Use validation rules such as 'photo' => 'file|size:100|mimes:jpg,bmp,png' to restrict file uploads to specific MIME types and maximum file size in kilobytes.

Use basename() to strip directory traversal from uploaded filenames

When storing uploaded files with user-provided filenames, use the PHP basename() function to strip directory information. This prevents directory traversal attacks where filenames like '../2/filename.pdf' could upload to unintended directories. Example: storeAs(auth()->id(), basename($request->input('filename')))

Avoid processing ZIP and XML file uploads

If possible, avoid processing ZIP or XML file uploads. XML files expose applications to XXE attacks and billion laughs attacks. ZIP files expose applications to zip bomb DOS attacks that exhaust disk space.

Use basename() to prevent path traversal in file downloads

When allowing users to download files by filename, use the PHP basename() function to strip directory information from user input. This prevents path traversal attacks where filenames like '../../.env' could expose sensitive files. Example: response()->download(storage_path('content/').basename($request->input('filename')))

Validate redirect URLs to prevent open redirection

Do not allow user input to dictate redirect destinations. Open redirection vulnerabilities enable phishing attacks by redirecting users to attacker-controlled sites. Validate and whitelist redirect URLs or use safe redirect methods.

Enable VerifyCsrfToken middleware in web middleware group

Add \App\Http\Middleware\VerifyCsrfToken::class to the 'web' middleware group in App\Http\Kernel class to enable CSRF protection. This middleware must be present for all state-changing requests to be protected against CSRF attacks.

Use @csrf Blade directive in POST forms for CSRF token

Include the @csrf Blade directive in all POST request forms to generate hidden CSRF input token fields. This is equivalent to <input type="hidden" name="_token" value="{{ csrf_token() }}" />.

Setup X-CSRF-Token header for AJAX requests

For AJAX requests in Laravel, configure the X-CSRF-Token header instead of relying on form-based CSRF tokens. Laravel provides built-in support for this header in CSRF protection.

CSRF middleware: exclude only stateless routes

Use the $except variable in the CSRF middleware class to exclude routes from CSRF protection. Only exclude stateless routes such as APIs or webhooks. Excluding other routes from CSRF protection may result in CSRF vulnerabilities.

Escape shell commands using escapeshellcmd and escapeshellarg

When executing shell commands with user input via exec() or similar functions, use escapeshellcmd() and/or escapeshellarg() PHP functions to properly escape the input. This prevents command injection vulnerabilities.

Never unserialize, eval, or extract untrusted user input

Avoid passing untrusted user input data to dangerous PHP functions including unserialize(), eval(), and extract(). These functions can execute arbitrary code or modify variables in unexpected ways, leading to object injection, code injection, and variable hijacking vulnerabilities.

Rate limiting: throttle middleware with requests per minute

Apply the throttle middleware directly to routes using the syntax 'throttle:X,Y' where X is the number of requests and Y is the time period in minutes. Example: ->middleware('throttle:10,1') allows 10 requests per 1 minute.

Rate limiting: apply throttle to route groups

Apply rate limiting to multiple routes using Route::middleware('throttle:20,1')->group(). This applies the same rate limit (20 requests per 1 minute) to all routes within the group.

Custom rate limiter using RateLimiter::for()

Define custom rate limiting rules using RateLimiter::for() in RouteServiceProvider with Limit::perMinute(5)->by($request->user()?->id ?: $request->ip()). This allows rate limiting per user ID or per IP address with custom thresholds.

Global API rate limiting default: 60 requests per minute

The 'api' middleware group includes 'throttle:60,1' by default in Laravel, implementing global rate limiting of 60 requests per minute for all API routes.

Global web rate limiting recommendation: 30 requests per minute

The 'web' middleware group can include 'throttle:30,1' to implement global rate limiting of 30 requests per minute for all web routes. This should be configured in Kernel.php.

Validate user input for dynamic column names in queries

Never allow user input to dictate column names referenced in queries. Always validate column names using the 'in' validation rule and use $request->validated() to ensure only expected column names are used with orderBy() or where() methods.

Security headers to implement: X-Frame-Options, X-Content-Type-Options, HSTS, CSP

Implement the following security headers in the web server or Laravel application middleware: X-Frame-Options (clickjacking protection), X-Content-Type-Options (MIME type sniffing protection), Strict-Transport-Security for HTTPS (HSTS, protects against downgrade attacks), and Content-Security-Policy (XSS and injection protection).

Use $request->only or $request->validated to prevent mass assignment

To prevent mass assignment vulnerabilities in Laravel, qualify allowed parameters using $request->only() or $request->validated() instead of $request->all(). This ensures only intended fields can be updated.

Do not disable Laravel mass assignment protection via $guarded

Never unguard models or set the $guarded variable to an empty array, as this disables Laravel's built-in mass assignment protection mechanism entirely.

Avoid forceFill and forceCreate methods that bypass mass assignment protection

Avoid using methods such as forceFill() or forceCreate() that bypass the mass assignment protection mechanism, unless you are passing in a validated array of values.

Eloquent ORM parameterizes queries by default for SQL injection protection

Laravel's Eloquent ORM protects against SQL injection by default by parameterizing queries and using SQL bindings. For example, User::where('email', $email)->get() generates a parameterized query with ? placeholders regardless of the $email variable content.

Always use SQL bindings for whereRaw queries

When using raw query expressions like whereRaw() in Laravel, always use SQL data bindings with placeholders (?) or named bindings (:name) for untrusted user input. Concatenating input directly into whereRaw() queries is vulnerable to SQL injection.

Validate column names in unique validation rule

Validation rules that accept database column names, such as Rule::unique() with the ignore() method, are vulnerable to SQL injection if the column name comes from user input. Always validate and whitelist column names before passing them to validation rules.

Blade template: use {{ }} for auto-escaped output

Laravel's Blade templating engine automatically escapes variables using the htmlspecialchars PHP function when using {{ }} echo statements. This protects against XSS attacks. Always use {{ }} for displaying untrusted user data.

Blade template: never use {!! !!} with untrusted data

The {!! !!} unescaped syntax in Blade templates bypasses XSS protection and must never be used with untrusted user input data. Using {!! request()->input('data') !!} results in an XSS vulnerability.

Use ImagePolicyWebhook admission controller to govern image provenance

The ImagePolicyWebhook admission controller can prevent unapproved images from being used and reject pods using unapproved images. It can refuse container images that: have not been scanned recently; use a base image not explicitly allowed; come from insecure registries.

Container image base must be from approved and secure source

Container images must be built on an approved and secure base image. The base image must be scanned and monitored at regular intervals to ensure all container images are based on a secure and authentic image. Strong governance policies should determine how images are built and stored in trusted image registries.

Use CI pipeline with security assessment for container image builds

Implement a CI pipeline that integrates security assessment such as vulnerability scanning into the build process. The pipeline should vet all code for production use, build the images, then scan for security vulnerabilities. Only push images with no issues to private registries for deployment to production. A failed security assessment should create a pipeline failure to prevent vulnerable images from entering the registry. Many source repositories (GitHub, GitLab) and CI tools offer integration with vulnerability scanners like Trivy or Grype.

Pod Security Standards profiles: Privileged, Baseline, and Restricted

Three Pod Security Standard profiles exist: Privileged is unrestricted allowing known privilege escalations, intended for system and infrastructure workloads requiring privilege, all securityContext settings permitted; Baseline is minimally restrictive for common containerized workloads preventing known privilege escalations, disallows dangerous settings like privileged, hostPID, hostPath, hostIPC; Restricted is most restrictive enforcing pod hardening practices at expense of compatibility for security-critical workloads, requires dropping all capabilities and enforcing runAsNotRoot. The Pod Security Admission Controller can enforce, audit, or warn upon policy violations.

Pod Security Admission Controller namespace labels for policy enforcement

Pod Security Admission Controller is enforced via namespace labels. For example, to enforce the restricted Pod Security Standard on a namespace: add labels pod-security.kubernetes.io/enforce: restricted, pod-security.kubernetes.io/audit: restricted, and pod-security.kubernetes.io/warn: restricted to the namespace metadata. Cluster administrators should set namespaces to the lowest Pod Security Policy that can be enforced and supports their risk level, only permitting privileged policy where absolutely required.

Pod Security Admission prevents risky containers at deployment time

Pod Security Admission is the replacement for deprecated Pod Security Policy, allowing enforcement of security policies on pods in a Kubernetes cluster. Use baseline level as minimum security requirement for all pods to ensure standard security across cluster. Clusters should strive to apply restricted level which follows pod hardening best practices.

Data Transfer Objects for Mass Assignment prevention

An architectural approach to prevent Mass Assignment is to create Data Transfer Objects (DTOs) and avoid binding input directly to domain objects. Only the fields that are meant to be editable by the user are included in the DTO.

Spring MVC Mass Assignment allow-listing

In Spring MVC, use the @InitBinder annotation with binder.setAllowedFields() method to allow-list bindable fields. Example: binder.setAllowedFields(["userid","password","email"]);

Spring MVC Mass Assignment block-listing

In Spring MVC, use the @InitBinder annotation with binder.setDisallowedFields() method to block-list sensitive fields. Example: binder.setDisallowedFields(["isAdmin"]);

Give your agent this brain