














Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!















This exam assesses mastery of secure software development, software testing
principles, and Python-specific logging and error handling. It emphasizes practical
application of OWASP Top 10 (2021), OWASP ASVS 4.x, NIST SP 800-218 SSDF,
and CWE/SANS Top 25 within the context of a performance assessment task.
A. Use a custom Formatter that escapes newline characters in user input. B. Log user input directly without sanitization for audit fidelity. C. Rely on the logging module's default behavior to handle special characters. D. Encode all log messages in base64 before writing to file.
OWASP recommends sanitizing user input before logging to prevent log injection, such as by escaping newline characters. Direct logging (B) is vulnerable; default behavior (C) does not sanitize; base64 (D) obscures but does not prevent injection.
A. assertRaises B. assertRaisesRegex C. assertException D. assertRaisesException
assertRaises is the standard unittest method to verify an exception is raised. assertRaisesRegex also checks the message but is more specific; the others are not real methods.
A. Log injection attacks become easier. B. Sensitive information may be exposed to unauthorized users. C. Log rotation will fail. D. The logging module will raise a PermissionError.
World-readable log files can leak sensitive data such as passwords or PII. Log injection (A) is unrelated to file permissions; rotation (C) and PermissionError (D) are not directly caused by world-readable permissions.
A. To analyze source code for vulnerabilities without executing it. B. To monitor runtime behavior for anomalies. C. To test the application's response to malformed inputs. D. To verify the application's performance under load.
SAST analyzes source code statically to find security flaws. Runtime monitoring (B) is dynamic analysis; input testing (C) is fuzzing or dynamic testing; performance testing (D) is unrelated.
A. Catch all exceptions and log the full stack trace including sensitive data. B. Catch specific exceptions and log a generic error message without details. C. Use a bare except clause to ensure no exceptions propagate. D. Suppress all exceptions to avoid denial of service.
Catching specific exceptions and logging generic messages prevents information leakage. Logging full traces (A) may expose sensitive data; bare except (C) can hide bugs; suppressing (D) is insecure.
A. PO.1: Define security requirements B. PS.1: Protect all forms of code C. PW.7: Review and/or analyze human-readable code D. PW.8: Test executable code
PW.8 focuses on testing executable code to verify security. PO.1 is about requirements; PS.1 is about protecting code; PW.7 is code review.
A. Assertions are always executed, causing performance overhead. B. Assertions can be disabled with the -O flag, skipping validation. C. Assertions raise AssertionError which is not catchable. D. Assertions cannot check complex conditions.
Python's -O flag disables assertions, so validation would be skipped in optimized mode. Assertions are not for production validation. Performance (A) is not the main issue; AssertionError is catchable (C); assertions can check complex conditions (D).
A. Using a RotatingFileHandler with a maxBytes limit. B. Setting the formatter to include the raw message with no sanitization. C. Applying a custom Filter that escapes CR/LF characters in log records. D. Logging at DEBUG level to avoid writing to persistent storage.
Log injection occurs when untrusted input containing newline or control characters is written to logs, allowing forged entries. A custom logging.Filter that escapes CR/LF (and other control chars) before formatting mitigates CWE-117. RotatingFileHandler and log level do not sanitize content, and raw formatting preserves the injection vector.
A. Suppressing B608 with # nosec and documenting the risk. B. Replacing string-formatted SQL with parameterized queries. C. Increasing Bandit confidence threshold to HIGH. D. Moving the query into a separate module.
B608 flags SQL built via string formatting; the root-cause fix is parameterized queries, which separate code from data and eliminate injection. Suppression, threshold tuning, and relocation only hide the weakness and violate SSDF secure coding practices.
A. Logging full request bodies at INFO to the console. B. Using a Filter to redact PII fields before emission. C. Setting logger.disabled = True in production. D. Routing all logs to a world-readable file.
A logging.Filter can redact or mask PII/secret fields before records reach handlers, preserving audit trails without exposing sensitive data. Logging full bodies leaks data, disabling logging destroys auditability, and world-readable files violate confidentiality.
A. Equivalence partitioning on numeric inputs only. B. Boundary value analysis at the endpoints. C. Condition/decision (MC/DC) test case derivation. D. Random fuzzing until no failures occur.
Modified condition/decision coverage ensures each atomic condition independently affects the decision outcome, which is necessary to exercise all branches of compound guards. Equivalence partitioning and boundary analysis target input domains, not boolean structure; random fuzzing gives no coverage guarantee.
A. Increased log volume may fill disk, causing denial of service. B. DEBUG records may expose secrets and internal state to attackers. C. basicConfig disables exception tracebacks entirely. D. DEBUG level bypasses all formatters and filters.
DEBUG-level logging frequently emits sensitive internals (tokens, PII, stack details) that aid attackers and violate least disclosure. Disk exhaustion is a secondary availability risk, not the primary security concern; basicConfig does not disable tracebacks or bypass filters.
A. Testing only the happy path with valid tokens. B. Testing token entropy, expiry, single-use, and rate limiting. C. Verifying the UI displays a success message. D. Checking that the function returns HTTP 200.
ASVS requires verification of reset token strength, expiration, one-time use, and anti-automation controls, which are the security-critical properties. Happy-path, UI-message, and status-code checks do not verify the security controls and would miss exploitable weaknesses.
A. Using a custom Formatter that escapes newline and control characters in the message. B. Setting the logging level to DEBUG to capture all input for later analysis. C. Relying on the default logging module behavior, which automatically sanitizes input. D. Storing logs in a database instead of a file to avoid injection attacks.
Log injection occurs when untrusted input containing newlines or control characters is written to logs, allowing attackers to forge log entries. A custom Formatter that escapes such characters mitigates this. The default logging module does not sanitize input, and DEBUG level or database storage does not prevent injection.
A. It may leak sensitive data in failure messages, exposing secrets in logs. B. It performs a shallow comparison that can be bypassed by crafted objects. C. It uses a non-constant-time comparison, enabling timing side-channel attacks. D. It automatically logs both values to the root logger at DEBUG level.
assertEqual includes the compared values in its failure message, which can expose sensitive data such as passwords or tokens in test logs. While non-constant-time comparison is a concern for cryptographic operations, the primary risk in unit tests is data leakage. The other options are incorrect: assertEqual does not use shallow comparison, nor does it automatically log to the root logger.
A. A01:2021 - Broken Access Control B. A02:2021 - Cryptographic Failures C. A09:2021 - Security Logging and Monitoring Failures D. A05:2021 - Security Misconfiguration
A09:2021 specifically addresses security logging and monitoring failures, including insufficient logging of authentication failures. While broken access control and misconfiguration can involve logging, the category explicitly focused on logging is A09. Cryptographic failures are unrelated to logging authentication events.
A. PW.4: Reuse well-secured software B. PS.1: Protect all forms of code from unauthorized access C. RV.1: Identify and confirm vulnerabilities on an ongoing basis D. PW.8: Configure compilation, interpreter, and build tools to improve security
NIST SSDF RV.1 focuses on identifying and confirming vulnerabilities, which includes monitoring and logging security events to detect issues. The other practices relate to reuse, code protection, and build configuration, not directly to logging security events.
A. To ensure data conforms to expected format and reject malicious input. B. To sanitize output before rendering to prevent XSS. C. To encrypt sensitive data before storage. D. To log all user actions for auditing.
Input validation ensures that data meets expected format and constraints, rejecting potentially malicious input. Output sanitization, encryption, and logging are separate concerns. Input validation is a fundamental secure coding practice to prevent injection attacks.
A. Logging to a local file with rotation B. Including timestamps and user identifiers in log records C. Using the DEBUG level for all events D. Storing logs in an easily modifiable database
Non-repudiation requires that actions can be attributed to a specific user and time. Including timestamps and user identifiers in log records supports this. Local files and modifiable databases are susceptible to tampering, and DEBUG level does not ensure non-repudiation.
A. Mocks may not accurately simulate real authentication, leading to false confidence. B. Mocks always introduce SQL injection vulnerabilities. C. Mocks automatically log sensitive credentials. D. Mocks bypass all input validation, causing buffer overflows.
Mocks are simplified replacements that may not replicate the security behavior of real authentication systems, potentially giving a false sense of security. They do not inherently introduce SQL injection, log credentials, or cause buffer overflows (which are not typical in Python).
A. Log injection via forged newlines enabling log forging B. Format-string vulnerability enabling arbitrary memory writes C. SQL injection through the logging handler's database backend D. Denial of service via excessive log rotation
Using %-formatting with untrusted input allows attackers to inject newlines and forged log entries (CWE-117), corrupting audit trails. Python's %-formatting is memory-safe, so format-string memory corruption (B) does not apply; SQL injection (C) and log rotation DoS (D) are unrelated to this logging practice.
A. Assertions are removed when Python runs with -O, disabling validation B. Assertions raise AssertionError, which is not an exception C. Assertions cannot check complex conditions D. Assertions are slower than if-statements and cause DoS
Python's -O (optimize) flag strips assert statements, so validation logic disappears in production, enabling bypass (CWE-617). Assertions do raise AssertionError (B is false); they can check any condition (C false); performance (D) is not the security issue.
A. A03:2021 - Injection B. A01:2021 - Broken Access Control C. A02:2021 - Cryptographic Failures D. A05:2021 - Security Misconfiguration
Injection flaws (including log injection and OS command injection) are mitigated by separating data from code, such as parameterized queries and proper output encoding. Parameterized logging prevents log forging, a form of injection. The other categories address access control, cryptography, and configuration, not injection.
A. Tests should not contain real credentials or sensitive data B. Tests must use mocking for all external dependencies C. Tests should assert only boolean outcomes D. Tests must be run in isolation from the network
Hardcoding real passwords in test code risks credential leakage and violates secure coding practices (CWE-798). Tests should use dummy or generated values. Mocking (B), boolean assertions (C), and network isolation (D) are not the primary issue here.
A. Using a custom Formatter that escapes newlines and control characters B. Setting the logging level to DEBUG C. Logging to a file instead of stdout D. Using the root logger for all messages
Escaping newlines and control characters in log messages prevents attackers from forging log entries (CWE-117). Changing level (B), destination (C), or logger hierarchy (D) does not address injection.
A. To ensure the test can detect the absence of the feature B. To measure code coverage before implementation C. To document the API for future maintainers D. To validate performance requirements early
Writing a failing test first confirms the test is valid and will catch regressions; it ensures the test actually exercises the new functionality. Coverage (B), documentation (C), and performance (D) are secondary benefits, not the primary purpose.
A. Log injection via CRLF characters enabling log forging B. Format string injection through unescaped braces C. Sensitive data exposure if user_supplied contains secrets D. Denial of service from excessive log volume
Unsanitized user input in log messages allows attackers to inject CRLF sequences (e.g., '\n') to forge log entries, a CWE-117 log injection vulnerability. While f-strings are not format-string vulnerable (unlike str.format with user-controlled format), the primary risk here is log injection. Sensitive data exposure is a separate concern (CWE-532) not caused by f-string interpolation per se.
A. Wrap eval in a try/except block to catch syntax errors B. Replace eval with ast.literal_eval for safe literal parsing C. Sanitize input using a regex allowlist before eval D. Log the eval input for auditing before execution
ast.literal_eval safely evaluates only Python literals, eliminating arbitrary code execution (CWE-95). Regex allowlisting (C) is insufficient for complex expressions and error-prone. try/except (A) does not prevent code execution. Logging (D) is detective, not preventive.
A. Set root logger level to DEBUG and log all request bodies B. Use a custom Filter that redacts PII fields before emission C. Disable all logging in production to avoid exposure D. Write logs to a world-readable file for transparency
A logging Filter can redact or mask sensitive fields (e.g., passwords, tokens) before they reach handlers, satisfying CWE-532 mitigation while retaining audit trails. DEBUG logging (A) increases exposure. Disabling logging (C) removes auditability. World-readable logs (D) worsen confidentiality.
A. tearDown is still executed to clean up resources B. The test is skipped and tearDown is not called C. tearDown is not executed, potentially leaking resources D. The exception is suppressed and the test passes
If setUp fails, unittest does not call tearDown, so any resources acquired before the failure point may leak. This is a known unittest behavior; best practice is to use addCleanup or context managers. Options A and B are incorrect; D is false-the test errors.