
































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!

































EXAM INFORMATION
Subject: Software Security and Testing with Python Questions: 49 | Format: Multiple choice Duration: 3 hours Passing score: 90%
ABOUT THIS EXAM
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.
WHAT THIS COVERS
Detailed Explanations
Q 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.
CORRECT
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.
EXPLANATION 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.
Detailed Explanations
Q 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. CORRECT
C (^) Escaping single quotes with a custom replace function.
D (^) Enforcing a maximum input length of 64 characters.
EXPLANATION 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.
Detailed Explanations
Q 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.
CORRECT
B (^) The function raises ValueError for any input containing a space.
C (^) Parsing is idempotent when applied twice to the same string.
D (^) The parser's runtime is O(n) in input length.
EXPLANATION Round-trip invariants force the generator to explore the full valid input space, surfacing normalization, timezone, and leap-second edge cases that example tests overlook. The other properties are either trivially true, overly narrow, or unrelated to correctness of parsing.
Detailed Explanations
Q A multithreaded Python service uses a shared dict guarded by a threading.Lock. A race condition still corrupts data under high load. Which is the most likely cause?
A (^) The GIL makes the lock redundant, so the lock is optimized away.
B (^) Some code paths mutate the dict without acquiring the lock. CORRECT
C (^) dict operations are not atomic even under the GIL.
D (^) The lock must be an RLock to be effective across threads.
EXPLANATION A lock only protects critical sections where it is actually acquired; any unguarded mutation path breaks mutual exclusion. The GIL does not eliminate the need for locks, dict operations are not guaranteed atomic for compound updates, and RLock is only needed for reentrant acquisition, not basic correctness.
Detailed Explanations
Q A team uses pickle to cache ML models. An attacker who can write to the cache directory achieves RCE. Which mitigation best preserves functionality while eliminating the vulnerability?
A (^) Restrict cache directory permissions to the service user.
B (^) Replace pickle with a safe serialization format like JSON or safetensors and validate integrity.
CORRECT
C (^) Sign the pickle files with HMAC and verify before loading.
D (^) Run the unpickling in a subprocess with reduced privileges.
EXPLANATION 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.
Detailed Explanations
Q 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. CORRECT
B (^) Spoofing; require client certificates.
C (^) Repudiation; log all requests immutably.
D (^) Information disclosure; encrypt the payload.
EXPLANATION 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.
Detailed Explanations
Q 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.
CORRECT
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.
EXPLANATION 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.
Detailed Explanations
Q 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
CORRECT
D (^) Use scrypt with N=2^14, r=8, p=1 and 8-byte salt.
EXPLANATION OWASP's current Password Storage Cheat Sheet recommends Argon2id with m= MiB, t=2, p=1 as the first choice because it is memory-hard and resists GPU cracking. PBKDF2 remains acceptable but weaker; bcrypt cost 10 and scrypt with 8-byte salt are below current recommended parameters.
Detailed Explanations
Q A code review finds: cursor.execute('SELECT * FROM users WHERE name = %s' % name). Which vulnerability class does this represent, and which fix is correct?
A (^) Command injection; use subprocess with a list.
B (^) SQL injection via string formatting; use parameterized queries with a tuple.
CORRECT
C (^) XSS; escape the name with html.escape().
D (^) Path traversal; normalize with os.path.realpath().
EXPLANATION String interpolation into SQL builds attacker-controlled query text, enabling SQL injection; DB-API parameterization (execute(sql, (name,))) sends the value separately so it cannot alter query structure. The other options misclassify the flaw or apply unrelated mitigations.
Detailed Explanations
Q A REST API accepts a JSON body with a 'role' field and uses it to set user permissions without server-side checks. Which OWASP API Security Top 10 (2023) category best describes this flaw?
A (^) API1: Broken Object Level Authorization
B (^) API3: Broken Object Property Level Authorization CORRECT
C (^) API5: Broken Function Level Authorization
D (^) API8: Security Misconfiguration
EXPLANATION Allowing clients to set privileged properties like 'role' via mass assignment is API (Broken Object Property Level Authorization / mass assignment). API1 concerns accessing other users' objects, API5 concerns invoking privileged functions, and API covers configuration issues, not property-level trust.
Detailed Explanations
Q 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)
CORRECT
B (^) try: f(-1) except ValueError: pass
C (^) assert f(-1) == ValueError
D (^) pytest.raises(ValueError, f, -1) without capturing the message
EXPLANATION 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.
Detailed Explanations
Q 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.
CORRECT
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.
EXPLANATION 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.
Detailed Explanations
Q 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.
CORRECT
D (^) Run mypy in strict mode.
EXPLANATION 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.