Django REST Framework (DRF) Cheat Sheet / Django REST 框架 (DRF) 技巧表¶
Introduction / 介绍¶
This cheat sheet provides Django REST Framework security advice for developers. It is a basic set of guidelines for Django REST developers who need to secure fundamental aspects of an application.
此技巧表为开发者提供了 Django REST 框架的安全建议。它是 Django REST 开发者需要确保应用程序基本方面安全的基本指南集。
For the original analysis of unsafe deserialization and serializer field selection, see sections 4.4.1.12 and 4.4.1.18 of Django REST Framework (DRF) Secure Code Guidelines.
有关不安全反序列化和序列化器字段选择的原分析,请参阅 Django REST 框架 (DRF) 安全代码指南 的第 4.4.1.12 和 4.4.1.18 节。
What is a view in Django? / Django 中的视图是什么?¶
A view in Django is a Python class or a function that returns a web response after it receives a web request. That response can be in simple HTTP, an HTML template, or an HTTP redirect request that redirects a user to another page.
Django 中的视图是一个 Python 类或函数,它在接收到网络请求后返回一个网络响应。该响应可以是简单的 HTTP、HTML 模板或 HTTP 重定向请求,该请求将用户重定向到另一个页面。
Settings / 设置¶
To configure the Django REST Framework (DRF), you will need to access the namespace REST_FRAMEWORK. Normally, you will find this namespace in the settings.py file. From a security perspective, the most relevant items are:
要配置 Django REST 框架 (DRF),您需要访问 REST_FRAMEWORK 命名空间。通常,您可以在 settings.py 文件中找到此命名空间。从安全角度来看,最相关的项包括:
DEFAULT_AUTHENTICATION_CLASSES¶
A list of authentication classes that are used by default to identify which user is authenticated by accessing the request.user or request.auth properties. These classes are 'rest_framework.authentication.SessionAuthentication' (session authentication) and 'rest_framework.authentication.BasicAuthentication' (basic authentication).
默认使用的身份验证类列表,用于通过访问request.user或request.auth属性来识别哪个用户被认证。这些类包括'rest_framework.authentication.SessionAuthentication'(会话认证)和'rest_framework.authentication.BasicAuthentication'(基本认证)。
DEFAULT_PERMISSION_CLASSES¶
A list of permission classes that defines the default set of permissions that Django checks before a view can be accessed. Since the default is 'rest_framework.permissions.AllowAny', that means unless the default permission class is changed, everybody can access every view by default.
权限类列表,定义了Django在视图可访问之前检查的默认权限集。由于默认为'rest_framework.permissions.AllowAny',这意味着除非更改默认权限类,否则默认情况下所有人都可以访问所有视图。
DEFAULT_THROTTLE_CLASSES¶
A list of throttle classes that determines the default set of throttles checked at the start of a view. By default, there is no throttling in place since the default class is empty.
在视图开始时确定默认节流集的节流类列表。默认情况下,没有设置节流,因为默认类为空。
DEFAULT_PAGINATION_CLASS¶
The default class to use for queryset pagination. In Django, pagination is disabled by default. Without proper pagination, Denial of Service (DoS) problems or attacks could occur if there’s a lot of data.
用于查询集分页的默认类。在Django中,分页默认是禁用的。如果没有适当的分页,可能会出现大量数据时的拒绝服务(DoS)问题或攻击。
OWASP API Security Top 10 (2019) / OWASP API安全十大(2019)¶
The OWASP API Security Top 10 is a list of the most critical security risks for APIs that was developed by the Open Worldwide Application Security Project (OWASP). It is designed to help organizations identify and prioritize the most significant risks to their APIs so that they can implement appropriate controls to mitigate those risks.
OWASP API 安全性前10名 是由 开放式网络应用安全项目 (OWASP) 开发的一份针对 API 最关键安全风险的列表。它旨在帮助组织识别和优先处理对其 API 最重大的风险,以便他们可以实施适当的控制措施来减轻这些风险。
This section uses the 2019 version of the API Security Top 10. The best approach to securing your web API is to start at the top threat (A1 below) and work your way down. This will ensure that any time spent on security will be spent most effectively because you will cover the top threats first. After you look at the Top 10, it is generally advisable to assess for other threats or get a professional penetration test.
本节使用 2019 版本的 API 安全性前10名。确保您的 Web API 安全的最佳做法是从最顶层的威胁(以下 A1)开始,逐步向下工作。这将确保您在安全方面的任何投入都将最有效地使用,因为您将首先覆盖顶级威胁。在查看前10名之后,通常建议评估其他威胁或进行专业的渗透测试。
API1:2019 Broken Object Level Authorization / API1:2019 破碎的对象级别授权¶
When using object-level permissions, you should make sure that the object can be accessed by the user using the method .check_object_permissions(request, obj).
当使用对象级别权限时,您应确保该对象可以通过使用方法 .check_object_permissions(request, obj) 被用户访问。
Example:
示例:
def get_object(self):
obj = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"])
self.check_object_permissions(self.request, obj)
return obj
DO NOT override the method get_object() without checking if the request should have access to that object.
不要在没有检查请求是否应该访问该对象的情况下覆盖方法 get_object()。
API2:2019 Broken User Authentication / API2:2019 破碎的用户认证¶
To prevent broken user authentication, use the setting value DEFAULT_AUTHENTICATION_CLASSES with the correct classes for your project and have authentication on every non-public API endpoint. Do not overwrite the authentication class on a class-based (variable authentication_classes) or function-based (decorator authentication_classes) view unless you are confident about the change and understand the impact.
为了防止破碎的用户认证,使用设置值 DEFAULT_AUTHENTICATION_CLASSES 并为您的项目选择正确的类,并在每个非公开 API 端点上进行认证。除非您对更改有信心并理解其影响,否则不要在基于类的(变量 authentication_classes)或基于函数的(装饰器 authentication_classes)视图中覆盖认证类。
API3:2019 Excessive Data Exposure / API3:2019 过度数据暴露¶
To prevent this problem, only display the minimum amount of required information. Make sure you review the serializer and the information you are displaying. If the serializer is inheriting from ModelSerializer, DO NOT use the exclude Meta property.
为防止此问题,仅显示所需的最少信息。确保您已审查序列化器和您显示的信息。如果序列化器继承自 ModelSerializer,请勿使用 exclude Meta 属性。
API4:2019 Lack of Resources & Rate Limiting / API4:2019 资源不足与速率限制¶
Configure DEFAULT_THROTTLE_CLASSES and DEFAULT_THROTTLE_RATES for application usage policies, and review any per-view overrides. DRF explicitly warns that its built-in throttling is not a security defense against brute force or denial-of-service attacks. Its cache operations are non-atomic, so concurrent requests can exceed the configured limit.
配置 DEFAULT_THROTTLE_CLASSES 和 DEFAULT_THROTTLE_RATES 以用于应用程序使用策略,并审查任何视图级别的覆盖。DRF 明确警告,其内置速率限制不是针对暴力破解或拒绝服务攻击的安全防御。其缓存操作是非原子的,因此并发请求可能会超过配置的限制。
Enforce abuse controls at the reverse proxy or API gateway as well as in the application. Apply request-size and resource limits; see the Denial of Service Cheat Sheet for layered defenses.
在反向代理或 API 网关以及应用程序中强制执行滥用控制。应用请求大小和资源限制;参见拒绝服务攻击备忘录以了解分层防御。
API5:2019 Broken Function Level Authorization / API5:2019 函数级别授权损坏¶
To stop this problem, change the default value ('rest_framework.permissions.AllowAny') of DEFAULT_PERMISSION_CLASSES. Use the setting value DEFAULT_PERMISSION_CLASSES with the correct classes for your project.
要停止此问题,更改 DEFAULT_PERMISSION_CLASSES 的默认值('rest_framework.permissions.AllowAny')。使用设置值 DEFAULT_PERMISSION_CLASSES 并为您的项目使用正确的类。
DO NOT use rest_framework.permissions.AllowAny except for public API endpoints and DO NOT overwrite the authorization class on a class-based (variable permission_classes) or function-based (decorator permission_classes) view unless you are confident about the change and understand the impact.
除非您对更改有信心并理解其影响,否则请勿使用 rest_framework.permissions.AllowAny,除非是公共 API 端点,并且请勿在基于类的(变量 permission_classes)或基于函数的(装饰器 permission_classes)视图中覆盖授权类。
API6:2019 Mass Assignment / API6:2019 大量赋值¶
For DRF APIs, explicitly allowlist the fields in ModelSerializer.Meta.fields; avoid Meta.exclude and fields = "__all__", which can expose newly added model fields. Follow the serializer field selection guidance. Fields that clients may read but must not change should be read-only: use Meta.read_only_fields for generated fields, or read_only=True on explicitly declared fields. These serializer controls do not replace authorization checks for the requested operation.
API7:2019 Security Misconfiguration¶
To stop this problem, you must have a repeatable hardening process leading to fast and easy deployment of a properly locked down environment. Have an automated process to continuously assess the effectiveness of the configuration and settings in all environments.
DO NOT use default passwords. Set the Django settings DEBUG and DEBUG_PROPAGATE_EXCEPTIONS to False. Ensure API can only be accessed by the specified HTTP verbs. All other HTTP verbs should be disabled. Set SECRET_KEY to a random value and NEVER hardcode secrets.
DO validate, filter, and sanitize all client-provided data, or other data coming from integrated systems.
API8:2019 Injection¶
SQLi¶
To prevent this problem, use parametrized queries. Be careful when using dangerous methods like raw(), extra() and custom SQL (via cursor.execute()). DO NOT add user input to dangerous methods (raw(), extra(), cursor.execute()).
RCE / 远程代码执行¶
To stop this problem, use the Loader=yaml.SafeLoader for YAML files. DO NOT load user-controlled YAML files using the method load().
为防止此问题,在处理 YAML 文件时使用 Loader=yaml.SafeLoader。请勿使用 load() 方法加载用户控制的 YAML 文件。
Also, DO NOT add user input to dangerous methods (eval(), exec() and execfile()) and DO NOT load user-controlled pickle files, which includes the pandas method pandas.read_pickle().
同样,请勿将用户输入添加到危险的方法(eval()、exec() 和 execfile())中,并且请勿加载用户控制的 pickle 文件,这包括 pandas 的 pandas.read_pickle() 方法。
API9:2019 Improper Assets Management / API9:2019 不当资产管理¶
To prevent this problem, create an inventory of all API hosts. In this inventory, document the important aspects of each host. Focus on the API version and the API environment (e.g., production, staging, test, development) and determine who should have network access to the host (e.g., public, internal, partners). Make sure you document all aspects of your API such as authentication, errors, redirects, rate limiting, cross-origin resource sharing (CORS) policy and endpoints, including their parameters, requests, and responses.
为防止此问题,创建所有 API 主机的清单。在此清单中,记录每个主机的关键信息。重点关注 API 版本和 API 环境(例如,生产、预发布、测试、开发)以及确定谁应该有权访问主机(例如,公开、内部、合作伙伴)。确保记录您 API 的所有方面,如身份验证、错误、重定向、速率限制、跨源资源共享(CORS)策略和端点,包括它们的参数、请求和响应。
API10:2019 Insufficient Logging & Monitoring / API10:2019 日志记录和监控不足¶
For proper logging and monitoring capabilities, do the following:
为了实现适当的日志记录和监控功能,请执行以下操作:
--Log all failed authentication attempts, denied access, and input validation errors with sufficient user context to identify suspicious or malicious accounts.
--记录所有失败的认证尝试、拒绝访问和输入验证错误,并包含足够的使用上下文以识别可疑或恶意账户。
--Create logs in a format suited to be consumed by a log management solution and include enough detail to identify the malicious actor.
--以适合日志管理解决方案消费的格式创建日志,并包含足够详细的信息以识别恶意行为者。
--Handle logs as sensitive data, and their integrity should be guaranteed at rest and transit.
--将日志视为敏感数据,并确保其在静态和传输过程中的完整性。
--Configure a monitoring system to continuously monitor the infrastructure, network, and the API functioning.
--配置监控系统以持续监控基础设施、网络和API的功能。
--Use a Security Information and Event Management (SIEM) system to aggregate and manage logs from all components of the API stack and hosts.
--使用安全信息和事件管理(SIEM)系统来聚合和管理API堆栈和主机所有组件的日志。
--Configure custom dashboards and alerts, enabling suspicious activities to be detected and responded to earlier.
--配置自定义仪表板和警报,以便更早地检测和响应可疑活动。
--Establish effective monitoring and alerting so suspicious activities are detected and responded to in a timely fashion.
--建立有效的监控和警报机制,以便及时检测和响应可疑活动。
DO NOT:
--Log generic error messages such as: Log.Error("Error was thrown"); rather log the stack trace, error message and user ID who caused the error.
--记录通用错误消息,例如:Log.Error("Error was thrown"); 而应记录堆栈跟踪、错误消息和导致错误的用户ID。
--Log sensitive data such as user's passwords, API Tokens or PII.
--记录敏感数据,例如用户密码、API令牌或PII。
Other Security Risks / 其他安全风险¶
Below is a list of security risks for APIs not discussed in the OWASP API Security Top 10.
以下是一份未在OWASP API安全前10中讨论的安全风险列表。
Business Logic Bugs / 业务逻辑错误¶
Be aware of possible business logic errors that result in security bugs. Since business logic bugs are difficult to impossible to detect using automated tools, the best ways to prevent business logic security bugs are use threat models, do security design reviews, do code reviews, pair programs and write unit tests.
注意可能导致安全漏洞的业务逻辑错误。由于业务逻辑错误难以或无法使用自动化工具检测,预防业务逻辑安全漏洞的最佳方法是使用威胁模型、进行安全设计审查、进行代码审查、结对编程和编写单元测试。
Secret Management / 秘密管理¶
Secrets should never be hardcoded. The best practice is to use a Secret Manager. For more information review OWASP Secrets Management Cheat Sheet
秘密绝不应该硬编码。最佳实践是使用秘密管理器。 更多信息请参阅OWASP 秘密管理备忘单
Updating Django and DRF and Having a Process for Updating Dependencies / 更新Django和DRF以及更新依赖项的流程¶
All applications have dependencies and those dependencies can have vulnerabilities. One good practice is to audit the dependencies your project is using. In general, it is important to have a process for updating dependencies. A sample process might define three mechanisms for triggering an update of response:
--Every month/quarter dependencies in general are updated. --Every week important security vulnerabilities are considered and potentially trigger an update. --In EXCEPTIONAL conditions, emergency updates may need to be applied.
The Django Security team has information on How Django discloses security issues.
When a library is under consideration, consider the "Security Health" of the library. How often it's updated? Does it have known vulnerabilities? Does it have an active community? etc. Some tools can help with this task (E.g. Snyk Advisor)
SAST Tools¶
There are several excellent open-source static analysis security tools for Python that are worth considering, including:
Bandit – Bandit is a tool designed to find common security issues in Python. Bandit processes each file, builds an Abstract Syntax Tree (AST) from it, and runs appropriate plugins against the AST nodes. Once Bandit has finished scanning all the files it generates a report. Bandit was originally developed within the OpenStack Security Project and later rehomed to PyCQA.
Semgrep – Semgrep is a fast, open-source, static analysis engine for finding bugs, detecting vulnerabilities in third-party dependencies, and enforcing code standards. Developed by “Return To Corporation” (usually referred to as r2c) and open-source contributors. It works based on rules, which can focus on security, language best practices, or something else. Creating a rule is easy and semgrep is very powerful. For Django there are 29 rules.
PyCharm Security – Pycharm-security is a plugin for PyCharm, or JetBrains IDEs with the Python plugin. The plugin looks at Python code for common security vulnerabilities and suggests fixes. It can also be executed from a Docker container. It has about 40 checks and some are Django specific.
PyCharm 安全 – PyCharm 安全 是 PyCharm 或带有 Python 插件的 JetBrains IDE 的插件。该插件检查 Python 代码中的常见安全漏洞并提出修复建议。它还可以从 Docker 容器中执行。它大约有 40 个检查,其中一些是 Django 特定的。
References / 参考¶
- Security in Django) (Django 安全)
- Django REST framework permissions) (Django REST 框架权限)
- Django REST framework settings) (Django REST 框架设置)