HIGH cross site request forgeryfiber

Cross Site Request Forgery in Fiber

How Cross Site Request Forgery Manifests in Fiber

Cross Site Request Forgery (CSRF) in Fiber applications typically occurs when authenticated users can be tricked into executing unwanted actions on a web application where they're logged in. In Fiber, this vulnerability manifests through several specific patterns that developers should understand.

The most common CSRF attack vector in Fiber involves state-changing operations that lack proper anti-CSRF tokens. Consider a banking application where a user can transfer funds:

app.Post("/transfer", func(c *fiber.Ctx) error {
    amount := c.FormValue("amount")
    to := c.FormValue("to")
    
    // Process transfer without any CSRF protection
    transferFunds(c.Locals("user").(User), amount, to)
    
    return c.SendString("Transfer successful")
})

An attacker could create a malicious page that automatically submits a form to this endpoint when visited by an authenticated user:

<form action="https://yourbank.com/transfer" method="POST" id="csrf-form" style="display:none;">
    <input type="hidden" name="amount" value="1000">
    <input type="hidden" name="to" value="attacker@example.com">
</form>
<script>document.getElementById('csrf-form').submit();</script>

Another Fiber-specific CSRF pattern involves API endpoints that accept JSON payloads without proper verification. Many developers assume that same-origin policies protect them, but when CORS is misconfigured or when the API is accessible from the browser, CSRF becomes possible:

app.Post("/api/update-email", func(c *fiber.Ctx) error {
    var req struct {
        Email string `json:"email"`
    }
    
    if err := c.BodyParser(&req); err != nil {
        return c.Status(400).SendString("Invalid request")
    }
    
    // No CSRF token validation - vulnerable!
    updateEmail(c.Locals("user").(User).ID, req.Email)
    return c.SendStatus(200)
})

Fiber applications that use session-based authentication without CSRF protection are particularly vulnerable. The browser automatically includes session cookies with any request to the domain, allowing attackers to trigger actions simply by getting users to visit malicious pages.

Fiber-Specific Detection

Detecting CSRF vulnerabilities in Fiber applications requires both manual code review and automated scanning. middleBrick's black-box scanning approach is particularly effective for identifying CSRF vulnerabilities without needing access to source code.

middleBrick tests for CSRF by attempting to submit state-changing requests to your Fiber endpoints without including any anti-CSRF tokens. The scanner sends POST, PUT, DELETE, and PATCH requests to all discovered endpoints and analyzes the responses. If the server processes these requests and performs actions (like creating records, updating data, or deleting resources) without rejecting them for missing CSRF tokens, middleBrick flags this as a vulnerability.

For Fiber applications, middleBrick specifically looks for:

  • Endpoints that accept POST/PUT/DELETE/PATCH requests without CSRF protection
  • API endpoints that process JSON payloads without authentication context validation
  • Session-based endpoints that don't validate anti-CSRF tokens
  • State-changing operations that can be triggered via cross-origin requests
  • Missing SameSite cookie attributes on session cookies

The scanner also analyzes your OpenAPI/Swagger specifications if available, cross-referencing documented endpoints with the actual runtime behavior. This helps identify discrepancies between documented security requirements and implemented security controls.

Developers can also perform manual detection by examining their Fiber routes. Look for any routes that modify data and check if they implement CSRF protection. Routes using app.Post(), app.Put(), app.Delete(), or app.Patch() that handle authenticated user actions are prime candidates for CSRF protection.

Fiber-Specific Remediation

Remediating CSRF vulnerabilities in Fiber applications involves implementing proper anti-CSRF tokens and validating them on state-changing requests. Fiber provides several approaches to protect against CSRF attacks.

The most straightforward method is using the csrf middleware that comes with Fiber. Here's how to implement it:

import "github.com/gofiber/csrf"
app.Use(csrf.New(csrf.Config{
    KeyLookup:      "header:X-Csrf-Token",
    CookieName:     "csrf_" + app.Settings.Name,
    Expiration:     30 * 60 * 1000, // 30 minutes
    ContextKey:     "csrf";
    TemplateFolder: "templates",
}))

This middleware automatically generates CSRF tokens and validates them on incoming requests. For HTML forms, you need to include the token:

<form method="POST" action="/transfer">
    <input type="hidden" name="csrf" value="{{.csrf}}">
    <input type="text" name="amount">
    <input type="text" name="to">
    <button type="submit">Transfer</button>
</form>

For API endpoints that consume JSON, you should use the KeyLookup: "header:X-Csrf-Token" configuration and require clients to include the token in the header:

app.Post("/api/update-email", func(c *fiber.Ctx) error {
    // CSRF middleware automatically validates the token
    var req struct {
        Email string `json:"email"`
    }
    
    if err := c.BodyParser(&req); err != nil {
        return c.Status(400).SendString("Invalid request")
    }
    
    updateEmail(c.Locals("user").(User).ID, req.Email)
    return c.SendStatus(200)
})

Another important remediation step is setting proper SameSite attributes on session cookies:

app.Use(session.New(session.Config{
    CookieSameSite: cookie.SameSiteLaxMode,
}))

For applications that need to support cross-site requests but still prevent CSRF, consider implementing double-submit cookies or custom header validation patterns. The double-submit pattern involves sending the CSRF token both as a cookie and in the request header, then validating they match on the server.

middleBrick's continuous monitoring in the Pro plan can help verify that your CSRF protections remain effective over time. The scanner will periodically test your endpoints and alert you if any new CSRF vulnerabilities are introduced during development.

Frequently Asked Questions

How does middleBrick detect CSRF vulnerabilities in my Fiber application?
middleBrick performs black-box scanning by sending state-changing requests (POST, PUT, DELETE, PATCH) to your Fiber endpoints without including anti-CSRF tokens. If the server processes these requests and performs actions without rejecting them for missing tokens, the scanner flags this as a CSRF vulnerability. The scan takes 5-15 seconds and requires no credentials or configuration - just submit your API URL.
Can I integrate CSRF testing into my Fiber CI/CD pipeline?
Yes, you can use the middleBrick GitHub Action to automatically scan your Fiber APIs during CI/CD. Add middleBrick to your workflow and configure it to fail builds if security scores drop below your threshold. This ensures CSRF vulnerabilities and other security issues are caught before deployment to production.