简体   繁体   English

具有 CSRF 和 XSS 保护的无状态 REST API

[英]Stateless REST API with CSRF and XSS protection

Is it possible to protect stateless REST API from both XSS and CSRF attacks?是否可以保护无状态 REST API 免受 XSS 和 CSRF 攻击?

Currently, I'm using JWT token stored in secure/httpOnly cookie for stateless authentication.目前,我正在使用存储在安全/httpOnly cookie 中的 JWT 令牌进行无状态身份验证。 This should protect the API from most common XSS attack: stealing cookies with XSS-injected JavaScript and sending them to the attacker.这应该可以保护 API 免受最常见的 XSS 攻击:使用注入 XSS 的 JavaScript 窃取 cookie 并将它们发送给攻击者。

However, this doesn't protect the API from CSRF attack, where attacker would trick the authenticated user to follow a link to the particular web API call to actuate adverse transaction on behalf of the victim.但是,这并不能保护 API 免受 CSRF 攻击,攻击者会欺骗经过身份验证的用户点击指向特定 Web API 调用的链接,以代表受害者执行不利交易。 How could I protect the API from this attack without introducing server side state ?如何在不引入服务器端状态的情况下保护 API 免受这种攻击?

Also, is it true XSS vulnerability would inheritedly allow CSRF type attack in the following scenario: Injected JavaScript would retrieve CSRF token from the client side state, DOM or the browser storage and prepare a malicious ajax call to the server.此外,在以下情况下,XSS 漏洞是否会继承允许 CSRF 类型攻击:注入的 JavaScript 将从客户端状态、DOM 或浏览器存储中检索 CSRF 令牌,并准备对服务器的恶意 ajax 调用。 Browser would still automatically include the httpOnly cookie for the same origin request.浏览器仍会自动包含同一来源请求的 httpOnly cookie。 Is there a way to get protected from this other than protecting from the XSS vulnerability in the first place?除了首先防止 XSS 漏洞之外,还有其他方法可以避免这种情况吗?

Stateless anti-forgery tokens无状态防伪令牌

The first question is about preventing CSRF without server-side state.第一个问题是关于在没有服务器端状态的情况下防止CSRF The current approach for stateless anti-forgery tokens is the double submit cookie pattern.当前用于无状态防伪令牌的方法是双重提交 cookie模式。

CSRF attacks depend on the browser automatically sending the API's own cookies back to it, regardless of where the request originated. CSRF 攻击依赖于浏览器自动将 API 自己的 cookie 发送回它,而不管请求来自何处。 The attacker doesn't have or need access to the cookie contents.攻击者没有或不需要访问 cookie 内容。 They only need to trick the user into loading malicious HTML.他们只需要欺骗用户加载恶意 HTML。 The double cookie pattern adds a new requirement: the attacker must know and separately send the contents of the anti-forgery cookie.双cookie模式增加了一个新要求:攻击者必须知道并单独发送防伪cookie的内容。

There are ways for an attacker to overwrite the anti-forgery cookie with their own.攻击者有办法用自己的方法覆盖防伪 cookie。 So you may want to look at some additional security hardening for this approach.因此,您可能希望针对这种方法查看一些额外的安全强化 Especially HMAC signing the anti-forgery token to prevent token substitution.特别是 HMAC 对防伪令牌进行签名以防止令牌替换。 Using HSTS and the __Host cookie prefix to ensure transport security and proper cookie scope.使用 HSTS 和__Host cookie 前缀来确保传输安全性和正确的 cookie 范围。 And having the client provide the anti-forgery token in a custom header.并让客户端在自定义标头中提供防伪令牌。

The custom header ensures the request must be sent from JS, since HTML-tag-based CSRF attacks cannot set custom headers.自定义标头确保请求必须从 JS 发送,因为基于 HTML 标记的 CSRF 攻击无法设置自定义标头。 Being sent from JS also triggers additional protections.从 JS 发送也会触发额外的保护。 For cross-origin requests it triggers SOP on the browser and CORS validation on the server.对于跨域请求,它会触发浏览器上的SOP和服务器上的CORS验证。 The server can also do basic Origin validation .服务器还可以进行基本的Origin 验证

Regarding the scope of CSRF attacks, here is a note from the OWASP CSRF link at the top.关于 CSRF 攻击的范围,这里是顶部 OWASP CSRF 链接的注释。

Forcing the victim to retrieve data doesn't benefit an attacker because the attacker doesn't receive the response, the victim does.强迫受害者检索数据对攻击者没有好处,因为攻击者没有收到响应,而受害者却收到了。 As such, CSRF attacks target state-changing requests.因此,CSRF 攻击针对状态更改请求。

XSS question跨站脚本问题

Yes, an XSS attack could happen that way.是的, XSS攻击可能会以这种方式发生。 Once a malicious script is loaded into JS, it has free reign to use anything accessible to Javascript.一旦将恶意脚本加载到 JS 中,它就可以自由支配使用 Javascript 可访问的任何内容。 Including app code/memory, browser storage, and cookies.包括应用程序代码/内存、浏览器存储和 cookie。 Even though HttpOnly cookies are not readable, they can still be sent in requests.即使 HttpOnly cookie 不可读,它们仍然可以在请求中发送。 A non-targeted attack might look for key data in locations used by popular frameworks.非目标攻击可能会在流行框架使用的位置中寻找关键数据。 And might try to probe for popular/discoverable API frameworks on the server.并且可能会尝试在服务器上探查流行/可发现的 API 框架。 A targeted attack means the attacker studied your system and crafted a custom payload for it.有针对性的攻击意味着攻击者研究了您的系统并为其制作了自定义有效负载。

The primary vector for XSS is unsanitized external data (user input, database values, etc.). XSS 的主要载体是未经处理的外部数据(用户输入、数据库值等)。 To prevent XSS, check out these guidelines from OWASP .要防止 XSS,请查看OWASP 中的这些指南 Of note is that front-end frameworks like Angular, React, Svelte, Vue, and others have built-in XSS protection.值得注意的是,Angular、React、Svelte、Vue 等前端框架具有内置的 XSS 保护。 Because they sanitize data before rendering it.因为他们在渲染数据之前对其进行了清理。 Example: an attacker enters an HTML string into an input.示例:攻击者将 HTML 字符串输入到输入中。 When it is later displayed, these frameworks HTML-encode the string.稍后显示时,这些框架会对字符串进行 HTML 编码。 So left and right angle brackets are replaced with <所以左右尖括号被替换为< and >> and so on.等等。 This causes the browser to evaluate the string as text instead of runnable HTML.这会导致浏览器将字符串评估为文本而不是可运行的 HTML。 But you can still mess it up in different ways if careless.但是如果不小心,你仍然可以用不同的方式把它搞砸

XSS attacks can also come from external resources. XSS 攻击也可能来自外部资源。 Maybe a compromised CDN or NPM script.可能是受损的 CDN 或 NPM 脚本。 If your deployed code takes dependencies on NPM libraries, pay extra attention to NPM audit warnings.如果您部署的代码依赖于 NPM 库,请特别注意 NPM 审计警告。 One attack pattern is to attach a small loader (easier to go unnoticed), which will fetch attack payloads at runtime.一种攻击模式是附加一个小型加载程序(更容易被忽视),它将在运行时获取攻击载荷。 A CSP policy can help prevent this. CSP策略可以帮助防止这种情况。 Specify an allowed list of resources -- your app assets and API URLs -- and block all others.指定允许的资源列表(您的应用资产和 API URL)并阻止所有其他资源。 CSP can also prevent data exfiltration. CSP 还可以防止数据泄露。

For both CSRF and XSS对于 CSRF 和 XSS

For attacks on your API, you can additionally employ server-side mitigations.对于对 API 的攻击,您还可以使用服务器端缓解措施。 IP-based throttling / temporary bans, unusual activity grey-listing and alerting, etc.基于 IP 的限制/临时禁令、异常活动灰名单和警报等。

For especially sensitive operations, one strategy is to use an escalated authorization.对于特别敏感的操作,一种策略是使用升级授权。 This could take the form of requiring the user to re-authenticate or use a 2nd factor like a one-time password.这可以采取要求用户重新验证或使用第二个因素(如一次性密码)的形式。 This can block automated attacks since it requires active user intervention.这可以阻止自动攻击,因为它需要主动的用户干预。

To mitigate attackers using existing escalated authorizations (which may also be in a cookie or app memory), they can have short expirations and be limited to specific operations.为了缓解使用现有升级授权(也可能在 cookie 或应用程序内存中)的攻击者,他们可以有很短的过期时间,并且仅限于特定操作。 To go even further, the approved operations + relevant data can be signed.更进一步,可以签署批准的操作+相关数据。 This will prevent malicious scripts from reusing an escalation to execute the same kind of operation with different data.这将防止恶意脚本重用升级以对不同数据执行相同类型的操作。 Even further, these sensitive operations can be idempotent .更进一步,这些敏感操作可以是幂等的。 So if an attacker does resend already-executed operations, they will not cause any additional changes in the system.因此,如果攻击者确实重新发送了已经执行的操作,它们不会对系统造成任何额外的变化。

Zooming out缩小

Try to engineer your systems to be as uninteresting as possible to hackers.尝试将您的系统设计为对黑客尽可能不感兴趣。 Use trusted external services for sensitive needs like credit cards and credentials.使用受信任的外部服务来满足信用卡和凭证等敏感需求。 Ideally (from a security perspective) the hacking risk would be reduced to just data vandalism/loss.理想情况下(从安全角度来看),黑客风险将降低为数据破坏/丢失。 So in the worst case that a breach happens, it would have little long-term impact.因此,在发生违规的最坏情况下,它几乎不会产生长期影响。 And it could be recovered with common practices, including routinely tested backups.它可以通过常见的做法来恢复,包括定期测试的备份。 And then further mitigations added for the specific attacks used.然后为所使用的特定攻击添加了进一步的缓解措施。

Tread especially carefully with user-to-user interaction.在进行用户与用户交互时要特别小心。 Since this adds more targets and pivot points for hackers -- your user base.因为这为黑客增加了更多的目标和支点——你的用户群。 The most security-conscious eyes should be on these pieces.最有安全意识的眼睛应该在这些作品上。 Not only for technical dangers like user-to-user XSS attacks, but also social ones.不仅针对用户对用户 XSS 攻击等技术危险,还针对社交危险。 Human weaknesses are the most well-known and easiest to exploit.人类的弱点是最广为人知且最容易被利用的。

Lastly, there is no sense investing in mitigations which have low risk/consequences in your situation.最后,对您的情况风险/后果低的缓解措施进行投资是没有意义的。 So do not take everything here as a requirements checklist.所以不要把这里的所有东西都当作需求清单。 It's not a complete list anyway.无论如何,这不是一个完整的列表。 Focus on your biggest risks first.首先关注您最大的风险。 Reevaluate periodically.定期重新评估。

You can generate a token (eg a UUID) and put it into the jwt token as well as send it back to the client.您可以生成一个令牌(例如 UUID)并将其放入 jwt 令牌中,然后将其发送回客户端。 Then the client sends it during every each request in a header.然后客户端在每个请求的标头中发送它。 Then the server can compare the token in the header and the token in the jwt token to make sure the request comes from the client who was aunthenticated.然后服务器可以比较标头中的令牌和 jwt 令牌中的令牌,以确保请求来自经过身份验证的客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM