Python 3.0 Fixers
API Usage Issues (2):
Check Bad Path Declaration –
For a Django application, paths should use Unix-style forward slashes even on Windows. Backslashes should not be used while defining a path. This is specific for Django applications.
Set Request Timeout –
Requests to external servers should be made with a timeout mechanism, so that the application making the request does not hang indefinitely when the server is not available.
Broken Authentication (3):
Avoid Default or Empty Password –
A secure password should be chosen when making a database connection. Fixes CWE 521, OWASP A7-Identification and Authentication Failures.
Enable Authentication for LDAP –
Allowing LDAP access without an authentication mechanism is strongly discouraged. Fixes CWE 521, OWASP A7-Identification and Authentication Failures.
Fix Hard-coded Password –
User passwords should not be kept hard-coded in the source code. An attacker can extract the strings or byte arrays from an application source code or binary. Fixes CWE 259, CWE 798, OWASP A7-Identification and Authentication Failures.
Error Handling (6):
Group Multiple Exceptions –
When multiple exceptions are caught, group them as a tuple.
Inherit Exception Class –
Caught and raised exceptions should inherit from
Exception
. User defined Exception classes should not be derived fromBaseException
,KeyboardInterrupt
,SystemExit
, orGeneratorExit
exception.Maintain Exception Handler Order –
Handler for a specific exception should not shadow an Exception to be caught afterwards. If it happens, the latter Exception will never be caught. Fixes subtle, hard-to-detect, logical bugs.
Proper Exception Chaining –
When chaining exceptions by catching and re-raising another one, the raised exception must come from
None
or a valid Exception.Raise Custom Exceptions –
Raising instances of
Exception
andBaseException
is discouraged since it will be hard to distinguish different kinds of exception all thrown asException-s
orBaseException-s
.Raise Instantiated Exception –
When a custom
Exception
is instantiated, it must be raised.
Improper Access Control (4):
Check HTTP Method Mixing –
Both safe
HTTP
methods (GET
,HEAD
,OPTIONS
) and unsafeHTTP
methods (PUT
,DELETE
,POST
) are used together on a single operation which is sensitive to application security. Fixes CWE 352, OWASP A1-Broken Access Control, OWASP A4-Insecure Design.Fix Hard-coded IP Address –
If an IP address is hard-coded, an attacker will have access to internal details of a service. An attacker may perform a Denial of Service (DoS) attack on the service, or attempt to access the service. Fixes OWASP A1-Broken Access Control.
Prevent Untrusted File Extraction –
Attempting to extract an archive file from an untrusted source may lead to a Denial of Service (DoS) attack. The archived file may be very small in size but the uncompressed file is huge. Identifies potential denial of service opportunities through a zip bomb. Fixes CWE 409, OWASP A1-Broken Access Control, OWASP A5-Security Misconfiguration.
Prevent URL Redirection –
Using untrusted user-provided data to perform HTTP redirect leads to an Open Redirection attack. This allows an attacker to redirect a user to a malicious website and steal the user's credential by phishing. Identifies potential Open Redirection opportunities. Fixes CWE 601, OWASP A1-Broken Access Control.
Improper Method Call (6):
Add Required Parameter –
A method is declared with a required parameter missing or is declared with a parameter that does not have a name following the Python coding style.
Flag Inappropriate Parameter Count –
If a
dunder
or a special method (e.g.,__add__
,__getattr__
, etc.,) contains an unexpected number of parameters, each call to this method will result in aTypeError
. Special methods should be defined with the required number of parameters.Standardize Property Accessor –
A getter, setter, or a deleter method has an unexpected number of parameters.
Use Appropriate Return Value For An Unimplemented Special Method –
If a special method is not implemented, it should return
NotImplemented
. For a special method that supports a binary operation (e.g.,__add__
), this allows the interpreter to dispatch the method in a reverse way. If an error such as aNotImplementedError
is raised instead, the exception may crash the application.Use Safe API to Create Temporary Files –
Temporary files should not be created with an unsafe API. Rather, they should be created using a safe API. Fixes CWE 377, CWE 379, OWASP A1-Broken Access Control.
Validate Mode in open Method –
A file should be opened using a valid mode. Using an invalid mode will result in an undefined behavior.
Inappropriate Logic (9):
Avoid Silly Equality Checks –
In some cases, a comparison with an equals (
==
) or a not equals (!=
) operator always returns eithertrue
orfalse
. Such logical short circuits in code lead to unintended behavior.Avoid Wildcard Imports –
Usage of wildcard imports are discouraged as it can lead to conflicts in the local namespace. Also, it hurts code readability.
Check Collection Length Meaningfully –
The size of a Collection is always greater than or equal to zero and never less than zero. Checking if a Collection length is greater than or equal to zero or less than zero is useless.
Check Shadowing of Imported Symbol –
If a method is defined in a file and another method with the same name is also imported using wildcard import, the local definition shadows the imported one. This may lead to unintended behavior.
Check Unexpected Control Flow In
Finally
Block –Unexpected control flow initiated by a
return
,break
, orcontinue
statement should not happen inside afinally
block. Such an unexpected flow will discard the temporarily saved unhandledexception
which was raised inside atry
,else
orexcept
block.Fix Argument Swap –
Swapping arguments in a method call may change the entire logic. Because of dynamic typing in Python, all method calls that pass two or more arguments are susceptible. Fixes subtle, hard-to-detect logical bugs.
Fix Inappropriate Binary Operator –
If a wrong operator is used in a binary operation, the outcome of the operation may change. Fixes subtle, hard-to-detect, logical bugs.
Fix Inappropriate Operand –
In a binary operation, using a wrong operand may change the outcome of the operation. Fixes subtle, hard-to-detect, logical bugs.
Refactor Redundant Method Call –
In a test expression, having multiple calls of the same method is redundant and affects performance. On the other hand, if this was intentionally done, the code should be reviewed and refactored to make it clean.
Injection (12):
Prevent Cross-Site Scripting –
When endpoints reflect back tainted, user-provided data such as
POST
content, URL parameters, etc., it may allow attackers to inject code that will eventually be executed on the browser of a user. Identifies potential Cross-Site Scripting (XSS) opportunities. Fixes CWE 79, CWE 80, CWE 81, CWE 82, CWE 83, CWE 84, CWE 85, CWE 86, CWE 87, OWASP A3-Injection.Prevent Dynamic Code Injection –
Applications that execute code dynamically should do so only on trusted code. Fixes CWE 20, CWE 95, OWASP A3-Injection.
Prevent HTTP Response Splitting –
Constructing HTTP response headers with user-provided, untrusted data may allow an attacker to tamper with the header data. Check that malformed HTTP responses are not created. Fixes CWE 113, OWASP A3-Injection.
Prevent LDAP Injection –
Constructing LDAP names or search filters using untrusted user-provided data enables attackers to inject values that change the way the name or the filter is supposed to interpreted under normal circumstances. Identifies potential LDAP injection opportunities. Fixes CWE 90, OWASP A3-Injection.
Prevent Log Injection –
User-provided, untrusted data should not be injected into logs directly. This allows an attacker to corrupt the log file structure. Fixes CWE 117, OWASP A9-Security Logging and Monitoring Failures.
Prevent OS Command Injection –
Applications that execute operating system calls should not use untrusted user-provided data to create the command or command parameters. Identifies potential OS command injection opportunities. Fixes CWE 20, CWE 78, OWASP A3-Injection.
Prevent Path Manipulation –
Constructing file system paths from untrusted user-provided data such as
POST
content, URL parameters, etc., enables attackers to inject specific path browsing symbols, such as "..
", to manipulate the file path and to access files that they are not allowed to access otherwise. Identifies potential path manipulation opportunities. Fixes CWE 20, CWE 22, CWE 99, CWE 641, OWASP A1-Broken Access Control, OWASP A3-Injection.Prevent Regular Expression Denial of Service –
Using external strings as regular expressions leads to potential denial of service attack since evaluating regular expressions is CPU intensive. Identifies potential regular expression injection opportunities. Fixes CWE 400, OWASP A3-Injection.
Prevent Server-Side Request Forgery –
User-provided, untrusted data should not be used to fetch remote resources. This allows an attacker to send a crafted request to an unexpected destination. Fixes CWE 20, CWE 641, CWE 918, OWASP A10-Server-Side Request Forgery (SSRF).
Prevent SQL Injection –
Constructing SQL queries with untrusted user provided data, e.g., URL parameters, enables attackers to inject code in place of data that changes the meaning of the SQL query. Identifies potential SQL injection opportunities. Fixes CWE 20, CWE 85, CWE 943, OWASP A3-Injection Issue.
Prevent Untrusted Deserialization –
Deserializing user-provided data with an unsafe module may allow an attacker to remotely execute code. Check that the deserialization is done with safe libraries. Fixes CWE 502, OWASP A8-Software and Data Integrity Failures.
Prevent XPath Injection –
Constructing XPath expressions using untrusted user-provided data such as POST content, URL parameters, etc., enables attackers to inject specially crafted values that change the way the expression is supposed to be interpreted under normal circumstances. Identifies potential XPath injection opportunities. Fixes CWE 643, OWASP A3-Injection.
Security Misconfiguration Issues (12):
Allow CSRF Protection –
Web applications should be created with Cross-Site Request Forgery (CSRF) protection. Disallowing it opens up opportunities for an attacker to force a trusted user to perform sensitive operations, such as making the user click a link and visit a malicious website. Fixes CWE 352, OWASP-A1 Broken Access Control. This is specific for Flask applications.
Avoid Permissive Cross-Origin Resource Sharing (CORS) Policy –
Cross-Origin Resource Sharing (CORS) is an
HTTP
header-based mechanism that allows a server to specify that it can support loading resources from some whitelisted domains other than its own. This should not be set with a wildcard because it undermines the same origin policy. Fixes CWE 346, CWE 942, OWASP A5-Security Misconfiguration, OWASP A7-Identification and Authentication Failures. This is specific for Django and Flask applications.Check CSRF Disabled Form –
Protection from Cross-Site Request Forgeries (CSRF) should not be disabled in forms. This opens up opportunities for an attacker to force a trusted user to perform sensitive operations, such as making the user click a link and visit a malicious website. Fixes CWE 352, OWASP-A1 Broken Access Control. This is specific for Flask applications.
Check CSRF Exempt View –
Protection from Cross-Site Request Forgery (CSRF) attacks should not be exempt on a view using a decorator. This opens up opportunities for an attacker to force a trusted user to perform sensitive operations, such as making the user click a link and visit a malicious website. Fixes CWE 352, OWASP-A1 Broken Access Control. This is specific for Django and Flask applications.
Check Sensitive Value Reuse –
Some values for sensitive fields should be kept separate because of security reasons. For example, the values for
MEDIA_ROOT
andSTATIC_ROOT
must be different for Django applications. BeforeSTATIC_ROOT
was introduced, it was common to rely onMEDIA_ROOT
to also serve static files, but this must be avoided because of security implications. Similarly, the values forMEDIA_URL
andSTATIC_URL
should not be mixed. This is specific for Django applications.Configure Logs to be Safe –
The logger configuration is extremely important to ensure that logging is done safely (e.g., determining whether to store warnings, info, or error messages, deciding which details to store, etc.). Adopting the default configuration or disabling the logging altogether is security sensitive. Fixes CWE 117, CWE 532, OWASP A9-Security Logging and Monitoring Failures.
Enable HTML
Autoescape
Mechanism –If
HTML Autoescape
Mechanism is disabled globally, it increases the risk of Cross-Site Scripting (XSS) attacks. This should be enabled globally and if needed can be disabled for specific use cases. Fixes CWE 79, CWE 80, CWE 81, CWE 82, CWE 83, CWE 84, CWE 85, CWE 86, CWE 87.Ensure CSRF Protection in Middleware List –
The Django settings file contains all the configurations of a Django installation. If
CsrfViewMiddleware
is absent from the middleware list in Django settings, it can lead to Cross-Site Request Forgery (CSRF) attacks. This opens up opportunities for an attacker to force a trusted user to perform sensitive operations, such as making the user click a link and visit a malicious website. Fixes CWE 352, OWASP-A1 Broken Access Control. This is specific for Django applications.Missing List of
ALLOWED_HOSTS
–According to Django documentation,
ALLOWED_HOSTS
should be set to a list of strings representing the host/domain names that the site can serve. This is a security measure to prevent HTTP Host header attacks. This is specific for Django applications.Prevent Insufficient Permission for Signaling a Process –
An attacker may be able to control the process ID in an application. In that case, the attacker may be able to send a signal to a process without possessing the appropriate privileges to do so. The signal will be ignored causing a denial of service. Fixes CWE 283.
Prevent XML eXternal Entity –
XML Document Type Definition (DTD) should be disabled to prevent information disclosure via XXE attacks. Fixes CWE 611, CWE 827, OWASP A5-Security Misconfiguration.
Validate Dunder All List –
The list named {
__all__
} should not contain undefined names or non-string elements.
Sensitive Data Exposure (3):
Avoid Hard-coded File Path to Publicly Writable Directories –
Files should not be created with predictable names. Moreover, they should not be created in a publicly writable directory. This exposes any temporarily created file to race condition attacks. An attacker can access, modify or even delete a file. Fixes CWE 377, CWE 379, OWASP A1-Broken Access Control.
Disallow Loose POSIX File Permission –
Granting file access permission to the others class in the POSIX file system exposes the file content to unauthorized entities. Fixes CWE 266, CWE 732, OWASP A1-Broken Access Control, OWASP A4-Insecure Design.
Replace Random Generator –
Weak random number generator should be replaced with a strong random number generator. Fixes CWE 326, CWE 330, CWE 338, CWE 1241, OWASP A2-Cryptographic Failures, OWASP A3-Sensitive Data Exposure.
Weak Cryptography Issues (11):
Avoid Plain Text Communication –
Using clear-text protocols is security-sensitive. Secure all transport channels to protect the communication. Fixes CWE-200, CWE-319, OWASP A3-Sensitive Data Exposure.
Generate Robust Keys –
Generate cryptographic keys with strong parameters such that the keys withstand brute-force cryptanalysis attacks. Fixes CWE-326, OWASP A3-Sensitive Data Exposure, OWASP A6-Security Misconfiguration.
Protect Session Cookies –
Access to the session cookies should be protected when the cookie is stored and when information is transferred. This prevents the theft of cookies done primarily by Cross-Site Scripting (XSS) attacks. Fixes CWE-79, CWE-311, CWE-315, CWE-614, CWE-1004, OWASP A3-Sensitive Data Exposure, OWASP A7-XSS.
Unpredictable Cipher Block Chaining –
Use a secure random number generator to generate the Initialization Vector (IV) in the Cipher Block Chaining (CBC) mode of encryption. This unpredictability prevents a chosen plaintext attack. Fixes CWE-329, CWE-330, OWASP A6-Security Misconfiguration.
Unpredictable Salt in Hash –
The salt used in association with a hashing function should be random, not too short, and it should not have been reused from before. This unpredictability prevents a rainbow table attack. Fixes CWE-759, CWE-760, OWASP A3-Sensitive Data Exposure.
Update SSL Protocol –
Older versions of SSL/TLS protocols, such as SSLv2 or SSLv3, are insecure. Only TLSv1.2 and TLSv1.3 should be used. Fixes CWE-326, CWE-327, OWASP A3-Sensitive Data Exposure, OWASP A6-Security Misconfiguration
Use Secure Hash Function –
Using weak hashing algorithms is security-sensitive. A weak hashing algorithm allows collisions. Fixes CWE-327, CWE-916, OWASP A3-Sensitive Data Exposure, OWASP A6-Security Misconfiguration.
Use Strong Cipher Algorithms –
Data transfer protocols should use strong cipher algorithms. If a weak algorithm is used, the data is vulnerable to brute-force cryptanalysis attacks. If a weak algorithm is used, the data is vulnerable to brute-force cryptanalysis attacks. Fixes CWE 327, OWASP A3-Sensitive Data Exposure.
Validate Server Certificate –
When an SSL/TLS connection is established, the server certificate should be validated. The appropriate options provided by the libraries should be used to ensure that the validation is done correctly. Fixes CWE-295, OWASP A3-Sensitive Data Exposure, OWASP A6-Security Misconfiguration.
Verify Server Hostname –
When an SSL/TLS connection is established, the server should present the correct certificate such that the certificate's hostname specific data matches the server hostname. Hostname verification should not be turned off. Fixes CWE-297, OWASP A3-Sensitive Data Exposure, OWASP A6-Security Misconfiguration.
Verify Signature Properly –
If a weak cipher algorithm is used for signature creation and verification, or no cipher algorithms are used, attackers have the option to impersonate their identities. Data transfer protocols should use strong cipher algorithms. Fixes CWE 347, OWASP A3-Sensitive Data Exposure.
Last updated