Docsity

WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING STATIC ANALYSIS, PYTH, Exams of Computer Security

Toggle sidebar
bg1
2026
A+ VERIFIED
WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE
SECURITY & TESTING STATIC ANALYSIS, PYTHON LOGGING,
ASSERTIONS, EXCEPTION HANDLING & REMEDIATION PRACTICE
EXAM QUESTIONS AND CORRECT ANSWERS PLUS RATIONALES
INSTANT DOWNLOAD 150 Questions
Clinical | Rationale-Driven - Pass Guaranteed - A+ Graded
150
QUESTIONS
1
SECTIONS
150
RATIONALES
WHAT THIS COVERS
01 Software Security and Testing
02 Secure coding in Python (logging
03 Assertions
04 Exception handling)
05 Vulnerability identification
06 Remediation aligned with OWASP Top 10 2021/2025
ABOUT THIS ASSESSMENT
This exam assesses mastery of static analysis, secure coding in Python (logging, assertions, exception handling), vulnerability
identification, and remediation aligned with OWASP Top 10 2021/2025, NIST SSDF SP 800-218, and CWE/SANS Top 25. It
emphasizes applied reasoning for WGU D385 Task 1 performance assessment readiness.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21

Partial preview of the text

Download WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE SECURITY & TESTING STATIC ANALYSIS, PYTH and more Exams Computer Security in PDF only on Docsity!

A+ VERIFIED

WGU D385 TASK 1 COMPLETE PRACTICE GUIDE SOFTWARE

SECURITY & TESTING STATIC ANALYSIS, PYTHON LOGGING,

ASSERTIONS, EXCEPTION HANDLING & REMEDIATION PRACTICE

EXAM QUESTIONS AND CORRECT ANSWERS PLUS RATIONALES

INSTANT DOWNLOAD 150 Questions

Clinical | Rationale-Driven - Pass Guaranteed - A+ Graded

150

QUESTIONS

1

SECTIONS

150

RATIONALES

WHAT THIS COVERS

01 Software Security and Testing

02 Secure coding in Python (logging

03 Assertions

04 Exception handling)

05 Vulnerability identification

06 Remediation aligned with OWASP Top 10 2021/

ABOUT THIS ASSESSMENT This exam assesses mastery of static analysis, secure coding in Python (logging, assertions, exception handling), vulnerability identification, and remediation aligned with OWASP Top 10 2021/2025, NIST SSDF SP 800-218, and CWE/SANS Top 25. It emphasizes applied reasoning for WGU D385 Task 1 performance assessment readiness.

EXAMINATION QUESTIONS

SECTION 1 - Software Security and Testing (Questions 1 to 150)

  1. Which Python logging configuration correctly prevents log injection while preserving structured context in a multi-threaded Flask app?

A. Use a custom Formatter that sanitizes newline characters and a LoggerAdapter to inject request IDs. B. Set logging.basicConfig(format='%(message)s') and rely on the default thread-safe handler. C. Use logging.config.dictConfig with a RotatingFileHandler and disable thread safety for performance. D. Log raw user input directly with logging.info() and rely on downstream SIEM parsing to sanitize. Answer: A [Concept: Software Security and Testing] Rationale: Log injection occurs when untrusted input containing newlines or control characters is written to logs, enabling forged entries. A custom Formatter that escapes or strips newlines and a LoggerAdapter that adds contextual request IDs mitigate this while preserving structure. The other options either fail to sanitize (B, D) or disable thread safety (C), which is unsafe in multi-threaded apps.

  1. A developer runs Python with -O. Which statement about assert-based authorization checks is most accurate?

A. assert statements are stripped, so security checks must not rely on them B. assert statements execute normally but raise AssertionError instead of SystemExit C. assert statements are converted to logging.warning calls D. assert statements are retained only if debug is set to False Answer: A [Concept: Software Security and Testing] Rationale: Under -O (optimized mode), the interpreter removes assert statements entirely, so any security or authorization logic placed in an assert silently disappears in production. The other options misstate interpreter behavior; asserts are not converted to logging, do not change exception type, and debug is False under -O, not the condition for retention.

  1. A unit test mocks datetime.now() to assert an audit log's timestamp format. Which test type is this?

A. Integration test B. Property-based test C. Isolated unit test with a test double D. Mutation test Answer: C [Concept: Software Security and Testing] Rationale: Replacing a dependency with a controlled substitute isolates the unit under test, which is the defining feature of a unit test using a test double. Integration tests exercise real collaborators; property-based tests generate inputs; mutation testing measures test suite strength. This is classic unit-test isolation.

  1. Which logging configuration best prevents CWE-117 log injection in a Python service recording untrusted usernames?

A. Using a custom Formatter that escapes CR/LF and other control characters in the message. B. Setting the logger level to DEBUG to capture all raw input verbatim. C. Writing logs to a file with permissions 0644 for audit accessibility. D. Relying on the default StreamHandler, which sanitizes newlines automatically. Answer: A [Concept: Software Security and Testing] Rationale: CWE-117 occurs when untrusted data with CR/LF forges log entries; explicit sanitization in a Formatter neutralizes it. DEBUG verbosity, permissive file permissions, and the default StreamHandler (which does not sanitize) do not prevent injection.

  1. Which logging configuration flaw most enables log injection (CWE-117) in a Python web service?

A. Using a RotatingFileHandler with size limits B. Writing unsanitized user input containing newlines into log messages C. Setting the root logger level to WARNING D. Emitting logs to stderr instead of a file Answer: B [Concept: Software Security and Testing] Rationale: Unsanitized newline-bearing input lets attackers forge log entries (CWE-117); remediation is to escape CR/LF or use structured logging. Rotation, level settings, and stream choice do not prevent injection.

  1. In Python, what is the primary security consequence of using except Exception: pass around a cryptographic verification routine?

A. It improves performance by skipping expensive exception tracebacks B. It converts verification failures into silent success, enabling authentication bypass C. It automatically logs the exception to the root logger D. It re-raises the exception after the pass statement completes Answer: B [Concept: Software Security and Testing] Rationale: Swallowing all exceptions with pass hides verification failures, so execution continues as if verification succeeded, creating an authentication bypass. It does not improve performance meaningfully, log automatically, or re-raise.

  1. Which OWASP Top 10 (2021) category most directly encompasses insecure deserialization of untrusted Python pickle data?

A. A01: Broken Access Control B. A03: Injection C. A08: Software and Data Integrity Failures D. A10: Server-Side Request Forgery Answer: C [Concept: Software Security and Testing] Rationale: OWASP 2021 moved insecure deserialization under A08 Software and Data Integrity Failures. Injection covers SQL/command injection, A01 covers access control, and A10 covers SSRF; none is the primary mapping for unsafe deserialization.

  1. Which Bandit plugin finding most likely indicates a hardcoded credential vulnerability in a Python module?

A. B105: hardcoded_password_string B. B101: assert_used C. B608: hardcoded_sql_expressions D. B404: import_subprocess Answer: A [Concept: Software Security and Testing] Rationale: Bandit B105 specifically flags hardcoded password strings assigned to variables. B101 flags assert statements, B608 flags SQL string construction, and B404 flags subprocess import; none directly target hardcoded credentials.

  1. Which change most effectively remediates a CWE-798 hardcoded credential discovered in a Python repository?

A. Base64-encoding the credential to obscure it in source. B. Moving the credential to an environment variable injected at runtime by a secrets manager. C. Adding the credential to .gitignore in the next commit. D. Encrypting the credential with a key stored in the same file. Answer: B [Concept: Software Security and Testing] Rationale: CWE-798 remediation requires removing secrets from source and sourcing them from a secrets manager or environment at runtime, plus rotation. Encoding, .gitignore (history remains), and same-file keys are ineffective obfuscations.

  1. A Bandit B101 finding flags assert user.is_admin guarding a privilege check in production. What is the correct remediation?

A. Replace the assertion with an explicit if-not-raise PermissionError check. B. Disable the B101 plugin for the entire module via a # nosec comment. C. Wrap the assertion in a try/except AssertionError to catch bypass attempts. D. Move the assertion into a __debug__-guarded block for optimized builds. Answer: A [Concept: Software Security and Testing] Rationale: Assertions are stripped when Python runs with -O, so security checks must use explicit conditional raises. Suppressing B101, catching AssertionError, or relying on debug all leave the check absent in optimized builds.

  1. A bare 'except:' clause surrounds a file-parsing routine. Which consequence most undermines secure remediation?

A. It re-raises KeyboardInterrupt to the caller B. It catches SystemExit and masks shutdown signals only C. It swallows all exceptions, hiding defects and attack indicators D. It forces the interpreter into debug mode Answer: C [Concept: Software Security and Testing] Rationale: A bare except catches BaseException (including SystemExit/KeyboardInterrupt) and silently masks errors, preventing detection of exploitation attempts. Specific exception handling preserves diagnosability and auditability.

  1. A SAST tool reports a taint path from request.args to os.system. Which remediation most directly breaks the taint?

A. Replace os.system with subprocess.run using a list and shell=False. B. HTML-escape the argument before passing it to os.system. C. Log the argument at DEBUG level before invocation for auditability. D. Wrap the os.system call in try/except to catch CommandError. Answer: A [Concept: Software Security and Testing] Rationale: CWE-78 command injection is remediated by avoiding the shell and passing argv lists to subprocess with shell=False. Escaping for HTML, logging, or catching exceptions does not sanitize shell metacharacters.

  1. Which exception-handling pattern in Python best avoids leaking sensitive information while logging errors securely?

A. Catch broad Exception, log the full stack trace with user data, and re-raise the original exception. B. Catch specific exceptions, log a generic error message with a correlation ID, and raise a custom exception without sensitive details. C. Suppress all exceptions with pass to prevent information disclosure in responses. D. Log the exception message directly to the client response for debugging transparency. Answer: B [Concept: Software Security and Testing] Rationale: Secure exception handling catches only expected exceptions, logs details server-side with a correlation ID for tracing, and returns a generic error to the user to avoid information leakage. Option A leaks sensitive data in logs, C hides errors and harms availability, and D exposes internal details to clients, violating OWASP guidance.

  1. Which testing approach most directly validates that a remediation for a path traversal (CWE-22) defect is effective?

A. Unit test asserting the function returns a string B. Fuzz test with encoded traversal sequences (../, %2e%2e%2f) asserting access denial C. Integration test with valid filenames only D. Static scan confirming the absence of the string '..' Answer: B [Concept: Software Security and Testing] Rationale: Fuzzing with encoded traversal payloads verifies the fix handles canonicalization and bypass attempts, directly testing the vulnerability class. Type-only unit tests, happy-path integration tests, and string-literal scans do not exercise malicious inputs or encoding variants.

  1. In unittest, a test uses assertEqual on floats and intermittently fails across platforms. Which change most improves determinism?

A. Switch to assertTrue(a == b) for speed. B. Use assertAlmostEqual with an explicit places or delta argument. C. Seed random at module import and retry the test. D. Increase the test timeout to reduce flakiness. Answer: B [Concept: Software Security and Testing] Rationale: Floating-point comparisons require tolerance; assertAlmostEqual with explicit places/delta gives deterministic, platform-tolerant comparison. assertTrue(a==b) is stricter and more brittle; seeding random doesn't address FP representation; timeouts don't affect numeric equality.

  1. Which remediation most directly addresses a CWE-798 hardcoded credential finding in a Python repository?

A. Move the credential to a .env file committed to the repository for team access. B. Rotate the credential and retrieve it at runtime from a secrets manager with least privilege. C. Base64-encode the credential in source to obscure it. D. Store the credential in an encrypted config file with the key in the same repo. Answer: B [Concept: Software Security and Testing] Rationale: Rotation plus runtime retrieval from a secrets manager removes the secret from source and limits exposure. A and D still commit secrets or keys, and C is trivially reversible encoding, not protection.

  1. A function uses assert user.is_admin for authorization. Under python -O, what is the security impact?

A. The assertion still runs and blocks non-admins. B. The assertion is stripped, allowing unauthorized access. C. Python raises a SyntaxError at startup. D. The assertion becomes a warning but still enforces. Answer: B [Concept: Software Security and Testing] Rationale: The -O flag removes assert statements, so authorization checks vanish, enabling privilege escalation. Assertions must never enforce security controls; explicit checks are required.

  1. Bandit flags B608 (SQL built via string formatting). Which remediation most directly eliminates the root cause?

A. Escape single quotes on all user input before concatenation B. Use parameterized queries with bound placeholders C. Wrap the query in a try/except and log the SQL error D. Suppress B608 with a # nosec comment after review Answer: B [Concept: Software Security and Testing] Rationale: Parameterized queries separate code from data, eliminating SQL injection at the root (CWE-89). Escaping is error-prone and context-dependent; try/except and nosec suppress symptoms or hide the defect without remediation.

  1. A SAST tool flags a potential SQL injection via string concatenation. Which remediation is most robust per OWASP?

A. Escape single quotes in the input before concatenation. B. Use parameterized queries with bound parameters. C. Apply a blocklist filter for SQL keywords in input. D. Encode the input using HTML entity encoding. Answer: B [Concept: Software Security and Testing] Rationale: Parameterized queries separate code from data, preventing injection regardless of input content, as recommended by OWASP. Escaping quotes and blocklists are bypassable and context-dependent. HTML encoding addresses XSS, not SQL injection.

  1. Which Python logging practice best supports forensic non-repudiation while avoiding sensitive-data exposure?

A. Logging full request bodies at INFO for completeness. B. Logging structured events with hashed identifiers and a trusted timestamp. C. Logging only at ERROR level to minimize volume. D. Logging to stdout without timestamps to preserve privacy. Answer: B [Concept: Software Security and Testing] Rationale: Structured events with hashed identifiers and trusted timestamps provide attributable, tamper-evident audit trails without exposing PII (aligns with OWASP logging guidance). Full bodies leak secrets, ERROR-only logging loses events, and timestamp-free logs undermine forensics.

  1. In a taint analysis of a Flask route, which data flow constitutes a confirmed path traversal vulnerability?

A. request.args value validated against an allowlist, then used in os.path.join B. request.args value passed unsanitized into open(os.path.join(BASE, filename)) C. request.args value hashed with SHA-256 before being used as a cache key D. request.args value length-checked to 32 characters, then used in a query Answer: B [Concept: Software Security and Testing] Rationale: Unsanitized request data flowing into a filesystem path (os.path.join with open) is the classic CWE-22 path traversal taint path. Allowlisting, hashing, and length checks either break the taint or mitigate the risk, so A, C, and D are not confirmed traversal flows.

  1. Which SAST finding most likely indicates a false positive when analyzing Python code that uses subprocess with a list argument?

A. CWE-78 command injection due to shell=True usage. B. CWE-78 command injection flagged despite shell=False and list arguments. C. CWE-89 SQL injection in a parameterized query. D. CWE-79 XSS in a template using autoescaping. Answer: B [Concept: Software Security and Testing] Rationale: When subprocess is called with a list and shell=False, arguments are not interpreted by a shell, so a CWE-78 flag is typically a false positive. shell=True with untrusted input is a true positive, and C and D describe unrelated weaknesses. Recognizing context is essential to triage.

  1. Which practice most effectively integrates static analysis into a secure SDLC under NIST SSDF PW.7?

A. Run SAST only once before release on the final build B. Gate merges on SAST findings with documented triage C. Rely solely on developer manual review without tooling D. Run SAST only on production artifacts post-deployment Answer: B [Concept: Software Security and Testing] Rationale: SSDF PW.7 calls for code review and static analysis integrated into the workflow with triage gates, catching defects early. One-time, post-deployment, or manual-only approaches fail to provide continuous assurance.

  1. In a CI pipeline, which static analysis configuration best reduces false negatives for taint-style vulnerabilities?

A. Run only style linters (flake8) with default rules B. Enable interprocedural taint tracking with source-to-sink rules and fail on high-confidence findings C. Suppress all findings below CVSS 7.0 to reduce noise D. Scan only files changed in the last commit Answer: B [Concept: Software Security and Testing] Rationale: Taint-style flaws (e.g., injection) require tracking untrusted sources to sensitive sinks across function boundaries; interprocedural taint rules catch these that pattern linters miss. Style linters, CVSS-threshold suppression, and diff-only scanning all increase false negatives by ignoring data-flow context or unscanned code.

  1. A code review finds except Exception: pass around a file write. Which remediation best aligns with secure exception handling?

A. Replace with except: pass to catch all errors. B. Log the exception at ERROR level and re-raise or handle it specifically. C. Wrap the block in a retry loop without logging. D. Remove the try/except and let the program crash. Answer: B [Concept: Software Security and Testing] Rationale: Silently swallowing exceptions hides failures and violates secure coding (CWE-390). Logging at ERROR and re-raising or handling specific exceptions preserves visibility. Bare except is worse, retries without logging obscure issues, and crashing is not always acceptable.

  1. Which testing approach best validates that input validation rejects malicious payloads across encodings?

A. Equivalence partitioning on valid inputs only. B. Property-based fuzzing with encoded and boundary payloads asserting rejection. C. A single happy-path integration test. D. Manual code inspection without execution. Answer: B [Concept: Software Security and Testing] Rationale: Property-based fuzzing with encoded/boundary payloads exercises bypass variants and asserts rejection, aligning with OWASP ASVS testing. Valid-only partitioning, happy-path tests, and inspection alone miss encoded bypasses.

  1. A function wraps a database call in try/except Exception and logs only e.args. Which remediation most improves diagnosability without leaking secrets?

A. Log the full traceback with logger.exception and scrub sensitive fields from the message. B. Re-raise the bare exception after logging e.args at DEBUG level. C. Replace the except with a bare except: pass to avoid noise. D. Log str(e) at ERROR and include the raw SQL query string. Answer: A [Concept: Software Security and Testing] Rationale: logger.exception captures the traceback with stack context, essential for diagnosis, while scrubbing secrets prevents sensitive data leakage (CWE-532). Logging only e.args loses the stack; bare except: pass swallows errors; logging raw SQL risks exposing PII/credentials.

  1. Which ordering of exception handlers prevents a security-relevant subclass from being silently shadowed?

A. except Exception first, then except PermissionError B. except PermissionError first, then except OSError, then except Exception C. except BaseException first, then except PermissionError D. except OSError first, then except PermissionError Answer: B [Concept: Software Security and Testing] Rationale: Python matches handlers top-down, so the most specific subclass (PermissionError) must precede its parent OSError and the broad Exception. Placing Exception or BaseException first shadows the specific handler; placing OSError before PermissionError makes the PermissionError branch unreachable.

  1. A SAST tool reports a potential command injection in subprocess.call(user_input, shell=True). Which remediation is most effective?

A. Replacing shell=True with shell=False and passing an argument list. B. Escaping spaces in the user input before concatenation. C. Adding a try/except around the call to catch errors. D. Logging the user input before execution for auditing. Answer: A [Concept: Software Security and Testing] Rationale: Disabling the shell and passing a list of arguments prevents shell metacharacter interpretation, eliminating command injection. Escaping spaces is insufficient, and try/except or logging do not remove the vulnerability.

  1. Which exception-handling pattern best satisfies fail-safe and non-repudiation requirements for a payment authorization module?

A. Catch broad Exception, log the stack trace with card data, and return success to avoid user friction. B. Catch specific exceptions, log a correlation ID without sensitive data, and return a generic failure. C. Let exceptions propagate to the framework default handler and rely on server logs. D. Catch Exception and retry indefinitely until the transaction succeeds. Answer: B [Concept: Software Security and Testing] Rationale: Specific catches with correlation IDs avoid sensitive-data leakage (CWE-209) and fail closed. A leaks card data and fails open, C may expose stack traces and lacks controlled handling, and D risks resource exhaustion and duplicate charges.

  1. Which Python construct most directly mitigates CWE-798 hard-coded credentials in a service configuration?

A. Storing the password as a base64-encoded string in settings.py B. Reading secrets at runtime from an environment variable or secrets manager C. Encrypting the password with a key embedded in the same repository D. Committing the credential to a private repository with restricted access Answer: B [Concept: Software Security and Testing] Rationale: Externalizing secrets to environment variables or a secrets manager removes them from source control, the core CWE- mitigation. Base64 encoding, embedded decryption keys, and private-repo storage all still place recoverable credentials in the codebase, so A, C, and D fail to remediate.

  1. In Python, which approach best prevents sensitive data from appearing in logs when using the logging module?

A. Use a logging.Filter that redacts known sensitive keys from LogRecord attributes. B. Set the logging level to ERROR to avoid logging sensitive data at lower levels. C. Disable logging entirely in production to eliminate risk. D. Rely on developers to manually sanitize each log call. Answer: A [Concept: Software Security and Testing] Rationale: A logging.Filter can inspect and redact sensitive fields (e.g., passwords, tokens) from LogRecord objects before they are emitted, providing centralized protection. Raising the level (B) does not stop sensitive data logged at ERROR, disabling logging (C) harms observability, and manual sanitization (D) is error-prone and inconsistent.

  1. Why must Python assert statements never enforce runtime security checks in production code?

A. Assertions cannot reference variables from enclosing scopes. B. Assertions raise AssertionError, which cannot be caught by handlers. C. Running with -O strips assertions, silently disabling the check. D. Assertions execute only inside unittest test methods. Answer: C [Concept: Software Security and Testing] Rationale: The -O (and PYTHONOPTIMIZE) flag removes assert statements at compile time, so any security control implemented as an assertion vanishes in optimized deployments. Assertions can access enclosing scopes, AssertionError is catchable, and assertions run anywhere-only their optimization removal is the security flaw.

  1. Which Python logging practice most directly mitigates CWE-117 log injection in a web service?

A. Set the logger level to CRITICAL to reduce attack surface. B. Sanitize or encode user-controlled values (e.g., strip CR/LF) before logging. C. Use print() instead of logging to avoid handler issues. D. Store logs in a binary format to prevent newline interpretation. Answer: B [Concept: Software Security and Testing] Rationale: CWE-117 occurs when untrusted input containing CR/LF forges log entries; sanitizing or encoding user data before logging prevents this. Raising level or using print() doesn't neutralize injection; binary storage still decodes to text downstream.

  1. A code review finds 'except Exception: pass'. Which remediation best aligns with NIST SSDF PW.5 and CWE-390?

A. Replace with 'except Exception as e: logging.error(e)' and continue. B. Remove the try block entirely to let errors surface. C. Catch specific exceptions, log sanitized context, and re-raise or fail closed. D. Add 'raise' inside the except block without logging. Answer: C [Concept: Software Security and Testing] Rationale: CWE-390 (detection of error without action) is remediated by specific handling, sanitized logging, and fail-closed behavior. A still swallows errors after logging, B may crash unpredictably, and D loses diagnostic context.

  1. A CI pipeline runs Bandit and Semgrep on every commit; findings are auto-triaged. Which configuration best prevents developer fatigue while preserving security signal?

A. Fail the build on every Low-severity finding and require manual sign-off for all. B. Suppress all findings in a baseline file and review quarterly only. C. Gate the merge on High/Critical findings, record Medium in a tracked backlog, and baseline-reviewed Low noise. D. Run only Bandit with default rules and post results to a chat channel. Answer: C [Concept: Software Security and Testing] Rationale: Risk-based gating (block on High/Critical, track Medium, baseline Low) aligns with NIST SSDF and OWASP guidance to prioritize exploitable issues while avoiding alert fatigue. Failing on all Low findings or suppressing everything destroys signal; chat-only reporting lacks enforcement.

  1. Which exception-handling pattern most reduces the risk of resource leaks during remediation of file-handling code?

A. try/finally with explicit close in finally B. try/except with close inside the except block only C. Relying on garbage collection to close file handles D. Using a bare except to catch close() failures Answer: A [Concept: Software Security and Testing] Rationale: try/finally guarantees close() executes on both success and failure paths; the with statement is equivalent best practice. Closing only in except, relying on GC, or bare except does not ensure deterministic release and can mask errors.

  1. After remediating a CWE-89 finding, which evidence best demonstrates closure per NIST SSDF?

A. A screenshot of the code change in the pull request B. A regression test with injection payloads plus a clean SAST/DAST run on the commit C. An email from the developer confirming the fix D. A reduction in the scanner's overall finding count Answer: B [Concept: Software Security and Testing] Rationale: SSDF (PW.7, RV.1) expects verification through automated testing and re-scanning tied to the commit, proving the vulnerability class is closed. Screenshots, emails, and aggregate count drops lack the specificity and reproducibility required for assurance.

  1. In Python's logging module, which handler configuration most directly mitigates log injection (CWE-117) while preserving audit fidelity?

A. RotatingFileHandler with delay=True and mode='a' B. StreamHandler writing to sys.stderr with default formatter C. SysLogHandler with a custom formatter that escapes CR/LF and uses structured fields D. MemoryHandler with capacity set to a large buffer and flushLevel=ERROR Answer: C [Concept: Software Security and Testing] Rationale: Log injection occurs when untrusted input containing newline or control characters is written verbatim, allowing forged log entries; escaping CR/LF and using structured fields neutralizes this while keeping records auditable. RotatingFileHandler, StreamHandler, and MemoryHandler do not sanitize record content, so they leave the injection vector intact.

  1. Which static analysis finding most likely indicates a CWE-798 hardcoded credential vulnerability in a Python codebase?

A. A variable named password assigned from os.environ.get('DB_PASSWORD'). B. A string literal 'admin123' assigned to a variable named API_KEY used in requests. C. A configuration file loaded via configparser with encrypted values. D. A function parameter named secret passed from a secrets manager at runtime. Answer: B [Concept: Software Security and Testing] Rationale: CWE-798 (Use of Hard-coded Credentials) is flagged when literal credentials like 'admin123' appear in source code. Option A uses environment variables, C uses encrypted config, and D uses runtime secrets management-all secure practices that avoid hardcoding. Only B contains a literal credential embedded in code.

  1. In Python logging, which configuration best prevents log injection while preserving structured context for security events?

A. Use f-strings to embed user input directly in the log message. B. Log raw user input with newline characters intact for forensic accuracy. C. Use a structured formatter (e.g., JSON) and sanitize or escape control characters in untrusted fields. D. Disable logging of user-supplied data entirely to avoid injection. Answer: C [Concept: Software Security and Testing] Rationale: Structured logging with JSON and escaping control characters prevents log injection (CWE-117) while retaining context. F-strings and raw newlines enable injection; disabling logging loses audit data.

  1. A developer replaces a bare except with except (ValueError, KeyError) as e: logger.exception(...). Which outcome is most accurate?

A. The change hides exceptions from monitoring B. Only expected exceptions are caught and full traceback is logged C. logger.exception suppresses the traceback by design D. The change breaks -O optimization semantics Answer: B [Concept: Software Security and Testing] Rationale: Catching specific exceptions avoids masking bugs, and logger.exception logs the traceback at ERROR level. It improves monitoring rather than hiding it; logger.exception includes traceback by design; -O affects asserts, not exception handling. This aligns with CWE-703 remediation and OWASP logging guidance.

  1. A developer must remediate a CWE-798 hardcoded API key found by SAST. Which remediation best aligns with NIST SSDF PW.7?

A. Base64-encode the key literal in source to obscure it B. Move the key to an environment variable or secrets manager and rotate the exposed key C. Add the file to the SAST exclusion list D. Encrypt the key with a symmetric key stored in the same file Answer: B [Concept: Software Security and Testing] Rationale: SSDF PW.7 requires removing secrets from source, storing them in secure configuration or a secrets manager, and rotating exposed credentials. Obfuscation, exclusion, and same-file encryption leave the secret recoverable and the exposure unaddressed.

  1. Which exception-handling pattern best prevents resource leaks while preserving security-relevant error context?

A. try/finally around the resource and log sanitized exception metadata B. Bare except that retries the operation indefinitely C. Catch Exception and return a generic 200 response D. Rely on garbage collection to close file handles Answer: A [Concept: Software Security and Testing] Rationale: try/finally guarantees release of resources (e.g., files, sockets) while logging sanitized metadata preserves diagnostics without leaking secrets (CWE-209). Bare retries enable DoS, generic 200s hide failures, and GC nondeterminism risks leaks.

  1. Which ordering of exception handlers preserves the most specific subclass semantics in Python 3?

A. except ValueError, then except Exception - specific before general. B. except Exception, then except ValueError - general before specific. C. except BaseException, then except ValueError - base before subclass. D. except ValueError, then except LookupError - sibling classes either order. Answer: A [Concept: Software Security and Testing] Rationale: Python matches handlers top-down, so subclasses must precede superclasses; placing Exception first shadows ValueError. BaseException-first is worse, and sibling ordering is irrelevant but does not address specificity.

  1. Which static analysis finding most directly corresponds to CWE-89 (SQL Injection) in Python code using string concatenation for queries?

A. Use of the eval() function on user-supplied data. B. Concatenation of user input into a string passed to cursor.execute(). C. Hard-coded database credentials in source code. D. Missing timeout on network socket connections. Answer: B [Concept: Software Security and Testing] Rationale: CWE-89 arises when untrusted input is concatenated into SQL statements; static analyzers flag cursor.execute() calls with concatenated strings. eval() maps to CWE-95, hard-coded credentials to CWE-798, and socket timeouts to CWE-400.

  1. After remediation of a deserialization flaw, which verification most convincingly demonstrates the fix to an assessor?

A. A code comment stating the vulnerability was fixed by the developer B. A regression test using a malicious pickle payload that now safely raises an error C. A passing unit test that only serializes trusted internal objects D. A manual code walkthrough confirming the pickle.loads call remains present Answer: B [Concept: Software Security and Testing] Rationale: A regression test that replays the original exploit payload and confirms safe rejection (e.g., restricted unpickler raising) provides objective evidence the vulnerability is closed. Comments, tests only of trusted paths, and confirming the risky call still exists do not demonstrate remediation, so A, C, and D are inadequate.

  1. Which exception-handling pattern best supports secure remediation when calling an external payment API?

A. Catch Exception, log the full request including card number, and retry indefinitely. B. Catch specific exceptions, log sanitized context, and fail closed with a user-safe message. C. Suppress all exceptions to avoid leaking API details to the caller. D. Reraise the raw exception to the UI to preserve diagnostic fidelity. Answer: B [Concept: Software Security and Testing] Rationale: Catching specific exceptions, logging sanitized context, and failing closed prevents sensitive data exposure (CWE-209) and maintains availability. Logging card numbers violates privacy, indefinite retries enable DoS, suppressing exceptions hides failures, and raw exceptions to the UI leak internals.

  1. A SAST tool flags a tainted parameter flowing into subprocess.run with shell=True. Which remediation best satisfies SSDF PW.7?

A. Escape the parameter with shlex.quote() and keep shell=True. B. Replace with subprocess.run(args_list, shell=False) and validate against an allowlist. C. Suppress the finding with a # nosec comment and document the risk. D. Log the parameter at DEBUG level and proceed with shell=True. Answer: B [Concept: Software Security and Testing] Rationale: SSDF PW.7 requires eliminating injection weaknesses; passing an argument list with shell=False removes shell metacharacter interpretation, and allowlisting adds defense in depth. shlex.quote reduces but does not eliminate risk and is error-prone; suppression does not remediate; logging does not mitigate injection.

  1. A unit test must verify that a function raises ValueError on bad input. Which assertion is most appropriate and robust?

A. self.assertTrue(True) after calling the function inside a try/except B. with self.assertRaises(ValueError): parse_input('bad') C. self.assertEqual(parse_input('bad'), None) D. self.assertIsNone(parse_input('bad')) Answer: B [Concept: Software Security and Testing] Rationale: assertRaises(ValueError) context manager precisely asserts the expected exception type and fails if none is raised, giving robust, readable tests. The try/except with assertTrue(True) can pass even if no exception occurs, and C and D assert return values rather than the required exception behavior.

  1. Which combination of static analysis and manual review best detects a second-order SQL injection in Python?

A. Taint analysis tracking user input stored in the database and later used in queries. B. Regex scanning for 'SELECT' keywords in source files. C. Dependency scanning for outdated database drivers. D. Fuzzing HTTP endpoints with random strings only. Answer: A [Concept: Software Security and Testing] Rationale: Second-order injection requires tracking stored tainted data to later sinks, which taint analysis plus review provides. B is superficial, C addresses dependencies, and D may miss stored payloads executed later.

  1. Which SAST finding most likely reflects a true positive rather than a false positive in Python code?

A. Hard-coded secret flagged in a test fixture file excluded from deployment artifacts B. SQL string concatenation flagged where parameterized queries are already used upstream C. Use of eval() on user-supplied input in a request handler D. Weak hash flagged in a non-security checksum utility for cache keys Answer: C [Concept: Software Security and Testing] Rationale: eval() on untrusted request input is a genuine code-injection sink (CWE-95) and is exploitable regardless of context, making it a true positive. Options A and D involve non-security contexts or excluded artifacts (common false-positive classes), and B is a false positive because parameterization already mitigates injection.

  1. In Python, which statement about assert is most accurate for security-sensitive input validation in production code?

A. assert statements are removed when Python runs with -O, so they must not be used for security checks. B. assert statements raise AssertionError and are always executed regardless of optimization flags. C. assert can be used for security validation because it raises an exception that halts execution. D. assert is equivalent to if not condition: raise ValueError and is safe for input validation. Answer: A [Concept: Software Security and Testing] Rationale: Python's assert statements are stripped when the interpreter runs with the -O (optimize) flag, so any security check relying on assert can be bypassed. They should be used only for debugging and internal invariants, not for validating untrusted input. Options B and C incorrectly claim assert is always executed or safe for security, and D wrongly equates assert with an explicit raise.

  1. A static analyzer flags a tainted path from request.args to os.system. Which remediation most directly satisfies SSDF PW.5.1?

A. Replace os.system with subprocess.run using shell=False and an argument list. B. Wrap the os.system call in a try/except and log the exception. C. Add an assert validating the input is non-empty before the call. D. Increase logging verbosity to capture the constructed command string. Answer: A [Concept: Software Security and Testing] Rationale: SSDF PW.5.1 requires eliminating injection paths; passing an argument list with shell=False avoids shell interpretation, removing the OS command injection vector (CWE-78). Try/except, asserts, and logging are detective controls that do not remediate the vulnerability.

  1. A Flask app logs full request bodies including passwords at DEBUG. Which remediation best satisfies ASVS logging requirements?

A. Keep DEBUG logging but rotate logs more frequently B. Redact sensitive fields and enforce INFO-level logging in production C. Encrypt the log files at rest only D. Move logging to stdout and rely on container isolation Answer: B [Concept: Software Security and Testing] Rationale: ASVS v4/v5 requires that sensitive data (passwords, tokens) never be logged; redaction plus production-level gating directly addresses CWE-532. Rotation, encryption at rest, or stdout redirection do not prevent the sensitive data from being written, so they fail the requirement.

  1. A team adds '# nosec' to silence Bandit B602 (subprocess with shell=True). Why is this remediation inadequate?

A. nosec comments are ignored by Bandit by default B. It suppresses detection without removing the injection risk C. Bandit requires nosec to be placed on the import line D. shell=True is safe when the command is a constant string Answer: B [Concept: Software Security and Testing] Rationale: Suppression hides the finding while shell=True still enables command injection (CWE-78); the fix is to avoid the shell and pass argument lists. nosec is honored by Bandit, and constant strings do not make shell=True safe.

  1. Which static analysis finding most plausibly indicates a hard-coded cryptographic key vulnerability (CWE-798)?

A. A variable named API_KEY assigned from os.environ. B. A string literal of high entropy assigned to SECRET_KEY in source. C. A call to secrets.token_bytes(32) at startup. D. A function parameter named password with type hint str. Answer: B [Concept: Software Security and Testing] Rationale: CWE-798 is indicated by embedded high-entropy literals assigned to secret-named variables in source. Reading from environment, generating secrets at runtime, and typed parameters do not embed credentials in code.

  1. A logger call inside an except block includes the raw exception message and stack trace at INFO. What is the primary security concern?

A. INFO level is too verbose and will exhaust disk space B. Stack traces cannot be serialized to JSON handlers C. Sensitive internal details may leak to untrusted log sinks D. Python forbids logging within exception handlers Answer: C [Concept: Software Security and Testing] Rationale: Logging exception details can expose file paths, queries, or secrets to attackers with log access (CWE-209/CWE-532). Verbosity and serialization are operational concerns, and logging in handlers is permitted.

  1. A team must fix a deserialization vulnerability in Python using pickle. Which remediation is most secure?

A. Replace pickle with json for untrusted data and validate the schema B. Wrap pickle.loads in a try/except to catch malicious payload errors C. Add an HMAC signature to the pickle payload and verify before loading D. Restrict pickle to a custom Unpickler with an allowlist of classes Answer: A [Concept: Software Security and Testing] Rationale: pickle can execute arbitrary code during deserialization; using a safe format like JSON with schema validation eliminates code execution risk. Exception handling does not prevent execution, HMAC only authenticates if keys are protected and still deserializes untrusted data, and allowlisting classes is complex and error-prone compared to avoiding pickle for untrusted input.

  1. Under python -O, which statement about assert statements is accurate for security-relevant validation?

A. asserts remain active but log a warning B. asserts are compiled out, so validation inside them vanishes C. asserts raise AssertionError only when debug is False D. asserts become no-ops only inside functions, not at module scope Answer: B [Concept: Software Security and Testing] Rationale: The -O flag sets debug to False and strips assert statements entirely at compile time. Never use assert for input validation or authorization checks; raise explicit exceptions instead. Options A, C, and D misstate the optimization semantics.

  1. A password reset token is compared with == in Python. Which remediation best prevents timing attacks?

A. Hash both values with SHA-256 before comparing B. Use hmac.compare_digest for constant-time comparison C. Compare token lengths first, then bytes D. Store tokens in environment variables Answer: B [Concept: Software Security and Testing] Rationale: hmac.compare_digest performs constant-time comparison, eliminating the timing side channel (CWE-208) that == exposes. Hashing then comparing with == still leaks timing, length checks add no protection, and storage location does not affect comparison timing.

  1. A function catches Exception broadly, logs only str(e), and returns None. Which remediation best aligns with secure exception handling?

A. Catch specific exceptions, log with logger.exception() for stack context, and fail closed B. Replace the broad catch with a bare except to capture BaseException subclasses C. Suppress logging entirely to avoid leaking exception details to attackers D. Re-raise the same exception unchanged after logging str(e) at DEBUG level Answer: A [Concept: Software Security and Testing] Rationale: Catching specific exceptions, using logger.exception() to capture traceback context, and failing closed preserves security and diagnosability, consistent with CWE-209/703 guidance. A bare except is worse, suppressing logs destroys auditability, and DEBUG-level str(e) re-raise still loses stack context and may leak or hide failures.

  1. A static analyzer flags 'assert' used for input validation in production. What is the most secure remediation?

A. Replace assert with explicit if-not-raise ValueError checks that run under -O. B. Keep assert but run Python with -O to disable it in production. C. Wrap assert in try/except AssertionError to catch validation failures. D. Convert assert to logging.warning and continue execution. Answer: A [Concept: Software Security and Testing] Rationale: Assertions are removed when Python runs with -O, so they must not enforce security controls; explicit checks with exceptions persist. Option B removes validation entirely, C cannot catch removed asserts, and D fails open.

  1. Given: try: risky() except Exception: pass. Which CWE most directly characterizes this pattern?

A. CWE-798 Hard-coded Credentials B. CWE-703 Improper Check or Handling of Exceptional Conditions C. CWE-22 Path Traversal D. CWE-502 Deserialization of Untrusted Data Answer: B [Concept: Software Security and Testing] Rationale: Swallowing all exceptions with a bare pass hides failures and violates CWE-703 (improper exception handling). CWE-798, CWE-22, and CWE-502 describe unrelated vulnerability classes. Best practice: catch specific exceptions and log or re-raise.