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 - Questions
and Answers Already Graded A+ Premium Exam Tested And
Verified
GRADED A+
ABSTRACT
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.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17

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 - Questions

and Answers Already Graded A+ Premium Exam Tested And

Verified

GRADED A+

ABSTRACT

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.

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. Server-Side Template Injection (SSTI); use render_template with a

static template file and pass username as a context variable.

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. SESSION_COOKIE_SECURE = True,

SESSION_COOKIE_HTTPONLY = True, CSRF_COOKIE_SECURE = True

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.

6. Which of the following code snippets correctly implements a constant-time

comparison to prevent timing attacks when verifying a password hash?

A. if hashlib.sha256(user_input).hexdigest() == stored_hash: B. if hmac.compare_digest(hashlib.sha256(user_input).hexdigest(), stored_hash): C. if user_input == stored_hash: D. if hashlib.sha256(user_input).digest() == stored_hash:

Answer: B. if hmac.compare_digest(hashlib.sha256(user_input).hexdigest(),

stored_hash):

hmac.compare_digest provides constant-time comparison, mitigating timing attacks. Direct string or byte comparison (A, C, D) can leak information through timing variations. Using compare_digest is the secure best practice.

7. During a threat modeling session for a Python microservice, which technique best

identifies potential injection flaws early in the design phase?

A. STRIDE analysis focusing on tampering and information disclosure. B. Conducting a dynamic application security test (DAST) on the running service. C. Reviewing the code with a static analysis tool after implementation. D. Performing a penetration test on the deployed service.

Answer: A. STRIDE analysis focusing on tampering and information disclosure.

STRIDE is a threat modeling framework that helps identify threats like tampering and information disclosure during design, before code is written. DAST, SAST, and pen testing are later-stage activities. Thus, STRIDE is the proactive design-phase technique.

8. A Python application uses the cryptography library to encrypt sensitive data.

Which mode of operation for AES provides both confidentiality and integrity?

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. GCM with a random nonce.

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. secrets.token_urlsafe(32)

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. Sanitize the filename by removing path separators and save it with a

randomly generated name.

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.

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 D. It fails because jwt.decode always verifies signatures; the vulnerability is elsewhere

Answer: A. It succeeds because alg is attacker-controlled; enforce an explicit

algorithms allowlist and reject "none"

The classic JWT algorithm-confusion/none attack relies on the verifier honoring the header's alg; passing an explicit algorithms list (already shown) is the correct control, and "none" must be rejected. The other options misstate how JWT libraries behave or assume verification is automatic when it is not.

14. A pytest suite uses @pytest.mark.parametrize to feed SQL-like strings into a

query builder that uses f-strings. Which test design most rigorously demonstrates

injection resistance across the input space?

A. One test with the literal string "' OR '1'='1" asserting no exception is raised B. Hypothesis-based property tests asserting that the built query contains no unescaped quotes for arbitrary generated inputs C. A mock that asserts cursor.execute is called exactly once D. A coverage run asserting 100% line coverage of the query builder

Answer: B. Hypothesis-based property tests asserting that the built query contains

no unescaped quotes for arbitrary generated inputs

Property-based testing with Hypothesis explores a vast, adversarial input space and asserts an invariant (no unescaped quotes), which is far stronger than a single example. A single string, a call-count mock, and line coverage do not demonstrate injection resistance.

15. A service uses pickle.loads on data from a Redis queue. Which statement best

characterizes the security boundary and the correct alternative for untrusted data?

A. pickle is safe if the queue is internal; keep it for performance B. pickle can execute arbitrary code via reduce, so untrusted data must use a data-only format like JSON or a schema-validated format C. pickle is safe if you subclass Unpickler and override find_class to return None D. pickle is safe if the payload is compressed with zlib first

Answer: B. pickle can execute arbitrary code via reduce, so untrusted data

must use a data-only format like JSON or a schema-validated format

pickle's reduce and related hooks allow arbitrary code execution during unpickling, so it must never process untrusted data; JSON or schema-validated formats are data-only. Blocking find_class is a partial mitigation but not a guarantee, and compression does not remove the code-execution primitive.

16. A C extension exposes a function that reads a length-prefixed buffer into a fixed

256-byte stack array using memcpy(dst, src, n) with n from the wire. Which

combination of controls most reliably prevents a stack buffer overflow?

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. Validate n <= sizeof(dst) before memcpy and use a bounds-checked

copy like memcpy_s or a length-checked wrapper

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.

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. 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

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. 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

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. D. Strip leading '/' and '\' characters from the filename before joining.

Answer: B. Normalize the joined path with os.path.realpath and verify it is still

within the realpath of UPLOAD_DIR.

Canonicalizing the final path and confirming containment defeats traversal regardless of encoding tricks or symlinks. Substring checks and quote() are bypassable via alternate encodings or absolute paths, and stripping slashes alone fails against '..' sequences.

22. A developer uses subprocess.run('grep ' + user_input, shell=True). Which

refactor eliminates shell-injection risk while keeping equivalent grep behavior?

A. Wrap user_input in double quotes: subprocess.run('grep "' + user_input + '"', shell=True). B. Replace shell=True with shell=False but keep the concatenated string as the command. C. Call subprocess.run(['grep', user_input], shell=False) with a list of arguments. D. Escape semicolons and ampersands in user_input before concatenation.

Answer: C. Call subprocess.run(['grep', user_input], shell=False) with a list of

arguments.

Passing an argument list with shell=False bypasses the shell entirely, so metacharacters carry no special meaning. Quoting and blacklisting metacharacters are fragile, and shell=False with a single concatenated string treats the whole string as one executable name.

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. pickle can execute arbitrary code via reduce, so the correct fix is to

use a safe format like JSON with an integrity check.

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. Move tokens to HttpOnly, Secure, SameSite cookies and add CSRF

protection.

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. pip install from requirements.txt with hashes plus a lockfile and a

virtual environment per build.

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. Mutual TLS plus HMAC signatures over request bodies.

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.

31. A security review flags that a Python service uses tempfile.mktemp() to generate

upload paths. Which replacement best prevents the underlying race condition?

A. tempfile.NamedTemporaryFile(delete=False) or tempfile.mkstemp(), which atomically create the file. B. os.urandom(16).hex() concatenated with the filename, then open() with mode 'x'. C. A UUID4 filename stored in a module-level dictionary to track usage. D. hashlib.sha256(os.getpid().encode()).hexdigest() as the filename.

Answer: A. tempfile.NamedTemporaryFile(delete=False) or tempfile.mkstemp(),

which atomically create the file.

mktemp() returns a name without creating the file, allowing a TOCTOU race; mkstemp() and NamedTemporaryFile create the file atomically. Option B still has a race between name generation and open, and C/D do not guarantee atomic creation.

32. A developer uses subprocess.run(f"ping {host}", shell=True) in a diagnostic tool.

Which change most effectively prevents command injection while retaining shell

features?

A. Set shell=False and pass args as a list: subprocess.run(['ping', host]). 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. Set shell=False and pass args as a list: subprocess.run(['ping', host]).

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. pickle executes arbitrary code via reduce during unpickling.

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. Retrieve keys at runtime from a managed secret store (e.g., AWS

Secrets Manager) using an instance role.

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. mock_get.return_value.status_code = 500; result = func(); assert result

is None

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.

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

request.args['name']) then opens it. Which mitigation most directly prevents

traversal while preserving legitimate nested filenames?

A. Reject any input containing the substring '..' before joining. B. Resolve the joined path with os.path.realpath and verify it remains within os.path.realpath(UPLOAD_DIR). C. URL-decode the argument once, then pass it to open() unchanged. D. Wrap the open() call in a try/except and log failures.

Answer: B. Resolve the joined path with os.path.realpath and verify it remains

within os.path.realpath(UPLOAD_DIR).

Canonicalizing both the target and base directory with realpath and checking containment defeats traversal regardless of encoding or symlinks. Substring filtering misses encoded, absolute, or symlink-based bypasses; decoding alone changes nothing; exception handling is detection, not prevention.

40. A login handler computes hmac.new(SECRET, password.encode(),

hashlib.sha256).hexdigest() and compares it to the stored value with ==. Which

change addresses the residual vulnerability?

A. Increase the digest to SHA-512 for stronger collision resistance. B. Replace == with hmac.compare_digest to make comparison constant-time. C. Salt the password before HMAC to prevent rainbow-table attacks. D. Base64-encode the hexdigest before storage to obscure it.

Answer: B. Replace == with hmac.compare_digest to make comparison

constant-time.

The flaw is a timing side channel from short-circuiting ==, which compare_digest eliminates by comparing in constant time. Changing hash size, salting, or encoding does not remove the timing leak; salting is orthogonal to the comparison vulnerability.

41. A service deserializes untrusted data with yaml.load(data, Loader=yaml.Loader).

Which remediation most completely removes the code-execution risk while retaining

YAML parsing?

A. Switch to yaml.safe_load, which restricts construction to basic Python types. B. Validate the input length before calling yaml.load. C. Wrap yaml.load in try/except to catch constructor errors. D. Run yaml.load inside a subprocess with a timeout.

Answer: A. Switch to yaml.safe_load, which restricts construction to basic Python

types.

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. Use cursor.execute('SELECT * FROM users WHERE name = %s',

(name,)).

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.