简体   繁体   English

如何保护Rest API?

[英]How do I secure rest api?

I'm working an app with Angular.I want to get the data to be listed from rest api. 我正在使用Angular开发一个应用程序。我想从rest api中列出数据。 However, I don't want users to access the resource. 但是,我不希望用户访问该资源。 Which language, library or framework can I secure it with? 我可以使用哪种语言,库或框架进行保护? And users are using the app without membership. 用户正在使用没有会员资格的应用程序。

I tried jwt but I didn't get the result I wanted. 我尝试了jwt,但没有得到想要的结果。 Maybe I couldn't. 也许我做不到。

Here is express.js 这是express.js

const app = require('express')()
const express = require('express')
const fs = require('fs')
const cors = require('cors')
const bodyParser = require('body-parser');
app.use(cors())
app.use(bodyParser.json())

app.get('/', (req, res) => {
  res.json({message: 'Rest API Work'})
})

app.get('/list', (req, res) => {
    fs.readFile('data1.json','utf-8',(err,data)=>{
    res.setHeader("Content-Type", "application/json; charset=utf-8")
        data = JSON.parse(data)
        console.log(data)
        res.end(JSON.stringify(data,null,4))
    })
})



app.listen(3002, function(){
  console.log('Server OK')  
})

I want a simple security method where I can connect with Angular. 我想要一种可以与Angular连接的简单安全方法。

Best way to secure your API is start using a reverse proxy like Nginx. 保护API的最佳方法是开始使用Nginx之类的反向代理。 Javascript frameworks are all basically the same in terms of security. 就安全性而言,JavaScript框架基本上都是相同的。 They all have a basic router handler, dispatcher (based of native Node.js HTTP library) and some basic helper methods, they give it a nice catchy name and that's it. 它们都有一个基本的路由器处理程序,调度程序(基于本机Node.js HTTP库)和一些基本的辅助方法,它们为它提供了一个不错的上乘名称。 I've checked the source code of almost all major frameworks. 我已经检查了几乎所有主要框架的源代码。 Now, some basic configuration params of Nginx are: client_body_buffer_size proxy_buffers etc. All your directives should regex input data too. 现在,Nginx的一些基本配置参数是: client_body_buffer_size proxy_buffers等。您所有的指令也应该对输入数据进行正则表达式。 Generally anything that could "filter" the malicious code is useful. 通常,任何可以“过滤”恶意代码的东西都是有用的。 Cloudflare can somehow help and some other companies that could secure your app but they're expensive. Cloudflare可以以某种方式提供帮助,而其他一些公司则可以保护您的应用程序安全,但价格昂贵。 Another good example is containerizing your app using Docker. 另一个很好的例子是使用Docker容器化您的应用程序。
If you have a basic piece of code in Node.js, the most easy way to hack it is through your app's logic. 如果您在Node.js中有一段基本的代码,最简单的破解方法是通过应用程序的逻辑。 You should use anti-XSS modules like xss or express-sanitizer . 您应该使用xssexpress-sanitizer类的反XSS模块。 If you're using SQL database you should always escape the query values. 如果您使用的是SQL数据库,则应始终转义查询值。

ASSUMPTIONS 的假设

I'm working an app with Angular. 我正在使用Angular开发一个应用程序。

I am assuming that you are doing a Web App, and not a mobile app with something like NativeScript. 我假设您正在使用Web应用程序,而不是使用NativeScript之类的移动应用程序。

I want to get the data to be listed from rest api. 我想从Rest API获取要列出的数据。 However, I don't want users to access the resource 但是,我不希望用户访问资源

I assume here that you want that only the web app to have access to the API, and not anyone else. 我在这里假设您只希望Web应用程序有权访问API,而其他任何人都不能。

LETS TACKLE YOUR QUESTIONS 解决您的问题

Which language, library or framework can I secure it with? 我可以使用哪种语言,库或框架进行保护?

The problem is not the programming language or framework, but what you are trying to achieve, and I honestly have to tell you a cruel truth... In the context of the web is not possible to lock down an API to a Web app, and this is just because of the way the web was built, you know you hit F12 and you can see all the code running in the browser, therefore any secret you put there to identify your web app in each request it does to the API, will be up for grabs and reuse by anyone who wants to replicate your web app, and your API will not be able to distinguish the WHO is doing the request from WHAT is doing the request. 问题不是编程语言或框架,而是您要实现的目标,老实说,我必须告诉您一个残酷的事实……在网络环境中,无法将API锁定到网络应用程序,这仅仅是因为网络的构建方式,您知道您按了F12键,并且可以看到浏览器中正在运行的所有代码,因此,您在其中存储的用于在对API进行的每个请求中标识您的Web应用的任何秘密,将争夺和谁想要复制您的Web应用程序重复使用,和你的API将无法区分世卫组织正在开展从什么是做请求的请求。

And users are using the app without membership. 用户正在使用没有会员资格的应用程序。

Contrary to what many developers may think, authenticated users don't lock-down a web app or mobile app to the API server, because the user is only one part of the equation, he represents the WHO is accessing the API, but you still need to address WHAT is accessing it. 与许多开发人员可能认为的相反,经过身份验证的用户不会将Web应用程序或移动应用程序锁定到API服务器,因为该用户只是等式的一部分,他表示正在使用WHO ,但您仍然需要解决什么是访问它。

Wait, wait a second... You keep referring to the WHO and the WHAT , do you care to explain it in more detail? 等一下,等一下...您一直在指WHOWHAT ,您是否愿意详细解释?

Glad you asked ;) 很高兴你问;)

The Difference Between WHO and WHAT is Accessing the API Server WHO与访问API服务器之间的区别

So let's clear a common misconception, among developers, about WHO and WHAT is accessing an API server. 因此,让我们清除一下开发人员之间关于WHOWHAT正在访问API服务器的常见误解。

To better understand the differences between the WHO and the WHAT are accessing an API server, let's use this picture: 为了更好地了解WHOWHAT访问API服务器之间的区别,让我们使用以下图片:

中间人攻击

So replace the mobile app by web app, and keep following my analogy around this picture. 因此,用Web应用程序代替移动应用程序,并继续遵循我对这张图片的类比。

The Intended Communication Channel represents the web app being used as you expected, by a legit user without any malicious intentions, communicating with the API server from the browser, not using Postman or using any other tool to perform a man in the middle(MitM) attack. 预期的通信渠道表示合法用户在没有任何恶意意图的情况下按预期使用的Web应用程序,通过浏览器与API服务器进行通信,而不使用Postman或使用任何其他工具来执行中间操作(MitM)攻击。

The actual channel may represent several different scenarios, like a legit user with malicious intentions that may be using Curl or a tool like Postman to perform the requests, a hacker using a MitM attack tool, like MitmProxy, to understand how the communication between the web app and the API server is being done in order to be able to replay the requests or even automate attacks against the API server. 实际渠道可能代表几种不同的情况,例如具有恶意意图的合法用户可能正在使用Curl或Postman等工具来执行请求,黑客使用MitM攻击工具(例如MitmProxy)来了解网络之间的通信方式应用程序和API服务器已经完成,以便能够重播请求,甚至自动对API服务器进行攻击。 Many other scenarios are possible, but we will not enumerate each one here. 其他许多情况也是可能的,但在此我们将不逐一列举。

I hope that by now you may already have a clue why the WHO and the WHAT are not the same, but if not it will become clear in a moment. 我希望到现在为止您可能已经有了线索,为什么WHOWHAT并不相同,但是如果不是这样,那一会儿就会明白。

The WHO is the user of the web app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows. WHO是Web应用程序的用户,我们可以通过多种方式来进行身份验证,授权和标识,例如使用OpenID Connect或OAUTH2流。

OAUTH OAUTH

Generally, OAuth provides to clients a "secure delegated access" to server resources on behalf of a resource owner. 通常,OAuth代表资源所有者向客户端提供对服务器资源的“安全委派访问”。 It specifies a process for resource owners to authorize third-party access to their server resources without sharing their credentials. 它为资源所有者指定了一个在不共享凭据的情况下授权第三方访问其服务器资源的过程。 Designed specifically to work with Hypertext Transfer Protocol (HTTP), OAuth essentially allows access tokens to be issued to third-party clients by an authorization server, with the approval of the resource owner. OAuth专为与超文本传输​​协议(HTTP)配合使用而设计,实质上允许在资源所有者的批准下,授权服务器将访问令牌发布给第三方客户端。 The third party then uses the access token to access the protected resources hosted by the resource server. 然后,第三方使用访问令牌访问资源服务器托管的受保护资源。

OpenID Connect OpenID连接

OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. OpenID Connect 1.0是基于OAuth 2.0协议的简单身份层。 It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner. 它允许客户端基于授权服务器执行的身份验证来验证最终用户的身份,并以可互操作且类似于REST的方式获取有关最终​​用户的基本配置文件信息。

While user authentication may let the API server know WHO is using the API, it cannot guarantee that the requests have originated from WHAT you expect, the browser were your web app should be running from, with a real user. 虽然用户认证可以让API服务器知道在使用API,它不能保证请求源自你所期望 ,浏览器是你的web应用程序应该运行,与真正的用户。

Now we need a way to identify WHAT is calling the API server, and here things become more tricky than most developers may think. 现在,我们需要一种方法来确定哪些是调用API服务器,这里的事情变得比大多数开发人员可能会觉得更靠谱。 The WHAT is the thing making the request to the API server. 向API服务器发出请求的是什么 Is it really a genuine instance of the web app, or is a bot, an automated script or an attacker manually poking around with the API server, using a tool like Postman? 它是Web应用程序的真正实例,还是使用诸如Postman之类的工具通过API服务器手动访问的机器人,自动脚本或攻击者?

For your surprise, you may end up discovering that It can be one of the legit users manipulating manually the requests or an automated script that is trying to gamify and take advantage of the service provided by the web app. 令您惊讶的是,您可能最终发现它可能是手动处理请求的合法用户之一,或者是试图游戏化并利用Web应用程序提供的服务的自动脚本。

Well, to identify the WHAT , developers tend to resort to an API key that usually is sent in the headers of the web app. 好了,为了确定WHAT ,开发人员倾向于求助于通常在Web应用程序标头中发送的API密钥。 Some developers go the extra mile and compute the key at run-time in the web app, inside obfuscated javascript, thus it becomes a runtime secret, that can be reverse engineered by deobusfaction tools, and by inspecting the traffic between the web app and API server with the F12 or MitM tools. 一些开发人员会加倍努力,并在运行时在混淆的javascript内的web应用程序中计算密钥,因此它成为运行时的秘密,可以通过除臭工具以及检查Web应用程序与API之间的流量进行逆向工程F12或MitM工具的服务器。

The above write-up was extracted from an article I wrote, entitled WHY DOES YOUR MOBILE APP NEED AN API KEY? 以上文章摘自我写的一篇文章,标题为《 为什么您的移动应用程序需要API密钥? . While in the context of a Mobile App, the overall idea is still valid in the context of a web app. 在移动应用程序的上下文中,总体思想在Web应用程序的上下文中仍然有效。 You wish you can read the article in full here , that is the first article in a series of articles about API keys. 您希望可以在此处阅读全文,这是有关API密钥的系列文章中的第一篇。

Now you may ask... If I can not lock down the API server to my web app only, how can I defend it? 现在您可能会问...如果我不能仅将API服务器锁定到我的Web应用程序,该如何保护它?

Defending an API Server 防御API服务器

To start with a web app or even a mobile should only communicate with an API server that is under your control and any access to third part APIs services must be done by this same API server you control. 要从Web应用程序甚至移动设备开始,只能与您控制下的API服务器进行通信,并且对第三方API服务的任何访问都必须由您控制的同一API服务器来完成。 This way you limit the attack surface to only one place, where you will employ as many layers of defense as what you are protecting is worth. 通过这种方式,您可以将攻击面限制在一个地方,在那里您将采用防御所需要保护的多层防御。

So anything that runs on the client side and needs some secret to access an API can be abused in different ways and you can learn more on this series of articles about Mobile API Security Techniques. 因此,在客户端运行的任何需要秘密访问API的东西都可能以不同的方式被滥用,您可以在本系列有关移动API安全技术的文章中了解更多信息。 While this articles are in the context of an API serving a mobile app, some of the content are applicable for an API serving a web app to, and will help you to understand how fragile an API is when it comes to distinguish from WHO and WHAT is accessing it. 虽然本文是在为移动应用程序提供服务的API的上下文中,但其中一些内容适用于为网络应用程序提供服务的API,并且将帮助您了解API与WHOWHAT区别时的脆弱性正在访问它。 So this series of articles will teach you how API Keys, User Access Tokens, HMAC and TLS Pinning can be used to protect the API and how they can be bypassed. 因此,本系列文章将教您如何使用API​​密钥,用户访问令牌,HMAC和TLS固定来保护API以及如何绕过它们。

Now that you are more aware of the pains of defending an API server, let's see what can be done to mitigate the security risks is facing in the context of a web app. 现在,您已经更多地了解了捍卫API服务器的痛苦,让我们看看可以采取什么措施来减轻Web应用程序环境中面临的安全风险。 For an API serving a web app, you can employ several layers of dense, starting with reCaptcha V3 , followed by Web Application Firewall (WAF) and finally if you can afford it a User Behavior Analytics (UBA) solution. 对于服务于Web应用程序的API,您可以采用多个密集层,从reCaptcha V3开始,然后是Web应用程序防火墙 (WAF),最后是您可以负担得起的用户行为分析 (UBA)解决方案。

Google reCAPTCHA V3 : Google reCAPTCHA V3

reCAPTCHA is a free service that protects your website from spam and abuse. reCAPTCHA是一项免费服务,可保护您的网站免受垃圾邮件和滥用的侵害。 reCAPTCHA uses an advanced risk analysis engine and adaptive challenges to keep automated software from engaging in abusive activities on your site. reCAPTCHA使用高级风险分析引擎和适应性挑战,以防止自动化软件参与您网站上的滥用行为。 It does this while letting your valid users pass through with ease. 这样做是为了让您的有效用户轻松通过。

...helps you detect abusive traffic on your website without any user friction. ...可帮助您检测网站上的滥用流量,而不会引起用户的摩擦。 It returns a score based on the interactions with your website and provides you more flexibility to take appropriate actions. 它会根据与您网站的互动情况返回得分,并为您提供更大的灵活性以采取适当的措施。

WAF - Web Application Firewall : WAF-Web应用程序防火墙

A web application firewall (or WAF) filters, monitors, and blocks HTTP traffic to and from a web application. Web应用程序防火墙(或WAF)筛选,监视和阻止与Web应用程序之间的HTTP通信。 A WAF is differentiated from a regular firewall in that a WAF is able to filter the content of specific web applications while regular firewalls serve as a safety gate between servers. WAF与常规防火墙的区别在于,WAF能够过滤特定Web应用程序的内容,而常规防火墙充当服务器之间的安全门。 By inspecting HTTP traffic, it can prevent attacks stemming from web application security flaws, such as SQL injection, cross-site scripting (XSS), file inclusion, and security misconfigurations. 通过检查HTTP流量,它可以防止Web应用程序安全漏洞(例如SQL注入,跨站点脚本(XSS),文件包含和安全性错误配置)引起的攻击。

UBA - User Behavior Analytics : UBA-用户行为分析

User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about the detection of insider threats, targeted attacks, and financial fraud. Gartner定义的用户行为分析(UBA)是一个有关检测内部威胁,针对性攻击和财务欺诈的网络安全流程。 UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. UBA解决方案着眼于人类行为模式,然后应用算法和统计分析从这些模式中检测出有意义的异常,即表明潜在威胁的异常。 Instead of tracking devices or security events, UBA tracks a system's users. UBA不会跟踪设备或安全事件,而是跟踪系统的用户。 Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats. 像Apache Hadoop这样的大数据平台通过允许它们分析PB级的数据来检测内部威胁和高级持久威胁,正在增强UBA功能。

All these solutions work based on a negative identification model, by other words they try their best to differentiate the bad from the good by identifying what is bad, not what is good, thus they are prone to false positives, despite the advanced technology used by some of them, like machine learning and artificial intelligence. 所有这些解决方案都基于否定性识别模型,换句话说,他们通过识别出什么是坏的而不是什么好,来尽最大的努力将好与坏区别开来,因此尽管使用了先进的技术,但它们还是容易产生误报。其中一些,例如机器学习和人工智能。

So you may find yourself more often than not in having to relax how you block the access to the API server in order to not affect the good users. 因此,您可能经常会发现自己不必放松放松如何阻止对API服务器的访问,以免影响良好的用户。 This also means that these solutions require constant monitoring to validate that the false positives are not blocking your legit users and that at the same time they are properly keeping at bay the unauthorized ones. 这也意味着这些解决方案需要不断监控,以确认误报不会阻止您的合法用户,同时又可以正确阻止未经授权的用户。

CONCLUSION 结论

I want a simple security method where I can connect with Angular. 我想要一种可以与Angular连接的简单安全方法。

So as may have realized already, you are not able to achieve a simple security method to lock down your Angular app with the API server. 就像已经意识到的那样,您将无法实现一种简单的安全方法来使用API​​服务器锁定Angular应用。 That's it, a simple security method does not do the trick, and instead you need to resort to several solutions, that will reduce the attack surface, but will not eliminate it. 就是这样,简单的安全方法无法解决问题,而是需要诉诸几种解决方案,这将减少攻击面,但不会消除攻击面。

So In the end, the solution to use in order to protect your API server must be chosen in accordance with the value of what you are trying to protect and the legal requirements for that type of data, like the GDPR regulations in Europe. 因此,最后,必须根据要保护的内容的价值以及此类数据的法律要求(例如欧洲的GDPR法规)来选择用于保护API服务器的解决方案。

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

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