















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. 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.
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 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
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. 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:
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. 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.
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. D. CTR with a constant counter.
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. random.randint(100000, 999999) B. secrets.token_urlsafe(32) C. uuid.uuid4().hex D. hashlib.md5(str(time.time()).encode()).hexdigest()
secrets.token_urlsafe uses a cryptographically secure random number generator, suitable for security tokens. random is not cryptographically secure; UUID4 may be predictable in some contexts; MD5 of time is insecure. Thus, B is correct.
A. Use the original filename provided by the user and save it directly to the upload directory. B. Sanitize the filename by removing path separators and save it with a randomly generated name. C. Store the file content in a database as a BLOB and serve it with the original MIME type. D. Validate the file extension against a whitelist and save it in a directory outside the web root.
Sanitizing the filename to remove path separators prevents traversal, and using a random name avoids overwrites and execution. Option D also helps but doesn't address traversal if the filename is not sanitized. B is the most robust combined approach.
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
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 C. A mock that asserts cursor.execute is called exactly once D. A coverage run asserting 100% line coverage of the query builder
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. pickle is safe if the queue is internal; keep it for performance B. pickle can execute arbitrary code via reduce, so untrusted data must use a data-only format like JSON or a schema-validated format C. pickle is safe if you subclass Unpickler and override find_class to return None D. pickle is safe if the payload is compressed with zlib first
pickle's reduce and related hooks allow arbitrary code execution during unpickling, so it must never process untrusted data; JSON or schema-validated formats are data-only. Blocking find_class is a partial mitigation but not a guarantee, and compression does not remove the code-execution primitive.
A. Compile with -fstack-protector-strong and rely on the canary B. Validate n <= sizeof(dst) before memcpy and use a bounds-checked copy like memcpy_s or a length-checked wrapper C. Mark the function static to reduce its attack surface D. Run the process under a seccomp filter
Bounds validation before the copy, combined with a checked copy primitive, prevents the overflow at its source. Stack canaries, static linkage, and seccomp are defense-in-depth mitigations that do not eliminate the out-of-bounds write.
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
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 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
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. Reject any filename containing the substring '..' before joining. B. Normalize the joined path with os.path.realpath and verify it is still within the realpath of UPLOAD_DIR. C. Pass the filename through urllib.parse.quote before joining. D. Strip leading '/' and '\' characters from the filename before joining.
Canonicalizing the final path and confirming containment defeats traversal regardless of encoding tricks or symlinks. Substring checks and quote() are bypassable via alternate encodings or absolute paths, and stripping slashes alone fails against '..' sequences.
A. Wrap user_input in double quotes: subprocess.run('grep "' + user_input + '"', shell=True). B. Replace shell=True with shell=False but keep the concatenated string as the command. C. Call subprocess.run(['grep', user_input], shell=False) with a list of arguments. D. Escape semicolons and ampersands in user_input before concatenation.
Passing an argument list with shell=False bypasses the shell entirely, so metacharacters carry no special meaning. Quoting and blacklisting metacharacters are fragile, and shell=False with a single concatenated string treats the whole string as one executable name.
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.
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. C. Encrypt the JWT payload with a symmetric key before storing it. D. Add the 'alg': 'none' option to simplify verification.
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. pip install with --no-cache-dir and a requirements.txt pinned to exact versions. B. pip install from requirements.txt with hashes plus a lockfile and a virtual environment per build. C. conda install from the default channel with the latest packages. D. pip install -e. in the system Python to avoid environment overhead.
Hash-pinned requirements with a lockfile and isolated virtualenvs ensure reproducible, tamper-evident installs. Exact version pinning without hashes does not verify artifact integrity, 'latest' packages are non-reproducible, and editable installs into system Python break isolation.
A. Rate limiting per client IP. B. Mutual TLS plus HMAC signatures over request bodies. C. Structured logging with correlation IDs. D. Input length validation on all string fields.
Tampering concerns unauthorized modification of data in transit or at rest, so integrity mechanisms like mTLS and HMAC signatures directly counter it. Rate limiting addresses DoS, logging supports detection and non-repudiation, and length validation addresses input handling rather than integrity.
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.
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]). 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.
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. pickle only supports primitive types, causing data corruption. B. pickle executes arbitrary code via reduce during unpickling. C. pickle is slower than JSON, enabling denial of service. D. pickle does not preserve object identity across processes.
pickle's reduce can invoke arbitrary callables during deserialization, so untrusted data leads to RCE. The other options describe performance or correctness issues, not remote code execution.
A. Hardcode keys in a config.py file excluded from version control. B. Encrypt keys with a symmetric key stored in the same repository. C. Retrieve keys at runtime from a managed secret store (e.g., AWS Secrets Manager) using an instance role. D. Store keys in environment variables set in the Dockerfile.
Managed secret stores with instance roles avoid embedding secrets in code or images and support rotation/auditing. Hardcoding, same-repo encryption, and Dockerfile env vars expose secrets in artifacts or version control.
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'}
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. Reject any input containing the substring '..' before joining. B. Resolve the joined path with os.path.realpath and verify it remains within os.path.realpath(UPLOAD_DIR). C. URL-decode the argument once, then pass it to open() unchanged. D. Wrap the open() call in a try/except and log failures.
Canonicalizing both the target and base directory with realpath and checking containment defeats traversal regardless of encoding or symlinks. Substring filtering misses encoded, absolute, or symlink-based bypasses; decoding alone changes nothing; exception handling is detection, not prevention.
A. Increase the digest to SHA-512 for stronger collision resistance. B. Replace == with hmac.compare_digest to make comparison constant-time. C. Salt the password before HMAC to prevent rainbow-table attacks. D. Base64-encode the hexdigest before storage to obscure it.
The flaw is a timing side channel from short-circuiting ==, which compare_digest eliminates by comparing in constant time. Changing hash size, salting, or encoding does not remove the timing leak; salting is orthogonal to the comparison vulnerability.
A. Switch to yaml.safe_load, which restricts construction to basic Python types. B. Validate the input length before calling yaml.load. C. Wrap yaml.load in try/except to catch constructor errors. D. Run yaml.load inside a subprocess with a timeout.
safe_load disallows arbitrary object construction (e.g., !!python/object), eliminating the gadget-based RCE vector. Length checks, exception handling, and timeouts do not prevent malicious tags from executing during load.
A. Escape single quotes in name with name.replace("'", "''") before interpolation. B. Use cursor.execute('SELECT * FROM users WHERE name = %s', (name,)). C. Encode name with base64 before embedding it in the string. D. Restrict name to alphanumeric characters with a regex.
Parameterized queries send the value separately from the SQL text, so the database never treats it as code. Manual escaping, encoding, or input whitelisting are weaker, error-prone defenses that fail for numeric or complex inputs.