Skip to content

Commit 54addac

Browse files
committed
updates
1 parent cbaaaf7 commit 54addac

5 files changed

Lines changed: 299 additions & 1 deletion

File tree

‎constructs/base64.md‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# Base64 Statements
2+
3+
Python Code should not contain obfuscated content, particularly code that uses `base64` (and related encodings) for encoding or decoding data is always suspected.
4+
5+
The following calls can be an indication for obfuscated contain that might cause a security weakness.
6+
7+
* `base64.b64decode`
8+
* `base64.b64encode`
9+
* `base64.b85encode`
10+
* `base64.z85decode`
11+
12+
## Security concerns
13+
14+
Obfuscation using Base64 is a **long-standing and simple technique** commonly employed to conceal malicious code in Python projects. It enables attackers to hide payloads that would otherwise be easily identified.
15+
16+
The use of obfuscated content is uncommon in well-structured, legitimate Python code and is therefore considered a strong indicator of potential security risks.
17+
18+
:::{tip}
19+
It is strongly recommended that any code containing Base64 encoding/decoding be carefully reviewed before deployment to production. Good modern Python SAST scanners, like [**Python Code Audit**](https://github.com/nocomplexity/codeaudit) check for `base64` module usage in code.
20+
:::
21+
22+
**Key red flags include:**
23+
* `base64.b64decode` followed immediately by `exec()` or `eval()`
24+
* Long Base64 strings embedded in Python scripts
25+
* Constructs such as `exec(base64.b64decode(...))` from untrusted sources
26+
27+
### Common Malware Patterns
28+
29+
Base64 encoding patterns are frequently found in Python-based malware and droppers:
30+
31+
| Pattern | Code Snippet | Security Concern |
32+
|----------------------|---------------------------------------------------|-----------------------------------------------|
33+
| Standard b64 + exec | `exec(base64.b64decode(long_string))` | Extremely common obfuscation technique |
34+
| Compressed | `exec(zlib.decompress(base64.b64decode(...)))` | Suggests larger hidden payload and evasion |
35+
| Multi-layer | `base64.b64decode(base64.b64decode(...))` | Attempts to bypass simple pattern matching |
36+
| Bytes decode | `exec(base64.b64decode(data).decode())` | Hides intent by decoding to string |
37+
| Using aliases | `b64 = base64.b64decode; exec(b64(payload))` | Evasion of basic static analysis |
38+
| Z85 / b85 | `base64.b85decode(...)` or `base64.z85decode(...)` | Non-standard encodings often indicate stealth|
39+
40+
### Security Considerations
41+
42+
Base encoding does not provide confidentiality. As noted in RFC 4648 (Section 12), care must be taken when implementing base encoding and decoding to avoid introducing vulnerabilities.
43+
44+
Security considerations section from RFC 4648 (section 12):
45+
46+
```text
47+
Security Considerations
48+
49+
When base encoding and decoding is implemented, care should be taken
50+
not to introduce vulnerabilities to buffer overflow attacks, or other
51+
attacks on the implementation. A decoder should not break on invalid
52+
input including, e.g., embedded NUL characters (ASCII 0).
53+
54+
If non-alphabet characters are ignored, instead of causing rejection
55+
of the entire encoding (as recommended), a covert channel that can be
56+
used to "leak" information is made possible. The ignored characters
57+
could also be used for other nefarious purposes, such as to avoid a
58+
string equality comparison or to trigger implementation bugs. The
59+
implications of ignoring non-alphabet characters should be understood
60+
in applications that do not follow the recommended practice.
61+
Similarly, when the base 16 and base 32 alphabets are handled case
62+
insensitively, alteration of case can be used to leak information or
63+
make string equality comparisons fail.
64+
65+
When padding is used, there are some non-significant bits that
66+
warrant security concerns, as they may be abused to leak information
67+
or used to bypass string equality comparisons or to trigger
68+
implementation problems.
69+
70+
Base encoding visually hides otherwise easily recognized information,
71+
such as passwords, but does not provide any computational
72+
confidentiality. This has been known to cause security incidents
73+
when, e.g., a user reports details of a network protocol exchange
74+
(perhaps to illustrate some other problem) and accidentally reveals
75+
the password because she is unaware that the base encoding does not
76+
protect the password.
77+
78+
Base encoding adds no entropy to the plaintext, but it does increase
79+
the amount of plaintext available and provide a signature for
80+
cryptanalysis in the form of a characteristic probability
81+
distribution.
82+
```
83+
84+
## Example
85+
86+
```python
87+
import base64
88+
safe_string=b'aW1wb3J0IG9zOyBvcy5zeXN0ZW0oJ21hbGljaW91cyBjb21tYW5kJyk='
89+
90+
# Decoding patterns - still common in Python malware
91+
b64 = base64.b64decode
92+
exec(b64(safe_string))
93+
```
94+
95+
What some Python novice did - the attacker side:
96+
97+
```python
98+
payload = b"import os; os.system('malicious command')"
99+
encoded_b64 = base64.b64encode(payload)
100+
101+
```
102+
103+
## References
104+
105+
* [Python Documentation – base64](https://docs.python.org/3/library/base64.html)
106+
* [RFC 4648 – Security Considerations](https://datatracker.ietf.org/doc/html/rfc4648#section-12)
107+
* [Base64 Malleability in Practice](https://eprint.iacr.org/2022/361.pdf)
108+

‎constructs/httpserver.md‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# HTTP Server Use
2+
3+
## Security Concerns
4+
5+
The Python standard library provides `http.server` as a convenient module for quickly launching a web server. However, this convenience comes with significant security implications that should be considering before using.
6+
7+
:::{attention}
8+
The `http.server` module is **explicitly designed for development and testing purposes only**.
9+
:::
10+
11+
The `http.server` module implements **only** a basic HTTP server that lacks essential security features required for production environments, including:
12+
- **No encryption**: Communication occurs over plain HTTP, making all data transmissions vulnerable to interception and eavesdropping
13+
- **No authentication mechanisms**: The server provides no built-in user authentication or authorisation controls
14+
- **Limited request handling**: The server is susceptible to various denial-of-service attacks and malformed request exploits
15+
- **Directory traversal vulnerabilities**: Without careful configuration, the server may expose files outside the intended document root
16+
- **No input sanitisation**: The server does not validate or sanitise incoming requests, potentially leading to injection attacks
17+
18+
These vulnerabilities make `http.server` unsuitable for **any** environment where data confidentiality, integrity, or availability is a concern.
19+
20+
## Preventive Measures
21+
22+
### Development Environment Isolation
23+
24+
The `http.server` module **MUST** be confined exclusively to local development environments. Under no circumstances should this server be exposed to untrusted networks, including local area networks (LANs) or virtual private networks (VPNs) that contain other users.
25+
26+
### Production Deployment Alternatives
27+
28+
For production deployments, Python applications **SHOULD** be served through industry-standard web servers that provide robust security features:
29+
30+
- **Apache HTTP Server**: Offers comprehensive security modules, authentication mechanisms, and SSL/TLS support
31+
- **NGINX**: Provides high-performance request handling with built-in security features and rate limiting
32+
- **Gunicorn or uWSGI**: Application servers designed to work behind reverse proxies, providing process isolation and security boundaries
33+
34+
When deploying Python web applications, adopt a defence-in-depth approach by placing your application behind a production-grade web server that handles security-critical functions.
35+
36+
### Container and Deployment Considerations
37+
38+
Even within containerised environments (Docker, Kubernetes, etc.), using `http.server` remains inadvisable. Container isolation does not compensate for the fundamental security deficiencies of this module. The principle of least privilege dictates that production services should use purpose-built web servers with proven security track records.
39+
40+
## Example
41+
42+
The following example demonstrates the **incorrect** usage of `http.server` in a development scenario that could accidentally expose sensitive data:
43+
44+
This is for demonstration of insecure practice only!
45+
46+
DO NOT use this code in production or on any network!
47+
48+
```python
49+
50+
from http.server import HTTPServer, SimpleHTTPRequestHandler
51+
import os
52+
53+
# This serves the current directory over HTTP on all interfaces
54+
# This is extremely dangerous and should never be used
55+
server_address = ('0.0.0.0', 8000)
56+
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
57+
58+
# This will serve all files in the current directory
59+
# Potentially exposing source code, configuration files, and secrets
60+
print("Serving files from:", os.getcwd())
61+
print("WARNING: This server is insecure and should only be used for local testing")
62+
httpd.serve_forever()
63+
```
64+
65+
66+
## Discussion
67+
68+
A valid question is: Why Is This Module Still in the Standard Library?
69+
70+
The `http.server` module remains in the Python standard library due to its utility for:
71+
- Quick local testing of static content
72+
- Educational purposes to demonstrate HTTP fundamentals
73+
- Internal tooling in isolated development environments
74+
75+
However, its inclusion should **never** be interpreted as an endorsement for production use. The module's documentation explicitly warns against production deployment.
76+
77+
A common misconception is that development environments are inherently secure because they are "not production." This thinking is dangerous because:
78+
79+
1. Development environments often contain production-like data or connection strings
80+
2. Many security breaches originate from compromised development systems
81+
3. The boundary between development and production can become blurred in CI/CD pipelines
82+
4. Internal networks are frequently targeted by attackers seeking footholds
83+
84+
Treat development environments with the same security rigour as production systems. If a server is accessible on any network interface other than `localhost`, it should be considered at risk.
85+
86+
87+
## More Information
88+
89+
- [Python `http.server` Module Documentation](https://docs.python.org/3/library/http.server.html#module-http.server)
90+
- [Python `http.server` Security Considerations](https://docs.python.org/3/library/http.server.html#http-server-security)
91+
92+

‎constructs/logging.md‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Logging Configuration
2+
3+
4+
## Security Concerns
5+
6+
Using Python's `logging` module can introduce security risks if sensitive information (such as credentials, personal data, or internal system details) is logged without proper sanitization or access controls. Attackers who gain access to log files or outputs can use this information for reconnaissance, privilege escalation, or data exfiltration attacks.
7+
8+
The `logging.config` module provides convenient ways to configure logging from files or dictionaries. For flexibility, it supports converting configuration text into Python objects — including importing callables from user-defined modules and invoking them with parameters supplied in the configuration.
9+
10+
While powerful, these mechanisms can be abused to execute arbitrary code if the configuration comes from an untrusted source.
11+
12+
:::{important}
13+
Creating pipes and importing `dicts` for configuration can become a security nightmare.
14+
:::
15+
16+
Additionally, portions of the configuration (especially when using `listen()`) are passed through `eval()`. Although the socket is bound to localhost by default, on multi-user systems this can allow a malicious local user to inject and execute arbitrary code in the context of the logging process by connecting to the listening socket and sending a malicious configuration.
17+
18+
## Preventive Measures
19+
20+
- **Never load configuration from untrusted sources**. Thoroughly review and validate any logging configuration files or dictionaries before use.
21+
- Use the `verify` argument with `logging.config.listen()` to ensure only recognised/signed configurations are applied.
22+
- Prefer programmatic configuration (via `dictConfig` with hardcoded, trusted dictionaries) over file-based configuration in production environments.
23+
- Sanitize all data before logging — never log raw user input, secrets, or sensitive payloads.
24+
- Run logging processes with the principle of least privilege.
25+
- Consider using secure alternatives or wrappers that enforce strict validation on configuration inputs.
26+
- Avoid exposing the `listen()` socket in environments where multiple untrusted users share the same machine.
27+
28+
## Example
29+
30+
**Unsafe configuration loading:**
31+
32+
Dangerous — loading from untrusted source:
33+
34+
```python
35+
import logging.config
36+
37+
38+
logging.config.fileConfig('/path/to/untrusted/logging.conf')
39+
40+
# Or using listen without verification
41+
logging.config.listen()
42+
```
43+
44+
**Safer approach:**
45+
46+
Trusted, hardcoded configuration:
47+
48+
```python
49+
import logging.config
50+
51+
52+
LOGGING_CONFIG = {
53+
'version': 1,
54+
'disable_existing_loggers': False,
55+
'formatters': {
56+
'standard': {
57+
'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
58+
}
59+
},
60+
'handlers': {
61+
'default': {
62+
'level': 'INFO',
63+
'formatter': 'standard',
64+
'class': 'logging.StreamHandler'
65+
}
66+
},
67+
'root': {
68+
'handlers': ['default'],
69+
'level': 'INFO'
70+
}
71+
}
72+
73+
logging.config.dictConfig(LOGGING_CONFIG)
74+
```
75+
76+
**Using listen safely:**
77+
78+
Only accept verified configurations:
79+
80+
```python
81+
82+
logging.config.listen(verify=some_verification_function)
83+
```
84+
85+
## Discussion
86+
87+
The convenience offered by Python's logging configuration system is a double-edged sword. The ability to dynamically import and instantiate objects makes the system highly extensible, but it also opens the door to code execution vulnerabilities similar to deserialization attacks in other languages.
88+
89+
The `eval()` usage and socket-based configuration listening are particularly concerning in shared hosting or multi-user scenarios. Even in single-user environments, a compromised configuration file (e.g., via supply-chain attack) could lead to remote code execution.
90+
91+
Modern security best practice favours explicit, code-reviewed configuration over dynamic loading wherever possible.
92+
93+
## More Information
94+
95+
- [Security considerations — Python Logging Configuration (PSF)](https://docs.python.org/3/library/logging.config.html#security-considerations)

‎constructs/subprocess.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ Wherever possible, you should use a native Python API instead of invoking shell
128128

129129
`Popen` is the low-level foundation and used for some advanced cases, but use `run()` for most cases if you need this kind of functionality.
130130

131-
Using `Popen` itself is not directly a [vulnerability](vulnerability), but too often crucial checks are missing so within code `Popen` is often a weakness that should be reviewed in depth.
131+
Using `Popen` itself is not directly a [vulnerability](#vulnerability), but too often crucial checks are missing so within code `Popen` is often a weakness that should be reviewed in depth.
132132

133133
## More information
134134

‎toc.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,9 @@ project:
4848
- file: constructs/mktemp.md
4949
- file: constructs/subprocess.md
5050
- file: constructs/systemcalls.md
51+
- file: constructs/logging.md
52+
- file: constructs/base64.md
53+
- file: constructs/httpserver.md
5154

5255

5356
- file: guidelines/guidelines_intro.md

0 commit comments

Comments
 (0)