Docsity

WGU D385 - Software Security and Testing Static Analysis, Python Logging, Assertions, Exce, Exams of Software Engineering

Toggle sidebar
bg1
1
WGU D385 - Software Security and Testing
Static Analysis, Python Logging,
Assertions, Exception Handling &
Remediation
COMPREHENSIVE PRACTICE STUDY GUIDE
Original Practice Questions 1-40 with Answers & Detailed Rationales
UPDATED 2026/2027 | 100% ORIGINAL | STUDY AID
NOT AFFILIATED WITH WGU - FOR LEARNING PURPOSES ONLY
Disclaimer: This guide contains 100% original practice material created for learning the
concepts of software security and testing. It is NOT actual WGU exam content, not
braindump, not affiliated with or endorsed by Western Governors University. Use this as a
study aid to master concepts, not to memorize answers. Passing requires understanding, not
memorization.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download WGU D385 - Software Security and Testing Static Analysis, Python Logging, Assertions, Exce and more Exams Software Engineering in PDF only on Docsity!

WGU D385 - Software Security and Testing

Static Analysis, Python Logging,

Assertions, Exception Handling &

Remediation

COMPREHENSIVE PRACTICE STUDY GUIDE

Original Practice Questions 1-40 with Answers & Detailed Rationales

UPDATED 2026/2027 | 100% ORIGINAL | STUDY AID

NOT AFFILIATED WITH WGU - FOR LEARNING PURPOSES ONLY

Disclaimer: This guide contains 100% original practice material created for learning the concepts of software security and testing. It is NOT actual WGU exam content, not braindump, not affiliated with or endorsed by Western Governors University. Use this as a study aid to master concepts, not to memorize answers. Passing requires understanding, not memorization.

A) Introduction

This practice study guide is designed to help you master WGU D385 Task 1 concepts: Static Analysis, Python Logging, Assertions, Exception Handling, and Remediation. These 40 original questions progress from foundational to advanced, mirroring the skills needed for the performance assessment. How to use: Attempt each question without looking at the answer, read the rationale to understand why the correct answer is right and why distractors are wrong, then revisit core domains. Study tips: 1) Run Bandit and pylint on sample Python code,

  1. Practice configuring logging with handlers and formatters, 3) Write code that distinguishes asserts (for invariants) from exceptions (for recoverable errors), 4) Document remediation steps. This material is original and for learning only.

B) Core Domains Overview

1. Static Analysis (SAST): Analyzes code without execution. Tools: Bandit (security), pylint/flake8 (quality). Concepts: false positives/negatives, taint analysis, SARIF reporting, CI/CD integration. 2. Python Logging: Standard library logging module. Levels: DEBUG(10), INFO(20), WARNING(30), ERROR(40), CRITICAL(50). Secure practices: parameterized logging, PII redaction, preventing log injection/forging, rotating handlers, least-privilege file permissions. 3. Assertions: assert statement for internal invariants, pre/postconditions. Disabled with python -O. Never for user input validation or security checks. Bandit B101 warns on assert_used. 4. Exception Handling: try/except/else/finally, with statement for cleanup, specific exception catching (avoid bare except), exception chaining (raise from), secure error messages (no stack traces to users). 5. Remediation: Triage, prioritize by severity/exploitability, fix code (parameterized queries, secrets module, safe serialization), verify fix, add preventive controls (SAST gates, code review checklists), document risk acceptance.

D) An error that crashes the analyzer

Correct Answer: B) A reported issue that is not actually a vulnerability

Rationale: A false positive is when the tool flags safe code as problematic. A false negative (Option A) is when it misses a real flaw. This distinction is critical for tuning static analysis tools.

Q4. Which of the following is BEST detected by static analysis?

A) Race conditions under heavy load B) Memory leak after 24 hours C) Use of eval() with user-controlled input D) Incorrect API response latency

Correct Answer: C) Use of eval() with user-controlled input

Rationale: eval() with user input is a code pattern visible without execution, ideal for static detection. Race conditions, long-running memory leaks, and latency issues require dynamic/runtime testing.

Q5. What is taint analysis in static security testing?

A) Checking code formatting B) Tracking untrusted user input from source to dangerous sink C) Counting lines of code D) Measuring cyclomatic complexity

Correct Answer: B) Tracking untrusted user input from source to dangerous sink

Rationale: Taint analysis tracks data flow from sources (e.g., input()) to sinks (e.g., os.system, SQL execution). If tainted data reaches a sink without sanitization, it flags an injection risk. Other options are not security taint concepts.

Q6. Which Python logging level should be used for detailed debugging

information useful during development?

A) CRITICAL

B) ERROR

C) DEBUG

D) WARNING

Correct Answer: C) DEBUG

Rationale: DEBUG (level 10) is the lowest level for detailed diagnostic info. WARNING (30) is for unexpected but handled issues, ERROR (40) for failures, CRITICAL (50) for system-level failures.

Q7. What is the correct way to avoid logging sensitive data like passwords in

Python?

A) Use logging.info(password) B) Use print() instead of logging C) Filter or mask sensitive data before logging, and avoid logging at DEBUG in production D) Set logging level to NOTSET

Correct Answer: C) Filter or mask sensitive data before logging, and avoid logging at DEBUG in production

Rationale: Secure logging requires explicit filtering/masking and not logging secrets. Option A directly logs the secret, B doesn't solve it (print also exposes), and D logs everything, making it worse.

Q8. In Python logging, what does logger = logging.getLogger(name)

achieve?

A) Creates a root logger that logs everything B) Creates a module-specific hierarchical logger supporting configuration inheritance C) Disables all logging D) Writes logs only to console

Correct Answer: B) Creates a module-specific hierarchical logger supporting configuration inheritance

Rationale: Using name creates a logger named after the module, enabling hierarchical configuration and avoiding root logger conflicts. It does not disable logging or restrict output to console by itself.

Q9. Which logging practice helps prevent log injection attacks?

A) Logging raw user input with newlines intact B) Using parameterized logging and sanitizing newlines/carriage returns from user data

A) Because asserts are too slow B) Because Python's -O optimization flag removes assert statements, bypassing validation C) Because assert cannot check strings D) Because assert always crashes the program

Correct Answer: B) Because Python's -O optimization flag removes assert statements, bypassing validation

Rationale: Running python -O strips assert, so security checks would disappear. Assertions are also not meant for recoverable user errors; explicit if checks and raising ValueError are correct for input validation.

Q13. Which assertion best validates a function's precondition that age must be

non-negative?

A) assert age >= 0, 'age must be non-negative' B) logging.warning(age) C) try: age >=0 except: pass D) if age: print('ok')

Correct Answer: A) assert age >= 0, 'age must be non-negative'

Rationale: This assert clearly states the precondition with a helpful message. Other options do not enforce the invariant; logging alone doesn't stop execution, and the try/except logic is incorrect.

Q14. In secure software design, where should assertions be placed?

A) Only at the end of programs B) At points where internal state assumptions must hold: preconditions, postconditions, invariants C) Only in test files D) To replace all logging

Correct Answer: B) At points where internal state assumptions must hold: preconditions, postconditions, invariants

Rationale: Assertions enforce design-by-contract principles at critical internal checkpoints. Placing them only at end or only in tests misses their value for early failure detection during development.

Q15. What happens if an assertion fails and is not caught?

A) Program continues silently B) Raises AssertionError and typically terminates unless handled C) Automatically logs and recovers D) Returns None

Correct Answer: B) Raises AssertionError and typically terminates unless handled

Rationale: Uncaught AssertionError propagates up and stops execution, making bugs visible. It does not auto-recover or return None, which is why asserts should not be used for expected recoverable errors.

Q16. What is the key difference between exception handling and assertion for

error management?

A) They are identical B) Exceptions handle expected, recoverable error conditions; assertions check unexpected programming errors that should never happen C) Assertions are for user errors, exceptions for logic errors D) Exceptions are removed with -O flag

Correct Answer: B) Exceptions handle expected, recoverable error conditions; assertions check unexpected programming errors that should never happen

Rationale: Exception handling is for operational errors (file not found, network failure) where recovery is possible. Assertions are for logic bugs. Option D is reversed; only asserts are removed by -O.

Q17. Which Python construct is used to catch and handle exceptions?

A) if/else B) try/except/finally C) for/while D) assert/check

Correct Answer: B) try/except/finally

Correct Answer: B) It executes regardless of whether an exception occurred or was caught, ideal for cleanup

Rationale: finally always runs for resource cleanup (closing files, releasing locks). It does not suppress exceptions unless explicitly returning inside it, and it does not retry.

Q21. Which pattern correctly handles file opening with automatic cleanup even

if exception occurs?

A) f=open(); f.read() B) with open('file') as f: data=f.read() C) try: open() except: pass D) assert open()

Correct Answer: B) with open('file') as f: data=f.read()

Rationale: with statement uses context manager to guarantee close() even on exception. Manual open() risks leaking file descriptors if exception happens before close().

Q22. What is exception chaining (raise ... from ...) used for?

A) To hide original exception B) To preserve context by linking a new exception to the original cause for better debugging C) To speed up execution D) To disable logging

Correct Answer: B) To preserve context by linking a new exception to the original cause for better debugging

Rationale: raise NewError() from orig keeps traceback chain, aiding root-cause analysis without losing info. Hiding original exception makes debugging harder.

Q23. What is remediation in software security context?

A) Ignoring vulnerabilities B) The process of fixing, mitigating, or accepting risk for identified vulnerabilities

C) Adding more features D) Deleting logs

Correct Answer: B) The process of fixing, mitigating, or accepting risk for identified vulnerabilities

Rationale: Remediation involves triage, fixing code, applying controls, or documenting risk acceptance. It is not ignoring or deleting evidence.

Q24. After Bandit reports 'B608: hardcoded SQL expression' in Python code

using f-string in query, what is the secure remediation?

A) Ignore the warning B) Use parameterized queries / ORM placeholders, e.g., cursor.execute('SELECT ... WHERE id=%s', (user_id,)) C) Add more logging D) Use eval()

Correct Answer: B) Use parameterized queries / ORM placeholders, e.g., cursor.execute('SELECT ... WHERE id=%s', (user_id,))

Rationale: Parameterized queries separate code from data, preventing SQL injection. F-string concatenation is vulnerable; ignoring or using eval() worsens it.

Q25. For a finding of 'use of random module for security purposes', what is the

correct remediation?

A) Keep random B) Replace with secrets module for cryptographically strong randomness C) Use time.time() D) Disable Bandit

Correct Answer: B) Replace with secrets module for cryptographically strong randomness

Rationale: random is not CSPRNG; secrets module provides secure tokens. time.time() is predictable, disabling tool hides risk.

Q26. Which step should come FIRST in a remediation workflow after static

analysis?

Q29. Advanced: How to securely configure Python logging to prevent log file

permission issues on Linux?

A) chmod 777 log file B) Create log file with restrictive permissions (e.g., 640), owned by service user, directory not world-writable C) Store logs in /tmp D) Log as root

Correct Answer: B) Create log file with restrictive permissions (e.g., 640), owned by service user, directory not world-writable

Rationale: Least privilege prevents tampering and info disclosure. 777 is world-writable, /tmp is shared and risky, logging as root violates principle of least privilege.

Q30. Advanced: Which static analysis approach combines static and dynamic

techniques?

A) SAST only B) DAST only C) IAST - Interactive Application Security Testing D) Manual code review only

Correct Answer: C) IAST - Interactive Application Security Testing

Rationale: IAST instruments application at runtime (like DAST) but analyzes code flow (like SAST). Pure SAST or DAST alone don't combine both.

Q31. Advanced: For code: assert file_exists(path) - what is a more robust

production-ready alternative?

A) Keep assert B) if not os.path.exists(path): raise FileNotFoundError(f'File not found: {path}') with logging C) pass D) print('file missing')

Correct Answer: B) if not os.path.exists(path): raise FileNotFoundError(f'File not found: {path}') with logging

Rationale: Explicit check with specific exception and logging survives -O flag and provides recoverable error handling, unlike assert which disappears in optimized mode.

Q32. Advanced: What does Bandit B101 (assert_used) warn about and how to

remediate for security checks?

A) Assert is always secure, ignore B) Assert can be disabled, so replace security-critical asserts with explicit validation and exceptions C) Remove all asserts from codebase D) Convert assert to print

Correct Answer: B) Assert can be disabled, so replace security-critical asserts with explicit validation and exceptions

Rationale: B101 warns assert used for security should not be relied upon. Remediation is to use if + raise for security logic, while asserts can remain for debug-only invariants.

Q33. Advanced: Best practice for exception handling in Python library code?

A) Catch all and silently ignore B) Catch specific exceptions, clean up, log context, and re-raise or raise custom domain-specific exception preserving chain C) Always crash D) Use assert

Correct Answer: B) Catch specific exceptions, clean up, log context, and re-raise or raise custom domain-specific exception preserving chain

Rationale: Libraries should not swallow errors silently. Preserving chain with logging gives callers context to handle appropriately, following fail-fast but informative principles.

Q34. Advanced: Remediation for Python pickle deserialization vulnerability

found by static analysis?

Rationale: Comprehensive fix includes immediate code fix (remove secret), preventive controls (Bandit B106 for hardcoded passwords, secure logging guidelines), and detective controls (code review checklist). Just changing level still logs secret at DEBUG.

How to Expand to 200 Questions

The Python code that generated this PDF is fully provided. To create 200 questions:

  1. Open the Python file and extend the 'questions' list from 40 to 200 entries following the same dict format.
  2. Keep domains balanced: ~40 questions per domain (Static Analysis, Logging, Assertions, Exception Handling, Remediation).
  3. Progress difficulty: Q1-50 foundational definitions, Q51-120 intermediate code analysis, Q121-200 advanced remediation scenarios and capstone integrations.
  4. Ensure each question has 4 options, one correct answer, and a 2-4 sentence rationale explaining why correct and why others are wrong.
  5. Re-run the script to generate a new PDF with navy border, header, page numbers, green answer boxes (#DCFCE7/#16A34A) and blue rationale boxes (#DBEAFE/#1D4ED8) at 1. line spacing as requested.

Study tip for D385 Task 1: Don't memorize. For your actual WGU task, you will need to demonstrate static analysis findings, fix insecure logging/assertion/exception code, and explain remediation. Practice by running: pip install bandit, bandit -r your_code.py -f sarif, and fixing each B1xx issue.