Docsity

WGU D385 Software Security and Testing Python Secure Coding Practice Workbook 40 Exercise, Exams of Computer Security

Toggle sidebar
bg1
Page 1
WGU D385 SOFTWARE SECURITY AND TESTING
PYTHON SECURE-CODING PRACTICE
WORKBOOK 40 EXERCISES + 4 CAPSTONES 2026
49 QUESTIONS
TABLE OF CONTENTS
# TOPIC
1 Apply threat modeling and secure design principles to identify and mitigate Python-specific vulnerabilities
2 Implement and evaluate cryptographic, input-validation, and deserialization defenses in Python
applications
3 Design rigorous test suites using fuzzing, property-based testing, and mutation testing to uncover security
defects
4 Integrate security controls into CI/CD pipelines and assess software supply-chain integrity
5 WGU D385 Software Security and Testing Python Secure
6 Coding Practice Workbook 40 Exercises + 4 Capstones 2026
7 Foundations of Software Security and Testing with Python
8 Applied Software Security and Testing with Python
9 Advanced Software Security and Testing with Python
10 Software Security and Testing with Python Review
ABSTRACT
This study document brings together 49 carefully worded exam questions drawn from WGU D385
Software Security and Testing Python Secure-Coding Practice Workbook 40 Exercises + 4
Capstones 2026, with the strongest emphasis placed on Apply threat modeling and secure design
principles to identify and mitigate Python-specific vulnerabilities, Implement and evaluate
cryptographic, input-validation, and deserialization defenses in Python applications, Design
rigorous test suites using fuzzing, property-based testing and and mutation testing to uncover
security defects. Every item follows the wording style and level of reasoning you meet in the real
paper, and each one is paired with a clear rationale so the correct choice is never a guess. Work
through the set at your own pace, mark the questions that slow you down, then come back to them
until the reasoning feels automatic. Learners who revise this way walk into the exam room
recognising the pattern behind the questions instead of meeting them for the first time. Keep going
- steady, honest practice is what turns a difficult paper into a comfortable pass.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download WGU D385 Software Security and Testing Python Secure Coding Practice Workbook 40 Exercise and more Exams Computer Security in PDF only on Docsity!

WGU D385 SOFTWARE SECURITY AND TESTING

PYTHON SECURE-CODING PRACTICE

WORKBOOK 40 EXERCISES + 4 CAPSTONES 2026

49 QUESTIONS

TABLE OF CONTENTS

# TOPIC 1 Apply threat modeling and secure design principles to identify and mitigate Python-specific vulnerabilities 2 Implement and evaluate cryptographic, input-validation, and deserialization defenses in Python applications 3 Design rigorous test suites using fuzzing, property-based testing, and mutation testing to uncover security defects 4 Integrate security controls into CI/CD pipelines and assess software supply-chain integrity 5 WGU D385 Software Security and Testing Python Secure 6 Coding Practice Workbook 40 Exercises + 4 Capstones 2026 7 Foundations of Software Security and Testing with Python 8 Applied Software Security and Testing with Python 9 Advanced Software Security and Testing with Python 10 Software Security and Testing with Python Review

ABSTRACT

This study document brings together 49 carefully worded exam questions drawn from WGU D Software Security and Testing Python Secure-Coding Practice Workbook 40 Exercises + 4 Capstones 2026, with the strongest emphasis placed on Apply threat modeling and secure design principles to identify and mitigate Python-specific vulnerabilities, Implement and evaluate cryptographic, input-validation, and deserialization defenses in Python applications, Design rigorous test suites using fuzzing, property-based testing and and mutation testing to uncover security defects. Every item follows the wording style and level of reasoning you meet in the real paper, and each one is paired with a clear rationale so the correct choice is never a guess. Work through the set at your own pace, mark the questions that slow you down, then come back to them until the reasoning feels automatic. Learners who revise this way walk into the exam room recognising the pattern behind the questions instead of meeting them for the first time. Keep going

  • steady, honest practice is what turns a difficult paper into a comfortable pass.

Q1 APPLY THREAT MODELING AND SECURE DESIGN PRINCIPLES TO IDENTIFY AND

MITIGATE PYTHON-SPECIFIC VULNERABILITIES

A Flask API uses its default session cookie signing. An attacker who obtains a

valid session cookie from a user can forge arbitrary session contents without

knowing the server's secret key. Which property of the underlying construction is

most directly responsible?

A. The cookie is encrypted with AES-CBC but lacks an HMAC, allowing bit-flipping. B. The signing uses a length-extension-vulnerable hash over a secret-prefix MAC. CORRECT C. The cookie is signed with a per-process random key regenerated on each worker restart. D. The session serializer permits arbitrary object instantiation during deserialization. RATIONALE: Flask's default secure cookie uses itsdangerous with an HMAC, but naive secret-prefix constructions (e.g., SHA1(secret||data)) are vulnerable to length-extension attacks, allowing forgery without the key. AES-CBC without HMAC is a different flaw not present here; per-process key regeneration would invalidate cookies, not enable forgery; and arbitrary deserialization is a separate RCE risk, not cookie forgery.

Q2 APPLY THREAT MODELING AND SECURE DESIGN PRINCIPLES TO IDENTIFY AND

MITIGATE PYTHON-SPECIFIC VULNERABILITIES

A service must verify user-supplied passwords. The team proposes storing

Argon2id hashes with parameters m=64 MiB, t=3, p=4. A reviewer argues for

bcrypt cost 12 instead. Which statement best justifies the Argon2id choice under

current best practice?

A. Argon2id is preferred because it is memory-hard, resisting GPU/ASIC parallelism that bcrypt cannot, while bcrypt remains acceptable but weaker against such attackers. CORRECT B. Argon2id is required by NIST SP 800-63B, whereas bcrypt is explicitly deprecated for all federal systems. C. bcrypt is vulnerable to length-extension attacks, while Argon2id uses a sponge construction immune to them. D. Argon2id's parallelism parameter p=4 makes it faster than bcrypt at equivalent security, reducing server load. RATIONALE: Argon2id's memory-hardness specifically thwarts GPU/ASIC parallel attacks that bcrypt's fixed memory footprint cannot match; bcrypt remains acceptable but less resistant. NIST does not mandate Argon2id nor deprecate bcrypt; length-extension is irrelevant to password hashing; and higher p increases resource use, not speed at equivalent security.

Q5 APPLY THREAT MODELING AND SECURE DESIGN PRINCIPLES TO IDENTIFY AND

MITIGATE PYTHON-SPECIFIC VULNERABILITIES

A CI pipeline runs bandit, safety, and pip-audit on every PR. A developer adds a

dependency with a known CVE but pins it to a commit hash. Which control most

effectively prevents this from reaching production?

A. Requiring signed commits from all contributors. B. Enforcing a Software Bill of Materials (SBOM) and blocking builds on critical CVEs via policy-as-code. CORRECT C. Running the test suite with -W error to treat warnings as errors. D. Enabling branch protection requiring two approvals. RATIONALE: An SBOM combined with policy-as-code gates can detect and block known-vulnerable dependencies regardless of pinning method, directly addressing supply-chain risk. Signed commits, warning flags, and approvals do not evaluate dependency vulnerability status.

Q6 IMPLEMENT AND EVALUATE CRYPTOGRAPHIC, INPUT-VALIDATION, AND

DESERIALIZATION DEFENSES IN PYTHON APPLICATIONS

A multithreaded Python service uses a shared dict guarded by a threading.Lock. A

race condition still corrupts data under high load. Which is the most likely cause?

A. The GIL makes the lock redundant, so the lock is optimized away. B. Some code paths mutate the dict without acquiring the lock. CORRECT C. dict operations are not atomic even under the GIL. D. The lock must be an RLock to be effective across threads. RATIONALE: A lock only protects critical sections where it is actually acquired; any unguarded mutation path breaks mutual exclusion. The GIL does not eliminate the need for locks, dict operations are not guaranteed atomic for compound updates, and RLock is only needed for reentrant acquisition, not basic correctness.

Q7 IMPLEMENT AND EVALUATE CRYPTOGRAPHIC, INPUT-VALIDATION, AND

DESERIALIZATION DEFENSES IN PYTHON APPLICATIONS

A team uses pickle to cache ML models. An attacker who can write to the cache

directory achieves RCE. Which mitigation best preserves functionality while

eliminating the vulnerability?

A. Restrict cache directory permissions to the service user. B. Replace pickle with a safe serialization format like JSON or safetensors and validate integrity. CORRECT C. Sign the pickle files with HMAC and verify before loading. D. Run the unpickling in a subprocess with reduced privileges. RATIONALE: Pickle is inherently unsafe for untrusted data because it can execute arbitrary code during deserialization; replacing it with a data-only format removes the attack surface. Permissions, HMAC signing, and sandboxing are mitigations that still leave risk if the key or sandbox is compromised.

Q8 IMPLEMENT AND EVALUATE CRYPTOGRAPHIC, INPUT-VALIDATION, AND

DESERIALIZATION DEFENSES IN PYTHON APPLICATIONS

A security test uses mutation testing to evaluate a test suite's effectiveness. After

mutating a boundary check from < to <=, all tests still pass. What does this

most directly indicate?

A. The mutation is equivalent and cannot be killed by any test. B. The test suite lacks a case exercising the exact boundary value. CORRECT C. The mutation operator is invalid and should be excluded. D. The code under test is not covered by any test. RATIONALE: A surviving non-equivalent mutant at a boundary indicates missing test cases at that boundary; adding a test for the exact threshold value would kill it. Equivalent mutants are rare and require proof, the operator is standard, and lack of coverage would typically be reported separately.

Q11 DESIGN RIGOROUS TEST SUITES USING FUZZING, PROPERTY-BASED TESTING, AND

MUTATION TESTING TO UNCOVER SECURITY DEFECTS

A Flask endpoint builds a shell command as f"nslookup {host}" and calls

subprocess.run(cmd, shell=True). Which remediation most directly eliminates

command injection while preserving shell features like pipes?

A. Escape the host with shlex.quote() before interpolation. CORRECT B. Replace shell=True with shell=False and pass a list of arguments. C. Validate host against a regex allowing only [A-Za-z0-9.-]. D. Run the command under a restricted user with no shell access. RATIONALE: shlex.quote() neutralizes metacharacters while still allowing a shell pipeline to be used, which is the only option that preserves pipes and directly blocks injection. shell=False with a list disables pipes, regex validation is brittle and may reject valid hosts, and least-privilege limits impact but does not remove the injection vector.

Q12 DESIGN RIGOROUS TEST SUITES USING FUZZING, PROPERTY-BASED TESTING, AND

MUTATION TESTING TO UNCOVER SECURITY DEFECTS

A login handler stores passwords with PBKDF2-HMAC-SHA256, 100,000 iterations,

16-byte salt. Which change best aligns with current OWASP guidance for

password storage?

A. Increase iterations to 600,000 and keep SHA-256. B. Switch to bcrypt with cost factor 10 and 8-byte salt. C. Use Argon2id with memory cost 19 MiB, iterations 2, parallelism 1. CORRECT D. Use scrypt with N=2^14, r=8, p=1 and 8-byte salt. RATIONALE: OWASP's current Password Storage Cheat Sheet recommends Argon2id with m=19 MiB, t=2, p=1 as the first choice because it is memory-hard and resists GPU cracking. PBKDF2 remains acceptable but weaker; bcrypt cost 10 and scrypt with 8-byte salt are below current recommended parameters.

Q13 DESIGN RIGOROUS TEST SUITES USING FUZZING, PROPERTY-BASED TESTING, AND

MUTATION TESTING TO UNCOVER SECURITY DEFECTS

A code review finds: cursor.execute('SELECT * FROM users WHERE name = %s' %

name). Which vulnerability class does this represent, and which fix is correct?

A. Command injection; use subprocess with a list. B. SQL injection via string formatting; use parameterized queries with a tuple. CORRECT C. XSS; escape the name with html.escape(). D. Path traversal; normalize with os.path.realpath(). RATIONALE: String interpolation into SQL builds attacker-controlled query text, enabling SQL injection; DB-API parameterization (execute(sql, (name,))) sends the value separately so it cannot alter query structure. The other options misclassify the flaw or apply unrelated mitigations.

Q14 DESIGN RIGOROUS TEST SUITES USING FUZZING, PROPERTY-BASED TESTING, AND

MUTATION TESTING TO UNCOVER SECURITY DEFECTS

A Django view returns HttpResponse(f"Hello {username}") where

username is user-supplied. Which mitigation is most appropriate and minimal?

A. Enable Django's CSRF middleware. B. Use django.utils.html.escape(username) or render a template with autoescaping. CORRECT C. Set the Content-Security-Policy header to 'unsafe-inline'. D. Store username in an HttpOnly cookie. RATIONALE: The reflected output of untrusted data creates XSS; escaping or using Django's autoescaping templates neutralizes it. CSRF middleware addresses forged requests, a permissive CSP worsens the problem, and HttpOnly cookies do not prevent script injection into the page.

Q17 INTEGRATE SECURITY CONTROLS INTO CI/CD PIPELINES AND ASSESS SOFTWARE

SUPPLY-CHAIN INTEGRITY

A Flask app accepts a filename and serves it with send_file(os.path.join('/data',

name)). Which input should be rejected to prevent path traversal?

A. report.pdf B. ../etc/passwd CORRECT C. subdir/report.pdf D. report_2024.pdf RATIONALE: '../etc/passwd' contains traversal sequences that escape the intended directory. The other filenames stay within /data and are legitimate; subdirectory access is safe if the resolved path is verified to remain under the base directory.

Q18 INTEGRATE SECURITY CONTROLS INTO CI/CD PIPELINES AND ASSESS SOFTWARE

SUPPLY-CHAIN INTEGRITY

A developer stores API keys in a .env file committed to the repository. Which

combination of controls best remediates the exposure?

A. Rotate the keys, remove the file from history with git filter-repo, and load secrets from a vault or environment at runtime. CORRECT B. Add .env to .gitignore and continue using the same keys. C. Encrypt the .env file with a hardcoded password in the source. D. Move the keys into a config.py module imported by the app. RATIONALE: Once committed, secrets must be rotated because history retains them; purging history and moving to a secret manager prevents recurrence. Gitignoring alone leaves exposed keys valid, and hardcoded encryption or config modules still expose secrets in source.

Q19 INTEGRATE SECURITY CONTROLS INTO CI/CD PIPELINES AND ASSESS SOFTWARE

SUPPLY-CHAIN INTEGRITY

A team wants to detect known-vulnerable dependencies in a Python project during

CI. Which tool and practice best fits a current secure SDLC?

A. Run flake8 on the source tree. B. Run bandit and treat findings as build failures. C. Run pip-audit (or safety) against requirements and fail on known CVEs. CORRECT D. Run mypy in strict mode. RATIONALE: pip-audit and safety query vulnerability databases for installed/declared dependencies, which is the correct SCA practice. flake8 and mypy are linters/type checkers, and bandit performs static analysis of first-party code, not dependency CVE detection.

Q20 INTEGRATE SECURITY CONTROLS INTO CI/CD PIPELINES AND ASSESS SOFTWARE

SUPPLY-CHAIN INTEGRITY

A service uses Python's pickle to deserialize data received from an untrusted

queue. Which statement is most accurate about the risk and mitigation?

A. pickle is safe if the payload is base64-encoded. B. pickle can execute arbitrary code via reduce; use JSON or a safe schema like protobuf instead. CORRECT C. pickle is safe when using protocol 5. D. pickle is safe if the class is defined in the same module. RATIONALE: pickle's reduce and related hooks allow arbitrary code execution during unpickling, so untrusted data must never be unpickled; JSON or schema-based formats are safe alternatives. Encoding, protocol version, and module locality do not remove the code-execution primitive.

Q23 WGU D385 SOFTWARE SECURITY AND TESTING PYTHON SECURE

A property-based test uses Hypothesis to fuzz a JSON parser. Which strategy

most effectively exposes crash-inducing inputs beyond naive random generation?

A. Generate only ASCII strings of length 1-10 to keep runtime bounded. B. Use st.recursive with dictionaries, lists, and text, letting Hypothesis shrink failures. CORRECT C. Seed the generator with a fixed random seed for reproducibility. D. Replace Hypothesis with random.choice over a curated corpus of valid JSON. RATIONALE: Recursive strategies explore nested structures and Hypothesis's shrinking yields minimal counterexamples, maximizing bug discovery. Restricting to short ASCII (A), fixing seeds (C), and sampling only valid JSON (D) miss structural edge cases.

Q24 WGU D385 SOFTWARE SECURITY AND TESTING PYTHON SECURE

An auditor notes a service logs `f"Login failed for {username} with password

{password}"`. Which control most directly satisfies OWASP logging guidance

while retaining forensic value?

A. Base64-encode the password before logging. B. Log the username and a hashed password fingerprint, never the plaintext secret. CORRECT C. Rotate log files daily to limit exposure window. D. Restrict log file permissions to root-only. RATIONALE: Secrets must never be logged; hashing preserves correlation without exposing credentials. Encoding (A) is reversible, and rotation/permissions (C, D) do not prevent secret disclosure at write time.

Q25 WGU D385 SOFTWARE SECURITY AND TESTING PYTHON SECURE

A pipeline runs pip install -r requirements.txt where one pin is requests==2.31.0

from PyPI. Which practice most reduces supply-chain risk without breaking

reproducibility?

A. Add --no-deps to skip transitive packages. B. Pin transitive dependencies with hashes via pip-compile --generate-hashes and verify them. CORRECT C. Upgrade to the latest unpinned version on every build. D. Mirror PyPI internally but skip signature verification for speed. RATIONALE: Hash-pinning locks the full dependency graph and detects tampering. --no-deps (A) breaks functionality, unpinned upgrades (C) reintroduce drift, and skipping verification (D) defeats the mirror's protective purpose.

Q26 CODING PRACTICE WORKBOOK 40 EXERCISES + 4 CAPSTONES 2026

A YAML config loader uses yaml.load(stream) on untrusted input. Which

replacement preserves legitimate YAML features while removing the

code-execution vector?

A. yaml.safe_load(stream) CORRECT B. json.loads(stream) after converting YAML to JSON C. yaml.load(stream, Loader=yaml.FullLoader) D. Wrap yaml.load in a try/except block RATIONALE: safe_load restricts to basic types, blocking arbitrary object construction. FullLoader (C) still allows some tags, JSON conversion (B) loses YAML features, and try/except (D) does not prevent execution.

Q29 CODING PRACTICE WORKBOOK 40 EXERCISES + 4 CAPSTONES 2026

A test suite uses unittest.mock.patch to stub requests.get but the production

code calls requests.Session().get. The test passes while production fails. Which

testing principle does this best illustrate?

A. Mocks should target the seam actually invoked by the code under test. CORRECT B. Integration tests are always preferable to unit tests. C. Coverage percentage guarantees correctness. D. Property-based tests eliminate the need for mocks. RATIONALE: Patching the wrong symbol creates a false positive; mocks must intercept the exact call path. The other options are overgeneralizations unrelated to this specific mocking failure.

Q30 CODING PRACTICE WORKBOOK 40 EXERCISES + 4 CAPSTONES 2026

A capstone requires constant-time comparison of an HMAC to prevent timing

leaks. Which Python construct is most appropriate?

A. if a == b: on bytes B. hmac.compare_digest(a, b) CORRECT C. hashlib.sha256(a).digest() == hashlib.sha256(b).digest() D. a.startswith(b) and len(a) == len(b) RATIONALE: compare_digest performs constant-time comparison resistant to timing attacks. Direct equality (A), hashing then comparing (C), and startswith (D) all short-circuit and leak timing information.

Q31 FOUNDATIONS OF SOFTWARE SECURITY AND TESTING WITH PYTHON

A Flask endpoint builds a filesystem path as os.path.join(BASE_DIR,

request.args.get('file')). Which implementation most reliably prevents path

traversal while still allowing legitimate nested subdirectories?

A. Reject any input containing the substring '..' before joining it to BASE_DIR. B. After joining, call os.path.realpath and verify the result starts with os.path.realpath(BASE_DIR) + os.sep. CORRECT C. Apply urllib.parse.quote to the parameter to neutralize traversal sequences. D. Use os.path.normpath on the parameter alone, then concatenate it to BASE_DIR with a string '+'. RATIONALE: Canonicalizing both the base and the joined path and comparing with a trailing separator defeats traversal via symlinks, absolute paths, and encoded variants. Substring blacklists (A) miss encoded or absolute forms, quoting (C) does not change path semantics, and normpath on the parameter alone (D) fails for absolute inputs.

Q32 FOUNDATIONS OF SOFTWARE SECURITY AND TESTING WITH PYTHON

A service verifies RS256 JWTs but accepts the token header's 'alg' field to select

the verification algorithm. Which attack does this enable, and what is the correct

remediation?

A. Algorithm confusion via 'none'/'HS256' substitution; pin the expected algorithm and reject mismatches. CORRECT B. Key ID (kid) injection; validate the kid against an allowlist of trusted keys. C. Signature stripping; require the 'typ' header to equal 'JWT'. D. Replay via 'jti' reuse; enforce short token lifetimes and a nonce cache. RATIONALE: Trusting the header-driven algorithm lets an attacker downgrade to 'none' or force HMAC verification using the public key as the secret (algorithm confusion). The fix is to pin the algorithm server-side and reject any mismatch. kid allowlisting, typ checks, and jti caches address different, though real, concerns.

Q35 FOUNDATIONS OF SOFTWARE SECURITY AND TESTING WITH PYTHON

An application stores passwords using bcrypt with cost factor 10. Which change

most directly increases resistance to offline GPU cracking without altering the

stored hash format?

A. Increase the bcrypt cost factor to 12 or higher. CORRECT B. Switch to SHA-256 with a per-user salt. C. Concatenate a global pepper to the password before hashing. D. Base64-encode the resulting hash before storage. RATIONALE: Raising the work factor increases the computational cost of each guess, directly slowing offline attacks. SHA-256 with salt (B) is fast and unsuitable for passwords, a global pepper (C) adds secrecy but not per-guess cost, and base64 encoding (D) provides no security benefit.

Q36 APPLIED SOFTWARE SECURITY AND TESTING WITH PYTHON

A team enables Django's CSRF middleware but writes a JSON API consumed by a

single-page app. Which configuration correctly preserves protection without

breaking the SPA?

A. Exempt the API views from CSRF and rely on CORS to block cross-site requests. B. Set CSRF_COOKIE_HTTPONLY to True so JavaScript cannot read the token. C. Send the CSRF token in a header (e.g., X-CSRFToken) and ensure the cookie is SameSite=Lax or Strict. CORRECT D. Disable CSRF middleware and validate the Origin header inside each view. RATIONALE: Django supports header-based CSRF tokens, and SameSite cookies prevent cross-site submission, preserving protection for SPAs. CORS (A) does not block simple cross-site requests, CSRF_COOKIE_HTTPONLY (B) breaks JavaScript token access, and manual Origin checks (D) are error-prone and incomplete.

Q37 APPLIED SOFTWARE SECURITY AND TESTING WITH PYTHON

A function uses random.random() to generate password reset tokens. Which

replacement most appropriately satisfies cryptographic unpredictability

requirements?

A. random.SystemRandom().random() seeded from os.urandom(16). B. secrets.token_urlsafe(32). CORRECT C. hashlib.sha256(str(time.time()).encode()).hexdigest(). D. uuid.uuid4().hex truncated to 16 characters. RATIONALE: secrets.token_urlsafe draws from the OS CSPRNG and is designed for security tokens. SystemRandom (A) is acceptable but the manual seeding is unnecessary and less idiomatic, time-based hashing (C) is predictable, and truncated UUIDv4 (D) reduces entropy and is not intended for secrets.

Q38 APPLIED SOFTWARE SECURITY AND TESTING WITH PYTHON

A developer uses yaml.load(user_supplied_yaml) with the default loader. Which

change best mitigates code execution risk while preserving legitimate data

parsing?

A. Replace with yaml.safe_load to restrict to standard YAML tags. CORRECT B. Wrap the call in try/except to catch parsing errors. C. Prepend a '!!python/object' guard to reject dangerous tags. D. Limit input size to 1 MB before parsing. RATIONALE: yaml.safe_load restricts parsing to standard YAML types, preventing object construction and code execution. Exception handling (B) does not stop payload execution, ad hoc tag guards (C) are incomplete, and size limits (D) address DoS, not deserialization RCE.