Docsity

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

Toggle sidebar
bg1
WGU D385 Software Security and Testing Python
Secure-Coding Practice Workbook 40 Exercises + 4 Capstones
2026
This exam assesses mastery of secure Python development, covering OWASP Top 10 vulnerabilities,
cryptographic best practices, input validation, authentication/authorization, secure testing methodologies, and
DevSecOps integration. It emphasizes hands-on application through scenario-based problems and code analysis.
It contains 48 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: Identify and mitigate common Python security
vulnerabilities such as injection, XSS, and insecure deserialization.; Implement secure authentication, session
management, and access control mechanisms in Python applications.; Apply cryptographic primitives correctly
using libraries like cryptography and hashlib.; Integrate security testing (SAST, DAST, fuzzing) into CI/CD
pipelines.. 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 70%. Aligned with This exam adheres to US
university standards for graduate-level assessment, aligning with ACM/IEEE curricula and industry best
practices (OWASP, NIST). standards and reflects the question style commonly seen on accredited program
Section 1: General (Questions 1-48)
1A Flask application uses the following code to render a user profile page: `return
render_template_string('<h1>Welcome, %s!</h1>' % username)`. Which
vulnerability is most directly introduced, and what is the most robust remediation?
A) Cross-Site Scripting (XSS); escape the username using `markupsafe.escape`
before formatting.
B) Server-Side Template Injection (SSTI); use `render_template` with a static
template file and pass `username` as a context variable.
C) SQL Injection; parameterize the query using SQLAlchemy.
D) Command Injection; sanitize the username with `shlex.quote`.
Answer: B
Rationale: The code uses string formatting to inject user input into a template string,
allowing SSTI if the input contains template syntax. The robust fix is to use
`render_template` with a separate template file, which auto-escapes and prevents
injection. XSS is possible but SSTI is more severe and directly caused by the
pattern; SQL and command injection are unrelated.
2In a Django application, which setting combination ensures that session cookies
are protected against interception and cross-site request forgery?
A) SESSION_COOKIE_SECURE = True, SESSION_COOKIE_HTTPONLY =
True, CSRF_COOKIE_SECURE = True
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

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

This exam assesses mastery of secure Python development, covering OWASP Top 10 vulnerabilities, cryptographic best practices, input validation, authentication/authorization, secure testing methodologies, and DevSecOps integration. It emphasizes hands-on application through scenario-based problems and code analysis. It contains 48 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: Identify and mitigate common Python security vulnerabilities such as injection, XSS, and insecure deserialization.; Implement secure authentication, session management, and access control mechanisms in Python applications.; Apply cryptographic primitives correctly using libraries like cryptography and hashlib.; Integrate security testing (SAST, DAST, fuzzing) into CI/CD pipelines.. 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 70%. Aligned with This exam adheres to US university standards for graduate-level assessment, aligning with ACM/IEEE curricula and industry best practices (OWASP, NIST). standards and reflects the question style commonly seen on accredited program

Section 1: General (Questions 1-48)

1 A Flask application uses the following code to render a user profile page: return render_template_string('Welcome, %s!' % username). Which vulnerability is most directly introduced, and what is the most robust remediation?

A) Cross-Site Scripting (XSS); escape the username using markupsafe.escape before formatting.

B) Server-Side Template Injection (SSTI); use render_template with a static template file and pass username as a context variable.

C) SQL Injection; parameterize the query using SQLAlchemy. D) Command Injection; sanitize the username with shlex.quote.

Answer: B Rationale: The code uses string formatting to inject user input into a template string, allowing SSTI if the input contains template syntax. The robust fix is to use render_template with a separate template file, which auto-escapes and prevents injection. XSS is possible but SSTI is more severe and directly caused by the pattern; SQL and command injection are unrelated.

2 In a Django application, which setting combination ensures that session cookies are protected against interception and cross-site request forgery?

A) SESSION_COOKIE_SECURE = True, SESSION_COOKIE_HTTPONLY = True, CSRF_COOKIE_SECURE = True

B) SESSION_COOKIE_SECURE = False, SESSION_COOKIE_HTTPONLY = True, CSRF_COOKIE_SECURE = False

C) SESSION_COOKIE_SECURE = True, SESSION_COOKIE_HTTPONLY = False, CSRF_COOKIE_SECURE = True

D) SESSION_COOKIE_SECURE = True, SESSION_COOKIE_HTTPONLY = True, CSRF_COOKIE_SECURE = False

Answer: A Rationale: SESSION_COOKIE_SECURE ensures cookies are only sent over HTTPS, preventing interception. SESSION_COOKIE_HTTPONLY prevents JavaScript access, mitigating XSS. CSRF_COOKIE_SECURE ensures the CSRF cookie is only sent over HTTPS. All three together provide robust protection; other options miss at least one critical setting.

3 When using Python's hashlib for password storage, which approach is considered secure according to current NIST guidelines?

A) SHA-256 with a random salt per user. B) PBKDF2-HMAC-SHA256 with at least 600,000 iterations and a 16-byte salt. C) MD5 with a static salt for all users. D) bcrypt with a cost factor of 4.

Answer: B Rationale: NIST SP 800-63B recommends PBKDF2 with a minimum of 10, iterations, but current best practice suggests 600,000 for SHA-256 to resist brute-force. SHA-256 alone is too fast; MD5 is broken; bcrypt cost factor 4 is too low. PBKDF2 with high iterations and salt is secure.

4 A developer uses pickle.loads to deserialize data from an untrusted source. Which secure alternative should be used to prevent remote code execution?

A) json.loads with a custom object hook. B) yaml.safe_load C) marshal.loads D) eval with a restricted namespace.

Answer: B Rationale: yaml.safe_load safely parses YAML without executing arbitrary code, unlike pickle or marshal. JSON is safe but lacks support for complex Python objects; eval is dangerous. yaml.safe_load is the recommended secure alternative for serialization when possible.

A) CBC with a random IV. B) ECB with a fixed key. C) GCM with a random nonce. D) CTR with a constant counter.

Answer: C Rationale: AES-GCM is an authenticated encryption mode that provides confidentiality and integrity. CBC and CTR provide only confidentiality; ECB is insecure. GCM with a unique nonce is the correct choice.

9 Which of the following is a secure way to generate a random token for password reset in Python?

A) random.randint(100000, 999999) B) secrets.token_urlsafe(32) C) uuid.uuid4().hex D) hashlib.md5(str(time.time()).encode()).hexdigest()

Answer: B Rationale: secrets.token_urlsafe uses a cryptographically secure random number generator, suitable for security tokens. random is not cryptographically secure; UUID4 may be predictable in some contexts; MD5 of time is insecure. Thus, B is correct.

10 In a Python web application, which approach to file uploads best prevents path traversal and arbitrary file execution?

A) Use the original filename provided by the user and save it directly to the upload directory.

B) Sanitize the filename by removing path separators and save it with a randomly generated name.

C) Store the file content in a database as a BLOB and serve it with the original MIME type.

D) Validate the file extension against a whitelist and save it in a directory outside the web root.

Answer: B Rationale: Sanitizing the filename to remove path separators prevents traversal, and using a random name avoids overwrites and execution. Option D also helps but doesn't address traversal if the filename is not sanitized. B is the most robust combined approach.

11 A Flask endpoint builds a shell command as f"convert {user_filename} out.png" and runs it with subprocess.run(..., shell=True). Which remediation most directly eliminates command injection while preserving the same shell pipeline semantics?

A) Escape user_filename with shlex.quote before interpolation B) Pass an argv list to subprocess.run with shell=False and validate the path against an allowlist

C) Replace shell=True with shell=False but keep the f-string as a single argument D) Strip semicolons and backticks from user_filename with a regex denylist

Answer: B Rationale: Passing an argv list with shell=False removes the shell interpreter entirely, so metacharacters have no special meaning; validating the path adds defense in depth. shlex.quote and denylists are fragile because quoting rules and metacharacter sets vary, and shell=False with a single string still fails to tokenize safely.

12 A developer stores session tokens with secrets.token_bytes(32) but compares them using ==. A reviewer flags this as a vulnerability. Which property of the comparison makes the finding valid, and what is the correct fix?

A) == leaks token length via timing; pad tokens to a fixed length B) == short-circuits on the first differing byte, leaking a timing side channel; use hmac.compare_digest

C) == is not constant-time across Python versions; upgrade the interpreter D) == raises on bytes comparison; cast to str first

Answer: B Rationale: Python's == on bytes returns as soon as a mismatch is found, so an attacker can measure response time to recover the token byte by byte. hmac.compare_digest performs a constant-time comparison. Length padding and interpreter upgrades do not address the byte-wise short-circuit, and == does not raise on bytes.

13 A REST API returns {"role": "user"} in a JWT payload signed with HS256, and the server verifies with jwt.decode(token, key, algorithms=["HS256"]). An attacker submits a token with alg set to "none" and role "admin". Why does this attack succeed or fail, and what is the robust control?

A) It succeeds because alg is attacker-controlled; enforce an explicit algorithms allowlist and reject "none"

B) It fails because HS256 signatures cannot be stripped; no change needed C) It succeeds only if the key is empty; rotate keys

A) Compile with -fstack-protector-strong and rely on the canary B) Validate n <= sizeof(dst) before memcpy and use a bounds-checked copy like memcpy_s or a length-checked wrapper

C) Mark the function static to reduce its attack surface D) Run the process under a seccomp filter

Answer: B Rationale: Bounds validation before the copy, combined with a checked copy primitive, prevents the overflow at its source. Stack canaries, static linkage, and seccomp are defense-in-depth mitigations that do not eliminate the out-of-bounds write.

17 A developer uses hashlib.sha256(password.encode()).hexdigest() to store credentials. A security review rejects this. Which replacement best aligns with current password-storage guidance, and why?

A) SHA-256 with a per-user random salt; salting alone defeats cracking B) Argon2id with tuned memory, iterations, and parallelism, plus a per-user salt C) PBKDF2-HMAC-SHA256 with 1,000 iterations for speed D) AES-256 encryption of the password with a server key

Answer: B Rationale: Argon2id is memory-hard and the current OWASP-recommended KDF, resisting GPU and ASIC cracking; a per-user salt prevents rainbow tables. A salted fast hash remains too fast to brute-force, low-iteration PBKDF2 is weak, and reversible encryption is inappropriate for passwords.

18 A CI pipeline runs bandit and safety but a vulnerable dependency is only reachable at runtime through a transitive package. Which practice most directly catches this class of risk before deployment?

A) Increase bandit's severity threshold to HIGH B) Generate and continuously monitor an SBOM with an SCA tool that maps transitive dependencies to CVEs

C) Add more unit tests around the direct dependency D) Enable Dependabot only for direct dependencies

Answer: B Rationale: An SBOM plus SCA tooling enumerates transitive dependencies and correlates them with known CVEs, which is the intended control for supply-chain risk. Bandit thresholds, unit tests, and direct-only Dependabot do not surface transitive vulnerabilities.

19 A web app reflects a user-supplied name into an HTML page without escaping but sets Content-Security-Policy: default-src 'self'. Which statement best describes the residual risk?

A) CSP fully mitigates reflected XSS because inline scripts are blocked B) CSP reduces but does not eliminate XSS; output encoding is still required because script-src 'self' allows same-origin script loads and CSP can be bypassed via JSONP or DOM sinks

C) CSP is irrelevant to XSS; only input validation matters D) CSP eliminates the need for output encoding if HttpOnly cookies are set

Answer: B Rationale: CSP is a defense-in-depth layer; without output encoding, same-origin script loads, JSONP endpoints, and DOM sinks can still execute attacker code. CSP does not replace contextual output encoding, and HttpOnly only protects cookies, not the DOM.

20 A team must decide between fuzzing a Python parser with Atheris and running a large example-based test suite. Which statement best captures when fuzzing adds unique value?

A) Fuzzing replaces unit tests entirely and should be the only test type B) Fuzzing excels at discovering crash-inducing edge cases and memory-safety issues in native code paths that example-based tests miss, while example tests verify specified behavior

C) Fuzzing is only useful for C and C++ and has no role in Python D) Fuzzing guarantees the absence of vulnerabilities once coverage saturates

Answer: B Rationale: Coverage-guided fuzzing explores unexpected inputs and is especially effective at finding crashes and memory-safety bugs in C extensions, complementing example-based tests that verify specified behavior. Fuzzing does not replace unit tests, is applicable to Python (e.g., Atheris), and cannot prove absence of vulnerabilities.

21 A Flask endpoint builds a filesystem path as os.path.join(UPLOAD_DIR, filename) where filename is user-supplied. Which mitigation most robustly prevents path traversal while preserving legitimate nested uploads?

A) Reject any filename containing the substring '..' before joining. B) Normalize the joined path with os.path.realpath and verify it is still within the realpath of UPLOAD_DIR.

C) Pass the filename through urllib.parse.quote before joining.

B) Use pytest.raises with a specific exception type and assert the sanitized output equals the expected safe value.

C) Increase coverage to 100% on the module containing the function. D) Mark the test with @pytest.mark.xfail to document known injection behavior.

Answer: B Rationale: Security tests must assert both that the malicious input is rejected (specific exception) and that outputs are sanitized, not merely that no error occurs. Absence of exceptions, coverage percentage, and xfail markers do not verify rejection semantics.

25 A service deserializes session state with pickle.loads on data from a cookie. Which statement most accurately characterizes the risk and the correct remediation?

A) Risk is low because cookies are base64-encoded; remediation is to add an HMAC.

B) pickle can execute arbitrary code via reduce, so the correct fix is to use a safe format like JSON with an integrity check.

C) Risk is limited to denial of service; remediation is to set a maximum recursion depth.

D) pickle is safe if the loading process runs as an unprivileged user; no change is needed.

Answer: B Rationale: Unpickling untrusted data can invoke reduce to execute arbitrary code, so the format must be replaced with a data-only serializer such as JSON plus a MAC for integrity. HMAC over pickle still deserializes attacker-controlled payloads, and privilege reduction does not prevent code execution.

26 An application stores JWTs in localStorage and also accepts them via an Authorization header. Which design change most directly mitigates token theft via XSS?

A) Shorten token lifetime to five minutes and disable refresh tokens. B) Move tokens to HttpOnly, Secure, SameSite cookies and add CSRF protection. C) Encrypt the JWT payload with a symmetric key before storing it. D) Add the 'alg': 'none' option to simplify verification.

Answer: B Rationale: HttpOnly cookies are inaccessible to JavaScript, removing the primary XSS exfiltration path, with SameSite and CSRF tokens addressing the resulting cross-site request risk. Shorter lifetimes reduce but do not prevent theft, payload

encryption does not stop script access, and 'alg': 'none' disables verification entirely.

27 A team wants reproducible, isolated test environments for a security-sensitive Python project. Which combination best achieves hermetic builds and dependency integrity?

A) pip install with --no-cache-dir and a requirements.txt pinned to exact versions. B) pip install from requirements.txt with hashes plus a lockfile and a virtual environment per build.

C) conda install from the default channel with the latest packages. D) pip install -e. in the system Python to avoid environment overhead.

Answer: B Rationale: Hash-pinned requirements with a lockfile and isolated virtualenvs ensure reproducible, tamper-evident installs. Exact version pinning without hashes does not verify artifact integrity, 'latest' packages are non-reproducible, and editable installs into system Python break isolation.

28 In a threat model, a STRIDE analysis identifies 'Tampering' on a REST API. Which control most directly addresses this category?

A) Rate limiting per client IP. B) Mutual TLS plus HMAC signatures over request bodies. C) Structured logging with correlation IDs. D) Input length validation on all string fields.

Answer: B Rationale: Tampering concerns unauthorized modification of data in transit or at rest, so integrity mechanisms like mTLS and HMAC signatures directly counter it. Rate limiting addresses DoS, logging supports detection and non-repudiation, and length validation addresses input handling rather than integrity.

29 A capstone requires integrating SAST, DAST, and dependency scanning into CI. Which sequencing best reflects defense-in-depth without redundant gating?

A) Run DAST on every commit, block merges on any SAST finding, and scan dependencies weekly.

B) Run SAST and dependency scanning on every commit as merge gates, and run DAST against a deployed staging environment on a schedule.

C) Run only dependency scanning in CI and defer SAST and DAST to an annual penetration test.

D) Run all three tools on every commit and block merges on any finding regardless of severity.

B) Sanitize host by removing ';', '|', and '&' characters. C) Set a restrictive PATH environment variable before execution. D) Run the command with a low-privilege user account.

Answer: A Rationale: shell=False with a list avoids shell interpretation entirely, so metacharacters in host cannot inject commands. Sanitization is denylist-based and bypassable; PATH and privilege reduction do not prevent injection.

33 A Python web app deserializes session data with pickle.loads(request.cookies['session']). Which property of pickle makes this a critical vulnerability?

A) pickle only supports primitive types, causing data corruption. B) pickle executes arbitrary code via reduce during unpickling. C) pickle is slower than JSON, enabling denial of service. D) pickle does not preserve object identity across processes.

Answer: B Rationale: pickle's reduce can invoke arbitrary callables during deserialization, so untrusted data leads to RCE. The other options describe performance or correctness issues, not remote code execution.

34 A developer must store API keys for a Python service deployed to a cloud environment. Which approach best aligns with secure secret management?

A) Hardcode keys in a config.py file excluded from version control. B) Encrypt keys with a symmetric key stored in the same repository. C) Retrieve keys at runtime from a managed secret store (e.g., AWS Secrets Manager) using an instance role.

D) Store keys in environment variables set in the Dockerfile.

Answer: C Rationale: Managed secret stores with instance roles avoid embedding secrets in code or images and support rotation/auditing. Hardcoding, same-repo encryption, and Dockerfile env vars expose secrets in artifacts or version control.

35 A test suite uses unittest.mock.patch to replace requests.get. Which assertion best verifies that the function under test handles a 500 response without raising?

A) mock_get.assert_called_once_with(url) B) mock_get.return_value.status_code = 500; result = func(); assert result is None C) mock_get.side_effect = requests.exceptions.HTTPError D) mock_get.return_value.json.return_value = {'error': 'server'}

Answer: B Rationale: Setting status_code=500 on the mock return value simulates the server error; asserting the function returns None verifies graceful handling. A only checks invocation, C simulates an exception rather than a 500 response, and D tests JSON parsing, not error handling.

36 A Flask app sets session cookies without the Secure, HttpOnly, or SameSite attributes. Which combination most directly mitigates session hijacking and CSRF?

A) Secure=True, HttpOnly=True, SameSite='Lax' B) Secure=True, HttpOnly=False, SameSite='None' C) Secure=False, HttpOnly=True, SameSite='Strict' D) Secure=True, HttpOnly=True, SameSite='None'

Answer: A Rationale: Secure prevents transmission over HTTP, HttpOnly blocks JavaScript access, and SameSite='Lax' mitigates CSRF while preserving usability. SameSite='None' requires Secure and weakens CSRF protection; disabling Secure or HttpOnly undermines defense.

37 A Python script uses yaml.load(user_input) without a Loader. Which risk does this introduce, and what is the secure alternative?

A) Risk: YAML anchors cause infinite loops; use yaml.safe_load. B) Risk: arbitrary code execution via !!python/object; use yaml.safe_load or SafeLoader.

C) Risk: data type coercion; use yaml.full_load. D) Risk: encoding errors; use yaml.load with encoding='utf-8'.

Answer: B Rationale: yaml.load with the default Loader can instantiate arbitrary Python objects, enabling RCE; safe_load restricts to basic types. The other options misidentify the risk or propose insecure alternatives.

38 A developer must hash passwords in a new Python service. Which choice best reflects current best practice for password storage?

A) hashlib.sha256(password + salt) B) hashlib.pbkdf2_hmac('sha256', password, salt, 100000) C) hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1) D) base64.b64encode(password.encode())

Answer: C

Answer: A Rationale: safe_load disallows arbitrary object construction (e.g., !!python/object), eliminating the gadget-based RCE vector. Length checks, exception handling, and timeouts do not prevent malicious tags from executing during load.

42 A developer writes query = f"SELECT * FROM users WHERE name = '{name}'" and passes it to cursor.execute. Which refactor is the correct parameterized fix?

A) Escape single quotes in name with name.replace("'", "''") before interpolation. B) Use cursor.execute('SELECT * FROM users WHERE name = %s', (name,)). C) Encode name with base64 before embedding it in the string. D) Restrict name to alphanumeric characters with a regex.

Answer: B Rationale: Parameterized queries send the value separately from the SQL text, so the database never treats it as code. Manual escaping, encoding, or input whitelisting are weaker, error-prone defenses that fail for numeric or complex inputs.

43 To test whether a function is vulnerable to a timing attack on token comparison, which approach best isolates the vulnerability?

A) Assert the function returns True for a valid token and False otherwise. B) Measure and statistically compare execution times across many inputs differing in matching-prefix length.

C) Fuzz the token with random bytes and check for exceptions. D) Run the function under a coverage tool to confirm all branches execute.

Answer: B Rationale: Timing vulnerabilities manifest as execution-time differences correlated with prefix match length, detectable only via statistical timing measurement. Correctness assertions, fuzzing, and coverage do not reveal timing side channels.

44 A developer stores passwords using hashlib.sha256(password).hexdigest() with a per-user random salt. Which statement best characterizes the remaining weakness?

A) Salt reuse across users enables rainbow-table attacks. B) SHA-256 is a fast hash, so GPU-accelerated brute force remains cheap; a memory-hard KDF is needed.

C) Hexdigest truncation weakens the digest to 128 bits. D) The salt must be secret to provide security.

Answer: B

Rationale: Per-user salts defeat rainbow tables, but SHA-256's speed makes offline guessing feasible; Argon2/bcrypt/scrypt impose deliberate cost. Salts need not be secret, hexdigest is full-length, and per-user salts are not reused.

45 A web app renders user comments with Jinja2 autoescaping disabled and inserts them via {{ comment }}. Which control most directly prevents stored XSS in this context?

A) Strip all HTML tags from the comment with a regex before storage. B) Enable Jinja2 autoescaping so {{ comment }} HTML-escapes output. C) Set the Content-Type header to text/html explicitly. D) Store comments in a database column with a length limit.

Answer: B Rationale: Context-appropriate output encoding via autoescaping neutralizes injected markup at the sink. Regex tag stripping is bypassable, Content-Type does not encode data, and length limits do not affect XSS.

46 A CI pipeline runs bandit and reports a B602 (subprocess with shell=True) finding. Which remediation best preserves functionality while eliminating the finding?

A) Add '# nosec' to the line to suppress the warning. B) Replace shell=True with a list-form argument and shell=False, passing arguments as a sequence.

C) Lower the bandit severity threshold so the finding is ignored. D) Move the subprocess call into a try/except block.

Answer: B Rationale: Using shell=False with an argument list avoids shell interpretation and command injection while retaining execution. Suppressing, lowering thresholds, or wrapping in try/except does not remove the underlying injection risk.

47 A developer uses random.random() to generate a password-reset token. Which change best addresses the security requirement?

A) Seed random with time.time() for better unpredictability. B) Use secrets.token_urlsafe() to draw from a cryptographically secure source. C) Increase the token length generated by random.random(). D) Hash the random output with MD5 before using it as the token.

Answer: B Rationale: The random module is a Mersenne Twister PRNG, predictable from observed outputs; secrets uses the OS CSPRNG. Seeding, lengthening, or hashing