Docsity

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

Toggle sidebar
bg1
WGU D385 Task 1 Complete Practice Guide
Software Security & Testing Static Analysis, Pyth,
Exams of Computer Security - Complete 50
Verified Q&A with Answers & Rationales for Exam
Prep
Q1
Which SAST finding best explains why `cur.execute(f"SELECT * FROM u WHERE n='{name}'")` is
CWE-89?
A. String interpolation lets attacker-controlled input alter SQL syntax, so the parser treats data as code.
B. The f-string is slower than a prepared statement, causing a timing side channel exploitable via blind
SQLi.
C. The cursor object is not closed, leaking connections that permit unauthorized query replay.
D. The database driver auto-escapes quotes only for literal strings, so f-strings bypass TLS.
Answer: A
Rationale: CWE-89 arises because f-string interpolation merges untrusted data into the SQL grammar,
allowing syntax injection; parameterized queries keep data separate from code. B confuses performance
with injection, C describes a resource leak (CWE-404), and D is a fabricated TLS claim unrelated to SQL
parsing.
Q2
A branch has two conditions `A and B`; which test set achieves full MC/DC with the fewest cases?
A. TT, FF
B. TT, FT, TF
C. TT, FT, TF, FF
D. TT, TF, FT, FF, plus TT with A inverted
Answer: B
Rationale: MC/DC requires each condition to independently affect the outcome: TT (baseline), FT (A
varies, B fixed true), TF (B varies, A fixed true) - three cases suffice for two conditions. TT/FF gives only
branch coverage, four cases is redundant, and D over-specifies beyond MC/DC.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

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, Pyth,

Exams of Computer Security - Complete 50

Verified Q&A with Answers & Rationales for Exam

Prep

Q

Which SAST finding best explains why cur.execute(f"SELECT * FROM u WHERE n='{name}'") is CWE-89?

A. String interpolation lets attacker-controlled input alter SQL syntax, so the parser treats data as code. B. The f-string is slower than a prepared statement, causing a timing side channel exploitable via blind SQLi. C. The cursor object is not closed, leaking connections that permit unauthorized query replay. D. The database driver auto-escapes quotes only for literal strings, so f-strings bypass TLS.

Answer: A Rationale: CWE-89 arises because f-string interpolation merges untrusted data into the SQL grammar, allowing syntax injection; parameterized queries keep data separate from code. B confuses performance with injection, C describes a resource leak (CWE-404), and D is a fabricated TLS claim unrelated to SQL parsing.

Q

A branch has two conditions A and B; which test set achieves full MC/DC with the fewest cases?

A. TT, FF B. TT, FT, TF C. TT, FT, TF, FF D. TT, TF, FT, FF, plus TT with A inverted

Answer: B Rationale: MC/DC requires each condition to independently affect the outcome: TT (baseline), FT (A varies, B fixed true), TF (B varies, A fixed true) - three cases suffice for two conditions. TT/FF gives only branch coverage, four cases is redundant, and D over-specifies beyond MC/DC.

Which remediation most directly eliminates the CWE-502 risk in pickle.loads(request.data)?

A. Wrap the call in try/except and log exceptions to a SIEM. B. Replace pickle with a schema-validated JSON parser and explicit type checks. C. Restrict pickle to protocol 0, which cannot execute reduce. D. Hash the payload with SHA-256 before deserializing.

Answer: B Rationale: Insecure deserialization (CWE-502) is eliminated only by avoiding pickle on untrusted data and using a safe, schema-validated format such as JSON with type enforcement. try/except does not prevent gadget execution, protocol 0 still supports reduce, and hashing does not prevent deserialization of attacker-supplied bytes.

Q

A linter flags subprocess.call('ls ' + user_dir, shell=True). Which fix best satisfies CWE-78 and ASVS?

A. Quote user_dir with shlex.quote and keep shell=True. B. Use subprocess.run(['ls', user_dir], shell=False, check=True). C. Prepend 'sudo' to reduce privilege of injected commands. D. Base64-encode user_dir before concatenation.

Answer: B Rationale: CWE-78 is mitigated by avoiding the shell and passing an argument list, so user_dir cannot introduce metacharacters. shlex.quote reduces but does not eliminate risk with shell=True, sudo escalates rather than mitigates, and base64 encoding is reversible and irrelevant to shell parsing.

Q

Which statement about coverage metrics best guides a D385 test-plan justification?

A. 100% statement coverage guarantees absence of security defects. B. Branch coverage subsumes path coverage for all loop-containing functions. C. High branch coverage with weak oracles can still miss injection vulnerabilities. D. MC/DC is required by OWASP ASVS for every Python module.

Answer: C Rationale: Coverage measures execution, not assertion strength; without security-relevant oracles, injection flaws can pass. Statement coverage never proves defect absence, branch coverage does not subsume path coverage with loops, and ASVS does not mandate MC/DC universally.

Using random.random() to generate a session token is flagged. Which CWE and correct replacement apply?

A. CWE-338; use secrets.token_urlsafe() backed by the OS CSPRNG. B. CWE-327; use MD5 of random.random() for speed. C. CWE-759; salt random.random() with the username. D. CWE-311; encrypt the token with AES-ECB before storage.

Answer: A Rationale: random is a Mersenne Twister PRNG unsuitable for secrets (CWE-338); secrets.token_urlsafe uses os.urandom/CSPRNG. MD5, username salting of a weak PRNG, and ECB encryption do not fix predictability and introduce additional weaknesses.

Q

A team must prioritize CWE-798 findings. Which rationale aligns best with NIST SP 800-218 SSDF?

A. Hardcoded credentials are low risk because they are inside the repo, not exposed. B. Secrets in VCS are high risk: they persist in history and require rotation plus secret scanning in CI. C. CWE-798 can be closed by adding the secret to .gitignore in the next commit. D. CWE-798 is only relevant to compiled languages, not Python.

Answer: B Rationale: SSDF PW.4/PW.7 and RV practices treat embedded secrets as high risk due to history persistence; remediation requires rotation and automated secret scanning. Repo location does not reduce exposure, .gitignore does not purge history, and Python is equally affected.

Q

In Python, which Bandit check identifies use of assert statements that may be stripped with -O?

A. B B. B C. B D. B

Answer: A Rationale: Bandit B101 flags assert_used because assertions are removed when Python runs with -O, potentially disabling security checks. B301 detects pickle, B404 flags subprocess import, and B602 flags shell=True in subprocess calls, so they do not target assert statements.

Which CWE maps most directly to Python's os.system() command injection risk?

A. CWE-89 SQL Injection B. CWE-78 OS Command Injection C. CWE-79 Cross-site Scripting D. CWE-22 Path Traversal

Answer: B Rationale: CWE-78 is Improper Neutralization of Special Elements used in an OS Command, which is exactly the risk when os.system() passes unsanitized input to a shell. CWE-89 concerns SQL, CWE- concerns browser script injection, and CWE-22 concerns file path manipulation, so none is the direct mapping.

Q

Which pytest feature best supports parameterized security test cases for input validation?

A. pytest.mark.parametrize B. pytest.fixture(scope='session') C. pytest.mark.skipif D. pytest.raises context manager

Answer: A Rationale: pytest.mark.parametrize runs the same test logic against multiple input/output sets, ideal for validating many malicious payloads. Fixtures manage setup/teardown, skipif conditionally skips tests, and pytest.raises asserts exceptions, but none directly parameterizes input validation cases.

Q

A SAST tool reports a taint flow from request.args to eval(). Which remediation best preserves functionality?

A. Replace eval() with ast.literal_eval() for literal parsing B. Wrap eval() in a try/except block C. Encode the input using base64 before eval() D. Add a comment suppressing the SAST finding

Answer: A Rationale: ast.literal_eval() safely evaluates only Python literals, eliminating arbitrary code execution while supporting literal parsing needs. Exception handling does not prevent code execution, base encoding is reversible and still unsafe, and suppression hides rather than fixes the vulnerability.

Which OWASP Top 10 2021 category most directly encompasses insecure deserialization in Python pickle?

A. A03: Injection B. A08: Software and Data Integrity Failures C. A02: Cryptographic Failures D. A05: Security Misconfiguration

Answer: B Rationale: A08: Software and Data Integrity Failures covers insecure deserialization because it involves trusting data without integrity verification. A03 focuses on injection like SQL/OS command, A02 on cryptography, and A05 on configuration, so they are not the primary mapping.

Q

When reporting a SAST finding, which element is most critical for developers to prioritize remediation?

A. CWE identifier and data-flow trace B. Tool version and scan duration C. Line count of the affected file D. Developer name who wrote the code

Answer: A Rationale: A CWE identifier classifies the weakness and the data-flow trace shows how tainted input reaches the sink, enabling targeted fixes. Tool metadata, file size, and authorship do not convey the vulnerability's nature or exploit path.

Q

Which Python construct most reliably enforces least privilege for a subprocess call?

A. subprocess.run(cmd, shell=False) B. os.popen(cmd) C. subprocess.call(cmd, shell=True) D. eval(subprocess.check_output(cmd))

Answer: A Rationale: Using shell=False avoids invoking a shell, preventing shell metacharacter injection and reducing privilege exposure. os.popen and shell=True invoke a shell, and eval on subprocess output enables code execution, so they violate least privilege.

A SAST tool reports a taint flow from request.args.get('q') to cursor.execute('SELECT * FROM t WHERE name=' + q). Which remediation best eliminates the vulnerability?

A. Wrap q in html.escape() before concatenation B. Replace string concatenation with a parameterized query using placeholders C. Add a WAF rule blocking SQL keywords in q D. Encode q with base64 before concatenation

Answer: B Rationale: Parameterized queries separate code from data, neutralizing SQL injection at the source (CWE-89); the SAST taint flow is broken because q is bound, not concatenated. html.escape targets XSS (CWE-79), not SQL context; WAF and base64 are compensating/obfuscation measures that do not remove the root-cause taint flow.

Q

Given def f(x): return eval('x' + input()), which CWE most precisely classifies the primary weakness?

A. CWE-79 Cross-site Scripting B. CWE-798 Hard-coded Credentials C. CWE-95 Eval Injection (Code Injection) D. CWE-22 Path Traversal

Answer: C Rationale: Passing untrusted input into eval() permits arbitrary Python code execution, the defining characteristic of CWE-95 (Improper Neutralization of Directives in Dynamically Evaluated Code: 'Eval Injection'). XSS applies to browser output contexts, hard-coded credentials involve embedded secrets, and path traversal concerns filesystem path manipulation-none match eval() code execution.

Q

A test suite achieves 100% statement coverage but misses a divide-by-zero branch. Which coverage criterion would most likely expose the gap?

A. Line coverage B. Function coverage C. Branch (decision) coverage D. Loop coverage

Answer: C Rationale: Branch coverage requires each decision outcome (true/false) to be exercised; the untested else/zero path would be flagged even when every line executes. Statement/line and function coverage can be satisfied by a single path; loop coverage targets iteration counts, not the missing decision outcome.

Which pytest construct most directly verifies that a function raises ValueError for negative input?

A. assert func(-1) == None B. with pytest.raises(ValueError): func(-1) C. @pytest.mark.xfail D. pytest.skip('negative')

Answer: B Rationale: pytest.raises is the idiomatic context manager asserting that the expected exception type is raised, confirming the error-handling branch. Comparing to None tests a return value, xfail marks an expected failure without asserting the type, and skip bypasses execution entirely.

Q

A linter reports E501 and W0611 (unused import) in a Python module. Which statement about these findings is most accurate?

A. Both are security vulnerabilities per OWASP Top 10 B. E501 is style; W0611 is a maintainability defect that can mask dead code C. Both are false positives and should be globally suppressed D. W0611 indicates a SQL injection risk

Answer: B Rationale: PEP 8/line-length (E501) is stylistic, whereas unused imports (W0611) are code-quality issues that may hide dead or unintended dependencies and complicate review-relevant to ISO/IEC 25010 maintainability. Neither is an OWASP Top 10 vulnerability, blanket suppression is poor practice, and unused imports do not imply SQL injection.

Q

A developer uses assert user.is_admin to gate an admin action. Why is this a security defect in optimized Python?

A. assert statements are removed when Python runs with -O, disabling the check B. assert only works with integers C. assert raises TypeError for booleans D. assert executes asynchronously

Answer: A Rationale: The -O optimization flag strips assert statements, so authorization checks written as asserts vanish in production-CWE-617-style reliance on assertions for security. Asserts handle booleans fine, do not raise TypeError for them, and are synchronous; the core issue is conditional removal under optimization.

A test plan must cover boundary values for def grade(score) rejecting scores outside 0-100. Which set best applies boundary value analysis?

A. {50} B. {-1, 0, 100, 101} C. {0, 50, 100} D. {99, 100, 101, 102}

Answer: B Rationale: Boundary value analysis tests just inside and just outside each limit; for the inclusive range 0-100 the critical values are -1, 0, 100, and 101. A single midpoint, only in-range values, or shifted values miss the off-by-one defects at the actual boundaries.

Q

A SAST tool flags a taint flow from request.args to cursor.execute. Which remediation best preserves functionality while eliminating CWE-89?

A. Escape single quotes using str.replace before concatenating the SQL string B. Replace string concatenation with a parameterized query using bound placeholders C. Apply html.escape to the user input before building the SQL statement D. Wrap the execute call in a try/except to suppress database error messages

Answer: B Rationale: Parameterized queries separate code from data, so the DBMS treats user input as a value, not SQL syntax, definitively removing the injection sink (CWE-89). Manual escaping (A) and HTML encoding (C) are context-mismatched and bypassable; exception handling (D) hides errors without fixing the vulnerability.

Q

Which Python construct most reliably defeats interprocedural taint tracking in a flow-insensitive SAST engine?

A. Passing tainted data through a list comprehension B. Storing tainted data in an instance attribute set in init C. Dynamically invoking a sanitizer via getattr with a computed name D. Concatenating two tainted strings with the += operator

Answer: C Rationale: A computed getattr call defeats flow-insensitive engines because the callee name is not statically resolvable, so the engine cannot confirm the sanitizer ran. List comprehensions (A), instance attributes (B), and += concatenation (D) are all modeled by modern interprocedural analyses.

A code review finds secrets hard-coded in source. Which control aligns with NIST SP 800-218 (SSDF) and OWASP guidance?

A. Encrypt the secret with a key stored in the same repository B. Externalize secrets to a managed secret store and rotate on exposure C. Obfuscate the literal using base64 encoding in the source file D. Add the file to .gitignore after the secret has been committed

Answer: B Rationale: SSDF PW.4 and OWASP Secrets Management require secrets to live outside source in a managed store with rotation, since committed secrets are permanently exposed in history. Base64 (C) is reversible, same-repo keys (A) add no protection, and .gitignore (D) does not purge history.

Q

Which Python pattern most directly enables a CWE-502 unsafe deserialization vulnerability in a web service?

A. json.loads on a request body validated against a schema B. pickle.loads on a base64-decoded cookie supplied by the client C. yaml.safe_load on a configuration file read from disk D. xml.etree.ElementTree.parse on a trusted internal feed

Answer: B Rationale: pickle.loads executes arbitrary reduce payloads, so deserializing untrusted client data yields remote code execution (CWE-502). json.loads (A) and yaml.safe_load (C) do not execute code; ElementTree (D) is limited to XML parsing and the source is trusted.

Q

A finding states: 'User input reaches os.path.join then open()'. Which CWE most precisely classifies this?

A. CWE-89 SQL Injection B. CWE-79 Cross-site Scripting C. CWE-22 Path Traversal D. CWE-798 Hard-coded Credentials

Answer: C Rationale: Unsantized input flowing into a path join and file open permits '../' sequences to escape the intended directory, which is CWE-22 Path Traversal. SQL injection (A) concerns database queries, XSS (B) concerns browser output, and hard-coded credentials (D) concern embedded secrets.

A team wants mutation testing to assess test-suite strength. Which outcome best indicates weak tests?

A. High mutation score with few surviving mutants B. Low mutation score with many surviving mutants C. High statement coverage with low branch coverage D. Low cyclomatic complexity with high function count

Answer: B Rationale: Mutation score is killed mutants divided by total mutants; many survivors mean the suite fails to detect injected faults, signaling weak assertions. High mutation score (A) indicates strong tests; coverage (C) and complexity (D) are structural metrics, not mutation outcomes.

Q

A SAST report lists a finding with no CWE, no data-flow trace, and 'informational' severity. What is the best triage action?

A. Immediately remediate as a critical vulnerability B. Suppress the rule globally to reduce noise C. Validate the finding manually and document the disposition D. Escalate to the vendor without code review

Answer: C Rationale: Findings lacking CWE mapping and a reproducible trace require manual validation to confirm exploitability before any action, with the disposition documented for auditability. Blind remediation (A) wastes effort, global suppression (B) hides real issues, and vendor escalation (D) skips the required review.

Q

A SAST tool reports 'B608: possible SQL injection' for a Python query built with f-strings. Which remediation most directly satisfies CWE-89?

A. Escape single quotes with str.replace before interpolation B. Use parameterized queries with DB-API placeholders and bind parameters C. Wrap the query in a try/except to catch database errors D. Apply html.escape() to all user-supplied values

Answer: B Rationale: Parameterized queries separate code from data, which is the canonical fix for CWE-89 SQL injection. Manual escaping is error-prone and bypassable; exception handling does not prevent injection; html.escape is for HTML contexts, not SQL.

A team must document a SAST finding for a rubric. Which element is most essential to enable reproducible remediation?

A. The developer's name and commit timestamp B. CWE identifier, file/line, evidence snippet, and remediation guidance C. The scanner's version and license key D. A screenshot of the IDE with the warning highlighted

Answer: B Rationale: Reproducible findings require a standardized weakness ID (CWE), precise location, code evidence, and actionable fix guidance, aligning with SSDF and ASVS reporting expectations. Metadata like author or scanner license does not support remediation.

Q

Which Python pattern best mitigates CWE-798 hardcoded credentials while preserving testability in a CI pipeline?

A. Store secrets in a committed .env file encrypted with a static key B. Load secrets from environment variables or a secrets manager at runtime C. Obfuscate credentials with base64 encoding in source D. Keep credentials in a private repository branch

Answer: B Rationale: Runtime injection from environment variables or a secrets manager keeps credentials out of source, satisfying CWE-798 and SSDF PS.1. Base64 is reversible; committed encrypted files with static keys and private branches still expose secrets.

Q

A code review finds subprocess.call(user_input, shell=True). Which change most directly addresses CWE-78?

A. Set shell=False and pass arguments as a list B. Prefix the command with 'sudo' C. Log the command before execution D. Wrap the call in a timeout

Answer: A Rationale: Disabling the shell and passing an argument list prevents shell metacharacter injection (CWE-78). Logging, timeouts, and privilege changes do not remove the injection vector.

Which ISO/IEC 25010 quality characteristic is most directly improved by adding comprehensive unit tests with mutation testing?

A. Functional suitability B. Reliability C. Portability D. Usability

Answer: B Rationale: Mutation testing strengthens fault detection, improving reliability (fault tolerance and maturity) under ISO/IEC 25010. It does not directly improve functional suitability, portability, or usability.

Q

A linter flags 'B506: yaml.load'. Which replacement both preserves YAML parsing and eliminates arbitrary object instantiation?

A. yaml.load(stream, Loader=yaml.FullLoader) B. yaml.safe_load(stream) C. json.loads(stream) D. eval(stream)

Answer: B Rationale: yaml.safe_load restricts constructors to safe types, preventing code execution (CWE-502). FullLoader still permits some unsafe tags historically; json.loads changes format; eval is strictly worse.

Q

When designing branch coverage tests for a function with a short-circuit 'and', which subtlety must be addressed to avoid false confidence?

A. Each operand must independently evaluate true and false across tests B. Only the overall decision outcome needs both true and false C. Statement coverage subsumes the need for operand-level tests D. Short-circuit operators are equivalent to bitwise operators for coverage

Answer: A Rationale: Short-circuit evaluation can skip operands, so branch coverage may miss faults unless each operand is exercised both ways (condition/operand coverage). Overall decision coverage and statement coverage do not guarantee operand-level testing; short-circuit and bitwise semantics differ.