2023-03-07 17:16:47 +01:00
== How to fix it in Python Standard Library
=== Code examples
2022-11-07 09:05:01 +01:00
include::../../common/fix/code-rationale.adoc[]
==== Noncompliant code example
2023-08-21 15:22:49 +02:00
[source,python,diff-id=11,diff-type=noncompliant]
2022-11-07 09:05:01 +01:00
----
import logging
logger = logging.getLogger(__name__)
@app.route('/example')
def log():
data = request.args["data"]
logger.log(logging.CRITICAL, "%s", data) # Noncompliant
----
==== Compliant solution
2023-08-21 15:22:49 +02:00
[source,python,diff-id=11,diff-type=compliant]
2022-11-07 09:05:01 +01:00
----
import logging
import base64
logger = logging.getLogger(__name__)
@app.route('/example')
def log():
data = request.args["data"]
if data.isalnum():
logger.log(logging.CRITICAL, "%s", data)
else:
logger.log(logging.CRITICAL, "Invalid Input: %s", base64.b64encode(data.encode('UTF-8')))
----
include::../../common/fix/how-does-this-work.adoc[]
Here, the example compliant code uses the `isalnum` function to ensure the untrusted data is safe. If not, it performs Base64 encoding to protect from log injection.