Django Framework

Django Framework

Basic Information regarding Django framework

Everything about Django

What is Django?

  • Django is a high-level Python web framework that enables the rapid development of secure and maintainable websites.
  • Django creates a boilerplate of a website so that we can only focus on building the main app.
  • It's free and open-source and has a big community.

Django's MVT architecture

Django framework is based on the MODELS - VIEW - TEMPLATE architecture

django-mvt.png

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other clients). When a request is received the application works out what is needed based on the URL and possibly information in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request.

The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

Django web applications typically group the code that handles each of these steps into separate files:

Screenshot 2021-09-24 at 5.30.09 PM.png

  • URLs: While it is possible to process requests from every single URL via a single function, it is much more maintainable to write a separate view function to handle each resource. A URL mapper is used to redirect HTTP requests to the appropriate view based on the request URL. The URL mapper can also match particular patterns of strings or digits that appear in a URL and pass these to a view function as data.

  • View: A view is a request handler function, which receives HTTP requests and returns HTTP responses. Views access the data needed to satisfy requests via models and delegate the formatting of the response to templates.

  • Models: Models are Python objects that define the structure of an application's data and provide mechanisms to manage (add, modify, delete) and query records in the database.

  • Templates: A template is a text file defining the structure or layout of a file (such as an HTML page), with placeholders used to represent actual content. A view can dynamically create an HTML page using an HTML template, populating it with data from a model. A template can be used to define the structure of any type of file; it doesn't have to be HTML!

Security Features in Django

  • Cross Site Scripting(XSS)

XSS attacks allow a user to inject client-side scripts into the browsers of other users. This is usually achieved by storing the malicious scripts in the database where it will be retrieved and displayed to other users, or by getting users to click a link that will cause the attacker’s JavaScript to be executed by the user’s browser. However, XSS attacks can originate from any untrusted source of data, such as cookies or Web services, whenever the data is not sufficiently sanitized before including in a page.

Django templates escape specific characters which are particularly dangerous to HTML. While this protects users from most malicious input, it is not entirely foolproof.

If an attack is detected, the browser will prevent the rendering of the page.

To enable it in Django, make sure Django.middleware.security.SecurityMiddleware is present in the middleware's list and adds the following lines in your settings.py file.

```
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
```

Cross Site Scripting(XSS)

sorted-XSS.png

  • Cross site request forgery (CSRF) protection

In a web application, basically, the webforms take input from the user and send them to server-side components to process them. The server-side components generally expose the service as a POST, PUT, DELETE method for accepting the data over HTTP. Django has built-in security against most forms of CSRF threats, as long as you have allowed and used it if necessary.

To enable it we just need to add {% csrf_token %} inside the form tag.

The CSRF protection cannot protect against man-in-the-middle attacks, so use HTTPS with HTTP Strict Transport Security Once you've set up HTTPS, add these lines in your settings.py

```
CSRF_COOKIE_SECURE = True #to avoid transmitting the CSRF cookie over HTTP accidentally.
SESSION_COOKIE_SECURE = True #to avoid transmitting the session cookie over HTTP accidentally.
```

csrf-cross-site-request-forgery.png

  • SQL injection Protection

SQL injection is a type of attack where a malicious user is able to execute arbitrary SQL code on a database. This can result in records being deleted or data leakage.

Django’s querysets are protected from SQL injection since their queries are constructed using query parameterization. A query’s SQL code is defined separately from the query’s parameters. Since parameters may be user-provided and therefore unsafe, they are escaped by the underlying database driver.

Django also gives developers the power to write raw queries or execute custom SQL. These capabilities should be used sparingly and you should always be careful to properly escape any parameters that the user can control. In addition, you should exercise caution when using extra() and RawSQL.

what-is-sql-injection.png

  • HOST header Validation

Django uses the Host header provided by the client to construct URLs in certain cases. While these values are sanitized to prevent Cross-Site Scripting attacks, a fake Host value can be used for Cross-Site Request Forgery, cache poisoning attacks, and poisoning links in emails.

Django validates Host headers against the ALLOWED_HOSTS setting in the django.http.HttpRequest.get_host() method.

  • Additional security Topics

    • Make sure that your Python code is outside of the Web server’s root. This will ensure that your Python code is not accidentally served as plain text (or accidentally executed).
    • Keep your SECRET_KEY a secret.
    • Try using environment variables for secret credentials.

Resources

Author