

















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!


















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.
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. SESSION_COOKIE_SECURE = True, SESSION_COOKIE_HTTPONLY = True, CSRF_COOKIE_SECURE = True
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.
5. In a CI/CD pipeline, which combination of security testing tools provides the most comprehensive coverage for a Python web application?
A. Bandit for SAST, OWASP ZAP for DAST, and pytest with hypothesis for fuzzing. 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.
Answer: A. Bandit for SAST, OWASP ZAP for DAST, and pytest with hypothesis 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).
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):
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.
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.
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.
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.
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.
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. Pass an argv list to subprocess.run with shell=False and validate the path against an allowlist
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. == short-circuits on the first differing byte, leaking a timing side channel; use hmac.compare_digest
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 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"
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.
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
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.
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. Argon2id with tuned memory, iterations, and parallelism, plus a per-user salt
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. Generate and continuously monitor an SBOM with an SCA tool that maps transitive dependencies to CVEs
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. 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
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. 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
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.
23. A CI pipeline runs 'bandit -r src' and reports zero issues, yet a SQL injection ships to production. Which explanation best accounts for this outcome?
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. C. Bandit requires the --sql flag to enable database-related checks. D. Bandit only flags issues when run with -lll or higher severity thresholds.
Answer: B. Bandit is a pattern-based static analyzer and cannot follow tainted data through helper functions or f-strings into cursor.execute.
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.
24. Which pytest practice most effectively validates that a function rejects malicious input rather than merely returning without error?
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. 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. Use pytest.raises with a specific exception type and assert the sanitized output equals the expected safe value.
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. pickle can execute arbitrary code via reduce, so the correct fix is to use a safe format like JSON with an integrity check.
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. Move tokens to HttpOnly, Secure, SameSite cookies and add CSRF protection.
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.
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.
Answer: B. Run SAST and dependency scanning on every commit as merge gates, and run DAST against a deployed staging environment on a schedule.
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.
30. A Flask route builds a SQL query as f"SELECT * FROM users WHERE name = '{name}'". Which remediation most directly eliminates SQL injection while preserving parameterized behavior?
A. Escape single quotes with name.replace("'", "''") before interpolation. B. Use cursor.execute('SELECT * FROM users WHERE name = ?', (name,)) with a parameterized placeholder. C. Wrap the query in a transaction and set autocommit=False. D. Validate name against a regex allowing only alphanumeric characters.
Answer: B. Use cursor.execute('SELECT * FROM users WHERE name = ?', (name,)) with a parameterized placeholder.
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.
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.
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.
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]).
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.
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
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. Secure=True, HttpOnly=True, SameSite='Lax'
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. Risk: arbitrary code execution via !!python/object; use yaml.safe_load or SafeLoader.
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. hashlib.scrypt(password, salt=salt, n=214, r=8, p=1)**
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- and base64 are not password-hashing functions.