

















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. Replace pickle with json and validate the schema with pydantic before use. B. Wrap pickle.loads in a try/except and log the exception. C. Use pickle.Unpickler with find_class restricted to a whitelist of safe classes. D. Enable Python's -X dev mode to catch deserialization errors.
Restricting find_class to a whitelist maintains pickle compatibility while blocking arbitrary code execution. JSON (A) may not support all types; try/except (B) does not prevent exploitation; -X dev (D) only adds runtime checks, not security.
A. Add # noqa: E501 to suppress the warning and commit. B. Refactor the line and move the secret to an environment variable, then rotate the exposed key. C. Increase max-line-length in setup.cfg to 120. D. Use a pre-commit hook to auto-format with black.
The secret must be removed from source and rotated; refactoring addresses the lint issue. Suppression (A) or config change (C) hides the problem; auto-formatting (D) does not remove the secret.
A. flake8-docstrings and flake8-import-order B. flake8-bugbear and flake8-comprehensions C. flake8-bandit and flake8-bugbear D. flake8-annotations and flake8-quotes
flake8-bandit integrates Bandit security checks; flake8-bugbear catches likely bugs. The others focus on style, documentation, or import ordering, not security.
A. hashlib.md5(password.encode()).hexdigest() B. hashlib.sha256(password.encode()).hexdigest() C. bcrypt.hashpw(password.encode(), bcrypt.gensalt()) D. base64.b64encode(password.encode())
bcrypt is designed for password hashing with salt and work factor. MD5 (A) and SHA-256 (B) are fast and unsuitable; base64 (D) is encoding, not hashing.
A. Block all merges on any flake8 warning. B. Run flake8 only on changed files and fail on high-severity security issues. C. Run flake8 nightly and email reports. D. Disable flake8 and rely on code reviews.
Incremental scanning with severity-based gating reduces noise while catching critical issues. Blocking all warnings (A) causes friction; nightly (C) delays feedback; disabling (D) removes automation.
A. Using f-strings to embed user input directly. B. Sanitizing user input before logging and using structured logging. C. Logging only at ERROR level. D. Storing logs in a database instead of files.
Sanitization and structured logging prevent newline injection. F-strings (A) allow injection; log level (C) doesn't sanitize; database storage (D) doesn't prevent injection.
A. Replace MD5 with SHA-1. B. Replace MD5 with SHA-256 for non-security checksums. C. Replace MD5 with SHA-256 or better for security-sensitive hashing. D. Add # nosec to suppress the warning.
For security, use SHA-256 or stronger. SHA-1 (A) is also broken; SHA-256 for non-security (B) is acceptable but not for security; suppression (D) ignores the risk.
A. Match only ast.Call nodes whose func is an ast.Name with id 'eval'. B. Resolve the Name id through the module's import bindings before comparing it to the canonical builtin name. C. Use a regex over the raw source lines to detect the token 'eval('. D. Flag any ast.Call whose func is an ast.Attribute regardless of the attribute name.
Aliasing rebinds the name, so matching only the literal id 'eval' misses aliased calls; resolving import bindings to the canonical builtin is required. Regex over source is brittle and ignores AST semantics, and flagging all Attribute calls produces massive false positives unrelated to eval.
A. Add '# nosec' to the flagged line. B. Replace the f-string with cursor.execute('... WHERE id = %s', (user_id,)). C. Wrap the user_id in str() before interpolation. D. Configure Bandit to skip the B608 test.
Parameterized execution separates code from data, structurally preventing injection, which is the true remediation. Suppression via nosec or config, and string coercion, leave the injection vector intact.
A. Lower flake8's max-line-length to 88. B. Configure both tools to a shared line length and disable flake8's E203/W503 conflicts. C. Disable black's line-length check in CI. D. Add '# noqa' to every line black reformats.
Black and flake8 disagree on slice and whitespace conventions, so aligning line length and ignoring E203/W503 resolves the conflict without suppressing real issues. Lowering the limit or disabling black's check does not reconcile the tools and weakens enforcement.
A. Log the body only when the log level is DEBUG. B. Redact or omit sensitive fields before logging, and log structured, non-sensitive metadata. C. Encrypt the log file at rest and continue logging the body. D. Log only the HTTP status code and drop all request context.
OWASP recommends minimizing and redacting sensitive data at the point of logging; structured metadata preserves diagnostics without exposing secrets. Logging at DEBUG still persists secrets, encryption at rest does not prevent exposure to log readers, and dropping all context harms operability.
A. When the token is a bytes object rather than a str. B. When Python is run with -O, which strips assert statements. C. When the assert uses '==' instead of 'is'. D. When the assert is inside a try/except block.
The -O flag removes assert statements, so authentication checks silently disappear in optimized builds, a classic vulnerability. The other options describe type or style issues that do not disable the check.
A. patch('requests.get') B. patch('mymodule.get') where mymodule imported it C. patch('requests') D. patch.object(requests, 'get', autospec=True)
Mock patches the name where it is looked up, so the module that imported get must be patched. Patching requests.get affects the original binding, not the local reference, and patching the module object is too broad.
A. Flake8's E722 only fires when a bare except is followed by a raise statement, whereas Bandit flags all bare excepts. B. Bandit detects bare except: clauses as a security weakness (B110/B112 patterns), while Flake8's E722 requires a specific pycodestyle configuration and may be disabled by default in some setups or suppressed via noqa. C. Bandit only inspects compiled bytecode, so it detects exceptions that Flake8's AST-based parser cannot see. D. E722 applies exclusively to Python 2 syntax, so Python 3 code will never trigger it regardless of configuration.
Bandit's B110/B112 checks flag bare or overly broad exception handling as a security-relevant weakness, whereas pycodestyle's E722 is a style rule that can be disabled, overridden, or suppressed via # noqa, so a clean Flake8 run does not guarantee Bandit silence. Options A, C, and D misstate the semantics of each tool: E does not require a raise, both tools parse source/AST rather than bytecode, and E applies to Python 3 as well.
A. Escape single quotes in name using name.replace("'", "''") before interpolation. B. Wrap the call in a try/except and log the exception. C. Replace string interpolation with a parameterized query: cursor.execute("SELECT * FROM users WHERE name = %s", (name,)). D. Switch the database driver to one that auto-sanitizes all string inputs.
Parameterized queries send the SQL structure and the data separately, so user input cannot alter the query's parse tree regardless of content. Manual escaping (A) is error-prone and driver-dependent, exception handling (B) does not prevent injection, and no mainstream driver (D) auto-sanitizes interpolated strings.
A. Assert that requests.get was called exactly three times using assert_called_with on the final call. B. Configure the mock's side_effect to return a 500 response twice and a 200 response once, then assert the function returns the parsed payload and that requests.get.call_count == 3. C. Patch time.sleep to a no-op and assert the function completes within a fixed wall-clock budget. D. Use pytest.mark.integration and hit a real endpoint that returns 500 to observe retries.
Driving the mock with a side_effect sequence exercises the retry logic deterministically and asserts both the observable outcome (parsed payload) and the interaction (call count), which is the strongest contract-level check. Option A checks only the last call, C tests timing rather than retry semantics, and D introduces nondeterminism and external dependency.
A. hashlib.sha256(password.encode()).hexdigest() with a fixed application salt. B. hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 600000) with a per-user random salt. C. base64.b64encode(password.encode()) to obfuscate the credential. D. hmac.new(secret_key, password.encode(), hashlib.md5).hexdigest().
Current guidance (OWASP/NIST) requires a memory-hard or iterated KDF with a per-user random salt; PBKDF2-HMAC-SHA256 with a high iteration count satisfies this. SHA-256 alone (A) is fast and unsuitable for passwords, base64 (C) is encoding not hashing, and HMAC-MD5 (D) retains a broken hash primitive.
A. Increasing the number of integration tests against a live database. B. Measuring branch/decision coverage and adding a test that forces the authorization check to evaluate False. C. Adding property-based tests that only generate valid inputs. D. Running mutation testing on unrelated modules to raise the overall score.
Line coverage can be satisfied while a branch outcome is never exercised; branch/decision coverage explicitly requires each outcome, and adding a False-path test closes the gap. Options A, C, and D do not guarantee the specific untested branch is executed.
A. Wrap the load in try/except to catch parse errors. B. Replace yaml.load with yaml.safe_load, which restricts construction to basic Python types. C. Validate the file extension is .yaml before loading. D. Run the loader in a thread pool to isolate failures.
yaml.load with the default loader can instantiate arbitrary Python objects via tags like !!python/object, enabling code execution; yaml.safe_load disallows those constructors. Extension checks (C) are trivially bypassed, try/except (A) does not prevent execution, and thread isolation (D) does not sandbox code.
A. Run flake8 with the flake8-bandit plugin to detect vulnerable dependencies. B. Run pip-audit (or safety) against the locked requirements and fail the build on any reported CVE. C. Run mypy --strict to catch type errors that indicate vulnerabilities. D. Run pytest --cov and require 100% coverage before merging.
SCA tools like pip-audit and safety query vulnerability databases against the resolved dependency set, which is the correct control for third-party CVEs. Flake plugins (A) analyze source style/security patterns, mypy (C) checks types, and coverage (D) measures test execution, none of which detect dependency CVEs.
A. Replace with subprocess.Popen(user_input.split(), shell=False); Bandit flags B (subprocess_popen_with_shell_equals_true). B. Escape user_input with shlex.quote and keep shell=True; Bandit flags B603. C. Replace with os.system(user_input); Bandit flags B605. D. Use subprocess.Popen([user_input], shell=False) without splitting; Bandit flags B (start_process_with_partial_path).
Using shell=False with a list of arguments prevents shell interpretation; Bandit's B specifically flags subprocess calls with shell=True. Escaping still leaves shell=True (B602 remains), os.system is worse, and B607 concerns partial paths, not shell injection.
A. Use monkeypatch.setattr('requests.get', lambda url: Mock(status_code=200)) and assert on the logger's info call via caplog. B. Use mocker.patch('requests.get', return_value=Mock(status_code=200)) and assert caplog.records[0].status_code == 200. C. Use mocker.patch('requests.get', return_value=Mock(status_code=200)) and assert that the logger's info was called with the expected message using caplog.text. D. Use responses library to mock HTTP and assert that logging.getLogger().handlers contains a StreamHandler.
mocker.patch cleanly replaces requests.get, and caplog.text captures emitted log messages for assertion; this verifies both isolation and logging. Option A uses monkeypatch but asserts on the wrong attribute; B incorrectly inspects record attributes not present; D tests handler configuration, not the log message.
A. SAST analyzes running code and detects runtime injection; DAST scans source for insecure patterns like eval. B. SAST examines source or bytecode without execution and can catch insecure deserialization patterns; DAST probes a running application and can detect reflected XSS. C. SAST requires a deployed environment; DAST runs at commit time and is faster for Python. D. SAST and DAST are interchangeable for Python because both rely on Flake8 plugins.
SAST inspects code without executing it (e.g., Bandit finding insecure deserialization), while DAST tests a live application (e.g., reflected XSS). A reverses the definitions, C misstates deployment needs, and D falsely equates them with Flake8 plugins.
A. Change level to debug and keep the password for troubleshooting. B. Hash the password with MD5 before logging to preserve traceability. C. Remove the password from the log message and log only the username and a success flag; ensure logs are not world-readable. D. Log the password only when DEBUG=True and disable logging in production.
OWASP advises never logging credentials; removing the password and restricting log permissions prevents exposure. Debug-level logging still leaks secrets, MD5 is insecure and unnecessary, and disabling logging entirely harms auditability.
A. Run bandit -r. -lll and flake8 --max-complexity=10; fail the build if either returns non-zero. B. Run bandit -r . and flake8; only warn on failures. C. Run bandit -r. -s B101 and flake8 --max-complexity=10; ignore HIGH issues. D. Run bandit -r. -ll and flake8; fail only on Bandit.
bandit -lll reports only HIGH severity issues, and --max-complexity=10 enforces the complexity limit; non-zero exit fails the build. Other options either warn instead of fail, ignore HIGH issues, or omit the complexity gate.
A. Use logging.basicConfig(format='%(message)s') and log raw user input. B. Sanitize newline characters in user input before logging, and use structured logging (e.g., logger.info('user=%s', sanitized)). C. Set logging.raiseExceptions = False to suppress injection errors. D. Encode user input with base64 before logging.
Sanitizing newlines and using parameterized structured logging prevents attackers from forging log entries. Raw logging enables injection, raiseExceptions=False hides errors, and base64 obscures but does not prevent injection.
A. Use render_template_string('Hello {{ name }}', name=name). B. Escape name with html.escape and keep concatenation. C. Use render_template('hello.html', name=name) with a template file. D. Switch to string.Template('Hello $name').substitute(name=name).
Using render_template with a static file separates code from data and prevents SSTI. Option A still uses render_template_string with user input, B only escapes HTML (SSTI persists), and D bypasses the template engine but may not fit Flask patterns.
A. Add # nosec B301 to each flagged line and document the trust boundary in a code comment. B. Replace pickle with json.loads and validate the schema with a strict allow-list. C. Wrap the unpickling call in a try/except and log the exception at WARNING level. D. Move the unpickling into a separate process running as a low-privilege user.
Pickle deserialization is inherently unsafe because the byte stream can execute arbitrary code; the only robust fix is to avoid pickle for untrusted data and use a safe, schema-validated format such as JSON. Suppressing the finding with # nosec, catching exceptions, or sandboxing the process does not eliminate the code-execution primitive.