Rest Security
Rest Security
Guidelines
January 2023
Esta obra está sujeta a una licencia de
Reconocimiento-NoComercial-CompartirIgual
3.0 España de Creative Commons
ACKNOWLEDGEMENTS
I would like to thank my family and friends for their love and support throughout
this journey. Their constant belief in me has been a constant source of
motivation and inspiration.
I would also like thank H., F., M., V. and T. for their love and support inspired
me to move forward. They are a constant source of love and joy.
I would also like to thank my supervisor, Pau del Canto Rodrigo, for his valuable
guidance and support. Without his help, this project would not have been
possible.
i
FICHA DEL TRABAJO FINAL
ii
pueden asegurar que sus aplicaciones web basadas en DRF sean seguras y
resistentes a las vulnerabilidades comunes.
Abstract
The purpose of the work titled "Django REST Framework (DRF) Secure Code
Guidelines" is to provide guidance on how to write secure code when using the
Django REST Framework (DRF) for web application development. The
research aims to address the following questions: What are the best practices
for secure coding in the context of DRF? What are the common vulnerabilities
that developers using DRF should be aware of, and how can they be
prevented?
To answer these questions, the methodology for this work involves researching
best practices for secure coding in the context of DRF, as well as examining
common vulnerabilities and how to prevent them. The results of this research
include a set of recommendations or guidelines for secure coding with DRF,
including a cheat sheet and a presentation.
The main findings of this work include a summary of the importance of secure
coding in general, as well as specific considerations for developers using DRF.
The thesis also provides suggestions for further research or areas for
improvement in secure coding with DRF.
Overall, this thesis aims to provide valuable guidance and recommendations
for writing secure code with DRF in the context of web application
development. By following these guidelines, developers can ensure that their
DRF-based web applications are secure and resistant to common
vulnerabilities.
iii
Index
1 Introduction ................................................................................................. 1
1.1 Context and justification of the work ...................................................... 1
1.2 Objectives ............................................................................................. 2
1.3 Study of the ethical, social, and environmental impact .......................... 3
1.4 Methodology.......................................................................................... 4
1.5 Work Plan.............................................................................................. 6
1.6 Summary of products obtained ............................................................. 8
1.7 Brief description of the other chapters of the work ................................ 8
2 Python API development state of the art ..................................................... 9
2.1 Django ................................................................................................... 9
2.2 REST APIs .......................................................................................... 11
2.3 Django REST Framework ................................................................... 12
3 Web security state of the art...................................................................... 14
3.1 OWASP Top 10 ................................................................................... 16
3.2 OWASP API Security Top 10 .............................................................. 20
3.3 CWE/SANS TOP 25 ............................................................................ 22
3.4 SSDLC ................................................................................................ 24
4 DRF Security Guideline ............................................................................. 26
4.1 Framework Security ............................................................................ 26
4.2 Vulnerable dependencies .................................................................... 34
4.3 Dependency confusion ........................................................................ 36
4.4 Secure Code ....................................................................................... 39
4.5 Secure Deployment ............................................................................. 53
5 OWASP Cheat Sheet ................................................................................ 56
6 Conclusions and future work ..................................................................... 59
7 Glossary .................................................................................................... 60
8 Bibliography .............................................................................................. 62
9 Annexes .................................................................................................... 68
9.1 Appendix 1 - Django REST Framework (DRF) Cheat Sheet ............... 68
iv
Figure list
Figure 1. Gantt Chart of PEC 1, PEC 2 and PEC 3 ............................................ 6
Figure 2. Gantt Chart of PEC 4, Video Delivery and Defense ............................ 7
Figure 3. Average cost of all cyber-attacks in the US and Europe from 2021 to
2022 by country [24] ......................................................................................... 14
Figure 4. Leading risks to businesses worldwide from 2018 to 2022 [26] ........ 15
Figure 5. Icons of OWASP Top 10 – 2021. Source: OWASP ........................... 16
Figure 6. Comparison of OWASP Top 10 across the years ............................. 18
Figure 7. CWE Top 25 2021 vs 2022. Source: MITRE ..................................... 23
Figure 8. Phases of SSDLC. Source: Snyk ...................................................... 25
Figure 9. Django supported versions. Source: Django Download .................... 28
Figure 10. Twilio’s approach to prevent Dependency Confusion. Source: Twilio
Blog .................................................................................................................. 37
Figure 11. Screenshot of how the new DRF CS will look like ........................... 56
Figure 12. Screenshot of the Contributing Guide to propose a new CS ........... 57
Figure 13. Screenshot of the issue I created to propose the new CS............... 57
Figure 14. Screenshot of the issue I created to propose the new CS............... 58
v
1 Introduction
Cisco Global 2021 Forecast Highlights [1] estimates that, globally, IP traffic will
reach 278.1 Exabytes per month in 2021. One hour of standard definition
streaming of Netflix [2] consumes 1 GB. One Exabyte approx. equals to
1,073,741,824 GB. According to a 2019 Akamai traffic review, API calls
represent 83 percent of web traffic [3]. As we can see, APIs are critical for
Today’s Internet.
Django is a very popular Python-based web framework that handles most of the
heavy lifting of building a website. According to Stack Overflow “2022 Developer
Survey”, Django is the most popular Python based Web Framework [7]. Django
follows a philosophy of “batteries-included”, masking much of the underlying
complexity, allowing for rapid and secure development. Some of the common
web development problems that Django solves are authentication, connecting
to a database, logic, security, among others.
There are no public Secure Code Guidelines for Django nor for Django REST
Framework (DRF). The lack of such guidelines significantly increases the
cognitive load of developers when making decisions and increases the risk of
adding security bugs to DRF applications.
The guideline created with this work will also help security professionals
(auditors, consultants, etc.) and engineering managers have a guideline to use
1
as a reference when checking that the software produced by the developing
team is secure.
The desired results are specific guidelines for secure coding of REST APIs
using Django Rest Framework (DRF). This should make it easy for people
writing software to make better security decisions.
1.2 Objectives
The intention of this project is to generate guidelines for secure coding of REST
APIs using Django Rest Framework (DRF).
The general objective of the project is to create a document with clear and
concise guidelines on how to code secure APIs using DRF. The resulting
guideline should be clear enough for people who are writing DRF applications to
follow and to provide them enough detail and context in case they want to
understand why something is being recommended. The specific objectives to
be achieved are:
1. Research and document the state of the art of web security in 2022.
2. Understand and briefly explain the history, architecture and operation
of Django.
3. Understand and briefly explain the history, architecture and operation
of DRF.
4. Understand, analyze, and explain the DRF settings that have an
impact on the security of the application.
5. Understand, analyze, and explain the DRF functions that might be
used in an unsafe way.
6. Provide guidance on what aspects of an DRF application should be
considered and reviewed to have a secure application.
7. Provide guidance on recommended settings, functions, and
architectural approaches to follow to have a secure application.
The first objective will help us have a better context about what we should
protect in our web applications.
The following two objectives help have context of the specific technologies that
are covered in this project. The minimum depth that must be obtained from
each objective must be sufficient to understand how they work, and to be able
to use and configure them in a safe way. This means that it is not necessary to
understand everything related to the frameworks.
Objectives four and five are focused on the secure usage of the technologies.
They will be required to perform a study of literature, documents and if needed
even reading the code. Objectives six and seven is where the expected product
will be created.
2
1.3 Study of the ethical, social, and environmental impact
Sustainability
This work should not have a significant impact in terms of sustainability because
it has no impact on the environment. The only requirement it has is a running
computer and in most cases the computer will already be running with the
existence of this work or not.
The work will be 100% digital, hence there is no impact on printing and shipping
several copies of this document.
The negative impacts of this work can be countered with the saved hours of
forensic analysis, urgent meetings, crisis, etc. that will be averted if developers
follow the guidelines described here.
This work has a positive impact in terms of ethical behavior and social
responsibility because it empowers developers to write safer Django
applications, hence reducing the number of hacks, data loss, attacks on
individual privacy and other negative impacts of unsafe software.
It is important to mention that this work can also have a negative impact since
malicious actors can also use this to write safer code for nefarious tools. Since
this impact exists on every open source project, and the benefits are always
greater than the damages.
This work should not have a negative impact in terms of diversity, gender, or
human rights. Given that it will be available for everyone, it could be considered
a positive impact to reduce gender inequality and general inequality to give
opportunities for everyone to learn.
3
After the work is done, I will consider working in a Spanish translation so more
people could have access to this knowledge.
This work will be done with a mindful consideration of all genders gender
perspective. Some of the actions to assure this, are the following:
- Consider every author, without considering the gender of the author.
- Make a final product that could be used by every user, no matter their
gender.
- Constantly and actively consider that this work will not reinforce biases or
stereotypes.
- Use an inclusive language when possible. I will use they/them pronouns
to refer to individuals, that way we are not having a bias towards any
gender.
The previous considerations also apply to other aspects as race, origin, sexual
orientation, religion, or any other aspect that might be a factor of discrimination.
This work should be as inclusive as possible.
1.4 Methodology
There are several strategies that could be followed to develop this project, some
of those are:
- Interviews – Interviewing subject matter experts (SME) and gathering
information about security concerns, best practices, and guidelines to
write secure code.
- Literature review/research – Searching and reading relevant
documents about the topic.
- Code review – Reviewing the Django and DRF code base.
- Historic review of vulnerabilities – Searching and reviewing
vulnerabilities that have appeared in Django and DRF.
The other methodologies will not be used, because they are either very time
consuming (code review), have significant dependencies on people’s availability
(interviews) or will have a limited visibility of the problem and will not necessarily
help to prevent future problems (historic review of vulnerabilities).
4
This project will be delivered in six stages:
In the first 3 stages, after delivery, I will receive feedback from my tutor. I will
also ask coworkers and SME some time so they can provide feedback.
5
1.5 Work Plan
The following images describe the planning of the work with a Gantt Chart:
6
Figure 2. Gantt Chart of PEC 4, Video Delivery and Defense
7
1.6 Summary of products obtained
In chapter 1, the purpose and objectives of the work are explained. A brief
contextualization and a justification of the reason for the work done.
In chapter 2, the state of the art of the main technologies covered: Django,
REST APIs and Django REST Framework (DRF).
In chapter 3, the state of the art of security. This will include context to
understand why the secure code guidelines are relevant.
In chapter 4, the security guidelines are presented. This will be the most
technical chapter and it will include all relevant findings.
In chapter 5, explanation of OWASP Cheat Sheet project and a cheat sheet for
DRF.
In chapter 6, the conclusions of the work carried out according to the results
obtained are documented.
8
2 Python API development state of the art
2.1 Django
2.1.1 What it is
Django is a very popular, free, and open source, high-level Python-based web
framework that encourages rapid development and clean, pragmatic design by
handling the challenging parts of building a website: authentication, connecting
to a database, logic, security, and so on. [8]
The Model acts as a data access layer which handles the data in the
database.
The View is used to execute the business logic and interact with a model
to carry data and render a template.
9
2.1.2 History
Django was initially developed in 2005 and named after the guitarist Django
Reinhardt. From the Django documentation site, we can get the history [9]:
World Online, a newspaper Web operation, is responsible for building
intensive Web applications on journalism deadlines. In the fast-paced
newsroom, World Online often has only a matter of hours to take a
complicated Web application from concept to public launch.
…
In summer 2005, World Online decided to open-source the resulting
software, Django. Django would not be possible without a whole host of
open-source projects – Apache, Python, and PostgreSQL to name a few
– and we’re thrilled to be able to give something back to the open-source
community.
It is quite popular, some of the global companies that use Django are [9] [13]
Instagram, Belvo, National Geographic, Mozilla, Spotify, Pinterest among
others.
2.1.3 Security
10
providing functions that are safe, It is possible to write insecure code in
Django.
4. Business logic – This is related to flaws in the design and
implementation of an application that allow an attacker to have an
unintended behavior, potentially causing a malicious goal. This type of
vulnerabilities can happen on any programming language and framework
since they are vulnerabilities in the design and implementation.
This document will cover all the areas described above and will go into detail in
the last two aspects.
One of the main advantages of having the backend expose API is that when the
current front-end frameworks are eventually replaced by newer, the backend
API can remain the same. No major rewrite is required.
Another major benefit is that one single API can support multiple front ends
written in different languages and frameworks. For example, JavaScript for web
front ends, Java for Android apps and Swift for iOS apps. All can use the same
API communicating with the same underlying database back-end [15].
11
2.3 Django REST Framework
2.3.1 What it is
DRF is an app for Django that mimics many of Django’s traditional conventions
and makes it a great and easy option for building a REST API on top of a
Django project.
It is the most popular Django app, for creating REST APIs, in GitHub with 24.3k
stars.
2.3.2 History
Tom Christie created a Kickstarter campaign to get funding for the release of
version 3.3 of DRF. The campaign was launched on July 17th, 2014, and it was
last updated in October of 2015 [18]. The campaign was very successful with
440 backers pledging £32,650. The original goal was £4,000 and the biggest
stretch goal was £12,000 for an Admin interface.
On October 28th, 2015, version 3.3 of DRF was released, making the Kickstarter
campaign achieve its goal [19]. As of the writing of this section, the last version
released of DRF was 3.14 [20].
Django REST Framework is a powerful and accessible way to build web APIs
[15]. Some of the global companies that use DRF are [21] Sentry, Retool,
Robinhood, Belvo, O’Reilly Media, Digital Ocean, among others.
12
2.3.3 Security
13
3 Web security state of the art
According to Hiscox “Cyber Readiness Report 2022” Cyber-attacks have
intensified in the past 12 months. 48% of companies reported a cyber-attack in
the past 12 months and the median cost of an attack is just under $17,000.
Anyhow, attacks can be way more expensive, for example the single largest
cyber-attack suffered in 2021 in Germany cost $3,400,000 USD [23].
The average cost in thousand U.S. dollars per country:
Figure 3. Average cost of all cyber-attacks in the US and Europe from 2021 to 2022 by
country [24]
14
According to Allianz, Cyber Incidents is the leading risk for business worldwide
in 2022 and has been quite important for the last 5 years:
Reducing risk by having proper cyber security practices and having secure web
applications, including APIs, is critical for any business additionally it can help
them save a significant amount of money by preventing cybersecurity incidents.
15
Finally, a process that helps organizations develop secure software is called the
Secure Software Development Life Cycle (SSDLC). It includes activities such as
security requirements gathering, security design, security testing, and security
deployment. The benefits of using the SSDLC include improved security,
reduced development costs, and improved software quality [31] [32]. Section
3.4 SSDLC will go into detail of the SSDLC.
The categories, with a brief explanation extracted from the OWASP site [33]
are:
16
A02:2021-Cryptographic Failures – Previously known as Sensitive Data
Exposure, which was a broad symptom rather than a root cause. The renewed
focus here is on failures related to cryptography which often leads to sensitive
data exposure or system compromise.
A04:2021 Insecure Design – Is a new category for 2021, with a focus on risks
related to design flaws. Insecure design is a broad category representing
different weaknesses, expressed as “missing or ineffective control design.”
There is a difference between insecure design and insecure implementation.
One of the factors that contribute to insecure design is the lack of business risk
profiling inherent in the software or system being developed, and thus the
failure to determine what level of security design is required.
A08:2021 Software and Data Integrity Failures – Software and data integrity
failures relate to code and infrastructure that does not protect against integrity
violations. Insecure Deserialization from 2017 is now a part of this larger
category.
17
A10:2021 Server-Side Request Forgery (SSRF) – A vulnerability that occurs
whenever a web application is fetching a remote resource without validating the
user-supplied URL. It allows an attacker to coerce the application to send a
crafted request to an unexpected destination, even when protected by a firewall,
VPN, or another type of network access control list (ACL).
Table notes:
[1] Renamed “Broken Access Control” from T10 2003
[2] Split “Broken Access Control” from T10 2003
[3] Renamed “Command Injection Flaws” from T10 2003
[4] Renamed “Error Handling Problems” from T10 2003
[5] Renamed “Insecure Use of Cryptography” from T10 2003
[6] Renamed “Web and Application Server” from T10 2003
[7] Split “Insecure Configuration Management” from T10 2004
[8] Reconsidered during T10 2010 Release Candidate (RC)
[9] Renamed “Unvalidated Parameters” from T10 2003
[10] Renamed “Injection Flaws” from T10 2007
[11] Split “Broken Access Control” from T10 2004
[12] Renamed “Insecure Configuration Management” from T10 2004
1 Accessible at https://github.com/OWASP/Top10/tree/master/2017-2003_Comparison
18
[13] Split “Broken Access Control” from T10 2004
[14] Renamed “Improper Error Handling” from T10 2004
[15] Renamed “Insecure Storage” from T10 2004
[16] Renamed “Failure to Restrict URL Access” from T10 2010
[17] Renamed “Insecure Cryptographic Storage” from T10 2010
[18] Split “Insecure Cryptographic Storage” from T10 2010
[19] Split “Security Misconfiguration” from T10 2010
[20] Split “Broken Access Control” from T10 2013
[21] “A4:2014-Insecure Direct Object References” and “A7:2013-Missing Function Level Access Control”
merged into “A5:2017-Broken Access Control”
[22] “A5:2017-Broken Authentication” now includes CWEs that are more related to identification failures
and was renamed into “A7:2021-Identification and Authentication Failures”
[23] “A3:2017-Sensitive Data Exposure” was renamed into “A02:2021-Cryptographic Failures”, focusing on
failures related to cryptography as it has been implicitly before
[24] “A05:2021-Security Misconfiguration” now includes the former category for “A4:2017-XML External
Entities (XXE)”
[25] Cross-site Scripting is now part of this category
[26] “A8:2017-Insecure Deserialization” is now a part of this larger category, named “A08:2021-Software
and Data Integrity Failures”
[27] “A09:2021-Security Logging and Monitoring Failures” was previously “A10:2017-Insufficient Logging &
Monitoring”. This category is expanded to include more types of failures. Failures in this category can
directly impact visibility, incident alerting, and forensics
[28] “A06:2021-Vulnerable and Outdated Components” was previously titled “Using Components with
Known Vulnerabilities”
As we can see, there is a tendency change, and it makes sense when we see
how technologies have changed from the early 2000s to today’s technologies.
For example, buffer overflow no longer appears in the list, even that it was the
risk rated as #1 in 2003, and that makes sense since those are vulnerabilities
most common in the C and C++ languages and today very few web applications
are written in those languages. The only common web technology written in C
and C++, as of today, are web servers and those have already been “battle
tested” for more than one decade.
Insecure communications are another risk that no longer appears in the Top 10
and that may be linked to the ease of use, along with the reduced costs of
today’s encryption technologies with comparison to early 2000s.
The risks that have been present on all releases of the Top 10 are "Injection",
"Cross Site Scripting (XSS)", "Broken Authentication and Session
Management", "Broken Access Control" and "Sensitive Data Exposure". All
those risks have in common that they are more related with the proper design
and coding of the web applications and not the technology used.
19
3.2 OWASP API Security Top 10
In 2019 OWASP released the first version of the “OWASP API Security Top 10”,
a project very similar to “OWASP Top 10”, but with a sole focus on APIs. The
“OWASP API Security Top 10 – 2019” risks, with a brief explanation, are [36]
[37]:
API8:2019 Injection
Injection flaws, such as SQL, NoSQL, Command Injection, etc., occur when
untrusted data is sent to an interpreter as part of a command or query.
20
API9:2019 Improper Assets Management
APIs must be properly hosted and deployed, having an API version inventory
play an important role. This vulnerability includes issues such as deprecated
API versions and exposed debug endpoints.
21
3.3 CWE/SANS TOP 25
Since 2009 SANS, with MITRE, have been making the list “CWE/SANS TOP 25
Most Dangerous Software Errors” [30]. SANS last release of this list was in
20212 MITRE has released the 2022 list. The Top 25 security vulnerabilities,
from the 2022 MITRE list, are [38]:
22
MITRE provide the following visual representation of the difference in 2021 and
2022 Top 25 lists:
As we can see, most CWEs remain present, they only shift a few positions up or
down. The 3 new entries in the Top 25 are:
The next section will cover the SSDLC, which has stages that help reduce the
chances of vulnerabilities being present in the application being developed.
23
3.4 SSDLC
The Secure Software Development Life Cycle (SSDLC) is a process that can be
used by organizations to develop more secure software, it covers the entire
development process. The SSDLC includes several security-focused activities
that should be completed at each stage of the software development process.
By following the SSDLC, organizations can improve the security of their
software products and better protect themselves from potential attacks [39].
The SSDLC includes the following stages: requirement gathering and analysis
(also known as planning), design, implementation (also known as build,
development, or coding), testing (also known as verification), deployment (also
known as release) and maintenance [39].
Design – The process of creating a detailed plan for the software. Threat
modeling will be done to identify potential vulnerabilities. In this stage, it should
also be specified how system authentication will be performed and where
secure communication is required. The resulting plan should consider the
security risks that have been identified and should include measures to mitigate
those risks.
Testing – The process of verifying that the software works as intended. This
stage also includes testing the security controls to ensure that they are
effective.
24
Maintenance – The process of making changes to the software after it has
been deployed. This stage includes ensuring that security controls are still in
place and that the software remains compliant with security policies and
procedures.
The stages of the SSDLC, with the security activities that could be performed
are:
The previous image does not include maintenance since some authors consider
that to not be part of the scope or be included in Deployment.
This work will focus mainly on the stage implementation since that’s when
coding takes place. Secure Code Guidelines are critical for that stage since they
empower developers to write safer code and to make less mistakes. Knowledge
of this guide can benefit other stages too.
To have properly secure software, the team should do the full SSDLC,
especially the earlier stages since that is where more information about the
system, expectations and requirements is gathered.
25
4 DRF Security Guideline
Every programming language and framework has characteristics that make
them unique.
In this chapter I will only cover attacks that affect Django and Django REST
Framework (DRF). This chapter will have the following sections:
Secure Coding – This section covers the most common attacks on a Django
and DRF app, maps them to the vulnerabilities described in the previous section
and explains how to prevent them. It also covers some open source Static
Application Security Testing (SAST) tools and briefly explains Business Logic
attacks.
However, not everything is secure by default. In this section, I will explain the 3
aspects that are key to make an API developed with Django and Django REST
Framework (DRF) secure:
26
1. Django Security Policies – Explain the Security Policies of the
framework and project so we have context and understand what is
expected from the development team of an application built on Django.
2. Django Settings – Explain the Django Settings relevant from a security
point of view.
3. DRF Settings – Explain the DRF Settings relevant from a security point
of view.
Supported version
The Django team provides official security support for the following versions of
Django:
• The main development branch. It is hosted on GitHub4 and it will
become the next major release of Django. It is important to mention that
security issues that only affect this version are fixed in public without
going through the disclosure process.
• The two most recent Django releases.
• Long-term support release. Usually It is one at a time, anyhow there is
an overlap, every 2 years, where 2 LTS releases are supported at the
same time.
3 https://www.djangoproject.com/foundation/teams/#security-team
4 https://github.com/django/django/tree/main
5 https://github.com/django/django/blob/main/django/__init__.py#L5
27
Finally, a diagram from the Django website with the supported versions [42]:
The mainstream support includes security fixes, data loss bugs, crashing bugs,
major functionality bugs in newly introduced features, and regressions from
older versions of Django.
The extended support only includes security fixes and data loss bugs.
On the day of disclosure, Django Security team will take the following steps:
6 https://docs.djangoproject.com/en/4.1/internals/mailing-lists/#django-announce-mailing-list
28
3. Post a public entry on the official Django development blog7, with all
the relevant information.
4. Post a notice to the django-announce mailing list and oss-
[email protected] mailing lists that link to the blog post.
Finally, Django Security team classifies severity levels with the following logic:
The project maintainers will then work with you to resolve any issues
where required, prior to any public disclosure.
7 https://www.djangoproject.com/weblog/
29
4.1.2 Django Settings
According to Django documentation8, the core settings are over 180 different
settings, this is very complex. It is not reasonable to ask every developer to
review every setting and understand it.
The following list includes the settings I consider relevant from a security
standpoint in a Django project that builds an API. For each setting, I give a brief
description of what it controls and what value should it contain [44] [45] [46]:
It is important to never hardcode secrets on the settings file, or any other file,
including the username or password to connect to the email provider (setting
“EMAIL_HOST_PASSWORD”), database (setting “DATABASES”), cache
(setting “CACHES”).
8 https://docs.djangoproject.com/en/4.1/ref/settings/
30
Secrets, including database URLs with username and password, should be
handled by a Secret Manager like Hashicorp Vault9, AWS Secret Manager10,
among others.
Security Middleware
The setting MIDDLEWARE contains a list of middleware to use. The
Middleware “django.middleware.security.SecurityMiddleware” 11 provides some
security functionalities, anyhow none of them are very relevant for API projects
since most of them are related to browser security and the security headers
(HSTS, Cross origin, Content Type, etc.).
External Systems
The database should only be accessible to Django. It should never be exposed
to the Internet. The same applies for the caching system.
Logging
The settings “LOGGING” and “LOGGING_CONFIG” are related to how the
application logs events. This is critical for any application. Generation, storage
and analysis of logs should also be part of the well architected approach.
Secure Communications
Incoming traffic
Django has many settings to control HTTPS14 like
“SECURE_HSTS_INCLUDE_SUBDOMAINS”, “SECURE_SSL_HOST”, among
others. Anyhow It is recommended to not do HTTPS at the Django layer and
handle that on something like a network load balancer, application load
9 https://www.hashicorp.com/products/vault
10 https://aws.amazon.com/secrets-manager/
11 https://docs.djangoproject.com/en/4.1/ref/middleware/#module-django.middleware.security
12 https://docs.djangoproject.com/en/4.1/topics/security/#host-header-validation
13 AWS Well-Architected: https://aws.amazon.com/architecture/well-architected/
31
balancer, WAF or proxy [47]. It will be easier, and it is a better separation of
responsibilities.
Outgoing traffic
Any outgoing traffic, for example to connect to the cache, the database, the
email provider (Django setting “EMAIL_USE_TLS”), etc. should be done over
an encrypted channel (TLS).
Many of the previous settings are related to a well architected application and
are outside of the scope of this document.
Finally, many Django settings are not covered here since they are either not
related to a regular API application (for example, cookies, CSRF or XSS
prevention) or they should be handled by something else like an application
load balancer, WAF or proxy (HTTP Headers, HTTPS, etc.). Anyhow those
should be reviewed and properly configured if they are needed, for example for
the admin panel.
All the Django REST Framework (DRF) configuration is done under the
namespace REST_FRAMEWORK, usually in the settings.py file, anyhow it can
be in a different file if Django recognizes that file as part of the application
settings. An example of the configuration is:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
],
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
]
}
32
According to DRF documentation15 it has 40 different settings. The following list
includes the settings I consider relevant from a security standpoint in a Django
project that builds an API. For each setting, I give a brief description of what it
controls and what value should it contain [15] [48] :
The previous settings are part of the API policy settings, and they are applied to
every APIView class-based view, or @api_view function-based view. Anyhow,
each view (either class or function based) can have a different authentication,
permission, and throttling policy by configuring it on the view.
15 https://www.django-rest-framework.org/api-guide/settings/
16 https://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication
17 https://www.django-rest-framework.org/api-guide/authentication/#basicauthentication
18 https://www.django-rest-framework.org/api-guide/permissions/#allowany
19 For very large datasets Cursor Pagination is the best approach https://www.django-rest-
framework.org/api-guide/pagination/#cursorpagination
20 https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication
33
4.2 Vulnerable dependencies
According to Synopsys “2022 Open Source Security and Risk Analysis Report”,
97% of the software projects reviewed contained open source components and
78% of the code in codebases was open source [49]. That means that most of
the software that most companies use was not written by them. It is important to
keep track of these dependencies because they can introduce security
vulnerabilities or break compatibility with other software.
A software Bill of Materials (SBOM) is a list of all the software dependencies for
a given piece of software. The National Telecommunications and Information
Administration define a SBOM as [50]:
Python has many ways to manage dependencies such as pip, Poetry, pyenv
setuptools, conda, easy_install, pipenv, among others [51]. Anyhow, the most
common and the current best practice is to use pip with a “requirements.txt” file.
In order to keep it more organized, It is possible to have multiple requirements
files [52] [53], for example:
34
There are several tools, known as Software composition analysis (SCA), to help
with this, two of the most common are:
Github’s Dependabot
Additionally, Snyk has a great free tool called Snyk Advisor23 that gives valuable
information about a package such as Popularity, Maintenance, Security and
Community. This allows developers to compare packages and choose the best
package for their needs, considering the security posture of the package.
22https://docs.github.com/en/code-security/dependabot/dependabot-version-
updates/configuration-options-for-the-dependabot.yml-file
23 https://snyk.io/advisor/python
35
4.3 Dependency confusion
For Python, the language which this work covers, Pip is the package-
management system most widely used to install and manage software
packages. When using the CLI argument “--extra-index-url”, a common way to
reference an internal pip server for internal dependencies, works in the following
way:
That is dangerous since an attacker can create a malicious package with the
same name, and a higher version number, as an internal package and execute
code on the machine.
The problems of installing another package than the expected one are many,
including loss of desired functionality, the software not behaving as expected,
unknown bugs among many others. Anyhow, the biggest problem is that the
undesired package may be malicious and do nefarious activities on the server
such as steal secrets, data, delete files, launch attacks against other servers,
etc.
24 https://medium.com/@alex.birsan/dependency-confusion-4a5d60fec610
36
The previous is extremely dangerous since malicious package can cause
damages just by being downloaded (pip download <package_name>)25, even
before execution or even installation.
There are ways to mitigate the execution of code when downloading a package,
anyhow the best mitigation is to make sure all the packages used are not
malicious.
For Python: Use the index-url option in pip’s configuration file or command
line to specify the feed, overriding the default. Avoid the extra-index-url
option, which is additive and may lead to having multiple indexes.
A correct approach, especially for a company with many software projects is the
one Twilio described in their blog post called “Dependencies, Confusions, and
Solutions: What Did Twilio Do to Solve Dependency Confusion”, that is
summarized in the following image [59]:
Figure 10. Twilio’s approach to prevent Dependency Confusion. Source: Twilio Blog
25 This behavior is not a bug but rather a feature in the pip design
37
if needed. Old packages not following the internal naming convention should be
deleted.
Block Proxying of Certain Packages – Any public package that has a name
collision with internal packages should be blocked. If possible, we should also
block known malicious packages or any other package that does not follow the
company guidelines (package health, license, etc.)
26 https://security.snyk.io/
38
4.4 Secure Code
On Section “4.4.1 Secure Code” I will cover the most common attacks on a
Django and Django REST Framework app, on what list they are present and the
methods to prevent them.
On Section “4.4.2. Open Source SAST” I will cover some open source Static
Application Security Testing (SAST) tools to detect the vulnerabilities covered in
this section.
Django, along with Django REST Framework, follow the philosophy of “batteries
included” so they take care of many things, security included. In order to give
developers flexibility to build whatever solution they want, for example that
could require a very specific SQL query, it also includes functions to have full
control of certain situations. Nevertheless, the incorrect usage of such functions
could lead to vulnerabilities.
27 https://docs.djangoproject.com/en/4.1/ref/templates/language/#automatic-html-escaping
39
4.4.1.2 Cross site request forgery (CSRF) protection
No longer present in OWASP Top 10, last year it appeared was 2013.
Django has built-in protection against most types of CSRF attacks. The
important thing to prevent this is to deploy the Middleware
“CsrfViewMiddleware” and be extra careful when marking a view with the
csrf_exempt decorator since that will disable CSRF protections for that view.
Django also provides developers power to write raw queries or execute custom
SQL. Incorrect usage of these powers is the only case where a SQLi can
happen.
Developers should avoid using the dangerous methods raw()28, extra()29 and
custom SQL30 (via cursor.execute()). If those methods are unavoidable for the
application, no user input should be used. If that is unavoidable too, proper
cleaning and filtering should be done on those inputs, anyhow the general
recommendation is avoid doing this since there is a chance the filtering is not
done properly or there is a way to bypass it.
28 https://docs.djangoproject.com/en/4.1/topics/db/sql/#executing-raw-queries
29
https://docs.djangoproject.com/en/4.1/ref/models/querysets/#django.db.models.query.QuerySet.
extra
30 https://docs.djangoproject.com/en/4.1/topics/db/sql/#executing-custom-sql
40
4.4.1.4 Clickjacking protection
4.4.1.5 SSL/HTTPS
Django has several settings to enforce the use of HTTPS, but I suggest this is
done on a separate layer of the network architecture, for example being
handled by a proxy, a load balance, a CDN, a WAF, etc.
What should be verified is that the site is only accessible by HTTPS, and it has
secure configuration, sites like https://www.ssllabs.com/ can help verify that.
This should be handled by the external layer of the network architecture, for
example being handled by a proxy, a load balance, a CDN, a WAF, etc.
31 https://docs.djangoproject.com/en/4.1/ref/settings/#std-setting-ALLOWED_HOSTS
32 https://docs.djangoproject.com/en/4.1/ref/middleware/#referrer-policy
41
4.4.1.8 Cross-origin opener policy
This is related to Cookie security34 and it is not a good practice to have APIs
using Cookies or sessions, especially for REST APIs since they shall be
stateless. Every request shall be stateless and isolated from other requests.
✓ 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).
✓ Take care with any user uploaded files.
✓ Django does not throttle requests to authenticate users. To protect
against brute-force attacks against the authentication system, you
may consider deploying a Django plugin or web server module to
throttle these requests.
33https://docs.djangoproject.com/en/4.1/ref/settings/#std-setting-
SECURE_CROSS_ORIGIN_OPENER_POLICY
34 https://docs.djangoproject.com/en/4.1/topics/http/sessions/#topics-session-security
35 Some of them described in https://docs.djangoproject.com/en/4.1/topics/security/#user-
uploaded-content
36 https://docs.djangoproject.com/en/4.1/topics/security/#additional-security-topics
42
✓ Keep your SECRET_KEY, and SECRET_KEY_FALLBACKS if in
use, secret.
✓ It is a good idea to limit the accessibility of your caching system
and database using a firewall.
✓ Take a look at the Open Web Application Security Project
(OWASP) Top 10 list which identifies some common
vulnerabilities in web applications. While Django has tools to
address some of the issues, other issues must be accounted for in
the design of your project.
✓ Mozilla discusses various topics regarding web security. Their
pages also include security principles that apply to any system.
Additionally, the following are some protections worth discussing [44] [64].
The following python built-ins functions execute code: eval(), exec() and
execfile(). If the application makes use of this functions, no arbitrary user input
should ever reach them37.
The pickle module38 is another unsafe module of Python. Only data where we
have complete control, and there is no way for a user to tamper with should be
unpickled. It is trivial to construct a malicious pickle data file which will execute
arbitrary code during unpickling [65]. This includes the pandas.read_pickle39
which is also unsafe.
If the Django app uses PyYAML40, the method load() should be used carefully
since it can also lead to RCE. The easiest mitigation is to use the method
37 It’s hard to properly sanitize this, especially if a wide array of values is allowed. A nice write-
up of how a blocklist approach can be bypassed is present at
https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
38 The pickle module implements binary protocols for serializing and de-serializing a Python
object structure.
39 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_pickle.html
40 https://pyyaml.docsforge.com/
43
safe_load(), if It is not possible, the parameter “Loader=yaml.SafeLoader”
should be used.
The mass assignment vulnerability happens when database fields that are
intended to be updated only through special processes are open to general
update processes. When using ModelForms, always use Meta.fields (allow list
approach) and never use Meta.exclude (blocklist approach) since it is easy to
forget or make a mistake (for example, when updating the model in the future)
that could lead to this type of vulnerability.
ModelForms.Meta.fields = “__all__”
44
4.4.1.14 Identification and Authentication Failures protection
The setting expects “A list or tuple of authentication classes”. The default value
is:
['rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication']
It is important to know that just checking if the request has a user is not enough
since the user AnonymousUser might be set.
Finally, the authentication setting can also be overwritten on a class using the
APIView class-based views and modifying the variable authentication_classes.
On a function based view, it could be modified with the decorators @api_view
and @authentication_classes.
45
4.4.1.15 Authorization Failures protection
The setting expects “A list or tuple of permission classes”. The default value is:
['rest_framework.permissions.AllowAny']
It is important to change the default value if the functions or view require some
level of authorization. Using classes without bugs is also key to prevent this
vulnerability.
Before running the main body of the view each permission in the list is
checked. If any permission check fails, an exceptions.PermissionDenied
or exceptions.NotAuthenticated exception will be raised, and the main
body of the view will not run.
The authorization setting can also be overwritten on a class using the APIView
class-based views and modifying the variable permission_classes.
On a function based view, it could be modified with the decorators @api_view
and @permission_classes. All the above could be grouped as Function Level
Authorization.
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
46
4.4.1.16 Resources & Rate Limiting protection
The setting expects “A list or tuple of throttle classes”. The default value is
empty. For most installations It is important to change the default value.
Finally, the throttling setting can also be overwritten on a class using the
APIView class-based views and modifying the variable throttle_classes.
On a function based view, it could be modified with the decorators @api_view
and @throttle_classes.
47
4.4.1.18 Excessive Data Exposure protection
It is present in OWASP API Security Top 10, inside API3:2019 Excessive Data
Exposure.
The excessive data exposure vulnerability, in DRF, happens when the serializer
displays too much information about a model. It is also more present on public
endpoints.
48
4.4.1.19 Summary tables
OWASP API Security Top 10
OWASP API Security Top 10 How to prevent it
API1:2019 Broken Object Level On class-based views verify the variable authentication_classes.
Authorization On a function based view, verify the decorators @api_view and
@authentication_classes
API2:2019 Broken User Authentication Verify the setting value DEFAULT_AUTHENTICATION_ CLASSES
API3:2019 Excessive Data Exposure Verify the data returned by the serializer
API4:2019 Lack of Resources & Rate Verify the setting value DEFAULT_THROTTLE_CLASSES
Limiting On class-based views verify the variable throttle_classes.
On a function based view, verify the decorators @api_view and @ throttle_classes
API5:2019 Broken Function Level Verify the setting value DEFAULT_PERMISSION_ CLASSES
Authorization On class-based views verify the variable authentication_classes.
On a function based view, verify the decorators @api_view and
@authentication_classes
API6:2019 Mass Assignment Don’t use meta.exclude, instead use meta.fields
Never use ModelForms.Meta.fields = "__all__"
API7:2019 Security Misconfiguration Review Django Settings (especially DEBUG and SECRET_KEY) and the whole
content of the settings file
API8:2019 Injection Don’t use any user controlled variables in the methods:
raw, extra and cursor.execute (SQLi)
eval, exec, execfile, pickle.load and yaml.load (RCE)
API9:2019 Improper Assets Management Not related to code. Do proper asset management.
API10:2019 Insufficient Logging & Review the application is doing proper logging and there are alerts and monitors
Monitoring on those logs.
49
OWASP Top 10 2021
OWASP Top 10 2021 How to prevent it?
A01:2021-Broken Access Control Verify the setting value DEFAULT_PERMISSION_ CLASSES
50
4.4.2 Open Source SAST
There are many different SAST options each will have their unique attributes
such as speed, complexity to set up, quality of findings, price, among others. I
will cover three open source solutions:
All 3 tools run locally or in the build environment, there is no need to upload
code.
Finally, each project should be confident they are using a SAST tool that’s
updated, maintained, and has good findings. If possible, running a secondary
SAST once a month is useful to detect gaps in findings.
44 https://docs.python.org/3/library/ast.html
45 Found at the registry: https://semgrep.dev/explore
46 https://semgrep.dev/p/django
47 https://pycharm-security.readthedocs.io/en/latest/installation.html#installation-from-docker
51
4.4.3 Business Logic
They are often the most critical in terms of consequences, as they are deeply
tied into the company’s process, anyhow they Do not follow a pattern48.
48Examples of this vulnerabilities can be found in Jeremiah Grossman’s slides “Seven Business
Logic Flaws that put your Website at Risk” found at https://owasp.org/www-pdf-
archive/FROCo8_JeremiahGrossman_BizLogicFlaws.pdf
52
4.5 Secure Deployment
In this section I will cover the basics for doing a secure deployment of a Django
and Django REST Framework app.
It is important to mention that each application is unique and has its own
architecture, business requirements, security requirements, technical
capabilities, resources, among others. It is best to have their own process,
anyhow this section should help as a starting point.
4.5.1 Settings
Secrets should never be hardcoded on the settings file or any other file since
it is a poor practice because it can compromise security, make maintenance
difficult, and hinder portability. It is recommended to handle secrets with a
secret manager.
As explained in section “4.1.3 DRF Settings” DRF settings will hardly change.
Anyhow, if there is an authentication, permission or throttle class that’s only
used for local development or debugging, for example to allow all access, it
should be removed before the application is deployed in production.
A good practice that some teams follow is to have separate files, all inside a
folder called settings, for each environment. An example of that is:
53
• settings/production.py for the live production servers.
4.5.2 System Checks
Django Documentation has a page for the system check framework [73] that
says:
Checks can be triggered explicitly via the check command. Checks are
triggered implicitly before most commands, including runserver and
migrate. For performance reasons, checks are not run as part of the
WSGI stack that is used in deployment. If you need to run system checks
on your deployment server, trigger them explicitly using check.
4.5.3 CI/CD
54
A proper CI/CD pipeline gives the business, and developers, enough
confidence about their code and their deployment process that they can push
new code multiple times per hour.
A robust CI/CD pipeline should also include security checks. For a Django
application, the following are a good idea to have:
Having a robust CI/CD pipeline requires many teams to communicate and work
together. Security should never impose, or in any way force, their tools into a
CI/CD pipeline since that would create friction and teams will try to find a way to
bypass them if they keep adding friction.
The best approach is to add security tools in a gradual manner and have a
timeline that adjusts with the business. For example, having a 6 month plan to
add all 3 tools:
1. Communicate the plan with the teams and ask for feedback.
2. Start with the tools that will cause lower friction and less work for the
teams. Probably creating a first iteration of custom system checks.
3. Continue with SAST on warning mode (not failing the pipeline).
4. Ask teams to work on the findings. Provide help and resources so they
can fix the issues.
5. Integrate the Dependency checks.
6. Repeat step 4, but with the dependency checks.
7. Establish and share a deadline when the SAST will be a blocking
factor in the pipeline.
8. Establish and share a deadline when the Vulnerability checks will be a
blocking factor in the pipeline.
In every step keep an open mindset and a good communication channel with
every other team involved. Having a weekly office hour for teams to reach out
and solve questions is a good practice.
55
5 OWASP Cheat Sheet
The OWASP Cheat Sheet Series is a collection of documents that provide
guidance on how to secure web applications and APIs. The series includes
cheat sheets on a variety of topics, including secure coding practices, input
validation and sanitization, authentication, and authorization, and more. It’s
another project of OWASP.
Cheat Sheet
Figure 11. Screenshot of how the new DRF CS will look like
56
The complete text is in “9.1 Appendix 1 - Django REST Framework (DRF)
Cheat Sheet”.
To submit a new Cheat Sheet, the project has a Contributing Guide50 that I
followed. From the guide:
The issue I created51 to propose the new Cheat Sheet (CS) looked like:
50 https://github.com/OWASP/CheatSheetSeries/blob/master/CONTRIBUTING.md
51 https://github.com/OWASP/CheatSheetSeries/issues/1034
57
On Dec 26th, 2022, I created a PR to introduce the first version of the draft of
the DRF Cheat Sheet and it was accepted as a draft on January 2nd, 2023:
On January 4th, 2023, the PR that published the draft was accepted and the
“Django REST Framework (DRF) Cheat Sheet” is officially published52:
52 At the URL:
https://cheatsheetseries.owasp.org/cheatsheets/Django_REST_Framework_Cheat_Sheet.html#
introduction
58
6 Conclusions and future work
In conclusion, the work successfully achieved its objectives of providing
guidance on how to write secure code when using the Django REST
Framework (DRF). However, the timeline for this work was not without
challenges. The main section, "DRF Security Guidelines," took longer to
complete than expected, particularly the portion on "Secure Code." Additionally,
there were a few changes made to the organization and presentation of the
document, as is often the case with initial planning.
The methodology for this work was followed, except for interviews. Due to a
lack of availability of experts, it was not possible to conduct interviews as part of
the research process. Anyhow a more in-depth analysis of the literature was
done along with in-depth research of publicly available information.
Despite these challenges, the research for this thesis resulted in the
development of a set of recommendations or guidelines for secure coding with
DRF, including a cheat sheet and a presentation. These guidelines provide
valuable information for developers looking to ensure the security of their DRF-
based APIs.
Additionally, the ethical, social, and environmental impacts of this work were all
positive. By promoting the use of secure coding practices, this work helps to
protect the privacy and security of users of web applications built with DRF. This
can have a positive impact on society, as it helps to prevent data breaches and
other security incidents that can have serious consequences.
There are several potential areas for future work in this field. One possibility is
to create a vulnerable API where the guidelines could be tested and refined.
Another option is to develop a course that teaches developers how to use these
guidelines in practice. Additionally, translating this work into Spanish and other
languages could help to make the guidelines more widely accessible to a global
audience. Finally, creating guidelines for secure network segmentation,
implementing a firewall, using a WAF, and restricting Django admin access
using a firewall could further enhance the security of the system.
Overall, the "Django REST Framework (DRF) Secure Code Guidelines" provide
a valuable resource for developers looking to write secure code with DRF in the
context of web application development. With further research and
development, these guidelines have the potential to become an even more
valuable tool for ensuring the security of web applications built with DRF.
59
7 Glossary
API – An application programming interface (API) is a way for two or more
computer programs to communicate with each other [14].
60
Programming Language – A system of notation for writing computer
programs. Some examples are C, Python, Java, Ruby and Rust.
REST API – The dominant architectural pattern for APIs and it means
REpresentational State Transfer.
Secret – Credentials are often called “secrets”. Any private piece of information
that acts as a key to unlock protected resources or sensitive information in
tools, applications, etc. should be considered a secret. The most common types
of secrets are Account credentials (username and password), API Keys,
Passwords, SSH keys and Encryption keys.
61
8 Bibliography
[1] Cisco, "Global - 2021 Forecast Highlights," Cisco, 2021. [Online].
Available: https://www.cisco.com/c/dam/m/en_us/solutions/service-
provider/vni-forecast-
highlights/pdf/Global_2021_Forecast_Highlights.pdf. [Accessed 9
October 2022].
[2] Netflix, "How to control how much data Netflix uses," [Online]. Available:
https://help.netflix.com/en/node/87. [Accessed 09 October 2022].
[3] Akamai, "[state of the internet] / security Retail Volume 5, Issue 2," 02
2019. [Online]. Available:
https://www.akamai.com/site/it/documents/state-of-the-internet/state-of-
the-internet-security-retail-attacks-and-api-traffic-report-2019.pdf.
[4] Wikipedia contributors, "Python (programming language)," Wikipedia,
The Free Encyclopedia., 16 October 2022. [Online]. Available:
https://en.wikipedia.org/w/index.php?title=Python_(programming_langua
ge)&oldid=1116394427. [Accessed 16 October 2022].
[5] L. S. Vailshery, "Statista," Statista, 5 May 2022. [Online]. Available:
Python - Statistics & Facts. [Accessed 09 October 2022].
[6] Statista, "Most used programming languages among developers
worldwide as of 2022," 2022. [Online]. Available: https://www-statista-
com.eu1.proxy.openathens.net/statistics/793628/worldwide-developer-
survey-most-used-languages/. [Accessed 09 October 2022].
[7] Stack Overflow, "2022 Developer Survey," Stack Overflow, 2022.
[Online]. Available: https://survey.stackoverflow.co/2022/#most-popular-
technologies-webframe. [Accessed 09 October 2022].
[8] Django Project, "The web framework for perfectionists with deadlines |
Django," Django Project, [Online]. Available:
https://www.djangoproject.com/. [Accessed 14 October 2022].
[9] Django Project, "FAQ: General," Django , [Online]. Available:
https://docs.djangoproject.com/en/4.1/faq/general/#why-does-this-
project-exist. [Accessed 14 October 2022].
[10] Django Project, "Applications," [Online]. Available:
https://docs.djangoproject.com/en/4.1/ref/applications/. [Accessed 14
October 2022].
[11] Django Packages, "Django Packages : Frequently Asked Questions,"
Django Packages, [Online]. Available: https://djangopackages.org/faq/.
[Accessed 14 October 2022].
[12] Django Project, "About the Django Software Foundation," Django,
[Online]. Available: https://www.djangoproject.com/foundation/.
[Accessed 14 October 2022].
[13] Trio Blog, "9 Examples of Companies Using Django in 2022," Trio ,
[Online]. Available: https://www.trio.dev/blog/django-applications.
[Accessed 14 October 2022].
[14] Wikipedia contributors, "API," Wikipedia, The Free Encyclopedia, 12
October 2022. [Online]. Available:
https://en.wikipedia.org/w/index.php?title=API&oldid=1115721711.
62
[Accessed 14 October 2022].
[15] W. S. Vincent, Django for APIs: Build web APIs with Python and Django,
WelcomeToCode, 2022.
[16] encode, "encode/django-rest-framework: Web APIs for Django. ,"
Github.com, [Online]. Available: https://github.com/encode/django-rest-
framework. [Accessed 14 October 2022].
[17] T. Christie, "Posts - Django REST framework 3 by Tom Christie -
Kickstarter," Kickstarter, [Online]. Available:
https://www.kickstarter.com/projects/tomchristie/django-rest-framework-
3/posts. [Accessed 14 October 2022].
[18] T. Christie, "Django REST framework 3 by Tom Christie - Kickstarter,"
Kickstarter, [Online]. Available:
https://www.kickstarter.com/projects/tomchristie/django-rest-framework-
3. [Accessed 14 October 2022].
[19] T. Christie, "3.3 Release," Kickstarter, [Online]. Available:
https://www.kickstarter.com/projects/tomchristie/django-rest-framework-
3/posts/1391664. [Accessed 14 October 2022].
[20] Django REST framework, "Django REST framework 3.14," Django REST
framework, [Online]. Available: https://www.django-rest-
framework.org/community/3.14-announcement/. [Accessed 14 October
2022].
[21] Django REST framework, "Funding - Django REST framework," Django
REST framework, [Online]. Available: https://fund.django-rest-
framework.org/topics/funding/#our-sponsors. [Accessed 14 October
2022].
[22] encode, "Security Policy," Github, [Online]. Available:
https://github.com/encode/django-rest-framework/security/policy.
[Accessed 16 October 2022].
[23] Hiscox Group, "22054 - Hiscox Cyber Readiness Report 2022-
EN_0.pdf," 2022. [Online]. Available:
https://www.hiscoxgroup.com/sites/group/files/documents/2022-
05/22054%20-%20Hiscox%20Cyber%20Readiness%20Report%202022-
EN_0.pdf. [Accessed 17 October 2022].
[24] Hiscox; Forrester Research, "Average costs of all cyber attacks in the
United States and Europe from 2021 to 2022, by country," statista,
[Online]. Available: https://www-statista-
com.eu1.proxy.openathens.net/statistics/1327147/median-cost-attacks-
in-cyber-security-united-states-europe/. [Accessed 17 October 2022].
[25] Imperva, "Quantifying the Cost of API Insecurity," Imperva, Marsh-
McLennan, 2022.
[26] Allianz, "Leading risks to businesses worldwide from 2018 to 2022,"
statista, [Online]. Available: https://www-statista-
com.eu1.proxy.openathens.net/statistics/422171/leading-business-risks-
globally/. [Accessed 17 October 2022].
[27] Open Web Application Security Project® (OWASP), "Open Web
Application Security Project® (OWASP)," Open Web Application Security
Project® (OWASP), [Online]. Available: https://owasp.org/. [Accessed 17
63
October 2022].
[28] SANS Institute, "About SANS Institute," SANS Institute, [Online].
Available: https://www.sans.org/about/. [Accessed 17 October 2022].
[29] Wikipedia contributors, "SANS Institute," Wikipedia, The Free
Encyclopedia., 7 October 2022 . [Online]. Available:
https://en.wikipedia.org/w/index.php?title=SANS_Institute&oldid=111470
9978. [Accessed 17 October 2022 ].
[30] Centro Criptológico Nacional, "CWE/SANS publica la lista de los 25
errores de software más peligrosos," CCN CERT, 10 January 2011.
[Online]. Available: https://www.ccn-cert.cni.es/seguridad-al-dia/noticias-
seguridad/895-cwesans-publica-la-lista-de-los-25-errores-de-software-
mas-peligrosos.html. [Accessed 17 October 2022].
[31] Wikipedia contributors, "Systems development life cycle," Wikipedia, The
Free Encyclopedia., 4 October 2022 . [Online]. Available:
https://en.wikipedia.org/w/index.php?title=Systems_development_life_cy
cle&oldid=1114002735. [Accessed 17 October 2022].
[32] Wikipedia contributors, "Application security," Wikipedia, The Free
Encyclopedia., 26 August 2022 . [Online]. Available:
https://en.wikipedia.org/wiki/Application_security. [Accessed 17 October
2022 ].
[33] OWASP, "OWASP Top Ten," Open Web Application Security Project,
[Online]. Available: https://owasp.org/www-project-top-ten/. [Accessed 23
October 2022].
[34] OWASP , "Top10/archives at master · OWASP/Top10," Github, [Online].
Available: https://github.com/OWASP/Top10/tree/master/archives.
[Accessed 23 October 2022].
[35] B. Glas, "The Release of the OWASP Top 10:2021," OWASP, 24
September 2021. [Online]. Available: https://www.owasptopten.org/the-
release-of-the-owasp-top-10-2021. [Accessed 23 October 2022].
[36] OWASP, "OWASP API Security Top 10 2019," OWASP, 2019.
[37] Open Web Application Security Project, "OWASP API Security Project,"
OWASP , [Online]. Available: https://owasp.org/www-project-api-
security/. [Accessed 27 October 2022].
[38] The MITRE Corporation, "2022 CWE Top 25 Most Dangerous Software
Weaknesses," MITRE , [Online]. Available:
https://cwe.mitre.org/top25/archive/2022/2022_cwe_top25.html.
[Accessed 27 October 2022].
[39] Snyk, "Secure Software Development Lifecycle (SSDLC)," Snyk Blog,
[Online]. Available: https://snyk.io/learn/secure-sdlc/. [Accessed 28
October 2022].
[40] E. Johnson, "Securing the Software Development Lifecycle," SANS, 15
April 2015. [Online]. Available: https://www.sans.org/blog/securing-the-
software-development-lifecycle/. [Accessed 28 October 2022].
[41] Django Project, "Django’s security policies," Django Project, [Online].
Available: https://docs.djangoproject.com/en/4.1/internals/security/.
[Accessed 12 November 2022].
[42] Django Project, "Download," Django Project, [Online]. Available:
64
https://www.djangoproject.com/download/. [Accessed 12 November
2022].
[43] T. Christie, "Security Policy," Github, 16 March 2022. [Online]. Available:
https://github.com/encode/django-rest-framework/security/policy.
[Accessed 12 November 2022].
[44] D. R. G. a. A. R. Greenfeld, Two Scoops of Django 3.x, Feldroy Shop PS
Feldroy LLC., 2021.
[45] Django Project, "Settings," Django Project, [Online]. Available:
https://docs.djangoproject.com/en/4.1/ref/settings/. [Accessed 13
November 2022].
[46] W. Vincent, "Django Best Practices: Security," Learn Django, 24 October
2022. [Online]. Available: https://learndjango.com/tutorials/django-best-
practices-security. [Accessed 13 November 2022].
[47] AWS Amazon, "Application Load Balancer," AWS Amazon, [Online].
Available: https://aws.amazon.com/elasticloadbalancing/application-load-
balancer/. [Accessed 13 November 2022].
[48] Django REST Framework, "Settings," Django REST Framework,
[Online]. Available: https://www.django-rest-framework.org/api-
guide/settings/. [Accessed 14 November 2022].
[49] Synopsys, "2022 Open Source Security and Risk Analysis Report," 2022.
[Online]. Available:
https://www.synopsys.com/content/dam/synopsys/sig-assets/reports/rep-
ossra-2022.pdf. [Accessed 14 November 2022].
[50] National Telecommunications and Information Administration, "SBOM
FAQ," 16 November 2022. [Online]. Available:
https://www.ntia.gov/files/ntia/publications/sbom_faq_-_20201116.pdf.
[Accessed 14 November 2022].
[51] L. Irsigler, "A (soft) introduction to Python dependency management,"
Snyk, 14 September 2021. [Online]. Available:
https://snyk.io/blog/introduction-to-python-dependency-management/.
[Accessed 14 November 2022].
[52] A. R. G. Daniel Roy Greenfeld, A Wedge of Django, Feldroy, 2021.
[53] riptutorial, "Using multiple requirements files," riptutorial, [Online].
Available: https://riptutorial.com/django/example/8561/using-multiple-
requirements-files. [Accessed 14 November 2022].
[54] B. O'Shea, "How Dependabot empowers you to keep your projects
secure," Github, 6 April 2022. [Online]. Available:
https://github.blog/2022-04-06-how-dependabot-empowers-you-to-keep-
your-projects-secure/. [Accessed 14 November 2022].
[55] Snyk, "Open Source Security Management | SCA Tool | Snyk," Snyk,
[Online]. Available: https://snyk.io/product/open-source-security-
management/. [Accessed 14 November 2022].
[56] A. Birsan, "Dependency Confusion: How I Hacked Into Apple, Microsoft
and Dozens of Other Companies," Medium, 9 February 2021. [Online].
Available: https://medium.com/@alex.birsan/dependency-confusion-
4a5d60fec610. [Accessed 15 November 2022].
[57] Y. Gelb, "Automatic Execution of Code Upon Package Download on
65
Python Package Manager," Checkmarx Security, 29 August 2022.
[Online]. Available: https://medium.com/checkmarx-security/automatic-
execution-of-code-upon-package-download-on-python-package-
manager-cd6ed9e366a8. [Accessed 19 November 2022].
[58] Microsoft, "3 ways to mitigate risk when using private package feeds,"
[Online]. Available:
https://azure.microsoft.com/mediahandler/files/resourcefiles/3-ways-to-
mitigate-risk-using-private-package-
feeds/3%20Ways%20to%20Mitigate%20Risk%20When%20Using%20Pri
vate%20Package%20Feeds%20-%20v1.0.pdf. [Accessed 15 November
2022].
[59] L. EPPALAGUDEM, "Dependencies, Confusions, and Solutions: What
Did Twilio Do to Solve Dependency Confusion," Twilio Blog, 03 August
2021. [Online]. Available: https://www.twilio.com/blog/avoiding-
dependency-confusion-attacks. [Accessed 18 November 2022].
[60] DataDog, "Github's GuardDog," DataDog, [Online]. Available:
https://github.com/DataDog/guarddog. [Accessed 19 November 2022].
[61] C. T.-D. Ellen Wang, "Finding malicious PyPI packages through static
code analysis: Meet GuardDog," DataDog, 15 November 2022. [Online].
Available: https://securitylabs.datadoghq.com/articles/guarddog-identify-
malicious-pypi-packages/. [Accessed 19 November 2022].
[62] pyupio, "safety-db," Github, 1 November 2022. [Online]. Available:
https://github.com/pyupio/safety-db. [Accessed 26 November 2022].
[63] Django Project, "Security in Django," Django Project, [Online]. Available:
https://docs.djangoproject.com/en/4.1/topics/security/. [Accessed 20
November 2022].
[64] W. S. Vincent, Django for Professionals,
https://djangoforprofessionals.com, 2020.
[65] Python Software Foundation, "pickle — Python object serialization,"
Python Software Foundation, 21 November 2022. [Online]. Available:
https://docs.python.org/3/library/pickle.html. [Accessed 21 November
2022].
[66] Django REST Framework, "Authentication," Django REST Framework,
[Online]. Available: https://www.django-rest-framework.org/api-
guide/authentication/. [Accessed 25 November 2022].
[67] Django REST Framework, "Permissions," Django REST Framework,
[Online]. Available: https://www.django-rest-framework.org/api-
guide/permissions/. [Accessed 25 November 2022].
[68] Django REST Framework, "Serializers," Django REST Framework,
[Online]. Available: https://www.django-rest-framework.org/api-
guide/serializers/#specifying-which-fields-to-include. [Accessed 25
November 2022].
[69] mikecodase, "codase," codase, 8 February 2022. [Online]. Available:
https://codase.com/sast-tools-everything-you-need-to-know/. [Accessed
26 November 2022].
[70] PyCQA, "bandit," Github, 28 October 2022. [Online]. Available:
https://github.com/PyCQA/bandit. [Accessed 26 November 2022].
66
[71] pycharm-security, "PyCharm Python Security plugin," Read The Docs,
[Online]. Available: https://pycharm-
security.readthedocs.io/en/latest/index.html. [Accessed 26 November
2022].
[72] MITRE, "CWE CATEGORY: Business Logic Errors," MITRE, [Online].
Available: https://cwe.mitre.org/data/definitions/840.html. [Accessed 26
November 2022].
[73] Django Project, "System check framework," Django Project, [Online].
Available: https://docs.djangoproject.com/en/4.1/topics/checks/.
[Accessed 27 November 2022].
[74] Microsoft, "CI/CD for microservices architectures," Microsoft, [Online].
Available: https://learn.microsoft.com/en-
us/azure/architecture/microservices/ci-cd. [Accessed 27 November
2022].
[75] OWASP, " OWASP Cheat Sheet Series," OWASP, [Online]. Available:
https://cheatsheetseries.owasp.org/index.html. [Accessed 20 December
2022].
[76] Wikipedia contributors, "Common Vulnerabilities and Exposures,"
Wikipedia, The Free Encyclopedia., 15 July 2022. [Online]. Available:
https://en.wikipedia.org/w/index.php?title=Common_Vulnerabilities_and_
Exposures&oldid=1098348060. [Accessed 16 October 2022].
[77] Mozilla Foundation, "HTTP," Mozilla Foundation, [Online]. Available:
https://developer.mozilla.org/en-US/docs/Glossary/HTTP. [Accessed 16
October 2022].
[78] Wikipedia contributors, "Mitre Corporation," Wikipedia, The Free
Encyclopedia., 21 August 2022. [Online]. Available:
https://en.wikipedia.org/w/index.php?title=Mitre_Corporation&oldid=1105
777011. [Accessed 16 October 2022].
[79] Wikipedia contributors, "Transport Layer Security," Wikipedia, The Free
Encyclopedia., 17 September 2022 . [Online]. Available:
https://en.wikipedia.org/w/index.php?title=Transport_Layer_Security&oldi
d=1110721112. [Accessed 16 October 2022 ].
67
9 Annexes
9.1 Appendix 1 - Django REST Framework (DRF) Cheat Sheet
## Introduction
This *Cheat sheet* intends to provide quick basic Django REST Framework
security tips for developers.
## Settings
All the Django REST Framework (DRF) configuration is done under the
namespace REST_FRAMEWORK, usually in the settings.py file. From a
security perspective, the most relevant ones are:
### DEFAULT_AUTHENTICATION_CLASSES
### DEFAULT_PERMISSION_CLASSES
### DEFAULT_THROTTLE_CLASSES
68
A list of throttle classes that determines the default set of throttles
checked at the start of a view.
**Default is empty**, that means that by default there is no throttling
in place.
### DEFAULT_PAGINATION_CLASS
This section is based on this. Your approach to securing your web API
should be to start at the top threat A1 below and work down, this will
ensure that any time spent on security will be spent most effectively
spent and cover the top threats first and lesser threats afterwards.
After covering the top 10 it is generally advisable to assess for other
threats or get a professionally completed Penetration Test.
DO: Validate that the object can be accessed by the user using the method
`.check_object_permissions(request, obj)`. Example:
```python
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
```
69
DO: Have authentication on every non-public API endpoint.
DO: Review the serializer and the information you are displaying.
70
DO NOT: Use `ModelForms.Meta.fields = "__all__"`
DO: Ensure API can only be accessed by the specified HTTP verbs. All
other HTTP verbs should be disabled.
#### SQLi
TRY NOT TO: Use dangerous methods like `raw()`, `extra()` and custom SQL
(via `cursor.execute()`).
#### RCE
71
### API9:2019 Improper Assets Management
DO: Have an inventory of all API hosts and document important aspects of
each one of them, focusing on the API environment (e.g., production,
staging, test, development), who should have network access to the host
(e.g., public, internal, partners) and the API version.
DO: Log all failed authentication attempts, denied access, and input
validation errors with sufficient user context to identify suspicious or
malicious accounts.
DO NOT: Log sensitive data such as user's passwords, API Tokens or PII.
Below is a list of security risks for APIs not discussed in the OWASP API
Security Top 10.
72
Any application in any technology can contain business logic errors that
result in security bugs. Business logic bugs are difficult to impossible
to detect using automated tools. The best ways to prevent business logic
security bugs are to do threat model, security design review, code
review, pair program and write unit tests.
## Updating Django and DRF and Having a Process for Updating Dependencies
## SAST Tools
73
scanning all the files it generates a report. Bandit was originally
developed within the OpenStack Security Project and later rehomed to
PyCQA.
- [Django’s security
policies](https://docs.djangoproject.com/en/4.1/internals/security/)
- [Security in
Django](https://docs.djangoproject.com/en/4.1/topics/security/)
74