Security Testing - Django Defense Security Policy

Django Security
Django has some processing for security. Learning how to process settings is also conducive to learning security testing knowledge.

CSRF

Cross-Site Request Forgery (Cross-Site Request Forgery, CSRF) is a network attack method in which attackers deceive users to perform malicious operations on the websites they visit, and send requests without user permission by using the user's current identity and permissions .

In layman's terms, let's say you're browsing a social media site and you're logged in. In another tab, you clicked on a malicious link you got via email or otherwise, and you didn't realize it was malicious. The link is actually a request to your bank's website, and the attacker has included some malicious actions in the link, such as transferring money to the attacker's account. If you happen to be logged in on a banking website that doesn't have CSRF defenses in place, this malicious operation could be successful.

Common Defenses

To defend against CSRF attacks, the following are some commonly used defenses:

  1. CSRF Token: The application can generate a unique CSRF token for each user and embed it in the request. Every POST request submitted needs to include this token and be validated on the server side. In this way, a malicious website cannot obtain a valid token and cannot correctly construct a request.

  2. SameSite Cookie: By setting the SameSite attribute to Strict or Lax, you can restrict cookies to be automatically attached only to requests initiated by the same site. This prevents cross-site request attacks.

  3. Verify source domain name: The server can verify the source domain name of the request, and if the request does not come from a legal domain name, it will refuse to perform the operation. The origin can be verified using the Referer header, the Origin header, or by checking the host field.

  4. Double confirmation: For sensitive operations, users can be required to enter additional confirmation information, such as passwords, verification codes, etc., to add an additional layer of security.

  5. Secure coding practices: Developers should follow secure coding practices, such as properly escaping and validating user input, avoiding disclosing sensitive information in requests, etc.

These defenses can increase the security of your website against CSRF attacks. However, the situation of each website may be different. It is very important to customize and apply a CSRF defense strategy suitable for your own application by comprehensively considering other factors such as error messages, access control, and security auditing.

django-defense

1) CSRF middleware is activated by default in MIDDLEWARE configuration. If you override this configuration, remember that 'django.middleware.csrf.CsrfViewMiddleware' should be ordered before any view middleware that assumes CSRF attacks have been handled.
2) In the template using the POST form, the template adds

<form method="post">{% csrf_token %}

SQL injection

SQL injection enables malicious users to execute arbitrary SQL code in the database. This will result in records being deleted or compromised.

Django's querysets are protected from SQL injection as they are constructed from parameterized queries. The query's SQL code is defined separately from the query's parameters. Parameters may come from the user and thus be unsafe, so they are escaped by the underlying database engine.

Django also provides developers with the power to write raw queries or execute custom sql. These methods should be used as sparingly as possible, and you should be careful to properly escape any user-controllable parameters. Also, care should be taken when using extra() with RawSQL.

Defense against clickjacking-Clickjacking protection

Prevent web pages from being embedded in other iframes
Browsers support the X-Frame-Options HTTP header, which indicates whether resources are allowed to be loaded in frames or iframes. If the response contains a header with the value SAMEORIGIN, the browser will only load the resource in the frame if the request comes from the same website. If the header is set to DENY, then the browser will prevent the resource from loading in the frame, no matter which website the request is made from.

django clickjacking

https://docs.djangoproject.com/zh-hans/4.2/ref/clickjacking/#clickjacking-prevention
Suppose an online store has a page where logged-in users can click "Buy Now" to purchase items. For convenience, the user chooses to stay logged into the store. An attacker site could create an "I Like Ponies" button on one of its pages and load the store's page in a transparent iframe, with the "Buy Now" button invisibly overlaid on top of the "I Like Ponies" button. If a user visits the attacker's website, clicking "I Like Ponies" will result in inadvertently clicking the "Buy Now" button and purchasing the item without their knowledge.

Django defense example

If you directly access the django application,
insert image description here
insert image description here
you can see that X-Frame-Options is set to DENY, which prohibits embedding other iframes.

An html containing an iframe embeds the address

<!DOCTYPE html>
<html>
<head>
    <title>包含 iframe 的页面</title>
</head>
<body>
    <h1>这是一个包含 iframe 的页面</h1>
    
    <iframe src="http://127.0.0.1:8000/polls/" width="500" height="300"></iframe>
</body>
</html>

Visit this html and find that the webpage cannot be displayed
insert image description here

User uploaded content attack

User-uploaded content attacks refer to malicious users or attackers uploading content containing malicious code or malicious files on a website or application for attack or abuse.

This attack can lead to the following security issues:

  1. Code Injection: An attacker may upload files containing malicious scripts that will be executed in other users' browsers when they access those files. This type of attack is called code injection or remote code execution (Remote Code Execution, RCE), which can cause the browser of the attacked user to be controlled and perform arbitrary malicious operations.

  2. File inclusion vulnerabilities: An attacker may upload files containing sensitive data or system file paths to discover and exploit file inclusion vulnerabilities. By exploiting these vulnerabilities, an attacker could be able to read, replace, or delete important files on the system.

  3. Malicious file distribution: Attackers may upload files containing malware, viruses, or ransomware. When other users download or execute these files, their computers may be infected or exposed to threats such as data leakage, data corruption, or ransomware.

Common Security Measures

To defend against user-uploaded content attacks, the following are some commonly used security measures:

  1. File type verification: Limit the file types uploaded by users, and verify the extension and MIME type of uploaded files. Only trustworthy and safe file types are allowed to be uploaded, and unknown or high-risk file types are rejected.

  2. File size limit: Limit the size of uploaded files to avoid exceeding the processing capacity of the server or application.

  3. File Containment Vulnerability Fixes and Security Configurations: Ensure that the application has fixed code issues that could lead to file containment vulnerabilities, and has appropriate security configurations on the server to restrict access to sensitive files and avoid exposing information such as system paths.

  4. Secure file storage: Store user-uploaded files in a secure location and take steps to ensure files cannot be executed or downloaded through direct access. Store uploaded files in non-web-accessible directories, and use server-side scripts to provide secure read and download interfaces.

  5. Secure coding practices: During development, use proper input validation and output encoding techniques to prevent security issues such as code injection and cross-site scripting (XSS).

To sum up, user-uploaded content attack is a serious security threat. Appropriate security measures should be taken during the design, development, and maintenance of applications to defend against such attacks, and regular security audits and vulnerability scans should be performed as well as timely repairs. Vulnerabilities found.

django-suggestion

1) Consider serving static files from a cloud service or CDN to avoid such issues.
2) Limit these uploaded files to a reasonable size in the web server configuration to prevent denial of service (DOS) attacks. In Apache, you can use the LimitRequestBody directive
3) Make sure that handlers like Apache's mod_php that can execute static files as code are turned off
4) Optionally define a list to limit the file extensions that users are allowed to upload

other suggestion

  1. Make sure your Python code is outside the web server's root directory. This will ensure that your Python code is not accidentally served (or accidentally executed) as plain text.
  2. Be careful with all user-uploaded files. Django does not throttle requests for authenticated users. To prevent brute force attacks against the authentication system, you might consider deploying a Django
    plugin or web server module to throttle these requests.
  3. Keep your SECRET_KEY, and SECRET_KEY_FALLBACKS if in use, secret. It is a good idea to restrict the accessibility of cache systems and databases with a firewall
  4. Take a look at the Open Source Web Application Security Project (OWASP) Top 10 list, which specifies some common vulnerabilities in web applications. While Django
    has the tools to solve some problems, others must be considered in project design.
    2023 edition: https://owasp.org/API-Security/editions/2023/en/0x11-t10/
  5. Mozilla discusses many topics related to web security. Their webpage also includes security principles that apply to any system.

Guess you like

Origin blog.csdn.net/seanyang_/article/details/132543051