Node.js最佳实践-安全攻击

Node.js is a popular runtime to write apps for. These apps are often production quality apps that are used by many people. To make maintaining them easier, we’ve to set some guidelines for people to follow.

Node.js是一个流行的运行时,可以为其编写应用程序。 这些应用通常是许多人使用的具有生产质量的应用。 为了使维护更加容易,我们必须设置一些准则供人们遵循。

In this article, we’ll look at some basic security practices to be aware of writing Node apps.

在本文中,我们将介绍一些基本的安全实践,以了解编写Node应用程序的情况。

使用ORM / ODM库防止查询注入漏洞 (Prevent Query Injection Vulnerabilities with ORM/ODM Libraries)

We should never pass in user-inputted strings straight into our app to prevent SQL or NoSQL injection attacks. Inputs should be validated and sanitized before being passed into database queries.

我们绝不应该将用户输入的字符串直接传递到我们的应用程序中,以防止SQL或NoSQL注入攻击。 在将输入传递到数据库查询之前,应先对其进行验证和清除。

All reputable data access libraries like Sequelize, Knex, and Mongoose have built-in protection against script injection attacks.

所有知名的数据访问库(例如Sequelize,Knex和Mongoose)都具有针对脚本注入攻击的内置保护。

Unsanitized strings can easily destroy data and expose them to unauthorized parties if they’re left unsanitized.

未经消毒的字符串可以很容易地销毁数据,如果未经消毒就可以将其暴露给未经授权的各方。

通用安全最佳实践集合 (Collection of Generic Security Best Practices)

We should keep up-to-date with general security best practices so we can implement them when we’re developing and running apps.

我们应该保持最新的常规安全最佳做法,以便在开发和运行应用程序时可以实施它们。

调整HTTP响应标头以增强安全性 (Adjust the HTTP Response Headers for Enhanced Security)

We can use modules like helmet to secure headers to prevent attacks from using common attacks like cross-site scripting with our apps.

我们可以使用诸如helmet模块来保护标头,以防止攻击通过我们的应用程序使用跨站点脚本之类的常见攻击。

To add helmet and use it, we run:

要添加helmet并使用它,我们运行:

npm i helmet

and then use it as follows:

然后按如下方式使用它:

const express = require('express');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const app = express();
app.use(helmet());app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));app.get('/', (req, res) => {
res.send('hello');
});app.listen(3000, () => console.log('server started'));

Helmet automatically protects us from cross-site scripting, enables strict transport security, and keep clients from sniffing the MIME types from responses.

头盔自动保护我们免受跨站点脚本攻击,实现严格的传输安全性,并防止客户端从响应中嗅探MIME类型。

The X-Powered-By header is also removed from the response so that attackers won’t know that our app is an Express app.

X-Powered-By标头也会从响应中删除,这样攻击者就不会知道我们的应用程序是Express应用程序。

不断自动检查脆弱的依赖关系 (Constantly and Automatically Inspect for Vulnerable Dependencies)

We can use npm audit or snyk to check for packages with vulnerable dependencies before going to production. Otherwise, attacks may take advantage of the vulnerabilities to commit attacks.

在投入生产之前,我们可以使用npm audit或snyk来检查具有易受依赖项的软件包。 否则,攻击可能会利用这些漏洞进行攻击。

避免使用Node.js加密库来处理密码,请使用Bcrypt (Avoid Using the Node.js crypto Library for Handling Passwords, use Bcrypt)

bcrypt provides hash and salt functionality. Therefore it’s better for handling secrets than the built-in crypto library. It’s also faster.

bcrypt提供哈希和盐功能。 因此,与内置的加密库相比,处理秘密更好。 它也更快。

We don’t want attackers to be able to brute-force passwords and tokens with dictionary attacks.

我们不希望攻击者能够通过字典攻击来暴力破解密码和令牌。

转义HTML,JS和CSS输出 (Escape HTML, JS and CSS Output)

We should escape these kinds of code so that attacks can’t run malicious client-side code with our app. Dedicated libraries can explicitly mark the data as pure content and should never be executed.

我们应该转义这些代码,以使攻击无法在我们的应用程序中运行恶意的客户端代码。 专用库可以将数据显式标记为纯内容,并且永远不应执行。

Hussain Badshah on 侯赛因· Unsplash 巴德沙(Unslash)摄

验证传入的JSON模式 (Validate Incoming JSON Schemas)

JSON schemas should be validated to make sure that the income request payload has valid data. For instance, we can use the jsonschema library to validate the structure and values of the JSON that’s sent.

应该验证JSON模式,以确保收入请求有效负载具有有效数据。 例如,我们可以使用jsonschema库来验证发送的JSON的结构和值。

We can use the jsonschema library as follows with an Express app:

我们可以在Express应用程序中使用jsonschema库,如下所示:

const express = require('express');
const bodyParser = require('body-parser');
const Validator = require('jsonschema').Validator;
const v = new Validator();
const app = express();const addressSchema = {
"id": "/SimpleAddress",
"type": "object",
"properties": {
"address": { "type": "string" },
},
"required": ["address"]
};const schema = {
"id": "/SimplePerson",
"type": "object",
"properties": {
"name": { "type": "string" },
"address": { "$ref": "/SimpleAddress" },
},
"required": ["name", "address"]
};v.addSchema(addressSchema, '/SimpleAddress');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));app.post('/person', (req, res) => {
if (v.validate(req.body, schema).errors.length) {
return res.send(400)
}
res.send('success');
});app.listen(3000, () => console.log('server started'));

In the code above, we required the jsonschema library and use its validator. Then we defined the /SimpleAddress schema, which is referenced by the /SimplePerson schema.

在上面的代码中,我们需要jsonschema库并使用其验证程序。 然后,我们定义了/SimpleAddress模式,该模式由/SimplePerson模式引用。

We add the /SimpleAddress schema with:

我们使用以下命令添加/SimpleAddress模式:

v.addSchema(addressSchema, '/SimpleAddress');

to reference it in /SimplePerson .

/SimplePerson引用它。

Then we can check our request body against our schema with:

然后,我们可以使用以下模式对照我们的模式检查请求主体:

v.validate(req.body, schema).errors.length

Then we stop the request from proceeding if the request body fails validation.

然后,如果请求主体验证失败,我们将停止继续处理请求。

支持将JWT列入黑名单 (Support blacklisting JWTs)

JSON Web Tokens (JWTs) that were used for malicious user activity should be revoked. Therefore, our app needs a way to revoke these tokens.

应该撤销用于恶意用户活动的JSON Web令牌(JWT)。 因此,我们的应用程序需要一种方法来撤销这些令牌。

结论 (Conclusion)

We should secure our app by checking for vulnerabilities and revoking tokens that were used for malicious purposes. Also, we need to take steps to prevent malicious from running on client and server-side by sanitizing data everywhere.

我们应该通过检查漏洞和吊销用于恶意目的的令牌来保护我们的应用程序。 另外,我们需要采取措施,通过在各处清理数据来防止恶意软件在客户端和服务器端运行。

Finally, we should validate request bodies to make sure that valid data is submitted to our app.

最后,我们应该验证请求主体,以确保将有效数据提交到我们的应用程序。

翻译自: https://levelup.gitconnected.com/node-js-best-practices-security-attacks-999a82fe5c36

你可能感兴趣的:(安全,java,python,算法,https)