﻿# V5917\. OWASP\. Possible cross\-site request forgery\. Potentially tainted data is used in a state\-changing operation\.

The analyzer has detected that HTTP request data is used in a state\-changing operation \(writing to a database, modifying files, or sending emails\), without verifying the origin of the request\. This makes the application vulnerable to cross\-site request forgery \(CSRF\)\.

CSRF allows an attacker to make an authenticated user's browser send a request to a vulnerable website from a page controlled by the attacker\. The browser automatically includes the session cookie in the request, so the server treats it as an action performed by the user\. The attacker does not need to read the response\. They only need an action to be carried out \(changing an email address, deleting an account, transferring money, etc\.\)\.

Vulnerabilities of this type can be categorized under the OWASP Top 10 Application Security Risks 2025:  [A01:2025 Broken Access Control](https://top10.owasp.org/2025/A01_2025-Broken_Access_Control/)\.

The example:

```cpp
func UpdateEmail(w http.ResponseWriter, r *http.Request) {
  cookie, err := r.Cookie("session")
  if err != nil {
    unauthorized(w)
    return
  }
  userID := getUserIDBySession(cookie.Value)
  db.Exec("UPDATE users SET email = $1 WHERE id = $2",
          r.FormValue("email"), userID)                // <=
  ....
}
```

The attacker hosts the following page on their website:

```cpp
<form action="https://victim.example/update-email" method="POST" id="f">
  <input type="hidden" name="email" value="attacker@evil.com">
</form>
<script>document.getElementById('f').submit();</script>
```

When a user with an active session visits this page, the browser sends a POST request with the user's session cookie, and the server changes the email address\.

Checking the request method and using cookie\-based authentication do not protect against CSRF: the browser automatically includes the cookie, and a POST form can be submitted from any website\.

There are several ways to fix the code\.

**The fix N1\. **Verify the request origin\.

```cpp
func main() {
  mux := http.NewServeMux()
  mux.HandleFunc("/update-email", UpdateEmail)

  protection := http.NewCrossOriginProtection()
  http.ListenAndServe(":8080", protection.Handler(mux))
}
```

The idea is that the browser tells the server where the request originated\. A script running on another website cannot forge these headers\. The server checks the request origin against its own and rejects cross\-origin requests\. This approach does not require tokens or server\-side state\.

Starting with Go 1\.25, the standard library provides a built\-in mechanism for verifying request origins: [`http.CrossOriginProtection`](https://pkg.go.dev/net/http#CrossOriginProtection)\.

**The fix N2\.** Validate a CSRF token\.

The server issues a secret token to the client and requires it to be included in every state\-changing request\. A malicious website can make the user's browser send a request with the session cookie, but it cannot obtain or read the CSRF token:

```cpp
func UpdateEmail(w http.ResponseWriter, r *http.Request) {
  cookie, err := r.Cookie("session")
  if err != nil {
    unauthorized(w)
    return
  }

  session, err := getSession(cookie.Value)
  if err != nil {
    unauthorized(w)
    return
  }

  token := r.PostFormValue("csrf_token")
  if token == "" ||
    subtle.ConstantTimeCompare([]byte(token),
                               []byte(session.CSRFToken)) != 1 {
    unauthorized(w)
    return
  }

  _, err = db.ExecContext(r.Context(),
             "UPDATE users SET email = $1 WHERE id = $2",
             r.PostFormValue("email"), session.UserID)
  if err != nil {
    http.Error(w, "failed to update email",
               http.StatusInternalServerError)
    return
  }

  w.WriteHeader(http.StatusNoContent)
}
```

**The fix N3\.** Avoid using cookies for authentication\.

Instead, authentication can use the `Authorization` header with a token that the application explicitly adds to each request, such as a Bearer token in a `fetch` call\. Unlike cookies, this token is not automatically included by the browser\. Therefore, a request forged from another website will not contain the token, which the attacker cannot obtain:

```cpp
func auth(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter,
                               r *http.Request) {
    h := r.Header.Get("Authorization")
    raw, ok := strings.CutPrefix(h, "Bearer ")
    if !ok {
      unauthorized(w)
      return
    }

    u, ok := store.Lookup(strings.TrimSpace(raw))
    if !ok {
      unauthorized(w)
      return
    } 

    next.ServeHTTP(w, r.WithContext(withUser(r.Context(), u)))
  })
}
```