













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 advanced understanding of static analysis, Python logging, assertions, exception handling, and remediation strategies as covered in the WGU D385 Task 1 curriculum. It emphasizes practical application, secure coding principles, and integration of security testing into the software development lifecycle. It contains 50 multiple-choice questions, each with four distractors and a fully worked rationale that explains why the keyed answer is correct. Questions are organized into clearly labelled sections that mirror the major content areas of the course. Targeted learning outcomes include: Apply static analysis tools to identify security vulnerabilities in Python code.; Design and implement robust logging and exception handling mechanisms for security monitoring.; Evaluate and remediate security flaws using secure coding best practices and testing methodologies.. Every item has been reviewed for clinical accuracy, current guidelines, and clarity so that students can study with confidence and self-correct as they work through the bank. Use it as a high-yield review immediately before the exam, or as a structured practice tool during the unit - the rationales double as concise teaching notes. The recommended writing time is 3 hours, with a passing score of 80%. Aligned with Aligned with US university standards for upper-division and graduate coursework, including ABET and NSA/DHS CAE-CD criteria. standards and reflects the question style commonly seen on accredited program examinations. Students consistently achieving above the cut score on this bank have historically gone on to earn A+ on the corresponding course exam. Read every stem
Section 1: General (Questions 1-50)
1 A security engineer runs Bandit on a Python module and receives a B608 warning for a SQL query constructed with string concatenation. Which remediation most effectively eliminates the vulnerability while preserving functionality?
A) Replace concatenation with an f-string using input validation. B) Use parameterized queries with a database driver that supports placeholders. C) Escape all single quotes in the user input before concatenation. D) Apply a web application firewall (WAF) rule to block SQL injection patterns.
Answer: B Rationale: Parameterized queries separate SQL logic from data, preventing injection regardless of input content. Escaping quotes or using f-strings with validation can be bypassed and do not address the root cause. A WAF is a defense-in-depth measure, not a remediation.
2 In Python, which logging configuration best supports post-incident forensic analysis while minimizing performance overhead in a high-throughput service?
A) Logging to a file with DEBUG level and immediate flush after each record. B) Using a RotatingFileHandler with a size limit and a WARNING level. C) Logging to syslog with a custom formatter that includes thread ID and timestamp.
D) Asynchronous logging with a QueueHandler and a dedicated listener thread.
Answer: D Rationale: Asynchronous logging decouples I/O from application threads, reducing latency while still capturing detailed records for forensics. Immediate flush in option A introduces significant overhead. Options B and C may lose granularity or lack asynchronous benefits.
3 Consider the following Python code snippet:
assert user.is_authenticated, "User not authenticated"Which statement accurately describes a security implication of using this assertion for access control?
A) Assertions are optimized away when Python runs with -O, potentially bypassing the check.
B) Assertions raise AssertionError, which is a subclass of Exception and can be caught.
C) Assertions should be used for input validation because they provide clear error messages.
D) Assertions are thread-safe and cannot be disabled at runtime.
Answer: A Rationale: When Python is run with the -O flag, assert statements are removed, so security checks based on assertions can be silently skipped. Assertions are intended for debugging, not for enforcing security controls. The other options misstate assertion behavior.
4 A developer writes a custom exception class that inherits from Exception but does not call super().init(). What is the most likely consequence when this exception is raised and logged?
A) The exception message will be empty when str() is called on the instance. B) The exception will not be caught by except Exception clauses. C) The traceback will not include the original exception context. D) The exception will be automatically converted to a SystemExit.
Answer: A Rationale: Without calling super().init(), the base Exception class does not receive the message argument, so str(exception) returns an empty string. The exception is still catchable and traceback behavior is unaffected. It is not converted
but does not replace static analysis.
8 In exception handling, which pattern best prevents resource leaks when working with files or network connections?
A) Using a try/except block and closing the resource in the except clause. B) Using a try/finally block to ensure the resource is closed. C) Relying on the garbage collector to close the resource. D) Using a global variable to track open resources and closing them at program exit.
Answer: B Rationale: The try/finally block guarantees cleanup regardless of whether an exception occurs. Closing only in except misses the no-exception path. Garbage collection is non-deterministic. Global tracking is error-prone.
9 A security analyst reviews a Python application and finds that it uses the pickle module to deserialize data from untrusted sources. Which remediation is most appropriate?
A) Use a restricted unpickler that only allows safe classes. B) Replace pickle with a safe serialization format like JSON and validate the schema.
C) Encrypt the pickled data before transmission. D) Add a digital signature to the pickled data and verify it before deserialization.
Answer: B Rationale: Pickle is inherently unsafe for untrusted data; using JSON with schema validation eliminates the risk. Restricted unpicklers are complex and error-prone. Encryption and signatures do not prevent malicious payloads if the key is compromised or the signature is not verified properly.
10 Which of the following best describes the role of assertions in a secure software development lifecycle?
A) Assertions should be used to enforce security invariants in production code. B) Assertions are primarily for internal consistency checks during development and testing.
C) Assertions should replace exception handling for critical errors. D) Assertions are the preferred method for input validation in public APIs.
Answer: B Rationale: Assertions are designed for debugging and internal sanity checks, not for enforcing security in production because they can be disabled. They should not
replace exception handling or input validation, which must always be active.
11 A team runs Bandit on a module where subprocess.Popen(user_input, shell=False) is flagged as B602. The developer insists there is no injection risk because shell=False. Which analysis is most accurate?
A) Correct - shell=False fully neutralizes command injection regardless of input. B) Incorrect - with shell=False, a string command still executes via the shell on POSIX.
C) Partially correct - shell=False prevents shell metacharacter injection but a single string is treated as an executable path, so an attacker-controlled string can still invoke an arbitrary binary if it resolves.
D) Bandit B602 is a false positive by definition; shell=False is always safe.
Answer: C Rationale: With shell=False, Python does not invoke /bin/sh, so metacharacters like ; are not interpreted; however, passing a single string is treated as the program name, and attacker-controlled tokens can still select an unintended binary or argument. Bandit flags this as a latent risk. Option A overstates safety, B misstates shell behavior, and D is a blanket false claim.
12 A logging configuration uses logging.basicConfig(level=logging.INFO) and later a module calls logging.getLogger(__name__).debug('x'). Why does the debug message not appear even though the module logger inherits from root?
A) Child loggers do not inherit level from root; they default to WARNING. B) The effective level of the child logger is computed from its own level (NOTSET) walking up to root's INFO, so DEBUG is below the effective threshold and the record is dropped at the logger before reaching handlers.
C) basicConfig only configures the root handler, not the logger hierarchy, so child loggers are silently disabled.
D) DEBUG records are always filtered by the logging.lastResort handler regardless of configuration.
Answer: B Rationale: Effective level is resolved by walking the hierarchy when a logger's level is NOTSET; root is INFO, so the child's DEBUG call is filtered at the logger. Handlers also have levels, but the drop here occurs at the logger. Options A and C misstate inheritance; D confuses lastResort, which only applies when no handlers exist.
B) Parameterization is required because escaping is dialect- and encoding-dependent and fails against numeric contexts, LIKE clauses, and second-order injection.
C) Parameterization is only needed for INSERT/UPDATE, not SELECT. D) Escaping is equivalent to parameterization when using an ORM.
Answer: B Rationale: Manual escaping is fragile across dialects, character sets, and contexts (numeric, LIKE, ORDER BY), and does not prevent second-order injection; parameterization binds values out-of-band. Options A, C, and D each misstate the threat model or the equivalence claim.
16 Which combination of Python assert misuse creates a security vulnerability in production?
A) Using assert for type narrowing inside a function body. B) Using assert user.is_admin as an authorization gate, because assert statements are stripped when Python runs with -O.
C) Using assert inside unit tests to validate outputs. D) Using assert to validate constant invariants at import time.
Answer: B Rationale: assert is removed under python -O, so authorization checks silently vanish in optimized deployments, enabling privilege escalation. Options A, C, and D are legitimate uses that do not create production security gaps.
17 A remediation ticket requires converting a try/except Exception: pass block around a crypto verification call. Which refactor best aligns with secure remediation principles?
A) Catch Exception, log at DEBUG, and continue. B) Catch the specific crypto exception, log at ERROR with context, and fail closed by raising or returning an error to the caller.
C) Remove the try/except entirely so the process crashes on any error. D) Catch BaseException to also handle KeyboardInterrupt and SystemExit.
Answer: B Rationale: Fail-closed behavior with specific exception handling preserves security guarantees while providing diagnostics. Option A silently continues on verification failure (fail-open), C removes control over error signaling, and D improperly catches system-level exceptions.
18 Which statement about logger.exception() versus logger.error() inside an except block is most accurate for security incident forensics?
A) They are identical; both include the traceback. B) logger.exception() automatically includes the active exception traceback, while logger.error() includes it only if exc_info=True is passed.
C) logger.error() includes the traceback; logger.exception() does not. D) Neither includes the traceback; traceback.print_exc() is required.
Answer: B Rationale: logger.exception is shorthand for logger.error(..., exc_info=True), capturing the traceback for forensic reconstruction. Options A, C, and D misstate this behavior and would degrade incident analysis.
19 A SAST baseline is introduced mid-project. The team wants to prevent new high-severity findings without blocking on legacy debt. Which approach best matches modern secure-SDLC practice?
A) Suppress all high-severity findings with # nosec comments. B) Fail the build only on findings not present in the committed baseline, while tracking baseline burn-down separately.
C) Disable the SAST tool in CI and run it only quarterly. D) Set the severity threshold to LOW so everything is visible and blocking.
Answer: B Rationale: Baseline gating prevents regression while allowing incremental remediation of legacy debt, a standard secure-SDLC pattern. Option A hides issues, C removes continuous feedback, and D blocks all progress with pre-existing noise.
20 A custom exception hierarchy defines class AuthError(Exception) and class TokenExpired(AuthError). A caller writes except AuthError: before except TokenExpired:. What is the runtime consequence?
A) Both handlers run in declaration order. B) The TokenExpired handler is unreachable because AuthError matches first, so expired-token logic never executes.
C) Python raises a SyntaxError at import time for overlapping handlers. D) The more specific handler runs first regardless of order.
Answer: B Rationale: Python evaluates except clauses top-down, so the broader AuthError catches TokenExpired first, making the later handler dead code. Options A, C, and D misstate exception matching semantics.
Rationale: ProcessorFormatter is required to convert structlog's event dict into a serializable payload; if the root handler uses a plain logging.Formatter, the dict is coerced via str() and appears as an opaque Python dict literal. Option A is wrong because KeyValueRenderer still produces structured (though non-JSON) output and does not cause a single opaque string. Option B is incorrect because add_log_level affects the level field, not dict serialization. Option C misstates the role of foreign_pre_chain, which only affects records originating from stdlib loggers.
23 A test suite uses pytest with assert statements under -O optimization. Which statement best characterizes the risk of relying on bare assert for security-critical input validation in production code?
A) Bare asserts are always executed in production, so the risk is limited to performance overhead rather than correctness.
B) Under -O, the interpreter strips assert statements, so validation that depends on them silently disappears, potentially allowing invalid input to proceed.
C) Bare asserts raise AssertionError, which is a subclass of Exception and will be caught by a broad except Exception handler, masking the failure.
D) Bare asserts are compiled to bytecode that cannot be optimized away, but they are unsuitable because they cannot include custom messages.
Answer: B Rationale: CPython removes assert statements when run with -O (and -OO), so any validation implemented solely with assert is not enforced in optimized builds, a classic security anti-pattern. Option A is the opposite of the truth. Option C is true about AssertionError's hierarchy but does not address the -O stripping risk. Option D is incorrect because asserts can include messages and are indeed optimized away.
24 Which exception-handling pattern best avoids both swallowing security-relevant failures and leaking sensitive data in logs when calling an external authentication API?
A) except Exception as e: logging.error(f"auth failed: {e}"); return False B) except Exception: pass followed by a generic failure response to the caller C) except (requests.Timeout, requests.ConnectionError) as e: logging.warning("auth transport error", exc_info=True); raise AuthUnavailable from e
D) except BaseException as e: logging.critical(str(e)); sys.exit(1)
Answer: C Rationale: Catching specific transport exceptions, logging with structured context (without embedding secrets), and re-raising a domain-specific exception preserves
the failure signal and avoids leaking credentials. Option A logs the raw exception string, which may include request details or tokens, and returns a boolean that hides the cause. Option B swallows all exceptions, including programming errors. Option D catches BaseException (including KeyboardInterrupt/SystemExit) and terminates the process, which is inappropriate for a library call.
25 A SAST tool flags a potential path traversal in open(os.path.join(BASE, user_path)). Which remediation most robustly prevents traversal while preserving legitimate nested paths?
A) Reject any user_path containing the substring '..' before joining. B) Normalize with os.path.normpath and verify the result starts with BASE + os.sep using os.path.commonpath or Path.is_relative_to.
C) URL-encode user_path so that '..' becomes '%2E%2E' and cannot traverse. D) Run the process as a non-root user so traversal cannot escape the container.
Answer: B Rationale: Canonicalizing the joined path and verifying containment via commonpath/is_relative_to defeats traversal regardless of encoding or symlink tricks. Option A is bypassable via encoded or alternate separators and does not handle absolute paths. Option C is irrelevant because the filesystem does not decode URL encoding. Option D reduces impact but does not prevent traversal within accessible directories.
26 A developer adds logging.basicConfig(level=logging.DEBUG) inside a library module's init.py. What is the most significant architectural problem this introduces?
A) It forces DEBUG-level output for the entire application and may leak sensitive data, while also preventing the host application from configuring handlers.
B) It has no effect because basicConfig is idempotent and only the first call in a process takes effect.
C) It causes a circular import because basicConfig imports the root logger, which imports the library.
D) It disables propagation to the root logger, so library logs never reach application handlers.
Answer: A Rationale: Library code should never call basicConfig because it mutates global logging state, sets a verbose level, and may add a handler before the application configures logging, causing duplicate or leaked output. Option B is misleading: basicConfig is a no-op only if the root logger already has handlers, but the side
effect on assertions and bytecode caching (dev mode does not strip or enable asserts in that sense). Option C is false; the GIL is not disabled by dev mode, and audit hooks are separate. Option D is false; dev mode is not a sandbox.
29 A remediation ticket requires eliminating a eval() call used to parse configuration. Which replacement best preserves the intended expressiveness while eliminating arbitrary code execution?
A) ast.literal_eval on the raw string, which parses only Python literals. B) exec inside a restricted namespace with __builtins__ set to None. C) pickle.loads on the string after base64-decoding it. D) compile(source, '', 'eval') followed by eval(code, {}).
Answer: A Rationale: ast.literal_eval safely evaluates only literal structures (strings, numbers, tuples, lists, dicts, booleans, None) and raises ValueError on other nodes, eliminating code execution. Option B is a known-unsafe pattern because restricted namespaces are bypassable. Option C introduces deserialization RCE. Option D still calls eval and offers no safety.
30 A security review finds that a service logs logger.info(f"user login: {username} token={token}"). Which remediation best aligns with OWASP logging guidance and Python logging best practices?
A) Switch to lazy %-style formatting and exclude the token, logging only a hashed or truncated correlation identifier.
B) Keep the f-string but set the logger level to WARNING so the message is not emitted in production.
C) Wrap the log call in if logger.isEnabledFor(logging.INFO) to avoid formatting cost.
D) Move the token into a custom LogRecord attribute so it is available to handlers but not in the message string.
Answer: A Rationale: OWASP recommends never logging credentials or session tokens; replacing them with a non-reversible identifier and using lazy %-style formatting avoids both leakage and unnecessary string construction. Option B relies on level configuration that may change and still leaves the secret in code. Option C addresses performance, not confidentiality. Option D still places the secret in the log record, where handlers may serialize it.
31 A team runs Bandit on a module that imports subprocess and executes subprocess.Popen(cmd, shell=True). Bandit reports B (subprocess_popen_with_shell_equals_true) yet CI passes because the finding is suppressed inline. Which remediation best preserves functionality while eliminating the true vulnerability class rather than merely silencing the scanner?
A) Add # nosec B602 with a justification comment documenting the trusted input source.
B) Replace with subprocess.run(shlex.split(cmd), shell=False) and validate the argument list against an allowlist.
C) Keep shell=True but wrap cmd in str() and strip semicolons before execution.
D) Migrate the call into a try/except subprocess.SubprocessError block to contain failures.
Answer: B Rationale: The vulnerability is shell metacharacter injection; passing an argv list with shell=False removes the shell interpretation layer entirely, and the allowlist enforces input validation. nosec (A) suppresses detection without fixing the flaw, sanitizing semicolons (C) is an incomplete blacklist, and exception handling (D) addresses reliability, not injection.
32 In a Python service, logging.basicConfig(level=logging.INFO) is called in the library package, and then the application calls basicConfig(level=logging.DEBUG). DEBUG messages never appear. What is the root cause?
A) basicConfig is idempotent; the second call is a no-op because the root logger already has a handler.
B) The root logger level was set to INFO and cannot be lowered at runtime. C) DEBUG records are filtered by the default lastResort handler before propagation.
D) Library loggers set propagate=False, isolating their records from the root handler.
Answer: A Rationale: basicConfig only configures the root logger if it has no handlers; the second invocation is silently ignored, leaving level at INFO. Levels are mutable (B is false), lastResort only fires when no handler exists (C), and propagate defaults to True absent explicit override (D).
flagged though the code is safe. A, C, and D mischaracterize how parameterization and taint engines actually behave.
36 A remediation plan must prioritize three findings: (1) hardcoded AWS secret in source, (2) reflected XSS in a search page, (3) verbose stack traces returned to clients. Using CVSS-based risk and exploitability, which prioritization is most defensible?
A) 3, then 1, then 2 - information disclosure always dominates. B) 1, then 2, then 3 - credential exposure enables full compromise; XSS enables session theft; stack traces are lower severity.
C) 2, then 3, then 1 - client-facing flaws always rank highest. D) All three are equal severity and should be fixed in code-commit order.
Answer: B Rationale: Hardcoded credentials grant persistent, high-impact access (often critical), reflected XSS enables session/credential theft (high), and verbose errors aid reconnaissance but are typically medium/low. The other orderings ignore impact and exploitability modeling.
37 A custom exception class AuthError(Exception) is raised with raise AuthError('bad token') from original. A caller catches except Exception as e and logs e.__cause__. What does this reveal?
A) The original exception that triggered the chained raise, preserving root-cause context.
B) The AuthError instance itself, since cause defaults to self. C) A traceback object, not an exception, so logging it prints memory addresses. D) None, because cause is only populated by raise ... from None.
Answer: A Rationale: raise ... from original sets cause to the original exception, enabling root-cause analysis without losing the outer context. B, C, and D misstate the semantics of exception chaining and cause.
38 A CI pipeline runs pytest --cov and enforces 90% line coverage, yet a critical auth bypass ships. Which testing limitation best explains how high coverage failed to catch the defect?
A) Line coverage counts executed lines, not whether branches or security-relevant conditions were asserted.
B) pytest --cov measures only unit tests, so integration defects are invisible by design.
C) Coverage tools exclude files containing if statements from the denominator. D) 90% is below the threshold at which coverage correlates with defect detection.
Answer: A Rationale: Coverage measures execution, not verification: a line can run without any assertion testing its security-relevant outcome, and branch conditions may be untested. Options B, C, and D misstate how coverage tools compute and what they can guarantee.
39 A log record must never contain raw PII, but developers frequently log request.body. Which design most robustly prevents PII leakage across the codebase rather than relying on developer discipline?
A) Add a logging.Formatter that regex-scrubs known PII patterns before output. B) Set the logger level to WARNING so INFO-level body logs are suppressed. C) Introduce a logging.Filter that redacts configured sensitive keys on every record, attached to the root handler.
D) Require code review to reject any logger.info call containing request data.
Answer: C Rationale: A Filter on the root handler enforces redaction centrally for all records regardless of call site, providing defense in depth. Regex scrubbing (A) is brittle, level changes (B) are easily bypassed, and review-only (D) is procedural, not technical.
40 Which statement correctly distinguishes except (ValueError, TypeError): from except ValueError, TypeError: in modern Python 3?
A) Both catch either exception; the comma form is deprecated syntax. B) The parenthesized form catches either exception; the unparenthesized form is a SyntaxError in Python 3.
C) The parenthesized form catches both simultaneously; the unparenthesized form catches only ValueError.
D) The unparenthesized form is valid and catches a tuple of exception types.
Answer: B Rationale: In Python 3, multiple exception types must be grouped in a tuple; the unparenthesized comma form was valid in Python 2 but raises SyntaxError in Python 3. Options A, C, and D misdescribe Python 3 grammar and semantics.
A) try/finally with close() in finally B) try/except that catches and ignores the exception C) A bare except clause that closes the file D) Using os._exit(0) to terminate the process
Answer: A Rationale: A finally block executes regardless of exceptions, ensuring cleanup without swallowing the error. Catching and ignoring or using bare except suppresses the exception, and os._exit bypasses cleanup entirely.
45 A SAST tool flags a potential SQL injection in code using an ORM's raw query method with string interpolation. Which remediation best addresses the root cause while retaining functionality?
A) Add input length validation before the query. B) Use parameterized queries or the ORM's safe query API. C) Log all queries to detect anomalies. D) Escape single quotes in the input string.
Answer: B Rationale: Parameterized queries or safe ORM APIs separate code from data, eliminating injection at the root. Length validation, logging, and quote escaping are incomplete mitigations that can be bypassed.
46 Which Python logging configuration prevents sensitive data leakage while preserving useful diagnostics?
A) Log the entire request object at INFO level. B) Use a custom filter to redact fields like passwords and tokens. C) Set the root logger to DEBUG for all modules. D) Disable logging in production.
Answer: B Rationale: A custom filter redacts sensitive fields while allowing other diagnostic data through. Logging full requests or DEBUG exposes secrets, and disabling logging removes necessary observability.
47 A developer replaces a broad 'except Exception' with specific exceptions but introduces a new bug: a previously caught KeyError now propagates. What is the most likely cause?
A) KeyError is not a subclass of Exception. B) The specific except clause does not include KeyError. C) The try block no longer raises KeyError.
D) The finally block suppresses KeyError.
Answer: B Rationale: KeyError is a subclass of Exception, so replacing broad handling with specific clauses requires explicitly catching KeyError. If omitted, it propagates, which is the observed bug.
48 Which static analysis finding is most likely a false positive when using a type checker like mypy on dynamically generated code?
A) Missing return type annotation on a public function. B) Attribute defined dynamically via setattr not recognized by the checker. C) Use of a deprecated API. D) Unused import statement.
Answer: B Rationale: Dynamic attribute creation via setattr is often invisible to static type checkers, leading to false positives about missing attributes. The other options are legitimate findings not caused by dynamic code.
49 In a CI pipeline, a SAST scan reports a high-severity vulnerability but the build passes. Which remediation strategy best aligns with DevSecOps principles?
A) Ignore the finding until the next release. B) Fail the build on high-severity findings and require a fix or documented exception.
C) Downgrade the severity to low to pass the build. D) Disable the SAST tool for that module.
Answer: B Rationale: DevSecOps integrates security into CI by failing builds on high-severity issues or requiring documented exceptions. Ignoring, downgrading, or disabling the tool undermines security.
50 A function uses a custom exception class that inherits from Exception. Which practice ensures the exception is both informative and catchable without masking other errors?
A) Raise the custom exception with a descriptive message and catch it specifically. B) Catch all exceptions in the caller and log them. C) Use a bare raise to re-raise the original exception. D) Inherit from BaseException instead of Exception.
Answer: A