What Is CSRF? How Can We Prevent CSRF?

Yilia - Jan 23 - - Dev Community

In the digital age, the Internet has woven into the fabric of our everyday lives. We've migrated numerous activities online, from shopping to socializing on various platforms and conducting banking transactions. As financial interactions become more widespread, the ramifications of network security have grown more pronounced. One of the most prevalent cyber threats on the Internet is CSRF (Cross-site request forgery), and it's imperative to delve into its nuances.

What Is CSRF?

CSRF attacks capitalize on vulnerabilities in a target website's request validation mechanisms. In certain situations, users unwittingly execute malicious requests while logged into the target website. Attackers typically employ addresses resembling the target website's domain, enticing users to click. They embed nefarious code by disguising it as image loads or hidden forms, initiating requests to the target website, and executing covert unauthorized actions. Objectives such as altering user passwords or initiating unauthorized bank transfers can result in significant losses for users.

Real-Life Example

Picture a website named e-bank.com offering electronic banking services, featuring a page named /transfer for submitting transfer requests. When users access the e-bank.com/transfer page, a form displaying user-inputted details is presented. Upon form completion and submission, an HTTP POST request is sent to the page's address, carrying parameters like the recipient and amount entered by the user.

At this juncture, an attacker can construct a malicious page with an invisible form, directing the submission address to e-bank.com/transfer. The attacker pre-fills the form with the specific recipient and amount parameters. When users are deceived into clicking on this malicious page, the browser executes JavaScript code, submitting the form.

If the user isn't registered or logged in on e-bank.com, the transfer request cannot be executed. However, if the user has recently used the service and the login status persists, the transfer request may be successfully executed.

This encapsulates CSRF attacks—simple in principle yet harboring immense potential harm. Thankfully, there are numerous mature methods to thwart such attacks. Let's explore them below.

How Can We Prevent CSRF?

Addressing this issue involves proactive and passive measures.

HTTP Method Restriction and Referer Restriction

As developers, we can enforce stricter restrictions on sensitive addresses within the service, such as:

  • For addresses requiring data submission, prohibit using HTTP GET requests, compelling the use of POST requests. This adds complexity for attackers attempting to construct malicious pages.

  • Additionally, we can restrict the Referer field in the HTTP request header (Referer), only allowing it from known legitimate addresses and blocking malicious requests.

This represents a straightforward, proactive protective measure with a lower cost but still some susceptibility to attacks.

CSRF Token

CSRF Token is a widely adopted solution, combining server-side session mechanisms to thwart CSRF attacks. Specifically, the server-side program embeds a hidden input field on pages requiring protection with a randomly generated CSRF Token in the output form. Simultaneously, a session is created on the server side, storing this random string with an expiration time.

When a user requests the page, the server initializes the session, storing data on the server side and setting a cookie on the client-side browser containing the Session ID for association. The CSRF Token is stored in the session. Upon form submission, the CSRF Token is sent. The server-side program compares this token with the stored part in the session. Successful validation leads to subsequent logic execution; otherwise, an error is returned. Simultaneously, a new CSRF Token is inserted into the form for the next submission.

This represents a proactive protective measure, demanding some effort but providing robust protection.

Cross-Origin Protection

We often encounter a technology named CORS (Cross-Origin Resource Sharing), a specification indicating whether browsers permit cross-origin requests. Modern browsers support this specification. When initiating a Fetch/XHR request on an existing page, the browser sends an HTTP OPTIONS request to pre-check if the target service allows requests from the current source address. The server will provide a response-headers list, specifying allowed sources, request methods, and headers. The browser adheres to these indications, preventing forbidden requests on the client side.

This serves as another proactive protective measure, configurable on the server side, but note that although normal users are unlikely to disable this feature, it remains possible on the client side.

Blocking Third-Party Cookies

Services we develop sometimes store user Session IDs in Cookies to maintain login status. Cookies support SameSite settings, preventing the browser from sending cookies to cross-origin sites. Attempting CSRF attacks results in an unauthenticated status on the target site.

Moreover, due to the misuse of HTTP Cookie mechanisms for client tracking, browser developers have decided to restrict and block third-party cookies (Cookie Countdown) gradually. When a page on domain A attempts to make a call to domain B, even if it passes CORS rule checks, the browser won't send cookies to that cross-origin site.

Chrome Timeline Example

Summary

As API gateways, both Apache APISIX and API7 Enterprise support CSRF Token and CORS—two protective measures mentioned earlier—to thwart CSRF attacks.

In conclusion, preventing CSRF attacks necessitates a multifaceted approach, incorporating various techniques across server-side, browser, HTTP protocol, and more to achieve comprehensive protection.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .