CSRF(跨站请求伪造)

10.14

参考

OWASP: The Open Web Application Security Project

介绍

跨站请求伪造(Cross-site request forgery),也被称为 one-click attack 或者 session riding,通常缩写为 CSRF 或者 XSRF, 是一种挟制用户在当前已登录的 Web 应用程序上执行非本意的操作的攻击方法。跟跨网站脚本(XSS)相比,XSS 利用的是用户对指定网站的信任,CSRF 利用的是网站对用户网页浏览器的信任。

举例

恶意图片

  • img标签会自动请求src属性中的地址。针对部分旧的浏览器,攻击者可能在邮件中嵌入图片,当用户在网页中打开邮件时可能会使用 session 信息发送任意GET请求。

  • imgonload方法能执行脚本,可能被用来动态创建表单并提交,从而伪造POST请求。

<img src="http://www.example.com/..." onload="" />

图片代码可能存在于恶意网站、论坛博客等用户生成内容的网站

恶意 HTML 页面

<form action="https://www.example.com/..." method="POST">
  <input type="hidden" name="data" value="..." />
  <input type="submit" value="Submit Request" />
</form>

提交页面的表单后,会向任意目标地址发起POST请求

应对

确保请求由用户自愿在合法网站发出

  • 检查请求来源

    检查请求头的来源字段 OriginReferer 等,是否与目标地址 Host:authority (HTTP2) 一致

  • 表单请求:校验 token

    在表单中添加隐藏的 token 字段,提交到服务器时进行校验。token 由服务器生成和校验

  • 普通 AJAX 请求:在前端添加自定义头部,后端进行校验

Ref

https://www.playframework.com/documentation/2.2.x/JavaCsrf

It is recommended that you familiarise yourself with CSRF, what the attack vectors are, and what the attack vectors are not. We recommend starting with this information from OWASP.

Simply put, an attacker can coerce a victims browser to make the following types of requests:

  • All GET requests
  • POST requests with bodies of type application/x-www-form-urlencoded, multipart/form-data and text/plain

An attacker can not:

  • Coerce the browser to use other request methods such as PUT and DELETE
  • Coerce the browser to post other content types, such as application/json
  • Coerce the browser to send new cookies, other than those that the server has already set
  • Coerce the browser to set arbitrary headers, other than the normal headers the browser adds to requests

Since GET requests are not meant to be mutative, there is no danger to an application that follows this best practice. So the only requests that need CSRF protection are POST requests with the above mentioned content types.

📖