Docsity

WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python, Exams of Computer Security

Toggle sidebar
bg1
WGU D385 Software Security and Testing
Static Code Analysis & Flake8 Practice
Lab Python Security, Logging, Testing &
1. A flake8 run with the bandit plugin reports B301: pickle.loads() on untrusted data.
Which remediation best preserves functionality while eliminating the vulnerability?
A. Replace pickle with json and validate the schema with pydantic before use.
B. Wrap pickle.loads in a try/except and log the exception.
C. Use pickle.Unpickler with find_class restricted to a whitelist of safe classes.
D. Enable Python's -X dev mode to catch deserialization errors.
Answer: C. Use pickle.Unpickler with find_class restricted to a whitelist of safe
classes.
Rationale: Restricting find_class to a whitelist maintains pickle compatibility while
blocking arbitrary code execution. JSON (A) may not support all types; try/except (B) does
not prevent exploitation; -X dev (D) only adds runtime checks, not security.
2. In a CI pipeline, flake8 reports E501 line too long on a line containing a hardcoded
AWS secret. Which action best aligns with secure remediation and linting policy?
A. Add # noqa: E501 to suppress the warning and commit.
B. Refactor the line and move the secret to an environment variable, then rotate the
exposed key.
C. Increase max-line-length in setup.cfg to 120.
D. Use a pre-commit hook to auto-format with black.
Answer: B. Refactor the line and move the secret to an environment variable, then
rotate the exposed key.
Rationale: The secret must be removed from source and rotated; refactoring addresses the
lint issue. Suppression (A) or config change (C) hides the problem; auto-formatting (D)
does not remove the secret.
Page 1 of 28
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download WGU D385 Software Security and Testing Static Code Analysis & Flake8 Practice Lab Python and more Exams Computer Security in PDF only on Docsity!

WGU D385 Software Security and Testing

Static Code Analysis & Flake8 Practice

Lab Python Security, Logging, Testing &

1. A flake8 run with the bandit plugin reports B301: pickle.loads() on untrusted data. Which remediation best preserves functionality while eliminating the vulnerability?

A. Replace pickle with json and validate the schema with pydantic before use. B. Wrap pickle.loads in a try/except and log the exception. C. Use pickle.Unpickler with find_class restricted to a whitelist of safe classes. D. Enable Python's -X dev mode to catch deserialization errors.

Answer: C. Use pickle.Unpickler with find_class restricted to a whitelist of safe classes.

Rationale: Restricting find_class to a whitelist maintains pickle compatibility while blocking arbitrary code execution. JSON (A) may not support all types; try/except (B) does not prevent exploitation; -X dev (D) only adds runtime checks, not security.

2. In a CI pipeline, flake8 reports E501 line too long on a line containing a hardcoded AWS secret. Which action best aligns with secure remediation and linting policy?

A. Add # noqa: E501 to suppress the warning and commit. B. Refactor the line and move the secret to an environment variable, then rotate the exposed key. C. Increase max-line-length in setup.cfg to 120. D. Use a pre-commit hook to auto-format with black.

Answer: B. Refactor the line and move the secret to an environment variable, then rotate the exposed key.

Rationale: The secret must be removed from source and rotated; refactoring addresses the lint issue. Suppression (A) or config change (C) hides the problem; auto-formatting (D) does not remove the secret.

3. Which flake8 plugin combination best detects both style and security issues in Python code?

A. flake8-docstrings and flake8-import-order B. flake8-bugbear and flake8-comprehensions C. flake8-bandit and flake8-bugbear D. flake8-annotations and flake8-quotes

Answer: C. flake8-bandit and flake8-bugbear

Rationale: flake8-bandit integrates Bandit security checks; flake8-bugbear catches likely bugs. The others focus on style, documentation, or import ordering, not security.

4. A developer uses logging.info(f"User {user} logged in with password {password}"). What is the most critical security flaw?

A. Using f-strings instead of %-formatting causes performance overhead. B. Logging at INFO level may be disabled in production. C. Sensitive credentials are written to logs, risking exposure. D. The log message lacks a timestamp and correlation ID.

Answer: C. Sensitive credentials are written to logs, risking exposure.

Rationale: Logging passwords is a severe data leakage vulnerability. Performance (A) and log level (B) are secondary; missing metadata (D) is an audit concern, not the primary flaw.

7. Which of the following is a secure way to handle password hashing in Python?

A. hashlib.md5(password.encode()).hexdigest() B. hashlib.sha256(password.encode()).hexdigest() C. bcrypt.hashpw(password.encode(), bcrypt.gensalt()) D. base64.b64encode(password.encode())

Answer: C. bcrypt.hashpw(password.encode(), bcrypt.gensalt())

Rationale: bcrypt is designed for password hashing with salt and work factor. MD5 (A) and SHA-256 (B) are fast and unsuitable; base64 (D) is encoding, not hashing.

8. In a CI/CD pipeline, which strategy best balances security and developer productivity when integrating static analysis?

A. Block all merges on any flake8 warning. B. Run flake8 only on changed files and fail on high-severity security issues. C. Run flake8 nightly and email reports. D. Disable flake8 and rely on code reviews.

Answer: B. Run flake8 only on changed files and fail on high-severity security issues.

Rationale: Incremental scanning with severity-based gating reduces noise while catching critical issues. Blocking all warnings (A) causes friction; nightly (C) delays feedback; disabling (D) removes automation.

9. Which Python logging practice best prevents log injection attacks?

A. Using f-strings to embed user input directly. B. Sanitizing user input before logging and using structured logging. C. Logging only at ERROR level. D. Storing logs in a database instead of files.

Answer: B. Sanitizing user input before logging and using structured logging.

Rationale: Sanitization and structured logging prevent newline injection. F-strings (A) allow injection; log level (C) doesn't sanitize; database storage (D) doesn't prevent injection.

10. A flake8-bandit report flags B303: use of insecure MD5. Which remediation is most appropriate?

A. Replace MD5 with SHA-1. B. Replace MD5 with SHA-256 for non-security checksums. C. Replace MD5 with SHA-256 or better for security-sensitive hashing. D. Add # nosec to suppress the warning.

Answer: C. Replace MD5 with SHA-256 or better for security-sensitive hashing.

Rationale: For security, use SHA-256 or stronger. SHA-1 (A) is also broken; SHA-256 for non-security (B) is acceptable but not for security; suppression (D) ignores the risk.

13. A test asserts that a function raises ValueError for negative input, but the function currently calls sys.exit(1). Which pytest construct most precisely verifies the intended contract without allowing the process to terminate the test runner?

A. with pytest.raises(SystemExit): fn(-1) B. with pytest.raises(ValueError): fn(-1) C. assert fn(-1) is None D. monkeypatch.setattr(sys, 'exit', lambda code: None) then call fn(-1)

Answer: B. with pytest.raises(ValueError): fn(-1)

Rationale: The intended contract is ValueError, so pytest.raises(ValueError) encodes that expectation and will fail until the code is remediated. pytest.raises(SystemExit) merely asserts the buggy behavior, and monkeypatching sys.exit hides the defect rather than testing the contract.

14. Bandit reports B608 (possible SQL injection) for a query built with an f-string, but the same query built with a parameterized placeholder is not flagged. Which remediation most directly eliminates the vulnerability class rather than suppressing the finding?

A. Add '# nosec' to the flagged line. B. Replace the f-string with cursor.execute('... WHERE id = %s', (user_id,)). C. Wrap the user_id in str() before interpolation. D. Configure Bandit to skip the B608 test.

Answer: B. Replace the f-string with cursor.execute('... WHERE id = %s', (user_id,)).

Rationale: Parameterized execution separates code from data, structurally preventing injection, which is the true remediation. Suppression via nosec or config, and string coercion, leave the injection vector intact.

15. A project's CI runs flake8 --max-line-length=79 and passes, yet black --check fails. Which change most likely reconciles both tools without weakening linting?

A. Lower flake8's max-line-length to 88. B. Configure both tools to a shared line length and disable flake8's E203/W503 conflicts. C. Disable black's line-length check in CI. D. Add '# noqa' to every line black reformats.

Answer: B. Configure both tools to a shared line length and disable flake8's E203/W503 conflicts.

Rationale: Black and flake8 disagree on slice and whitespace conventions, so aligning line length and ignoring E203/W503 resolves the conflict without suppressing real issues. Lowering the limit or disabling black's check does not reconcile the tools and weakens enforcement.

16. A security review finds that a Flask app logs full request bodies, including passwords. Which logging change best follows current OWASP guidance while preserving useful diagnostics?

A. Log the body only when the log level is DEBUG. B. Redact or omit sensitive fields before logging, and log structured, non-sensitive metadata. C. Encrypt the log file at rest and continue logging the body. D. Log only the HTTP status code and drop all request context.

Answer: B. Redact or omit sensitive fields before logging, and log structured, non-sensitive metadata.

Rationale: OWASP recommends minimizing and redacting sensitive data at the point of logging; structured metadata preserves diagnostics without exposing secrets. Logging at DEBUG still persists secrets, encryption at rest does not prevent exposure to log readers, and dropping all context harms operability.

19. A CI pipeline runs pip-audit and reports a vulnerable transitive dependency. The team cannot upgrade it directly. Which remediation best reduces risk while preserving functionality?

A. Pin the vulnerable version and add it to an allowlist. B. Add a constraints file overriding the transitive version to a patched release and re-run tests. C. Vendor the vulnerable package source into the repo unchanged. D. Disable pip-audit for transitive dependencies.

Answer: B. Add a constraints file overriding the transitive version to a patched release and re-run tests.

Rationale: A constraints file forces a patched transitive version without altering direct dependencies, and re-running tests verifies compatibility. Pinning or allowlisting the vulnerable version, vendoring unchanged code, or disabling the audit all preserve the vulnerability.

20. A code review flags subprocess.Popen(cmd, shell=True) where cmd includes user input. Which remediation most completely removes the command injection risk?

A. Escape shell metacharacters in the user input before concatenation. B. Use subprocess.Popen with a list of arguments and shell=False. C. Wrap the command in shlex.quote and keep shell=True. D. Run the command as a non-root user with shell=True.

Answer: B. Use subprocess.Popen with a list of arguments and shell=False.

Rationale: Passing an argument list with shell=False avoids shell interpretation entirely, eliminating injection. Escaping or quoting is error-prone and incomplete, and dropping privileges reduces impact but not the vulnerability itself.

21. A developer runs flake8 --select=E722 on a codebase and receives no warnings, yet a subsequent Bandit scan reports a high-severity finding in the same file. Which explanation best accounts for this discrepancy?

A. Flake8's E722 only fires when a bare except is followed by a raise statement, whereas Bandit flags all bare excepts. B. Bandit detects bare except: clauses as a security weakness (B110/B112 patterns), while Flake8's E722 requires a specific pycodestyle configuration and may be disabled by default in some setups or suppressed via noqa. C. Bandit only inspects compiled bytecode, so it detects exceptions that Flake8's AST-based parser cannot see. D. E722 applies exclusively to Python 2 syntax, so Python 3 code will never trigger it regardless of configuration.

Answer: B. Bandit detects bare except: clauses as a security weakness (B110/B patterns), while Flake8's E722 requires a specific pycodestyle configuration and may be disabled by default in some setups or suppressed via noqa.

Rationale: Bandit's B110/B112 checks flag bare or overly broad exception handling as a security-relevant weakness, whereas pycodestyle's E722 is a style rule that can be disabled, overridden, or suppressed via # noqa, so a clean Flake8 run does not guarantee Bandit silence. Options A, C, and D misstate the semantics of each tool: E722 does not require a raise, both tools parse source/AST rather than bytecode, and E722 applies to Python 3 as well.

23. A team writes a pytest fixture that patches requests.get with unittest.mock.patch to test a function that retries on HTTP 500. Which design most rigorously verifies the retry behavior without coupling the test to implementation details?

A. Assert that requests.get was called exactly three times using assert_called_with on the final call. B. Configure the mock's side_effect to return a 500 response twice and a 200 response once, then assert the function returns the parsed payload and that requests.get.call_count == 3. C. Patch time.sleep to a no-op and assert the function completes within a fixed wall-clock budget. D. Use pytest.mark.integration and hit a real endpoint that returns 500 to observe retries.

Answer: B. Configure the mock's side_effect to return a 500 response twice and a 200 response once, then assert the function returns the parsed payload and that requests.get.call_count == 3.

Rationale: Driving the mock with a side_effect sequence exercises the retry logic deterministically and asserts both the observable outcome (parsed payload) and the interaction (call count), which is the strongest contract-level check. Option A checks only the last call, C tests timing rather than retry semantics, and D introduces nondeterminism and external dependency.

24. A logging configuration sets logging.basicConfig(level=logging.INFO) and a module calls logging.getLogger(__name__).debug("token=%s", token). What is the most significant security concern, and what is the correct remediation?

A. The debug call is silently dropped at INFO level, so no risk exists; no remediation needed. B. The token is formatted eagerly and may leak if the root level is later raised to DEBUG; the fix is to never log secrets and to use structured redaction or omit the token entirely. C. Using %s formatting is unsafe; the fix is to use f-strings so the token is evaluated lazily. D. The __name__ logger bypasses the root handler, so the message will always be emitted regardless of level.

Answer: B. The token is formatted eagerly and may leak if the root level is later raised to DEBUG; the fix is to never log secrets and to use structured redaction or omit the token entirely.

Rationale: The lazy %s argument is only formatted when the record is emitted, but if any environment raises the effective level to DEBUG the secret is written to logs; secrets should never be passed to logging at all, and redaction or omission is the correct fix. Option A ignores configuration drift, C inverts the laziness tradeoff (f-strings evaluate eagerly), and D misstates logger propagation.

27. A test suite achieves 95% line coverage but misses a branch where an authorization check returns False. Which testing technique most directly exposes this gap?

A. Increasing the number of integration tests against a live database. B. Measuring branch/decision coverage and adding a test that forces the authorization check to evaluate False. C. Adding property-based tests that only generate valid inputs. D. Running mutation testing on unrelated modules to raise the overall score.

Answer: B. Measuring branch/decision coverage and adding a test that forces the authorization check to evaluate False.

Rationale: Line coverage can be satisfied while a branch outcome is never exercised; branch/decision coverage explicitly requires each outcome, and adding a False-path test closes the gap. Options A, C, and D do not guarantee the specific untested branch is executed.

28. A Python service loads YAML configuration with yaml.load(stream) from a user-uploadable file. Which change most effectively prevents arbitrary code execution?

A. Wrap the load in try/except to catch parse errors. B. Replace yaml.load with yaml.safe_load, which restricts construction to basic Python types. C. Validate the file extension is .yaml before loading. D. Run the loader in a thread pool to isolate failures.

Answer: B. Replace yaml.load with yaml.safe_load, which restricts construction to basic Python types.

Rationale: yaml.load with the default loader can instantiate arbitrary Python objects via tags like !!python/object, enabling code execution; yaml.safe_load disallows those constructors. Extension checks (C) are trivially bypassed, try/except (A) does not prevent execution, and thread isolation (D) does not sandbox code.

29. An audit requires that a Python package's dependencies be checked for known CVEs as part of CI. Which tool and workflow best satisfies this requirement?

A. Run flake8 with the flake8-bandit plugin to detect vulnerable dependencies. B. Run pip-audit (or safety) against the locked requirements and fail the build on any reported CVE. C. Run mypy --strict to catch type errors that indicate vulnerabilities. D. Run pytest --cov and require 100% coverage before merging.

Answer: B. Run pip-audit (or safety) against the locked requirements and fail the build on any reported CVE.

Rationale: SCA tools like pip-audit and safety query vulnerability databases against the resolved dependency set, which is the correct control for third-party CVEs. Flake8 plugins (A) analyze source style/security patterns, mypy (C) checks types, and coverage (D) measures test execution, none of which detect dependency CVEs.

30. A developer must remediate a Bandit finding for assert used to enforce an authorization invariant in production code. Why is this a genuine security issue, and what is the appropriate fix?

A. Asserts are slow; replace them with logging statements. B. Asserts are stripped when Python runs with -O, so security-critical checks may vanish; replace with explicit if not condition: raise logic. C. Asserts raise the wrong exception type; replace with sys.exit(1). D. Asserts leak stack traces; wrap them in try/except.

Answer: B. Asserts are stripped when Python runs with -O, so security-critical checks may vanish; replace with explicit if not condition: raise logic.

Rationale: Running with optimization (python -O) removes assert statements entirely, so using them for authorization or input validation can silently disable security controls in production; explicit conditionals that raise appropriate exceptions are the correct remediation. The other options misidentify the risk (performance, exception type, or trace leakage) and do not address the stripping behavior.

33. A test suite uses pytest with pytest-mock. The code under test calls requests.get and then logs the response status. Which approach best isolates the test from network while verifying logging behavior?

A. Use monkeypatch.setattr('requests.get', lambda url: Mock(status_code=200)) and assert on the logger's info call via caplog. B. Use mocker.patch('requests.get', return_value=Mock(status_code=200)) and assert caplog.records[0].status_code == 200. C. Use mocker.patch('requests.get', return_value=Mock(status_code=200)) and assert that the logger's info was called with the expected message using caplog.text. D. Use responses library to mock HTTP and assert that logging.getLogger().handlers contains a StreamHandler.

Answer: C. Use mocker.patch('requests.get', return_value=Mock(status_code=200)) and assert that the logger's info was called with the expected message using caplog.text.

Rationale: mocker.patch cleanly replaces requests.get, and caplog.text captures emitted log messages for assertion; this verifies both isolation and logging. Option A uses monkeypatch but asserts on the wrong attribute; B incorrectly inspects record attributes not present; D tests handler configuration, not the log message.

34. Which statement accurately distinguishes static application security testing (SAST) from dynamic application security testing (DAST) in a Python CI pipeline?

A. SAST analyzes running code and detects runtime injection; DAST scans source for insecure patterns like eval. B. SAST examines source or bytecode without execution and can catch insecure deserialization patterns; DAST probes a running application and can detect reflected XSS. C. SAST requires a deployed environment; DAST runs at commit time and is faster for Python. D. SAST and DAST are interchangeable for Python because both rely on Flake8 plugins.

Answer: B. SAST examines source or bytecode without execution and can catch insecure deserialization patterns; DAST probes a running application and can detect reflected XSS.

Rationale: SAST inspects code without executing it (e.g., Bandit finding insecure deserialization), while DAST tests a live application (e.g., reflected XSS). A reverses the

definitions, C misstates deployment needs, and D falsely equates them with Flake8 plugins.