Skip to main content

Node.js 安全

Summary

  • Request and Response
    • HTTPS protocol
    • Rate Limiting
    • Response headers & helmet
  • Application
    • Check input and token
      • JSON Schema Validation
      • Password Encryption
      • Escaping HTML & CSS
      • Limiting the Payload Size
    • Auth
      • JWT Blacklisting
      • Authentication Limis
    • Interaction with database
      • ORM/ODM against Injections
    • Tools
      • Security Linter
      • Vulnerability Inspections
  • Configuration environment
    • Running Node.js as Non-Root User
    • Module Loading with a Variable

1. Rate Limiting

DDsS attack(Distributed Denial of Service attack)

express-rate-limit: https://www.npmjs.com/package/express-rate-limit

不适合可扩展的大型项目,因为你的 NodeJS 项目更多关心的是商业的逻辑代码,rate limiter 应该是代理 nginx 的事情。

在云环境中已经有 rate limiting 的功能,比如 AWS API Gateway 已经集成这项功能。

2. Password Encryption

bcrypt: https://www.npmjs.com/package/bcrypt

hash, salt

3. JWT Blacklisting

Save JWT in the database to check if the JWT is validated.

Generate JWT with to token, one short-term authentication token and second long-term refresh token.

4. JSON Schema Validation

jsonschema: https://www.npmjs.com/package/jsonschema

"Typescript" for HTTP calls.

5. Escaping HTML & CSS

escapte-html: https://www.npmjs.com/package/escape-html

Issues: SQL Injection for string with '&' or others.

6. ORM/ODM against Injections

Sequelize: https://www.npmjs.com/package/sequelize
Mongoose: https://www.npmjs.com/package/mongoose
prisma: https://www.npmjs.com/package/prisma

7. Security Linter

eslint-plugin-security: https://www.npmjs.com/package/eslint-plugin-security

8. Running Node.js as Non-Root User

Wrong

From node:latest

COPY package.json .
RUN num install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]

Good

From node:latest

COPY package.json .
RUN num install
COPY . .
EXPOSE 3000
User node # Add node user as the operator
CMD ["node", "server.js"]

9. Module Loading with a Variable

Wrong

const badWayToRequireUploadHelpers = require(helperPath);

Good

const uploadHelpers = require("./helpers/upload");

10. Limiting the Payload Size

rate-limiter-flexible: https://www.npmjs.com/package/rate-limiter-flexible

11. Authentication Limis

当用户在一定时间内连续登录错误,我们会在接下来一段时间内锁定账户。

12. HTTP response headers & helmet

helmet: https://www.npmjs.com/package/helmet

13. Vulnerability Inspections

这是为非常大的项目需要的,因为大项目需要非常多的依赖包,因此我们需要检测依赖包的漏洞以防止此类漏洞上线。

npm audit

https://docs.npmjs.com/cli/v9/commands/npm-audit

GitHub Dependabot

https://docs.github.com/en/code-security/getting-started/dependabot-quickstart-guide

历史

  • 2024-02-29, created by xiaoka, first commit