Docsity

WGU D385 Task 1 Complete Practice Guide Software Security & Testing Static Analysis, Pyth, Exams of Computer Security

Toggle sidebar
bg1
Page 1
WGU D385 Task 1 Complete Practice Guide Software Security &
Testing Static Analysis, Python Logging, Assertions, Exception
Handling & Remediation 2026 - Questions and Answers Already
Graded A+ Premium Exam Tested And Verified
GRADED A+
ABSTRACT
This exam covers static analysis, Python logging, assertions, exception handling, and
remediation strategies for secure software development. It emphasizes practical
application of tools and techniques to identify and mitigate vulnerabilities, with a focus
on Python-specific implementations and industry best practices.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a

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!

WGU D385 Task 1 Complete Practice Guide Software Security &

Testing Static Analysis, Python Logging, Assertions, Exception

Handling & Remediation 2026 - Questions and Answers Already

Graded A+ Premium Exam Tested And Verified

GRADED A+

ABSTRACT

This exam covers static analysis, Python logging, assertions, exception handling, and

remediation strategies for secure software development. It emphasizes practical

application of tools and techniques to identify and mitigate vulnerabilities, with a focus

on Python-specific implementations and industry best practices.

1. A static analysis tool reports a potential SQL injection vulnerability in a Python

function that constructs a query using string formatting. Which remediation strategy

best addresses the root cause while maintaining functionality?

A. Replace string formatting with parameterized queries using the database driver's placeholder syntax. B. Sanitize all user inputs by escaping single quotes and semicolons before concatenation. C. Implement a web application firewall (WAF) rule to block SQL injection patterns. D. Use an ORM exclusively for all database interactions without reviewing generated SQL.

Answer: A. Replace string formatting with parameterized queries using the

database driver's placeholder syntax.

Parameterized queries separate SQL logic from data, preventing injection by design. Escaping is error-prone and bypassable; WAFs are defense-in-depth but not a fix; ORMs can still be misused and may not cover all cases.

2. In Python's logging module, which configuration ensures that log records are

written to a file only when an exception occurs, while still capturing full stack traces?

A. Set the logging level to ERROR and use a FileHandler with a formatter that includes %(exc_info)s. B. Use a try-except block that calls logging.exception() within the except clause, with a FileHandler configured. C. Configure a SMTPHandler to email logs on exceptions and a FileHandler for all levels. D. Use logging.basicConfig(filename='app.log', level=logging.CRITICAL) and call logging.critical() in except blocks.

Answer: B. Use a try-except block that calls logging.exception() within the except

clause, with a FileHandler configured.

logging.exception() automatically logs an ERROR-level message with exception information. Option A would log all errors, not just exceptions; C sends emails; D only logs critical messages and misses stack traces unless explicitly passed.

5. In the context of static analysis, what distinguishes a false positive from a false

negative, and which is more dangerous from a security perspective?

A. False positive: flagging a non-issue; false negative: missing a real issue. False negatives are more dangerous as they leave vulnerabilities undetected. B. False positive: missing a real issue; false negative: flagging a non-issue. False positives are more dangerous as they cause alert fatigue. C. False positive: flagging a non-issue; false negative: missing a real issue. False positives are more dangerous as they waste developer time. D. False positive: incorrect severity rating; false negative: incorrect location. Both are equally dangerous.

Answer: A. False positive: flagging a non-issue; false negative: missing a real issue.

False negatives are more dangerous as they leave vulnerabilities undetected.

False positives are incorrect warnings; false negatives are missed vulnerabilities. False negatives are more dangerous because they allow exploits to remain. The other options misdefine the terms or prioritize incorrectly.

6. When using Python's logging module, which handler and formatter combination

best supports forensic analysis after a security incident?

A. StreamHandler with a simple message format to console for real-time monitoring. B. RotatingFileHandler with a detailed format including timestamp, log level, module, and process ID. C. SysLogHandler sending logs to a remote syslog server with default formatting. D. MemoryHandler buffering logs and flushing only on critical errors.

Answer: B. RotatingFileHandler with a detailed format including timestamp, log

level, module, and process ID.

RotatingFileHandler preserves logs with rotation, and detailed formatting aids forensics. Console logging is ephemeral; syslog may lack detail; MemoryHandler may lose logs on crash.

7. Which exception handling anti-pattern is most likely to introduce a security

vulnerability in a Python web application?

A. Catching specific exceptions like ValueError and returning a generic error message. B. Using a bare except: clause that swallows all exceptions and continues execution. C. Logging exceptions with logging.exception() and re-raising them. D. Using finally blocks to release resources such as database connections.

Answer: B. Using a bare except: clause that swallows all exceptions and continues

execution.

Bare excepts can hide critical errors, leading to inconsistent state and potential security bypasses. The other options are good practices or less risky.

8. A static analysis tool flags a potential path traversal vulnerability in a Python file

download function. Which code change effectively remediates this?

A. Use os.path.basename() on the user-supplied filename before constructing the path. B. Validate the filename against a whitelist of allowed filenames. C. Use os.path.realpath() to resolve the absolute path and ensure it starts with the intended base directory. D. Encode the filename using URL encoding before use.

Answer: C. Use os.path.realpath() to resolve the absolute path and ensure it starts

with the intended base directory.

realpath() canonicalizes the path, preventing traversal outside the base directory. basename() may not handle all cases; whitelisting is good but less general; URL encoding does not prevent traversal.

9. In Python, which logging level is most appropriate for recording security-relevant

events such as failed login attempts, and why?

A. DEBUG, because it provides detailed information for troubleshooting. B. INFO, because it indicates normal but significant events. C. WARNING, because it indicates a potential issue that should be investigated. D. ERROR, because it indicates a failure that requires immediate attention.

Answer: C. WARNING, because it indicates a potential issue that should be

investigated.

Failed logins are potential security issues, so WARNING is appropriate. DEBUG is too verbose, INFO is for normal events, ERROR is for actual errors, not just attempts.

12. A developer writes: try: risky(); except (ValueError, TypeError):

logger.exception('failed'); raise SystemExit(1). During review, a senior engineer

objects. Which critique is most accurate?

A. logger.exception should be logger.error because no exception is active in the handler. B. SystemExit should be replaced with sys.exit(1) for portability across platforms. C. Re-raising SystemExit masks the original exception's traceback and prevents upstream recovery. D. Catching both ValueError and TypeError violates the single-responsibility principle.

Answer: C. Re-raising SystemExit masks the original exception's traceback and

prevents upstream recovery.

SystemExit is not a subclass of Exception and terminates the interpreter, discarding the chained traceback and preventing callers from handling the original error; use bare 'raise' or a custom exception. logger.exception is correct inside an except block (A), sys.exit raises SystemExit identically (B), and grouping exception types is idiomatic (D).

13. A team configures Python logging with dictConfig using a RotatingFileHandler

and a StreamHandler sharing one logger. During a burst of warnings, duplicate lines

appear in the file but not on the console. Which configuration error most likely

explains this?

A. The logger's propagate flag is True and a parent logger also has a RotatingFileHandler attached. B. The StreamHandler level is set to WARNING while the RotatingFileHandler level is DEBUG. C. The formatter uses %(message)s without a timestamp, causing apparent duplicates. D. The RotatingFileHandler maxBytes is smaller than the burst size, triggering rotation mid-write.

Answer: A. The logger's propagate flag is True and a parent logger also has a

RotatingFileHandler attached.

Duplicate records typically arise when a record propagates to an ancestor logger that also has a handler writing to the same destination; setting propagate=False or attaching handlers only at the root fixes it. Level mismatches (B) change filtering, not duplication, formatting (C) cannot duplicate lines, and rotation (D) does not duplicate records.

14. Consider this assertion: assert validate(payload), f'invalid: {payload}'. A

production deployment runs with python -O. Which statement about behavior is

correct?

A. The assertion still executes and raises AssertionError with the message. B. The assertion is stripped entirely, and payload is never validated. C. The assertion executes but the message expression is skipped for performance. D. The assertion raises a RuntimeError instead of AssertionError under -O.

Answer: B. The assertion is stripped entirely, and payload is never validated.

Under -O (and PYTHONOPTIMIZE), the compiler removes assert statements and their message expressions entirely, so validation silently disappears - a classic rationale for never using asserts for runtime input validation. The other options misstate the optimizer's effect on asserts.

15. A SAST tool reports a taint flow from request.args['q'] to cursor.execute(query).

The developer adds html.escape(q) before the query. Which statement best

characterizes the residual risk?

A. The flow is fully mitigated because escaping neutralizes all metacharacters. B. The flow remains exploitable because HTML escaping does not address SQL context. C. The flow is mitigated only if the database uses a UTF-8 collation. D. The flow is mitigated because taint analyzers recognize html.escape as a sanitizer.

Answer: B. The flow remains exploitable because HTML escaping does not address

SQL context.

Sanitizers are context-specific: HTML escaping is irrelevant in a SQL grammar, so injection persists and the taint flow should remain flagged. Option A overstates escaping, C confuses collation with sanitization, and D is false - most analyzers do not treat html.escape as a SQL sanitizer.

18. A module defines class AuditError(Exception) with init(self, code, msg) that

calls super().init(msg) and sets self.code. A caller does 'raise AuditError(42,

"bad") from KeyError("k")'. Which statement about the resulting exception is

correct?

A. str(exc) returns 'bad' and exc.cause is the KeyError instance. B. str(exc) returns '(42, "bad")' because init overrides the message. C. exc.context is None because 'from' clears the implicit context. D. The KeyError is discarded because AuditError is not a subclass of it.

Answer: A. str(exc) returns 'bad' and exc.cause is the KeyError instance.

super().init(msg) sets the args so str(exc) yields 'bad', and 'raise ... from ...' explicitly sets cause to the KeyError. Option B misstates args handling, C confuses context (still set) with cause, and D ignores chaining semantics.

19. A reviewer sees: 'assert isinstance(user, Admin)'. The code then calls

user.delete_all(). Which statement best explains why this pattern is a security

weakness?

A. isinstance is too slow for security checks and should use type() instead. B. Asserts can be disabled with -O, so the authorization check may vanish in production. C. Admin is a subclass of User, so isinstance returns False and blocks access. D. The assert raises AssertionError, which is not a subclass of Exception.

Answer: B. Asserts can be disabled with -O, so the authorization check may vanish

in production.

Using assert for authorization is unsafe because the -O flag strips asserts, silently removing the check; explicit if/raise is required. Speed (A), subclass direction (C), and AssertionError's hierarchy (D, it is a subclass of Exception) are all incorrect.

20. A team must remediate a SAST finding on a subprocess call built from user

input. Which remediation most directly eliminates the injection class while

preserving functionality?

A. Pass shell=False and provide the command as a list of arguments. B. Escape shell metacharacters in the input before concatenation. C. Set a strict timeout on subprocess.run to limit damage. D. Redirect stderr to DEVNULL to prevent error-based leakage.

Answer: A. Pass shell=False and provide the command as a list of arguments.

Using shell=False with an argument list bypasses the shell entirely, so metacharacters cannot be interpreted - the canonical fix. Escaping (B) is fragile and context-dependent, timeouts (C) do not prevent injection, and stderr redirection (D) is orthogonal to injection.

21. A developer runs Bandit on a module that constructs SQL via f-strings inside a

try/except that catches Exception. Bandit reports B608 but the code never reaches

the sink at runtime because a guard returns early. Which statement best

characterizes the finding's validity and the correct remediation posture?

A. It is a false positive because the vulnerable path is unreachable; suppress it with # nosec and no code change is warranted. B. It is a true positive for a dangerous pattern; static analysis is path-insensitive here, so the correct remediation is parameterized queries regardless of the guard. C. It is a false positive unless the guard uses a constant condition; Bandit performs full symbolic execution and would otherwise not flag it. D. It is a true positive only if the except clause re-raises; catching Exception converts it to a finding.

Answer: B. It is a true positive for a dangerous pattern; static analysis is

path-insensitive here, so the correct remediation is parameterized queries

regardless of the guard.

Bandit's B608 flags the dangerous SQL-construction pattern and is largely path-insensitive, so an early guard does not make the pattern safe to retain. Suppressing with # nosec hides a genuine anti-pattern that could become reachable after refactoring. Parameterized queries eliminate the root cause, which is the correct remediation posture.

24. A function raises ValueError for malformed input and OSError for I/O failures.

A caller wraps it in try/except (ValueError, OSError) as e: log and re-raise. Which

refactor best preserves diagnostic fidelity while enabling targeted recovery?

A. Catch Exception broadly and re-raise a new RuntimeError to unify error types. B. Separate except clauses: handle ValueError with user feedback and OSError with retry/backoff, logging each with exc_info=True. C. Remove the try block and let exceptions propagate to the top-level handler only. D. Catch BaseException to ensure no failure escapes, then log and continue.

Answer: B. Separate except clauses: handle ValueError with user feedback and

OSError with retry/backoff, logging each with exc_info=True.

Distinct exception types signal different recovery strategies, so separate handlers with exc_info=True preserve the traceback and enable targeted logic. Catching Exception or BaseException erases type information and can swallow KeyboardInterrupt/SystemExit. Removing handling entirely forfeits the opportunity for user feedback and retry.

25. A pipeline fails security gates on a medium-severity finding in a dependency. The

team argues it is not exploitable in their usage. Which remediation decision best

aligns with modern supply-chain risk management?

A. Ignore it because exploitability is the only criterion for remediation. B. Pin the vulnerable version and add a suppression with no expiry. C. Triage with reachability and exploitability context, apply a compensating control or upgrade, and record a time-boxed, documented exception if deferring. D. Fork the dependency and patch silently without notifying upstream.

Answer: C. Triage with reachability and exploitability context, apply a

compensating control or upgrade, and record a time-boxed, documented exception

if deferring.

Modern practice combines reachability/exploitability triage with compensating controls and time-boxed, documented exceptions to manage risk transparently. Permanent suppressions or ignoring based solely on claimed non-exploitability bypass governance. Silent forks create maintenance and disclosure burdens without addressing upstream risk.

26. A test asserts that a function raises KeyError for a missing key. The

implementation was changed to raise a custom ConfigError(KeyError). Which

assertion most robustly encodes the intended contract?

A. with self.assertRaises(KeyError): B. with self.assertRaises(ConfigError): C. with self.assertRaises(Exception): D. with self.assertRaisesRegex(KeyError, 'missing'):

Answer: B. with self.assertRaises(ConfigError):

Asserting the specific ConfigError type captures the refined contract and will fail if the type regresses to a bare KeyError. Asserting KeyError passes for the subclass, masking the intended specificity, while Exception is too broad. assertRaisesRegex on KeyError still under-specifies the type.

27. A codebase logs sensitive tokens at INFO. Which change most effectively

prevents leakage while preserving operational visibility?

A. Raise the logger level to WARNING globally. B. Add a logging.Filter that redacts or drops records containing token patterns before they reach handlers. C. Switch to print() for non-sensitive messages and keep logging for tokens. D. Disable propagation to the root logger.

Answer: B. Add a logging.Filter that redacts or drops records containing token

patterns before they reach handlers.

A Filter can inspect and sanitize or drop records regardless of level, directly preventing sensitive data from reaching any handler. Raising the level may hide useful INFO diagnostics and still leaks if tokens are logged at WARNING. Disabling propagation and using print do not reliably prevent leakage and undermine structured logging.

30. A module defines a custom exception hierarchy: AppError(Exception),

ValidationError(AppError), and NotFoundError(AppError). A caller uses except

AppError as e. Which behavior is expected when a ValidationError is raised?

A. The handler catches ValidationError because it is a subclass of AppError. B. The handler does not catch ValidationError because only exact type matches are caught. C. The handler catches it only if ValidationError is listed first in the except tuple. D. The handler catches it only if AppError is also raised in the same try block.

Answer: A. The handler catches ValidationError because it is a subclass of

AppError.

Python's except matches subclasses, so catching AppError also catches ValidationError and NotFoundError. Exact-type matching is not required, and ordering within a single except clause is irrelevant here. The presence of other raises in the block does not affect matching.

31. A team runs Bandit on a Python module and it flags `subprocess.Popen(cmd,

shell=True)in a function wherecmd` is assembled from a config file. Which

remediation most directly eliminates the injection class while preserving the ability

to pass arguments?

A. Wrap the call in try/except and log the exception B. Replace shell=True with shell=False and pass an argument list (e.g., shlex.split or explicit list) C. Add # nosec to suppress the finding D. URL-encode the config values before interpolation

Answer: B. Replace shell=True with shell=False and pass an argument list (e.g.,

shlex.split or explicit list)

shell=True invokes the shell, so metacharacters in cmd become injectable; passing an argument list with shell=False (or shlex.split) prevents shell interpretation. try/except, # nosec, and URL-encoding do not remove the shell parsing vulnerability.

32. A developer configures logging.basicConfig(level=logging.INFO) and then calls

logging.debug('token=%s', token) in a hot path. Which statement about runtime

behavior and security is most accurate?

A. The token is logged because basicConfig overrides the logger's effective level B. The message is not emitted because DEBUG < INFO, so the token is not written to the log C. The message is emitted but the token is masked by the logging module D. The message is emitted at WARNING level due to level coercion

Answer: B. The message is not emitted because DEBUG < INFO, so the token is

not written to the log

The root logger's effective level is INFO, so DEBUG records are filtered before emission; the token is not logged. The logging module does not mask secrets, does not coerce levels, and basicConfig does not force DEBUG emission.

33. A function is expected to raise ValueError for malformed input. Under `python

-O`, which assertion strategy still enforces this contract in production?

A. assert isinstance(x, str), 'x must be str' B. assert x, 'x must be truthy' C. if not isinstance(x, str): raise ValueError('x must be str') D. assert x is not None and isinstance(x, str)

Answer: C. if not isinstance(x, str): raise ValueError('x must be str')

Under -O, assert statements are stripped, so only an explicit raise survives optimization. Options A, B, and D are all assert-based and vanish, breaking the contract in production.

36. A pytest suite uses @pytest.mark.parametrize to test a sanitizer. Which

property best distinguishes a unit test from a property-based test in this context?

A. Parametrize runs the same assertion on fixed inputs; property-based tests generate inputs and check invariants B. Parametrize is only for performance tests C. Property-based tests require a database fixture D. Parametrize cannot assert on exceptions

Answer: A. Parametrize runs the same assertion on fixed inputs; property-based

tests generate inputs and check invariants

Parametrize enumerates explicit cases, while property-based frameworks (e.g., Hypothesis) generate inputs to falsify invariants, often finding edge cases. The other options misstate pytest capabilities.

37. A logging handler writes to a file shared by multiple processes. Which

configuration most reliably prevents interleaved or lost records under concurrent

writes?

A. Use a single FileHandler with default buffering B. Use a RotatingFileHandler with a small maxBytes C. Use a QueueHandler feeding a single logging process/thread that owns the file D. Set logging.raiseExceptions = False

Answer: C. Use a QueueHandler feeding a single logging process/thread that owns

the file

A QueueHandler with a dedicated consumer serializes writes, avoiding interleaving and loss across processes. RotatingFileHandler does not coordinate processes, default buffering can interleave, and raiseExceptions only affects error reporting.

38. A security review finds except: pass around a crypto operation. Which

remediation best aligns with fail-closed design and auditability?

A. Replace with except Exception: continue B. Catch specific exceptions, log with structured context, and re-raise or abort the operation C. Wrap the call in a retry loop with no logging D. Convert the bare except to except BaseException: pass

Answer: B. Catch specific exceptions, log with structured context, and re-raise or

abort the operation

Fail-closed requires catching specific exceptions, recording auditable context, and aborting or re-raising rather than silently continuing. The other options either swallow errors, broaden the catch, or omit logging, all weakening security posture.

39. A CI pipeline runs bandit -r src and pytest --cov=src. A developer adds `#

nosec` to silence a high-severity finding. What is the most appropriate governance

response?

A. Accept it because nosec is a standard suppression B. Require a documented justification and a compensating control, and track the suppression in the risk register C. Delete the bandit step to avoid noise D. Increase the coverage threshold to compensate

Answer: B. Require a documented justification and a compensating control, and

track the suppression in the risk register

Suppressions must be justified, reviewed, and tracked with compensating controls to maintain risk visibility. Accepting blindly, removing scanning, or substituting coverage thresholds does not address the underlying risk.