










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!











This exam assesses advanced secure-coding and software-testing competencies in Python, covering threat modeling, cryptographic primitives, injection defenses, deserialization risks, concurrency safety, supply-chain integrity, fuzzing, property-based testing, and CI/CD security gates. Questions require synthesis across defensive programming, static/dynamic analysis, and adversarial reasoning aligned with OWASP ASVS and NIST SSDF. It contains 49 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: Apply threat modeling and secure design principles to identify and mitigate Python-specific vulnerabilities.; Implement and evaluate cryptographic, input-validation, and deserialization defenses in Python applications.; Design rigorous test suites using fuzzing, property-based testing, and mutation testing to uncover security defects.; Integrate security controls into CI/CD pipelines and assess software supply-chain integrity.. 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 80% (A- threshold at 90%). Aligned with Aligned with US university graduate standards and industry frameworks
Section 1: General (Questions 1-49)
1 A Flask API uses its default session cookie signing. An attacker who obtains a valid session cookie from a user can forge arbitrary session contents without knowing the server's secret key. Which property of the underlying construction is most directly responsible?
A) The cookie is encrypted with AES-CBC but lacks an HMAC, allowing bit-flipping.
B) The signing uses a length-extension-vulnerable hash over a secret-prefix MAC. C) The cookie is signed with a per-process random key regenerated on each worker restart.
D) The session serializer permits arbitrary object instantiation during deserialization.
Answer: B Rationale: Flask's default secure cookie uses itsdangerous with an HMAC, but naive secret-prefix constructions (e.g., SHA1(secret||data)) are vulnerable to length-extension attacks, allowing forgery without the key. AES-CBC without HMAC is a different flaw not present here; per-process key regeneration would invalidate cookies, not enable forgery; and arbitrary deserialization is a separate RCE risk, not cookie forgery.
2 A service must verify user-supplied passwords. The team proposes storing Argon2id hashes with parameters m=64 MiB, t=3, p=4. A reviewer argues for bcrypt cost 12 instead. Which statement best justifies the Argon2id choice under current best practice?
A) Argon2id is preferred because it is memory-hard, resisting GPU/ASIC parallelism that bcrypt cannot, while bcrypt remains acceptable but weaker against such attackers.
B) Argon2id is required by NIST SP 800-63B, whereas bcrypt is explicitly deprecated for all federal systems.
C) bcrypt is vulnerable to length-extension attacks, while Argon2id uses a sponge construction immune to them.
D) Argon2id's parallelism parameter p=4 makes it faster than bcrypt at equivalent security, reducing server load.
Answer: A Rationale: Argon2id's memory-hardness specifically thwarts GPU/ASIC parallel attacks that bcrypt's fixed memory footprint cannot match; bcrypt remains acceptable but less resistant. NIST does not mandate Argon2id nor deprecate bcrypt; length-extension is irrelevant to password hashing; and higher p increases resource use, not speed at equivalent security.
3 A Python web app builds SQL with f-strings but validates all inputs against a strict allowlist regex. A penetration tester still achieves injection via a crafted Unicode string. Which defense most directly addresses this residual risk?
A) Switching to a WAF with OWASP Core Rule Set. B) Using parameterized queries with the DB-API driver. C) Escaping single quotes with a custom replace function. D) Enforcing a maximum input length of 64 characters.
Answer: B Rationale: Parameterized queries separate code from data at the protocol level, eliminating injection regardless of input content, whereas allowlist regexes can be bypassed by Unicode normalization or encoding tricks. A WAF is defense-in-depth, custom escaping is error-prone, and length limits do not prevent injection.
4 Consider a test suite using hypothesis to validate a function that parses RFC 3339 timestamps. Which property best exposes edge-case bugs that example-based tests miss?
A) For all valid inputs, the parsed datetime round-trips to an identical string. B) The function raises ValueError for any input containing a space.
B) Replace pickle with a safe serialization format like JSON or safetensors and validate integrity.
C) Sign the pickle files with HMAC and verify before loading. D) Run the unpickling in a subprocess with reduced privileges.
Answer: B Rationale: Pickle is inherently unsafe for untrusted data because it can execute arbitrary code during deserialization; replacing it with a data-only format removes the attack surface. Permissions, HMAC signing, and sandboxing are mitigations that still leave risk if the key or sandbox is compromised.
8 A security test uses mutation testing to evaluate a test suite's effectiveness. After mutating a boundary check from < to <=, all tests still pass. What does this most directly indicate?
A) The mutation is equivalent and cannot be killed by any test. B) The test suite lacks a case exercising the exact boundary value. C) The mutation operator is invalid and should be excluded. D) The code under test is not covered by any test.
Answer: B Rationale: A surviving non-equivalent mutant at a boundary indicates missing test cases at that boundary; adding a test for the exact threshold value would kill it. Equivalent mutants are rare and require proof, the operator is standard, and lack of coverage would typically be reported separately.
9 In a threat model using STRIDE, a team identifies that an attacker can replay a signed API request. Which STRIDE category and mitigation pair is most appropriate?
A) Tampering; use HMAC with a timestamp and nonce. B) Spoofing; require client certificates. C) Repudiation; log all requests immutably. D) Information disclosure; encrypt the payload.
Answer: A Rationale: Replay attacks fall under Tampering because the attacker reuses a valid message; adding a timestamp and nonce to the HMAC prevents reuse. Spoofing concerns identity, repudiation concerns denial of actions, and information disclosure concerns confidentiality, none of which directly address replay.
10 A developer uses subprocess.run(cmd, shell=True) with user input. Which change most effectively prevents command injection while preserving shell features like pipes?
A) Set shell=False and pass a list of arguments, refactoring to avoid pipes. B) Escape shell metacharacters with shlex.quote on each argument. C) Run the command as a low-privileged user. D) Validate input against a regex allowlist of alphanumeric characters.
Answer: A Rationale: Using shell=False with an argument list eliminates the shell interpreter entirely, preventing injection; pipes must be implemented in Python. shlex.quote is error-prone for complex commands, privilege reduction limits impact but not injection, and allowlists can be bypassed if not exhaustive.
11 A Flask endpoint builds a shell command as f"nslookup {host}" and calls subprocess.run(cmd, shell=True). Which remediation most directly eliminates command injection while preserving shell features like pipes?
A) Escape the host with shlex.quote() before interpolation. B) Replace shell=True with shell=False and pass a list of arguments. C) Validate host against a regex allowing only [A-Za-z0-9.-]. D) Run the command under a restricted user with no shell access.
Answer: A Rationale: shlex.quote() neutralizes metacharacters while still allowing a shell pipeline to be used, which is the only option that preserves pipes and directly blocks injection. shell=False with a list disables pipes, regex validation is brittle and may reject valid hosts, and least-privilege limits impact but does not remove the injection vector.
12 A login handler stores passwords with PBKDF2-HMAC-SHA256, 100, iterations, 16-byte salt. Which change best aligns with current OWASP guidance for password storage?
A) Increase iterations to 600,000 and keep SHA-256. B) Switch to bcrypt with cost factor 10 and 8-byte salt. C) Use Argon2id with memory cost 19 MiB, iterations 2, parallelism 1. D) Use scrypt with N=2^14, r=8, p=1 and 8-byte salt.
Answer: C Rationale: OWASP's current Password Storage Cheat Sheet recommends Argon2id with m=19 MiB, t=2, p=1 as the first choice because it is memory-hard and resists
assignment). API1 concerns accessing other users' objects, API5 concerns invoking privileged functions, and API8 covers configuration issues, not property-level trust.
16 A test suite uses pytest and needs to verify that a function raises ValueError on negative input while also checking the error message. Which pattern is idiomatic and correct?
A) with pytest.raises(ValueError) as exc: f(-1) then assert 'negative' in str(exc.value)
B) try: f(-1) except ValueError: pass C) assert f(-1) == ValueError D) pytest.raises(ValueError, f, -1) without capturing the message
Answer: A Rationale: pytest.raises as a context manager both asserts the exception type and exposes exc.value for message assertions. Option B swallows the exception without asserting, C compares a return value to a class, and D asserts type only and cannot verify the message.
17 A Flask app accepts a filename and serves it with send_file(os.path.join('/data', name)). Which input should be rejected to prevent path traversal?
A) report.pdf B) ../etc/passwd C) subdir/report.pdf D) report_2024.pdf
Answer: B Rationale: '../etc/passwd' contains traversal sequences that escape the intended directory. The other filenames stay within /data and are legitimate; subdirectory access is safe if the resolved path is verified to remain under the base directory.
18 A developer stores API keys in a .env file committed to the repository. Which combination of controls best remediates the exposure?
A) Rotate the keys, remove the file from history with git filter-repo, and load secrets from a vault or environment at runtime.
B) Add .env to .gitignore and continue using the same keys. C) Encrypt the .env file with a hardcoded password in the source. D) Move the keys into a config.py module imported by the app.
Answer: A Rationale: Once committed, secrets must be rotated because history retains them; purging history and moving to a secret manager prevents recurrence. Gitignoring
alone leaves exposed keys valid, and hardcoded encryption or config modules still expose secrets in source.
19 A team wants to detect known-vulnerable dependencies in a Python project during CI. Which tool and practice best fits a current secure SDLC?
A) Run flake8 on the source tree. B) Run bandit and treat findings as build failures. C) Run pip-audit (or safety) against requirements and fail on known CVEs. D) Run mypy in strict mode.
Answer: C Rationale: pip-audit and safety query vulnerability databases for installed/declared dependencies, which is the correct SCA practice. flake8 and mypy are linters/type checkers, and bandit performs static analysis of first-party code, not dependency CVE detection.
20 A service uses Python's pickle to deserialize data received from an untrusted queue. Which statement is most accurate about the risk and mitigation?
A) pickle is safe if the payload is base64-encoded. B) pickle can execute arbitrary code via reduce; use JSON or a safe schema like protobuf instead.
C) pickle is safe when using protocol 5. D) pickle is safe if the class is defined in the same module.
Answer: B Rationale: pickle's reduce and related hooks allow arbitrary code execution during unpickling, so untrusted data must never be unpickled; JSON or schema-based formats are safe alternatives. Encoding, protocol version, and module locality do not remove the code-execution primitive.
21 A Flask endpoint builds a SQL query as "SELECT * FROM users WHERE name = '" + request.args.get('name') + "'". Which remediation most completely eliminates the injection class while preserving identical result semantics?
A) Escape single quotes with name.replace("'", "''") before concatenation. B) Pass the value as a bound parameter: cursor.execute("SELECT * FROM users WHERE name = %s", (name,)).
C) Wrap the input in html.escape() to neutralize metacharacters. D) Reject requests whose name contains the substring -- or ;.
Answer: B Rationale: Parameterized queries separate code from data at the driver level, so
not prevent secret disclosure at write time.
25 A pipeline runs pip install -r requirements.txt where one pin is requests==2.31.0 from PyPI. Which practice most reduces supply-chain risk without breaking reproducibility?
A) Add --no-deps to skip transitive packages. B) Pin transitive dependencies with hashes via pip-compile --generate-hashes and verify them.
C) Upgrade to the latest unpinned version on every build. D) Mirror PyPI internally but skip signature verification for speed.
Answer: B Rationale: Hash-pinning locks the full dependency graph and detects tampering. --no-deps (A) breaks functionality, unpinned upgrades (C) reintroduce drift, and skipping verification (D) defeats the mirror's protective purpose.
26 A YAML config loader uses yaml.load(stream) on untrusted input. Which replacement preserves legitimate YAML features while removing the code-execution vector?
A) yaml.safe_load(stream) B) json.loads(stream) after converting YAML to JSON C) yaml.load(stream, Loader=yaml.FullLoader) D) Wrap yaml.load in a try/except block
Answer: A Rationale: safe_load restricts to basic types, blocking arbitrary object construction. FullLoader (C) still allows some tags, JSON conversion (B) loses YAML features, and try/except (D) does not prevent execution.
27 A code review flags subprocess.run(cmd, shell=True) where cmd includes user input. Which refactor most robustly removes command-injection risk while keeping the same external program invocation?
A) Quote the input with shlex.quote and keep shell=True. B) Pass an argument list with shell=False and validate against an allowlist. C) Prefix the command with sudo to isolate privileges. D) Redirect stderr to /dev/null to suppress injection warnings.
Answer: B Rationale: shell=False with a list avoids shell parsing entirely; allowlisting constrains inputs. Quoting (A) is fragile, sudo (C) escalates risk, and suppressing output (D) hides symptoms.
28 A JWT verification routine calls jwt.decode(token, options={"verify_signature": False}) then checks alg manually. Which vulnerability class does this most directly enable?
A) Cross-site request forgery via cookie replay. B) Algorithm-confusion / none-algorithm token forgery. C) Server-side request forgery through claim URLs. D) Timing side-channel in HMAC comparison.
Answer: B Rationale: Skipping signature verification lets attackers craft tokens with alg: none or swapped algorithms. CSRF (A), SSRF (C), and timing attacks (D) are distinct issues not caused by disabling verification.
29 A test suite uses unittest.mock.patch to stub requests.get but the production code calls requests.Session().get. The test passes while production fails. Which testing principle does this best illustrate?
A) Mocks should target the seam actually invoked by the code under test. B) Integration tests are always preferable to unit tests. C) Coverage percentage guarantees correctness. D) Property-based tests eliminate the need for mocks.
Answer: A Rationale: Patching the wrong symbol creates a false positive; mocks must intercept the exact call path. The other options are overgeneralizations unrelated to this specific mocking failure.
30 A capstone requires constant-time comparison of an HMAC to prevent timing leaks. Which Python construct is most appropriate?
A) if a == b: on bytes B) hmac.compare_digest(a, b) C) hashlib.sha256(a).digest() == hashlib.sha256(b).digest() D) a.startswith(b) and len(a) == len(b)
Answer: B Rationale: compare_digest performs constant-time comparison resistant to timing attacks. Direct equality (A), hashing then comparing (C), and startswith (D) all short-circuit and leak timing information.
31 A Flask endpoint builds a filesystem path as os.path.join(BASE_DIR, request.args.get('file')). Which implementation most reliably prevents path traversal while still allowing legitimate nested subdirectories?
Answer: C Rationale: Pinning to a locked requirements file and consuming machine-readable JSON with --strict yields deterministic gating tied to the exact dependency set. Parsing human output (A) is brittle, querying a live feed without a lockfile (B) is non-reproducible, and outdated-version checks (D) conflate staleness with exploitable vulnerabilities.
34 A developer uses subprocess.run('grep ' + user_input, shell=True). Which refactor most completely eliminates command injection while preserving the search behavior?
A) Escape user_input with shlex.quote before concatenating into the shell string. B) Replace shell=True with shell=False and pass ['grep', user_input] as the argument list.
C) Wrap user_input in double quotes and prepend a backslash to every metacharacter.
D) Set the environment variable IFS to empty before invoking the shell.
Answer: B Rationale: Passing an argument list with shell=False bypasses the shell entirely, so metacharacters are treated as literal data. shlex.quote (A) and manual escaping (C) are fragile and version-dependent, while clearing IFS (D) does not prevent command substitution or pipelines.
35 An application stores passwords using bcrypt with cost factor 10. Which change most directly increases resistance to offline GPU cracking without altering the stored hash format?
A) Increase the bcrypt cost factor to 12 or higher. B) Switch to SHA-256 with a per-user salt. C) Concatenate a global pepper to the password before hashing. D) Base64-encode the resulting hash before storage.
Answer: A Rationale: Raising the work factor increases the computational cost of each guess, directly slowing offline attacks. SHA-256 with salt (B) is fast and unsuitable for passwords, a global pepper (C) adds secrecy but not per-guess cost, and base encoding (D) provides no security benefit.
36 A team enables Django's CSRF middleware but writes a JSON API consumed by a single-page app. Which configuration correctly preserves protection without breaking the SPA?
A) Exempt the API views from CSRF and rely on CORS to block cross-site requests.
B) Set CSRF_COOKIE_HTTPONLY to True so JavaScript cannot read the token. C) Send the CSRF token in a header (e.g., X-CSRFToken) and ensure the cookie is SameSite=Lax or Strict.
D) Disable CSRF middleware and validate the Origin header inside each view.
Answer: C Rationale: Django supports header-based CSRF tokens, and SameSite cookies prevent cross-site submission, preserving protection for SPAs. CORS (A) does not block simple cross-site requests, CSRF_COOKIE_HTTPONLY (B) breaks JavaScript token access, and manual Origin checks (D) are error-prone and incomplete.
37 A function uses random.random() to generate password reset tokens. Which replacement most appropriately satisfies cryptographic unpredictability requirements?
A) random.SystemRandom().random() seeded from os.urandom(16). B) secrets.token_urlsafe(32). C) hashlib.sha256(str(time.time()).encode()).hexdigest(). D) uuid.uuid4().hex truncated to 16 characters.
Answer: B Rationale: secrets.token_urlsafe draws from the OS CSPRNG and is designed for security tokens. SystemRandom (A) is acceptable but the manual seeding is unnecessary and less idiomatic, time-based hashing (C) is predictable, and truncated UUIDv4 (D) reduces entropy and is not intended for secrets.
38 A developer uses yaml.load(user_supplied_yaml) with the default loader. Which change best mitigates code execution risk while preserving legitimate data parsing?
A) Replace with yaml.safe_load to restrict to standard YAML tags. B) Wrap the call in try/except to catch parsing errors. C) Prepend a '!!python/object' guard to reject dangerous tags. D) Limit input size to 1 MB before parsing.
Answer: A Rationale: yaml.safe_load restricts parsing to standard YAML types, preventing object construction and code execution. Exception handling (B) does not stop payload execution, ad hoc tag guards (C) are incomplete, and size limits (D) address DoS, not deserialization RCE.
addresses the true risk without weakening the whole scan. Global disables, format() rewrites, and threshold changes hide the class of defect and are not risk-based decisions.
42 Which use of Python's secrets module is cryptographically appropriate for generating a password-reset token that must be unguessable and URL-safe?
A) base64.b64encode(random.randbytes(32)).decode() B) secrets.token_urlsafe(32) C) hashlib.sha256(str(time.time()).encode()).hexdigest() D) uuid.uuid4().hex + secrets.token_hex(4)
Answer: B Rationale: secrets.token_urlsafe draws from the OS CSPRNG and returns URL-safe text with adequate entropy. random.randbytes and time-based hashes are not cryptographically secure, and concatenating uuid4 with a short token still relies on a non-CSPRNG component.
43 A service stores passwords with PBKDF2-HMAC-SHA256, 100,000 iterations, per-user 16-byte salt. A code review proposes switching to Argon2id. Which statement best justifies the migration?
A) Argon2id is memory-hard and tunable, raising the cost of GPU/ASIC cracking compared with PBKDF2's compute-only hardness
B) Argon2id removes the need for per-user salts because it embeds a nonce C) Argon2id is faster than PBKDF2, reducing authentication latency without security loss
D) Argon2id is a NIST-approved mode that supersedes PBKDF2 for all FIPS contexts
Answer: A Rationale: Argon2id's memory-hardness and parameter tuning increase attacker cost on parallel hardware, the main advantage over PBKDF2. It still requires unique salts, is not necessarily faster, and FIPS considerations are more nuanced than a blanket supersession.
44 An application deserializes session data with pickle.loads on a cookie value. Which control most directly eliminates the remote code execution class of risk?
A) Signing the cookie with HMAC-SHA256 and rejecting invalid signatures B) Replacing pickle with a safe format such as JSON and validating the schema before use
C) Wrapping the loads call in try/except to catch deserialization errors
D) Restricting the cookie to HttpOnly and Secure attributes
Answer: B Rationale: Pickle can execute arbitrary code via reduce; using a non-executable format like JSON with schema validation removes the primitive. HMAC and cookie flags reduce tampering and theft but do not neutralize pickle's inherent code-execution risk, and try/except does not prevent execution.
45 In a threat model for a Python web service, which pairing correctly maps a STRIDE category to a representative Python-specific mitigation?
A) Tampering - enforce TLS 1.3 and HSTS on all endpoints B) Information disclosure - use secrets.compare_digest for token comparison C) Spoofing - validate JWT signatures with the algorithm pinned to RS256 and reject 'none'
D) Denial of service - apply output encoding with markupsafe.escape
Answer: C Rationale: Spoofing of identity is mitigated by robust token verification, including algorithm pinning to prevent alg confusion and 'none' attacks. TLS/HSTS addresses information disclosure in transit, compare_digest addresses timing-based disclosure, and output encoding addresses tampering/XSS, not DoS.
46 A Django view renders user-supplied HTML into a template with {{ bio|safe }}. An attacker submits . Which defense most precisely addresses the vulnerability while preserving intended rich text?
A) Enable Django's CSRF middleware and require POST for the view B) Sanitize bio with a allowlist-based HTML sanitizer such as bleach before marking it safe
C) Set the Content-Security-Policy header to 'unsafe-inline' D) Escape bio with django.utils.html.escape and remove the safe filter
Answer: B Rationale: An allowlist sanitizer (e.g., bleach) strips dangerous attributes/handlers while permitting safe markup, matching the requirement for rich text. CSRF does not stop stored XSS, 'unsafe-inline' weakens CSP, and full escaping destroys intended formatting.
47 A test suite for a file-upload endpoint must verify that path traversal is blocked. Which assertion set best validates robust defense-in-depth rather than a single string check?
A) Assert that '../etc/passwd' raises HTTP 400