

















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!


















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.
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.
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.
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.
A. Requiring signed commits from all contributors. B. Enforcing a Software Bill of Materials (SBOM) and blocking builds on critical CVEs via policy-as-code. C. Running the test suite with -W error to treat warnings as errors. D. Enabling branch protection requiring two approvals.
An SBOM combined with policy-as-code gates can detect and block known-vulnerable dependencies regardless of pinning method, directly addressing supply-chain risk. Signed commits, warning flags, and approvals do not evaluate dependency vulnerability status.
A. The GIL makes the lock redundant, so the lock is optimized away. B. Some code paths mutate the dict without acquiring the lock. C. dict operations are not atomic even under the GIL. D. The lock must be an RLock to be effective across threads.
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.
A. Restrict cache directory permissions to the service user. 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.
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.
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.
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.
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.
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.
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.
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.
A. Command injection; use subprocess with a list. B. SQL injection via string formatting; use parameterized queries with a tuple. C. XSS; escape the name with html.escape(). D. Path traversal; normalize with os.path.realpath().
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.
A. Enable Django's CSRF middleware. B. Use django.utils.html.escape(username) or render a template with autoescaping. C. Set the Content-Security-Policy header to 'unsafe-inline'. D. Store username in an HttpOnly cookie.
The reflected output of untrusted data creates XSS; escaping or using Django's autoescaping templates neutralizes it. CSRF middleware addresses forged requests, a permissive CSP worsens the problem, and HttpOnly cookies do not prevent script injection into the page.
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.
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.
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.
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.
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.
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.
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 ;.
Parameterized queries separate code from data at the driver level, so metacharacters cannot alter query structure. Quote-doubling (A) and blocklists (D) are bypassable, and html.escape (C) targets HTML context, not SQL parsing.
A. Base64-encode the password before logging. B. Log the username and a hashed password fingerprint, never the plaintext secret. C. Rotate log files daily to limit exposure window. D. Restrict log file permissions to root-only.
Secrets must never be logged; hashing preserves correlation without exposing credentials. Encoding (A) is reversible, and rotation/permissions (C, D) do not prevent secret disclosure at write time.
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.
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.
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
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.
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.
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.
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.
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.
A. Reject any input containing the substring '..' before joining it to BASE_DIR. B. After joining, call os.path.realpath and verify the result starts with os.path.realpath(BASE_DIR) + os.sep. C. Apply urllib.parse.quote to the parameter to neutralize traversal sequences. D. Use os.path.normpath on the parameter alone, then concatenate it to BASE_DIR with a string '+'.
Canonicalizing both the base and the joined path and comparing with a trailing separator defeats traversal via symlinks, absolute paths, and encoded variants. Substring blacklists (A) miss encoded or absolute forms, quoting (C) does not change path semantics, and normpath on the parameter alone (D) fails for absolute inputs.
A. Algorithm confusion via 'none'/'HS256' substitution; pin the expected algorithm and reject mismatches. B. Key ID (kid) injection; validate the kid against an allowlist of trusted keys. C. Signature stripping; require the 'typ' header to equal 'JWT'. D. Replay via 'jti' reuse; enforce short token lifetimes and a nonce cache.
Trusting the header-driven algorithm lets an attacker downgrade to 'none' or force HMAC verification using the public key as the secret (algorithm confusion). The fix is to pin the algorithm server-side and reject any mismatch. kid allowlisting, typ checks, and jti caches address different, though real, concerns.
A. Run 'pip-audit' with default settings and parse its human-readable output with a regex for 'HIGH'. B. Run 'safety check' against the live PyPI advisory feed with no lockfile. C. Run 'pip-audit --strict --requirement requirements.txt --format json' and fail on any entry whose severity is high or critical. D. Run 'pip list --outdated' and fail if any dependency has a newer version available.
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.
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.
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.
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.
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.
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.
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.
A. String interpolation is safe if name is escaped; the fix is to escape quotes. B. The defect is SQL injection; use parameterized queries with the DB-API placeholder. C. The defect is only performance; use a prepared statement cache. D. The defect is XSS; sanitize name with html.escape before interpolation.
Interpolating user input into SQL enables injection regardless of escaping heuristics; parameterized queries separate code from data. Escaping (A) is unreliable, the issue is not performance (C), and XSS mitigation (D) does not address SQL injection.
A. name = "Robert'); DROP TABLE users;--" B. name = "O'Brien" C. name = "1 OR 1=1" D. name = "%s"
String interpolation with %s of an already-quoted literal still breaks on a single quote in the value (e.g., O'Brien), producing malformed SQL that an attacker can exploit; parameterized queries are required. Options A and C assume unquoted concatenation, and D is inert literal input.