




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















48 QUESTIONS
# TOPIC 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 6 WGU D385 Software Security and Testing Python Secure 7 Coding Practice Workbook 40 Exercises + 4 Capstones 2026 8 Foundations of Software Security and Secure Coding in Python 9 Applied Software Security and Secure Coding in Python 10 Advanced Software Security and Secure Coding in Python 11 Software Security and Secure Coding in Python Review
This study document brings together 48 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 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 and Apply cryptographic primitives correctly using libraries like cryptography and hashlib. 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.
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. 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.
A. SESSION_COOKIE_SECURE = True, SESSION_COOKIE_HTTPONLY = True, CSRF_COOKIE_SECURE = True CORRECT 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 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.
A. Bandit for SAST, OWASP ZAP for DAST, and pytest with hypothesis for fuzzing. CORRECT B. Pylint for SAST, Nessus for DAST, and unittest for fuzzing. C. SonarQube for SAST, Burp Suite for DAST, and locust for fuzzing. D. Flake8 for SAST, Nikto for DAST, and pytest for fuzzing. RATIONALE: Bandit is a dedicated Python SAST tool, OWASP ZAP is a leading DAST tool, and Hypothesis is a property-based testing library for fuzzing. Other options use less specialized or inappropriate tools (e.g., Pylint is a linter, Nessus is a network scanner).
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: RATIONALE: 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.
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. RATIONALE: 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.
A. CBC with a random IV. B. ECB with a fixed key. C. GCM with a random nonce. CORRECT D. CTR with a constant counter. 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.
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 CORRECT 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 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.
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 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.
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 RATIONALE: 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.
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 CORRECT C. A mock that asserts cursor.execute is called exactly once D. A coverage run asserting 100% line coverage of the query builder RATIONALE: 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.
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 CORRECT C. PBKDF2-HMAC-SHA256 with 1,000 iterations for speed D. AES-256 encryption of the password with a server key 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.
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 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.
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 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.
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 CORRECT 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 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.
A. Bandit only analyzes Python 2 syntax and silently skips Python 3 files. B. Bandit is a pattern-based static analyzer and cannot follow tainted data through helper functions or f-strings into cursor.execute. CORRECT C. Bandit requires the --sql flag to enable database-related checks. D. Bandit only flags issues when run with -lll or higher severity thresholds. RATIONALE: Bandit matches syntactic patterns and lacks full interprocedural taint tracking, so injections assembled through helpers or f-strings can evade it. It supports Python 3, has no --sql flag, and severity thresholds only filter, not enable, detections.
A. Assert that the function does not raise any exception for the malicious input. B. Use pytest.raises with a specific exception type and assert the sanitized output equals the expected safe value. CORRECT C. Increase coverage to 100% on the module containing the function. D. Mark the test with @pytest.mark.xfail to document known injection behavior. 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.
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. CORRECT 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. 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.
A. Shorten token lifetime to five minutes and disable refresh tokens. B. Move tokens to HttpOnly, Secure, SameSite cookies and add CSRF protection. CORRECT C. Encrypt the JWT payload with a symmetric key before storing it. D. Add the 'alg': 'none' option to simplify verification. 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.
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. CORRECT 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. RATIONALE: Fast static and dependency scans fit per-commit gating, while DAST requires a running target and is better scheduled against staging. Running DAST per commit is impractical, annual-only scanning leaves gaps, and blocking on every finding regardless of severity creates unsustainable false-positive friction.
A. Escape single quotes with name.replace("'", "''") before interpolation. B. Use cursor.execute('SELECT * FROM users WHERE name = ?', (name,)) with a parameterized placeholder. CORRECT C. Wrap the query in a transaction and set autocommit=False. D. Validate name against a regex allowing only alphanumeric characters. RATIONALE: Parameterized queries bind data separately from SQL syntax, so user input cannot alter query structure, eliminating injection at the source. Escaping and regex validation are fragile denylist/allowlist mitigations that fail on edge cases, and transactions do not prevent injection.
A. tempfile.NamedTemporaryFile(delete=False) or tempfile.mkstemp(), which atomically create the file. CORRECT 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. RATIONALE: 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.
A. Set shell=False and pass args as a list: subprocess.run(['ping', host]). CORRECT 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. 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.
A. mock_get.assert_called_once_with(url) B. mock_get.return_value.status_code = 500; result = func(); assert result is None CORRECT C. mock_get.side_effect = requests.exceptions.HTTPError D. mock_get.return_value.json.return_value = {'error': 'server'} 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.
A. Secure=True, HttpOnly=True, SameSite='Lax' CORRECT B. Secure=True, HttpOnly=False, SameSite='None' C. Secure=False, HttpOnly=True, SameSite='Strict' D. Secure=True, HttpOnly=True, SameSite='None' 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.
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. CORRECT C. Risk: data type coercion; use yaml.full_load. D. Risk: encoding errors; use yaml.load with encoding='utf-8'. 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.
A. hashlib.sha256(password + salt) B. hashlib.pbkdf2_hmac('sha256', password, salt, 100000) C. hashlib.scrypt(password, salt=salt, n=214, r=8, p=1) CORRECT** D. base64.b64encode(password.encode()) RATIONALE: scrypt is a memory-hard KDF designed to resist GPU/ASIC attacks and is recommended for password hashing. PBKDF2 is acceptable but less resistant; SHA-256 and base64 are not password-hashing functions.