ievans.python-all-2020-07
All the python rules as of July 7, 2020
Run Locally
Rules (149)

Detected a Jinja2 environment without autoescaping. Jinja2 does not autoescape by default. This is dangerous if you are rendering to a browser because this allows for cross-site scripting (XSS) attacks. If you are in a web context, enable autoescaping by setting 'autoescape=True.' You may also consider using 'jinja2.select_autoescape()' to only enable automatic escaping for certain file extensions.

Detected user data flowing into eval. This is code injection and should be avoided.

Detected user data flowing into exec. This is code injection and should be avoided.

This rule is deprecated.

Function $F mutates default dict $D. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new dictionary at that time. For example: `if $D is None: $D = {}`.

Function $F mutates default list $D. Python only instantiates default function arguments once and shares the instance across the function calls. If the default function argument is mutated, that will modify the instance used by all future function calls. This can cause unexpected results, or lead to security vulnerabilities whereby one function consumer can view or modify the data of another function consumer. Instead, use a default argument (like None) to indicate that no argument was provided and instantiate a new list at that time. For example: `if $D is None: $D = []`.

It appears that `$DICT[$KEY]` is a dict with items being deleted while in a for loop. This is usually a bad idea and will likely lead to a RuntimeError: dictionary changed size during iteration

User data detected in os.system. This could be vulnerable to a command injection and should be avoided. If this must be done, use the 'subprocess' module instead and pass the arguments as a list.

Found request data in a call to 'open'. Ensure the request data is validated or sanitized, otherwise it could result in path traversal attacks.

Data from request object is passed to a new server-side request. This could lead to a server-side request forgery (SSRF). To mitigate, ensure that schemes and hosts are validated against an allowlist, do not forward the response to the user, and ensure proper authentication and transport-layer security in the proxied request.

This expression is always True: `$X == $X` or `$X != $X`. If testing for floating point NaN, use `math.isnan($X)`, or `cmath.isnan($X)` if the number is complex.

Certificate verification has been explicitly disabled. This permits insecure connections to insecure servers. Re-enable certification validation.

Authentication detected over HTTP. HTTP does not provide any encryption or protection for these authentication credentials. This may expose these credentials to unauthorized parties. Use 'https://' instead.

Because portions of the logging configuration are passed through eval(), use of this function may open its users to a security risk. While the function only binds to a socket on localhost, and so does not accept connections from remote machines, there are scenarios where untrusted code could be run under the account of the process which calls listen(). To avoid this happening, use the `verify()` argument to `listen()` to prevent unrecognized configurations.

Using '$F.name' without '.flush()' or '.close()' may cause an error because the file may not exist when '$F.name' is used. Use '.flush()' or close the file before using '$F.name'.

if block checks for the same condition on both branches (`$X`)

key `$X` is uselessly assigned twice

Found a template created with string formatting. This is susceptible to server-side template injection and cross-site scripting attacks.

A hard-coded credential was detected. It is not recommended to store credentials in source-code, as this risks secrets being leaked and used by either an internal or external malicious adversary. It is recommended to use environment variables to securely provide credentials or retrieve credentials from a secure vault or HSM (Hardware Security Module).

Detected Blowfish cipher algorithm which is considered insecure. The algorithm has many known vulnerabilities. Use AES instead.

Detected IDEA cipher algorithm which is considered insecure. The algorithm is considered weak and has been deprecated. Use AES instead.

Detected RC4 cipher algorithm which is considered insecure. The algorithm has many known vulnerabilities. Use AES instead.

Detected ECB cipher mode which is considered insecure. The algorithm can potentially leak information about the plaintext. Use CBC mode instead.

Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.

Detected SHA1 hash algorithm which is considered insecure. SHA1 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.

An insecure SSL version was detected. TLS versions 1.0, 1.1, and all SSL versions are considered weak encryption and are deprecated. Use 'ssl.PROTOCOL_TLSv1_2' or higher.

Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.

Detected SHA1 hash algorithm which is considered insecure. SHA1 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.

Unverified SSL context detected. This will permit insecure connections without verifying SSL certificates. Use 'ssl.create_default_context' instead.

The Python documentation recommends using `defusedxml` instead of `xml` because the native Python `xml` library is vulnerable to XML External Entity (XXE) attacks. These attacks can leak confidential data and "XML bombs" can cause denial of service.

Detected Blowfish cipher algorithm which is considered insecure. The algorithm has many known vulnerabilities. Use AES instead.

Detected DES cipher algorithm which is considered insecure. The algorithm is considered weak and has been deprecated. Use AES instead.

Detected RC2 cipher algorithm which is considered insecure. The algorithm has known vulnerabilities and is difficult to use securely. Use AES instead.

Detected RC4 cipher algorithm which is considered insecure. The algorithm has many known vulnerabilities. Use AES instead.

Detected XOR cipher algorithm which is considered insecure. This algorithm is not cryptographically secure and can be reversed easily. Use AES instead.

Detected MD2 hash algorithm which is considered insecure. This algorithm has many known vulnerabilities and has been deprecated. Use SHA256 or SHA3 instead.

Detected MD4 hash algorithm which is considered insecure. This algorithm has many known vulnerabilities and has been deprecated. Use SHA256 or SHA3 instead.

Detected MD5 hash algorithm which is considered insecure. MD5 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.

Detected SHA1 hash algorithm which is considered insecure. SHA1 is not collision resistant and is therefore not suitable as a cryptographic signature. Use SHA256 or SHA3 instead.

Detected the use of an insecure deserialization library in a Flask route. These libraries are prone to code execution vulnerabilities. Ensure user data does not enter this function. To fix this, try to avoid serializing whole objects. Consider instead using a serializer such as JSON.

Detected an insufficient curve size for EC. NIST recommends a key size of 224 or higher. For example, use 'ec.SECP256R1'.

Detected use of xmlrpc. xmlrpc is not inherently safe from vulnerabilities. Use defusedxml.xmlrpc instead.

Found string comparison using 'is' operator. The 'is' operator is for reference equality, not value equality, and therefore should not be used to compare strings. For more information, see https://github.com/satwikkansal/wtfpython#-how-not-to-use-is-operator"

Found a template created with string formatting. This is susceptible to server-side template injection and cross-site scripting attacks.

Running flask app with host 0.0.0.0 could expose the server publicly.

top-level app.run(...) is ignored by flask. Consider putting app.run(...) behind a guard, like inside a function

Detected a user-controlled `filename` that could flow to `flask.send_file()` function. This could lead to an attacker reading arbitrary file from the system, leaking private information. Make sure to properly sanitize filename or use `flask.send_from_directory`

Hardcoded variable `DEBUG` detected. Set this by using FLASK_DEBUG environment variable

Hardcoded variable `ENV` detected. Set this by using FLASK_ENV environment variable

Hardcoded variable `SECRET_KEY` detected. Use environment variables or config files instead

Hardcoded variable `TESTING` detected. Use environment variables or config files instead

The marshal module is not intended to be secure against erroneous or maliciously constructed data. Never unmarshal data received from an untrusted or unauthenticated source. See more details: https://docs.python.org/3/library/marshal.html?highlight=security

Running `socket.bind` to 0.0.0.0, or empty string could unexpectedly expose the server publicly as it binds to all available interfaces. Consider instead getting correct address from an environment variable or configuration file.

Avoid using `cPickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.

Avoid using `dill`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.

Avoid using `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.

Avoid using `shelve`, which uses `pickle`, which is known to lead to code execution vulnerabilities. When unpickling, the serialized data could be manipulated to run arbitrary code. Instead, consider serializing the relevant data as JSON or a similar text-based serialization format.

Detected HTTPConnectionPool. This will transmit data in cleartext. It is recommended to use HTTPSConnectionPool instead for to encrypt communications.

Found dynamic content used in a system call. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Use the 'subprocess' module instead, which is easier to use without accidentally exposing a command injection vulnerability.

The Connection.recv() method automatically unpickles the data it receives, which can be a security risk unless you can trust the process which sent the message. Therefore, unless the connection object was produced using Pipe() you should only use the recv() and send() methods after performing some sort of authentication. See more dettails: https://docs.python.org/3/library/multiprocessing.html?highlight=security#multiprocessing.connection.Connection

Detected a dynamic value being used with urllib. urllib supports 'file://' schemes, so a dynamic value controlled by a malicious actor may allow them to read arbitrary files. Audit uses of urllib calls to ensure user data cannot control the URLs, or consider using the 'requests' library instead.

In Python 'X is not ...' is different from 'X is (not ...)'. In the latter the 'not' converts the '...' directly to boolean.

`return` should never appear inside a class __init__ function. This will cause a runtime error.

`yield` should never appear inside a class __init__ function. This will cause a runtime error.

Flask does not automatically escape Jinja templates unless they have .html, .htm, .xml, or .xhtml extensions. This could lead to XSS attacks. Use .html, .htm, .xml, or .xhtml for your template extensions. See https://flask.palletsprojects.com/en/1.1.x/templating/#jinja-setup for more information.

Flask response reflects unsanitized user input. This could lead to a cross-site scripting vulnerability (https://owasp.org/www-community/attacks/xss/) in which an attacker causes arbitrary code to be executed in the user's browser. To prevent, please sanitize the user input, e.g. by rendering the response in a Jinja2 template (see considerations in https://flask.palletsprojects.com/en/1.0.x/security/).

Found a Flask cookie without secure, httponly, or samesite correctly set. Flask cookies should be handled securely by setting secure=True, httponly=True, and samesite='Lax' in response.set_cookie(...). If these parameters are not properly set, your cookies are not properly protected and are at risk of being stolen by an attacker. Include the 'secure=True', 'httponly=True', samesite='Lax' arguments or set these to be true in the Flask configuration.

Setting 'WTF_CSRF_ENABLED' to 'False' explicitly disables CSRF protection.

Data from request is passed to redirect(). This is an open redirect and could be exploited. Consider using 'url_for()' to generate links to known locations. If you must use a URL to unknown pages, consider using 'urlparse()' or similar and checking if the 'netloc' property is the same as your site's host name. See the references for more information.

Detected the use of eval(). eval() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.

Detected the use of exec(). exec() can be dangerous if used to evaluate dynamic content. If this content can be input from outside the program, this may be a code injection vulnerability. Ensure evaluated content is not definable by external sources.

Unverified SSL context detected. This will permit insecure connections without verifying SSL certificates. Use 'ssl.create_default_context()' instead.

Found 'subprocess' function '$FUNC' with 'shell=True'. This is dangerous because this call will spawn the command using a shell process. Doing so propagates current shell settings and variables, which makes it much easier for a malicious actor to execute commands. Use 'shell=False' instead.

Detected Flask app with debug=True. Do not deploy to production with this flag enabled as it will leak sensitive information. Instead, consider using Flask configuration variables or setting 'debug' using system environment variables.

FTP does not encrypt communications by default. This can lead to sensitive data being exposed. Ensure use of FTP here does not expose sensitive data.

The HTTPSConnection API has changed frequently with minor releases of Python. Ensure you are using the API for your version of Python securely. For example, Python 3 versions prior to 3.4.3 will not verify SSL certificates by default. See https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection for more information.

Mako templates do not provide a global HTML escaping mechanism. This means you must escape all sensitive data in your templates using '| u' for URL escaping or '| h' for HTML escaping. If you are using Mako to serve web content, consider using a system such as Jinja2 which enables global escaping.

Detected a paramiko host key policy that implicitly trusts a server's host key. Host keys should be verified to ensure the connection is not to a malicious server. Use RejectPolicy or a custom subclass instead.

'ssl.wrap_socket()' is deprecated. This function creates an insecure socket without server name indication or hostname matching. Instead, create an SSL context using 'ssl.SSLContext()' and use that to wrap a socket.

Telnet does not encrypt communications. Use SSH instead.

Detected use of an insecure MD4 or MD5 hash function. These functions have known vulnerabilities and are considered deprecated. Consider using 'SHA256' or a similar function instead.

Found a formatted string in BashOperator: $CMD. This could be vulnerable to injection. Be extra sure your variables are not controllable by external sources.

Detected a possible YAML deserialization vulnerability. `yaml.unsafe_load`, `yaml.Loader`, `yaml.CLoader`, and `yaml.UnsafeLoader` are all known to be unsafe methods of deserializing YAML. An attacker with control over the YAML input could create special YAML input that allows the attacker to run arbitrary Python code. This would allow the attacker to steal files, download and install malware, or otherwise take over the machine. Use `yaml.safe_load` or `yaml.SafeLoader` instead.

Hardcoded password is used as a default argument to '$FUNC'. This could be dangerous if a real password is not supplied.

This is not checking the return value of this subprocess call; if it fails no exception will be raised. Consider subprocess.check_call() instead

Found identical comparison using is. Ensure this is what you intended.

In Python3, a runtime `TypeError` will be thrown if you attempt to raise an object or class which does not inherit from `BaseException`

Found dynamic content when spawning a process. This is dangerous if external data can reach this function call because it allows a malicious actor to execute commands. Ensure no external data reaches here.

Detected use of `exit`. Use `sys.exit` over the python shell `exit` built-in. `exit` is a helper for the interactive shell and may not be available on all Python implementations.

Detected strings that are implicitly concatenated inside a list. Python will implicitly concatenate strings when not explicitly delimited. Was this supposed to be individual elements of the list?

Detected a 'requests' call without a timeout set. By default, 'requests' calls wait until the connection is closed. This means a 'requests' call without a timeout will hang the program if a response is never received. Consider setting a timeout for all 'requests'.

Use tempfile.NamedTemporaryFile instead. From the official Python documentation: THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may refer to a file that did not exist at some point, but by the time you get around to creating it, someone else may have beaten you to the punch.

This rule is deprecated. It will no longer produce findings.

Detected a file object that is redefined and never closed. This could leak file descriptors and unnecessarily consume system resources.

Accessing request object inside a route handle for HTTP GET command will throw due to missing request body.

flask.jsonify() is a Flask helper method which handles the correct settings for returning JSON from Flask routes

Looks like `$R` is a flask function handler that registered to two different routes. This will cause a runtime error

.delete().where(...) results in a no-op in SQLAlchemy unless the command is executed, use .filter(...).delete() instead.

Use `click.secho($X)` instead. It combines click.echo() and click.style().

deprecated Flask API

Rather than adding one element at a time, consider batch loading to improve performance.

Using QUERY.count() instead of len(QUERY.all()) sends less data to the client since the SQLAlchemy method is performed server-side.

manually creating a counter - use collections.Counter

manually creating a defaultdict - use collections.defaultdict(dict)

manually creating a defaultdict - use collections.defaultdict(list)

manually creating a defaultdict - use collections.defaultdict(set)

Class `$A` has defined `__eq__` which means it should also have defined `__hash__`;

file object opened without corresponding close

`pass` is the body of function $X. Consider removing this or raise NotImplementedError() if this is a TODO

`pass` is the body of for $X in $Y. Consider removing this or raise NotImplementedError() if this is a TODO

Importing the python debugger; did you mean to leave this in?

time.sleep() call; did you mean to leave this in?

code after return statement will not be executed

key `$Y` in `$X` is assigned twice; the first assignment is useless

Useless if statement; both blocks have the same body

function `$FF` is defined inside a function but never used

Detected hardcoded temp directory. Consider using 'tempfile.TemporaryFile' instead.

Only comparison operators should be used inside SQLAlchemy filter expressions. Use `==` instead of `is`, `!=` instead of `is not`, `sqlalchemy.and_` instead of `and`, `sqlalchemy.or_` instead of `or`, `sqlalchemy.not_` instead of `not`, and `sqlalchemy.in_` instead of `in_`.

The Python 'os' tempnam|tmpnam functions are vulnerable to symlink attacks

The Python 'xmlrpc' module used with 'allow_dotted_names' is not secure against maliciously constructed input

Insecure XML parsing functionality, prefer 'defusedxml'

Weak or insecure 'xmlsec' module attribute usage

The Python 'pickle' module is not secure against maliciously constructed input

The Python 'commands' module is not secure against maliciously constructed input

The Python 'compile' function is not secure against maliciously constructed input

Weak or insecure 'cryptography' module attribute usage

The Python 'dl' module may cause segmentation faults or other incorrect behavior

The Python third-party 'duo_client' module used with SSL verfication disabled

The Python 'eval' function is not secure against maliciously constructed input

The Python 'exec' function is not secure against maliciously constructed input

The Python 'gl' module may cause core dumps or other unsafe behavior

Weak or insecure 'hashlib' module usage

The Python third-party 'itsdangerous' module used with 'none' signing algorithm

The Python 'marshal' module is not secure against maliciously constructed input

Weak or insecure 'onelogin' module attribute usage

The Python 'os' execution functions are not secure against maliciously constructed input

The Python 'popen2' module is not secure against maliciously constructed input

The Python third-party 'Crypto' module is unmaintained and has known vulnerabilities and exploits

The Python third-party 'requests' module used with SSL verification disabled

The Python 'shelve' module is not secure against maliciously constructed input

Weak or insecure 'ssl' module usage

The Python 'subprocess' module called with 'shell=True' may allow for shell injection

The Python 'tarfile' extract|extractall functions are vulnerable to arbitrary file overwrites

The Python 'tempfile.mktemp' function allows for race conditions

The Python 'urllib3' module used with SSL verfication disabled

Warnings disabled on insecure network requests with Python 'urllib3' module

The Python 'yaml' module's `load`, `load_all`, `dump`, and `dump_all` functions are not secure against maliciously constructed input

The Python 'zipfile' extract|extractall functions are vulnerable to arbitrary file overwrites
xss