Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Django's security


May 14, 2021 Django


Table of contents


Cross-site scripting (XSS) protection

XSS attacks enable users to inject client scripts into other users' browsers. T ypically, this is done by storing malicious scripts in a database for retrieval and displaying them to other users, or by using a user to click a link that causes an attacker's JavaScript to be executed by the user's browser. However, XSS attacks can originate from any untrusted data source, such as cookies or Web services, as long as the data is not cleaned up enough before it is included in the page.

Use the Django template to protect you from most XSS attacks. However, it is important to understand the protection it provides and its limitations.

Django templates escape specific characters, which is especially dangerous for HTML. A lthough this protects users from most malicious input, it is not absolutely secure. For example, it will not protect the following:

<style class={{ var }}>...</style>

If the var is set, it may result in unauthorized JavaScript execution, depending on how the browser renders imperfect HTML. ( Reference property values will resolve this situation.) )'class1 onmouseover=javascript:func()'

is_safe be especially careful when working with custom template labels, safe mark_safe labels, and turning off auto-escape.

In addition, if you use a template system to output content other than HTML, there may be completely separate characters and words that need to be escaped.

Special care should also be taken when storing HTML in a database, especially when retrieving and displaying HTML.

Request forgery (CSRF) protection across sites

A CSRF attack allows a malicious user to perform an action using another user's credentials without the user's knowledge or consent.

Django has built-in protection against most CSRF attacks, as long as you enable and use it wherever you want. H owever, as with any mitigation technique, there are limitations. F or example, you can disable CSRF modules globally or for specific views. Y ou should only do this if you know what you're doing. If your site has sub-domains that you cannot control, there are additional restrictions.

CSRF protection works by checking the secrets in each POST request. T his ensures that a malicious user cannot "replay" a form POST to your site and that another logged-in user inadvertently submits the form. A malicious user must know a user-specific secret (using cookies).

When deployed with HTTPS, CsrfViewMiddleware checks whether the HTTP reference header is set to a URL on the same source, including sub-domains and ports. Because HTTPS provides additional security, you must ensure that connections are available using HTTPS by forwarding unsecured connection requests and using HTML for supported browsers.

csrf_exempt unless absolutely necessary, carefully mark the view with an decorator.

SQL injection protection

SQL injection is an attack in which a malicious user can execute arbitrary SQL code on a database. This can result in record deletion or data leakage.

Because Django's query set is constructed using query parameterization, SQL injection can be prevented. T he SQL code for a query is defined separately from the parameters of the query. Because parameters can be provided by the user and therefore unsafe, the underlying database driver escapes them.

Django also enables developers to write original queries or perform custom sqls. T hese features should be used with caution, and you should always be careful to escape any parameters that the user can control. In addition, use extra() and when using RawSQL with extreme caution.

Click hijack protection

Clickjacking is an attack in which a malicious site wraps another site in a framework. Such an attack can result in unsuspecting users being tricked into performing unexpected actions on the target site.

Django includes clickjacking protection in the form of a supported browser that prevents websites from rendering within the framework. T he exact header value sent can be disabled for protection or configuration based on each view. X-Frame-Options middleware

It is highly recommended that middleware be used for any site that does not require a third-party site to wrap its pages in a framework, or that only a small part of the site be allowed to use the middleware.

SSL / HTTPS

Deploying a site after HTTPS is always a better option for security. Otherwise, a malicious network user may sniff authentication credentials or any other information transmitted between the client and the server, and in some cases (active network attackers) may change the data sent in either direction.

If you want the protection provided by HTTPS and you have it enabled on the server, you may need to perform some additional steps:

  • If necessary, set up SECURE_PROXY_SSL_HEADER to ensure that you are fully aware of the warnings. Failure to do so can lead to CSRF vulnerabilities, which can be dangerous if done incorrectly!
  • Set SECURE_SSL_REDIRECT to True so that it can be redirected to HTTPS via HTTP requests. P lease note the warning SECURE_PROXY_SSL_HEADER. For reverse agents, it may be easier or more secure to configure the main Web server to redirect to HTTPS.
  • Use "safe" cookies. E xisting cookies may leak if the browser is initially connected via HTTP, which is the default setting for most browsers. T herefore, you should set SESSION_COOKIE_SECURE and CSRF_COOKIE_SECURE settings to True. T his indicates that the browser sends these cookies only over the HTTPS connection. Note that this will mean that the session will not work through HTTP, and CSRF protection will prevent any POST data from being accepted through HTTP (which would be nice if you redirect all HTTP traffic to HTTPS).
  • HSTS using HTTP Strict Transport Security (HSTS) is an HTTP header that informs browsers that all future connections to a particular site should always use HTTPS. C ombined with redirecting requests to HTTPS via HTTP, this ensures that the connection always enjoys the additional security of SSL whenever a successful connection occurs. HSTS can be associated with configuration SECURE_HSTS_SECONDS, SECURE_HSTS_INCLUDE_SUBDOMAINS and SECURE_HSTS_PRELOAD, or on a Web server.

Host header authentication

Host In some cases, Django uses a header provided by the client to construct a URL. Although these values are cleared to prevent cross-site scripting attacks, forged Host values can be used for cross-site request forgery, caching poisoning attacks, and poisoning links in e-mail messages.

Because even seemingly secure Web server configurations are susceptible to fake Host headers, Django verifies headers django.http.HttpRequest.get_host) based on the ALLOWED_HOSTS settings in the method Host.

This verification only get_host ();

For more details, see the full ALLOWED_HOSTS documentation.

Warning: Previous versions of this document recommended configuring a Web server to ensure that it validates the incoming HTTP Host header. A lthough this is still recommended, in many common Web servers, it seems possible to verify that the configuration of the Host header may not actually do so. F or example, even if Apache is configured to serve the Django site from a non-default virtual host with the ServerName setting, it is still possible for HTTP requests to match the virtual host and provide a fake Host header. Therefore, Django now requires you to ALLOWED_HOSTS settings, rather than relying on the Web server configuration.

In addition, if your configuration requires Django, Django requires you to explicitly enable support for the X-Forwarded-Host header (USE_X_FORWARDED_HOST settings).

Referral policy

The browser uses the Referer header as a way to send the user information about where the user arrived. B y setting a referral source URL policy, you can help protect users' privacy and limit the circumstances under which the Referer header is set. For more information, see the Referral Source URL Policy section of the Security Middleware Reference.

Session security

Similar to the CSRF restriction, which requires the deployment of a Web site so that untrusted users cannot access any sub-domains, this django.contrib.sessions also has restrictions. For more information, see the session topic guide section on security.

The content uploaded by the user

Note: Consider providing static files from a cloud service or CDN to avoid some of these issues.

  • If your site accepts file uploads, it is highly recommended that you limit these uploads in your Web server configuration to a reasonable size to prevent denial of service (DOS) attacks. In Apache, you can easily set this value using the LimitRequestBody directive.
  • If you are providing your own static files, make sure mod_php disable handlers such as Apache, which execute static files as code. You do not want users to be able to execute arbitrary code by uploading and requesting specially eddy files.
  • Django's media upload processing introduces vulnerabilities when media is provided in a way that does not follow security best practices. S pecifically, if an HTML file contains a valid PNG header and malicious HTML, the HTML file can be uploaded as an image. T he file will be verified (pillows) through Django's library for ImageField image processing. W hen the file is then displayed to the user, it may appear as HTML depending on the type and configuration of your Web server. T here is no bulletproof technology solution at the framework level that securely verifies that all users upload file content, but there are other steps you can take to mitigate these attacks: you can prevent a class of attacks by always serving content uploaded by users from different top-level or second-level domains. T his prevents any exploits that are blocked by same-origin policy protection, such as cross-site scripts. F or example, if your site is running example.com, you might want to provide an example of what you MEDIA_URL (usercontent-example.com). T his is not enough to provide content from a sub-domain usercontent.example.com. In addition, the application may choose to whitelist the allowed file extensions for files uploaded by the user and configure the Web server to provide only such files.

Other security topics

Although Django provides good out-of-the-box security, it is important to deploy applications correctly and take advantage of the security of Web servers, operating systems, and other components.

  • Make sure that your Python code is outside the root of the Web server. This will ensure that your Python code is not accidentally used as plain text (or executed unexpectedly).
  • Note any files uploaded by users.
  • Django does not restrict requests for user authentication. To prevent violent attacks on authentication systems, you may want to consider deploying Django plug-ins or Web server modules to limit these requests.
  • Keep SECRET_KEY secret
  • It is a good idea to use a firewall to restrict the accessability of the cache system and database.
  • Review the top 10 lists of open Web application security projects (OWASPs) that identify some common vulnerabilities in Web applications. Although Django has the tools to solve some problems, other issues must be considered in the project design.
  • Mozilla discusses various topics related to Web security. Their pages also contain security principles that apply to any system.

For more information: https://docs.djangoproject.com/en/3.0/