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 48 Questions
EXAM INFORMATION
Subject: Software Security and Secure Coding in Python
Questions: 48 | Format: Multiple choice
Duration: 3 hours
Passing score: 90%
ABOUT THIS EXAM
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.
WHAT THIS COVERS
1. Identify and mitigate common Python security vulnerabilities such as injection, XSS, and insecure
deserialization.
2. Implement secure authentication, session management, and access control mechanisms in Python
applications.
3. Apply cryptographic primitives correctly using libraries like cryptography and hashlib.
4. Integrate security testing (SAST, DAST, fuzzing) into CI/CD pipelines.
5. Design and conduct security-focused code reviews and threat modeling for Python projects.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28

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

EXAM INFORMATION

Subject: Software Security and Secure Coding in Python Questions: 48 | Format: Multiple choice Duration: 3 hours Passing score: 90%

ABOUT THIS EXAM

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.

WHAT THIS COVERS

  1. Identify and mitigate common Python security vulnerabilities such as injection, XSS, and insecure deserialization.
  2. Implement secure authentication, session management, and access control mechanisms in Python applications.
  3. Apply cryptographic primitives correctly using libraries like cryptography and hashlib.
  4. Integrate security testing (SAST, DAST, fuzzing) into CI/CD pipelines.
  5. Design and conduct security-focused code reviews and threat modeling for Python projects.

Detailed Explanations

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

CORRECT

C (^) SQL Injection; parameterize the query using SQLAlchemy.

D (^) Command Injection; sanitize the username with shlex.quote.

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

Detailed Explanations

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

CORRECT

C (^) MD5 with a static salt for all users.

D (^) bcrypt with a cost factor of 4.

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

Detailed Explanations

Q 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 CORRECT

C (^) marshal.loads

D (^) eval with a restricted namespace.

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

Detailed Explanations

Q 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):

CORRECT

C (^) if user_input == stored_hash:

D (^) if hashlib.sha256(user_input).digest() == stored_hash:

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

Detailed Explanations

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

CORRECT

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.

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

Detailed Explanations

Q 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) CORRECT

C (^) uuid.uuid4().hex

D (^) hashlib.md5(str(time.time()).encode()).hexdigest()

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

Detailed Explanations

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

CORRECT

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.

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

Detailed Explanations

Q 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

CORRECT

C (^) == is not constant-time across Python versions; upgrade the interpreter

D (^) == raises on bytes comparison; cast to str first

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

Detailed Explanations

Q 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"

CORRECT

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

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

Detailed Explanations

Q 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

CORRECT

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

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

Detailed Explanations

Q 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

CORRECT

C (^) Mark the function static to reduce its attack surface

D (^) Run the process under a seccomp filter

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

Detailed Explanations

Q 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

CORRECT

C (^) Add more unit tests around the direct dependency

D (^) Enable Dependabot only for direct dependencies

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

Detailed Explanations

Q 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

CORRECT

C (^) CSP is irrelevant to XSS; only input validation matters

D (^) CSP eliminates the need for output encoding if HttpOnly cookies are set

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