博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Node.js+Express商业开发中的安全性考虑
阅读量:5979 次
发布时间:2019-06-20

本文共 9101 字,大约阅读时间需要 30 分钟。

无论基于什么技术进行网站开发,安全性都是第一位的,特别是对于一些数据敏感性网站而言。本文引用的文章来自于Express.js官方网站,应当是每一个基于Express.js(或者基于此框架的更高级框架)进行开发所必须了解并逐渐掌握的技术。因为数据的安全问题不得不使我们尽可能从往最好处打算,而且从最坏处作准备。原文如下:

=================

Production Best Practices: Security

Overview

The term “production” refers to the stage in the software lifecycle when an application or API is generally available to its end-users or consumers. In contrast, in the “development” stage, you’re still actively writing and testing code, and the application is not open to external access. The corresponding system environments are known as production and development environments, respectively.

Development and production environments are usually set up differently and have vastly different requirements. What’s fine in development may not be acceptable in production. For example, in a development environment you may want verbose logging of errors for debugging, while the same behavior can become a security concern in a production environment. And in development, you don’t need to worry about scalability, reliability, and performance, while those concerns become critical in production.

This article discusses some security best practices for Express applications deployed to production.

NOTE: If you believe you have discovered a security vulnerability in Express, please see .

Don’t use deprecated or vulnerable versions of Express

Express 2.x and 3.x are no longer maintained. Security and performance issues in these versions won’t be fixed. Do not use them! If you haven’t moved to version 4, follow the .

Also ensure you are not using any of the vulnerable Express versions listed on the . If you are, update to one of the stable releases, preferably the latest.

Use TLS

If your app deals with or transmits sensitive data, use  (TLS) to secure the connection and the data. This technology encrypts data before it is sent from the client to the server, thus preventing some common (and easy) hacks. Although Ajax and POST requests might not be visibly obvious and seem “hidden” in browsers, their network traffic is vulnerable to  and .

You may be familiar with Secure Socket Layer (SSL) encryption. . In other words, if you were using SSL before, consider upgrading to TLS. In general, we recommend Nginx to handle TLS. For a good reference to configure TLS on Nginx (and other servers), see .

Also, a handy tool to get a free TLS certificate is , a free, automated, and open certificate authority (CA) provided by the .

Use Helmet

 can help protect your app from some well-known web vulnerabilities by setting HTTP headers appropriately.

Helmet is actually just a collection of nine smaller middleware functions that set security-related HTTP headers:

  •  sets the Content-Security-Policy header to help prevent cross-site scripting attacks and other cross-site injections.

  •  removes the X-Powered-By header.

  •  Adds  headers to prevent man-in-the-middle attacks with forged certificates.

  •  sets Strict-Transport-Security header that enforces secure (HTTP over SSL/TLS) connections to the server.

  •  sets X-Download-Options for IE8+.

  •  sets Cache-Control and Pragma headers to disable client-side caching.

  •  sets X-Content-Type-Options to prevent browsers from MIME-sniffing a response away from the declared content-type.

  •  sets the X-Frame-Options header to provide  protection.

  •  sets X-XSS-Protection to enable the Cross-site scripting (XSS) filter in most recent web browsers.

Install Helmet like any other module:

$ npm install --save helmet

Then to use it in your code:

...var helmet = require('helmet');app.use(helmet());...

At a minimum, disable X-Powered-By header

If you don’t want to use Helmet, then at least disable the X-Powered-By header. Attackers can use this header (which is enabled by default) to detect apps running Express and then launch specifically-targeted attacks.

So, best practice is to to turn off the header with the app.disable() method:

app.disable('x-powered-by');

If you use helmet.js, it takes care of this for you.

Use cookies securely

To ensure cookies don’t open your app to exploits, don’t use the default session cookie name and set cookie security options appropriately.

There are two main middleware cookie session modules:

  •  that replaces express.session middleware built-in to Express 3.x.

  •  that replaces express.cookieSession middleware built-in to Express 3.x.

The main difference between these two modules is how they save cookie session data. The  middleware stores session data on the server; it only saves the session ID in the cookie itself, not session data. By default, it uses in-memory storage and is not designed for a production environment. In production, you’ll need to set up a scalable session-store; see the list of .

In contrast,  middleware implements cookie-backed storage: it serializes the entire session to the cookie, rather than just a session key. Only use it when session data is relatively small and easily encoded as primitive values (rather than objects). Although browsers are supposed to support at least 4096 bytes per cookie, to ensure you don’t exceed the limit, don’t exceed a size of 4093 bytes per domain. Also, be aware that the cookie data will be visible to the client, so if there is any reason to keep it secure or obscure, then express-session may be a better choice.

Using the default session cookie name can open your app to attacks. The security issue posed is similar to X-Powered-By: a potential attacker can use it to fingerprint the server and target attacks accordingly.

To avoid this problem, use generic cookie names; for example using  middleware:

var session = require('express-session');app.set('trust proxy', 1) // trust first proxyapp.use( session({   secret : 's3Cur3',   name : 'sessionId',  }));

Set the following cookie options to enhance security:

  • secure - Ensures the browser only sends the cookie over HTTPS.

  • httpOnly - Ensures the cookie is sent only over HTTP(S), not client JavaScript, helping to protect against cross-site scripting attacks.

  • domain - indicates the domain of the cookie; use it to compare against the domain of the server in which the URL is being requested. If they match, then check the path attribute next.

  • path - indicates the path of the cookie; use it to compare against the request path. If this and domain match, then send the cookie in the request.

  • expires - use to set expiration date for persistent cookies.

Here is an example using  middleware:

var session = require('cookie-session');var express = require('express');var app = express();var expiryDate = new Date( Date.now() + 60 * 60 * 1000 ); // 1 hourapp.use(session({  name: 'session',  keys: ['key1', 'key2'],  cookie: { secure: true,            httpOnly: true,            domain: 'example.com',            path: 'foo/bar',            expires: expiryDate          }  }));

Ensure your dependencies are secure

Using npm to manage your application’s dependencies is powerful and convenient. But the packages that you use may contain critical security vulnerabilities that could also affect your application. The security of your app is only as strong as the “weakest link” in your dependencies.

Use either or both of the following two tools to help ensure the security of third-party packages that you use:  and . These two tools do largely the same thing.

 is a command-line tool that checks the  vulnerability database to determine if your application uses packages with known vulnerabilities. Install it as follows:

$ npm i nsp -g

Use this command to submit the npm-shrinkwrap.json / package.json files for validation to :

$ nsp check

Here’s how to use  to audit your Node modules:

$ npm install -g requiresafe$ cd your-app$ requiresafe check

Additional considerations

Here are some further recommendations from the excellent . Refer to that blog post for all the details on these recommendations:

  • Implement rate-limiting to prevent brute-force attacks against authentication. One way to do this is to use  to enforce a rate-limiting policy. Alternatively, you can use middleware such as , but doing so will require you to modify your code somewhat.

  • Use  middleware to protect against cross-site request forgery (CSRF).

  • Always filter and sanitize user input to protect against cross-site scripting (XSS) and command injection attacks.

  • Defend against SQL injection attacks by using parameterized queries or prepared statements.

  • Use the open-source  tool to detect SQL injection vulnerabilities in your app.

  • Use the  and  tools to test the configuration of your SSL ciphers, keys, and renegotiation as well as the validity of your certificate.

  • Use  to ensure your regular expressions are not susceptible to  attacks.

Avoid other known vulnerabilities

Keep an eye out for  advisories that may affect Express or other modules that your app uses. In general, the Node Security Project is an excellent resource for knowledge and tools about Node security.

Finally, Express apps - like any other web apps - can be vulnerable to a variety of web-based attacks. Familiarize yourself with known  and take precautions to avoid them.

=================

转载地址:http://hxaox.baihongyu.com/

你可能感兴趣的文章
MySQL5.6中新增特性、不推荐使用的功能以及废弃的功能
查看>>
OnePlus安装Kali-NetHunter
查看>>
[Oracle][DataGuard]Standby数据库文件有损坏时的处理方法
查看>>
JavaScript:Array 对象
查看>>
PDFCreator:一款免费,开源的PDF(Tiff,pcx,png,jpeg,bmp,PS,EPS)打印机(VB,GPL),并提供了COM接口,方便使用各种编程语言调用...
查看>>
Note 1773479 - SYB: Displaying multiple triggers per object
查看>>
联手云计算核心技术开发,BoCloud与中科院软件所战略合作
查看>>
2017年背景下的SSD选购技巧有哪些变化?
查看>>
2016年的数据存储和管理的成本将何去何从?
查看>>
Airpods 并非无用,而是苹果借助语音交互布局物联网的新“棋子”
查看>>
项目总结:数据迁移测试
查看>>
SQL中存储过程的创建和使用
查看>>
荷兰政府:保证不强制在任何产品中留有后门
查看>>
编写单元测试的10条理由
查看>>
LINUX-SAMBA服务配置
查看>>
图像处理------光束效果
查看>>
剑指offer 面试题6:重建二叉树
查看>>
智能合约从入门到精通:Solidity语法之内存变量的布局和状态变量的存储模型...
查看>>
基于ES5`defineProperty` 实现简单的 Mvvm框架
查看>>
关于UI设计的一些工作了解
查看>>