## CSRF

CSRF attacks rely on trusted, authenticated users which are tricked into performing a certain action on the web application. CSRF attacks craft a web URL which is then visited by the victim. The victim's browser will send a session cookie when visiting the URL, thus making the request completely legitimate from the perspective of the web application.

In general, CSRF protection is implemented using random tokens which are kept secret between the web application and the legitimate user.

## CSRF Protection in ntopng

ntopng implements token-based CSRF protection. Upon user authentication, a random CSRF token is generated by ntopng and associated to the session which is being created. From this point on, every request which attempts at modifying the status or data of ntopng (e.g., set a host name, change a password), must be performed using a POST and with a valid `csrf` token. *ntopng checks the validity of this token, before doing any actual modification*.

ntopng GUI pages containing forms for the modification of ntopng status and data, are already served with forms carrying the `csrf` token. Hence, CSRF protection takes place transparently from the point of view of the GUI user.

### CSRF Token Lifetime

A token is randomly generated upon session creation, that is, when a user logs in successfully. Token duration equals session duration. Session duration can be tuned from the ntopng preferences. As the token is never added to the session cookie, it is never stored client-side, thus making it virtually impossible for an attacker to guess it for a CSRF attack. Indeed, [having static CSRF tokens throughout the session provides adequate CSRF protection](https://www.sjoerdlangkemper.nl/2019/12/18/different-csrf-token-for-each-form/).

Reducing token lifetime can be beneficial if the token is stolen. [However, this may result in usability concerns. For example, the "Back" button browser capability is often hindered as the previous page may contain a token that is no longer valid.](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#synchronizer-token-pattern)


## CSRF Protection in the ntopng REST API

By definition, REST APIs are stateless and ntopng REST APIs represent no exception to this. Hence, each REST API request should be performed with authentication data, not with session cookies.

For example, `curl` should be used with explicit `-u <username>:<password>`:


```
curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "0", "status": "historical-flows", "epoch_begin": 1590710400, "epoch_end": 1590796800}' http://localhost:3000/lua/rest/v1/get/alert/ts.lua
```

When authentication data is submitted explicitly, CSRF checks are not enforced as, by construction, CSRF attacks rely on session cookies as explained above.
